repo_name
stringlengths 6
91
| ref
stringlengths 12
59
| path
stringlengths 7
936
| license
stringclasses 15
values | copies
stringlengths 1
3
| content
stringlengths 61
714k
| hash
stringlengths 32
32
| line_mean
float64 4.88
60.8
| line_max
int64 12
421
| alpha_frac
float64 0.1
0.92
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
ghodeaniket/CityList_IOS | refs/heads/master | CityList_IOS/CityList_IOS/City.swift | apache-2.0 | 1 | //
// City.swift
// CityList_IOS
//
// Created by Aniket Ghode on 24/06/17.
// Copyright © 2017 Aniket Ghode. All rights reserved.
//
import Foundation
// Structure to hold the information for city from cities.json
struct City{
let name: String
let country: String
let id: Int
let location: Location
init(json: [String: Any]) {
name = json["name"] as? String ?? "Unknown City"
country = json["country"] as? String ?? "Unknown Country"
id = json["_id"] as? Int ?? 0
location = Location(json: json["coord"] as! [String : Any])
}
}
//MARK: - Protocols
extension City : Equatable{
public static func ==(lhs: City, rhs: City) -> Bool{
return (lhs.name == rhs.name) &&
(lhs.country == rhs.country)
}
}
| de144161932562d12543eddfef673ecc | 21.714286 | 67 | 0.593711 | false | false | false | false |
greycats/Greycats.swift | refs/heads/master | Greycats/Graphics/Graphics.swift | mit | 1 | //
// Graphics.swift
// Greycats
//
// Created by Rex Sheng on 8/1/16.
// Copyright (c) 2016 Interactive Labs. All rights reserved.
//
import UIKit
private var _bitmapInfo: UInt32 = {
var bitmapInfo = CGBitmapInfo.byteOrder32Little.rawValue
bitmapInfo &= ~CGBitmapInfo.alphaInfoMask.rawValue
bitmapInfo |= CGImageAlphaInfo.premultipliedFirst.rawValue
return bitmapInfo
}()
extension CGImage {
public func op(_ closure: (CGContext?, CGRect) -> Void) -> CGImage? {
let width = self.width
let height = self.height
let colourSpace = CGColorSpaceCreateDeviceRGB()
let context = CGContext(data: nil, width: width, height: height, bitsPerComponent: 8, bytesPerRow: width * 8, space: colourSpace, bitmapInfo: bitmapInfo.rawValue)
let rect = CGRect(x: 0, y: 0, width: CGFloat(width), height: CGFloat(height))
closure(context, rect)
return context!.makeImage()
}
public static func op(_ width: Int, _ height: Int, closure: (CGContext?) -> Void) -> CGImage? {
let scale = UIScreen.main.scale
let w = width * Int(scale)
let h = height * Int(scale)
let colourSpace = CGColorSpaceCreateDeviceRGB()
let context = CGContext(data: nil, width: w, height: h, bitsPerComponent: 8, bytesPerRow: w * 8, space: colourSpace, bitmapInfo: _bitmapInfo)
context!.translateBy(x: 0, y: CGFloat(h))
context!.scaleBy(x: scale, y: -scale)
closure(context)
return context!.makeImage()
}
}
| 975faacaa431f44770959c5cb0a1a758 | 37.075 | 170 | 0.659225 | false | false | false | false |
BelledonneCommunications/linphone-iphone | refs/heads/master | Classes/Swift/Voip/ViewModels/CallsViewModel.swift | gpl-3.0 | 1 | /*
* Copyright (c) 2010-2020 Belledonne Communications SARL.
*
* This file is part of linhome
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import Foundation
import linphonesw
import AVFoundation
class CallsViewModel {
let currentCallData = MutableLiveData<CallData?>(nil)
let callsData = MutableLiveData<[CallData]>([])
let inactiveCallsCount = MutableLiveData(0)
let currentCallUnreadChatMessageCount = MutableLiveData(0)
let chatAndCallsCount = MutableLiveData(0)
let callConnectedEvent = MutableLiveData<Call>()
let callUpdateEvent = MutableLiveData<Call>()
let noMoreCallEvent = MutableLiveData(false)
var core : Core { get { Core.get() } }
static let shared = CallsViewModel()
private var coreDelegate : CoreDelegateStub?
init () {
coreDelegate = CoreDelegateStub(
onCallStateChanged : { (core: Core, call: Call, state: Call.State, message:String) -> Void in
Log.i("[Calls] Call state changed: \(call) : \(state)")
let currentCall = core.currentCall
if (currentCall != nil && self.currentCallData.value??.call.getCobject != currentCall?.getCobject) {
self.updateCurrentCallData(currentCall: currentCall)
} else if (currentCall == nil && core.callsNb > 0) {
self.updateCurrentCallData(currentCall: currentCall)
}
if ([.End,.Released,.Error].contains(state)) {
self.removeCallFromList(call: call)
} else if ([.OutgoingInit].contains(state)) {
self.addCallToList(call:call)
} else if ([.IncomingReceived].contains(state)) {
self.addCallToList(call:call)
} else if (state == .UpdatedByRemote) {
let remoteVideo = call.remoteParams?.videoEnabled == true
let localVideo = call.currentParams?.videoEnabled == true
let autoAccept = call.core?.videoActivationPolicy?.automaticallyAccept == true
if (remoteVideo && !localVideo && !autoAccept) {
if (core.videoCaptureEnabled || core.videoDisplayEnabled) {
try?call.deferUpdate()
self.callUpdateEvent.value = call
} else {
call.answerVideoUpdateRequest(accept: false)
}
}
}else if (state == Call.State.Connected) {
self.callConnectedEvent.value = call
} else if (state == Call.State.StreamsRunning) {
self.callUpdateEvent.value = call
}
self.updateInactiveCallsCount()
self.callsData.notifyValue()
},
onMessageReceived : { (core: Core, room: ChatRoom, message: ChatMessage) -> Void in
self.updateUnreadChatCount()
},
onChatRoomRead : { (core: Core, room: ChatRoom) -> Void in
self.updateUnreadChatCount()
},
onLastCallEnded: { (core: Core) -> Void in
self.currentCallData.value??.destroy()
self.currentCallData.value = nil
self.noMoreCallEvent.value = true
}
)
Core.get().addDelegate(delegate: coreDelegate!)
if let currentCall = core.currentCall {
currentCallData.value??.destroy()
currentCallData.value = CallData(call:currentCall)
}
chatAndCallsCount.value = 0
inactiveCallsCount.readCurrentAndObserve { (_) in
self.updateCallsAndChatCount()
}
currentCallUnreadChatMessageCount.readCurrentAndObserve { (_) in
self.updateCallsAndChatCount()
}
initCallList()
updateInactiveCallsCount()
updateUnreadChatCount()
}
private func initCallList() {
core.calls.forEach { addCallToList(call: $0) }
}
private func removeCallFromList(call: Call) {
Log.i("[Calls] Removing call \(call) from calls list")
if let removeCandidate = callsData.value?.filter{$0.call.getCobject == call.getCobject}.first {
removeCandidate.destroy()
}
callsData.value = callsData.value?.filter(){$0.call.getCobject != call.getCobject}
callsData.notifyValue()
}
private func addCallToList(call: Call) {
Log.i("[Calls] Adding call \(call) to calls list")
callsData.value?.append(CallData(call: call))
callsData.notifyValue()
}
private func updateUnreadChatCount() {
guard let unread = currentCallData.value??.chatRoom?.unreadMessagesCount else {
currentCallUnreadChatMessageCount.value = 0
return
}
currentCallUnreadChatMessageCount.value = unread
}
private func updateInactiveCallsCount() {
inactiveCallsCount.value = core.callsNb - 1
}
private func updateCallsAndChatCount() {
var value = 0
if let calls = inactiveCallsCount.value {
value += calls
}
if let chats = currentCallUnreadChatMessageCount.value {
value += chats
}
chatAndCallsCount.value = value
}
func mergeCallsIntoLocalConference() {
CallManager.instance().startLocalConference()
}
private func updateCurrentCallData(currentCall: Call?) {
var callToUse = currentCall
if (currentCall == nil) {
Log.w("[Calls] Current call is now null")
let firstCall = core.calls.first
if (firstCall != nil && currentCallData.value??.call.getCobject != firstCall?.getCobject) {
Log.i("[Calls] Using first call as \"current\" call")
callToUse = firstCall
}
}
guard let callToUse = callToUse else {
Log.w("[Calls] No call found to be used as \"current\"")
return
}
let firstToUse = callsData.value?.filter{$0.call.getCobject != callToUse.getCobject}.first
if (firstToUse != nil) {
currentCallData.value = firstToUse
} else {
Log.w("[Calls] Call not found in calls data list, shouldn't happen!")
currentCallData.value = CallData(call: callToUse)
}
updateUnreadChatCount()
}
}
| 603462e27404da8c1db5824e82069e05 | 30.426316 | 104 | 0.709094 | false | false | false | false |
CodaFi/swift | refs/heads/main | validation-test/compiler_crashers_fixed/00216-swift-unqualifiedlookup-unqualifiedlookup.swift | apache-2.0 | 65 | // This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -typecheck
({})
var f = 1
var e: Int -> Int = {
return $0
}
let d: Int = { c, b in
}(f, e)
class k {
func l((Any, k))(m }
}
func j<f: l: e -> e = {
{
l) {
m }
}
protocol k {
class func j()
}
class e: k{ }
}
func a(x: Any, y: Any) -> (((Any, Any) -> Any) -> Any) {
return {
(m: (Any, Any) -> Any) -> Any in
return m(x, y)
}
}
func b(z: (((Any, Any) - = b
=b as c=b
func q(v: h) -> <r>(() -> r) -> h {
n { u o "\(v): \(u())" }
}
struct e<r> {
j p: , () -> ())] = []
}
protocol p {
}
protocol m : p {
}
protocol v : p {
}
protocol m {
v = m
}
func s<s : m, v : m u v.v == s> (m: v) {
}
func s<v : m u v.v == v> (m: v) {
}
s( {
({})
}
t
func c<g>() -> (g, g -> g) -> g {
d b d.f = {
}
{
g) {
i }
}
i c {
class func f()
}
class d: c{ class func f {}
struct d<c : f,f where g.i == c.i>
fu ^(a: Bo
}
}
| 176cd3480586c6464111a1607dda9e3f | 15.776316 | 79 | 0.49098 | false | false | false | false |
malcommac/Hydra | refs/heads/master | Sources/Hydra/Promise+Timeout.swift | mit | 1 | /*
* Hydra
* Fullfeatured lightweight Promise & Await Library for Swift
*
* Created by: Daniele Margutti
* Email: [email protected]
* Web: http://www.danielemargutti.com
* Twitter: @danielemargutti
*
* Copyright © 2017 Daniele Margutti
*
*
* 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 extension Promise {
/// Reject the receiving Promise if it does not resolve or reject after a given number of seconds
///
/// - Parameters:
/// - context: context in which the nextPromise will be executed (if not specified `background` is used)
/// - timeout: timeout expressed in seconds
/// - error: error to report, if nil `PromiseError.timeout` is used instead
/// - Returns: promise
func timeout(in context: Context? = nil, timeout: TimeInterval, error: Error? = nil) -> Promise<Value> {
let ctx = context ?? .background
let nextPromise = Promise<Value>(in: ctx, token: self.invalidationToken) { resolve, reject, operation in
// Dispatch the result of self promise to the nextPromise
// If self promise does not resolve or reject in given amount of time
// nextPromise is rejected with passed error or generic timeout error
// and any other result of the self promise is ignored
let timer = DispatchTimerWrapper(queue: ctx.queue)
timer.setEventHandler {
let errorToPass = (error ?? PromiseError.timeout)
reject(errorToPass)
}
timer.scheduleOneShot(deadline: .now() + timeout)
timer.resume()
// Observe resolve
self.add(onResolve: { v in
resolve(v) // resolve with value
timer.cancel() // cancel timeout timer and release promise
}, onReject: reject, onCancel: operation.cancel)
}
nextPromise.runBody()
self.runBody()
return nextPromise
}
}
| 8970be790dd6a734dbcbbb430deff56e | 38.084507 | 107 | 0.736577 | false | false | false | false |
ruipfcosta/AutoLayoutPlus | refs/heads/master | AutoLayoutPlus/NSLayoutConstraint.swift | mit | 1 | //
// NSLayoutConstraint.swift
// AutoLayoutPlus
//
// Created by Rui Costa on 17/11/15.
// Copyright © 2015 Rui Costa. All rights reserved.
//
import Foundation
import UIKit
public extension NSLayoutConstraint {
public convenience init(item view1: AnyObject, attribute attr1: NSLayoutAttribute, relatedBy relation: NSLayoutRelation, toItem view2: AnyObject?, attribute attr2: NSLayoutAttribute) {
self.init(item: view1, attribute: attr1, relatedBy: relation, toItem: view2, attribute: attr2, multiplier: 1, constant: 0)
}
public class func constraints(items views: [AnyObject], attribute attr1: NSLayoutAttribute, relatedBy relation: NSLayoutRelation, toItem view: AnyObject?, attribute attr2: NSLayoutAttribute, multiplier: CGFloat = 1, constant c: CGFloat = 0) -> [NSLayoutConstraint] {
return views.map { NSLayoutConstraint(item: $0, attribute: attr1, relatedBy: relation, toItem: view, attribute: attr2, multiplier: multiplier, constant: c) }
}
public class func withFormat(_ format: String, options: NSLayoutFormatOptions = NSLayoutFormatOptions(rawValue: 0), metrics: [String : AnyObject]? = nil, views: [String : AnyObject]) -> [NSLayoutConstraint] {
return NSLayoutConstraint.constraints(withVisualFormat: format, options: options, metrics: metrics, views: views)
}
public class func withFormat(_ format: [String], metrics: [String : AnyObject]? = nil, views: [String : AnyObject]) -> [NSLayoutConstraint] {
return format.flatMap { NSLayoutConstraint.constraints(withVisualFormat: $0, options: NSLayoutFormatOptions(rawValue: 0), metrics: metrics, views: views) }
}
}
| 21996062e060c77c9380db9cca942532 | 54.6 | 270 | 0.730815 | false | false | false | false |
hacktoolkit/hacktoolkit-ios_lib | refs/heads/master | Hacktoolkit/lib/GitHub/models/GitHubUser.swift | mit | 1 | //
// GitHubUser.swift
//
// Created by Hacktoolkit (@hacktoolkit) and Jonathan Tsai (@jontsai)
// Copyright (c) 2014 Hacktoolkit. All rights reserved.
//
import Foundation
class GitHubUser: GitHubResource {
// User attributes
var login: String!
var id: Int!
var avatar_url: String!
var gravatar_id: String!
var url: String!
var html_url: String!
var followers_url: String!
var following_url: String!
var gists_url: String!
var starred_url: String!
var subscriptions_url: String!
var organizations_url: String!
var name: String!
var company: String!
var blog: String!
var location: String!
var email: String!
var bio: String!
var public_repos: Int!
var public_gists: Int!
var followers: Int!
var following: Int!
init() {
}
init(fromDict userDict: NSDictionary) {
self.login = userDict["login"] as? String
self.id = userDict["id"] as? Int
self.avatar_url = userDict["avatar_url"] as? String
self.gravatar_id = userDict["gravatar_id"] as? String
self.url = userDict["url"] as? String
self.html_url = userDict["html_url"] as? String
self.followers_url = userDict["followers_url"] as? String
self.following_url = userDict["following_url"] as? String
self.gists_url = userDict["gists_url"] as? String
self.starred_url = userDict["starred_url"] as? String
self.subscriptions_url = userDict["subscriptions_url"] as? String
self.organizations_url = userDict["organizations_url"] as? String
self.name = userDict["name"] as? String
self.company = userDict["company"] as? String
self.blog = userDict["blog"] as? String
self.location = userDict["location"] as? String
self.email = userDict["email"] as? String
self.bio = userDict["bio"] as? String
self.public_repos = userDict["public_repos"] as? Int
self.public_gists = userDict["public_gists"] as? Int
self.followers = userDict["followers"] as? Int
self.following = userDict["following"] as? Int
}
}
//{
// "login": "octocat",
// "id": 1,
// "avatar_url": "https://github.com/images/error/octocat_happy.gif",
// "gravatar_id": "somehexcode",
// "url": "https://api.github.com/users/octocat",
// "html_url": "https://github.com/octocat",
// "followers_url": "https://api.github.com/users/octocat/followers",
// "following_url": "https://api.github.com/users/octocat/following{/other_user}",
// "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}",
// "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}",
// "subscriptions_url": "https://api.github.com/users/octocat/subscriptions",
// "organizations_url": "https://api.github.com/users/octocat/orgs",
// "repos_url": "https://api.github.com/users/octocat/repos",
// "events_url": "https://api.github.com/users/octocat/events{/privacy}",
// "received_events_url": "https://api.github.com/users/octocat/received_events",
// "type": "User",
// "site_admin": false,
// "name": "monalisa octocat",
// "company": "GitHub",
// "blog": "https://github.com/blog",
// "location": "San Francisco",
// "email": "[email protected]",
// "hireable": false,
// "bio": "There once was...",
// "public_repos": 2,
// "public_gists": 1,
// "followers": 20,
// "following": 0,
// "created_at": "2008-01-14T04:33:35Z",
// "updated_at": "2008-01-14T04:33:35Z"
//}
| 5bf923b60b46a4138471076dc6598123 | 36.104167 | 85 | 0.62128 | false | false | false | false |
ContinuousLearning/PokemonKit | refs/heads/master | Carthage/Checkouts/PromiseKit/Categories/AssetsLibrary/ALAssetsLibrary+Promise.swift | mit | 1 | import AssetsLibrary
import Foundation.NSData
#if !COCOAPODS
import PromiseKit
#endif
import UIKit.UIViewController
/**
To import this `UIViewController` extension:
use_frameworks!
pod "PromiseKit/AssetsLibrary"
And then in your sources:
#if !COCOAPODS
import PromiseKit
#endif
*/
extension UIViewController {
/**
@return A promise that presents the provided UIImagePickerController and
fulfills with the user selected media’s `NSData`.
*/
public func promiseViewController(vc: UIImagePickerController, animated: Bool = false, completion: (() -> Void)? = nil) -> Promise<NSData> {
let proxy = UIImagePickerControllerProxy()
vc.delegate = proxy
presentViewController(vc, animated: animated, completion: completion)
return proxy.promise.then(on: zalgo) { info -> Promise<NSData> in
let url = info[UIImagePickerControllerReferenceURL] as! NSURL
return Promise { sealant in
ALAssetsLibrary().assetForURL(url, resultBlock: { asset in
let N = Int(asset.defaultRepresentation().size())
let bytes = UnsafeMutablePointer<UInt8>.alloc(N)
var error: NSError?
asset.defaultRepresentation().getBytes(bytes, fromOffset: 0, length: N, error: &error)
sealant.resolve(NSData(bytesNoCopy: bytes, length: N), error as NSError!)
}, failureBlock: sealant.resolve)
}
}.finally {
self.dismissViewControllerAnimated(animated, completion: nil)
}
}
}
| b083f294f2ceb847b15e0197ada4309d | 32.816327 | 144 | 0.627037 | false | false | false | false |
airspeedswift/swift | refs/heads/master | test/Sema/enum_conformance_synthesis.swift | apache-2.0 | 3 | // RUN: %target-swift-frontend -typecheck -verify -primary-file %s %S/Inputs/enum_conformance_synthesis_other.swift -verify-ignore-unknown -swift-version 4
var hasher = Hasher()
enum Foo: CaseIterable {
case A, B
}
func foo() {
if Foo.A == .B { }
var _: Int = Foo.A.hashValue
Foo.A.hash(into: &hasher)
_ = Foo.allCases
Foo.A == Foo.B // expected-warning {{result of operator '==' is unused}}
}
enum Generic<T>: CaseIterable {
case A, B
static func method() -> Int {
// Test synthesis of == without any member lookup being done
if A == B { }
return Generic.A.hashValue
}
}
func generic() {
if Generic<Foo>.A == .B { }
var _: Int = Generic<Foo>.A.hashValue
Generic<Foo>.A.hash(into: &hasher)
_ = Generic<Foo>.allCases
}
func localEnum() -> Bool {
enum Local {
case A, B
}
return Local.A == .B
}
enum CustomHashable {
case A, B
func hash(into hasher: inout Hasher) {}
}
func ==(x: CustomHashable, y: CustomHashable) -> Bool {
return true
}
func customHashable() {
if CustomHashable.A == .B { }
var _: Int = CustomHashable.A.hashValue
CustomHashable.A.hash(into: &hasher)
}
// We still synthesize conforming overloads of '==' and 'hashValue' if
// explicit definitions don't satisfy the protocol requirements. Probably
// not what we actually want.
enum InvalidCustomHashable {
case A, B
var hashValue: String { return "" } // expected-error {{invalid redeclaration of synthesized implementation for protocol requirement 'hashValue'}}
}
func ==(x: InvalidCustomHashable, y: InvalidCustomHashable) -> String {
return ""
}
func invalidCustomHashable() {
if InvalidCustomHashable.A == .B { }
var s: String = InvalidCustomHashable.A == .B
s = InvalidCustomHashable.A.hashValue
_ = s
var _: Int = InvalidCustomHashable.A.hashValue
InvalidCustomHashable.A.hash(into: &hasher)
}
// Check use of an enum's synthesized members before the enum is actually declared.
struct UseEnumBeforeDeclaration {
let eqValue = EnumToUseBeforeDeclaration.A == .A
let hashValue = EnumToUseBeforeDeclaration.A.hashValue
}
enum EnumToUseBeforeDeclaration {
case A
}
func getFromOtherFile() -> AlsoFromOtherFile { return .A }
func overloadFromOtherFile() -> YetAnotherFromOtherFile { return .A }
func overloadFromOtherFile() -> Bool { return false }
func useEnumBeforeDeclaration() {
// Check enums from another file in the same module.
if FromOtherFile.A == .A {}
let _: Int = FromOtherFile.A.hashValue
if .A == getFromOtherFile() {}
if .A == overloadFromOtherFile() {}
}
// Complex enums are not automatically Equatable, Hashable, or CaseIterable.
enum Complex {
case A(Int)
case B
}
func complex() {
if Complex.A(1) == .B { } // expected-error{{cannot convert value of type 'Complex' to expected argument type 'CustomHashable'}}
}
// Enums with equatable payloads are equatable if they explicitly conform.
enum EnumWithEquatablePayload: Equatable {
case A(Int)
case B(String, Int)
case C
}
func enumWithEquatablePayload() {
if EnumWithEquatablePayload.A(1) == .B("x", 1) { }
if EnumWithEquatablePayload.A(1) == .C { }
if EnumWithEquatablePayload.B("x", 1) == .C { }
}
// Enums with hashable payloads are hashable if they explicitly conform.
enum EnumWithHashablePayload: Hashable {
case A(Int)
case B(String, Int)
case C
}
func enumWithHashablePayload() {
_ = EnumWithHashablePayload.A(1).hashValue
_ = EnumWithHashablePayload.B("x", 1).hashValue
_ = EnumWithHashablePayload.C.hashValue
EnumWithHashablePayload.A(1).hash(into: &hasher)
EnumWithHashablePayload.B("x", 1).hash(into: &hasher)
EnumWithHashablePayload.C.hash(into: &hasher)
// ...and they should also inherit equatability from Hashable.
if EnumWithHashablePayload.A(1) == .B("x", 1) { }
if EnumWithHashablePayload.A(1) == .C { }
if EnumWithHashablePayload.B("x", 1) == .C { }
}
// Enums with non-hashable payloads don't derive conformance.
struct NotHashable {}
enum EnumWithNonHashablePayload: Hashable { // expected-error 2 {{does not conform}}
case A(NotHashable) //expected-note {{associated value type 'NotHashable' does not conform to protocol 'Hashable', preventing synthesized conformance of 'EnumWithNonHashablePayload' to 'Hashable'}}
// expected-note@-1 {{associated value type 'NotHashable' does not conform to protocol 'Equatable', preventing synthesized conformance of 'EnumWithNonHashablePayload' to 'Equatable'}}
}
// Enums should be able to derive conformances based on the conformances of
// their generic arguments.
enum GenericHashable<T: Hashable>: Hashable {
case A(T)
case B
}
func genericHashable() {
if GenericHashable<String>.A("a") == .B { }
var _: Int = GenericHashable<String>.A("a").hashValue
}
// But it should be an error if the generic argument doesn't have the necessary
// constraints to satisfy the conditions for derivation.
enum GenericNotHashable<T: Equatable>: Hashable { // expected-error 2 {{does not conform to protocol 'Hashable'}}
case A(T) //expected-note 2 {{associated value type 'T' does not conform to protocol 'Hashable', preventing synthesized conformance of 'GenericNotHashable<T>' to 'Hashable'}}
case B
}
func genericNotHashable() {
if GenericNotHashable<String>.A("a") == .B { }
let _: Int = GenericNotHashable<String>.A("a").hashValue // No error. hashValue is always synthesized, even if Hashable derivation fails
GenericNotHashable<String>.A("a").hash(into: &hasher) // expected-error {{value of type 'GenericNotHashable<String>' has no member 'hash'}}
}
// An enum with no cases should also derive conformance.
enum NoCases: Hashable {}
// rdar://19773050
private enum Bar<T> {
case E(Unknown<T>) // expected-error {{cannot find type 'Unknown' in scope}}
mutating func value() -> T {
switch self {
// FIXME: Should diagnose here that '.' needs to be inserted, but E has an ErrorType at this point
case E(let x):
return x.value
}
}
}
// Equatable extension -- rdar://20981254
enum Instrument {
case Piano
case Violin
case Guitar
}
extension Instrument : Equatable {}
extension Instrument : CaseIterable {}
enum UnusedGeneric<T> {
case a, b, c
}
extension UnusedGeneric : CaseIterable {}
// Explicit conformance should work too
public enum Medicine {
case Antibiotic
case Antihistamine
}
extension Medicine : Equatable {}
public func ==(lhs: Medicine, rhs: Medicine) -> Bool {
return true
}
// No explicit conformance; but it can be derived, for the same-file cases.
enum Complex2 {
case A(Int)
case B
}
extension Complex2 : Hashable {}
extension Complex2 : CaseIterable {} // expected-error {{type 'Complex2' does not conform to protocol 'CaseIterable'}}
extension FromOtherFile: CaseIterable {} // expected-error {{cannot be automatically synthesized in an extension in a different file to the type}}
extension CaseIterableAcrossFiles: CaseIterable {
public static var allCases: [CaseIterableAcrossFiles] {
return [ .A ]
}
}
// No explicit conformance and it cannot be derived.
enum NotExplicitlyHashableAndCannotDerive {
case A(NotHashable) //expected-note {{associated value type 'NotHashable' does not conform to protocol 'Hashable', preventing synthesized conformance of 'NotExplicitlyHashableAndCannotDerive' to 'Hashable'}}
// expected-note@-1 {{associated value type 'NotHashable' does not conform to protocol 'Equatable', preventing synthesized conformance of 'NotExplicitlyHashableAndCannotDerive' to 'Equatable'}}
}
extension NotExplicitlyHashableAndCannotDerive : Hashable {} // expected-error 2 {{does not conform}}
extension NotExplicitlyHashableAndCannotDerive : CaseIterable {} // expected-error {{does not conform}}
// Verify that conformance (albeit manually implemented) can still be added to
// a type in a different file.
extension OtherFileNonconforming: Hashable {
static func ==(lhs: OtherFileNonconforming, rhs: OtherFileNonconforming) -> Bool {
return true
}
func hash(into hasher: inout Hasher) {}
}
// ...but synthesis in a type defined in another file doesn't work yet.
extension YetOtherFileNonconforming: Equatable {} // expected-error {{cannot be automatically synthesized in an extension in a different file to the type}}
extension YetOtherFileNonconforming: CaseIterable {} // expected-error {{does not conform}}
// Verify that an indirect enum doesn't emit any errors as long as its "leaves"
// are conformant.
enum StringBinaryTree: Hashable {
indirect case tree(StringBinaryTree, StringBinaryTree)
case leaf(String)
}
// Add some generics to make it more complex.
enum BinaryTree<Element: Hashable>: Hashable {
indirect case tree(BinaryTree, BinaryTree)
case leaf(Element)
}
// Verify mutually indirect enums.
enum MutuallyIndirectA: Hashable {
indirect case b(MutuallyIndirectB)
case data(Int)
}
enum MutuallyIndirectB: Hashable {
indirect case a(MutuallyIndirectA)
case data(Int)
}
// Verify that it works if the enum itself is indirect, rather than the cases.
indirect enum TotallyIndirect: Hashable {
case another(TotallyIndirect)
case end(Int)
}
// Check the use of conditional conformances.
enum ArrayOfEquatables : Equatable {
case only([Int])
}
struct NotEquatable { }
enum ArrayOfNotEquatables : Equatable { // expected-error{{type 'ArrayOfNotEquatables' does not conform to protocol 'Equatable'}}
case only([NotEquatable]) //expected-note {{associated value type '[NotEquatable]' does not conform to protocol 'Equatable', preventing synthesized conformance of 'ArrayOfNotEquatables' to 'Equatable'}}
}
// Conditional conformances should be able to be synthesized
enum GenericDeriveExtension<T> {
case A(T)
}
extension GenericDeriveExtension: Equatable where T: Equatable {}
extension GenericDeriveExtension: Hashable where T: Hashable {}
// Incorrectly/insufficiently conditional shouldn't work
enum BadGenericDeriveExtension<T> {
case A(T) //expected-note {{associated value type 'T' does not conform to protocol 'Hashable', preventing synthesized conformance of 'BadGenericDeriveExtension<T>' to 'Hashable'}}
//expected-note@-1 {{associated value type 'T' does not conform to protocol 'Equatable', preventing synthesized conformance of 'BadGenericDeriveExtension<T>' to 'Equatable'}}
}
extension BadGenericDeriveExtension: Equatable {} //
// expected-error@-1 {{type 'BadGenericDeriveExtension<T>' does not conform to protocol 'Equatable'}}
extension BadGenericDeriveExtension: Hashable where T: Equatable {}
// expected-error@-1 {{type 'BadGenericDeriveExtension' does not conform to protocol 'Hashable'}}
// But some cases don't need to be conditional, even if they look similar to the
// above
struct AlwaysHashable<T>: Hashable {}
enum UnusedGenericDeriveExtension<T> {
case A(AlwaysHashable<T>)
}
extension UnusedGenericDeriveExtension: Hashable {}
// Cross-file synthesis is disallowed for conditional cases just as it is for
// non-conditional ones.
extension GenericOtherFileNonconforming: Equatable where T: Equatable {}
// expected-error@-1{{implementation of 'Equatable' cannot be automatically synthesized in an extension in a different file to the type}}
// rdar://problem/41852654
// There is a conformance to Equatable (or at least, one that implies Equatable)
// in the same file as the type, so the synthesis is okay. Both orderings are
// tested, to catch choosing extensions based on the order of the files, etc.
protocol ImplierMain: Equatable {}
enum ImpliedMain: ImplierMain {
case a(Int)
}
extension ImpliedOther: ImplierMain {}
// FIXME: Remove -verify-ignore-unknown.
// <unknown>:0: error: unexpected note produced: candidate has non-matching type '(Foo, Foo) -> Bool'
// <unknown>:0: error: unexpected note produced: candidate has non-matching type '<T> (Generic<T>, Generic<T>) -> Bool'
// <unknown>:0: error: unexpected note produced: candidate has non-matching type '(InvalidCustomHashable, InvalidCustomHashable) -> Bool'
// <unknown>:0: error: unexpected note produced: candidate has non-matching type '(EnumToUseBeforeDeclaration, EnumToUseBeforeDeclaration) -> Bool'
| 7845942bc6b8f584b9adacf6a6829af2 | 34.584071 | 209 | 0.738208 | false | false | false | false |
yunzixun/V2ex-Swift | refs/heads/master | Common/V2EXMentionedBindingParser.swift | mit | 1 | //
// V2EXMentionedBindingParser.swift
// V2ex-Swift
//
// Created by huangfeng on 1/25/16.
// Copyright © 2016 Fin. All rights reserved.
//
import UIKit
import YYText
class V2EXMentionedBindingParser: NSObject ,YYTextParser{
var regex:NSRegularExpression
override init() {
self.regex = try! NSRegularExpression(pattern: "@(\\S+)\\s", options: [.caseInsensitive])
super.init()
}
func parseText(_ text: NSMutableAttributedString?, selectedRange: NSRangePointer?) -> Bool {
guard let text = text else {
return false;
}
self.regex.enumerateMatches(in: text.string, options: [.withoutAnchoringBounds], range: text.yy_rangeOfAll()) { (result, flags, stop) -> Void in
if let result = result {
let range = result.range
if range.location == NSNotFound || range.length < 1 {
return ;
}
if text.attribute(NSAttributedStringKey(rawValue: YYTextBindingAttributeName), at: range.location, effectiveRange: nil) != nil {
return ;
}
let bindlingRange = NSMakeRange(range.location, range.length-1)
let binding = YYTextBinding()
binding.deleteConfirm = true ;
text.yy_setTextBinding(binding, range: bindlingRange)
text.yy_setColor(colorWith255RGB(0, g: 132, b: 255), range: bindlingRange)
}
}
return false;
}
}
| 5938af4faef132985d0cfa957040167c | 33.622222 | 152 | 0.574454 | false | false | false | false |
matsprea/omim | refs/heads/master | iphone/Maps/UI/PlacePage/Components/TaxiViewController.swift | apache-2.0 | 1 | protocol TaxiViewControllerDelegate: AnyObject {
func didPressOrder()
}
class TaxiViewController: UIViewController {
@IBOutlet var taxiImageView: UIImageView!
@IBOutlet var taxiNameLabel: UILabel!
var taxiProvider: PlacePageTaxiProvider = .none
weak var delegate: TaxiViewControllerDelegate?
override func viewDidLoad() {
super.viewDidLoad()
switch taxiProvider {
case .none:
assertionFailure()
case .uber:
taxiImageView.image = UIImage(named: "icTaxiUber")
taxiNameLabel.text = L("uber")
case .yandex:
taxiImageView.image = UIImage(named: "ic_taxi_logo_yandex")
taxiNameLabel.text = L("yandex_taxi_title")
case .maxim:
taxiImageView.image = UIImage(named: "ic_taxi_logo_maksim")
taxiNameLabel.text = L("maxim_taxi_title")
case .rutaxi:
taxiImageView.image = UIImage(named: "ic_taxi_logo_vezet")
taxiNameLabel.text = L("vezet_taxi")
case .freenow:
taxiImageView.image = UIImage(named: "ic_logo_freenow")
taxiNameLabel.text = L("freenow_taxi_title")
@unknown default:
fatalError()
}
}
@IBAction func onOrder(_ sender: UIButton) {
delegate?.didPressOrder()
}
}
| 92f8db302753074c8534fbf16722d0e5 | 28.219512 | 65 | 0.685309 | false | false | false | false |
devios1/Gravity | refs/heads/master | Plugins/Appearance.swift | mit | 1 | //
// Appearance.swift
// Gravity
//
// Created by Logan Murray on 2016-02-19.
// Copyright © 2016 Logan Murray. All rights reserved.
//
import Foundation
@available(iOS 9.0, *)
extension Gravity {
@objc public class Appearance: GravityPlugin {
// public override var registeredElements: [String]? {
// get {
// return nil
// }
// }
public override var handledAttributes: [String]? {
get {
return ["color", "font"]
}
}
// public override func processValue(value: GravityNode) -> GravityResult {
// // TODO: convert things like "font" and "color" here (?)
// return .NotHandled
// }
override public func handleAttribute(node: GravityNode, attribute: String?, value: GravityNode?) -> GravityResult {
// this avoids annoying warnings on the console (perhaps find a better way to more accurately determine if the layer is a transform-only layer)
if node.view.isKindOfClass(UIStackView.self) {
return .NotHandled
}
if attribute == "borderColor" || attribute == nil {
if let borderColor = value?.convert() as UIColor? {
node.view.layer.borderColor = borderColor.CGColor
return .Handled
} else {
node.view.layer.borderColor = node.color.CGColor
}
}
if attribute == "borderSize" || attribute == nil {
if let borderSize = value?.floatValue {
node.view.layer.borderWidth = CGFloat(borderSize)
return .Handled
} else {
node.view.layer.borderWidth = 0
}
}
if attribute == "cornerRadius" || attribute == nil {
if let cornerRadius = value?.floatValue {
// TODO: add support for multiple radii, e.g. "5 10", "8 4 10 4"
node.view.layer.cornerRadius = CGFloat(cornerRadius)
node.view.clipsToBounds = true // assume this is still needed
return .Handled
} else {
node.view.layer.cornerRadius = 0
node.view.clipsToBounds = true // false is a bad idea; true seems to work as a default
}
}
return .NotHandled
}
}
}
@available(iOS 9.0, *)
extension GravityNode {
public var color: UIColor {
get {
return getAttribute("color", scope: .Global)?.convert() as UIColor? ?? UIColor.blackColor()
}
}
public var font: UIFont {
get {
return getAttribute("font", scope: .Global)?.convert() as UIFont? ?? UIFont.systemFontOfSize(17) // same as UILabel default font
}
}
} | a14f9e608249cb378bfe38bcc9dbfc60 | 26.406977 | 146 | 0.654924 | false | false | false | false |
ReactiveX/RxSwift | refs/heads/develop | Example/Pods/RxSwift/RxSwift/Observables/Dematerialize.swift | gpl-3.0 | 8 | //
// Dematerialize.swift
// RxSwift
//
// Created by Jamie Pinkham on 3/13/17.
// Copyright © 2017 Krunoslav Zaher. All rights reserved.
//
extension ObservableType where Element: EventConvertible {
/**
Convert any previously materialized Observable into it's original form.
- seealso: [materialize operator on reactivex.io](http://reactivex.io/documentation/operators/materialize-dematerialize.html)
- returns: The dematerialized observable sequence.
*/
public func dematerialize() -> Observable<Element.Element> {
Dematerialize(source: self.asObservable())
}
}
private final class DematerializeSink<T: EventConvertible, Observer: ObserverType>: Sink<Observer>, ObserverType where Observer.Element == T.Element {
fileprivate func on(_ event: Event<T>) {
switch event {
case .next(let element):
self.forwardOn(element.event)
if element.event.isStopEvent {
self.dispose()
}
case .completed:
self.forwardOn(.completed)
self.dispose()
case .error(let error):
self.forwardOn(.error(error))
self.dispose()
}
}
}
final private class Dematerialize<T: EventConvertible>: Producer<T.Element> {
private let source: Observable<T>
init(source: Observable<T>) {
self.source = source
}
override func run<Observer: ObserverType>(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == T.Element {
let sink = DematerializeSink<T, Observer>(observer: observer, cancel: cancel)
let subscription = self.source.subscribe(sink)
return (sink: sink, subscription: subscription)
}
}
| 6fbc314df2529e9ec98f0c3c174d9acf | 33.705882 | 173 | 0.661017 | false | false | false | false |
CodaFi/PersistentStructure.swift | refs/heads/master | Persistent/PersistentTreeSet.swift | mit | 1 | //
// PersistentTreeSet.swift
// Persistent
//
// Created by Robert Widmann on 12/23/15.
// Copyright © 2015 TypeLift. All rights reserved.
//
private let EMPTY : PersistentTreeSet = PersistentTreeSet(meta: nil, implementation: PersistentTreeMap.empty())
public class PersistentTreeSet: AbstractPersistentSet, IObj, IReversible, ISorted {
private var _meta: IPersistentMap?
class func create(items: ISeq) -> PersistentTreeSet {
var ret: PersistentTreeSet = EMPTY
for entry in items.generate() {
ret = ret.cons(entry) as! PersistentTreeSet
}
return ret
}
class func create(comparator: (AnyObject?, AnyObject?) -> NSComparisonResult, items: ISeq) -> PersistentTreeSet {
let impl: PersistentTreeMap = PersistentTreeMap(meta: nil, comparator: comparator)
var ret: PersistentTreeSet = PersistentTreeSet(meta: nil, implementation: impl)
for entry in items.generate() {
ret = ret.cons(entry) as! PersistentTreeSet
}
return ret
}
init(meta: IPersistentMap?, implementation impl: IPersistentMap) {
super.init(impl: impl)
_meta = meta
}
public override func disjoin(key: AnyObject) -> IPersistentSet {
if self.containsObject(key) {
return PersistentTreeSet(meta: self.meta, implementation: _impl.without(key))
}
return self
}
public override func cons(other : AnyObject) -> IPersistentCollection {
if self.containsObject(other) {
return self
}
return PersistentTreeSet(meta: self.meta, implementation: _impl.associateKey(other, withValue: other) as! IPersistentMap)
}
public override var empty : IPersistentCollection {
return PersistentTreeSet(meta: self.meta, implementation: PersistentTreeMap.empty())
}
public var reversedSeq : ISeq {
return KeySeq(seq: (_impl as! IReversible).reversedSeq)
}
public func withMeta(meta: IPersistentMap?) -> IObj {
return PersistentTreeSet(meta: meta, implementation: _impl)
}
public var comparator : (AnyObject?, AnyObject?) -> NSComparisonResult {
return (_impl as! ISorted).comparator
}
public func entryKey(entry: AnyObject) -> AnyObject? {
return entry
}
public func seq(ascending: Bool) -> ISeq? {
let m: PersistentTreeMap = _impl as! PersistentTreeMap
return Utils.keys(m.seq(ascending)!)
}
public func seqFrom(key: AnyObject, ascending: Bool) -> ISeq? {
let m: PersistentTreeMap = _impl as! PersistentTreeMap
return Utils.keys(m.seqFrom(key, ascending: ascending)!)
}
var meta : IPersistentMap? {
return _meta
}
}
| adffdea1cbad0d7392646b3198479bcf | 28.638554 | 123 | 0.732927 | false | false | false | false |
suifengqjn/CatLive | refs/heads/master | CatLive/CatLive/Classes/Tools/Emitterable.swift | apache-2.0 | 1 | //
// Emitterable.swift
// CatLive
//
// Created by qianjn on 2017/6/29.
// Copyright © 2017年 SF. All rights reserved.
//
import UIKit
//面向协议开发,类似于多继承,遵守某个协议,就拥有协议中的方法
protocol Emitterable {
}
// 对协议进行约束, 只有是UIViewController 的子类 才能 遵守这个协议
extension Emitterable where Self: UIViewController {
func startEmitter() {
// 1.创建发射器
let emitter = CAEmitterLayer()
// 2.设置发射器的位置
emitter.emitterPosition = CGPoint(x: view.bounds.width - 50, y: view.bounds.height - 60)
// 3.开启三维效果
emitter.preservesDepth = true
// 4.创建例子, 并且设置例子相关的属性
// 4.1.创建例子Cell
let cell = CAEmitterCell()
// 4.2.设置粒子速度
cell.velocity = 150
cell.velocityRange = 100
// 4.3.设置例子的大小
cell.scale = 0.7
cell.scaleRange = 0.3
// 4.4.设置粒子方向
cell.emissionLongitude = CGFloat(-Double.pi / 2)
cell.emissionRange = CGFloat(Double.pi / 2 / 6)
// 4.5.设置例子的存活时间
cell.lifetime = 6
cell.lifetimeRange = 1.5
// 4.6.设置粒子旋转
cell.spin = CGFloat(Double.pi / 2)
cell.spinRange = CGFloat(Double.pi / 2 / 2)
// 4.6.设置例子每秒弹出的个数
cell.birthRate = 20
// 4.7.设置粒子展示的图片
cell.contents = UIImage(named: "good6_30x30")?.cgImage
// 5.将粒子设置到发射器中
emitter.emitterCells = [cell]
// 6.将发射器的layer添加到父layer中
view.layer.addSublayer(emitter)
}
func stopEmittering() {
/*
for layer in view.layer.sublayers! {
if layer.isKind(of: CAEmitterLayer.self) {
layer.removeFromSuperlayer()
}
}
*/
view.layer.sublayers?.filter({ $0.isKind(of: CAEmitterLayer.self)}).first?.removeFromSuperlayer()
}
}
| 9bcb0922b7f8284c8e391be855328d01 | 23.115385 | 105 | 0.54386 | false | false | false | false |
edx/edx-app-ios | refs/heads/master | Source/CourseHandoutsViewController.swift | apache-2.0 | 1 | //
// CourseHandoutsViewController.swift
// edX
//
// Created by Ehmad Zubair Chughtai on 26/06/2015.
// Copyright (c) 2015 edX. All rights reserved.
//
import UIKit
import WebKit
public class CourseHandoutsViewController: OfflineSupportViewController, LoadStateViewReloadSupport, InterfaceOrientationOverriding {
public typealias Environment = DataManagerProvider & NetworkManagerProvider & ReachabilityProvider & OEXAnalyticsProvider & OEXStylesProvider & OEXConfigProvider
let courseID : String
let environment : Environment
let webView : WKWebView
let loadController : LoadStateViewController
let handouts : BackedStream<String> = BackedStream()
init(environment : Environment, courseID : String) {
self.environment = environment
self.courseID = courseID
self.webView = WKWebView(frame: .zero, configuration: environment.config.webViewConfiguration())
self.loadController = LoadStateViewController()
super.init(env: environment)
addListener()
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override public func viewDidLoad() {
super.viewDidLoad()
loadController.setupInController(controller: self, contentView: webView)
addSubviews()
setConstraints()
setStyles()
webView.navigationDelegate = self
view.backgroundColor = environment.styles.standardBackgroundColor()
setAccessibilityIdentifiers()
}
public override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
environment.analytics.trackScreen(withName: OEXAnalyticsScreenHandouts, courseID: courseID, value: nil)
loadHandouts()
}
override func reloadViewData() {
loadHandouts()
}
override public var shouldAutorotate: Bool {
return true
}
override public var supportedInterfaceOrientations: UIInterfaceOrientationMask {
return .allButUpsideDown
}
private func setAccessibilityIdentifiers() {
view.accessibilityIdentifier = "CourseHandoutsViewController:view"
webView.accessibilityIdentifier = "CourseHandoutsViewController:web-view"
}
private func addSubviews() {
view.addSubview(webView)
}
private func setConstraints() {
webView.snp.makeConstraints { make in
make.edges.equalTo(safeEdges)
}
}
private func setStyles() {
self.navigationItem.title = Strings.courseHandouts
}
private func streamForCourse(course : OEXCourse) -> OEXStream<String>? {
if let access = course.courseware_access, !access.has_access {
return OEXStream<String>(error: OEXCoursewareAccessError(coursewareAccess: access, displayInfo: course.start_display_info))
}
else {
let request = CourseInfoAPI.getHandoutsForCourseWithID(courseID: courseID, overrideURL: course.course_handouts)
let loader = self.environment.networkManager.streamForRequest(request, persistResponse: true)
return loader
}
}
private func loadHandouts() {
if !handouts.active {
loadController.state = .Initial
let courseStream = self.environment.dataManager.enrollmentManager.streamForCourseWithID(courseID: courseID)
let handoutStream = courseStream.transform {[weak self] enrollment in
return self?.streamForCourse(course: enrollment.course) ?? OEXStream<String>(error : NSError.oex_courseContentLoadError())
}
self.handouts.backWithStream((courseStream.value != nil) ? handoutStream : OEXStream<String>(error : NSError.oex_courseContentLoadError()))
}
}
private func addListener() {
handouts.listen(self, success: { [weak self] courseHandouts in
if let
displayHTML = OEXStyles.shared().styleHTMLContent(courseHandouts, stylesheet: "handouts-announcements"),
let apiHostUrl = OEXConfig.shared().apiHostURL()
{
self?.webView.loadHTMLString(displayHTML, baseURL: apiHostUrl)
self?.loadController.state = .Loaded
}
else {
self?.loadController.state = LoadState.failed()
}
}, failure: {[weak self] error in
self?.loadController.state = LoadState.failed(error: error)
} )
}
override public func updateViewConstraints() {
loadController.insets = UIEdgeInsets(top: view.safeAreaInsets.top, left: 0, bottom: view.safeAreaInsets.bottom, right: 0)
super.updateViewConstraints()
}
//MARK:- LoadStateViewReloadSupport method
func loadStateViewReload() {
loadHandouts()
}
}
extension CourseHandoutsViewController: WKNavigationDelegate {
public func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
switch navigationAction.navigationType {
case .linkActivated, .formSubmitted, .formResubmitted:
if let URL = navigationAction.request.url, UIApplication.shared.canOpenURL(URL){
UIApplication.shared.open(URL, options: [:], completionHandler: nil)
}
decisionHandler(.cancel)
default:
decisionHandler(.allow)
}
}
}
| 90b2797e5d73baccda09f3cb3a893e37 | 35.907285 | 165 | 0.665351 | false | false | false | false |
ftxbird/NetEaseMoive | refs/heads/master | NetEaseMoive/NetEaseMoive/Movie/Controller/MovieViewController.swift | mit | 1 | //
// MovieViewController.swift
// NetEaseMoive
//
// Created by ftxbird on 15/11/28.
// Copyright © 2015年 swiftMe. All rights reserved.
//
import UIKit
import Alamofire
import AlamofireObjectMapper
class MovieViewController: UIViewController {
@IBOutlet weak var tableView: UITableView!
var swipeVC = SESwipeMovieViewController()
var movies:[SEMoiveModel]? = [] {
didSet{
tableView.reloadData()
}
}
override func viewDidLoad() {
super.viewDidLoad()
configUI()
requestDataSource()
}
// MARK: -数据源获取
func requestDataSource() {
//待整理
let url = "http://piao.163.com/m/movie/list.html?app_id=2&mobileType=iPhone&ver=3.7.1&channel=lede&deviceId=694045B8-1E5F-4237-BE59-929C5A5922A2&apiVer=21&city=110000"
Alamofire.request(.GET, url).responseObject { (response: Response<SEMoiveList, NSError>) in
let movieList = response.result.value
if let list : [SEMoiveModel] = movieList?.movies {
self.movies = list
}
}
}
// MARK: -UI设置 --后期加入UI配置中心
func configUI() {
//设置tableView
tableView.backgroundColor = UIColor.whiteColor()
tableView.delegate = self
tableView.dataSource = self
tableView.separatorStyle = .None
let nib: UINib = UINib(nibName: "SEMovieTableViewCell", bundle: NSBundle.mainBundle())
tableView.registerNib(nib, forCellReuseIdentifier: "SEMovieTableViewCell")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
// MARK: -tableview delegate & datasource
extension MovieViewController :UITableViewDataSource,UITableViewDelegate {
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return (movies?.count)!
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("SEMovieTableViewCell") as? SEMovieTableViewCell
cell!.configCellForModel((movies?[indexPath.row])!)
return cell!
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 110
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
}
}
| 166fa8744df3e49caa8a82ddb28064bf | 26.623762 | 175 | 0.634409 | false | false | false | false |
certificate-helper/TLS-Inspector | refs/heads/master | TLS Inspector/View Controllers/AdvancedOptionsTableViewController.swift | gpl-3.0 | 1 | import UIKit
class AdvancedOptionsTableViewController: UITableViewController {
var segmentControl: UISegmentedControl?
override func viewDidLoad() {
super.viewDidLoad()
if !UserOptions.advancedSettingsNagDismissed {
UIHelper(self).presentAlert(title: lang(key: "Warning"), body: lang(key: "advanced_settings_nag"), dismissed: nil)
UserOptions.advancedSettingsNagDismissed = true
}
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
return UserOptions.useOpenSSL ? 2 : 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, titleForFooterInSection section: Int) -> String? {
if section == 0 {
return lang(key: "crypto_engine_footer")
}
return nil
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell: UITableViewCell!
if indexPath.section == 0 {
cell = tableView.dequeueReusableCell(withIdentifier: "Segment", for: indexPath)
if let label = cell.viewWithTag(1) as? UILabel {
label.text = lang(key: "Crypto Engine")
}
self.segmentControl = cell.viewWithTag(2) as? UISegmentedControl
self.segmentControl?.setTitle("iOS", forSegmentAt: 0)
self.segmentControl?.setTitle("OpenSSL", forSegmentAt: 1)
self.segmentControl?.selectedSegmentIndex = UserOptions.useOpenSSL ? 1 : 0
self.segmentControl?.addTarget(self, action: #selector(self.changeCryptoEngine(sender:)), for: .valueChanged)
} else if indexPath.section == 1 {
cell = tableView.dequeueReusableCell(withIdentifier: "Input", for: indexPath)
if let label = cell.viewWithTag(1) as? UILabel {
label.text = lang(key: "Ciphers")
}
if let input = cell.viewWithTag(2) as? UITextField {
input.placeholder = "HIGH:!aNULL:!MD5:!RC4"
input.text = UserOptions.preferredCiphers
input.addTarget(self, action: #selector(changeCiphers(_:)), for: .editingChanged)
}
}
return cell
}
@objc func changeCryptoEngine(sender: UISegmentedControl) {
UserOptions.useOpenSSL = sender.selectedSegmentIndex == 1
if sender.selectedSegmentIndex == 1 {
self.tableView.insertSections(IndexSet(arrayLiteral: 1), with: .fade)
} else {
self.tableView.deleteSections(IndexSet(arrayLiteral: 1), with: .fade)
}
}
@objc func changeCiphers(_ sender: UITextField) {
UserOptions.preferredCiphers = sender.text ?? ""
}
}
| dbfac1aa71b0eef62dce0ed1a9e24b0a | 38.246575 | 126 | 0.634206 | false | false | false | false |
xplorld/WordOuroboros | refs/heads/master | WordOuroboros/WordView.swift | mit | 1 | //
// WordView.swift
// WordOuroboros
//
// Created by Xplorld on 2015/6/10.
// Copyright (c) 2015年 Xplorld. All rights reserved.
//
import UIKit
class WordView: UIView {
@IBOutlet var label:UILabel!
@IBOutlet weak var detailLabel: UILabel!
weak var word:WordType! {
didSet {
if word != nil {
label.text = word.string
detailLabel.text = word.detailedString
backgroundColor = word.color
self.setNeedsUpdateConstraints()
}
}
}
override func awakeFromNib() {
super.awakeFromNib()
label.textColor = WOColor.textColor
detailLabel.textColor = WOColor.textColor
label.adjustsFontSizeToFitWidth = true
}
}
| e040789aeac1b2813462bc26bfbcc975 | 23.1875 | 54 | 0.589147 | false | false | false | false |
eurofurence/ef-app_ios | refs/heads/release/4.0.0 | Packages/EurofurenceApplication/Sources/EurofurenceApplication/Application/Components/News/Widgets/Announcements/View Model/AnnouncementWidgetContent.swift | mit | 1 | public enum AnnouncementWidgetContent<ViewModel>: Equatable where ViewModel: NewsAnnouncementViewModel {
public static func == (lhs: AnnouncementWidgetContent, rhs: AnnouncementWidgetContent) -> Bool {
switch (lhs, rhs) {
case (.showMoreAnnouncements, .showMoreAnnouncements):
return true
case (.announcement(let lhs), .announcement(let rhs)):
return lhs === rhs
default:
return false
}
}
case showMoreAnnouncements
case announcement(ViewModel)
public var viewModel: ViewModel? {
if case .announcement(let viewModel) = self {
return viewModel
} else {
return nil
}
}
}
| 9eb743a98bc83a74aa6baa67a25efeb5 | 27.259259 | 104 | 0.583224 | false | false | false | false |
montehurd/apps-ios-wikipedia | refs/heads/develop | Wikipedia/Code/URL+WMFLinkParsing.swift | mit | 1 | import Foundation
extension CharacterSet {
public static var wmf_articleTitlePathComponentAllowed: CharacterSet {
return NSCharacterSet.wmf_URLArticleTitlePathComponentAllowed()
}
static let urlQueryComponentAllowed: CharacterSet = {
var characterSet = CharacterSet.urlQueryAllowed
characterSet.remove(charactersIn: "+&=")
return characterSet
}()
}
extension URL {
/// Returns a new URL with the existing scheme replaced with the wikipedia:// scheme
public var replacingSchemeWithWikipediaScheme: URL? {
var components = URLComponents(url: self, resolvingAgainstBaseURL: false)
components?.scheme = "wikipedia"
return components?.url
}
public var wmf_percentEscapedTitle: String? {
return wmf_titleWithUnderscores?.addingPercentEncoding(withAllowedCharacters: .wmf_articleTitlePathComponentAllowed)
}
public var wmf_language: String? {
return (self as NSURL).wmf_language
}
public var wmf_title: String? {
return (self as NSURL).wmf_title
}
public var wmf_titleWithUnderscores: String? {
return (self as NSURL).wmf_titleWithUnderscores
}
public var wmf_databaseKey: String? {
return (self as NSURL).wmf_databaseKey
}
public var wmf_site: URL? {
return (self as NSURL).wmf_site
}
public func wmf_URL(withTitle title: String) -> URL? {
return (self as NSURL).wmf_URL(withTitle: title)
}
public func wmf_URL(withFragment fragment: String) -> URL? {
return (self as NSURL).wmf_URL(withFragment: fragment)
}
public func wmf_URL(withPath path: String, isMobile: Bool) -> URL? {
return (self as NSURL).wmf_URL(withPath: path, isMobile: isMobile)
}
public var wmf_isNonStandardURL: Bool {
return (self as NSURL).wmf_isNonStandardURL
}
public var wmf_wiki: String? {
return wmf_language?.replacingOccurrences(of: "-", with: "_").appending("wiki")
}
fileprivate func wmf_URLForSharing(with wprov: String) -> URL {
let queryItems = [URLQueryItem(name: "wprov", value: wprov)]
var components = URLComponents(url: self, resolvingAgainstBaseURL: false)
components?.queryItems = queryItems
return components?.url ?? self
}
// URL for sharing text only
public var wmf_URLForTextSharing: URL {
return wmf_URLForSharing(with: "sfti1")
}
// URL for sharing that includes an image (for example, Share-a-fact)
public var wmf_URLForImageSharing: URL {
return wmf_URLForSharing(with: "sfii1")
}
public var canonical: URL {
return (self as NSURL).wmf_canonical ?? self
}
public var wikiResourcePath: String? {
return path.wikiResourcePath
}
public var wResourcePath: String? {
return path.wResourcePath
}
public var namespace: PageNamespace? {
guard let language = wmf_language else {
return nil
}
return wikiResourcePath?.namespaceOfWikiResourcePath(with: language)
}
public var namespaceAndTitle: (namespace: PageNamespace, title: String)? {
guard let language = wmf_language else {
return nil
}
return wikiResourcePath?.namespaceAndTitleOfWikiResourcePath(with: language)
}
}
extension NSRegularExpression {
func firstMatch(in string: String) -> NSTextCheckingResult? {
return firstMatch(in: string, options: [], range: NSMakeRange(0, string.count))
}
func firstReplacementString(in string: String, template: String = "$1") -> String? {
guard let result = firstMatch(in: string)
else {
return nil
}
return replacementString(for: result, in: string, offset: 0, template: template)
}
}
extension String {
static let namespaceRegex = try! NSRegularExpression(pattern: "^(.+?)_*:_*(.*)$")
// Assumes the input is the remainder of a /wiki/ path
func namespaceOfWikiResourcePath(with language: String) -> PageNamespace {
guard let namespaceString = String.namespaceRegex.firstReplacementString(in: self) else {
return .main
}
return WikipediaURLTranslations.commonNamespace(for: namespaceString, in: language) ?? .main
}
func namespaceAndTitleOfWikiResourcePath(with language: String) -> (namespace: PageNamespace, title: String) {
guard let result = String.namespaceRegex.firstMatch(in: self) else {
return (.main, self)
}
let namespaceString = String.namespaceRegex.replacementString(for: result, in: self, offset: 0, template: "$1")
guard let namespace = WikipediaURLTranslations.commonNamespace(for: namespaceString, in: language) else {
return (.main, self)
}
let title = String.namespaceRegex.replacementString(for: result, in: self, offset: 0, template: "$2")
return (namespace, title)
}
static let wikiResourceRegex = try! NSRegularExpression(pattern: "^/wiki/(.+)$", options: .caseInsensitive)
var wikiResourcePath: String? {
return String.wikiResourceRegex.firstReplacementString(in: self)
}
static let wResourceRegex = try! NSRegularExpression(pattern: "^/w/(.+)$", options: .caseInsensitive)
public var wResourcePath: String? {
return String.wResourceRegex.firstReplacementString(in: self)
}
}
@objc extension NSURL {
// deprecated - use namespace methods
@objc var wmf_isWikiResource: Bool {
return (self as URL).wikiResourcePath != nil
}
}
@objc extension NSString {
// deprecated - use namespace methods
@objc var wmf_isWikiResource: Bool {
return (self as String).wikiResourcePath != nil
}
// deprecated - use swift methods
@objc var wmf_pathWithoutWikiPrefix: String? {
return (self as String).wikiResourcePath
}
}
| d786f923b31961a586a4bded7519b3e1 | 32.814607 | 124 | 0.654926 | false | false | false | false |
BlueTatami/Angle | refs/heads/master | Angle/Angle.swift | mit | 1 | //
// Angle.swift
// Angle
//
// Created by Alexandre Lopoukhine on 09/12/2015.
// Copyright © 2015 bluetatami. All rights reserved.
//
/// Struct acts as a wrapper for an angle value in degrees.
public struct Angle {
/// Always in the range 0 ..< 360.0
public var degrees: Double {
didSet {
guard degrees < 0 || 360 <= degrees else { return }
degrees.formTruncatingRemainder(dividingBy: 360)
if degrees < 0 {
degrees += 360
}
}
}
public init(degrees: Double) {
self.degrees = degrees
guard degrees < 0 || 360 <= degrees else { return }
self.degrees.formTruncatingRemainder(dividingBy: 360)
if degrees < 0 {
self.degrees += 360
}
}
public static func degreesToRadians(_ degrees: Double) -> Double {
return degrees * Double.pi / 180
}
public static func radiansToDegrees(_ radians: Double) -> Double {
return radians * 180 / Double.pi
}
}
extension Angle {
public var radians: Double {
get {
return Angle.degreesToRadians(degrees)
}
set {
degrees = Angle.radiansToDegrees(newValue)
}
}
public init(radians: Double) {
self = Angle(degrees: Angle.radiansToDegrees(radians))
}
}
// MARK: Equatable
extension Angle: Equatable {}
public func ==(lhs: Angle, rhs: Angle) -> Bool {
return lhs.degrees == rhs.degrees
}
// MARK: CustomStringConvertible
extension Angle: CustomStringConvertible {
public var description: String {
return "\(degrees)°"
}
}
| 76c57f569570f2d1a75ce453614b4115 | 22.424658 | 70 | 0.566082 | false | false | false | false |
apple/swift | refs/heads/main | test/IRGen/prespecialized-metadata/struct-extradata-run.swift | apache-2.0 | 2 | // RUN: %empty-directory(%t)
// RUN: %clang -c -v %target-cc-options %target-threading-opt -g -O0 -isysroot %sdk %S/Inputs/extraDataFields.cpp -o %t/extraDataFields.o -I %clang-include-dir -I %swift_src_root/include/ -I %swift_src_root/stdlib/public/SwiftShims/ -I %llvm_src_root/include -I %llvm_obj_root/include -L %clang-include-dir/../lib/swift/macosx -I %swift_obj_root/include
// RUN: %target-build-swift -c %S/Inputs/struct-extra-data-fields.swift -emit-library -emit-module -module-name ExtraDataFieldsNoTrailingFlags -target %module-target-future -Xfrontend -disable-generic-metadata-prespecialization -emit-module-path %t/ExtraDataFieldsNoTrailingFlags.swiftmodule -o %t/%target-library-name(ExtraDataFieldsNoTrailingFlags)
// RUN: %target-build-swift -c %S/Inputs/struct-extra-data-fields.swift -emit-library -emit-module -module-name ExtraDataFieldsTrailingFlags -target %module-target-future -Xfrontend -prespecialize-generic-metadata -emit-module-path %t/ExtraDataFieldsTrailingFlags.swiftmodule -o %t/%target-library-name(ExtraDataFieldsTrailingFlags)
// RUN: %target-build-swift -v %mcp_opt %s %t/extraDataFields.o -import-objc-header %S/Inputs/extraDataFields.h -Xfrontend -disable-generic-metadata-prespecialization -target %module-target-future -lc++ -L %clang-include-dir/../lib/swift/macosx -sdk %sdk -o %t/main -I %t -L %t -lExtraDataFieldsTrailingFlags -lExtraDataFieldsNoTrailingFlags -module-name main
// RUN: %target-codesign %t/main
// RUN: %target-run %t/main | %FileCheck %s
// REQUIRES: OS=macosx
// REQUIRES: executable_test
// UNSUPPORTED: use_os_stdlib
// UNSUPPORTED: swift_test_mode_optimize
// UNSUPPORTED: swift_test_mode_optimize_size
func ptr<T>(to ty: T.Type) -> UnsafeMutableRawPointer {
UnsafeMutableRawPointer(mutating: unsafePointerToMetadata(of: ty))!
}
func unsafePointerToMetadata<T>(of ty: T.Type) -> UnsafePointer<T.Type> {
unsafeBitCast(ty, to: UnsafePointer<T.Type>.self)
}
import ExtraDataFieldsNoTrailingFlags
let one = completeMetadata(
ptr(
to: ExtraDataFieldsNoTrailingFlags.FixedFieldOffsets<Void>.self
)
)
// CHECK: nil
print(
trailingFlagsForStructMetadata(
one
)
)
guard let oneOffsets = fieldOffsetsForStructMetadata(one) else {
fatalError("no field offsets")
}
// CHECK-NEXT: 0
print(oneOffsets.advanced(by: 0).pointee)
// CHECK-NEXT: 8
print(oneOffsets.advanced(by: 1).pointee)
let two = completeMetadata(
ptr(
to: ExtraDataFieldsNoTrailingFlags.DynamicFieldOffsets<Int32>.self
)
)
// CHECK-NEXT: nil
print(
trailingFlagsForStructMetadata(
two
)
)
guard let twoOffsets = fieldOffsetsForStructMetadata(two) else {
fatalError("no field offsets")
}
// CHECK-NEXT: 0
print(twoOffsets.advanced(by: 0).pointee)
// CHECK-NEXT: 4
print(twoOffsets.advanced(by: 1).pointee)
import ExtraDataFieldsTrailingFlags
let three = completeMetadata(
ptr(
to: ExtraDataFieldsTrailingFlags.FixedFieldOffsets<Void>.self
)
)
// CHECK-NEXT: 0
print(
trailingFlagsForStructMetadata(
three
)!.pointee
)
guard let threeOffsets = fieldOffsetsForStructMetadata(three) else {
fatalError("no field offsets")
}
// CHECK-NEXT: 0
print(threeOffsets.advanced(by: 0).pointee)
// CHECK-NEXT: 8
print(threeOffsets.advanced(by: 1).pointee)
let four = completeMetadata(
ptr(
to: ExtraDataFieldsTrailingFlags.DynamicFieldOffsets<Int32>.self
)
)
// CHECK-NEXT: 0
print(
trailingFlagsForStructMetadata(
four
)!.pointee
)
guard let fourOffsets = fieldOffsetsForStructMetadata(four) else {
fatalError("no field offsets")
}
// CHECK-NEXT: 0
print(fourOffsets.advanced(by: 0).pointee)
// CHECK-NEXT: 4
print(fourOffsets.advanced(by: 1).pointee)
| 7b0600fd9969d52760c7ef902094e34c | 29.798319 | 359 | 0.755252 | false | false | false | false |
garygriswold/Bible.js | refs/heads/master | OBSOLETE/YourBible/plugins/com-shortsands-utility/src/ios/Utility/DeviceSettings.swift | mit | 1 | //
// DeviceSettings.swift
// TempDevice
//
// Created by Gary Griswold on 1/8/18.
// Copyright © 2018 ShortSands. All rights reserved.
//
import UIKit
public class DeviceSettings {
static func modelName() -> String {
#if (arch(i386) || arch(x86_64)) && os(iOS)
let DEVICE_IS_SIMULATOR = true
#else
let DEVICE_IS_SIMULATOR = false
#endif
var machineString : String = ""
if DEVICE_IS_SIMULATOR == true {
if let dir = ProcessInfo().environment["SIMULATOR_MODEL_IDENTIFIER"] {
machineString = dir
}
}
else {
var systemInfo = utsname()
uname(&systemInfo)
let machineMirror = Mirror(reflecting: systemInfo.machine)
machineString = machineMirror.children.reduce("") { identifier, element in
guard let value = element.value as? Int8, value != 0 else { return identifier }
return identifier + String(UnicodeScalar(UInt8(value)))
}
}
switch machineString {
case "iPhone3,1", "iPhone3,2", "iPhone3,3": return "iPhone 4"
case "iPhone4,1": return "iPhone 4s"
case "iPhone5,1", "iPhone5,2": return "iPhone 5"
case "iPhone5,3", "iPhone5,4": return "iPhone 5c"
case "iPhone6,1", "iPhone6,2": return "iPhone 5s"
case "iPhone7,2": return "iPhone 6"
case "iPhone7,1": return "iPhone 6 Plus"
case "iPhone8,1": return "iPhone 6s"
case "iPhone8,2": return "iPhone 6s Plus"
case "iPhone9,1", "iPhone9,3": return "iPhone 7"
case "iPhone9,2", "iPhone9,4": return "iPhone 7 Plus"
case "iPhone8,4": return "iPhone SE"
case "iPhone10,1", "iPhone10,4": return "iPhone 8"
case "iPhone10,2", "iPhone10,5": return "iPhone 8 Plus"
case "iPhone10,3", "iPhone10,6": return "iPhone X"
case "iPad2,1", "iPad2,2", "iPad2,3", "iPad2,4":return "iPad 2"
case "iPad3,1", "iPad3,2", "iPad3,3": return "iPad 3"
case "iPad3,4", "iPad3,5", "iPad3,6": return "iPad 4"
case "iPad4,1", "iPad4,2", "iPad4,3": return "iPad Air"
case "iPad5,3", "iPad5,4": return "iPad Air 2"
case "iPad6,11", "iPad6,12": return "iPad 5"
case "iPad2,5", "iPad2,6", "iPad2,7": return "iPad Mini"
case "iPad4,4", "iPad4,5", "iPad4,6": return "iPad Mini 2"
case "iPad4,7", "iPad4,8", "iPad4,9": return "iPad Mini 3"
case "iPad5,1", "iPad5,2": return "iPad Mini 4"
case "iPad6,3", "iPad6,4": return "iPad Pro 9.7 Inch"
case "iPad6,7", "iPad6,8": return "iPad Pro 12.9 Inch"
case "iPad7,1", "iPad7,2": return "iPad Pro 12.9 Inch 2. Generation"
case "iPad7,3", "iPad7,4": return "iPad Pro 10.5 Inch"
case "i386", "x86_64": return "Simulator"
default: return machineString
}
}
static func deviceSize() -> String {
let height = UIScreen.main.nativeBounds.height
let width = UIScreen.main.nativeBounds.width
let bigger = max(height, width)
switch bigger {
case 1136:
return "iPhone 5/5s/5c/SE"
case 1334:
return "iPhone 6/6s/7/8"
case 2048:
return "iPad 5/Air/Air 2/Pro 9.7 Inch"
case 2208:
return "iPhone 6+/6s+/7+/8+"
case 2224:
return "iPad Pro 10.5 Inch"
case 2436:
return "iPhone X"
case 2732:
return "iPad Pro 12.9 Inch"
default:
return "type Unknown \(width) \(height)"
}
}
}
| 36122ebb3578e52b3b39d2b45b88bd59 | 43.589474 | 97 | 0.475449 | false | false | false | false |
zhoujihang/SwiftNetworkAgent | refs/heads/master | SwiftNetworkAgent/SwiftNetworkAgent/Extension/UIViewControllerExtension.swift | mit | 1 | //
// UIViewControllerExtension.swift
// SwiftNetworkAgent
//
// Created by 周际航 on 2017/3/15.
// Copyright © 2017年 com.zjh. All rights reserved.
//
import UIKit
// MARK: - 扩展 hierarchy
extension UIViewController {
// 该 vc 下,最后一个 presented 的vc
func ext_lastPresentedViewController() -> UIViewController? {
guard var vc = self.presentedViewController else {return nil}
while vc.presentedViewController != nil {
vc = vc.presentedViewController!
}
return vc
}
// 该 vc 下,显示在最上层的 vc
func ext_topShowViewController() -> UIViewController {
if let topPresentVC = self.ext_lastPresentedViewController() {
return topPresentVC.ext_topShowViewController()
}
if let tabBarVC = self as? UITabBarController {
guard let selectedVC = tabBarVC.selectedViewController else {return self}
return selectedVC.ext_topShowViewController()
}
if let navVC = self as? UINavigationController {
guard let topVC = navVC.topViewController else {return self}
return topVC.ext_topShowViewController()
}
return self
}
}
| 9600621aa69da4c4768363da1c3cd5c1 | 31.611111 | 85 | 0.651618 | false | false | false | false |
SuPair/firefox-ios | refs/heads/master | Shared/LaunchArguments.swift | mpl-2.0 | 3 | /* 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
public struct LaunchArguments {
public static let Test = "FIREFOX_TEST"
public static let SkipIntro = "FIREFOX_SKIP_INTRO"
public static let SkipWhatsNew = "FIREFOX_SKIP_WHATS_NEW"
public static let ClearProfile = "FIREFOX_CLEAR_PROFILE"
public static let StageServer = "FIREFOX_USE_STAGE_SERVER"
public static let DeviceName = "DEVICE_NAME"
// After the colon, put the name of the file to load from test bundle
public static let LoadDatabasePrefix = "FIREFOX_LOAD_DB_NAMED:"
}
| 048f083f22926e3087108ac23999092e | 42.294118 | 73 | 0.726902 | false | true | false | false |
rain2540/Play-with-Algorithms-in-Swift | refs/heads/master | LeetCode/01-Array.playground/Pages/Pascal Triangle.xcplaygroundpage/Contents.swift | mit | 1 | //: [Previous](@previous)
import Foundation
//: ## Pascal's Triangle
//:
//: Given numRows, generate the first numRows of Pascal's triangle.
//:
//: For example, given numRows = 5, Return
//:
//: [
//:
//: [1],
//:
//: [1,1],
//:
//: [1,2,1],
//:
//: [1,3,3,1],
//:
//:[1,4,6,4,1]
//:
//: ]
//: 分析
//:
//: 帕斯卡三角有如下的规律
//:
//: * 第 k 层有 k 个元素
//:
//: * 每层第一个以及最后一个元素值为 1
//:
//: * 对于第 k (k > 2) 层第 n (n > 1 && n < k) 个元素 A[k][n], A[k][n] = A[k - 1][n - 1] + A[k - 1][n]
func generate(numRows: Int) -> Array<[Int]> {
var vals = Array<[Int]>(repeating: [], count: numRows)
for i in 0 ..< numRows {
vals[i] = [Int](repeating: 0, count: i + 1)
vals[i][0] = 1
vals[i][vals[i].count - 1] = 1
if i > 0 {
for j in 1 ..< vals[i].count - 1 {
vals[i][j] = vals[i - 1][j - 1] + vals[i - 1][j]
}
}
}
return vals
}
print(generate(numRows: 5))
//: [Next](@next)
| 254387b41d5676cf3ccc49f1d909724f | 16.381818 | 94 | 0.441423 | false | false | false | false |
mattdeckard/Lilliput | refs/heads/master | Lilliput/ArgumentBinder.swift | mit | 1 | import Foundation
class ArgumentBinder<T: Equatable> {
let arg: T
init(_ arg: T) {
self.arg = arg
}
}
func ==<T: Equatable>(lhs: ArgumentBinder<T>, rhs: T) -> Bool {
return lhs.arg == rhs
} | 49c16c22fdfdb7446af7fae2e43a905d | 17 | 63 | 0.581395 | false | false | false | false |
AjayOdedara/CoreKitTest | refs/heads/master | CoreKit/Pods/SwiftDate/Sources/SwiftDate/DateComponents+Extension.swift | mit | 2 | //
// SwiftDate, Full featured Swift date library for parsing, validating, manipulating, and formatting dates and timezones.
// Created by: Daniele Margutti
// Main contributors: Jeroen Houtzager
//
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
// MARK: - DateComponents Extension
/// Invert the value expressed by a `DateComponents` instance
///
/// - parameter dateComponents: instance to invert (ie. days=5 will become days=-5)
///
/// - returns: a new `DateComponents` with inverted values
public prefix func - (dateComponents: DateComponents) -> DateComponents {
var invertedCmps = DateComponents()
DateComponents.allComponents.forEach { component in
let value = dateComponents.value(for: component)
if value != nil && value != Int(NSDateComponentUndefined) {
invertedCmps.setValue(-value!, for: component)
}
}
return invertedCmps
}
/// Sum two date components; allows us to make `"5.days + 3.hours"` by producing a single `DateComponents`
/// where both `.days` and `.hours` are set.
///
/// - parameter lhs: first date component
/// - parameter rhs: second date component
///
/// - returns: a new `DateComponents`
public func + (lhs: DateComponents, rhs: DateComponents) -> DateComponents {
return lhs.add(components: rhs)
}
/// Same as su but with diff
///
/// - parameter lhs: first date component
/// - parameter rhs: second date component
///
/// - returns: a new `DateComponents`
public func - (lhs: DateComponents, rhs: DateComponents) -> DateComponents {
return lhs.add(components: rhs, multipler: -1)
}
/// Merge two DateComponents values `(ex. a=1.hour,1.day, b=2.hour, the sum is c=3.hours,1.day)`
///
/// - Parameters:
/// - lhs: left date component
/// - rhs: right date component
/// - Returns: the sum of valid components of two instances
public func && (lhs: DateComponents, rhs: DateComponents) -> DateComponents {
var mergedComponents = DateComponents()
let flagSet = DateComponents.allComponents
flagSet.forEach { component in
func sumComponent(left: Int?, right: Int?) -> Int? {
let leftValue = (left != nil && left != Int(NSDateComponentUndefined) ? left : nil)
let rightValue = (right != nil && right != Int(NSDateComponentUndefined) ? right : nil)
if leftValue == nil && rightValue == nil { return nil }
return (leftValue ?? 0) + (rightValue ?? 0)
}
let sum = sumComponent(left: lhs.value(for: component), right: rhs.value(for: component))
if sum != nil {
mergedComponents.setValue(sum!, for: component)
}
}
return mergedComponents
}
public extension DateComponents {
/// A shortcut to produce a `DateInRegion` instance from an instance of `DateComponents`.
/// It's the same of `DateInRegion(components:)` init func but it may return nil (instead of throwing an exception)
/// if a valid date cannot be produced.
public var dateInRegion: DateInRegion? {
return DateInRegion(components: self)
}
/// Internal function helper for + and - operators between two `DateComponents`
///
/// - parameter components: components
/// - parameter multipler: optional multipler for each component
///
/// - returns: a new `DateComponents` instance
internal func add(components: DateComponents, multipler: Int = 1) -> DateComponents {
let lhs = self
let rhs = components
var newCmps = DateComponents()
let flagSet = DateComponents.allComponents
flagSet.forEach { component in
let left = lhs.value(for: component)
let right = rhs.value(for: component)
if left != nil && right != nil && left != Int(NSDateComponentUndefined) && right != Int(NSDateComponentUndefined) {
let value = left! + (right! * multipler)
newCmps.setValue(value, for: component)
}
}
return newCmps
}
/// Transform a `DateComponents` instance to a dictionary where key is the `Calendar.Component` and value is the
/// value associated.
///
/// - returns: a new `[Calendar.Component : Int]` dict representing source `DateComponents` instance
internal func toComponentsDict() -> [Calendar.Component : Int] {
var list: [Calendar.Component : Int] = [:]
DateComponents.allComponents.forEach { component in
let value = self.value(for: component)
if value != nil && value != Int(NSDateComponentUndefined) {
list[component] = value!
}
}
return list
}
}
public extension DateComponents {
/// Create a new `Date` in absolute time from a specific date by adding self components
///
/// - parameter date: reference date
/// - parameter region: optional region to define the timezone and calendar. If not specified, Region.GMT() will be used instead.
///
/// - returns: a new `Date`
public func from(date: Date, in region: Region? = nil) -> Date? {
let srcRegion = region ?? Region.GMT()
return srcRegion.calendar.date(byAdding: self, to: date)
}
/// Create a new `DateInRegion` from another `DateInRegion` by adding self components
/// Returned object has the same `Region` of the source.
///
/// - parameter dateInRegion: reference `DateInRegion`
///
/// - returns: a new `DateInRegion`
public func from(dateInRegion: DateInRegion) -> DateInRegion? {
guard let absDate = dateInRegion.region.calendar.date(byAdding: self, to: dateInRegion.absoluteDate) else {
return nil
}
let newDateInRegion = DateInRegion(absoluteDate: absDate, in: dateInRegion.region)
return newDateInRegion
}
/// Create a new `Date` in absolute time from a specific date by subtracting self components
///
/// - parameter date: reference date
/// - parameter region: optional region to define the timezone and calendar. If not specific, Region.GTM() will be used instead
///
/// - returns: a new `Date`
public func ago(from date: Date, in region: Region? = nil) -> Date? {
let srcRegion = region ?? Region.GMT()
return srcRegion.calendar.date(byAdding: -self, to: date)
}
/// Create a new `DateInRegion` from another `DateInRegion` by subtracting self components
/// Returned object has the same `Region` of the source.
///
/// - parameter dateInRegion: reference `DateInRegion`
///
/// - returns: a new `DateInRegion`
public func ago(fromDateInRegion date: DateInRegion) -> DateInRegion? {
guard let absDate = date.region.calendar.date(byAdding: -self, to: date.absoluteDate) else {
return nil
}
let newDateInRegion = DateInRegion(absoluteDate: absDate, in: date.region)
return newDateInRegion
}
/// Create a new `Date` in absolute time from current date by adding self components
///
/// - parameter region: optional region to define the timezone and calendar. If not specified, Region.GMT() will be used instead.
///
/// - returns: a new `Date`
public func fromNow(in region: Region? = nil) -> Date? {
return self.from(date: Date(), in: region)
}
/// Create a new `DateInRegion` from current by subtracting self components
/// Returned object has the same `Region` of the source.
///
/// - parameter dateInRegion: reference `DateInRegion`
///
/// - returns: a new `DateInRegion`
public func ago(in region: Region? = nil) -> Date? {
return self.ago(from: Date(), in: region)
}
/// Express a DateComponents instances in another time unit you choose
///
/// - parameter component: time component
/// - parameter calendar: context calendar to use
///
/// - returns: the value of interval expressed in selected `Calendar.Component`
public func `in`(_ component: Calendar.Component, of calendar: CalendarName? = nil) -> Int? {
let cal = calendar ?? CalendarName.current
let dateFrom = Date()
let dateTo: Date = dateFrom.add(components: self)
let components: Set<Calendar.Component> = [component]
let value = cal.calendar.dateComponents(components, from: dateFrom, to: dateTo).value(for: component)
return value
}
}
// MARK: - DateComponents Private Extension
extension DateComponents {
/// Define a list of all calendar components as a set
internal static let allComponentsSet: Set<Calendar.Component> = [.nanosecond, .second, .minute, .hour,
.day, .month, .year, .yearForWeekOfYear, .weekOfYear, .weekday, .quarter, .weekdayOrdinal,
.weekOfMonth]
/// Define a list of all calendar components as array
internal static let allComponents: [Calendar.Component] = [.nanosecond, .second, .minute, .hour,
.day, .month, .year, .yearForWeekOfYear, .weekOfYear, .weekday, .quarter, .weekdayOrdinal,
.weekOfMonth]
}
| 265ddfee25a57aafde45d8683d6a8e99 | 37.011811 | 156 | 0.692905 | false | false | false | false |
dunkelstern/unchained | refs/heads/master | Unchained/router.swift | bsd-3-clause | 1 | //
// router.swift
// unchained
//
// Created by Johannes Schriewer on 30/11/15.
// Copyright © 2015 Johannes Schriewer. All rights reserved.
//
import TwoHundred
import UnchainedString
import UnchainedLogger
import SwiftyRegex
/// Unchained route entry
public struct Route {
/// Router errors
public enum Error: ErrorType {
/// No route with that name exists
case NoRouteWithThatName(name: String)
/// Route contains mix of numbered and named parameters
case MixedNumberedAndNamedParameters
/// Missing parameter of `name` to call that route
case MissingParameterForRoute(name: String)
/// Wrong parameter count for a route with unnamed parameters
case WrongParameterCountForRoute
}
/// A route request handler, takes `request`, numbered `parameters` and `namedParameters`, returns `HTTPResponseBase`
public typealias RequestHandler = ((request: HTTPRequest, parameters: [String], namedParameters: [String:String]) -> HTTPResponseBase)
/// Name of the route (used for route reversing)
public var name: String
private var re: RegEx?
private var handler:RequestHandler
/// Initialize a route
///
/// - parameter regex: Regex to match
/// - parameter handler: handler callback to run if route matches
/// - parameter name: (optional) name of this route to `reverse`
public init(_ regex: String, handler:RequestHandler, name: String? = nil) {
do {
self.re = try RegEx(pattern: regex)
} catch RegEx.Error.InvalidPattern(let offset, let message) {
Log.error("Route: Pattern parse error for pattern \(regex) at character \(offset): \(message)")
} catch {
// unused
}
self.handler = handler
if let name = name {
self.name = name
} else {
self.name = "r'\(regex)'"
}
}
/// execute a route on a request
///
/// - parameter request: the request on which to execute this route
/// - returns: response to the request or nil if the route does not match
public func execute(request: HTTPRequest) -> HTTPResponseBase? {
guard let re = self.re else {
return nil
}
let matches = re.match(request.header.url)
if matches.numberedParams.count > 0 {
return self.handler(request: request, parameters: matches.numberedParams, namedParameters: matches.namedParams)
}
return nil
}
// MARK: - Internal
enum RouteComponentType {
case Text(String)
case NamedPattern(String)
case NumberedPattern(Int)
}
/// split a route regex into components for route reversal
///
/// - returns: Array of route components
func splitIntoComponents() -> [RouteComponentType]? {
guard let pattern = self.re?.pattern else {
return nil
}
var patternNum = 0
var openBrackets = 0
var components = [RouteComponentType]()
var currentComponent = ""
currentComponent.reserveCapacity(pattern.characters.count)
var gen = pattern.characters.generate()
while let c = gen.next() {
switch c {
case "(":
if openBrackets == 0 {
// split point
if currentComponent.characters.count > 0 {
patternNum += 1
components.append(.Text(currentComponent))
currentComponent.removeAll()
}
}
break
case ")":
if openBrackets == 0 {
// split point
if currentComponent.characters.count > 0 {
var found = false
for (name, idx) in self.re!.namedCaptureGroups {
if idx == patternNum {
components.append(.NamedPattern(name))
currentComponent.removeAll()
found = true
break
}
}
if !found {
components.append(.NumberedPattern(patternNum))
}
}
}
case "[":
openBrackets += 1
case "]":
openBrackets -= 1
case "\\":
// skip next char
gen.next()
default:
currentComponent.append(c)
}
}
if currentComponent.characters.count > 0 {
components.append(.Text(currentComponent))
}
// strip ^ on start
if case .Text(let text) = components.first! {
if text.characters.first! == "^" {
components[0] = .Text(text.subString(fromIndex: text.startIndex.advancedBy(1)))
}
}
// strip $ on end
if case .Text(let text) = components.last! {
if text.characters.last! == "$" {
components.removeLast()
if text.characters.count > 1 {
components.append(.Text(text.subString(toIndex: text.startIndex.advancedBy(text.characters.count - 2))))
}
}
}
return components
}
}
/// Route reversion
public extension UnchainedResponseHandler {
/// reverse a route with named parameters
///
/// - parameter name: the name of the route URL to produce
/// - parameter parameters: the parameters to substitute
/// - parameter absolute: (optional) return relative path (from root, default) or absolute URL with hostname
/// - returns: URL of route with parameters
///
/// - throws: Throws errors if route could not be reversed
public func reverseRoute(name: String, parameters:[String:String], absolute: Bool = false) throws -> String {
guard let route = self.fetchRoute(name) else {
throw Route.Error.NoRouteWithThatName(name: name)
}
var result = ""
if absolute {
result.appendContentsOf(self.request.config.externalServerURL)
}
// Build route string
for item in route {
switch item {
case .NumberedPattern:
throw Route.Error.MixedNumberedAndNamedParameters
case .NamedPattern(let name):
if let param = parameters[name] {
result.appendContentsOf(param)
} else {
throw Route.Error.MissingParameterForRoute(name: name)
}
case .Text(let text):
result.appendContentsOf(text)
}
}
return result
}
/// reverse a route with numbered parameters
///
/// - parameter name: the name of the route URL to produce
/// - parameter parameters: the parameters to substitute
/// - parameter absolute: (optional) return relative path (from root, default) or absolute URL with hostname
/// - returns: URL of route with parameters
///
/// - throws: Throws errors if route could not be reversed
public func reverseRoute(name: String, parameters:[String], absolute: Bool = false) throws -> String {
guard let route = self.fetchRoute(name) else {
throw Route.Error.NoRouteWithThatName(name: name)
}
var result = ""
if absolute {
result.appendContentsOf(self.request.config.externalServerURL)
}
// Build route string
for item in route {
switch item {
case .NumberedPattern(let num):
if parameters.count > num - 1 {
result.appendContentsOf(parameters[num - 1])
} else {
throw Route.Error.WrongParameterCountForRoute
}
case .NamedPattern:
throw Route.Error.MixedNumberedAndNamedParameters
case .Text(let text):
result.appendContentsOf(text)
}
}
return result
}
/// reverse a route without parameters
///
/// - parameter name: the name of the route URL to produce
/// - parameter absolute: (optional) return relative path (from root, default) or absolute URL with hostname
/// - returns: URL of route with parameters
///
/// - throws: Throws errors if route could not be reversed
public func reverseRoute(name: String, absolute: Bool = false) throws -> String {
guard let route = self.fetchRoute(name) else {
throw Route.Error.NoRouteWithThatName(name: name)
}
var result = ""
if absolute {
result.appendContentsOf(self.request.config.externalServerURL)
}
// Build route string
for item in route {
switch item {
case .NumberedPattern:
throw Route.Error.WrongParameterCountForRoute
case .NamedPattern(let name):
throw Route.Error.MissingParameterForRoute(name: name)
case .Text(let text):
result.appendContentsOf(text)
}
}
return result
}
/// Fetch a route by name
///
/// - parameter name: Name to search
/// - returns: Route instance or nil if not found
private func fetchRoute(name: String) -> [Route.RouteComponentType]? {
for route in self.request.config.routes {
if route.name == name {
return route.splitIntoComponents()
}
}
return nil
}
}
| 6451e300d99497dc30943dc5fd38284d | 32.608247 | 138 | 0.557362 | false | false | false | false |
toggl/superday | refs/heads/develop | teferi/Services/Implementations/Persistency/DefaultTimeSlotService.swift | bsd-3-clause | 1 | import CoreData
import RxSwift
import Foundation
class DefaultTimeSlotService : TimeSlotService
{
// MARK: Private Properties
private let timeService : TimeService
private let loggingService : LoggingService
private let locationService : LocationService
private let persistencyService : BasePersistencyService<TimeSlot>
private let timeSlotCreatedSubject = PublishSubject<TimeSlot>()
private let timeSlotsUpdatedSubject = PublishSubject<[TimeSlot]>()
// MARK: Initializer
init(timeService: TimeService,
loggingService: LoggingService,
locationService: LocationService,
persistencyService: BasePersistencyService<TimeSlot>)
{
self.timeService = timeService
self.loggingService = loggingService
self.locationService = locationService
self.persistencyService = persistencyService
}
// MARK: Public Methods
@discardableResult func addTimeSlot(withStartTime startTime: Date, category: Category, categoryWasSetByUser: Bool, tryUsingLatestLocation: Bool) -> TimeSlot?
{
let location : Location? = tryUsingLatestLocation ? locationService.getLastKnownLocation() : nil
return addTimeSlot(withStartTime: startTime,
category: category,
categoryWasSetByUser: categoryWasSetByUser,
location: location)
}
@discardableResult func addTimeSlot(withStartTime startTime: Date, category: Category, categoryWasSetByUser: Bool, location: Location?) -> TimeSlot?
{
let timeSlot = TimeSlot(startTime: startTime,
category: category,
categoryWasSetByUser: categoryWasSetByUser,
categoryWasSmartGuessed: false,
location: location)
return tryAdd(timeSlot: timeSlot)
}
@discardableResult func addTimeSlot(withStartTime startTime: Date, category: Category, location: Location?) -> TimeSlot?
{
let timeSlot = TimeSlot(startTime: startTime,
category: category,
location: location)
return tryAdd(timeSlot: timeSlot)
}
@discardableResult func addTimeSlot(fromTemporaryTimeslot temporaryTimeSlot: TemporaryTimeSlot) -> TimeSlot?
{
let timeSlot = TimeSlot(startTime: temporaryTimeSlot.start,
endTime: temporaryTimeSlot.end,
category: temporaryTimeSlot.category,
location: temporaryTimeSlot.location,
categoryWasSetByUser: false,
categoryWasSmartGuessed: temporaryTimeSlot.isSmartGuessed,
activity: temporaryTimeSlot.activity)
return tryAdd(timeSlot: timeSlot)
}
func getTimeSlots(forDay day: Date) -> [TimeSlot]
{
return getTimeSlots(forDay: day, category: nil)
}
func getTimeSlots(forDay day: Date, category: Category?) -> [TimeSlot]
{
let startTime = day.ignoreTimeComponents() as NSDate
let endTime = day.tomorrow.ignoreTimeComponents().addingTimeInterval(-1) as NSDate
var timeSlots = [TimeSlot]()
if let category = category
{
let predicates = [Predicate(parameter: "startTime", rangesFromDate: startTime, toDate: endTime),
Predicate(parameter: "category", equals: category.rawValue as AnyObject)]
timeSlots = persistencyService.get(withANDPredicates: predicates)
}
else
{
let predicate = Predicate(parameter: "startTime", rangesFromDate: startTime, toDate: endTime)
timeSlots = persistencyService.get(withPredicate: predicate)
}
return timeSlots
}
func getTimeSlots(sinceDaysAgo days: Int) -> [TimeSlot]
{
let today = timeService.now.ignoreTimeComponents()
let startTime = today.add(days: -days).ignoreTimeComponents() as NSDate
let endTime = today.tomorrow.ignoreTimeComponents() as NSDate
let predicate = Predicate(parameter: "startTime", rangesFromDate: startTime, toDate: endTime)
let timeSlots = persistencyService.get(withPredicate: predicate)
return timeSlots
}
func getTimeSlots(betweenDate firstDate: Date, andDate secondDate: Date) -> [TimeSlot]
{
let date1 = firstDate.ignoreTimeComponents() as NSDate
let date2 = secondDate.add(days: 1).ignoreTimeComponents() as NSDate
let predicate = Predicate(parameter: "startTime", rangesFromDate: date1, toDate: date2)
let timeSlots = persistencyService.get(withPredicate: predicate)
return timeSlots
}
func getLast() -> TimeSlot?
{
return persistencyService.getLast()
}
func calculateDuration(ofTimeSlot timeSlot: TimeSlot) -> TimeInterval
{
let endTime = getEndTime(ofTimeSlot: timeSlot)
return endTime.timeIntervalSince(timeSlot.startTime)
}
// MARK: Private Methods
private func tryAdd(timeSlot: TimeSlot) -> TimeSlot?
{
//The previous TimeSlot needs to be finished before a new one can start
guard endPreviousTimeSlot(atDate: timeSlot.startTime) && persistencyService.create(timeSlot) else
{
loggingService.log(withLogLevel: .warning, message: "Failed to create new TimeSlot")
return nil
}
loggingService.log(withLogLevel: .info, message: "New TimeSlot with category \"\(timeSlot.category)\" created")
NotificationCenter.default.post(OnTimeSlotCreated(startTime: timeSlot.startTime))
timeSlotCreatedSubject.on(.next(timeSlot))
return timeSlot
}
private func getEndTime(ofTimeSlot timeSlot: TimeSlot) -> Date
{
if let endTime = timeSlot.endTime { return endTime}
let date = timeService.now
let timeEntryLimit = timeSlot.startTime.tomorrow.ignoreTimeComponents()
let timeEntryLastedOverOneDay = date > timeEntryLimit
//TimeSlots can't go past midnight
let endTime = timeEntryLastedOverOneDay ? timeEntryLimit : date
return endTime
}
private func endPreviousTimeSlot(atDate date: Date) -> Bool
{
guard let timeSlot = persistencyService.getLast() else { return true }
let startDate = timeSlot.startTime
var endDate = date
guard endDate > startDate else
{
loggingService.log(withLogLevel: .warning, message: "Trying to create a negative duration TimeSlot")
return false
}
//TimeSlot is going for over one day, we should end it at midnight
if startDate.ignoreTimeComponents() != endDate.ignoreTimeComponents()
{
loggingService.log(withLogLevel: .info, message: "Early ending TimeSlot at midnight")
endDate = startDate.tomorrow.ignoreTimeComponents()
}
let predicate = Predicate(parameter: "startTime", equals: timeSlot.startTime as AnyObject)
let editFunction = { (timeSlot: TimeSlot) -> TimeSlot in
return timeSlot.withEndDate(endDate)
}
guard let _ = persistencyService.singleUpdate(withPredicate: predicate, updateFunction: editFunction) else
{
loggingService.log(withLogLevel: .warning, message: "Failed to end TimeSlot started at \(timeSlot.startTime) with category \(timeSlot.category)")
return false
}
return true
}
}
| a6badb335cba3cf5c107f5fc539e7d05 | 38.80303 | 161 | 0.631011 | false | false | false | false |
testpress/ios-app | refs/heads/master | ios-app/UI/StartQuizExamViewController.swift | mit | 1 | //
// StartQuizExamViewController.swift
// ios-app
//
// Created by Karthik on 12/05/20.
// Copyright © 2020 Testpress. All rights reserved.
//
import UIKit
import RealmSwift
class StartQuizExamViewController: UIViewController {
@IBOutlet weak var examTitle: UILabel!
@IBOutlet weak var questionsCount: UILabel!
@IBOutlet weak var startEndDate: UILabel!
@IBOutlet weak var startButton: UIButton!
@IBOutlet weak var examInfoLabel: UILabel!
@IBOutlet weak var bottomShadowView: UIView!
@IBOutlet weak var startButtonLayout: UIView!
@IBOutlet weak var navigationBarItem: UINavigationItem!
@IBOutlet weak var descriptionLabel: UILabel!
@IBOutlet weak var scrollView: UIScrollView!
@IBOutlet weak var contentView: UIStackView!
@IBOutlet weak var containerView: UIView!
var content: Content!
var viewModel: QuizExamViewModel!
var emptyView: EmptyView!
let alertController = UIUtils.initProgressDialog(message: "Please wait\n\n")
override func viewDidLoad() {
viewModel = QuizExamViewModel(content: content)
bindData()
UIUtils.setButtonDropShadow(startButton)
addContentAttemptListViewController()
initializeEmptyView()
}
func initializeEmptyView() {
emptyView = EmptyView.getInstance(parentView: view)
emptyView.frame = view.frame
}
func addContentAttemptListViewController() {
let storyboard = UIStoryboard(name: Constants.CHAPTER_CONTENT_STORYBOARD, bundle: nil)
let viewController = storyboard.instantiateViewController(
withIdentifier: Constants.CONTENT_EXAM_ATTEMPS_TABLE_VIEW_CONTROLLER
) as! ContentExamAttemptsTableViewController
viewController.content = content
add(viewController)
viewController.view.autoresizingMask = [.flexibleHeight, .flexibleWidth]
viewController.view.frame = self.containerView.frame
}
func bindData() {
examTitle.text = viewModel.title
questionsCount.text = viewModel.noOfQuestions
startEndDate.text = viewModel.startEndDate
descriptionLabel.text = viewModel.description
if viewModel.description.isEmpty {
descriptionLabel.isHidden = true
}
startButtonLayout.isHidden = !viewModel.canStartExam && content.isLocked
examInfoLabel.text = viewModel.examInfo
if content != nil && content.isLocked {
examInfoLabel.text = Strings.SCORE_GOOD_IN_PREVIOUS
startButtonLayout.isHidden = true
}
if (examInfoLabel.text?.isEmpty == true) {
examInfoLabel.isHidden = true
}
}
@IBAction func startExam(_ sender: UIButton) {
present(alertController, animated: false, completion: nil)
viewModel.loadAttempt { contentAttempt, error in
self.alertController.dismiss(animated: true, completion: nil)
if let error = error {
var retryButtonText: String?
var retryHandler: (() -> Void)?
if error.kind == .network {
retryButtonText = Strings.TRY_AGAIN
retryHandler = {
self.startExam(sender)
}
}
let (image, title, description) = error.getDisplayInfo()
self.emptyView.show(image: image, title: title, description: description, retryButtonText: retryButtonText, retryHandler: retryHandler)
return
}
try! Realm().write {
self.content.attemptsCount += 1
}
self.showQuestions(contentAttempt: contentAttempt!)
}
}
func showQuestions(contentAttempt: ContentAttempt) {
let storyboard = UIStoryboard(name: Constants.TEST_ENGINE, bundle: nil)
let viewController = storyboard.instantiateViewController(withIdentifier:
Constants.QUIZ_EXAM_VIEW_CONTROLLER) as! QuizExamViewController
viewController.contentAttempt = contentAttempt
viewController.exam = content.exam
present(viewController, animated: true, completion: nil)
}
override func viewDidLayoutSubviews() {
// Add gradient shadow layer to the shadow container view
if bottomShadowView != nil {
let bottomGradient = CAGradientLayer()
bottomGradient.frame = bottomShadowView.bounds
bottomGradient.colors = [UIColor.white.cgColor, UIColor.black.cgColor]
bottomShadowView.layer.insertSublayer(bottomGradient, at: 0)
}
// Set scroll view content height to support the scroll
scrollView.contentSize.height = contentView.frame.size.height
}
}
| 90d15031a6036a0a509ccf8898c15a35 | 37.188976 | 152 | 0.648866 | false | false | false | false |
See-Ku/SK4Toolkit | refs/heads/master | SK4Toolkit/core/SK4Interpolation.swift | mit | 1 | //
// SK4Interpolation.swift
// SK4Toolkit
//
// Created by See.Ku on 2016/03/30.
// Copyright (c) 2016 AxeRoad. All rights reserved.
//
import UIKit
// /////////////////////////////////////////////////////////////
// MARK: - 線形補間で使用するプロトコル
public protocol SK4InterpolationType: SignedNumberType {
func +(lhs: Self, rhs: Self) -> Self
func -(lhs: Self, rhs: Self) -> Self
func *(lhs: Self, rhs: Self) -> Self
func /(lhs: Self, rhs: Self) -> Self
func %(lhs: Self, rhs: Self) -> Self
}
extension Double: SK4InterpolationType {
}
extension CGFloat: SK4InterpolationType {
}
extension Int: SK4InterpolationType {
}
// /////////////////////////////////////////////////////////////
// MARK: - 線形補間
/// 単純な線形補間
public func sk4Interpolation<T: SK4InterpolationType>(y0 y0: T, y1: T, x0: T, x1: T, x: T) -> T {
if x0 == x1 {
return (y0 + y1) / 2
} else {
return (y0 * (x1 - x) + y1 * (x - x0)) / (x1 - x0)
}
}
/// 上限/下限付きの線形補間
public func sk4InterpolationFloor<T: SK4InterpolationType>(y0 y0: T, y1: T, x0: T, x1: T, x: T) -> T {
if x <= x0 {
return y0
}
if x >= x1 {
return y1
}
return sk4Interpolation(y0: y0, y1: y1, x0: x0, x1: x1, x: x)
}
/// 繰り返す形式の線形補間
public func sk4InterpolatioCycle<T: SK4InterpolationType>(y0: T, y1: T, x0: T, x1: T, x: T) -> T {
if x0 == x1 {
return (y0 + y1) / 2
}
let max = abs(x1 - x0)
let dif = abs(x - x0)
let xn = dif % (max * 2)
if xn < max {
return sk4Interpolation(y0: y0, y1: y1, x0: 0, x1: max, x: xn)
} else {
return sk4Interpolation(y0: y0, y1: y1, x0: 0, x1: max, x: xn - max)
}
}
// /////////////////////////////////////////////////////////////
/// 単純な線形補間(UIColor用)
public func sk4Interpolation(y0 y0: UIColor, y1: UIColor, x0: CGFloat, x1: CGFloat, x: CGFloat) -> UIColor {
let c0 = y0.colors
let c1 = y1.colors
var cn: [CGFloat] = [1, 1, 1, 1]
for i in 0..<4 {
cn[i] = sk4Interpolation(y0: c0[i], y1: c1[i], x0: x0, x1: x1, x: x)
}
return UIColor(colors: cn)
}
// eof
| 34a9a6c81f5cd09e3d6fd63d012c2712 | 21.191011 | 108 | 0.549367 | false | false | false | false |
coderwhy/DouYuZB | refs/heads/master | DYZB/DYZB/Classes/Home/View/RecommendGameView.swift | mit | 1 | //
// RecommendGameView.swift
// DYZB
//
// Created by 1 on 16/9/21.
// Copyright © 2016年 小码哥. All rights reserved.
//
import UIKit
private let kGameCellID = "kGameCellID"
private let kEdgeInsetMargin : CGFloat = 10
class RecommendGameView: UIView {
// MARK: 定义数据的属性
var groups : [BaseGameModel]? {
didSet {
// 刷新表格
collectionView.reloadData()
}
}
// MARK: 控件属性
@IBOutlet weak var collectionView: UICollectionView!
// MARK: 系统回调
override func awakeFromNib() {
super.awakeFromNib()
// 让控件不随着父控件的拉伸而拉伸
autoresizingMask = UIViewAutoresizing()
// 注册Cell
collectionView.register(UINib(nibName: "CollectionGameCell", bundle: nil), forCellWithReuseIdentifier: kGameCellID)
// 给collectionView添加内边距
collectionView.contentInset = UIEdgeInsets(top: 0, left: kEdgeInsetMargin, bottom: 0, right: kEdgeInsetMargin)
}
}
// MARK:- 提供快速创建的类方法
extension RecommendGameView {
class func recommendGameView() -> RecommendGameView {
return Bundle.main.loadNibNamed("RecommendGameView", owner: nil, options: nil)?.first as! RecommendGameView
}
}
// MARK:- 遵守UICollectionView的数据源协议
extension RecommendGameView : UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return groups?.count ?? 0
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: kGameCellID, for: indexPath) as! CollectionGameCell
cell.baseGame = groups![(indexPath as NSIndexPath).item]
return cell
}
}
| 76e4eec7cfe0a328e6df6dd5943e6c3b | 27.5 | 126 | 0.669408 | false | false | false | false |
groue/GRDB.swift | refs/heads/master | GRDB/QueryInterface/SQL/Column.swift | mit | 1 | /// A type that represents a column in a database table.
///
/// ## Topics
///
/// ### Standard Columns
///
/// - ``rowID``
///
/// ### Deriving SQL Expressions
///
/// - ``detached``
/// - ``match(_:)``
///
/// ### Creating Column Assignments
///
/// - ``noOverwrite``
/// - ``set(to:)``
public protocol ColumnExpression: SQLSpecificExpressible {
/// The column name.
///
/// The column name is never qualified with a table name.
///
/// For example, the name of a column can be `"score"`, but
/// not `"player.score"`.
var name: String { get }
}
extension ColumnExpression {
public var sqlExpression: SQLExpression {
.column(name)
}
/// An SQL expression that refers to an aliased column
/// (`expression AS alias`).
///
/// Once detached, a column is never qualified with any table name in the
/// SQL generated by the query interface.
///
/// For example, see how `Column("total").detached` makes it possible to
/// sort this query, when a raw `Column("total")` could not:
///
/// ```swift
/// // SELECT player.*,
/// // (player.score + player.bonus) AS total,
/// // team.*
/// // FROM player
/// // JOIN team ON team.id = player.teamID
/// // ORDER BY total, player.name
/// // ~~~~~
/// let request = Player
/// .annotated(with: (Column("score") + Column("bonus")).forKey("total"))
/// .including(required: Player.team)
/// .order(Column("total").detached, Column("name"))
/// ```
public var detached: SQLExpression {
SQL(sql: name.quotedDatabaseIdentifier).sqlExpression
}
}
extension ColumnExpression where Self == Column {
/// The hidden rowID column.
public static var rowID: Self { Column.rowID }
}
/// A column in a database table.
///
/// ## Topics
///
/// ### Standard Columns
///
/// - ``rowID-3bn70``
///
/// ### Creating A Column
///
/// - ``init(_:)-5grmu``
/// - ``init(_:)-7xc4z``
public struct Column {
/// The hidden rowID column.
public static let rowID = Column("rowid")
public var name: String
/// Creates a `Column` given its name.
///
/// The name should be unqualified, such as `"score"`. Qualified name such
/// as `"player.score"` are unsupported.
public init(_ name: String) {
self.name = name
}
/// Creates a `Column` given a `CodingKey`.
public init(_ codingKey: some CodingKey) {
self.name = codingKey.stringValue
}
}
extension Column: ColumnExpression { }
/// Support for column enums:
///
/// struct Player {
/// enum Columns: String, ColumnExpression {
/// case id, name, score
/// }
/// }
extension ColumnExpression where Self: RawRepresentable, Self.RawValue == String {
public var name: String { rawValue }
}
| dede64efff0b934cf574627c0584a0a9 | 25.574074 | 82 | 0.572822 | false | false | false | false |
ACChe/eidolon | refs/heads/master | Kiosk/Admin/ChooseAuctionViewController.swift | mit | 6 | import UIKit
import ORStackView
import Artsy_UIFonts
import Artsy_UIButtons
class ChooseAuctionViewController: UIViewController {
var auctions: [Sale]!
override func viewDidLoad() {
super.viewDidLoad()
stackScrollView.backgroundColor = .whiteColor()
stackScrollView.bottomMarginHeight = CGFloat(NSNotFound)
stackScrollView.updateConstraints()
let endpoint: ArtsyAPI = ArtsyAPI.ActiveAuctions
XAppRequest(endpoint).filterSuccessfulStatusCodes().mapJSON().mapToObjectArray(Sale.self)
.subscribeNext({ [weak self] (activeSales) -> Void in
self!.auctions = activeSales as! [Sale]
for i in 0 ..< self!.auctions.count {
let sale = self!.auctions[i]
let title = " \(sale.name) - #\(sale.auctionState) - \(sale.artworkCount)"
let button = ARFlatButton()
button.setTitle(title, forState: .Normal)
button.setTitleColor(.blackColor(), forState: .Normal)
button.tag = i
button.rac_signalForControlEvents(.TouchUpInside).subscribeNext { (_) in
let defaults = NSUserDefaults.standardUserDefaults()
defaults.setObject(sale.id, forKey: "KioskAuctionID")
defaults.synchronize()
exit(1)
}
self!.stackScrollView.addSubview(button, withTopMargin: "12", sideMargin: "0")
button.constrainHeight("50")
}
})
}
@IBOutlet weak var stackScrollView: ORStackView!
@IBAction func backButtonTapped(sender: AnyObject) {
self.navigationController?.popViewControllerAnimated(true)
}
}
| 64673f52708877b1cc47e4313db4a06d | 36.604167 | 98 | 0.590582 | false | false | false | false |
JaSpa/swift | refs/heads/master | test/RemoteAST/member_offsets.swift | apache-2.0 | 25 | // RUN: %target-swift-remoteast-test %s | %FileCheck %s
// REQUIRES: swift-remoteast-test
// REQUIRES: PTRSIZE=64
@_silgen_name("printTypeMemberOffset")
func printTypeMemberOffset(_: Any.Type, _: StaticString)
@_silgen_name("printTypeMetadataMemberOffset")
func printTypeMetadataMemberOffset(_: Any.Type, _: StaticString)
printTypeMemberOffset((Int,Bool,Float,Bool,Int16).self, "0")
// CHECK: found offset: 0
printTypeMemberOffset((Int,Bool,Float,Bool,Int16).self, "1")
// CHECK-NEXT: found offset: 8
printTypeMemberOffset((Int,Bool,Float,Bool,Int16).self, "2")
// CHECK-NEXT: found offset: 12
printTypeMemberOffset((Int,Bool,Float,Bool,Int16).self, "3")
// CHECK-NEXT: found offset: 16
printTypeMemberOffset((Int,Bool,Float,Bool,Int16).self, "4")
// CHECK-NEXT: found offset: 18
printTypeMemberOffset((Int,Bool,Float,Bool,Int16).self, "5")
// CHECK-NEXT: type has no member named '5'
struct A {
var a: Int
var b: Bool
var c: Float
var d: Bool
var e: Int16
}
printTypeMemberOffset(A.self, "a")
// CHECK-NEXT: found offset: 0
printTypeMemberOffset(A.self, "b")
// CHECK-NEXT: found offset: 8
printTypeMemberOffset(A.self, "c")
// CHECK-NEXT: found offset: 12
printTypeMemberOffset(A.self, "d")
// CHECK-NEXT: found offset: 16
printTypeMemberOffset(A.self, "e")
// CHECK-NEXT: found offset: 18
printTypeMemberOffset(A.self, "f")
// CHECK-NEXT: type has no member named 'f'
struct B<T> {
var a: Int
var b: Bool
var c: T
var d: Bool
var e: Int16
}
printTypeMemberOffset(B<Float>.self, "a")
// CHECK-NEXT: found offset: 0
printTypeMemberOffset(B<Float>.self, "b")
// CHECK-NEXT: found offset: 8
printTypeMemberOffset(B<Float>.self, "c")
// CHECK-NEXT: found offset: 12
printTypeMemberOffset(B<Float>.self, "d")
// CHECK-NEXT: found offset: 16
printTypeMemberOffset(B<Float>.self, "e")
// CHECK-NEXT: found offset: 18
printTypeMemberOffset(B<Float>.self, "f")
// CHECK-NEXT: type has no member named 'f'
class C {
var a: Int
var b: Bool
var c: Float
var d: Bool
var e: Int16
init() {
a = 0; b = false; c = 0; d = false; e = 0
}
}
printTypeMemberOffset(C.self, "a")
// CHECK-NEXT: found offset: 16
printTypeMemberOffset(C.self, "b")
// CHECK-NEXT: found offset: 24
printTypeMemberOffset(C.self, "c")
// CHECK-NEXT: found offset: 28
printTypeMemberOffset(C.self, "d")
// CHECK-NEXT: found offset: 32
printTypeMemberOffset(C.self, "e")
// CHECK-NEXT: found offset: 34
printTypeMemberOffset(C.self, "f")
// CHECK-NEXT: type has no member named 'f'
class D<T> {
var a: Int
var b: Bool
var c: T
var d: Bool
var e: Int16
init(v: T) {
a = 0; b = false; c = v; d = false; e = 0
}
}
printTypeMemberOffset(D<Float>.self, "a")
// CHECK-NEXT: found offset: 16
printTypeMemberOffset(D<Float>.self, "b")
// CHECK-NEXT: found offset: 24
printTypeMemberOffset(D<Float>.self, "c")
// CHECK-NEXT: found offset: 28
printTypeMemberOffset(D<Float>.self, "d")
// CHECK-NEXT: found offset: 32
printTypeMemberOffset(D<Float>.self, "e")
// CHECK-NEXT: found offset: 34
printTypeMemberOffset(D<Float>.self, "f")
// CHECK-NEXT: type has no member named 'f'
| 88c461ce06e57bd364ea29bc1fe2b927 | 21.120567 | 64 | 0.691568 | false | false | false | false |
tbaranes/SwiftyUtils | refs/heads/master | Sources/PropertyWrappers/UserDefaultsBacked.swift | mit | 1 | //
// UserDefaultsBacked.swift
// SwiftyUtils
//
// Created by Tom Baranes on 25/04/2020.
// Copyright © 2020 Tom Baranes. All rights reserved.
//
// Inspiration from: https://www.swiftbysundell.com/articles/property-wrappers-in-swift/
//
import Foundation
/// A property wrapper to get or set values in a user's defaults database.
@propertyWrapper
public struct UserDefaultsBacked<Value> {
private let key: String
private let defaultValue: Value
private var storage: UserDefaults
/// Initialize a `UserDefaultsBacked` with a default value.
/// - Parameters:
/// - key: The name of one of the receiver's properties.
/// - defaultValue: The default value to use if there's none in the database.
/// - storage: The `UserDefaults` database to use. The default value is `.standard`.
public init(key: String, defaultValue: Value, storage: UserDefaults = .standard) {
self.key = key
self.defaultValue = defaultValue
self.storage = storage
}
public var wrappedValue: Value {
get {
let value = storage.value(forKey: key) as? Value
return value ?? defaultValue
}
set {
if let optional = newValue as? AnyOptional, optional.isNil {
storage.removeObject(forKey: key)
} else {
storage.setValue(newValue, forKey: key)
}
}
}
}
extension UserDefaultsBacked where Value: ExpressibleByNilLiteral {
/// Initialize a `UserDefaultsBacked` without default value.
/// - Parameters:
/// - key: The name of one of the receiver's properties.
/// - storage: The `UserDefaults` database to use. The default value is `.standard`.
public init(key: String, storage: UserDefaults = .standard) {
self.init(key: key, defaultValue: nil, storage: storage)
}
}
| f86ecceaf83d609be51d5b7c43746efd | 32.446429 | 90 | 0.646022 | false | false | false | false |
JGiola/swift | refs/heads/main | test/Concurrency/Runtime/async_taskgroup_next_not_invoked_cancelAll.swift | apache-2.0 | 9 | // RUN: %target-run-simple-swift( -Xfrontend -disable-availability-checking %import-libdispatch -parse-as-library) | %FileCheck %s --dump-input=always
// REQUIRES: executable_test
// REQUIRES: concurrency
// REQUIRES: libdispatch
// rdar://76038845
// REQUIRES: concurrency_runtime
// UNSUPPORTED: back_deployment_runtime
import Dispatch
@available(SwiftStdlib 5.1, *)
func test_skipCallingNext_butInvokeCancelAll() async {
let numbers = [1, 1]
let result = try! await withTaskGroup(of: Int.self) { (group) async -> Int in
for n in numbers {
print("group.spawn { \(n) }")
group.spawn { [group] () async -> Int in
await Task.sleep(1_000_000_000)
print(" inside group.spawn { \(n) }")
print(" inside group.spawn { \(n) } (group cancelled: \(group.isCancelled))")
print(" inside group.spawn { \(n) } (group child task cancelled: \(Task.isCancelled))")
return n
}
}
group.cancelAll()
// return immediately; the group should wait on the tasks anyway
print("return immediately 0 (group cancelled: \(group.isCancelled))")
print("return immediately 0 (task cancelled: \(Task.isCancelled))")
return 0
}
// CHECK: group.spawn { 1 }
//
// CHECK: return immediately 0 (group cancelled: true)
// CHECK: return immediately 0 (task cancelled: false)
//
// CHECK: inside group.spawn { 1 } (group cancelled: true)
// CHECK: inside group.spawn { 1 } (group child task cancelled: true)
// CHECK: result: 0
print("result: \(result)")
assert(result == 0)
}
@available(SwiftStdlib 5.1, *)
@main struct Main {
static func main() async {
await test_skipCallingNext_butInvokeCancelAll()
}
}
| 128e0f2009fe9a522a3eb20504e84fa8 | 29.890909 | 150 | 0.65568 | false | true | false | false |
DiegoSan1895/Smartisan-Notes | refs/heads/master | Smartisan-Notes/Constants.swift | mit | 1 |
//
// Configs.swift
// Smartisan-Notes
//
// Created by DiegoSan on 3/4/16.
// Copyright © 2016 DiegoSan. All rights reserved.
//
import UIKit
let isNotFirstOpenSmartisanNotes = "isNotFirstOpenSmartisanNotes"
let ueAgreeOrNot = "userAgreeToJoinUEPlan"
let NSBundleURL = NSBundle.mainBundle().bundleURL
struct AppID {
static let notesID = 867934588
static let clockID = 828812911
static let syncID = 880078620
static let calenderID = 944154964
}
struct AppURL {
static let clockURL = NSURL(string: "smartisanclock://")!
static let syncURL = NSURL(string: "smartisansync://")!
static let calenderURL = NSURL(string: "smartisancalendar://")!
static let smartisanWeb = NSURL(string: "https://store.smartisan.com")!
}
struct AppItunsURL {
let baseURLString = "http://itunes.apple.com/us/app/id"
static let calenderURL = NSURL(string: "http://itunes.apple.com/us/app/id\(AppID.calenderID)")!
static let syncURL = NSURL(string: "http://itunes.apple.com/us/app/id\(AppID.syncID)")!
static let clockURL = NSURL(string: "http://itunes.apple.com/us/app/id\(AppID.clockID)")!
static let notesURL = NSURL(string: "http://itunes.apple.com/us/app/id\(AppID.notesID)")!
}
struct AppShareURL {
static let notesURL = NSURL(string: "https://itunes.apple.com/us/app/smartisan-notes/id867934588?ls=1&mt=8")!
}
struct iPhoneInfo{
static let iOS_Version = UIDevice.currentDevice().systemVersion
static let deviceName = NSString.deviceName() as String
}
struct AppInfo{
static let App_Version = NSBundle.mainBundle().objectForInfoDictionaryKey("CFBundleShortVersionString") as! String
}
struct Configs {
struct Weibo {
static let appID = "1682079354"
static let appKey = "94c42dacce2401ad73e5080ccd743052"
static let redirectURL = "http://www.limon.top"
}
struct Wechat {
static let appID = "wx4868b35061f87885"
static let appKey = "64020361b8ec4c99936c0e3999a9f249"
}
struct QQ {
static let appID = "1104881792"
}
struct Pocket {
static let appID = "48363-344532f670a052acff492a25"
static let redirectURL = "pocketapp48363:authorizationFinished" // pocketapp + $prefix + :authorizationFinished
}
struct Alipay {
static let appID = "2016012101112529"
}
} | 106a1f612919be5defa706c60098cd68 | 29.25641 | 119 | 0.690971 | false | false | false | false |
Rdxer/SnapKit | refs/heads/develop | Sources/ConstraintDescription.swift | mit | 1 | //
// SnapKit
//
// Copyright (c) 2011-Present SnapKit Team - https://github.com/SnapKit
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#if os(iOS) || os(tvOS)
import UIKit
#else
import AppKit
#endif
public class ConstraintDescription {
public let item: LayoutConstraintItem
public var attributes: ConstraintAttributes
internal var relation: ConstraintRelation? = nil
internal var sourceLocation: (String, UInt)? = nil
internal var label: String? = nil
internal var related: ConstraintItem? = nil
internal var multiplier: ConstraintMultiplierTarget = 1.0
internal var constant: ConstraintConstantTarget = 0.0
internal var priority: ConstraintPriorityTarget = 1000.0
internal lazy var constraint: Constraint? = {
guard let relation = self.relation,
let related = self.related,
let sourceLocation = self.sourceLocation else {
return nil
}
let from = ConstraintItem(target: self.item, attributes: self.attributes)
return Constraint(
from: from,
to: related,
relation: relation,
sourceLocation: sourceLocation,
label: self.label,
multiplier: self.multiplier,
constant: self.constant,
priority: self.priority
)
}()
// MARK: Initialization
internal init(item: LayoutConstraintItem, attributes: ConstraintAttributes) {
self.item = item
self.attributes = attributes
}
}
| 1fb8aed4afc844da22b2363276b5190d | 36.608696 | 81 | 0.68632 | false | false | false | false |
MaartenBrijker/project | refs/heads/back | project/External/AudioKit-master/AudioKit/Common/MIDI/AKMIDI+ReceivingMIDI.swift | apache-2.0 | 1 | //
// AKMIDI+ReceivingMIDI.swift
// AudioKit For OSX
//
// Created by Aurelius Prochazka on 4/30/16.
// Copyright © 2016 AudioKit. All rights reserved.
//
extension AKMIDI {
/// Array of input names
public var inputNames: [String] {
var nameArray = [String]()
let sourceCount = MIDIGetNumberOfSources()
for i in 0 ..< sourceCount {
let source = MIDIGetSource(i)
var inputName: Unmanaged<CFString>?
inputName = nil
MIDIObjectGetStringProperty(source, kMIDIPropertyName, &inputName)
let inputNameStr = (inputName?.takeRetainedValue())! as String
nameArray.append(inputNameStr)
}
return nameArray
}
/// Add a listener to the listeners
public func addListener(listener: AKMIDIListener) {
listeners.append(listener)
}
/// Open a MIDI Input port
///
/// - parameter namedInput: String containing the name of the MIDI Input
///
public func openInput(namedInput: String = "") {
var result = noErr
let sourceCount = MIDIGetNumberOfSources()
for i in 0 ..< sourceCount {
let src = MIDIGetSource(i)
var tempName: Unmanaged<CFString>? = nil
MIDIObjectGetStringProperty(src, kMIDIPropertyName, &tempName)
let inputNameStr = (tempName?.takeRetainedValue())! as String
if namedInput.isEmpty || namedInput == inputNameStr {
inputPorts.append(MIDIPortRef())
var port = inputPorts.last!
result = MIDIInputPortCreateWithBlock(
client, inputPortName, &port, MyMIDIReadBlock)
if result != noErr {
print("Error creating midiInPort : \(result)")
}
MIDIPortConnectSource(port, src, nil)
}
}
}
internal func handleMidiMessage(event: AKMIDIEvent) {
for listener in listeners {
let type = event.status
switch type {
case AKMIDIStatus.ControllerChange:
listener.receivedMIDIController(Int(event.internalData[1]),
value: Int(event.internalData[2]),
channel: Int(event.channel))
case AKMIDIStatus.ChannelAftertouch:
listener.receivedMIDIAfterTouch(Int(event.internalData[1]),
channel: Int(event.channel))
case AKMIDIStatus.NoteOn:
listener.receivedMIDINoteOn(Int(event.internalData[1]),
velocity: Int(event.internalData[2]),
channel: Int(event.channel))
case AKMIDIStatus.NoteOff:
listener.receivedMIDINoteOff(Int(event.internalData[1]),
velocity: Int(event.internalData[2]),
channel: Int(event.channel))
case AKMIDIStatus.PitchWheel:
listener.receivedMIDIPitchWheel(Int(event.data),
channel: Int(event.channel))
case AKMIDIStatus.PolyphonicAftertouch:
listener.receivedMIDIAftertouchOnNote(Int(event.internalData[1]),
pressure: Int(event.internalData[2]),
channel: Int(event.channel))
case AKMIDIStatus.ProgramChange:
listener.receivedMIDIProgramChange(Int(event.internalData[1]),
channel: Int(event.channel))
case AKMIDIStatus.SystemCommand:
listener.receivedMIDISystemCommand(event.internalData)
}
}
}
internal func MyMIDINotifyBlock(midiNotification: UnsafePointer<MIDINotification>) {
_ = midiNotification.memory
//do something with notification - change _ above to let varname
//print("MIDI Notify, messageId= \(notification.messageID.rawValue)")
}
internal func MyMIDIReadBlock(
packetList: UnsafePointer<MIDIPacketList>,
srcConnRefCon: UnsafeMutablePointer<Void>) -> Void {
/*
//can't yet figure out how to access the port passed via srcConnRefCon
//maybe having this port is not that necessary though...
let midiPortPointer = UnsafeMutablePointer<MIDIPortRef>(srcConnRefCon)
let midiPort = midiPortPointer.memory
*/
for packet in packetList.memory {
// a coremidi packet may contain multiple midi events
for event in packet {
handleMidiMessage(event)
}
}
}
} | c3b87202f4e74efe53a66d360dc70f84 | 40.216667 | 91 | 0.548231 | false | false | false | false |
LoveZYForever/HXWeiboPhotoPicker | refs/heads/master | Pods/HXPHPicker/Sources/HXPHPicker/Editor/Controller/Photo/PhotoEditorViewController+Animation.swift | mit | 1 | //
// PhotoEditorViewController+Animation.swift
// HXPHPicker
//
// Created by Slience on 2021/7/14.
//
import UIKit
extension PhotoEditorViewController {
func showChartletView() {
UIView.animate(withDuration: 0.25) {
self.setChartletViewFrame()
}
}
func hiddenChartletView() {
UIView.animate(withDuration: 0.25) {
self.setChartletViewFrame()
}
}
func showFilterView() {
UIView.animate(withDuration: 0.25) {
self.setFilterViewFrame()
}
}
func hiddenFilterView() {
UIView.animate(withDuration: 0.25) {
self.setFilterViewFrame()
}
}
func showBrushColorView() {
brushColorView.isHidden = false
UIView.animate(withDuration: 0.25) {
self.brushColorView.alpha = 1
}
}
func hiddenBrushColorView() {
if brushColorView.isHidden {
return
}
UIView.animate(withDuration: 0.25) {
self.brushColorView.alpha = 0
} completion: { (_) in
guard let option = self.currentToolOption,
option.type == .graffiti else {
return
}
self.brushColorView.isHidden = true
}
}
func showMosaicToolView() {
mosaicToolView.isHidden = false
UIView.animate(withDuration: 0.25) {
self.mosaicToolView.alpha = 1
}
}
func hiddenMosaicToolView() {
if mosaicToolView.isHidden {
return
}
UIView.animate(withDuration: 0.25) {
self.mosaicToolView.alpha = 0
} completion: { (_) in
guard let option = self.currentToolOption,
option.type == .mosaic else {
return
}
self.mosaicToolView.isHidden = true
}
}
func croppingAction() {
if state == .cropping {
cropConfirmView.isHidden = false
cropToolView.isHidden = false
hidenTopView()
}else {
if let option = currentToolOption {
if option.type == .graffiti {
imageView.drawEnabled = true
}else if option.type == .mosaic {
imageView.mosaicEnabled = true
}
}
showTopView()
}
UIView.animate(withDuration: 0.25) {
self.cropConfirmView.alpha = self.state == .cropping ? 1 : 0
self.cropToolView.alpha = self.state == .cropping ? 1 : 0
} completion: { (isFinished) in
if self.state != .cropping {
self.cropConfirmView.isHidden = true
self.cropToolView.isHidden = true
}
}
}
func showTopView() {
topViewIsHidden = false
toolView.isHidden = false
topView.isHidden = false
if let option = currentToolOption {
if option.type == .graffiti {
brushColorView.isHidden = false
}else if option.type == .mosaic {
mosaicToolView.isHidden = false
}
}else {
imageView.stickerEnabled = true
}
UIView.animate(withDuration: 0.25) {
self.toolView.alpha = 1
self.topView.alpha = 1
self.topMaskLayer.isHidden = false
if let option = self.currentToolOption {
if option.type == .graffiti {
self.brushColorView.alpha = 1
}else if option.type == .mosaic {
self.mosaicToolView.alpha = 1
}
}
}
}
func hidenTopView() {
topViewIsHidden = true
UIView.animate(withDuration: 0.25) {
self.toolView.alpha = 0
self.topView.alpha = 0
self.topMaskLayer.isHidden = true
if let option = self.currentToolOption {
if option.type == .graffiti {
self.brushColorView.alpha = 0
}else if option.type == .mosaic {
self.mosaicToolView.alpha = 0
}
}
} completion: { (isFinished) in
if self.topViewIsHidden {
self.toolView.isHidden = true
self.topView.isHidden = true
self.brushColorView.isHidden = true
self.mosaicToolView.isHidden = true
}
}
}
}
| 91ca0375669ab209de5eeff809e9563c | 29.214765 | 72 | 0.51355 | false | false | false | false |
seba368/Flappy-Bird | refs/heads/master | Flappy Bird/GameViewController.swift | mit | 1 | //
// GameViewController.swift
// Flappy Bird
//
// Created by Sebastian Brukalo on 11/7/15.
// Copyright (c) 2015 Sebastian Brukalo. All rights reserved.
//
import UIKit
import SpriteKit
class GameViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
if let scene = GameScene(fileNamed:"GameScene") {
// Configure the view.
let skView = self.view as! SKView
skView.showsFPS = true
skView.showsNodeCount = true
/* Sprite Kit applies additional optimizations to improve rendering performance */
skView.ignoresSiblingOrder = true
/* Set the scale mode to scale to fit the window */
scene.scaleMode = .AspectFill
skView.presentScene(scene)
}
}
override func shouldAutorotate() -> Bool {
return true
}
override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask {
if UIDevice.currentDevice().userInterfaceIdiom == .Phone {
return .AllButUpsideDown
} else {
return .All
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Release any cached data, images, etc that aren't in use.
}
override func prefersStatusBarHidden() -> Bool {
return true
}
}
| 7d9c8f60e842c5eeb54d440fee32cfe7 | 25.811321 | 94 | 0.605911 | false | false | false | false |
mathewsheets/SwiftLearningAssignments | refs/heads/master | Todo_Assignment_2.playground/Contents.swift | mit | 1 | /*:
* callout(Assignment): Based on Sessions 1-7 (specifically Collection Types, Functions, Closures, Enumerations), create a playground that will manage your todos.
**You will need to:**
- Print all your Todos (small description)
- Print a single Todo (large description)
- Add a Todo
- Update a Todo
- Delete a Todo
**Constraints:**
- Model a Todo
- Create functions to:
- Get all your Todos
- Get a single Todo passing an id as an argument
- Add a Todo
- Update a Todo
- Delete a Todo
*/
import Foundation
func printTodos(todos: [Todo]) {
each(todos: todos) { (todo, index) -> Void in
print("\t\(todo.0): \(todo.1) = \(todo.4)")
}
}
initData()
print("Print all your Todos (small description)")
printTodos(todos: todos)
print("\nPrint a single Todo (large description)")
var study = getTodo(id: "1")!
print("\t\(description(todo: study))\n")
print("Add a Todo")
let sweep = createTodo(title: "Sweep", subtitle: "The stairs need a cleaning", description: "Sweep the stairs and then the bedrooms")
addTodo(todo: sweep)
printTodos(todos: todos)
print("\nUpdate a Todo")
updateTodo(todo: (study.0, study.1, study.2, study.3, Status.Completed))
study = getTodo(id: "1")!
print("\t\(description(todo: study))")
print("\nDelete a Todo")
let weed = deleteTodo(id: "0")!
print("\t\(description(todo: weed))\n")
print("Updated list of Todos")
printTodos(todos: todos)
print("\nDisplay only non completed todos")
let nonComplete = filter(todos: todos) { $0.4 != .Completed }
printTodos(todos: nonComplete ?? [])
| 6112c1b4e6af1bfd9ae0bbbda6c8b151 | 26.086207 | 162 | 0.677276 | false | false | false | false |
t4thswm/Course | refs/heads/master | Course/CourseMainViewController.swift | gpl-3.0 | 1 | //
// CourseMainViewController.swift
// Course
//
// Created by Cedric on 2016/12/8.
// Copyright © 2016年 Archie Yu. All rights reserved.
//
import UIKit
import CourseModel
class CourseMainViewController: UIViewController, UIPageViewControllerDelegate, UIPageViewControllerDataSource, UIPickerViewDataSource, UIPickerViewDelegate {
var coursePageVC: UIPageViewController!
var dayControllers: [DisplayCoursesViewController] = []
var nextWeekday = 0
var selectingWeek = false
var editView: UIView!
var labelView: UILabel!
var pickerView: UIPickerView!
let offset: CGFloat = -18
@IBOutlet weak var titleButton: UIButton!
@IBOutlet weak var weekdayPageControl: UIPageControl!
override func viewDidLoad() {
super.viewDidLoad()
self.automaticallyAdjustsScrollViewInsets = false
resumeWeek()
load(from: courseDataFilePath())
for vc in self.childViewControllers {
if vc is UIPageViewController {
coursePageVC = vc as! UIPageViewController
}
}
coursePageVC.delegate = self
coursePageVC.dataSource = self
weekdayPageControl.numberOfPages = weekdayNum
for i in 0..<7 {
dayControllers.append(
storyboard?.instantiateViewController(withIdentifier: "DayCourse") as!
DisplayCoursesViewController)
dayControllers[i].weekday = i
}
titleButton.titleLabel?.font = .boldSystemFont(ofSize: 17)
let width = UIScreen.main.bounds.width
var frame = CGRect(x: 0, y: -224, width: width, height: 224)
editView = UIView(frame: frame)
editView.backgroundColor = UIColor(white: 0.05, alpha: 1)
self.view.addSubview(editView)
frame = CGRect(x: offset, y: -100, width: width, height: 40)
labelView = UILabel(frame: frame)
labelView.text = "当前为第\t\t\t星期"
labelView.textColor = .white
labelView.textAlignment = .center
self.view.addSubview(labelView)
frame = CGRect(x: 0, y: -162, width: width, height: 162)
pickerView = UIPickerView(frame: frame)
pickerView.dataSource = self
pickerView.delegate = self
self.view.addSubview(pickerView)
}
override func viewWillAppear(_ animated: Bool) {
if needReload {
weekdayPageControl.numberOfPages = weekdayNum
var weekday = (Calendar.current.dateComponents([.weekday], from: Date()).weekday! + 5) % 7
if weekday >= weekdayNum { weekday = 0 }
weekdayPageControl.currentPage = weekday
coursePageVC.setViewControllers(
[dayControllers[weekday]], direction: .forward, animated: false, completion: nil)
needReload = false
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? {
let nextWeekday = (weekdayPageControl.currentPage + 1) % weekdayNum
return dayControllers[nextWeekday]
}
func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? {
let nextWeekday = (weekdayPageControl.currentPage + weekdayNum - 1) % weekdayNum
return dayControllers[nextWeekday]
}
func pageViewController(_ pageViewController: UIPageViewController, willTransitionTo pendingViewControllers: [UIViewController]) {
if let displayController = pendingViewControllers[0] as? DisplayCoursesViewController {
nextWeekday = displayController.weekday
}
}
func pageViewController(_ pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [UIViewController], transitionCompleted completed: Bool) {
if completed {
weekdayPageControl.currentPage = nextWeekday
}
}
@IBAction func changeWeek(_ sender: UIButton) {
let width = UIScreen.main.bounds.width
if selectingWeek {
titleButton.setTitle("课程", for: .normal)
titleButton.titleLabel?.font = .boldSystemFont(ofSize: 17)
let frame = CGRect(x: 0, y: -224, width: width, height: 224)
let labelFrame = CGRect(x: offset, y: -100, width: width, height: 40)
let pickerFrame = CGRect(x: 0, y: -162, width: width, height: 162)
UIView.animate(withDuration: 0.5, animations: {() -> Void in
self.editView.frame = frame
self.labelView.frame = labelFrame
self.pickerView.frame = pickerFrame
})
courseWeek = pickerView.selectedRow(inComponent: 0) + 1
relevantWeek = Calendar.current.dateComponents([.weekOfYear], from: Date()).weekOfYear!
let userDefault = UserDefaults(suiteName: "group.studio.sloth.Course")
userDefault?.set(courseWeek, forKey: "CourseWeek")
userDefault?.set(relevantWeek, forKey: "RelevantWeek")
userDefault?.synchronize()
for controller in dayControllers {
for i in 0..<lessonList.count {
lessonList[i].removeAll()
}
for course in courseList {
for lesson in course.lessons {
if lesson.firstWeek <= courseWeek && lesson.lastWeek >= courseWeek && (lesson.alternate == 3 || (lesson.alternate % 2) == (courseWeek % 2)) {
lessonList[lesson.weekday].append(lesson)
}
}
}
for i in 0..<lessonList.count {
lessonList[i].sort() { $0.firstClass < $1.firstClass }
}
(controller.view as! UITableView).reloadData()
}
} else {
resumeWeek()
pickerView.selectRow(courseWeek - 1, inComponent: 0, animated: false)
titleButton.setTitle("确认", for: .normal)
titleButton.titleLabel?.font = .boldSystemFont(ofSize: 21)
let frame = CGRect(x: 0, y: 0, width: width, height: 224)
let labelFrame = CGRect(x: offset, y: 124, width: width, height: 40)
let pickerFrame = CGRect(x: 0, y: 64, width: width, height: 162)
UIView.animate(withDuration: 0.5, animations: {() -> Void in
self.editView.frame = frame
self.labelView.frame = labelFrame
self.pickerView.frame = pickerFrame
})
}
selectingWeek = !selectingWeek
}
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return weekNum
}
func pickerView(_ pickerView: UIPickerView, rowHeightForComponent component: Int) -> CGFloat {
return 40
}
func pickerView(_ pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusing view: UIView?) -> UIView {
let label = UILabel()
label.text = "\(row + 1)"
label.textColor = .white
label.font = UIFont.systemFont(ofSize: 28)
label.textAlignment = .center
return label
}
}
| 3363c5c0d6a5fce628a134de05df63bb | 37.929648 | 190 | 0.606428 | false | false | false | false |
mownier/photostream | refs/heads/master | Photostream/Modules/Liked Post/Presenter/LikedPostPresenter.swift | mit | 1 | //
// LikedPostPresenter.swift
// Photostream
//
// Created by Mounir Ybanez on 19/01/2017.
// Copyright © 2017 Mounir Ybanez. All rights reserved.
//
protocol LikedPostPresenterInterface: BaseModulePresenter, BaseModuleInteractable {
var userId: String! { set get }
var posts: [LikedPostData] { set get }
var limit: UInt { set get }
func indexOf(post id: String) -> Int?
func appendPosts(_ data: [LikedPostData])
}
class LikedPostPresenter: LikedPostPresenterInterface {
typealias ModuleInteractor = LikedPostInteractorInput
typealias ModuleView = LikedPostScene
typealias ModuleWireframe = LikedPostWireframeInterface
weak var view: ModuleView!
var interactor: ModuleInteractor!
var wireframe: ModuleWireframe!
var userId: String!
var posts = [LikedPostData]()
var limit: UInt = 10
func indexOf(post id: String) -> Int? {
return posts.index { item -> Bool in
return item.id == id
}
}
func appendPosts(_ data: [LikedPostData]) {
let filtered = data.filter { post in
return indexOf(post: post.id) == nil
}
posts.append(contentsOf: filtered)
}
}
extension LikedPostPresenter: LikedPostModuleInterface {
var postCount: Int {
return posts.count
}
func exit() {
var property = WireframeExitProperty()
property.controller = view.controller
wireframe.exit(with: property)
}
func viewDidLoad() {
view.isLoadingViewHidden = false
interactor.fetchNew(userId: userId, limit: limit)
}
func refresh() {
view.isEmptyViewHidden = true
view.isRefreshingViewHidden = false
interactor.fetchNew(userId: userId, limit: limit)
}
func loadMore() {
interactor.fetchNext(userId: userId, limit: limit)
}
func unlikePost(at index: Int) {
guard var post = post(at: index), post.isLiked else {
view.reload(at: index)
return
}
post.isLiked = false
post.likes -= 1
posts[index] = post
view.reload(at: index)
interactor.unlikePost(id: post.id)
}
func likePost(at index: Int) {
guard var post = post(at: index), !post.isLiked else {
view.reload(at: index)
return
}
post.isLiked = true
post.likes += 1
posts[index] = post
view.reload(at: index)
interactor.likePost(id: post.id)
}
func toggleLike(at index: Int) {
guard let post = post(at: index) else {
view.reload(at: index)
return
}
if post.isLiked {
unlikePost(at: index)
} else {
likePost(at: index)
}
}
func post(at index: Int) -> LikedPostData? {
guard posts.isValid(index) else {
return nil
}
return posts[index]
}
}
extension LikedPostPresenter: LikedPostInteractorOutput {
func didRefresh(data: [LikedPostData]) {
view.isLoadingViewHidden = true
view.isRefreshingViewHidden = true
posts.removeAll()
appendPosts(data)
if postCount == 0 {
view.isEmptyViewHidden = false
}
view.didRefresh(error: nil)
view.reload()
}
func didLoadMore(data: [LikedPostData]) {
view.didLoadMore(error: nil)
guard data.count > 0 else {
return
}
appendPosts(data)
view.reload()
}
func didRefresh(error: PostServiceError) {
view.isLoadingViewHidden = true
view.isRefreshingViewHidden = true
view.didRefresh(error: error.message)
}
func didLoadMore(error: PostServiceError) {
view.didLoadMore(error: error.message)
}
func didLike(error: PostServiceError?, postId: String) {
view.didLike(error: error?.message)
guard let index = indexOf(post: postId),
var post = post(at: index),
error != nil else {
return
}
post.isLiked = false
if post.likes > 0 {
post.likes -= 1
}
posts[index] = post
view.reload(at: index)
}
func didUnlike(error: PostServiceError?, postId: String) {
view.didUnlike(error: error?.message)
guard let index = indexOf(post: postId),
var post = post(at: index),
error != nil else {
return
}
post.isLiked = true
post.likes += 1
posts[index] = post
view.reload(at: index)
}
}
| e668d844b7379a76664c723fe93be493 | 23.262376 | 83 | 0.550704 | false | false | false | false |
ReactiveKit/ReactiveGitter | refs/heads/master | Views/View Controllers/Authentication.swift | mit | 1 | //
// AuthenticationViewController.swift
// ReactiveGitter
//
// Created by Srdan Rasic on 15/01/2017.
// Copyright © 2017 ReactiveKit. All rights reserved.
//
import UIKit
extension ViewController {
public class Authentication: UIViewController {
public private(set) lazy var titleLabel = UILabel().setup {
$0.text = "Reactive Gitter"
$0.font = .preferredFont(forTextStyle: .title1)
}
public private(set) lazy var loginButton = UIButton(type: .system).setup {
$0.setTitle("Log in", for: .normal)
}
public init() {
super.init(nibName: nil, bundle: nil)
view.backgroundColor = .white
view.addSubview(titleLabel)
titleLabel.center(in: view)
view.addSubview(loginButton)
loginButton.center(in: view, offset: .init(x: 0, y: 60))
}
public required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
}
| 40aff54d99866ab2bc3adf67ad980d0b | 23.179487 | 78 | 0.658537 | false | false | false | false |
AaronMT/firefox-ios | refs/heads/master | Client/Frontend/Browser/TopTabsViews.swift | mpl-2.0 | 6 | /* 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
struct TopTabsSeparatorUX {
static let Identifier = "Separator"
static let Width: CGFloat = 1
}
class TopTabsSeparator: UICollectionReusableView {
override init(frame: CGRect) {
super.init(frame: frame)
self.backgroundColor = UIColor.theme.topTabs.separator
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
class TopTabsHeaderFooter: UICollectionReusableView {
let line = UIView()
override init(frame: CGRect) {
super.init(frame: frame)
line.semanticContentAttribute = .forceLeftToRight
addSubview(line)
line.backgroundColor = UIColor.theme.topTabs.separator
}
func arrangeLine(_ kind: String) {
line.snp.removeConstraints()
switch kind {
case UICollectionView.elementKindSectionHeader:
line.snp.makeConstraints { make in
make.trailing.equalTo(self)
}
case UICollectionView.elementKindSectionFooter:
line.snp.makeConstraints { make in
make.leading.equalTo(self)
}
default:
break
}
line.snp.makeConstraints { make in
make.height.equalTo(TopTabsUX.SeparatorHeight)
make.width.equalTo(TopTabsUX.SeparatorWidth)
make.top.equalTo(self).offset(TopTabsUX.SeparatorYOffset)
}
}
override func apply(_ layoutAttributes: UICollectionViewLayoutAttributes) {
layer.zPosition = CGFloat(layoutAttributes.zIndex)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
class TopTabCell: UICollectionViewCell, PrivateModeUI {
static let Identifier = "TopTabCellIdentifier"
static let ShadowOffsetSize: CGFloat = 2 //The shadow is used to hide the tab separator
var selectedTab = false {
didSet {
backgroundColor = selectedTab ? UIColor.theme.topTabs.tabBackgroundSelected : UIColor.theme.topTabs.tabBackgroundUnselected
titleText.textColor = selectedTab ? UIColor.theme.topTabs.tabForegroundSelected : UIColor.theme.topTabs.tabForegroundUnselected
highlightLine.isHidden = !selectedTab
closeButton.tintColor = selectedTab ? UIColor.theme.topTabs.closeButtonSelectedTab : UIColor.theme.topTabs.closeButtonUnselectedTab
closeButton.backgroundColor = backgroundColor
closeButton.layer.shadowColor = backgroundColor?.cgColor
if selectedTab {
drawShadow()
} else {
self.layer.shadowOpacity = 0
}
}
}
let titleText: UILabel = {
let titleText = UILabel()
titleText.textAlignment = .left
titleText.isUserInteractionEnabled = false
titleText.numberOfLines = 1
titleText.lineBreakMode = .byCharWrapping
titleText.font = DynamicFontHelper.defaultHelper.DefaultSmallFont
titleText.semanticContentAttribute = .forceLeftToRight
return titleText
}()
let favicon: UIImageView = {
let favicon = UIImageView()
favicon.layer.cornerRadius = 2.0
favicon.layer.masksToBounds = true
favicon.semanticContentAttribute = .forceLeftToRight
return favicon
}()
let closeButton: UIButton = {
let closeButton = UIButton()
closeButton.setImage(UIImage.templateImageNamed("menu-CloseTabs"), for: [])
closeButton.tintColor = UIColor.Photon.Grey40
closeButton.imageEdgeInsets = UIEdgeInsets(top: 15, left: TopTabsUX.TabTitlePadding, bottom: 15, right: TopTabsUX.TabTitlePadding)
closeButton.layer.shadowOpacity = 0.8
closeButton.layer.masksToBounds = false
closeButton.layer.shadowOffset = CGSize(width: -TopTabsUX.TabTitlePadding, height: 0)
closeButton.semanticContentAttribute = .forceLeftToRight
return closeButton
}()
let highlightLine: UIView = {
let line = UIView()
line.backgroundColor = UIColor.Photon.Blue60
line.isHidden = true
line.semanticContentAttribute = .forceLeftToRight
return line
}()
weak var delegate: TopTabCellDelegate?
override init(frame: CGRect) {
super.init(frame: frame)
closeButton.addTarget(self, action: #selector(closeTab), for: .touchUpInside)
contentView.addSubview(titleText)
contentView.addSubview(closeButton)
contentView.addSubview(favicon)
contentView.addSubview(highlightLine)
favicon.snp.makeConstraints { make in
make.centerY.equalTo(self).offset(TopTabsUX.TabNudge)
make.size.equalTo(TabTrayControllerUX.FaviconSize)
make.leading.equalTo(self).offset(TopTabsUX.TabTitlePadding)
}
titleText.snp.makeConstraints { make in
make.centerY.equalTo(self)
make.height.equalTo(self)
make.trailing.equalTo(closeButton.snp.leading).offset(TopTabsUX.TabTitlePadding)
make.leading.equalTo(favicon.snp.trailing).offset(TopTabsUX.TabTitlePadding)
}
closeButton.snp.makeConstraints { make in
make.centerY.equalTo(self).offset(TopTabsUX.TabNudge)
make.height.equalTo(self)
make.width.equalTo(self.snp.height).offset(-TopTabsUX.TabTitlePadding)
make.trailing.equalTo(self.snp.trailing)
}
highlightLine.snp.makeConstraints { make in
make.top.equalTo(self)
make.leading.equalTo(self).offset(-TopTabCell.ShadowOffsetSize)
make.trailing.equalTo(self).offset(TopTabCell.ShadowOffsetSize)
make.height.equalTo(TopTabsUX.HighlightLineWidth)
}
self.clipsToBounds = false
applyUIMode(isPrivate: false)
}
func applyUIMode(isPrivate: Bool) {
highlightLine.backgroundColor = UIColor.theme.topTabs.tabSelectedIndicatorBar(isPrivate)
}
func configureWith(tab: Tab, isSelected: Bool) {
applyUIMode(isPrivate: tab.isPrivate)
self.titleText.text = tab.displayTitle
if tab.displayTitle.isEmpty {
if let url = tab.webView?.url, let internalScheme = InternalURL(url) {
self.titleText.text = Strings.AppMenuNewTabTitleString
self.accessibilityLabel = internalScheme.aboutComponent
} else {
self.titleText.text = tab.webView?.url?.absoluteDisplayString
}
self.closeButton.accessibilityLabel = String(format: Strings.TopSitesRemoveButtonAccessibilityLabel, self.titleText.text ?? "")
} else {
self.accessibilityLabel = tab.displayTitle
self.closeButton.accessibilityLabel = String(format: Strings.TopSitesRemoveButtonAccessibilityLabel, tab.displayTitle)
}
self.selectedTab = isSelected
if let siteURL = tab.url?.displayURL {
self.favicon.contentMode = .center
self.favicon.setImageAndBackground(forIcon: tab.displayFavicon, website: siteURL) { [weak self] in
guard let self = self else { return }
self.favicon.image = self.favicon.image?.createScaled(CGSize(width: 15, height: 15))
if self.favicon.backgroundColor == .clear {
self.favicon.backgroundColor = .white
}
}
} else {
self.favicon.image = UIImage(named: "defaultFavicon")
self.favicon.contentMode = .scaleAspectFit
self.favicon.backgroundColor = .clear
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func prepareForReuse() {
super.prepareForReuse()
self.layer.shadowOpacity = 0
}
@objc func closeTab() {
delegate?.tabCellDidClose(self)
}
// When a tab is selected the shadow prevents the tab separators from showing.
func drawShadow() {
self.layer.masksToBounds = false
self.layer.shadowColor = backgroundColor?.cgColor
self.layer.shadowOpacity = 1
self.layer.shadowRadius = 0
self.layer.shadowPath = UIBezierPath(roundedRect: CGRect(width: self.frame.size.width + (TopTabCell.ShadowOffsetSize * 2), height: self.frame.size.height), cornerRadius: 0).cgPath
self.layer.shadowOffset = CGSize(width: -TopTabCell.ShadowOffsetSize, height: 0)
}
override func apply(_ layoutAttributes: UICollectionViewLayoutAttributes) {
layer.zPosition = CGFloat(layoutAttributes.zIndex)
}
}
class TopTabFader: UIView {
lazy var hMaskLayer: CAGradientLayer = {
let innerColor: CGColor = UIColor.Photon.White100.cgColor
let outerColor: CGColor = UIColor(white: 1, alpha: 0.0).cgColor
let hMaskLayer = CAGradientLayer()
hMaskLayer.colors = [outerColor, innerColor, innerColor, outerColor]
hMaskLayer.locations = [0.00, 0.005, 0.995, 1.0]
hMaskLayer.startPoint = CGPoint(x: 0, y: 0.5)
hMaskLayer.endPoint = CGPoint(x: 1.0, y: 0.5)
hMaskLayer.anchorPoint = .zero
return hMaskLayer
}()
init() {
super.init(frame: .zero)
layer.mask = hMaskLayer
}
internal override func layoutSubviews() {
super.layoutSubviews()
let widthA = NSNumber(value: Float(CGFloat(8) / frame.width))
let widthB = NSNumber(value: Float(1 - CGFloat(8) / frame.width))
hMaskLayer.locations = [0.00, widthA, widthB, 1.0]
hMaskLayer.frame = CGRect(width: frame.width, height: frame.height)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
class TopTabsViewLayoutAttributes: UICollectionViewLayoutAttributes {
override func isEqual(_ object: Any?) -> Bool {
guard let object = object as? TopTabsViewLayoutAttributes else {
return false
}
return super.isEqual(object)
}
}
| 8458ee1a216e66aa1f29b1572b149389 | 36.846154 | 187 | 0.656794 | false | false | false | false |
izotx/iTenWired-Swift | refs/heads/master | Conference App/SocialMediaCell.swift | bsd-2-clause | 1 | // Copyright (c) 2016, Izotx
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of Izotx nor the names of its contributors may be used to
// endorse or promote products derived from this software without specific
// prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
// SocialMediaCell.swift
// Conference App
//
// Created by Felipe on 5/17/16.
import UIKit
import UIKit
class SocialMediaCell: UITableViewCell {
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var logo: UIImageView!
func setName(name:String){
self.nameLabel.text = name
}
func setlogo(logo:String){
let image = UIImage(named: logo)
self.logo.image = image
}
func build(socialItem: SocialItem){
self.UIConfig()
self.setName(socialItem.name)
self.setlogo(socialItem.logo)
}
internal func UIConfig(){
self.backgroundColor = ItenWiredStyle.background.color.mainColor
self.nameLabel.textColor = ItenWiredStyle.text.color.mainColor
}
} | 32801b5b2f6576840d95b16717d59e88 | 36.68254 | 82 | 0.711757 | false | false | false | false |
leizh007/HiPDA | refs/heads/master | HiPDA/HiPDA/Sections/Message/MessageNavigationBarTitleView.swift | mit | 1 | //
// MessageNavigationBarTitleView.swift
// HiPDA
//
// Created by leizh007 on 2017/6/27.
// Copyright © 2017年 HiPDA. All rights reserved.
//
import UIKit
protocol MesssageNavigationBarTitleViewDelegate: class {
func itemDidSelect(_ index: Int)
}
class MessageNavigationBarTitleView: UIView {
@IBOutlet private var messagesCountLabels: [UILabel]!
@IBOutlet private var messageLabels: [UILabel]!
weak var delegate: MesssageNavigationBarTitleViewDelegate?
private var lastSelectedIndex = 0
var model: UnReadMessagesCountModel! {
didSet {
messagesCountLabels[0].text = "\(model.threadMessagesCount)"
messagesCountLabels[1].text = "\(model.privateMessagesCount)"
messagesCountLabels[2].text = "\(model.friendMessagesCount)"
messagesCountLabels[0].isHidden = model.threadMessagesCount == 0
messagesCountLabels[1].isHidden = model.privateMessagesCount == 0
messagesCountLabels[2].isHidden = model.friendMessagesCount == 0
}
}
@IBAction private func messagesContainerViewDidTapped(_ sender: UITapGestureRecognizer) {
let tag = sender.view?.tag ?? 0
select(index: tag)
if lastSelectedIndex != tag {
lastSelectedIndex = tag
delegate?.itemDidSelect(tag)
} else {
NotificationCenter.default.post(name: .MessageViewControllerTabRepeatedSelected, object: nil)
}
}
func configureApperance(with offset: CGFloat) {
var lowerIndex = Int(floor(offset))
if lowerIndex < 0 {
lowerIndex = 0
}
var upperIndex = Int(ceil(offset))
if upperIndex >= messagesCountLabels.count {
upperIndex = messagesCountLabels.count - 1
}
let lowerFactor = 1 - (offset - CGFloat(lowerIndex))
let upperFactor = 1 - (CGFloat(upperIndex) - offset)
for (index, factor) in zip([lowerIndex, upperIndex], [lowerFactor, upperFactor]) {
messageLabels[index].textColor = UIColor(red: (101.0 - 72 * factor) / 255.0,
green: (119.0 + 43 * factor) / 255.0,
blue: (134.0 + 108 * factor) / 255.0,
alpha: 1.0)
messageLabels[index].transform = CGAffineTransform(scaleX: 1.0 - 2.0 * (1 - factor) / 17.0,
y: 1.0 - 2.0 * (1 - factor) / 17.0)
}
lastSelectedIndex = Int(round(offset))
}
func select(index: Int) {
guard index >= 0 && index < messageLabels.count else { return }
UIView.animate(withDuration: C.UI.animationDuration) {
for i in 0..<self.messageLabels.count {
let label = self.messageLabels[i]
if i == index {
label.transform = .identity
label.textColor = #colorLiteral(red: 0.1137254902, green: 0.6352941176, blue: 0.9490196078, alpha: 1)
} else {
label.transform = CGAffineTransform(scaleX: 15.0 / 17.0, y: 15.0 / 17.0)
label.textColor = #colorLiteral(red: 0.3960784314, green: 0.4666666667, blue: 0.5254901961, alpha: 1)
}
}
}
}
}
| bbf6fd3013671a35254c2422c6a962e7 | 41.4375 | 121 | 0.569367 | false | false | false | false |
vchuo/Photoasis | refs/heads/master | Photoasis/Classes/Views/Views/ImageViewer/POImageViewerLinkedImageView.swift | mit | 1 | //
// POImageViewerLinkedImageView.swift
// イメージビューアとリンクしているイメージビュー。
// このクラスを使用するには、UIImageViewを使う場所はPOImageViewerLinkedImageViewを入れるだけ。
// イメージビューアを開くに必要なボタンなどは自動で生成する。
//
// 使用上の注意:
// ・POImageViewerLinkedImageViewのポジションとサイズを設定する時に、必ず
// 用意しているupdateOriginとupdateSizeのファンクションを使う。このビューに
// 関連するオーバーレイボタンのポジションとサイズの調整も必要から。
//
// Created by Vernon Chuo Chian Khye on 2017/02/26.
// Copyright © 2017 Vernon Chuo Chian Khye. All rights reserved.
//
import UIKit
import RxSwift
import ChuoUtil
class POImageViewerLinkedImageView: UIImageView {
// MARK: - Public Properties
// イメージビューアーモードを有効するか
var imageViewerModeEnabled: Bool = true
// 著者名
private var _photoAuthorName = ""
var photoAuthorName: String {
get { return _photoAuthorName }
set(newValue) { _photoAuthorName = newValue }
}
// オーバーレイボタン
var overlayButtonAction: (() -> Void)? // オーバーレイボタンに関連するアクション
var overlayButtonPressBeganEventCallback: (() -> Void)? // オーバーレイボタンプレス開始時のコールバック
var overlayButtonPressEndedEventCallback: (() -> Void)? // オーバーレイボタンプレス終わる時のコールバック
var overlayButtonShouldDisplayFadeEffectWhenPressed: Bool { // オーバーレイボタンが押された時にフェード効果を表示するか
get { return overlayButton.shouldDisplayFadeEffectWhenPressed }
set(display) { overlayButton.shouldDisplayFadeEffectWhenPressed = display }
}
// MARK: - Views
private var topView = UIView()
private var parentView: UIView?
private let overlayButton = CUOverlayButtonView() // イメージビューアを開くにはオーバーレイボタンを押す
private let imageViewerScrollView = UIScrollView() // 画像を拡大するためのスクロールビュー
private let imageView = UIImageView() // 拡大・パニング用イメージビュー
private let transitionImageView = UIImageView()
private let backButtonContainerView = UIView()
private let backButtonImageView = UIImageView()
private let backButtonOverlayButton = CUOverlayButtonView()
private let shareButtonImageView = UIImageView()
private let shareButtonOverlayButton = CUOverlayButtonView()
private var authorNameView = POImageViewerAuthorNameView()
// MARK: - Private Properties
private let disposeBag = DisposeBag()
// ステート関連
private var imageViewerIsDisplaying: Bool = false
private var executingImageViewerTransitionAnimation: Bool = false
private var buttonsDisplaying: Bool = true
// アニメーション関連
private var panGestureStartCoordinate: CGPoint = CGPointZero
private var executingSwipeToHideAnimation: Bool = false
// レイアウト関連
private var imageCenterAtMinimumZoom: CGPoint = CGPointZero
// ジェスチャ認識
private var pan = UIPanGestureRecognizer()
private var singleTap = UITapGestureRecognizer()
private var doubleTap = UITapGestureRecognizer()
// MARK: - Init
init() {
super.init(frame: CGRectZero)
setup()
}
required init?(coder aDecoder: NSCoder) {
super.init(frame: CGRectZero)
setup()
}
// MARK: - Public Functions
/**
ビュー起源の更新。
- parameter originX: 起源のx座標
- parameter originY: 起源のy座標
*/
func updateOrigin(originX: CGFloat? = nil, originY: CGFloat? = nil) {
if parentView == nil {
guard let superview = self.superview else { return }
superview.addSubview(overlayButton)
self.parentView = superview
}
if let originX = originX {
self.frame.origin.x = originX
overlayButton.frame.origin.x = originX
}
if let originY = originY {
self.frame.origin.y = originY
overlayButton.frame.origin.y = originY
}
}
/**
ビューの更新。
- parameter origin: 起源
- parameter size: サイズ
*/
func updateSize(width: CGFloat? = nil, height: CGFloat? = nil) {
if parentView == nil {
guard let superview = self.superview else { return }
superview.addSubview(overlayButton)
self.parentView = superview
}
if let width = width {
self.bounds.size.width = width
overlayButton.bounds.size.width = width
}
if let height = height {
self.bounds.size.height = height
overlayButton.bounds.size.height = height
}
}
/**
イメージビューを表示。
*/
func display() {
self.hidden = false
self.overlayButton.hidden = false
}
/**
イメージビューを隠す。
*/
func hide() {
self.hidden = true
self.overlayButton.hidden = true
}
/**
イメージビューアを表示。
*/
func displayImageViewer() {
guard let image = self.image else { return }
if imageViewerIsDisplaying { return }
guard let view = POUtilities.getTopViewController()?.view else { return }
guard let parentView = parentView else { return }
executingImageViewerTransitionAnimation = true
topView = view
imageViewerIsDisplaying = true
UIApplication.sharedApplication().setStatusBarHidden(true, withAnimation: .Slide)
let aspectRatio = image.size.width / image.size.height,
maxWidth = POConstants.MainScreenSize.width,
maxHeight = POConstants.MainScreenSize.height,
desiredHeight = maxWidth / aspectRatio,
size = (desiredHeight <= maxHeight) ? CGSizeMake(maxWidth, desiredHeight)
: CGSizeMake(maxHeight * aspectRatio, maxHeight)
imageViewerScrollView.zoomScale = 1
imageViewerScrollView.minimumZoomScale = POConstants.ImageViewerScrollViewMinimumZoomLevel
imageViewerScrollView.maximumZoomScale = POConstants.ImageViewerScrollViewMaximumZoomLevel
imageViewerScrollView.bounds.size = topView.bounds.size
imageViewerScrollView.center = CUHelper.centerPointOf(topView)
imageView.layer.cornerRadius = 0
imageView.transform = CGAffineTransformIdentity
imageView.bounds.size = size
imageView.center = CUHelper.centerPointOf(imageViewerScrollView)
imageView.image = image
imageViewerScrollView.contentSize = size
// 借りのイメージビュー
let startBounds = parentView.convertRect(self.bounds, toView: topView),
startScale = startBounds.width / imageView.bounds.size.width,
startOrigin = parentView.convertPoint(self.frame.origin, toView: topView),
startCenter = CGPointMake(startOrigin.x + (startBounds.width / 2), startOrigin.y + (startBounds.height / 2))
transitionImageView.bounds.size = imageView.bounds.size
transitionImageView.center = startCenter
transitionImageView.layer.cornerRadius = POConstants.HomeTableViewCellPhotoCornerRadius
transitionImageView.transform = CGAffineTransformMakeScale(startScale, startScale)
transitionImageView.image = image
// 最初ズームレベルのイメージセンターを先に計算して保存
imageCenterAtMinimumZoom = centerPointNeededToCenterImageViewInImageViewerScrollView()
// 著者名ビュー
authorNameView.updateAuthorName(_photoAuthorName)
// ボタン
backButtonContainerView.transform = POConstants.ImageViewerButtonHiddenScaleTransform
shareButtonImageView.transform = POConstants.ImageViewerButtonHiddenScaleTransform
// サブビューの追加
imageViewerScrollView.addSubview(imageView)
topView.addSubview(imageViewerScrollView)
topView.addSubview(transitionImageView)
topView.addSubview(authorNameView)
topView.addSubview(shareButtonImageView)
topView.addSubview(shareButtonOverlayButton)
topView.addSubview(backButtonContainerView)
topView.addSubview(backButtonOverlayButton)
// アニメーション前の準備
transitionImageView.alpha = 0.0
imageView.hidden = true
imageViewerScrollView.backgroundColor = UIColor.fromHexa(0xFFFFFF, alpha: 0.0)
// 表示アニメーション
CUHelper.animateKeyframes(
POConstants.ImageViewerDisplayAnimationDuration,
animations: {
UIView.addKeyframeWithRelativeStartTime(0.0, relativeDuration: 0.4) {
self.alpha = 0.0
self.transitionImageView.alpha = 1.0
}
UIView.addKeyframeWithRelativeStartTime(0.0, relativeDuration: 0.9) {
self.imageViewerScrollView.backgroundColor = UIColor.fromHexa(0xFFFFFF, alpha: POConstants.ImageViewerScrollViewBackgroundMaxAlpha)
self.transitionImageView.transform = CGAffineTransformMakeScale(1, 1)
self.transitionImageView.layer.cornerRadius = 0
self.transitionImageView.center = CUHelper.centerPointOf(self.imageViewerScrollView)
}
}
) { _ in
// 確認とクリーンアップ
if self.transitionImageView.center == CUHelper.centerPointOf(self.imageViewerScrollView) {
self.executeCleanupForImageViewerDisplaySequence(); return
}
CUHelper.animate(
POConstants.ImageViewerDisplayAnimationDuration,
animations: { self.transitionImageView.center = CUHelper.centerPointOf(self.imageViewerScrollView) }
) { _ in self.executeCleanupForImageViewerDisplaySequence() }
}
}
// MARK: - Gesture Related Functions
/**
パンジェスチャがあるときの処理。
- parameter sender: パンジェスチャ
*/
func panGesture(sender: UIPanGestureRecognizer) {
if executingImageViewerTransitionAnimation { return }
let currentCoordinate = sender.locationInView(imageViewerScrollView)
if sender.state == .Began {
updateViewForPanGestureStart(currentCoordinate); return
}
if sender.state == .Ended {
updateViewForPanGestureEnd(sender, currentCoordinate: currentCoordinate); return
}
if executingSwipeToHideAnimation { self.updateViewForPanGestureChange(currentCoordinate) }
}
/**
シングルタップジェスチャがあるときの処理。
- parameter sender: シングルタップジェスチャ
*/
func singleTapGesture(sender: UITapGestureRecognizer) {
if executingImageViewerTransitionAnimation { return }
if imageViewerScrollView.zoomScale == POConstants.ImageViewerScrollViewMinimumZoomLevel {
if buttonsDisplaying {
hideButtons()
} else {
displayButtons()
}
} else {
if !imageView.bounds.contains(sender.locationInView(imageView)) {
CUHelper.animate(
POConstants.ImageViewerDoubleTapZoomAnimationDuration,
animations: {
self.imageViewerScrollView.zoomScale = POConstants.ImageViewerScrollViewMinimumZoomLevel
self.imageView.center = self.centerPointNeededToCenterImageViewInImageViewerScrollView()
}
)
}
}
}
/**
ダブルタップジェスチャがあるときの処理。
- parameter sender: ダブルタップジェスチャ
*/
func doubleTapGesture(sender: UITapGestureRecognizer) {
if executingImageViewerTransitionAnimation { return }
if imageView.bounds.contains(sender.locationInView(imageView)) {
if imageViewerScrollView.zoomScale == 1 {
updateViewForDoubleTapGestureZoomIn(sender)
} else {
updateViewForDoubleTapGestureZoomOut()
}
}
}
// MARK: - Private Functions
/**
セットアップ。
*/
private func setup() {
imageViewerScrollView.delegate = self
imageViewerScrollView.bouncesZoom = false
imageView.contentMode = .ScaleAspectFit
imageView.clipsToBounds = true
transitionImageView.contentMode = .ScaleAspectFit
transitionImageView.clipsToBounds = true
setupOverlayButton()
setupBackButton()
setupShareButton()
setupGestureRecognizers()
}
/**
戻るボタンのセットアップ。
*/
private func setupBackButton() {
// コンテナビュー
backButtonContainerView.bounds.size = POConstants.ImageViewerButtonSize
backButtonContainerView.center = CGPointMake(
backButtonContainerView.bounds.width * (4 / 5),
POConstants.MainScreenSize.height - backButtonContainerView.bounds.height * (5 / 4)
)
backButtonContainerView.backgroundColor = POColors.ImageViewerBackButtonBackgroundColor
backButtonContainerView.layer.cornerRadius = POConstants.ImageViewerButtonSize.width / 2
backButtonContainerView.clipsToBounds = true
// 戻る矢印アイコン
if let icon = UIImage(named: "back") {
backButtonImageView.image = icon.imageWithRenderingMode(.AlwaysTemplate)
backButtonImageView.tintColor = UIColor.whiteColor()
}
backButtonImageView.bounds.size = POConstants.ImageViewerBackButtonImageViewSize
backButtonImageView.center = CUHelper.centerPointOf(backButtonContainerView)
backButtonContainerView.addSubview(backButtonImageView)
// オーバーレイボタン
backButtonOverlayButton.bounds.size = POConstants.ImageViewerButtonSize
backButtonOverlayButton.center = backButtonContainerView.center
backButtonOverlayButton.layer.cornerRadius = POConstants.ImageViewerButtonSize.width / 2
backButtonOverlayButton.clipsToBounds = true
backButtonOverlayButton.buttonAction = { self.hideImageViewer() }
}
/**
シェアボタンのセットアップ。
*/
private func setupShareButton() {
// イメージビュー
shareButtonImageView.image = UIImage(named: "share")
shareButtonImageView.bounds.size = POConstants.ImageViewerButtonSize
shareButtonImageView.center = CGPointMake(
POConstants.MainScreenSize.width - backButtonContainerView.center.x,
backButtonContainerView.center.y
)
shareButtonImageView.alpha = POConstants.ImageViewerShareButtonAlpha
// オーバーレイボタン
shareButtonOverlayButton.bounds.size = CGSizeMake(
POConstants.ImageViewerButtonSize.width - POConstants.ImageViewerShareButtonOverlayButtonSizeAdjustment,
POConstants.ImageViewerButtonSize.height - POConstants.ImageViewerShareButtonOverlayButtonSizeAdjustment
)
shareButtonOverlayButton.center = shareButtonImageView.center
shareButtonOverlayButton.layer.cornerRadius = POConstants.ImageViewerButtonSize.width / 2
shareButtonOverlayButton.buttonAction = {
if let topViewController = POUtilities.getTopViewController() {
var activityItems: [AnyObject] = [POStrings.ShareMessage]
if let image = self.image {
activityItems.append(image)
}
let activityVC = UIActivityViewController(activityItems: activityItems, applicationActivities: nil)
activityVC.completionWithItemsHandler = {(activityType, completed:Bool, returnedItems:[AnyObject]?, error: NSError?) in
if completed {
if let activityType = activityType {
if activityType == UIActivityTypeSaveToCameraRoll {
// フォトがカメラロールに保存した情報を伝えるビュー
let photoSavedToCameraRollToastView = POImageViewerPhotoSavedToCameraRollToastView()
photoSavedToCameraRollToastView.center = CUHelper.centerPointOf(self.topView)
self.topView.addSubview(photoSavedToCameraRollToastView)
photoSavedToCameraRollToastView.display()
}
}
}
}
topViewController.presentViewController(activityVC, animated: true, completion: nil)
}
}
}
/**
オーバーレイボタンのセットアップ。
*/
private func setupOverlayButton() {
overlayButton.layer.anchorPoint = CGPointZero
overlayButton.buttonAction = {
if self.imageViewerModeEnabled { self.displayImageViewer() }
if let action = self.overlayButtonAction { action() }
}
overlayButton.buttonPressBeganEventCallback = {
if let callback = self.overlayButtonPressBeganEventCallback { callback() }
}
overlayButton.buttonPressEndedEventCallback = {
if let callback = self.overlayButtonPressEndedEventCallback { callback() }
}
}
/**
ジェスチャ認識のセットアップ。
*/
private func setupGestureRecognizers() {
// パンジェスチャ
pan = UIPanGestureRecognizer(target: self, action: #selector(POImageViewerLinkedImageView.panGesture(_:)))
pan.maximumNumberOfTouches = 1
pan.delegate = self
imageViewerScrollView.addGestureRecognizer(pan)
// シングルタップジェスチャ
singleTap = UITapGestureRecognizer(target: self, action: #selector(POImageViewerLinkedImageView.singleTapGesture(_:)))
singleTap.numberOfTapsRequired = 1
singleTap.numberOfTouchesRequired = 1
singleTap.delegate = self
imageViewerScrollView.addGestureRecognizer(singleTap)
// ダブルタップジェスチャ
doubleTap = UITapGestureRecognizer(target: self, action: #selector(POImageViewerLinkedImageView.doubleTapGesture(_:)))
doubleTap.numberOfTapsRequired = 2
doubleTap.numberOfTouchesRequired = 1
doubleTap.delegate = self
imageViewerScrollView.addGestureRecognizer(doubleTap)
}
/**
イメージビューアを隠す。
*/
private func hideImageViewer() {
guard let parentView = parentView else { return }
executingImageViewerTransitionAnimation = true
imageViewerIsDisplaying = false
hideButtons()
// アニメーションするためのイメージビュー
let newAspectRatio = self.bounds.width / self.bounds.height,
imageViewAspectRatio = imageView.bounds.width / imageView.bounds.height,
newSize = (imageViewAspectRatio <= 1)
? CGSizeMake(imageView.bounds.height * newAspectRatio, imageView.bounds.height)
: CGSizeMake(imageView.bounds.width, imageView.bounds.width / newAspectRatio)
transitionImageView.bounds.size = newSize
transitionImageView.image = imageView.image
transitionImageView.center = imageView.center
topView.addSubview(transitionImageView)
// アニメーション前の準備
imageView.hidden = true
// 隠すアニメーション
let newOrigin = parentView.convertPoint(self.frame.origin, toView: topView),
newBounds = parentView.convertRect(self.bounds, toView: topView),
newCenter = CGPointMake(newOrigin.x + (newBounds.width / 2), newOrigin.y + (newBounds.height / 2)),
newScale = newBounds.width / transitionImageView.bounds.width
CUHelper.animateKeyframes(
POConstants.ImageViewerHideAnimationDuration,
animations: {
UIView.addKeyframeWithRelativeStartTime(0.94, relativeDuration: 0.06) {
self.transitionImageView.alpha = 0.5
}
UIView.addKeyframeWithRelativeStartTime(0.92, relativeDuration: 0.08) {
self.alpha = 1.0
}
UIView.addKeyframeWithRelativeStartTime(0.0, relativeDuration: 1.0) {
self.imageViewerScrollView.backgroundColor = UIColor.fromHexa(0xFFFFFF, alpha: 0)
self.transitionImageView.transform = CGAffineTransformMakeScale(newScale, newScale)
self.transitionImageView.layer.cornerRadius = POConstants.HomeTableViewCellPhotoCornerRadius
self.transitionImageView.center = newCenter
}
}
) { _ in
CUHelper.animate(
POConstants.ImageViewerHideAnimationDuration / 20,
animations: { self.transitionImageView.alpha = 0.0 }
) { _ in
// 確認とクリーンアップ
if self.transitionImageView.center == newCenter {
self.executeCleanupForImageViewerHideSequence(); return
}
CUHelper.animate(
POConstants.ImageViewerHideAnimationDuration,
animations: { self.transitionImageView.center = newCenter }
) { _ in self.executeCleanupForImageViewerHideSequence() }
}
}
}
/**
パンジェスチャが開始したためビューの更新。
- parameter currentCoordinate: 現在のジェスチャ座標
*/
private func updateViewForPanGestureStart(currentCoordinate: CGPoint) {
panGestureStartCoordinate = currentCoordinate
executingSwipeToHideAnimation = imageViewerScrollView.zoomScale == 1
if executingSwipeToHideAnimation {
hideButtons()
imageViewerScrollView.maximumZoomScale = imageViewerScrollView.minimumZoomScale
} else {
imageViewerScrollView.maximumZoomScale = POConstants.ImageViewerScrollViewMaximumZoomLevel
}
}
/**
パンジェスチャが終了したためビューの更新。
- parameter sender: パンジェスチャ
- parameter currentCoordinate: 現在のジェスチャ座標
*/
private func updateViewForPanGestureEnd(sender: UIPanGestureRecognizer, currentCoordinate: CGPoint) {
if imageViewerScrollView.zoomScale > 1 { return }
let horizontalSquaredTerm = pow(Double(panGestureStartCoordinate.x - currentCoordinate.x), Double(2)),
verticalSquaredTerm = pow(Double(panGestureStartCoordinate.y - currentCoordinate.y), Double(2)),
distanceMoved = CGFloat(pow(Double(horizontalSquaredTerm + verticalSquaredTerm), Double(0.5))),
velocity = sender.velocityInView(imageViewerScrollView),
minimumVelocityAttained = abs(velocity.x) > POConstants.ImageViewerMinimumVelocitySwipeRequiredToHide
|| abs(velocity.y) > POConstants.ImageViewerMinimumVelocitySwipeRequiredToHide
if minimumVelocityAttained && (distanceMoved > POConstants.ImageViewerMinimumDistanceSwipeRequiredToHide) {
hideImageViewer()
} else if distanceMoved > POConstants.ImageViewerMinimumDistanceRequiredToHide {
hideImageViewer()
} else { // イメージビューアを隠すアニメーションがキャンセルされた場合
CUHelper.animate(
POConstants.ImageViewerHideAnimationCancelledAnimationDuration,
options: .CurveEaseOut,
animations: { self.imageViewerScrollView.backgroundColor = UIColor.fromHexa(0xFFFFFF, alpha: POConstants.ImageViewerScrollViewBackgroundMaxAlpha) }
)
CUHelper.animateWithSpringBehavior(
POConstants.ImageViewerHideAnimationCancelledAnimationDuration,
usingSpringWithDamping: 0.3,
initialSpringVelocity: 0.2,
animations: {
self.imageView.center = CUHelper.centerPointOf(self.imageViewerScrollView)
self.imageView.layer.cornerRadius = 0
}
) { _ in
self.imageViewerScrollView.maximumZoomScale = POConstants.ImageViewerScrollViewMaximumZoomLevel
self.displayButtons()
}
}
executingSwipeToHideAnimation = false
}
/**
パンジェスチャが変更したためビューの更新。
- parameter currentCoordinate: 現在のジェスチャ座標
*/
private func updateViewForPanGestureChange(currentCoordinate: CGPoint) {
let pulledHorizontalDistance = panGestureStartCoordinate.x - currentCoordinate.x,
pulledVerticalDistance = panGestureStartCoordinate.y - currentCoordinate.y,
horizontalSquaredTerm = pow(Double(pulledHorizontalDistance), Double(2)),
verticalSquaredTerm = pow(Double(pulledVerticalDistance), Double(2)),
distanceMoved = CGFloat(pow(Double(horizontalSquaredTerm + verticalSquaredTerm), Double(0.5))),
scrollViewAlpha = max(1 - (distanceMoved / POConstants.ImageViewerMinimumDistanceRequiredToHide), 0) * POConstants.ImageViewerScrollViewBackgroundMaxAlpha,
imageViewCornerRadius = max((distanceMoved / POConstants.ImageViewerMinimumDistanceRequiredToHide), 0) * POConstants.HomeTableViewCellPhotoCornerRadius
imageViewerScrollView.backgroundColor = UIColor.fromHexa(0xFFFFFF, alpha: scrollViewAlpha)
imageView.layer.cornerRadius = imageViewCornerRadius
imageView.center = CGPointMake(
imageViewerScrollView.bounds.width / 2 - pulledHorizontalDistance,
imageViewerScrollView.bounds.height / 2 - pulledVerticalDistance
)
}
/**
ダブルタップジェスチャズームインアニメーション。
- parameter sender: ダブルタップジェスチャ
*/
private func updateViewForDoubleTapGestureZoomIn(sender: UITapGestureRecognizer) {
let currentCoordinate = sender.locationInView(imageView),
thirdOfViewWidth = imageView.bounds.width / 3,
thirdOfViewHeight = imageView.bounds.height / 3,
imageViewWidthAtMaximumZoomLevel = imageView.bounds.width * POConstants.ImageViewerScrollViewMaximumZoomLevel,
imageViewHeightAtMaximumZoomLevel = imageView.bounds.height * POConstants.ImageViewerScrollViewMaximumZoomLevel,
middleSegmentContentOffsetX = max((imageViewWidthAtMaximumZoomLevel - imageViewerScrollView.bounds.width) / 2, 0),
rightSegmentContentOffsetX = max(imageViewWidthAtMaximumZoomLevel - imageViewerScrollView.bounds.width, 0),
middleSegmentContentOffsetY = max((imageViewHeightAtMaximumZoomLevel - imageViewerScrollView.bounds.height) / 2, 0),
bottomSegmentContentOffsetY = max(imageViewHeightAtMaximumZoomLevel - imageViewerScrollView.bounds.height, 0)
var newContentOffset = CGPointZero
if currentCoordinate.x <= thirdOfViewWidth && currentCoordinate.y <= thirdOfViewHeight
{ // top-left segment
newContentOffset = CGPointZero
} else if currentCoordinate.x > thirdOfViewWidth
&& currentCoordinate.x <= 2*thirdOfViewWidth
&& currentCoordinate.y <= thirdOfViewHeight
{ // top-middle segment
newContentOffset = CGPointMake(middleSegmentContentOffsetX, 0)
} else if currentCoordinate.x > 2 * thirdOfViewWidth
&& currentCoordinate.y <= thirdOfViewHeight
{ // top-right segment
newContentOffset = CGPointMake(rightSegmentContentOffsetX, 0)
} else if currentCoordinate.x <= thirdOfViewWidth
&& currentCoordinate.y > thirdOfViewHeight
&& currentCoordinate.y <= 2*thirdOfViewHeight
{ // middle-left segment
newContentOffset = CGPointMake(0, middleSegmentContentOffsetY)
} else if currentCoordinate.x > thirdOfViewWidth
&& currentCoordinate.x <= 2*thirdOfViewWidth
&& currentCoordinate.y > thirdOfViewHeight
&& currentCoordinate.y <= 2*thirdOfViewHeight
{ // middle-middle segment
newContentOffset = CGPointMake(middleSegmentContentOffsetX, middleSegmentContentOffsetY)
} else if currentCoordinate.x > 2*thirdOfViewWidth
&& currentCoordinate.y > thirdOfViewHeight
&& currentCoordinate.y < 2*thirdOfViewHeight
{ // middle-right segment
newContentOffset = CGPointMake(rightSegmentContentOffsetX, middleSegmentContentOffsetY)
} else if currentCoordinate.x <= thirdOfViewWidth
&& currentCoordinate.y > 2*thirdOfViewHeight
{ // bottom-left segment
newContentOffset = CGPointMake(0, bottomSegmentContentOffsetY)
} else if currentCoordinate.x > thirdOfViewWidth
&& currentCoordinate.x <= 2*thirdOfViewWidth
&& currentCoordinate.y > 2*thirdOfViewHeight
{ // bottom-middle segment
newContentOffset = CGPointMake(middleSegmentContentOffsetX, bottomSegmentContentOffsetY)
} else if currentCoordinate.x > 2*thirdOfViewWidth
&& currentCoordinate.y > 2*thirdOfViewHeight
{ // bottom-right segment
newContentOffset = CGPointMake(rightSegmentContentOffsetX, bottomSegmentContentOffsetY)
}
CUHelper.animate(
POConstants.ImageViewerDoubleTapZoomAnimationDuration,
options: .CurveEaseOut,
animations: {
self.imageViewerScrollView.zoomScale = POConstants.ImageViewerScrollViewMaximumZoomLevel
self.imageViewerScrollView.contentOffset = newContentOffset
}
) { _ in
if self.buttonsDisplaying {
self.hideButtons()
}
if !self.shareButtonImageView.hidden {
}
}
}
/**
ダブルタップジェスチャズームアウトアニメーション。
*/
private func updateViewForDoubleTapGestureZoomOut() {
let currentContentOffset = imageViewerScrollView.contentOffset
if imageViewerScrollView.contentOffset == CGPointZero {
imageViewerScrollView.contentOffset = CGPointMake(1, 1) // contentOffsetが(0,0)の場合にちゃんとセンターしないバグの
}
if currentContentOffset.x >= 0 && currentContentOffset.y >= 0 {
executeDoubleTapZoomOutAnimation()
} else {
let newContentOffset = CGPointMake(max(currentContentOffset.x, 1), max(currentContentOffset.y, 1))
UIView.animateWithDuration(0.1) { self.imageViewerScrollView.contentOffset = newContentOffset }
CUHelper.executeOnMainThreadAfter(0.1) { self.executeDoubleTapZoomOutAnimation() }
}
}
/**
ダブルタップのズームアウトアニメーション。
*/
private func executeDoubleTapZoomOutAnimation() {
let newCenter = centerPointNeededToCenterImageViewInImageViewerScrollView()
CUHelper.animate(
POConstants.ImageViewerDoubleTapZoomAnimationDuration,
options: .CurveEaseOut,
animations: {
self.imageView.center = newCenter
self.imageViewerScrollView.zoomScale = POConstants.ImageViewerScrollViewMinimumZoomLevel + 0.001
}
) { _ in
CUHelper.executeOnMainThreadAfter(0.1) {
self.imageViewerScrollView.zoomScale = POConstants.ImageViewerScrollViewMinimumZoomLevel
}
}
}
// MARK: - Helper Functions
/**
ビューのボタンを表示。
*/
private func displayButtons() {
buttonsDisplaying = true
backButtonContainerView.hidden = false
backButtonOverlayButton.hidden = false
shareButtonImageView.hidden = false
shareButtonOverlayButton.hidden = false
authorNameView.display()
CUHelper.animate(
POConstants.ImageViewerButtonAnimationDuration,
options: .CurveEaseOut,
animations: {
self.backButtonContainerView.transform = POConstants.ImageViewerButtonDefaultScaleTransform
self.shareButtonImageView.transform = POConstants.ImageViewerButtonDefaultScaleTransform
}
)
}
/**
ビューのボタンを隠す。
*/
private func hideButtons() {
buttonsDisplaying = false
backButtonOverlayButton.hidden = true
shareButtonOverlayButton.hidden = true
authorNameView.hide()
CUHelper.animate(
POConstants.ImageViewerButtonAnimationDuration,
options: .CurveEaseOut,
animations: {
self.backButtonContainerView.transform = POConstants.ImageViewerButtonHiddenScaleTransform
self.shareButtonImageView.transform = POConstants.ImageViewerButtonHiddenScaleTransform
}
) { _ in
self.backButtonContainerView.hidden = true
self.shareButtonImageView.hidden = true
}
}
/**
イメージビューアディスプレイする時のセンタリングアニメーションを実行。
- parameter completion: コールバック
*/
private func executeCenteringAnimationForImageViewerDisplaySequence(completion: (() -> Void)? = nil) {
CUHelper.animate(
POConstants.ImageViewerDisplayAnimationDuration,
animations: {
self.transitionImageView.center = CUHelper.centerPointOf(self.imageViewerScrollView)
}
) { _ in if let complete = completion { complete() } }
}
/**
イメージビューアディスプレイする時のクリーンアップを実行。
*/
private func executeCleanupForImageViewerDisplaySequence() {
displayHintsIfNecessary()
CUHelper.executeOnMainThreadAfter(POConstants.ImageViewerDisplaySequenceBackButtonAnimationDelay) {
if self.imageViewerIsDisplaying
&& self.imageViewerScrollView.zoomScale == POConstants.ImageViewerScrollViewMinimumZoomLevel
&& !self.executingSwipeToHideAnimation
{
self.displayButtons()
}
}
imageView.hidden = false
transitionImageView.removeFromSuperview()
executingImageViewerTransitionAnimation = false
}
/**
イメージビュー隠す時のクリーンアップを実行。
*/
private func executeCleanupForImageViewerHideSequence() {
imageViewerScrollView.removeFromSuperview()
transitionImageView.removeFromSuperview()
backButtonContainerView.removeFromSuperview()
backButtonOverlayButton.removeFromSuperview()
authorNameView.removeFromSuperview()
imageViewerScrollView.center = CUHelper.centerPointOf(self.imageViewerScrollView)
self.hidden = false
UIApplication.sharedApplication().setStatusBarHidden(false, withAnimation: .Slide)
executingImageViewerTransitionAnimation = false
}
/**
イメージビューを親スクロールビューにセンターするため必要なイメージビューのセンターポイントをゲット。
- returns: イメージビューを親スクロールビューにセンターするため必要なイメージビューのセンターポイント
*/
private func centerPointNeededToCenterImageViewInImageViewerScrollView() -> CGPoint {
let offsetX = max((imageViewerScrollView.bounds.size.width - imageViewerScrollView.contentSize.width) / 2, 0),
offsetY = max((imageViewerScrollView.bounds.size.height - imageViewerScrollView.contentSize.height) / 2, 0)
return CGPointMake(
offsetX + (imageViewerScrollView.contentSize.width / 2),
offsetY + (imageViewerScrollView.contentSize.height / 2)
)
}
/**
最初イメージビューアーを表示する時にヒントを表示する。
*/
private func displayHintsIfNecessary() {
if !NSUserDefaults.standardUserDefaults().boolForKey(POStrings.ImageViewerZoomHintShownUserDefaultsKey) {
let zoomHintToastView = POImageViewerZoomHintToastView()
zoomHintToastView.center = CUHelper.centerPointOf(topView)
topView.addSubview(zoomHintToastView)
zoomHintToastView.displayHint()
NSUserDefaults.standardUserDefaults().setBool(true, forKey: POStrings.ImageViewerZoomHintShownUserDefaultsKey)
} else if !NSUserDefaults.standardUserDefaults().boolForKey(POStrings.ImageViewerSwipeGestureHintShownUserDefaultsKey) {
let swipeToHideHintToastView = POImageViewerSwipeToHideHintToastView()
swipeToHideHintToastView.center = CUHelper.centerPointOf(topView)
topView.addSubview(swipeToHideHintToastView)
swipeToHideHintToastView.displayHint()
NSUserDefaults.standardUserDefaults().setBool(true, forKey: POStrings.ImageViewerSwipeGestureHintShownUserDefaultsKey)
}
}
}
extension POImageViewerLinkedImageView: UIGestureRecognizerDelegate {
func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWithGestureRecognizer otherGestureRecognizer: UIGestureRecognizer) -> Bool {
return true
}
func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldRequireFailureOfGestureRecognizer otherGestureRecognizer: UIGestureRecognizer) -> Bool {
if ((gestureRecognizer == singleTap && otherGestureRecognizer == doubleTap) ||
(gestureRecognizer == singleTap && otherGestureRecognizer == pan)) &&
(self.imageView.bounds.contains(gestureRecognizer.locationInView(imageView)) ||
self.imageView.bounds.contains(otherGestureRecognizer.locationInView(imageView))
)
{
return true
}
return false
}
}
extension POImageViewerLinkedImageView: UIScrollViewDelegate {
func viewForZoomingInScrollView(scrollView: UIScrollView) -> UIView? {
return imageView
}
func scrollViewDidScroll(scrollView: UIScrollView) {
imageView.center = centerPointNeededToCenterImageViewInImageViewerScrollView()
}
func scrollViewDidZoom(scrollView: UIScrollView) {
if scrollView.zoomScale == POConstants.ImageViewerScrollViewMinimumZoomLevel {
displayButtons()
} else {
hideButtons()
}
}
func scrollViewDidEndZooming(scrollView: UIScrollView, withView view: UIView?, atScale scale: CGFloat) {
if scrollView.zoomScale == POConstants.ImageViewerScrollViewMinimumZoomLevel {
if !buttonsDisplaying {
displayButtons()
}
if imageView.center != imageCenterAtMinimumZoom {
UIView.animateWithDuration(POConstants.ImageViewerCenteringMisalignedImageAnimationDuration) {
self.imageView.center = self.imageCenterAtMinimumZoom
}
}
}
}
}
| 119673d6b91e618e9155e6d32f0799a3 | 42.137813 | 172 | 0.660172 | false | false | false | false |
VernonVan/SmartClass | refs/heads/master | SmartClass/Quiz/View/QuizListViewController.swift | mit | 1 | //
// QuizListViewController.swift
// SmartClass
//
// Created by Vernon on 16/9/14.
// Copyright © 2016年 Vernon. All rights reserved.
//
import UIKit
import RealmSwift
import DZNEmptyDataSet
class QuizListViewController: UIViewController
{
@IBOutlet weak var tableView: UITableView!
var fromDate: Date!
var toDate: Date!
var quizs: Results<Quiz>!
override func viewDidLoad()
{
super.viewDidLoad()
let realm = try! Realm()
quizs = realm.objects(Quiz.self).filter("date BETWEEN {%@, %@}", fromDate, toDate)
// try! realm.write {
// let quiz1 = Quiz(value: ["content": "第一题怎么做", "name": "卢建晖", "date": NSDate()])
// realm.add(quiz1)
// let quiz2 = Quiz(value: ["content": "为什么1+1=2", "name": "刘德华", "date": NSDate()])
// realm.add(quiz2)
// let quiz3 = Quiz(value: ["content": "为什么1+1=2", "name": "卢建晖", "date": NSDate(timeIntervalSince1970: 10000000)])
// realm.add(quiz3)
// }
tableView.dataSource = self
tableView.delegate = self
tableView.separatorStyle = .none
tableView.backgroundColor = UIColor(netHex: 0xeeeeee)
tableView.emptyDataSetSource = self
navigationItem.backBarButtonItem = UIBarButtonItem(title:"", style:.plain, target:nil, action:nil)
}
}
extension QuizListViewController: UITableViewDataSource, UITableViewDelegate
{
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return quizs.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
let cell = tableView.dequeueReusableCell(withIdentifier: "QuizCell", for: indexPath) as! QuizCell
cell.configureWithQuiz(quizs[(indexPath as NSIndexPath).row])
return cell
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat
{
return QuizCell.cellHeight
}
}
extension QuizListViewController: DZNEmptyDataSetSource
{
func image(forEmptyDataSet scrollView: UIScrollView!) -> UIImage!
{
return UIImage(named: "emptyQuiz")
}
func title(forEmptyDataSet scrollView: UIScrollView!) -> NSAttributedString!
{
let text = NSLocalizedString("本节课暂无学生提问", comment: "")
let attributes = [NSFontAttributeName: UIFont.boldSystemFont(ofSize: 16.0),
NSForegroundColorAttributeName: UIColor.darkGray]
return NSAttributedString(string: text, attributes: attributes)
}
}
| 8d2f1b0d1bac727cbbdbc7a432edfecd | 29.988235 | 126 | 0.642369 | false | false | false | false |
VirgilSecurity/VirgilCryptoiOS | refs/heads/master | Source/VirgilCrypto/VirgilCrypto+AuthEncrypt.swift | bsd-3-clause | 2 | //
// Copyright (C) 2015-2019 Virgil Security Inc.
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// (1) Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// (2) Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in
// the documentation and/or other materials provided with the
// distribution.
//
// (3) Neither the name of the copyright holder nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE AUTHOR ''AS IS'' AND ANY EXPRESS OR
// IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT,
// INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
// IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//
// Lead Maintainer: Virgil Security Inc. <[email protected]>
//
import Foundation
import VirgilCryptoFoundation
extension VirgilCrypto {
/// Signs (with private key) Then Encrypts data (and signature) for passed PublicKeys
///
/// 1. Generates signature depending on KeyType
/// 2. Generates random AES-256 KEY1
/// 3. Encrypts data with KEY1 using AES-256-GCM and generates signature
/// 4. Encrypts signature with KEY1 using AES-256-GCM
/// 5. Generates ephemeral key pair for each recipient
/// 6. Uses Diffie-Hellman to obtain shared secret with each recipient's public key & each ephemeral private key
/// 7. Computes KDF to obtain AES-256 key from shared secret for each recipient
/// 8. Encrypts KEY1 with this key using AES-256-CBC for each recipient
///
/// - Parameters:
/// - data: Data to be signedThenEncrypted
/// - privateKey: Sender private key
/// - recipients: Recipients' public keys
/// - enablePadding: If true, will add padding to plain text before encryption.
/// This is recommended for data for which exposing length can
/// cause security issues (e.g. text messages)
/// - Returns: SignedThenEncrypted data
/// - Throws: Rethrows from `RecipientCipher`.
@objc open func authEncrypt(_ data: Data, with privateKey: VirgilPrivateKey,
for recipients: [VirgilPublicKey], enablePadding: Bool = true) throws -> Data {
return try self.encrypt(inputOutput: .data(input: data),
signingOptions: SigningOptions(privateKey: privateKey, mode: .signThenEncrypt),
recipients: recipients,
enablePadding: enablePadding)!
}
/// Decrypts (with private key) data and signature and Verifies signature using any of signers' PublicKeys
///
/// 1. Uses Diffie-Hellman to obtain shared secret with sender ephemeral public key & recipient's private key
/// 2. Computes KDF to obtain AES-256 KEY2 from shared secret
/// 3. Decrypts KEY1 using AES-256-CBC
/// 4. Decrypts data and signature using KEY1 and AES-256-GCM
/// 5. Finds corresponding PublicKey according to signer id inside data
/// 6. Verifies signature
///
/// - Parameters:
/// - data: Signed Then Encrypted data
/// - privateKey: Receiver's private key
/// - signersPublicKeys: Array of possible signers public keys.
/// WARNING: Data should have signature of ANY public key from array.
/// - Returns: DecryptedThenVerified data
/// - Throws: Rethrows from `RecipientCipher`.
@objc open func authDecrypt(_ data: Data, with privateKey: VirgilPrivateKey,
usingOneOf signersPublicKeys: [VirgilPublicKey]) throws -> Data {
return try self.authDecrypt(data,
with: privateKey,
usingOneOf: signersPublicKeys,
allowNotEncryptedSignature: false)
}
/// Decrypts (with private key) data and signature and Verifies signature using any of signers' PublicKeys
///
/// 1. Uses Diffie-Hellman to obtain shared secret with sender ephemeral public key & recipient's private key
/// 2. Computes KDF to obtain AES-256 KEY2 from shared secret
/// 3. Decrypts KEY1 using AES-256-CBC
/// 4. Decrypts data and signature using KEY1 and AES-256-GCM
/// 5. Finds corresponding PublicKey according to signer id inside data
/// 6. Verifies signature
///
/// - Parameters:
/// - data: Signed Then Encrypted data
/// - privateKey: Receiver's private key
/// - signersPublicKeys: Array of possible signers public keys.
/// WARNING: Data should have signature of ANY public key from array.
/// - allowNotEncryptedSignature: Allows storing signature in plain text
/// for compatibility with deprecated signAndEncrypt
/// - Returns: DecryptedThenVerified data
/// - Throws: Rethrows from `RecipientCipher`.
@objc open func authDecrypt(_ data: Data, with privateKey: VirgilPrivateKey,
usingOneOf signersPublicKeys: [VirgilPublicKey],
allowNotEncryptedSignature: Bool) throws -> Data {
let verifyMode: VerifyingMode = allowNotEncryptedSignature ? .any : .decryptThenVerify
return try self.decrypt(inputOutput: .data(input: data),
verifyingOptions: VerifyingOptions(publicKeys: signersPublicKeys,
mode: verifyMode),
privateKey: privateKey)!
}
/// Signs (with private key) Then Encrypts stream (and signature) for passed PublicKeys
///
/// 1. Generates signature depending on KeyType
/// 2. Generates random AES-256 KEY1
/// 3. Encrypts data with KEY1 using AES-256-GCM and generates signature
/// 4. Encrypts signature with KEY1 using AES-256-GCM
/// 5. Generates ephemeral key pair for each recipient
/// 6. Uses Diffie-Hellman to obtain shared secret with each recipient's public key & each ephemeral private key
/// 7. Computes KDF to obtain AES-256 key from shared secret for each recipient
/// 8. Encrypts KEY1 with this key using AES-256-CBC for each recipient
///
/// - Parameters:
/// - stream: Input stream
/// - streamSize: Input stream size
/// - outputStream: Output stream
/// - privateKey: Private key to generate signatures
/// - recipients: Recipients public keys
/// - enablePadding: If true, will add padding to plain text before encryption.
/// This is recommended for data for which exposing length can
/// cause security issues (e.g. text messages)
/// - Throws: Rethrows from `RecipientCipher`.
@objc open func authEncrypt(_ stream: InputStream,
streamSize: Int,
to outputStream: OutputStream,
with privateKey: VirgilPrivateKey,
for recipients: [VirgilPublicKey],
enablePadding: Bool = false) throws {
_ = try self.encrypt(inputOutput: .stream(input: stream, streamSize: streamSize, output: outputStream),
signingOptions: SigningOptions(privateKey: privateKey, mode: .signThenEncrypt),
recipients: recipients,
enablePadding: enablePadding)
}
/// Decrypts (using passed PrivateKey) then verifies (using one of public keys) stream
///
/// - Note: Decrypted stream should not be used until decryption
/// of whole InputStream completed due to security reasons
///
/// 1. Uses Diffie-Hellman to obtain shared secret with sender ephemeral public key & recipient's private key
/// 2. Computes KDF to obtain AES-256 KEY2 from shared secret
/// 3. Decrypts KEY1 using AES-256-CBC
/// 4. Decrypts data and signature using KEY1 and AES-256-GCM
/// 5. Finds corresponding PublicKey according to signer id inside data
/// 6. Verifies signature
///
/// - Parameters:
/// - stream: Stream with encrypted data
/// - outputStream: Stream with decrypted data
/// - privateKey: Recipient's private key
/// - signersPublicKeys: Array of possible signers public keys.
/// WARNING: Stream should have signature of ANY public key from array.
/// - Throws: Rethrows from `RecipientCipher`.
@objc open func authDecrypt(_ stream: InputStream, to outputStream: OutputStream,
with privateKey: VirgilPrivateKey,
usingOneOf signersPublicKeys: [VirgilPublicKey]) throws {
_ = try self.decrypt(inputOutput: .stream(input: stream, streamSize: nil, output: outputStream),
verifyingOptions: VerifyingOptions(publicKeys: signersPublicKeys,
mode: .decryptThenVerify),
privateKey: privateKey)
}
}
| 4355fa16a6e204c5c6c9c3045059bef4 | 54.165746 | 116 | 0.636855 | false | false | false | false |
FolioReader/FolioReaderKit | refs/heads/master | Example/FolioReaderTests/FolioReaderTests.swift | bsd-3-clause | 2 | //
// FolioReaderTests.swift
// FolioReaderTests
//
// Created by Brandon Kobilansky on 1/25/16.
// Copyright © 2016 FolioReader. All rights reserved.
//
@testable import FolioReaderKit
import Quick
import Nimble
class FolioReaderTests: QuickSpec {
override func spec() {
context("epub parsing") {
var subject: FREpubParser!
var epubPath: String!
beforeEach {
guard let path = Bundle.main.path(forResource: "The Silver Chair", ofType: "epub") else {
fail("Could not read the epub file")
return
}
subject = FREpubParser()
epubPath = path
do {
let book = try subject.readEpub(epubPath: epubPath)
print(book.tableOfContents.first!.title)
} catch {
fail("Error: \(error.localizedDescription)")
}
}
it("flat table of contents") {
expect(subject.flatTOC.count).to(equal(17))
}
it("parses table of contents") {
expect(subject.book.tableOfContents.count).to(equal(17))
}
it("parses cover image") {
guard let coverImage = subject.book.coverImage, let fromFileImage = UIImage(contentsOfFile: coverImage.fullHref) else {
fail("Could not read the cover image")
return
}
do {
let parsedImage = try subject.parseCoverImage(epubPath)
let data1 = parsedImage.pngData()
let data2 = fromFileImage.pngData()
expect(data1).to(equal(data2))
} catch {
fail("Error: \(error.localizedDescription)")
}
}
it("parses book title") {
do {
let title = try subject.parseTitle(epubPath)
expect(title).to(equal("The Silver Chair"))
} catch {
fail("Error: \(error.localizedDescription)")
}
}
it("parses author name") {
do {
let name = try subject.parseAuthorName(epubPath)
expect(name).to(equal("C. S. Lewis"))
} catch {
fail("Error: \(error.localizedDescription)")
}
}
}
}
}
| c112b5c82c31ee62ad92fa0419c45db3 | 30.625 | 135 | 0.477866 | false | false | false | false |
MaartenBrijker/project | refs/heads/back | AudioKit/iOS/AudioKit/AudioKit.playground/Pages/AutoPan Operation.xcplaygroundpage/Contents.swift | apache-2.0 | 2 | //: [TOC](Table%20Of%20Contents) | [Previous](@previous) | [Next](@next)
//:
//: ---
//:
//: ## AutoPan Operation
//:
import XCPlayground
import AudioKit
//: This first section sets up parameter naming in such a way to make the operation code easier to read below.
enum AutoPanParameter: Int {
case Speed, Depth
}
struct AutoPan {
static var speed: AKOperation {
return AKOperation.parameters(AutoPanParameter.Speed.rawValue)
}
static var depth: AKOperation {
return AKOperation.parameters(AutoPanParameter.Depth.rawValue)
}
}
extension AKOperationEffect {
var speed: Double {
get { return self.parameters[AutoPanParameter.Speed.rawValue] }
set(newValue) { self.parameters[AutoPanParameter.Speed.rawValue] = newValue }
}
var depth: Double {
get { return self.parameters[AutoPanParameter.Depth.rawValue] }
set(newValue) { self.parameters[AutoPanParameter.Depth.rawValue] = newValue }
}
}
//: Here we'll use the struct and the extension to refer to the autopan parameters by name
let bundle = NSBundle.mainBundle()
let file = bundle.pathForResource("guitarloop", ofType: "wav")
var player = AKAudioPlayer(file!)
player.looping = true
let oscillator = AKOperation.sineWave(frequency: AutoPan.speed, amplitude: AutoPan.depth)
let panner = AKOperation.input.pan(oscillator)
let effect = AKOperationEffect(player, stereoOperation: panner)
effect.parameters = [10, 1]
AudioKit.output = effect
AudioKit.start()
let playgroundWidth = 500
class PlaygroundView: AKPlaygroundView {
var speedLabel: Label?
var depthLabel: Label?
override func setup() {
addTitle("AutoPan")
addLabel("Audio Playback")
addButton("Start", action: #selector(start))
addButton("Stop", action: #selector(stop))
speedLabel = addLabel("Speed: \(effect.speed)")
addSlider(#selector(setSpeed), value: effect.speed, minimum: 0.1, maximum: 25)
depthLabel = addLabel("Depth: \(effect.depth)")
addSlider(#selector(setDepth), value: effect.depth)
}
func start() {
player.play()
}
func stop() {
player.stop()
}
func setSpeed(slider: Slider) {
effect.speed = Double(slider.value)
speedLabel!.text = "Speed: \(String(format: "%0.3f", effect.speed))"
}
func setDepth(slider: Slider) {
effect.depth = Double(slider.value)
depthLabel!.text = "Depth: \(String(format: "%0.3f", effect.depth))"
}
}
let view = PlaygroundView(frame: CGRect(x: 0, y: 0, width: playgroundWidth, height: 650))
XCPlaygroundPage.currentPage.needsIndefiniteExecution = true
XCPlaygroundPage.currentPage.liveView = view
//: [TOC](Table%20Of%20Contents) | [Previous](@previous) | [Next](@next)
| c4d260f143c2a258e7c6c828f98c9f68 | 28.819149 | 110 | 0.674634 | false | false | false | false |
bmichotte/HSTracker | refs/heads/master | HSTracker/UIs/Trackers/FloatingCard.swift | mit | 1 | //
// FloatingCard.swift
// HSTracker
//
// Created by Benjamin Michotte on 7/04/16.
// Copyright © 2016 Benjamin Michotte. All rights reserved.
//
import Foundation
import TextAttributes
import CleanroomLogger
enum FloatingCardStyle: String {
case text
case image
}
class FloatingCard: OverWindowController {
@IBOutlet weak var title: NSTextField!
@IBOutlet weak var scrollview: NSScrollView!
@IBOutlet weak var imageView: NSImageView!
// for reference http://stackoverflow.com/questions/24062437
var text: NSTextView? {
if let scrollview = self.scrollview {
return scrollview.contentView.documentView as? NSTextView
}
return nil
}
var card: Card?
private var drawChanceTop: Float = 0
private var drawChanceTop2: Float = 0
let attributes: TextAttributes = {
$0.font(NSFont(name: "Belwe Bd BT", size: 13))
.foregroundColor(.black)
.strokeColor(.black)
.alignment(.center)
return $0
}(TextAttributes())
let titleAttributes: TextAttributes = {
$0.font(NSFont(name: "Belwe Bd BT", size: 16))
.foregroundColor(.black)
.strokeColor(.black)
.alignment(.center)
return $0
}(TextAttributes())
func set(card: Card, drawChanceTop: Float, drawChanceTop2: Float) {
self.drawChanceTop = drawChanceTop
self.drawChanceTop2 = drawChanceTop2
self.card = card
reload()
}
func set(drawChanceTop: Float) {
self.drawChanceTop = drawChanceTop
reload()
}
func set(drawChanceTop2: Float) {
self.drawChanceTop2 = drawChanceTop2
reload()
}
private func reload() {
if Settings.useHearthstoneAssets && Settings.floatingCardStyle == .image {
reloadImage()
} else {
reloadText()
}
}
private func reloadImage() {
guard let card = self.card, let assetGenerator = CoreManager.assetGenerator else {
imageView.image = nil
reloadText()
return
}
title.isHidden = true
scrollview.isHidden = true
imageView.isHidden = false
assetGenerator.generate(card: card) { [weak self] (image, error) in
if let image = image {
self?.imageView.image = image
} else if let error = error {
Log.warning?.message("asset generation: \(error)")
}
}
}
private func reloadText() {
title.isHidden = false
scrollview.isHidden = false
imageView.isHidden = true
var information = ""
if let card = card, let title = self.title {
title.attributedStringValue = NSAttributedString(string: card.name,
attributes: titleAttributes)
if !card.text.isEmpty {
information = card.formattedText() + "\n\n"
}
}
if drawChanceTop > 0 {
information += NSLocalizedString("Top deck:", comment: "")
+ "\(String(format: " %.2f", drawChanceTop))%\n"
}
if drawChanceTop2 > 0 {
information += NSLocalizedString("In top 2:", comment: "")
+ "\(String(format: " %.2f", drawChanceTop2))%\n"
}
text?.string = ""
text?.textStorage?.append(NSAttributedString(string: information,
attributes: attributes))
// "pack frame"
if let window = self.window {
let layoutManager = NSLayoutManager()
let textStorage = NSTextStorage(attributedString:
NSAttributedString(string: information, attributes: attributes))
let flt_max = Float.greatestFiniteMagnitude
let textContainer = NSTextContainer(containerSize:
NSSize(width: window.frame.size.width, height: CGFloat(flt_max)))
layoutManager.addTextContainer(textContainer)
textStorage.addLayoutManager(layoutManager)
textContainer.lineFragmentPadding = 0.0
layoutManager.glyphRange(for: textContainer)
let textheight = layoutManager.usedRect(for: textContainer).size.height
self.window?.setContentSize(NSSize(width: window.frame.size.width,
height: self.title.frame.size.height +
textheight))
}
}
}
| dc259c40dc3bc803bf83e9dc033c0818 | 31.223776 | 89 | 0.571615 | false | false | false | false |
mukang/MKWeibo | refs/heads/master | MKWeibo/MKWeibo/Classes/UI/Profile/ProfileViewController.swift | mit | 1 | //
// ProfileViewController.swift
// MKWeibo
//
// Created by 穆康 on 15/3/13.
// Copyright (c) 2015年 穆康. All rights reserved.
//
import UIKit
class ProfileViewController: UITableViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Potentially incomplete method implementation.
// Return the number of sections.
return 0
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete method implementation.
// Return the number of rows in the section.
return 0
}
/*
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath) as! UITableViewCell
// Configure the cell...
return cell
}
*/
/*
// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return NO if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
// Delete the row from the data source
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return NO if you do not want the item to be re-orderable.
return true
}
*/
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
*/
}
| 24342b5d256691c50a3ec3e2597fc1ac | 33.030928 | 157 | 0.682823 | false | false | false | false |
brettg/Signal-iOS | refs/heads/master | Signal/src/call/PeerConnectionClient.swift | gpl-3.0 | 1 | //
// Copyright (c) 2017 Open Whisper Systems. All rights reserved.
//
import Foundation
import PromiseKit
import WebRTC
// HACK - Seeing crazy SEGFAULTs on iOS9 when accessing these objc externs.
// iOS10 seems unaffected. Reproducible for ~1 in 3 calls.
// Binding them to a file constant seems to work around the problem.
let kAudioTrackType = kRTCMediaStreamTrackKindAudio
let kVideoTrackType = kRTCMediaStreamTrackKindVideo
let kMediaConstraintsMinWidth = kRTCMediaConstraintsMinWidth
let kMediaConstraintsMaxWidth = kRTCMediaConstraintsMaxWidth
let kMediaConstraintsMinHeight = kRTCMediaConstraintsMinHeight
let kMediaConstraintsMaxHeight = kRTCMediaConstraintsMaxHeight
/**
* The PeerConnectionClient notifies it's delegate (the CallService) of key events in the call signaling life cycle
*
* The delegate's methods will always be called on the main thread.
*/
protocol PeerConnectionClientDelegate: class {
/**
* The connection has been established. The clients can now communicate.
*/
func peerConnectionClientIceConnected(_ peerconnectionClient: PeerConnectionClient)
/**
* The connection failed to establish. The clients will not be able to communicate.
*/
func peerConnectionClientIceFailed(_ peerconnectionClient: PeerConnectionClient)
/**
* During the Signaling process each client generates IceCandidates locally, which contain information about how to
* reach the local client via the internet. The delegate must shuttle these IceCandates to the other (remote) client
* out of band, as part of establishing a connection over WebRTC.
*/
func peerConnectionClient(_ peerconnectionClient: PeerConnectionClient, addedLocalIceCandidate iceCandidate: RTCIceCandidate)
/**
* Once the peerconnection is established, we can receive messages via the data channel, and notify the delegate.
*/
func peerConnectionClient(_ peerconnectionClient: PeerConnectionClient, received dataChannelMessage: OWSWebRTCProtosData)
/**
* Fired whenever the local video track become active or inactive.
*/
func peerConnectionClient(_ peerconnectionClient: PeerConnectionClient, didUpdateLocal videoTrack: RTCVideoTrack?)
/**
* Fired whenever the remote video track become active or inactive.
*/
func peerConnectionClient(_ peerconnectionClient: PeerConnectionClient, didUpdateRemote videoTrack: RTCVideoTrack?)
}
/**
* `PeerConnectionClient` is our interface to WebRTC.
*
* It is primarily a wrapper around `RTCPeerConnection`, which is responsible for sending and receiving our call data
* including audio, video, and some post-connected signaling (hangup, add video)
*/
class PeerConnectionClient: NSObject, RTCPeerConnectionDelegate, RTCDataChannelDelegate {
let TAG = "[PeerConnectionClient]"
enum Identifiers: String {
case mediaStream = "ARDAMS",
videoTrack = "ARDAMSv0",
audioTrack = "ARDAMSa0",
dataChannelSignaling = "signaling"
}
// A state in this class should only be accessed on this queue in order to
// serialize access.
//
// This queue is also used to perform expensive calls to the WebRTC API.
private static let signalingQueue = DispatchQueue(label: "CallServiceSignalingQueue")
// Delegate is notified of key events in the call lifecycle.
private weak var delegate: PeerConnectionClientDelegate!
func setDelegate(delegate: PeerConnectionClientDelegate?) {
PeerConnectionClient.signalingQueue.async {
self.delegate = delegate
}
}
// Connection
private var peerConnection: RTCPeerConnection!
private let iceServers: [RTCIceServer]
private let connectionConstraints: RTCMediaConstraints
private let configuration: RTCConfiguration
private let factory = RTCPeerConnectionFactory()
// DataChannel
private var dataChannel: RTCDataChannel?
// Audio
private var audioSender: RTCRtpSender?
private var audioTrack: RTCAudioTrack?
private var audioConstraints: RTCMediaConstraints
static private let sharedAudioSession = CallAudioSession()
// Video
private var videoCaptureSession: AVCaptureSession?
private var videoSender: RTCRtpSender?
private var localVideoTrack: RTCVideoTrack?
// RTCVideoTrack is fragile and prone to throwing exceptions and/or
// causing deadlock in its destructor. Therefore we take great care
// with this property.
//
// We synchronize access to this property and ensure that we never
// set or use a strong reference to the remote video track if
// peerConnection is nil.
private var remoteVideoTrack: RTCVideoTrack?
private var cameraConstraints: RTCMediaConstraints
init(iceServers: [RTCIceServer], delegate: PeerConnectionClientDelegate, callDirection: CallDirection, useTurnOnly: Bool) {
AssertIsOnMainThread()
self.iceServers = iceServers
self.delegate = delegate
configuration = RTCConfiguration()
configuration.iceServers = iceServers
configuration.bundlePolicy = .maxBundle
configuration.rtcpMuxPolicy = .require
if useTurnOnly {
Logger.debug("\(TAG) using iceTransportPolicy: relay")
configuration.iceTransportPolicy = .relay
} else {
Logger.debug("\(TAG) using iceTransportPolicy: default")
}
let connectionConstraintsDict = ["DtlsSrtpKeyAgreement": "true"]
connectionConstraints = RTCMediaConstraints(mandatoryConstraints: nil, optionalConstraints: connectionConstraintsDict)
audioConstraints = RTCMediaConstraints(mandatoryConstraints: nil, optionalConstraints:nil)
cameraConstraints = RTCMediaConstraints(mandatoryConstraints: nil, optionalConstraints: nil)
super.init()
// Configure audio session so we don't prompt user with Record permission until call is connected.
type(of: self).configureAudioSession()
peerConnection = factory.peerConnection(with: configuration,
constraints: connectionConstraints,
delegate: self)
createAudioSender()
createVideoSender()
if callDirection == .outgoing {
// When placing an outgoing call, it's our responsibility to create the DataChannel.
// Recipient will not have to do this explicitly.
createSignalingDataChannel()
}
}
// MARK: - Media Streams
private func createSignalingDataChannel() {
AssertIsOnMainThread()
let configuration = RTCDataChannelConfiguration()
// Insist upon an "ordered" TCP data channel for delivery reliability.
configuration.isOrdered = true
let dataChannel = peerConnection.dataChannel(forLabel: Identifiers.dataChannelSignaling.rawValue,
configuration: configuration)
dataChannel.delegate = self
assert(self.dataChannel == nil)
self.dataChannel = dataChannel
}
// MARK: Video
fileprivate func createVideoSender() {
AssertIsOnMainThread()
Logger.debug("\(TAG) in \(#function)")
assert(self.videoSender == nil, "\(#function) should only be called once.")
guard !Platform.isSimulator else {
Logger.warn("\(TAG) Refusing to create local video track on simulator which has no capture device.")
return
}
// TODO: We could cap the maximum video size.
let cameraConstraints = RTCMediaConstraints(mandatoryConstraints:nil,
optionalConstraints:nil)
// TODO: Revisit the cameraConstraints.
let videoSource = factory.avFoundationVideoSource(with: cameraConstraints)
self.videoCaptureSession = videoSource.captureSession
videoSource.useBackCamera = false
let localVideoTrack = factory.videoTrack(with: videoSource, trackId: Identifiers.videoTrack.rawValue)
self.localVideoTrack = localVideoTrack
// Disable by default until call is connected.
// FIXME - do we require mic permissions at this point?
// if so maybe it would be better to not even add the track until the call is connected
// instead of creating it and disabling it.
localVideoTrack.isEnabled = false
let videoSender = peerConnection.sender(withKind: kVideoTrackType, streamId: Identifiers.mediaStream.rawValue)
videoSender.track = localVideoTrack
self.videoSender = videoSender
}
public func setLocalVideoEnabled(enabled: Bool) {
AssertIsOnMainThread()
PeerConnectionClient.signalingQueue.async {
guard self.peerConnection != nil else {
Logger.debug("\(self.TAG) \(#function) Ignoring obsolete event in terminated client")
return
}
guard let localVideoTrack = self.localVideoTrack else {
let action = enabled ? "enable" : "disable"
Logger.error("\(self.TAG)) trying to \(action) videoTrack which doesn't exist")
return
}
guard let videoCaptureSession = self.videoCaptureSession else {
Logger.error("\(self.TAG) videoCaptureSession was unexpectedly nil")
assertionFailure()
return
}
localVideoTrack.isEnabled = enabled
if enabled {
Logger.debug("\(self.TAG) in \(#function) starting videoCaptureSession")
videoCaptureSession.startRunning()
} else {
Logger.debug("\(self.TAG) in \(#function) stopping videoCaptureSession")
videoCaptureSession.stopRunning()
}
if let delegate = self.delegate {
DispatchQueue.main.async { [weak self, weak localVideoTrack] in
guard let strongSelf = self else { return }
guard let strongLocalVideoTrack = localVideoTrack else { return }
delegate.peerConnectionClient(strongSelf, didUpdateLocal: enabled ? strongLocalVideoTrack : nil)
}
}
}
}
// MARK: Audio
fileprivate func createAudioSender() {
AssertIsOnMainThread()
Logger.debug("\(TAG) in \(#function)")
assert(self.audioSender == nil, "\(#function) should only be called once.")
let audioSource = factory.audioSource(with: self.audioConstraints)
let audioTrack = factory.audioTrack(with: audioSource, trackId: Identifiers.audioTrack.rawValue)
self.audioTrack = audioTrack
// Disable by default until call is connected.
// FIXME - do we require mic permissions at this point?
// if so maybe it would be better to not even add the track until the call is connected
// instead of creating it and disabling it.
audioTrack.isEnabled = false
let audioSender = peerConnection.sender(withKind: kAudioTrackType, streamId: Identifiers.mediaStream.rawValue)
audioSender.track = audioTrack
self.audioSender = audioSender
}
public func setAudioEnabled(enabled: Bool) {
AssertIsOnMainThread()
PeerConnectionClient.signalingQueue.async {
guard self.peerConnection != nil else {
Logger.debug("\(self.TAG) \(#function) Ignoring obsolete event in terminated client")
return
}
guard let audioTrack = self.audioTrack else {
let action = enabled ? "enable" : "disable"
Logger.error("\(self.TAG) trying to \(action) audioTrack which doesn't exist.")
return
}
audioTrack.isEnabled = enabled
}
}
// MARK: - Session negotiation
private var defaultOfferConstraints: RTCMediaConstraints {
let mandatoryConstraints = [
"OfferToReceiveAudio": "true",
"OfferToReceiveVideo": "true"
]
return RTCMediaConstraints(mandatoryConstraints:mandatoryConstraints, optionalConstraints:nil)
}
public func createOffer() -> Promise<HardenedRTCSessionDescription> {
AssertIsOnMainThread()
return Promise { fulfill, reject in
AssertIsOnMainThread()
PeerConnectionClient.signalingQueue.async {
guard self.peerConnection != nil else {
Logger.debug("\(self.TAG) \(#function) Ignoring obsolete event in terminated client")
reject(NSError(domain:"Obsolete client", code:0, userInfo:nil))
return
}
self.peerConnection.offer(for: self.defaultOfferConstraints, completionHandler: { (sdp: RTCSessionDescription?, error: Error?) in
PeerConnectionClient.signalingQueue.async {
guard self.peerConnection != nil else {
Logger.debug("\(self.TAG) \(#function) Ignoring obsolete event in terminated client")
reject(NSError(domain:"Obsolete client", code:0, userInfo:nil))
return
}
guard error == nil else {
reject(error!)
return
}
guard let sessionDescription = sdp else {
Logger.error("\(self.TAG) No session description was obtained, even though there was no error reported.")
let error = OWSErrorMakeUnableToProcessServerResponseError()
reject(error)
return
}
fulfill(HardenedRTCSessionDescription(rtcSessionDescription: sessionDescription))
}
})
}
}
}
public func setLocalSessionDescriptionInternal(_ sessionDescription: HardenedRTCSessionDescription) -> Promise<Void> {
return PromiseKit.wrap { resolve in
self.assertOnSignalingQueue()
Logger.verbose("\(self.TAG) setting local session description: \(sessionDescription)")
self.peerConnection.setLocalDescription(sessionDescription.rtcSessionDescription, completionHandler:resolve)
}
}
public func setLocalSessionDescription(_ sessionDescription: HardenedRTCSessionDescription) -> Promise<Void> {
AssertIsOnMainThread()
return Promise { fulfill, reject in
PeerConnectionClient.signalingQueue.async {
guard self.peerConnection != nil else {
Logger.debug("\(self.TAG) \(#function) Ignoring obsolete event in terminated client")
reject(NSError(domain:"Obsolete client", code:0, userInfo:nil))
return
}
Logger.verbose("\(self.TAG) setting local session description: \(sessionDescription)")
self.peerConnection.setLocalDescription(sessionDescription.rtcSessionDescription,
completionHandler: { _ in
fulfill()
})
}
}
}
public func negotiateSessionDescription(remoteDescription: RTCSessionDescription, constraints: RTCMediaConstraints) -> Promise<HardenedRTCSessionDescription> {
AssertIsOnMainThread()
return setRemoteSessionDescription(remoteDescription)
.then(on: PeerConnectionClient.signalingQueue) {
return self.negotiateAnswerSessionDescription(constraints: constraints)
}
}
public func setRemoteSessionDescription(_ sessionDescription: RTCSessionDescription) -> Promise<Void> {
AssertIsOnMainThread()
return Promise { fulfill, reject in
PeerConnectionClient.signalingQueue.async {
guard self.peerConnection != nil else {
Logger.debug("\(self.TAG) \(#function) Ignoring obsolete event in terminated client")
reject(NSError(domain:"Obsolete client", code:0, userInfo:nil))
return
}
Logger.verbose("\(self.TAG) setting remote description: \(sessionDescription)")
self.peerConnection.setRemoteDescription(sessionDescription,
completionHandler: { _ in
fulfill()
})
}
}
}
private func negotiateAnswerSessionDescription(constraints: RTCMediaConstraints) -> Promise<HardenedRTCSessionDescription> {
assertOnSignalingQueue()
return Promise { fulfill, reject in
assertOnSignalingQueue()
guard self.peerConnection != nil else {
Logger.debug("\(self.TAG) \(#function) Ignoring obsolete event in terminated client")
reject(NSError(domain:"Obsolete client", code:0, userInfo:nil))
return
}
Logger.debug("\(self.TAG) negotiating answer session.")
peerConnection.answer(for: constraints, completionHandler: { (sdp: RTCSessionDescription?, error: Error?) in
PeerConnectionClient.signalingQueue.async {
guard self.peerConnection != nil else {
Logger.debug("\(self.TAG) \(#function) Ignoring obsolete event in terminated client")
reject(NSError(domain:"Obsolete client", code:0, userInfo:nil))
return
}
guard error == nil else {
reject(error!)
return
}
guard let sessionDescription = sdp else {
Logger.error("\(self.TAG) unexpected empty session description, even though no error was reported.")
let error = OWSErrorMakeUnableToProcessServerResponseError()
reject(error)
return
}
let hardenedSessionDescription = HardenedRTCSessionDescription(rtcSessionDescription: sessionDescription)
self.setLocalSessionDescriptionInternal(hardenedSessionDescription)
.then(on: PeerConnectionClient.signalingQueue) {
fulfill(hardenedSessionDescription)
}.catch { error in
reject(error)
}
}
})
}
}
public func addIceCandidate(_ candidate: RTCIceCandidate) {
PeerConnectionClient.signalingQueue.async {
guard self.peerConnection != nil else {
Logger.debug("\(self.TAG) \(#function) Ignoring obsolete event in terminated client")
return
}
Logger.debug("\(self.TAG) adding candidate")
self.peerConnection.add(candidate)
}
}
public func terminate() {
AssertIsOnMainThread()
Logger.debug("\(TAG) in \(#function)")
PeerConnectionClient.signalingQueue.async {
assert(self.peerConnection != nil)
self.terminateInternal()
}
}
private func terminateInternal() {
assertOnSignalingQueue()
Logger.debug("\(TAG) in \(#function)")
// Some notes on preventing crashes while disposing of peerConnection for video calls
// from: https://groups.google.com/forum/#!searchin/discuss-webrtc/objc$20crash$20dealloc%7Csort:relevance/discuss-webrtc/7D-vk5yLjn8/rBW2D6EW4GYJ
// The sequence to make it work appears to be
//
// [capturer stop]; // I had to add this as a method to RTCVideoCapturer
// [localRenderer stop];
// [remoteRenderer stop];
// [peerConnection close];
// audioTrack is a strong property because we need access to it to mute/unmute, but I was seeing it
// become nil when it was only a weak property. So we retain it and manually nil the reference here, because
// we are likely to crash if we retain any peer connection properties when the peerconnection is released
// See the comments on the remoteVideoTrack property.
objc_sync_enter(self)
localVideoTrack?.isEnabled = false
remoteVideoTrack?.isEnabled = false
dataChannel = nil
audioSender = nil
audioTrack = nil
videoSender = nil
localVideoTrack = nil
remoteVideoTrack = nil
peerConnection.delegate = nil
peerConnection.close()
peerConnection = nil
objc_sync_exit(self)
delegate = nil
}
// MARK: - Data Channel
public func sendDataChannelMessage(data: Data) {
AssertIsOnMainThread()
PeerConnectionClient.signalingQueue.async {
guard self.peerConnection != nil else {
Logger.debug("\(self.TAG) \(#function) Ignoring obsolete event in terminated client")
return
}
guard let dataChannel = self.dataChannel else {
Logger.error("\(self.TAG) in \(#function) ignoring sending \(data) for nil dataChannel")
return
}
let buffer = RTCDataBuffer(data: data, isBinary: false)
let result = dataChannel.sendData(buffer)
if result {
Logger.debug("\(self.TAG) sendDataChannelMessage succeeded")
} else {
Logger.warn("\(self.TAG) sendDataChannelMessage failed")
}
}
}
// MARK: RTCDataChannelDelegate
/** The data channel state changed. */
internal func dataChannelDidChangeState(_ dataChannel: RTCDataChannel) {
Logger.debug("\(TAG) dataChannelDidChangeState: \(dataChannel)")
}
/** The data channel successfully received a data buffer. */
internal func dataChannel(_ dataChannel: RTCDataChannel, didReceiveMessageWith buffer: RTCDataBuffer) {
PeerConnectionClient.signalingQueue.async {
guard self.peerConnection != nil else {
Logger.debug("\(self.TAG) \(#function) Ignoring obsolete event in terminated client")
return
}
Logger.debug("\(self.TAG) dataChannel didReceiveMessageWith buffer:\(buffer)")
guard let dataChannelMessage = OWSWebRTCProtosData.parse(from:buffer.data) else {
// TODO can't proto parsings throw an exception? Is it just being lost in the Objc->Swift?
Logger.error("\(self.TAG) failed to parse dataProto")
return
}
if let delegate = self.delegate {
DispatchQueue.main.async { [weak self] in
guard let strongSelf = self else { return }
delegate.peerConnectionClient(strongSelf, received: dataChannelMessage)
}
}
}
}
/** The data channel's |bufferedAmount| changed. */
internal func dataChannel(_ dataChannel: RTCDataChannel, didChangeBufferedAmount amount: UInt64) {
Logger.debug("\(TAG) didChangeBufferedAmount: \(amount)")
}
// MARK: - RTCPeerConnectionDelegate
/** Called when the SignalingState changed. */
internal func peerConnection(_ peerConnection: RTCPeerConnection, didChange stateChanged: RTCSignalingState) {
Logger.debug("\(TAG) didChange signalingState:\(stateChanged.debugDescription)")
}
/** Called when media is received on a new stream from remote peer. */
internal func peerConnection(_ peerConnection: RTCPeerConnection, didAdd stream: RTCMediaStream) {
guard stream.videoTracks.count > 0 else {
return
}
let remoteVideoTrack = stream.videoTracks[0]
Logger.debug("\(self.TAG) didAdd stream:\(stream) video tracks: \(stream.videoTracks.count) audio tracks: \(stream.audioTracks.count)")
// See the comments on the remoteVideoTrack property.
//
// We only set the remoteVideoTrack property if peerConnection is non-nil.
objc_sync_enter(self)
if self.peerConnection != nil {
self.remoteVideoTrack = remoteVideoTrack
}
objc_sync_exit(self)
PeerConnectionClient.signalingQueue.async {
guard self.peerConnection != nil else {
Logger.debug("\(self.TAG) \(#function) Ignoring obsolete event in terminated client")
return
}
if let delegate = self.delegate {
DispatchQueue.main.async { [weak self] in
guard let strongSelf = self else { return }
// See the comments on the remoteVideoTrack property.
//
// We only access the remoteVideoTrack property if peerConnection is non-nil.
var remoteVideoTrack: RTCVideoTrack?
objc_sync_enter(strongSelf)
if strongSelf.peerConnection != nil {
remoteVideoTrack = strongSelf.remoteVideoTrack
}
objc_sync_exit(strongSelf)
delegate.peerConnectionClient(strongSelf, didUpdateRemote: remoteVideoTrack)
}
}
}
}
/** Called when a remote peer closes a stream. */
internal func peerConnection(_ peerConnection: RTCPeerConnection, didRemove stream: RTCMediaStream) {
Logger.debug("\(TAG) didRemove Stream:\(stream)")
}
/** Called when negotiation is needed, for example ICE has restarted. */
internal func peerConnectionShouldNegotiate(_ peerConnection: RTCPeerConnection) {
Logger.debug("\(TAG) shouldNegotiate")
}
/** Called any time the IceConnectionState changes. */
internal func peerConnection(_ peerConnection: RTCPeerConnection, didChange newState: RTCIceConnectionState) {
PeerConnectionClient.signalingQueue.async {
guard self.peerConnection != nil else {
Logger.debug("\(self.TAG) \(#function) Ignoring obsolete event in terminated client")
return
}
Logger.debug("\(self.TAG) didChange IceConnectionState:\(newState.debugDescription)")
switch newState {
case .connected, .completed:
if let delegate = self.delegate {
DispatchQueue.main.async { [weak self] in
guard let strongSelf = self else { return }
delegate.peerConnectionClientIceConnected(strongSelf)
}
}
case .failed:
Logger.warn("\(self.TAG) RTCIceConnection failed.")
if let delegate = self.delegate {
DispatchQueue.main.async { [weak self] in
guard let strongSelf = self else { return }
delegate.peerConnectionClientIceFailed(strongSelf)
}
}
case .disconnected:
Logger.warn("\(self.TAG) RTCIceConnection disconnected.")
default:
Logger.debug("\(self.TAG) ignoring change IceConnectionState:\(newState.debugDescription)")
}
}
}
/** Called any time the IceGatheringState changes. */
internal func peerConnection(_ peerConnection: RTCPeerConnection, didChange newState: RTCIceGatheringState) {
Logger.debug("\(TAG) didChange IceGatheringState:\(newState.debugDescription)")
}
/** New ice candidate has been found. */
internal func peerConnection(_ peerConnection: RTCPeerConnection, didGenerate candidate: RTCIceCandidate) {
PeerConnectionClient.signalingQueue.async {
guard self.peerConnection != nil else {
Logger.debug("\(self.TAG) \(#function) Ignoring obsolete event in terminated client")
return
}
Logger.debug("\(self.TAG) didGenerate IceCandidate:\(candidate.sdp)")
if let delegate = self.delegate {
DispatchQueue.main.async { [weak self] in
guard let strongSelf = self else { return }
delegate.peerConnectionClient(strongSelf, addedLocalIceCandidate: candidate)
}
}
}
}
/** Called when a group of local Ice candidates have been removed. */
internal func peerConnection(_ peerConnection: RTCPeerConnection, didRemove candidates: [RTCIceCandidate]) {
Logger.debug("\(TAG) didRemove IceCandidates:\(candidates)")
}
/** New data channel has been opened. */
internal func peerConnection(_ peerConnection: RTCPeerConnection, didOpen dataChannel: RTCDataChannel) {
PeerConnectionClient.signalingQueue.async {
guard self.peerConnection != nil else {
Logger.debug("\(self.TAG) \(#function) Ignoring obsolete event in terminated client")
return
}
Logger.debug("\(self.TAG) didOpen dataChannel:\(dataChannel)")
assert(self.dataChannel == nil)
self.dataChannel = dataChannel
dataChannel.delegate = self
}
}
// Mark: Audio Session
class func configureAudioSession() {
sharedAudioSession.configure()
}
class func startAudioSession() {
sharedAudioSession.start()
}
class func stopAudioSession() {
sharedAudioSession.stop()
}
// MARK: Helpers
/**
* We synchronize access to state in this class using this queue.
*/
private func assertOnSignalingQueue() {
if #available(iOS 10.0, *) {
dispatchPrecondition(condition: .onQueue(type(of: self).signalingQueue))
} else {
// Skipping check on <iOS10, since syntax is different and it's just a development convenience.
}
}
// MARK: Test-only accessors
internal func peerConnectionForTests() -> RTCPeerConnection {
AssertIsOnMainThread()
var result: RTCPeerConnection? = nil
PeerConnectionClient.signalingQueue.sync {
result = peerConnection
Logger.info("\(self.TAG) called \(#function)")
}
return result!
}
internal func dataChannelForTests() -> RTCDataChannel {
AssertIsOnMainThread()
var result: RTCDataChannel? = nil
PeerConnectionClient.signalingQueue.sync {
result = dataChannel
Logger.info("\(self.TAG) called \(#function)")
}
return result!
}
internal func flushSignalingQueueForTests() {
AssertIsOnMainThread()
PeerConnectionClient.signalingQueue.sync {
// Noop.
}
}
}
/**
* Restrict an RTCSessionDescription to more secure parameters
*/
class HardenedRTCSessionDescription {
let rtcSessionDescription: RTCSessionDescription
var sdp: String { return rtcSessionDescription.sdp }
init(rtcSessionDescription: RTCSessionDescription) {
self.rtcSessionDescription = HardenedRTCSessionDescription.harden(rtcSessionDescription: rtcSessionDescription)
}
/**
* Set some more secure parameters for the session description
*/
class func harden(rtcSessionDescription: RTCSessionDescription) -> RTCSessionDescription {
var description = rtcSessionDescription.sdp
// Enforce Constant bit rate.
let cbrRegex = try! NSRegularExpression(pattern:"(a=fmtp:111 ((?!cbr=).)*)\r?\n", options:.caseInsensitive)
description = cbrRegex.stringByReplacingMatches(in: description, options: [], range: NSMakeRange(0, description.characters.count), withTemplate: "$1;cbr=1\r\n")
// Strip plaintext audio-level details
// https://tools.ietf.org/html/rfc6464
let audioLevelRegex = try! NSRegularExpression(pattern:".+urn:ietf:params:rtp-hdrext:ssrc-audio-level.*\r?\n", options:.caseInsensitive)
description = audioLevelRegex.stringByReplacingMatches(in: description, options: [], range: NSMakeRange(0, description.characters.count), withTemplate: "")
return RTCSessionDescription.init(type: rtcSessionDescription.type, sdp: description)
}
}
// Mark: Pretty Print Objc enums.
fileprivate extension RTCSignalingState {
var debugDescription: String {
switch self {
case .stable:
return "stable"
case .haveLocalOffer:
return "haveLocalOffer"
case .haveLocalPrAnswer:
return "haveLocalPrAnswer"
case .haveRemoteOffer:
return "haveRemoteOffer"
case .haveRemotePrAnswer:
return "haveRemotePrAnswer"
case .closed:
return "closed"
}
}
}
fileprivate extension RTCIceGatheringState {
var debugDescription: String {
switch self {
case .new:
return "new"
case .gathering:
return "gathering"
case .complete:
return "complete"
}
}
}
fileprivate extension RTCIceConnectionState {
var debugDescription: String {
switch self {
case .new:
return "new"
case .checking:
return "checking"
case .connected:
return "connected"
case .completed:
return "completed"
case .failed:
return "failed"
case .disconnected:
return "disconnected"
case .closed:
return "closed"
case .count:
return "count"
}
}
}
| a4a21ec2ff2dfd7609eee79e231db4c9 | 39.134593 | 168 | 0.623757 | false | false | false | false |
silt-lang/silt | refs/heads/master | Sources/OuterCore/ParseGIR.swift | mit | 1 | /// ParseGIR.swift
///
/// Copyright 2017-2018, The Silt Language Project.
///
/// This project is released under the MIT license, a copy of which is
/// available in the repository.
import Lithosphere
import Crust
import Seismography
import Moho
import Mantle
public final class GIRParser {
struct ParserScope {
let name: String
}
let parser: Parser
var module: GIRModule
private var _activeScope: ParserScope?
fileprivate var continuationsByName: [Name: Continuation] = [:]
fileprivate var undefinedContinuation: [Continuation: TokenSyntax] = [:]
fileprivate var localValues: [String: Value] = [:]
fileprivate var forwardRefLocalValues: [String: TokenSyntax] = [:]
private let tc: TypeChecker<CheckPhaseState>
var currentScope: ParserScope {
guard let scope = self._activeScope else {
fatalError("Attempted to request current scope without pushing a scope.")
}
return scope
}
public init(_ parser: Parser) {
self.parser = parser
self.tc = TypeChecker<CheckPhaseState>(CheckPhaseState(), parser.engine)
self.module = GIRModule(parent: nil, tc: TypeConverter(self.tc))
}
@discardableResult
func withScope<T>(named name: String,
_ actions: () throws -> T) rethrows -> T {
let prevScope = self._activeScope
let prevLocals = localValues
let prevForwardRefLocals = forwardRefLocalValues
self._activeScope = ParserScope(name: name)
defer {
self._activeScope = prevScope
self.localValues = prevLocals
self.forwardRefLocalValues = prevForwardRefLocals
}
return try actions()
}
func namedContinuation(_ B: GIRBuilder, _ name: Name) -> Continuation {
// If there was no name specified for this block, just create a new one.
if name.description.isEmpty {
return B.buildContinuation(name: QualifiedName(name: name))
}
// If the block has never been named yet, just create it.
guard let cont = self.continuationsByName[name] else {
let cont = B.buildContinuation(name: QualifiedName(name: name))
self.continuationsByName[name] = cont
return cont
}
if undefinedContinuation.removeValue(forKey: cont) == nil {
// If we have a redefinition, return a new BB to avoid inserting
// instructions after the terminator.
fatalError("Redefinition of Basic Block")
}
return cont
}
func getReferencedContinuation(
_ B: GIRBuilder, _ syntax: TokenSyntax) -> Continuation {
assert(syntax.render.starts(with: "@"))
let noAtNode = syntax.withKind(
.identifier(String(syntax.render.dropFirst())))
let name = Name(name: noAtNode)
// If the block has already been created, use it.
guard let cont = self.continuationsByName[name] else {
// Otherwise, create it and remember that this is a forward reference so
// that we can diagnose use without definition problems.
let cont = B.buildContinuation(name: QualifiedName(name: name))
self.continuationsByName[name] = cont
self.undefinedContinuation[cont] = syntax
return cont
}
return cont
}
func getLocalValue(_ name: TokenSyntax) -> Value {
// Check to see if this is already defined.
guard let entry = self.localValues[name.render] else {
// Otherwise, this is a forward reference. Create a dummy node to
// represent it until we see a real definition.
self.forwardRefLocalValues[name.render] = name
let entry = NoOp()
self.localValues[name.render] = entry
return entry
}
return entry
}
func setLocalValue(_ value: Value, _ name: String) {
// If this value was already defined, it is either a redefinition, or a
// specification for a forward referenced value.
guard let entry = self.localValues[name] else {
// Otherwise, just store it in our map.
self.localValues[name] = value
return
}
guard self.forwardRefLocalValues.removeValue(forKey: name) != nil else {
fatalError("Redefinition of named value \(name) by \(value)")
}
// Forward references only live here if they have a single result.
entry.replaceAllUsesWith(value)
}
}
extension GIRParser {
public func parseTopLevelModule() -> GIRModule {
do {
_ = try self.parser.consume(.moduleKeyword)
let moduleId = try self.parser.parseQualifiedName().render
_ = try self.parser.consume(.whereKeyword)
let mod = GIRModule(name: moduleId,
parent: nil, tc: TypeConverter(self.tc))
self.module = mod
let builder = GIRBuilder(module: mod)
try self.parseDecls(builder)
assert(self.parser.currentToken?.tokenKind == .eof)
return mod
} catch _ {
return self.module
}
}
func parseDecls(_ B: GIRBuilder) throws {
while self.parser.peek() != .rightBrace && self.parser.peek() != .eof {
_ = try parseDecl(B)
}
}
func parseDecl(_ B: GIRBuilder) throws -> Bool {
guard
case let .identifier(identStr) = parser.peek(), identStr.starts(with: "@")
else {
throw self.parser.unexpectedToken()
}
let ident = try self.parser.parseIdentifierToken()
_ = try self.parser.consume(.colon)
_ = try self.parser.parseGIRTypeExpr()
_ = try self.parser.consume(.leftBrace)
return try self.withScope(named: ident.render) {
repeat {
guard try self.parseGIRBasicBlock(B) else {
return false
}
} while self.parser.peek() != .rightBrace && self.parser.peek() != .eof
_ = try self.parser.consume(.rightBrace)
return true
}
}
func parseGIRBasicBlock(_ B: GIRBuilder) throws -> Bool {
var ident = try self.parser.parseIdentifierToken()
if ident.render.hasSuffix(":") {
ident = ident.withKind(.identifier(String(ident.render.dropLast())))
}
let cont = self.namedContinuation(B, Name(name: ident))
// If there is a basic block argument list, process it.
if try self.parser.consumeIf(.leftParen) != nil {
repeat {
let name = try self.parser.parseIdentifierToken().render
_ = try self.parser.consume(.colon)
let typeRepr = try self.parser.parseGIRTypeExpr()
let arg = cont.appendParameter(type: GIRExprType(typeRepr))
self.setLocalValue(arg, name)
} while try self.parser.consumeIf(.semicolon) != nil
_ = try self.parser.consume(.rightParen)
_ = try self.parser.consume(.colon)
}
repeat {
guard try parseGIRInstruction(B, in: cont) else {
return true
}
} while isStartOfGIRPrimop()
return true
}
func isStartOfGIRPrimop() -> Bool {
guard case .identifier(_) = self.parser.peek() else {
return false
}
return true
}
// swiftlint:disable function_body_length
func parseGIRInstruction(
_ B: GIRBuilder, in cont: Continuation) throws -> Bool {
guard self.parser.peekToken()!.leadingTrivia.containsNewline else {
fatalError("Instruction must begin on a new line")
}
guard case .identifier(_) = self.parser.peek() else {
return false
}
let resultName = tryParseGIRValueName()
if resultName != nil {
_ = try self.parser.consume(.equals)
}
guard let opcode = parseGIRPrimOpcode() else {
return false
}
var resultValue: Value?
switch opcode {
case .dataExtract:
fatalError("unimplemented")
case .forceEffects:
fatalError("unimplemented")
case .tuple:
fatalError("unimplemented")
case .tupleElementAddress:
fatalError("unimplemented")
case .thicken:
fatalError("unimplemented")
case .noop:
fatalError("noop cannot be spelled")
case .alloca:
let typeRepr = try self.parser.parseGIRTypeExpr()
let type = GIRExprType(typeRepr)
resultValue = B.createAlloca(type)
case .allocBox:
let typeRepr = try self.parser.parseGIRTypeExpr()
let type = GIRExprType(typeRepr)
resultValue = B.createAllocBox(type)
case .apply:
guard let fnName = tryParseGIRValueToken() else {
return false
}
let fnVal = self.getLocalValue(fnName)
_ = try self.parser.consume(.leftParen)
var argNames = [TokenSyntax]()
if self.parser.peek() != .rightParen {
repeat {
guard let arg = self.tryParseGIRValueToken() else {
return false
}
argNames.append(arg)
} while try self.parser.consumeIf(.semicolon) != nil
}
_ = try self.parser.consume(.rightParen)
_ = try self.parser.consume(.colon)
_ = try self.parser.parseGIRTypeExpr()
var args = [Value]()
for argName in argNames {
let argVal = self.getLocalValue(argName)
args.append(argVal)
}
_ = B.createApply(cont, fnVal, args)
case .copyValue:
guard let valueName = tryParseGIRValueToken() else {
return false
}
_ = try self.parser.consumeIf(.colon)
_ = try self.parser.parseGIRTypeExpr()
resultValue = B.createCopyValue(self.getLocalValue(valueName))
case .copyAddress:
guard let valueName = tryParseGIRValueToken() else {
return false
}
_ = try self.parser.consume(.identifier("to"))
guard let addressName = tryParseGIRValueToken() else {
return false
}
_ = try self.parser.consumeIf(.colon)
_ = try self.parser.parseGIRTypeExpr()
resultValue = B.createCopyAddress(self.getLocalValue(valueName),
to: self.getLocalValue(addressName))
case .dealloca:
guard let valueName = tryParseGIRValueToken() else {
return false
}
_ = try self.parser.consumeIf(.colon)
_ = try self.parser.parseGIRTypeExpr()
cont.appendCleanupOp(B.createDealloca(self.getLocalValue(valueName)))
case .deallocBox:
guard let valueName = tryParseGIRValueToken() else {
return false
}
_ = try self.parser.consumeIf(.colon)
_ = try self.parser.parseGIRTypeExpr()
cont.appendCleanupOp(B.createDeallocBox(self.getLocalValue(valueName)))
case .destroyValue:
guard let valueName = tryParseGIRValueToken() else {
return false
}
_ = try self.parser.consumeIf(.colon)
_ = try self.parser.parseGIRTypeExpr()
cont.appendCleanupOp(B.createDestroyValue(self.getLocalValue(valueName)))
case .destroyAddress:
guard let valueName = tryParseGIRValueToken() else {
return false
}
_ = try self.parser.consumeIf(.colon)
_ = try self.parser.parseGIRTypeExpr()
cont.appendCleanupOp(
B.createDestroyAddress(self.getLocalValue(valueName)))
case .switchConstr:
guard let val = self.tryParseGIRValueToken() else {
return false
}
let srcVal = self.getLocalValue(val)
_ = try self.parser.consume(.colon)
_ = try self.parser.parseGIRTypeExpr()
var caseConts = [(String, FunctionRefOp)]()
while case .semicolon = self.parser.peek() {
_ = try self.parser.consume(.semicolon)
guard
case let .identifier(ident) = self.parser.peek(), ident == "case"
else {
return false
}
_ = try self.parser.parseIdentifierToken()
let caseName = try self.parser.parseQualifiedName()
_ = try self.parser.consume(.colon)
guard let arg = self.tryParseGIRValueToken() else {
return false
}
// swiftlint:disable force_cast
let fnVal = self.getLocalValue(arg) as! FunctionRefOp
caseConts.append((caseName.render, fnVal))
}
_ = B.createSwitchConstr(cont, srcVal, caseConts)
case .functionRef:
guard
case let .identifier(refName) = parser.peek(), refName.starts(with: "@")
else {
return false
}
let ident = try self.parser.parseIdentifierToken()
let resultFn = getReferencedContinuation(B, ident)
resultValue = B.createFunctionRef(resultFn)
case .dataInit:
let typeRepr = try self.parser.parseGIRTypeExpr()
_ = try self.parser.consume(.semicolon)
let ident = try self.parser.parseQualifiedName()
let type = GIRExprType(typeRepr)
var args = [Value]()
while case .semicolon = self.parser.peek() {
_ = try self.parser.consume(.semicolon)
guard let arg = self.tryParseGIRValueToken() else {
return false
}
let argVal = self.getLocalValue(arg)
_ = try self.parser.consume(.colon)
_ = try self.parser.parseGIRTypeExpr()
args.append(argVal)
}
resultValue = B.createDataInit(ident.render, type, nil)
case .projectBox:
guard let valueName = tryParseGIRValueToken() else {
return false
}
_ = try self.parser.consumeIf(.colon)
let typeRepr = try self.parser.parseGIRTypeExpr()
resultValue = B.createProjectBox(self.getLocalValue(valueName),
type: GIRExprType(typeRepr))
case .load:
guard let valueName = tryParseGIRValueToken() else {
return false
}
_ = try self.parser.consumeIf(.colon)
_ = try self.parser.parseGIRTypeExpr()
resultValue = B.createLoad(self.getLocalValue(valueName), .copy)
case .store:
guard let valueName = tryParseGIRValueToken() else {
return false
}
_ = try self.parser.consume(.identifier("to"))
guard let addressName = tryParseGIRValueToken() else {
return false
}
_ = try self.parser.consumeIf(.colon)
_ = try self.parser.parseGIRTypeExpr()
_ = B.createStore(self.getLocalValue(valueName),
to: self.getLocalValue(addressName))
case .unreachable:
resultValue = B.createUnreachable(cont)
}
guard let resName = resultName, let resValue = resultValue else {
return true
}
self.setLocalValue(resValue, resName)
return true
}
func tryParseGIRValueName() -> String? {
return tryParseGIRValueToken()?.render
}
func tryParseGIRValueToken() -> TokenSyntax? {
guard let result = self.parser.peekToken() else {
return nil
}
guard case let .identifier(ident) = result.tokenKind else {
return nil
}
guard ident.starts(with: "%") else {
return nil
}
self.parser.advance()
return result
}
func parseGIRPrimOpcode() -> PrimOp.Code? {
guard case let .identifier(ident) = self.parser.peek() else {
return nil
}
guard let opCode = PrimOp.Code(rawValue: ident) else {
return nil
}
_ = self.parser.advance()
return opCode
}
}
extension TokenSyntax {
var render: String {
return self.triviaFreeSourceText
}
}
extension QualifiedNameSyntax {
var render: String {
var result = ""
for component in self {
result += component.triviaFreeSourceText
}
return result
}
}
| 7937daf834154c272eec941b10510beb | 30.307531 | 80 | 0.643502 | false | false | false | false |
scubers/JRDB | refs/heads/master | JRDB/AViewController.swift | mit | 1 | //
// AViewController.swift
// JRDB
//
// Created by JMacMini on 16/5/10.
// Copyright © 2016年 Jrwong. All rights reserved.
//
import UIKit
enum Sex : Int {
case man
case woman
}
class AAA: NSObject {
var type: String?
deinit {
print("\(self) deinit")
}
}
class PPP: AAA {
var sss : Sex = .man
var a_int: Int = 0
var a_int1: Int? = nil
var b_string: String = "1"
var b_string1: String! = "2"
var b_string2: String? = "3"
var c_nsstring: NSString = "4"
var c_nsstring1: NSString! = "5"
var c_nsstring2: NSString? = nil
var d_double: Double = 7
var e_float: Float = 8
var f_cgfloat: CGFloat = 9
var g_nsData: Data = Data()
var h_nsDate: Date = Date()
var ccc: CCC?
var ccc1: CCC?
var ppp: PPP?
// override static func jr_singleLinkedPropertyNames() -> [String : AnyObject.Type]? {
// return [
// "ccc" : CCC.self,
// "ccc1" : CCC.self,
// "ppp" : PPP.self,
// ]
// }
}
class CCC: NSObject {
var serialNumber: String = ""
weak var ppp: PPP?
// override static func jr_singleLinkedPropertyNames() -> [String : AnyObject.Type]? {
// return [
// "ppp" : PPP.self,
// ]
// }
deinit {
print("\(self) deinit")
}
}
class AViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// let db = JRDBMgr.shareInstance().createDB(withPath: "/Users/mac/Desktop/test.sqlite")
JRDBMgr.shareInstance().defaultDatabasePath = "/Users/mac/Desktop/test.sqlite";
let db = JRDBMgr.shareInstance().getHandler()
print(db);
// test1Cycle()
// testFindByID()
// testThreeNodeCycle()
// test2Node1Cycle()
// truncateTable()
}
func test2Node1Cycle() {
let p = PPP()
let p1 = PPP()
let c = CCC()
p.ppp = p1
p1.ccc = c
c.ppp = p1
p.jr_save()
}
func testThreeNodeCycle() {
let p1 = PPP()
let p2 = PPP()
let p3 = PPP()
p1.ppp = p2
p2.ppp = p3
p3.ppp = p1
p1.jr_save()
}
func test1Cycle() {
let p = PPP()
let c = CCC()
p.ccc = c
c.ppp = p
p.jr_save()
}
func testFindByID() {
let p = PPP.jr_find(byID: "FBE5701E-ECBB-494A-BE62-7C7114C780A1")
p?.isEqual(nil);
}
func truncateTable() {
PPP.jr_truncateTable()
CCC.jr_truncateTable()
}
}
| 9b1e3491a0a1f00bdf9a558914af5afa | 19.219697 | 95 | 0.500937 | false | true | false | false |
roroque/Compiladores | refs/heads/master | MaquinaVirtual/MaquinaVirtual/Commands.swift | apache-2.0 | 1 | //
// Commands.swift
// MaquinaVirtualCompiladores
//
// Created by Gabriel Neves Ferreira on 8/11/16.
// Copyright © 2016 Gabriel Neves Ferreira. All rights reserved.
//
import Cocoa
class Commands {
//Views to modify
var outputView : NSTextView
var inputView : NSTextView
//Engine variables
var s : Int = 0 //numero da pilha
var M : [Int] = [] //pilha de dados
var i : Int = 0 //numero da instrucao
//class init
init(aOutputView: NSTextView,aInputView : NSTextView){
outputView = aOutputView
inputView = aInputView
}
//engine helpers
func getStackCount() -> Int {
return M.count
}
func getStackRowContent(row : Int) -> String{
if row < M.count {
return M[row].description
}
return ""
}
//Virtual Machine Functions
//ldc function
func loadConstant(k : Int) {
s = s + 1
M[s] = k
}
//ldv function
func loadValue(n : Int) {
s = s + 1
M[s] = M[n]
}
//add function
func add() {
M[s-1] = M[s-1] + M[s]
s = s-1
}
//sub function
func sub() {
M[s-1] = M[s-1] - M[s]
s = s-1
}
//mult function
func mult() {
M[s-1] = M[s-1] * M[s]
s = s-1
}
//div function
func div() {
M[s-1] = M[s-1] / M[s]
s = s-1
}
//inv function
func invert() {
M[s] = -M[s]
}
//and function
func and(){
if M[s-1] == 1 && M[s] == 1 {
M[s-1] = 1
}else{
M[s-1] = 0
}
s = s-1
}
//or function
func or(){
if M[s-1] == 1 || M[s] == 1 {
M[s-1] = 1
}else{
M[s-1] = 0
}
s = s-1
}
//neg function
func neg(){
M[s] = 1 - M[s]
}
//less than function
func lessThan() {
if M[s-1] < M[s]{
M[s-1] = 1
}else{
M[s-1] = 0
}
s = s-1
}
//greater than function
func greaterThan() {
if M[s-1] > M[s]{
M[s-1] = 1
}else{
M[s-1] = 0
}
s = s-1
}
//equal than function
func equalThan() {
if M[s-1] == M[s]{
M[s-1] = 1
}else{
M[s-1] = 0
}
s = s-1
}
//different than function
func diferentThan() {
if M[s-1] != M[s]{
M[s-1] = 1
}else{
M[s-1] = 0
}
s = s-1
}
//less or equal than function
func lessEqualThan() {
if M[s-1] <= M[s]{
M[s-1] = 1
}else{
M[s-1] = 0
}
s = s-1
}
//greater or equal than function
func greaterEqualThan() {
if M[s-1] >= M[s]{
M[s-1] = 1
}else{
M[s-1] = 0
}
s = s-1
}
//start Function
func startProgram() {
s = -1
//olhar melhor essa logica
}
//halt function
func haltProgram() {
//olhar melhor essa logica
}
//store function
func store(n : Int) {
M[n] = M[s]
s = s-1
}
//jump function
func jump(t : Int){
i = t
}
//jump false function
func jumpFalse(t : Int){
if M[s] == 0 {
i = t
}else{
i = i + 1
}
s = s - 1
}
//null
func null() {
//do nothing
}
//reading Functions
func startReading(){
s = s + 1
//enable text field for writing
//disable text field to continue
//olhar melhor essa logica
}
func finishReading(value : Int){
M.append(value)
//disable text field for writing
//enable text field to continue
//olhar melhor essa logica
printInAView(value.description, aTextView: inputView)
}
//printing Funtion
func printOutput(){
printInAView(M[s].description, aTextView: outputView)
s = s-1
}
//alloc Function
func alloc(m : Int, n : Int) {
//equal to for int i = 0 ; i < n; i ++
for k in 0...(n - 1) {
s = s + 1
M[s] = M[m + k]
}
}
//dalloc Function
func dalloc(m : Int, n : Int) {
//equal to for int k = n - 1; k >= 0; k--
for k in (0...(n - 1)).reverse() {
M[m+k] = M[s]
s = s-1
}
}
//call Function
func call(t : Int) {
s = s + 1
M[s] = i + 1
i = t
}
//return Function
func returnFromFunction() {
i = M[s]
s = s - 1
}
//Auxiliary Functions
private func printInAView(aString: String,aTextView : NSTextView) {
aTextView.editable = true
aTextView.insertText(aString)
aTextView.insertNewline(nil)
aTextView.editable = false
}
//Switch for functions
func callFunctionWithCommand(command : String,firstParameter : Int?, secondParameter : Int?){
switch command {
case "LDC":
loadConstant(firstParameter!)
break
case "LDV":
loadValue(firstParameter!)
break
case "ADD":
add()
break
case "SUB":
sub()
break
case "MULT":
mult()
break
case "DIVI":
div()
break
case "INV":
invert()
break
case "AND":
and()
break
case "OR":
or()
break
case "NEG":
neg()
break
case "CME":
lessThan()
break
case "CMA":
greaterThan()
break
case "CEQ":
equalThan()
break
case "CDIF":
diferentThan()
break
case "CMEQ":
lessEqualThan()
break
case "CMAQ":
greaterEqualThan()
break
case "START":
startProgram()
break
case "HLT":
haltProgram()
break
case "STR":
store(firstParameter!)
break
case "JMP":
jump(firstParameter!)
break
case "JMPF":
jumpFalse(firstParameter!)
break
case "NULL":
null()
break
case "RD":
startReading()
break
case "PRN":
printOutput()
break
case "ALLOC":
alloc(firstParameter!, n: secondParameter!)
break
case "DALLOC":
dalloc(firstParameter!, n: secondParameter!)
break
case "CALL":
call(firstParameter!)
break
case "RETURN":
returnFromFunction()
break
default:
print(command + " is not valid")
}
//checar se o incremento ta implicito ou nao apenas se for algum dos jumps
if command != "JMP" || command != "JMPF" {
i = i + 1
}
}
}
| cf9cd91b4d26a8be2fe5adcfa90cab17 | 17.454976 | 97 | 0.39471 | false | false | false | false |
blockchain/My-Wallet-V3-iOS | refs/heads/master | Modules/DelegatedSelfCustody/Tests/DelegatedSelfCustodyDataTests/BuildTxResponseTests.swift | lgpl-3.0 | 1 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
@testable import DelegatedSelfCustodyData
import ToolKit
import XCTest
// swiftlint:disable line_length
final class BuildTxResponseTests: XCTestCase {
func testDecodes() throws {
guard let jsonData = json.data(using: .utf8) else {
XCTFail("Failed to read data.")
return
}
let response = try JSONDecoder().decode(BuildTxResponse.self, from: jsonData)
XCTAssertEqual(response.summary.relativeFee, "1")
XCTAssertEqual(response.summary.absoluteFeeMaximum, "2")
XCTAssertEqual(response.summary.absoluteFeeEstimate, "3")
XCTAssertEqual(response.summary.amount, "4")
XCTAssertEqual(response.summary.balance, "5")
XCTAssertEqual(response.preImages.count, 1)
let preImage = response.preImages[0]
XCTAssertEqual(preImage.preImage, "1")
XCTAssertEqual(preImage.signingKey, "2")
XCTAssertEqual(preImage.signatureAlgorithm, .secp256k1)
XCTAssertNil(preImage.descriptor)
let payloadJsonValue: JSONValue = .dictionary([
"version": .number(0),
"auth": .dictionary([
"authType": .number(4),
"spendingCondition": .dictionary([
"hashMode": .number(0),
"signer": .string("71cb17c2d7f5e2ba71fab0aa6172f02d7265ff14"),
"nonce": .string("0"),
"fee": .string("600"),
"keyEncoding": .number(0),
"signature": .dictionary([
"type": .number(9),
"data": .string("0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000")
])
])
]),
"payload": .dictionary([
"type": .number(8),
"payloadType": .number(0),
"recipient": .dictionary([
"type": .number(5),
"address": .dictionary([
"type": .number(0),
"version": .number(22),
"hash160": .string("afc896bb4b998cd40dd885b31d7446ef86b04eb0")
])
]),
"amount": .string("1"),
"memo": .dictionary([
"type": .number(3),
"content": .string("")
])
]),
"chainId": .number(1),
"postConditionMode": .number(2),
"postConditions": .dictionary([
"type": .number(7),
"lengthPrefixBytes": .number(4),
"values": .array([])
]),
"anchorMode": .number(3)
])
let rawTxJsonValue: JSONValue = .dictionary(
[
"version": .number(1),
"payload": payloadJsonValue
]
)
XCTAssertEqual(response.rawTx, rawTxJsonValue)
}
}
private let json = """
{
"summary": {
"relativeFee": "1",
"absoluteFeeMaximum": "2",
"absoluteFeeEstimate": "3",
"amount": "4",
"balance": "5"
},
"rawTx": {
"version": 1,
"payload": {
"version": 0,
"auth": {
"authType": 4,
"spendingCondition": {
"hashMode": 0,
"signer": "71cb17c2d7f5e2ba71fab0aa6172f02d7265ff14",
"nonce": "0",
"fee": "600",
"keyEncoding": 0,
"signature": {
"type": 9,
"data": "0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
}
}
},
"payload": {
"type": 8,
"payloadType": 0,
"recipient": {
"type": 5,
"address": {
"type": 0,
"version": 22,
"hash160": "afc896bb4b998cd40dd885b31d7446ef86b04eb0"
}
},
"amount": "1",
"memo": {
"type": 3,
"content": ""
}
},
"chainId": 1,
"postConditionMode": 2,
"postConditions": {
"type": 7,
"lengthPrefixBytes": 4,
"values": []
},
"anchorMode": 3
}
},
"preImages": [
{
"preImage": "1",
"signingKey": "2",
"descriptor": null,
"signatureAlgorithm": "secp256k1"
}
]
}
"""
| ac6b79630ad9679f792692cb98fd11ab | 32.25 | 173 | 0.456411 | false | false | false | false |
imod/VisualEffect_ios8 | refs/heads/master | VisualEffect_ios8/ViewController.swift | mit | 1 | //
// ViewController.swift
// VisualEffect_ios8
//
// Created by Dominik on 09/06/14.
// Copyright (c) 2014 Dominik. All rights reserved.
//
import UIKit
extension Array {
func each(callback: T -> ()) {
for item in self {
callback(item)
}
}
func eachWithIndex(callback: (T, Int) -> ()) {
var index = 0
for item in self {
callback(item, index)
index += 1
}
}
}
class CustomTableViewCell: UITableViewCell {
@IBOutlet var backgroundImage: UIImageView
@IBOutlet var titleLabel: UILabel
func loadItem(#title: String, image: String) {
backgroundImage.image = UIImage(named: image)
titleLabel.text = title
}
}
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet var tableView: UITableView
var items: (String, String)[] = [
("❤", "swift 1.jpeg"),
("We", "swift 2.jpeg"),
("❤", "swift 3.jpeg"),
("Swift", "swift 4.jpeg"),
("❤", "swift 5.jpeg")
]
func tableView(tableView: UITableView!, numberOfRowsInSection section: Int) -> Int {
return items.count
}
func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! {
var cell: CustomTableViewCell = self.tableView.dequeueReusableCellWithIdentifier("customCell") as CustomTableViewCell
var (title, image) = items[indexPath.row]
cell.loadItem(title: title, image: image)
return cell
}
func tableView(tableView: UITableView!, didSelectRowAtindexPath indexPath: NSIndexPath!) {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
println("you selected cell #\(indexPath.row)")
}
func addEffects() {
[
UIBlurEffectStyle.Light,
UIBlurEffectStyle.Dark,
UIBlurEffectStyle.ExtraLight
].map {
UIBlurEffect(style: $0)
}.eachWithIndex { (effect, index) in
var effectView = UIVisualEffectView(effect: effect)
effectView.frame = CGRectMake(0, CGFloat(50 * index), 320, 50)
self.view.addSubview(effectView)
}
}
override func viewDidLoad() {
super.viewDidLoad()
addEffects()
var nib = UINib(nibName: "CustomTableViewCell", bundle: nil)
tableView.registerNib(nib, forCellReuseIdentifier: "customCell")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| e3e5fdc0d5664e78c1200f43b12671e1 | 24.990476 | 125 | 0.594723 | false | false | false | false |
AnthonyMDev/AmazonS3RequestManager | refs/heads/develop | Carthage/Checkouts/Nimble/Sources/Nimble/Matchers/BeGreaterThan.swift | apache-2.0 | 64 | import Foundation
/// A Nimble matcher that succeeds when the actual value is greater than the expected value.
public func beGreaterThan<T: Comparable>(_ expectedValue: T?) -> Predicate<T> {
let errorMessage = "be greater than <\(stringify(expectedValue))>"
return Predicate.simple(errorMessage) { actualExpression in
if let actual = try actualExpression.evaluate(), let expected = expectedValue {
return PredicateStatus(bool: actual > expected)
}
return .fail
}
}
/// A Nimble matcher that succeeds when the actual value is greater than the expected value.
public func beGreaterThan(_ expectedValue: NMBComparable?) -> Predicate<NMBComparable> {
return Predicate.fromDeprecatedClosure { actualExpression, failureMessage in
failureMessage.postfixMessage = "be greater than <\(stringify(expectedValue))>"
let actualValue = try actualExpression.evaluate()
let matches = actualValue != nil
&& actualValue!.NMB_compare(expectedValue) == ComparisonResult.orderedDescending
return matches
}.requireNonNil
}
public func ><T: Comparable>(lhs: Expectation<T>, rhs: T) {
lhs.to(beGreaterThan(rhs))
}
public func > (lhs: Expectation<NMBComparable>, rhs: NMBComparable?) {
lhs.to(beGreaterThan(rhs))
}
#if os(macOS) || os(iOS) || os(tvOS) || os(watchOS)
extension NMBObjCMatcher {
@objc public class func beGreaterThanMatcher(_ expected: NMBComparable?) -> NMBObjCMatcher {
return NMBObjCMatcher(canMatchNil: false) { actualExpression, failureMessage in
let expr = actualExpression.cast { $0 as? NMBComparable }
return try! beGreaterThan(expected).matches(expr, failureMessage: failureMessage)
}
}
}
#endif
| 396fb7481897a92eb110b7f33bd1ab3d | 40.809524 | 96 | 0.705011 | false | false | false | false |
mike-wernli/six-scrum-poker | refs/heads/master | six-scrum-poker/ClassicViewController.swift | apache-2.0 | 1 | //
// ClassicViewController.swift
// six-scrum-poker
//
// Created by codecamp on 10.06.16.
// Copyright © 2016 six.codecamp16. All rights reserved.
//
import UIKit
class ClassicViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
let detailView = segue.destinationViewController as! ClassicDetailsViewController
NSLog("Segue is: " + segue.identifier!)
if segue.identifier == "showCardQuestion" {
detailView.labelCardText = "?"
//detailView.view.backgroundColor = UIColor(red: 0, green: 165/255, blue: 0, alpha: 1)
detailView.view.backgroundColor = UIColor.lightGrayColor()
NSLog("Pressed for Card ?")
} else if segue.identifier == "showCardCoffee" {
detailView.labelCardText = "☕️"
detailView.view.backgroundColor = UIColor.lightGrayColor()
NSLog("Pressed for Card coffee")
} else if segue.identifier == "showCard0" {
detailView.labelCardText = "0"
detailView.view.backgroundColor = UIColor.lightGrayColor()
NSLog("Pressed for Card 0")
} else if segue.identifier == "showCardHalf" {
detailView.labelCardText = "½"
detailView.view.backgroundColor = UIColor.lightGrayColor()
NSLog("Pressed for Card Half")
} else if segue.identifier == "showCard1" {
detailView.labelCardText = "1"
detailView.view.backgroundColor = UIColor.grayColor()
NSLog("Pressed for Card 1")
} else if segue.identifier == "showCard2" {
detailView.labelCardText = "2"
detailView.view.backgroundColor = UIColor.lightGrayColor().colorWithAlphaComponent(0.75)
NSLog("Pressed for Card 2")
} else if segue.identifier == "showCard3" {
detailView.labelCardText = "3"
detailView.view.backgroundColor = UIColor.greenColor().colorWithAlphaComponent(0.75)
NSLog("Pressed for Card 3")
} else if segue.identifier == "showCard5" {
detailView.labelCardText = "5"
detailView.view.backgroundColor = UIColor.yellowColor().colorWithAlphaComponent(0.75)
detailView.view.opaque = true
NSLog("Pressed for Card 5")
} else if segue.identifier == "showCard8" {
detailView.labelCardText = "8"
detailView.view.backgroundColor = UIColor.orangeColor()
detailView.labelPokerCard.textColor = UIColor.lightGrayColor()
NSLog("Pressed for Card 8")
} else if segue.identifier == "showCard13" {
detailView.labelCardText = "13"
detailView.view.backgroundColor = UIColor.blueColor().colorWithAlphaComponent(0.75)
NSLog("Pressed for Card 13")
} else if segue.identifier == "showCard20" {
detailView.labelCardText = "20"
detailView.view.backgroundColor = UIColor.redColor().colorWithAlphaComponent(0.75)
NSLog("Pressed for Card 20")
} else if segue.identifier == "showCard40" {
detailView.labelCardText = "40"
detailView.view.backgroundColor = UIColor.purpleColor().colorWithAlphaComponent(0.75)
NSLog("Pressed for Card 40")
} else if segue.identifier == "showCard100" {
detailView.labelCardText = "100"
detailView.view.backgroundColor = UIColor.brownColor().colorWithAlphaComponent(0.75)
detailView.labelPokerCard.hidden = true
detailView.labelPokerCardSmall.hidden = false
NSLog("Pressed for Card 100")
} else if segue.identifier == "showCardInfinity" {
detailView.labelCardText = "∞"
detailView.view.backgroundColor = UIColor.blackColor().colorWithAlphaComponent(0.75)
detailView.labelPokerCard.textColor = UIColor.whiteColor()
NSLog("Pressed for Card Infinity")
} else {
detailView.labelCardText = "na"
}
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| 9fe929d18878480a70f78a4c9f105454 | 38.669421 | 106 | 0.627083 | false | false | false | false |
MaTriXy/androidtool-mac | refs/heads/master | AndroidTool/DropReceiverView.swift | apache-2.0 | 1 | //
// DropReceiverView.swift
// Shellpad
//
// Created by Morten Just Petersen on 10/30/15.
// Copyright © 2015 Morten Just Petersen. All rights reserved.
//
import Cocoa
protocol DropDelegate {
func dropDragEntered(filePath:String)
func dropDragPerformed(filePath:String)
func dropDragExited()
func dropUpdated(mouseAt:NSPoint)
}
class DropReceiverView: NSView {
var delegate:DropDelegate?
var testVar = "only you can see this";
func removeBackgroundColor(){
layer?.backgroundColor = NSColor.clearColor().CGColor
}
func addBackgroundColor(){
layer?.backgroundColor = NSColor(red:0.267, green:0.251, blue:0.290, alpha:1).CGColor
}
func setup(){
wantsLayer = true
let fileTypes = [
"public.data"
]
registerForDraggedTypes(fileTypes);
}
//https://developer.apple.com/library/mac/documentation/Miscellaneous/Reference/UTIRef/Articles/System-DeclaredUniformTypeIdentifiers.html
override func draggingEntered(sender: NSDraggingInfo) -> NSDragOperation {
// Swift.print("HELLO \(getPathFromBoard(sender.draggingPasteboard()))")
let path = getPathFromBoard(sender.draggingPasteboard())
delegate?.dropDragEntered(path)
addBackgroundColor()
return NSDragOperation.Copy
}
override func performDragOperation(sender: NSDraggingInfo) -> Bool {
return true
}
override func draggingUpdated(sender: NSDraggingInfo) -> NSDragOperation {
delegate?.dropUpdated(sender.draggingLocation())
return NSDragOperation.Copy
}
override func draggingExited(sender: NSDraggingInfo?) {
removeBackgroundColor()
delegate?.dropDragExited()
}
override func concludeDragOperation(sender: NSDraggingInfo?) {
let path = getPathFromBoard((sender?.draggingPasteboard())!)
Swift.print("path is \(path)")
removeBackgroundColor()
delegate?.dropDragPerformed(path)
}
func getPathFromBoard(board:NSPasteboard) -> String {
let url = NSURL(fromPasteboard: board)
let path = url?.path!
return path!;
}
override init(frame frameRect: NSRect) {
super.init(frame: frameRect)
setup()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
setup()
}
override func drawRect(dirtyRect: NSRect) {
super.drawRect(dirtyRect)
// Drawing code here.
}
}
| 195a700f6601870252078d3a227bc58e | 27.252747 | 142 | 0.642552 | false | false | false | false |
mbcharbonneau/MonsterPit | refs/heads/master | Home Control/RoomSensorCell.swift | mit | 1 | //
// RoomSensorCell.swift
// Home Control
//
// Created by mbcharbonneau on 7/21/15.
// Copyright (c) 2015 Once Living LLC. All rights reserved.
//
import UIKit
class RoomSensorCell: UICollectionViewCell {
@IBOutlet weak private var nameLabel: UILabel?
@IBOutlet weak private var tempLabel: UILabel?
@IBOutlet weak private var humidityLabel: UILabel?
@IBOutlet weak private var lightLabel: UILabel?
@IBOutlet weak private var lastUpdatedLabel: UILabel?
private var lastUpdate: NSDate?
required init?(coder aDecoder: NSCoder) {
super.init(coder:aDecoder)
backgroundColor = Configuration.Colors.Red
layer.cornerRadius = 6.0
}
func configureWithSensor( sensor: RoomSensor ) {
nameLabel?.text = sensor.name
lastUpdate = sensor.updatedAt
if let degreesC = sensor.temperature {
let tempString = NSString( format:"%.1f", celsiusToFahrenheit( degreesC ) )
tempLabel?.text = "\(tempString) ℉"
} else {
tempLabel?.text = "-.- ℉"
}
if let humidity = sensor.humidity {
let humidityString = NSString( format:"%.0f", humidity * 100.0 )
humidityLabel?.text = "H: \(humidityString)%"
} else {
humidityLabel?.text = "H: -.-%"
}
if let light = sensor.light {
let lightString = NSString( format:"%.0f", luxToPercent( light ) * 100.0 )
lightLabel?.text = "L: \(lightString)%"
} else {
lightLabel?.text = "L: -.-%"
}
updateTimeLabel()
}
func updateTimeLabel() {
let formatter = NSDateComponentsFormatter()
formatter.unitsStyle = NSDateComponentsFormatterUnitsStyle.Short
formatter.includesApproximationPhrase = false
formatter.collapsesLargestUnit = false
formatter.maximumUnitCount = 1
formatter.allowedUnits = [.Hour, .Minute, .Second, .Day]
if let date = lastUpdate {
let string = formatter.stringFromDate( date, toDate:NSDate() )!
lastUpdatedLabel?.text = "Data is \(string) old"
} else {
lastUpdatedLabel?.text = ""
}
}
private func celsiusToFahrenheit( celsius: Double ) -> Double {
return celsius * 9 / 5 + 32
}
private func luxToPercent( lux: Double ) -> Double {
return min( lux / 60, 1.0 )
}
}
| 1bc300172b14a1fb6220a43be50533e4 | 29.777778 | 87 | 0.587244 | false | false | false | false |
NoryCao/zhuishushenqi | refs/heads/master | zhuishushenqi/Root/Controllers/ZSVoucherViewController.swift | mit | 1 | //
// ZSVoucherViewController.swift
// zhuishushenqi
//
// Created by caony on 2019/1/9.
// Copyright © 2019年 QS. All rights reserved.
//
import UIKit
import RxSwift
import RxCocoa
import MJRefresh
typealias ZSVoucherHandler = (_ indexPath:IndexPath)->Void
class ZSVoucherParentViewController: BaseViewController, ZSSegmentProtocol {
var segmentViewController = ZSSegmentViewController()
var segmentView:UISegmentedControl!
var headerView:UIView!
private var vcs:[UIViewController] = []
override func viewDidLoad() {
super.viewDidLoad()
setupSubviews()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
segmentViewController.scrollViewDidEndDeceleratingHandler = { index in
self.segmentView.selectedSegmentIndex = index
}
segmentViewController.view.frame = CGRect(x: 0, y: headerView.frame.maxY, width: self.view.bounds.width, height: self.view.bounds.height - headerView.frame.maxY)
}
func setupSubviews() {
headerView = UIView(frame: CGRect(x: 0, y: kNavgationBarHeight, width: self.view.bounds.width, height: 60))
headerView.backgroundColor = UIColor.white
segmentView = UISegmentedControl(frame: CGRect(x: 0, y: 20, width: self.view.bounds.width, height: 30))
segmentView.tintColor = UIColor.red
headerView.addSubview(segmentView)
view.addSubview(headerView)
var viewControllers:[UIViewController] = []
var titles = ["可使用","已用完","已过期"]
for i in 0..<3 {
let viewController = ZSVoucherViewController()
viewController.index = i
viewController.title = titles[i]
viewController.didSelectRowHandler = { indexPath in
}
viewControllers.append(viewController)
segmentView.insertSegment(withTitle: titles[i], at: i, animated: false)
}
vcs = viewControllers
segmentView.selectedSegmentIndex = 0
segmentView.addTarget(self, action: #selector(segmentTap), for: .valueChanged)
addChild(segmentViewController)
view.addSubview(segmentViewController.view)
}
func segmentViewControllers() -> [UIViewController] {
return vcs
}
@objc func segmentTap() {
let index = segmentView.selectedSegmentIndex
self.segmentViewController.didSelect(index: index)
}
}
class ZSVoucherViewController: ZSBaseTableViewController, Refreshable {
var index:Int = 0
var viewModel:ZSMyViewModel = ZSMyViewModel()
fileprivate let disposeBag = DisposeBag()
var headerRefresh:MJRefreshHeader?
var footerRefresh:MJRefreshFooter?
var start = 0
var limit = 20
var didSelectRowHandler:ZSVoucherHandler?
override func viewDidLoad() {
super.viewDidLoad()
setupSubviews()
}
func setupSubviews() {
let header = initRefreshHeader(tableView) {
self.start = 0
self.viewModel.fetchVoucher(token: ZSLogin.share.token, type: self.voucherType(), start: self.start, limit: self.limit, completion: { (voucherList) in
self.tableView.reloadData()
})
}
let footer = initRefreshFooter(tableView) {
self.start += self.limit
self.viewModel.fetchMoreVoucher(token: ZSLogin.share.token, type: self.voucherType(), start: self.start, limit: self.limit, completion: { (vouchers) in
self.tableView.reloadData()
})
}
headerRefresh = header
footerRefresh = footer
headerRefresh?.beginRefreshing()
viewModel
.autoSetRefreshHeaderStatus(header: header, footer: footer)
.disposed(by: disposeBag)
}
func vouchers() ->[ZSVoucher]? {
if index == 0 {
return viewModel.useableVoucher
} else if index == 1 {
return viewModel.unuseableVoucher
}
return viewModel.expiredVoucher
}
func voucherType()->String {
let types = ["useable","unuseable","expired"]
return types[index]
}
override func registerCellClasses() -> Array<AnyClass> {
return [ZSVoucherCell.self]
}
//MARK: - UITableView
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return vouchers()?.count ?? 0
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.qs_dequeueReusableCell(ZSVoucherCell.self)
if let voucherList = vouchers() {
cell?.titleText = "\(voucherList[indexPath.row].amount)"
cell?.rightText = "\(voucherList[indexPath.row].balance)"
cell?.titleDetailText = "\(voucherList[indexPath.row].expired.qs_subStr(to: 10))"
cell?.rightDetailText = voucherList[indexPath.row].from
}
return cell!
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 60
}
}
| b8616aacafa85a2a7361729e4c8824ba | 32.626582 | 169 | 0.639563 | false | false | false | false |
maxoly/PulsarKit | refs/heads/master | PulsarKit/PulsarKit/Sources/Sizes/CompositeSize.swift | mit | 1 | //
// CompositeSize.swift
// PulsarKit
//
// Created by Massimo Oliviero on 02/03/2018.
// Copyright © 2019 Nacoon. All rights reserved.
//
import UIKit
public struct CompositeSize: Sizeable {
let widthSize: Sizeable
let heightSize: Sizeable
public init(widthSize: Sizeable = AutolayoutSize(), heightSize: Sizeable = AutolayoutSize()) {
self.widthSize = widthSize
self.heightSize = heightSize
}
public func size<View: UIView>(for view: View, descriptor: Descriptor, model: AnyHashable, in container: UIScrollView, at indexPath: IndexPath) -> CGSize {
let width = widthSize.size(for: view, descriptor: descriptor, model: model, in: container, at: indexPath).width
let height = heightSize.size(for: view, descriptor: descriptor, model: model, in: container, at: indexPath).height
return CGSize(width: width, height: height)
}
}
| 99753596271f3bfa49bed0308b88093a | 35.4 | 159 | 0.69011 | false | false | false | false |
RocketChat/Rocket.Chat.iOS | refs/heads/develop | Rocket.Chat/Models/Mapping/MentionModelMapping.swift | mit | 1 | //
// MentionModelMapping.swift
// Rocket.Chat
//
// Created by Matheus Cardoso on 9/8/17.
// Copyright © 2017 Rocket.Chat. All rights reserved.
//
import Foundation
import SwiftyJSON
import RealmSwift
extension Mention: ModelMappeable {
func map(_ values: JSON, realm: Realm?) {
self.userId = values["_id"].string
self.username = values["username"].stringValue
if let realName = values["name"].string {
self.realName = realName
} else if let userId = userId {
if let realm = realm {
if let user = realm.object(ofType: User.self, forPrimaryKey: userId as AnyObject) {
self.realName = user.name ?? user.username ?? ""
} else {
self.realName = values["username"].stringValue
}
}
}
}
}
| 550c7bfc692ce8aa2b44180b93ecf785 | 28.689655 | 99 | 0.570267 | false | false | false | false |
BennyHarv3/habitica-ios | refs/heads/master | HabitRPG/UI/Login/LoginViewModel.swift | gpl-3.0 | 1 | //
// LoginViewModel.swift
// Habitica
//
// Created by Phillip Thelen on 25/12/2016.
// Copyright © 2016 Phillip Thelen. All rights reserved.
//
import ReactiveCocoa
import ReactiveSwift
import Result
import AppAuth
import Keys
import FBSDKLoginKit
enum LoginViewAuthType {
case login
case register
}
protocol LoginViewModelInputs {
func authTypeChanged()
func setAuthType(authType: LoginViewAuthType)
func emailChanged(email: String?)
func usernameChanged(username: String?)
func passwordChanged(password: String?)
func passwordDoneEditing()
func passwordRepeatChanged(passwordRepeat: String?)
func passwordRepeatDoneEditing()
func onePassword(isAvailable: Bool)
func onePasswordTapped()
func loginButtonPressed()
func googleLoginButtonPressed()
func facebookLoginButtonPressed()
func onSuccessfulLogin()
func setSharedManager(sharedManager: HRPGManager?)
func setViewController(viewController: LoginTableViewController)
}
protocol LoginViewModelOutputs {
var authTypeButtonTitle: Signal<String, NoError> { get }
var usernameFieldTitle: Signal<String, NoError> { get }
var loginButtonTitle: Signal<String, NoError> { get }
var isFormValid: Signal<Bool, NoError> { get }
var emailFieldVisibility: Signal<Bool, NoError> { get }
var passwordRepeatFieldVisibility: Signal<Bool, NoError> { get }
var passwordFieldReturnButtonIsDone: Signal<Bool, NoError> { get }
var passwordRepeatFieldReturnButtonIsDone: Signal<Bool, NoError> { get }
var onePasswordButtonHidden: Signal<Bool, NoError> { get }
var onePasswordFindLogin: Signal<(), NoError> { get }
var emailText: Signal<String, NoError> { get }
var usernameText: Signal<String, NoError> { get }
var passwordText: Signal<String, NoError> { get }
var passwordRepeatText: Signal<String, NoError> { get }
var showError: Signal<String, NoError> { get }
var showNextViewController: Signal<String, NoError> { get }
var loadingIndicatorVisibility: Signal<Bool, NoError> { get }
}
protocol LoginViewModelType {
var inputs: LoginViewModelInputs { get }
var outputs: LoginViewModelOutputs { get }
}
class LoginViewModel: LoginViewModelType, LoginViewModelInputs, LoginViewModelOutputs {
//swiftlint:disable function_body_length
init() {
let authValues = Signal.combineLatest(
self.authTypeProperty.signal.skipNil(),
Signal.merge(self.emailChangedProperty.signal, self.prefillEmailProperty.signal),
Signal.merge(self.usernameChangedProperty.signal, self.prefillUsernameProperty.signal),
Signal.merge(self.passwordChangedProperty.signal, self.prefillPasswordProperty.signal),
Signal.merge(self.passwordRepeatChangedProperty.signal, self.prefillPasswordRepeatProperty.signal)
)
self.authValuesProperty = Property(initial: nil, then: authValues.map { $0 })
self.authTypeButtonTitle = self.authTypeProperty.signal.skipNil().map { value in
switch value {
case .login:
return "Register".localized
case .register:
return "Login".localized
}
}
self.loginButtonTitle = self.authTypeProperty.signal.skipNil().map { value in
switch value {
case .login:
return "Login".localized
case .register:
return "Register".localized
}
}
self.usernameFieldTitle = self.authTypeProperty.signal.skipNil().map { value in
switch value {
case .login:
return "Email / Username".localized
case .register:
return "Username".localized
}
}
let isRegistering = self.authTypeProperty.signal.skipNil().map { value -> Bool in
switch value {
case .login:
return false
case .register:
return true
}
}
self.emailFieldVisibility = isRegistering
self.passwordRepeatFieldVisibility = isRegistering
self.passwordFieldReturnButtonIsDone = isRegistering.map({ value -> Bool in
return !value
})
self.passwordRepeatFieldReturnButtonIsDone = isRegistering.map({ value -> Bool in
return value
})
self.isFormValid = authValues.map(isValid)
self.emailChangedProperty.value = ""
self.usernameChangedProperty.value = ""
self.passwordChangedProperty.value = ""
self.passwordRepeatChangedProperty.value = ""
self.usernameText = self.prefillUsernameProperty.signal
self.emailText = self.prefillEmailProperty.signal
self.passwordText = self.prefillPasswordProperty.signal
self.passwordRepeatText = self.prefillPasswordRepeatProperty.signal
self.onePasswordButtonHidden = self.onePasswordAvailable.signal.map { value in
return !value
}
self.onePasswordFindLogin = self.onePasswordTappedProperty.signal
let (showNextViewControllerSignal, showNextViewControllerObserver) = Signal<(), NoError>.pipe()
self.showNextViewControllerObserver = showNextViewControllerObserver
self.showNextViewController = Signal.merge(
showNextViewControllerSignal,
self.onSuccessfulLoginProperty.signal
).combineLatest(with: self.authTypeProperty.signal)
.map({ (_, authType) -> String in
if authType == .login {
return "MainSegue"
} else {
return "SetupSegue"
}
})
(self.showError, self.showErrorObserver) = Signal.pipe()
(self.loadingIndicatorVisibility, self.loadingIndicatorVisibilityObserver) = Signal<Bool, NoError>.pipe()
}
func setDefaultValues() {
}
private let authTypeProperty = MutableProperty<LoginViewAuthType?>(nil)
internal func authTypeChanged() {
if authTypeProperty.value == LoginViewAuthType.login {
authTypeProperty.value = LoginViewAuthType.register
} else {
authTypeProperty.value = LoginViewAuthType.login
}
}
func setAuthType(authType: LoginViewAuthType) {
self.authTypeProperty.value = authType
}
private let emailChangedProperty = MutableProperty<String>("")
func emailChanged(email: String?) {
if email != nil {
self.emailChangedProperty.value = email ?? ""
}
}
private let usernameChangedProperty = MutableProperty<String>("")
func usernameChanged(username: String?) {
if username != nil {
self.usernameChangedProperty.value = username ?? ""
}
}
private let passwordChangedProperty = MutableProperty<String>("")
func passwordChanged(password: String?) {
if password != nil {
self.passwordChangedProperty.value = password ?? ""
}
}
private let passwordDoneEditingProperty = MutableProperty(())
func passwordDoneEditing() {
self.passwordDoneEditingProperty.value = ()
}
private let passwordRepeatChangedProperty = MutableProperty<String>("")
func passwordRepeatChanged(passwordRepeat: String?) {
if passwordRepeat != nil {
self.passwordRepeatChangedProperty.value = passwordRepeat ?? ""
}
}
private let passwordRepeatDoneEditingProperty = MutableProperty(())
func passwordRepeatDoneEditing() {
self.passwordRepeatDoneEditingProperty.value = ()
}
private let onePasswordAvailable = MutableProperty<Bool>(false)
func onePassword(isAvailable: Bool) {
self.onePasswordAvailable.value = isAvailable
}
private let onePasswordTappedProperty = MutableProperty(())
func onePasswordTapped() {
self.onePasswordTappedProperty.value = ()
}
private let prefillUsernameProperty = MutableProperty<String>("")
private let prefillEmailProperty = MutableProperty<String>("")
private let prefillPasswordProperty = MutableProperty<String>("")
private let prefillPasswordRepeatProperty = MutableProperty<String>("")
public func onePasswordFoundLogin(username: String, password: String) {
self.prefillUsernameProperty.value = username
self.prefillPasswordProperty.value = password
self.prefillPasswordRepeatProperty.value = password
}
//swiftlint:disable large_tuple
private let authValuesProperty: Property<(authType: LoginViewAuthType, email: String, username: String, password: String, passwordRepeat: String)?>
func loginButtonPressed() {
guard let (authType, email, username, password, passwordRepeat) = self.authValuesProperty.value else {
return
}
if isValid(authType: authType,
email: email,
username: username,
password: password,
passwordRepeat: passwordRepeat) {
self.loadingIndicatorVisibilityObserver.send(value: true)
if self.authTypeProperty.value == .login {
self.sharedManager?.loginUser(self.usernameChangedProperty.value, withPassword: self.passwordChangedProperty.value, onSuccess: {
self.onSuccessfulLogin()
}, onError: {
self.loadingIndicatorVisibilityObserver.send(value: false)
self.showErrorObserver.send(value: "Invalid username or password".localized)
})
} else {
self.sharedManager?.registerUser(self.usernameChangedProperty.value, withPassword: self.passwordChangedProperty.value, withEmail: self.emailChangedProperty.value, onSuccess: {
self.onSuccessfulLogin()
}, onError: {
self.loadingIndicatorVisibilityObserver.send(value: false)
})
}
}
}
private let googleLoginButtonPressedProperty = MutableProperty(())
func googleLoginButtonPressed() {
guard let authorizationEndpoint = URL(string: "https://accounts.google.com/o/oauth2/v2/auth") else {
return
}
guard let tokenEndpoint = URL(string: "https://www.googleapis.com/oauth2/v4/token") else {
return
}
let keys = HabiticaKeys()
guard let redirectUrl = URL(string: keys.googleRedirectUrl()) else {
return
}
let configuration = OIDServiceConfiguration(authorizationEndpoint: authorizationEndpoint, tokenEndpoint: tokenEndpoint)
let request = OIDAuthorizationRequest.init(configuration: configuration,
clientId: keys.googleClient(),
scopes: [OIDScopeOpenID, OIDScopeProfile],
redirectURL: redirectUrl,
responseType: OIDResponseTypeCode,
additionalParameters: nil)
// performs authentication request
if let appDelegate = UIApplication.shared.delegate as? HRPGAppDelegate {
guard let viewController = self.viewController else {
return
}
appDelegate.currentAuthorizationFlow = OIDAuthState.authState(byPresenting: request, presenting:viewController, callback: {[weak self] (authState, _) in
if authState != nil {
self?.sharedManager?.loginUserSocial("", withNetwork: "google", withAccessToken: authState?.lastTokenResponse?.accessToken, onSuccess: {
self?.onSuccessfulLogin()
}, onError: {
self?.showErrorObserver.send(value: "There was an error with the authentication. Try again later")
})
}
})
}
}
private let onSuccessfulLoginProperty = MutableProperty(())
func onSuccessfulLogin() {
self.sharedManager?.setCredentials()
self.sharedManager?.fetchUser({[weak self] _ in
self?.onSuccessfulLoginProperty.value = ()
}, onError: {[weak self] _ in
self?.onSuccessfulLoginProperty.value = ()
})
}
private let facebookLoginButtonPressedProperty = MutableProperty(())
func facebookLoginButtonPressed() {
let fbManager = FBSDKLoginManager()
fbManager.logIn(withReadPermissions: ["public_profile", "email"], from: viewController) { [weak self] (result, error) in
if error != nil || result?.isCancelled == true {
// If there is an error or the user cancelled login
} else if let userId = result?.token.userID, let token = result?.token.tokenString {
self?.sharedManager?.loginUserSocial(userId, withNetwork: "facebook", withAccessToken: token, onSuccess: {
self?.onSuccessfulLogin()
}, onError: {
self?.showErrorObserver.send(value: "There was an error with the authentication. Try again later")
})
}
}
}
private var sharedManager: HRPGManager?
func setSharedManager(sharedManager: HRPGManager?) {
self.sharedManager = sharedManager
}
private weak var viewController: LoginTableViewController?
func setViewController(viewController: LoginTableViewController) {
self.viewController = viewController
}
internal var authTypeButtonTitle: Signal<String, NoError>
internal var loginButtonTitle: Signal<String, NoError>
internal var usernameFieldTitle: Signal<String, NoError>
internal var isFormValid: Signal<Bool, NoError>
internal var emailFieldVisibility: Signal<Bool, NoError>
internal var passwordRepeatFieldVisibility: Signal<Bool, NoError>
internal var passwordFieldReturnButtonIsDone: Signal<Bool, NoError>
internal var passwordRepeatFieldReturnButtonIsDone: Signal<Bool, NoError>
internal var onePasswordButtonHidden: Signal<Bool, NoError>
internal var showError: Signal<String, NoError>
internal var showNextViewController: Signal<String, NoError>
internal var loadingIndicatorVisibility: Signal<Bool, NoError>
internal var onePasswordFindLogin: Signal<(), NoError>
internal var emailText: Signal<String, NoError>
internal var usernameText: Signal<String, NoError>
internal var passwordText: Signal<String, NoError>
internal var passwordRepeatText: Signal<String, NoError>
private var showNextViewControllerObserver: Observer<(), NoError>
private var showErrorObserver: Observer<String, NoError>
private var loadingIndicatorVisibilityObserver: Observer<Bool, NoError>
internal var inputs: LoginViewModelInputs { return self }
internal var outputs: LoginViewModelOutputs { return self }
}
func isValid(authType: LoginViewAuthType, email: String, username: String, password: String, passwordRepeat: String) -> Bool {
if username.characters.isEmpty || password.characters.isEmpty {
return false
}
if authType == .register {
if !isValidEmail(email: email) {
return false
}
if !password.characters.isEmpty && password != passwordRepeat {
return false
}
}
return true
}
func isValidEmail(email: String) -> Bool {
let emailRegEx = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}"
let emailTest = NSPredicate(format:"SELF MATCHES %@", emailRegEx)
return emailTest.evaluate(with: email)
}
| 294aa952acef5cc027d5a26e951547b2 | 38.0798 | 191 | 0.656244 | false | false | false | false |
davidbutz/ChristmasFamDuels | refs/heads/master | iOS/Boat Aware/registerControllerViewController.swift | mit | 1 | //
// registerControllerViewController.swift
// ChristmasFanDuel
//
// Created by Dave Butz on 1/10/16.
// Copyright © 2016 Dave Butz. All rights reserved.
//
import UIKit
class registerControllerViewController: UIViewController {
@IBOutlet weak var txtControllerName: UITextField!
@IBOutlet weak var btnRegister: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func btnRegisterClick(sender: AnyObject) {
//I should be connected to the Thrive Network. (192.168.41.1)
//A known IP address.
//I need to POST a response to /api/register/controller
//TODO: handle blank controllername
let appvar = ApplicationVariables.applicationvariables;
let controller_name = txtControllerName.text;
let JSONObject: [String : AnyObject] = [
"userid" : appvar.userid ,
"account_id" : appvar.account_id,
"fname" : appvar.fname,
"lname" : appvar.lname,
"password" : appvar.password,
"account_name" : appvar.account_name,
"username" : appvar.username,
"cellphone" : appvar.cellphone,
"controller_name" : controller_name!
]
let api = APICalls();
api.apicallout("/api/register/controller" , iptype: "thriveIPAddress", method: "POST", JSONObject: JSONObject, callback: { (response) -> () in
//handle the response. i should get status : fail/success and message: various
let status = (response as! NSDictionary)["status"] as! String;
let message = (response as! NSDictionary)["message"] as! String;
print(message);
if(status=="success"){
dispatch_async(dispatch_get_main_queue(),{
self.performSegueWithIdentifier("SetupSeq3New", sender: self);
});
}
else{
print(message);
}
});
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| 89889282516f15553fd6fb180ae0f973 | 34.256757 | 150 | 0.607129 | false | false | false | false |
SanctionCo/pilot-ios | refs/heads/master | pilot/LoginViewController.swift | mit | 1 | //
// LoginViewController.swift
// pilot
//
// Created by Nick Eckert on 7/24/17.
// Copyright © 2017 sanction. All rights reserved.
//
import Alamofire
import HTTPStatusCodes
import SwiftHash
import UIKit
class LoginViewController: UIViewController {
let authenticationHelper = AuthenticationHelper()
let profileImageView: UIImageView = {
let imageView = UIImageView()
imageView.image = UIImage(named: "ProfileImage")
imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.contentMode = .scaleAspectFit
return imageView
}()
let loginRegisterSegmentedControl: UISegmentedControl = {
let segmentedControl = UISegmentedControl(items: ["Login", "Register"])
segmentedControl.translatesAutoresizingMaskIntoConstraints = false
segmentedControl.tintColor = UIColor.white
segmentedControl.selectedSegmentIndex = 0
segmentedControl.addTarget(self, action: #selector(updateLoginRegisterView), for: .valueChanged)
return segmentedControl
}()
let inputsContainerView: UIView = {
let inputsView = UIView()
inputsView.backgroundColor = UIColor.white
inputsView.translatesAutoresizingMaskIntoConstraints = false
inputsView.layer.cornerRadius = 5
inputsView.layer.masksToBounds = true
return inputsView
}()
let emailTextField: UITextField = {
let textField = UITextField()
textField.placeholder = "Email"
textField.translatesAutoresizingMaskIntoConstraints = false
textField.autocapitalizationType = .none
textField.autocorrectionType = .no
return textField
}()
let passwordTextField: UITextField = {
let textField = UITextField()
textField.placeholder = "Password"
textField.translatesAutoresizingMaskIntoConstraints = false
textField.isSecureTextEntry = true
return textField
}()
let confirmPasswordTextField: UITextField = {
let textField = UITextField()
textField.placeholder = "Re-type Password"
textField.translatesAutoresizingMaskIntoConstraints = false
textField.isSecureTextEntry = true
return textField
}()
let emailSeparatorView: UIView = {
let view = UIView()
view.backgroundColor = UIColor.LayoutLightGray
view.translatesAutoresizingMaskIntoConstraints = false
return view
}()
let passwordSeparatorView: UIView = {
let view = UIView()
view.backgroundColor = UIColor.LayoutLightGray
view.translatesAutoresizingMaskIntoConstraints = false
return view
}()
let loginRegisterButton: UIButton = {
let button = UIButton(type: .system)
button.backgroundColor = UIColor.PilotDarkBlue
button.setTitle("Login", for: .normal)
button.setTitleColor(UIColor.TextWhite, for: .normal)
button.titleLabel?.font = UIFont.boldSystemFont(ofSize: 16)
button.translatesAutoresizingMaskIntoConstraints = false
button.layer.cornerRadius = 5
button.layer.masksToBounds = true
button.addTarget(self, action: #selector(handleButtonAction), for: .touchUpInside)
return button
}()
let activitySpinner: UIActivityIndicatorView = {
let spinner = UIActivityIndicatorView()
spinner.translatesAutoresizingMaskIntoConstraints = false
spinner.hidesWhenStopped = true
return spinner
}()
override func viewDidLoad() {
super.viewDidLoad()
navigationController?.navigationBar.isHidden = true
view.backgroundColor = UIColor.PilotLightBlue
view.addSubview(profileImageView)
view.addSubview(loginRegisterSegmentedControl)
view.addSubview(inputsContainerView)
view.addSubview(loginRegisterButton)
view.addSubview(activitySpinner)
setupProfileImageView()
setupLoginRegisterSegmentedControl()
setupInputsContainerView()
setupLoginRegisterButton()
setupActivitySpinner()
NetworkManager.sharedInstance.adapter = AuthAdapter()
attemptAutomaticLogin()
}
@objc private func handleButtonAction() {
if loginRegisterSegmentedControl.selectedSegmentIndex == 0 {
performTextLogin()
} else {
register()
}
}
private func attemptAutomaticLogin() {
self.fillFromKeychain()
// If this is the first login or the user has declined to set up Biometrics, we can't use biometrics
guard UserDefaults.standard.contains(key: "biometrics"),
UserDefaults.standard.bool(forKey: "biometrics") else {
return
}
// Otherwise, Biometrics should be enabled and we can prompt for authentication
authenticationHelper.authenticationWithBiometrics(onSuccess: {
DispatchQueue.main.async {
self.performBiometricLogin()
}
}, onFailure: { fallbackType, message in
// If failure is called with fallback type fallbackWithError, show an alert
if fallbackType == .fallbackWithError {
DispatchQueue.main.async {
let alert = UIAlertController(title: self.authenticationHelper.biometricType().rawValue + " Error",
message: message,
preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
self.present(alert, animated: true, completion: nil)
}
}
})
}
/// Perform a login that the user completed from biometrics
private func performBiometricLogin() {
if let (email, password) = authenticationHelper.getFromKeychain() {
login(email: email, password: password)
}
}
/// Perform a login that the user completed from the text boxes
private func performTextLogin() {
if let error = LoginValidationForm(email: emailTextField.text, password: passwordTextField.text).validate() {
let alert = UIAlertController(title: "Invalid Input", message: error.errorString, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
present(alert, animated: true, completion: nil)
return
}
let hashedPassword = MD5(passwordTextField.text!).lowercased()
authenticationHelper.saveToKeychain(email: emailTextField.text!, password: hashedPassword)
login(email: emailTextField.text!, password: hashedPassword)
}
/// Perform the login by getting the user from Thunder
private func login(email: String, password: String) {
self.activitySpinner.startAnimating()
self.loginRegisterButton.isEnabled = false
PilotUser.fetch(with: ThunderRouter.login(email, password), onSuccess: { pilotUser in
UserManager.sharedInstance = UserManager(pilotUser: pilotUser)
// Attempt to set up biometrics if this is the first time logging in
self.setUpBiometrics(completion: {
let homeTabBarController = HomeTabBarController()
// Set the platform list in the PlatformManager class
PlatformManager.sharedInstance.setPlatforms(platforms: pilotUser.availablePlatforms)
DispatchQueue.main.async { [weak self] in
self?.activitySpinner.stopAnimating()
self?.loginRegisterButton.isEnabled = true
self?.present(homeTabBarController, animated: true, completion: nil)
}
})
}, onError: { _ in
DispatchQueue.main.async { [weak self] in
self?.activitySpinner.stopAnimating()
self?.loginRegisterButton.isEnabled = true
}
})
}
/// Register a new user in Thunder
private func register() {
if let error = RegisterValidationForm(email: emailTextField.text,
password: passwordTextField.text,
confirmPassword: confirmPasswordTextField.text).validate() {
let alert = UIAlertController(title: "Invalid Input", message: error.errorString, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
present(alert, animated: true, completion: nil)
return
}
let hashedPassword = MD5(passwordTextField.text!).lowercased()
authenticationHelper.saveToKeychain(email: emailTextField.text!, password: hashedPassword)
self.activitySpinner.startAnimating()
self.loginRegisterButton.isEnabled = false
let pilotUser = PilotUser(email: emailTextField.text!, password: hashedPassword)
PilotUser.upload(with: ThunderRouter.createPilotUser(pilotUser), onSuccess: { _ in
DispatchQueue.main.async { [weak self] in
self?.activitySpinner.stopAnimating()
self?.loginRegisterButton.isEnabled = true
let alert = UIAlertController(title: "Account Created!", message: "", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { _ in
self?.loginRegisterSegmentedControl.selectedSegmentIndex = 0
self?.updateLoginRegisterView()
}))
self?.present(alert, animated: true, completion: nil)
}
}, onError: { _ in
DispatchQueue.main.async { [weak self] in
self?.activitySpinner.stopAnimating()
self?.loginRegisterButton.isEnabled = true
let alert = UIAlertController(title: "Registration Error",
message: "There was a problem creating your account",
preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
self?.present(alert, animated: true, completion: nil)
}
})
}
/// Prompt the user to set up biometrics for the first time
private func setUpBiometrics(completion: @escaping () -> Void) {
// Only set up if the user has not been asked before
guard !UserDefaults.standard.contains(key: "biometrics") else {
completion()
return
}
// Only set up if the user can use biometrics
guard authenticationHelper.canUseBiometrics() else {
completion()
return
}
let biometricType = self.authenticationHelper.biometricType().rawValue
let alert = UIAlertController(title: "Enable " + biometricType,
message: "Do you want to enable " + biometricType + " login?",
preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Yes", style: .default, handler: { _ in
UserDefaults.standard.set(true, forKey: "biometrics")
completion()
}))
alert.addAction(UIAlertAction(title: "No", style: .default, handler: { _ in
UserDefaults.standard.set(false, forKey: "biometrics")
completion()
}))
present(alert, animated: true, completion: nil)
}
/// Fill the email text field from the keychain
private func fillFromKeychain() {
if let (email, _) = authenticationHelper.getFromKeychain() {
emailTextField.text = email
}
}
@objc private func updateLoginRegisterView() {
// Change height of inputsContainerView
inputsContainerViewHeight?.constant = loginRegisterSegmentedControl.selectedSegmentIndex == 0 ? 80 : 120
// Change the height of the passwordSeperatorView
passwordSeperatorViewHeight?.isActive = false
passwordSeperatorViewHeight = passwordSeparatorView.heightAnchor
.constraint(equalToConstant: loginRegisterSegmentedControl.selectedSegmentIndex == 0 ? 0 : 1)
passwordSeperatorViewHeight?.isActive = true
// Change height of the confirmPasswordTextField
confirmPasswordTextFieldHeight?.isActive = false
confirmPasswordTextFieldHeight = confirmPasswordTextField.heightAnchor
.constraint(equalTo: inputsContainerView.heightAnchor,
multiplier: loginRegisterSegmentedControl.selectedSegmentIndex == 0 ? 0 : 1/3)
confirmPasswordTextFieldHeight?.isActive = true
// Change the height of the emailTextField
emailTextFieldHeight?.isActive = false
emailTextFieldHeight =
emailTextField.heightAnchor.constraint(equalTo: inputsContainerView.heightAnchor,
multiplier: loginRegisterSegmentedControl.selectedSegmentIndex == 0 ? 1/2 : 1/3)
emailTextFieldHeight?.isActive = true
// Change the height of the passwordTextField
passwordTextFieldHeight?.isActive = false
passwordTextFieldHeight = passwordTextField
.heightAnchor.constraint(equalTo: inputsContainerView.heightAnchor,
multiplier: loginRegisterSegmentedControl.selectedSegmentIndex == 0 ? 1/2 : 1/3)
passwordTextFieldHeight?.isActive = true
// Clear the second password field
confirmPasswordTextField.text = ""
// Rename button to "Register"
loginRegisterButton
.setTitle(loginRegisterSegmentedControl.selectedSegmentIndex == 0 ? "Login": "Register", for: .normal)
view.layoutIfNeeded()
}
private func setupProfileImageView() {
profileImageView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
profileImageView.widthAnchor.constraint(equalToConstant: 150).isActive = true
profileImageView.heightAnchor.constraint(equalTo: profileImageView.widthAnchor, multiplier: 21/50).isActive = true
profileImageView.bottomAnchor
.constraint(equalTo: loginRegisterSegmentedControl.topAnchor, constant: -50).isActive = true
}
private func setupLoginRegisterSegmentedControl() {
loginRegisterSegmentedControl.centerXAnchor.constraint(equalTo: profileImageView.centerXAnchor).isActive = true
loginRegisterSegmentedControl.widthAnchor.constraint(equalTo: inputsContainerView.widthAnchor).isActive = true
loginRegisterSegmentedControl.heightAnchor.constraint(equalToConstant: 36).isActive = true
loginRegisterSegmentedControl.bottomAnchor
.constraint(equalTo: inputsContainerView.topAnchor, constant: -12).isActive = true
}
var inputsContainerViewHeight: NSLayoutConstraint?
var emailTextFieldHeight: NSLayoutConstraint?
var passwordTextFieldHeight: NSLayoutConstraint?
var passwordSeperatorViewHeight: NSLayoutConstraint?
var confirmPasswordTextFieldHeight: NSLayoutConstraint?
private func setupInputsContainerView() {
// Add the subviews to the inputsContainerView
inputsContainerView.addSubview(emailTextField)
inputsContainerView.addSubview(passwordTextField)
inputsContainerView.addSubview(confirmPasswordTextField)
inputsContainerView.addSubview(passwordSeparatorView)
inputsContainerView.addSubview(emailSeparatorView)
// Add constraints to the inputsContainerView
inputsContainerView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
inputsContainerView.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
inputsContainerView.widthAnchor.constraint(equalTo: view.widthAnchor, constant: -25).isActive = true
inputsContainerViewHeight = inputsContainerView.heightAnchor.constraint(equalToConstant: 80)
inputsContainerViewHeight?.isActive = true
// Add constraints to the emailTextField
emailTextField.leftAnchor.constraint(equalTo: inputsContainerView.leftAnchor, constant: 12).isActive = true
emailTextField.topAnchor.constraint(equalTo: inputsContainerView.topAnchor).isActive = true
emailTextField.widthAnchor.constraint(equalTo: inputsContainerView.widthAnchor).isActive = true
emailTextFieldHeight =
emailTextField.heightAnchor.constraint(equalTo: inputsContainerView.heightAnchor, multiplier: 1/2)
emailTextFieldHeight?.isActive = true
// Add constraints to the emailSeperatorView
emailSeparatorView.leftAnchor.constraint(equalTo: inputsContainerView.leftAnchor).isActive = true
emailSeparatorView.topAnchor.constraint(equalTo: emailTextField.bottomAnchor).isActive = true
emailSeparatorView.widthAnchor.constraint(equalTo: inputsContainerView.widthAnchor).isActive = true
emailSeparatorView.heightAnchor.constraint(equalToConstant: 1).isActive = true
// Add constraints to the passwordTextField
passwordTextField.leftAnchor.constraint(equalTo: inputsContainerView.leftAnchor, constant: 12).isActive = true
passwordTextField.topAnchor.constraint(equalTo: emailSeparatorView.bottomAnchor).isActive = true
passwordTextField.widthAnchor.constraint(equalTo: inputsContainerView.widthAnchor).isActive = true
passwordTextFieldHeight =
passwordTextField.heightAnchor.constraint(equalTo: inputsContainerView.heightAnchor, multiplier: 1/2)
passwordTextFieldHeight?.isActive = true
// Add constraints to passwordSeperatorView
passwordSeparatorView.leftAnchor.constraint(equalTo: inputsContainerView.leftAnchor).isActive = true
passwordSeparatorView.topAnchor.constraint(equalTo: passwordTextField.bottomAnchor).isActive = true
passwordSeparatorView.widthAnchor.constraint(equalTo: inputsContainerView.widthAnchor).isActive = true
passwordSeperatorViewHeight = passwordSeparatorView.heightAnchor.constraint(equalToConstant: 0)
passwordSeperatorViewHeight?.isActive = true
// Add constraints to confirmPasswordTextField
confirmPasswordTextField
.leftAnchor.constraint(equalTo: inputsContainerView.leftAnchor, constant: 12).isActive = true
confirmPasswordTextField.topAnchor.constraint(equalTo: passwordSeparatorView.bottomAnchor).isActive = true
confirmPasswordTextField.widthAnchor.constraint(equalTo: inputsContainerView.widthAnchor).isActive = true
confirmPasswordTextFieldHeight =
confirmPasswordTextField.heightAnchor.constraint(equalTo: inputsContainerView.heightAnchor, multiplier: 0)
confirmPasswordTextFieldHeight?.isActive = true
}
private func setupLoginRegisterButton() {
loginRegisterButton.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
loginRegisterButton.topAnchor.constraint(equalTo: inputsContainerView.bottomAnchor, constant: 12).isActive = true
loginRegisterButton.widthAnchor.constraint(equalTo: inputsContainerView.widthAnchor).isActive = true
loginRegisterButton.heightAnchor.constraint(equalToConstant: 32).isActive = true
}
private func setupActivitySpinner() {
activitySpinner.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
activitySpinner.topAnchor.constraint(equalTo: loginRegisterButton.bottomAnchor, constant: 20).isActive = true
activitySpinner.widthAnchor.constraint(equalToConstant: 10).isActive = true
activitySpinner.heightAnchor.constraint(equalToConstant: 10).isActive = true
}
}
| 33232fba7c74adf853872abb71293f69 | 40.775744 | 118 | 0.740359 | false | false | false | false |
M2Mobi/Marky-Mark | refs/heads/master | markymark/Classes/Layout Builders/UIView/Block Builders/Block/QuoteBlockLayoutBuilder.swift | mit | 1 | //
// Created by Jim van Zummeren on 11/05/16.
// Copyright © 2016 M2mobi. All rights reserved.
//
import Foundation
import UIKit
class QuoteBlockLayoutBuilder: InlineAttributedStringViewLayoutBlockBuilder {
// MARK: LayoutBuilder
override func relatedMarkDownItemType() -> MarkDownItem.Type {
return QuoteMarkDownItem.self
}
override func build(_ markDownItem: MarkDownItem, asPartOfConverter converter: MarkDownConverter<UIView>, styling: ItemStyling) -> UIView {
let label = AttributedInteractiveLabel()
label.markDownAttributedString = attributedStringForMarkDownItem(markDownItem, styling: styling)
if let urlOpener = urlOpener {
label.urlOpener = urlOpener
}
let spacing: UIEdgeInsets? = (styling as? ContentInsetStylingRule)?.contentInsets
return ContainerView(view: label, spacing: spacing)
}
}
| 9b080390bdfd626e34461ae11f3eb68a | 31.142857 | 143 | 0.722222 | false | false | false | false |
mlibai/XZKit | refs/heads/master | XZKit/Code/UICollectionViewFlowLayout/XZCollectionViewFlowLayout.swift | mit | 1 | //
// CollectionViewFlowLayout.swift
// XZKit
//
// Created by Xezun on 2018/7/10.
// Copyright © 2018年 XEZUN INC.com All rights reserved.
//
import UIKit
@available(*, unavailable, renamed: "XZKit.UICollectionViewDelegateFlowLayout")
typealias CollectionViewDelegateFlowLayout = XZKit.UICollectionViewDelegateFlowLayout
@available(*, unavailable, renamed: "XZKit.UICollectionViewFlowLayout")
typealias CollectionViewFlowLayout = XZKit.UICollectionViewFlowLayout
/// 通过本协议,可以具体的控制 XZKit.UICollectionViewFlowLayout 布局的 LineAlignment、InteritemAlignment 等内容。
@objc(XZCollectionViewDelegateFlowLayout)
public protocol UICollectionViewDelegateFlowLayout: UIKit.UICollectionViewDelegateFlowLayout {
/// 当 XZKit.UICollectionViewFlowLayout 计算元素布局时,通过此代理方法,获取指定行的对齐方式。
///
/// - Parameters:
/// - collectionView: UICollectionView 视图。
/// - collectionViewLayout: UICollectionViewLayout 视图布局对象。
/// - indexPath: 行的布局信息,包括行所在的区 section、行在区中的次序 line 。
/// - Returns: 行对齐方式。
@objc optional func collectionView(_ collectionView: UIKit.UICollectionView, layout collectionViewLayout: UIKit.UICollectionViewLayout, lineAlignmentForLineAt indexPath: XZKit.UICollectionViewIndexPath) -> XZKit.UICollectionViewFlowLayout.LineAlignment
/// 获取同一行元素间的对齐方式:垂直滚动时,为同一横排元素在垂直方向上的对齐方式;水平滚动时,同一竖排元素,在水平方向的对齐方式。
///
/// - Parameters:
/// - collectionView: UICollectionView 视图。
/// - collectionViewLayout: UICollectionViewLayout 视图布局对象。
/// - indexPath: 元素的布局信息,包括元素所在的区 section、在区中的次序 item、所在的行 line、在行中的次序 column 。
/// - Returns: 元素对齐方式。
@objc optional func collectionView(_ collectionView: UIKit.UICollectionView, layout collectionViewLayout: UIKit.UICollectionViewLayout, interitemAlignmentForItemAt indexPath: XZKit.UICollectionViewIndexPath) -> XZKit.UICollectionViewFlowLayout.InteritemAlignment
/// 获取 section 的内边距,与原生的方法不同,本方法返回的为自适应布局方向的 XZKit.EdgeInsets 结构体。
///
/// - Parameters:
/// - collectionView: UICollectionView 视图。
/// - collectionViewLayout: UICollectionViewLayout 视图布局对象。
/// - section: 指定的 section 序数。
/// - Returns: 内边距。
@objc optional func collectionView(_ collectionView: UIKit.UICollectionView, layout collectionViewLayout: UIKit.UICollectionViewLayout, edgeInsetsForSectionAt section: Int) -> EdgeInsets
}
extension UICollectionViewFlowLayout {
/// LineAlignment 描述了每行内元素的排列方式。
/// 当滚动方向为垂直方向时,水平方向上为一行,那么 LineAlignment 可以表述为向左对齐、向右对齐等;
/// 当滚动方向为水平时,垂直方向为一行,那么 LineAlignment 可以表述为向上对齐、向下对齐。
@objc(XZCollectionViewFlowLayoutLineAlignment)
public enum LineAlignment: Int, CustomStringConvertible {
/// 向首端对齐,末端不足留空。
/// - Note: 首端对齐与布局方向相关,例如 A、B、C 三元素在同一行,自左向右布局 [ A B C _ ],自右向左则为 [ _ C B A ] 。
case leading
/// 向末端对齐,首端不足留空。
/// - Note: 末端对齐与布局方向相关,例如 A、B、C 三元素在同一行,自左向右布局 [ _ A B C ],自右向左则为 [ C B A _ ] 。
case trailing
/// 居中对齐,两端可能留空。
case center
/// 两端对齐,平均分布,占满整行;如果行只有一个元素,该元素首端对齐。
/// - Note: 每行的元素间距可能都不一样。
case justified
/// 两端对齐,平均分布,占满整行,如果行只有一个元素,该元素居中对齐。
/// - Note: 每行的元素间距可能都不一样。
case justifiedCenter
/// 两端对齐,平均分布,占满整行,如果行只有一个元素,该元素末端对齐。
/// - Note: 每行的元素间距可能都不一样。
case justifiedTrailing
public var description: String {
switch self {
case .leading: return "leading"
case .trailing: return "trailing"
case .center: return "center"
case .justified: return "justified"
case .justifiedCenter: return "justifiedCenter"
case .justifiedTrailing: return "justifiedTrailing"
}
}
}
/// 同一行元素与元素的对齐方式。
@objc(XZCollectionViewFlowLayoutInteritemAlignment)
public enum InteritemAlignment: Int, CustomStringConvertible {
/// 垂直滚动时,顶部对齐;水平滚动时,布局方向从左到右,左对齐,布局方向从右到左,右对齐。
case ascender
/// 垂直滚动时,水平中线对齐;水平滚动时,垂直中线对齐。
case median
/// 垂直滚动时,底部对齐;水平滚动时,布局方向从左到右,右对齐,布局方向从右到左,左对齐。
case descender
public var description: String {
switch self {
case .ascender: return "ascender"
case .median: return "median"
case .descender: return "descender"
}
}
}
fileprivate class SectionItem {
let header: XZKit.UICollectionViewLayoutAttributes?
let items: [XZKit.UICollectionViewLayoutAttributes]
let footer: XZKit.UICollectionViewLayoutAttributes?
init(header: XZKit.UICollectionViewLayoutAttributes?, items: [XZKit.UICollectionViewLayoutAttributes], footer: XZKit.UICollectionViewLayoutAttributes?, frame: CGRect) {
self.header = header
self.items = items
self.footer = footer
self.frame = frame
}
/// Section 的 frame ,用于优化性能。
let frame: CGRect
}
}
/// XZKit.UICollectionViewFlowLayout 布局属性,记录了 Cell 所在行列的信息。
@objc(XZCollectionViewLayoutAttributes)
open class UICollectionViewLayoutAttributes: UIKit.UICollectionViewLayoutAttributes, UICollectionViewIndexPath {
public var item: Int {
return indexPath.item
}
public var section: Int {
return indexPath.section
}
public fileprivate(set) var line: Int = 0
public fileprivate(set) var column: Int = 0
}
/// 支持多种对齐方式的 UICollectionView 自定义布局,为了区分于 UIKit.UICollectionViewFlowLayout ,引用需加 XZKit 前缀。
/// - Note: 优先使用 XZKit.UICollectionViewDelegateFlowLayout 作为代理协议,并兼容 UIKit.UICollectionViewDelegateFlowLayout 协议。
/// - Note: 对于 zIndex 进行了特殊处理,排序越后的视图 zIndex 越大;Header/Footer 的 zIndex 比 Cell 的大。
@objc(XZCollectionViewFlowLayout)
open class UICollectionViewFlowLayout: UIKit.UICollectionViewLayout {
/// 滚动方向。默认 .vertical 。
@objc open var scrollDirection: UIKit.UICollectionView.ScrollDirection = .vertical {
didSet { invalidateLayout() }
}
/// 行间距。滚动方向为垂直时,水平方向为一行;滚动方向为水平时,垂直方向为一行。默认 0 ,代理方法的返回值优先。
@objc open var minimumLineSpacing: CGFloat = 0 {
didSet { invalidateLayout() }
}
/// 内间距。同一行内两个元素之间的距离。默认 0 ,代理方法的返回值优先。
@objc open var minimumInteritemSpacing: CGFloat = 0 {
didSet { invalidateLayout() }
}
/// 元素大小。默认 (50, 50),代理方法返回的大小优先。
@objc open var itemSize: CGSize = CGSize.init(width: 50, height: 50) {
didSet { invalidateLayout() }
}
/// SectionHeader 大小,默认 0 ,代理方法的返回值优先。
@objc open var headerReferenceSize: CGSize = .zero {
didSet { invalidateLayout() }
}
/// SectionFooter 大小,默认 0 ,代理方法的返回值优先。
@objc open var footerReferenceSize: CGSize = .zero {
didSet { invalidateLayout() }
}
/// SectionItem 外边距。不包括 SectionHeader/SectionFooter 。默认 .zero ,代理方法的返回值优先。
@objc open var sectionInsets: EdgeInsets = .zero {
didSet { invalidateLayout() }
}
/// 行对齐方式,默认 .leading ,代理方法的返回值优先。
@objc open var lineAlignment: LineAlignment = .justified {
didSet { invalidateLayout() }
}
/// 元素对齐方式,默认 .median ,代理方法的返回值优先。
@objc open var interitemAlignment: InteritemAlignment = .median {
didSet { invalidateLayout() }
}
/// 记录了所有元素信息。
fileprivate var sectionItems = [SectionItem]()
/// 记录了 contentSize 。
fileprivate var contentSize = CGSize.zero
}
extension UICollectionViewFlowLayout {
open override class var layoutAttributesClass: Swift.AnyClass {
return XZKit.UICollectionViewLayoutAttributes.self
}
open override var collectionViewContentSize: CGSize {
return contentSize
}
open override func invalidateLayout() {
super.invalidateLayout()
sectionItems.removeAll()
}
/// 当 UICollectionView 的宽度改变时,需重新计算布局。
///
/// - Parameter newBounds: The collectionView's new bounds.
/// - Returns: true or false.
open override func shouldInvalidateLayout(forBoundsChange newBounds: CGRect) -> Bool {
switch scrollDirection {
case .vertical:
return (newBounds.width != contentSize.width)
case .horizontal:
return (newBounds.height != contentSize.height)
default:
return false
}
}
private func adjustedContentInset(_ collectionView: UIKit.UICollectionView) -> UIEdgeInsets {
if #available(iOS 11.0, *) {
// iOS 11 以后,导航栏的高度,安全边距合并到这个属性了。
return collectionView.adjustedContentInset
} else {
// iOS 11 之前,导航栏的高度是加入到这个属性里的。
return collectionView.contentInset
}
}
override open func prepare() {
guard let collectionView = self.collectionView else { return }
let delegate = collectionView.delegate as? UIKit.UICollectionViewDelegateFlowLayout
let frame = collectionView.frame
let adjustedContentInset = self.adjustedContentInset(collectionView)
// 使用 (0, 0) 作为起始坐标进行计算,根据 adjustedContentInset 来计算内容区域大小。
switch self.scrollDirection {
case .horizontal:
contentSize = CGSize.init(width: 0, height: frame.height - adjustedContentInset.top - adjustedContentInset.bottom)
for section in 0 ..< collectionView.numberOfSections {
let x = contentSize.width
let headerAttributes = self.prepareHorizontal(collectionView, delegate: delegate, layoutAttributesForHeaderInSection: section)
let itemAttributes = self.prepareHorizontal(collectionView, delegate: delegate, layoutAttributesForItemsInSection: section)
let footerAttributes = self.prepareHorizontal(collectionView, delegate: delegate, layoutAttributesForFooterInSection: section)
headerAttributes?.zIndex = itemAttributes.count + section
footerAttributes?.zIndex = itemAttributes.count + section
let frame = CGRect.init(x: x, y: 0, width: contentSize.width - x, height: contentSize.height)
self.sectionItems.append(SectionItem.init(header: headerAttributes, items: itemAttributes, footer: footerAttributes, frame: frame))
}
case .vertical: fallthrough
default:
contentSize = CGSize.init(width: frame.width - adjustedContentInset.left - adjustedContentInset.right, height: 0)
for section in 0 ..< collectionView.numberOfSections {
let y = contentSize.height
let headerAttributes = self.prepareVertical(collectionView, delegate: delegate, layoutAttributesForHeaderInSection: section)
let itemAttributes = self.prepareVertical(collectionView, delegate: delegate, layoutAttributesForItemsInSection: section)
let footerAttributes = self.prepareVertical(collectionView, delegate: delegate, layoutAttributesForFooterInSection: section)
// 同一 Section 的 Header/Footer 具有相同的 zIndex 并且越靠后越大,保证后面的 SectionHeader/Footer 在前面的之上。
// 同时,Header/Footer 的 zIndex 比 Cell 的 zIndex 都大,Cell 也是索引越大 zIndex 越大。
headerAttributes?.zIndex = itemAttributes.count + section
footerAttributes?.zIndex = itemAttributes.count + section
let frame = CGRect.init(x: 0, y: y, width: contentSize.width, height: contentSize.height - y)
self.sectionItems.append(SectionItem.init(header: headerAttributes, items: itemAttributes, footer: footerAttributes, frame: frame))
}
}
}
override open func layoutAttributesForElements(in rect: CGRect) -> [UIKit.UICollectionViewLayoutAttributes]? {
// 超出范围肯定没有了。
if rect.maxX <= 0 || rect.minX >= contentSize.width || rect.minY >= contentSize.height || rect.maxY <= 0 {
return nil
}
// 如果当前已有找到在 rect 范围内的,那么如果遍历时,又遇到不在 rect 内的,说明已经超出屏幕,没有必要继续遍历了。
// 由于对齐方式的不同,Cell可能与指定区域没有交集,但是其后面的 Cell 却可能在该区域内。
var array = [UICollectionViewLayoutAttributes]()
// 遍历所有 Cell 布局。
for sectionItem in self.sectionItems {
guard rect.intersects(sectionItem.frame) else {
continue
}
if let header = sectionItem.header {
if rect.intersects(header.frame) {
array.append(header)
}
}
for item in sectionItem.items {
if rect.intersects(item.frame) {
array.append(item)
}
}
if let footer = sectionItem.footer {
if rect.intersects(footer.frame) {
array.append(footer)
}
}
}
return array
}
override open func layoutAttributesForItem(at indexPath: Foundation.IndexPath) -> UIKit.UICollectionViewLayoutAttributes? {
return sectionItems[indexPath.section].items[indexPath.item]
}
override open func layoutAttributesForSupplementaryView(ofKind elementKind: String, at indexPath: Foundation.IndexPath) -> UIKit.UICollectionViewLayoutAttributes? {
switch elementKind {
case UIKit.UICollectionView.elementKindSectionHeader: return sectionItems[indexPath.section].header
case UIKit.UICollectionView.elementKindSectionFooter: return sectionItems[indexPath.section].footer
default: fatalError("Not supported UICollectionElementKind `\(elementKind)`.")
}
}
/// Returns .leftToRight.
open override var developmentLayoutDirection: UIUserInterfaceLayoutDirection {
return .leftToRight
}
/// Retruns true.
open override var flipsHorizontallyInOppositeLayoutDirection: Bool {
return true
}
}
extension UICollectionViewFlowLayout {
/// 准备指定 Section 的 Header 布局信息。
@objc open func prepareVertical(_ collectionView: UIKit.UICollectionView, delegate: UIKit.UICollectionViewDelegateFlowLayout?, layoutAttributesForHeaderInSection section: Int) -> XZKit.UICollectionViewLayoutAttributes? {
let headerSize = delegate?.collectionView?(collectionView, layout: self, referenceSizeForHeaderInSection: section) ?? self.headerReferenceSize
guard headerSize != .zero else {
return nil
}
let headerAttributes = XZKit.UICollectionViewLayoutAttributes.init(
forSupplementaryViewOfKind: UIKit.UICollectionView.elementKindSectionHeader,
with: Foundation.IndexPath.init(item: 0, section: section)
)
headerAttributes.frame = CGRect.init(
// SectionHeader 水平居中
x: (contentSize.width - headerSize.width) * 0.5,
y: contentSize.height,
width: headerSize.width,
height: headerSize.height
)
contentSize.height += headerSize.height
return headerAttributes
}
/// 准备指定 Section 的 Footer 布局信息。
@objc open func prepareVertical(_ collectionView: UIKit.UICollectionView, delegate: UIKit.UICollectionViewDelegateFlowLayout?, layoutAttributesForFooterInSection section: Int) -> XZKit.UICollectionViewLayoutAttributes? {
let footerSize = delegate?.collectionView?(collectionView, layout: self, referenceSizeForFooterInSection: section) ?? self.footerReferenceSize
guard footerSize != .zero else {
return nil
}
let footerAttributes = XZKit.UICollectionViewLayoutAttributes.init(
forSupplementaryViewOfKind: UIKit.UICollectionView.elementKindSectionFooter,
with: Foundation.IndexPath.init(item: 0, section: section)
)
footerAttributes.frame = CGRect.init(
x: (contentSize.width - footerSize.width) * 0.5,
y: contentSize.height,
width: footerSize.width,
height: footerSize.height
)
contentSize.height += footerSize.height
return footerAttributes
}
/// 获取行对齐方式。
@objc open func collectionView(_ collectionView: UIKit.UICollectionView, lineAlignmentForLineAt indexPath: XZKit.UICollectionViewIndexPath, delegate: UIKit.UICollectionViewDelegateFlowLayout?) -> LineAlignment {
guard let delegate = delegate as? UICollectionViewDelegateFlowLayout else { return self.lineAlignment }
guard let lineAlignment = delegate.collectionView?(collectionView, layout: self, lineAlignmentForLineAt: indexPath) else { return self.lineAlignment }
return lineAlignment
}
/// 获取元素对齐方式。
@objc open func collectionView(_ collectionView: UIKit.UICollectionView, interitemAlignmentForItemAt indexPath: UICollectionViewIndexPath, delegate: UIKit.UICollectionViewDelegateFlowLayout?) -> InteritemAlignment {
guard let delegate = delegate as? UICollectionViewDelegateFlowLayout else { return self.interitemAlignment }
guard let interitemAlignment = delegate.collectionView?(collectionView, layout: self, interitemAlignmentForItemAt: indexPath) else { return self.interitemAlignment }
return interitemAlignment
}
@objc open func collectionView(_ collectionView: UIKit.UICollectionView, edgeInsetsForSectionAt section: Int, delegate: UIKit.UICollectionViewDelegateFlowLayout?) -> EdgeInsets {
if let delegate = delegate as? UICollectionViewDelegateFlowLayout {
if let edgeInsets = delegate.collectionView?(collectionView, layout: self, edgeInsetsForSectionAt: section) {
return edgeInsets
}
}
if let edgeInsets = delegate?.collectionView?(collectionView, layout: self, insetForSectionAt: section) {
return EdgeInsets.init(edgeInsets, layoutDirection: collectionView.userInterfaceLayoutDirection)
}
return self.sectionInsets
}
@objc open func collectionView(_ collectionView: UIKit.UICollectionView, sizeForItemAt indexPath: IndexPath, delegate: UIKit.UICollectionViewDelegateFlowLayout?) -> CGSize {
guard let delegate = delegate as? UICollectionViewDelegateFlowLayout else { return self.itemSize }
guard let itemSize = delegate.collectionView?(collectionView, layout: self, sizeForItemAt: indexPath) else { return self.itemSize }
return itemSize
}
/// 准备指定 Section 的 Cell 布局信息。
@objc open func prepareVertical(_ collectionView: UIKit.UICollectionView, delegate: UIKit.UICollectionViewDelegateFlowLayout?, layoutAttributesForItemsInSection section: Int) -> [XZKit.UICollectionViewLayoutAttributes] {
let sectionInsets = self.collectionView(collectionView, edgeInsetsForSectionAt: section, delegate: delegate)
contentSize.height += sectionInsets.top
let minimumLineSpacing = delegate?.collectionView?(collectionView, layout: self, minimumLineSpacingForSectionAt: section) ?? self.minimumLineSpacing
let minimumInteritemSpacing = delegate?.collectionView?(collectionView, layout: self, minimumInteritemSpacingForSectionAt: section) ?? self.minimumInteritemSpacing
var sectionAttributes = [XZKit.UICollectionViewLayoutAttributes]()
// 行最大宽度。
let maxLineLength: CGFloat = contentSize.width - sectionInsets.leading - sectionInsets.trailing
// Section 高度,仅内容区域,不包括 header、footer 和内边距。
// 初始值扣除一个间距,方便使用 间距 + 行高度 来计算高度。
// 每计算完一行,增加此值,并在最终增加到 contentSize 中。
var sectionHeight: CGFloat = -minimumLineSpacing
// 当前正在计算的行的宽度,新行开始后此值会被初始化。
// 初始值扣除一个间距,方便使用 间距 + 宽度 来计算总宽度。
var currentLineLength: CGFloat = -minimumInteritemSpacing
// 行最大高度。以行中最高的 Item 为行高度。
var currentLineHeight: CGFloat = 0
/// 保存了一行的 Cell 的布局信息。
var currentLineAttributes = [XZKit.UICollectionViewLayoutAttributes]()
/// 当一行的布局信息获取完毕时,从当前上下文中添加行布局信息,并重置上下文变量。
func addLineAttributesFromCurrentContext() {
var length: CGFloat = 0
let lineLayoutInfo = self.collectionView(collectionView, lineLayoutForLineWith: currentLineAttributes, maxLineLength: maxLineLength, lineLength: currentLineLength, minimumInteritemSpacing: minimumInteritemSpacing, delegate: delegate)
for column in 0 ..< currentLineAttributes.count {
let itemAttributes = currentLineAttributes[column]
itemAttributes.column = column
var x: CGFloat = 0
if column == 0 {
x = sectionInsets.leading + lineLayoutInfo.indent
length = itemAttributes.size.width
} else {
x = sectionInsets.leading + lineLayoutInfo.indent + length + lineLayoutInfo.spacing
length = length + lineLayoutInfo.spacing + itemAttributes.size.width
}
var y: CGFloat = contentSize.height + sectionHeight + minimumLineSpacing
let interitemAlignment = self.collectionView(collectionView, interitemAlignmentForItemAt: itemAttributes, delegate: delegate)
switch interitemAlignment {
case .ascender: break
case .median: y += (currentLineHeight - itemAttributes.size.height) * 0.5
case .descender: y += (currentLineHeight - itemAttributes.size.height)
}
itemAttributes.frame = CGRect.init(x: x, y: y, width: itemAttributes.size.width, height: itemAttributes.size.height)
sectionAttributes.append(itemAttributes)
}
currentLineAttributes.removeAll()
// 开始新的一行,Section 高度增加,重置高度、宽度。
sectionHeight += (minimumLineSpacing + currentLineHeight)
currentLineHeight = 0
currentLineLength = -minimumInteritemSpacing
}
var currentLine: Int = 0
// 获取所有 Cell 的大小。
for index in 0 ..< collectionView.numberOfItems(inSection: section) {
let indexPath = IndexPath.init(item: index, section: section)
let itemSize = self.collectionView(collectionView, sizeForItemAt: indexPath, delegate: delegate)
// 新的宽度超出最大宽度,且行元素不为空,那么该换行了,把当前行中的所有元素移动到总的元素集合中。
var newLineWidth = currentLineLength + (minimumInteritemSpacing + itemSize.width)
if newLineWidth > maxLineLength && !currentLineAttributes.isEmpty {
// 将已有数据添加到布局中。
addLineAttributesFromCurrentContext()
// 换行。
currentLine += 1
// 新行的宽度
newLineWidth = itemSize.width
}
// 如果没有超出最大宽度,或者行为空(其中包括,单个 Cell 的宽度超过最大宽度的情况),或者换行后的新行,将元素添加到行中。
let itemAttributes = UICollectionViewLayoutAttributes(forCellWith: indexPath)
itemAttributes.line = currentLine
itemAttributes.size = itemSize
itemAttributes.zIndex = index
currentLineAttributes.append(itemAttributes)
// 当前行宽度、高度。
currentLineLength = newLineWidth
currentLineHeight = max(currentLineHeight, itemSize.height)
}
addLineAttributesFromCurrentContext()
contentSize.height += sectionHeight
contentSize.height += sectionInsets.bottom
return sectionAttributes
}
// MARK: - 水平方向。
@objc open func prepareHorizontal(_ collectionView: UIKit.UICollectionView, delegate: UIKit.UICollectionViewDelegateFlowLayout?, layoutAttributesForHeaderInSection section: Int) -> XZKit.UICollectionViewLayoutAttributes? {
let headerSize = delegate?.collectionView?(collectionView, layout: self, referenceSizeForHeaderInSection: section) ?? self.headerReferenceSize
guard headerSize != .zero else {
return nil
}
let headerAttributes = XZKit.UICollectionViewLayoutAttributes.init(
forSupplementaryViewOfKind: UIKit.UICollectionView.elementKindSectionHeader,
with: Foundation.IndexPath.init(item: 0, section: section)
)
headerAttributes.frame = CGRect.init(
x: contentSize.width,
y: (contentSize.height - headerSize.height) * 0.5,
width: headerSize.width,
height: headerSize.height
)
contentSize.width += headerSize.width
return headerAttributes
}
@objc open func prepareHorizontal(_ collectionView: UIKit.UICollectionView, delegate: UIKit.UICollectionViewDelegateFlowLayout?, layoutAttributesForFooterInSection section: Int) -> XZKit.UICollectionViewLayoutAttributes? {
let footerSize = delegate?.collectionView?(collectionView, layout: self, referenceSizeForFooterInSection: section) ?? self.footerReferenceSize
guard footerSize != .zero else {
return nil
}
let footerAttributes = XZKit.UICollectionViewLayoutAttributes.init(
forSupplementaryViewOfKind: UIKit.UICollectionView.elementKindSectionFooter,
with: Foundation.IndexPath.init(item: 0, section: section)
)
footerAttributes.frame = CGRect.init(
x: contentSize.width,
y: (contentSize.height - footerSize.height) * 0.5,
width: footerSize.width,
height: footerSize.height
)
contentSize.width += footerSize.width
return footerAttributes
}
@objc open func prepareHorizontal(_ collectionView: UIKit.UICollectionView, delegate: UIKit.UICollectionViewDelegateFlowLayout?, layoutAttributesForItemsInSection section: Int) -> [XZKit.UICollectionViewLayoutAttributes] {
let sectionInsets = self.collectionView(collectionView, edgeInsetsForSectionAt: section, delegate: delegate)
contentSize.width += sectionInsets.leading
let minimumLineSpacing = delegate?.collectionView?(collectionView, layout: self, minimumLineSpacingForSectionAt: section) ?? self.minimumLineSpacing
let minimumInteritemSpacing = delegate?.collectionView?(collectionView, layout: self, minimumInteritemSpacingForSectionAt: section) ?? self.minimumInteritemSpacing
var sectionAttributes = [XZKit.UICollectionViewLayoutAttributes]()
// 行最大宽度。
let maxLineLength: CGFloat = contentSize.height - sectionInsets.top - sectionInsets.bottom
// Section 高度,仅内容区域,不包括 header、footer 和内边距。
// 初始值扣除一个间距,方便使用 间距 + 行高度 来计算高度。
// 每计算完一行,增加此值,并在最终增加到 contentSize 中。
var sectionHeight: CGFloat = -minimumLineSpacing
// 当前正在计算的行的宽度,新行开始后此值会被初始化。
// 初始值扣除一个间距,方便使用 间距 + 宽度 来计算总宽度。
var currentLineLength: CGFloat = -minimumInteritemSpacing
// 行最大高度。以行中最高的 Item 为行高度。
var currentLineHeight: CGFloat = 0
/// 保存了一行的 Cell 的布局信息。
var currentLineAttributes = [UICollectionViewLayoutAttributes]()
/// 当一行的布局信息获取完毕时,从当前上下文中添加行布局信息,并重置上下文变量。
func addLineAttributesFromCurrentContext() {
let lineLayoutInfo = self.collectionView(collectionView, lineLayoutForLineWith: currentLineAttributes, maxLineLength: maxLineLength, lineLength: currentLineLength, minimumInteritemSpacing: minimumInteritemSpacing, delegate: delegate)
var length: CGFloat = 0
for column in 0 ..< currentLineAttributes.count {
let itemAttributes = currentLineAttributes[column]
itemAttributes.column = column
var y: CGFloat = 0
if column == 0 {
y = contentSize.height - sectionInsets.bottom - lineLayoutInfo.indent - itemAttributes.size.height
length = itemAttributes.size.height
} else {
y = contentSize.height - sectionInsets.bottom - lineLayoutInfo.indent - length - lineLayoutInfo.spacing - itemAttributes.size.height
length = length + lineLayoutInfo.spacing + itemAttributes.size.height
}
var x: CGFloat = contentSize.width + sectionHeight + minimumLineSpacing
let interitemAlignment = self.collectionView(collectionView, interitemAlignmentForItemAt: itemAttributes, delegate: delegate)
switch interitemAlignment {
case .ascender: break
case .median: x += (currentLineHeight - itemAttributes.size.width) * 0.5
case .descender: x += (currentLineHeight - itemAttributes.size.width)
}
itemAttributes.frame = CGRect.init(x: x, y: y, width: itemAttributes.size.width, height: itemAttributes.size.height)
sectionAttributes.append(itemAttributes)
}
currentLineAttributes.removeAll()
sectionHeight += (minimumLineSpacing + currentLineHeight)
currentLineHeight = 0
currentLineLength = -minimumInteritemSpacing
}
var currentLine: Int = 0
// 获取所有 Cell 的大小。
for index in 0 ..< collectionView.numberOfItems(inSection: section) {
let indexPath = IndexPath.init(item: index, section: section)
let itemSize = self.collectionView(collectionView, sizeForItemAt: indexPath, delegate: delegate)
var newLineLength = currentLineLength + (minimumInteritemSpacing + itemSize.height)
if newLineLength > maxLineLength && !currentLineAttributes.isEmpty {
addLineAttributesFromCurrentContext()
currentLine += 1
newLineLength = itemSize.height
}
let itemAttributes = UICollectionViewLayoutAttributes(forCellWith: indexPath)
itemAttributes.line = currentLine
itemAttributes.zIndex = index
itemAttributes.size = itemSize
currentLineAttributes.append(itemAttributes)
currentLineLength = newLineLength
currentLineHeight = max(currentLineHeight, itemSize.width)
}
addLineAttributesFromCurrentContext()
contentSize.width += sectionHeight
contentSize.width += sectionInsets.trailing
return sectionAttributes
}
/// 根据行信息计算行布局。因为每一行不能完全占满,根据对齐方式不同,x 坐标相对于起始点,可能需要不同的偏移,元素的间距也可能需要重新计算。
private func collectionView(_ collectionView: UICollectionView, lineLayoutForLineWith currentLineAttributes: [UICollectionViewLayoutAttributes], maxLineLength: CGFloat, lineLength currentLineLength: CGFloat, minimumInteritemSpacing: CGFloat, delegate: UIKit.UICollectionViewDelegateFlowLayout?) -> (indent: CGFloat, spacing: CGFloat) {
let lineAlignment = self.collectionView(collectionView, lineAlignmentForLineAt: currentLineAttributes[0], delegate: delegate)
switch lineAlignment {
case .leading:
return (0, minimumInteritemSpacing)
case .trailing:
return (maxLineLength - currentLineLength, minimumInteritemSpacing)
case .center:
return ((maxLineLength - currentLineLength) * 0.5, minimumInteritemSpacing)
case .justified:
if currentLineAttributes.count > 1 {
return (0, minimumInteritemSpacing + (maxLineLength - currentLineLength) / CGFloat(currentLineAttributes.count - 1))
}
return (0, 0)
case .justifiedCenter:
if currentLineAttributes.count > 1 {
return (0, minimumInteritemSpacing + (maxLineLength - currentLineLength) / CGFloat(currentLineAttributes.count - 1))
}
return ((maxLineLength - currentLineLength) * 0.5, 0)
case .justifiedTrailing:
if currentLineAttributes.count > 1 {
return (0, minimumInteritemSpacing + (maxLineLength - currentLineLength) / CGFloat(currentLineAttributes.count - 1))
}
return ((maxLineLength - currentLineLength), 0)
}
}
}
/// 描述了 UICollectionView 中元素的布局信息。
@objc(XZCollectionViewIndexPath)
public protocol UICollectionViewIndexPath: NSObjectProtocol {
/// 元素在其所在的 section 中的序数。
@objc var item: Int { get }
/// 元素所在的 section 在 UICollectionView 中的序数。
@objc var section: Int { get }
/// 元素在其所在的 line 中的序数。
@objc var column: Int { get }
/// 元素所在的 line 在 section 中的序数。
@objc var line: Int { get }
}
| 901f14bedb4494e01684c02a6489203a | 46.172214 | 339 | 0.662627 | false | false | false | false |
edragoev1/pdfjet | refs/heads/master | Sources/PDFjet/QRCode.swift | mit | 1 | /**
*
Copyright 2009 Kazuhiko Arase
URL: http://www.d-project.com/
Licensed under the MIT license:
http://www.opensource.org/licenses/mit-license.php
The word "QR Code" is registered trademark of
DENSO WAVE INCORPORATED
http://www.denso-wave.com/qrcode/faqpatent-e.html
*/
///
/// Modified and adapted for use in PDFjet by Eugene Dragoev
///
import Foundation
///
/// Used to create 2D QR Code barcodes. Please see Example_21.
///
/// @author Kazuhiko Arase
///
public class QRCode : Drawable {
private let PAD0: UInt32 = 0xEC
private let PAD1: UInt32 = 0x11
private var modules: [[Bool?]]?
private var moduleCount = 33 // Magic Number
private var errorCorrectLevel = ErrorCorrectLevel.M
private var x: Float = 0.0
private var y: Float = 0.0
private var qrData: [UInt8]?
private var m1: Float = 2.0 // Module length
private var color: UInt32 = Color.black
///
/// Used to create 2D QR Code barcodes.
///
/// @param str the string to encode.
/// @param errorCorrectLevel the desired error correction level.
/// @throws UnsupportedEncodingException
///
public init(
_ str: String,
_ errorCorrectLevel: Int) {
self.qrData = Array(str.utf8)
self.errorCorrectLevel = errorCorrectLevel
self.make(false, getBestMaskPattern())
}
public func setPosition(_ x: Float, _ y: Float) {
setLocation(x, y)
}
///
/// Sets the location where this barcode will be drawn on the page.
///
/// @param x the x coordinate of the top left corner of the barcode.
/// @param y the y coordinate of the top left corner of the barcode.
///
@discardableResult
public func setLocation(_ x: Float, _ y: Float) -> QRCode {
self.x = x
self.y = y
return self
}
///
/// Sets the module length of this barcode.
/// The default value is 2.0
///
/// @param moduleLength the specified module length.
///
@discardableResult
public func setModuleLength(_ moduleLength: Float) -> QRCode {
self.m1 = moduleLength
return self
}
public func setColor(_ color: UInt32) {
self.color = color
}
///
/// Draws this barcode on the specified page.
///
/// @param page the specified page.
/// @return x and y coordinates of the bottom right corner of this component.
/// @throws Exception
///
@discardableResult
public func drawOn(_ page: Page?) -> [Float] {
page!.setBrushColor(self.color)
for row in 0..<modules!.count {
for col in 0..<modules!.count {
if isDark(row, col) {
page!.fillRect(x + Float(col)*m1, y + Float(row)*m1, m1, m1)
}
}
}
let w = m1*Float(modules!.count)
let h = m1*Float(modules!.count)
return [self.x + w, self.y + h]
}
public func getData() -> [[Bool?]]? {
return self.modules
}
///
/// @param row the row.
/// @param col the column.
///
func isDark(_ row: Int, _ col: Int) -> Bool {
if modules![row][col] != nil {
return modules![row][col]!
}
return false
}
func getModuleCount() -> Int {
return self.moduleCount
}
func getBestMaskPattern() -> Int {
var minLostPoint = 0
var pattern = 0
for i in 0..<8 {
make(true, i)
let lostPoint = QRUtil.singleton.getLostPoint(self)
if i == 0 || minLostPoint > lostPoint {
minLostPoint = lostPoint
pattern = i
}
}
return pattern
}
func make(
_ test: Bool,
_ maskPattern: Int) {
modules = [[Bool?]]()
for _ in 0..<moduleCount {
modules!.append([Bool?](repeating: nil, count: moduleCount))
}
setupPositionProbePattern(0, 0)
setupPositionProbePattern(moduleCount - 7, 0)
setupPositionProbePattern(0, moduleCount - 7)
setupPositionAdjustPattern()
setupTimingPattern()
setupTypeInfo(test, maskPattern)
mapData(createData(errorCorrectLevel), maskPattern)
}
private func mapData(
_ data: [UInt8],
_ maskPattern: Int) {
var inc = -1
var row = moduleCount - 1
var bitIndex = 7
var byteIndex = 0
var col = moduleCount - 1
while col > 0 {
if col == 6 {
col -= 1
}
while true {
for c in 0..<2 {
if modules![row][col - c] == nil {
var dark = false
if byteIndex < data.count {
dark = (((data[byteIndex] >> bitIndex) & 1) == 1)
}
let mask = QRUtil.singleton.getMask(maskPattern, row, col - c)
if mask {
dark = !dark
}
modules![row][col - c] = dark
bitIndex -= 1
if (bitIndex == -1) {
byteIndex += 1
bitIndex = 7
}
}
}
row += inc
if row < 0 || moduleCount <= row {
row -= inc
inc = -inc
break
}
}
col -= 2
}
}
private func setupPositionAdjustPattern() {
let pos = [6, 26] // Magic Numbers
for i in 0..<pos.count {
for j in 0..<pos.count {
let row = pos[i]
let col = pos[j]
if modules![row][col] != nil {
continue
}
var r = -2
while r <= 2 {
var c = -2
while c <= 2 {
modules![row + r][col + c] =
r == -2 || r == 2 ||
c == -2 || c == 2 ||
(r == 0 && c == 0)
c += 1
}
r += 1
}
}
}
}
private func setupPositionProbePattern(_ row: Int, _ col: Int) {
for r in -1...7 {
for c in -1...7 {
if (row + r <= -1 || moduleCount <= row + r ||
col + c <= -1 || moduleCount <= col + c) {
continue
}
if (0 <= r && r <= 6 && (c == 0 || c == 6)) ||
(0 <= c && c <= 6 && (r == 0 || r == 6)) ||
(2 <= r && r <= 4 && 2 <= c && c <= 4) {
modules![row + r][col + c] = true
}
else {
modules![row + r][col + c] = false
}
}
}
}
private func setupTimingPattern() {
var r = 8
while r < (moduleCount - 8) {
if modules![r][6] == nil {
modules![r][6] = (r % 2 == 0)
r += 1
}
}
var c = 8
while c < (moduleCount - 8) {
if modules![6][c] == nil {
modules![6][c] = (c % 2 == 0)
c += 1
}
}
}
private func setupTypeInfo(
_ test: Bool,
_ maskPattern: Int) {
let data = (errorCorrectLevel << 3) | maskPattern
let bits = QRUtil.singleton.getBCHTypeInfo(data)
for i in 0..<15 {
let mod = (!test && ((bits >> i) & 1) == 1)
if i < 6 {
modules![i][8] = mod
}
else if i < 8 {
modules![i + 1][8] = mod
}
else {
modules![moduleCount - 15 + i][8] = mod
}
}
for i in 0..<15 {
let mod = (!test && ((bits >> i) & 1) == 1)
if i < 8 {
modules![8][moduleCount - i - 1] = mod
}
else if i < 9 {
modules![8][15 - i - 1 + 1] = mod
}
else {
modules![8][15 - i - 1] = mod
}
}
modules![moduleCount - 8][8] = !test
}
private func createData(_ errorCorrectLevel: Int) -> [UInt8] {
let rsBlocks = RSBlock.getRSBlocks(errorCorrectLevel)
let buffer = BitBuffer()
buffer.put(UInt32(4), 4)
buffer.put(UInt32(qrData!.count), 8)
for i in 0..<qrData!.count {
buffer.put(UInt32(qrData![i]), 8)
}
var totalDataCount = 0
for block in rsBlocks {
totalDataCount += block.getDataCount()
}
if buffer.getLengthInBits() > totalDataCount * 8 {
Swift.print("code length overflow. ( " +
String(describing: buffer.getLengthInBits()) + " > " +
String(describing: (totalDataCount * 8)) + " )")
}
if buffer.getLengthInBits() + 4 <= totalDataCount * 8 {
buffer.put(0, 4)
}
// padding
while buffer.getLengthInBits() % 8 != 0 {
buffer.put(false)
}
// padding
while true {
if buffer.getLengthInBits() >= totalDataCount * 8 {
break
}
buffer.put(PAD0, 8)
if buffer.getLengthInBits() >= totalDataCount * 8 {
break
}
buffer.put(PAD1, 8)
}
return createBytes(buffer, rsBlocks)
}
private func createBytes(
_ buffer: BitBuffer,
_ rsBlocks: [RSBlock]) -> [UInt8] {
var offset = 0
var maxDcCount = 0
var maxEcCount = 0
var dcdata = [[Int]?](repeating: nil, count: rsBlocks.count)
var ecdata = [[Int]?](repeating: nil, count: rsBlocks.count)
for r in 0..<rsBlocks.count {
let dcCount = rsBlocks[r].getDataCount()
let ecCount = rsBlocks[r].getTotalCount() - dcCount
maxDcCount = max(maxDcCount, dcCount)
maxEcCount = max(maxEcCount, ecCount)
dcdata[r] = [Int](repeating: 0, count: dcCount)
for i in 0..<dcdata[r]!.count {
dcdata[r]![i] = Int(buffer.getBuffer()![i + offset])
}
offset += dcCount
let rsPoly = QRUtil.singleton.getErrorCorrectPolynomial(ecCount)
let rawPoly = Polynomial(dcdata[r]!, rsPoly.getLength() - 1)
let modPoly = rawPoly.mod(rsPoly)
ecdata[r] = [Int](repeating: 0, count: (rsPoly.getLength() - 1))
for i in 0..<ecdata[r]!.count {
let modIndex = i + modPoly.getLength() - ecdata[r]!.count
ecdata[r]![i] = (modIndex >= 0) ? modPoly.get(modIndex) : 0
}
}
var totalCodeCount = 0
for block in rsBlocks {
totalCodeCount += block.getTotalCount()
}
var data = [UInt8](repeating: 0, count: totalCodeCount)
var index = 0
for i in 0..<maxDcCount {
for r in 0..<rsBlocks.count {
if i < dcdata[r]!.count {
data[index] = UInt8(dcdata[r]![i])
index += 1
}
}
}
for i in 0..<maxEcCount {
for r in 0..<rsBlocks.count {
if i < ecdata[r]!.count {
data[index] = UInt8(ecdata[r]![i])
index += 1
}
}
}
return data
}
}
| 363fe3588bba9022551c811692a00e4b | 27.539759 | 86 | 0.448244 | false | false | false | false |
ello/ello-ios | refs/heads/master | Specs/Networking/UserServiceSpec.swift | mit | 1 | ////
/// UserServiceSpec.swift
//
@testable import Ello
import Quick
import Nimble
class UserServiceSpec: QuickSpec {
override func spec() {
describe("UserService") {
var subject: UserService!
beforeEach {
subject = UserService()
}
describe("join(email:username:password:invitationCode:)") {
it("stores the email and password in the keychain") {
subject.join(
email: "[email protected]",
username: "fake-username",
password: "fake-password",
invitationCode: .none,
success: {},
failure: .none
)
let authToken = AuthToken()
expect(authToken.username) == "fake-username"
expect(authToken.password) == "fake-password"
}
}
}
}
}
| 2d56d27435ab60e4185d8b5ba8ce53a4 | 27.714286 | 71 | 0.455721 | false | false | false | false |
EBGToo/SBFrames | refs/heads/master | Tests/OrientationTest.swift | mit | 1 | //
// OrientationTest.swift
// SBFrames
//
// Created by Ed Gamble on 7/2/16.
// Copyright © 2016 Edward B. Gamble Jr. All rights reserved.
//
// See the LICENSE file at the project root for license information.
// See the CONTRIBUTORS file at the project root for a list of contributors.
//
import XCTest
import SBUnits
import GLKit
@testable import SBFrames
class OrientationTest: XCTestCase {
let accuracy = Quaternion.epsilon
let base = Frame.root
let a0 = Quantity<Angle>(value: 0.0, unit: radian)
let a45 = Quantity<Angle>(value: Double.pi / 4, unit: radian)
let a90 = Quantity<Angle>(value: Double.pi / 2, unit: radian)
let a180 = Quantity<Angle>(value: Double.pi / 1, unit: radian)
let a90n = Quantity<Angle>(value: -Double.pi / 2, unit: radian)
override func setUp() {
super.setUp()
// What does Apple say is the direction for a quaternion with 0 angle?
let g1 = GLKQuaternionMakeWithAngleAndAxis (0, 0, 0, 1)
let angle = GLKQuaternionAngle (g1)
let axis = GLKQuaternionAxis (g1)
XCTAssertEqual(Double( angle), 0.0, accuracy: 1e-5)
XCTAssertEqual(Double(axis.x), 0.0, accuracy: 1e-5)
XCTAssertEqual(Double(axis.y), 0.0, accuracy: 1e-5)
XCTAssertEqual(Double(axis.z), 0.0, accuracy: 1e-3)
}
override func tearDown() {
super.tearDown()
}
func checkValues (_ p: Position, frame: Frame, unit: SBUnits.Unit<Length>, x: Double, y: Double, z: Double) {
XCTAssert(p.has (frame: frame))
XCTAssertEqual(p.x.value, x, accuracy: accuracy)
XCTAssertEqual(p.y.value, y, accuracy: accuracy)
XCTAssertEqual(p.z.value, z, accuracy: accuracy)
XCTAssertTrue(p.x.unit === unit)
XCTAssertTrue(p.y.unit === unit)
XCTAssertTrue(p.z.unit === unit)
XCTAssertTrue(p.unit === unit)
XCTAssertEqual(p.unit, unit)
}
func checkOrientation (_ o: Orientation, frame: Frame, a: Double, x: Double, y: Double, z: Double) {
guard let (ao, (xo, yo, zo)) = o.quat.asAngleDirection else {
XCTAssert(false)
return
}
XCTAssertEqual(ao, a, accuracy: accuracy)
XCTAssertEqual(xo, x, accuracy: accuracy)
XCTAssertEqual(yo, y, accuracy: accuracy)
XCTAssertEqual(zo, z, accuracy: accuracy)
XCTAssert(o.has (frame: frame))
}
func checkQuant (qA: Quaternion, qB: Quaternion) {
XCTAssertEqual(qA.q0, qB.q0, accuracy: accuracy)
XCTAssertEqual(qA.q1, qB.q1, accuracy: accuracy)
XCTAssertEqual(qA.q2, qB.q2, accuracy: accuracy)
XCTAssertEqual(qA.q3, qB.q3, accuracy: accuracy)
}
func testInit() {
let ob = Orientation (frame: base)
let o0 = Orientation (frame: base, angle: a0, axis: .z)
checkOrientation(o0, frame: base, a: a0.value, x: 0, y: 0, z: 0)
let o45 = Orientation (frame: base, angle: a45, axis: .z)
let o90 = Orientation (frame: base, angle: a90, axis: .z)
checkOrientation(o90, frame: base, a: a90.value, x: 0, y: 0, z: 1)
let _ = [ob, o0, o45,o90]
}
func testInvert () {
// rot .z 90
let o90p = Orientation (frame: base, angle: a90 , axis: .z)
checkOrientation(o90p, frame: base, a: a90.value, x: 0, y: 0, z: 1)
// rot .z -90 -> quat ambiguity rot -.z 90
let o90n = Orientation (frame: base, angle: a90n, axis: .z)
checkOrientation(o90n, frame: base, a: a90.value, x: 0, y: 0, z: -1)
// rot .z 90 .invert ->
let o90i = o90p.inverse
checkOrientation(o90i, frame: base, a: a90.value, x: 0, y: 0, z: -1)
let oc = o90p.compose(o90i)
checkOrientation(oc, frame: base, a: 0, x: 0, y: 0, z: 0)
}
func testCompose () {
let o0 = Orientation (frame: base, angle: a0, axis: .z)
checkOrientation(o0, frame: base, a: a0.value, x: 0, y: 0, z: 0)
let o45 = Orientation (frame: base, angle: a45, axis: .z)
let o90 = Orientation (frame: base, angle: a90, axis: .z)
checkOrientation(o90, frame: base, a: a90.value, x: 0, y: 0, z: 1)
let o90c = o0.compose(o45).compose(o45)
checkOrientation(o90c, frame: base, a: a90.value, x: 0, y: 0, z: 1)
let o0c = o90c.compose(o90.inverse)
checkOrientation(o0c, frame: base, a: a0.value, x: 0, y: 0, z: 1)
}
func testRotate () {
let o45 = Orientation (frame: base, angle: a45, axis: .z)
let c90 = o45.compose(o45)
let o90 = Orientation (frame: base, angle: a90, axis: .z)
XCTAssertEqual(c90.quat.q0, o90.quat.q0, accuracy: 1e-10)
let c180 = o90.compose(o90)
let o180 = Orientation (frame: base, angle: a180, axis: .z)
XCTAssertEqual(c180.quat.q0, o180.quat.q0, accuracy: 1e-10)
let o180x = Orientation (frame: base, angle: a180, axis: .z)
let c180x = Orientation (frame: base, angle: a0, axis: .z).compose(o180x)
checkQuant(qA: o180x.quat, qB: c180x.quat)
}
/*
func testAngles () {
let (phi,theta,psi) = (37.5, 10.0, 22.0)
let o1 = Orientation(frame: base, unit: degree, convention: .fixedXYZ, x: phi, y: theta, z: psi)
let (oPhi, oTheta, oPsi) = o1.asFixedXYZAngles
XCTAssertEqual(phi, degree.convert(oPhi, unit: radian), accuracy: 1e-10)
XCTAssertEqual(theta, degree.convert(oTheta, unit: radian), accuracy: 1e-10)
XCTAssertEqual(psi, degree.convert(oPsi, unit: radian), accuracy: 1e-10)
}
*/
func testPerformanceExample() {
self.measure {
}
}
}
| ae517db1a08826659664257d637304ec | 31.760736 | 111 | 0.636704 | false | true | false | false |
khizkhiz/swift | refs/heads/master | stdlib/public/SDK/AppKit/NSError.swift | apache-2.0 | 1 | extension NSCocoaError {
public static var textReadInapplicableDocumentTypeError: NSCocoaError {
return NSCocoaError(rawValue: 65806)
}
public static var textWriteInapplicableDocumentTypeError: NSCocoaError {
return NSCocoaError(rawValue: 66062)
}
public static var serviceApplicationNotFoundError: NSCocoaError {
return NSCocoaError(rawValue: 66560)
}
public static var serviceApplicationLaunchFailedError: NSCocoaError {
return NSCocoaError(rawValue: 66561)
}
public static var serviceRequestTimedOutError: NSCocoaError {
return NSCocoaError(rawValue: 66562)
}
public static var serviceInvalidPasteboardDataError: NSCocoaError {
return NSCocoaError(rawValue: 66563)
}
public static var serviceMalformedServiceDictionaryError: NSCocoaError {
return NSCocoaError(rawValue: 66564)
}
public static var serviceMiscellaneousError: NSCocoaError {
return NSCocoaError(rawValue: 66800)
}
public static var sharingServiceNotConfiguredError: NSCocoaError {
return NSCocoaError(rawValue: 67072)
}
public var isServiceError: Bool {
return rawValue >= 66560 && rawValue <= 66817
}
public var isSharingServiceError: Bool {
return rawValue >= 67072 && rawValue <= 67327
}
public var isTextReadWriteError: Bool {
return rawValue >= 65792 && rawValue <= 66303
}
}
extension NSCocoaError {
@swift3_migration(renamed="textReadInapplicableDocumentTypeError")
public static var TextReadInapplicableDocumentTypeError: NSCocoaError {
return NSCocoaError(rawValue: 65806)
}
@swift3_migration(renamed="textWriteInapplicableDocumentTypeError")
public static var TextWriteInapplicableDocumentTypeError: NSCocoaError {
return NSCocoaError(rawValue: 66062)
}
@swift3_migration(renamed="serviceApplicationNotFoundError")
public static var ServiceApplicationNotFoundError: NSCocoaError {
return NSCocoaError(rawValue: 66560)
}
@swift3_migration(renamed="serviceApplicationLaunchFailedError")
public static var ServiceApplicationLaunchFailedError: NSCocoaError {
return NSCocoaError(rawValue: 66561)
}
@swift3_migration(renamed="serviceRequestTimedOutError")
public static var ServiceRequestTimedOutError: NSCocoaError {
return NSCocoaError(rawValue: 66562)
}
@swift3_migration(renamed="serviceInvalidPasteboardDataError")
public static var ServiceInvalidPasteboardDataError: NSCocoaError {
return NSCocoaError(rawValue: 66563)
}
@swift3_migration(renamed="serviceMalformedServiceDictionaryError")
public static var ServiceMalformedServiceDictionaryError: NSCocoaError {
return NSCocoaError(rawValue: 66564)
}
@swift3_migration(renamed="serviceMiscellaneousError")
public static var ServiceMiscellaneousError: NSCocoaError {
return NSCocoaError(rawValue: 66800)
}
@swift3_migration(renamed="sharingServiceNotConfiguredError")
public static var SharingServiceNotConfiguredError: NSCocoaError {
return NSCocoaError(rawValue: 67072)
}
}
| e3414d2761503d0f606b8e91431574d6 | 36.4125 | 74 | 0.789175 | false | false | false | false |
gxf2015/DYZB | refs/heads/master | DYZB/DYZB/Classes/Main/Model/AncnorGroup.swift | mit | 1 | //
// AncnorGroup.swift
// DYZB
//
// Created by guo xiaofei on 2017/8/14.
// Copyright © 2017年 guo xiaofei. All rights reserved.
//
import UIKit
import HandyJSON
class AncnorGroup: HandyJSON {
var room_list : [AncnorModel]?
var tag_name : String = ""
var icon_name = "home_header_normal"
var icon_url : String = ""
required init(){}
}
class AncnorModel: HandyJSON {
var room_id : Int = 0
var vertical_src : String = ""
var icon_name = "home_header_normal"
var isVertical : Int = 0
var room_name : String = ""
var nickname : String = ""
var online : Int = 0
var anchor_city : String = ""
required init(){}
}
| 95fa392873080fec7c907a8202a360f4 | 15.377778 | 55 | 0.56038 | false | false | false | false |
Jnosh/swift | refs/heads/master | stdlib/public/core/ASCII.swift | apache-2.0 | 2 | //===--- ASCII.swift ------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
extension Unicode {
@_fixed_layout
public enum ASCII {}
}
extension Unicode.ASCII : Unicode.Encoding {
public typealias CodeUnit = UInt8
public typealias EncodedScalar = CollectionOfOne<CodeUnit>
public static var encodedReplacementCharacter : EncodedScalar {
return EncodedScalar(0x1a) // U+001A SUBSTITUTE; best we can do for ASCII
}
@inline(__always)
@_inlineable
public static func _isScalar(_ x: CodeUnit) -> Bool {
return true
}
@inline(__always)
@_inlineable
public static func decode(_ source: EncodedScalar) -> Unicode.Scalar {
return Unicode.Scalar(_unchecked: UInt32(
source.first._unsafelyUnwrappedUnchecked))
}
@inline(__always)
@_inlineable
public static func encode(
_ source: Unicode.Scalar
) -> EncodedScalar? {
guard source.value < (1&<<7) else { return nil }
return EncodedScalar(UInt8(extendingOrTruncating: source.value))
}
@inline(__always)
public static func transcode<FromEncoding : Unicode.Encoding>(
_ content: FromEncoding.EncodedScalar, from _: FromEncoding.Type
) -> EncodedScalar? {
if _fastPath(FromEncoding.self == UTF16.self) {
let c = _identityCast(content, to: UTF16.EncodedScalar.self)
guard (c._storage & 0xFF80 == 0) else { return nil }
return EncodedScalar(CodeUnit(c._storage & 0x7f))
}
else if _fastPath(FromEncoding.self == UTF8.self) {
let c = _identityCast(content, to: UTF8.EncodedScalar.self)
guard (c._storage & 0x80 == 0) else { return nil }
return EncodedScalar(CodeUnit(c._storage & 0x7f))
}
return encode(FromEncoding.decode(content))
}
public struct Parser {
public init() { }
}
public typealias ForwardParser = Parser
public typealias ReverseParser = Parser
}
extension Unicode.ASCII.Parser : Unicode.Parser {
public typealias Encoding = Unicode.ASCII
/// Parses a single Unicode scalar value from `input`.
public mutating func parseScalar<I : IteratorProtocol>(
from input: inout I
) -> Unicode.ParseResult<Encoding.EncodedScalar>
where I.Element == Encoding.CodeUnit {
let n = input.next()
if _fastPath(n != nil), let x = n {
guard _fastPath(Int8(extendingOrTruncating: x) >= 0)
else { return .error(length: 1) }
return .valid(Unicode.ASCII.EncodedScalar(x))
}
return .emptyInput
}
}
| ec1f4385a89e452da1d5645c628bc185 | 31.636364 | 80 | 0.656337 | false | false | false | false |
vanhuyz/learn_swift | refs/heads/master | JSON Demo/JSON Demo/ViewController.swift | mit | 1 | //
// ViewController.swift
// JSON Demo
//
// Created by Van Huy on 12/3/15.
// Copyright (c) 2015 Example. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let urlPath = "http://api.openweathermap.org/data/2.5/weather?q=Tokyo,jp&appid=2de143494c0b295cca9337e1e96b00e0"
let url = NSURL(string: urlPath)
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithURL(url!, completionHandler: { (data, response, error) -> Void in
if error != nil {
println(error)
} else {
let jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as! NSDictionary
println(jsonResult["weather"])
}
})
task.resume()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| 6b690ea7a74e007d89ce0f486bc13d4e | 27.52381 | 155 | 0.611853 | false | false | false | false |
orta/SignalKit | refs/heads/master | SignalKit/Observables/ObservableProperty.swift | mit | 1 | //
// ObservableProperty.swift
// SignalKit
//
// Created by Yanko Dimitrov on 8/12/15.
// Copyright © 2015 Yanko Dimitrov. All rights reserved.
//
import Foundation
public final class ObservableProperty<T>: Observable {
public typealias Item = T
private var internalValue: Item
private let lock: LockType
public let dispatcher: Dispatcher<Item>
public var value: Item {
get {
lock.lock()
let theValue = internalValue
lock.unlock()
return theValue
}
set {
lock.lock()
internalValue = newValue
lock.unlock()
dispatcher.dispatch(newValue)
}
}
public init(value: Item, lock: LockType) {
self.internalValue = value
self.lock = lock
self.dispatcher = Dispatcher<Item>(lock: lock)
}
public convenience init(_ value: Item) {
self.init(value: value, lock: SpinLock())
}
public func dispatch(item: Item) {
value = item
}
}
public extension ObservableProperty {
/**
Observe the observable property for value changes
*/
public func observe() -> Signal<Item> {
let signal = Signal<Item>(lock: SpinLock())
signal.observe(self)
return signal
}
}
| ffac2a4a60b79c6da161ab0a24fc3888 | 19.926471 | 57 | 0.541813 | false | false | false | false |
Ben21hao/edx-app-ios-enterprise-new | refs/heads/master | Test/UserPreferenceManagerTests.swift | apache-2.0 | 2 | //
// UserPreferenceManagerTests.swift
// edX
//
// Created by Kevin Kim on 8/8/16.
// Copyright © 2016 edX. All rights reserved.
//
import Foundation
@testable import edX
class UserPreferenceManagerTests : XCTestCase {
func testUserPreferencesLoginLogout() {
let userPrefernces = UserPreference(json: ["time_zone": "Asia/Tokyo"])
XCTAssertNotNil(userPrefernces)
let preferences = userPrefernces!
let environment = TestRouterEnvironment()
environment.mockNetworkManager.interceptWhenMatching({_ in true }) {
return (nil, preferences)
}
let manager = UserPreferenceManager(networkManager: environment.networkManager)
let feed = manager.feed
// starts empty
XCTAssertNil(feed.output.value)
// Log in. Preferences should load
environment.logInTestUser()
feed.refresh()
stepRunLoop()
waitForStream(feed.output)
XCTAssertEqual(feed.output.value??.timeZone, preferences.timeZone)
// Log out. Now preferences should be cleared
environment.session.closeAndClearSession()
XCTAssertNil(feed.output.value!)
}
}
| 38f5b2042b94069e7f4c9a6521e8b002 | 27 | 87 | 0.630952 | false | true | false | false |
depl0y/pixelbits | refs/heads/develop | pixelbits/Other/Swizzling.swift | mit | 1 | //
// Swizzling.swift
// pixelbits
//
// Created by Wim Haanstra on 19/01/16.
// Copyright © 2016 Wim Haanstra. All rights reserved.
//
internal class Swizzling {
internal static func setup() {
Swizzling.swizzle(UIView.self, originalSelector: #selector(UIView.setNeedsDisplay), swizzledClass: UIView.self, swizzledSelector:
#selector(UIView.pixelbitsSetNeedsDisplay))
}
private static func swizzle(originalClass: AnyClass!, originalSelector: Selector, swizzledClass: AnyClass!, swizzledSelector: Selector) {
let method: Method = class_getInstanceMethod(originalClass, originalSelector)
let swizzledMethod: Method = class_getInstanceMethod(swizzledClass, swizzledSelector)
if method != nil && swizzledMethod != nil {
Log.debug("SWIZZLE: \(originalClass).\(originalSelector) => \(swizzledClass).\(swizzledSelector)")
method_exchangeImplementations(method, swizzledMethod)
}
}
}
| 786fc375d941eff45d327dc8caa0c9fb | 31.714286 | 138 | 0.752183 | false | false | false | false |
wireapp/wire-ios | refs/heads/develop | Wire-iOS/Sources/UserInterface/Components/Views/UserCellSubtitleProtocol.swift | gpl-3.0 | 1 | //
// Wire
// Copyright (C) 2018 Wire Swiss GmbH
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
import Foundation
import WireDataModel
import WireCommonComponents
protocol UserCellSubtitleProtocol: AnyObject {
func subtitle(forRegularUser user: UserType?) -> NSAttributedString?
static var correlationFormatters: [ColorSchemeVariant: AddressBookCorrelationFormatter] { get set }
static var boldFont: FontSpec { get }
static var lightFont: FontSpec { get }
}
extension UserCellSubtitleProtocol where Self: UIView & Themeable {
func subtitle(forRegularUser user: UserType?) -> NSAttributedString? {
guard let user = user else { return nil }
var components: [NSAttributedString?] = []
if let handle = user.handleDisplayString(withDomain: user.isFederated), !handle.isEmpty {
components.append(handle && UserCell.boldFont.font!)
}
WirelessExpirationTimeFormatter.shared.string(for: user).apply {
components.append($0 && UserCell.boldFont.font!)
}
if let user = user as? ZMUser, let addressBookName = user.addressBookEntry?.cachedName {
let formatter = Self.correlationFormatter(for: colorSchemeVariant)
components.append(formatter.correlationText(for: user, addressBookName: addressBookName))
}
return components.compactMap({ $0 }).joined(separator: " " + String.MessageToolbox.middleDot + " " && UserCell.lightFont.font!)
}
private static func correlationFormatter(for colorSchemeVariant: ColorSchemeVariant) -> AddressBookCorrelationFormatter {
if let formatter = correlationFormatters[colorSchemeVariant] {
return formatter
}
let color = UIColor.from(scheme: .sectionText, variant: colorSchemeVariant)
let formatter = AddressBookCorrelationFormatter(lightFont: lightFont, boldFont: boldFont, color: color)
correlationFormatters[colorSchemeVariant] = formatter
return formatter
}
}
| 4673b1180bded145991cf239aaf41b37 | 37.925373 | 135 | 0.719709 | false | false | false | false |
vimeo/VimeoNetworking | refs/heads/develop | Sources/Shared/Core/SessionManaging.swift | mit | 1 | //
// VimeoSessionManaging.swift
// VimeoNetworking
//
// Created by Rogerio de Paula Assis on 9/5/19.
// Copyright © 2019 Vimeo. All rights reserved.
//
import Foundation
public struct SessionManagingResult<T> {
public let request: URLRequest?
public let response: URLResponse?
public let result: Result<T, Error>
init(request: URLRequest? = nil, response: URLResponse? = nil, result: Result<T, Error>) {
self.request = request
self.response = response
self.result = result
}
}
/// A type that can perform asynchronous requests from a
/// URLRequestConvertible parameter and a response callback.
public protocol SessionManaging: AuthenticationListener {
/// Used to invalidate the session manager, and optionally cancel any pending tasks
func invalidate(cancelingPendingTasks cancelPendingTasks: Bool)
/// The various methods below create asynchronous operations described by the
/// requestConvertible object, and return a corresponding task that can be used to identify and
/// control the lifecycle of the request.
/// The callback provided will be executed once the operation completes. It will include
/// the result object along with the originating request and corresponding response objects.
// Data request
func request(
_ requestConvertible: URLRequestConvertible,
parameters: Any?,
then callback: @escaping (SessionManagingResult<Data>) -> Void
) -> Task?
// JSON request
func request(
_ requestConvertible: URLRequestConvertible,
parameters: Any?,
then callback: @escaping (SessionManagingResult<JSON>) -> Void
) -> Task?
// Decodable request
func request<T: Decodable>(
_ requestConvertible: URLRequestConvertible,
parameters: Any?,
then callback: @escaping (SessionManagingResult<T>) -> Void
) -> Task?
// Download request
func download(
_ requestConvertible: URLRequestConvertible,
destinationURL: URL?,
then callback: @escaping (SessionManagingResult<URL>) -> Void
) -> Task?
// Upload request
func upload(
_ requestConvertible: URLRequestConvertible,
sourceFile: URL,
then callback: @escaping (SessionManagingResult<JSON>) -> Void
) -> Task?
}
| b0fb92c3164de7fa907632d147558872 | 31.929577 | 99 | 0.685201 | false | false | false | false |
eno314/MyTopics | refs/heads/develop | MyTopics/AppDelegate.swift | mit | 1 | //
// AppDelegate.swift
// MyTopics
//
// Created by hiroto kitamur on 2014/11/15.
// Copyright (c) 2014年 eno. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
let navigationController = self.window!.rootViewController as UINavigationController
let controller = navigationController.topViewController as MasterViewController
controller.managedObjectContext = self.managedObjectContext
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Core Data stack
lazy var applicationDocumentsDirectory: NSURL = {
// The directory the application uses to store the Core Data store file. This code uses a directory named "jp.eno.MyTopics" in the application's documents Application Support directory.
let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
return urls[urls.count-1] as NSURL
}()
lazy var managedObjectModel: NSManagedObjectModel = {
// The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
let modelURL = NSBundle.mainBundle().URLForResource("MyTopics", withExtension: "momd")!
return NSManagedObjectModel(contentsOfURL: modelURL)!
}()
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = {
// The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail.
// Create the coordinator and store
var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("MyTopics.sqlite")
var error: NSError? = nil
var failureReason = "There was an error creating or loading the application's saved data."
if coordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil, error: &error) == nil {
coordinator = nil
// Report any error we got.
let dict = NSMutableDictionary()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
dict[NSLocalizedFailureReasonErrorKey] = failureReason
dict[NSUnderlyingErrorKey] = error
error = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
// Replace this with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(error), \(error!.userInfo)")
abort()
}
return coordinator
}()
lazy var managedObjectContext: NSManagedObjectContext? = {
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
let coordinator = self.persistentStoreCoordinator
if coordinator == nil {
return nil
}
var managedObjectContext = NSManagedObjectContext()
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
// MARK: - Core Data Saving support
func saveContext () {
if let moc = self.managedObjectContext {
var error: NSError? = nil
if moc.hasChanges && !moc.save(&error) {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(error), \(error!.userInfo)")
abort()
}
}
}
}
| 7233a0250be474cec065f824226ade83 | 54.824561 | 290 | 0.719516 | false | false | false | false |
ALHariPrasad/BluetoothKit | refs/heads/master | Example/Vendor/CryptoSwift/CryptoSwift/AES.swift | mit | 11 | //
// AES.swift
// CryptoSwift
//
// Created by Marcin Krzyzanowski on 21/11/14.
// Copyright (c) 2014 Marcin Krzyzanowski. All rights reserved.
//
import Foundation
final public class AES {
enum Error: ErrorType {
case BlockSizeExceeded
}
public enum AESVariant:Int {
case aes128 = 1, aes192, aes256
var Nk:Int { // Nk words
return [4,6,8][self.rawValue - 1]
}
var Nb:Int { // Nb words
return 4
}
var Nr:Int { // Nr
return Nk + 6
}
}
public let blockMode:CipherBlockMode
public static let blockSize:Int = 16 // 128 /8
public var variant:AESVariant {
switch (self.key.count * 8) {
case 128:
return .aes128
case 192:
return .aes192
case 256:
return .aes256
default:
preconditionFailure("Unknown AES variant for given key.")
}
}
private let key:[UInt8]
private let iv:[UInt8]?
public lazy var expandedKey:[UInt8] = { AES.expandKey(self.key, variant: self.variant) }()
static private let sBox:[UInt8] = [
0x63, 0x7c, 0x77, 0x7b, 0xf2, 0x6b, 0x6f, 0xc5, 0x30, 0x01, 0x67, 0x2b, 0xfe, 0xd7, 0xab, 0x76,
0xca, 0x82, 0xc9, 0x7d, 0xfa, 0x59, 0x47, 0xf0, 0xad, 0xd4, 0xa2, 0xaf, 0x9c, 0xa4, 0x72, 0xc0,
0xb7, 0xfd, 0x93, 0x26, 0x36, 0x3f, 0xf7, 0xcc, 0x34, 0xa5, 0xe5, 0xf1, 0x71, 0xd8, 0x31, 0x15,
0x04, 0xc7, 0x23, 0xc3, 0x18, 0x96, 0x05, 0x9a, 0x07, 0x12, 0x80, 0xe2, 0xeb, 0x27, 0xb2, 0x75,
0x09, 0x83, 0x2c, 0x1a, 0x1b, 0x6e, 0x5a, 0xa0, 0x52, 0x3b, 0xd6, 0xb3, 0x29, 0xe3, 0x2f, 0x84,
0x53, 0xd1, 0x00, 0xed, 0x20, 0xfc, 0xb1, 0x5b, 0x6a, 0xcb, 0xbe, 0x39, 0x4a, 0x4c, 0x58, 0xcf,
0xd0, 0xef, 0xaa, 0xfb, 0x43, 0x4d, 0x33, 0x85, 0x45, 0xf9, 0x02, 0x7f, 0x50, 0x3c, 0x9f, 0xa8,
0x51, 0xa3, 0x40, 0x8f, 0x92, 0x9d, 0x38, 0xf5, 0xbc, 0xb6, 0xda, 0x21, 0x10, 0xff, 0xf3, 0xd2,
0xcd, 0x0c, 0x13, 0xec, 0x5f, 0x97, 0x44, 0x17, 0xc4, 0xa7, 0x7e, 0x3d, 0x64, 0x5d, 0x19, 0x73,
0x60, 0x81, 0x4f, 0xdc, 0x22, 0x2a, 0x90, 0x88, 0x46, 0xee, 0xb8, 0x14, 0xde, 0x5e, 0x0b, 0xdb,
0xe0, 0x32, 0x3a, 0x0a, 0x49, 0x06, 0x24, 0x5c, 0xc2, 0xd3, 0xac, 0x62, 0x91, 0x95, 0xe4, 0x79,
0xe7, 0xc8, 0x37, 0x6d, 0x8d, 0xd5, 0x4e, 0xa9, 0x6c, 0x56, 0xf4, 0xea, 0x65, 0x7a, 0xae, 0x08,
0xba, 0x78, 0x25, 0x2e, 0x1c, 0xa6, 0xb4, 0xc6, 0xe8, 0xdd, 0x74, 0x1f, 0x4b, 0xbd, 0x8b, 0x8a,
0x70, 0x3e, 0xb5, 0x66, 0x48, 0x03, 0xf6, 0x0e, 0x61, 0x35, 0x57, 0xb9, 0x86, 0xc1, 0x1d, 0x9e,
0xe1, 0xf8, 0x98, 0x11, 0x69, 0xd9, 0x8e, 0x94, 0x9b, 0x1e, 0x87, 0xe9, 0xce, 0x55, 0x28, 0xdf,
0x8c, 0xa1, 0x89, 0x0d, 0xbf, 0xe6, 0x42, 0x68, 0x41, 0x99, 0x2d, 0x0f, 0xb0, 0x54, 0xbb, 0x16]
static private let invSBox:[UInt8] = [
0x52, 0x09, 0x6a, 0xd5, 0x30, 0x36, 0xa5, 0x38, 0xbf, 0x40, 0xa3,
0x9e, 0x81, 0xf3, 0xd7, 0xfb, 0x7c, 0xe3, 0x39, 0x82, 0x9b, 0x2f,
0xff, 0x87, 0x34, 0x8e, 0x43, 0x44, 0xc4, 0xde, 0xe9, 0xcb, 0x54,
0x7b, 0x94, 0x32, 0xa6, 0xc2, 0x23, 0x3d, 0xee, 0x4c, 0x95, 0x0b,
0x42, 0xfa, 0xc3, 0x4e, 0x08, 0x2e, 0xa1, 0x66, 0x28, 0xd9, 0x24,
0xb2, 0x76, 0x5b, 0xa2, 0x49, 0x6d, 0x8b, 0xd1, 0x25, 0x72, 0xf8,
0xf6, 0x64, 0x86, 0x68, 0x98, 0x16, 0xd4, 0xa4, 0x5c, 0xcc, 0x5d,
0x65, 0xb6, 0x92, 0x6c, 0x70, 0x48, 0x50, 0xfd, 0xed, 0xb9, 0xda,
0x5e, 0x15, 0x46, 0x57, 0xa7, 0x8d, 0x9d, 0x84, 0x90, 0xd8, 0xab,
0x00, 0x8c, 0xbc, 0xd3, 0x0a, 0xf7, 0xe4, 0x58, 0x05, 0xb8, 0xb3,
0x45, 0x06, 0xd0, 0x2c, 0x1e, 0x8f, 0xca, 0x3f, 0x0f, 0x02, 0xc1,
0xaf, 0xbd, 0x03, 0x01, 0x13, 0x8a, 0x6b, 0x3a, 0x91, 0x11, 0x41,
0x4f, 0x67, 0xdc, 0xea, 0x97, 0xf2, 0xcf, 0xce, 0xf0, 0xb4, 0xe6,
0x73, 0x96, 0xac, 0x74, 0x22, 0xe7, 0xad, 0x35, 0x85, 0xe2, 0xf9,
0x37, 0xe8, 0x1c, 0x75, 0xdf, 0x6e, 0x47, 0xf1, 0x1a, 0x71, 0x1d,
0x29, 0xc5, 0x89, 0x6f, 0xb7, 0x62, 0x0e, 0xaa, 0x18, 0xbe, 0x1b,
0xfc, 0x56, 0x3e, 0x4b, 0xc6, 0xd2, 0x79, 0x20, 0x9a, 0xdb, 0xc0,
0xfe, 0x78, 0xcd, 0x5a, 0xf4, 0x1f, 0xdd, 0xa8, 0x33, 0x88, 0x07,
0xc7, 0x31, 0xb1, 0x12, 0x10, 0x59, 0x27, 0x80, 0xec, 0x5f, 0x60,
0x51, 0x7f, 0xa9, 0x19, 0xb5, 0x4a, 0x0d, 0x2d, 0xe5, 0x7a, 0x9f,
0x93, 0xc9, 0x9c, 0xef, 0xa0, 0xe0, 0x3b, 0x4d, 0xae, 0x2a, 0xf5,
0xb0, 0xc8, 0xeb, 0xbb, 0x3c, 0x83, 0x53, 0x99, 0x61, 0x17, 0x2b,
0x04, 0x7e, 0xba, 0x77, 0xd6, 0x26, 0xe1, 0x69, 0x14, 0x63, 0x55,
0x21, 0x0c, 0x7d]
// Parameters for Linear Congruence Generators
static private let Rcon:[UInt8] = [
0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d, 0x9a,
0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5, 0x91, 0x39,
0x72, 0xe4, 0xd3, 0xbd, 0x61, 0xc2, 0x9f, 0x25, 0x4a, 0x94, 0x33, 0x66, 0xcc, 0x83, 0x1d, 0x3a,
0x74, 0xe8, 0xcb, 0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8,
0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3, 0x7d, 0xfa, 0xef,
0xc5, 0x91, 0x39, 0x72, 0xe4, 0xd3, 0xbd, 0x61, 0xc2, 0x9f, 0x25, 0x4a, 0x94, 0x33, 0x66, 0xcc,
0x83, 0x1d, 0x3a, 0x74, 0xe8, 0xcb, 0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b,
0x36, 0x6c, 0xd8, 0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3,
0x7d, 0xfa, 0xef, 0xc5, 0x91, 0x39, 0x72, 0xe4, 0xd3, 0xbd, 0x61, 0xc2, 0x9f, 0x25, 0x4a, 0x94,
0x33, 0x66, 0xcc, 0x83, 0x1d, 0x3a, 0x74, 0xe8, 0xcb, 0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20,
0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35,
0x6a, 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5, 0x91, 0x39, 0x72, 0xe4, 0xd3, 0xbd, 0x61, 0xc2, 0x9f,
0x25, 0x4a, 0x94, 0x33, 0x66, 0xcc, 0x83, 0x1d, 0x3a, 0x74, 0xe8, 0xcb, 0x8d, 0x01, 0x02, 0x04,
0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc, 0x63,
0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5, 0x91, 0x39, 0x72, 0xe4, 0xd3, 0xbd,
0x61, 0xc2, 0x9f, 0x25, 0x4a, 0x94, 0x33, 0x66, 0xcc, 0x83, 0x1d, 0x3a, 0x74, 0xe8, 0xcb, 0x8d]
public init?(key:[UInt8], iv:[UInt8], blockMode:CipherBlockMode = .CBC) {
self.key = key
self.iv = iv
self.blockMode = blockMode
if (blockMode.needIV && iv.count != AES.blockSize) {
assert(false, "Block size and Initialization Vector must be the same length!")
return nil
}
}
convenience public init?(key:[UInt8], blockMode:CipherBlockMode = .CBC) {
// default IV is all 0x00...
let defaultIV = [UInt8](count: AES.blockSize, repeatedValue: 0)
self.init(key: key, iv: defaultIV, blockMode: blockMode)
}
convenience public init?(key:String, iv:String, blockMode:CipherBlockMode = .CBC) {
if let kkey = key.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)?.arrayOfBytes(), let iiv = iv.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)?.arrayOfBytes() {
self.init(key: kkey, iv: iiv, blockMode: blockMode)
}
return nil
}
/**
Encrypt message. If padding is necessary, then PKCS7 padding is added and needs to be removed after decryption.
- parameter message: Plaintext data
- returns: Encrypted data
*/
public func encrypt(bytes:[UInt8], padding:Padding? = PKCS7()) throws -> [UInt8] {
var finalBytes = bytes;
if let padding = padding {
finalBytes = padding.add(bytes, blockSize: AES.blockSize)
} else if bytes.count % AES.blockSize != 0 {
throw Error.BlockSizeExceeded
}
let blocks = finalBytes.chunks(AES.blockSize) // 0.34
return try blockMode.encryptBlocks(blocks, iv: self.iv, cipherOperation: encryptBlock)
}
private func encryptBlock(block:[UInt8]) -> [UInt8]? {
var out:[UInt8] = [UInt8]()
autoreleasepool { () -> () in
var state:[[UInt8]] = [[UInt8]](count: variant.Nb, repeatedValue: [UInt8](count: variant.Nb, repeatedValue: 0))
for (i, row) in state.enumerate() {
for (j, _) in row.enumerate() {
state[j][i] = block[i * row.count + j]
}
}
state = addRoundKey(state,expandedKey, 0)
for roundCount in 1..<variant.Nr {
subBytes(&state)
state = shiftRows(state)
state = mixColumns(state)
state = addRoundKey(state, expandedKey, roundCount)
}
subBytes(&state)
state = shiftRows(state)
state = addRoundKey(state, expandedKey, variant.Nr)
out = [UInt8](count: state.count * state.first!.count, repeatedValue: 0)
for i in 0..<state.count {
for j in 0..<state[i].count {
out[(i * 4) + j] = state[j][i]
}
}
}
return out
}
public func decrypt(bytes:[UInt8], padding:Padding? = PKCS7()) throws -> [UInt8] {
if bytes.count % AES.blockSize != 0 {
throw Error.BlockSizeExceeded
}
let blocks = bytes.chunks(AES.blockSize)
let out:[UInt8]
switch (blockMode) {
case .CFB, .CTR:
// CFB, CTR uses encryptBlock to decrypt
out = try blockMode.decryptBlocks(blocks, iv: self.iv, cipherOperation: encryptBlock)
default:
out = try blockMode.decryptBlocks(blocks, iv: self.iv, cipherOperation: decryptBlock)
}
if let padding = padding {
return padding.remove(out, blockSize: nil)
}
return out
}
private func decryptBlock(block:[UInt8]) -> [UInt8]? {
var state:[[UInt8]] = [[UInt8]](count: variant.Nb, repeatedValue: [UInt8](count: variant.Nb, repeatedValue: 0))
for (i, row) in state.enumerate() {
for (j, _) in row.enumerate() {
state[j][i] = block[i * row.count + j]
}
}
state = addRoundKey(state,expandedKey, variant.Nr)
for roundCount in (1..<variant.Nr).reverse() {
state = invShiftRows(state)
state = invSubBytes(state)
state = addRoundKey(state, expandedKey, roundCount)
state = invMixColumns(state)
}
state = invShiftRows(state)
state = invSubBytes(state)
state = addRoundKey(state, expandedKey, 0)
var out:[UInt8] = [UInt8]()
for i in 0..<state.count {
for j in 0..<state[0].count {
out.append(state[j][i])
}
}
return out
}
static private func expandKey(key:[UInt8], variant:AESVariant) -> [UInt8] {
/*
* Function used in the Key Expansion routine that takes a four-byte
* input word and applies an S-box to each of the four bytes to
* produce an output word.
*/
func subWord(word:[UInt8]) -> [UInt8] {
var result = word
for i in 0..<4 {
result[i] = self.sBox[Int(word[i])]
}
return result
}
var w = [UInt8](count: variant.Nb * (variant.Nr + 1) * 4, repeatedValue: 0)
for i in 0..<variant.Nk {
for wordIdx in 0..<4 {
w[(4*i)+wordIdx] = key[(4*i)+wordIdx]
}
}
var tmp:[UInt8]
for (var i = variant.Nk; i < variant.Nb * (variant.Nr + 1); i++) {
tmp = [UInt8](count: 4, repeatedValue: 0)
for wordIdx in 0..<4 {
tmp[wordIdx] = w[4*(i-1)+wordIdx]
}
if ((i % variant.Nk) == 0) {
let rotWord = rotateLeft(UInt32.withBytes(tmp), n: 8).bytes(sizeof(UInt32)) // RotWord
tmp = subWord(rotWord)
tmp[0] = tmp[0] ^ Rcon[i/variant.Nk]
} else if (variant.Nk > 6 && (i % variant.Nk) == 4) {
tmp = subWord(tmp)
}
// xor array of bytes
for wordIdx in 0..<4 {
w[4*i+wordIdx] = w[4*(i-variant.Nk)+wordIdx]^tmp[wordIdx];
}
}
return w;
}
}
extension AES {
// byte substitution with table (S-box)
public func subBytes(inout state:[[UInt8]]) {
for (i,row) in state.enumerate() {
for (j,value) in row.enumerate() {
state[i][j] = AES.sBox[Int(value)]
}
}
}
public func invSubBytes(state:[[UInt8]]) -> [[UInt8]] {
var result = state
for (i,row) in state.enumerate() {
for (j,value) in row.enumerate() {
result[i][j] = AES.invSBox[Int(value)]
}
}
return result
}
// Applies a cyclic shift to the last 3 rows of a state matrix.
public func shiftRows(state:[[UInt8]]) -> [[UInt8]] {
var result = state
for r in 1..<4 {
for c in 0..<variant.Nb {
result[r][c] = state[r][(c + r) % variant.Nb]
}
}
return result
}
public func invShiftRows(state:[[UInt8]]) -> [[UInt8]] {
var result = state
for r in 1..<4 {
for c in 0..<variant.Nb {
result[r][(c + r) % variant.Nb] = state[r][c]
}
}
return result
}
// Multiplies two polynomials
public func multiplyPolys(a:UInt8, _ b:UInt8) -> UInt8 {
var a = a, b = b
var p:UInt8 = 0, hbs:UInt8 = 0
for _ in 0..<8 {
if (b & 1 == 1) {
p ^= a
}
hbs = a & 0x80
a <<= 1
if (hbs > 0) {
a ^= 0x1B
}
b >>= 1
}
return p
}
public func matrixMultiplyPolys(matrix:[[UInt8]], _ array:[UInt8]) -> [UInt8] {
var returnArray:[UInt8] = [UInt8](count: array.count, repeatedValue: 0)
for (i, row) in matrix.enumerate() {
for (j, boxVal) in row.enumerate() {
returnArray[i] = multiplyPolys(boxVal, array[j]) ^ returnArray[i]
}
}
return returnArray
}
public func addRoundKey(state:[[UInt8]], _ expandedKeyW:[UInt8], _ round:Int) -> [[UInt8]] {
var newState = [[UInt8]](count: state.count, repeatedValue: [UInt8](count: variant.Nb, repeatedValue: 0))
let idxRow = 4*variant.Nb*round
for c in 0..<variant.Nb {
let idxCol = variant.Nb*c
newState[0][c] = state[0][c] ^ expandedKeyW[idxRow+idxCol+0]
newState[1][c] = state[1][c] ^ expandedKeyW[idxRow+idxCol+1]
newState[2][c] = state[2][c] ^ expandedKeyW[idxRow+idxCol+2]
newState[3][c] = state[3][c] ^ expandedKeyW[idxRow+idxCol+3]
}
return newState
}
// mixes data (independently of one another)
public func mixColumns(state:[[UInt8]]) -> [[UInt8]] {
var state = state
let colBox:[[UInt8]] = [[2,3,1,1],[1,2,3,1],[1,1,2,3],[3,1,1,2]]
var rowMajorState = [[UInt8]](count: state.count, repeatedValue: [UInt8](count: state.first!.count, repeatedValue: 0)) //state.map({ val -> [UInt8] in return val.map { _ in return 0 } }) // zeroing
var newRowMajorState = rowMajorState
for i in 0..<state.count {
for j in 0..<state[0].count {
rowMajorState[j][i] = state[i][j]
}
}
for (i, row) in rowMajorState.enumerate() {
newRowMajorState[i] = matrixMultiplyPolys(colBox, row)
}
for i in 0..<state.count {
for j in 0..<state[0].count {
state[i][j] = newRowMajorState[j][i]
}
}
return state
}
public func invMixColumns(state:[[UInt8]]) -> [[UInt8]] {
var state = state
let invColBox:[[UInt8]] = [[14,11,13,9],[9,14,11,13],[13,9,14,11],[11,13,9,14]]
var colOrderState = state.map({ val -> [UInt8] in return val.map { _ in return 0 } }) // zeroing
for i in 0..<state.count {
for j in 0..<state[0].count {
colOrderState[j][i] = state[i][j]
}
}
var newState = state.map({ val -> [UInt8] in return val.map { _ in return 0 } })
for (i, row) in colOrderState.enumerate() {
newState[i] = matrixMultiplyPolys(invColBox, row)
}
for i in 0..<state.count {
for j in 0..<state[0].count {
state[i][j] = newState[j][i]
}
}
return state
}
} | 37947b75f1c033942a8e2146dbd2c0de | 38.965197 | 211 | 0.536287 | false | false | false | false |
kentya6/Fuwari | refs/heads/master | Fuwari/FloatWindow.swift | mit | 1 | //
// FloatWindow.swift
// Fuwari
//
// Created by Kengo Yokoyama on 2016/12/07.
// Copyright © 2016年 AppKnop. All rights reserved.
//
import Cocoa
import Magnet
import Sauce
import Carbon
protocol FloatDelegate: AnyObject {
func save(floatWindow: FloatWindow, image: CGImage)
func close(floatWindow: FloatWindow)
}
class FloatWindow: NSWindow {
override var canBecomeKey: Bool { return true }
override var canBecomeMain: Bool { return true }
weak var floatDelegate: FloatDelegate? = nil
private var closeButton: NSButton!
private var spaceButton: NSButton!
private var allSpaceMenuItem: NSMenuItem!
private var currentSpaceMenuItem: NSMenuItem!
private var originalRect = NSRect()
private var popUpLabel = NSTextField()
private var windowScale = CGFloat(1.0)
private var windowOpacity = CGFloat(1.0)
private var spaceMode = SpaceMode.all {
didSet {
collectionBehavior = spaceMode.getCollectionBehavior()
if spaceMode == .all {
allSpaceMenuItem.state = .on
currentSpaceMenuItem.state = .off
NSAnimationContext.runAnimationGroup({ context in
context.duration = self.buttonOpacityDuration
self.spaceButton.animator().alphaValue = 0.0
}, completionHandler: {
self.spaceButton.image = NSImage(named: "SpaceAll")
NSAnimationContext.runAnimationGroup({ context in
context.duration = self.buttonOpacityDuration
self.spaceButton.animator().alphaValue = self.buttonOpacity
})
})
} else {
allSpaceMenuItem.state = .off
currentSpaceMenuItem.state = .on
NSAnimationContext.runAnimationGroup({ context in
context.duration = self.buttonOpacityDuration
self.spaceButton.animator().alphaValue = 0.0
}, completionHandler: {
self.spaceButton.image = NSImage(named: "SpaceCurrent")
NSAnimationContext.runAnimationGroup({ context in
context.duration = self.buttonOpacityDuration
self.spaceButton.animator().alphaValue = self.buttonOpacity
})
})
}
}
}
private let defaults = UserDefaults.standard
private let windowScaleInterval = CGFloat(0.25)
private let minWindowScale = CGFloat(0.25)
private let maxWindowScale = CGFloat(2.5)
private let buttonOpacity = CGFloat(0.5)
private let buttonOpacityDuration = TimeInterval(0.3)
init(contentRect: NSRect, styleMask style: NSWindow.StyleMask = [.borderless, .resizable], backing bufferingType: NSWindow.BackingStoreType = .buffered, defer flag: Bool = false, image: CGImage, spaceMode: SpaceMode) {
super.init(contentRect: contentRect, styleMask: style, backing: bufferingType, defer: flag)
contentView = FloatView(frame: contentRect)
originalRect = contentRect
self.spaceMode = spaceMode
collectionBehavior = spaceMode.getCollectionBehavior()
level = .floating
isMovableByWindowBackground = true
hasShadow = true
contentView?.wantsLayer = true
contentView?.layer?.contents = image
minSize = NSMakeSize(30, 30)
animationBehavior = NSWindow.AnimationBehavior.alertPanel
popUpLabel = NSTextField(frame: NSRect(x: 10, y: 10, width: 120, height: 26))
popUpLabel.textColor = .white
popUpLabel.font = NSFont.boldSystemFont(ofSize: 20)
popUpLabel.alignment = .center
popUpLabel.drawsBackground = true
popUpLabel.backgroundColor = NSColor(red: 0.0, green: 0.0, blue: 0.0, alpha: 0.4)
popUpLabel.wantsLayer = true
popUpLabel.layer?.cornerRadius = 10.0
popUpLabel.isBordered = false
popUpLabel.isEditable = false
popUpLabel.isSelectable = false
popUpLabel.alphaValue = 0.0
contentView?.addSubview(popUpLabel)
if let image = NSImage(named: "Close") {
closeButton = NSButton(frame: NSRect(x: 4, y: frame.height - 20, width: 16, height: 16))
closeButton.image = image
closeButton.imageScaling = .scaleProportionallyDown
closeButton.isBordered = false
closeButton.alphaValue = 0.0
closeButton.target = self
closeButton.action = #selector(closeWindow)
contentView?.addSubview(closeButton)
}
if let image = NSImage(named: spaceMode == .all ? "SpaceAll" : "SpaceCurrent") {
spaceButton = NSButton(frame: NSRect(x: frame.width - 20, y: frame.height - 20, width: 16, height: 16))
spaceButton.image = image
spaceButton.imageScaling = .scaleProportionallyDown
spaceButton.isBordered = false
spaceButton.alphaValue = 0.0
spaceButton.target = self
spaceButton.action = #selector(changeSpaceMode)
contentView?.addSubview(spaceButton)
}
allSpaceMenuItem = NSMenuItem(title: LocalizedString.ShowAllSpaces.value, action: #selector(changeSpaceModeAll), keyEquivalent: "k")
currentSpaceMenuItem = NSMenuItem(title: LocalizedString.ShowCurrentSpace.value, action: #selector(changeSpaceModeCurrent), keyEquivalent: "l")
allSpaceMenuItem.state = spaceMode == .all ? .on : .off
currentSpaceMenuItem.state = spaceMode == .all ? .off : .on
menu = NSMenu()
menu?.addItem(NSMenuItem(title: LocalizedString.Copy.value, action: #selector(copyImage), keyEquivalent: "c"))
menu?.addItem(NSMenuItem.separator())
menu?.addItem(NSMenuItem(title: LocalizedString.Save.value, action: #selector(saveImage), keyEquivalent: "s"))
menu?.addItem(NSMenuItem.separator())
menu?.addItem(NSMenuItem(title: LocalizedString.Upload.value, action: #selector(uploadImage), keyEquivalent: ""))
menu?.addItem(NSMenuItem.separator())
menu?.addItem(NSMenuItem(title: LocalizedString.ZoomReset.value, action: #selector(resetWindowScale), keyEquivalent: "r"))
menu?.addItem(NSMenuItem(title: LocalizedString.ResetWindow.value, action: #selector(resetWindow), keyEquivalent: "0"))
menu?.addItem(NSMenuItem(title: LocalizedString.ZoomIn.value, action: #selector(zoomInWindow), keyEquivalent: "+"))
menu?.addItem(NSMenuItem(title: LocalizedString.ZoomOut.value, action: #selector(zoomOutWindow), keyEquivalent: "-"))
menu?.addItem(allSpaceMenuItem)
menu?.addItem(currentSpaceMenuItem)
menu?.addItem(NSMenuItem.separator())
menu?.addItem(NSMenuItem(title: LocalizedString.Close.value, action: #selector(closeWindow), keyEquivalent: "w"))
fadeWindow(isIn: true)
}
func windowDidResize(_ notification: Notification) {
windowScale = frame.width > frame.height ? frame.height / originalRect.height : frame.width / originalRect.width
closeButton.frame = NSRect(x: 4, y: frame.height - 20, width: 16, height: 16)
spaceButton.frame = NSRect(x: frame.width - 20, y: frame.height - 20, width: 16, height: 16)
showPopUp(text: "\(Int(windowScale * 100))%")
}
override func keyDown(with event: NSEvent) {
guard let key = Sauce.shared.key(for: Int(event.keyCode)) else { return }
var moveOffset = (dx: 0.0, dy: 0.0)
switch key {
case .leftArrow:
moveOffset = (dx: -1, dy: 0)
case .rightArrow:
moveOffset = (dx: 1, dy: 0)
case .upArrow:
moveOffset = (dx: 0, dy: 1)
case .downArrow:
moveOffset = (dx: 0, dy: -1)
case .escape:
closeWindow()
default:
break
}
if event.modifierFlags.rawValue & NSEvent.ModifierFlags.shift.rawValue != 0 {
moveOffset = (moveOffset.dx * 10, moveOffset.dy * 10)
}
if moveOffset.dx != 0.0 || moveOffset.dy != 0.0 {
guard let screen = screen else { return }
// clamp offset
if frame.origin.x + moveOffset.dx < screen.frame.origin.x - (frame.width / 2) || (screen.frame.origin.x + screen.frame.width) - (frame.width / 2) < frame.origin.x + moveOffset.dx {
moveOffset.dx = 0
}
if frame.origin.y + moveOffset.dy < screen.frame.origin.y - (frame.height / 2) || (screen.frame.origin.y + screen.frame.height) - (frame.height / 2) < frame.origin.y + moveOffset.dy {
moveOffset.dy = 0
}
moveWindow(dx: moveOffset.dx, dy: moveOffset.dy)
}
if event.modifierFlags.rawValue & NSEvent.ModifierFlags.command.rawValue != 0 {
switch key {
case .s:
saveImage()
case .c:
copyImage()
case .k:
changeSpaceModeAll()
case .l:
changeSpaceModeCurrent()
case .zero, .keypadZero:
resetWindow()
case .one, .keypadOne:
resetWindowScale()
case .equal, .six, .semicolon, .keypadPlus:
zoomInWindow()
case .minus, .keypadMinus:
zoomOutWindow()
case .w:
closeWindow()
default:
break
}
}
}
override func rightMouseDown(with event: NSEvent) {
if let menu = menu, let contentView = contentView {
NSMenu.popUpContextMenu(menu, with: event, for: contentView)
}
}
override func mouseEntered(with event: NSEvent) {
NSAnimationContext.runAnimationGroup { context in
context.duration = self.buttonOpacityDuration
self.closeButton.animator().alphaValue = self.buttonOpacity
self.spaceButton.animator().alphaValue = self.buttonOpacity
}
}
override func mouseExited(with event: NSEvent) {
NSAnimationContext.runAnimationGroup { context in
context.duration = self.buttonOpacityDuration
self.closeButton.animator().alphaValue = 0.0
self.spaceButton.animator().alphaValue = 0.0
}
}
override func scrollWheel(with event: NSEvent) {
let min = CGFloat(0.1), max = CGFloat(1.0)
if windowOpacity > min || windowOpacity < max {
windowOpacity += event.deltaY * 0.005
if windowOpacity < min { windowOpacity = min }
else if windowOpacity > max { windowOpacity = max }
alphaValue = windowOpacity
}
}
override func performClose(_ sender: Any?) {
closeWindow()
}
override func mouseDown(with event: NSEvent) {
let movingOpacity = defaults.float(forKey: Constants.UserDefaults.movingOpacity)
if movingOpacity < 1 {
alphaValue = CGFloat(movingOpacity)
}
closeButton.alphaValue = 0.0
spaceButton.alphaValue = 0.0
}
override func mouseUp(with event: NSEvent) {
alphaValue = windowOpacity
closeButton.alphaValue = buttonOpacity
spaceButton.alphaValue = buttonOpacity
// Double click to close
if event.clickCount >= 2 {
closeWindow()
}
}
@objc private func saveImage() {
DispatchQueue.main.asyncAfter(deadline: .now()) {
if let image = self.contentView?.layer?.contents {
self.showPopUp(text: "Save")
self.floatDelegate?.save(floatWindow: self, image: image as! CGImage)
}
}
}
@objc private func copyImage() {
DispatchQueue.main.asyncAfter(deadline: .now()) {
if let image = self.contentView?.layer?.contents {
let cgImage = image as! CGImage
let size = CGSize(width: cgImage.width, height: cgImage.height)
let nsImage = NSImage(cgImage: cgImage, size: size)
NSPasteboard.general.clearContents()
NSPasteboard.general.writeObjects([nsImage])
self.showPopUp(text: "Copy")
}
}
}
@objc private func uploadImage() {
DispatchQueue.main.asyncAfter(deadline: .now()) {
if let image = self.contentView?.layer?.contents {
let cgImage = image as! CGImage
let size = CGSize(width: cgImage.width, height: cgImage.height)
let nsImage = NSImage(cgImage: cgImage, size: size)
GyazoManager.shared.uploadImage(image: nsImage)
}
}
}
@objc private func zoomInWindow() {
let scale = floor((windowScale + windowScaleInterval) * 100) / 100
if scale <= maxWindowScale {
windowScale = scale
setFrame(NSRect(x: frame.origin.x - (originalRect.width / 2 * windowScaleInterval), y: frame.origin.y - (originalRect.height / 2 * windowScaleInterval), width: originalRect.width * windowScale, height: originalRect.height * windowScale), display: true, animate: true)
}
showPopUp(text: "\(Int(windowScale * 100))%")
}
@objc private func zoomOutWindow() {
let scale = floor((windowScale - windowScaleInterval) * 100) / 100
if scale >= minWindowScale {
windowScale = scale
setFrame(NSRect(x: frame.origin.x + (originalRect.width / 2 * windowScaleInterval), y: frame.origin.y + (originalRect.height / 2 * windowScaleInterval), width: originalRect.width * windowScale, height: originalRect.height * windowScale), display: true, animate: true)
}
showPopUp(text: "\(Int(windowScale * 100))%")
}
@objc private func moveWindow(dx: CGFloat, dy: CGFloat) {
setFrame(NSRect(x: frame.origin.x + dx, y: frame.origin.y + dy, width: frame.width, height: frame.height), display: true, animate: true)
showPopUp(text: "(\(Int(frame.origin.x)),\(Int(frame.origin.y)))")
}
@objc private func resetWindowScale() {
let diffScale = 1.0 - windowScale
windowScale = CGFloat(1.0)
setFrame(NSRect(x: frame.origin.x - (originalRect.width * diffScale / 2), y: frame.origin.y - (originalRect.height * diffScale / 2), width: originalRect.width * windowScale, height: originalRect.height * windowScale), display: true, animate: true)
showPopUp(text: "\(Int(windowScale * 100))%")
}
@objc private func resetWindow() {
windowScale = CGFloat(1.0)
setFrame(originalRect, display: true, animate: true)
}
@objc private func changeSpaceModeAll() {
spaceMode = .all
}
@objc private func changeSpaceModeCurrent() {
spaceMode = .current
}
@objc private func changeSpaceMode() {
spaceMode = spaceMode == .all ? .current : .all
}
@objc private func closeWindow() {
floatDelegate?.close(floatWindow: self)
}
private func showPopUp(text: String, duration: Double = 0.5, interval: Double = 0.5) {
popUpLabel.stringValue = text
NSAnimationContext.runAnimationGroup({ context in
context.duration = duration
context.timingFunction = CAMediaTimingFunction(name: .easeOut)
popUpLabel.animator().alphaValue = 1.0
}) {
DispatchQueue.main.asyncAfter(deadline: .now() + interval) {
NSAnimationContext.runAnimationGroup({ context in
context.duration = duration
context.timingFunction = CAMediaTimingFunction(name: .easeIn)
self.popUpLabel.animator().alphaValue = 0.0
})
}
}
}
internal override func validateMenuItem(_ menuItem: NSMenuItem) -> Bool {
if menuItem.action == #selector(resetWindowScale) {
return windowScale != CGFloat(1.0)
}
return true
}
func fadeWindow(isIn: Bool, completion: (() -> Void)? = nil) {
makeKeyAndOrderFront(self)
NSAnimationContext.runAnimationGroup({ context in
context.duration = 0.2
animator().alphaValue = isIn ? 1.0 : 0.0
}, completionHandler: { [weak self] in
if !isIn {
self?.orderOut(self)
}
completion?()
})
}
}
| 1768735dfe4290349edc5853b58fe6e0 | 40.861809 | 279 | 0.603385 | false | false | false | false |
13983441921/ios-charts | refs/heads/master | Charts/Classes/Renderers/ChartXAxisRendererHorizontalBarChart.swift | apache-2.0 | 3 | //
// ChartXAxisRendererHorizontalBarChart.swift
// Charts
//
// Created by Daniel Cohen Gindi on 3/3/15.
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/ios-charts
//
import Foundation
import CoreGraphics.CGBase
import UIKit.UIFont
public class ChartXAxisRendererHorizontalBarChart: ChartXAxisRendererBarChart
{
public override init(viewPortHandler: ChartViewPortHandler, xAxis: ChartXAxis, transformer: ChartTransformer!, chart: BarChartView)
{
super.init(viewPortHandler: viewPortHandler, xAxis: xAxis, transformer: transformer, chart: chart);
}
public override func computeAxis(#xValAverageLength: Float, xValues: [String?])
{
_xAxis.values = xValues;
var longest = _xAxis.getLongestLabel() as NSString;
var longestSize = longest.sizeWithAttributes([NSFontAttributeName: _xAxis.labelFont]);
_xAxis.labelWidth = floor(longestSize.width + _xAxis.xOffset * 3.5);
_xAxis.labelHeight = longestSize.height;
}
public override func renderAxisLabels(#context: CGContext)
{
if (!_xAxis.isEnabled || !_xAxis.isDrawLabelsEnabled || _chart.data === nil)
{
return;
}
var xoffset = _xAxis.xOffset;
if (_xAxis.labelPosition == .Top)
{
drawLabels(context: context, pos: viewPortHandler.contentRight + xoffset, align: .Left);
}
else if (_xAxis.labelPosition == .Bottom)
{
drawLabels(context: context, pos: viewPortHandler.contentLeft - xoffset, align: .Right);
}
else if (_xAxis.labelPosition == .BottomInside)
{
drawLabels(context: context, pos: viewPortHandler.contentLeft + xoffset, align: .Left);
}
else if (_xAxis.labelPosition == .TopInside)
{
drawLabels(context: context, pos: viewPortHandler.contentRight - xoffset, align: .Right);
}
else
{ // BOTH SIDED
drawLabels(context: context, pos: viewPortHandler.contentLeft, align: .Left);
drawLabels(context: context, pos: viewPortHandler.contentRight, align: .Left);
}
}
/// draws the x-labels on the specified y-position
internal func drawLabels(#context: CGContext, pos: CGFloat, align: NSTextAlignment)
{
var labelFont = _xAxis.labelFont;
var labelTextColor = _xAxis.labelTextColor;
// pre allocate to save performance (dont allocate in loop)
var position = CGPoint(x: 0.0, y: 0.0);
var bd = _chart.data as! BarChartData;
var step = bd.dataSetCount;
for (var i = _minX; i <= _maxX; i += _xAxis.axisLabelModulus)
{
var label = _xAxis.values[i];
if (label == nil)
{
continue;
}
position.x = 0.0;
position.y = CGFloat(i * step) + CGFloat(i) * bd.groupSpace + bd.groupSpace / 2.0;
// consider groups (center label for each group)
if (step > 1)
{
position.y += (CGFloat(step) - 1.0) / 2.0;
}
transformer.pointValueToPixel(&position);
if (viewPortHandler.isInBoundsY(position.y))
{
ChartUtils.drawText(context: context, text: label!, point: CGPoint(x: pos, y: position.y - _xAxis.labelHeight / 2.0), align: align, attributes: [NSFontAttributeName: labelFont, NSForegroundColorAttributeName: labelTextColor]);
}
}
}
private var _gridLineSegmentsBuffer = [CGPoint](count: 2, repeatedValue: CGPoint());
public override func renderGridLines(#context: CGContext)
{
if (!_xAxis.isEnabled || !_xAxis.isDrawGridLinesEnabled || _chart.data === nil)
{
return;
}
CGContextSaveGState(context);
CGContextSetStrokeColorWithColor(context, _xAxis.gridColor.CGColor);
CGContextSetLineWidth(context, _xAxis.gridLineWidth);
if (_xAxis.gridLineDashLengths != nil)
{
CGContextSetLineDash(context, _xAxis.gridLineDashPhase, _xAxis.gridLineDashLengths, _xAxis.gridLineDashLengths.count);
}
else
{
CGContextSetLineDash(context, 0.0, nil, 0);
}
var position = CGPoint(x: 0.0, y: 0.0);
var bd = _chart.data as! BarChartData;
// take into consideration that multiple DataSets increase _deltaX
var step = bd.dataSetCount;
for (var i = _minX; i <= _maxX; i += _xAxis.axisLabelModulus)
{
position.x = 0.0;
position.y = CGFloat(i * step) + CGFloat(i) * bd.groupSpace - 0.5;
transformer.pointValueToPixel(&position);
if (viewPortHandler.isInBoundsY(position.y))
{
_gridLineSegmentsBuffer[0].x = viewPortHandler.contentLeft;
_gridLineSegmentsBuffer[0].y = position.y;
_gridLineSegmentsBuffer[1].x = viewPortHandler.contentRight;
_gridLineSegmentsBuffer[1].y = position.y;
CGContextStrokeLineSegments(context, _gridLineSegmentsBuffer, 2);
}
}
CGContextRestoreGState(context);
}
private var _axisLineSegmentsBuffer = [CGPoint](count: 2, repeatedValue: CGPoint());
public override func renderAxisLine(#context: CGContext)
{
if (!_xAxis.isEnabled || !_xAxis.isDrawAxisLineEnabled)
{
return;
}
CGContextSaveGState(context);
CGContextSetStrokeColorWithColor(context, _xAxis.axisLineColor.CGColor);
CGContextSetLineWidth(context, _xAxis.axisLineWidth);
if (_xAxis.axisLineDashLengths != nil)
{
CGContextSetLineDash(context, _xAxis.axisLineDashPhase, _xAxis.axisLineDashLengths, _xAxis.axisLineDashLengths.count);
}
else
{
CGContextSetLineDash(context, 0.0, nil, 0);
}
if (_xAxis.labelPosition == .Top
|| _xAxis.labelPosition == .TopInside
|| _xAxis.labelPosition == .BothSided)
{
_axisLineSegmentsBuffer[0].x = viewPortHandler.contentRight;
_axisLineSegmentsBuffer[0].y = viewPortHandler.contentTop;
_axisLineSegmentsBuffer[1].x = viewPortHandler.contentRight;
_axisLineSegmentsBuffer[1].y = viewPortHandler.contentBottom;
CGContextStrokeLineSegments(context, _axisLineSegmentsBuffer, 2);
}
if (_xAxis.labelPosition == .Bottom
|| _xAxis.labelPosition == .BottomInside
|| _xAxis.labelPosition == .BothSided)
{
_axisLineSegmentsBuffer[0].x = viewPortHandler.contentLeft;
_axisLineSegmentsBuffer[0].y = viewPortHandler.contentTop;
_axisLineSegmentsBuffer[1].x = viewPortHandler.contentLeft;
_axisLineSegmentsBuffer[1].y = viewPortHandler.contentBottom;
CGContextStrokeLineSegments(context, _axisLineSegmentsBuffer, 2);
}
CGContextRestoreGState(context);
}
private var _limitLineSegmentsBuffer = [CGPoint](count: 2, repeatedValue: CGPoint());
public override func renderLimitLines(#context: CGContext)
{
var limitLines = _xAxis.limitLines;
if (limitLines.count == 0)
{
return;
}
CGContextSaveGState(context);
var trans = transformer.valueToPixelMatrix;
var position = CGPoint(x: 0.0, y: 0.0);
for (var i = 0; i < limitLines.count; i++)
{
var l = limitLines[i];
position.x = 0.0;
position.y = CGFloat(l.limit);
position = CGPointApplyAffineTransform(position, trans);
_limitLineSegmentsBuffer[0].x = viewPortHandler.contentLeft;
_limitLineSegmentsBuffer[0].y = position.y;
_limitLineSegmentsBuffer[1].x = viewPortHandler.contentRight;
_limitLineSegmentsBuffer[1].y = position.y;
CGContextSetStrokeColorWithColor(context, l.lineColor.CGColor);
CGContextSetLineWidth(context, l.lineWidth);
if (l.lineDashLengths != nil)
{
CGContextSetLineDash(context, l.lineDashPhase, l.lineDashLengths!, l.lineDashLengths!.count);
}
else
{
CGContextSetLineDash(context, 0.0, nil, 0);
}
CGContextStrokeLineSegments(context, _limitLineSegmentsBuffer, 2);
var label = l.label;
// if drawing the limit-value label is enabled
if (label.lengthOfBytesUsingEncoding(NSUTF16StringEncoding) > 0)
{
var labelLineHeight = l.valueFont.lineHeight;
let add = CGFloat(4.0);
var xOffset: CGFloat = add;
var yOffset: CGFloat = l.lineWidth + labelLineHeight / 2.0;
if (l.labelPosition == .Right)
{
ChartUtils.drawText(context: context,
text: label,
point: CGPoint(
x: viewPortHandler.contentRight - xOffset,
y: position.y - yOffset - labelLineHeight),
align: .Right,
attributes: [NSFontAttributeName: l.valueFont, NSForegroundColorAttributeName: l.valueTextColor]);
}
else
{
ChartUtils.drawText(context: context,
text: label,
point: CGPoint(
x: viewPortHandler.contentLeft + xOffset,
y: position.y - yOffset - labelLineHeight),
align: .Left,
attributes: [NSFontAttributeName: l.valueFont, NSForegroundColorAttributeName: l.valueTextColor]);
}
}
}
CGContextRestoreGState(context);
}
} | 7ea3ed6138413af8b5b7b343274b6b8b | 36.359431 | 242 | 0.5674 | false | false | false | false |
See-Ku/SK4Toolkit | refs/heads/master | SK4Toolkit/extention/SK4UIPopoverPresentationControllerExtension.swift | mit | 1 | //
// SK4UIPopoverPresentationControllerExtension.swift
// SK4Toolkit
//
// Created by See.Ku on 2016/06/10.
// Copyright (c) 2016 AxeRoad. All rights reserved.
//
import UIKit
extension UIPopoverPresentationController {
/// 表示する位置を指定
public func sk4SetSourceItem(item: AnyObject) {
// UIBarButtonItemか?
if let bar = item as? UIBarButtonItem {
barButtonItem = bar
return
}
// UIViewか?
if let view = item as? UIView {
sk4SetSourceView(view)
return
}
}
/// 表示する位置を指定 ※矢印の向きは自動で判定
public func sk4SetSourceView(view: UIView) {
sourceView = view
sourceRect.size = CGSize()
sourceRect.origin.x = view.bounds.midX
sourceRect.origin.y = view.bounds.midY
guard let sv = view.superview else { return }
let pos = view.center
let base = sv.bounds
if pos.y < base.height / 3 {
sourceRect.origin.y = view.bounds.maxY
permittedArrowDirections = .Up
} else if pos.y > (base.height * 2) / 3 {
sourceRect.origin.y = 0
permittedArrowDirections = .Down
} else if pos.x < base.width / 3 {
sourceRect.origin.x = view.bounds.maxX
permittedArrowDirections = .Left
} else if pos.x > (base.width * 2) / 3 {
sourceRect.origin.x = 0
permittedArrowDirections = .Right
} else {
sourceRect.origin.y = view.bounds.maxY
permittedArrowDirections = .Up
}
}
}
// eof
| eee76e9c2100ca219726c3dca7e29ab4 | 19.569231 | 53 | 0.67988 | false | false | false | false |
AshuMishra/PhotoGallery | refs/heads/develop | AlamoFireTestApp/Pods/Alamofire/Source/ParameterEncoding.swift | apache-2.0 | 33 | // ParameterEncoding.swift
//
// Copyright (c) 2014–2015 Alamofire Software Foundation (http://alamofire.org/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
/**
HTTP method definitions.
See https://tools.ietf.org/html/rfc7231#section-4.3
*/
public enum Method: String {
case OPTIONS, GET, HEAD, POST, PUT, PATCH, DELETE, TRACE, CONNECT
}
// MARK: ParameterEncoding
/**
Used to specify the way in which a set of parameters are applied to a URL request.
- `URL`: Creates a query string to be set as or appended to any existing URL query for `GET`, `HEAD`,
and `DELETE` requests, or set as the body for requests with any other HTTP method. The
`Content-Type` HTTP header field of an encoded request with HTTP body is set to
`application/x-www-form-urlencoded; charset=utf-8`. Since there is no published specification
for how to encode collection types, the convention of appending `[]` to the key for array
values (`foo[]=1&foo[]=2`), and appending the key surrounded by square brackets for nested
dictionary values (`foo[bar]=baz`).
- `URLEncodedInURL`: Creates query string to be set as or appended to any existing URL query. Uses the same
implementation as the `.URL` case, but always applies the encoded result to the URL.
- `JSON`: Uses `NSJSONSerialization` to create a JSON representation of the parameters object, which is
set as the body of the request. The `Content-Type` HTTP header field of an encoded request is
set to `application/json`.
- `PropertyList`: Uses `NSPropertyListSerialization` to create a plist representation of the parameters object,
according to the associated format and write options values, which is set as the body of the
request. The `Content-Type` HTTP header field of an encoded request is set to
`application/x-plist`.
- `Custom`: Uses the associated closure value to construct a new request given an existing request and
parameters.
*/
public enum ParameterEncoding {
case URL
case URLEncodedInURL
case JSON
case PropertyList(NSPropertyListFormat, NSPropertyListWriteOptions)
case Custom((URLRequestConvertible, [String: AnyObject]?) -> (NSMutableURLRequest, NSError?))
/**
Creates a URL request by encoding parameters and applying them onto an existing request.
- parameter URLRequest: The request to have parameters applied
- parameter parameters: The parameters to apply
- returns: A tuple containing the constructed request and the error that occurred during parameter encoding,
if any.
*/
public func encode(
URLRequest: URLRequestConvertible,
parameters: [String: AnyObject]?)
-> (NSMutableURLRequest, NSError?)
{
var mutableURLRequest = URLRequest.URLRequest
guard let parameters = parameters where !parameters.isEmpty else {
return (mutableURLRequest, nil)
}
var encodingError: NSError? = nil
switch self {
case .URL, .URLEncodedInURL:
func query(parameters: [String: AnyObject]) -> String {
var components: [(String, String)] = []
for key in parameters.keys.sort(<) {
let value = parameters[key]!
components += queryComponents(key, value)
}
return (components.map { "\($0)=\($1)" } as [String]).joinWithSeparator("&")
}
func encodesParametersInURL(method: Method) -> Bool {
switch self {
case .URLEncodedInURL:
return true
default:
break
}
switch method {
case .GET, .HEAD, .DELETE:
return true
default:
return false
}
}
if let method = Method(rawValue: mutableURLRequest.HTTPMethod) where encodesParametersInURL(method) {
if let URLComponents = NSURLComponents(URL: mutableURLRequest.URL!, resolvingAgainstBaseURL: false) {
let percentEncodedQuery = (URLComponents.percentEncodedQuery.map { $0 + "&" } ?? "") + query(parameters)
URLComponents.percentEncodedQuery = percentEncodedQuery
mutableURLRequest.URL = URLComponents.URL
}
} else {
if mutableURLRequest.valueForHTTPHeaderField("Content-Type") == nil {
mutableURLRequest.setValue(
"application/x-www-form-urlencoded; charset=utf-8",
forHTTPHeaderField: "Content-Type"
)
}
mutableURLRequest.HTTPBody = query(parameters).dataUsingEncoding(
NSUTF8StringEncoding,
allowLossyConversion: false
)
}
case .JSON:
do {
let options = NSJSONWritingOptions()
let data = try NSJSONSerialization.dataWithJSONObject(parameters, options: options)
mutableURLRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
mutableURLRequest.HTTPBody = data
} catch {
encodingError = error as NSError
}
case .PropertyList(let format, let options):
do {
let data = try NSPropertyListSerialization.dataWithPropertyList(
parameters,
format: format,
options: options
)
mutableURLRequest.setValue("application/x-plist", forHTTPHeaderField: "Content-Type")
mutableURLRequest.HTTPBody = data
} catch {
encodingError = error as NSError
}
case .Custom(let closure):
(mutableURLRequest, encodingError) = closure(mutableURLRequest, parameters)
}
return (mutableURLRequest, encodingError)
}
/**
Creates percent-escaped, URL encoded query string components from the given key-value pair using recursion.
- parameter key: The key of the query component.
- parameter value: The value of the query component.
- returns: The percent-escaped, URL encoded query string components.
*/
public func queryComponents(key: String, _ value: AnyObject) -> [(String, String)] {
var components: [(String, String)] = []
if let dictionary = value as? [String: AnyObject] {
for (nestedKey, value) in dictionary {
components += queryComponents("\(key)[\(nestedKey)]", value)
}
} else if let array = value as? [AnyObject] {
for value in array {
components += queryComponents("\(key)[]", value)
}
} else {
components.append((escape(key), escape("\(value)")))
}
return components
}
/**
Returns a percent-escaped string following RFC 3986 for a query string key or value.
RFC 3986 states that the following characters are "reserved" characters.
- General Delimiters: ":", "#", "[", "]", "@", "?", "/"
- Sub-Delimiters: "!", "$", "&", "'", "(", ")", "*", "+", ",", ";", "="
In RFC 3986 - Section 3.4, it states that the "?" and "/" characters should not be escaped to allow
query strings to include a URL. Therefore, all "reserved" characters with the exception of "?" and "/"
should be percent-escaped in the query string.
- parameter string: The string to be percent-escaped.
- returns: The percent-escaped string.
*/
public func escape(string: String) -> String {
let generalDelimitersToEncode = ":#[]@" // does not include "?" or "/" due to RFC 3986 - Section 3.4
let subDelimitersToEncode = "!$&'()*+,;="
let allowedCharacterSet = NSCharacterSet.URLQueryAllowedCharacterSet().mutableCopy() as! NSMutableCharacterSet
allowedCharacterSet.removeCharactersInString(generalDelimitersToEncode + subDelimitersToEncode)
var escaped = ""
//==========================================================================================================
//
// Batching is required for escaping due to an internal bug in iOS 8.1 and 8.2. Encoding more than a few
// hundred Chinense characters causes various malloc error crashes. To avoid this issue until iOS 8 is no
// longer supported, batching MUST be used for encoding. This introduces roughly a 20% overhead. For more
// info, please refer to:
//
// - https://github.com/Alamofire/Alamofire/issues/206
//
//==========================================================================================================
if #available(iOS 8.3, OSX 10.10, *) {
escaped = string.stringByAddingPercentEncodingWithAllowedCharacters(allowedCharacterSet) ?? string
} else {
let batchSize = 50
var index = string.startIndex
while index != string.endIndex {
let startIndex = index
let endIndex = index.advancedBy(batchSize, limit: string.endIndex)
let range = Range(start: startIndex, end: endIndex)
let substring = string.substringWithRange(range)
escaped += substring.stringByAddingPercentEncodingWithAllowedCharacters(allowedCharacterSet) ?? substring
index = endIndex
}
}
return escaped
}
}
| 4abe44ea322412b55aecab499dbff4bd | 43.083665 | 124 | 0.593041 | false | false | false | false |
AnthonyMDev/Nimble | refs/heads/TableViewCells | Carthage/Checkouts/Commandant/Carthage/Checkouts/Nimble/Sources/Nimble/Matchers/BeLogical.swift | apache-2.0 | 47 | import Foundation
extension Int8: ExpressibleByBooleanLiteral {
public init(booleanLiteral value: Bool) {
self = NSNumber(value: value).int8Value
}
}
extension UInt8: ExpressibleByBooleanLiteral {
public init(booleanLiteral value: Bool) {
self = NSNumber(value: value).uint8Value
}
}
extension Int16: ExpressibleByBooleanLiteral {
public init(booleanLiteral value: Bool) {
self = NSNumber(value: value).int16Value
}
}
extension UInt16: ExpressibleByBooleanLiteral {
public init(booleanLiteral value: Bool) {
self = NSNumber(value: value).uint16Value
}
}
extension Int32: ExpressibleByBooleanLiteral {
public init(booleanLiteral value: Bool) {
self = NSNumber(value: value).int32Value
}
}
extension UInt32: ExpressibleByBooleanLiteral {
public init(booleanLiteral value: Bool) {
self = NSNumber(value: value).uint32Value
}
}
extension Int64: ExpressibleByBooleanLiteral {
public init(booleanLiteral value: Bool) {
self = NSNumber(value: value).int64Value
}
}
extension UInt64: ExpressibleByBooleanLiteral {
public init(booleanLiteral value: Bool) {
self = NSNumber(value: value).uint64Value
}
}
extension Float: ExpressibleByBooleanLiteral {
public init(booleanLiteral value: Bool) {
self = NSNumber(value: value).floatValue
}
}
extension Double: ExpressibleByBooleanLiteral {
public init(booleanLiteral value: Bool) {
self = NSNumber(value: value).doubleValue
}
}
extension Int: ExpressibleByBooleanLiteral {
public init(booleanLiteral value: Bool) {
self = NSNumber(value: value).intValue
}
}
extension UInt: ExpressibleByBooleanLiteral {
public init(booleanLiteral value: Bool) {
self = NSNumber(value: value).uintValue
}
}
internal func rename<T>(_ matcher: Predicate<T>, failureMessage message: ExpectationMessage) -> Predicate<T> {
return Predicate { actualExpression in
let result = try matcher.satisfies(actualExpression)
return PredicateResult(status: result.status, message: message)
}.requireNonNil
}
// MARK: beTrue() / beFalse()
/// A Nimble matcher that succeeds when the actual value is exactly true.
/// This matcher will not match against nils.
public func beTrue() -> Predicate<Bool> {
return rename(equal(true), failureMessage: .expectedActualValueTo("be true"))
}
/// A Nimble matcher that succeeds when the actual value is exactly false.
/// This matcher will not match against nils.
public func beFalse() -> Predicate<Bool> {
return rename(equal(false), failureMessage: .expectedActualValueTo("be false"))
}
// MARK: beTruthy() / beFalsy()
/// A Nimble matcher that succeeds when the actual value is not logically false.
public func beTruthy<T: ExpressibleByBooleanLiteral & Equatable>() -> Predicate<T> {
return Predicate.simpleNilable("be truthy") { actualExpression in
let actualValue = try actualExpression.evaluate()
if let actualValue = actualValue {
return PredicateStatus(bool: actualValue == (true as T))
}
return PredicateStatus(bool: actualValue != nil)
}
}
/// A Nimble matcher that succeeds when the actual value is logically false.
/// This matcher will match against nils.
public func beFalsy<T: ExpressibleByBooleanLiteral & Equatable>() -> Predicate<T> {
return Predicate.simpleNilable("be falsy") { actualExpression in
let actualValue = try actualExpression.evaluate()
if let actualValue = actualValue {
return PredicateStatus(bool: actualValue == (false as T))
}
return PredicateStatus(bool: actualValue == nil)
}
}
#if canImport(Darwin)
extension NMBObjCMatcher {
@objc public class func beTruthyMatcher() -> NMBMatcher {
return NMBPredicate { actualExpression in
let expr = actualExpression.cast { ($0 as? NSNumber)?.boolValue ?? false }
return try beTruthy().satisfies(expr).toObjectiveC()
}
}
@objc public class func beFalsyMatcher() -> NMBMatcher {
return NMBPredicate { actualExpression in
let expr = actualExpression.cast { ($0 as? NSNumber)?.boolValue ?? false }
return try beFalsy().satisfies(expr).toObjectiveC()
}
}
@objc public class func beTrueMatcher() -> NMBMatcher {
return NMBPredicate { actualExpression in
let expr = actualExpression.cast { ($0 as? NSNumber)?.boolValue ?? false }
return try beTrue().satisfies(expr).toObjectiveC()
}
}
@objc public class func beFalseMatcher() -> NMBMatcher {
return NMBPredicate { actualExpression in
let expr = actualExpression.cast { value -> Bool? in
guard let value = value else { return nil }
return (value as? NSNumber)?.boolValue ?? false
}
return try beFalse().satisfies(expr).toObjectiveC()
}
}
}
#endif
| 71bca5829cb42da312b539f702f80f45 | 31.422078 | 110 | 0.680152 | false | false | false | false |
Ossey/WUO-iOS | refs/heads/master | WUO/WUO/Classes/DetailPages/TrendDetail/XYTrendDetaileSelectView.swift | apache-2.0 | 1 | //
// XYTrendDetaileSelectView.swift
// WUO
//
// Created by mofeini on 17/1/20.
// Copyright © 2017年 com.test.demo. All rights reserved.
//
import UIKit
class XYTrendDetaileSelectView: UITableViewHeaderFooterView {
lazy var labelView : XYTrendDetailLabelView = {
let labelView = XYTrendDetailLabelView.init(frame: CGRect.init(x: 0, y: 0, width: SCREENT_W(), height: SIZE_TREND_DETAIL_SELECTVIEW_H), delegate: nil, channelCates: nil, rightBtnWidth: 0)
labelView.itemNameKey = "labelName"
labelView.itemImageNameKey = "labelEname"
return labelView
}()
override init(reuseIdentifier: String?) {
super.init(reuseIdentifier: reuseIdentifier)
contentView.addSubview(labelView)
// 这句代码,尽然引发labelView不能响应事件,肯定是frame不正确导致的,郁闷了
// labelView.frame = contentView.bounds
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| 6d2f2bdc029d60f437a6ab0826bff06a | 28.878788 | 195 | 0.677485 | false | false | false | false |
aronse/Hero | refs/heads/master | Examples/Examples/AppleHomePage/AppleProductViewController.swift | mit | 1 | // The MIT License (MIT)
//
// Copyright (c) 2016 Luke Zhao <[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 UIKit
import Hero
let viewControllerIDs = ["iphone", "watch", "macbook"]
class AppleProductViewController: UIViewController, HeroViewControllerDelegate {
var panGR: UIPanGestureRecognizer!
@IBOutlet weak var imageView: UIImageView!
@IBOutlet weak var primaryLabel: UILabel!
@IBOutlet weak var secondaryLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
panGR = UIPanGestureRecognizer(target: self, action: #selector(pan))
view.addGestureRecognizer(panGR)
}
func applyShrinkModifiers() {
view.heroModifiers = nil
primaryLabel.heroModifiers = [.translate(x:-50, y:(view.center.y - primaryLabel.center.y)/10), .scale(0.9), HeroModifier.duration(0.3)]
secondaryLabel.heroModifiers = [.translate(x:-50, y:(view.center.y - secondaryLabel.center.y)/10), .scale(0.9), HeroModifier.duration(0.3)]
imageView.heroModifiers = [.translate(x:-80), .scale(0.9), HeroModifier.duration(0.3)]
}
func applySlideModifiers() {
view.heroModifiers = [.translate(x: view.bounds.width), .duration(0.3), .beginWith(modifiers: [.zPosition(2)])]
primaryLabel.heroModifiers = [.translate(x:100), .duration(0.3)]
secondaryLabel.heroModifiers = [.translate(x:100), .duration(0.3)]
imageView.heroModifiers = nil
}
enum TransitionState {
case normal, slidingLeft, slidingRight
}
var state: TransitionState = .normal
weak var nextVC: AppleProductViewController?
@objc func pan() {
let translateX = panGR.translation(in: nil).x
let velocityX = panGR.velocity(in: nil).x
switch panGR.state {
case .began, .changed:
let nextState: TransitionState
if state == .normal {
nextState = velocityX < 0 ? .slidingLeft : .slidingRight
} else {
nextState = translateX < 0 ? .slidingLeft : .slidingRight
}
if nextState != state {
Hero.shared.cancel(animate: false)
let currentIndex = viewControllerIDs.index(of: self.title!)!
let nextIndex = (currentIndex + (nextState == .slidingLeft ? 1 : viewControllerIDs.count - 1)) % viewControllerIDs.count
nextVC = self.storyboard!.instantiateViewController(withIdentifier: viewControllerIDs[nextIndex]) as? AppleProductViewController
if nextState == .slidingLeft {
applyShrinkModifiers()
nextVC!.applySlideModifiers()
} else {
applySlideModifiers()
nextVC!.applyShrinkModifiers()
}
state = nextState
hero_replaceViewController(with: nextVC!)
} else {
let progress = abs(translateX / view.bounds.width)
Hero.shared.update(progress)
if state == .slidingLeft, let nextVC = nextVC {
Hero.shared.apply(modifiers: [.translate(x: view.bounds.width + translateX)], to: nextVC.view)
} else {
Hero.shared.apply(modifiers: [.translate(x: translateX)], to: view)
}
}
default:
let progress = (translateX + velocityX) / view.bounds.width
if (progress < 0) == (state == .slidingLeft) && abs(progress) > 0.3 {
Hero.shared.finish()
} else {
Hero.shared.cancel()
}
state = .normal
}
}
func heroWillStartAnimatingTo(viewController: UIViewController) {
if !(viewController is AppleProductViewController) {
view.heroModifiers = [.ignoreSubviewModifiers(recursive: true)]
}
}
}
| 8fc365aee87c0a5212eb9156d62a9918 | 38.77193 | 143 | 0.691442 | false | false | false | false |
cloudconvert/cloudconvert-swift | refs/heads/master | CloudConvert/CloudConvert.swift | mit | 1 | //
// CloudConvert.swift
//
// Copyright (c) 2015 CloudConvert (https://cloudconvert.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.
//
//
// Created by Josias Montag on 03.04.15.
//
import Foundation
import Alamofire
public let apiProtocol = "https"
public let apiHost = "api.cloudconvert.com"
public var apiKey: String = "" {
didSet {
// reset manager instance because we need a new auth header
managerInstance = nil;
}
}
public let errorDomain = "com.cloudconvert.error"
// MARK: - Request
private var managerInstance: Alamofire.SessionManager?
private var manager: Alamofire.SessionManager {
if (managerInstance != nil) {
return managerInstance!
}
let configuration = URLSessionConfiguration.default
configuration.httpAdditionalHeaders = [
"Authorization": "Bearer " + apiKey
]
managerInstance = SessionManager(configuration: configuration)
return managerInstance!
}
/**
*/
private func stringURL(for endpoint: String) -> String {
var url = endpoint
if url.hasPrefix("//") {
url = apiProtocol + ":" + url;
} else if !url.hasPrefix("http") {
url = apiProtocol + "://" + apiHost + url;
}
return url
}
/**
Wrapper for Alamofire.request()
:param: url The URL String, can be relative to api Host
:param: method HTTP Method (.GET, .POST...)
:param: parameters Dictionary of Query String (GET) or JSON Body (POST) parameters
:returns: Alamofire.Request
*/
public func req(url: String, method: Alamofire.HTTPMethod, parameters: Parameters? = nil) -> Alamofire.DataRequest {
var encoding: Alamofire.ParameterEncoding = URLEncoding()
if method == .post {
encoding = JSONEncoding()
}
let strURL = stringURL(for: url)
let request = manager.request(strURL, method: method, parameters: parameters, encoding: encoding)
return request
}
/**
Wrapper for Alamofire.upload()
:param: url The URL String, can be relative to api Host
:param: file The URL to the local file to upload
:returns: Alamofire.Request
*/
public func ccUpload(url: String, file: URL) -> Alamofire.UploadRequest {
let strURL = stringURL(for: url)
let request = manager.upload(file, to: strURL, method: .put)
return request
}
/**
Wrapper for Alamofire.download()
:param: url The URL String, can be relative to api Host
:param: parameters Dictionary of Query String parameters
:param: destination Closure to generate the destination NSURL
:returns: Alamofire.Request
*/
public func ccDownload(url: String, parameters: Parameters? = nil, destination: @escaping Alamofire.DownloadRequest.DownloadFileDestination) -> Alamofire.DownloadRequest {
let strURL = stringURL(for: url)
let request = manager.download(strURL, method: .get, parameters: parameters, to: destination)
return request
}
// MARK: - Process
public protocol ProcessDelegate {
/**
Monitor conversion progress
:param: process The CloudConvert.Process
:param: step Current step of the process; see https://cloudconvert.com/apidoc#status
:param: percent Percentage (0-100) of the current step as Float value
:param: message Description of the current progress
*/
func conversionProgress(process: Process, step: String?, percent: CGFloat?, message: String?)
/**
Conversion completed on server side. This happens before the output file was downloaded!
:param: process The CloudConvert.Process
:param: error Error object if the conversion failed
*/
func conversionCompleted(process: Process?, error: Error?)
/**
Conversion output file was downloaded to local path
:param: process The CloudConvert.Process
:param: path URL of the downloaded output file
*/
func conversionFileDownloaded(process: Process?, path: URL)
}
public class Process: NSObject {
public var delegate: ProcessDelegate? = nil
public var url: String?
private var data: [String: Any]? = [:] {
didSet {
if let url = data?["url"] as? String {
self.url = url
}
}
}
private var currentRequest: Alamofire.Request? = nil
private var waitCompletionHandler: ((Error?) -> Void)? = nil
fileprivate var progressHandler: ((_ step: String?, _ percent: CGFloat?, _ message: String?) -> Void)? = nil
private var refreshTimer: Timer? = nil
subscript(name: String) -> Any? {
return data?[name]
}
override init() { }
init(url: String) {
self.url = url
}
/**
Create Process on the CloudConvert API
:param: parameters Dictionary of parameters. See: https://cloudconvert.com/apidoc#create
:param: completionHandler The code to be executed once the request has finished.
:returns: CloudConvert.Process
*/
public func create(parameters: [String: Any], completionHandler: @escaping (Error?) -> Void) -> Self {
var parameters = parameters
parameters.removeValue(forKey: "file")
parameters.removeValue(forKey: "download")
req(url: "/process", method: .post, parameters: parameters).responseJSON { (response: DataResponse<Any>) in
if let error = response.error {
completionHandler(error)
} else if let dict = response.value as? [String : Any],
let url = dict["url"] as? String {
self.url = url
completionHandler(nil)
} else {
completionHandler(NSError(domain: errorDomain, code: -1, userInfo: nil))
}
}
return self
}
/**
Refresh process data from API
:param: parameters Dictionary of Query String parameters
:param: completionHandler The code to be executed once the request has finished.
:returns: CloudConvert.Process
*/
public func refresh(parameters: Parameters? = nil, completionHandler: ((Error?) -> Void)? = nil) -> Self {
if currentRequest != nil {
// if there is a active refresh request, cancel it
self.currentRequest?.cancel()
}
guard let url = url else {
completionHandler?(NSError(domain: errorDomain, code: -1, userInfo: ["localizedDescription" : "No Process URL!"] ))
return self
}
currentRequest = req(url: url, method: .get, parameters: parameters).responseJSON { [weak self] response in
self?.currentRequest = nil
let currentValue = response.value as? [String : Any]
if let error = response.error {
completionHandler?(error)
} else if let value = currentValue {
self?.data = value
completionHandler?(nil)
}
self?.progressHandler?(currentValue?["step"] as? String, currentValue?["percent"] as? CGFloat, currentValue?["message"] as? String)
if let strongSelf = self {
strongSelf.delegate?.conversionProgress(process: strongSelf, step: currentValue?["step"] as? String, percent: currentValue?["percent"] as? CGFloat, message: currentValue?["message"] as? String)
}
if response.error != nil || (currentValue?["step"] as? String) == "finished" {
// Conversion finished
DispatchQueue.main.async {
self?.refreshTimer?.invalidate()
self?.refreshTimer = nil
}
self?.waitCompletionHandler?(response.error)
self?.waitCompletionHandler = nil
self?.delegate?.conversionCompleted(process: self, error: response.error)
}
}
return self
}
/**
Starts the conversion on the CloudConvert API
:param: parameters Dictionary of parameters. See: https://cloudconvert.com/apidoc#start
:param: completionHandler The code to be executed once the request has finished.
:returns: CloudConvert.Process
*/
public func start(parameters: Parameters? = nil, completionHandler: ((Error?) -> Void)? = nil) -> Self {
guard let url = url else {
completionHandler?(NSError(domain: errorDomain, code: -1, userInfo: ["localizedDescription" : "No Process URL!"] ))
return self
}
var parameters = parameters
let file: URL? = parameters?["file"] as? URL
parameters?.removeValue(forKey: "download")
if let file = file {
parameters?["file"] = file.absoluteString
}
currentRequest = req(url: url, method: .post, parameters: parameters).responseJSON { [weak self] response in
self?.currentRequest = nil
let currentValue = response.value as? [String : Any]
if let error = response.error {
completionHandler?(error)
} else {
self?.data = currentValue
if let file = file, (parameters?["input"] as? String) == "upload" {
// Upload
_ = self?.upload(uploadPath: file, completionHandler: completionHandler)
} else {
completionHandler?(nil)
}
}
}
return self
}
/**
Uploads an input file to the CloudConvert API
:param: uploadPath Local path of the input file.
:param: completionHandler The code to be executed once the upload has finished.
:returns: CloudConvert.Process
*/
public func upload(uploadPath: URL, completionHandler: ((Error?) -> Void)?) -> Self {
if let upload = self.data?["upload"] as? [String: String], var url = upload["url"] {
url += "/" + uploadPath.lastPathComponent
let formatter = ByteCountFormatter()
formatter.allowsNonnumericFormatting = false
currentRequest = ccUpload(url: url, file: uploadPath).uploadProgress(closure: { [weak self] progress in
let totalBytesExpectedToSend = progress.totalUnitCount
let totalBytesSent = progress.completedUnitCount
let percent = CGFloat(totalBytesSent) / CGFloat(totalBytesExpectedToSend)
let message = "Uploading (" + formatter.string(fromByteCount: totalBytesSent) + " / " + formatter.string(fromByteCount: totalBytesExpectedToSend) + ") ..."
if let strongSelf = self {
strongSelf.delegate?.conversionProgress(process: strongSelf, step: "upload", percent: percent, message: message)
strongSelf.progressHandler?("upload", percent, message)
}
}).responseJSON(completionHandler: { (response) in
if let error = response.error {
completionHandler?(error)
} else {
completionHandler?(nil)
}
})
} else {
completionHandler?(NSError(domain: errorDomain, code: -1, userInfo: ["localizedDescription" : "File cannot be uploaded in this process state!"] ))
}
return self
}
/**
Downloads the output file from the CloudConvert API
:param: downloadPath Local path for downloading the output file.
If set to nil a temporary location will be choosen.
Can be set to a directory or a file. Any existing file will be overwritten.
:param: completionHandler The code to be executed once the download has finished.
:returns: CloudConvert.Process
*/
public func download(downloadPath: URL? = nil, completionHandler: ((URL?, Error?) -> Void)?) -> Self {
var downloadPath = downloadPath
if let output = self.data?["output"] as? [String: Any], let url = output["url"] as? String {
let formatter = ByteCountFormatter()
formatter.allowsNonnumericFormatting = false
let destination: DownloadRequest.DownloadFileDestination = { (temporaryURL, response) in
if let downloadName = response.suggestedFilename {
let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
downloadPath = documentsURL.appendingPathComponent(downloadName)
return (downloadPath!, [.removePreviousFile, .createIntermediateDirectories])
} else {
return (temporaryURL, [.removePreviousFile, .createIntermediateDirectories])
}
}
currentRequest = ccDownload(url: url, destination: destination).downloadProgress(closure: { [weak self] progress in
let totalBytesExpectedToSend = progress.totalUnitCount
let totalBytesSent = progress.completedUnitCount
let percent = CGFloat(totalBytesSent) / CGFloat(totalBytesExpectedToSend)
let message = "Uploading (" + formatter.string(fromByteCount: totalBytesSent) + " / " + formatter.string(fromByteCount: totalBytesExpectedToSend) + ") ..."
if let strongSelf = self {
strongSelf.delegate?.conversionProgress(process: strongSelf, step: "download", percent: percent, message: message)
strongSelf.progressHandler?("download", percent, message)
}
}).response(completionHandler: { [weak self] response in
if let strongSelf = self {
strongSelf.delegate?.conversionProgress(process: strongSelf, step: "finished", percent: 100, message: "Conversion finished!")
}
self?.progressHandler?("finished", 100, "Conversion finished!")
completionHandler?(downloadPath, response.error)
if let downloadPath = downloadPath {
self?.delegate?.conversionFileDownloaded(process: self, path: downloadPath)
}
})
} else {
completionHandler?(nil, NSError(domain: errorDomain, code: -1, userInfo: ["localizedDescription" : "Output file not yet available!"] ))
}
return self
}
/**
Waits until the conversion has finished
:param: completionHandler The code to be executed once the conversion has finished.
:returns: CloudConvert.Process
*/
public func wait(completionHandler: ((Error?) -> Void)?) -> Self {
self.waitCompletionHandler = completionHandler
DispatchQueue.main.async {
self.refreshTimer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(Process.refreshTimerTick), userInfo: nil, repeats: true)
}
return self
}
@objc public func refreshTimerTick() {
_ = self.refresh()
}
/**
Cancels the conversion, including any running upload or download.
Also deletes the process from the CloudConvert API.
:returns: CloudConvert.Process
*/
@discardableResult
public func cancel() -> Self {
self.currentRequest?.cancel()
self.currentRequest = nil;
DispatchQueue.main.async {
self.refreshTimer?.invalidate()
self.refreshTimer = nil
}
if let url = self.url {
_ = req(url: url, method: .delete, parameters: nil)
}
return self
}
// Printable
public override var description: String {
return "Process " + (self.url ?? "") + " " + ( data?.description ?? "")
}
}
// MARK: - Methods
/**
Converts a file using the CloudConvert API.
:param: parameters Parameters for the conversion.
Can be generated using the API Console: https://cloudconvert.com/apiconsole
:param: progressHandler Can be used to monitor the progress of the conversion.
Parameters of the Handler:
step: Current step of the process; see https://cloudconvert.com/apidoc#status ;
percent: Percentage (0-100) of the current step as Float value;
message: Description of the current progress
:param: completionHandler The code to be executed once the conversion has finished.
Parameters of the Handler:
path: local NSURL of the downloaded output file;
error: Error if the conversion failed
:returns: A CloudConvert.Porcess object, which can be used to cancel the conversion.
*/
public func convert(parameters: [String: Any], progressHandler: ((_ step: String?, _ percent: CGFloat?, _ message: String?) -> Void)? = nil, completionHandler: ((URL?, Error?) -> Void)? = nil) -> Process {
var process = Process()
process.progressHandler = progressHandler
process = process.create(parameters: parameters) { error in
if let error = error {
completionHandler?(nil, error)
} else {
process = process.start(parameters: parameters) { error in
if let error = error {
completionHandler?(nil, error)
} else {
process = process.wait { error in
if let error = error {
completionHandler?(nil, error)
} else {
if let download = parameters["download"] as? URL {
process = process.download(downloadPath: download, completionHandler: completionHandler)
} else if let download = parameters["download"] as? String, download != "false" {
process = process.download(completionHandler: completionHandler)
} else if let download = parameters["download"] as? Bool, download != false {
process = process.download(completionHandler: completionHandler)
} else {
completionHandler?(nil, nil)
}
}
}
}
}
}
}
return process
}
/**
Find possible conversion types.
:param: parameters Find conversion types for a specific inputformat and/or outputformat.
For example: ["inputformat" : "png"]
See https://cloudconvert.com/apidoc#types
:param: completionHandler The code to be executed once the request has finished.
*/
public func conversionTypes(parameters: [String: Any], completionHandler: @escaping (Array<[String: Any]>?, Error?) -> Void) -> Void {
req(url: "/conversiontypes", method: .get, parameters: parameters).responseJSON { (response) in
if let types = response.value as? Array<[String: Any]> {
completionHandler(types, nil)
} else {
completionHandler(nil, response.error)
}
}
}
| 0b23c363ec51bf220f1736746836bdc7 | 32.54958 | 209 | 0.618225 | false | false | false | false |
CoderST/DYZB | refs/heads/master | DYZB/DYZB/Class/Tools/Category/DownButton.swift | mit | 1 | //
// DownButton.swift
// DYZB
//
// Created by xiudou on 2017/6/22.
// Copyright © 2017年 xiudo. All rights reserved.
//
import UIKit
class DownButton: UIButton {
init(frame: CGRect, title : String, backGroundColor : UIColor?, font : UIFont, cornerRadius : CGFloat? = 0) {
super.init(frame: frame)
backgroundColor = backGroundColor
setTitle(title, for: .normal)
titleLabel?.font = font
layer.cornerRadius = cornerRadius ?? 0
clipsToBounds = true
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| 33302ce0cdded57f5ef8166897658e2b | 22.703704 | 113 | 0.623438 | false | false | false | false |
onevcat/CotEditor | refs/heads/develop | CotEditor/Sources/Collection+String.swift | apache-2.0 | 1 | //
// Collection+String.swift
//
// CotEditor
// https://coteditor.com
//
// Created by 1024jp on 2017-03-19.
//
// ---------------------------------------------------------------------------
//
// © 2017-2020 1024jp
//
// 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
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Foundation
// MARK: Sort
struct StringComparisonOptions: OptionSet {
let rawValue: Int
static let localized = StringComparisonOptions(rawValue: 1 << 0)
static let caseInsensitive = StringComparisonOptions(rawValue: 1 << 1)
}
extension MutableCollection where Self: RandomAccessCollection, Element == String {
/// Sort the collection in place, using the string value that the given key path refers as the comparison between elements.
///
/// - Parameters:
/// - keyPath: The key path to the string to compare.
/// - options: The storategy to compare strings.
mutating func sort(_ keyPath: KeyPath<Element, String> = \Element.self, options: StringComparisonOptions) {
let compare = compareFunction(options: options)
self.sort { compare($0[keyPath: keyPath], $1[keyPath: keyPath]) == .orderedAscending }
}
}
extension Sequence where Element == String {
/// Return the elements of the sequence, sorted using the string value that the given key path refers with the desired string comparison storategy.
///
/// - Parameters:
/// - keyPath: The key path to the string to compare.
/// - options: The storategy to compare strings.
/// - Returns: A sorted array of the sequence’s elements.
func sorted(_ keyPath: KeyPath<Element, String> = \Element.self, options: StringComparisonOptions) -> [Element] {
let compare = compareFunction(options: options)
return self.sorted { compare($0[keyPath: keyPath], $1[keyPath: keyPath]) == .orderedAscending }
}
}
private func compareFunction(options: StringComparisonOptions) -> (String, String) -> ComparisonResult {
switch options {
case [.localized, .caseInsensitive]:
return { $0.localizedCaseInsensitiveCompare($1) }
case [.localized]:
return { $0.localizedCompare($1) }
case [.caseInsensitive]:
return { $0.caseInsensitiveCompare($1) }
case []:
return { $0.compare($1) }
default:
fatalError()
}
}
// MARK: - File Name
extension Collection where Element == String {
/// Create a unique name from the receiver's elements by adding the suffix and also a number if needed.
///
/// - Parameters:
/// - proposedName: The name candidate.
/// - suffix: The name suffix to be appended before the number.
/// - Returns: An unique name.
func createAvailableName(for proposedName: String, suffix: String? = nil) -> String {
let spaceSuffix = suffix.flatMap { " " + $0 } ?? ""
let (rootName, baseCount): (String, Int?) = {
let suffixPattern = NSRegularExpression.escapedPattern(for: spaceSuffix)
let regex = try! NSRegularExpression(pattern: suffixPattern + "(?: ([0-9]+))?$")
guard let result = regex.firstMatch(in: proposedName, range: proposedName.nsRange) else { return (proposedName, nil) }
let root = (proposedName as NSString).substring(to: result.range.location)
let numberRange = result.range(at: 1)
guard numberRange != .notFound else { return (root, nil) }
let number = Int((proposedName as NSString).substring(with: numberRange))
return (root, number)
}()
let baseName = rootName + spaceSuffix
guard baseCount != nil || self.contains(baseName) else { return baseName }
return ((baseCount ?? 2)...).lazy
.map { baseName + " " + String($0) }
.first { !self.contains($0) }!
}
}
| 4e0b01d47c1de83dc5af6feaa35eb2eb | 33.664122 | 151 | 0.61242 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.