repo_name
stringlengths 6
91
| path
stringlengths 8
968
| copies
stringclasses 202
values | size
stringlengths 2
7
| content
stringlengths 61
1.01M
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6
99.8
| line_max
int64 12
1k
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.89
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
XeresRazor/SMeaGOL
|
SmeagolMath/SmeagolMath/Geometry/Vector4.swift
|
1
|
6874
|
//
// Vector4.swift
// Smeagol
//
// Created by Green2, David on 10/3/14.
// Copyright (c) 2014 Digital Worlds. All rights reserved.
//
import Foundation
//
// MARK: - Definition and initializes -
//
public struct Vector4 {
let x: Float
let y: Float
let z: Float
let w: Float
public init(_ x: Float, _ y: Float, _ z: Float, _ w: Float) {
self.x = x
self.y = y
self.z = z
self.w = w
}
public init(s: Float, t: Float, p: Float, q: Float) {
self.x = s
self.y = t
self.z = p
self.w = q
}
public init(r: Float, g: Float, b: Float, a: Float) {
self.x = r
self.y = g
self.z = b
self.w = a
}
public init(array: [Float]) {
assert(array.count == 4, "Vector4 must be instantiated with 4 values.")
self.x = array[0]
self.y = array[1]
self.z = array[2]
self.w = array[3]
}
public init(vector: Vector3, w: Float) {
self.x = vector.x
self.y = vector.y
self.z = vector.z
self.w = w
}
}
//
// MARK: - Property accessors -
//
public extension Vector4 { // Property getters
// Floatexture coordinate properties
public var s: Float {
return self.x
}
public var t: Float {
return self.y
}
public var p: Float {
return self.z
}
public var q: Float {
return self.w
}
// Color properties
public var r: Float {
return self.x
}
public var g: Float {
return self.y
}
public var b: Float {
return self.z
}
public var a: Float {
return self.w
}
// Array property
public subscript (index: Int) -> Float {
assert(index >= 0 && index < 4, "Index must be in the range 0...3")
switch index {
case 0:
return self.x
case 1:
return self.y
case 2:
return self.z
case 3:
return self.w
default:
fatalError("Index out of bounds accessing Vector4")
}
}
}
//
// MARK: - Vector methods -
//
public extension Vector4 {
public func normalize() -> Vector4 {
return self * self.length()
}
public func length() -> Float {
return sqrt(self.x * self.x + self.y * self.y + self.z * self.z + self.w * self.w)
}
public func dot(vector: Vector4) -> Float {
let x: Float = self.x * vector.x
let y: Float = self.y * vector.y
let z: Float = self.z * vector.z
let w: Float = self.w * vector.w
return x + y + z + w
}
public func cross(vector: Vector4) -> Vector4 {
let x: Float = (self.x * vector.z) - (self.z * vector.y)
let y: Float = (self.z * vector.x) - (self.x * vector.z)
let z: Float = (self.x * vector.y) - (self.y * vector.x)
let w: Float = 0.0
return Vector4(x, y, z, w)
}
public func project(on: Vector4) -> Vector4 {
let scale: Float = on.dot(self) / on.dot(self)
return on * scale
}
public func distance(to: Vector4) -> Float {
let lengthVec: Vector4 = self - to
return lengthVec.length()
}
}
//
// MARK: - Operators -
//
public prefix func - (vector: Vector4) -> Vector4 {
return Vector4(-vector.x, -vector.y, -vector.z, -vector.w)
}
public func + (lhs: Vector4, rhs: Vector4) -> Vector4 {
return Vector4(lhs.x + rhs.x, lhs.y + rhs.y, lhs.z + rhs.z, lhs.w + rhs.w)
}
public func += (inout lhs: Vector4, rhs: Vector4) {
lhs = Vector4(lhs.x + rhs.x, lhs.y + rhs.y, lhs.z + rhs.z, lhs.w + rhs.w)
}
public func + (lhs: Vector4, rhs: Float) -> Vector4 {
return Vector4(lhs.x + rhs, lhs.y + rhs, lhs.z + rhs, lhs.w + rhs)
}
public func += (inout lhs: Vector4, rhs: Float) {
lhs = Vector4(lhs.x + rhs, lhs.y + rhs, lhs.z + rhs, lhs.w + rhs)
}
public func - (lhs: Vector4, rhs: Vector4) -> Vector4 {
return Vector4(lhs.x - rhs.x, lhs.y - rhs.y, lhs.z - rhs.z, lhs.w - rhs.w)
}
public func -= (inout lhs: Vector4, rhs: Vector4) {
lhs = Vector4(lhs.x - rhs.x, lhs.y - rhs.y, lhs.z - rhs.z, lhs.w - rhs.w)
}
public func - (lhs: Vector4, rhs: Float) -> Vector4 {
return Vector4(lhs.x - rhs, lhs.y - rhs, lhs.z - rhs, lhs.w - rhs)
}
public func -= (inout lhs: Vector4, rhs: Float) {
lhs = Vector4(lhs.x - rhs, lhs.y - rhs, lhs.z - rhs, lhs.w - rhs)
}
public func * (lhs: Vector4, rhs: Vector4) -> Vector4 {
return Vector4(lhs.x * rhs.x, lhs.y * rhs.y, lhs.z * rhs.z, lhs.w * rhs.w)
}
public func *= (inout lhs: Vector4, rhs: Vector4) {
lhs = Vector4(lhs.x * rhs.x, lhs.y * rhs.y, lhs.z * rhs.z, lhs.w * rhs.w)
}
public func * (lhs: Vector4, rhs: Float) -> Vector4 {
return Vector4(lhs.x * rhs, lhs.y * rhs, lhs.z * rhs, lhs.w * rhs)
}
public func *= (inout lhs: Vector4, rhs: Float) {
lhs = Vector4(lhs.x * rhs, lhs.y * rhs, lhs.z * rhs, lhs.w * rhs)
}
public func / (lhs: Vector4, rhs: Vector4) -> Vector4 {
return Vector4(lhs.x / rhs.x, lhs.y / rhs.y, lhs.z / rhs.z, lhs.w / rhs.w)
}
public func /= (inout lhs: Vector4, rhs: Vector4) {
lhs = Vector4(lhs.x / rhs.x, lhs.y / rhs.y, lhs.z / rhs.z, lhs.w / rhs.w)
}
public func / (lhs: Vector4, rhs: Float) -> Vector4 {
return Vector4(lhs.x / rhs, lhs.y / rhs, lhs.z / rhs, lhs.w / rhs)
}
public func /= (inout lhs: Vector4, rhs: Float) {
lhs = Vector4(lhs.x / rhs, lhs.y / rhs, lhs.z / rhs, lhs.w / rhs)
}
public func == (lhs: Vector4, rhs: Vector4) -> Bool {
return (lhs.x == rhs.x && lhs.y == rhs.y && lhs.z == rhs.z && lhs.w == rhs.w)
}
public func == (lhs: Vector4, rhs: Float) -> Bool {
return (lhs.x == rhs && lhs.y == rhs && lhs.z == rhs && lhs.w == rhs)
}
public func > (lhs: Vector4, rhs: Vector4) -> Bool {
return (lhs.x > rhs.x && lhs.y > rhs.y && lhs.z > rhs.z && lhs.w > rhs.w)
}
public func > (lhs: Vector4, rhs: Float) -> Bool {
return (lhs.x > rhs && lhs.y > rhs && lhs.z > rhs && lhs.w > rhs)
}
public func < (lhs: Vector4, rhs: Vector4) -> Bool {
return (lhs.x < rhs.x && lhs.y < rhs.y && lhs.z < rhs.z && lhs.w < rhs.w)
}
public func < (lhs: Vector4, rhs: Float) -> Bool {
return (lhs.x < rhs && lhs.y < rhs && lhs.z < rhs && lhs.w < rhs)
}
public func >= (lhs: Vector4, rhs: Vector4) -> Bool {
return (lhs.x >= rhs.x && lhs.y >= rhs.y && lhs.z >= rhs.z && lhs.w >= rhs.w)
}
public func >= (lhs: Vector4, rhs: Float) -> Bool {
return (lhs.x >= rhs && lhs.y >= rhs && lhs.z >= rhs && lhs.w >= rhs)
}
public func <= (lhs: Vector4, rhs: Vector4) -> Bool {
return (lhs.x <= rhs.x && lhs.y <= rhs.y && lhs.z <= rhs.z && lhs.w <= rhs.w)
}
public func <= (lhs: Vector4, rhs: Float) -> Bool {
return (lhs.x <= rhs && lhs.y <= rhs && lhs.z <= rhs && lhs.w <= rhs)
}
public func max(lhs: Vector4, rhs: Vector4) -> Vector4 {
return Vector4(
lhs.x > rhs.x ? lhs.x : rhs.x,
lhs.y > rhs.y ? lhs.y : rhs.y,
lhs.z > rhs.z ? lhs.z : rhs.z,
lhs.w > rhs.w ? lhs.w : rhs.w)
}
public func min(lhs: Vector4, rhs: Vector4) -> Vector4 {
return Vector4(
lhs.x < rhs.x ? lhs.x : rhs.x,
lhs.y < rhs.y ? lhs.y : rhs.y,
lhs.z < rhs.z ? lhs.z : rhs.z,
lhs.w < rhs.w ? lhs.w : rhs.w)
}
public func lerp(from: Vector4, to: Vector4, t: Float) -> Vector4 {
return Vector4(
from.x + ((to.x - from.x) * t),
from.y + ((to.y - from.y) * t),
from.z + ((to.z - from.z) * t),
from.w + ((to.w - from.w) * t)
)
}
|
mit
|
fb85c763c04c995da9c99599eb831523
| 23.905797 | 84 | 0.584958 | 2.439319 | false | false | false | false |
sketchytech/SwiftPlaygrounds
|
JoinFlatMapReduce.playground/Pages/Page_1.xcplaygroundpage/Contents.swift
|
1
|
922
|
//: [Previous](@previous)
//: # Similarly different
//: ## join(), reduce() and flatMap() in Swift 2
let nestedArray = [[1,2,3,4],[6,7,8,9]]
//: reduce(), flatMap() and join() can produce the same results
let joined = [].join(nestedArray)
let flattened = nestedArray.flatMap{$0}
let reduced = nestedArray.reduce([], combine: {$0 + $1})
joined // [1, 2, 3, 4, 6, 7, 8, 9]
flattened // [1, 2, 3, 4, 6, 7, 8, 9]
reduced // [1, 2, 3, 4, 6, 7, 8, 9]
//: The differences only real become clear when we want to add elements to the array we're flattening
let joinedPlus = [5].join(nestedArray)
let reducedPlus = nestedArray.reduce([], combine: {$0 + [5] + $1})
let flattenedPlus = nestedArray.flatMap{$0 + [5]}
joinedPlus // [1, 2, 3, 4, 5, 6, 7, 8, 9]
flattenedPlus // [1, 2, 3, 4, 5, 6, 7, 8, 9, 5]
reducedPlus // [5, 1, 2, 3, 4, 5, 6, 7, 8, 9]
//: Look carefully at the position of the 5 in each case.
//: [Next](@next)
|
mit
|
ff14a4c5a7fb97cce5950b3de4f20580
| 34.461538 | 101 | 0.611714 | 2.785498 | false | false | false | false |
JohnSansoucie/MyProject2
|
BlueCapKit/Central/Connectorator.swift
|
1
|
3058
|
//
// Connector.swift
// BlueCap
//
// Created by Troy Stribling on 6/14/14.
// Copyright (c) 2014 gnos.us. All rights reserved.
//
import Foundation
public class Connectorator {
private var timeoutCount = 0
private var disconnectCount = 0
private let promise : StreamPromise<Peripheral>
public var timeoutRetries = -1
public var disconnectRetries = -1
public var connectionTimeout = 10.0
public var characteristicTimeout = 10.0
public init () {
self.promise = StreamPromise<Peripheral>()
}
public init (capacity:Int) {
self.promise = StreamPromise<Peripheral>(capacity:capacity)
}
convenience public init(initializer:((connectorator:Connectorator) -> Void)?) {
self.init()
if let initializer = initializer {
initializer(connectorator:self)
}
}
convenience public init(capacity:Int, initializer:((connectorator:Connectorator) -> Void)?) {
self.init(capacity:capacity)
if let initializer = initializer {
initializer(connectorator:self)
}
}
public func onConnect() -> FutureStream<Peripheral> {
return self.promise.future
}
internal func didTimeout() {
Logger.debug("Connectorator#didTimeout")
if self.timeoutRetries > 0 {
if self.timeoutCount < self.timeoutRetries {
self.callDidTimeout()
++self.timeoutCount
} else {
self.callDidGiveUp()
self.timeoutCount = 0
}
} else {
self.callDidTimeout()
}
}
internal func didDisconnect() {
Logger.debug("Connectorator#didDisconnect")
if self.disconnectRetries > 0 {
if self.disconnectCount < self.disconnectRetries {
++self.disconnectCount
self.callDidDisconnect()
} else {
self.disconnectCount = 0
self.callDidGiveUp()
}
} else {
self.callDidDisconnect()
}
}
internal func didForceDisconnect() {
Logger.debug("Connectorator#didForceDisconnect")
self.promise.failure(BCError.connectoratorForcedDisconnect)
}
internal func didConnect(peripheral:Peripheral) {
Logger.debug("Connectorator#didConnect")
self.promise.success(peripheral)
}
internal func didFailConnect(error:NSError?) {
Logger.debug("Connectorator#didFailConnect")
if let error = error {
self.promise.failure(error)
} else {
self.promise.failure(BCError.connectoratorFailed)
}
}
internal func callDidTimeout() {
self.promise.failure(BCError.connectoratorDisconnect)
}
internal func callDidDisconnect() {
self.promise.failure(BCError.connectoratorTimeout)
}
internal func callDidGiveUp() {
self.promise.failure(BCError.connectoratorGiveUp)
}
}
|
mit
|
bff0344526e97e6db5ef9f50178294f5
| 27.06422 | 97 | 0.600065 | 4.719136 | false | false | false | false |
SwiftMeetupHamburg/pixelated-mosaic-ios
|
Mosaic/Reachability.swift
|
2
|
864
|
import Foundation
import SystemConfiguration
public class Reachability {
class func connectedToNetwork() -> Bool {
var zeroAddress = sockaddr_in()
zeroAddress.sin_len = UInt8(sizeofValue(zeroAddress))
zeroAddress.sin_family = sa_family_t(AF_INET)
guard let defaultRouteReachability = withUnsafePointer(&zeroAddress, {
SCNetworkReachabilityCreateWithAddress(nil, UnsafePointer($0))
}) else {
return false
}
var flags : SCNetworkReachabilityFlags = []
if !SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags) {
return false
}
let isReachable = flags.contains(.Reachable)
let needsConnection = flags.contains(.ConnectionRequired)
return (isReachable && !needsConnection)
}
}
|
agpl-3.0
|
08e3ee4b2b851863b5ecee99e68c384f
| 31.037037 | 78 | 0.636574 | 6.041958 | false | false | false | false |
ibru/Swifter
|
Swifter/SwifterTimelines.swift
|
2
|
6548
|
//
// SwifterTimelines.swift
// Swifter
//
// Copyright (c) 2014 Matt Donnelly.
//
// 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 Swifter {
// Convenience method
private func getTimelineAtPath(path: String, parameters: Dictionary<String, Any>, count: Int? = nil, sinceID: String? = nil, maxID: String? = nil, trimUser: Bool? = nil, contributorDetails: Bool? = nil, includeEntities: Bool? = nil, success: ((statuses: [JSONValue]?) -> Void)? = nil, failure: FailureHandler? = nil) {
var params = parameters
if count != nil {
params["count"] = count!
}
if sinceID != nil {
params["since_id"] = sinceID!
}
if maxID != nil {
params["max_id"] = maxID!
}
if trimUser != nil {
params["trim_user"] = Int(trimUser!)
}
if contributorDetails != nil {
params["contributor_details"] = Int(!contributorDetails!)
}
if includeEntities != nil {
params["include_entities"] = Int(includeEntities!)
}
self.getJSONWithPath(path, baseURL: self.apiURL, parameters: params, uploadProgress: nil, downloadProgress: nil, success: {
json, response in
success?(statuses: json.array)
return
}, failure: failure)
}
/*
GET statuses/mentions_timeline
Returns Tweets (*: mentions for the user)
Returns the 20 most recent mentions (tweets containing a users's @screen_name) for the authenticating user.
The timeline returned is the equivalent of the one seen when you view your mentions on twitter.com.
This method can only return up to 800 tweets.
*/
public func getStatusesMentionTimelineWithCount(count: Int? = nil, sinceID: String? = nil, maxID: String? = nil, trimUser: Bool? = nil, contributorDetails: Bool? = nil, includeEntities: Bool? = nil, success: ((statuses: [JSONValue]?) -> Void)? = nil, failure: FailureHandler?) {
self.getTimelineAtPath("statuses/mentions_timeline.json", parameters: [:], count: count, sinceID: sinceID, maxID: maxID, trimUser: trimUser, contributorDetails: contributorDetails, includeEntities: includeEntities, success: success, failure: failure)
}
/*
GET statuses/user_timeline
Returns Tweets (*: tweets for the user)
Returns a collection of the most recent Tweets posted by the user indicated by the screen_name or user_id parameters.
User timelines belonging to protected users may only be requested when the authenticated user either "owns" the timeline or is an approved follower of the owner.
The timeline returned is the equivalent of the one seen when you view a user's profile on twitter.com.
This method can only return up to 3,200 of a user's most recent Tweets. Native retweets of other statuses by the user is included in this total, regardless of whether include_rts is set to false when requesting this resource.
*/
public func getStatusesUserTimelineWithUserID(userID: String, count: Int? = nil, sinceID: String? = nil, maxID: String? = nil, trimUser: Bool? = nil, contributorDetails: Bool? = nil, includeEntities: Bool? = nil, success: ((statuses: [JSONValue]?) -> Void)? = nil, failure: FailureHandler? = nil) {
let parameters: Dictionary<String, Any> = ["user_id": userID]
self.getTimelineAtPath("statuses/user_timeline.json", parameters: parameters, count: count, sinceID: sinceID, maxID: maxID, trimUser: trimUser, contributorDetails: contributorDetails, includeEntities: includeEntities, success: success, failure: failure)
}
/*
GET statuses/home_timeline
Returns Tweets (*: tweets from people the user follows)
Returns a collection of the most recent Tweets and retweets posted by the authenticating user and the users they follow. The home timeline is central to how most users interact with the Twitter service.
Up to 800 Tweets are obtainable on the home timeline. It is more volatile for users that follow many users or follow users who tweet frequently.
*/
public func getStatusesHomeTimelineWithCount(count: Int? = nil, sinceID: String? = nil, maxID: String? = nil, trimUser: Bool? = nil, contributorDetails: Bool? = nil, includeEntities: Bool? = nil, success: ((statuses: [JSONValue]?) -> Void)? = nil, failure: FailureHandler? = nil) {
self.getTimelineAtPath("statuses/home_timeline.json", parameters: [:], count: count, sinceID: sinceID, maxID: maxID, trimUser: trimUser, contributorDetails: contributorDetails, includeEntities: includeEntities, success: success, failure: failure)
}
/*
GET statuses/retweets_of_me
Returns the most recent tweets authored by the authenticating user that have been retweeted by others. This timeline is a subset of the user's GET statuses/user_timeline. See Working with Timelines for instructions on traversing timelines.
*/
public func getStatusesRetweetsOfMeWithCount(count: Int? = nil, sinceID: String? = nil, maxID: String? = nil, trimUser: Bool? = nil, contributorDetails: Bool? = nil, includeEntities: Bool? = nil, success: ((statuses: [JSONValue]?) -> Void)? = nil, failure: FailureHandler? = nil) {
self.getTimelineAtPath("statuses/retweets_of_me.json", parameters: [:], count: count, sinceID: sinceID, maxID: maxID, trimUser: trimUser, contributorDetails: contributorDetails, includeEntities: includeEntities, success: success, failure: failure)
}
}
|
mit
|
890a0670defbafec9eb04b047ddfa355
| 54.965812 | 322 | 0.707086 | 4.403497 | false | false | false | false |
alfishe/mooshimeter-osx
|
mooshimeter-osx/AppDelegate.swift
|
1
|
2984
|
//
// AppDelegate.swift
// mooshimeter-osx
//
// Created by Dev on 8/27/16.
// Copyright © 2016 alfishe. All rights reserved.
//
import Foundation
import AppKit
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate
{
let bleManager = BLEManager.sharedInstance
var deviceDebugWindow: DeviceDebugWindow?
func applicationDidFinishLaunching(_ aNotification: Notification)
{
bleManager.start()
//showDeviceSelectionWindow()
showDeviceDebugWindow()
}
func applicationWillTerminate(_ aNotification: Notification)
{
print("applicationWillTerminate")
// Unsubscribe from all notifications
NotificationCenter.default.removeObserver(self)
}
func applicationShouldTerminate(_ sender: NSApplication) -> NSApplication.TerminateReply
{
print("applicationShouldTerminate")
var result: NSApplication.TerminateReply = .terminateNow
if DeviceManager.sharedInstance.count() > 0
{
result = NSApplication.TerminateReply.terminateLater
// Disconnect all active peripheral devices asynchronously and notify application to finalize termination
Async.background
{
// Disconnect all devices
DeviceManager.sharedInstance.removeAll()
// Subscribe for notification about all devices disconnection (application will terminate when triggered)
NotificationCenter.default.addObserver(self, selector: #selector(self.exitApplication), name: NSNotification.Name(rawValue: Constants.NOTIFICATION_ALL_DEVICES_DISCONNECTED), object: nil)
// But to be sure that application is not blocked for termination forever - start watchdog closure with termination in 10 seconds
delay(bySeconds: 10)
{
// Delayed code, by default run in main thread
print("Devices disconnection timeout. Enforcing process termination")
NSApplication.shared.reply(toApplicationShouldTerminate: true)
}
}
}
return result
}
func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool
{
return true
}
//MARK: -
//MARK: Helper methods
@objc
fileprivate func exitApplication(_ notification: Notification)
{
print("-> exitApplication")
NSApplication.shared.reply(toApplicationShouldTerminate: true)
}
fileprivate func showDeviceSelectionWindow()
{
let mainStoryboard = NSStoryboard.init(name: "Main", bundle: nil)
let deviceSelectionWindow = mainStoryboard.instantiateController(withIdentifier: "DeviceSelectionWindow") as? NSWindowController
let application = NSApplication.shared
application.runModal(for: (deviceSelectionWindow?.window)!)
}
fileprivate func showDeviceDebugWindow()
{
let debugStoryboard = NSStoryboard.init(name: "Debug", bundle: nil)
deviceDebugWindow = debugStoryboard.instantiateController(withIdentifier: "DeviceDebugWindow") as? DeviceDebugWindow
deviceDebugWindow?.showWindow(self)
}
}
|
mit
|
f44ae06c0ab8004a50f2bcd873d4ee01
| 30.072917 | 194 | 0.737513 | 5.224168 | false | false | false | false |
overtake/TelegramSwift
|
Telegram-Mac/GroupedLayout.swift
|
1
|
25490
|
//
// GroupedLayout.swift
// Telegram
//
// Created by keepcoder on 31/10/2017.
// Copyright © 2017 Telegram. All rights reserved.
//
import Cocoa
import TelegramCore
import TGUIKit
import Postbox
private final class MessagePhotoInfo {
let mid:MessageId
let imageSize: NSSize
let aspectRatio: CGFloat
fileprivate(set) var layoutFrame: NSRect = NSZeroRect
fileprivate(set) var positionFlags: LayoutPositionFlags = .none
init(_ message: Message) {
self.mid = message.id
self.imageSize = ChatLayoutUtils.contentSize(for: message.media[0], with: 320)
self.aspectRatio = self.imageSize.width / self.imageSize.height
}
}
private final class GroupedLayoutAttempt {
let lineCounts:[Int]
let heights:[CGFloat]
init(lineCounts:[Int], heights: [CGFloat]) {
self.lineCounts = lineCounts
self.heights = heights
}
}
enum GroupedMediaType {
case photoOrVideo
case files
}
class GroupedLayout {
private(set) var dimensions: NSSize = NSZeroSize
private var layouts:[MessageId: MessagePhotoInfo] = [:]
private(set) var messages:[Message]
private(set) var type: GroupedMediaType
init(_ messages: [Message], type: GroupedMediaType = .photoOrVideo) {
switch type {
case .photoOrVideo:
self.messages = messages.filter { $0.effectiveMedia!.isInteractiveMedia }
case .files:
self.messages = messages.filter { $0.effectiveMedia is TelegramMediaFile }
}
self.type = type
}
func contentNode(for index: Int) -> ChatMediaContentView.Type {
return ChatLayoutUtils.contentNode(for: messages[index].media[0])
}
var count: Int {
return messages.count
}
func message(at point: NSPoint) -> Message? {
for i in 0 ..< messages.count {
if NSPointInRect(point, frame(at: i)) {
return messages[i]
}
}
return nil
}
func measure(_ maxSize: NSSize, spacing: CGFloat = 4.0) {
var photos: [MessagePhotoInfo] = []
switch type {
case .photoOrVideo:
if messages.count == 1 {
let photo = MessagePhotoInfo(messages[0])
photos.append(photo)
photos[0].layoutFrame = NSMakeRect(0, 0, photos[0].imageSize.width, photos[0].imageSize.height)
photos[0].positionFlags = .none
} else {
var proportions: String = ""
var averageAspectRatio: CGFloat = 1.0
var forceCalc: Bool = false
for message in messages {
let photo = MessagePhotoInfo(message)
photos.append(photo)
if photo.aspectRatio > 1.2 {
proportions += "w"
} else if photo.aspectRatio < 0.8 {
proportions += "n"
} else {
proportions += "q"
}
averageAspectRatio += photo.aspectRatio
if photo.aspectRatio > 2.0 {
forceCalc = true
}
}
let minWidth: CGFloat = 70
let maxAspectRatio = maxSize.width / maxSize.height
if (photos.count > 0) {
averageAspectRatio = averageAspectRatio / CGFloat(photos.count)
}
if !forceCalc {
if photos.count == 2 {
if proportions == "ww" && averageAspectRatio > 1.4 * maxAspectRatio && photos[1].aspectRatio - photos[0].aspectRatio < 0.2 {
let width: CGFloat = maxSize.width
let height:CGFloat = min(width / photos[0].aspectRatio, min(width / photos[1].aspectRatio, (maxSize.height - spacing) / 2.0))
photos[0].layoutFrame = NSMakeRect(0.0, 0.0, width, height)
photos[0].positionFlags = [.top, .left, .right]
photos[1].layoutFrame = NSMakeRect(0.0, height + spacing, width, height)
photos[1].positionFlags = [.bottom, .left, .right]
} else if proportions == "ww" || proportions == "qq" {
let width: CGFloat = (maxSize.width - spacing) / 2.0
let height: CGFloat = min(width / photos[0].aspectRatio, min(width / photos[1].aspectRatio, maxSize.height))
photos[0].layoutFrame = NSMakeRect(0.0, 0.0, width, height)
photos[0].positionFlags = [.top, .left, .bottom]
photos[1].layoutFrame = NSMakeRect(width + spacing, 0.0, width, height)
photos[1].positionFlags = [.top, .right, .bottom]
} else {
let firstWidth: CGFloat = (maxSize.width - spacing) / photos[1].aspectRatio / (1.0 / photos[0].aspectRatio + 1.0 / photos[1].aspectRatio)
let secondWidth: CGFloat = maxSize.width - firstWidth - spacing
let height: CGFloat = min(maxSize.height, min(firstWidth / photos[0].aspectRatio, secondWidth / photos[1].aspectRatio))
photos[0].layoutFrame = NSMakeRect(0.0, 0.0, firstWidth, height)
photos[0].positionFlags = [.top, .left, .bottom]
photos[1].layoutFrame = NSMakeRect(firstWidth + spacing, 0.0, secondWidth, height)
photos[1].positionFlags = [.top, .right, .bottom]
}
} else if photos.count == 3 {
if proportions.hasPrefix("n") {
let firstHeight = maxSize.height
let thirdHeight = min((maxSize.height - spacing) * 0.5, round(photos[1].aspectRatio * (maxSize.width - spacing) / (photos[2].aspectRatio + photos[1].aspectRatio)))
let secondHeight = maxSize.height - thirdHeight - spacing
let rightWidth = max(minWidth, min((maxSize.width - spacing) * 0.5, round(min(thirdHeight * photos[2].aspectRatio, secondHeight * photos[1].aspectRatio))))
let leftWidth = round(min(firstHeight * photos[0].aspectRatio, (maxSize.width - spacing - rightWidth)))
photos[0].layoutFrame = CGRect(x: 0.0, y: 0.0, width: leftWidth, height: firstHeight)
photos[0].positionFlags = [.top, .left, .bottom]
photos[1].layoutFrame = CGRect(x: leftWidth + spacing, y: 0.0, width: rightWidth, height: secondHeight)
photos[1].positionFlags = [.right, .top]
photos[2].layoutFrame = CGRect(x: leftWidth + spacing, y: secondHeight + spacing, width: rightWidth, height: thirdHeight)
photos[2].positionFlags = [.right, .bottom]
} else {
var width = maxSize.width
let firstHeight = floor(min(width / photos[0].aspectRatio, (maxSize.height - spacing) * 0.66))
photos[0].layoutFrame = CGRect(x: 0.0, y: 0.0, width: width, height: firstHeight)
photos[0].positionFlags = [.top, .left, .right]
width = (maxSize.width - spacing) / 2.0
let secondHeight = min(maxSize.height - firstHeight - spacing, round(min(width / photos[1].aspectRatio, width / photos[2].aspectRatio)))
photos[1].layoutFrame = CGRect(x: 0.0, y: firstHeight + spacing, width: width, height: secondHeight)
photos[1].positionFlags = [.left, .bottom]
photos[2].layoutFrame = CGRect(x: width + spacing, y: firstHeight + spacing, width: width, height: secondHeight)
photos[2].positionFlags = [.right, .bottom]
}
} else if photos.count == 4 {
if proportions == "www" || proportions.hasPrefix("w") {
let w: CGFloat = maxSize.width
let h0: CGFloat = min(w / photos[0].aspectRatio, (maxSize.height - spacing) * 0.66)
photos[0].layoutFrame = NSMakeRect(0.0, 0.0, w, h0)
photos[0].positionFlags = [.top, .left, .right]
var h: CGFloat = (maxSize.width - 2 * spacing) / (photos[1].aspectRatio + photos[2].aspectRatio + photos[3].aspectRatio)
let w0: CGFloat = max((maxSize.width - 2 * spacing) * 0.33, h * photos[1].aspectRatio)
var w2: CGFloat = max((maxSize.width - 2 * spacing) * 0.33, h * photos[3].aspectRatio)
var w1: CGFloat = w - w0 - w2 - 2 * spacing
if w1 < minWidth {
w2 -= minWidth - w1
w1 = minWidth
}
h = min(maxSize.height - h0 - spacing, h)
photos[1].layoutFrame = NSMakeRect(0.0, h0 + spacing, w0, h)
photos[1].positionFlags = [.left, .bottom]
photos[2].layoutFrame = NSMakeRect(w0 + spacing, h0 + spacing, w1, h)
photos[2].positionFlags = [.bottom]
photos[3].layoutFrame = NSMakeRect(w0 + w1 + 2 * spacing, h0 + spacing, w2, h)
photos[3].positionFlags = [.right, .bottom]
} else {
let h: CGFloat = maxSize.height
let w0: CGFloat = min(h * photos[0].aspectRatio, (maxSize.width - spacing) * 0.6)
photos[0].layoutFrame = NSMakeRect(0.0, 0.0, w0, h)
photos[0].positionFlags = [.top, .left, .bottom]
var w: CGFloat = (maxSize.height - 2 * spacing) / (1.0 / photos[1].aspectRatio + 1.0 / photos[2].aspectRatio + 1.0 / photos[3].aspectRatio)
let h0: CGFloat = w / photos[1].aspectRatio
let h1: CGFloat = w / photos[2].aspectRatio
let h2: CGFloat = w / photos[3].aspectRatio
w = min(maxSize.width - w0 - spacing, w)
photos[1].layoutFrame = NSMakeRect(w0 + spacing, 0.0, w, h0)
photos[1].positionFlags = [.right, .top]
photos[2].layoutFrame = NSMakeRect(w0 + spacing, h0 + spacing, w, h1)
photos[2].positionFlags = [.right]
photos[3].layoutFrame = NSMakeRect(w0 + spacing, h0 + h1 + 2 * spacing, w, h2)
photos[3].positionFlags = [.right, .bottom]
}
}
}
if forceCalc || photos.count >= 5 {
var croppedRatios:[CGFloat] = []
for photo in photos {
if averageAspectRatio > 1.1 {
croppedRatios.append(max(1.0, photo.aspectRatio))
} else {
croppedRatios.append(min(1.0, photo.aspectRatio))
}
}
func multiHeight(_ ratios: [CGFloat]) -> CGFloat {
var ratioSum: CGFloat = 0
for ratio in ratios {
ratioSum += ratio
}
return (maxSize.width - (CGFloat(ratios.count) - 1) * spacing) / ratioSum
}
var attempts: [GroupedLayoutAttempt] = []
func addAttempt(_ lineCounts:[Int], _ heights:[CGFloat]) {
attempts.append(GroupedLayoutAttempt(lineCounts: lineCounts, heights: heights))
}
addAttempt([croppedRatios.count], [multiHeight(croppedRatios)])
var secondLine:Int = 0
var thirdLine:Int = 0
var fourthLine:Int = 0
for firstLine in 1 ..< croppedRatios.count {
secondLine = croppedRatios.count - firstLine
if firstLine > 3 || secondLine > 3 {
continue
}
addAttempt([firstLine, croppedRatios.count - firstLine], [multiHeight(croppedRatios.subarray(with: NSMakeRange(0, firstLine))), multiHeight(croppedRatios.subarray(with: NSMakeRange(firstLine, croppedRatios.count - firstLine)))])
}
for firstLine in 1 ..< croppedRatios.count - 1 {
for secondLine in 1..<croppedRatios.count - firstLine {
thirdLine = croppedRatios.count - firstLine - secondLine;
if firstLine > 3 || secondLine > (averageAspectRatio < 0.85 ? 4 : 3) || thirdLine > 3 {
continue
}
addAttempt([firstLine, secondLine, thirdLine], [multiHeight(croppedRatios.subarray(with: NSMakeRange(0, firstLine))), multiHeight(croppedRatios.subarray(with: NSMakeRange(firstLine, croppedRatios.count - firstLine - thirdLine))), multiHeight(croppedRatios.subarray(with: NSMakeRange(firstLine + secondLine, croppedRatios.count - firstLine - secondLine)))])
}
}
if croppedRatios.count > 2 {
for firstLine in 1 ..< croppedRatios.count - 2 {
for secondLine in 1 ..< croppedRatios.count - firstLine {
for thirdLine in 1 ..< croppedRatios.count - firstLine - secondLine {
fourthLine = croppedRatios.count - firstLine - secondLine - thirdLine;
if firstLine > 3 || secondLine > 3 || thirdLine > 3 || fourthLine > 3 {
continue
}
addAttempt([firstLine, secondLine, thirdLine, fourthLine], [multiHeight(croppedRatios.subarray(with: NSMakeRange(0, firstLine))), multiHeight(croppedRatios.subarray(with: NSMakeRange(firstLine, croppedRatios.count - firstLine - thirdLine - fourthLine))), multiHeight(croppedRatios.subarray(with: NSMakeRange(firstLine + secondLine, croppedRatios.count - firstLine - secondLine - fourthLine))), multiHeight(croppedRatios.subarray(with: NSMakeRange(firstLine + secondLine + thirdLine, croppedRatios.count - firstLine - secondLine - thirdLine)))])
}
}
}
}
let maxHeight: CGFloat = maxSize.height / 3 * 4
var optimal: GroupedLayoutAttempt? = nil
var optimalDiff: CGFloat = 0.0
for attempt in attempts {
var totalHeight: CGFloat = spacing * (CGFloat(attempt.heights.count) - 1);
var minLineHeight: CGFloat = .greatestFiniteMagnitude;
var maxLineHeight: CGFloat = 0.0
for lineHeight in attempt.heights {
totalHeight += lineHeight
if lineHeight < minLineHeight {
minLineHeight = lineHeight
}
if lineHeight > maxLineHeight {
maxLineHeight = lineHeight;
}
}
var diff: CGFloat = fabs(totalHeight - maxHeight);
if (attempt.lineCounts.count > 1) {
if (attempt.lineCounts[0] > attempt.lineCounts[1])
|| (attempt.lineCounts.count > 2 && attempt.lineCounts[1] > attempt.lineCounts[2])
|| (attempt.lineCounts.count > 3 && attempt.lineCounts[2] > attempt.lineCounts[3]) {
diff *= 1.5
}
}
if minLineHeight < minWidth {
diff *= 1.5
}
if (optimal == nil || diff < optimalDiff)
{
optimal = attempt;
optimalDiff = diff;
}
}
var index: Int = 0
var y: CGFloat = 0.0
if let optimal = optimal {
for i in 0 ..< optimal.lineCounts.count {
let count: Int = optimal.lineCounts[i]
let lineHeight: CGFloat = optimal.heights[i]
var x: CGFloat = 0.0
var positionFlags: LayoutPositionFlags = [.none]
if i == 0 {
positionFlags.insert(.top)
}
if i == optimal.lineCounts.count - 1 {
positionFlags.insert(.bottom)
}
for k in 0 ..< count
{
var innerPositionFlags:LayoutPositionFlags = positionFlags;
if k == 0 {
innerPositionFlags.insert(.left);
}
if k == count - 1 {
innerPositionFlags.insert(.right)
}
if positionFlags == .none {
innerPositionFlags.insert(.inside)
}
let ratio: CGFloat = croppedRatios[index];
let width: CGFloat = ratio * lineHeight;
photos[index].layoutFrame = NSMakeRect(x, y, width, lineHeight);
photos[index].positionFlags = innerPositionFlags;
x += width + spacing;
index += 1
}
y += lineHeight + spacing;
}
}
}
}
var dimensions: CGSize = NSZeroSize
var layouts: [MessageId: MessagePhotoInfo] = [:]
for photo in photos {
layouts[photo.mid] = photo
if photo.layoutFrame.maxX > dimensions.width {
dimensions.width = photo.layoutFrame.maxX
}
if photo.layoutFrame.maxY > dimensions.height {
dimensions.height = photo.layoutFrame.maxY
}
}
for (_, layout) in layouts {
layout.layoutFrame = NSMakeRect(floorToScreenPixels(System.backingScale, layout.layoutFrame.minX), floorToScreenPixels(System.backingScale, layout.layoutFrame.minY), floorToScreenPixels(System.backingScale, layout.layoutFrame.width), floorToScreenPixels(System.backingScale, layout.layoutFrame.height))
}
self.layouts = layouts
self.dimensions = NSMakeSize(floorToScreenPixels(System.backingScale, dimensions.width), floorToScreenPixels(System.backingScale, dimensions.height))
case .files:
var layouts: [MessageId: MessagePhotoInfo] = [:]
var y: CGFloat = 0
for (i, message) in messages.enumerated() {
let info = MessagePhotoInfo(message)
var height:CGFloat = 40
if let file = message.effectiveMedia as? TelegramMediaFile {
if file.isMusicFile {
height = 40
} else if file.previewRepresentations.isEmpty {
height = 40
} else {
height = 70
}
}
info.layoutFrame = NSMakeRect(0, y, maxSize.width, height)
var flags: LayoutPositionFlags = []
if i == 0 {
flags.insert(.top)
flags.insert(.right)
flags.insert(.left)
if messages.count == 1 {
flags.insert(.bottom)
}
} else if i == messages.count - 1 {
flags.insert(.right)
flags.insert(.left)
flags.insert(.bottom)
}
layouts[message.id] = info
y += height + 8
}
self.layouts = layouts
self.dimensions = NSMakeSize(maxSize.width, y - 8)
}
}
func applyCaptions(_ captions: [ChatRowItem.RowCaption]) -> [ChatRowItem.RowCaption] {
var captions = captions
switch self.type {
case .photoOrVideo:
break
case .files:
var offset: CGFloat = 0
for message in messages {
let info = self.layouts[message.id]
let index = captions.firstIndex(where: {$0.id == message.stableId })
if let info = info {
info.layoutFrame = info.layoutFrame.offsetBy(dx: 0, dy: offset)
if let index = index {
let caption = captions[index]
offset += caption.layout.layoutSize.height + 6
}
}
}
self.dimensions.height += offset
for (i, caption) in captions.enumerated() {
if let message = messages.first(where: { $0.stableId == caption.id}), let info = self.layouts[message.id] {
captions[i] = caption.withUpdatedOffset(-(self.dimensions.height - info.layoutFrame.maxY))
}
}
}
return captions
}
func frame(for messageId: MessageId) -> NSRect {
guard let photo = layouts[messageId] else {
return NSZeroRect
}
return photo.layoutFrame
}
func frame(at index: Int) -> NSRect {
return frame(for: messages[index].id)
}
func position(for messageId: MessageId) -> LayoutPositionFlags {
guard let photo = layouts[messageId] else {
return .none
}
return photo.positionFlags
}
func moveItemIfNeeded(at index:Int, point: NSPoint) -> Int? {
for i in 0 ..< count {
let frame = self.frame(at: i)
if NSPointInRect(point, frame) && i != index {
let current = messages[index]
messages.remove(at: index)
messages.insert(current, at: i)
return i
}
}
return nil
}
func isNeedMoveItem(at index:Int, point: NSPoint) -> Bool {
for i in 0 ..< count {
let frame = self.frame(at: i)
if NSPointInRect(point, frame) && i != index {
return true
}
}
return false
}
func position(at index: Int) -> LayoutPositionFlags {
return position(for: messages[index].id)
}
}
|
gpl-2.0
|
9fac1a43a5affda88e9b2abd20650616
| 47.736138 | 580 | 0.452234 | 5.525471 | false | false | false | false |
HJliu1123/LearningNotes-LHJ
|
April/Xbook/Xbook/BookDetail/VIew/HJBookDetailView.swift
|
1
|
3330
|
//
// HJBookDetailView.swift
// Xbook
//
// Created by liuhj on 16/4/12.
// Copyright © 2016年 liuhj. All rights reserved.
//
import UIKit
class HJBookDetailView: UIView {
var VIEW_WIDTH : CGFloat!
var VIEW_HEIGHT : CGFloat!
var Bookname : UILabel?
var Editor : UILabel?
var userName : UILabel?
var date : UILabel?
var more : UILabel?
var score : LDXScore?
var cover : UIImageView?
//各种标签的frame有些值写死了
override init(frame: CGRect) {
super.init(frame: frame)
self.VIEW_HEIGHT = frame.size.height
self.VIEW_WIDTH = frame.size.width
self.cover = UIImageView(frame: CGRectMake(8, 8, (VIEW_WIDTH - 16) / 1.273, VIEW_WIDTH - 16))
self.addSubview(self.cover!)
self.Bookname = UILabel(frame: CGRectMake((VIEW_HEIGHT - 16) / 1.273 + 16, 8, VIEW_WIDTH - (VIEW_HEIGHT - 16) / 1.273 - 16, VIEW_HEIGHT / 4))
self.Bookname?.font = UIFont(name: MY_FONT, size: 18)
self.addSubview(self.Bookname!)
self.Editor = UILabel(frame: CGRectMake((VIEW_HEIGHT - 16) / 1.273 + 16, VIEW_HEIGHT / 4, VIEW_WIDTH - (VIEW_HEIGHT - 16) / 1.273 - 16, VIEW_HEIGHT / 4))
self.Editor?.font = UIFont(name: MY_FONT, size: 18)
self.addSubview(self.Editor!)
self.userName = UILabel(frame: CGRectMake((VIEW_HEIGHT - 16) / 1.273 + 16, VIEW_HEIGHT / 4 + VIEW_HEIGHT / 6, VIEW_WIDTH - (VIEW_HEIGHT - 16) / 1.273 - 16, VIEW_HEIGHT / 6))
self.userName?.font = UIFont(name: MY_FONT, size: 13)
self.userName?.textColor = RGB(35, g: 87, b: 139)
self.addSubview(self.userName!)
self.date = UILabel(frame: CGRectMake((VIEW_HEIGHT - 16) / 1.273 + 16, VIEW_HEIGHT / 4 + VIEW_HEIGHT / 6 * 2 - 8, 80, VIEW_HEIGHT / 6))
self.date?.font = UIFont(name: MY_FONT, size: 13)
self.date?.textColor = RGB(35, g: 87, b: 139)
self.addSubview(self.date!)
self.score = LDXScore(frame: CGRectMake((VIEW_HEIGHT - 16) / 1.273 + 16, 8 + VIEW_HEIGHT / 4 + VIEW_HEIGHT / 6 * 2, 80, VIEW_HEIGHT / 6))
self.score?.isSelect = false
self.score?.normalImg = UIImage(named: "btn_star_evaluation_normal")
self.score?.highlightImg = UIImage(named: "btn_star_evaluation_press")
self.score?.max_star = 5
self.score?.show_star = 5
self.addSubview(self.score!)
self.more = UILabel(frame: CGRectMake((VIEW_HEIGHT - 16) / 1.273 + 16, 24 + VIEW_HEIGHT / 4 + VIEW_HEIGHT / 6 * 2, (VIEW_HEIGHT - 16) / 1.273 - 16, VIEW_HEIGHT / 6))
self.more?.textColor = UIColor.grayColor()
self.more?.font = UIFont(name: MY_FONT, size: 13)
self.addSubview(self.more!)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func drawRect(rect: CGRect) {
let context = UIGraphicsGetCurrentContext()
CGContextSetLineWidth(context, 0.5)
CGContextSetRGBFillColor(context, 231/255, 231/255, 231/255, 1)
CGContextMoveToPoint(context, 8, VIEW_HEIGHT - 2)
CGContextAddLineToPoint(context, VIEW_WIDTH - 8, VIEW_HEIGHT - 2)
CGContextStrokePath(context)
}
}
|
apache-2.0
|
cc8d48659d5d29c721a43143223f2623
| 36.988506 | 181 | 0.595764 | 3.5963 | false | false | false | false |
farzadshbfn/Layoutter
|
LayoutterTests/LayoutterTests.swift
|
1
|
29921
|
//
// LayoutterTests.swift
// LayoutterTests
//
// Created by Farzad Sharbafian on 3/12/17.
// Copyright © 2017 FarzadShbfn. All rights reserved.
//
import XCTest
@testable import Layoutter
/**
A simple layout type to use for testing. We can check the frame after laying
out the rect to see the effect of composing other layouts. Note that this layout's
`Content` is also a `TestLayout`, so these layouts will be at the leaves.
*/
struct TestLayout: Layout {
typealias Content = TestLayout
var frame: CGRect
init(frame: CGRect = .zero) {
self.frame = frame
}
mutating func layout(in rect: CGRect) {
self.frame = rect
}
func sizeThatFits(_ size: CGSize) -> CGSize {
return frame.size
}
var contents: [Content] {
return [self]
}
}
class VerticalDecorationLayoutTests: XCTestCase {
func testSizeThatFits() {
let child1 = TestLayout(frame: CGRect(x: 0, y: 0, width: 30, height: 40))
let child2 = TestLayout(frame: CGRect(x: 0, y: 0, width: 32, height: 40))
let layout = VerticalDecoratingLayout(decoration: child1, content: child2)
// Check if sizeThatFits works correctly
let sizeThatFits = layout.sizeThatFits(CGSize(width: 100, height: 120))
XCTAssertEqual(sizeThatFits, CGSize(width: 48, height: 104))
}
func testLayout_noAlignment() {
let child1 = TestLayout(frame: CGRect(x: 0, y: 0, width: 30, height: 40))
let child2 = TestLayout(frame: CGRect(x: 0, y: 0, width: 32, height: 40))
var layout = VerticalDecoratingLayout(decoration: child1, content: child2, alignment: .center)
layout.layout(in: CGRect(x: 0, y: 0, width: 50, height: 120))
// Check to see that the framse are at expected values with no alignments
XCTAssertEqual(layout.contents[0].frame, CGRect(x: 8, y: 8, width: 34, height: 48))
XCTAssertEqual(layout.contents[1].frame, CGRect(x: 8, y: 64, width: 34, height: 48))
}
func testLayout_bottomAlignment() {
let child1 = TestLayout(frame: CGRect(x: 0, y: 0, width: 30, height: 40))
let child2 = TestLayout(frame: CGRect(x: 0, y: 0, width: 32, height: 40))
var layout = VerticalDecoratingLayout(decoration: child1, content: child2, alignment: .bottom)
layout.layout(in: CGRect(x: 0, y: 0, width: 50, height: 120))
// Check to see that the framse are at expected values with bottom alignment
XCTAssertEqual(layout.contents[0].frame, CGRect(x: 8, y: 8, width: 34, height: 56))
XCTAssertEqual(layout.contents[1].frame, CGRect(x: 8, y: 72, width: 34, height: 40))
}
func testLayout_topAlignment() {
let child1 = TestLayout(frame: CGRect(x: 0, y: 0, width: 30, height: 40))
let child2 = TestLayout(frame: CGRect(x: 0, y: 0, width: 32, height: 40))
var layout = VerticalDecoratingLayout(decoration: child1, content: child2, alignment: .top)
layout.layout(in: CGRect(x: 0, y: 0, width: 50, height: 120))
// Check to see that the framse are at expected values with top alignment
XCTAssertEqual(layout.contents[0].frame, CGRect(x: 8, y: 8, width: 34, height: 40))
XCTAssertEqual(layout.contents[1].frame, CGRect(x: 8, y: 56, width: 34, height: 56))
}
func testLayout_topBottomAlignment() {
let child1 = TestLayout(frame: CGRect(x: 0, y: 0, width: 30, height: 40))
let child2 = TestLayout(frame: CGRect(x: 0, y: 0, width: 32, height: 40))
var layout = VerticalDecoratingLayout(decoration: child1, content: child2, alignment: .fill)
layout.layout(in: CGRect(x: 0, y: 0, width: 50, height: 120))
// Check to see that the framse are at expected values with both alignments
XCTAssertEqual(layout.contents[0].frame, CGRect(x: 8, y: 8, width: 34, height: 40))
XCTAssertEqual(layout.contents[1].frame, CGRect(x: 8, y: 72, width: 34, height: 40))
}
}
class HorizontalDecorationLayoutTests: XCTestCase {
func testSizeThatFits() {
let child1 = TestLayout(frame: CGRect(x: 0, y: 0, width: 30, height: 40))
let child2 = TestLayout(frame: CGRect(x: 0, y: 0, width: 32, height: 40))
let layout = HorizontalDecoratingLayout(decoration: child1, content: child2)
// Check if sizeThatFits works correctly
let sizeThatFits = layout.sizeThatFits(CGSize(width: 100, height: 120))
XCTAssertEqual(sizeThatFits, CGSize(width: 86, height: 56))
}
func testLayout_noAlignment() {
let child1 = TestLayout(frame: CGRect(x: 0, y: 0, width: 30, height: 40))
let child2 = TestLayout(frame: CGRect(x: 0, y: 0, width: 32, height: 40))
var layout = HorizontalDecoratingLayout(decoration: child1, content: child2, alignment: .center)
layout.layout(in: CGRect(x: 0, y: 0, width: 100, height: 60))
// Check to see that the framse are at expected values with no alignments
XCTAssertEqual(layout.contents[0].frame, CGRect(x: 8, y: 8, width: 38, height: 44))
XCTAssertEqual(layout.contents[1].frame, CGRect(x: 54, y: 8, width: 38, height: 44))
}
func testLayout_rightAlignment() {
let child1 = TestLayout(frame: CGRect(x: 0, y: 0, width: 30, height: 40))
let child2 = TestLayout(frame: CGRect(x: 0, y: 0, width: 32, height: 40))
var layout = HorizontalDecoratingLayout(decoration: child1, content: child2, alignment: .right)
layout.layout(in: CGRect(x: 0, y: 0, width: 100, height: 60))
// Check to see that the framse are at expected values with no alignments
XCTAssertEqual(layout.contents[0].frame, CGRect(x: 8, y: 8, width: 44, height: 44))
XCTAssertEqual(layout.contents[1].frame, CGRect(x: 60, y: 8, width: 32, height: 44))
}
func testLayout_leftAlignment() {
let child1 = TestLayout(frame: CGRect(x: 0, y: 0, width: 30, height: 40))
let child2 = TestLayout(frame: CGRect(x: 0, y: 0, width: 32, height: 40))
var layout = HorizontalDecoratingLayout(decoration: child1, content: child2, alignment: .left)
layout.layout(in: CGRect(x: 0, y: 0, width: 100, height: 60))
// Check to see that the framse are at expected values with no alignments
XCTAssertEqual(layout.contents[0].frame, CGRect(x: 8, y: 8, width: 30, height: 44))
XCTAssertEqual(layout.contents[1].frame, CGRect(x: 46, y: 8, width: 46, height: 44))
}
func testLayout_topBottomAlignment() {
let child1 = TestLayout(frame: CGRect(x: 0, y: 0, width: 30, height: 40))
let child2 = TestLayout(frame: CGRect(x: 0, y: 0, width: 32, height: 40))
var layout = HorizontalDecoratingLayout(decoration: child1, content: child2, alignment: .fill)
layout.layout(in: CGRect(x: 0, y: 0, width: 100, height: 60))
// Check to see that the framse are at expected values with no alignments
XCTAssertEqual(layout.contents[0].frame, CGRect(x: 8, y: 8, width: 30, height: 44))
XCTAssertEqual(layout.contents[1].frame, CGRect(x: 60, y: 8, width: 32, height: 44))
}
}
class FloatLayoutTests: XCTestCase {
func testCenter() {
let child = TestLayout(frame: CGRect(x: 0, y: 0, width: 30, height: 40))
var layout = FloatLayout(child: child, verticalAlignment: .center, horizontalAlignment: .center)
layout.layout(in: CGRect(x: 0, y: 0, width: 100, height: 100))
// Check to see that the frames are at expected values with given alignments
XCTAssertEqual(layout.contents[0].frame, CGRect(x: 35, y: 30, width: 30, height: 40))
}
func testTop() {
let child = TestLayout(frame: CGRect(x: 0, y: 0, width: 30, height: 40))
var layout = FloatLayout(child: child, verticalAlignment: .top, horizontalAlignment: .center)
layout.layout(in: CGRect(x: 0, y: 0, width: 100, height: 100))
// Check to see that the frames are at expected values with given alignments
XCTAssertEqual(layout.contents[0].frame, CGRect(x: 35, y: 0, width: 30, height: 40))
}
func testBottom() {
let child = TestLayout(frame: CGRect(x: 0, y: 0, width: 30, height: 40))
var layout = FloatLayout(child: child, verticalAlignment: .bottom, horizontalAlignment: .center)
layout.layout(in: CGRect(x: 0, y: 0, width: 100, height: 100))
// Check to see that the frames are at expected values with given alignments
XCTAssertEqual(layout.contents[0].frame, CGRect(x: 35, y: 60, width: 30, height: 40))
}
func testVerticalFill() {
let child = TestLayout(frame: CGRect(x: 0, y: 0, width: 30, height: 40))
var layout = FloatLayout(child: child, verticalAlignment: .fill, horizontalAlignment: .center)
layout.layout(in: CGRect(x: 0, y: 0, width: 100, height: 100))
// Check to see that the frames are at expected values with given alignments
XCTAssertEqual(layout.contents[0].frame, CGRect(x: 35, y: 0, width: 30, height: 100))
}
func testLeft() {
let child = TestLayout(frame: CGRect(x: 0, y: 0, width: 30, height: 40))
var layout = FloatLayout(child: child, verticalAlignment: .center, horizontalAlignment: .left)
layout.layout(in: CGRect(x: 0, y: 0, width: 100, height: 100))
// Check to see that the frames are at expected values with given alignments
XCTAssertEqual(layout.contents[0].frame, CGRect(x: 0, y: 30, width: 30, height: 40))
}
func testRight() {
let child = TestLayout(frame: CGRect(x: 0, y: 0, width: 30, height: 40))
var layout = FloatLayout(child: child, verticalAlignment: .center, horizontalAlignment: .right)
layout.layout(in: CGRect(x: 0, y: 0, width: 100, height: 100))
// Check to see that the frames are at expected values with given alignments
XCTAssertEqual(layout.contents[0].frame, CGRect(x: 70, y: 30, width: 30, height: 40))
}
func testHorizontalFill() {
let child = TestLayout(frame: CGRect(x: 0, y: 0, width: 30, height: 40))
var layout = FloatLayout(child: child, verticalAlignment: .center, horizontalAlignment: .fill)
layout.layout(in: CGRect(x: 0, y: 0, width: 100, height: 100))
// Check to see that the frames are at expected values with given alignments
XCTAssertEqual(layout.contents[0].frame, CGRect(x: 0, y: 30, width: 100, height: 40))
}
func testFill() {
let child = TestLayout(frame: CGRect(x: 0, y: 0, width: 30, height: 40))
var layout = FloatLayout(child: child, verticalAlignment: .fill, horizontalAlignment: .fill)
layout.layout(in: CGRect(x: 0, y: 0, width: 100, height: 100))
// Check to see that the frames are at expected values with given alignments
XCTAssertEqual(layout.contents[0].frame, CGRect(x: 0, y: 0, width: 100, height: 100))
}
func testBottomRightCorner() {
let child = TestLayout(frame: CGRect(x: 0, y: 0, width: 30, height: 40))
var layout = FloatLayout(child: child, verticalAlignment: .bottom, horizontalAlignment: .right)
layout.layout(in: CGRect(x: 0, y: 0, width: 100, height: 100))
// Check to see that the frames are at expected values with given alignments
XCTAssertEqual(layout.contents[0].frame, CGRect(x: 70, y: 60, width: 30, height: 40))
}
func testTopLeftCorner() {
let child = TestLayout(frame: CGRect(x: 0, y: 0, width: 30, height: 40))
var layout = child.withFloat(verticalAlignment: .top, horizontalAlignment: .left)
layout.layout(in: CGRect(x: 0, y: 0, width: 100, height: 100))
// Check to see that the frames are at expected values with given alignments
XCTAssertEqual(layout.contents[0].frame, CGRect(x: 0, y: 0, width: 30, height: 40))
}
}
class AspectLayoutTests: XCTestCase {
func testHeightCompact() {
let child = TestLayout(frame: CGRect(x: 0, y: 0, width: 30, height: 40))
let layout = child.withAspect(CGSize(width: 1.0, height: 1.0))
XCTAssertEqual(layout.sizeThatFits(CGSize(width: 200.0, height: 30.0)), CGSize(width: 30.0, height: 30.0))
}
func testWidthCompact() {
let child = TestLayout(frame: CGRect(x: 0, y: 0, width: 30, height: 40))
let layout = child.withAspect(CGSize(width: 1.0, height: 1.0))
XCTAssertEqual(layout.sizeThatFits(CGSize(width: 30.0, height: 200.0)), CGSize(width: 30.0, height: 30.0))
}
func testMultiply() {
let child = TestLayout(frame: CGRect(x: 0, y: 0, width: 30, height: 40))
let layout = child.withAspect(CGSize(width: 1.0, height: 2.0))
XCTAssertEqual(layout.sizeThatFits(CGSize(width: 30.0, height: 200.0)), CGSize(width: 30.0, height: 60.0))
}
}
class GridLayoutTests: XCTestCase {
var children: [TestLayout] = [
TestLayout(frame: CGRect(x: 0, y: 0, width: 30, height: 40)),
TestLayout(frame: CGRect(x: 0, y: 0, width: 30, height: 30)),
TestLayout(frame: CGRect(x: 0, y: 0, width: 10, height: 30)),
TestLayout(frame: CGRect(x: 0, y: 0, width: 30, height: 20)),
TestLayout(frame: CGRect(x: 0, y: 0, width: 20, height: 10)),
TestLayout(frame: CGRect(x: 0, y: 0, width: 50, height: 20)),
TestLayout(frame: CGRect(x: 0, y: 0, width: 60, height: 30)),
TestLayout(frame: CGRect(x: 0, y: 0, width: 10, height: 30)),
]
func testVertical_Size() {
let layout = GridLayout(children: children, direction: .vertical(.left), itemSpacing: 4, lineSpacing: 8)
XCTAssertEqual(layout.sizeThatFits(CGSize(width: 1000, height: 1000)), CGSize(width: 268, height: 40))
XCTAssertEqual(layout.sizeThatFits(CGSize(width: 100, height: 1000)), CGSize(width: 78, height: 134))
XCTAssertEqual(layout.sizeThatFits(CGSize(width: 100, height: 100)), CGSize(width: 78, height: 134))
XCTAssertEqual(layout.sizeThatFits(CGSize(width: 78, height: 100)), CGSize(width: 78, height: 134))
XCTAssertEqual(layout.sizeThatFits(CGSize(width: 74, height: 100)), CGSize(width: 74, height: 144))
XCTAssertEqual(layout.sizeThatFits(CGSize(width: 72, height: 100)), CGSize(width: 68, height: 182))
XCTAssertEqual(layout.sizeThatFits(CGSize(width: 10, height: 100)), CGSize(width: 60, height: 266))
}
func testVertical_Left() {
var layout = GridLayout(children: children, direction: .vertical(.left), itemSpacing: 4, lineSpacing: 8)
layout.layout(in: CGRect(x: 10, y: 10, width: 100, height: 244))
XCTAssertEqual(layout.contents[0].frame, CGRect(x: 10, y: 10, width: 30, height: 80))
XCTAssertEqual(layout.contents[1].frame, CGRect(x: 44, y: 10, width: 30, height: 80))
XCTAssertEqual(layout.contents[2].frame, CGRect(x: 78, y: 10, width: 10, height: 80))
XCTAssertEqual(layout.contents[3].frame, CGRect(x: 10, y: 98, width: 30, height: 40))
XCTAssertEqual(layout.contents[4].frame, CGRect(x: 44, y: 98, width: 20, height: 40))
XCTAssertEqual(layout.contents[5].frame, CGRect(x: 10, y: 146, width: 50, height: 40))
XCTAssertEqual(layout.contents[6].frame, CGRect(x: 10, y: 194, width: 60, height: 60))
XCTAssertEqual(layout.contents[7].frame, CGRect(x: 74, y: 194, width: 10, height: 60))
}
func testVertical_Right() {
var layout = GridLayout(children: children, direction: .vertical(.right), itemSpacing: 4, lineSpacing: 8)
layout.layout(in: CGRect(x: 10, y: 10, width: 100, height: 244))
XCTAssertEqual(layout.contents[0].frame, CGRect(x: 32, y: 10, width: 30, height: 80))
XCTAssertEqual(layout.contents[1].frame, CGRect(x: 66, y: 10, width: 30, height: 80))
XCTAssertEqual(layout.contents[2].frame, CGRect(x: 100, y: 10, width: 10, height: 80))
XCTAssertEqual(layout.contents[3].frame, CGRect(x: 56, y: 98, width: 30, height: 40))
XCTAssertEqual(layout.contents[4].frame, CGRect(x: 90, y: 98, width: 20, height: 40))
XCTAssertEqual(layout.contents[5].frame, CGRect(x: 60, y: 146, width: 50, height: 40))
XCTAssertEqual(layout.contents[6].frame, CGRect(x: 36, y: 194, width: 60, height: 60))
XCTAssertEqual(layout.contents[7].frame, CGRect(x: 100, y: 194, width: 10, height: 60))
}
func testVertical_Center() {
var layout = GridLayout(children: children, direction: .vertical(.center), itemSpacing: 4, lineSpacing: 8)
layout.layout(in: CGRect(x: 10, y: 10, width: 100, height: 244))
XCTAssertEqual(layout.contents[0].frame, CGRect(x: 21, y: 10, width: 30, height: 80))
XCTAssertEqual(layout.contents[1].frame, CGRect(x: 55, y: 10, width: 30, height: 80))
XCTAssertEqual(layout.contents[2].frame, CGRect(x: 89, y: 10, width: 10, height: 80))
XCTAssertEqual(layout.contents[3].frame, CGRect(x: 33, y: 98, width: 30, height: 40))
XCTAssertEqual(layout.contents[4].frame, CGRect(x: 67, y: 98, width: 20, height: 40))
XCTAssertEqual(layout.contents[5].frame, CGRect(x: 35, y: 146, width: 50, height: 40))
XCTAssertEqual(layout.contents[6].frame, CGRect(x: 23, y: 194, width: 60, height: 60))
XCTAssertEqual(layout.contents[7].frame, CGRect(x: 87, y: 194, width: 10, height: 60))
}
func testVertical_Fill() {
var layout = GridLayout(children: children, direction: .vertical(.fill), itemSpacing: 4, lineSpacing: 8)
layout.layout(in: CGRect(x: 10, y: 10, width: 92, height: 244))
XCTAssertEqual(layout.contents[0].frame, CGRect(x: 10, y: 10, width: 36, height: 80))
XCTAssertEqual(layout.contents[1].frame, CGRect(x: 50, y: 10, width: 36, height: 80))
XCTAssertEqual(layout.contents[2].frame, CGRect(x: 90, y: 10, width: 12, height: 80))
XCTAssertEqual(layout.contents[3].frame, CGRect(x: 10, y: 98, width: 52.8, height: 40))
XCTAssertEqual(layout.contents[4].frame, CGRect(x: 66.8, y: 98, width: 35.2, height: 40))
XCTAssertEqual(layout.contents[5].frame, CGRect(x: 10, y: 146, width: 92, height: 40))
// XCTAssertEqual(layout.contents[6].frame, CGRect(x: 23, y: 194, width: 75.4285714285714, height: 60))
// XCTAssertEqual(layout.contents[7].frame, CGRect(x: 89.4285714285714, y: 194, width: 12.5714285714286, height: 60))
}
func testVertical_NoSpace_Left() {
var layout = GridLayout(children: children, direction: .vertical(.left), itemSpacing: 4, lineSpacing: 8)
layout.layout(in: CGRect(x: 10, y: 10, width: 8, height: 98))
XCTAssertEqual(layout.contents[0].frame, CGRect(x: 10, y: 10, width: 30, height: 8))
XCTAssertEqual(layout.contents[1].frame, CGRect(x: 10, y: 26, width: 30, height: 6))
XCTAssertEqual(layout.contents[2].frame, CGRect(x: 10, y: 40, width: 10, height: 6))
XCTAssertEqual(layout.contents[3].frame, CGRect(x: 10, y: 54, width: 30, height: 4))
XCTAssertEqual(layout.contents[4].frame, CGRect(x: 10, y: 66, width: 20, height: 2))
XCTAssertEqual(layout.contents[5].frame, CGRect(x: 10, y: 76, width: 50, height: 4))
XCTAssertEqual(layout.contents[6].frame, CGRect(x: 10, y: 88, width: 60, height: 6))
XCTAssertEqual(layout.contents[7].frame, CGRect(x: 10, y: 102, width: 10, height: 6))
}
func testVertical_NoSpace_Right() {
var layout = GridLayout(children: children, direction: .vertical(.right), itemSpacing: 4, lineSpacing: 8)
layout.layout(in: CGRect(x: 10, y: 10, width: 8, height: 98))
XCTAssertEqual(layout.contents[0].frame, CGRect(x: -12, y: 10, width: 30, height: 8))
XCTAssertEqual(layout.contents[1].frame, CGRect(x: -12, y: 26, width: 30, height: 6))
XCTAssertEqual(layout.contents[2].frame, CGRect(x: 8, y: 40, width: 10, height: 6))
XCTAssertEqual(layout.contents[3].frame, CGRect(x: -12, y: 54, width: 30, height: 4))
XCTAssertEqual(layout.contents[4].frame, CGRect(x: -2, y: 66, width: 20, height: 2))
XCTAssertEqual(layout.contents[5].frame, CGRect(x: -32, y: 76, width: 50, height: 4))
XCTAssertEqual(layout.contents[6].frame, CGRect(x: -42, y: 88, width: 60, height: 6))
XCTAssertEqual(layout.contents[7].frame, CGRect(x: 8, y: 102, width: 10, height: 6))
}
func testVertical_NoSpace_Center() {
var layout = GridLayout(children: children, direction: .vertical(.center), itemSpacing: 4, lineSpacing: 8)
layout.layout(in: CGRect(x: 10, y: 10, width: 8, height: 98))
XCTAssertEqual(layout.contents[0].frame, CGRect(x: -1, y: 10, width: 30, height: 8))
XCTAssertEqual(layout.contents[1].frame, CGRect(x: -1, y: 26, width: 30, height: 6))
XCTAssertEqual(layout.contents[2].frame, CGRect(x: 9, y: 40, width: 10, height: 6))
XCTAssertEqual(layout.contents[3].frame, CGRect(x: -1, y: 54, width: 30, height: 4))
XCTAssertEqual(layout.contents[4].frame, CGRect(x: 4, y: 66, width: 20, height: 2))
XCTAssertEqual(layout.contents[5].frame, CGRect(x: -11, y: 76, width: 50, height: 4))
XCTAssertEqual(layout.contents[6].frame, CGRect(x: -16, y: 88, width: 60, height: 6))
XCTAssertEqual(layout.contents[7].frame, CGRect(x: 9, y: 102, width: 10, height: 6))
}
func testVertical_NoSpace_Fill() {
var layout = GridLayout(children: children, direction: .vertical(.fill), itemSpacing: 4, lineSpacing: 8)
layout.layout(in: CGRect(x: 10, y: 10, width: 8, height: 98))
XCTAssertEqual(layout.contents[0].frame, CGRect(x: 10, y: 10, width: 8, height: 8))
XCTAssertEqual(layout.contents[1].frame, CGRect(x: 10, y: 26, width: 8, height: 6))
XCTAssertEqual(layout.contents[2].frame, CGRect(x: 10, y: 40, width: 8, height: 6))
XCTAssertEqual(layout.contents[3].frame, CGRect(x: 10, y: 54, width: 8, height: 4))
XCTAssertEqual(layout.contents[4].frame, CGRect(x: 10, y: 66, width: 8, height: 2))
XCTAssertEqual(layout.contents[5].frame, CGRect(x: 10, y: 76, width: 8, height: 4))
XCTAssertEqual(layout.contents[6].frame, CGRect(x: 10, y: 88, width: 8, height: 6))
XCTAssertEqual(layout.contents[7].frame, CGRect(x: 10, y: 102, width: 8, height: 6))
}
func testHorizontal_Size() {
let layout = GridLayout(children: children, direction: .horizontal(.top), itemSpacing: 4, lineSpacing: 8)
XCTAssertEqual(layout.sizeThatFits(CGSize(width: 100, height: 1000)), CGSize(width: 60, height: 238))
XCTAssertEqual(layout.sizeThatFits(CGSize(width: 100, height: 110)), CGSize(width: 116, height: 108))
XCTAssertEqual(layout.sizeThatFits(CGSize(width: 100, height: 108)), CGSize(width: 116, height: 108))
XCTAssertEqual(layout.sizeThatFits(CGSize(width: 78, height: 92)), CGSize(width: 156, height: 92))
XCTAssertEqual(layout.sizeThatFits(CGSize(width: 74, height: 76)), CGSize(width: 154, height: 74))
XCTAssertEqual(layout.sizeThatFits(CGSize(width: 1000, height: 10)), CGSize(width: 296, height: 40))
}
func testHorizontal_Top() {
var layout = GridLayout(children: children, direction: .horizontal(.top), itemSpacing: 4, lineSpacing: 8)
layout.layout(in: CGRect(x: 10, y: 10, width: 156, height: 92))
XCTAssertEqual(layout.contents[0].frame, CGRect(x: 10, y: 10, width: 30, height: 40))
XCTAssertEqual(layout.contents[1].frame, CGRect(x: 10, y: 54, width: 30, height: 30))
XCTAssertEqual(layout.contents[2].frame, CGRect(x: 48, y: 10, width: 50, height: 30))
XCTAssertEqual(layout.contents[3].frame, CGRect(x: 48, y: 44, width: 50, height: 20))
XCTAssertEqual(layout.contents[4].frame, CGRect(x: 48, y: 68, width: 50, height: 10))
XCTAssertEqual(layout.contents[5].frame, CGRect(x: 48, y: 82, width: 50, height: 20))
XCTAssertEqual(layout.contents[6].frame, CGRect(x: 106, y: 10, width: 60, height: 30))
XCTAssertEqual(layout.contents[7].frame, CGRect(x: 106, y: 44, width: 60, height: 30))
}
func testHorizontal_Bottom() {
var layout = GridLayout(children: children, direction: .horizontal(.bottom), itemSpacing: 4, lineSpacing: 8)
layout.layout(in: CGRect(x: 10, y: 10, width: 156, height: 92))
XCTAssertEqual(layout.contents[0].frame, CGRect(x: 10, y: 28, width: 30, height: 40))
XCTAssertEqual(layout.contents[1].frame, CGRect(x: 10, y: 72, width: 30, height: 30))
XCTAssertEqual(layout.contents[2].frame, CGRect(x: 48, y: 10, width: 50, height: 30))
XCTAssertEqual(layout.contents[3].frame, CGRect(x: 48, y: 44, width: 50, height: 20))
XCTAssertEqual(layout.contents[4].frame, CGRect(x: 48, y: 68, width: 50, height: 10))
XCTAssertEqual(layout.contents[5].frame, CGRect(x: 48, y: 82, width: 50, height: 20))
XCTAssertEqual(layout.contents[6].frame, CGRect(x: 106, y: 38, width: 60, height: 30))
XCTAssertEqual(layout.contents[7].frame, CGRect(x: 106, y: 72, width: 60, height: 30))
}
func testHorizontal_Center() {
var layout = GridLayout(children: children, direction: .horizontal(.center), itemSpacing: 4, lineSpacing: 8)
layout.layout(in: CGRect(x: 10, y: 10, width: 156, height: 92))
XCTAssertEqual(layout.contents[0].frame, CGRect(x: 10, y: 19, width: 30, height: 40))
XCTAssertEqual(layout.contents[1].frame, CGRect(x: 10, y: 63, width: 30, height: 30))
XCTAssertEqual(layout.contents[2].frame, CGRect(x: 48, y: 10, width: 50, height: 30))
XCTAssertEqual(layout.contents[3].frame, CGRect(x: 48, y: 44, width: 50, height: 20))
XCTAssertEqual(layout.contents[4].frame, CGRect(x: 48, y: 68, width: 50, height: 10))
XCTAssertEqual(layout.contents[5].frame, CGRect(x: 48, y: 82, width: 50, height: 20))
XCTAssertEqual(layout.contents[6].frame, CGRect(x: 106, y: 24, width: 60, height: 30))
XCTAssertEqual(layout.contents[7].frame, CGRect(x: 106, y: 58, width: 60, height: 30))
}
func testHorizontal_Fill() {
var layout = GridLayout(children: children, direction: .horizontal(.fill), itemSpacing: 4, lineSpacing: 8)
layout.layout(in: CGRect(x: 10, y: 10, width: 116, height: 108))
XCTAssertEqual(layout.contents[0].frame, CGRect(x: 10, y: 10, width: 30, height: 40))
XCTAssertEqual(layout.contents[1].frame, CGRect(x: 10, y: 54, width: 30, height: 30))
XCTAssertEqual(layout.contents[2].frame, CGRect(x: 10, y: 88, width: 30, height: 30))
XCTAssertEqual(layout.contents[3].frame, CGRect(x: 48, y: 10, width: 60, height: 24))
XCTAssertEqual(layout.contents[4].frame, CGRect(x: 48, y: 38, width: 60, height: 12))
XCTAssertEqual(layout.contents[5].frame, CGRect(x: 48, y: 54, width: 60, height: 24))
XCTAssertEqual(layout.contents[6].frame, CGRect(x: 48, y: 82, width: 60, height: 36))
XCTAssertEqual(layout.contents[7].frame, CGRect(x: 116, y: 10, width: 10, height: 108))
}
func testHorizontal_NoSpace_Top() {
var layout = GridLayout(children: children, direction: .horizontal(.top), itemSpacing: 4, lineSpacing: 8)
layout.layout(in: CGRect(x: 10, y: 10, width: 104, height: 8))
XCTAssertEqual(layout.contents[0].frame, CGRect(x: 10, y: 10, width: 6, height: 40))
XCTAssertEqual(layout.contents[1].frame, CGRect(x: 24, y: 10, width: 6, height: 30))
XCTAssertEqual(layout.contents[2].frame, CGRect(x: 38, y: 10, width: 2, height: 30))
XCTAssertEqual(layout.contents[3].frame, CGRect(x: 48, y: 10, width: 6, height: 20))
XCTAssertEqual(layout.contents[4].frame, CGRect(x: 62, y: 10, width: 4, height: 10))
XCTAssertEqual(layout.contents[5].frame, CGRect(x: 74, y: 10, width: 10, height: 20))
XCTAssertEqual(layout.contents[6].frame, CGRect(x: 92, y: 10, width: 12, height: 30))
XCTAssertEqual(layout.contents[7].frame, CGRect(x: 112, y: 10, width: 2, height: 30))
}
func testHorizontal_NoSpace_Bottom() {
var layout = GridLayout(children: children, direction: .horizontal(.bottom), itemSpacing: 4, lineSpacing: 8)
layout.layout(in: CGRect(x: 10, y: 10, width: 104, height: 8))
XCTAssertEqual(layout.contents[0].frame, CGRect(x: 10, y: -22, width: 6, height: 40))
XCTAssertEqual(layout.contents[1].frame, CGRect(x: 24, y: -12, width: 6, height: 30))
XCTAssertEqual(layout.contents[2].frame, CGRect(x: 38, y: -12, width: 2, height: 30))
XCTAssertEqual(layout.contents[3].frame, CGRect(x: 48, y: -2, width: 6, height: 20))
XCTAssertEqual(layout.contents[4].frame, CGRect(x: 62, y: 8, width: 4, height: 10))
XCTAssertEqual(layout.contents[5].frame, CGRect(x: 74, y: -2, width: 10, height: 20))
XCTAssertEqual(layout.contents[6].frame, CGRect(x: 92, y: -12, width: 12, height: 30))
XCTAssertEqual(layout.contents[7].frame, CGRect(x: 112, y: -12, width: 2, height: 30))
}
func testHorizontal_NoSpace_Center() {
var layout = GridLayout(children: children, direction: .horizontal(.center), itemSpacing: 4, lineSpacing: 8)
layout.layout(in: CGRect(x: 10, y: 10, width: 104, height: 8))
XCTAssertEqual(layout.contents[0].frame, CGRect(x: 10, y: -6, width: 6, height: 40))
XCTAssertEqual(layout.contents[1].frame, CGRect(x: 24, y: -1, width: 6, height: 30))
XCTAssertEqual(layout.contents[2].frame, CGRect(x: 38, y: -1, width: 2, height: 30))
XCTAssertEqual(layout.contents[3].frame, CGRect(x: 48, y: 4, width: 6, height: 20))
XCTAssertEqual(layout.contents[4].frame, CGRect(x: 62, y: 9, width: 4, height: 10))
XCTAssertEqual(layout.contents[5].frame, CGRect(x: 74, y: 4, width: 10, height: 20))
XCTAssertEqual(layout.contents[6].frame, CGRect(x: 92, y: -1, width: 12, height: 30))
XCTAssertEqual(layout.contents[7].frame, CGRect(x: 112, y: -1, width: 2, height: 30))
}
func testHorizontal_NoSpace_Fill() {
var layout = GridLayout(children: children, direction: .horizontal(.fill), itemSpacing: 4, lineSpacing: 8)
layout.layout(in: CGRect(x: 10, y: 10, width: 104, height: 8))
XCTAssertEqual(layout.contents[0].frame, CGRect(x: 10, y: 10, width: 6, height: 8))
XCTAssertEqual(layout.contents[1].frame, CGRect(x: 24, y: 10, width: 6, height: 8))
XCTAssertEqual(layout.contents[2].frame, CGRect(x: 38, y: 10, width: 2, height: 8))
XCTAssertEqual(layout.contents[3].frame, CGRect(x: 48, y: 10, width: 6, height: 8))
XCTAssertEqual(layout.contents[4].frame, CGRect(x: 62, y: 10, width: 4, height: 8))
XCTAssertEqual(layout.contents[5].frame, CGRect(x: 74, y: 10, width: 10, height: 8))
XCTAssertEqual(layout.contents[6].frame, CGRect(x: 92, y: 10, width: 12, height: 8))
XCTAssertEqual(layout.contents[7].frame, CGRect(x: 112, y: 10, width: 2, height: 8))
}
}
class SizeLayoutTests: XCTestCase {
func testWidth() {
let child = TestLayout(frame: CGRect(x: 10, y: 10, width: 30, height: 50))
let layout = child.withSize(width: 50)
XCTAssertEqual(layout.sizeThatFits(CGSize(width: 100, height: 60)), CGSize(width: 50, height: 50))
}
func testHeight() {
let child = TestLayout(frame: CGRect(x: 10, y: 10, width: 30, height: 50))
let layout = child.withSize(height: 70)
XCTAssertEqual(layout.sizeThatFits(CGSize(width: 100, height: 60)), CGSize(width: 30, height: 70))
}
func testSize() {
let child = TestLayout(frame: CGRect(x: 10, y: 10, width: 30, height: 50))
let layout = child.withSize(width: 50, height: 70)
XCTAssertEqual(layout.sizeThatFits(CGSize(width: 100, height: 60)), CGSize(width: 50, height: 70))
let layout2 = child.withSize(width: 50).withSize(height: 70)
XCTAssertEqual(layout2.sizeThatFits(CGSize(width: 100, height: 60)), CGSize(width: 50, height: 70))
}
}
|
mit
|
45c6a9492b363125fda36371fceebcbb
| 48.700997 | 120 | 0.691243 | 3.103413 | false | true | false | false |
BanyaKrylov/Learn-Swift
|
Skill/test/test/TwoViewController.swift
|
1
|
808
|
//
// TwoViewController.swift
// test
//
// Created by Ivan Krylov on 04.02.2020.
// Copyright © 2020 Ivan Krylov. All rights reserved.
//
import UIKit
class TwoViewController: UIViewController {
var repeatLabelOne = "Выбран зеленый"
override func viewDidLoad() {
super.viewDidLoad()
labelTwo.text = repeatLabelOne
}
@IBOutlet weak var labelTwo: UILabel!
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let vc = segue.destination as? TwoOneViewController, segue.identifier == "ShowTwoOne" {
vc.repeatLabel = labelTwo.text!
vc.delegate = self
}
}
}
extension TwoViewController: TwoOneControllerDelegate {
func setLabelTwo(_ label: String) {
labelTwo.text = label
}
}
|
apache-2.0
|
658058b8b897bc68f7f120df7cbd3cd4
| 23.8125 | 98 | 0.65995 | 4.11399 | false | false | false | false |
taketo1024/SwiftComplex
|
SwiftComplex/MasterViewController.swift
|
1
|
1781
|
//
// MasterViewController.swift
// SwiftComplex
//
// Created by Taketo Sano on 2014/10/18.
//
//
import UIKit
class MasterViewController: UITableViewController {
let titles = ["w = z * z", "w = 1 / z", "w = z^2 + z + 1"]
func map(index: Int) -> ((Complex) -> Complex) {
switch(index) {
case 0: return {$0 * $0}
case 1: return {1 / $0}
case 2: return {$0 * $0 + $0 + 1}
default: return {$0}
}
}
override func awakeFromNib() {
super.awakeFromNib()
}
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
// MARK: - Segue
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "showDetail" {
let vc = segue.destinationViewController as DetailViewController
if let indexPath = self.tableView.indexPathForSelectedRow() {
let index = indexPath.row
vc.title = titles[index];
vc.map = map(index)
}
}
}
// MARK: - Table View
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return titles.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as UITableViewCell
let object = titles[indexPath.row] as String
cell.textLabel?.text = object
return cell
}
}
|
mit
|
1a8870ad200a40968838969736280cd4
| 25.58209 | 118 | 0.600225 | 4.749333 | false | false | false | false |
jeremy-pereira/EnigmaMachine
|
components/PlugBoard.swift
|
1
|
2151
|
//
// PlugBoard.swift
// EnigmaMachine
//
// Created by Jeremy Pereira on 02/03/2015.
// Copyright (c) 2015 Jeremy Pereira. All rights reserved.
//
/*
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import Foundation
/**
A class that models a plugboard
*/
public class PlugBoard: Connector
{
public var forward: Connection = NullConnection.null
public var reverse: Connection = NullConnection.null
private var map: [Letter : Letter] = [:]
public init()
{
forward = ClosureConnection(name: "plugboard")
{
// TODO: Probably a reference cycle on self
letter in
var ret = letter
if let result = self.map[letter]
{
ret = result
}
return ret
}
reverse = forward
}
/**
Plug in a wire between two letters. This creates a reciprocal swap between the
letters in question. If either letter in the pair is already plugged in, it is
unplugged.
:param: pair The pair of letters to plug in.
*/
public func plugIn(pair: (Letter, Letter))
{
if map[pair.0] != nil
{
unplug(aLetter: pair.0)
}
if map[pair.1] != nil
{
unplug(aLetter: pair.1)
}
if pair.0 != pair.1
{
map[pair.0] = pair.1
map[pair.1] = pair.0
}
}
func unplug(aLetter: Letter)
{
if let otherEnd = map[aLetter]
{
map.removeValue(forKey: aLetter)
map.removeValue(forKey: otherEnd)
}
}
public func letterConnectedTo(letter: Letter) -> Letter?
{
return map[letter]
}
}
|
apache-2.0
|
f434406009bc04138f0ee2a550fd072f
| 22.129032 | 79 | 0.613668 | 3.932358 | false | false | false | false |
benlangmuir/swift
|
stdlib/public/core/DictionaryVariant.swift
|
13
|
13346
|
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2018 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
//
//===----------------------------------------------------------------------===//
/// This protocol is only used for compile-time checks that
/// every buffer type implements all required operations.
internal protocol _DictionaryBuffer {
associatedtype Key
associatedtype Value
associatedtype Index
var startIndex: Index { get }
var endIndex: Index { get }
func index(after i: Index) -> Index
func index(forKey key: Key) -> Index?
var count: Int { get }
func contains(_ key: Key) -> Bool
func lookup(_ key: Key) -> Value?
func lookup(_ index: Index) -> (key: Key, value: Value)
func key(at index: Index) -> Key
func value(at index: Index) -> Value
}
extension Dictionary {
@usableFromInline
@frozen
internal struct _Variant {
@usableFromInline
internal var object: _BridgeStorage<__RawDictionaryStorage>
@inlinable
@inline(__always)
init(native: __owned _NativeDictionary<Key, Value>) {
self.object = _BridgeStorage(native: native._storage)
}
@inlinable
@inline(__always)
init(dummy: Void) {
#if arch(i386) || arch(arm) || arch(arm64_32) || arch(wasm32)
self.init(native: _NativeDictionary())
#else
self.object = _BridgeStorage(taggedPayload: 0)
#endif
}
#if _runtime(_ObjC)
@inlinable
@inline(__always)
init(cocoa: __owned __CocoaDictionary) {
self.object = _BridgeStorage(objC: cocoa.object)
}
#endif
}
}
extension Dictionary._Variant {
#if _runtime(_ObjC)
@usableFromInline @_transparent
internal var guaranteedNative: Bool {
return _canBeClass(Key.self) == 0 || _canBeClass(Value.self) == 0
}
#endif
@inlinable
internal mutating func isUniquelyReferenced() -> Bool {
return object.isUniquelyReferencedUnflaggedNative()
}
#if _runtime(_ObjC)
@usableFromInline @_transparent
internal var isNative: Bool {
if guaranteedNative { return true }
return object.isUnflaggedNative
}
#endif
@usableFromInline @_transparent
internal var asNative: _NativeDictionary<Key, Value> {
get {
return _NativeDictionary<Key, Value>(object.unflaggedNativeInstance)
}
set {
self = .init(native: newValue)
}
_modify {
var native = _NativeDictionary<Key, Value>(object.unflaggedNativeInstance)
self = .init(dummy: ())
defer { object = .init(native: native._storage) }
yield &native
}
}
#if _runtime(_ObjC)
@inlinable
internal var asCocoa: __CocoaDictionary {
return __CocoaDictionary(object.objCInstance)
}
#endif
/// Reserves enough space for the specified number of elements to be stored
/// without reallocating additional storage.
internal mutating func reserveCapacity(_ capacity: Int) {
#if _runtime(_ObjC)
guard isNative else {
let cocoa = asCocoa
let capacity = Swift.max(cocoa.count, capacity)
self = .init(native: _NativeDictionary(cocoa, capacity: capacity))
return
}
#endif
let isUnique = isUniquelyReferenced()
asNative.reserveCapacity(capacity, isUnique: isUnique)
}
/// The number of elements that can be stored without expanding the current
/// storage.
///
/// For bridged storage, this is equal to the current count of the
/// collection, since any addition will trigger a copy of the elements into
/// newly allocated storage. For native storage, this is the element count
/// at which adding any more elements will exceed the load factor.
@inlinable
internal var capacity: Int {
#if _runtime(_ObjC)
guard isNative else {
return asCocoa.count
}
#endif
return asNative.capacity
}
}
extension Dictionary._Variant: _DictionaryBuffer {
@usableFromInline
internal typealias Element = (key: Key, value: Value)
@usableFromInline
internal typealias Index = Dictionary<Key, Value>.Index
@inlinable
internal var startIndex: Index {
#if _runtime(_ObjC)
guard isNative else {
return Index(_cocoa: asCocoa.startIndex)
}
#endif
return asNative.startIndex
}
@inlinable
internal var endIndex: Index {
#if _runtime(_ObjC)
guard isNative else {
return Index(_cocoa: asCocoa.endIndex)
}
#endif
return asNative.endIndex
}
@inlinable
internal func index(after index: Index) -> Index {
#if _runtime(_ObjC)
guard isNative else {
return Index(_cocoa: asCocoa.index(after: index._asCocoa))
}
#endif
return asNative.index(after: index)
}
@inlinable
internal func formIndex(after index: inout Index) {
#if _runtime(_ObjC)
guard isNative else {
let isUnique = index._isUniquelyReferenced()
asCocoa.formIndex(after: &index._asCocoa, isUnique: isUnique)
return
}
#endif
index = asNative.index(after: index)
}
@inlinable
@inline(__always)
internal func index(forKey key: Key) -> Index? {
#if _runtime(_ObjC)
guard isNative else {
let cocoaKey = _bridgeAnythingToObjectiveC(key)
guard let index = asCocoa.index(forKey: cocoaKey) else { return nil }
return Index(_cocoa: index)
}
#endif
return asNative.index(forKey: key)
}
@inlinable
internal var count: Int {
@inline(__always)
get {
#if _runtime(_ObjC)
guard isNative else {
return asCocoa.count
}
#endif
return asNative.count
}
}
@inlinable
@inline(__always)
func contains(_ key: Key) -> Bool {
#if _runtime(_ObjC)
guard isNative else {
let cocoaKey = _bridgeAnythingToObjectiveC(key)
return asCocoa.contains(cocoaKey)
}
#endif
return asNative.contains(key)
}
@inlinable
@inline(__always)
func lookup(_ key: Key) -> Value? {
#if _runtime(_ObjC)
guard isNative else {
let cocoaKey = _bridgeAnythingToObjectiveC(key)
guard let cocoaValue = asCocoa.lookup(cocoaKey) else { return nil }
return _forceBridgeFromObjectiveC(cocoaValue, Value.self)
}
#endif
return asNative.lookup(key)
}
@inlinable
@inline(__always)
func lookup(_ index: Index) -> (key: Key, value: Value) {
#if _runtime(_ObjC)
guard isNative else {
let (cocoaKey, cocoaValue) = asCocoa.lookup(index._asCocoa)
let nativeKey = _forceBridgeFromObjectiveC(cocoaKey, Key.self)
let nativeValue = _forceBridgeFromObjectiveC(cocoaValue, Value.self)
return (nativeKey, nativeValue)
}
#endif
return asNative.lookup(index)
}
@inlinable
@inline(__always)
func key(at index: Index) -> Key {
#if _runtime(_ObjC)
guard isNative else {
let cocoaKey = asCocoa.key(at: index._asCocoa)
return _forceBridgeFromObjectiveC(cocoaKey, Key.self)
}
#endif
return asNative.key(at: index)
}
@inlinable
@inline(__always)
func value(at index: Index) -> Value {
#if _runtime(_ObjC)
guard isNative else {
let cocoaValue = asCocoa.value(at: index._asCocoa)
return _forceBridgeFromObjectiveC(cocoaValue, Value.self)
}
#endif
return asNative.value(at: index)
}
}
extension Dictionary._Variant {
@inlinable
internal subscript(key: Key) -> Value? {
@inline(__always)
get {
return lookup(key)
}
@inline(__always)
_modify {
#if _runtime(_ObjC)
guard isNative else {
let cocoa = asCocoa
var native = _NativeDictionary<Key, Value>(
cocoa, capacity: cocoa.count + 1)
self = .init(native: native)
yield &native[key, isUnique: true]
return
}
#endif
let isUnique = isUniquelyReferenced()
yield &asNative[key, isUnique: isUnique]
}
}
}
extension Dictionary._Variant {
/// Same as find(_:), except assume a corresponding key/value pair will be
/// inserted if it doesn't already exist, and mutated if it does exist. When
/// this function returns, the storage is guaranteed to be native, uniquely
/// held, and with enough capacity for a single insertion (if the key isn't
/// already in the dictionary.)
@inlinable
@inline(__always)
internal mutating func mutatingFind(
_ key: Key
) -> (bucket: _NativeDictionary<Key, Value>.Bucket, found: Bool) {
#if _runtime(_ObjC)
guard isNative else {
let cocoa = asCocoa
var native = _NativeDictionary<Key, Value>(
cocoa, capacity: cocoa.count + 1)
let result = native.mutatingFind(key, isUnique: true)
self = .init(native: native)
return result
}
#endif
let isUnique = isUniquelyReferenced()
return asNative.mutatingFind(key, isUnique: isUnique)
}
@inlinable
@inline(__always)
internal mutating func ensureUniqueNative() -> _NativeDictionary<Key, Value> {
#if _runtime(_ObjC)
guard isNative else {
let native = _NativeDictionary<Key, Value>(asCocoa)
self = .init(native: native)
return native
}
#endif
let isUnique = isUniquelyReferenced()
if !isUnique {
asNative.copy()
}
return asNative
}
@inlinable
internal mutating func updateValue(
_ value: __owned Value,
forKey key: Key
) -> Value? {
#if _runtime(_ObjC)
guard isNative else {
// Make sure we have space for an extra element.
let cocoa = asCocoa
var native = _NativeDictionary<Key, Value>(
cocoa,
capacity: cocoa.count + 1)
let result = native.updateValue(value, forKey: key, isUnique: true)
self = .init(native: native)
return result
}
#endif
let isUnique = self.isUniquelyReferenced()
return asNative.updateValue(value, forKey: key, isUnique: isUnique)
}
@inlinable
internal mutating func setValue(_ value: __owned Value, forKey key: Key) {
#if _runtime(_ObjC)
if !isNative {
// Make sure we have space for an extra element.
let cocoa = asCocoa
self = .init(native: _NativeDictionary<Key, Value>(
cocoa,
capacity: cocoa.count + 1))
}
#endif
let isUnique = self.isUniquelyReferenced()
asNative.setValue(value, forKey: key, isUnique: isUnique)
}
@inlinable
@_semantics("optimize.sil.specialize.generic.size.never")
internal mutating func remove(at index: Index) -> Element {
// FIXME(performance): fuse data migration and element deletion into one
// operation.
let native = ensureUniqueNative()
let bucket = native.validatedBucket(for: index)
return asNative.uncheckedRemove(at: bucket, isUnique: true)
}
@inlinable
internal mutating func removeValue(forKey key: Key) -> Value? {
#if _runtime(_ObjC)
guard isNative else {
let cocoaKey = _bridgeAnythingToObjectiveC(key)
let cocoa = asCocoa
guard cocoa.lookup(cocoaKey) != nil else { return nil }
var native = _NativeDictionary<Key, Value>(cocoa)
let (bucket, found) = native.find(key)
_precondition(found, "Bridging did not preserve equality")
let old = native.uncheckedRemove(at: bucket, isUnique: true).value
self = .init(native: native)
return old
}
#endif
let (bucket, found) = asNative.find(key)
guard found else { return nil }
let isUnique = isUniquelyReferenced()
return asNative.uncheckedRemove(at: bucket, isUnique: isUnique).value
}
@inlinable
@_semantics("optimize.sil.specialize.generic.size.never")
internal mutating func removeAll(keepingCapacity keepCapacity: Bool) {
if !keepCapacity {
self = .init(native: _NativeDictionary())
return
}
guard count > 0 else { return }
#if _runtime(_ObjC)
guard isNative else {
self = .init(native: _NativeDictionary(capacity: asCocoa.count))
return
}
#endif
let isUnique = isUniquelyReferenced()
asNative.removeAll(isUnique: isUnique)
}
}
extension Dictionary._Variant {
/// Returns an iterator over the `(Key, Value)` pairs.
///
/// - Complexity: O(1).
@inlinable
@inline(__always)
__consuming internal func makeIterator() -> Dictionary<Key, Value>.Iterator {
#if _runtime(_ObjC)
guard isNative else {
return Dictionary.Iterator(_cocoa: asCocoa.makeIterator())
}
#endif
return Dictionary.Iterator(_native: asNative.makeIterator())
}
}
extension Dictionary._Variant {
@inlinable
internal func mapValues<T>(
_ transform: (Value) throws -> T
) rethrows -> _NativeDictionary<Key, T> {
#if _runtime(_ObjC)
guard isNative else {
return try asCocoa.mapValues(transform)
}
#endif
return try asNative.mapValues(transform)
}
@inlinable
internal mutating func merge<S: Sequence>(
_ keysAndValues: __owned S,
uniquingKeysWith combine: (Value, Value) throws -> Value
) rethrows where S.Element == (Key, Value) {
#if _runtime(_ObjC)
guard isNative else {
var native = _NativeDictionary<Key, Value>(asCocoa)
try native.merge(
keysAndValues,
isUnique: true,
uniquingKeysWith: combine)
self = .init(native: native)
return
}
#endif
let isUnique = isUniquelyReferenced()
try asNative.merge(
keysAndValues,
isUnique: isUnique,
uniquingKeysWith: combine)
}
}
|
apache-2.0
|
b1464c2c010197d7fab4fd3679478739
| 26.404517 | 80 | 0.660273 | 4.126778 | false | false | false | false |
mamelend/YonderSwift
|
Yonder/WaterViewController.swift
|
1
|
5832
|
//
// ShowViewController.swift
// Yonder
//
// Created by Miguel Melendez on 4/23/16.
// Copyright © 2016 Miguel Melendez. All rights reserved.
//
import UIKit
import CoreLocation
class WaterViewController: UIViewController, CLLocationManagerDelegate {
var locationManager = CLLocationManager()
var lastDir: String = "?"
var lastPoint = (x: 0.0, y: 0.0)
@IBOutlet weak var textLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
textLabel.numberOfLines = 0
textLabel.lineBreakMode = NSLineBreakMode.ByWordWrapping
getNearestWaterSource()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestWhenInUseAuthorization()
locationManager.startUpdatingHeading()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func getNearestWaterSource() {
print("getNearestWaterSource Hit")
let url = NSURL(string: "https://data.waterpointdata.org/resource/gihr-buz6.json?$where=within_circle(location,\(currentLat),\(currentLon), 5000)".stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())!)
let task = NSURLSession.sharedSession().dataTaskWithURL(url!) { (data, response, error) -> Void in
if data?.length > 5 {
let urlContent = data
print("JSON Data Available")
do {
var counter = 0
var nearestDistance: Double = 5000
var nearestDirection = ""
let jsonResult = try NSJSONSerialization.JSONObjectWithData(urlContent!, options: NSJSONReadingOptions.MutableContainers) as! NSArray
print(jsonResult)
for x in 0 ..< jsonResult.count {
// Iterate through json data and determine nearest water point and save nearest distance
var lat = ""
var lon = ""
if (jsonResult[x]["lat_deg"] != nil) {
lat = jsonResult[x]["lat_deg"] as! String
}
if (jsonResult[x]["lon_deg"] != nil) {
lon = jsonResult[x]["lon_deg"] as! String
}
if (lat != "" && lon != "") {
if (self.findDistance(Double(lat)!, lon: Double(lon)!) < nearestDistance) {
nearestDistance = self.findDistance(Double(lat)!, lon: Double(lon)!)
nearestDirection = self.findDirection(Double(lat)!, lon: Double(lon)!)
self.lastPoint.x = Double(lat)!
self.lastPoint.y = Double(lon)!
counter = x
}
}
}
if (!jsonResult.isEqualToArray([])) {
let waterSource = jsonResult[counter]["water_source"] as! String
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.textLabel.text = "The nearest water source is a \(waterSource.lowercaseString) and is \(nearestDistance) miles away due \(nearestDirection). You are currently heading \(currentDir)."
self.lastDir = currentDir
})
}
} catch {
print("JSON Serialization Failed.")
}
} else {
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.textLabel.text = "There are no water sources in this area."
})
}
}
task.resume()
}
func findDistance(lat: Double, lon: Double) -> Double {
let lat1 = lat
let lon1 = lon
let lat2 = currentLat
let lon2 = currentLon
// Radius of the earth in: 1.609344 miles, 6371 km | var R = (6371 / 1.609344)
let R = 3958.7558657440545;
let dLat = toRad(lat2-lat1);
let dLon = toRad(lon2-lon1);
let a = sin(dLat/2) * sin(dLat/2) +
cos(toRad(lat1)) * cos(toRad(lat2)) *
sin(dLon/2) * sin(dLon/2);
let c = 2 * atan2(sqrt(a), sqrt(1-a));
let d = R * c;
return toFixed(d)
}
func toRad(value: Double) -> Double {
// Converts numeric degrees to radians
return value * M_PI / 180;
}
func toFixed(num: Double) -> Double {
return Double(round(1000*num)/1000)
}
func findDirection(lat: Double, lon: Double) -> String {
let lat1 = lat
let lon1 = lon
let lat2 = currentLat
let lon2 = currentLon
let radians = getAtan2((lon1 - lon2), x: (lat1 - lat2))
let compassReading = radians * (180 / M_PI)
var coordNames = ["N", "NE", "E", "SE", "S", "SW", "W", "NW", "N"]
var coordIndex: Int = Int(round(compassReading / 45))
if (coordIndex < 0) {
coordIndex = coordIndex + 8
}
return coordNames[coordIndex]
}
func getAtan2(y: Double, x: Double) -> Double {
return atan2(y, x)
}
func locationManager(manager: CLLocationManager, didUpdateHeading newHeading: CLHeading) {
if(lastDir != currentDir && findDistance(currentLat, lon: currentLon) != findDistance(lastPoint.x, lon: lastPoint.y)) {
getNearestWaterSource()
}
}
}
|
mit
|
15b9e2d41f3e234e416571dd5ef76507
| 37.368421 | 253 | 0.519122 | 4.851082 | false | false | false | false |
Zewo/Zewo
|
Sources/Media/JSON/JSONDecodingMedia.swift
|
1
|
13128
|
import Core
import Venice
extension JSON : DecodingMedia {
public init(from readable: Readable, deadline: Deadline) throws {
let parser = JSONParser()
let buffer = UnsafeMutableRawBufferPointer.allocate(
byteCount: 4096,
alignment: MemoryLayout<UInt8>.alignment
)
defer {
buffer.deallocate()
}
while true {
let read = try readable.read(buffer, deadline: deadline)
guard !read.isEmpty else {
break
}
guard let json = try parser.parse(read) else {
continue
}
self = json
return
}
self = try parser.finish()
}
public func keyCount() -> Int? {
if case let .object(object) = self {
return object.keys.count
}
if case let .array(array) = self {
return array.count
}
return nil
}
public func allKeys<Key>(keyedBy: Key.Type) -> [Key] where Key : CodingKey {
if case let .object(object) = self {
return object.keys.compactMap(Key.init)
}
if case let .array(array) = self {
return array.indices.compactMap(Key.init)
}
return []
}
public func contains<Key>(_ key: Key) -> Bool where Key : CodingKey {
do {
_ = try decodeIfPresent(type(of: self), forKey: key)
return true
} catch {
return false
}
}
public func keyedContainer() throws -> DecodingMedia {
guard isObject else {
throw DecodingError.typeMismatch(type(of: self), DecodingError.Context())
}
return self
}
public func unkeyedContainer() throws -> DecodingMedia {
guard isArray else {
throw DecodingError.typeMismatch(type(of: self), DecodingError.Context())
}
return self
}
public func singleValueContainer() throws -> DecodingMedia {
if isObject {
throw DecodingError.typeMismatch(type(of: self), DecodingError.Context())
}
if isArray {
throw DecodingError.typeMismatch(type(of: self), DecodingError.Context())
}
return self
}
public func decode(_ type: DecodingMedia.Type, forKey key: CodingKey) throws -> DecodingMedia {
if let index = key.intValue {
guard case let .array(array) = self else {
throw DecodingError.typeMismatch(
[JSON].self,
DecodingError.Context(codingPath: [key])
)
}
guard array.indices.contains(index) else {
throw DecodingError.valueNotFound(
JSON.self,
DecodingError.Context(codingPath: [key])
)
}
return array[index]
} else {
guard case let .object(object) = self else {
throw DecodingError.typeMismatch(
[String: JSON].self,
DecodingError.Context(codingPath: [key])
)
}
guard let newValue = object[key.stringValue] else {
throw DecodingError.valueNotFound(
JSON.self,
DecodingError.Context(codingPath: [key])
)
}
return newValue
}
}
public func decodeIfPresent(
_ type: DecodingMedia.Type,
forKey key: CodingKey
) throws -> DecodingMedia? {
if let index = key.intValue {
guard case let .array(array) = self else {
throw DecodingError.typeMismatch(
[JSON].self,
DecodingError.Context(codingPath: [key])
)
}
guard array.indices.contains(index) else {
throw DecodingError.valueNotFound(
JSON.self,
DecodingError.Context(codingPath: [key])
)
}
return array[index]
} else {
guard case let .object(object) = self else {
throw DecodingError.typeMismatch(
[String: JSON].self,
DecodingError.Context(codingPath: [key])
)
}
guard let newValue = object[key.stringValue] else {
throw DecodingError.valueNotFound(
JSON.self,
DecodingError.Context(codingPath: [key])
)
}
return newValue
}
}
public func decodeNil() -> Bool {
return isNull
}
public func decode(_ type: Bool.Type) throws -> Bool {
if case .null = self {
throw DecodingError.valueNotFound(
Bool.self,
DecodingError.Context()
)
}
guard case let .bool(bool) = self else {
throw DecodingError.typeMismatch(
Bool.self,
DecodingError.Context()
)
}
return bool
}
public func decode(_ type: Int.Type) throws -> Int {
if case .null = self {
throw DecodingError.valueNotFound(
Int.self,
DecodingError.Context()
)
}
if case let .int(int) = self {
return int
}
if case let .double(double) = self, let int = Int(exactly: double) {
return int
}
throw DecodingError.typeMismatch(
Int.self,
DecodingError.Context()
)
}
public func decode(_ type: Int8.Type) throws -> Int8 {
if case .null = self {
throw DecodingError.valueNotFound(
Int8.self,
DecodingError.Context()
)
}
if case let .int(int) = self, let int8 = Int8(exactly: int) {
return int8
}
if case let .double(double) = self, let int8 = Int8(exactly: double) {
return int8
}
throw DecodingError.typeMismatch(
Int8.self,
DecodingError.Context()
)
}
public func decode(_ type: Int16.Type) throws -> Int16 {
if case .null = self {
throw DecodingError.valueNotFound(
Int16.self,
DecodingError.Context()
)
}
if case let .int(int) = self, let int16 = Int16(exactly: int) {
return int16
}
if case let .double(double) = self, let int16 = Int16(exactly: double) {
return int16
}
throw DecodingError.typeMismatch(
Int16.self,
DecodingError.Context()
)
}
public func decode(_ type: Int32.Type) throws -> Int32 {
if case .null = self {
throw DecodingError.valueNotFound(
Int32.self,
DecodingError.Context()
)
}
if case let .int(int) = self, let int32 = Int32(exactly: int) {
return int32
}
if case let .double(double) = self, let int32 = Int32(exactly: double) {
return int32
}
throw DecodingError.typeMismatch(
Int32.self,
DecodingError.Context()
)
}
public func decode(_ type: Int64.Type) throws -> Int64 {
if case .null = self {
throw DecodingError.valueNotFound(
Int64.self,
DecodingError.Context()
)
}
if case let .int(int) = self, let int64 = Int64(exactly: int) {
return int64
}
if case let .double(double) = self, let int64 = Int64(exactly: double) {
return int64
}
throw DecodingError.typeMismatch(
Int64.self,
DecodingError.Context()
)
}
public func decode(_ type: UInt.Type) throws -> UInt {
if case .null = self {
throw DecodingError.valueNotFound(
UInt.self,
DecodingError.Context()
)
}
if case let .int(int) = self, let uint = UInt(exactly: int) {
return uint
}
if case let .double(double) = self, let uint = UInt(exactly: double) {
return uint
}
throw DecodingError.typeMismatch(
UInt.self,
DecodingError.Context()
)
}
public func decode(_ type: UInt8.Type) throws -> UInt8 {
if case .null = self {
throw DecodingError.valueNotFound(
UInt8.self,
DecodingError.Context()
)
}
if case let .int(int) = self, let uint8 = UInt8(exactly: int) {
return uint8
}
if case let .double(double) = self, let uint8 = UInt8(exactly: double) {
return uint8
}
throw DecodingError.typeMismatch(
UInt8.self,
DecodingError.Context()
)
}
public func decode(_ type: UInt16.Type) throws -> UInt16 {
if case .null = self {
throw DecodingError.valueNotFound(
UInt16.self,
DecodingError.Context()
)
}
if case let .int(int) = self, let uint16 = UInt16(exactly: int) {
return uint16
}
if case let .double(double) = self, let uint16 = UInt16(exactly: double) {
return uint16
}
throw DecodingError.typeMismatch(
UInt16.self,
DecodingError.Context()
)
}
public func decode(_ type: UInt32.Type) throws -> UInt32 {
if case .null = self {
throw DecodingError.valueNotFound(
UInt32.self,
DecodingError.Context()
)
}
if case let .int(int) = self, let uint32 = UInt32(exactly: int) {
return uint32
}
if case let .double(double) = self, let uint32 = UInt32(exactly: double) {
return uint32
}
throw DecodingError.typeMismatch(
UInt32.self,
DecodingError.Context()
)
}
public func decode(_ type: UInt64.Type) throws -> UInt64 {
if case .null = self {
throw DecodingError.valueNotFound(
UInt64.self,
DecodingError.Context()
)
}
if case let .int(int) = self, let uint64 = UInt64(exactly: int) {
return uint64
}
if case let .double(double) = self, let uint64 = UInt64(exactly: double) {
return uint64
}
throw DecodingError.typeMismatch(
UInt64.self,
DecodingError.Context()
)
}
public func decode(_ type: Float.Type) throws -> Float {
if case .null = self {
throw DecodingError.valueNotFound(
Float.self,
DecodingError.Context()
)
}
if case let .int(int) = self, let float = Float(exactly: int) {
return float
}
if case let .double(double) = self, let float = Float(exactly: double) {
return float
}
throw DecodingError.typeMismatch(
Float.self,
DecodingError.Context()
)
}
public func decode(_ type: Double.Type) throws -> Double {
if case .null = self {
throw DecodingError.valueNotFound(
Double.self,
DecodingError.Context()
)
}
if case let .int(int) = self, let double = Double(exactly: int) {
return double
}
if case let .double(double) = self {
return double
}
throw DecodingError.typeMismatch(
Double.self,
DecodingError.Context()
)
}
public func decode(_ type: String.Type) throws -> String {
if case .null = self {
throw DecodingError.valueNotFound(
String.self,
DecodingError.Context()
)
}
guard case let .string(string) = self else {
throw DecodingError.typeMismatch(
String.self,
DecodingError.Context()
)
}
return string
}
}
|
mit
|
11f2bc1f42b3be3e4fc65f814c7513a9
| 26.579832 | 99 | 0.475701 | 5.226115 | false | false | false | false |
DestructHub/ProjectEuler
|
Problem043/Swift/solution_1.swift
|
1
|
1163
|
// send the items from the right to the left
func permute(array:[Int]) -> [Int]
{
var mutArr = array
var i = mutArr.count - 2
loop: while true
{
switch i
{
case let x where x < 0: return []
case let x where mutArr[x] < mutArr[x+1]: break loop
default: i -= 1
}
}
var j = 1
while j + i < mutArr.count - j
{
let n = mutArr[j + i]
mutArr[j + i] = mutArr[mutArr.count - j]
mutArr[mutArr.count - j] = n
j += 1
}
j = i + 1
while mutArr[j] <= mutArr[i]
{
j += 1
}
let n = mutArr[i]
mutArr[i] = mutArr[j]
mutArr[j] = n
return mutArr
}
let primes = [2, 3, 5, 7, 11, 13, 17]
let numbers = Array("0123456789".characters).map{Int(String($0))!}
var arr = permute(numbers)
var sum:UInt64 = 0
while !arr.isEmpty
{
var i = 0
while i < primes.count
{
let n1 = Int(arr[i + 1]) * 100
let n2 = Int(arr[i + 2]) * 10
let n3 = Int(arr[i + 3])
if (n1+n2+n3) % primes[i] != 0
{
break
}
i += 1
}
if (i == primes.count)
{
var str = arr.map { String($0) }.joinWithSeparator("")
sum += UInt64(str)!
}
arr = permute(arr)
}
print(sum)
|
mit
|
2423d0b339fd158e91342d962862cd0c
| 15.614286 | 66 | 0.525365 | 2.710956 | false | false | false | false |
JohnEstropia/CoreStore
|
Sources/CoreStoreObject.swift
|
1
|
8484
|
//
// CoreStoreObject.swift
// CoreStore
//
// Copyright © 2018 John Rommel Estropia
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
import CoreData
import Foundation
// MARK: - CoreStoreObject
/**
The `CoreStoreObject` is an abstract class for creating CoreStore-managed objects that are more type-safe and more convenient than `NSManagedObject` subclasses. The model entities for `CoreStoreObject` subclasses are inferred from the Swift declaration themselves; no .xcdatamodeld files are needed. To declare persisted attributes and relationships for the `CoreStoreObject` subclass, declare properties of type `Value.Required<T>`, `Value.Optional<T>` for values, or `Relationship.ToOne<T>`, `Relationship.ToManyOrdered<T>`, `Relationship.ToManyUnordered<T>` for relationships.
```
class Animal: CoreStoreObject {
let species = Value.Required<String>("species", initial: "")
let nickname = Value.Optional<String>("nickname")
let master = Relationship.ToOne<Person>("master")
}
class Person: CoreStoreObject {
let name = Value.Required<String>("name", initial: "")
let pet = Relationship.ToOne<Animal>("pet", inverse: { $0.master })
}
```
`CoreStoreObject` entities for a model version should be added to `CoreStoreSchema` instance.
```
CoreStoreDefaults.dataStack = DataStack(
CoreStoreSchema(
modelVersion: "V1",
entities: [
Entity<Animal>("Animal"),
Entity<Person>("Person")
]
)
)
```
- SeeAlso: CoreStoreSchema
- SeeAlso: CoreStoreObject.Value
- SeeAlso: CoreStoreObject.Relationship
*/
open /*abstract*/ class CoreStoreObject: DynamicObject, Hashable {
/**
Do not call this directly. This is exposed as public only as a required initializer.
- Important: subclasses that need a custom initializer should override both `init(rawObject:)` and `init(asMeta:)`, and to call their corresponding super implementations.
*/
public required init(rawObject: NSManagedObject) {
self.isMeta = false
self.rawObject = (rawObject as! CoreStoreManagedObject)
guard Self.meta.needsReflection else {
return
}
self.registerReceiver(
mirror: Mirror(reflecting: self),
object: self
)
}
/**
Do not call this directly. This is exposed as public only as a required initializer.
- Important: subclasses that need a custom initializer should override both `init(rawObject:)` and `init(asMeta:)`, and to call their corresponding super implementations.
*/
public required init(asMeta: Void) {
self.isMeta = true
self.rawObject = nil
}
// MARK: Equatable
public static func == (lhs: CoreStoreObject, rhs: CoreStoreObject) -> Bool {
guard lhs.isMeta == rhs.isMeta else {
return false
}
if lhs.isMeta {
return lhs.runtimeType() == rhs.runtimeType()
}
return lhs.rawObject!.isEqual(rhs.rawObject!)
}
// MARK: Hashable
public func hash(into hasher: inout Hasher) {
hasher.combine(self.isMeta)
hasher.combine(ObjectIdentifier(self))
hasher.combine(self.rawObject)
}
// MARK: Internal
internal let rawObject: CoreStoreManagedObject?
internal let isMeta: Bool
internal lazy var needsReflection: Bool = self.containsLegacyAttributes(
mirror: Mirror(reflecting: self),
object: self
)
internal class func metaProperties(includeSuperclasses: Bool) -> [PropertyProtocol] {
func keyPaths(_ allKeyPaths: inout [PropertyProtocol], for dynamicType: CoreStoreObject.Type) {
allKeyPaths.append(contentsOf: dynamicType.meta.propertyProtocolsByName())
guard
includeSuperclasses,
case let superType as CoreStoreObject.Type = (dynamicType as AnyClass).superclass(),
superType != CoreStoreObject.self
else {
return
}
keyPaths(&allKeyPaths, for: superType)
}
var allKeyPaths: [PropertyProtocol] = []
keyPaths(&allKeyPaths, for: self)
return allKeyPaths
}
// MARK: Private
private func containsLegacyAttributes(mirror: Mirror, object: CoreStoreObject) -> Bool {
if let superclassMirror = mirror.superclassMirror,
self.containsLegacyAttributes(mirror: superclassMirror, object: object) {
return true
}
for child in mirror.children {
switch child.value {
case is AttributeProtocol:
return true
case is RelationshipProtocol:
return true
default:
continue
}
}
return false
}
private func registerReceiver(mirror: Mirror, object: CoreStoreObject) {
if let superclassMirror = mirror.superclassMirror {
self.registerReceiver(
mirror: superclassMirror,
object: object
)
}
for child in mirror.children {
switch child.value {
case let property as AttributeProtocol:
property.rawObject = object.rawObject
case let property as RelationshipProtocol:
property.rawObject = object.rawObject
default:
continue
}
}
}
private func propertyProtocolsByName() -> [PropertyProtocol] {
Internals.assert(self.isMeta, "'propertyProtocolsByName()' accessed from non-meta instance of \(Internals.typeName(self))")
let cacheKey = ObjectIdentifier(Self.self)
if let properties = Static.propertiesCache[cacheKey] {
return properties
}
let values: [PropertyProtocol] = Mirror(reflecting: self)
.children
.compactMap({ $0.value as? PropertyProtocol })
Static.propertiesCache[cacheKey] = values
return values
}
}
// MARK: - DynamicObject where Self: CoreStoreObject
extension DynamicObject where Self: CoreStoreObject {
/**
Returns the `PartialObject` instance for the object, which acts as a fast, type-safe KVC interface for `CoreStoreObject`.
*/
public func partialObject() -> PartialObject<Self> {
Internals.assert(
!self.isMeta,
"Attempted to create a \(Internals.typeName(PartialObject<Self>.self)) from a meta object. Meta objects are only used for querying keyPaths and infering types."
)
return PartialObject<Self>(self.rawObject!)
}
// MARK: Internal
internal static var meta: Self {
let cacheKey = ObjectIdentifier(self)
if case let meta as Self = Static.metaCache[cacheKey] {
return meta
}
let meta = self.init(asMeta: ())
Static.metaCache[cacheKey] = meta
return meta
}
}
// MARK: - Static
fileprivate enum Static {
// MARK: FilePrivate
fileprivate static var metaCache: [ObjectIdentifier: Any] = [:]
fileprivate static var propertiesCache: [ObjectIdentifier: [PropertyProtocol]] = [:]
}
|
mit
|
84559053f021ddb99442d01c6f9ec379
| 31.377863 | 580 | 0.635624 | 5.122585 | false | false | false | false |
KittenYang/A-GUIDE-TO-iOS-ANIMATION
|
Swift Version/KYCuteView-Swift/KYCuteView-Swift/ViewController.swift
|
1
|
776
|
//
// ViewController.swift
// KYCuteView-Swift
//
// Created by Kitten Yang on 1/19/16.
// Copyright © 2016 Kitten Yang. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
var option = BubbleOptions()
option.viscosity = 20.0
option.bubbleWidth = 35.0
option.bubbleColor = UIColor(red: 0.0, green: 0.722, blue: 1.0, alpha: 1.0)
let cuteView = CuteView(point: CGPointMake(25, UIScreen.mainScreen().bounds.size.height - 65), superView: view, options: option)
option.text = "20"
cuteView.bubbleOptions = option
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
|
gpl-2.0
|
fb362911f63009e47ee595443b6395d2
| 21.794118 | 136 | 0.64129 | 3.974359 | false | false | false | false |
kitasuke/SwiftProtobufSample
|
Client/Carthage/Checkouts/swift-protobuf/Tests/SwiftProtobufTests/Test_TextFormat_proto2.swift
|
1
|
1384
|
// Tests/SwiftProtobufTests/Test_TextFormat_proto2.swift - Exercise proto3 text format coding
//
// Copyright (c) 2014 - 2016 Apple Inc. and the project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See LICENSE.txt for license information:
// https://github.com/apple/swift-protobuf/blob/master/LICENSE.txt
//
// -----------------------------------------------------------------------------
///
/// This is a set of tests for text format protobuf files.
///
// -----------------------------------------------------------------------------
import Foundation
import XCTest
import SwiftProtobuf
class Test_TextFormat_proto2: XCTestCase, PBTestHelpers {
typealias MessageTestType = ProtobufUnittest_TestAllTypes
func test_group() {
assertTextFormatEncode("OptionalGroup {\n a: 17\n}\n") {(o: inout MessageTestType) in
o.optionalGroup = ProtobufUnittest_TestAllTypes.OptionalGroup.with {$0.a = 17}
}
}
func test_repeatedGroup() {
assertTextFormatEncode("RepeatedGroup {\n a: 17\n}\nRepeatedGroup {\n a: 18\n}\n") {(o: inout MessageTestType) in
let group17 = ProtobufUnittest_TestAllTypes.RepeatedGroup.with {$0.a = 17}
let group18 = ProtobufUnittest_TestAllTypes.RepeatedGroup.with {$0.a = 18}
o.repeatedGroup = [group17, group18]
}
}
}
|
mit
|
687f2aed915645030c5f6f895f80dbe7
| 38.542857 | 123 | 0.611272 | 4.756014 | false | true | false | false |
rambler-digital-solutions/rambler-it-ios
|
Carthage/Checkouts/rides-ios-sdk/source/UberRides/ModalRideRequestViewController.swift
|
1
|
4640
|
//
// ModalRideRequestViewController.swift
// UberRides
//
// Copyright © 2015 Uber Technologies, Inc. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
/// Modal View Controller to use for presenting a RideRequestViewController. Handles errors & closing the modal for you
@objc(UBSDKModalRideRequestViewController) public class ModalRideRequestViewController : ModalViewController {
/// The RideRequestViewController this modal is wrapping
@objc public internal(set) var rideRequestViewController : RideRequestViewController
/**
Initializer for the ModalRideRequestViewController. Wraps the provided RideRequestViewController
and acts as it's delegate. Will handle errors coming in via the RideRequestViewControllerDelegate
and dismiss the modal appropriately
- parameter rideRequestViewController: The RideRequestViewController to wrap
- returns: An initialized ModalRideRequestViewController
*/
@objc public init(rideRequestViewController: RideRequestViewController) {
self.rideRequestViewController = rideRequestViewController
super.init(childViewController: rideRequestViewController, buttonStyle: ModalViewControllerButtonStyle.backButton)
self.rideRequestViewController.delegate = self
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: UIViewController
public override var supportedInterfaceOrientations : UIInterfaceOrientationMask {
return [.portrait, .portraitUpsideDown]
}
}
extension ModalRideRequestViewController : RideRequestViewControllerDelegate {
/**
ModalRideRequestViewController's implmentation for the RideRequestViewController delegate.
- parameter rideRequestViewController: The RideRequestViewController that experienced an error
- parameter error: The RideRequestViewError that occured
*/
public func rideRequestViewController(_ rideRequestViewController: RideRequestViewController, didReceiveError error: NSError) {
let errorType = RideRequestViewErrorType(rawValue: error.code) ?? RideRequestViewErrorType.unknown
var errorString: String?
navigationItem.title = LocalizationUtil.localizedString(forKey: "Sign in with Uber", comment: "Title of navigation bar during OAuth")
switch errorType {
case .accessTokenExpired:
fallthrough
case .accessTokenMissing:
errorString = LocalizationUtil.localizedString(forKey: "There was a problem authenticating you. Please try again.", comment: "RideRequestView error text for authentication error")
case .networkError:
break
default:
errorString = LocalizationUtil.localizedString(forKey: "The Ride Request Widget encountered a problem. Please try again.", comment: "RideRequestView error text for a generic error")
}
if let errorString = errorString {
let actionString = LocalizationUtil.localizedString(forKey: "OK", comment: "OK button title")
let alert = UIAlertController(title: nil, message: errorString, preferredStyle: UIAlertControllerStyle.alert)
let okayAction = UIAlertAction(title: actionString, style: UIAlertActionStyle.default, handler: { (_) -> Void in
self.dismiss()
})
alert.addAction(okayAction)
self.present(alert, animated: true, completion: nil)
} else {
self.dismiss()
}
}
}
|
mit
|
ca833bd2aa680c1a076e474e68b19f43
| 50.544444 | 193 | 0.73227 | 5.555689 | false | false | false | false |
Harley-xk/Chrysan
|
Example/Examples/AnimationExamples.swift
|
1
|
1058
|
//
// SpringAnimationExample.swift
// Example
//
// Created by Harley-xk on 2020/9/30.
// Copyright © 2020 Harley. All rights reserved.
//
import Foundation
import Chrysan
import UIKit
struct SpringAnimationExample: AnyChyrsanExample {
let name = "Spring Animations"
func show(in viewController: UIViewController) {
let responder = viewController.chrysan.hudResponder
responder?.animatorProvider = SpringAnimatorProvider(
duraction: 0.25,
dampingRatio: 0.5
)
viewController.chrysan.showHUD(.success(message: "Animation Changed!"), hideAfterDelay: 1)
}
}
struct CubicAnimationExample: AnyChyrsanExample {
let name = "Cubic Animations"
func show(in viewController: UIViewController) {
let responder = viewController.chrysan.hudResponder
responder?.animatorProvider = CubicAnimatorProvider()
viewController.chrysan.changeStatus(to: .success(message: "Animation Changed!"))
viewController.chrysan.hide(afterDelay: 1)
}
}
|
mit
|
54b645a0fed91f9cd0bd9d95abfecb49
| 26.815789 | 98 | 0.693472 | 4.478814 | false | false | false | false |
bradkratky/BradColorPicker
|
BradColorPicker/Classes/BradColorUtils.swift
|
1
|
3785
|
//
// BradColorUtils.swift
// BradColorPicker
//
// Created by Brad on 2016-06-30.
// Copyright © 2016 braddev. All rights reserved.
//
import UIKit
let BRAD_CORNER_RADIUS = CGFloat.init(5);
// indicator circle width for color sliders and wheel
let BRAD_INDICATOR_WIDTH = CGFloat.init(6);
public typealias RGB = (r: CGFloat, g:CGFloat, b:CGFloat);
public typealias HSV = (h: CGFloat, s:CGFloat, v:CGFloat);
enum BradColorSetting :Character{
case red = "R"
case green = "G"
case blue = "B"
case hue = "H"
case saturation = "S"
case value = "V"
case alpha = "A"
}
// max ranges for different color components
func colorRange(_ setting:BradColorSetting) -> (min:CGFloat, max:CGFloat){
switch setting {
case .red: fallthrough
case .green: fallthrough
case .blue: fallthrough
case .alpha:
return (0, 255);
case .hue:
return (0, 360);
case .saturation: fallthrough
case .value:
return (0, 100);
}
}
func RGBtoUInt8(_ rgb:RGB) -> (r:UInt8, g:UInt8, b:UInt8){
return (CGFloatToUInt8(rgb.r), CGFloatToUInt8(rgb.g), CGFloatToUInt8(rgb.b));
}
func CGFloatToUInt8(_ float:CGFloat) -> UInt8{
return UInt8(max(0, min(255, 255 * float)));
}
// size of alpha checkering
let ALPHA_TILE:CGFloat = 8;
// draws a checkered background for displaying tranlucent colors
func drawAlphaBackground(_ context:CGContext?, rect:CGRect){
UIColor.lightGray.withAlphaComponent(0.5).set();
for x in 0...Int(rect.width / ALPHA_TILE) {
for y in 0...Int(rect.height / ALPHA_TILE) {
if (x % 2 == 0 && y % 2 == 0) || (x % 2 == 1 && y % 2 == 1){
context?.fill(CGRect(x: CGFloat(x) * ALPHA_TILE, y: CGFloat(y) * ALPHA_TILE, width: ALPHA_TILE, height: ALPHA_TILE))
}
}
}
}
// converts HSV to RGB
public func HSVtoRGB(h hue:CGFloat, s:CGFloat, v:CGFloat) -> (RGB) {
var h = hue;
h *= 360;
if(h >= 360){
h -= 360;
}
let hprime = h / 60;
var r,g,b:CGFloat;
if(s <= 0){
r = v;
g = v;
b = v;
}else{
let f = hprime - floor(hprime);
let p = v * (1 - s);
let q = v * (1 - s * f);
let t = v * (1 - s * (1 - f));
switch(floor(hprime)){
case 0:
r = v;
g = t;
b = p;
break;
case 1:
r = q;
g = v;
b = p;
break;
case 2:
r = p;
g = v;
b = t;
break;
case 3:
r = p;
g = q;
b = v;
break;
case 4:
r = t;
g = p;
b = v;
break;
default:
r = v;
g = p;
b = q;
break;
}
}
return RGB(r, g, b);
}
// converts RGB to HSV, returning oldHSV if the hue cannot be determined.
public func RGBtoHSV(_ rgb:RGB, oldHSV:HSV) -> (HSV) {
var hsv:HSV;
var cmin:CGFloat;
var cmax:CGFloat;
var delta:CGFloat;
cmin = min(rgb.r, min(rgb.g, rgb.b));
cmax = max(rgb.r, max(rgb.g, rgb.b));
hsv.v = cmax;
delta = cmax - cmin;
if(cmax != 0){
hsv.s = delta / cmax;
}else{
hsv.h = -1;
hsv.s = 0;
return hsv;
}
if(rgb.r == cmax){
hsv.h = (rgb.g - rgb.b) / delta;
}else if(rgb.g == cmax){
hsv.h = 2 + (rgb.b - rgb.r) / delta;
}else{
hsv.h = 4 + (rgb.r - rgb.g) / delta;
}
hsv.h *= 60;
if(hsv.h < 0){
hsv.h += 360;
}
hsv.h /= 360;
if(hsv.h.isNaN){
return oldHSV;
}
return hsv;
}
|
mit
|
e4b52cb89df930b680b793ed17aa71d0
| 20.747126 | 132 | 0.482294 | 3.166527 | false | false | false | false |
n41l/OMGenericTableView
|
Example/OMGenericTableView/PopoverInformationTableCell.swift
|
1
|
5375
|
//
// PopoverInformationTableCell.swift
// OMGenericTableView
//
// Created by HuangKun on 16/5/27.
// Copyright © 2016年 CocoaPods. All rights reserved.
//
import UIKit
import OMGenericTableView
class PopoverInformationTableCell: OMGenericTableCell {
private var informationLabels: [UILabel]?
private var separatorViews: [UIView]?
private var contentsStr: [String] = []
private var separatorStr: [String] = []
private var allCustomConstraints: [NSLayoutConstraint] = []
var infos: [[String]] = [] {
didSet {
_backInfos = infos.map { ($0.first!, $0.last!) }
}
}
private var _backInfos: [(title: String, content: String)] = []
// var handler: OMNPNRClosureBox?
// override func handleCellSelection(withMetaData: OMTableCellMetaData) {
// super.handleCellSelection(withMetaData)
// handler?.unbox()
// }
override func setup(cellWithMetaData: OMTableCellMetaData) {
super.setup(cellWithMetaData)
self.backgroundColor = UIColor(red: 0.467, green: 0.467, blue: 0.467, alpha: 1.00)
resetView()
var views: [String: AnyObject] = [:]
informationLabels = _backInfos.enumerate().map {index, data in
let result = UILabel()
result.text = data.content + " " + data.title
result.textColor = UIColor(red: 0.753, green: 0.753, blue: 0.753, alpha: 1.00)
result.font = UIFont.systemFontOfSize(15)
result.textAlignment = .Center
result.sizeToFit()
result.translatesAutoresizingMaskIntoConstraints = false
contentsStr.append("label_" + String(index))
views.updateValue(result, forKey: "label_" + String(index))
self.addSubview(result)
return result
}
for (index, label) in informationLabels!.enumerate() {
label.setContentHuggingPriority(Float(label.bounds.width), forAxis: .Horizontal)
}
let referencelabel = informationLabels?.first
let centerY = NSLayoutConstraint(item: referencelabel!, attribute: .CenterY, relatedBy: .Equal, toItem: self, attribute: .CenterY, multiplier: 1, constant: 0)
var separatorViewsWidthConstriants = [NSLayoutConstraint]()
var separatorViewsHightConStraints = [NSLayoutConstraint]()
separatorViews = (0..<(_backInfos.count + 1)).map { index in
let result = UIView(frame: CGRect(x: 0, y: 0, width: 1, height: self.bounds.height * 0.6))
result.backgroundColor = UIColor(red: 0.765, green: 0.765, blue: 0.765, alpha: 1.00)
separatorStr.append("separator_" + String(index))
views.updateValue(result, forKey: "separator_" + String(index))
result.translatesAutoresizingMaskIntoConstraints = false
let width = NSLayoutConstraint(item: result, attribute: .Width, relatedBy: .Equal, toItem: nil, attribute: NSLayoutAttribute(rawValue: 0)!, multiplier: 1, constant: 1)
let height = NSLayoutConstraint(item: result, attribute: .Height, relatedBy: .Equal, toItem: nil, attribute: NSLayoutAttribute(rawValue: 0)!, multiplier: 1, constant: self.bounds.height * 0.5)
separatorViewsWidthConstriants.append(width)
separatorViewsHightConStraints.append(height)
if index == 0 || index == _backInfos.count {
result.alpha = 0
}
self.addSubview(result)
return result
}
var horizontalString = (0..<separatorStr.count).reduce("H:|-(10)-") { (result, index) -> String in
let zeroStr = "-(10)-"
func convert(str: String) -> String {
return "[" + str + "]"
}
guard index < contentsStr.count else { return result + convert(separatorStr[index]) }
return result + convert(separatorStr[index]) + zeroStr + convert(contentsStr[index]) + zeroStr
}
horizontalString += "-(10)-|"
let baseHorizontalConstraints = NSLayoutConstraint.constraintsWithVisualFormat(horizontalString, options: .AlignAllCenterY, metrics: nil, views: views)
allCustomConstraints = baseHorizontalConstraints + separatorViewsWidthConstriants + separatorViewsHightConStraints
allCustomConstraints += [centerY]
_ = allCustomConstraints.map { $0.active = true }
// bottomLineView.frame = CGRect(x: 0, y: self.bounds.height - 1, width: self.bounds.width, height: 1)
// bottomLineView.backgroundColor = UIColor.gd_lineColor()
// self.addSubview(bottomLineView)
self.setNeedsDisplay()
}
private func resetView() {
_ = allCustomConstraints.map { $0.active = false }
allCustomConstraints.removeAll()
contentsStr.removeAll()
separatorStr.removeAll()
guard let labels = informationLabels, separator = separatorViews else { return }
_ = labels.map { $0.removeFromSuperview() }
_ = separator.map { $0.removeFromSuperview() }
informationLabels?.removeAll()
separatorViews?.removeAll()
}
}
|
mit
|
b598abb9c3af47dfe50dc8dd11edd379
| 41.299213 | 204 | 0.609643 | 4.63503 | false | false | false | false |
steelwheels/Canary
|
Source/CNJSONFile.swift
|
1
|
2812
|
/**
* @file CNJSONFile.swift
* @brief Extend CNJSONFile class
* @par Copyright
* Copyright (C) 2015 Steel Wheels Project
*/
import Foundation
public class CNJSONFile {
public class func readFile(URL url : URL) -> (CNJSONObject?, NSError?) {
do {
var result : CNJSONObject? = nil
var error : NSError? = nil
let datap : NSData? = NSData(contentsOf: url)
if let data = datap as Data? {
let json = try JSONSerialization.jsonObject(with: data, options: [])
if let dict = json as? NSDictionary {
result = CNJSONObject(dictionary: dict)
} else if let arr = json as? NSArray {
result = CNJSONObject(array: arr)
} else {
error = NSError.parseError(message: "The data type is NOT dictionary in URL:\(url.absoluteString)")
}
} else {
error = NSError.parseError(message: "Failed to read data from URL:\(url.absoluteString)")
}
return (result, error)
}
catch {
let error = NSError.parseError(message: "Can not serialize the objet in URL:\(url.absoluteString)")
return (nil, error)
}
}
public class func writeFile(URL url: URL, JSONObject srcobj: CNJSONObject) -> NSError? {
do {
let data = try JSONSerialization.data(withJSONObject: srcobj.toObject(), options: JSONSerialization.WritingOptions.prettyPrinted)
try data.write(to: url, options: .atomic)
return nil
}
catch {
let error = NSError.parseError(message: "Can not write data into \(url.absoluteString)")
return error
}
}
public class func serialize(JSONObject srcobj: CNJSONObject) -> (String?, NSError?) {
do {
let data = try JSONSerialization.data(withJSONObject: srcobj.toObject(), options: .prettyPrinted)
let strp = String(data: data, encoding: String.Encoding.utf8)
if let str = strp {
return (str, nil)
} else {
let error = NSError.parseError(message: "Can not translate into string")
return (nil, error)
}
}
catch {
let error = NSError.parseError(message: "Can not serialize")
return (nil, error)
}
}
public class func unserialize(string src : String) -> (CNJSONObject?, NSError?) {
do {
var result : CNJSONObject? = nil
var error : NSError? = nil
let datap = src.data(using: String.Encoding.utf8, allowLossyConversion: false)
if let data = datap {
let json = try JSONSerialization.jsonObject(with: data, options: [])
if let dict = json as? NSDictionary {
result = CNJSONObject(dictionary: dict)
} else if let arr = json as? NSArray {
result = CNJSONObject(array: arr)
} else {
error = NSError.parseError(message: "The data type is NOT dictionary in URL:\(src)")
}
}
return (result, error)
}
catch {
let error = NSError.parseError(message: "Can not serialize the objet in URL:\(src)")
return (nil, error)
}
}
}
|
gpl-2.0
|
434c121cae727b9077c90ffac191d161
| 31.321839 | 132 | 0.666074 | 3.475896 | false | false | false | false |
royhsu/tiny-core
|
Sources/Core/HTTP/HTTPRequest.swift
|
1
|
632
|
//
// HTTPRequest.swift
// TinyCore
//
// Created by Roy Hsu on 2019/1/26.
// Copyright © 2019 TinyWorld. All rights reserved.
//
// MARK: - HTTPRequest
public struct HTTPRequest<Body> where Body: Encodable {
public var url: URL
public var headers: [HTTPHeader: String] = [:]
public var method: HTTPMethod = .get
public var body: Body?
public let bodyEncoder: HTTPBodyEncoder
public init(
url: URL,
body: Body? = nil,
bodyEncoder: HTTPBodyEncoder = JSONEncoder()
) {
self.url = url
self.body = body
self.bodyEncoder = bodyEncoder
}
}
|
mit
|
9a5217746846e4f75ef17e958bc3c1e7
| 16.054054 | 55 | 0.611727 | 3.94375 | false | false | false | false |
MR-Zong/ZGResource
|
Project/FamilyEducationApp-master/家教/SignUpViewController.swift
|
1
|
19938
|
//
// SignUpViewController.swift
// 家教
//
// Created by goofygao on 15/11/16.
// Copyright © 2015年 goofyy. All rights reserved.
//
import UIKit
class SignUpViewController: UIViewController {
@IBOutlet weak var phoneSignButton: UIButton!
@IBOutlet weak var emailSignButton: UIButton!
var registerView: UIView = UIView()
let phoneTextField = UITextField()
let nickNameTextFied = UITextField()
let passwordFirstText = UITextField()
let passwordSecondText = UITextField()
let verificationCodeText = UITextField()
let getVerificationCodeButton = UIButton()
let agreeProtocolButton = UIButton()
let agreeTittleLabel = UILabel()
let registerButton = UIButton()
var timer = NSTimer?()
var second = 60
var alertView = UIAlertView()
let submitRegisterButton = UIButton()
let chooseTeacherOrStudent = UITextField()
let manager = AFHTTPRequestOperationManager()
var identtityButtonTag = 0
/// 需要post的数据
var postDictionary = NSMutableDictionary()
var defalutValue = NSUserDefaults()
override func viewDidLoad() {
super.viewDidLoad()
initView()
}
/**
界面初始化
- returns: no return value
*/
func initView() {
self.navigationController?.navigationBarHidden = false
self.view.backgroundColor = UIColor(red: 65.0 / 255.0, green: 62.0 / 255.0, blue: 79.0 / 255.0, alpha: 1)
let navBar = self.navigationController?.navigationBar
navBar?.barTintColor = UIColor(red: 65.0 / 255.0, green: 62.0 / 255.0, blue: 79.0 / 255.0, alpha: 1)
navBar?.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.whiteColor()]
UIApplication.sharedApplication().statusBarStyle = UIStatusBarStyle.LightContent
self.navigationController?.navigationBar.tintColor = UIColor.whiteColor()
phoneSignButton.addTarget(self, action: "phoneSignAction:", forControlEvents: UIControlEvents.TouchDown)
emailSignButton.addTarget(self, action: "emailSianAction:", forControlEvents: UIControlEvents.TouchDown)
registerView.frame = CGRectMake(0, 105, DeviceData.width * 2 , DeviceData.height - CGRectGetMaxY(phoneSignButton.frame))
registerView.backgroundColor = UIColor(red: 65.0 / 255.0, green: 62.0 / 255.0, blue: 79.0 / 255.0, alpha: 1)
self.view.addSubview(registerView)
phoneTextField.frame = CGRectMake(40, 40, DeviceData.width - 80, 30)
phoneTextField.placeholder = "输入你的手机号"
phoneTextField.textColor = UIColor.blackColor()
phoneTextField.borderStyle = UITextBorderStyle.RoundedRect
phoneTextField.textAlignment = NSTextAlignment.Center
phoneTextField.font = UIFont.systemFontOfSize(14)
phoneTextField.keyboardType = UIKeyboardType.NumberPad
phoneTextField.returnKeyType = UIReturnKeyType.Next
self.registerView.addSubview(phoneTextField)
nickNameTextFied.frame = CGRectMake(40, 80, DeviceData.width - 80, 30)
nickNameTextFied.placeholder = "输入你的昵称"
nickNameTextFied.textColor = UIColor.blackColor()
nickNameTextFied.borderStyle = UITextBorderStyle.RoundedRect
nickNameTextFied.textAlignment = NSTextAlignment.Center
nickNameTextFied.font = UIFont.systemFontOfSize(14)
nickNameTextFied.keyboardType = UIKeyboardType.EmailAddress
nickNameTextFied.returnKeyType = UIReturnKeyType.Next
self.registerView.addSubview(nickNameTextFied)
passwordFirstText.frame = CGRectMake(40, 120, DeviceData.width - 80, 30)
passwordFirstText.placeholder = "密码(不少于6位)"
passwordFirstText.textColor = UIColor.blackColor()
passwordFirstText.borderStyle = UITextBorderStyle.RoundedRect
passwordFirstText.textAlignment = NSTextAlignment.Center
passwordFirstText.font = UIFont.systemFontOfSize(14)
passwordFirstText.keyboardType = UIKeyboardType.EmailAddress
passwordFirstText.returnKeyType = UIReturnKeyType.Next
passwordFirstText.secureTextEntry = true
self.registerView.addSubview(passwordFirstText)
passwordSecondText.frame = CGRectMake(40, 160, DeviceData.width - 80, 30)
passwordSecondText.placeholder = "重复密码"
passwordSecondText.textColor = UIColor.blackColor()
passwordSecondText.borderStyle = UITextBorderStyle.RoundedRect
passwordSecondText.textAlignment = NSTextAlignment.Center
passwordSecondText.font = UIFont.systemFontOfSize(14)
passwordSecondText.keyboardType = UIKeyboardType.EmailAddress
passwordSecondText.returnKeyType = UIReturnKeyType.Next
passwordSecondText.secureTextEntry = true
self.registerView.addSubview(passwordSecondText)
verificationCodeText.frame = CGRectMake(40, 200, DeviceData.width - 200, 30)
verificationCodeText.placeholder = "输入验证码"
verificationCodeText.textColor = UIColor.blackColor()
verificationCodeText.borderStyle = UITextBorderStyle.RoundedRect
verificationCodeText.textAlignment = NSTextAlignment.Center
verificationCodeText.font = UIFont.systemFontOfSize(14)
verificationCodeText.keyboardType = UIKeyboardType.EmailAddress
verificationCodeText.returnKeyType = UIReturnKeyType.Next
self.registerView.addSubview(verificationCodeText)
getVerificationCodeButton.frame = CGRectMake(CGRectGetMaxX(verificationCodeText.frame) + 10, CGRectGetMinY(verificationCodeText.frame), 110, 30)
getVerificationCodeButton.layer.cornerRadius = 5
getVerificationCodeButton.layer.masksToBounds = true
getVerificationCodeButton.backgroundColor = UIColor.blueColor()
getVerificationCodeButton.setTitle("获取验证码", forState: UIControlState.Normal)
getVerificationCodeButton.titleLabel?.font = UIFont.systemFontOfSize(13)
getVerificationCodeButton.titleLabel?.text = "获取验证码"
getVerificationCodeButton.addTarget(self, action: "getVerificationCodeAction:", forControlEvents: UIControlEvents.TouchDown)
self.registerView.addSubview(getVerificationCodeButton)
// agreeProtocolButton.frame = CGRectMake(40, 240, 20, 20)
// agreeProtocolButton.setImage(UIImage(named: "new_feature_share_false"), forState: UIControlState.Normal)
// agreeProtocolButton.addTarget(self, action: "agreeProtocolAction:", forControlEvents: UIControlEvents.TouchDown)
// self.registerView.addSubview(agreeProtocolButton)
//
// agreeTittleLabel.frame = CGRectMake(65, 240, 100, 21)
// agreeTittleLabel.text = "同意协议 "
// self.registerView.addSubview(agreeTittleLabel)
phoneSignButton.enabled = true
alertView = UIAlertView(title: "提示", message: "请选择你注册的类型", delegate: self, cancelButtonTitle: "取消", otherButtonTitles: "老师", "家长")
alertView.targetForAction("alertAction", withSender: self)
chooseTeacherOrStudent.frame = CGRectMake(CGRectGetMinX(verificationCodeText.frame), CGRectGetMaxY(verificationCodeText.frame) + 15, DeviceData.width - 80, 30)
chooseTeacherOrStudent.keyboardType = UIKeyboardType.NumberPad
// chooseTeacherOrStudent.textColor = UIColor.whiteColor()
chooseTeacherOrStudent.borderStyle = UITextBorderStyle.RoundedRect
chooseTeacherOrStudent.font = UIFont.systemFontOfSize(14)
chooseTeacherOrStudent.text = "家长"
chooseTeacherOrStudent.delegate = self
chooseTeacherOrStudent.tag = 400
chooseTeacherOrStudent.placeholder = "你是老师还是家教"
self.registerView.addSubview(chooseTeacherOrStudent)
submitRegisterButton.frame = CGRectMake(CGRectGetMinX(verificationCodeText.frame), CGRectGetMaxY(chooseTeacherOrStudent.frame) + 15, DeviceData.width - 80, 35)
submitRegisterButton.setImage(UIImage(named: "bt_setr_submit.png"), forState: UIControlState.Normal)
submitRegisterButton.addTarget(self, action: "submitRegisterAction:", forControlEvents: UIControlEvents.TouchDown)
self.registerView.addSubview(submitRegisterButton)
identtityButtonTag = 10
phoneSignButton.setTitleColor(UIColor(white: 1, alpha: 0.8), forState: UIControlState.Normal)
phoneSignButton.backgroundColor = UIColor(red: 0.23, green: 0.34, blue: 0.54, alpha: 1)
phoneSignButton.enabled = false
}
/**
手机注册button
- parameter sender: button self
*/
func phoneSignAction(sender:UIButton) {
emailSignButton.backgroundColor = UIColor.clearColor()
sender.backgroundColor = UIColor(red: 0.23, green: 0.34, blue: 0.54, alpha: 1)
emailSignButton.setTitleColor(UIColor(white: 0, alpha: 0.8), forState: UIControlState.Normal)
sender.setTitleColor(UIColor(white: 1, alpha: 0.8), forState: UIControlState.Normal)
phoneTextField.keyboardType = UIKeyboardType.NumberPad
UIView.animateWithDuration(0.5, delay: 0, options: UIViewAnimationOptions.CurveEaseInOut, animations: { () -> Void in
self.registerView.bounds.origin.x -= DeviceData.width
self.nickNameTextFied.center.x -= DeviceData.width
self.passwordFirstText.center.x -= DeviceData.width
self.passwordSecondText.center.x -= DeviceData.width
self.getVerificationCodeButton.center.x -= DeviceData.height
self.phoneTextField.center.x -= DeviceData.width
self.phoneTextField.placeholder = "请输入你的手机号码"
self.chooseTeacherOrStudent.center.x -= DeviceData.width
self.chooseTeacherOrStudent.center.y += 45
self.verificationCodeText.center.x += DeviceData.width
self.submitRegisterButton.center.x -= DeviceData.width
self.submitRegisterButton.center.y += 45
}, completion: nil)
sender.enabled = false
emailSignButton.enabled = true
print(sender.tag)
identtityButtonTag = sender.tag
}
/**
邮箱注册BUTTON
- parameter sender: button self
*/
func emailSianAction(sender:UIButton) {
sender.backgroundColor = UIColor(red: 0.23, green: 0.34, blue: 0.54, alpha: 1)
phoneSignButton.setTitleColor(UIColor(white: 0, alpha: 0.8), forState: UIControlState.Normal)
sender.setTitleColor(UIColor(white: 1, alpha: 0.8), forState: UIControlState.Normal)
phoneTextField.keyboardType = UIKeyboardType.EmailAddress
phoneSignButton.backgroundColor = UIColor.clearColor()
UIView.animateWithDuration(0.5, delay: 0, options: UIViewAnimationOptions.CurveEaseInOut, animations: { () -> Void in
self.registerView.bounds.origin.x += DeviceData.width
self.nickNameTextFied.center.x += DeviceData.width
self.passwordFirstText.center.x += DeviceData.width
self.passwordSecondText.center.x += DeviceData.width
self.getVerificationCodeButton.center.x += DeviceData.height
self.phoneTextField.center.x += DeviceData.width
self.phoneTextField.placeholder = "请输入你的邮箱"
self.verificationCodeText.center.x -= DeviceData.width
self.chooseTeacherOrStudent.center.x += DeviceData.width
self.chooseTeacherOrStudent.center.y -= 45
self.submitRegisterButton.center.x += DeviceData.width
self.submitRegisterButton.center.y -= 45
}, completion: nil)
sender.enabled = false
phoneSignButton.enabled = true
identtityButtonTag = sender.tag
}
/**
获取验证码 BUTTON
- parameter sender: button self
*/
func getVerificationCodeAction(sender:UIButton) {
sender.enabled = false
timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: "timerAction", userInfo: nil, repeats: true)
if phoneTextField.text == "" {
} else {
manager.responseSerializer.acceptableContentTypes = NSSet(object: "text/html") as Set<NSObject>
let mobileDictionary:NSDictionary = ["mobile":phoneTextField.text!]
manager.POST("http://115.29.54.119:888/Get/getAuth", parameters: mobileDictionary, success: { (operation, response) -> Void in
let responseDic = response as? NSDictionary
let result = responseDic!["userid"]
if let _ = responseDic!["userid"] {
UIAlertView(title: "提示", message: "验证码已经发送\(responseDic!["authCode"])", delegate: nil, cancelButtonTitle: "完成").show()
self.defalutValue.setObject(responseDic!["userid"], forKey: "sign_userid")
self.defalutValue.setObject(responseDic!["authCode"], forKey: "sign_authCode")
} else {
UIAlertView(title: "提示", message: "验证码发送失败", delegate: nil, cancelButtonTitle: "完成").show()
}
}) { (operation, error) -> Void in
}
}
}
/**
验证码点击后倒计时效果
*/
func timerAction() {
if second == 1 {
timer = nil
getVerificationCodeButton.enabled = true
getVerificationCodeButton.backgroundColor = UIColor.blueColor()
} else {
second--
getVerificationCodeButton.backgroundColor = UIColor(hue: 1, saturation: 0.23, brightness: 0.54, alpha: 0.8)
getVerificationCodeButton.setTitle("\(second)" + "秒后重发", forState: UIControlState.Normal)
}
}
/**
同意协议 button
- parameter sender: button self
*/
func agreeProtocolAction(sender:UIButton) {
sender.setImage(UIImage(named: "new_feature_share_true"), forState: UIControlState.Normal)
}
/**
提交当前表单到服务器
- parameter sender: 提交 - button self
*/
func submitRegisterAction(sender:UIButton) {
/**
* 手机注册
*/
if passwordSecondText.text != passwordFirstText.text {
UIAlertView(title: "提示", message: "两次密码输入不一致", delegate: nil, cancelButtonTitle: "返回").show()
} else
if nickNameTextFied.text == "" || phoneTextField.text == "" {
UIAlertView(title: "提示", message: "请正确填写表格", delegate: nil, cancelButtonTitle: "返回").show()
}
if identtityButtonTag == 10 {
print("dfsfsd")
if verificationCodeText.text! == "" || verificationCodeText.text != defalutValue.valueForKey("sign_authCode") as? String {
UIAlertView(title: "提示", message: "请正确填写验证码", delegate: nil, cancelButtonTitle: "返回").show()
} else {
// 21459121print(responseDic)
print("手机注册")
if let userid_sign = defalutValue.valueForKey("sign_userid") {
print("go go go ")
if chooseTeacherOrStudent.text == "老师" {
postDictionary = ["username":nickNameTextFied.text!,"password":passwordFirstText.text!,"type":0,"authCode":verificationCodeText.text!,"mobile":phoneTextField.text!,"userid":userid_sign]
} else {
postDictionary = ["username":nickNameTextFied.text!,"password":passwordFirstText.text!,"type":1,"authCode":verificationCodeText.text!,"mobile":phoneTextField.text!,"userId":userid_sign]
}
manager.responseSerializer.acceptableContentTypes = NSSet(object: "text/html") as Set<NSObject>
manager.POST("http://115.29.54.119:888/Get/regByNum", parameters: postDictionary, success: { (operation, response) -> Void in
let responseDic = response as? NSDictionary
let result = responseDic!["userid"]
if let _ = responseDic!["userid"] {
UIAlertView(title: "注册消息", message: "恭喜你注册成功ID为\(responseDic!["userid"]!)", delegate: nil, cancelButtonTitle: "完成").show()
} else {
UIAlertView(title: "注册消息", message: "注册失败,用户名或手机已注册", delegate: nil, cancelButtonTitle: "完成").show()
}
}) { (operation, error) -> Void in
UIAlertView(title: "注册消息", message: "注册失败,用户名或手机已注册", delegate: nil, cancelButtonTitle: "完成").show()
}
}
}
} else {
if chooseTeacherOrStudent.text == "老师" {
postDictionary = ["username":nickNameTextFied.text!,"password":passwordFirstText.text!,"email":phoneTextField.text!,"type":0]
} else {
postDictionary = ["username":nickNameTextFied.text!,"password":passwordFirstText.text!,"email":phoneTextField.text!,"type":1]
}
/// 创建AFNetWorking管理者
manager.responseSerializer.acceptableContentTypes = NSSet(object: "text/html") as Set<NSObject>
manager.POST("http://115.29.54.119:888/Get/reg", parameters: postDictionary, success: { (operation, response) -> Void in
let responseDic = response as? NSDictionary
let result = responseDic!["userid"]
if let _ = responseDic!["userid"] {
UIAlertView(title: "注册消息", message: "恭喜你注册成功ID为\(responseDic!["userid"]!)", delegate: nil, cancelButtonTitle: "完成").show()
} else {
UIAlertView(title: "注册消息", message: "注册失败,用户名或邮箱重复", delegate: nil, cancelButtonTitle: "完成").show()
}
}) { (operation, error) -> Void in
}
}
}
/**
注销第一响应者
- parameter touches: 点击的透彻
- parameter event: 点击事件
*/
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
self.passwordFirstText.resignFirstResponder()
self.passwordSecondText.resignFirstResponder()
self.phoneTextField.resignFirstResponder()
self.verificationCodeText.resignFirstResponder()
self.nickNameTextFied.resignFirstResponder()
}
}
extension SignUpViewController: UIAlertViewDelegate,UITextFieldDelegate {
func textFieldShouldBeginEditing(textField: UITextField) -> Bool {
self.alertView.show()
return false
}
func alertView(alertView: UIAlertView, didDismissWithButtonIndex buttonIndex: Int) {
if buttonIndex == 1 {
self.chooseTeacherOrStudent.text = "老师"
} else if buttonIndex == 2{
self.chooseTeacherOrStudent.text = "家长"
}
}
}
|
gpl-2.0
|
310b3846c4eff4fa4126a5d1aad7cbcb
| 43.664352 | 209 | 0.63519 | 4.917176 | false | false | false | false |
shamanskyh/FluidQ
|
Shared Models/LengthFormatter.swift
|
1
|
9884
|
//
// LengthFormatter.swift
// FluidQ
// Taken from Precircuiter
// http://github.com/shamanskyh/Precircuiter
//
// Created by Harry Shamansky on 5/21/15.
// Copyright © 2015 Harry Shamansky. All rights reserved.
//
import Darwin
extension String {
/// Converts a string in Vectorworks' "Feet and Inches" format to meters.
/// - Returns: the value converted to meters
func feetAndInchesToMeters() throws -> Double {
var feet: Double = 0.0
var inches: Double = 0.0
var numerator: String = ""
var denominator: String = ""
var exponent: String = ""
var fillDenom = false
var fillExponent = false
for char in self.characters {
if char == "'" || char == "’" || char == "‘" { // feet
if exponent != "" {
guard let n1 = Float(numerator), let e1 = Float(exponent) else {
throw LengthFormatterError.StringToNumber
}
feet += Double(n1 * powf(10, e1))
} else if denominator == "" {
guard let n1 = Double(numerator) else {
throw LengthFormatterError.StringToNumber
}
feet += n1
} else {
guard let n1 = Double(numerator), let d1 = Double(denominator) else {
throw LengthFormatterError.StringToNumber
}
feet += n1 / d1
}
exponent = ""
numerator = ""
denominator = ""
fillDenom = false
} else if char == "\"" || char == "“" || char == "”" { // inches
if exponent != "" {
guard let n1 = Float(numerator), let e1 = Float(exponent) else {
throw LengthFormatterError.StringToNumber
}
inches += Double(n1 * powf(10, e1))
} else if denominator == "" {
guard let n1 = Double(numerator) else {
throw LengthFormatterError.StringToNumber
}
inches += n1
} else {
guard let n1 = Double(numerator), let d1 = Double(denominator) else {
throw LengthFormatterError.StringToNumber
}
inches += n1 / d1
}
exponent = ""
numerator = ""
denominator = ""
fillDenom = false
} else if char == "e" { // power
fillExponent = true
} else if char == "/" { // fractional feet or inches
guard fillDenom == false else {
throw LengthFormatterError.FractionalFormattingError
}
fillDenom = true
} else if char >= "0" && char <= "9" || char == "." || char == "-" { // number
if fillExponent {
exponent.append(char)
}else if fillDenom {
denominator.append(char)
} else {
numerator.append(char)
}
} else if char == " " { // space - either separator after apostrophe or improper fraction
if numerator == "" && denominator == "" {
continue
} else {
guard let n1 = Double(numerator) else {
throw LengthFormatterError.StringToNumber
}
inches += n1
numerator = ""
}
} else if char == "," {
continue
} else {
throw LengthFormatterError.UnexpectedCharacter
}
}
return (kMetersInFoot * feet) + (kMetersInInch * inches)
}
/// converts an string of known units to meters
/// - Parameter metersInUnit: the number of meters per unit
/// - Returns: the converted length in meters.
func unitToMeter(metersInUnit: Double) throws -> Double {
var units: Double = 0.0
var numerator: String = ""
var denominator: String = ""
var exponent: String = ""
var fillDenom = false
var fillExponent = false
for char in self.characters {
if char == "e" { // power
fillExponent = true
} else if char == "/" { // fractional feet or inches
guard fillDenom == false else {
throw LengthFormatterError.FractionalFormattingError
}
fillDenom = true
} else if char >= "0" && char <= "9" || char == "." || char == "-" { // number
if fillExponent {
exponent.append(char)
}else if fillDenom {
denominator.append(char)
} else {
numerator.append(char)
}
} else if char == " " { // space - either separator after apostrophe or improper fraction
if numerator == "" && denominator == "" {
continue
} else {
guard let n1 = Double(numerator) else {
throw LengthFormatterError.StringToNumber
}
units += n1
numerator = ""
}
} else if char == "," {
continue
} else {
throw LengthFormatterError.UnexpectedCharacter
}
}
if exponent != "" {
guard let n1 = Float(numerator), let e1 = Float(exponent) else {
throw LengthFormatterError.StringToNumber
}
units += Double(n1 * powf(10, e1))
} else if denominator == "" {
guard let n1 = Double(numerator) else {
throw LengthFormatterError.StringToNumber
}
units += n1
} else {
guard let n1 = Double(numerator), let d1 = Double(denominator) else {
throw LengthFormatterError.StringToNumber
}
units += n1 / d1
}
return units * metersInUnit
}
/// takes a string of arbitrary unit, and converts it to meters based on its
/// unit label. If unit label is not present, fallback to user preferences.
/// If those are unavailable, assume the string is already in meters.
/// - Returns: the (possibly converted) length in meters
func unknownUnitToMeters() throws -> Double {
// Determine the case
do {
if (self.rangeOfString("'") != nil || self.rangeOfString("’") != nil || self.rangeOfString("‘") != nil) &&
(self.rangeOfString("\"") != nil || self.rangeOfString("“") != nil || self.rangeOfString("”") != nil) {
return try self.feetAndInchesToMeters()
} else if (self.rangeOfString("'") != nil || self.rangeOfString("’") != nil || self.rangeOfString("‘") != nil) {
let replacementString = self.stringByReplacingOccurrencesOfString("'", withString: "").stringByReplacingOccurrencesOfString("’", withString: "").stringByReplacingOccurrencesOfString("‘", withString: "")
return try replacementString.unitToMeter(kMetersInFoot)
} else if (self.rangeOfString("\"") != nil || self.rangeOfString("“") != nil || self.rangeOfString("”") != nil) {
let replacementString = self.stringByReplacingOccurrencesOfString("\"", withString: "").stringByReplacingOccurrencesOfString("“", withString: "").stringByReplacingOccurrencesOfString("”", withString: "")
return try replacementString.unitToMeter(kMetersInInch)
} else if self.rangeOfString("yd") != nil {
return try self.stringByReplacingOccurrencesOfString("yd", withString: "").unitToMeter(kMetersInYard)
} else if self.rangeOfString("mi") != nil {
return try self.stringByReplacingOccurrencesOfString("mi", withString: "").unitToMeter(kMetersInMile)
} else if self.rangeOfString("µm") != nil {
return try self.stringByReplacingOccurrencesOfString("µm", withString: "").unitToMeter(kMetersInMicron)
} else if self.rangeOfString("mm") != nil {
return try self.stringByReplacingOccurrencesOfString("mm", withString: "").unitToMeter(kMetersInMillimeter)
} else if self.rangeOfString("cm") != nil {
return try self.stringByReplacingOccurrencesOfString("cm", withString: "").unitToMeter(kMetersInCentimeter)
} else if self.rangeOfString("km") != nil {
return try self.stringByReplacingOccurrencesOfString("km", withString: "").unitToMeter(kMetersInKilometer)
} else if self.rangeOfString("m") != nil {
return try self.stringByReplacingOccurrencesOfString("m", withString: "").unitToMeter(kMetersInMeter)
} else if self.rangeOfString("°") != nil {
return try self.stringByReplacingOccurrencesOfString("°", withString: "").unitToMeter(kMetersInDegrees)
} else {
// default to meters
return try self.unitToMeter(kMetersInMeter)
}
} catch LengthFormatterError.UnexpectedCharacter {
throw LengthFormatterError.UnexpectedCharacter
} catch LengthFormatterError.StringToNumber {
throw LengthFormatterError.StringToNumber
} catch LengthFormatterError.FractionalFormattingError {
throw LengthFormatterError.FractionalFormattingError
}
}
}
|
mit
|
c7c6bc14eae987655ab733d5638552f9
| 45.448113 | 219 | 0.519854 | 5.305496 | false | false | false | false |
cpmpercussion/microjam
|
chirpey/ChirpRecordingView.swift
|
1
|
9455
|
//
// ChirpRecordingView.swift
// microjam
//
// Created by Charles Martin on 11/8/17.
// Copyright © 2017 Charles Martin. All rights reserved.
//
import UIKit
/// Subclass of ChirpView that enables recording and user interaction
class ChirpRecordingView: ChirpView {
// Recording
/// Storage for the date that a performance started recording for timing
var startTime = Date()
/// True if the view has started a recording (so touches should be recorded)
var recording = false
/// Colour to render touches as they are recorded.
var recordingColour : CGColor?
/// Animated tail segments for practice mode.
var tailSegments = [TailSegment]()
/// Programmatic init getting ready for recording.
override init(frame: CGRect) {
super.init(frame: frame)
resetAnimationLayer()
print("ChirpRecordingView: Loading programmatically with frame: ", self.frame)
isMultipleTouchEnabled = true
isUserInteractionEnabled = true
clearForRecording() // gets view ready for recording.
}
/// Initialises view for recording, rather than playback.
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
resetAnimationLayer()
isMultipleTouchEnabled = true
isUserInteractionEnabled = true
clearForRecording() // gets view ready for recording.
}
}
//MARK: - touch interaction
/// Contains touch interaction and recording functions for ChirpView
extension ChirpRecordingView {
/// Responds to taps in the ChirpView, passes on to superviews and reacts.
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
superview?.touchesBegan(touches, with: event)
lastPoint = touches.first?.location(in: superview!)
let size = touches.first?.majorRadius
if recording {
// draw and record touch if recording
if (!started) {
startTime = Date()
started = true
}
swiped = false
drawDot(at: lastPoint!, withColour: recordingColour ?? DEFAULT_RECORDING_COLOUR)
recordTouch(at: lastPoint!, withRadius: size!, thatWasMoving:false)
} else {
// not recording, add disappearing touches.
addTailSegment(at: lastPoint!, withSize: size!, thatWasMoving: false)
}
// always make a sound.
self.makeSound(at: self.lastPoint!, withRadius: size!, thatWasMoving: false)
}
/// Clips a CGPoint to the bounds of the ChirpRecordingView.
func clipTouchLocationToBounds(_ point: CGPoint) -> CGPoint {
let x = max(min(point.x, bounds.width), 0)
let y = max(min(point.y, bounds.height), 0)
return CGPoint.init(x: x, y: y)
}
/// Responds to moving touch signals, responds with sound and recordings.
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
superview?.touchesMoved(touches, with: event)
let currentPoint = clipTouchLocationToBounds((touches.first?.location(in: superview!))!)
let size = touches.first?.majorRadius
if recording {
// draw and record touch if recording
swiped = true
drawLine(from:self.lastPoint!, to:currentPoint, withColour:recordingColour ?? DEFAULT_RECORDING_COLOUR)
lastPoint = currentPoint
recordTouch(at: currentPoint, withRadius: size!, thatWasMoving: true)
} else {
// not recording, add disappearing touches.
addTailSegment(at: currentPoint, withSize: size!, thatWasMoving: true)
lastPoint = currentPoint
}
// Always make a sound.
makeSound(at: currentPoint, withRadius: size!, thatWasMoving: true)
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
// touchesEnded in case needed.
superview?.touchesEnded(touches, with: event)
}
/**
Adds a touch point to the recording data including whether it was moving
and the current time.
**/
func recordTouch(at point : CGPoint, withRadius radius : CGFloat, thatWasMoving moving : Bool) {
let time = -1.0 * startTime.timeIntervalSinceNow
let x = Double(point.x) / Double(frame.size.width)
let y = Double(point.y) / Double(frame.size.width)
let z = Double(radius)
if recording { // only record when recording.
performance?.recordTouchAt(time: time, x: x, y: y, z: z, moving: moving)
}
}
/// Closes the recording and returns the performance.
func saveRecording() -> ChirpPerformance? {
recording = false
guard let output = self.performance,
let im = moveAnimationLayerToImage() else {
return nil
}
image = im // set the image to be the saved image
output.image = im // save the saved image to the output performance
output.performer = UserProfile.shared.profile.stageName
output.instrument = SoundSchemes.namesForKeys[UserProfile.shared.profile.soundScheme]!
output.date = Date()
return output
}
/// Initialise the ChirpView for a new recording
func clearForRecording() {
print("ChirpRecordingView: Clearing for a New Performance")
recording = false
started = false
lastPoint = CG_INIT_POINT
swiped = false
image = UIImage()
performance = ChirpPerformance() // get a blank performance.
performance?.instrument = SoundSchemes.namesForKeys[UserProfile.shared.profile.soundScheme]!
recordingColour = performance?.colour.cgColor ?? DEFAULT_RECORDING_COLOUR
playbackColour = performance?.colour.brighterColor.cgColor ?? DEFAULT_PLAYBACK_COLOUR
openUserSoundScheme()
}
}
// MARK: Tail segment drawing functions
extension ChirpRecordingView {
/// Storage for a single tail segment which consists of a touch location and a timer for removing it.
struct TailSegment {
var point: CGPoint
var moving: Bool
var size: CGFloat
var layer: CALayer?
var timer: Timer
}
/// Add animated tail segment that removes itself after a certain time.
private func addTailSegment(at point: CGPoint, withSize size: CGFloat, thatWasMoving moving: Bool) {
// make a timer to self destruct the segment.
let timer = Timer.scheduledTimer(withTimeInterval: 0.3, repeats: false) { (timer) in
self.removeOldestTailSegment() // remove the oldest segment
}
// figure out last point, if no previous segment, just use same point.
var lastPoint = point
// make a line only when point is moving, and there was a previous point.
if let seg = tailSegments.last, moving {
lastPoint = seg.point
}
// make a CALayer for the segment
let tailLayer = makeSegmentLayer(from: lastPoint, to: point, withColour: self.recordingColour ?? DEFAULT_RECORDING_COLOUR)
// make a struct for the segment
let tailSegment = TailSegment(point: point, moving: moving, size: size, layer: tailLayer, timer: timer)
tailSegments.append(tailSegment) // add to storage
layer.addSublayer(tailLayer) // draw the tail segment
}
/// Draw a tail segment returning a CALayer
func makeSegmentLayer(from: CGPoint, to: CGPoint, withColour color: CGColor) -> CALayer {
let line = CAShapeLayer()
let linePath = UIBezierPath()
linePath.move(to: from)
linePath.addLine(to: to)
line.path = linePath.cgPath
line.lineCap = .round
line.lineWidth = 10.0
line.fillColor = nil
line.opacity = 1.0
line.strokeColor = color
let animation = CABasicAnimation(keyPath: "opacity")
animation.fromValue = 1.0
animation.toValue = 0.0
animation.duration = 0.3
line.add(animation, forKey: animation.keyPath)
return line
}
/// A timed function to remove the oldest tail segment from the stored list.
func removeOldestTailSegment() {
if let seg = self.tailSegments.first {
self.tailSegments.removeFirst() // remove from array
seg.layer?.removeFromSuperlayer() // remove layer from view
seg.timer.invalidate() // cancel the timer
}
}
}
// MARK: Pd (Sound) Functions
extension ChirpRecordingView {
/// Opens the SoundScheme specified in the user's profile.
func openUserSoundScheme() {
let userChoiceKey = UserProfile.shared.profile.soundScheme
print("RecView: got sound \(userChoiceKey)")
if let userChoiceFile = SoundSchemes.pdFilesForKeys[userChoiceKey], let userChoiceName = SoundSchemes.namesForKeys[userChoiceKey] {
openPd(file: userChoiceFile)
self.performance?.instrument = userChoiceName // update recording performance.
print("RecView: opening \(userChoiceFile)")
}
}
}
// MARK : Gesture Recognition
extension ChirpRecordingView {
/// Don't return gesture recognizer signals if the view is in an interactive state.
override func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
return false
}
}
|
mit
|
5293e3866d81e19343385d9363c781b6
| 37.90535 | 139 | 0.646393 | 4.659438 | false | false | false | false |
Bartlebys/Bartleby
|
Bartleby.xOS/core/extensions/HTTPContext+Conveniences.swift
|
1
|
485
|
//
// HTTPContext+Conveniences.swift
// BartlebyKit
//
// Created by Benoit Pereira da silva on 27/10/2016.
//
//
import Foundation
extension HTTPContext{
public convenience init(code: Int!, caller: String!, relatedURL: URL?, httpStatusCode: Int, responseString:String="") {
self.init()
self.code=code
self.caller=caller
self.relatedURL=relatedURL
self.httpStatusCode=httpStatusCode
self.responseString=responseString
}
}
|
apache-2.0
|
60effe0a1f1c8c78dfdf97658b59fe75
| 21.045455 | 123 | 0.676289 | 4.110169 | false | false | false | false |
sstadelman/Socket.IO-Client-Swift
|
SocketIOClientSwift/SocketEngine.swift
|
6
|
25908
|
//
// SocketEngine.swift
// Socket.IO-Swift
//
// Created by Erik Little on 3/3/15.
//
// 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 final class SocketEngine: NSObject, WebSocketDelegate, SocketLogClient {
private typealias Probe = (msg:String, type:PacketType, data:ContiguousArray<NSData>?)
private typealias ProbeWaitQueue = [Probe]
private let allowedCharacterSet = NSCharacterSet(charactersInString: "!*'();:@&=+$,/?%#[]\" {}").invertedSet
private let workQueue = NSOperationQueue()
private let emitQueue = dispatch_queue_create("engineEmitQueue", DISPATCH_QUEUE_SERIAL)
private let parseQueue = dispatch_queue_create("engineParseQueue", DISPATCH_QUEUE_SERIAL)
private let handleQueue = dispatch_queue_create("engineHandleQueue", DISPATCH_QUEUE_SERIAL)
private let session:NSURLSession!
private var closed = false
private var _connected = false
private var extraHeaders:[String: String]?
private var fastUpgrade = false
private var forcePolling = false
private var forceWebsockets = false
private var pingInterval:Double?
private var pingTimer:NSTimer?
private var pingTimeout = 0.0 {
didSet {
pongsMissedMax = Int(pingTimeout / (pingInterval ?? 25))
}
}
private var pongsMissed = 0
private var pongsMissedMax = 0
private var postWait = [String]()
private var _polling = true
private var probing = false
private var probeWait = ProbeWaitQueue()
private var waitingForPoll = false
private var waitingForPost = false
private var _websocket = false
private var websocketConnected = false
let logType = "SocketEngine"
var connected:Bool {
return _connected
}
weak var client:SocketEngineClient?
var cookies:[NSHTTPCookie]?
var log = false
var polling:Bool {
return _polling
}
var sid = ""
var socketPath = ""
var urlPolling:String?
var urlWebSocket:String?
var websocket:Bool {
return _websocket
}
var ws:WebSocket?
public enum PacketType:Int {
case OPEN = 0
case CLOSE = 1
case PING = 2
case PONG = 3
case MESSAGE = 4
case UPGRADE = 5
case NOOP = 6
init?(str:String?) {
if let value = str?.toInt(), raw = PacketType(rawValue: value) {
self = raw
} else {
return nil
}
}
}
public init(client:SocketEngineClient, sessionDelegate:NSURLSessionDelegate?) {
self.client = client
self.session = NSURLSession(configuration: NSURLSessionConfiguration.defaultSessionConfiguration(),
delegate: sessionDelegate, delegateQueue: workQueue)
}
public convenience init(client:SocketEngineClient, opts:NSDictionary?) {
self.init(client: client, sessionDelegate: opts?["sessionDelegate"] as? NSURLSessionDelegate)
forceWebsockets = opts?["forceWebsockets"] as? Bool ?? false
forcePolling = opts?["forcePolling"] as? Bool ?? false
cookies = opts?["cookies"] as? [NSHTTPCookie]
log = opts?["log"] as? Bool ?? false
socketPath = opts?["path"] as? String ?? ""
extraHeaders = opts?["extraHeaders"] as? [String: String]
}
deinit {
SocketLogger.log("Engine is being deinit", client: self)
}
public func close(#fast:Bool) {
SocketLogger.log("Engine is being closed. Fast: %@", client: self, args: fast)
pingTimer?.invalidate()
closed = true
ws?.disconnect()
if fast || polling {
write("", withType: PacketType.CLOSE, withData: nil)
client?.engineDidClose("Disconnect")
}
stopPolling()
}
private func createBinaryDataForSend(data:NSData) -> (NSData?, String?) {
if websocket {
var byteArray = [UInt8](count: 1, repeatedValue: 0x0)
byteArray[0] = 4
var mutData = NSMutableData(bytes: &byteArray, length: 1)
mutData.appendData(data)
return (mutData, nil)
} else {
var str = "b4"
str += data.base64EncodedStringWithOptions(
NSDataBase64EncodingOptions.Encoding64CharacterLineLength)
return (nil, str)
}
}
private func createURLs(params:[String: AnyObject]?) -> (String?, String?) {
if client == nil {
return (nil, nil)
}
let path = socketPath == "" ? "/socket.io" : socketPath
var url = "\(client!.socketURL)\(path)/?transport="
var urlPolling:String
var urlWebSocket:String
if client!.secure {
urlPolling = "https://" + url + "polling"
urlWebSocket = "wss://" + url + "websocket"
} else {
urlPolling = "http://" + url + "polling"
urlWebSocket = "ws://" + url + "websocket"
}
if params != nil {
for (key, value) in params! {
let keyEsc = key.stringByAddingPercentEncodingWithAllowedCharacters(
allowedCharacterSet)!
urlPolling += "&\(keyEsc)="
urlWebSocket += "&\(keyEsc)="
if value is String {
let valueEsc = (value as! String).stringByAddingPercentEncodingWithAllowedCharacters(
allowedCharacterSet)!
urlPolling += "\(valueEsc)"
urlWebSocket += "\(valueEsc)"
} else {
urlPolling += "\(value)"
urlWebSocket += "\(value)"
}
}
}
return (urlPolling, urlWebSocket)
}
private func createWebsocket(andConnect connect:Bool) {
let wsUrl = urlWebSocket! + (sid == "" ? "" : "&sid=\(sid)")
ws = WebSocket(url: NSURL(string: wsUrl)!,
cookies: cookies)
if extraHeaders != nil {
for (headerName, value) in extraHeaders! {
ws?.headers[headerName] = value
}
}
ws?.queue = handleQueue
ws?.delegate = self
if connect {
ws?.connect()
}
}
private func doFastUpgrade() {
if waitingForPoll {
SocketLogger.err("Outstanding poll when switched to WebSockets," +
"we'll probably disconnect soon. You should report this.", client: self)
}
sendWebSocketMessage("", withType: PacketType.UPGRADE, datas: nil)
_websocket = true
_polling = false
fastUpgrade = false
probing = false
flushProbeWait()
}
private func doPoll() {
if websocket || waitingForPoll || !connected {
return
}
waitingForPoll = true
let req = NSMutableURLRequest(URL: NSURL(string: urlPolling! + "&sid=\(sid)&b64=1")!)
if cookies != nil {
let headers = NSHTTPCookie.requestHeaderFieldsWithCookies(cookies!)
req.allHTTPHeaderFields = headers
}
if extraHeaders != nil {
for (headerName, value) in extraHeaders! {
req.setValue(value, forHTTPHeaderField: headerName)
}
}
doRequest(req)
}
private func doRequest(req:NSMutableURLRequest) {
if !polling {
return
}
req.cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringLocalAndRemoteCacheData
SocketLogger.log("Doing polling request", client: self)
session.dataTaskWithRequest(req) {[weak self] data, res, err in
if let this = self {
if err != nil {
if this.polling {
this.handlePollingFailed(err.localizedDescription)
} else {
SocketLogger.err(err.localizedDescription, client: this)
}
return
}
SocketLogger.log("Got polling response", client: this)
if let str = NSString(data: data, encoding: NSUTF8StringEncoding) as? String {
dispatch_async(this.parseQueue) {[weak this] in
this?.parsePollingMessage(str)
}
}
this.waitingForPoll = false
if this.fastUpgrade {
this.doFastUpgrade()
} else if !this.closed && this.polling {
this.doPoll()
}
}}.resume()
}
private func flushProbeWait() {
SocketLogger.log("Flushing probe wait", client: self)
dispatch_async(emitQueue) {[weak self] in
if let this = self {
for waiter in this.probeWait {
this.write(waiter.msg, withType: waiter.type, withData: waiter.data)
}
this.probeWait.removeAll(keepCapacity: false)
if this.postWait.count != 0 {
this.flushWaitingForPostToWebSocket()
}
}
}
}
private func flushWaitingForPost() {
if postWait.count == 0 || !connected {
return
} else if websocket {
flushWaitingForPostToWebSocket()
return
}
var postStr = ""
for packet in postWait {
let len = count(packet)
postStr += "\(len):\(packet)"
}
postWait.removeAll(keepCapacity: false)
let req = NSMutableURLRequest(URL: NSURL(string: urlPolling! + "&sid=\(sid)")!)
if cookies != nil {
let headers = NSHTTPCookie.requestHeaderFieldsWithCookies(cookies!)
req.allHTTPHeaderFields = headers
}
req.HTTPMethod = "POST"
req.setValue("text/plain; charset=UTF-8", forHTTPHeaderField: "Content-Type")
let postData = postStr.dataUsingEncoding(NSUTF8StringEncoding,
allowLossyConversion: false)!
req.HTTPBody = postData
req.setValue(String(postData.length), forHTTPHeaderField: "Content-Length")
waitingForPost = true
SocketLogger.log("POSTing: %@", client: self, args: postStr)
session.dataTaskWithRequest(req) {[weak self] data, res, err in
if let this = self {
if err != nil && this.polling {
this.handlePollingFailed(err.localizedDescription)
return
} else if err != nil {
NSLog(err.localizedDescription)
return
}
this.waitingForPost = false
dispatch_async(this.emitQueue) {[weak this] in
if !(this?.fastUpgrade ?? true) {
this?.flushWaitingForPost()
this?.doPoll()
}
}
}}.resume()
}
// We had packets waiting for send when we upgraded
// Send them raw
private func flushWaitingForPostToWebSocket() {
for msg in postWait {
ws?.writeString(msg)
}
postWait.removeAll(keepCapacity: true)
}
private func handleClose() {
if polling {
client?.engineDidClose("Disconnect")
}
}
private func checkIfMessageIsBase64Binary(var message:String) {
if message.hasPrefix("b4") {
// binary in base64 string
message.removeRange(Range<String.Index>(start: message.startIndex,
end: advance(message.startIndex, 2)))
if let data = NSData(base64EncodedString: message,
options: NSDataBase64DecodingOptions.IgnoreUnknownCharacters), client = client {
dispatch_async(client.handleQueue) {[weak self] in
self?.client?.parseBinaryData(data)
}
}
}
}
private func handleMessage(message:String) {
if let client = client {
dispatch_async(client.handleQueue) {[weak client] in
client?.parseSocketMessage(message)
}
}
}
private func handleNOOP() {
doPoll()
}
private func handleOpen(openData:String) {
var err:NSError?
let mesData = openData.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!
if let json = NSJSONSerialization.JSONObjectWithData(mesData,
options: NSJSONReadingOptions.AllowFragments,
error: &err) as? NSDictionary, sid = json["sid"] as? String {
let upgradeWs: Bool
self.sid = sid
_connected = true
if let upgrades = json["upgrades"] as? [String] {
upgradeWs = upgrades.filter {$0 == "websocket"}.count != 0
} else {
upgradeWs = false
}
if let pingInterval = json["pingInterval"] as? Double, pingTimeout = json["pingTimeout"] as? Double {
self.pingInterval = pingInterval / 1000.0
self.pingTimeout = pingTimeout / 1000.0
}
if !forcePolling && !forceWebsockets && upgradeWs {
createWebsocket(andConnect: true)
}
} else {
client?.didError("Engine failed to handshake")
return
}
startPingTimer()
if !forceWebsockets {
doPoll()
}
}
private func handlePong(pongMessage:String) {
pongsMissed = 0
// We should upgrade
if pongMessage == "3probe" {
upgradeTransport()
}
}
// A poll failed, tell the client about it
private func handlePollingFailed(reason:String) {
_connected = false
ws?.disconnect()
pingTimer?.invalidate()
waitingForPoll = false
waitingForPost = false
// If cancelled we were already closing
if client == nil || reason == "cancelled" {
return
}
if !closed {
client?.didError(reason)
client?.engineDidClose(reason)
}
}
public func open(opts:[String: AnyObject]? = nil) {
if connected {
SocketLogger.err("Tried to open while connected", client: self)
client?.didError("Tried to open while connected")
return
}
SocketLogger.log("Starting engine", client: self)
SocketLogger.log("Handshaking", client: self)
closed = false
(urlPolling, urlWebSocket) = createURLs(opts)
if forceWebsockets {
_polling = false
_websocket = true
createWebsocket(andConnect: true)
return
}
let reqPolling = NSMutableURLRequest(URL: NSURL(string: urlPolling! + "&b64=1")!)
if cookies != nil {
let headers = NSHTTPCookie.requestHeaderFieldsWithCookies(cookies!)
reqPolling.allHTTPHeaderFields = headers
}
if extraHeaders != nil {
for (headerName, value) in extraHeaders! {
reqPolling.setValue(value, forHTTPHeaderField: headerName)
}
}
doRequest(reqPolling)
}
// Translatation of engine.io-parser#decodePayload
private func parsePollingMessage(str:String) {
if count(str) == 1 {
return
}
// println(str)
let strArray = Array(str)
var length = ""
var n = 0
var msg = ""
func testLength(length:String, inout n:Int) -> Bool {
if let num = length.toInt() {
n = num
return false
} else {
return true
}
}
for var i = 0, l = count(str); i < l; i++ {
let chr = String(strArray[i])
if chr != ":" {
length += chr
} else {
if length == "" || testLength(length, &n) {
SocketLogger.err("Parsing error: %@", client: self, args: str)
handlePollingFailed("Error parsing XHR message")
return
}
msg = String(strArray[i+1...i+n])
if let lengthInt = length.toInt() where lengthInt != count(msg) {
SocketLogger.err("Parsing error: %@", client: self, args: str)
return
}
if count(msg) != 0 {
// Be sure to capture the value of the msg
dispatch_async(handleQueue) {[weak self, msg] in
self?.parseEngineMessage(msg, fromPolling: true)
}
}
i += n
length = ""
}
}
}
private func parseEngineData(data:NSData) {
if let client = client {
dispatch_async(client.handleQueue) {[weak self] in
self?.client?.parseBinaryData(data.subdataWithRange(NSMakeRange(1, data.length - 1)))
}
}
}
private func parseEngineMessage(var message:String, fromPolling:Bool) {
SocketLogger.log("Got message: %@", client: self, args: message)
if fromPolling {
fixDoubleUTF8(&message)
}
let type = PacketType(str: (message["^(\\d)"].groups()?[1])) ?? {
self.checkIfMessageIsBase64Binary(message)
return PacketType.NOOP
}()
switch type {
case PacketType.MESSAGE:
message.removeAtIndex(message.startIndex)
handleMessage(message)
case PacketType.NOOP:
handleNOOP()
case PacketType.PONG:
handlePong(message)
case PacketType.OPEN:
message.removeAtIndex(message.startIndex)
handleOpen(message)
case PacketType.CLOSE:
handleClose()
default:
SocketLogger.log("Got unknown packet type", client: self)
}
}
private func probeWebSocket() {
if websocketConnected {
sendWebSocketMessage("probe", withType: PacketType.PING)
}
}
/// Send an engine message (4)
public func send(msg:String, withData datas:ContiguousArray<NSData>?) {
if probing {
probeWait.append((msg, PacketType.MESSAGE, datas))
} else {
write(msg, withType: PacketType.MESSAGE, withData: datas)
}
}
@objc private func sendPing() {
//Server is not responding
if pongsMissed > pongsMissedMax {
pingTimer?.invalidate()
client?.engineDidClose("Ping timeout")
return
}
++pongsMissed
write("", withType: PacketType.PING, withData: nil)
}
/// Send polling message.
/// Only call on emitQueue
private func sendPollMessage(var msg:String, withType type:PacketType,
datas:ContiguousArray<NSData>? = nil) {
SocketLogger.log("Sending poll: %@ as type: %@", client: self, args: msg, type.rawValue)
doubleEncodeUTF8(&msg)
let strMsg = "\(type.rawValue)\(msg)"
postWait.append(strMsg)
if datas != nil {
for data in datas! {
let (nilData, b64Data) = createBinaryDataForSend(data)
postWait.append(b64Data!)
}
}
if !waitingForPost {
flushWaitingForPost()
}
}
/// Send message on WebSockets
/// Only call on emitQueue
private func sendWebSocketMessage(str:String, withType type:PacketType,
datas:ContiguousArray<NSData>? = nil) {
SocketLogger.log("Sending ws: %@ as type: %@", client: self, args: str, type.rawValue)
ws?.writeString("\(type.rawValue)\(str)")
if datas != nil {
for data in datas! {
let (data, nilString) = createBinaryDataForSend(data)
if data != nil {
ws?.writeData(data!)
}
}
}
}
// Starts the ping timer
private func startPingTimer() {
if pingInterval == nil {
return
}
pingTimer?.invalidate()
dispatch_async(dispatch_get_main_queue()) {[weak self] in
if let this = self {
this.pingTimer = NSTimer.scheduledTimerWithTimeInterval(this.pingInterval!, target: this,
selector: Selector("sendPing"), userInfo: nil, repeats: true)
}
}
}
func stopPolling() {
session.invalidateAndCancel()
}
private func upgradeTransport() {
if websocketConnected {
SocketLogger.log("Upgrading transport to WebSockets", client: self)
fastUpgrade = true
sendPollMessage("", withType: PacketType.NOOP)
// After this point, we should not send anymore polling messages
}
}
/**
Write a message, independent of transport.
*/
public func write(msg:String, withType type:PacketType, withData data:ContiguousArray<NSData>?) {
dispatch_async(emitQueue) {[weak self] in
if let this = self where this.connected {
if this.websocket {
SocketLogger.log("Writing ws: %@ has data: %@", client: this,
args: msg, data == nil ? false : true)
this.sendWebSocketMessage(msg, withType: type, datas: data)
} else {
SocketLogger.log("Writing poll: %@ has data: %@", client: this,
args: msg, data == nil ? false : true)
this.sendPollMessage(msg, withType: type, datas: data)
}
}
}
}
/**
Write a message, independent of transport. For Objective-C. withData should be an NSArray of NSData
*/
public func writeObjc(msg:String, withType type:Int, withData data:NSArray?) {
if let pType = PacketType(rawValue: type) {
var arr = ContiguousArray<NSData>()
if data != nil {
for d in data! {
arr.append(d as! NSData)
}
}
write(msg, withType: pType, withData: arr)
}
}
// Delagate methods
public func websocketDidConnect(socket:WebSocket) {
websocketConnected = true
if !forceWebsockets {
probing = true
probeWebSocket()
} else {
_connected = true
probing = false
_polling = false
}
}
public func websocketDidDisconnect(socket:WebSocket, error:NSError?) {
websocketConnected = false
probing = false
if closed {
client?.engineDidClose("Disconnect")
return
}
if websocket {
pingTimer?.invalidate()
_connected = false
_websocket = false
let reason = error?.localizedDescription ?? "Socket Disconnected"
if error != nil {
client?.didError(reason)
}
client?.engineDidClose(reason)
} else {
flushProbeWait()
}
}
public func websocketDidReceiveMessage(socket:WebSocket, text:String) {
parseEngineMessage(text, fromPolling: false)
}
public func websocketDidReceiveData(socket:WebSocket, data:NSData) {
parseEngineData(data)
}
}
|
apache-2.0
|
667628e943afcce3ec8eab641972460c
| 31.878173 | 117 | 0.52752 | 5.431447 | false | false | false | false |
scinfu/SwiftSoup
|
Sources/CharacterReader.swift
|
1
|
10087
|
//
// CharacterReader.swift
// SwiftSoup
//
// Created by Nabil Chatbi on 10/10/16.
// Copyright © 2016 Nabil Chatbi.. All rights reserved.
//
import Foundation
/**
CharacterReader consumes tokens off a string. To replace the old TokenQueue.
*/
public final class CharacterReader {
private static let empty = ""
public static let EOF: UnicodeScalar = "\u{FFFF}"//65535
private let input: String.UnicodeScalarView
private var pos: String.UnicodeScalarView.Index
private var mark: String.UnicodeScalarView.Index
//private let stringCache: Array<String?> // holds reused strings in this doc, to lessen garbage
public init(_ input: String) {
self.input = input.unicodeScalars
self.pos = input.startIndex
self.mark = input.startIndex
}
public func getPos() -> Int {
return input.distance(from: input.startIndex, to: pos)
}
public func isEmpty() -> Bool {
return pos >= input.endIndex
}
public func current() -> UnicodeScalar {
return (pos >= input.endIndex) ? CharacterReader.EOF : input[pos]
}
@discardableResult
public func consume() -> UnicodeScalar {
guard pos < input.endIndex else {
return CharacterReader.EOF
}
let val = input[pos]
pos = input.index(after: pos)
return val
}
public func unconsume() {
guard pos > input.startIndex else { return }
pos = input.index(before: pos)
}
public func advance() {
guard pos < input.endIndex else { return }
pos = input.index(after: pos)
}
public func markPos() {
mark = pos
}
public func rewindToMark() {
pos = mark
}
public func consumeAsString() -> String {
guard pos < input.endIndex else { return "" }
let str = String(input[pos])
pos = input.index(after: pos)
return str
}
/**
* Locate the next occurrence of a Unicode scalar
*
* - Parameter c: scan target
* - Returns: offset between current position and next instance of target. -1 if not found.
*/
public func nextIndexOf(_ c: UnicodeScalar) -> String.UnicodeScalarView.Index? {
// doesn't handle scanning for surrogates
return input[pos...].firstIndex(of: c)
}
/**
* Locate the next occurence of a target string
*
* - Parameter seq: scan target
* - Returns: index of next instance of target. nil if not found.
*/
public func nextIndexOf(_ seq: String) -> String.UnicodeScalarView.Index? {
// doesn't handle scanning for surrogates
var start = pos
let targetScalars = seq.unicodeScalars
guard let firstChar = targetScalars.first else { return pos } // search for "" -> current place
MATCH: while true {
// Match on first scalar
guard let firstCharIx = input[start...].firstIndex(of: firstChar) else { return nil }
var current = firstCharIx
// Then manually match subsequent scalars
for scalar in targetScalars.dropFirst() {
current = input.index(after: current)
guard current < input.endIndex else { return nil }
if input[current] != scalar {
start = input.index(after: firstCharIx)
continue MATCH
}
}
// full match; current is at position of last matching character
return firstCharIx
}
}
public func consumeTo(_ c: UnicodeScalar) -> String {
guard let targetIx = nextIndexOf(c) else {
return consumeToEnd()
}
let consumed = cacheString(pos, targetIx)
pos = targetIx
return consumed
}
public func consumeTo(_ seq: String) -> String {
guard let targetIx = nextIndexOf(seq) else {
return consumeToEnd()
}
let consumed = cacheString(pos, targetIx)
pos = targetIx
return consumed
}
public func consumeToAny(_ chars: UnicodeScalar...) -> String {
return consumeToAny(chars)
}
public func consumeToAny(_ chars: [UnicodeScalar]) -> String {
let start = pos
while pos < input.endIndex {
if chars.contains(input[pos]) {
break
}
pos = input.index(after: pos)
}
return cacheString(start, pos)
}
public func consumeToAnySorted(_ chars: UnicodeScalar...) -> String {
return consumeToAny(chars)
}
public func consumeToAnySorted(_ chars: [UnicodeScalar]) -> String {
return consumeToAny(chars)
}
static let dataTerminators: [UnicodeScalar] = [.Ampersand, .LessThan, TokeniserStateVars.nullScalr]
// read to &, <, or null
public func consumeData() -> String {
return consumeToAny(CharacterReader.dataTerminators)
}
static let tagNameTerminators: [UnicodeScalar] = [.BackslashT, .BackslashN, .BackslashR, .BackslashF, .Space, .Slash, .GreaterThan, TokeniserStateVars.nullScalr]
// read to '\t', '\n', '\r', '\f', ' ', '/', '>', or nullChar
public func consumeTagName() -> String {
return consumeToAny(CharacterReader.tagNameTerminators)
}
public func consumeToEnd() -> String {
let consumed = cacheString(pos, input.endIndex)
pos = input.endIndex
return consumed
}
public func consumeLetterSequence() -> String {
let start = pos
while pos < input.endIndex {
let c = input[pos]
if ((c >= "A" && c <= "Z") || (c >= "a" && c <= "z") || c.isMemberOfCharacterSet(CharacterSet.letters)) {
pos = input.index(after: pos)
} else {
break
}
}
return cacheString(start, pos)
}
public func consumeLetterThenDigitSequence() -> String {
let start = pos
while pos < input.endIndex {
let c = input[pos]
if ((c >= "A" && c <= "Z") || (c >= "a" && c <= "z") || c.isMemberOfCharacterSet(CharacterSet.letters)) {
pos = input.index(after: pos)
} else {
break
}
}
while pos < input.endIndex {
let c = input[pos]
if (c >= "0" && c <= "9") {
pos = input.index(after: pos)
} else {
break
}
}
return cacheString(start, pos)
}
public func consumeHexSequence() -> String {
let start = pos
while pos < input.endIndex {
let c = input[pos]
if ((c >= "0" && c <= "9") || (c >= "A" && c <= "F") || (c >= "a" && c <= "f")) {
pos = input.index(after: pos)
} else {
break
}
}
return cacheString(start, pos)
}
public func consumeDigitSequence() -> String {
let start = pos
while pos < input.endIndex {
let c = input[pos]
if (c >= "0" && c <= "9") {
pos = input.index(after: pos)
} else {
break
}
}
return cacheString(start, pos)
}
public func matches(_ c: UnicodeScalar) -> Bool {
return !isEmpty() && input[pos] == c
}
public func matches(_ seq: String, ignoreCase: Bool = false, consume: Bool = false) -> Bool {
var current = pos
let scalars = seq.unicodeScalars
for scalar in scalars {
guard current < input.endIndex else { return false }
if ignoreCase {
guard input[current].uppercase == scalar.uppercase else { return false }
} else {
guard input[current] == scalar else { return false }
}
current = input.index(after: current)
}
if consume {
pos = current
}
return true
}
public func matchesIgnoreCase(_ seq: String ) -> Bool {
return matches(seq, ignoreCase: true)
}
public func matchesAny(_ seq: UnicodeScalar...) -> Bool {
return matchesAny(seq)
}
public func matchesAny(_ seq: [UnicodeScalar]) -> Bool {
guard pos < input.endIndex else { return false }
return seq.contains(input[pos])
}
public func matchesAnySorted(_ seq: [UnicodeScalar]) -> Bool {
return matchesAny(seq)
}
public func matchesLetter() -> Bool {
guard pos < input.endIndex else { return false }
let c = input[pos]
return (c >= "A" && c <= "Z") || (c >= "a" && c <= "z") || c.isMemberOfCharacterSet(CharacterSet.letters)
}
public func matchesDigit() -> Bool {
guard pos < input.endIndex else { return false }
let c = input[pos]
return c >= "0" && c <= "9"
}
@discardableResult
public func matchConsume(_ seq: String) -> Bool {
return matches(seq, consume: true)
}
@discardableResult
public func matchConsumeIgnoreCase(_ seq: String) -> Bool {
return matches(seq, ignoreCase: true, consume: true)
}
public func containsIgnoreCase(_ seq: String ) -> Bool {
// used to check presence of </title>, </style>. only finds consistent case.
let loScan = seq.lowercased(with: Locale(identifier: "en"))
let hiScan = seq.uppercased(with: Locale(identifier: "eng"))
return nextIndexOf(loScan) != nil || nextIndexOf(hiScan) != nil
}
public func toString() -> String {
return String(input[pos...])
}
/**
* Originally intended as a caching mechanism for strings, but caching doesn't
* seem to improve performance. Now just a stub.
*/
private func cacheString(_ start: String.UnicodeScalarView.Index, _ end: String.UnicodeScalarView.Index) -> String {
return String(input[start..<end])
}
}
extension CharacterReader: CustomDebugStringConvertible {
public var debugDescription: String {
return toString()
}
}
|
mit
|
ac4caa9564a4f57877b87a6dde3c31d2
| 30.51875 | 165 | 0.564942 | 4.456916 | false | false | false | false |
JKapanke/worldvisitor
|
WorldVisitor/DiceRollViewController.swift
|
1
|
2786
|
//
// DiceRollViewController.swift
// WorldTraveler
//
// Created by Jason Kapanke on 12/2/14.
// Copyright (c) 2014 Better Things. All rights reserved.
//
import UIKit
class DiceRollViewController: UIViewController
{
@IBOutlet weak var rollButton: UIButton!
@IBOutlet weak var secondDieImage: UIImageView!
@IBOutlet weak var firstDieImage: UIImageView!
@IBOutlet weak var gotoCountryButton: UIButton!
var countryRolled = Country()
override func viewDidLoad()
{
super.viewDidLoad()
}
//send them to the next view with the selected country by passing the country name as part of the seque
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?)
{
//the segue must be named as noted in the operator
if (segue.identifier == "toCountrySegue")
{
var cvc = segue.destinationViewController as CountryViewController;
cvc.typeOfCountry = countryRolled
}
}
override func didReceiveMemoryWarning()
{
super.didReceiveMemoryWarning()
}
@IBAction func rollButtonAction(sender: UIButton)
{
let firstDie = Dice()
let secondDie = Dice()
//initiate rolling die sound
firstDie.playRollingDiceSound()
//sleep for 2 seconds to allow the shaking and rolling of die to complete
sleep(2)
var firstDieValue = firstDie.rollDice()
var secondDieValue = secondDie.rollDice()
var dieTotal = firstDieValue + secondDieValue
firstDieImage.image = UIImage(named: "dice\(firstDieValue).png")
secondDieImage.image = UIImage(named: "dice\(secondDieValue).png")
println("you rolled a \(dieTotal)!")
//Call the function which returns a country to the value
countryRolled = determineCountryBasedOnRoll(dieTotal)
println("Country to visit: \(countryRolled.getCountryName())")
gotoCountryButton.setTitle("Swipe Right to go to \(countryRolled.getCountryName())", forState: .Normal)
}
func determineCountryBasedOnRoll(dieValue: Int) -> Country {
var determinedCountry = Country()
switch dieValue
{
case 0...4:
determinedCountry = Canada()
case 5...6:
determinedCountry = Brazil()
case 7...8:
determinedCountry = India()
case 9...10:
determinedCountry = Australia()
case 11...12:
determinedCountry = China()
default:
determinedCountry = Country()
}
return determinedCountry
}
}
|
gpl-2.0
|
741f967c67406d4bde0a4889713d12a3
| 28.956989 | 111 | 0.603374 | 4.966132 | false | false | false | false |
937447974/YJCocoa
|
YJCocoa/Classes/AppFrameworks/UIKit/CollectionView/YJWaterfallFlowLayout.swift
|
1
|
6230
|
//
// YJWaterfallFlowLayout.swift
// YJCocoa
//
// HomePage:https://github.com/937447974/YJCocoa
// YJ技术支持群:557445088
//
// Created by 阳君 on 2020/5/24.
// Copyright © 2016-现在 YJCocoa. All rights reserved.
//
import UIKit
/// CollectionView 瀑布流
open class YJWaterfallFlowLayout: UICollectionViewFlowLayout {
// 总列数
public var columnCount: Int = 0
private var maxHeight: CGFloat = 0
private var layoutAttributes = [UICollectionViewLayoutAttributes]()
open override var collectionViewContentSize: CGSize {
get { return CGSize(width: self.collectionView!.bounds.width, height: self.maxHeight) }
}
open override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
return self.layoutAttributes
}
open override func prepare() {
super.prepare()
self.maxHeight = 0
self.layoutAttributes.removeAll()
guard let collectionView = self.collectionView,
let delegate = collectionView.delegate as? UICollectionViewDelegateFlowLayout,
let dataSource = collectionView.dataSource else {
return
}
let sectionCount = dataSource.numberOfSections!(in: collectionView)
var laList = [UICollectionViewLayoutAttributes]()
for section in 0..<sectionCount {
// header
if let headerLA = self.prepareSupplementaryView(ofKind: UICollectionView.elementKindSectionHeader, section: section, y: self.maxHeight) {
laList.append(headerLA)
self.maxHeight = headerLA.frame.maxY
}
// cell
self.maxHeight = self.maxHeight + self.sectionInset.top
let cellLAList = self.prepareCell(delegate: delegate, dataSource: dataSource, section: section, y: self.maxHeight)
self.layoutAttributes.append(contentsOf: cellLAList)
cellLAList.forEach { (la) in
self.maxHeight = max(self.maxHeight, la.frame.maxY)
}
self.maxHeight = self.maxHeight + self.sectionInset.bottom
// bottom
if let bottomLA = self.prepareSupplementaryView(ofKind: UICollectionView.elementKindSectionFooter, section: section, y: self.maxHeight) {
laList.append(bottomLA)
self.maxHeight = bottomLA.frame.maxY
}
}
self.layoutAttributes.append(contentsOf: laList)
}
func prepareSupplementaryView(ofKind elementKind: String, section: Int, y: CGFloat) -> UICollectionViewLayoutAttributes? {
let indexPath = IndexPath(item: 0, section: section)
guard let layoutAttributes = self.layoutAttributesForSupplementaryView(ofKind: elementKind, at: indexPath), layoutAttributes.size != CGSize() else {
return nil
}
layoutAttributes.frame.origin.y = y
return layoutAttributes
}
func prepareCell(delegate: UICollectionViewDelegateFlowLayout ,dataSource: UICollectionViewDataSource, section: Int, y: CGFloat) -> [UICollectionViewLayoutAttributes] {
var result = [UICollectionViewLayoutAttributes]()
let columnXList = self.prepareColumnXList()
var columnYList = [CGFloat](repeating: y - self.minimumLineSpacing, count: self.columnCount)
var columnIndex = 0
var highLowIndex = (0, 0)
let itemCount = dataSource.collectionView(self.collectionView!, numberOfItemsInSection: section)
for item in 0..<itemCount {
let indexPath = IndexPath(item: item, section: section)
let layoutAttributes = UICollectionViewLayoutAttributes(forCellWith: indexPath)
result.append(layoutAttributes)
// size
let itemSize = self.sizeForItem(delegate: delegate, indexPath: indexPath)
layoutAttributes.size = itemSize
// origin
let highIndex = highLowIndex.0, lowIndex = highLowIndex.1
if itemSize.height <= columnYList[highIndex] - columnYList[lowIndex] {// 跳跃插入
layoutAttributes.frame.origin = CGPoint(x: columnXList[lowIndex], y: columnYList[lowIndex] + self.minimumLineSpacing)
columnYList[lowIndex] = layoutAttributes.frame.maxY
highLowIndex = self.prepareHighLowIndex(columnYList: columnYList)
} else {
layoutAttributes.frame.origin = CGPoint(x: columnXList[columnIndex], y: columnYList[columnIndex] + self.minimumLineSpacing)
columnYList[columnIndex] = layoutAttributes.frame.maxY
columnIndex = columnIndex + 1
if columnIndex == self.columnCount { // 换行
highLowIndex = self.prepareHighLowIndex(columnYList: columnYList)
columnIndex = 0
}
}
}
return result
}
func prepareColumnXList() -> [CGFloat] {
let contentWidth = self.collectionView!.boundsWidth - self.sectionInset.left - self.sectionInset.right
let itemWidth = (contentWidth - self.minimumInteritemSpacing * CGFloat(self.columnCount - 1)) / CGFloat(self.columnCount)
var columnXArray = [CGFloat]()
var x = self.sectionInset.left
for _ in 0..<self.columnCount {
columnXArray.append(x)
x = x + itemWidth + self.minimumInteritemSpacing
}
return columnXArray
}
func prepareHighLowIndex(columnYList: [CGFloat]) -> (Int, Int) {
var result = (0, 0)
var height = columnYList[0], low = columnYList[0]
for i in 1..<columnYList.count {
if columnYList[i] > height {
result.0 = i
height = columnYList[i]
} else if columnYList[i] < low {
result.1 = i
low = columnYList[i]
}
}
return result
}
func sizeForItem(delegate: UICollectionViewDelegateFlowLayout, indexPath: IndexPath) -> CGSize {
if let itemSize = delegate.collectionView?(self.collectionView!, layout: self, sizeForItemAt: indexPath) {
return itemSize
}
return self.itemSize
}
}
|
mit
|
8d787b2ba0e5cd6901da405710fba38a
| 43.192857 | 172 | 0.639082 | 4.96549 | false | false | false | false |
ustwo/videoplayback-ios
|
VideoPlaybackKit/Manager/Utils/Requests.swift
|
1
|
1978
|
//
// Requests.swift
// DemoVideoPlaybackKit
//
// Created by Sonam on 7/6/17.
// Copyright © 2017 ustwo. All rights reserved.
//
import Foundation
import AVFoundation
protocol Request: class {
var resourceUrl: URL {get}
var loadingRequest: AVAssetResourceLoadingRequest {get}
func cancel()
}
class ContentInfoRequest: Request {
let resourceUrl: URL
let loadingRequest: AVAssetResourceLoadingRequest
let infoRequest: AVAssetResourceLoadingContentInformationRequest
let task: URLSessionTask
init(resourceUrl: URL, loadingRequest: AVAssetResourceLoadingRequest, infoRequest: AVAssetResourceLoadingContentInformationRequest, task: URLSessionTask) {
self.resourceUrl = resourceUrl
self.loadingRequest = loadingRequest
self.infoRequest = infoRequest
self.task = task
}
func cancel() {
task.cancel()
if !loadingRequest.isCancelled && !loadingRequest.isFinished {
loadingRequest.finishLoading()
}
}
}
class DataRequest: Request {
let resourceUrl: URL
let loadingRequest: AVAssetResourceLoadingRequest
let dataRequest: AVAssetResourceLoadingDataRequest
let loader: VPKVideoRequestDownloader
init(resourceUrl: URL, loadingRequest: AVAssetResourceLoadingRequest, dataRequest: AVAssetResourceLoadingDataRequest, loader: VPKVideoRequestDownloader) {
self.resourceUrl = resourceUrl
self.loadingRequest = loadingRequest
self.dataRequest = dataRequest
self.loader = loader
}
func cancel() {
loader.cancel()
if !loadingRequest.isCancelled && !loadingRequest.isFinished {
loadingRequest.finishLoading()
}
}
}
extension AVAssetResourceLoadingDataRequest {
var byteRange: ByteRange {
let lowerBound = requestedOffset
let upperBound = (lowerBound + requestedLength - 1)
return (lowerBound..<upperBound)
}
}
|
mit
|
525d207de87bc978da991c9a556f5bcf
| 26.84507 | 159 | 0.701062 | 5.431319 | false | false | false | false |
x331275955/-
|
学习微博/学习微博/Classes/Model/UserAccount.swift
|
1
|
2742
|
//
// UserAccount.swift
// 我的微博
//
// Created by 刘凡 on 15/7/29.
// Copyright © 2015年 itheima. All rights reserved.
//
import UIKit
/// 用户账户类
class UserAccount: NSObject, NSCoding {
/// 全局账户信息
private static var sharedAccount: UserAccount?
class func sharedUserAccount() -> UserAccount? {
if sharedAccount == nil {
sharedAccount = UserAccount.loadAccount()
}
if let date = sharedAccount?.expiresDate where date.compare(NSDate()) == NSComparisonResult.OrderedAscending {
sharedAccount = nil
}
return sharedAccount
}
/// 用于调用access_token,接口获取授权后的access token
var access_token: String?
/// access_token的生命周期,单位是秒数
var expires_in: NSTimeInterval = 0
/// 过期日期
var expiresDate: NSDate?
/// 当前授权用户的UID
var uid: String?
private init(dict: [String: AnyObject]) {
super.init()
self.setValuesForKeysWithDictionary(dict)
expiresDate = NSDate(timeIntervalSinceNow: expires_in)
}
override func setValue(value: AnyObject?, forUndefinedKey key: String) {}
override var description: String {
let dict = ["access_token", "expires_in", "uid", "expiresDate"]
return "\(dictionaryWithValuesForKeys(dict))"
}
// MARK: - 归档 & 解档
/// 归档保存路径
private static let accountPath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last!.stringByAppendingPathComponent("useraccount.plist")
/// 保存账户信息
class func saveAccount(dict: [String: AnyObject]) {
sharedAccount = UserAccount(dict: dict)
NSKeyedArchiver.archiveRootObject(sharedAccount!, toFile: accountPath)
}
/// 加载账户信息
private class func loadAccount() -> UserAccount? {
return NSKeyedUnarchiver.unarchiveObjectWithFile(accountPath) as? UserAccount
}
// MARK: - NSCoding
func encodeWithCoder(aCoder: NSCoder) {
aCoder.encodeObject(access_token, forKey: "access_token")
aCoder.encodeDouble(expires_in, forKey: "expires_in")
aCoder.encodeObject(expiresDate, forKey: "expiresDate")
aCoder.encodeObject(uid, forKey: "uid")
}
required init?(coder aDecoder: NSCoder) {
access_token = aDecoder.decodeObjectForKey("access_token") as? String
expires_in = aDecoder.decodeDoubleForKey("expires_in")
expiresDate = aDecoder.decodeObjectForKey("expiresDate") as? NSDate
uid = aDecoder.decodeObjectForKey("uid") as? String
}
}
|
mit
|
2196f4c9d23e36a2991953861118cbf5
| 31.3875 | 216 | 0.660749 | 4.771639 | false | false | false | false |
Weswit/Lightstreamer-example-StockList-client-ios
|
iPhone/AppDelegate_iPhone.swift
|
2
|
1919
|
// Converted to Swift 5.4 by Swiftify v5.4.24488 - https://swiftify.com/
//
// AppDelegate_iPhone.swift
// StockList Demo for iOS
//
// Copyright (c) Lightstreamer Srl
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import UIKit
import LightstreamerClient
//@UIApplicationMain
class AppDelegate_iPhone: NSObject, UIApplicationDelegate, StockListAppDelegate {
var navController: UINavigationController?
// MARK: -
// MARK: Properties
@IBOutlet var window: UIWindow?
private(set) var stockListController: StockListViewController?
// MARK: -
// MARK: Application lifecycle
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {
application.statusBarStyle = .lightContent
// Uncomment for detailed logging
// LightstreamerClient.setLoggerProvider(ConsoleLoggerProvider(level: .debug))
// Create the user interface
stockListController = StockListViewController()
if let stockListController = stockListController {
navController = UINavigationController(rootViewController: stockListController)
}
navController?.navigationBar.barStyle = .black
window?.rootViewController = navController
window?.makeKeyAndVisible()
return true
}
// MARK: -
// MARK: Properties
}
|
apache-2.0
|
3261b2a17dd947a2876f29f5c788ae15
| 30.983333 | 152 | 0.719125 | 4.933162 | false | false | false | false |
wordpress-mobile/WordPress-iOS
|
WordPress/Classes/Services/JetpackRestoreService.swift
|
2
|
1302
|
import Foundation
@objc class JetpackRestoreService: LocalCoreDataService {
private lazy var serviceV1: ActivityServiceRemote_ApiVersion1_0 = {
let api = WordPressComRestApi.defaultApi(in: managedObjectContext)
return ActivityServiceRemote_ApiVersion1_0(wordPressComRestApi: api)
}()
private lazy var service: ActivityServiceRemote = {
let api = WordPressComRestApi.defaultApi(in: managedObjectContext,
localeKey: WordPressComRestApi.LocaleKeyV2)
return ActivityServiceRemote(wordPressComRestApi: api)
}()
func restoreSite(_ site: JetpackSiteRef,
rewindID: String?,
restoreTypes: JetpackRestoreTypes? = nil,
success: @escaping (String, Int) -> Void,
failure: @escaping (Error) -> Void) {
guard let rewindID = rewindID else {
return
}
serviceV1.restoreSite(site.siteID, rewindID: rewindID, types: restoreTypes, success: success, failure: failure)
}
func getRewindStatus(for site: JetpackSiteRef, success: @escaping (RewindStatus) -> Void, failure: @escaping (Error) -> Void) {
service.getRewindStatus(site.siteID, success: success, failure: failure)
}
}
|
gpl-2.0
|
480b689ae6cfd5385fc692c4ef1677b2
| 38.454545 | 131 | 0.645161 | 4.988506 | false | false | false | false |
haranicle/RealmRelationsSample
|
Carthage/Checkouts/realm-cocoa/Realm/Tests/Swift/SwiftTestCase.swift
|
2
|
2821
|
////////////////////////////////////////////////////////////////////////////
//
// Copyright 2014 Realm Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////
import XCTest
import Realm
func testRealmPath() -> String {
return realmPathForFile("test.realm")
}
func defaultRealmPath() -> String {
return realmPathForFile("default.realm")
}
func realmPathForFile(fileName: String) -> String {
#if os(iOS)
let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)
return (paths[0] as String) + "/" + fileName
#else
return fileName
#endif
}
func realmLockPath(path: String) -> String {
return path + ".lock"
}
func deleteRealmFilesAtPath(path: String) {
let fileManager = NSFileManager.defaultManager()
if fileManager.fileExistsAtPath(path) {
let succeeded = NSFileManager.defaultManager().removeItemAtPath(path, error: nil)
assert(succeeded, "Unable to delete realm")
}
let lockPath = realmLockPath(path)
if fileManager.fileExistsAtPath(lockPath) {
let succeeded = NSFileManager.defaultManager().removeItemAtPath(lockPath, error: nil)
assert(succeeded, "Unable to delete realm")
}
}
func realmWithTestPathAndSchema(schema: RLMSchema?) -> RLMRealm {
return RLMRealm(path: testRealmPath(), key: nil, readOnly: false, inMemory: false, dynamic: false, schema: schema, error: nil)
}
func dynamicRealmWithTestPathAndSchema(schema: RLMSchema?) -> RLMRealm {
return RLMRealm(path: testRealmPath(), key: nil, readOnly: false, inMemory: false, dynamic: true, schema: schema, error: nil)
}
class SwiftTestCase: XCTestCase {
func realmWithTestPath() -> RLMRealm {
return RLMRealm(path: testRealmPath(), readOnly: false, error: nil)
}
override func setUp() {
super.setUp()
// Delete realm files
deleteRealmFilesAtPath(defaultRealmPath())
deleteRealmFilesAtPath(testRealmPath())
}
override func tearDown() {
super.tearDown()
// Reset Realm cache
RLMRealm.resetRealmState()
// Delete realm files
deleteRealmFilesAtPath(defaultRealmPath())
deleteRealmFilesAtPath(testRealmPath())
}
}
|
mit
|
116d054209602f95c0b720e5285cfe1c
| 30.696629 | 130 | 0.661113 | 4.639803 | false | true | false | false |
shaymanjohn/speccyMac
|
speccyMac/z80/Z80+ed.swift
|
1
|
7629
|
//
// Z80+ed.swift
// speccyMac
//
// Created by John Ward on 21/07/2017.
// Copyright © 2017 John Ward. All rights reserved.
//
import Foundation
extension ZilogZ80 {
// swiftlint:disable cyclomatic_complexity
final func edprefix(opcode: UInt8, first: UInt8, second: UInt8) throws {
let word16 = (UInt16(second) << 8) | UInt16(first)
let instruction = instructionSet.edprefix[opcode]
// log(instruction)
switch opcode {
case 0x00: // nop
break
case 0x42: // sbc hl, bc
hl.sbc(bc)
case 0x43: // ld (nnnn), bc
memory.set(word16, regPair: bc)
case 0x44: // neg
a.neg()
case 0x47: // ld i, a
i = a.value
case 0x4a: // adc hl, bc
hl.adc(bc.value)
case 0x4b: // ld bc, (nnnn)
c.value = memory.get(word16)
b.value = memory.get(word16 &+ 1)
case 0x4d: // reti
pc = memory.pop()
pc = pc &- 2
case 0x4f: // ld r, a
r.value = a.value
case 0x50: // in d, (c)
d.value = machine?.input(b.value, low: c.value) ?? 0
ZilogZ80.f.value = (ZilogZ80.f.value & ZilogZ80.cBit) | ZilogZ80.sz53pvTable[d.value]
case 0x52: // sbc hl, de
hl.sbc(de)
case 0x53: // ld (nnnn), de
memory.set(word16, regPair: de)
case 0x56: // im 1
interruptMode = 1
case 0x57: // ld a, i
a.value = i
case 0x58: // in e, (c)
e.value = machine?.input(b.value, low: c.value) ?? 0
ZilogZ80.f.value = (ZilogZ80.f.value & ZilogZ80.cBit) | ZilogZ80.sz53pvTable[e.value]
case 0x5a: // adc hl, de
hl.adc(de.value)
case 0x5b: // le de, (nnnn)
e.value = memory.get(word16)
d.value = memory.get(word16 &+ 1)
case 0x5e: // im 2
interruptMode = 2
case 0x5f: // ld a, r
let rval = r.value
r.inc()
r.inc()
a.value = r.value
r.value = rval
ZilogZ80.f.value = (ZilogZ80.f.value & ZilogZ80.cBit) | ZilogZ80.sz53Table[a.value] | (iff2 > 0 ? ZilogZ80.pvBit : 0)
case 0x62: // sbc hl, hl
hl.sbc(hl.value)
case 0x67: // rrd
let byte = memory.get(hl)
memory.set(hl.value, byte: (a.value << 4) | (byte >> 4))
a.value = (a.value & 0xf0) | (byte & 0x0f)
ZilogZ80.f.value = (ZilogZ80.f.value & ZilogZ80.cBit) | ZilogZ80.sz53pvTable[a.value]
case 0x6a: // adc hl, hl
hl.adc(hl.value)
case 0x6f: // rld
let byte = memory.get(hl)
memory.set(hl.value, byte: (byte << 4) | (a.value & 0x0f))
a.value = (a.value & 0xf0) | (byte >> 4)
ZilogZ80.f.value = (ZilogZ80.f.value & ZilogZ80.cBit) | ZilogZ80.sz53pvTable[a.value]
case 0x72: // sbc hl, sp
hl.sbc(ZilogZ80.sp)
case 0x73: // ld (nn), sp
memory.set(word16, byte: UInt8(ZilogZ80.sp & 0xff))
memory.set(word16 &+ 1, byte: UInt8(ZilogZ80.sp >> 8))
case 0x78: // in a, (c)
a.value = machine?.input(b.value, low: c.value) ?? 0
ZilogZ80.f.value = (ZilogZ80.f.value & ZilogZ80.cBit) | ZilogZ80.sz53pvTable[a.value]
case 0x79: // out (c), a
machine?.output(c.value, byte: a.value)
case 0x7a: // adc hl, sp
hl.adc(ZilogZ80.sp)
case 0x7b: // ld sp, (nn)
let lo = memory.get(word16)
let hi = memory.get(word16 &+ 1)
ZilogZ80.sp = (UInt16(hi) << 8) | UInt16(lo)
case 0xa0: // ldi
var temp = memory.get(hl)
bc.value = bc.value &- 1
memory.set(de.value, byte: temp)
de.value = de.value &+ 1
hl.value = hl.value &+ 1
temp = temp &+ a.value
ZilogZ80.f.value = (ZilogZ80.f.value & (ZilogZ80.cBit | ZilogZ80.zBit | ZilogZ80.sBit)) | (bc.value > 0 ? ZilogZ80.pvBit : 0) | (temp & ZilogZ80.threeBit) | ((temp & 0x02) > 0 ? ZilogZ80.fiveBit : 0)
case 0xa8: // ldd
var temp = memory.get(hl)
bc.value = bc.value &- 1
memory.set(de.value, byte: temp)
de.value = de.value &- 1
hl.value = hl.value &- 1
temp = temp &+ a.value
ZilogZ80.f.value = (ZilogZ80.f.value & (ZilogZ80.cBit | ZilogZ80.zBit | ZilogZ80.sBit)) | (bc.value > 0 ? ZilogZ80.pvBit : 0) | (temp & ZilogZ80.threeBit) | ((temp & 0x02) > 0 ? ZilogZ80.fiveBit : 0)
case 0xb0: // ldir
var val = memory.get(hl)
memory.set(de.value, byte: val)
bc.value = bc.value &- 1
val = val &+ a.value
ZilogZ80.f.value = (ZilogZ80.f.value & (ZilogZ80.cBit | ZilogZ80.zBit | ZilogZ80.sBit)) | (bc.value > 0 ? ZilogZ80.pvBit : 0) | (val & ZilogZ80.threeBit) | ((val & 0x02) > 0 ? ZilogZ80.fiveBit : 0)
if bc.value > 0 {
pc = pc &- 2
incCounters(5)
}
de.value = de.value &+ 1
hl.value = hl.value &+ 1
case 0xb1: // cpir
let val = memory.get(hl)
var temp = a.value &- val
let lookup = ((a.value & 0x08) >> 3) | ((val & 0x08) >> 2) | ((temp & 0x08) >> 1)
bc.value = bc.value &- 1
ZilogZ80.f.value = (ZilogZ80.f.value & ZilogZ80.cBit) | (bc.value > 0 ? (ZilogZ80.pvBit | ZilogZ80.nBit) : ZilogZ80.nBit) | ZilogZ80.halfCarrySub[lookup] | (temp > 0 ? 0 : ZilogZ80.zBit) | (temp & ZilogZ80.sBit)
if ZilogZ80.f.value & ZilogZ80.hBit > 0 {
temp = temp &- 1
}
ZilogZ80.f.value |= (temp & ZilogZ80.threeBit) | ((temp & 0x02) > 0 ? ZilogZ80.fiveBit : 0)
if (ZilogZ80.f.value & (ZilogZ80.pvBit | ZilogZ80.zBit)) == ZilogZ80.pvBit {
pc = pc &- 2
incCounters(5)
}
hl.value = hl.value &+ 1
case 0xb8: // lddr
var val = memory.get(hl)
memory.set(de.value, byte: val)
bc.value = bc.value &- 1
val = val &+ a.value
ZilogZ80.f.value = (ZilogZ80.f.value & (ZilogZ80.cBit | ZilogZ80.zBit | ZilogZ80.sBit)) | (bc.value > 0 ? ZilogZ80.pvBit : 0) | (val & ZilogZ80.threeBit) | ((val & 0x02) > 0 ? ZilogZ80.fiveBit : 0)
if bc.value > 0 {
pc = pc &- 2
incCounters(5)
}
hl.value = hl.value &- 1
de.value = de.value &- 1
default:
throw NSError(domain: "z80+ed", code: 1, userInfo: ["opcode" : String(opcode, radix: 16, uppercase: true), "instruction" : instruction.opcode, "pc" : pc])
}
pc = pc &+ instruction.length
incCounters(instruction.tstates)
r.inc()
r.inc()
}
}
|
gpl-3.0
|
47dbb6b50f7ad759b881cabc7f666541
| 35.497608 | 223 | 0.456738 | 3.121113 | false | false | false | false |
LKY769215561/KYHandMade
|
KYHandMade/KYHandMade/Class/Home(首页)/View/PageViewCell/KYSlideCollectionViewCell.swift
|
1
|
1297
|
//
// KYSlideCollectionViewCell.swift
// KYHandMade
//
// Created by Kerain on 2017/6/19.
// Copyright © 2017年 广州市九章信息科技有限公司. All rights reserved.
//
import UIKit
class KYSlideCollectionViewCell: UICollectionViewCell {
@IBOutlet weak var shopPic: UIImageView!
@IBOutlet weak var subtitle: UILabel!
@IBOutlet weak var vote: UILabel!
@IBOutlet weak var useName: UILabel!
@IBOutlet weak var userPic: UIImageView!
var _slideShopModel : KYSlideShopModel?
var slideShopModel : KYSlideShopModel?{
set{
_slideShopModel = newValue
subtitle.text = _slideShopModel?.subject
vote.text = _slideShopModel?.votes
useName.text = _slideShopModel?.uname
guard let shopUrl = _slideShopModel?.host_pic else {
return
}
shopPic.kf.setImage(with: URL(string:shopUrl)!)
guard let useUrl = _slideShopModel?.avatar else {
return
}
userPic.kf.setImage(with: URL(string:useUrl)!)
}
get{
return _slideShopModel
}
}
override func awakeFromNib() {
super.awakeFromNib()
layer.cornerRadius = 5
}
}
|
apache-2.0
|
f8589dc7c4767ea3716ead5a1a3ff44f
| 23.384615 | 64 | 0.588328 | 4.402778 | false | false | false | false |
Kiandr/CrackingCodingInterview
|
Swift/Ch 5. Bit Manipulation/Ch 5. Bit Manipulation.playground/Pages/5.4 Next Number.xcplaygroundpage/Contents.swift
|
1
|
3348
|
import Foundation
/*:
Given a positive Int, print the next smallest and the next largest number that have the same
number of 1 bits in their binary representation.
*/
extension UInt {
var nextSmallerAndLargerIntsWithSameCountOfBitsSetTo1: (smaller: UInt?, larger: UInt?) {
return (nextSmaller, nextLarger)
}
private var nextLarger: UInt? {
guard self > 0 && self < UInt.max else { return nil }
var zerosCount: UInt = 0
var onesCount: UInt = 0
var selfCopy = self
while selfCopy & 1 == 0 {
zerosCount += 1
selfCopy >>= 1
}
while selfCopy & 1 == 1 {
onesCount += 1
selfCopy >>= 1
}
if zerosCount + onesCount >= 63 {
return nil
}
selfCopy = self & ~0 << (zerosCount + onesCount)
selfCopy |= 1 << (onesCount - 1) - 1
selfCopy |= 1 << (zerosCount + onesCount)
return selfCopy
}
private var nextSmaller: UInt? {
guard self > 0 else { return nil }
var zerosCount: UInt = 0
var onesCount: UInt = 0
var selfCopy = self
while selfCopy & 1 == 1 {
onesCount += 1
selfCopy >>= 1
}
guard selfCopy > 0 else { return nil }
while selfCopy & 1 == 0 {
zerosCount += 1
selfCopy >>= 1
}
selfCopy = self & ~0 << (zerosCount + onesCount + 1)
let mask = (1 << (onesCount + 1) - 1)
selfCopy |= mask << (zerosCount - 1)
return selfCopy
}
}
for i: UInt in 13000..<14000 {
let (smaller, larger) = i.nextSmallerAndLargerIntsWithSameCountOfBitsSetTo1
let iBitCount = i.bitsSetCount
if let smaller = smaller {
let smallerBitCount = smaller.bitsSetCount
assert(smaller < i, "i = \(i), smaller = \(smaller)", file: "")
assert(smallerBitCount == iBitCount, "i = \(i), iBitCount = \(iBitCount), smaller = \(smaller) smallerBitCount = \(smallerBitCount)", file: "")
var j = i - 1
while j > smaller {
let jBitCount = j.bitsSetCount
assert(jBitCount != iBitCount, "\(jBitCount) == \(iBitCount) for \(j) \(i) \(smaller)", file: "")
j -= 1
}
}
else {
var j = i - 1
while j > 0 {
let jBitCount = j.bitsSetCount
assert(jBitCount != iBitCount, "i = \(i): \(j) is next smaller with \(jBitCount) one bits\n", file: "")
j -= 1
}
}
if let larger = larger {
let largerBitCount = larger.bitsSetCount
assert(larger > i, "i = \(i), larger = \(larger)", file: "")
assert(largerBitCount == iBitCount, "i = \(i), iBitCount = \(iBitCount), larger = \(larger) largerBitCount = \(largerBitCount)", file: "")
var j = i + 1
while j < larger {
let jBitCount = j.bitsSetCount
assert(jBitCount != iBitCount, "\(jBitCount) == \(iBitCount) for \(j) \(i) \(larger)")
j += 1
}
}
else {
var j = i + 1
while j < UInt.max {
let jBitCount = j.bitsSetCount
assert(jBitCount != iBitCount, "i = \(i): \(j) is next larger with \(jBitCount) one bits\n", file: "")
j += 1
}
}
}
|
mit
|
e78ad147b1265d687c3ffaaf06fa96a6
| 30.885714 | 151 | 0.516726 | 4.087912 | false | false | false | false |
timd/InitialSwiftClock
|
SwiftClock/ClockViewController.swift
|
1
|
2567
|
//
// ClockViewController.swift
// InitialSwiftClock
//
// Created by Tim on 21/04/15.
// Copyright (c) 2015 Tim Duckett. All rights reserved.
//
import UIKit
class ClockViewController: UIViewController {
@IBOutlet var collectionView: UICollectionView!
var dataArray = []
let HourCellIdentifier = "HourCell"
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
setupData()
configureCollectionView()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
extension ClockViewController {
// MARK:
// MARK: UICollectionView methods
func configureCollectionView() {
collectionView.registerNib(UINib(nibName: "HourLabelCell", bundle: nil), forCellWithReuseIdentifier: HourCellIdentifier)
let flowLayout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
flowLayout.itemSize = CGSizeMake(100.0, 100.0)
flowLayout.minimumInteritemSpacing = 25.0
flowLayout.minimumLineSpacing = 25.0
collectionView.collectionViewLayout = flowLayout
}
func setupData() {
let hoursArray = ["12", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11"]
let handsArray = ["hours", "minutes", "seconds"]
dataArray = [hoursArray, handsArray]
}
}
extension ClockViewController: UICollectionViewDataSource, UICollectionViewDelegate {
func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
return dataArray.count
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
let innerArray = dataArray[section]
return innerArray.count
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(HourCellIdentifier, forIndexPath: indexPath) as UICollectionViewCell
let innerArray = dataArray[indexPath.section]
if let cellLabel: UILabel = cell.viewWithTag(1000) as? UILabel {
let text = innerArray[indexPath.row] as! String
cellLabel.text = text
}
return cell
}
}
|
mit
|
c844c1bd4b5584c22aa1df110fc07606
| 26.902174 | 141 | 0.641995 | 5.532328 | false | false | false | false |
googleprojectzero/fuzzilli
|
Sources/Fuzzilli/FuzzIL/Code.swift
|
1
|
11768
|
// Copyright 2020 Google LLC
//
// 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.
/// Code: a sequence of instructions. Forms the basis of Programs.
public struct Code: Collection {
public typealias Element = Instruction
/// Code is just a linear sequence of instructions.
private var instructions = [Instruction]()
/// Creates an empty code instance.
public init() {}
/// Creates a code instance containing the given instructions.
public init(_ instructions: [Instruction]) {
for instr in instructions {
append(instr)
}
}
/// The number of instructions.
public var count: Int {
return instructions.count
}
/// The index of the first instruction, always 0.
public var startIndex: Int {
return 0
}
/// The index of the last instruction plus one.
public var endIndex: Int {
return count
}
/// Advances the given index by one. Simply returns the argument plus 1.
public func index(after i: Int) -> Int {
return i + 1
}
/// Access the ith instruction in this code.
public subscript(i: Int) -> Instruction {
get {
assert(instructions[i].hasIndex && instructions[i].index == i)
return instructions[i]
}
set {
return instructions[i] = Instruction(newValue.op, inouts: newValue.inouts, index: i)
}
}
/// Returns the instruction after the given one, if it exists.
public func after(_ instr: Instruction) -> Instruction? {
let idx = instr.index + 1
return idx < endIndex ? self[idx] : nil
}
/// Returns the instruction before the given one, if it exists.
public func before(_ instr: Instruction) -> Instruction? {
let idx = instr.index - 1
return idx >= 0 ? self[idx] : nil
}
/// The last instruction in this code.
public var lastInstruction: Instruction {
return instructions.last!
}
/// Returns the instructions in this code in reversed order.
public func reversed() -> ReversedCollection<Array<Instruction>> {
return instructions.reversed()
}
/// Enumerates the instructions in this code.
public func enumerated() -> EnumeratedSequence<Array<Instruction>> {
return instructions.enumerated()
}
/// Appends the given instruction to this code.
/// The inserted instruction will now also contain its index in this code.
@discardableResult
public mutating func append(_ instr: Instruction) -> Instruction {
let instr = Instruction(instr.op, inouts: instr.inouts, index: count)
instructions.append(instr)
return instr
}
/// Removes all instructions in this code.
public mutating func removeAll() {
instructions.removeAll()
}
/// Removes the last instruction in this code.
public mutating func removeLast(_ n: Int = 1) {
instructions.removeLast(n)
}
/// Checks whether the given instruction belongs to this code.
public func contains(_ instr: Instruction) -> Bool {
let idx = instr.index
guard idx >= 0 && idx < count else { return false }
return instr.op === self[idx].op && instr.inouts == self[idx].inouts
}
/// Replaces an instruction with a different one.
///
/// - Parameters:
/// - instr: The instruction to replace.
/// - newInstr: The new instruction.
public mutating func replace(_ instr: Instruction, with newInstr: Instruction) {
assert(contains(instr))
self[instr.index] = newInstr
}
/// Computes the last variable (which will have the highest number) in this code or nil if there are no variables.
public func lastVariable() -> Variable? {
assert(isStaticallyValid())
for instr in instructions.reversed() {
if let v = instr.allOutputs.max() {
return v
}
}
return nil
}
/// Computes the next free variable in this code.
public func nextFreeVariable() -> Variable {
assert(isStaticallyValid())
if let lastVar = lastVariable() {
return Variable(number: lastVar.number + 1)
}
return Variable(number: 0)
}
/// Renumbers variables so that their numbers are again contiguous.
/// This can be useful after instructions have been reordered, for example for the purpose of minimization.
public mutating func renumberVariables() {
var numVariables = 0
var varMap = VariableMap<Variable>()
for (idx, instr) in self.enumerated() {
for output in instr.allOutputs {
assert(!varMap.contains(output))
let mappedVar = Variable(number: numVariables)
varMap[output] = mappedVar
numVariables += 1
}
let inouts = instr.inouts.map({ varMap[$0]! })
self[idx] = Instruction(instr.op, inouts: inouts)
}
}
/// Remove all nop instructions from this code.
/// Mainly used at the end of code minimization, as code reducers typically just replace deleted instructions with a nop.
public mutating func removeNops() {
instructions = instructions.filter({ !($0.op is Nop) })
// Need to renumber the variables now as nops can have outputs, but also because the instruction indices are no longer correct.
renumberVariables()
}
/// Checks if this code is statically valid, i.e. can be used as a Program.
public func check() throws {
var definedVariables = VariableMap<Int>()
var scopeCounter = 0
var visibleScopes = [scopeCounter]
var contextAnalyzer = ContextAnalyzer()
var blockHeads = [Operation]()
var defaultSwitchCaseStack: [Bool] = []
var classDefinitions = ClassDefinitionStack()
func defineVariable(_ v: Variable, in scope: Int) throws {
guard !definedVariables.contains(v) else {
throw FuzzilliError.codeVerificationError("variable \(v) was already defined")
}
if v.number != 0 {
let prev = Variable(number: v.number - 1)
guard definedVariables.contains(prev) else {
throw FuzzilliError.codeVerificationError("variable definitions are not contiguous: \(v) is defined before \(prev)")
}
}
definedVariables[v] = scope
}
for (idx, instr) in instructions.enumerated() {
guard idx == instr.index else {
throw FuzzilliError.codeVerificationError("instruction \(idx) has wrong index \(String(describing: instr.index))")
}
// Ensure all input variables are valid and have been defined
for input in instr.inputs {
guard let definingScope = definedVariables[input] else {
throw FuzzilliError.codeVerificationError("variable \(input) was never defined")
}
guard visibleScopes.contains(definingScope) else {
throw FuzzilliError.codeVerificationError("variable \(input) is not visible anymore")
}
}
guard instr.op.requiredContext.isSubset(of: contextAnalyzer.context) else {
throw FuzzilliError.codeVerificationError("operation \(instr.op.name) inside an invalid context")
}
// Ensure that the instruction exists in the right context
contextAnalyzer.analyze(instr)
// Block and scope management (1)
if instr.isBlockEnd {
guard let blockBegin = blockHeads.popLast() else {
throw FuzzilliError.codeVerificationError("block was never started")
}
guard instr.op.isMatchingEnd(for: blockBegin) else {
throw FuzzilliError.codeVerificationError("block end does not match block start")
}
visibleScopes.removeLast()
// Switch Case semantic verification
if instr.op is EndSwitch {
defaultSwitchCaseStack.removeLast()
}
// Class semantic verification
if instr.op is EndClass {
guard !classDefinitions.current.hasPendingMethods else {
let pendingMethods = classDefinitions.current.pendingMethods().map({ $0.name })
throw FuzzilliError.codeVerificationError("missing method definitions for methods \(pendingMethods) in class \(classDefinitions.current.name)")
}
classDefinitions.pop()
}
}
// Ensure output variables don't exist yet
for output in instr.outputs {
// Nop outputs aren't visible and so should not be used by other instruction
let scope = instr.op is Nop ? -1 : visibleScopes.last!
try defineVariable(output, in: scope)
}
// Block and scope management (2)
if instr.isBlockStart {
scopeCounter += 1
visibleScopes.append(scopeCounter)
blockHeads.append(instr.op)
// Switch Case semantic verification
if instr.op is BeginSwitch {
defaultSwitchCaseStack.append(false)
}
// Ensure that we have at most one default case in a switch block
if instr.op is BeginSwitchDefaultCase {
let stackTop = defaultSwitchCaseStack.removeLast()
// Check if the current block already has a default case
guard !stackTop else {
throw FuzzilliError.codeVerificationError("more than one default switch case defined")
}
defaultSwitchCaseStack.append(true)
}
// Class semantic verification
if let op = instr.op as? BeginClass {
classDefinitions.push(ClassDefinition(from: op, name: instr.output.identifier))
} else if instr.op is BeginMethod {
guard classDefinitions.current.hasPendingMethods else {
throw FuzzilliError.codeVerificationError("too many method definitions for class \(classDefinitions.current.name)")
}
let _ = classDefinitions.current.nextMethod()
}
}
// Ensure inner output variables don't exist yet
for output in instr.innerOutputs {
try defineVariable(output, in: visibleScopes.last!)
}
}
assert(!definedVariables.hasHoles())
}
/// Returns true if this code is valid, false otherwise.
public func isStaticallyValid() -> Bool {
do {
try check()
return true
} catch {
return false
}
}
// This restriction arises from the fact that variables and instruction indices are stored internally as UInt16
public static let maxNumberOfVariables = 0x10000
}
|
apache-2.0
|
17c41bbccd2aae67af5f797948dad00d
| 37.838284 | 167 | 0.602736 | 5.03121 | false | false | false | false |
DavidHu0921/LyricsEasy
|
Carthage/Checkouts/FileKit/Tests/FileKitTests.swift
|
1
|
24353
|
//
// FileKitTests.swift
// FileKitTests
//
// The MIT License (MIT)
//
// Copyright (c) 2015-2016 Nikolai Vazquez
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
// swiftlint:disable type_body_length
// swiftlint:disable file_length
//
import XCTest
import FileKit
class FileKitTests: XCTestCase {
// MARK: - Path
class Delegate: NSObject, FileManagerDelegate {
var expectedSourcePath: Path = ""
var expectedDestinationPath: Path = ""
func fileManager(
_ fileManager: FileManager,
shouldCopyItemAtPath srcPath: String,
toPath dstPath: String
) -> Bool {
XCTAssertEqual(srcPath, expectedSourcePath.rawValue)
XCTAssertEqual(dstPath, expectedDestinationPath.rawValue)
return true
}
}
func testPathFileManagerDelegate() {
do {
var sourcePath = .userTemporary + "filekit_test_filemanager_delegate"
let destinationPath = Path("\(sourcePath)1")
try sourcePath.createFile()
var delegate: Delegate {
let delegate = Delegate()
delegate.expectedSourcePath = sourcePath
delegate.expectedDestinationPath = destinationPath
return delegate
}
let d1 = delegate
sourcePath.fileManagerDelegate = d1
XCTAssertTrue(d1 === sourcePath.fileManagerDelegate)
try sourcePath +>! destinationPath
var secondSourcePath = sourcePath
secondSourcePath.fileManagerDelegate = delegate
XCTAssertFalse(sourcePath.fileManagerDelegate === secondSourcePath.fileManagerDelegate)
try secondSourcePath +>! destinationPath
} catch {
XCTFail(String(describing: error))
}
}
func testFindingPaths() {
let homeFolders = Path.userHome.find(searchDepth: 0) { $0.isDirectory }
XCTAssertFalse(homeFolders.isEmpty, "Home folder is not empty")
let rootFiles = Path.root.find(searchDepth: 1) { !$0.isDirectory }
XCTAssertFalse(rootFiles.isEmpty)
}
func testPathStringLiteralConvertible() {
let a = "/Users" as Path
let b: Path = "/Users"
let c = Path("/Users")
XCTAssertEqual(a, b)
XCTAssertEqual(a, c)
XCTAssertEqual(b, c)
}
func testPathStringInterpolationConvertible() {
let path: Path = "\(Path.userTemporary)/testfile_\(10)"
XCTAssertEqual(path.rawValue, Path.userTemporary.rawValue + "/testfile_10")
}
func testPathEquality() {
let a: Path = "~"
let b: Path = "~/"
let c: Path = "~//"
let d: Path = "~/./"
XCTAssertEqual(a, b)
XCTAssertEqual(a, c)
XCTAssertEqual(a, d)
}
func testStandardizingPath() {
let a: Path = "~/.."
let b: Path = "/Users"
XCTAssertEqual(a.standardized, b.standardized)
}
func testPathIsDirectory() {
let d = Path.systemApplications
XCTAssertTrue(d.isDirectory)
}
func testSequence() {
var i = 0
let parent = Path.userTemporary
for _ in parent {
i += 1
}
print("\(i) files under \(parent)")
i = 0
for (_, _) in Path.userTemporary.enumerated() {
i += 1
}
}
func testPathExtension() {
var path = Path.userTemporary + "file.txt"
XCTAssertEqual(path.pathExtension, "txt")
path.pathExtension = "pdf"
XCTAssertEqual(path.pathExtension, "pdf")
}
func testPathParent() {
let a: Path = "/"
let b: Path = a + "Users"
XCTAssertEqual(a, b.parent)
}
func testPathChildren() {
let p: Path = "/Users"
XCTAssertNotEqual(p.children(), [])
}
func testPathRecursiveChildren() {
let p: Path = Path.userTemporary
let children = p.children(recursive: true)
XCTAssertNotEqual(children, [])
}
func testRoot() {
let root = Path.root
XCTAssertTrue(root.isRoot)
XCTAssertEqual(root.standardized, root)
XCTAssertEqual(root.parent, root)
var p: Path = Path.userTemporary
XCTAssertFalse(p.isRoot)
while !p.isRoot { p = p.parent }
XCTAssertTrue(p.isRoot)
let empty = Path("")
XCTAssertFalse(empty.isRoot)
XCTAssertEqual(empty.standardized, empty)
XCTAssertTrue(Path("/.").isRoot)
XCTAssertTrue(Path("//").isRoot)
}
func testFamily() {
let p: Path = Path.userTemporary
let children = p.children()
guard let child = children.first else {
XCTFail("No child into \(p)")
return
}
XCTAssertTrue(child.isAncestorOfPath(p))
XCTAssertTrue(p.isChildOfPath(child))
XCTAssertFalse(p.isAncestorOfPath(child))
XCTAssertFalse(p.isAncestorOfPath(p))
XCTAssertFalse(p.isChildOfPath(p))
let directories = children.filter { $0.isDirectory }
guard let directory = directories.first, let childOfChild = directory.children().first else {
XCTFail("No child of child into \(p)")
return
}
XCTAssertTrue(childOfChild.isAncestorOfPath(p))
XCTAssertFalse(p.isChildOfPath(childOfChild, recursive: false))
XCTAssertTrue(p.isChildOfPath(childOfChild, recursive: true))
// common ancestor
XCTAssertTrue(p.commonAncestor(Path.root).isRoot)
XCTAssertEqual(.userDownloads <^> .userDocuments, Path.userHome)
XCTAssertEqual(("~/Downloads" <^> "~/Documents").rawValue, "~")
}
func testPathAttributes() {
let a = .userTemporary + "test.txt"
let b = .userTemporary + "TestDir"
do {
try "Hello there, sir" |> TextFile(path: a)
try b.createDirectory()
} catch {
XCTFail(String(describing: error))
}
for p in [a, b] {
print(p.creationDate)
print(p.modificationDate)
print(p.ownerName)
print(p.ownerID)
print(p.groupName)
print(p.groupID)
print(p.extensionIsHidden)
print(p.posixPermissions)
print(p.fileReferenceCount)
print(p.fileSize)
print(p.filesystemFileNumber)
print(p.fileType)
print("")
}
}
func testPathSubscript() {
let path = "~/Library/Preferences" as Path
let a = path[0]
XCTAssertEqual(a, "~")
let b = path[2]
XCTAssertEqual(b, path)
}
func testAddingPaths() {
let a: Path = "~/Desktop"
let b: Path = "Files"
XCTAssertEqual(a + b, "~/Desktop/Files")
}
func testPathPlusEquals() {
var a: Path = "~/Desktop"
a += "Files"
XCTAssertEqual(a, "~/Desktop/Files")
}
func testPathSymlinking() {
do {
let testDir: Path = .userTemporary + "filekit_test_symlinking"
if testDir.exists && !testDir.isDirectory {
try testDir.deleteFile()
XCTAssertFalse(testDir.exists)
}
try testDir.createDirectory()
XCTAssertTrue(testDir.exists)
let testFile = TextFile(path: testDir + "test_file.txt")
try "FileKit test" |> testFile
XCTAssertTrue(testFile.exists)
let symDir = testDir + "sym_dir"
if symDir.exists && !symDir.isDirectory {
try symDir.deleteFile()
}
try symDir.createDirectory()
// "/temporary/symDir/test_file.txt"
try testFile =>! symDir
let symPath = symDir + testFile.name
XCTAssertTrue(symPath.isSymbolicLink)
let symPathContents = try String(contentsOfPath: symPath)
XCTAssertEqual(symPathContents, "FileKit test")
let symLink = testDir + "test_file_link.txt"
try testFile =>! symLink
XCTAssertTrue(symLink.isSymbolicLink)
let symLinkContents = try String(contentsOfPath: symLink)
XCTAssertEqual(symLinkContents, "FileKit test")
} catch {
XCTFail(String(describing: error))
}
}
func testPathOperators() {
let p: Path = "~"
let ps = p.standardized
XCTAssertEqual(ps, p%)
XCTAssertEqual(ps.parent, ps^)
}
func testCurrent() {
let oldCurrent: Path = .current
let newCurrent: Path = .userTemporary
XCTAssertNotEqual(oldCurrent, newCurrent) // else there is no test
Path.current = newCurrent
XCTAssertEqual(Path.current, newCurrent)
Path.current = oldCurrent
XCTAssertEqual(Path.current, oldCurrent)
}
func testChangeDirectory() {
Path.userTemporary.changeDirectory {
XCTAssertEqual(Path.current, Path.userTemporary)
}
Path.userDesktop </> {
XCTAssertEqual(Path.current, Path.userDesktop)
}
XCTAssertNotEqual(Path.current, Path.userTemporary)
}
func testVolumes() {
var volumes = Path.volumes()
XCTAssertFalse(volumes.isEmpty, "No volume")
for volume in volumes {
XCTAssertNotNil("\(volume)")
}
volumes = Path.volumes(.skipHiddenVolumes)
XCTAssertFalse(volumes.isEmpty, "No visible volume")
for volume in volumes {
XCTAssertNotNil("\(volume)")
}
}
func testURL() {
let path: Path = .userTemporary
let url = path.url
if let pathFromURL = Path(url: url) {
XCTAssertEqual(pathFromURL, path)
let subPath = pathFromURL + "test"
XCTAssertEqual(Path(url: url.appendingPathComponent("test")), subPath)
} else {
XCTFail("Not able to create Path from URL")
}
}
func testBookmarkData() {
let path: Path = .userTemporary
XCTAssertNotNil(path.bookmarkData)
if let bookmarkData = path.bookmarkData {
if let pathFromBookmarkData = Path(bookmarkData: bookmarkData) {
XCTAssertEqual(pathFromBookmarkData, path)
} else {
XCTFail("Not able to create Path from Bookmark Data")
}
}
}
func testGroupIdentifier() {
let path = Path(groupIdentifier: "com.nikolaivazquez.FileKitTests")
XCTAssertNotNil(path, "Not able to create Path from group identifier")
}
func testTouch() {
let path: Path = .userTemporary + "filekit_test.touch"
do {
if path.exists { try path.deleteFile() }
XCTAssertFalse(path.exists)
try path.touch()
XCTAssertTrue(path.exists)
guard let modificationDate = path.modificationDate else {
XCTFail("Failed to get modification date")
return
}
sleep(1)
try path.touch()
guard let newModificationDate = path.modificationDate else {
XCTFail("Failed to get modification date")
return
}
XCTAssertTrue(modificationDate < newModificationDate)
} catch {
XCTFail(String(describing: error))
}
}
func testCreateDirectory() {
let dir: Path = .userTemporary + "filekit_testdir"
do {
if dir.exists { try dir.deleteFile() }
} catch {
XCTFail(String(describing: error))
}
defer {
do {
if dir.exists { try dir.deleteFile() }
} catch {
XCTFail(String(describing: error))
}
}
do {
XCTAssertFalse(dir.exists)
try dir.createDirectory()
XCTAssertTrue(dir.exists)
} catch {
XCTFail(String(describing: error))
}
do {
XCTAssertTrue(dir.exists)
try dir.createDirectory(withIntermediateDirectories: false)
XCTFail("must throw exception")
} catch FileKitError.createDirectoryFail {
print("Create directory fail ok")
} catch {
XCTFail("Unknown error: " + String(describing: error))
}
do {
XCTAssertTrue(dir.exists)
try dir.createDirectory(withIntermediateDirectories: true)
XCTAssertTrue(dir.exists)
} catch {
XCTFail("Unexpected error: " + String(describing: error))
}
}
func testWellKnownDirectories() {
var paths: [Path] = [
.userHome, .userTemporary, .userCaches, .userDesktop, .userDocuments,
.userAutosavedInformation, .userDownloads, .userLibrary, .userMovies,
.userMusic, .userPictures, .userApplicationSupport, .userApplications,
.userSharedPublic
]
paths += [
.systemApplications, .systemApplicationSupport, .systemLibrary,
.systemCoreServices, .systemPreferencePanes /* .systemPrinterDescription,*/
]
#if os(OSX)
paths += [.userTrash] // .userApplicationScripts (not testable)
#endif
for path in paths {
XCTAssertTrue(path.exists, path.rawValue)
}
// all
XCTAssertTrue(Path.allLibraries.contains(.userLibrary))
XCTAssertTrue(Path.allLibraries.contains(.systemLibrary))
XCTAssertTrue(Path.allApplications.contains(.userApplications))
XCTAssertTrue(Path.allApplications.contains(.systemApplications))
// temporary
XCTAssertFalse(Path.processTemporary.exists)
XCTAssertFalse(Path.uniqueTemporary.exists)
XCTAssertNotEqual(Path.uniqueTemporary, Path.uniqueTemporary)
}
// MARK: - TextFile
let textFile = TextFile(path: .userTemporary + "filekit_test.txt")
func testFileName() {
XCTAssertEqual(TextFile(path: "/Users/").name, "Users")
}
func testTextFileExtension() {
XCTAssertEqual(textFile.pathExtension, "txt")
}
func testTextFileExists() {
do {
try textFile.create()
XCTAssertTrue(textFile.exists)
} catch {
XCTFail(String(describing: error))
}
}
func testWriteToTextFile() {
do {
try textFile.write("This is some test.")
try textFile.write("This is another test.", atomically: false)
} catch {
XCTFail(String(describing: error))
}
}
func testTextFileOperators() {
do {
let text = "FileKit Test"
try text |> textFile
var contents = try textFile.read()
XCTAssertTrue(contents.hasSuffix(text))
try text |>> textFile
contents = try textFile.read()
XCTAssertTrue(contents.hasSuffix(text + "\n" + text))
} catch {
XCTFail(String(describing: error))
}
}
func testTextFileStreamReader() {
do {
let expectedLines = [
"Lorem ipsum dolor sit amet",
"consectetur adipiscing elit",
"Sed non risus"
]
let separator = "\n"
try expectedLines.joined(separator: separator) |> textFile
if let reader = textFile.streamReader() {
var lines = [String]()
for line in reader {
lines.append(line)
}
XCTAssertEqual(expectedLines, lines)
} else {
XCTFail("Failed to create reader")
}
} catch {
XCTFail(String(describing: error))
}
}
func testTextFileGrep() {
do {
let expectedLines = [
"Lorem ipsum dolor sit amet",
"consectetur adipiscing elit",
"Sed non risus"
]
let separator = "\n"
try expectedLines.joined(separator: separator) |> textFile
// all
var result = textFile | "e"
XCTAssertEqual(result, expectedLines)
// not all
result = textFile |- "e"
XCTAssertTrue(result.isEmpty)
// specific line
result = textFile | "eli"
XCTAssertEqual(result, [expectedLines[1]])
// the other line
result = textFile |- "eli"
XCTAssertEqual(result, [expectedLines[0], expectedLines[2]])
// regex
result = textFile |~ "e.*i.*e.*"
XCTAssertEqual(result, [expectedLines[0], expectedLines[1]])
// this not a regex
result = textFile | "e.*i.*e.*"
XCTAssertTrue(result.isEmpty)
} catch {
XCTFail(String(describing: error))
}
}
// MARK: - FileType
func testFileTypeComparable() {
let textFile1 = TextFile(path: .userTemporary + "filekit_test_comparable1.txt")
let textFile2 = TextFile(path: .userTemporary + "filekit_test_comparable2.txt")
do {
try "1234567890" |> textFile1
try "12345" |> textFile2
XCTAssert(textFile1 > textFile2)
} catch {
XCTFail(String(describing: error))
}
}
// MARK: - FilePermissions
func testFilePermissions() {
let swift: Path = "/usr/bin/swift"
if swift.exists {
XCTAssertTrue(swift.filePermissions.contains([.read, .execute]))
}
let file: Path = .userTemporary + "filekit_test_filepermissions"
do {
try file.createFile()
XCTAssertTrue(file.filePermissions.contains([.read, .write]))
} catch {
XCTFail(String(describing: error))
}
}
// MARK: - DictionaryFile
let nsDictionaryFile = NSDictionaryFile(path: .userTemporary + "filekit_test_nsdictionary.plist")
func testWriteToNSDictionaryFile() {
do {
let dict = NSMutableDictionary()
dict["FileKit" as NSString] = true
dict["Hello" as NSString] = "World"
try nsDictionaryFile.write(dict)
let contents = try nsDictionaryFile.read()
XCTAssertEqual(contents, dict)
} catch {
XCTFail(String(describing: error))
}
}
// MARK: - DictionaryFile
let dictionaryFile = DictionaryFile<String, Any>(path: .userTemporary + "filekit_test_dictionary.plist")
func testWriteToDictionaryFile() {
do {
var dict: [String: Any] = [:]
dict["FileKit"] = true
dict["Hello"] = "World"
try dictionaryFile.write(dict)
let contents = try dictionaryFile.read()
XCTAssertEqual(contents.count, dict.count)
for (kc, vc) in contents {
let v = dict[kc]
if let vb = v as? Bool , let vcb = vc as? Bool {
XCTAssertEqual(vb, vcb)
}
else if let vb = v as? String , let vcb = vc as? String {
XCTAssertEqual(vb, vcb)
}
else {
XCTFail("unknow type")
}
}
} catch {
XCTFail(String(describing: error))
}
}
// MARK: - ArrayFile
let nsArrayFile = NSArrayFile(path: .userTemporary + "filekit_test_nsarray.plist")
func testWriteToNSArrayFile() {
do {
let array: NSArray = ["ABCD", "WXYZ"]
try nsArrayFile.write(array)
let contents = try nsArrayFile.read()
XCTAssertEqual(contents, array)
} catch {
XCTFail(String(describing: error))
}
}
// MARK: - ArrayFile
let arrayFile = ArrayFile<String>(path: .userTemporary + "filekit_test_array.plist")
func testWriteToArrayFile() {
do {
let array = ["ABCD", "WXYZ"]
try arrayFile.write(array)
let contents = try arrayFile.read()
XCTAssertEqual(contents, array)
} catch {
XCTFail(String(describing: error))
}
}
// MARK: - NSDataFile
let nsDataFile = NSDataFile(path: .userTemporary + "filekit_test_nsdata")
func testWriteToNSDataFile() {
do {
let data = ("FileKit test" as NSString).data(using: String.Encoding.utf8.rawValue)! as NSData
try nsDataFile.write(data)
let contents = try nsDataFile.read()
XCTAssertEqual(contents, data)
} catch {
XCTFail(String(describing: error))
}
}
// MARK: - DataFile
let dataFile = DataFile(path: .userTemporary + "filekit_test_data")
func testWriteToDataFile() {
do {
let data = "FileKit test".data(using: String.Encoding.utf8)!
try dataFile.write(data)
let contents = try dataFile.read()
XCTAssertEqual(contents, data)
} catch {
XCTFail(String(describing: error))
}
}
// MARK: - String+FileKit
let stringFile = File<String>(path: .userTemporary + "filekit_stringtest.txt")
func testStringInitializationFromPath() {
do {
let message = "Testing string init..."
try stringFile.write(message)
let contents = try String(contentsOfPath: stringFile.path)
XCTAssertEqual(contents, message)
} catch {
XCTFail(String(describing: error))
}
}
func testStringWriting() {
do {
let message = "Testing string writing..."
try message.write(to: stringFile.path)
let contents = try String(contentsOfPath: stringFile.path)
XCTAssertEqual(contents, message)
} catch {
XCTFail(String(describing: error))
}
}
// MARK: - Image
func testImageWriting() {
let url = URL(string: "https://raw.githubusercontent.com/nvzqz/FileKit/assets/logo.png")!
let img = Image(contentsOf: url) ?? Image()
do {
let path: Path = .userTemporary + "filekit_imagetest.png"
try img.write(to: path)
} catch {
XCTFail(String(describing: error))
}
}
// MARK: - Watch
func testWatch() {
let pathToWatch = .userTemporary + "filekit_test_watch"
let expectation = "event"
let operation = {
do {
let message = "Testing file system event when writing..."
try message.write(to: pathToWatch, atomically: false)
} catch {
XCTFail(String(describing: error))
}
}
// Do watch test
let expt = self.expectation(description: expectation)
let watcher = pathToWatch.watch { event in
print(event)
// XXX here could check expected event type according to operation
expt.fulfill()
}
defer {
watcher.close()
}
operation()
self.waitForExpectations(timeout: 10, handler: nil)
}
}
|
mit
|
78fa44a5f6a260324d3373457cf8b481
| 28.662607 | 108 | 0.56802 | 4.750878 | false | true | false | false |
hironytic/Moltonf-iOS
|
Moltonf/Resources/Resource+Id.swift
|
1
|
1918
|
//
// Resource+Id.swift
// Moltonf
//
// Copyright (c) 2016 Hironori Ichimiya <hiron@hironytic.com>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
public extension Resource {
public struct Id {
private init() { }
/// General cell identifier
public static let cell = "Cell"
/// Cell identifier of "Event"
public static let event = "Event"
/// Cell identifier of "Talk"
public static let talk = "Talk"
/// Name of the storyboard "SelectPeriod"
public static let selectPeriod = "SelectPeriod"
/// Name of the storyboard "SelectArchiveFile"
public static let selectArchiveFile = "SelectArchiveFile"
/// Name of the storyboard "StoryWatching"
public static let storyWatching = "StoryWatching"
}
}
|
mit
|
6ffe0c37c1ce3079b26205a3348ad565
| 36.607843 | 80 | 0.688217 | 4.771144 | false | false | false | false |
pankcuf/DataContext
|
Example/DataContext/ViewController.swift
|
1
|
694
|
//
// ViewController.swift
// DataContext
//
// Created by Владимир Пирогов on 10/17/2016.
// Copyright (c) 2016 Владимир Пирогов. All rights reserved.
//
import UIKit
import DataContext
class ViewController: UITableViewController {
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.requestContextUpdates(DiscogsJsonRequest(artistID: 2522005, responseType: DiscogsJsonResponse.self))
}
override func loadView() {
let t = UITableView(frame: .zero, style: .plain)
let d = TableDataImpl()
t.delegate = d
t.dataSource = d
t.context = DiscogsTableContext(transport: JSONSessionTransport.shared)
self.view = t
}
}
|
mit
|
50f9e058fbeea110c5bb507882f803e9
| 19.75 | 117 | 0.72741 | 3.405128 | false | false | false | false |
vespax/GoMap-keyboard
|
ELDeveloperKeyboard/ELViewController.swift
|
1
|
1637
|
//
// ELViewController.swift
// ELDeveloperKeyboard
//
// Created by Kari Kraam on 2016-04-25.
// Copyright (c) 2016 Kari Kraam. All rights reserved.
//
import UIKit
// var keyboardHeight: CGFloat!
class ELViewController: UIViewController {
var textView: UITextView!
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override init(nibName nibNameOrNil: String!, bundle nibBundleOrNil: Bundle!) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}
override func loadView() {
super.loadView()
self.view = UIView(frame: UIScreen.main.applicationFrame)
self.textView = UITextView(frame: self.view.frame)
self.textView.isScrollEnabled = true
self.textView.isUserInteractionEnabled = true
self.view.addSubview(self.textView)
if #available(iOS 9.0, *) {
//self.textView.inputAssistantItem.leadingBarButtonGroups = []
self.textView.autocorrectionType = .default;
} else {
// Fallback on earlier versions
}
if #available(iOS 9.0, *) {
//self.textView.inputAssistantItem.trailingBarButtonGroups = []
} else {
// Fallback on earlier versions
}
self.textView.deleteBackward()
}
override func viewDidLoad() {
super.viewDidLoad()
self.textView.becomeFirstResponder()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
self.becomeFirstResponder()
}
}
|
apache-2.0
|
7fda19eadab65f29377e488d40cacdea
| 28.232143 | 82 | 0.623702 | 4.857567 | false | false | false | false |
utahiosmac/Marshal
|
Sources/MarshaledObject.swift
|
1
|
8938
|
//
// M A R S H A L
//
// ()
// /\
// ()--' '--()
// `. .'
// / .. \
// ()' '()
//
//
import Foundation
public protocol MarshaledObject {
func any(for key: KeyType) throws -> Any
func optionalAny(for key: KeyType) -> Any?
}
public extension MarshaledObject {
func any(for key: KeyType) throws -> Any {
let pathComponents = key.stringValue.split(separator: ".").map(String.init)
// Re-combine components ending in backslash…
var finalComponents = [String]()
var comp = ""
for component in pathComponents {
if component.hasSuffix("\\") {
let c = String(component.dropLast())
if comp.count > 0 {
comp += "."
}
comp += c
} else {
if comp.count > 0 {
comp += "." + component
finalComponents.append(comp)
comp = ""
} else {
finalComponents.append(component)
}
}
}
var accumulator: Any = self
for component in finalComponents {
if let componentData = accumulator as? Self, let value = componentData.optionalAny(for: component) {
accumulator = value
continue
}
throw MarshalError.keyNotFound(key: key.stringValue)
}
if let _ = accumulator as? NSNull {
throw MarshalError.nullValue(key: key.stringValue)
}
return accumulator
}
func value<A: ValueType>(for key: KeyType) throws -> A {
let any = try self.any(for: key)
do {
guard let result = try A.value(from: any) as? A else {
throw MarshalError.typeMismatchWithKey(key: key.stringValue, expected: A.self, actual: type(of: any))
}
return result
}
catch let MarshalError.typeMismatch(expected: expected, actual: actual) {
throw MarshalError.typeMismatchWithKey(key: key.stringValue, expected: expected, actual: actual)
}
}
func value<A: ValueType>(for key: KeyType) throws -> A? {
do {
return try self.value(for: key) as A
}
catch MarshalError.keyNotFound {
return nil
}
catch MarshalError.nullValue {
return nil
}
}
func value<A: ValueType>(for key: KeyType, discardingErrors: Bool = false) throws -> [A] {
let any = try self.any(for: key)
do {
return try Array<A>.value(from: any, discardingErrors: discardingErrors)
}
catch let MarshalError.typeMismatch(expected: expected, actual: actual) {
throw MarshalError.typeMismatchWithKey(key: key.stringValue, expected: expected, actual: actual)
}
}
func value<A: ValueType>(for key: KeyType) throws -> [A?] {
let any = try self.any(for: key)
do {
return try Array<A>.value(from: any)
}
catch let MarshalError.typeMismatch(expected: expected, actual: actual) {
throw MarshalError.typeMismatchWithKey(key: key.stringValue, expected: expected, actual: actual)
}
}
func value<A: ValueType>(for key: KeyType, discardingErrors: Bool = false) throws -> [A]? {
do {
return try self.value(for: key, discardingErrors: discardingErrors) as [A]
}
catch MarshalError.keyNotFound {
return nil
}
catch MarshalError.nullValue {
return nil
}
}
func value<A: ValueType>(for key: KeyType) throws -> [A?]? {
do {
return try self.value(for: key) as [A?]
}
catch MarshalError.keyNotFound {
return nil
}
catch MarshalError.nullValue {
return nil
}
}
func value<A: ValueType>(for key: KeyType) throws -> [String: A] {
let any = try self.any(for: key)
do {
return try [String: A].value(from: any)
}
catch let MarshalError.typeMismatch(expected: expected, actual: actual) {
throw MarshalError.typeMismatchWithKey(key: key.stringValue, expected: expected, actual: actual)
}
}
func value<A: ValueType>(for key: KeyType) throws -> [String: A]? {
do {
let any = try self.any(for: key)
return try [String: A].value(from: any)
}
catch MarshalError.keyNotFound {
return nil
}
catch MarshalError.nullValue {
return nil
}
}
func value(for key: KeyType) throws -> [MarshalDictionary] {
let any = try self.any(for: key)
guard let object = any as? [MarshalDictionary] else {
throw MarshalError.typeMismatchWithKey(key: key.stringValue, expected: [MarshalDictionary].self, actual: type(of: any))
}
return object
}
func value(for key: KeyType) throws -> [MarshalDictionary]? {
do {
return try value(for: key) as [MarshalDictionary]
}
catch MarshalError.keyNotFound {
return nil
}
catch MarshalError.nullValue {
return nil
}
}
func value(for key: KeyType) throws -> MarshalDictionary {
let any = try self.any(for: key)
guard let object = any as? MarshalDictionary else {
throw MarshalError.typeMismatchWithKey(key: key.stringValue, expected: MarshalDictionary.self, actual: type(of: any))
}
return object
}
func value(for key: KeyType) throws -> MarshalDictionary? {
do {
return try value(for: key) as MarshalDictionary
}
catch MarshalError.keyNotFound {
return nil
}
catch MarshalError.nullValue {
return nil
}
}
func value<A: ValueType>(for key: KeyType) throws -> Set<A> {
let any = try self.any(for: key)
do {
return try Set<A>.value(from: any)
}
catch let MarshalError.typeMismatch(expected: expected, actual: actual) {
throw MarshalError.typeMismatchWithKey(key: key.stringValue, expected: expected, actual: actual)
}
}
func value<A: ValueType>(for key: KeyType) throws -> Set<A>? {
do {
return try self.value(for: key) as Set<A>
}
catch MarshalError.keyNotFound {
return nil
}
catch MarshalError.nullValue {
return nil
}
}
func value<A: RawRepresentable>(for key: KeyType) throws -> A where A.RawValue: ValueType {
let raw = try self.value(for: key) as A.RawValue
guard let value = A(rawValue: raw) else {
throw MarshalError.typeMismatchWithKey(key: key.stringValue, expected: A.self, actual: raw)
}
return value
}
func value<A: RawRepresentable>(for key: KeyType) throws -> A? where A.RawValue: ValueType {
do {
return try self.value(for: key) as A
}
catch MarshalError.keyNotFound {
return nil
}
catch MarshalError.nullValue {
return nil
}
}
func value<A: RawRepresentable>(for key: KeyType) throws -> [A] where A.RawValue: ValueType {
let rawArray = try self.value(for: key) as [A.RawValue]
return try rawArray.map({ raw in
guard let value = A(rawValue: raw) else {
throw MarshalError.typeMismatchWithKey(key: key.stringValue, expected: A.self, actual: raw)
}
return value
})
}
func value<A: RawRepresentable>(for key: KeyType) throws -> [A]? where A.RawValue: ValueType {
do {
return try self.value(for: key) as [A]
}
catch MarshalError.keyNotFound {
return nil
}
catch MarshalError.nullValue {
return nil
}
}
func value<A: RawRepresentable>(for key: KeyType) throws -> Set<A> where A.RawValue: ValueType {
let rawArray = try self.value(for: key) as [A.RawValue]
let enumArray: [A] = try rawArray.map({ raw in
guard let value = A(rawValue: raw) else {
throw MarshalError.typeMismatchWithKey(key: key.stringValue, expected: A.self, actual: raw)
}
return value
})
return Set<A>(enumArray)
}
func value<A: RawRepresentable>(for key: KeyType) throws -> Set<A>? where A.RawValue: ValueType {
do {
return try self.value(for: key) as Set<A>
}
catch MarshalError.keyNotFound {
return nil
}
catch MarshalError.nullValue {
return nil
}
}
}
|
mit
|
dab375fc1ff66c153b665fe57a8ddbb5
| 30.575972 | 131 | 0.547337 | 4.479198 | false | false | false | false |
scsonic/cosremote
|
ios/Pods/SwiftHTTP/Source/Operation.swift
|
5
|
20416
|
//
// Operation.swift
// SwiftHTTP
//
// Created by Dalton Cherry on 8/2/15.
// Copyright © 2015 vluxe. All rights reserved.
//
import Foundation
enum HTTPOptError: ErrorType {
case InvalidRequest
}
/**
This protocol exist to allow easy and customizable swapping of a serializing format within an class methods of HTTP.
*/
public protocol HTTPSerializeProtocol {
/**
implement this protocol to support serializing parameters to the proper HTTP body or URL
-parameter request: The NSMutableURLRequest object you will modify to add the parameters to
-parameter parameters: The container (array or dictionary) to convert and append to the URL or Body
*/
func serialize(request: NSMutableURLRequest, parameters: HTTPParameterProtocol) throws
}
/**
Standard HTTP encoding
*/
public struct HTTPParameterSerializer: HTTPSerializeProtocol {
public init() { }
public func serialize(request: NSMutableURLRequest, parameters: HTTPParameterProtocol) throws {
try request.appendParameters(parameters)
}
}
/**
Send the data as a JSON body
*/
public struct JSONParameterSerializer: HTTPSerializeProtocol {
public init() { }
public func serialize(request: NSMutableURLRequest, parameters: HTTPParameterProtocol) throws {
try request.appendParametersAsJSON(parameters)
}
}
/**
All the things of an HTTP response
*/
public class Response {
/// The header values in HTTP response.
public var headers: Dictionary<String,String>?
/// The mime type of the HTTP response.
public var mimeType: String?
/// The suggested filename for a downloaded file.
public var suggestedFilename: String?
/// The body data of the HTTP response.
public var data: NSData {
return collectData
}
/// The status code of the HTTP response.
public var statusCode: Int?
/// The URL of the HTTP response.
public var URL: NSURL?
/// The Error of the HTTP response (if there was one).
public var error: NSError?
///Returns the response as a string
public var text: String? {
return NSString(data: data, encoding: NSUTF8StringEncoding) as? String
}
///get the description of the response
public var description: String {
var buffer = ""
if let u = URL {
buffer += "URL:\n\(u)\n\n"
}
if let code = self.statusCode {
buffer += "Status Code:\n\(code)\n\n"
}
if let heads = headers {
buffer += "Headers:\n"
for (key, value) in heads {
buffer += "\(key): \(value)\n"
}
buffer += "\n"
}
if let t = text {
buffer += "Payload:\n\(t)\n"
}
return buffer
}
///private things
///holds the collected data
var collectData = NSMutableData()
///finish closure
var completionHandler:((Response) -> Void)?
//progress closure. Progress is between 0 and 1.
var progressHandler:((Float) -> Void)?
///This gets called on auth challenges. If nil, default handling is use.
///Returning nil from this method will cause the request to be rejected and cancelled
var auth:((NSURLAuthenticationChallenge) -> NSURLCredential?)?
///This is for doing SSL pinning
var security: HTTPSecurity?
}
/**
The class that does the magic. Is a subclass of NSOperation so you can use it with operation queues or just a good ole HTTP request.
*/
public class HTTP: NSOperation {
/**
Get notified with a request finishes.
*/
public var onFinish:((Response) -> Void)? {
didSet {
if let handler = onFinish {
DelegateManager.sharedInstance.addTask(task, completionHandler: { (response: Response) in
self.finish()
handler(response)
})
}
}
}
///This is for handling authenication
public var auth:((NSURLAuthenticationChallenge) -> NSURLCredential?)? {
set {
guard let resp = DelegateManager.sharedInstance.responseForTask(task) else { return }
resp.auth = newValue
}
get {
guard let resp = DelegateManager.sharedInstance.responseForTask(task) else { return nil }
return resp.auth
}
}
///This is for doing SSL pinning
public var security: HTTPSecurity? {
set {
guard let resp = DelegateManager.sharedInstance.responseForTask(task) else { return }
resp.security = newValue
}
get {
guard let resp = DelegateManager.sharedInstance.responseForTask(task) else { return nil }
return resp.security
}
}
///This is for monitoring progress
public var progress: ((Float) -> Void)? {
set {
guard let resp = DelegateManager.sharedInstance.responseForTask(task) else { return }
resp.progressHandler = newValue
}
get {
guard let resp = DelegateManager.sharedInstance.responseForTask(task) else { return nil }
return resp.progressHandler
}
}
///the actual task
var task: NSURLSessionDataTask!
private enum State: Int, Comparable {
/// The initial state of an `Operation`.
case Initialized
/**
The `Operation`'s conditions have all been satisfied, and it is ready
to execute.
*/
case Ready
/// The `Operation` is executing.
case Executing
/// The `Operation` has finished executing.
case Finished
/// what state transitions are allowed
func canTransitionToState(target: State) -> Bool {
switch (self, target) {
case (.Initialized, .Ready):
return true
case (.Ready, .Executing):
return true
case (.Ready, .Finished):
return true
case (.Executing, .Finished):
return true
default:
return false
}
}
}
/// Private storage for the `state` property that will be KVO observed. don't set directly!
private var _state = State.Initialized
/// A lock to guard reads and writes to the `_state` property
private let stateLock = NSLock()
// use the KVO mechanism to indicate that changes to "state" affect ready, executing, finished properties
class func keyPathsForValuesAffectingIsReady() -> Set<NSObject> {
return ["state"]
}
class func keyPathsForValuesAffectingIsExecuting() -> Set<NSObject> {
return ["state"]
}
class func keyPathsForValuesAffectingIsFinished() -> Set<NSObject> {
return ["state"]
}
// threadsafe
private var state: State {
get {
return stateLock.withCriticalScope {
_state
}
}
set(newState) {
willChangeValueForKey("state")
stateLock.withCriticalScope { Void -> Void in
guard _state != .Finished else {
print("Invalid! - Attempted to back out of Finished State")
return
}
assert(_state.canTransitionToState(newState), "Performing invalid state transition.")
_state = newState
}
didChangeValueForKey("state")
}
}
/**
creates a new HTTP request.
*/
public init(_ req: NSURLRequest, session: NSURLSession = SharedSession.defaultSession) {
super.init()
task = session.dataTaskWithRequest(req)
DelegateManager.sharedInstance.addResponseForTask(task)
state = .Ready
}
//MARK: Subclassed NSOperation Methods
/// Returns if the task is asynchronous or not. NSURLSessionTask requests are asynchronous.
override public var asynchronous: Bool {
return true
}
// If the operation has been cancelled, "isReady" should return true
override public var ready: Bool {
switch state {
case .Initialized:
return cancelled
case .Ready:
return super.ready || cancelled
default:
return false
}
}
/// Returns if the task is current running.
override public var executing: Bool {
return state == .Executing
}
override public var finished: Bool {
return state == .Finished
}
/**
start/sends the HTTP task with a completionHandler. Use this when *NOT* using an NSOperationQueue.
*/
public func start(completionHandler:((Response) -> Void)) {
onFinish = completionHandler
start()
}
/**
Start the HTTP task. Make sure to set the onFinish closure before calling this to get a response.
*/
override public func start() {
if cancelled {
state = .Finished
return
}
state = .Executing
task.resume()
}
/**
Cancel the running task
*/
override public func cancel() {
task.cancel()
finish()
}
/**
Sets the task to finished.
If you aren't using the DelegateManager, you will have to call this in your delegate's URLSession:dataTask:didCompleteWithError: method
*/
public func finish() {
state = .Finished
}
/**
Check not executing or finished when adding dependencies
*/
override public func addDependency(operation: NSOperation) {
assert(state < .Executing, "Dependencies cannot be modified after execution has begun.")
super.addDependency(operation)
}
/**
Convenience bool to flag as operation userInitiated if necessary
*/
var userInitiated: Bool {
get {
return qualityOfService == .UserInitiated
}
set {
assert(state < State.Executing, "Cannot modify userInitiated after execution has begun.")
qualityOfService = newValue ? .UserInitiated : .Default
}
}
/**
Class method to create a GET request that handles the NSMutableURLRequest and parameter encoding for you.
*/
public class func GET(url: String, parameters: HTTPParameterProtocol? = nil, headers: [String:String]? = nil,
requestSerializer: HTTPSerializeProtocol = HTTPParameterSerializer()) throws -> HTTP {
return try HTTP.New(url, method: .GET, parameters: parameters, headers: headers, requestSerializer: requestSerializer)
}
/**
Class method to create a HEAD request that handles the NSMutableURLRequest and parameter encoding for you.
*/
public class func HEAD(url: String, parameters: HTTPParameterProtocol? = nil, headers: [String:String]? = nil, requestSerializer: HTTPSerializeProtocol = HTTPParameterSerializer()) throws -> HTTP {
return try HTTP.New(url, method: .HEAD, parameters: parameters, headers: headers, requestSerializer: requestSerializer)
}
/**
Class method to create a DELETE request that handles the NSMutableURLRequest and parameter encoding for you.
*/
public class func DELETE(url: String, parameters: HTTPParameterProtocol? = nil, headers: [String:String]? = nil, requestSerializer: HTTPSerializeProtocol = HTTPParameterSerializer()) throws -> HTTP {
return try HTTP.New(url, method: .DELETE, parameters: parameters, headers: headers, requestSerializer: requestSerializer)
}
/**
Class method to create a POST request that handles the NSMutableURLRequest and parameter encoding for you.
*/
public class func POST(url: String, parameters: HTTPParameterProtocol? = nil, headers: [String:String]? = nil, requestSerializer: HTTPSerializeProtocol = HTTPParameterSerializer()) throws -> HTTP {
return try HTTP.New(url, method: .POST, parameters: parameters, headers: headers, requestSerializer: requestSerializer)
}
/**
Class method to create a PUT request that handles the NSMutableURLRequest and parameter encoding for you.
*/
public class func PUT(url: String, parameters: HTTPParameterProtocol? = nil, headers: [String:String]? = nil,
requestSerializer: HTTPSerializeProtocol = HTTPParameterSerializer()) throws -> HTTP {
return try HTTP.New(url, method: .PUT, parameters: parameters, headers: headers, requestSerializer: requestSerializer)
}
/**
Class method to create a PUT request that handles the NSMutableURLRequest and parameter encoding for you.
*/
public class func PATCH(url: String, parameters: HTTPParameterProtocol? = nil, headers: [String:String]? = nil, requestSerializer: HTTPSerializeProtocol = HTTPParameterSerializer()) throws -> HTTP {
return try HTTP.New(url, method: .PATCH, parameters: parameters, headers: headers, requestSerializer: requestSerializer)
}
/**
Class method to create a HTTP request that handles the NSMutableURLRequest and parameter encoding for you.
*/
public class func New(url: String, method: HTTPVerb, parameters: HTTPParameterProtocol? = nil, headers: [String:String]? = nil, requestSerializer: HTTPSerializeProtocol = HTTPParameterSerializer()) throws -> HTTP {
guard let req = NSMutableURLRequest(urlString: url) else { throw HTTPOptError.InvalidRequest }
if let handler = DelegateManager.sharedInstance.requestHandler {
handler(req)
}
req.verb = method
if let params = parameters {
try requestSerializer.serialize(req, parameters: params)
}
if let heads = headers {
for (key,value) in heads {
req.addValue(value, forHTTPHeaderField: key)
}
}
return HTTP(req)
}
/**
Set the global auth handler
*/
public class func globalAuth(handler: ((NSURLAuthenticationChallenge) -> NSURLCredential?)?) {
DelegateManager.sharedInstance.auth = handler
}
/**
Set the global security handler
*/
public class func globalSecurity(security: HTTPSecurity?) {
DelegateManager.sharedInstance.security = security
}
/**
Set the global request handler
*/
public class func globalRequest(handler: ((NSMutableURLRequest) -> Void)?) {
DelegateManager.sharedInstance.requestHandler = handler
}
}
// Simple operator functions to simplify the assertions used above.
private func <(lhs: HTTP.State, rhs: HTTP.State) -> Bool {
return lhs.rawValue < rhs.rawValue
}
private func ==(lhs: HTTP.State, rhs: HTTP.State) -> Bool {
return lhs.rawValue == rhs.rawValue
}
// Lock for getting / setting state safely
extension NSLock {
func withCriticalScope<T>(@noescape block: Void -> T) -> T {
lock()
let value = block()
unlock()
return value
}
}
/**
Absorb all the delegates methods of NSURLSession and forwards them to pretty closures.
This is basically the sin eater for NSURLSession.
*/
class DelegateManager: NSObject, NSURLSessionDataDelegate {
//the singleton to handle delegate needs of NSURLSession
static let sharedInstance = DelegateManager()
/// this is for global authenication handling
var auth:((NSURLAuthenticationChallenge) -> NSURLCredential?)?
///This is for global SSL pinning
var security: HTTPSecurity?
/// this is for global request handling
var requestHandler:((NSMutableURLRequest) -> Void)?
var taskMap = Dictionary<Int,Response>()
//"install" a task by adding the task to the map and setting the completion handler
func addTask(task: NSURLSessionTask, completionHandler:((Response) -> Void)) {
addResponseForTask(task)
if let resp = responseForTask(task) {
resp.completionHandler = completionHandler
}
}
//"remove" a task by removing the task from the map
func removeTask(task: NSURLSessionTask) {
taskMap.removeValueForKey(task.taskIdentifier)
}
//add the response task
func addResponseForTask(task: NSURLSessionTask) {
if taskMap[task.taskIdentifier] == nil {
taskMap[task.taskIdentifier] = Response()
}
}
//get the response object for the task
func responseForTask(task: NSURLSessionTask) -> Response? {
return taskMap[task.taskIdentifier]
}
//handle getting data
func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveData data: NSData) {
addResponseForTask(dataTask)
guard let resp = responseForTask(dataTask) else { return }
resp.collectData.appendData(data)
if resp.progressHandler != nil { //don't want the extra cycles for no reason
guard let taskResp = dataTask.response else { return }
progressHandler(resp, expectedLength: taskResp.expectedContentLength, currentLength: Int64(resp.collectData.length))
}
}
//handle task finishing
func URLSession(session: NSURLSession, task: NSURLSessionTask, didCompleteWithError error: NSError?) {
guard let resp = responseForTask(task) else { return }
resp.error = error
if let hresponse = task.response as? NSHTTPURLResponse {
resp.headers = hresponse.allHeaderFields as? Dictionary<String,String>
resp.mimeType = hresponse.MIMEType
resp.suggestedFilename = hresponse.suggestedFilename
resp.statusCode = hresponse.statusCode
resp.URL = hresponse.URL
}
if let code = resp.statusCode where resp.statusCode > 299 {
resp.error = createError(code)
}
if let handler = resp.completionHandler {
handler(resp)
}
removeTask(task)
}
//handle authenication
func URLSession(session: NSURLSession, task: NSURLSessionTask, didReceiveChallenge challenge: NSURLAuthenticationChallenge, completionHandler: (NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void) {
var sec = security
var au = auth
if let resp = responseForTask(task) {
if let s = resp.security {
sec = s
}
if let a = resp.auth {
au = a
}
}
if let sec = sec where challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust {
let space = challenge.protectionSpace
if let trust = space.serverTrust {
if sec.isValid(trust, domain: space.host) {
completionHandler(.UseCredential, NSURLCredential(trust: trust))
return
}
}
completionHandler(.CancelAuthenticationChallenge, nil)
return
} else if let a = au {
let cred = a(challenge)
if let c = cred {
completionHandler(.UseCredential, c)
return
}
completionHandler(.RejectProtectionSpace, nil)
return
}
completionHandler(.PerformDefaultHandling, nil)
}
//upload progress
func URLSession(session: NSURLSession, task: NSURLSessionTask, didSendBodyData bytesSent: Int64, totalBytesSent: Int64, totalBytesExpectedToSend: Int64) {
guard let resp = responseForTask(task) else { return }
progressHandler(resp, expectedLength: totalBytesExpectedToSend, currentLength: totalBytesSent)
}
//download progress
func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
guard let resp = responseForTask(downloadTask) else { return }
progressHandler(resp, expectedLength: totalBytesExpectedToWrite, currentLength: bytesWritten)
}
//handle progress
func progressHandler(response: Response, expectedLength: Int64, currentLength: Int64) {
guard let handler = response.progressHandler else { return }
let slice = Float(1.0)/Float(expectedLength)
handler(slice*Float(currentLength))
}
/**
Create an error for response you probably don't want (400-500 HTTP responses for example).
-parameter code: Code for error.
-returns An NSError.
*/
private func createError(code: Int) -> NSError {
let text = HTTPStatusCode(statusCode: code).statusDescription
return NSError(domain: "HTTP", code: code, userInfo: [NSLocalizedDescriptionKey: text])
}
}
/**
Handles providing singletons of NSURLSession.
*/
class SharedSession {
static let defaultSession = NSURLSession(configuration: NSURLSessionConfiguration.defaultSessionConfiguration(),
delegate: DelegateManager.sharedInstance, delegateQueue: nil)
static let ephemeralSession = NSURLSession(configuration: NSURLSessionConfiguration.ephemeralSessionConfiguration(),
delegate: DelegateManager.sharedInstance, delegateQueue: nil)
}
|
mit
|
6b5fc186876004249ee45f1705290ff0
| 33.662139 | 219 | 0.665197 | 4.995106 | false | false | false | false |
necrowman/CRLAlamofireFuture
|
Examples/SimpleTvOSCarthage/Carthage/Checkouts/ExecutionContext/ExecutionContext/CustomExecutionContext.swift
|
111
|
1814
|
//===--- CustomExecutionContext.swift ------------------------------------------------------===//
//Copyright (c) 2016 Daniel Leping (dileping)
//
//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at
//
//http://www.apache.org/licenses/LICENSE-2.0
//
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
//limitations under the License.
//===----------------------------------------------------------------------===//
import Foundation
import Foundation3
import Boilerplate
public class CustomExecutionContext : ExecutionContextBase, ExecutionContextType {
let id = NSUUID()
let executor:Executor
public init(executor:Executor) {
self.executor = executor
}
public func async(task:SafeTask) {
executor {
let context = currentContext.value
defer {
currentContext.value = context
}
currentContext.value = self
task()
}
}
public func async(after:Timeout, task:SafeTask) {
async {
Thread.sleep(after)
task()
}
}
public func sync<ReturnType>(task:() throws -> ReturnType) rethrows -> ReturnType {
return try syncThroughAsync(task)
}
public func isEqualTo(other: NonStrictEquatable) -> Bool {
guard let other = other as? CustomExecutionContext else {
return false
}
return id.isEqual(other.id)
}
}
|
mit
|
614dbc8cac3fb7936f51cedd2c4d8c95
| 30.293103 | 97 | 0.594267 | 5.168091 | false | false | false | false |
Piwigo/Piwigo-Mobile
|
piwigoKit/Supporting Files/UserDefaults+AppGroups.swift
|
1
|
2567
|
//
// UserDefaults+AppGroups.swift
// piwigoKit
//
// Created by Eddy Lelièvre-Berna on 23/05/2021.
// Copyright © 2021 Piwigo.org. All rights reserved.
//
import Foundation
extension UserDefaults {
// We use different App Groups:
/// - Development: one chosen by the developer
/// - Release: the official group.org.piwigo
public static let appGroup = { () -> String in
let bundleID = Bundle.main.bundleIdentifier!.components(separatedBy: ".")
let pos = bundleID.firstIndex(of: "piwigo")
let mainBundleID = bundleID[0...pos!].joined(separator: ".")
return "group." + mainBundleID
}()
public static let dataSuite = { () -> UserDefaults in
guard let dataSuite = UserDefaults(suiteName: appGroup) else {
fatalError("Could not load UserDefaults for app group \(appGroup)")
}
return dataSuite
}()
}
// A type safe property wrapper to set and get values from UserDefaults with support for defaults values.
/// https://github.com/guillermomuntaner/Burritos/blob/master/Sources/UserDefault/UserDefault.swift
@propertyWrapper
public struct UserDefault<Value: PropertyListValue> {
public let defaultKey: String
public let defaultValue: Value
public var userDefaults: UserDefaults
public init(_ key: String, defaultValue: Value, userDefaults: UserDefaults = .standard) {
self.defaultKey = key
self.defaultValue = defaultValue
self.userDefaults = userDefaults
}
public var wrappedValue: Value {
get {
return userDefaults.object(forKey: defaultKey) as? Value ?? defaultValue
}
set {
userDefaults.set(newValue, forKey: defaultKey)
}
}
}
// A type than can be stored in `UserDefaults`.
//
/// - From UserDefaults;
/// The value parameter can be only property list objects: NSData, NSString, NSNumber, NSDate, NSArray, or NSDictionary.
/// For NSArray and NSDictionary objects, their contents must be property list objects. For more information, see What is a
/// Property List? in Property List Programming Guide.public protocol PropertyListValue {}
public protocol PropertyListValue {}
extension String: PropertyListValue {}
extension NSString: PropertyListValue {}
extension Bool: PropertyListValue {}
extension Int: PropertyListValue {}
extension Int16: PropertyListValue {}
extension UInt: PropertyListValue {}
extension UInt16: PropertyListValue {}
extension UInt32: PropertyListValue {}
extension TimeInterval: PropertyListValue {}
|
mit
|
f0e9f5831b856509a597fe81fad88a2a
| 33.2 | 123 | 0.699805 | 4.794393 | false | false | false | false |
imitationgame/pokemonpassport
|
pokepass/Model/Projects/MProjectsDetailItemSpeed.swift
|
1
|
1356
|
import UIKit
class MProjectsDetailItemSpeed:MProjectsDetailItem
{
let index:Int
let title:String
let maxDistance:Double
private let kCellHeight:CGFloat = 44
private let kSelectable:Bool = true
init(index:Int, title:String, maxDistance:Double)
{
self.index = index
self.title = title
self.maxDistance = maxDistance
let reusableIdentifier:String = VProjectsDetailCellSpeed.reusableIdentifier
super.init(reusableIdentifier:reusableIdentifier, cellHeight:kCellHeight, selectable:kSelectable)
}
override func config(cell:VProjectsDetailCell, controller:CProjectsDetail)
{
let cellSpeed:VProjectsDetailCellSpeed = cell as! VProjectsDetailCellSpeed
cellSpeed.label.text = title
if controller.model.sectionSpeed.selectedItem === self
{
cellSpeed.backgroundColor = UIColor.white
cellSpeed.label.textColor = UIColor.main
}
else
{
cellSpeed.backgroundColor = UIColor(white:1, alpha:0.2)
cellSpeed.label.textColor = UIColor.main.withAlphaComponent(0.4)
}
}
override func selected(controller:CProjectsDetail)
{
controller.model.sectionSpeed.selectedItem = self
controller.viewDetail.collection.reloadData()
}
}
|
mit
|
6bea72c88460528dbdcb78ca11069705
| 30.534884 | 105 | 0.673304 | 4.860215 | false | false | false | false |
blockchain/My-Wallet-V3-iOS
|
Modules/FeatureOpenBanking/Sources/FeatureOpenBankingUI/View/InstitutionList.swift
|
1
|
8393
|
// Copyright © Blockchain Luxembourg S.A. All rights reserved.
import BlockchainUI
import FeatureOpenBankingDomain
import SwiftUI
import UIComponentsKit
// swiftlint:disable:next type_name
typealias BlockchainComponentLibrarySecondaryButton = BlockchainComponentLibrary.SecondaryButton
public struct InstitutionListState: Equatable, NavigationState {
public var route: RouteIntent<InstitutionListRoute>?
var result: Result<OpenBanking.BankAccount, OpenBanking.Error>?
var selection: BankState?
}
public enum InstitutionListAction: Hashable, NavigationAction, FailureAction {
case route(RouteIntent<InstitutionListRoute>?)
case failure(OpenBanking.Error)
case fetch
case fetched(OpenBanking.BankAccount)
case select(OpenBanking.BankAccount, OpenBanking.Institution)
case showTransferDetails
case bank(BankAction)
case dismiss
}
public enum InstitutionListRoute: CaseIterable, NavigationRoute {
case bank
@ViewBuilder
public func destination(in store: Store<InstitutionListState, InstitutionListAction>) -> some View {
switch self {
case .bank:
IfLetStore(
store.scope(state: \.selection, action: InstitutionListAction.bank),
then: BankView.init(store:)
)
}
}
}
public let institutionListReducer = Reducer<InstitutionListState, InstitutionListAction, OpenBankingEnvironment>
.combine(
bankReducer
.optional()
.pullback(
state: \.selection,
action: /InstitutionListAction.bank,
environment: \.environment
),
.init { state, action, environment in
switch action {
case .route(let route):
state.route = route
return .none
case .fetch:
return environment.openBanking
.createBankAccount()
.receive(on: environment.scheduler)
.map(InstitutionListAction.fetched)
.catch(InstitutionListAction.failure)
.eraseToEffect()
case .fetched(let account):
state.result = .success(account)
return .none
case .showTransferDetails:
return .fireAndForget(environment.showTransferDetails)
case .select(let account, let institution):
state.selection = .init(
data: .init(
account: account,
action: .link(institution: institution)
)
)
return .merge(
.navigate(to: .bank),
.fireAndForget {
environment.analytics.record(
event: .linkBankSelected(institution: institution.name, account: account)
)
}
)
case .bank(.cancel):
state.route = nil
state.result = nil
return Effect(value: .fetch)
case .bank:
return .none
case .dismiss:
return .fireAndForget(environment.dismiss)
case .failure(let error):
state.result = .failure(error)
return .none
}
}
)
public struct InstitutionList: View {
@BlockchainApp var app
private let store: Store<InstitutionListState, InstitutionListAction>
@State private var loading: CGFloat = 44
@State private var padding: CGFloat = 40
public init(store: Store<InstitutionListState, InstitutionListAction>) {
self.store = store
}
public var body: some View {
WithViewStore(store.scope(state: \.result)) { viewStore in
ZStack {
switch viewStore.state {
case .success(let account) where account.attributes.institutions != nil:
SearchableList(
account.attributes.institutions.or(default: []),
placeholder: Localization.InstitutionList.search,
content: { bank in
Item(bank) {
viewStore.send(.select(account, bank))
}
},
empty: {
NoSearchResults
}
).background(Color.semantic.background)
case .failure(let error):
InfoView(
.init(
media: .bankIcon,
overlay: .init(media: .error),
title: Localization.Error.title,
subtitle: "\(error.description)"
)
)
default:
ProgressView(value: 0.25)
.frame(width: 12.vmin, alignment: .center)
.aspectRatio(1, contentMode: .fit)
.progressViewStyle(IndeterminateProgressStyle())
.onAppear { viewStore.send(.fetch) }
}
}
.navigationRoute(in: store, environmentObject: app)
.navigationTitle(Localization.InstitutionList.title)
.whiteNavigationBarStyle()
.trailingNavigationButton(.close) {
viewStore.send(.dismiss)
}
}
}
@ViewBuilder var NoSearchResults: some View {
WithViewStore(store) { view in
Spacer()
Text(Localization.InstitutionList.Error.couldNotFindBank)
.typography(.paragraph1)
.foregroundColor(.textDetail)
.frame(alignment: .center)
.multilineTextAlignment(.center)
.padding([.leading, .trailing], 12.5.vmin)
Spacer()
BlockchainComponentLibrarySecondaryButton(title: Localization.InstitutionList.Error.showTransferDetails) {
view.send(.showTransferDetails)
}
.padding(10.5.vmin)
}
}
}
extension InstitutionList {
public struct Item: View, Identifiable {
let institution: OpenBanking.Institution
let action: () -> Void
public var id: Identity<OpenBanking.Institution> { institution.id }
private var title: String { institution.fullName }
private var image: URL? {
institution.media.first(where: { $0.type == .icon })?.source
?? institution.media.first?.source
}
init(_ institution: OpenBanking.Institution, action: @escaping () -> Void) {
self.institution = institution
self.action = action
}
public var body: some View {
PrimaryRow(
title: title,
leading: {
Group {
if let image = image {
ImageResourceView(
url: image,
placeholder: { Color.semantic.background }
)
.resizable()
.aspectRatio(contentMode: .fit)
} else {
Color.viewPrimaryBackground
}
}
.frame(width: 12.vw, height: 12.vw, alignment: .center)
},
action: action
)
.frame(height: 9.5.vh)
.background(Color.semantic.background)
}
}
}
extension OpenBanking.Institution: CustomStringConvertible, Identifiable {
public var description: String { fullName }
}
#if DEBUG
struct InstitutionList_Previews: PreviewProvider {
static var previews: some View {
PrimaryNavigationView {
InstitutionList(
store: Store<InstitutionListState, InstitutionListAction>(
initialState: InstitutionListState(),
reducer: institutionListReducer,
environment: .mock
)
)
}
InstitutionList.Item(.mock, action: {})
}
}
#endif
|
lgpl-3.0
|
ac25b815390e5e13e2283af7aa20cd82
| 32.975709 | 118 | 0.52562 | 5.424693 | false | false | false | false |
Cacodaimon/GhostText-for-SublimeText
|
safari/GhostText/ViewController.swift
|
2
|
1561
|
import Cocoa
import SafariServices.SFSafariApplication
import SafariServices.SFSafariExtensionManager
let appName = "GhostText"
let extensionBundleIdentifier = "com.fregante.GhostText.Extension"
final class ViewController: NSViewController {
@IBOutlet private var appNameLabel: NSTextField!
override func viewDidLoad() {
super.viewDidLoad()
appNameLabel.stringValue = appName
SFSafariExtensionManager.getStateOfSafariExtension(withIdentifier: extensionBundleIdentifier) { (state, error) in
guard let state = state, error == nil else {
// Insert code to inform the user that something went wrong.
return
}
DispatchQueue.main.async { [self] in
if (state.isEnabled) {
appNameLabel.stringValue = "\(appName)'s extension is currently on."
} else {
appNameLabel.stringValue = "\(appName)'s extension is currently off. You can turn it on in Safari Extensions preferences."
}
}
}
}
@IBAction private func openSafariExtensionPreferences(_ sender: AnyObject?) {
SFSafariApplication.showPreferencesForExtension(withIdentifier: extensionBundleIdentifier) { error in
guard error == nil else {
// Insert code to inform the user that something went wrong.
return
}
DispatchQueue.main.async {
NSApplication.shared.terminate(nil)
}
}
}
}
|
mit
|
4e2cdc2ba0bb0fdb98e3c0ca51666ca7
| 34.477273 | 142 | 0.627803 | 5.615108 | false | false | false | false |
huonw/swift
|
stdlib/public/SDK/ObjectiveC/ObjectiveC.swift
|
2
|
6486
|
//===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
@_exported
import ObjectiveC
import _SwiftObjectiveCOverlayShims
//===----------------------------------------------------------------------===//
// Objective-C Primitive Types
//===----------------------------------------------------------------------===//
/// The Objective-C BOOL type.
///
/// On 64-bit iOS, the Objective-C BOOL type is a typedef of C/C++
/// bool. Elsewhere, it is "signed char". The Clang importer imports it as
/// ObjCBool.
@_fixed_layout
public struct ObjCBool : ExpressibleByBooleanLiteral {
#if os(macOS) || (os(iOS) && (arch(i386) || arch(arm)))
// On OS X and 32-bit iOS, Objective-C's BOOL type is a "signed char".
var _value: Int8
init(_ value: Int8) {
self._value = value
}
public init(_ value: Bool) {
self._value = value ? 1 : 0
}
#else
// Everywhere else it is C/C++'s "Bool"
var _value: Bool
public init(_ value: Bool) {
self._value = value
}
#endif
/// The value of `self`, expressed as a `Bool`.
public var boolValue: Bool {
#if os(macOS) || (os(iOS) && (arch(i386) || arch(arm)))
return _value != 0
#else
return _value
#endif
}
/// Create an instance initialized to `value`.
@_transparent
public init(booleanLiteral value: Bool) {
self.init(value)
}
}
extension ObjCBool : CustomReflectable {
/// Returns a mirror that reflects `self`.
public var customMirror: Mirror {
return Mirror(reflecting: boolValue)
}
}
extension ObjCBool : CustomStringConvertible {
/// A textual representation of `self`.
public var description: String {
return self.boolValue.description
}
}
// Functions used to implicitly bridge ObjCBool types to Swift's Bool type.
public // COMPILER_INTRINSIC
func _convertBoolToObjCBool(_ x: Bool) -> ObjCBool {
return ObjCBool(x)
}
public // COMPILER_INTRINSIC
func _convertObjCBoolToBool(_ x: ObjCBool) -> Bool {
return x.boolValue
}
/// The Objective-C SEL type.
///
/// The Objective-C SEL type is typically an opaque pointer. Swift
/// treats it as a distinct struct type, with operations to
/// convert between C strings and selectors.
///
/// The compiler has special knowledge of this type.
@_fixed_layout
public struct Selector : ExpressibleByStringLiteral {
var ptr: OpaquePointer
/// Create a selector from a string.
public init(_ str : String) {
ptr = str.withCString { sel_registerName($0).ptr }
}
// FIXME: Fast-path this in the compiler, so we don't end up with
// the sel_registerName call at compile time.
/// Create an instance initialized to `value`.
public init(stringLiteral value: String) {
self = sel_registerName(value)
}
}
extension Selector : Equatable, Hashable {
public static func ==(lhs: Selector, rhs: Selector) -> Bool {
return sel_isEqual(lhs, rhs)
}
/// The hash value.
///
/// **Axiom:** `x == y` implies `x.hashValue == y.hashValue`
///
/// - Note: the hash value is not guaranteed to be stable across
/// different invocations of the same program. Do not persist the
/// hash value across program runs.
public var hashValue: Int {
return ptr.hashValue
}
}
extension Selector : CustomStringConvertible {
/// A textual representation of `self`.
public var description: String {
return String(_sel: self)
}
}
extension String {
/// Construct the C string representation of an Objective-C selector.
public init(_sel: Selector) {
// FIXME: This misses the ASCII optimization.
self = String(cString: sel_getName(_sel))
}
}
extension Selector : CustomReflectable {
/// Returns a mirror that reflects `self`.
public var customMirror: Mirror {
return Mirror(reflecting: String(_sel: self))
}
}
//===----------------------------------------------------------------------===//
// NSZone
//===----------------------------------------------------------------------===//
@_fixed_layout
public struct NSZone {
var pointer: OpaquePointer
}
// Note: NSZone becomes Zone in Swift 3.
typealias Zone = NSZone
//===----------------------------------------------------------------------===//
// @autoreleasepool substitute
//===----------------------------------------------------------------------===//
public func autoreleasepool<Result>(
invoking body: () throws -> Result
) rethrows -> Result {
let pool = _swift_objc_autoreleasePoolPush()
defer {
_swift_objc_autoreleasePoolPop(pool)
}
return try body()
}
//===----------------------------------------------------------------------===//
// Mark YES and NO unavailable.
//===----------------------------------------------------------------------===//
@available(*, unavailable, message: "Use 'Bool' value 'true' instead")
public var YES: ObjCBool {
fatalError("can't retrieve unavailable property")
}
@available(*, unavailable, message: "Use 'Bool' value 'false' instead")
public var NO: ObjCBool {
fatalError("can't retrieve unavailable property")
}
//===----------------------------------------------------------------------===//
// NSObject
//===----------------------------------------------------------------------===//
// NSObject implements Equatable's == as -[NSObject isEqual:]
// NSObject implements Hashable's hashValue() as -[NSObject hash]
// FIXME: what about NSObjectProtocol?
extension NSObject : Equatable, Hashable {
public static func == (lhs: NSObject, rhs: NSObject) -> Bool {
return lhs.isEqual(rhs)
}
/// The hash value.
///
/// **Axiom:** `x == y` implies `x.hashValue == y.hashValue`
///
/// - Note: the hash value is not guaranteed to be stable across
/// different invocations of the same program. Do not persist the
/// hash value across program runs.
@objc
open var hashValue: Int {
return hash
}
}
extension NSObject : CVarArg {
/// Transform `self` into a series of machine words that can be
/// appropriately interpreted by C varargs
public var _cVarArgEncoding: [Int] {
_autorelease(self)
return _encodeBitsAsWords(self)
}
}
|
apache-2.0
|
2ae2954eddcf956a67a68ecfadcaad18
| 27.572687 | 80 | 0.583256 | 4.577276 | false | false | false | false |
petrusalin/APLfm
|
APLfm/Classes/LastfmAuthRequest.swift
|
1
|
2071
|
//
// LastfmAuthRequest.swift
// Kindio
//
// Created by Alin Petrus on 5/10/16.
// Copyright © 2016 Alin Petrus. All rights reserved.
//
import UIKit
/// Convenience class used to obtain an auth request. Use this one instead of using the signed/unsigned classes for an auth request
public class LastfmAuthRequest: LastfmRequest {
internal var username : String!
internal var password : String!
override internal var baseURL : String {
return "https://ws.audioscrobbler.com/2.0/"
}
/*!
Designated initializer for the class
- parameter credential: An instance of LastfmCredential
- parameter username: Lastfm user handle
- parameter password: Lastfm user password
- returns: A request of the class ready to be executed
*/
public init(credential: LastfmCredential, username: String, password: String) {
self.username = username
self.password = password
super.init(credential: credential)
self.lastfmMethod = LastfmMethod.authMethod(self.credential.appKey)
self.lastfmMethod!.parameters[LastfmKeys.Password.rawValue] = password;
self.lastfmMethod!.parameters[LastfmKeys.Username.rawValue] = username
self.prepareForExecute()
}
override public func executeWithCompletionBlock(completion: (response: AnyObject?, error: NSError?) -> Void) {
super.executeWithCompletionBlock { (response, error) in
if (error != nil) {
completion(response: nil, error: error)
} else {
if let dict = response as? [String : AnyObject] {
if let sessionDict = dict["session"] as? [String : AnyObject] {
completion(response: sessionDict, error: nil)
} else {
completion(response: nil, error: nil)
}
} else {
completion(response: nil, error: nil)
}
}
}
}
}
|
mit
|
d8ea97338cf8e5b280e405261e99c50d
| 33.5 | 131 | 0.601449 | 4.726027 | false | false | false | false |
zmian/xcore.swift
|
Tests/XcoreTests/ArrayTests.swift
|
1
|
5815
|
//
// Xcore
// Copyright © 2019 Xcore
// MIT license, see LICENSE file for details
//
import XCTest
@testable import Xcore
final class ArrayTests: TestCase {
func testSplitBy() {
let array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
let chunks = array.splitBy(5)
let expected = [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12]]
XCTAssertEqual(chunks, expected)
}
func testSortByPreferredOrder() {
let preferredOrder = ["Z", "A", "B", "C", "D"]
var alphabets = ["D", "C", "B", "A", "Z", "W"]
alphabets.sort(by: preferredOrder)
let expected = ["Z", "A", "B", "C", "D", "W"]
XCTAssertEqual(alphabets, expected)
}
func testSortedByPreferredOrder() {
let preferredOrder = ["Z", "A", "B", "C", "D"]
let alphabets = ["D", "C", "B", "A", "Z", "W"]
let sorted = alphabets.sorted(by: preferredOrder)
let expected = ["Z", "A", "B", "C", "D", "W"]
XCTAssertEqual(sorted, expected)
XCTAssertNotEqual(sorted, alphabets)
}
func testRawValues() {
let values = [
SomeType(rawValue: "Hello"),
SomeType(rawValue: "World"),
SomeType(rawValue: "!")
]
let expectedRawValues = [
"Hello",
"World",
"!"
]
XCTAssertEqual(values.rawValues, expectedRawValues)
}
func testContains() {
let instances = [UIView(), UIImageView()]
let result = instances.contains(any: [UIImageView.self, UILabel.self])
XCTAssertEqual(result, true)
XCTAssertEqual(instances.contains(any: [UILabel.self]), false)
}
func testRandomElement() {
let values = [132, 2432, 35435, 455]
let randomValue = values.randomElement()
XCTAssert(values.contains(randomValue))
}
func testRandomElements() {
let values = [132, 2432, 35435, 455]
let randomValue1 = values.randomElements(length: 17)
let randomValue2 = values.randomElements(length: 2)
XCTAssertEqual(randomValue1.count, values.count)
XCTAssertEqual(randomValue2.count, 2)
}
func testEmptyRandomElements() {
let values: [Int] = []
let randomValue1 = values.randomElements(length: 17)
let randomValue2 = values.randomElements(length: 2)
XCTAssertEqual(randomValue1.count, values.count)
XCTAssertEqual(randomValue2.count, 0)
}
func testFirstElement() {
let value: [Any] = ["232", 12, 2, 11.0, "hello"]
let resultString = value.firstElement(type: String.self)
let resultInt = value.firstElement(type: Int.self)
let resultDouble = value.firstElement(type: Double.self)
let resultCGFloat = value.firstElement(type: CGFloat.self)
XCTAssertEqual(resultString!, "232")
XCTAssertEqual(resultInt!, 12)
XCTAssertEqual(resultDouble!, 11)
XCTAssertNil(resultCGFloat)
}
func testLastElement() {
let value: [Any] = ["232", 12, 2, 11.0, "hello"]
let resultString = value.lastElement(type: String.self)
let resultInt = value.lastElement(type: Int.self)
let resultDouble = value.lastElement(type: Double.self)
let resultCGFloat = value.lastElement(type: CGFloat.self)
XCTAssertEqual(resultString!, "hello")
XCTAssertEqual(resultInt!, 2)
XCTAssertEqual(resultDouble!, 11)
XCTAssertNil(resultCGFloat)
}
func testFirstIndex() {
let tag1View = UIView().apply { $0.tag = 1 }
let tag2View = UIView().apply { $0.tag = 2 }
let tag1Label = UILabel().apply { $0.tag = 1 }
let tag2Label = UILabel().apply { $0.tag = 2 }
let value: [NSObject] = [NSString("232"), tag1View, tag2View, tag1Label, tag2Label, NSString("hello")]
let resultNSString = value.firstIndex(of: NSString.self)
let resultUIView = value.firstIndex(of: UIView.self)
let resultUILabel = value.firstIndex(of: UILabel.self)
let resultUIViewController = value.firstIndex(of: UIViewController.self)
XCTAssertEqual(resultNSString!, 0)
XCTAssertEqual(resultUIView!, 1)
XCTAssertEqual(resultUILabel!, 3)
XCTAssertNil(resultUIViewController)
}
func testLastIndex() {
let tag1View = UIView().apply { $0.tag = 1 }
let tag2View = UIView().apply { $0.tag = 2 }
let tag1Label = UILabel().apply { $0.tag = 1 }
let tag2Label = UILabel().apply { $0.tag = 2 }
let value: [NSObject] = [NSString("232"), tag1View, tag2View, tag1Label, tag2Label, NSString("hello")]
let resultNSString = value.lastIndex(of: NSString.self)
let resultUIView = value.lastIndex(of: UIView.self)
let resultUILabel = value.lastIndex(of: UILabel.self)
let resultUIViewController = value.lastIndex(of: UIViewController.self)
XCTAssertEqual(resultNSString!, 5)
XCTAssertEqual(resultUIView!, 4) // UILabel is subclass of UIView
XCTAssertEqual(resultUILabel!, 4)
XCTAssertNil(resultUIViewController)
}
func testJoined() {
let label1 = UILabel().apply {
$0.text = "Hello"
}
let label2 = UILabel()
let label3 = UILabel().apply {
$0.text = " "
}
let button = UIButton().apply {
$0.setTitle("World!", for: .normal)
}
let value1 = [label1.text, label2.text, label3.text, button.title(for: .normal)].joined(separator: ", ")
XCTAssertEqual(value1, "Hello, World!")
let value2 = [label1.text, label2.text, label3.text, button.title(for: .normal)].joined()
XCTAssertEqual(value2, "HelloWorld!")
}
}
private struct SomeType: RawRepresentable {
let rawValue: String
}
|
mit
|
625d1c9ce1de9aa84c625fd5c19ed077
| 33.814371 | 112 | 0.603371 | 4.015193 | false | true | false | false |
FengDeng/RxGitHubAPI
|
RxGitHubAPI/RxGitHubAPI/YYRepository.swift
|
1
|
3283
|
//
// YYRepository.swift
// RxGitHub
//
// Created by 邓锋 on 16/1/20.
// Copyright © 2016年 fengdeng. All rights reserved.
//
import Foundation
public class YYRepository : NSObject{
public private(set) var id = 0
public private(set) var owner = YYUser()
public private(set) var name = ""
public private(set) var full_name = ""
public private(set) var _description = ""
public private(set) var _private = false
public private(set) var fork = false
public private(set) var html_url = ""
public private(set) var clone_url = ""
public private(set) var git_url = ""
public private(set) var mirror_url = ""
public private(set) var ssh_url = ""
public private(set) var svn_url = ""
public private(set) var homepage = ""
public private(set) var language = ""
public private(set) var forks_count = 0
public private(set) var stargazers_count = 0
public private(set) var watchers_count = 0
public private(set) var size = 0
public private(set) var default_branch = ""
public private(set) var open_issues_count = 0
public private(set) var has_issues = false
public private(set) var has_downloads = false
public private(set) var has_wiki = false
public private(set) var has_pages = false
public private(set) var pushed_at = ""
public private(set) var created_at = ""
public private(set) var updated_at = ""
public private(set) var watchers = 0
public private(set) var open_issues = 0
public private(set) var permissions = YYPermission()
public private(set) var parent : YYRepository?
public private(set) var source : YYRepository?
public override static func mj_replacedKeyFromPropertyName() -> [NSObject : AnyObject]! {
return ["_description":"description","_private":"private"]
}
//api
var url = ""
var archive_url = ""
var assignees_url = ""
var blobs_url = ""
var branches_url = ""
var collaborators_url = ""
var comments_url = ""
var commits_url = ""
var compare_url = ""
var contents_url = ""
var contributors_url = ""
var deployments_url = ""
var downloads_url = ""
var events_url = ""
var forks_url = ""
var git_commits_url = ""
var git_refs_url = ""
var git_tags_url = ""
var hooks_url = ""
var issue_comment_url = ""
var issue_events_url = ""
var issues_url = ""
var keys_url = ""
var labels_url = ""
var languages_url = ""
var merges_url = ""
var milestones_url = ""
var notifications_url = ""
var pulls_url = ""
var releases_url = ""
var stargazers_url = ""
var statuses_url = ""
var subscribers_url = ""
var subscription_url = ""
var tags_url = ""
var teams_url = ""
var trees_url = ""
//combination api
var action_star_url : String{
get{
return domain + "/user/starred/\(self.full_name)"
}
}
var action_watch_url : String{
get{
return domain + "/user/subscriptions/\(self.full_name)"
}
}
}
public class YYPermission : NSObject{
public private(set) var admin = false
public private(set) var push = false
public private(set) var pull = false
}
|
apache-2.0
|
38ff381e9e8eedcb5ad159d54e20b32a
| 28.25 | 93 | 0.607753 | 3.827103 | false | false | false | false |
crossroadlabs/ExpressCommandLine
|
Package.swift
|
1
|
1324
|
//===--- Package.swift ----------------------------------------------------------===//
//Copyright (c) 2015-2016 Daniel Leping (dileping)
//
//This file is part of Swift Express Command Line
//
//Swift Express Command Line 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.
//
//Swift Express Command Line 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 Swift Express Command Line. If not, see <http://www.gnu.org/licenses/>.
//
//===---------------------------------------------------------------------------===//
import PackageDescription
let package = Package(
name: "swift-express",
targets: [
Target(
name: "swift-express"
)
],
dependencies: [
.Package(url: "https://github.com/crossroadlabs/Commandant.git", majorVersion: 0),
.Package(url: "https://github.com/crossroadlabs/Regex.git", majorVersion: 0)
]
)
|
gpl-3.0
|
5a8f32700207e4ea8dd3cd758fe74da5
| 37.941176 | 90 | 0.626888 | 4.549828 | false | false | false | false |
cactis/SwiftEasyKit
|
Source/Classes/DefaultViewController.swift
|
1
|
7203
|
//
// DefaultViewController.swift
import UIKit
open class DefaultViewController: UIViewController, UITextFieldDelegate, UITextViewDelegate {
public var swipeRight: UISwipeGestureRecognizer!
public var didFixedConstraints = false
public var keyboardSize: CGSize! = .zero
public var textViewShouldReturn = false
public var tabBarHidden = false { didSet { setTabBarStatus() } }
public var onDismissViewController: () -> () = { }// auto run
public var didDismissViewController: (_ action: DismissType) -> () = { _ in } // call by target
public var didLoadData: () -> () = {}
public var onViewDidLoad: (_ vc: UIViewController) -> () = {_ in}
override open func viewDidLoad() {
super.viewDidLoad()
onViewDidLoad(self)
navigationItem.title = navigationItem.title ?? K.App.name
layoutUI() // 建立 UI 框架。結束時 loadData() 載入動態資料
styleUI() // 視覺化 UI 框架
bindUI() // 綁定 UI 事件
bindData() // binding data
_autoRun()
}
open func _autoRun() {}
open override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
// appDelegate().preLoad()
}
override open func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
onDismissViewController()
}
open func layoutUI() {
view.setNeedsUpdateConstraints()
}
open func styleUI() {
hideBackBarButtonItemTitle()
view.backgroundColor = K.Color.body
baseStyle()
// scrollView.contentSize = CGSize(width: view.width(), height: view.height() + (navigationController?.navigationBar.height)! + 40)
// tabBarController?.tabBar.isTranslucent = false
// automaticallyAdjustsScrollViewInsets = false
}
open func baseStyle() {
let textAttributes = [NSAttributedStringKey.foregroundColor: K.Color.barButtonItem]
// UINavigationBar.appearance().titleTextAttributes = textAttributes
navigationController?.navigationBar.titleTextAttributes = textAttributes
navigationController?.navigationBar.barTintColor = K.Color.navigator
navigationController?.navigationBar.tintColor = K.Color.barButtonItem
navigationController?.navigationBar.isTranslucent = false
}
open func bindUI() {
swipeRight = enableSwipeRightToBack(self)
view.whenTapped(self, action: #selector(DefaultViewController.viewDidTapped))
registerKeyboardNotifications()
}
open func bindData() { }
open func enableSaveBarButtonItem(title: String = "") {
if title != "" {
setRightBarButtonItem(title: title, action: #selector(saveTapped))
} else {
setRightBarButtonItem(getIcon(.save, options: ["size": K.BarButtonItem.size, "color": K.Color.barButtonItem]), action: #selector(saveTapped))
}
}
@objc open func saveTapped() { _logForAnyMode()}
open func enableCloseBarButtonItemAtLeft() { setLeftBarButtonItem(
// getIcon(.close, options: ["size": K.BarButtonItem.size, "color": K.Color.barButtonItem])
getImage(iconCode: K.Icons.close, color: K.Color.barButtonItem, size: K.BarButtonItem.size)
, action: #selector(closeTapped)) }
@objc open func viewDidTapped() { view.endEditing(true) }
open func textFieldShouldReturn(_ textField: UITextField) -> Bool {
if let field = textField.nextField {
field.becomeFirstResponder()
} else {
view.endEditing(true)
}
return true
}
open func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
if !textViewShouldReturn && text == "\n" {
if let field = textView.nextField {
field.becomeFirstResponder()
} else {
textView.resignFirstResponder()
}
return false
} else {
return true
}
}
override open func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
// view.fillSuperview()
}
open func fixConstraints() {
self.updateViewConstraints()
self.view.setNeedsUpdateConstraints()
}
override open func viewWillAppear(_ animated: Bool) {
// _logForUIMode()
setTabBarStatus()
// _logForUIMode(K.Api.userToken, title: "K.Api.userToken")
}
open func setTabBarStatus() {
self.tabBarController?.tabBar.asFadable(0.1)
self.tabBarController?.tabBar.isHidden = tabBarHidden
}
override open func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
unregisterKeyboardNotifications()
}
@objc open func keyboardDidShow(_ notification: NSNotification) {
let userInfo: NSDictionary = notification.userInfo! as NSDictionary
keyboardSize = (userInfo.object(forKey: UIKeyboardFrameBeginUserInfoKey)! as AnyObject).cgRectValue.size
// _logForUIMode(keyboardSize.height, title: "keyboardSize.height")
// let userInfo: NSDictionary = notification.userInfo!
// let keyboardSize = userInfo.objectForKey(UIKeyboardFrameBeginUserInfoKey)!.CGRectValue.size
// let contentInsets = UIEdgeInsetsMake(0, 0, keyboardSize.height, 0)
// contentView.contentInset = contentInsets
// contentView.scrollIndicatorInsets = contentInsets
}
@objc open func keyboardDidHide(_ notification: NSNotification) {
let userInfo: NSDictionary = notification.userInfo! as NSDictionary
keyboardSize = (userInfo.object(forKey: UIKeyboardFrameBeginUserInfoKey)! as AnyObject).cgRectValue.size
}
@objc open func keyboardWillShow(_ notification: NSNotification) {
// _logForUIMode()
let userInfo: NSDictionary = notification.userInfo! as NSDictionary
keyboardSize = (userInfo.object(forKey: UIKeyboardFrameBeginUserInfoKey)! as AnyObject).cgRectValue.size
// _logForUIMode(keyboardSize.height, title: "keyboardSize.height")
}
@objc open func keyboardWillHide(_ notification: NSNotification) {
// _logForUIMode()
keyboardSize = .zero
// contentView.contentInset = .zero
// contentView.scrollIndicatorInsets = .zero
}
// func textFieldDidBeginEditing(textField: UITextField) {
//// var viewRect = view.frame
//// viewRect.size.height -= keyboardSize.height
//// if CGRectContainsPoint(viewRect, textField.frame.origin) {
//// let scrollPoint = CGPointMake(0, textField.frame.origin.y - keyboardSize.height)
//// contentView.setContentOffset(scrollPoint, animated: true)
//// }
// }
open func registerKeyboardNotifications() {
NotificationCenter.default.addObserver(self, selector: #selector(DefaultViewController.keyboardWillShow(_:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(DefaultViewController.keyboardWillHide(_:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(DefaultViewController.keyboardDidShow(_:)), name: NSNotification.Name.UIKeyboardDidShow, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(DefaultViewController.keyboardDidHide(_:)), name: NSNotification.Name.UIKeyboardDidHide, object: nil)
}
open func unregisterKeyboardNotifications() {
NotificationCenter.default.removeObserver(self)
}
}
|
mit
|
6668dc62048138fb25b04d9efdaae742
| 34.964824 | 172 | 0.718737 | 4.774516 | false | false | false | false |
Mirmeca/Mirmeca
|
Mirmeca/CommentsGateway.swift
|
1
|
1574
|
//
// CommentsGateway.swift
// Mirmeca
//
// Created by solal on 2/08/2015.
// Copyright (c) 2015 Mirmeca. All rights reserved.
//
import Alamofire
import ObjectMapper
public struct CommentsGateway: GatewayProtocol {
private var url: String?
public init(endpoint: String, env: String?) {
let env = MirmecaEnv.sharedInstance.getEnv(env)
self.url = "\(env)/\(endpoint)"
}
public func request(completion: (value: AnyObject?, error: NSError?) -> Void) {
Alamofire.request(.GET, self.url!).responseJSON { (_, _, JSON, _) in
var value: [Comment]?
var error: NSError?
if (JSON != nil) {
if (JSON![0]["code"]! != nil) {
error = NSError(domain: self.url!, code: 303, userInfo: nil)
} else {
if let mappedObject = self.parseResponse(JSON!) {
value = mappedObject
} else {
error = NSError(domain: self.url!, code: 303, userInfo: nil)
}
}
} else {
error = NSError(domain: self.url!, code: 302, userInfo: nil)
}
completion(value: value, error: error)
}
}
private func parseResponse(JSON: AnyObject) -> [Comment]? {
var comments = [Comment]()
for comment in JSON as! [AnyObject] {
comments.append( Mapper<Comment>().map(comment)! )
}
return comments
}
}
|
mit
|
3b07ac6bd7fc4a0c12d3327680dd7341
| 28.698113 | 84 | 0.503177 | 4.588921 | false | false | false | false |
tecgirl/firefox-ios
|
Client/Application/AppDelegate.swift
|
2
|
30209
|
/* 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 Shared
import Storage
import AVFoundation
import XCGLogger
import MessageUI
import SDWebImage
import SwiftKeychainWrapper
import LocalAuthentication
import SyncTelemetry
import Sync
import CoreSpotlight
import UserNotifications
private let log = Logger.browserLogger
let LatestAppVersionProfileKey = "latestAppVersion"
let AllowThirdPartyKeyboardsKey = "settings.allowThirdPartyKeyboards"
private let InitialPingSentKey = "initialPingSent"
class AppDelegate: UIResponder, UIApplicationDelegate, UIViewControllerRestoration {
public static func viewController(withRestorationIdentifierPath identifierComponents: [Any], coder: NSCoder) -> UIViewController? {
return nil
}
var window: UIWindow?
var browserViewController: BrowserViewController!
var rootViewController: UIViewController!
weak var profile: Profile?
var tabManager: TabManager!
var adjustIntegration: AdjustIntegration?
var applicationCleanlyBackgrounded = true
weak var application: UIApplication?
var launchOptions: [AnyHashable: Any]?
let appVersion = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as! String
var receivedURLs = [URL]()
var unifiedTelemetry: UnifiedTelemetry?
@discardableResult func application(_ application: UIApplication, willFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
//
// Determine if the application cleanly exited last time it was used. We default to true in
// case we have never done this before. Then check if the "ApplicationCleanlyBackgrounded" user
// default exists and whether was properly set to true on app exit.
//
// Then we always set the user default to false. It will be set to true when we the application
// is backgrounded.
//
self.applicationCleanlyBackgrounded = true
let defaults = UserDefaults()
if defaults.object(forKey: "ApplicationCleanlyBackgrounded") != nil {
self.applicationCleanlyBackgrounded = defaults.bool(forKey: "ApplicationCleanlyBackgrounded")
}
defaults.set(false, forKey: "ApplicationCleanlyBackgrounded")
defaults.synchronize()
// Hold references to willFinishLaunching parameters for delayed app launch
self.application = application
self.launchOptions = launchOptions
self.window = UIWindow(frame: UIScreen.main.bounds)
self.window!.backgroundColor = UIColor.Photon.White100
// If the 'Save logs to Files app on next launch' toggle
// is turned on in the Settings app, copy over old logs.
if DebugSettingsBundleOptions.saveLogsToDocuments {
Logger.copyPreviousLogsToDocuments();
}
return startApplication(application, withLaunchOptions: launchOptions)
}
@discardableResult fileprivate func startApplication(_ application: UIApplication, withLaunchOptions launchOptions: [AnyHashable: Any]?) -> Bool {
log.info("startApplication begin")
// Need to get "settings.sendUsageData" this way so that Sentry can be initialized
// before getting the Profile.
let sendUsageData = NSUserDefaultsPrefs(prefix: "profile").boolForKey(AppConstants.PrefSendUsageData) ?? true
Sentry.shared.setup(sendUsageData: sendUsageData)
// Set the Firefox UA for browsing.
setUserAgent()
// Start the keyboard helper to monitor and cache keyboard state.
KeyboardHelper.defaultHelper.startObserving()
DynamicFontHelper.defaultHelper.startObserving()
MenuHelper.defaultHelper.setItems()
let logDate = Date()
// Create a new sync log file on cold app launch. Note that this doesn't roll old logs.
Logger.syncLogger.newLogWithDate(logDate)
Logger.browserLogger.newLogWithDate(logDate)
let profile = getProfile(application)
unifiedTelemetry = UnifiedTelemetry(profile: profile)
// Set up a web server that serves us static content. Do this early so that it is ready when the UI is presented.
setUpWebServer(profile)
let imageStore = DiskImageStore(files: profile.files, namespace: "TabManagerScreenshots", quality: UIConstants.ScreenshotQuality)
// Temporary fix for Bug 1390871 - NSInvalidArgumentException: -[WKContentView menuHelperFindInPage]: unrecognized selector
if #available(iOS 11, *) {
if let clazz = NSClassFromString("WKCont" + "ent" + "View"), let swizzledMethod = class_getInstanceMethod(TabWebViewMenuHelper.self, #selector(TabWebViewMenuHelper.swizzledMenuHelperFindInPage)) {
class_addMethod(clazz, MenuHelper.SelectorFindInPage, method_getImplementation(swizzledMethod), method_getTypeEncoding(swizzledMethod))
}
}
self.tabManager = TabManager(prefs: profile.prefs, imageStore: imageStore)
self.tabManager.stateDelegate = self
// Add restoration class, the factory that will return the ViewController we
// will restore with.
browserViewController = BrowserViewController(profile: self.profile!, tabManager: self.tabManager)
browserViewController.edgesForExtendedLayout = []
browserViewController.restorationIdentifier = NSStringFromClass(BrowserViewController.self)
browserViewController.restorationClass = AppDelegate.self
let navigationController = UINavigationController(rootViewController: browserViewController)
navigationController.delegate = self
navigationController.isNavigationBarHidden = true
navigationController.edgesForExtendedLayout = UIRectEdge(rawValue: 0)
rootViewController = navigationController
self.window!.rootViewController = rootViewController
NotificationCenter.default.addObserver(forName: .FSReadingListAddReadingListItem, object: nil, queue: nil) { (notification) -> Void in
if let userInfo = notification.userInfo, let url = userInfo["URL"] as? URL {
let title = (userInfo["Title"] as? String) ?? ""
profile.readingList.createRecordWithURL(url.absoluteString, title: title, addedBy: UIDevice.current.name)
}
}
NotificationCenter.default.addObserver(forName: .FirefoxAccountDeviceRegistrationUpdated, object: nil, queue: nil) { _ in
profile.flushAccount()
}
adjustIntegration = AdjustIntegration(profile: profile)
if LeanPlumClient.shouldEnable(profile: profile) {
LeanPlumClient.shared.setup(profile: profile)
LeanPlumClient.shared.set(enabled: true)
}
self.updateAuthenticationInfo()
SystemUtils.onFirstRun()
let fxaLoginHelper = FxALoginHelper.sharedInstance
fxaLoginHelper.application(application, didLoadProfile: profile)
log.info("startApplication end")
return true
}
func applicationWillTerminate(_ application: UIApplication) {
// We have only five seconds here, so let's hope this doesn't take too long.
self.profile?.shutdown()
// Allow deinitializers to close our database connections.
self.profile = nil
self.tabManager = nil
self.browserViewController = nil
self.rootViewController = nil
}
/**
* We maintain a weak reference to the profile so that we can pause timed
* syncs when we're backgrounded.
*
* The long-lasting ref to the profile lives in BrowserViewController,
* which we set in application:willFinishLaunchingWithOptions:.
*
* If that ever disappears, we won't be able to grab the profile to stop
* syncing... but in that case the profile's deinit will take care of things.
*/
func getProfile(_ application: UIApplication) -> Profile {
if let profile = self.profile {
return profile
}
let p = BrowserProfile(localName: "profile", syncDelegate: application.syncDelegate)
self.profile = p
return p
}
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
var shouldPerformAdditionalDelegateHandling = true
adjustIntegration?.triggerApplicationDidFinishLaunchingWithOptions(launchOptions)
UNUserNotificationCenter.current().delegate = self
SentTabAction.registerActions()
UIScrollView.doBadSwizzleStuff()
#if BUDDYBUILD
print("Setting up BuddyBuild SDK")
BuddyBuildSDK.setup()
#endif
window!.makeKeyAndVisible()
// Now roll logs.
DispatchQueue.global(qos: DispatchQoS.background.qosClass).async {
Logger.syncLogger.deleteOldLogsDownToSizeLimit()
Logger.browserLogger.deleteOldLogsDownToSizeLimit()
}
// If a shortcut was launched, display its information and take the appropriate action
if let shortcutItem = launchOptions?[UIApplicationLaunchOptionsKey.shortcutItem] as? UIApplicationShortcutItem {
QuickActions.sharedInstance.launchedShortcutItem = shortcutItem
// This will block "performActionForShortcutItem:completionHandler" from being called.
shouldPerformAdditionalDelegateHandling = false
}
// Force the ToolbarTextField in LTR mode - without this change the UITextField's clear
// button will be in the incorrect position and overlap with the input text. Not clear if
// that is an iOS bug or not.
AutocompleteTextField.appearance().semanticContentAttribute = .forceLeftToRight
return shouldPerformAdditionalDelegateHandling
}
func application(_ application: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool {
guard let routerpath = NavigationPath(url: url) else {
return false
}
if let profile = profile, let _ = profile.prefs.boolForKey(PrefsKeys.AppExtensionTelemetryOpenUrl) {
profile.prefs.removeObjectForKey(PrefsKeys.AppExtensionTelemetryOpenUrl)
var object = UnifiedTelemetry.EventObject.url
if case .text(_) = routerpath {
object = .searchText
}
UnifiedTelemetry.recordEvent(category: .appExtensionAction, method: .applicationOpenUrl, object: object)
}
DispatchQueue.main.async {
NavigationPath.handle(nav: routerpath, with: self.browserViewController)
}
return true
}
// We sync in the foreground only, to avoid the possibility of runaway resource usage.
// Eventually we'll sync in response to notifications.
func applicationDidBecomeActive(_ application: UIApplication) {
//
// We are back in the foreground, so set CleanlyBackgrounded to false so that we can detect that
// the application was cleanly backgrounded later.
//
let defaults = UserDefaults()
defaults.set(false, forKey: "ApplicationCleanlyBackgrounded")
defaults.synchronize()
if let profile = self.profile {
profile.reopen()
if profile.prefs.boolForKey(PendingAccountDisconnectedKey) ?? false {
FxALoginHelper.sharedInstance.applicationDidDisconnect(application)
}
profile.syncManager.applicationDidBecomeActive()
}
// We could load these here, but then we have to futz with the tab counter
// and making NSURLRequests.
browserViewController.loadQueuedTabs(receivedURLs: receivedURLs)
receivedURLs.removeAll()
application.applicationIconBadgeNumber = 0
// handle quick actions is available
let quickActions = QuickActions.sharedInstance
if let shortcut = quickActions.launchedShortcutItem {
// dispatch asynchronously so that BVC is all set up for handling new tabs
// when we try and open them
quickActions.handleShortCutItem(shortcut, withBrowserViewController: browserViewController)
quickActions.launchedShortcutItem = nil
}
UnifiedTelemetry.recordEvent(category: .action, method: .foreground, object: .app)
}
func applicationDidEnterBackground(_ application: UIApplication) {
//
// At this point we are happy to mark the app as CleanlyBackgrounded. If a crash happens in background
// sync then that crash will still be reported. But we won't bother the user with the Restore Tabs
// dialog. We don't have to because at this point we already saved the tab state properly.
//
let defaults = UserDefaults()
defaults.set(true, forKey: "ApplicationCleanlyBackgrounded")
defaults.synchronize()
syncOnDidEnterBackground(application: application)
UnifiedTelemetry.recordEvent(category: .action, method: .background, object: .app)
}
fileprivate func syncOnDidEnterBackground(application: UIApplication) {
guard let profile = self.profile else {
return
}
profile.syncManager.applicationDidEnterBackground()
var taskId: UIBackgroundTaskIdentifier = 0
taskId = application.beginBackgroundTask (expirationHandler: {
print("Running out of background time, but we have a profile shutdown pending.")
self.shutdownProfileWhenNotActive(application)
application.endBackgroundTask(taskId)
})
if profile.hasSyncableAccount() {
profile.syncManager.syncEverything(why: .backgrounded).uponQueue(.main) { _ in
self.shutdownProfileWhenNotActive(application)
application.endBackgroundTask(taskId)
}
} else {
profile.shutdown()
application.endBackgroundTask(taskId)
}
}
fileprivate func shutdownProfileWhenNotActive(_ application: UIApplication) {
// Only shutdown the profile if we are not in the foreground
guard application.applicationState != .active else {
return
}
profile?.shutdown()
}
func applicationWillEnterForeground(_ application: UIApplication) {
// The reason we need to call this method here instead of `applicationDidBecomeActive`
// is that this method is only invoked whenever the application is entering the foreground where as
// `applicationDidBecomeActive` will get called whenever the Touch ID authentication overlay disappears.
self.updateAuthenticationInfo()
}
fileprivate func updateAuthenticationInfo() {
if let authInfo = KeychainWrapper.sharedAppContainerKeychain.authenticationInfo() {
if !LAContext().canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: nil) {
authInfo.useTouchID = false
KeychainWrapper.sharedAppContainerKeychain.setAuthenticationInfo(authInfo)
}
}
}
fileprivate func setUpWebServer(_ profile: Profile) {
let server = WebServer.sharedInstance
ReaderModeHandlers.register(server, profile: profile)
ErrorPageHelper.register(server, certStore: profile.certStore)
AboutHomeHandler.register(server)
AboutLicenseHandler.register(server)
SessionRestoreHandler.register(server)
if AppConstants.IsRunningTest {
registerHandlersForTestMethods(server: server.server)
}
// Bug 1223009 was an issue whereby CGDWebserver crashed when moving to a background task
// catching and handling the error seemed to fix things, but we're not sure why.
// Either way, not implicitly unwrapping a try is not a great way of doing things
// so this is better anyway.
do {
try server.start()
} catch let err as NSError {
print("Error: Unable to start WebServer \(err)")
}
}
fileprivate func setUserAgent() {
let firefoxUA = UserAgent.defaultUserAgent()
// Set the UA for WKWebView (via defaults), the favicon fetcher, and the image loader.
// This only needs to be done once per runtime. Note that we use defaults here that are
// readable from extensions, so they can just use the cached identifier.
let defaults = UserDefaults(suiteName: AppInfo.sharedContainerIdentifier)!
defaults.register(defaults: ["UserAgent": firefoxUA])
SDWebImageDownloader.shared().setValue(firefoxUA, forHTTPHeaderField: "User-Agent")
// Record the user agent for use by search suggestion clients.
SearchViewController.userAgent = firefoxUA
// Some sites will only serve HTML that points to .ico files.
// The FaviconFetcher is explicitly for getting high-res icons, so use the desktop user agent.
FaviconFetcher.userAgent = UserAgent.desktopUserAgent()
}
func application(_ application: UIApplication, continue userActivity: NSUserActivity, restorationHandler: @escaping ([Any]?) -> Void) -> Bool {
// If the `NSUserActivity` has a `webpageURL`, it is either a deep link or an old history item
// reached via a "Spotlight" search before we began indexing visited pages via CoreSpotlight.
if let url = userActivity.webpageURL {
let query = url.getQuery()
// Check for fxa sign-in code and launch the login screen directly
if query["signin"] != nil {
browserViewController.launchFxAFromDeeplinkURL(url)
return true
}
// Per Adjust documenation, https://docs.adjust.com/en/universal-links/#running-campaigns-through-universal-links,
// it is recommended that links contain the `deep_link` query parameter. This link will also
// be url encoded.
if let deepLink = query["deep_link"]?.removingPercentEncoding, let url = URL(string: deepLink) {
browserViewController.switchToTabForURLOrOpen(url, isPrivileged: true)
return true
}
browserViewController.switchToTabForURLOrOpen(url, isPrivileged: true)
return true
}
// Otherwise, check if the `NSUserActivity` is a CoreSpotlight item and switch to its tab or
// open a new one.
if userActivity.activityType == CSSearchableItemActionType {
if let userInfo = userActivity.userInfo,
let urlString = userInfo[CSSearchableItemActivityIdentifier] as? String,
let url = URL(string: urlString) {
browserViewController.switchToTabForURLOrOpen(url, isPrivileged: true)
return true
}
}
return false
}
fileprivate func openURLsInNewTabs(_ notification: UNNotification) {
guard let urls = notification.request.content.userInfo["sentTabs"] as? [NSDictionary] else { return }
for sentURL in urls {
if let urlString = sentURL.value(forKey: "url") as? String, let url = URL(string: urlString) {
receivedURLs.append(url)
}
}
// Check if the app is foregrounded, _also_ verify the BVC is initialized. Most BVC functions depend on viewDidLoad() having run –if not, they will crash.
if UIApplication.shared.applicationState == .active && browserViewController.isViewLoaded {
browserViewController.loadQueuedTabs(receivedURLs: receivedURLs)
receivedURLs.removeAll()
}
}
func application(_ application: UIApplication, performActionFor shortcutItem: UIApplicationShortcutItem, completionHandler: @escaping (Bool) -> Void) {
let handledShortCutItem = QuickActions.sharedInstance.handleShortCutItem(shortcutItem, withBrowserViewController: browserViewController)
completionHandler(handledShortCutItem)
}
}
// MARK: - Root View Controller Animations
extension AppDelegate: UINavigationControllerDelegate {
func navigationController(_ navigationController: UINavigationController, animationControllerFor operation: UINavigationControllerOperation, from fromVC: UIViewController, to toVC: UIViewController) -> UIViewControllerAnimatedTransitioning? {
switch operation {
case .push:
return BrowserToTrayAnimator()
case .pop:
return TrayToBrowserAnimator()
default:
return nil
}
}
}
extension AppDelegate: TabManagerStateDelegate {
func tabManagerWillStoreTabs(_ tabs: [Tab]) {
// It is possible that not all tabs have loaded yet, so we filter out tabs with a nil URL.
let storedTabs: [RemoteTab] = tabs.compactMap( Tab.toTab )
// Don't insert into the DB immediately. We tend to contend with more important
// work like querying for top sites.
let queue = DispatchQueue.global(qos: DispatchQoS.background.qosClass)
queue.asyncAfter(deadline: DispatchTime.now() + Double(Int64(ProfileRemoteTabsSyncDelay * Double(NSEC_PER_MSEC))) / Double(NSEC_PER_SEC)) {
self.profile?.storeTabs(storedTabs)
}
}
}
extension AppDelegate: MFMailComposeViewControllerDelegate {
func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) {
// Dismiss the view controller and start the app up
controller.dismiss(animated: true, completion: nil)
startApplication(application!, withLaunchOptions: self.launchOptions)
}
}
extension AppDelegate: UNUserNotificationCenterDelegate {
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
openURLsInNewTabs(response.notification)
}
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
openURLsInNewTabs(notification)
}
}
extension AppDelegate {
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
FxALoginHelper.sharedInstance.apnsRegisterDidSucceed(deviceToken)
}
func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
print("failed to register. \(error)")
FxALoginHelper.sharedInstance.apnsRegisterDidFail()
}
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
if Logger.logPII && log.isEnabledFor(level: .info) {
NSLog("APNS NOTIFICATION \(userInfo)")
}
// At this point, we know that NotificationService has been run.
// We get to this point if the notification was received while the app was in the foreground
// OR the app was backgrounded and now the user has tapped on the notification.
// Either way, if this method is being run, then the app is foregrounded.
// Either way, we should zero the badge number.
application.applicationIconBadgeNumber = 0
guard let profile = self.profile else {
return completionHandler(.noData)
}
// NotificationService will have decrypted the push message, and done some syncing
// activity. If the `client` collection was synced, and there are `displayURI` commands (i.e. sent tabs)
// NotificationService will have collected them for us in the userInfo.
if let serializedTabs = userInfo["sentTabs"] as? [[String: String]] {
// Let's go ahead and open those.
for item in serializedTabs {
if let tabURL = item["url"], let url = URL(string: tabURL) {
receivedURLs.append(url)
}
}
if receivedURLs.count > 0 {
// If we're in the foreground, load the queued tabs now.
if application.applicationState == .active {
DispatchQueue.main.async {
self.browserViewController.loadQueuedTabs(receivedURLs: self.receivedURLs)
self.receivedURLs.removeAll()
}
}
return completionHandler(.newData)
}
}
// By now, we've dealt with any sent tab notifications.
//
// The only thing left to do now is to perform actions that can only be performed
// while the app is foregrounded.
//
// Use the push message handler to re-parse the message,
// this time with a BrowserProfile and processing the return
// differently than in NotificationService.
let handler = FxAPushMessageHandler(with: profile)
handler.handle(userInfo: userInfo).upon { res in
if let message = res.successValue {
switch message {
case .accountVerified:
_ = handler.postVerification()
case .thisDeviceDisconnected:
FxALoginHelper.sharedInstance.applicationDidDisconnect(application)
default:
break
}
}
completionHandler(res.isSuccess ? .newData : .failed)
}
}
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) {
let completionHandler: (UIBackgroundFetchResult) -> Void = { _ in }
self.application(application, didReceiveRemoteNotification: userInfo, fetchCompletionHandler: completionHandler)
}
}
extension UIApplication {
var syncDelegate: SyncDelegate {
return AppSyncDelegate(app: self)
}
static var isInPrivateMode: Bool {
let appDelegate = UIApplication.shared.delegate as? AppDelegate
return appDelegate?.browserViewController.tabManager.selectedTab?.isPrivate ?? false
}
}
class AppSyncDelegate: SyncDelegate {
let app: UIApplication
init(app: UIApplication) {
self.app = app
}
open func displaySentTab(for url: URL, title: String, from deviceName: String?) {
DispatchQueue.main.sync {
if let appDelegate = app.delegate as? AppDelegate, app.applicationState == .active {
appDelegate.browserViewController.switchToTabForURLOrOpen(url, isPrivileged: false)
return
}
// check to see what the current notification settings are and only try and send a notification if
// the user has agreed to them
UNUserNotificationCenter.current().getNotificationSettings { settings in
if settings.alertSetting == .enabled {
if Logger.logPII {
log.info("Displaying notification for URL \(url.absoluteString)")
}
let notificationContent = UNMutableNotificationContent()
let title: String
if let deviceName = deviceName {
title = String(format: Strings.SentTab_TabArrivingNotification_WithDevice_title, deviceName)
} else {
title = Strings.SentTab_TabArrivingNotification_NoDevice_title
}
notificationContent.title = title
notificationContent.body = url.absoluteDisplayExternalString
notificationContent.userInfo = [SentTabAction.TabSendURLKey: url.absoluteString, SentTabAction.TabSendTitleKey: title]
notificationContent.categoryIdentifier = "org.mozilla.ios.SentTab.placeholder"
// `timeInterval` must be greater than zero
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 0.1, repeats: false)
// The identifier for each notification request must be unique in order to be created
let requestIdentifier = "\(SentTabAction.TabSendCategory).\(url.absoluteString)"
let request = UNNotificationRequest(identifier: requestIdentifier, content: notificationContent, trigger: trigger)
UNUserNotificationCenter.current().add(request) { error in
if let error = error {
log.error(error.localizedDescription)
}
}
}
}
}
}
}
/**
* This exists because the Sync code is extension-safe, and thus doesn't get
* direct access to UIApplication.sharedApplication, which it would need to
* display a notification.
* This will also likely be the extension point for wipes, resets, and
* getting access to data sources during a sync.
*/
enum SentTabAction: String {
case view = "TabSendViewAction"
static let TabSendURLKey = "TabSendURL"
static let TabSendTitleKey = "TabSendTitle"
static let TabSendCategory = "TabSendCategory"
static func registerActions() {
let viewAction = UNNotificationAction(identifier: SentTabAction.view.rawValue, title: Strings.SentTabViewActionTitle, options: .foreground)
// Register ourselves to handle the notification category set by NotificationService for APNS notifications
let sentTabCategory = UNNotificationCategory(identifier: "org.mozilla.ios.SentTab.placeholder", actions: [viewAction], intentIdentifiers: [], options: UNNotificationCategoryOptions(rawValue: 0))
UNUserNotificationCenter.current().setNotificationCategories([sentTabCategory])
}
}
|
mpl-2.0
|
8713eb31d5288f82d965a618373cd627
| 43.356828 | 246 | 0.680471 | 5.694062 | false | false | false | false |
ABTSoftware/SciChartiOSTutorial
|
v2.x/Showcase/SciChartShowcase/SciChartShowcaseDemo/TraderChartsExample/Model/TraderViewModel.swift
|
1
|
2170
|
//
// TraderViewModel.swift
// SciChartShowcaseDemo
//
// Created by Hrybeniuk Mykola on 7/27/17.
// Copyright © 2017 SciChart Ltd. All rights reserved.
//
import Foundation
import SciChart
enum TraderIndicators: Int, EnumCollection, CustomStringConvertible {
case movingAverage50
case movingAverage100
case rsiPanel
case macdPanel
case axisMarkers
var description: String {
switch self {
case .movingAverage50:
return "Moving Average 50"
case .movingAverage100:
return "Moving Average 100"
case .rsiPanel:
return "RSI Panel"
case .macdPanel:
return "MACD Panel"
case .axisMarkers:
return "Axis Markers"
}
}
}
struct TraderViewModel {
let stockType: StockIndex!
let timeScale: TimeScale!
let timePeriod: TimePeriod!
let stockPrices: SCIOhlcDataSeries!
let volume: SCIXyDataSeries!
let averageLow: SCIXyDataSeries!
let averageHigh: SCIXyDataSeries!
let rsi: SCIXyDataSeries!
let mcad: SCIXyyDataSeries!
let histogram: SCIXyDataSeries!
var traderIndicators: [TraderIndicators] = TraderIndicators.allValues
init(_ stock: StockIndex,
_ scale: TimeScale,
_ period: TimePeriod,
dataSeries: (ohlc: SCIOhlcDataSeries, volume: SCIXyDataSeries, averageLow: SCIXyDataSeries, averageHigh: SCIXyDataSeries, rsi: SCIXyDataSeries, mcad: SCIXyyDataSeries, histogram: SCIXyDataSeries)) {
stockType = stock
timeScale = scale
timePeriod = period
stockPrices = dataSeries.ohlc
volume = dataSeries.volume
averageHigh = dataSeries.averageHigh
averageLow = dataSeries.averageLow
rsi = dataSeries.rsi
mcad = dataSeries.mcad
histogram = dataSeries.histogram
stockPrices.seriesName = "Candlestick"
volume.seriesName = "Volume"
averageLow.seriesName = "Low"
averageHigh.seriesName = "High"
rsi.seriesName = "RSI"
histogram.seriesName = "Histogram"
mcad.seriesName = "MCAD"
}
}
|
mit
|
738666d294214b166a393f2e272133c7
| 27.168831 | 207 | 0.646381 | 4.444672 | false | false | false | false |
hustlzp/iOS-Base
|
Constants.swift
|
1
|
3275
|
import UIKit
struct Font {
static let WenTingFont = "FZLTTHK--GBK1-0"
}
struct NotificationName {
static let logOut = Notification.Name("logoutNotification")
static let logIn = Notification.Name("logInNotification")
}
struct Size {
static var statusBarHeight: CGFloat {
return safeAreaInsetsTop > 0 ? safeAreaInsetsTop : 20
}
static var navigationBarWithoutStatusHeight: CGFloat {
if Device.isPad, #available(iOS 12.0, *) {
return 50
} else {
return 44
}
}
static var navigationBarHeight: CGFloat = navigationBarWithoutStatusHeight + statusBarHeight
static var tabBarHeight: CGFloat {
if Device.isPad, #available(iOS 12.0, *) {
return 50 + Size.onePixel
} else {
return 49 + Size.onePixel
}
}
static var screenWidth: CGFloat {
return UIApplication.shared.keyWindow?.bounds.width ?? UIScreen.main.bounds.width
}
static var screenHeight: CGFloat {
return UIApplication.shared.keyWindow?.bounds.height ?? UIScreen.main.bounds.height
}
static let screenMinLength = min(UIScreen.main.bounds.size.height, UIScreen.main.bounds.size.width)
static let screenMaxLength = max(UIScreen.main.bounds.size.height, UIScreen.main.bounds.size.width)
static var horizonalGap: CGFloat {
if Device.isPhone {
if Device.isSmallPhone {
return 18
} else {
return 20
}
} else {
return 48
}
}
static let onePixel = 1 / UIScreen.main.scale
static var safeAreaInsetsTop: CGFloat {
if #available(iOS 11.0, *) {
let window = UIApplication.shared.keyWindow
let safeAreaInsetsTop = window?.safeAreaInsets.top ?? 0
if safeAreaInsetsTop == 20 {
return 0
} else {
return safeAreaInsetsTop
}
} else {
return 0
}
}
static var safeAreaInsetsBottom: CGFloat {
if #available(iOS 11.0, *) {
let window = UIApplication.shared.keyWindow
return window?.safeAreaInsets.bottom ?? 0
} else {
return 0
}
}
}
struct Device {
static let isPhone = UIDevice.current.userInterfaceIdiom == .phone
static let isSmallPhone = Device.isPhone && Int(Size.screenMinLength) <= 320
static let isBigPhone = Device.isPhone && Int(Size.screenMinLength) >= 414
static let isNormalPhone = Device.isPhone && !Device.isSmallPhone && !Device.isBigPhone
static let isPad = UIDevice.current.userInterfaceIdiom == .pad
static var isVertical: Bool {
return Size.screenWidth < Size.screenHeight
}
static var modelName: String {
var systemInfo = utsname()
uname(&systemInfo)
let machineMirror = Mirror(reflecting: systemInfo.machine)
let identifier = machineMirror.children.reduce("") { identifier, element in
guard let value = element.value as? Int8, value != 0 else { return identifier }
return identifier + String(UnicodeScalar(UInt8(value)))
}
return identifier
}
}
|
mit
|
bc860002b4c480a789ab74555560acc3
| 32.080808 | 103 | 0.609771 | 4.844675 | false | false | false | false |
bitboylabs/selluv-ios
|
selluv-ios/selluv-ios/Classes/Base/Vender/PopCircleMenu/PopCirCleMenuView.swift
|
1
|
3984
|
//
// PopCirCleMenuView.swift
// CircleMenu
//
// Created by 刘业臻 on 16/7/2.
// Copyright © 2016年 Alex K. All rights reserved.
//
import UIKit
open class PopCirCleMenuView: UIView, UIGestureRecognizerDelegate {
open var circleButton: CircleMenu?
fileprivate weak var selectedButton: CircleMenuButton?
fileprivate lazy var longPressGestureRecognizer: UILongPressGestureRecognizer = {
let recognizer = UILongPressGestureRecognizer(target: self, action: #selector(PopCirCleMenuView.onPress(_:)))
recognizer.delegate = self
return recognizer
}()
init(frame: CGRect, buttonSize: CGSize, buttonsCount: Int = 3, duration: Double = 2,
distance: Float = 100) {
super.init(frame: frame)
let rect = CGRect(x: 0.0, y: 0.0, width: buttonSize.width, height: buttonSize.height)
circleButton = CircleMenu(frame: rect, buttonsCount: buttonsCount, duration: duration, distance: distance)
guard let circleButton = circleButton else {return}
addSubview(circleButton)
addGestureRecognizer(longPressGestureRecognizer)
}
override init(frame: CGRect) {
super.init(frame: frame)
setup()
addGestureRecognizer(longPressGestureRecognizer)
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
addGestureRecognizer(longPressGestureRecognizer)
}
func onPress(_ sender: UILongPressGestureRecognizer) {
guard let circleButton = circleButton else {return}
circleButton.backgroundColor = UIColor.clear
//circleButton.layer.borderColor = UIColor.color(255, green: 22, blue: 93, alpha: 1.0).CGColor
circleButton.layer.borderWidth = 7.0
bringSubview(toFront: circleButton)
let buttonWidth = circleButton.bounds.width
if sender.state == .began {
circleButton.center = sender.location(in: self)
circleButton.onTap()
circleButton.isHidden = false
} else if sender.state == .changed {
guard let buttons = circleButton.buttons else {return}
for button in buttons {
guard let textLabel = button.textLabel else {return}
let distance = button.center.distanceTo(sender.location(in: button))
if distance <= buttonWidth / 2.0 {
let color = circleButton.highlightedBorderColor
button.changeDistance(CGFloat(circleButton.distance) + 15.0, animated: true)
button.layer.borderColor = color.cgColor
selectedButton = button
textLabel.isHidden = false
} else if distance >= 15.0 + buttonWidth / 2.0 {
let color = circleButton.normalBorderColor
button.changeDistance(CGFloat(circleButton.distance), animated: false)
button.layer.borderColor = color.cgColor
textLabel.isHidden = true
}
}
} else if sender.state == .ended {
let duration = circleButton.duration
if let button = selectedButton {
let distance = button.center.distanceTo(sender.location(in: button))
if distance <= button.bounds.width / 2.0 {
circleButton.buttonHandler(button)
} else {
circleButton.onTap()
circleButton.hideCenterButton(duration: min(duration, 0.2))
}
} else {
circleButton.onTap()
circleButton.hideCenterButton(duration: min(duration, 0.2))
}
}
}
func setup() {
let rect = CGRect(x: 0.0, y: 0.0, width: 44.0, height: 44.0)
circleButton = CircleMenu(frame: rect)
guard let circleButton = circleButton else {return}
addSubview(circleButton)
}
}
|
mit
|
dc4c66b6d633b1cae7925cb53f21df45
| 32.125 | 117 | 0.609811 | 4.919554 | false | false | false | false |
zzgo/v2ex
|
v2ex/v2ex/MainViewController.swift
|
1
|
2432
|
//
// MainViewController.swift
// v2ex
//
// Created by zz go on 2016/12/26.
// Copyright © 2016年 zzgo. All rights reserved.
//
import Foundation
import RAMAnimatedTabBarController
class MainViewController: RAMAnimatedTabBarController {
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.white
///添加所有的子控制器
addAllChildsControllors()
}
}
//MARK: - UI
extension MainViewController {
///添加所有的子控制器
fileprivate func addAllChildsControllors() {
///首页
let discoverVC = DiscoverViewController() //HomeViewController()
addOneChildVC(childVC: discoverVC,
title: "发现",
image: UIImage(named: "tabbar_hot"),//UIImage(imageLiteralResourceName: "btn_home_normal"),
selecteImage: UIImage(named: "tabbar_hot_selected"))
let profileVC = ProfileViewController()
//我的
addOneChildVC(childVC: profileVC,
title: "我的",
image: UIImage(named: "tabbar_profile"),
selecteImage: UIImage(named: "tabbar_profile_selected"))
}
private func addOneChildVC(childVC: UIViewController, title: String?, image: UIImage?, selecteImage: UIImage?) {
//添加标题 ps:selectedImage是没有效果的
let item = RAMAnimatedTabBarItem(title: title, image: image, selectedImage: selecteImage)
item.textColor = UIColor.init(colorLiteralRed: 219/255, green: 219/255, blue: 219/155, alpha: 1)
item.selectedImage = selecteImage
// let animation = RAMTransitionItemAnimations()//RAMTransitionItemAnimations()
// animation.iconSelectedColor = UIColor.orange
// animation.transitionOptions = UIViewAnimationOptions.transitionCurlUp
//自定义的animation
let animation = RAMBounceAnimation(selectedImage: selecteImage!,defaultImage: image!)
animation.textSelectedColor=UIColor.init(colorLiteralRed: 39/255, green: 39/255, blue: 39/255, alpha: 1)
item.animation = animation
//添加子控制器
let navVC = UINavigationController(rootViewController: childVC)
addChildViewController(navVC)
navVC.tabBarItem = item
}
}
|
mit
|
fa5a112f0daf034f5d59a5b74611c23a
| 34.953846 | 116 | 0.628156 | 4.982942 | false | false | false | false |
liufengting/FTChatMessageDemoProject
|
Demo/Demo/ChatTableViewController.swift
|
1
|
6243
|
//
// ChatTableViewController.swift
// FTChatMessage
//
// Created by liufengting on 16/2/28.
// Copyright © 2016年 liufengting <https://github.com/liufengting>. All rights reserved.
//
import UIKit
import FTIndicator
class ChatTableViewController: FTChatMessageTableViewController,FTChatMessageAccessoryViewDelegate,FTChatMessageAccessoryViewDataSource,FTChatMessageRecorderViewDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate{
let sender1 = FTChatMessageUserModel.init(id: "1", name: "Someone", icon_url: "http://ww3.sinaimg.cn/mw600/6cca1403jw1f3lrknzxczj20gj0g0t96.jpg", extra_data: nil, isSelf: false)
override func viewDidLoad() {
super.viewDidLoad()
self.navigationItem.setRightBarButton(UIBarButtonItem.init(barButtonSystemItem: UIBarButtonSystemItem.add, target: self, action: #selector(self.addNewIncomingMessage)), animated: true)
messageRecordView.recorderDelegate = self
messageAccessoryView.setupWithDataSource(self , accessoryViewDelegate : self)
chatMessageDataArray = self.loadDefaultMessages()
}
//MARK: - addNewIncomingMessage
func addNewIncomingMessage() {
let message8 = FTChatMessageModel(data: "New Message added, try something else.", time: "4.12 22:42", from: sender1, type: .text)
self.addNewMessage(message8)
}
func loadDefaultMessages() -> [FTChatMessageModel] {
let message1 = FTChatMessageModel(data: "最近有点无聊,抽点时间写了这个聊天的UI框架。", time: "4.12 21:09:50", from: sender1, type: .text)
let message2 = FTChatMessageModel(data: "哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈", time: "4.12 21:09:51", from: sender1, type: .video)
let message3 = FTChatMessageImageModel(data: "http://ww2.sinaimg.cn/mw600/6aa09e8fgw1f8iquoznw2j20dw0bv0uk.jpg", time: "4.12 21:09:52", from: sender1, type: .image)
message3.imageUrl = "http://ww2.sinaimg.cn/mw600/6aa09e8fgw1f8iquoznw2j20dw0bv0uk.jpg"
let message4 = FTChatMessageModel(data: "哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈", time: "4.12 21:09:53", from: sender2, type: .text)
let message5 = FTChatMessageModel(data: "文字背景不是图片,是用贝塞尔曲线画的,效率应该不高,后期优化", time: "4.12 21:09:53", from: sender2, type: .text)
let message6 = FTChatMessageModel(data: "哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈", time: "4.12 21:09:54", from: sender2, type: .text)
let message8 = FTChatMessageImageModel(data: "http://wx3.sinaimg.cn/mw600/9e745efdly1fbmfs45minj20tg0xcq6v.jpg", time: "4.12 21:09:56", from: sender1, type: .image)
message8.imageUrl = "http://wx3.sinaimg.cn/mw600/9e745efdly1fbmfs45minj20tg0xcq6v.jpg"
let message7 = FTChatMessageModel(data: "哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈", time: "4.12 21:09:55", from: sender1, type: .text)
let array = [message1,message2,message3,message4,message5,message6,message8,message7]
return array;
}
func getAccessoryItemTitleArray() -> [String] {
return ["Alarm","Camera","Contacts","Mail","Messages","Music","Phone","Photos","Settings","VideoChat","Videos","Weather"]
}
//MARK: - FTChatMessageAccessoryViewDataSource
func ftChatMessageAccessoryViewModelArray() -> [FTChatMessageAccessoryViewModel] {
var array : [FTChatMessageAccessoryViewModel] = []
let titleArray = self.getAccessoryItemTitleArray()
for i in 0...titleArray.count-1 {
let string = titleArray[i]
array.append(FTChatMessageAccessoryViewModel.init(title: string, iconImage: UIImage(named: string)!))
}
return array
}
//MARK: - FTChatMessageAccessoryViewDelegate
func ftChatMessageAccessoryViewDidTappedOnItemAtIndex(_ index: NSInteger) {
if index == 0 {
let imagePicker : UIImagePickerController = UIImagePickerController()
imagePicker.sourceType = .photoLibrary
imagePicker.delegate = self
self.present(imagePicker, animated: true, completion: {
})
}else{
let string = "I just tapped at accessory view at index : \(index)"
print(string)
// FTIndicator.showInfo(withMessage: string)
let message2 = FTChatMessageModel(data: string, time: "4.12 21:09:51", from: sender2, type: .text)
self.addNewMessage(message2)
}
}
//MARK: - FTChatMessageRecorderViewDelegate
func ft_chatMessageRecordViewDidStartRecording(){
print("Start recording...")
FTIndicator.showProgressWithmessage("Recording...")
}
func ft_chatMessageRecordViewDidCancelRecording(){
print("Recording canceled.")
FTIndicator.dismissProgress()
}
func ft_chatMessageRecordViewDidStopRecording(_ duriation: TimeInterval, file: Data?){
print("Recording ended!")
FTIndicator.showSuccess(withMessage: "Record done.")
let message2 = FTChatMessageModel(data: "", time: "4.12 21:09:51", from: sender2, type: .audio)
self.addNewMessage(message2)
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
picker.dismiss(animated: true) {
let image : UIImage = info[UIImagePickerControllerOriginalImage] as! UIImage
let message2 = FTChatMessageImageModel(data: "", time: "4.12 21:09:51", from: self.sender2, type: .image)
message2.image = image;
self.addNewMessage(message2)
}
}
func saveImageToDisk(image: UIImage) -> String {
return ""
}
}
|
mit
|
54c76afaf47abd2afc55cc63ee5d5b2c
| 39.344828 | 233 | 0.660684 | 4.023384 | false | false | false | false |
austinzheng/swift-compiler-crashes
|
crashes-duplicates/23701-llvm-smallvectortemplatebase-std-pair-std-basic-string-char.swift
|
10
|
2550
|
// Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
class B<T where g:AnyObject{
let t: A{
let start = [Void{struct B<b
typealias e : e{typealias F=b> {
protocol A{
protocol A{
return "
a}enum A{class A {
class A : NSObject {
typealias e {
typealias F=b<b where k.h> {
struct A? {
protocol A{
protocol A:B? {
struct c
var f = compose(t: Int = compose(map(
}
class b
class B<b
typealias b
struct c>() {
func a}
protocol A : e{
}
struct B
class B{
return "
var e
class d
typealias e : e
class d<b> {
protocol A {
protocol c
class d<T where g: T : BooleanType, A {{
extension g{
}
func b<T where k.h> {
typealias F== compose()?
class var d {
var f{
struct g:Int=b<T>(
class B{
extension g:e
a}
struct c:e
}1
extension g
let t: NSObject {
"
println(A{
typealias e : T : c:e: Array<T where g: B? {
func b
protocol A {
"
protocol A : Array<T where g:Int== e{
println((A? {
var:e
println()?
let t: A{
let start = compose(t: T where g:AnyObject{
struct B
protocol A {
}
extension g<b {
}
struct g: T where g: T where g<T>struct g
}
println(a!
}
var f{
typealias F== compose(t: e
}Void{
struct c
extension g:d<T where g<T where g: T where S<T>:a
class bb< {
"
class B{func a{
struct B<T where g: A{func b
protocol A : a {
}
struct
protocol A{
extension g<T>(
"
class B<b
var f{
var e
struct c>:e: Array<T where g:Int== [Void{
let start = e
var e:B? {
}
protocol A : Int = [Void{
}
}
let t: A? {
func g: Array<b where g: B<T : e
}
typealias F== e
}
class A : B? {
protocol c:A:A<T>struct B? {
{
class d
return "
class c:B
let t: Array<b<T where g:B:AnyObject{
var:A{
}
var f{func b
struct g
}
class A {
let:e{typealias e
class B
protocol A:a!
class bb< b where g<T where S<b
struct B? {
let start = [Void{
extension g<T : Array<b where S<T where g: Array<T where S<T where k.h> {
return "
extension g: NSObject {
typealias e : NSObject {
protocol A {
}
class d
struct c>:Int=(
let a{
struct c:e{
let t: e{
var:A){
}
protocol a}enum A? {
typealias e{
protocol A{
class b
protocol A {
class var f{class B? {
class b> {}
let t: B? {
class d<T where k.h> {
struct g<T where g
class d
class A {
protocol A : Array<T : B? {
struct A{class var f{
protocol A {
protocol A {
var f{
println(
func g: Array<b where k.h> {func a{}
protocol A {
var d {
class d
class d
}1
class bb< {
let:a
struct c:e: T : Int = compose(map((((
class A {class c>(t: a {func a{
class bb< {
typealias b< {
}
}
func b
class c{
protocol A {
extension g<b> {}
println((a
let t:
|
mit
|
776e9d5a177d2be0d60de65339505835
| 13.739884 | 87 | 0.656078 | 2.527255 | false | false | false | false |
LiskUser1234/SwiftyLisk
|
Lisk/Delegate/Operations/DelegateGetNextForgersOperation.swift
|
1
|
2556
|
/*
The MIT License
Copyright (C) 2017 LiskUser1234
- Github: https://github.com/liskuser1234
Please vote LiskUser1234 for delegate to support this project.
For donations:
- Lisk: 6137947831033853925L
- Bitcoin: 1NCTZwBJF7ZFpwPeQKiSgci9r2pQV3G7RG
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
import Foundation
import SwiftyJSON
open class DelegateGetNextForgersOperation : APIOperation {
private let limit: Int?
private let currentBlockPtr: UnsafeMutablePointer<Double>?
private let currentSlotPtr: UnsafeMutablePointer<Double>?
private let delegates: UnsafeMutablePointer<[JSON]>?
public init(limit: Int?,
currentBlockPtr: UnsafeMutablePointer<Double>?,
currentSlotPtr: UnsafeMutablePointer<Double>?,
delegates: UnsafeMutablePointer<[JSON]>?,
errorPtr: UnsafeMutablePointer<String?>? = nil) {
self.limit = limit
self.currentBlockPtr = currentBlockPtr
self.currentSlotPtr = currentSlotPtr
self.delegates = delegates
super.init(errorPtr: errorPtr)
}
override open func start() {
DelegateAPI.getNextForgers(limit: limit,
callback: callback)
}
override internal func processResponse(json: JSON) {
self.currentBlockPtr?.pointee = json["currentBlock"].doubleValue
self.currentSlotPtr?.pointee = json["currentSlot"].doubleValue
self.delegates?.pointee = json["delegates"].arrayValue
}
}
|
mit
|
3269510dfeebec7acb106b57d7b76ef7
| 36.588235 | 78 | 0.716354 | 4.831758 | false | false | false | false |
dengJunior/TestKitchen_1606
|
TestKitchen/TestKitchen/classes/cookbook/recommend/view/CBWorksCell.swift
|
1
|
4144
|
//
// CBWorksCell.swift
// TestKitchen
//
// Created by 邓江洲 on 16/8/22.
// Copyright © 2016年 邓江洲. All rights reserved.
//
import UIKit
class CBWorksCell: UITableViewCell {
var model : CBRecommendWidgetListModel?{
didSet{
showData()
}
}
func showData() -> Void {
let subView = contentView.viewWithTag(400)
if subView?.isKindOfClass(UILabel.self) == true{
let descLabel = subView as! UILabel
descLabel.text = model?.desc
}
for i in 0..<3{
if model?.widget_data?.count > i*3{
let imageModel = model?.widget_data![i*3]
if imageModel?.type == "image"{
let subView = contentView.viewWithTag(100+i)
if subView?.isKindOfClass(UIButton.self) == true{
let btn = subView as! UIButton
let url = NSURL(string: (imageModel?.content)!)
btn.kf_setImageWithURL(url!, forState: .Normal, placeholderImage: UIImage(named: "sdefaultImage"), optionsInfo: nil, progressBlock: nil, completionHandler: nil)
}
}
}
//1
if model?.widget_data?.count > i*3+1{
let imageModel = model?.widget_data![i*3+1]
if imageModel?.type == "image"{
let subView = contentView.viewWithTag(200+i)
if subView?.isKindOfClass(UIButton.self) == true{
let btn = subView as! UIButton
btn.layer.masksToBounds = true
btn.layer.cornerRadius = 20
let url = NSURL(string: (imageModel?.content)!)
btn.kf_setImageWithURL(url!, forState: .Normal, placeholderImage: UIImage(named: "sdefaultImage"), optionsInfo: nil, progressBlock: nil, completionHandler: nil)
}
}
}
//2
if model?.widget_data?.count > i*3+2{
let nameModel = model?.widget_data![i*3+2]
if nameModel?.type == "text"{
let subView = contentView.viewWithTag(300+i)
if subView?.isKindOfClass(UILabel.self) == true {
let nameLabel = subView as! UILabel
nameLabel.text = nameModel?.content
}
}
}
//3
}
}
@IBAction func clickBtn(sender: UIButton) {
}
@IBAction func clickUserBtn(sender: UIButton) {
}
class func createWorksCellFor(tableView: UITableView, atIndexPath indexPath: NSIndexPath, withListModel listModel: CBRecommendWidgetListModel) -> CBWorksCell{
let cellId = "worksCellId"
var cell = tableView.dequeueReusableCellWithIdentifier(cellId) as? CBWorksCell
if nil == cell {
cell = NSBundle.mainBundle().loadNibNamed("CBWorksCell", owner: nil, options: nil).last as? CBWorksCell
}
cell?.model = listModel
return cell!
}
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
|
mit
|
2ac96f06b3f52072e62bc161b1ad3246
| 21.440217 | 188 | 0.444418 | 5.831921 | false | false | false | false |
safx/TypetalkApp
|
TypetalkApp/OSX/ViewControllers/CreateNewMessageViewController.swift
|
1
|
2490
|
//
// CreateNewMessageViewController.swift
// TypetalkApp
//
// Created by Safx Developer on 2015/03/07.
// Copyright (c) 2015年 Safx Developers. All rights reserved.
//
import Foundation
import Cocoa
import TypetalkKit
import RxSwift
class CreateNewMessageViewController: NSViewController, NSTextFieldDelegate {
@IBOutlet var messageBox: NSTextField!
@IBOutlet weak var postButton: NSButton!
@IBOutlet weak var messageViewController: MessageViewController!
let viewModel = CreateNewMessageViewModel()
var topic: TopicWithUserInfo?
private let disposeBag = DisposeBag()
override func viewDidLoad() {
weak var weakSelf = self
messageBox.delegate = self
messageBox
.rx_text
.throttle(0.05, scheduler: MainScheduler.instance)
.distinctUntilChanged()
.subscribeNext { res in
if let text = res as NSString? {
Swift.print("\(text)")
weakSelf?.postButton.enabled = text.length > 0
}
}
.addDisposableTo(disposeBag)
}
@IBAction func postMessage(sender: AnyObject) {
guard viewModel.parentViewModel != nil else { return }
let text = messageBox.stringValue
guard !text.isEmpty else { return }
viewModel.postMessage(text)
.subscribeNext { [weak self] v in
dispatch_async(dispatch_get_main_queue()) {
self?.messageBox.stringValue = ""
()
}
()
}
.addDisposableTo(disposeBag)
}
// MARK: - NSTextFieldDelegate
func handleCurrentEvent(ev: NSEvent) -> Bool {
guard ev.type == .KeyDown else { return false }
let commandKey = ev.modifierFlags.contains(.CommandKeyMask)
if ev.keyCode == 0x24 && commandKey {
postMessage(messageBox)
return true
}
return false
}
func control(control: NSControl, textView: NSTextView, doCommandBySelector commandSelector: Selector) -> Bool {
if commandSelector == Selector("insertNewline:") {
textView.insertNewlineIgnoringFieldEditor(self)
return true
} else {
guard let ev = NSApp.currentEvent else { return false }
if !handleCurrentEvent(ev) {
print(commandSelector.description)
}
}
return false
}
}
|
mit
|
3b4d573ef333829819abc9d61a1155cd
| 27.930233 | 115 | 0.597669 | 5.140496 | false | false | false | false |
r-mckay/montreal-iqa
|
montrealIqaCore/Carthage/Checkouts/realm-cocoa/RealmSwift/RealmCollection.swift
|
12
|
35847
|
////////////////////////////////////////////////////////////////////////////
//
// Copyright 2014 Realm Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////
import Foundation
import Realm
/**
An iterator for a `RealmCollection` instance.
*/
public final class RLMIterator<T: Object>: IteratorProtocol {
private var i: UInt = 0
private var generatorBase: NSFastEnumerationIterator
init(collection: RLMCollection) {
generatorBase = NSFastEnumerationIterator(collection)
}
/// Advance to the next element and return it, or `nil` if no next element exists.
public func next() -> T? {
let accessor = unsafeBitCast(generatorBase.next() as! Object?, to: Optional<T>.self)
if let accessor = accessor {
RLMInitializeSwiftAccessorGenerics(accessor)
}
return accessor
}
}
/**
A `RealmCollectionChange` value encapsulates information about changes to collections
that are reported by Realm notifications.
The change information is available in two formats: a simple array of row
indices in the collection for each type of change, and an array of index paths
in a requested section suitable for passing directly to `UITableView`'s batch
update methods.
The arrays of indices in the `.update` case follow `UITableView`'s batching
conventions, and can be passed as-is to a table view's batch update functions after being converted to index paths.
For example, for a simple one-section table view, you can do the following:
```swift
self.notificationToken = results.addNotificationBlock { changes in
switch changes {
case .initial:
// Results are now populated and can be accessed without blocking the UI
self.tableView.reloadData()
break
case .update(_, let deletions, let insertions, let modifications):
// Query results have changed, so apply them to the TableView
self.tableView.beginUpdates()
self.tableView.insertRowsAtIndexPaths(insertions.map { NSIndexPath(forRow: $0, inSection: 0) },
withRowAnimation: .Automatic)
self.tableView.deleteRowsAtIndexPaths(deletions.map { NSIndexPath(forRow: $0, inSection: 0) },
withRowAnimation: .Automatic)
self.tableView.reloadRowsAtIndexPaths(modifications.map { NSIndexPath(forRow: $0, inSection: 0) },
withRowAnimation: .Automatic)
self.tableView.endUpdates()
break
case .error(let err):
// An error occurred while opening the Realm file on the background worker thread
fatalError("\(err)")
break
}
}
```
*/
public enum RealmCollectionChange<T> {
/**
`.initial` indicates that the initial run of the query has completed (if
applicable), and the collection can now be used without performing any
blocking work.
*/
case initial(T)
/**
`.update` indicates that a write transaction has been committed which
either changed which objects are in the collection, and/or modified one
or more of the objects in the collection.
All three of the change arrays are always sorted in ascending order.
- parameter deletions: The indices in the previous version of the collection which were removed from this one.
- parameter insertions: The indices in the new collection which were added in this version.
- parameter modifications: The indices of the objects in the new collection which were modified in this version.
*/
case update(T, deletions: [Int], insertions: [Int], modifications: [Int])
/**
If an error occurs, notification blocks are called one time with a `.error`
result and an `NSError` containing details about the error. This can only
currently happen if opening the Realm on a background thread to calcuate
the change set fails. The callback will never be called again after it is
invoked with a .error value.
*/
case error(Error)
static func fromObjc(value: T, change: RLMCollectionChange?, error: Error?) -> RealmCollectionChange {
if let error = error {
return .error(error)
}
if let change = change {
return .update(value,
deletions: forceCast(change.deletions, to: [Int].self),
insertions: forceCast(change.insertions, to: [Int].self),
modifications: forceCast(change.modifications, to: [Int].self))
}
return .initial(value)
}
}
private func forceCast<A, U>(_ from: A, to type: U.Type) -> U {
return from as! U
}
#if swift(>=3.2)
/// :nodoc:
public protocol RealmCollectionBase: RandomAccessCollection, LazyCollectionProtocol, CustomStringConvertible, ThreadConfined where Element: Object {
}
#else
/// :nodoc:
public protocol RealmCollectionBase: RandomAccessCollection, LazyCollectionProtocol, CustomStringConvertible, ThreadConfined {
/// The type of the objects contained in the collection.
associatedtype Element: Object
}
#endif
/**
A homogenous collection of `Object`s which can be retrieved, filtered, sorted, and operated upon.
*/
public protocol RealmCollection: RealmCollectionBase {
// Must also conform to `AssistedObjectiveCBridgeable`
// MARK: Properties
/// The Realm which manages the collection, or `nil` for unmanaged collections.
var realm: Realm? { get }
/**
Indicates if the collection can no longer be accessed.
The collection can no longer be accessed if `invalidate()` is called on the `Realm` that manages the collection.
*/
var isInvalidated: Bool { get }
/// The number of objects in the collection.
var count: Int { get }
/// A human-readable description of the objects contained in the collection.
var description: String { get }
// MARK: Index Retrieval
/**
Returns the index of an object in the collection, or `nil` if the object is not present.
- parameter object: An object.
*/
func index(of object: Element) -> Int?
/**
Returns the index of the first object matching the predicate, or `nil` if no objects match.
- parameter predicate: The predicate to use to filter the objects.
*/
func index(matching predicate: NSPredicate) -> Int?
/**
Returns the index of the first object matching the predicate, or `nil` if no objects match.
- parameter predicateFormat: A predicate format string, optionally followed by a variable number of arguments.
*/
func index(matching predicateFormat: String, _ args: Any...) -> Int?
// MARK: Filtering
/**
Returns a `Results` containing all objects matching the given predicate in the collection.
- parameter predicateFormat: A predicate format string, optionally followed by a variable number of arguments.
*/
func filter(_ predicateFormat: String, _ args: Any...) -> Results<Element>
/**
Returns a `Results` containing all objects matching the given predicate in the collection.
- parameter predicate: The predicate to use to filter the objects.
*/
func filter(_ predicate: NSPredicate) -> Results<Element>
// MARK: Sorting
/**
Returns a `Results` containing the objects in the collection, but sorted.
Objects are sorted based on the values of the given key path. For example, to sort a collection of `Student`s from
youngest to oldest based on their `age` property, you might call
`students.sorted(byKeyPath: "age", ascending: true)`.
- warning: Collections may only be sorted by properties of boolean, `Date`, `NSDate`, single and double-precision
floating point, integer, and string types.
- parameter keyPath: The key path to sort by.
- parameter ascending: The direction to sort in.
*/
func sorted(byKeyPath keyPath: String, ascending: Bool) -> Results<Element>
/**
Returns a `Results` containing the objects in the collection, but sorted.
Objects are sorted based on the values of the given property. For example, to sort a collection of `Student`s from
youngest to oldest based on their `age` property, you might call
`students.sorted(byProperty: "age", ascending: true)`.
- warning: Collections may only be sorted by properties of boolean, `Date`, `NSDate`, single and double-precision
floating point, integer, and string types.
- parameter property: The name of the property to sort by.
- parameter ascending: The direction to sort in.
*/
@available(*, deprecated, renamed: "sorted(byKeyPath:ascending:)")
func sorted(byProperty property: String, ascending: Bool) -> Results<Element>
/**
Returns a `Results` containing the objects in the collection, but sorted.
- warning: Collections may only be sorted by properties of boolean, `Date`, `NSDate`, single and double-precision
floating point, integer, and string types.
- see: `sorted(byKeyPath:ascending:)`
- parameter sortDescriptors: A sequence of `SortDescriptor`s to sort by.
*/
func sorted<S: Sequence>(by sortDescriptors: S) -> Results<Element> where S.Iterator.Element == SortDescriptor
// MARK: Aggregate Operations
/**
Returns the minimum (lowest) value of the given property among all the objects in the collection, or `nil` if the
collection is empty.
- warning: Only a property whose type conforms to the `MinMaxType` protocol can be specified.
- parameter property: The name of a property whose minimum value is desired.
*/
func min<U: MinMaxType>(ofProperty property: String) -> U?
/**
Returns the maximum (highest) value of the given property among all the objects in the collection, or `nil` if the
collection is empty.
- warning: Only a property whose type conforms to the `MinMaxType` protocol can be specified.
- parameter property: The name of a property whose minimum value is desired.
*/
func max<U: MinMaxType>(ofProperty property: String) -> U?
/**
Returns the sum of the given property for objects in the collection, or `nil` if the collection is empty.
- warning: Only names of properties of a type conforming to the `AddableType` protocol can be used.
- parameter property: The name of a property conforming to `AddableType` to calculate sum on.
*/
func sum<U: AddableType>(ofProperty property: String) -> U
/**
Returns the sum of the values of a given property over all the objects in the collection.
- warning: Only a property whose type conforms to the `AddableType` protocol can be specified.
- parameter property: The name of a property whose values should be summed.
*/
func average<U: AddableType>(ofProperty property: String) -> U?
// MARK: Key-Value Coding
/**
Returns an `Array` containing the results of invoking `valueForKey(_:)` with `key` on each of the collection's
objects.
- parameter key: The name of the property whose values are desired.
*/
func value(forKey key: String) -> Any?
/**
Returns an `Array` containing the results of invoking `valueForKeyPath(_:)` with `keyPath` on each of the
collection's objects.
- parameter keyPath: The key path to the property whose values are desired.
*/
func value(forKeyPath keyPath: String) -> Any?
/**
Invokes `setValue(_:forKey:)` on each of the collection's objects using the specified `value` and `key`.
- warning: This method may only be called during a write transaction.
- parameter value: The object value.
- parameter key: The name of the property whose value should be set on each object.
*/
func setValue(_ value: Any?, forKey key: String)
// MARK: Notifications
/**
Registers a block to be called each time the collection changes.
The block will be asynchronously called with the initial results, and then called again after each write
transaction which changes either any of the objects in the collection, or which objects are in the collection.
The `change` parameter that is passed to the block reports, in the form of indices within the collection, which of
the objects were added, removed, or modified during each write transaction. See the `RealmCollectionChange`
documentation for more information on the change information supplied and an example of how to use it to update a
`UITableView`.
At the time when the block is called, the collection will be fully evaluated and up-to-date, and as long as you do
not perform a write transaction on the same thread or explicitly call `realm.refresh()`, accessing it will never
perform blocking work.
Notifications are delivered via the standard run loop, and so can't be delivered while the run loop is blocked by
other activity. When notifications can't be delivered instantly, multiple notifications may be coalesced into a
single notification. This can include the notification with the initial collection.
For example, the following code performs a write transaction immediately after adding the notification block, so
there is no opportunity for the initial notification to be delivered first. As a result, the initial notification
will reflect the state of the Realm after the write transaction.
```swift
let results = realm.objects(Dog.self)
print("dogs.count: \(dogs?.count)") // => 0
let token = dogs.addNotificationBlock { changes in
switch changes {
case .initial(let dogs):
// Will print "dogs.count: 1"
print("dogs.count: \(dogs.count)")
break
case .update:
// Will not be hit in this example
break
case .error:
break
}
}
try! realm.write {
let dog = Dog()
dog.name = "Rex"
person.dogs.append(dog)
}
// end of run loop execution context
```
You must retain the returned token for as long as you want updates to be sent to the block. To stop receiving
updates, call `stop()` on the token.
- warning: This method cannot be called during a write transaction, or when the containing Realm is read-only.
- parameter block: The block to be called whenever a change occurs.
- returns: A token which must be held for as long as you want updates to be delivered.
*/
func addNotificationBlock(_ block: @escaping (RealmCollectionChange<Self>) -> Void) -> NotificationToken
/// :nodoc:
func _addNotificationBlock(_ block: @escaping (RealmCollectionChange<AnyRealmCollection<Element>>) -> Void) -> NotificationToken
}
private class _AnyRealmCollectionBase<T: Object>: AssistedObjectiveCBridgeable {
typealias Wrapper = AnyRealmCollection<Element>
typealias Element = T
var realm: Realm? { fatalError() }
var isInvalidated: Bool { fatalError() }
var count: Int { fatalError() }
var description: String { fatalError() }
func index(of object: Element) -> Int? { fatalError() }
func index(matching predicate: NSPredicate) -> Int? { fatalError() }
func index(matching predicateFormat: String, _ args: Any...) -> Int? { fatalError() }
func filter(_ predicateFormat: String, _ args: Any...) -> Results<Element> { fatalError() }
func filter(_ predicate: NSPredicate) -> Results<Element> { fatalError() }
func sorted(byKeyPath keyPath: String, ascending: Bool) -> Results<Element> { fatalError() }
func sorted<S: Sequence>(by sortDescriptors: S) -> Results<Element> where S.Iterator.Element == SortDescriptor {
fatalError()
}
func min<U: MinMaxType>(ofProperty property: String) -> U? { fatalError() }
func max<U: MinMaxType>(ofProperty property: String) -> U? { fatalError() }
func sum<U: AddableType>(ofProperty property: String) -> U { fatalError() }
func average<U: AddableType>(ofProperty property: String) -> U? { fatalError() }
subscript(position: Int) -> Element { fatalError() }
func makeIterator() -> RLMIterator<T> { fatalError() }
var startIndex: Int { fatalError() }
var endIndex: Int { fatalError() }
func value(forKey key: String) -> Any? { fatalError() }
func value(forKeyPath keyPath: String) -> Any? { fatalError() }
func setValue(_ value: Any?, forKey key: String) { fatalError() }
func _addNotificationBlock(_ block: @escaping (RealmCollectionChange<Wrapper>) -> Void)
-> NotificationToken { fatalError() }
class func bridging(from objectiveCValue: Any, with metadata: Any?) -> Self { fatalError() }
var bridged: (objectiveCValue: Any, metadata: Any?) { fatalError() }
}
private final class _AnyRealmCollection<C: RealmCollection>: _AnyRealmCollectionBase<C.Element> {
let base: C
init(base: C) {
self.base = base
}
// MARK: Properties
override var realm: Realm? { return base.realm }
override var isInvalidated: Bool { return base.isInvalidated }
override var count: Int { return base.count }
override var description: String { return base.description }
// MARK: Index Retrieval
override func index(of object: C.Element) -> Int? { return base.index(of: object) }
override func index(matching predicate: NSPredicate) -> Int? { return base.index(matching: predicate) }
override func index(matching predicateFormat: String, _ args: Any...) -> Int? {
return base.index(matching: NSPredicate(format: predicateFormat, argumentArray: args))
}
// MARK: Filtering
override func filter(_ predicateFormat: String, _ args: Any...) -> Results<C.Element> {
return base.filter(NSPredicate(format: predicateFormat, argumentArray: args))
}
override func filter(_ predicate: NSPredicate) -> Results<C.Element> { return base.filter(predicate) }
// MARK: Sorting
override func sorted(byKeyPath keyPath: String, ascending: Bool) -> Results<C.Element> {
return base.sorted(byKeyPath: keyPath, ascending: ascending)
}
override func sorted<S: Sequence>
(by sortDescriptors: S) -> Results<C.Element> where S.Iterator.Element == SortDescriptor {
return base.sorted(by: sortDescriptors)
}
// MARK: Aggregate Operations
override func min<U: MinMaxType>(ofProperty property: String) -> U? {
return base.min(ofProperty: property)
}
override func max<U: MinMaxType>(ofProperty property: String) -> U? {
return base.max(ofProperty: property)
}
override func sum<U: AddableType>(ofProperty property: String) -> U {
return base.sum(ofProperty: property)
}
override func average<U: AddableType>(ofProperty property: String) -> U? {
return base.average(ofProperty: property)
}
// MARK: Sequence Support
override subscript(position: Int) -> C.Element {
#if swift(>=3.2)
return base[position as! C.Index]
#else
return base[position as! C.Index] as! C.Element
#endif
}
override func makeIterator() -> RLMIterator<Element> {
// FIXME: it should be possible to avoid this force-casting
return base.makeIterator() as! RLMIterator<Element>
}
// MARK: Collection Support
override var startIndex: Int {
// FIXME: it should be possible to avoid this force-casting
return base.startIndex as! Int
}
override var endIndex: Int {
// FIXME: it should be possible to avoid this force-casting
return base.endIndex as! Int
}
// MARK: Key-Value Coding
override func value(forKey key: String) -> Any? { return base.value(forKey: key) }
override func value(forKeyPath keyPath: String) -> Any? { return base.value(forKeyPath: keyPath) }
override func setValue(_ value: Any?, forKey key: String) { base.setValue(value, forKey: key) }
// MARK: Notifications
/// :nodoc:
override func _addNotificationBlock(_ block: @escaping (RealmCollectionChange<Wrapper>) -> Void)
-> NotificationToken { return base._addNotificationBlock(block) }
// MARK: AssistedObjectiveCBridgeable
override class func bridging(from objectiveCValue: Any, with metadata: Any?) -> _AnyRealmCollection {
return _AnyRealmCollection(
base: (C.self as! AssistedObjectiveCBridgeable.Type).bridging(from: objectiveCValue, with: metadata) as! C)
}
override var bridged: (objectiveCValue: Any, metadata: Any?) {
return (base as! AssistedObjectiveCBridgeable).bridged
}
}
/**
A type-erased `RealmCollection`.
Instances of `RealmCollection` forward operations to an opaque underlying collection having the same `Element` type.
*/
public final class AnyRealmCollection<T: Object>: RealmCollection {
public func index(after i: Int) -> Int { return i + 1 }
public func index(before i: Int) -> Int { return i - 1 }
/// The type of the objects contained in the collection.
public typealias Element = T
fileprivate let base: _AnyRealmCollectionBase<T>
fileprivate init(base: _AnyRealmCollectionBase<T>) {
self.base = base
}
/// Creates an `AnyRealmCollection` wrapping `base`.
public init<C: RealmCollection>(_ base: C) where C.Element == T {
self.base = _AnyRealmCollection(base: base)
}
// MARK: Properties
/// The Realm which manages the collection, or `nil` if the collection is unmanaged.
public var realm: Realm? { return base.realm }
/**
Indicates if the collection can no longer be accessed.
The collection can no longer be accessed if `invalidate()` is called on the containing `realm`.
*/
public var isInvalidated: Bool { return base.isInvalidated }
/// The number of objects in the collection.
public var count: Int { return base.count }
/// A human-readable description of the objects contained in the collection.
public var description: String { return base.description }
// MARK: Index Retrieval
/**
Returns the index of the given object, or `nil` if the object is not in the collection.
- parameter object: An object.
*/
public func index(of object: Element) -> Int? { return base.index(of: object) }
/**
Returns the index of the first object matching the given predicate, or `nil` if no objects match.
- parameter predicate: The predicate with which to filter the objects.
*/
public func index(matching predicate: NSPredicate) -> Int? { return base.index(matching: predicate) }
/**
Returns the index of the first object matching the given predicate, or `nil` if no objects match.
- parameter predicateFormat: A predicate format string, optionally followed by a variable number of arguments.
*/
public func index(matching predicateFormat: String, _ args: Any...) -> Int? {
return base.index(matching: NSPredicate(format: predicateFormat, argumentArray: args))
}
// MARK: Filtering
/**
Returns a `Results` containing all objects matching the given predicate in the collection.
- parameter predicateFormat: A predicate format string, optionally followed by a variable number of arguments.
*/
public func filter(_ predicateFormat: String, _ args: Any...) -> Results<Element> {
return base.filter(NSPredicate(format: predicateFormat, argumentArray: args))
}
/**
Returns a `Results` containing all objects matching the given predicate in the collection.
- parameter predicate: The predicate with which to filter the objects.
- returns: A `Results` containing objects that match the given predicate.
*/
public func filter(_ predicate: NSPredicate) -> Results<Element> { return base.filter(predicate) }
// MARK: Sorting
/**
Returns a `Results` containing the objects in the collection, but sorted.
Objects are sorted based on the values of the given key path. For example, to sort a collection of `Student`s from
youngest to oldest based on their `age` property, you might call
`students.sorted(byKeyPath: "age", ascending: true)`.
- warning: Collections may only be sorted by properties of boolean, `Date`, `NSDate`, single and double-precision
floating point, integer, and string types.
- parameter keyPath: The key path to sort by.
- parameter ascending: The direction to sort in.
*/
public func sorted(byKeyPath keyPath: String, ascending: Bool) -> Results<Element> {
return base.sorted(byKeyPath: keyPath, ascending: ascending)
}
/**
Returns a `Results` containing the objects in the collection, but sorted.
Objects are sorted based on the values of the given property. For example, to sort a collection of `Student`s from
youngest to oldest based on their `age` property, you might call
`students.sorted(byProperty: "age", ascending: true)`.
- warning: Collections may only be sorted by properties of boolean, `Date`, `NSDate`, single and double-precision
floating point, integer, and string types.
- parameter property: The name of the property to sort by.
- parameter ascending: The direction to sort in.
*/
@available(*, deprecated, renamed: "sorted(byKeyPath:ascending:)")
public func sorted(byProperty property: String, ascending: Bool) -> Results<Element> {
return sorted(byKeyPath: property, ascending: ascending)
}
/**
Returns a `Results` containing the objects in the collection, but sorted.
- warning: Collections may only be sorted by properties of boolean, `Date`, `NSDate`, single and double-precision
floating point, integer, and string types.
- see: `sorted(byKeyPath:ascending:)`
- parameter sortDescriptors: A sequence of `SortDescriptor`s to sort by.
*/
public func sorted<S: Sequence>(by sortDescriptors: S) -> Results<Element>
where S.Iterator.Element == SortDescriptor {
return base.sorted(by: sortDescriptors)
}
// MARK: Aggregate Operations
/**
Returns the minimum (lowest) value of the given property among all the objects in the collection, or `nil` if the
collection is empty.
- warning: Only a property whose type conforms to the `MinMaxType` protocol can be specified.
- parameter property: The name of a property whose minimum value is desired.
*/
public func min<U: MinMaxType>(ofProperty property: String) -> U? {
return base.min(ofProperty: property)
}
/**
Returns the maximum (highest) value of the given property among all the objects in the collection, or `nil` if the
collection is empty.
- warning: Only a property whose type conforms to the `MinMaxType` protocol can be specified.
- parameter property: The name of a property whose minimum value is desired.
*/
public func max<U: MinMaxType>(ofProperty property: String) -> U? {
return base.max(ofProperty: property)
}
/**
Returns the sum of the values of a given property over all the objects in the collection.
- warning: Only a property whose type conforms to the `AddableType` protocol can be specified.
- parameter property: The name of a property whose values should be summed.
*/
public func sum<U: AddableType>(ofProperty property: String) -> U { return base.sum(ofProperty: property) }
/**
Returns the average value of a given property over all the objects in the collection, or `nil` if the collection is
empty.
- warning: Only the name of a property whose type conforms to the `AddableType` protocol can be specified.
- parameter property: The name of a property whose average value should be calculated.
*/
public func average<U: AddableType>(ofProperty property: String) -> U? { return base.average(ofProperty: property) }
// MARK: Sequence Support
/**
Returns the object at the given `index`.
- parameter index: The index.
*/
public subscript(position: Int) -> T { return base[position] }
/// Returns a `RLMIterator` that yields successive elements in the collection.
public func makeIterator() -> RLMIterator<T> { return base.makeIterator() }
// MARK: Collection Support
/// The position of the first element in a non-empty collection.
/// Identical to endIndex in an empty collection.
public var startIndex: Int { return base.startIndex }
/// The collection's "past the end" position.
/// endIndex is not a valid argument to subscript, and is always reachable from startIndex by
/// zero or more applications of successor().
public var endIndex: Int { return base.endIndex }
// MARK: Key-Value Coding
/**
Returns an `Array` containing the results of invoking `valueForKey(_:)` with `key` on each of the collection's
objects.
- parameter key: The name of the property whose values are desired.
*/
public func value(forKey key: String) -> Any? { return base.value(forKey: key) }
/**
Returns an `Array` containing the results of invoking `valueForKeyPath(_:)` with `keyPath` on each of the
collection's objects.
- parameter keyPath: The key path to the property whose values are desired.
*/
public func value(forKeyPath keyPath: String) -> Any? { return base.value(forKeyPath: keyPath) }
/**
Invokes `setValue(_:forKey:)` on each of the collection's objects using the specified `value` and `key`.
- warning: This method may only be called during a write transaction.
- parameter value: The value to set the property to.
- parameter key: The name of the property whose value should be set on each object.
*/
public func setValue(_ value: Any?, forKey key: String) { base.setValue(value, forKey: key) }
// MARK: Notifications
/**
Registers a block to be called each time the collection changes.
The block will be asynchronously called with the initial results, and then called again after each write
transaction which changes either any of the objects in the collection, or which objects are in the collection.
The `change` parameter that is passed to the block reports, in the form of indices within the collection, which of
the objects were added, removed, or modified during each write transaction. See the `RealmCollectionChange`
documentation for more information on the change information supplied and an example of how to use it to update a
`UITableView`.
At the time when the block is called, the collection will be fully evaluated and up-to-date, and as long as you do
not perform a write transaction on the same thread or explicitly call `realm.refresh()`, accessing it will never
perform blocking work.
Notifications are delivered via the standard run loop, and so can't be delivered while the run loop is blocked by
other activity. When notifications can't be delivered instantly, multiple notifications may be coalesced into a
single notification. This can include the notification with the initial collection.
For example, the following code performs a write transaction immediately after adding the notification block, so
there is no opportunity for the initial notification to be delivered first. As a result, the initial notification
will reflect the state of the Realm after the write transaction.
```swift
let results = realm.objects(Dog.self)
print("dogs.count: \(dogs?.count)") // => 0
let token = dogs.addNotificationBlock { changes in
switch changes {
case .initial(let dogs):
// Will print "dogs.count: 1"
print("dogs.count: \(dogs.count)")
break
case .update:
// Will not be hit in this example
break
case .error:
break
}
}
try! realm.write {
let dog = Dog()
dog.name = "Rex"
person.dogs.append(dog)
}
// end of run loop execution context
```
You must retain the returned token for as long as you want updates to be sent to the block. To stop receiving
updates, call `stop()` on the token.
- warning: This method cannot be called during a write transaction, or when the containing Realm is read-only.
- parameter block: The block to be called whenever a change occurs.
- returns: A token which must be held for as long as you want updates to be delivered.
*/
public func addNotificationBlock(_ block: @escaping (RealmCollectionChange<AnyRealmCollection>) -> Void)
-> NotificationToken { return base._addNotificationBlock(block) }
/// :nodoc:
public func _addNotificationBlock(_ block: @escaping (RealmCollectionChange<AnyRealmCollection>) -> Void)
-> NotificationToken { return base._addNotificationBlock(block) }
}
// MARK: AssistedObjectiveCBridgeable
private struct AnyRealmCollectionBridgingMetadata<T: Object> {
var baseMetadata: Any?
var baseType: _AnyRealmCollectionBase<T>.Type
}
extension AnyRealmCollection: AssistedObjectiveCBridgeable {
static func bridging(from objectiveCValue: Any, with metadata: Any?) -> AnyRealmCollection {
guard let metadata = metadata as? AnyRealmCollectionBridgingMetadata<T> else { preconditionFailure() }
return AnyRealmCollection(base: metadata.baseType.bridging(from: objectiveCValue, with: metadata.baseMetadata))
}
var bridged: (objectiveCValue: Any, metadata: Any?) {
return (
objectiveCValue: base.bridged.objectiveCValue,
metadata: AnyRealmCollectionBridgingMetadata(baseMetadata: base.bridged.metadata, baseType: type(of: base))
)
}
}
// MARK: Unavailable
extension AnyRealmCollection {
@available(*, unavailable, renamed: "isInvalidated")
public var invalidated: Bool { fatalError() }
@available(*, unavailable, renamed: "index(matching:)")
public func index(of predicate: NSPredicate) -> Int? { fatalError() }
@available(*, unavailable, renamed: "index(matching:_:)")
public func index(of predicateFormat: String, _ args: AnyObject...) -> Int? { fatalError() }
@available(*, unavailable, renamed: "sorted(byKeyPath:ascending:)")
public func sorted(_ property: String, ascending: Bool = true) -> Results<T> { fatalError() }
@available(*, unavailable, renamed: "sorted(by:)")
public func sorted<S: Sequence>(_ sortDescriptors: S) -> Results<T> where S.Iterator.Element == SortDescriptor {
fatalError()
}
@available(*, unavailable, renamed: "min(ofProperty:)")
public func min<U: MinMaxType>(_ property: String) -> U? { fatalError() }
@available(*, unavailable, renamed: "max(ofProperty:)")
public func max<U: MinMaxType>(_ property: String) -> U? { fatalError() }
@available(*, unavailable, renamed: "sum(ofProperty:)")
public func sum<U: AddableType>(_ property: String) -> U { fatalError() }
@available(*, unavailable, renamed: "average(ofProperty:)")
public func average<U: AddableType>(_ property: String) -> U? { fatalError() }
}
|
mit
|
f92c16e2389e8d7797d61853d4554a6c
| 39.142217 | 148 | 0.68346 | 4.773236 | false | false | false | false |
BelledonneCommunications/linphone-iphone
|
Classes/Swift/Voip/Views/Fragments/Conference/VoipGridParticipantCell.swift
|
1
|
6101
|
/*
* Copyright (c) 2010-2020 Belledonne Communications SARL.
*
* This file is part of linphone-iphone
*
* 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 UIKit
import Foundation
import SnapKit
import linphonesw
class VoipGridParticipantCell: UICollectionViewCell {
// Layout Constants
let corner_radius = 20.0
static let avatar_size = 80.0
let switch_camera_button_margins = 8.0
let switch_camera_button_size = 30
let pause_label_left_margin = 5
static let mute_size = 25
let mute_margin = 5
let videoView = UIView()
let avatar = Avatar(color:VoipTheme.voipBackgroundColor, textStyle: VoipTheme.call_generated_avatar_medium)
let pause = UIImageView(image: UIImage(named: "voip_pause")?.tinted(with: .white))
let switchCamera = UIImageView(image: UIImage(named:"voip_change_camera")?.tinted(with:.white))
let displayName = StyledLabel(VoipTheme.conference_participant_name_font_grid)
let pauseLabel = StyledLabel(VoipTheme.conference_participant_name_font_grid,VoipTexts.conference_participant_paused)
let muted = MicMuted(VoipActiveSpeakerParticipantCell.mute_size)
let joining = RotatingSpinner()
var participantData: ConferenceParticipantDeviceData? = nil {
didSet {
if let data = participantData {
self.updateElements()
data.isJoining.clearObservers()
data.isJoining.observe { _ in
self.updateElements()
}
data.isInConference.clearObservers()
data.isInConference.observe { _ in
self.updateElements()
}
data.videoEnabled.clearObservers()
data.videoEnabled.observe { _ in
self.updateElements()
}
data.participantDevice.address.map {
avatar.fillFromAddress(address: $0)
if let displayName = $0.addressBookEnhancedDisplayName() {
self.displayName.text = displayName
}
}
data.isSpeaking.clearObservers()
data.isSpeaking.observe { _ in
self.updateElements(skipVideo: true)
}
data.micMuted.clearObservers()
data.micMuted.observe { _ in
self.updateElements(skipVideo: true)
}
}
}
}
func updateElements(skipVideo:Bool = false) {
if let data = participantData {
// Background
if (data.isInConference.value != true && data.isJoining.value != true) {
self.contentView.backgroundColor = VoipTheme.voip_conference_participant_paused_background
} else if (data.videoEnabled.value == true) {
self.contentView.backgroundColor = .black
} else {
self.contentView.backgroundColor = data.isMe ? VoipTheme.voipParticipantMeBackgroundColor.get() : VoipTheme.voipParticipantBackgroundColor.get()
}
// Avatar
self.avatar.isHidden = (data.isInConference.value != true && data.isJoining.value != true) || data.videoEnabled.value == true
// Video
if (!skipVideo) {
self.videoView.isHidden = data.isInConference.value != true || data.videoEnabled.value != true
if (!self.videoView.isHidden) {
data.setVideoView(view: self.videoView)
}
self.switchCamera.isHidden = self.videoView.isHidden || !data.isSwitchCameraAvailable()
}
// Pause
self.pause.isHidden = data.isInConference.value == true || data.isJoining.value == true
self.pauseLabel.isHidden = self.pause.isHidden
// Border for active speaker
self.layer.borderWidth = data.isSpeaking.value == true ? 2 : 0
// Joining indicator
if (data.isJoining.value == true) {
self.joining.isHidden = false
self.joining.startRotation()
} else {
self.joining.isHidden = true
self.joining.stopRotation()
}
// Muted
self.muted.isHidden = data.micMuted.value != true
}
}
override init(frame:CGRect) {
super.init(frame:.zero)
layer.cornerRadius = corner_radius
clipsToBounds = true
layer.borderColor = VoipTheme.primary_color.cgColor
contentView.addSubview(videoView)
videoView.matchParentDimmensions().done()
contentView.addSubview(avatar)
avatar.size(w: VoipGridParticipantCell.avatar_size, h: VoipGridParticipantCell.avatar_size).center().done()
contentView.addSubview(pause)
pause.layer.cornerRadius = VoipGridParticipantCell.avatar_size/2
pause.clipsToBounds = true
pause.backgroundColor = VoipTheme.voip_gray
pause.size(w: VoipGridParticipantCell.avatar_size, h: VoipGridParticipantCell.avatar_size).center().done()
contentView.addSubview(switchCamera)
switchCamera.alignParentTop(withMargin: switch_camera_button_margins).alignParentRight(withMargin: switch_camera_button_margins).square(switch_camera_button_size).done()
switchCamera.contentMode = .scaleAspectFit
switchCamera.onClick {
Core.get().toggleCamera()
}
contentView.addSubview(displayName)
displayName.alignParentLeft(withMargin:ActiveCallView.bottom_displayname_margin_left).alignParentBottom(withMargin:ActiveCallView.bottom_displayname_margin_bottom).alignParentRight().done()
contentView.addSubview(pauseLabel)
pauseLabel.toRightOf(displayName,withLeftMargin: pause_label_left_margin).alignParentBottom(withMargin:ActiveCallView.bottom_displayname_margin_bottom).done()
contentView.addSubview(muted)
muted.alignParentLeft(withMargin: mute_margin).alignParentTop(withMargin:mute_margin).done()
contentView.addSubview(joining)
joining.square(VoipActiveSpeakerParticipantCell.mute_size).alignParentTop(withMargin: mute_margin).alignParentLeft(withMargin: mute_margin).done()
contentView.matchParentDimmensions().done()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
|
gpl-3.0
|
82eaf512ba1610686464324ada58eeba
| 34.265896 | 191 | 0.742173 | 3.724664 | false | false | false | false |
Noders/NodersCL-App
|
StrongLoopForiOS/VideoModel.swift
|
1
|
417
|
//
// VideoModel.swift
// Noders
//
// Created by Jose Vildosola on 19-05-15.
// Copyright (c) 2015 DevIn. All rights reserved.
//
import UIKit
class VideoModel: NSObject {
var videoId:String = ""
var title:String = ""
var descripcion:String = ""
var duration:String = "0:0:0"
var thumbnailUrlDefault:String = ""
var thumbnailUrlMedium:String = ""
var thumbnailUrlHigh:String = ""
}
|
gpl-2.0
|
80f5bb53f728f3e8708287564d018443
| 20.947368 | 50 | 0.64988 | 3.362903 | false | false | false | false |
bustoutsolutions/siesta
|
Extensions/Alamofire/Networking-Alamofire.swift
|
1
|
2876
|
//
// Networking-Alamofire.swift
// Siesta
//
// Created by Paul on 2015/6/26.
// Copyright © 2016 Bust Out Solutions. All rights reserved.
//
import Foundation
#if !COCOAPODS
import Siesta
#endif
import Alamofire
/**
Uses [Alamofire](https://github.com/Alamofire/Alamofire) for networking.
You can create instances of this provider with a custom
[Alamofire.Manager](http://cocoadocs.org/docsets/Alamofire/1.3.0/Classes/Manager.html)
in order to control caching, certificate validation rules, etc. For example, here is a `Service` that will
not use the cell network:
class MyAPI: Service {
init() {
let configuration = URLSessionConfiguration.ephemeral
configuration.allowsCellularAccess = false
super.init(
baseURL: "http://foo.bar/v1",
networking: AlamofireProvider(configuration: configuration))
}
}
*/
public struct AlamofireProvider: NetworkingProvider
{
public let session: Alamofire.Session
public init(session: Alamofire.Session = Session.default)
{ self.session = session }
public init(configuration: URLSessionConfiguration)
{ self.init(session: Alamofire.Session(configuration: configuration)) }
public func startRequest(
_ request: URLRequest,
completion: @escaping RequestNetworkingCompletionCallback)
-> RequestNetworking
{
AlamofireRequestNetworking(
session: session,
alamofireRequest: session.request(request)
.response { completion($0.response, $0.data, $0.error) })
}
}
internal struct AlamofireRequestNetworking: RequestNetworking, SessionTaskContainer
{
let session: Alamofire.Session
let alamofireRequest: Alamofire.Request
var task: URLSessionTask
{
session.rootQueue.sync
{
guard let requestTask = alamofireRequest.task else
{ return ZeroProgressURLSessionTask() }
if requestTask.state == .suspended
{ alamofireRequest.resume() } // in case session.startRequestsImmediately is false
return requestTask
}
}
func cancel()
{ alamofireRequest.cancel() }
}
extension Alamofire.Session: NetworkingProviderConvertible
{
/// You can pass an `AlamoFire.Manager` when creating a `Service`.
public var siestaNetworkingProvider: NetworkingProvider
{ return AlamofireProvider(session: self) }
}
private class ZeroProgressURLSessionTask: URLSessionTask
{
override var countOfBytesSent: Int64
{ 0 }
override var countOfBytesExpectedToSend: Int64
{ 1 }
override var countOfBytesReceived: Int64
{ 0 }
override var countOfBytesExpectedToReceive: Int64
{ 1 }
}
|
mit
|
769967a85d010de9bf648ab778ba1e8a
| 28.947917 | 108 | 0.656348 | 5.017452 | false | true | false | false |
TeamProxima/predictive-fault-tracker
|
mobile/SieHack/Pods/Charts/Source/Charts/Data/Implementations/Standard/ScatterChartData.swift
|
54
|
1216
|
//
// ScatterChartData.swift
// Charts
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/Charts
//
import Foundation
import CoreGraphics
open class ScatterChartData: BarLineScatterCandleBubbleChartData
{
public override init()
{
super.init()
}
public override init(dataSets: [IChartDataSet]?)
{
super.init(dataSets: dataSets)
}
/// - returns: The maximum shape-size across all DataSets.
open func getGreatestShapeSize() -> CGFloat
{
var max = CGFloat(0.0)
for set in _dataSets
{
let scatterDataSet = set as? IScatterChartDataSet
if scatterDataSet == nil
{
print("ScatterChartData: Found a DataSet which is not a ScatterChartDataSet", terminator: "\n")
}
else
{
let size = scatterDataSet!.scatterShapeSize
if size > max
{
max = size
}
}
}
return max
}
}
|
mit
|
543980c94dbe11347046f358436b5b0f
| 21.943396 | 111 | 0.535362 | 5.218884 | false | false | false | false |
rhx/gir2swift
|
Sources/libgir2swift/models/gir elements/GirRecord.swift
|
1
|
13364
|
//
// GirRecord.swift
// gir2swift
//
// Created by Rene Hexel on 25/03/2016.
// Copyright © 2016, 2017, 2018, 2019, 2020, 2022 Rene Hexel. All rights reserved.
//
import SwiftLibXML
extension GIR {
/// a data type record to create a protocol/struct/class for
public class Record: CType {
/// String representation of `Record`s
public override var kind: String { return "Record" }
/// C language symbol prefix
public let cprefix: String
/// Corresponding C type of the record (gir-1.0.rnc:214)
public let correspondingCType: String?
/// C type getter function
public let typegetter: String?
/// Methods associated with this record
public let methods: [Method]
/// Functions associated with this record
public var functions = [Function]()
/// Constructors for this record
public let constructors: [Method]
/// Properties of this record
public let properties: [Property]
/// Fieldss of this record
public let fields: [Field]
/// List of signals for this record
public let signals: [Signal]
/// Type struct (e.g. class definition), typically nil for records
public var typeStruct: String?
/// Name of type which is defined by this record
public var isGTypeStructForType: String?
/// Name of the function that returns the GType for this record (`nil` if unspecified)
public var parentType: Record? { return nil }
/// Root class (`nil` for plain records)
public var rootType: Record { return self }
/// Names of implemented interfaces
public var implements: [String]
/// records contained within this record
public var records: [Record] = []
/// return all functions, methods, and constructors
public var allMethods: [Method] {
return constructors + methods + functions
}
/// return all functions, methods, and constructors inherited from ancestors
public var inheritedMethods: [Method] {
guard let parent = parentType else { return [] }
return parent.allMethods + parent.inheritedMethods
}
/// return the typed pointer name
@inlinable public var ptrName: String { cprefix + "_ptr" }
/// Designated initialiser
/// - Parameters:
/// - name: The name of the record to initialise
/// - cname: C identifier
/// - type: C typedef name of the constant
/// - ctype: underlying C type
/// - cprefix: prefix used for C language free functions that implement methods for this record
/// - typegetter: C type getter function
/// - methods: Methods associated with this record
/// - functions: Functions associated with this record
/// - constructors: Constructors for this record
/// - properties: Properties of this record
/// - fields: Fields of this record
/// - signals: List of signals for this record
/// - interfaces: Interfaces implemented by this record
/// - comment: Documentation text for the constant
/// - introspectable: Set to `true` if introspectable
/// - deprecated: Documentation on deprecation status if non-`nil`
public init(name: String, cname: String, type: TypeReference, cprefix: String, correspondingCType: String? = nil, typegetter: String? = nil, isGTypeStructForType: String? = nil, methods: [Method] = [], functions: [Function] = [], constructors: [Method] = [], properties: [Property] = [], fields: [Field] = [], signals: [Signal] = [], interfaces: [String] = [], comment: String = "", introspectable: Bool = false, deprecated: String? = nil) {
self.cprefix = cprefix
self.correspondingCType = correspondingCType
self.typegetter = typegetter
self.isGTypeStructForType = isGTypeStructForType
self.methods = methods
self.functions = functions
self.constructors = constructors
self.properties = properties
self.fields = fields
self.signals = signals
self.implements = interfaces
super.init(name: name, cname: cname, type: type, comment: comment, introspectable: introspectable, deprecated: deprecated)
}
/// Initialiser to construct a record type from XML
/// - Parameters:
/// - node: `XMLElement` to construct this constant from
/// - index: Index within the siblings of the `node`
public init(node: XMLElement, at index: Int) {
cprefix = node.attribute(named: "symbol-prefix") ?? ""
correspondingCType = node.attribute(named: "type")
// Regarding "intern": https://gitlab.gnome.org/GNOME/gobject-introspection/-/blob/gnome-3-36/girepository/giregisteredtypeinfo.c
if let typegetter = node.attribute(named: "get-type"), typegetter != "intern" {
self.typegetter = typegetter
} else {
self.typegetter = nil
}
typeStruct = node.attribute(named: "type-struct")
isGTypeStructForType = node.attribute(named: "is-gtype-struct-for")
let children = node.children.lazy
let meths = children.filter { $0.name == "method" }
methods = meths.enumerated().map { Method(node: $0.1, at: $0.0) }
let cons = children.filter { $0.name == "constructor" }
constructors = cons.enumerated().map { Method(node: $0.1, at: $0.0) }
let props = children.filter { $0.name == "property" }
properties = props.enumerated().map { Property(node: $0.1, at: $0.0) }
let fattrs = children.filter { $0.name == "field" }
fields = fattrs.enumerated().map { Field(node: $0.1, at: $0.0) }
let sigs = children.filter { $0.name == "signal" }
signals = sigs.enumerated().map { Signal(node: $0.1, at: $0.0) }
let interfaces = children.filter { $0.name == "implements" }
implements = interfaces.enumerated().compactMap { $0.1.attribute(named: "name") }
records = node.children.lazy.filter { $0.name == "record" }.enumerated().map {
Record(node: $0.element, at: $0.offset)
}
super.init(node: node, at: index)
let funcs = children.filter { $0.name == "function" }
functions = funcs.enumerated().map { Function(node: $0.1, at: $0.0) }
}
/// Register this type as a record type
@inlinable
override public func registerKnownType() {
let type = typeRef.type
let clsType = classType
let proType = protocolType
let refType = structType
let protocolRef = self.protocolRef
let clsRef = classRef
if type.parent == nil { type.parent = protocolRef }
if !GIR.recordTypes.contains(type) {
GIR.recordTypes.insert(type)
}
let ref = structRef
if GIR.protocols[type] == nil { GIR.protocols[type] = protocolRef }
if GIR.protocols[clsType] == nil { GIR.protocols[clsType] = clsRef }
if GIR.protocols[refType] == nil { GIR.protocols[refType] = protocolRef }
if GIR.recordRefs[type] == nil { GIR.recordRefs[type] = ref }
if GIR.recordRefs[clsType] == nil { GIR.recordRefs[clsType] = ref }
if GIR.recordRefs[refType] == nil { GIR.recordRefs[refType] = ref }
if GIR.recordRefs[proType] == nil { GIR.recordRefs[proType] = ref }
if GIR.refRecords[proType] == nil { GIR.refRecords[proType] = typeRef }
if GIR.refRecords[clsType] == nil { GIR.refRecords[clsType] = typeRef }
if GIR.refRecords[refType] == nil { GIR.refRecords[refType] = typeRef }
if GIR.refRecords[type] == nil { GIR.refRecords[type] = typeRef }
// let prefixedType = type.prefixed
// guard prefixedType !== type else { return }
// let prefixedCls = clsType.prefixed
// let prefixedRef = refType.prefixed
// let prefixedPro = proType.prefixed
// if GIR.protocols[prefixedType] == nil { GIR.protocols[prefixedType] = protocolRef }
// if GIR.protocols[prefixedCls] == nil { GIR.protocols[prefixedCls] = clsRef }
// if GIR.protocols[prefixedRef] == nil { GIR.protocols[prefixedRef] = protocolRef }
// if GIR.recordRefs[prefixedType] == nil { GIR.recordRefs[prefixedType] = ref }
// if GIR.recordRefs[prefixedCls] == nil { GIR.recordRefs[prefixedCls] = ref }
// if GIR.recordRefs[prefixedRef] == nil { GIR.recordRefs[prefixedRef] = ref }
// if GIR.recordRefs[prefixedPro] == nil { GIR.recordRefs[prefixedPro] = ref }
// if GIR.refRecords[prefixedPro] == nil { GIR.refRecords[prefixedPro] = typeRef }
// if GIR.refRecords[prefixedCls] == nil { GIR.refRecords[prefixedCls] = typeRef }
// if GIR.refRecords[prefixedRef] == nil { GIR.refRecords[prefixedRef] = typeRef }
// if GIR.refRecords[prefixedType] == nil { GIR.refRecords[prefixedType] = typeRef }
}
/// Name of the Protocol for this record
@inlinable
public var protocolName: String { typeRef.type.swiftName.protocolName }
/// Name of the `Ref` struct for this record
@inlinable
public var structName: String { typeRef.type.swiftName + "Ref" }
/// Type of the Class for this record
@inlinable public var classType: GIRRecordType {
let n = typeRef.type.swiftName.swift
return GIRRecordType(name: n, typeName: n, ctype: typeRef.type.ctype)
}
/// Type of the Protocol for this record
@inlinable public var protocolType: GIRType { GIRType(name: protocolName, in: typeRef.namespace, typeName: protocolName, ctype: "") }
/// Protocol reference for this record
@inlinable public var protocolRef: TypeReference { TypeReference(type: protocolType) }
/// Type of the `Ref` struct for this record
@inlinable
public var structType: GIRRecordType { GIRRecordType(name: structName, in: typeRef.namespace, typeName: structName, ctype: "", superType: protocolRef) }
/// Struct reference for this record
@inlinable public var structRef: TypeReference { TypeReference(type: structType) }
/// Class reference for this record
@inlinable public var classRef: TypeReference { TypeReference(type: classType) }
/// return the first method where the passed predicate closure returns `true`
public func methodMatching(_ predictate: (Method) -> Bool) -> Method? {
return allMethods.lazy.filter(predictate).first
}
/// return the first inherited method where the passed predicate closure returns `true`
public func inheritedMethodMatching(_ predictate: (Method) -> Bool) -> Method? {
return inheritedMethods.lazy.filter(predictate).first
}
/// return the first of my own or inherited methods where the passed predicate closure returns `true`
public func anyMethodMatching(_ predictate: (Method) -> Bool) -> Method? {
if let match = methodMatching(predictate) { return match }
return inheritedMethodMatching(predictate)
}
/// return the `retain` (ref) method for the given record, if any
public var ref: Method? { return anyMethodMatching { $0.isRef && $0.args.first!.isInstanceOfHierarchy(self) } }
/// return the `release` (unref) method for the given record, if any
public var unref: Method? { return anyMethodMatching { $0.isUnref && $0.args.first!.isInstanceOfHierarchy(self) } }
/// return whether the record or one of its parents has a given property
public func has(property name: String) -> Bool {
guard properties.first(where: { $0.name == name }) == nil else { return true }
guard let parent = parentType else { return false }
return parent.has(property: name)
}
/// return only the properties that are not derived
public var nonDerivedProperties: [Property] {
guard let parent = parentType else { return properties }
return properties.filter { !parent.has(property: $0.name) }
}
/// return all properties, including the ones derived from ancestors
public var allProperties: [Property] {
guard let parent = parentType else { return properties }
let all = Set(properties).union(Set(parent.allProperties))
return all.sorted()
}
/// return all signals, including the ones derived from ancestors
public var allSignals: [Signal] {
guard let parent = parentType else { return signals }
let all = Set(signals).union(Set(parent.allSignals))
return all.sorted()
}
var classInstanceType: GIR.Record? {
self.isGTypeStructForType.flatMap { GIR.knownRecords[$0] }
}
}
}
|
bsd-2-clause
|
cf6e02ca57c0256abc62c1eaebe8e274
| 50.396154 | 449 | 0.611015 | 4.375573 | false | false | false | false |
tiger8888/LayerPlayer
|
LayerPlayer/UIImage+TileCutter.swift
|
3
|
2291
|
//
// UIImage+TileCutter.swift
// LayerPlayer
//
// Created by Scott Gardner on 7/27/14.
// Copyright (c) 2014 Scott Gardner. All rights reserved.
//
// Adapted from Nick Lockwood's Terminal app in his book, iOS Core Animation: Advanced Techniques
// http://www.informit.com/store/ios-core-animation-advanced-techniques-9780133440751
//
import UIKit
extension UIImage {
class func saveTileOfSize(size: CGSize, name: String) -> () {
let cachesPath = NSSearchPathForDirectoriesInDomains(.CachesDirectory, .UserDomainMask, true)[0] as String
let filePath = "\(cachesPath)/\(name)_0_0.png"
let fileManager = NSFileManager.defaultManager()
let fileExists = fileManager.fileExistsAtPath(filePath)
if fileExists == false {
var tileSize = size
let scale = Float(UIScreen.mainScreen().scale)
if let image = UIImage(named: "\(name).jpg") {
let imageRef = image.CGImage
let totalColumns = Int(ceilf(Float(image.size.width / tileSize.width)) * scale)
let totalRows = Int(ceilf(Float(image.size.height / tileSize.height)) * scale)
let partialColumnWidth = Int(image.size.width % tileSize.width)
let partialRowHeight = Int(image.size.height % tileSize.height)
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), {
for y in 0..<totalRows {
for x in 0..<totalColumns {
if partialRowHeight > 0 && y + 1 == totalRows {
tileSize.height = CGFloat(partialRowHeight)
}
if partialColumnWidth > 0 && x + 1 == totalColumns {
tileSize.width = CGFloat(partialColumnWidth)
}
let xOffset = CGFloat(x) * tileSize.width
let yOffset = CGFloat(y) * tileSize.height
let point = CGPoint(x: xOffset, y: yOffset)
let tileImageRef = CGImageCreateWithImageInRect(imageRef, CGRect(origin: point, size: tileSize))
let imageData = UIImagePNGRepresentation(UIImage(CGImage: tileImageRef))
let path = "\(cachesPath)/\(name)_\(x)_\(y).png"
imageData?.writeToFile(path, atomically: false)
}
}
})
}
}
}
}
|
mit
|
16be6c225a727445192524f469208b45
| 38.5 | 110 | 0.616325 | 4.380497 | false | false | false | false |
jeremiahyan/ResearchKit
|
samples/ORKSample/ORKSample/ActivityViewController.swift
|
3
|
5924
|
/*
Copyright (c) 2015, Apple Inc. All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation and/or
other materials provided with the distribution.
3. Neither the name of the copyright holder(s) nor the names of any contributors
may be used to endorse or promote products derived from this software without
specific prior written permission. No license is granted to the trademarks of
the copyright holders even if such marks are included in this software.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import UIKit
import ResearchKit
enum Activity: Int {
case survey, microphone, tapping, trailmaking
static var allValues: [Activity] {
var index = 0
return Array(
AnyIterator {
let returnedElement = self.init(rawValue: index)
index += 1
return returnedElement
}
)
}
var title: String {
switch self {
case .survey:
return "Survey"
case .microphone:
return "Microphone"
case .tapping:
return "Tapping"
case .trailmaking:
return "Trail Making Test"
}
}
var subtitle: String {
switch self {
case .survey:
return "Answer 6 short questions"
case .microphone:
return "Voice evaluation"
case .tapping:
return "Test tapping speed"
case .trailmaking:
return "Test visual attention"
}
}
}
class ActivityViewController: UITableViewController {
// MARK: UITableViewDataSource
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
guard section == 0 else { return 0 }
return Activity.allValues.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "activityCell", for: indexPath)
if let activity = Activity(rawValue: (indexPath as NSIndexPath).row) {
cell.textLabel?.text = activity.title
cell.detailTextLabel?.text = activity.subtitle
}
return cell
}
// MARK: UITableViewDelegate
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
guard let activity = Activity(rawValue: (indexPath as NSIndexPath).row) else { return }
let taskViewController: ORKTaskViewController
switch activity {
case .survey:
taskViewController = ORKTaskViewController(task: StudyTasks.surveyTask, taskRun: NSUUID() as UUID)
case .microphone:
taskViewController = ORKTaskViewController(task: StudyTasks.microphoneTask, taskRun: NSUUID() as UUID)
do {
let defaultFileManager = FileManager.default
// Identify the documents directory.
let documentsDirectory = try defaultFileManager.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false)
// Create a directory based on the `taskRunUUID` to store output from the task.
let outputDirectory = documentsDirectory.appendingPathComponent(taskViewController.taskRunUUID.uuidString)
try defaultFileManager.createDirectory(at: outputDirectory, withIntermediateDirectories: true, attributes: nil)
taskViewController.outputDirectory = outputDirectory
} catch let error as NSError {
fatalError("The output directory for the task with UUID: \(taskViewController.taskRunUUID.uuidString) could not be created. Error: \(error.localizedDescription)")
}
case .tapping:
taskViewController = ORKTaskViewController(task: StudyTasks.tappingTask, taskRun: NSUUID() as UUID)
case .trailmaking:
taskViewController = ORKTaskViewController(task: StudyTasks.trailmakingTask, taskRun: NSUUID() as UUID)
}
taskViewController.delegate = self
navigationController?.present(taskViewController, animated: true, completion: nil)
}
}
extension ActivityViewController: ORKTaskViewControllerDelegate {
func taskViewController(_ taskViewController: ORKTaskViewController, didFinishWith reason: ORKTaskViewControllerFinishReason, error: Error?) {
// Handle results using taskViewController.result
taskViewController.dismiss(animated: true, completion: nil)
}
}
|
bsd-3-clause
|
de1404773ec3fd935229693d9185a15d
| 41.014184 | 182 | 0.662559 | 5.583412 | false | false | false | false |
AppriaTT/Swift_SelfLearning
|
Swift/swift10 videoBG/swift10 videoBG/VideoCutter.swift
|
1
|
2857
|
//
// VideoCutter.swift
// swift10 videoBG
//
// Created by Aaron on 16/7/14.
// Copyright © 2016年 Aaron. All rights reserved.
//
import UIKit
import AVFoundation
extension String {
var convert: NSString { return (self as NSString) }
}
public class VideoCutter: NSObject {
/**
Block based method for crop video url
@param videoUrl Video url
@param startTime The starting point of the video segments
@param duration Total time, video length
*/
public func cropVideoWithUrl(videoUrl url: NSURL, startTime: CGFloat, duration: CGFloat, completion: ((videoPath: NSURL?, error: NSError?) -> Void)?) {
let priority = DISPATCH_QUEUE_PRIORITY_DEFAULT
dispatch_async(dispatch_get_global_queue(priority, 0)) {
let asset = AVURLAsset(URL: url, options: nil)
let exportSession = AVAssetExportSession(asset: asset, presetName: "AVAssetExportPresetHighestQuality")
let paths: NSArray = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)
var outputURL = paths.objectAtIndex(0) as! String
let manager = NSFileManager.defaultManager()
do {
try manager.createDirectoryAtPath(outputURL, withIntermediateDirectories: true, attributes: nil)
} catch _ {
}
outputURL = outputURL.convert.stringByAppendingPathComponent("output.mp4")
do {
try manager.removeItemAtPath(outputURL)
} catch _ {
}
if let exportSession = exportSession as AVAssetExportSession? {
exportSession.outputURL = NSURL(fileURLWithPath: outputURL)
exportSession.shouldOptimizeForNetworkUse = true
exportSession.outputFileType = AVFileTypeMPEG4
let start = CMTimeMakeWithSeconds(Float64(startTime), 600)
let duration = CMTimeMakeWithSeconds(Float64(duration), 600)
let range = CMTimeRangeMake(start, duration)
exportSession.timeRange = range
exportSession.exportAsynchronouslyWithCompletionHandler { () -> Void in
switch exportSession.status {
case AVAssetExportSessionStatus.Completed:
completion?(videoPath: exportSession.outputURL, error: nil)
case AVAssetExportSessionStatus.Failed:
print("Failed: \(exportSession.error)")
case AVAssetExportSessionStatus.Cancelled:
print("Failed: \(exportSession.error)")
default:
print("default case")
}
}
}
// dispatch_async(dispatch_get_main_queue()) {
// }
}
}
}
|
mit
|
05445032f87913ef09b0966144c48cc9
| 39.197183 | 155 | 0.603364 | 5.651485 | false | false | false | false |
groue/GRDB.swift
|
GRDB/QueryInterface/Request/RequestProtocols.swift
|
1
|
52656
|
import Foundation
// MARK: - TypedRequest
/// A request that knows how to decode database rows.
public protocol TypedRequest<RowDecoder> {
/// The type that can decode database rows.
///
/// For example, it is `Player` in the request below:
///
/// ```swift
/// let request = Player.all()
/// ```
associatedtype RowDecoder
}
// MARK: - SelectionRequest
/// A request that can define the selected columns.
///
/// ## Topics
///
/// ### The SELECT Clause
///
/// - ``annotated(with:)-4qcem``
/// - ``annotated(with:)-6ehs4``
/// - ``annotatedWhenConnected(with:)``
/// - ``select(_:)-30yzl``
/// - ``select(_:)-7e2y5``
/// - ``select(literal:)``
/// - ``select(sql:arguments:)``
/// - ``selectWhenConnected(_:)``
public protocol SelectionRequest {
/// Defines the result columns.
///
/// The `selection` parameter is a closure that accepts a database
/// connection and returns an array of result columns. It is evaluated when
/// the request has an access to the database, and can perform database
/// requests in order to build its result.
///
/// For example:
///
/// ```swift
/// // SELECT id, name FROM player
/// let request = Player.all().selectWhenConnected { db in
/// [Column("id"), Column("name")]
/// }
/// ```
///
/// Any previous selection is discarded:
///
/// ```swift
/// // SELECT name FROM player
/// let request = Player.all()
/// .selectWhenConnected { db in [Column("id")] }
/// .selectWhenConnected { db in [Column("name")] }
/// ```
///
/// - parameter selection: A closure that accepts a database connection and
/// returns an array of result columns.
func selectWhenConnected(_ selection: @escaping (Database) throws -> [any SQLSelectable]) -> Self
/// Appends result columns to the selected columns.
///
/// The `selection` parameter is a closure that accepts a database
/// connection and returns an array of result columns. It is evaluated when
/// the request has an access to the database, and can perform database
/// requests in order to build its result.
///
/// For example:
///
/// ```swift
/// // SELECT *, score + bonus AS totalScore FROM player
/// let request = Player.all().annotatedWhenConnected { db in
/// [(Column("score") + Column("bonus")).forKey("totalScore")]
/// }
/// ```
///
/// - parameter selection: A closure that accepts a database connection and
/// returns an array of result columns.
func annotatedWhenConnected(with selection: @escaping (Database) throws -> [any SQLSelectable]) -> Self
}
extension SelectionRequest {
/// Defines the result columns.
///
/// For example:
///
/// ```swift
/// // SELECT id, score FROM player
/// let request = Player.all().select([Column("id"), Column("score")])
/// ```
///
/// Any previous selection is replaced:
///
/// ```swift
/// // SELECT score FROM player
/// let request = Player.all()
/// .select([Column("id")])
/// .select([Column("score")])
/// ```
public func select(_ selection: [any SQLSelectable]) -> Self {
selectWhenConnected { _ in selection }
}
/// Defines the result columns.
///
/// For example:
///
/// ```swift
/// // SELECT id, score FROM player
/// let request = Player.all().select(Column("id"), Column("score"))
/// ```
///
/// Any previous selection is discarded:
///
/// ```swift
/// // SELECT score FROM player
/// let request = Player.all()
/// .select(Column("id"))
/// .select(Column("score"))
/// ```
public func select(_ selection: any SQLSelectable...) -> Self {
select(selection)
}
/// Defines the result columns with an SQL string.
///
/// For example:
///
/// ```swift
/// // SELECT id, name FROM player
/// let request = Player.all()
/// .select(sql: "id, name")
///
/// // SELECT id, IFNULL(name, 'Anonymous') FROM player
/// let defaultName = "Anonymous"
/// let request = Player.all()
/// .select(sql: "id, IFNULL(name, ?)", arguments: [defaultName])
/// ```
///
/// Any previous selection is discarded:
///
/// ```swift
/// // SELECT score FROM player
/// let request = Player.all()
/// .select(sql: "id")
/// .select(sql: "name")
/// ```
public func select(sql: String, arguments: StatementArguments = StatementArguments()) -> Self {
select(SQL(sql: sql, arguments: arguments))
}
/// Defines the result columns with an ``SQL`` literal.
///
/// ``SQL`` literals allow you to safely embed raw values in your SQL,
/// without any risk of syntax errors or SQL injection:
///
/// ```swift
/// // SELECT id, IFNULL(name, 'Anonymous') FROM player
/// let defaultName = "Anonymous"
/// let request = Player.all()
/// .select(literal: "id, IFNULL(name, \(defaultName))")
/// ```
///
/// Any previous selection is discarded:
///
/// ```swift
/// // SELECT IFNULL(name, 'Anonymous') FROM player
/// let request = Player.all()
/// .select(literal: "id")
/// .select(literal: "IFNULL(name, \(defaultName))")
/// ```
public func select(literal sqlLiteral: SQL) -> Self {
// NOT TESTED
select(sqlLiteral)
}
/// Appends result columns to the selected columns.
///
/// For example:
///
/// ```swift
/// // SELECT *, score + bonus AS totalScore FROM player
/// let totalScore = (Column("score") + Column("bonus")).forKey("totalScore")
/// let request = Player.all().annotated(with: [totalScore])
/// ```
public func annotated(with selection: [any SQLSelectable]) -> Self {
annotatedWhenConnected(with: { _ in selection })
}
/// Appends result columns to the selected columns.
///
/// For example:
///
/// ```swift
/// // SELECT *, score + bonus AS totalScore FROM player
/// let totalScore = (Column("score") + Column("bonus")).forKey("totalScore")
/// let request = Player.all().annotated(with: totalScore)
/// ```
public func annotated(with selection: any SQLSelectable...) -> Self {
annotated(with: selection)
}
}
// MARK: - FilteredRequest
/// A request that can filter database rows.
///
/// The filter applies to the `WHERE` clause, or to the `ON` clause of
/// an SQL join.
///
/// ## Topics
///
/// ### The WHERE and JOIN ON Clauses
///
/// - ``filter(_:)``
/// - ``filter(literal:)``
/// - ``filter(sql:arguments:)``
/// - ``filterWhenConnected(_:)``
/// - ``none()``
public protocol FilteredRequest {
/// Filters the fetched rows with a boolean SQL expression.
///
/// The `predicate` parameter is a closure that accepts a database
/// connection and returns a boolean SQL expression. It is evaluated when
/// the request has an access to the database, and can perform database
/// requests in order to build its result.
///
/// For example:
///
/// ```swift
/// // SELECT * FROM player WHERE name = 'O''Brien'
/// let name = "O'Brien"
/// let request = Player.all().filterWhenConnected { db in
/// Column("name") == name
/// }
/// ```
///
/// - parameter predicate: A closure that accepts a database connection and
/// returns a boolean SQL expression.
func filterWhenConnected(_ predicate: @escaping (Database) throws -> any SQLExpressible) -> Self
}
extension FilteredRequest {
// Accept SQLSpecificExpressible instead of SQLExpressible, so that we
// prevent the `Player.filter(42)` misuse.
// See https://github.com/groue/GRDB.swift/pull/864
/// Filters the fetched rows with a boolean SQL expression.
///
/// For example:
///
/// ```swift
/// // SELECT * FROM player WHERE name = 'O''Brien'
/// let name = "O'Brien"
/// let request = Player.all().filter(Column("name") == name)
/// ```
public func filter(_ predicate: some SQLSpecificExpressible) -> Self {
filterWhenConnected { _ in predicate }
}
/// Filters the fetched rows with an SQL string.
///
/// For example:
///
/// ```swift
/// // SELECT * FROM player WHERE name = 'O''Brien'
/// let name = "O'Brien"
/// let request = Player.all().filter(sql: "name = ?", arguments: [name])
/// ```
public func filter(sql: String, arguments: StatementArguments = StatementArguments()) -> Self {
filter(SQL(sql: sql, arguments: arguments))
}
/// Filters the fetched rows with an ``SQL`` literal.
///
/// ``SQL`` literals allow you to safely embed raw values in your SQL,
/// without any risk of syntax errors or SQL injection:
///
/// ```swift
/// // SELECT * FROM player WHERE name = 'O''Brien'
/// let name = "O'Brien"
/// let request = Player.all().filter(literal: "name = \(name)")
/// ```
public func filter(literal sqlLiteral: SQL) -> Self {
// NOT TESTED
filter(sqlLiteral)
}
/// Returns an empty request that fetches no row.
public func none() -> Self {
filterWhenConnected { _ in false }
}
}
// MARK: - TableRequest
/// A request that feeds from a database table
///
/// ## Topics
///
/// ## The Database Table
///
/// - ``databaseTableName``
///
/// ### Instance Methods
///
/// - ``aliased(_:)``
/// - ``TableAlias``
///
/// ### The WHERE Clause
///
/// - ``filter(id:)``
/// - ``filter(ids:)``
/// - ``filter(key:)-1p9sq``
/// - ``filter(key:)-2te6v``
/// - ``filter(keys:)-6ggt1``
/// - ``filter(keys:)-8fbn9``
/// - ``matching(_:)``
///
/// ### The GROUP BY and HAVING Clauses
///
/// - ``groupByPrimaryKey()``
///
/// ### The ORDER BY Clause
///
/// - ``orderByPrimaryKey()``
public protocol TableRequest {
/// The name of the database table
var databaseTableName: String { get }
/// Returns a request that can be referred to with the provided alias.
///
/// Use this method when you need to refer to this request from
/// another request.
///
/// The first example fetches posthumous books:
///
/// ```swift
/// struct Author: TableRecord, FetchableRecord { }
/// struct Book: TableRecord, FetchableRecord {
/// static let author = belongsTo(Author.self)
/// }
///
/// // SELECT book.*
/// // FROM book
/// // JOIN author ON author.id = book.authorId
/// // WHERE book.publishDate >= author.deathDate
/// let authorAlias = TableAlias()
/// let posthumousBooks = try Book
/// .joining(required: Book.author.aliased(authorAlias))
/// .filter(Column("publishDate") >= authorAlias[Column("deathDate")])
/// .fetchAll(db)
/// ```
///
/// The second example sorts books by author name first, and then by title:
///
/// ```swift
/// // SELECT book.*
/// // FROM book
/// // JOIN author ON author.id = book.authorId
/// // ORDER BY author.name, book.title
/// let authorAlias = TableAlias()
/// let books = try Book
/// .joining(required: Book.author.aliased(authorAlias))
/// .order(authorAlias[Column("name")], Column("title"))
/// .fetchAll(db)
/// ```
///
/// The third example uses named ``TableAlias`` so that SQL snippets can
/// refer to SQL tables with those names:
///
/// ```swift
/// // SELECT b.*
/// // FROM book b
/// // JOIN author a ON a.id = b.authorId
/// // AND a.countryCode = 'FR'
/// // WHERE b.publishDate >= a.deathDate
/// let bookAlias = TableAlias(name: "b")
/// let authorAlias = TableAlias(name: "a")
/// let posthumousFrenchBooks = try Book.aliased(bookAlias)
/// .joining(required: Book.author.aliased(authorAlias)
/// .filter(sql: "a.countryCode = ?", arguments: ["FR"]))
/// .filter(sql: "b.publishDate >= a.deathDate")
/// .fetchAll(db)
/// ```
func aliased(_ alias: TableAlias) -> Self
}
extension TableRequest where Self: FilteredRequest, Self: TypedRequest {
/// Filters by primary key.
///
/// All single-column primary keys are supported:
///
/// ```swift
/// // SELECT * FROM player WHERE id = 1
/// let request = Player.all().filter(key: 1)
///
/// // SELECT * FROM country WHERE code = 'FR'
/// let request = Country.all().filter(key: "FR")
/// ```
///
/// - parameter key: A primary key
public func filter(key: some DatabaseValueConvertible) -> Self {
if key.databaseValue.isNull {
return none()
}
return filter(keys: [key])
}
/// Filters by primary key.
///
/// All single-column primary keys are supported:
///
/// ```swift
/// // SELECT * FROM player WHERE id = IN (1, 2, 3)
/// let request = Player.all().filter(keys: [1, 2, 3])
///
/// // SELECT * FROM country WHERE code = IN ('FR', 'US')
/// let request = Country.all().filter(keys: ["FR", "US"])
/// ```
///
/// - parameter keys: A collection of primary keys
public func filter<Sequence: Swift.Sequence>(keys: Sequence)
-> Self
where Sequence.Element: DatabaseValueConvertible
{
// In order to encode keys in the database, we perform a runtime check
// for EncodableRecord, and look for a customized encoding strategy.
// Such dynamic dispatch is unusual in GRDB, but static dispatch
// (customizing TableRequest where RowDecoder: EncodableRecord) would
// make it impractical to define `filter(id:)`, `fetchOne(_:key:)`,
// `deleteAll(_:ids:)` etc.
if let recordType = RowDecoder.self as? any EncodableRecord.Type {
if Sequence.Element.self == Date.self || Sequence.Element.self == Optional<Date>.self {
let strategy = recordType.databaseDateEncodingStrategy
let keys = keys.compactMap { ($0 as! Date?).flatMap(strategy.encode)?.databaseValue }
return filter(rawKeys: keys)
} else if Sequence.Element.self == UUID.self || Sequence.Element.self == Optional<UUID>.self {
let strategy = recordType.databaseUUIDEncodingStrategy
let keys = keys.map { ($0 as! UUID?).map(strategy.encode)?.databaseValue }
return filter(rawKeys: keys)
}
}
return filter(rawKeys: keys)
}
/// Creates a request filtered by primary key.
///
/// // SELECT * FROM player WHERE ... id IN (1, 2, 3)
/// let request = try Player...filter(rawKeys: [1, 2, 3])
///
/// - parameter keys: A collection of primary keys
func filter<Keys>(rawKeys: Keys) -> Self
where Keys: Sequence, Keys.Element: DatabaseValueConvertible
{
// Don't bother removing NULLs. We'd lose CPU cycles, and this does not
// change the SQLite results anyway.
let expressions = rawKeys.map {
$0.databaseValue.sqlExpression
}
if expressions.isEmpty {
// Don't hit the database
return none()
}
let databaseTableName = self.databaseTableName
return filterWhenConnected { db in
let primaryKey = try db.primaryKey(databaseTableName)
GRDBPrecondition(
primaryKey.columns.count == 1,
"Requesting by key requires a single-column primary key in the table \(databaseTableName)")
return SQLCollection.array(expressions).contains(Column(primaryKey.columns[0]).sqlExpression)
}
}
/// Filters by primary or unique key.
///
/// For example:
///
/// ```swift
/// // SELECT * FROM player WHERE id = 1
/// let request = Player.all().filter(key: ["id": 1])
///
/// // SELECT * FROM player WHERE email = 'arthur@example.com'
/// let request = Player.all().filter(key: ["email": "arthur@example.com"])
///
/// // SELECT * FROM citizenship WHERE citizenId = 1 AND countryCode = 'FR'
/// let request = Citizenship.all().filter(key: [
/// "citizenId": 1,
/// "countryCode": "FR",
/// ])
/// ```
///
/// When executed, this request raises a fatal error if no unique index
/// exists on a subset of the key columns.
///
/// - parameter key: A unique key.
public func filter(key: [String: (any DatabaseValueConvertible)?]?) -> Self {
guard let key else {
return none()
}
return filter(keys: [key])
}
/// Filters by primary or unique key.
///
/// For example:
///
/// ```swift
/// // SELECT * FROM player WHERE id = 1
/// let request = Player.all().filter(keys: [["id": 1]])
///
/// // SELECT * FROM player WHERE email = 'arthur@example.com'
/// let request = Player.all().filter(keys: [["email": "arthur@example.com"]])
///
/// // SELECT * FROM citizenship WHERE citizenId = 1 AND countryCode = 'FR'
/// let request = Citizenship.all().filter(keys: [
/// ["citizenId": 1, "countryCode": "FR"],
/// ])
/// ```
///
/// When executed, this request raises a fatal error if no unique index
/// exists on a subset of the key columns.
///
/// - parameter keys: A collection of unique keys
public func filter(keys: [[String: (any DatabaseValueConvertible)?]]) -> Self {
if keys.isEmpty {
return none()
}
let databaseTableName = self.databaseTableName
return filterWhenConnected { db in
try keys
.map { key in
// Prevent filter(keys: [["foo": 1, "bar": 2]]) where
// ("foo", "bar") do not contain a unique key (primary key
// or unique index).
guard let columns = try db.columnsForUniqueKey(key.keys, in: databaseTableName) else {
fatalError("""
table \(databaseTableName) has no unique key on column(s) \
\(key.keys.sorted().joined(separator: ", "))
""")
}
let lowercaseColumns = columns.map { $0.lowercased() }
return key
// Preserve ordering of columns in the unique index
.sorted { (kv1, kv2) in
guard let index1 = lowercaseColumns.firstIndex(of: kv1.key.lowercased()) else {
// We allow extra columns which are not in the unique key
// Put them last in the query
return false
}
guard let index2 = lowercaseColumns.firstIndex(of: kv2.key.lowercased()) else {
// We allow extra columns which are not in the unique key
// Put them last in the query
return true
}
return index1 < index2
}
.map { (column, value) in Column(column) == value }
.joined(operator: .and)
}
.joined(operator: .or)
}
}
}
@available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6, *)
extension TableRequest
where Self: FilteredRequest,
Self: TypedRequest,
RowDecoder: Identifiable,
RowDecoder.ID: DatabaseValueConvertible
{
/// Filters by primary key.
///
/// All single-column primary keys are supported:
///
/// ```swift
/// // SELECT * FROM player WHERE id = 1
/// let request = Player.all().filter(id: 1)
///
/// // SELECT * FROM country WHERE code = 'FR'
/// let request = Country.all().filter(id: "FR")
/// ```
///
/// - parameter id: A primary key
public func filter(id: RowDecoder.ID) -> Self {
filter(key: id)
}
/// Filters by primary key.
///
/// All single-column primary keys are supported:
///
/// ```swift
/// // SELECT * FROM player WHERE id = IN (1, 2, 3)
/// let request = Player.all().filter(ids: [1, 2, 3])
///
/// // SELECT * FROM country WHERE code = IN ('FR', 'US')
/// let request = Country.all().filter(ids: ["FR", "US"])
/// ```
///
/// - parameter ids: A collection of primary keys
public func filter<IDS>(ids: IDS) -> Self
where IDS: Collection, IDS.Element == RowDecoder.ID
{
filter(keys: ids)
}
}
extension TableRequest where Self: OrderedRequest {
/// Sorts the fetched rows according to the primary key.
///
/// All primary keys are supported:
///
/// ```swift
/// // SELECT * FROM player ORDER BY id
/// let request = Player.all().orderByPrimaryKey()
///
/// // SELECT * FROM country ORDER BY code
/// let request = Country.all().orderByPrimaryKey()
///
/// // SELECT * FROM citizenship ORDER BY citizenId, countryCode
/// let request = Citizenship.all().orderByPrimaryKey()
/// ```
///
/// Any previous ordering is discarded.
public func orderByPrimaryKey() -> Self {
let tableName = self.databaseTableName
return orderWhenConnected { db in
try db.primaryKey(tableName).columns.map(SQLExpression.column)
}
}
}
extension TableRequest where Self: AggregatingRequest {
/// Returns an aggregate request grouped on the primary key.
///
/// Any previous grouping is discarded.
public func groupByPrimaryKey() -> Self {
let tableName = self.databaseTableName
return groupWhenConnected { db in
let primaryKey = try db.primaryKey(tableName)
if let rowIDColumn = primaryKey.rowIDColumn {
// Prefer the user-provided name of the rowid:
//
// // CREATE TABLE player (id INTEGER PRIMARY KEY, ...)
// // SELECT * FROM player GROUP BY id
// Player.all().groupByPrimaryKey()
return [Column(rowIDColumn)]
} else if primaryKey.tableHasRowID {
// Prefer the rowid
//
// // CREATE TABLE player (uuid TEXT NOT NULL PRIMARY KEY, ...)
// // SELECT * FROM player GROUP BY rowid
// Player.all().groupByPrimaryKey()
return [.rowID]
} else {
// WITHOUT ROWID table: group by primary key columns
//
// // CREATE TABLE player (uuid TEXT NOT NULL PRIMARY KEY, ...) WITHOUT ROWID
// // SELECT * FROM player GROUP BY uuid
// Player.all().groupByPrimaryKey()
return primaryKey.columns.map { Column($0) }
}
}
}
}
// MARK: - AggregatingRequest
/// A request that can aggregate database rows.
///
/// ## Topics
///
/// ### The GROUP BY Clause
///
/// - ``group(_:)-edak``
/// - ``group(_:)-4216o``
/// - ``group(literal:)``
/// - ``group(sql:arguments:)``
/// - ``groupWhenConnected(_:)``
///
/// ### The HAVING Clause
///
/// - ``having(_:)``
/// - ``having(literal:)``
/// - ``having(sql:arguments:)``
/// - ``havingWhenConnected(_:)``
public protocol AggregatingRequest {
/// Returns an aggregate request grouped on the given SQL expressions.
///
/// The `expressions` parameter is a closure that accepts a database
/// connection and returns an array of grouping SQL expressions. It is
/// evaluated when the request has an access to the database, and can
/// perform database requests in order to build its result.
///
/// For example:
///
/// ```swift
/// // SELECT teamId, MAX(score)
/// // FROM player
/// // GROUP BY teamId
/// let request = Player
/// .select(Column("teamId"), max(Column("score")))
/// .groupWhenConnected { db in [Column("teamId")] }
/// ```
///
/// Any previous grouping is discarded.
///
/// - parameter expressions: A closure that accepts a database connection
/// and returns an array of SQL expressions.
func groupWhenConnected(_ expressions: @escaping (Database) throws -> [any SQLExpressible]) -> Self
/// Filters the aggregated groups with a boolean SQL expression.
///
/// The `predicate` parameter is a closure that accepts a database
/// connection and returns a boolean SQL expression. It is evaluated when
/// the request has an access to the database, and can perform database
/// requests in order to build its result.
///
/// For example:
///
/// ```swift
/// // SELECT teamId, MAX(score)
/// // FROM player
/// // GROUP BY teamId
/// // HAVING MAX(score) > 1000
/// let request = Player
/// .select(Column("teamId"), max(Column("score")))
/// .group(Column("teamId"))
/// .havingWhenConnected { db in max(Column("score")) > 1000 }
/// ```
///
/// - parameter predicate: A closure that accepts a database connection and
/// returns a boolean SQL expression.
func havingWhenConnected(_ predicate: @escaping (Database) throws -> any SQLExpressible) -> Self
}
extension AggregatingRequest {
/// Returns an aggregate request grouped on the given SQL expressions.
///
/// For example:
///
/// ```swift
/// // SELECT teamId, MAX(score)
/// // FROM player
/// // GROUP BY teamId
/// let request = Player
/// .select(Column("teamId"), max(Column("score")))
/// .group([Column("teamId")])
/// ```
///
/// Any previous grouping is discarded.
///
/// - parameter expressions: An array of SQL expressions.
public func group(_ expressions: [any SQLExpressible]) -> Self {
groupWhenConnected { _ in expressions }
}
/// Returns an aggregate request grouped on the given SQL expressions.
///
/// For example:
///
/// ```swift
/// // SELECT teamId, MAX(score)
/// // FROM player
/// // GROUP BY teamId
/// let request = Player
/// .select(Column("teamId"), max(Column("score")))
/// .group(Column("teamId"))
/// ```
///
/// Any previous grouping is discarded.
///
/// - parameter expressions: An array of SQL expressions.
public func group(_ expressions: any SQLExpressible...) -> Self {
group(expressions)
}
/// Returns an aggregate request grouped on an SQL string.
///
/// For example:
///
/// ```swift
/// // SELECT teamId, MAX(score)
/// // FROM player
/// // GROUP BY teamId
/// let request = Player
/// .select(Column("teamId"), max(Column("score")))
/// .group(sql: "teamId")
/// ```
///
/// Any previous grouping is discarded.
public func group(sql: String, arguments: StatementArguments = StatementArguments()) -> Self {
group(SQL(sql: sql, arguments: arguments))
}
/// Returns an aggregate request grouped on an ``SQL`` literal.
///
/// For example:
///
/// ```swift
/// // SELECT teamId, MAX(score)
/// // FROM player
/// // GROUP BY teamId
/// let request = Player
/// .select(Column("teamId"), max(Column("score")))
/// .group(literal: "teamId")
/// ```
///
/// Any previous grouping is discarded.
public func group(literal sqlLiteral: SQL) -> Self {
// NOT TESTED
group(sqlLiteral)
}
/// Filters the aggregated groups with a boolean SQL expression.
///
/// For example:
///
/// ```swift
/// // SELECT teamId, MAX(score)
/// // FROM player
/// // GROUP BY teamId
/// // HAVING MAX(score) > 1000
/// let request = Player
/// .select(Column("teamId"), max(Column("score")))
/// .group(Column("teamId"))
/// .having(max(Column("score")) > 1000)
/// ```
public func having(_ predicate: some SQLExpressible) -> Self {
havingWhenConnected { _ in predicate }
}
/// Filters the aggregated groups with an SQL string.
///
/// For example:
///
/// ```swift
/// // SELECT teamId, MAX(score)
/// // FROM player
/// // GROUP BY teamId
/// // HAVING MAX(score) > 1000
/// let request = Player
/// .select(Column("teamId"), max(Column("score")))
/// .group(Column("teamId"))
/// .having(sql: "MAX(score) > 1000")
/// ```
public func having(sql: String, arguments: StatementArguments = StatementArguments()) -> Self {
having(SQL(sql: sql, arguments: arguments))
}
/// Filters the aggregated groups with an ``SQL`` literal.
///
/// For example:
///
/// ```swift
/// // SELECT teamId, MAX(score)
/// // FROM player
/// // GROUP BY teamId
/// // HAVING MAX(score) > 1000
/// let request = Player
/// .select(Column("teamId"), max(Column("score")))
/// .group(Column("teamId"))
/// .having(literal: "MAX(score) > 1000")
/// ```
public func having(literal sqlLiteral: SQL) -> Self {
// NOT TESTED
having(sqlLiteral)
}
}
// MARK: - OrderedRequest
/// A request that can sort database rows.
///
/// ## Topics
///
/// ### The ORDER BY Clause
///
/// - ``order(_:)-63rzl``
/// - ``order(_:)-6co0m``
/// - ``order(literal:)``
/// - ``order(sql:arguments:)``
/// - ``orderWhenConnected(_:)``
/// - ``reversed()``
/// - ``unordered()``
public protocol OrderedRequest {
/// Sorts the fetched rows according to the given SQL ordering terms.
///
/// The `orderings` parameter is a closure that accepts a database
/// connection and returns an array of SQL ordering terms. It is evaluated
/// when the request has an access to the database, and can perform database
/// requests in order to build its result.
///
/// For example:
///
/// ```swift
/// // SELECT * FROM player ORDER BY score DESC, name
/// let request = Player.all().orderWhenConnected { db in
/// [Column("score").desc, Column("name")]
/// }
/// ```
///
/// Any previous ordering is discarded:
///
/// ```swift
/// // SELECT * FROM player ORDER BY name
/// let request = Player.all()
/// .orderWhenConnected { db in [Column("score").desc] }
/// .orderWhenConnected { db in [Column("name")] }
/// ```
///
/// - parameter orderings: A closure that accepts a database connection and
/// returns an array of SQL ordering terms.
func orderWhenConnected(_ orderings: @escaping (Database) throws -> [any SQLOrderingTerm]) -> Self
/// Returns a request with reversed ordering.
///
/// For example:
///
/// ```swift
/// // SELECT * FROM player ORDER BY name DESC
/// let request = Player.all()
/// .order(Column("name"))
/// .reversed()
/// ```
///
/// If no ordering was already specified, this method has no effect:
///
/// ```swift
/// // SELECT * FROM player
/// let request = Player.all().reversed()
/// ```
func reversed() -> Self
/// Returns a request without any ordering.
///
/// For example:
///
/// ```swift
/// // SELECT * FROM player
/// let request = Player.all()
/// .order(Column("name"))
/// .unordered()
/// ```
func unordered() -> Self
}
extension OrderedRequest {
/// Sorts the fetched rows according to the given SQL ordering terms.
///
/// For example:
///
/// ```swift
/// // SELECT * FROM player ORDER BY score DESC, name
/// let request = Player.all()
/// .order(Column("score").desc, Column("name"))
/// ```
///
/// Any previous ordering is discarded:
///
/// ```swift
/// // SELECT * FROM player ORDER BY name
/// let request = Player.all()
/// .order(Column("score").desc)
/// .order(Column("name"))
/// ```
public func order(_ orderings: any SQLOrderingTerm...) -> Self {
orderWhenConnected { _ in orderings }
}
/// Sorts the fetched rows according to the given SQL ordering terms.
///
/// For example:
///
/// ```swift
/// // SELECT * FROM player ORDER BY score DESC, name
/// let request = Player.all()
/// .order([Column("score").desc, Column("name")])
/// ```
///
/// Any previous ordering is discarded:
///
/// ```swift
/// // SELECT * FROM player ORDER BY name
/// let request = Player.all()
/// .order([Column("score").desc])
/// .order([Column("name")])
/// ```
public func order(_ orderings: [any SQLOrderingTerm]) -> Self {
orderWhenConnected { _ in orderings }
}
/// Sorts the fetched rows according to the given SQL string.
///
/// For example:
///
/// ```swift
/// // SELECT * FROM player ORDER BY score DESC, name
/// let request = Player.all()
/// .order(sql: "score DESC, name")
/// ```
///
/// Any previous ordering is discarded.
public func order(sql: String, arguments: StatementArguments = StatementArguments()) -> Self {
order(SQL(sql: sql, arguments: arguments))
}
/// Sorts the fetched rows according to the given ``SQL`` literal.
///
/// For example:
///
/// ```swift
/// // SELECT * FROM player ORDER BY score DESC, name
/// let request = Player.all()
/// .order(literal: "score DESC, name")
/// ```
///
/// Any previous ordering is discarded.
public func order(literal sqlLiteral: SQL) -> Self {
// NOT TESTED
order(sqlLiteral)
}
}
// MARK: - JoinableRequest
/// A request that can join and prefetch associations.
///
/// `JoinableRequest` is adopted by ``QueryInterfaceRequest`` and all
/// types conforming to ``Association``.
///
/// It provides the methods that build requests involving several tables linked
/// through associations.
///
/// ## Topics
///
/// ### Extending the Selection with Columns of Associated Records
///
/// - ``annotated(withOptional:)``
/// - ``annotated(withRequired:)``
///
/// ### Prefetching Associated Records
///
/// - ``including(all:)``
/// - ``including(optional:)``
/// - ``including(required:)``
///
/// ### Joining Associated Records
///
/// - ``joining(optional:)``
/// - ``joining(required:)``
public protocol JoinableRequest<RowDecoder>: TypedRequest {
/// Creates a request that prefetches an association.
func _including(all association: _SQLAssociation) -> Self
/// Creates a request that includes an association. The columns of the
/// associated record are selected. The returned request does not
/// require that the associated database table contains a matching row.
func _including(optional association: _SQLAssociation) -> Self
/// Creates a request that includes an association. The columns of the
/// associated record are selected. The returned request requires
/// that the associated database table contains a matching row.
func _including(required association: _SQLAssociation) -> Self
/// Creates a request that joins an association. The columns of the
/// associated record are not selected. The returned request does not
/// require that the associated database table contains a matching row.
func _joining(optional association: _SQLAssociation) -> Self
/// Creates a request that joins an association. The columns of the
/// associated record are not selected. The returned request requires
/// that the associated database table contains a matching row.
func _joining(required association: _SQLAssociation) -> Self
}
extension JoinableRequest {
/// Returns a request that fetches all records associated with each record
/// in this request.
///
/// For example, we can fetch authors along with their books:
///
/// ```swift
/// struct Author: TableRecord, FetchableRecord, Decodable {
/// static let books = hasMany(Book.self)
/// }
/// struct Book: TableRecord, FetchableRecord, Decodable { }
///
/// struct AuthorInfo: FetchableRecord, Decodable {
/// var author: Author
/// var books: [Book]
/// }
///
/// let authorInfos = try Author.all()
/// .including(all: Author.books)
/// .asRequest(of: AuthorInfo.self)
/// .fetchAll(db)
/// ```
public func including<A: AssociationToMany>(all association: A) -> Self where A.OriginRowDecoder == RowDecoder {
_including(all: association._sqlAssociation)
}
/// Returns a request that fetches the eventual record associated with each
/// record of this request.
///
/// For example, we can fetch books along with their eventual author:
///
/// ```swift
/// struct Author: TableRecord, FetchableRecord, Decodable { }
/// struct Book: TableRecord, FetchableRecord, Decodable {
/// static let author = belongsTo(Author.self)
/// }
///
/// struct BookInfo: FetchableRecord, Decodable {
/// var book: Book
/// var author: Author?
/// }
///
/// let bookInfos = try Book.all()
/// .including(optional: Book.author)
/// .asRequest(of: BookInfo.self)
/// .fetchAll(db)
/// ```
public func including<A: Association>(optional association: A) -> Self where A.OriginRowDecoder == RowDecoder {
_including(optional: association._sqlAssociation)
}
/// Returns a request that fetches the record associated with each record in
/// this request. Records that do not have an associated record
/// are discarded.
///
/// For example, we can fetch books along with their eventual author:
///
/// ```swift
/// struct Author: TableRecord, FetchableRecord, Decodable { }
/// struct Book: TableRecord, FetchableRecord, Decodable {
/// static let author = belongsTo(Author.self)
/// }
///
/// struct BookInfo: FetchableRecord, Decodable {
/// var book: Book
/// var author: Author
/// }
///
/// let bookInfos = try Book.all()
/// .including(required: Book.author)
/// .asRequest(of: BookInfo.self)
/// .fetchAll(db)
/// ```
public func including<A: Association>(required association: A) -> Self where A.OriginRowDecoder == RowDecoder {
_including(required: association._sqlAssociation)
}
/// Returns a request that joins each record of this request to its
/// eventual associated record.
public func joining<A: Association>(optional association: A) -> Self where A.OriginRowDecoder == RowDecoder {
_joining(optional: association._sqlAssociation)
}
/// Returns a request that joins each record of this request to its
/// associated record. Records that do not have an associated record
/// are discarded.
///
/// For example, we can fetch only books whose author is French:
///
/// ```swift
/// struct Author: TableRecord, FetchableRecord, Decodable { }
/// struct Book: TableRecord, FetchableRecord, Decodable {
/// static let author = belongsTo(Author.self)
/// }
///
/// let frenchAuthors = Book.author.filter(Column("countryCode") == "FR")
/// let bookInfos = try Book.all()
/// .joining(required: frenchAuthors)
/// .fetchAll(db)
/// ```
public func joining<A: Association>(required association: A) -> Self where A.OriginRowDecoder == RowDecoder {
_joining(required: association._sqlAssociation)
}
}
extension JoinableRequest where Self: SelectionRequest {
/// Appends the columns of the eventual associated record to the
/// selected columns.
///
/// For example:
///
/// ```swift
/// // SELECT player.*, team.color
/// // FROM player LEFT JOIN team ...
/// let teamColor = Player.team.select(Column("color"))
/// let request = Player.all().annotated(withOptional: teamColor)
/// ```
///
/// This method performs the exact same SQL request as
/// ``including(optional:)``. The difference is in the record type that can
/// decode such a request: the columns of the associated record must be
/// decoded at the same level as the main record. For example:
///
/// ```swift
/// struct PlayerWithTeamColor: FetchableRecord, Decodable {
/// var player: Player
/// var color: String?
/// }
/// try dbQueue.read { db in
/// let players = try request
/// .asRequest(of: PlayerWithTeamColor.self)
/// .fetchAll(db)
/// }
/// ```
///
/// This method is a convenience. You can build the same request with
/// ``TableAlias``, ``SelectionRequest/annotated(with:)-6ehs4``, and
/// ``JoinableRequest/joining(optional:)``:
///
/// ```swift
/// let teamAlias = TableAlias()
/// let request = Player.all()
/// .annotated(with: teamAlias[Column("color")])
/// .joining(optional: Player.team.aliased(teamAlias))
/// ```
public func annotated<A: Association>(withOptional association: A) -> Self where A.OriginRowDecoder == RowDecoder {
// TODO: find a way to prefix the selection with the association key
let alias = TableAlias()
let selection = association._sqlAssociation.destination.relation.selectionPromise
return self
.joining(optional: association.aliased(alias))
.annotatedWhenConnected(with: { db in
try selection.resolve(db).map { selection in
selection.qualified(with: alias)
}
})
}
/// Appends the columns of the associated record to the selected columns.
/// Records that do not have an associated record are discarded.
///
/// For example:
///
/// ```swift
/// // SELECT player.*, team.color
/// // FROM player JOIN team ...
/// let teamColor = Player.team.select(Column("color"))
/// let request = Player.all().annotated(withRequired: teamColor)
/// ```
///
/// This method performs the exact same SQL request as
/// ``including(required:)``. The difference is in the record type that can
/// decode such a request: the columns of the associated record must be
/// decoded at the same level as the main record. For example:
///
/// ```swift
/// struct PlayerWithTeamColor: FetchableRecord, Decodable {
/// var player: Player
/// var color: String
/// }
/// try dbQueue.read { db in
/// let players = try request
/// .asRequest(of: PlayerWithTeamColor.self)
/// .fetchAll(db)
/// }
/// ```
///
/// This method is a convenience. You can build the same request with
/// ``TableAlias``, ``SelectionRequest/annotated(with:)-6ehs4``, and
/// ``JoinableRequest/joining(required:)``:
///
/// ```swift
/// let teamAlias = TableAlias()
/// let request = Player.all()
/// .annotated(with: teamAlias[Column("color")])
/// .joining(required: Player.team.aliased(teamAlias))
/// ```
public func annotated<A: Association>(withRequired association: A) -> Self where A.OriginRowDecoder == RowDecoder {
// TODO: find a way to prefix the selection with the association key
let selection = association._sqlAssociation.destination.relation.selectionPromise
let alias = TableAlias()
return self
.joining(required: association.aliased(alias))
.annotatedWhenConnected(with: { db in
try selection.resolve(db).map { selection in
selection.qualified(with: alias)
}
})
}
}
// MARK: - DerivableRequest
/// `DerivableRequest` is the base protocol for ``QueryInterfaceRequest``
/// and ``Association``.
///
/// Most features of `DerivableRequest` come from the protocols it
/// inherits from.
///
/// ## Topics
///
/// ### Instance Methods
///
/// - ``TableRequest/aliased(_:)``
/// - ``TableAlias``
///
/// ### The WITH Clause
///
/// - ``with(_:)``
///
/// ### The SELECT Clause
///
/// - ``SelectionRequest/annotated(with:)-4qcem``
/// - ``SelectionRequest/annotated(with:)-6ehs4``
/// - ``SelectionRequest/annotatedWhenConnected(with:)``
/// - ``distinct()``
/// - ``SelectionRequest/select(_:)-30yzl``
/// - ``SelectionRequest/select(_:)-7e2y5``
/// - ``SelectionRequest/select(literal:)``
/// - ``SelectionRequest/select(sql:arguments:)``
/// - ``SelectionRequest/selectWhenConnected(_:)``
///
/// ### The WHERE Clause
///
/// - ``FilteredRequest/filter(_:)``
/// - ``TableRequest/filter(id:)``
/// - ``TableRequest/filter(ids:)``
/// - ``TableRequest/filter(key:)-1p9sq``
/// - ``TableRequest/filter(key:)-2te6v``
/// - ``TableRequest/filter(keys:)-6ggt1``
/// - ``TableRequest/filter(keys:)-8fbn9``
/// - ``FilteredRequest/filter(literal:)``
/// - ``FilteredRequest/filter(sql:arguments:)``
/// - ``FilteredRequest/filterWhenConnected(_:)``
/// - ``TableRequest/matching(_:)``
/// - ``FilteredRequest/none()``
///
/// ### The GROUP BY and HAVING Clauses
///
/// - ``AggregatingRequest/group(_:)-edak``
/// - ``AggregatingRequest/group(_:)-4216o``
/// - ``AggregatingRequest/group(literal:)``
/// - ``AggregatingRequest/group(sql:arguments:)``
/// - ``TableRequest/groupByPrimaryKey()``
/// - ``AggregatingRequest/groupWhenConnected(_:)``
/// - ``AggregatingRequest/having(_:)``
/// - ``AggregatingRequest/having(literal:)``
/// - ``AggregatingRequest/having(sql:arguments:)``
/// - ``AggregatingRequest/havingWhenConnected(_:)``
///
/// ### The ORDER BY Clause
///
/// - ``OrderedRequest/order(_:)-63rzl``
/// - ``OrderedRequest/order(_:)-6co0m``
/// - ``OrderedRequest/order(literal:)``
/// - ``OrderedRequest/order(sql:arguments:)``
/// - ``OrderedRequest/orderWhenConnected(_:)``
/// - ``TableRequest/orderByPrimaryKey()``
/// - ``OrderedRequest/reversed()``
/// - ``OrderedRequest/unordered()``
///
/// ### Associations
///
/// - ``JoinableRequest/annotated(withOptional:)``
/// - ``JoinableRequest/annotated(withRequired:)``
/// - ``annotated(with:)-74xfs``
/// - ``annotated(with:)-8snn4``
/// - ``having(_:)``
/// - ``JoinableRequest/including(all:)``
/// - ``JoinableRequest/including(optional:)``
/// - ``JoinableRequest/including(required:)``
/// - ``JoinableRequest/joining(optional:)``
/// - ``JoinableRequest/joining(required:)``
///
/// ### Supporting Types
///
/// - ``AggregatingRequest``
/// - ``FilteredRequest``
/// - ``JoinableRequest``
/// - ``OrderedRequest``
/// - ``SelectionRequest``
/// - ``TableRequest``
/// - ``TypedRequest``
public protocol DerivableRequest<RowDecoder>: AggregatingRequest, FilteredRequest,
JoinableRequest, OrderedRequest,
SelectionRequest, TableRequest
{
/// Returns a request which returns distinct rows.
///
/// For example:
///
/// ```swift
/// // SELECT DISTINCT * FROM player
/// let request = Player.all().distinct()
///
/// // SELECT DISTINCT name FROM player
/// let request = Player.select(Column("name")).distinct()
/// ```
func distinct() -> Self
/// Embeds a common table expression.
///
/// If a common table expression with the same table name had already been
/// embedded, it is replaced by the new one.
///
/// For example, you can build a request that fetches all chats with their
/// latest message:
///
/// ```swift
/// let latestMessageRequest = Message
/// .annotated(with: max(Column("date")))
/// .group(Column("chatID"))
///
/// let latestMessageCTE = CommonTableExpression(
/// named: "latestMessage",
/// request: latestMessageRequest)
///
/// let latestMessageAssociation = Chat.association(
/// to: latestMessageCTE,
/// on: { chat, latestMessage in
/// chat[Column("id")] == latestMessage[Column("chatID")]
/// })
///
/// // WITH latestMessage AS
/// // (SELECT *, MAX(date) FROM message GROUP BY chatID)
/// // SELECT chat.*, latestMessage.*
/// // FROM chat
/// // LEFT JOIN latestMessage ON chat.id = latestMessage.chatID
/// let request = Chat.all()
/// .with(latestMessageCTE)
/// .including(optional: latestMessageAssociation)
/// ```
func with<RowDecoder>(_ cte: CommonTableExpression<RowDecoder>) -> Self
}
// Association aggregates don't require all DerivableRequest abilities. The
// minimum set of requirements is:
//
// - AggregatingRequest, for the GROUP BY and HAVING clauses
// - TableRequest, for grouping by primary key
// - JoinableRequest, for joining associations
// - SelectionRequest, for annotating the selection
//
// It is just that extending DerivableRequest is simpler. We want the user to
// use aggregates on QueryInterfaceRequest and associations: both conform to
// DerivableRequest already.
extension DerivableRequest {
private func annotated(with aggregate: AssociationAggregate<RowDecoder>) -> Self {
var request = self
let expression = aggregate.prepare(&request)
if let key = aggregate.key {
return request.annotated(with: expression.forKey(key))
} else {
return request.annotated(with: expression)
}
}
/// Appends association aggregates to the selected columns.
///
/// For example:
///
/// ```swift
/// struct Author: TableRecord, FetchableRecord, Decodable {
/// static let books = hasMany(Book.self)
/// }
/// struct Book: TableRecord, FetchableRecord, Decodable { }
///
/// struct AuthorInfo: FetchableRecord, Decodable {
/// var author: Author
/// var bookCount: Int
/// }
///
/// // SELECT author.*, COUNT(DISTINCT book.id) AS bookCount
/// // FROM author
/// // LEFT JOIN book ON book.authorId = author.id
/// // GROUP BY author.id
/// let authorInfos = try Author.all()
/// .annotated(with: Author.books.count)
/// .asRequest(of: AuthorInfo.self)
/// .fetchAll(db)
/// ```
public func annotated(with aggregates: AssociationAggregate<RowDecoder>...) -> Self {
annotated(with: aggregates)
}
/// Appends association aggregates to the selected columns.
///
/// For example:
///
/// ```swift
/// struct Author: TableRecord, FetchableRecord, Decodable {
/// static let books = hasMany(Book.self)
/// }
/// struct Book: TableRecord, FetchableRecord, Decodable { }
///
/// struct AuthorInfo: FetchableRecord, Decodable {
/// var author: Author
/// var bookCount: Int
/// }
///
/// // SELECT author.*, COUNT(DISTINCT book.id) AS bookCount
/// // FROM author
/// // LEFT JOIN book ON book.authorId = author.id
/// // GROUP BY author.id
/// let authorInfos = try Author.all()
/// .annotated(with: [Author.books.count])
/// .asRequest(of: AuthorInfo.self)
/// .fetchAll(db)
/// ```
public func annotated(with aggregates: [AssociationAggregate<RowDecoder>]) -> Self {
aggregates.reduce(self) { request, aggregate in
request.annotated(with: aggregate)
}
}
/// Filters the fetched records with an association aggregate.
///
/// For example:
///
/// ```swift
/// struct Author: TableRecord, FetchableRecord {
/// static let books = hasMany(Book.self)
/// }
/// struct Book: TableRecord, FetchableRecord { }
///
/// // SELECT author.*
/// // FROM author
/// // LEFT JOIN book ON book.authorId = author.id
/// // GROUP BY author.id
/// // HAVING COUNT(DISTINCT book.id) > 5
/// let authors = try Author.all()
/// .having(Author.books.count > 5)
/// .fetchAll(db)
/// ```
public func having(_ predicate: AssociationAggregate<RowDecoder>) -> Self {
var request = self
let expression = predicate.prepare(&request)
return request.having(expression)
}
}
|
mit
|
82277f64c9f9040e73f5f46d54e5495a
| 33.081553 | 119 | 0.57361 | 4.401572 | false | false | false | false |
morbrian/udacity-nano-onthemap
|
OnTheMap/LoginViewController.swift
|
1
|
9741
|
//
// ViewController.swift
// OnTheMap
//
// Created by Brian Moriarty on 4/18/15.
// Copyright (c) 2015 Brian Moriarty. All rights reserved.
//
import UIKit
import FBSDKLoginKit
// LoginViewController
// Presents username / password enabling user to login to appliction.
// Displays error messages if login is not successful.
class LoginViewController: UIViewController {
@IBOutlet weak var usernameTextField: UITextField!
@IBOutlet weak var passwordTextField: UITextField!
@IBOutlet weak var loginStatusLabel: UILabel!
@IBOutlet weak var loginButton: UIButton!
@IBOutlet weak var signupButton: UIButton!
@IBOutlet weak var imageView: UIImageView!
@IBOutlet weak var facebookButton: FBSDKLoginButton!
// central data management object
private var dataManager: StudentDataAccessManager!
// remember how far we moved the view after the keyboard displays
private var viewShiftDistance: CGFloat? = nil
// network activity properties
var activityInProgress = false
private var spinnerBaseTransform: CGAffineTransform!
// MARK: ViewController Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
dataManager = StudentDataAccessManager()
navigationController?.navigationBar.hidden = true
// TODO: Consider using GBDeviceInfo, although this check is sufficient for our simple needs
if view.bounds.height <= CGFloat(Constants.DeviceiPhone5Height) {
// for iPhone5 or smaller, make some of the fonts smaller
signupButton.titleLabel?.font = signupButton.titleLabel?.font.fontWithSize(CGFloat(16.0))
loginStatusLabel.font = loginStatusLabel.font.fontWithSize(CGFloat(12.0))
}
let tapRecognizer = UITapGestureRecognizer(target: self, action: "handleTap:")
view.addGestureRecognizer(tapRecognizer)
spinnerBaseTransform = self.imageView.transform
facebookButton.delegate = self
}
override func viewWillAppear(animated: Bool) {
resetLoginStatusLabel()
// register action if keyboard will show
NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillShow:", name: UIKeyboardWillShowNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillHide:", name: UIKeyboardWillHideNotification, object: nil)
}
override func viewDidAppear(animated: Bool) {
if let token = FBSDKAccessToken.currentAccessToken() {
networkActivity(true)
dataManager.authenticateByFacebookToken(token.tokenString,
completionHandler: handleAuthenticationResponse)
}
}
override func viewWillDisappear(animated: Bool) {
// unregister keyboard actions when view not showing
NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillShowNotification, object: nil)
NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillHideNotification, object: nil)
}
// MARK: Keyboard Show/Hide Handling
// shift the entire view up if bottom text field being edited
func keyboardWillShow(notification: NSNotification) {
var bottomOfLoginButton: CGFloat {
let loginButtonOrigin = view.convertPoint(loginButton.bounds.origin, fromView: loginButton)
return loginButtonOrigin.y + loginButton.bounds.height
}
if viewShiftDistance == nil {
let keyboardHeight = getKeyboardHeight(notification)
let topOfKeyboard = view.bounds.maxY - keyboardHeight
// we only need to move the view if the keyboard will cover up the login button and text fields
if topOfKeyboard < bottomOfLoginButton {
viewShiftDistance = bottomOfLoginButton - topOfKeyboard
self.view.bounds.origin.y += viewShiftDistance!
}
}
}
// if bottom textfield just completed editing, shift the view back down
func keyboardWillHide(notification: NSNotification) {
if let shiftDistance = viewShiftDistance {
self.view.bounds.origin.y -= shiftDistance
viewShiftDistance = nil
}
}
// return height of displayed keyboard
private func getKeyboardHeight(notification: NSNotification) -> CGFloat {
let userInfo = notification.userInfo
let keyboardSize = userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue // of CGRect
Logger.info("we think the keyboard height is: \(keyboardSize.CGRectValue().height)")
return keyboardSize.CGRectValue().height
}
// MARK: IB Actions
@IBAction func beginEditTextfield(sender: UITextField) {
resetLoginStatusLabel()
}
@IBAction func performLogin(sender: UIButton) {
endTextEditing()
loginStatusLabel.hidden = true
if let username = usernameTextField.text,
password = passwordTextField.text {
networkActivity(true)
dataManager.authenticateByUsername(username, withPassword: password,
completionHandler: handleAuthenticationResponse)
}
}
@IBAction func gotoAccountSignup(sender: UIButton) {
UIApplication.sharedApplication().openURL(NSURL(string: Constants.UdacitySignupUrlString)!)
}
@IBAction func proceedAsGuest(sender: UIButton) {
transitionSucessfulLoginSegue()
}
// MARK: Segue Transition
private func transitionSucessfulLoginSegue() {
dispatch_async(dispatch_get_main_queue()) {
self.performSegueWithIdentifier(Constants.SuccessfulLoginSegue, sender: self.dataManager)
}
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if let destination = segue.destinationViewController as? ManagingTabBarController,
dataManager = sender as? StudentDataAccessManager {
destination.dataManager = dataManager
} else {
Logger.error("Unrecognized Segue Destination Class For Segue: \(segue.identifier ?? nil)")
}
}
// MARK: Support Helpers
// provide acivity indicators and animations
func networkActivity(active: Bool) {
dispatch_async(dispatch_get_main_queue()) {
UIApplication.sharedApplication().networkActivityIndicatorVisible = active
self.activityInProgress = active
self.usernameTextField.enabled = !active
self.passwordTextField.enabled = !active
self.loginButton.enabled = !active
self.signupButton.enabled = !active
if (active) {
self.animate()
} else if let transform = self.spinnerBaseTransform {
self.imageView.transform = transform
}
}
}
// animate Udacity imageView while network activity
func animate() {
dispatch_async(dispatch_get_main_queue()) {
UIView.animateWithDuration(0.001,
delay: 0.0,
options: UIViewAnimationOptions.CurveEaseInOut,
animations: { self.imageView.transform =
CGAffineTransformConcat(self.imageView.transform, CGAffineTransformMakeRotation((CGFloat(60.0) * CGFloat(M_PI)) / CGFloat(180.0)) )},
completion: { something in
if self.activityInProgress {
self.animate()
} else {
// TODO: this snaps to position at then end, we should perform the final animation.
self.imageView.transform = self.spinnerBaseTransform
}
})
}
}
func resetLoginStatusLabel() {
loginStatusLabel?.text = ""
loginStatusLabel?.hidden = true
}
func endTextEditing() {
usernameTextField?.endEditing(false)
passwordTextField?.endEditing(false)
}
// MARK: Gestures
func handleTap(sender: UIGestureRecognizer) {
endTextEditing()
}
// MARK: Authentication
func handleAuthenticationResponse(success success: Bool, error: NSError?) {
self.networkActivity(false)
if success {
self.transitionSucessfulLoginSegue()
} else {
dispatch_async(dispatch_get_main_queue()) {
if let reason = error?.localizedDescription {
self.loginStatusLabel?.text = "!! \(reason)"
} else {
self.loginStatusLabel?.text = "!! Login failed"
}
self.loginStatusLabel.hidden = false
}
}
}
func resetStateAfterUserLogout() {
Logger.info("Logging out...")
dataManager = StudentDataAccessManager()
resetLoginStatusLabel()
}
@IBAction func segueToLoginScreen(segue: UIStoryboardSegue) {
resetStateAfterUserLogout()
}
}
// MARK: - FBSDKLoginButtonDelegate
extension LoginViewController: FBSDKLoginButtonDelegate {
func loginButton(loginButton: FBSDKLoginButton!, didCompleteWithResult result: FBSDKLoginManagerLoginResult!, error: NSError!) {
if let token = result.token {
networkActivity(true)
dataManager.authenticateByFacebookToken(token.tokenString,
completionHandler: handleAuthenticationResponse)
} else if let error = error {
handleAuthenticationResponse(success: false, error: error)
}
}
func loginButtonDidLogOut(loginButton: FBSDKLoginButton!) {
resetStateAfterUserLogout()
}
}
|
mit
|
3c72599e2682e25074f46e7d5282e0b6
| 37.654762 | 153 | 0.655682 | 5.617647 | false | false | false | false |
xwu/swift
|
test/SILGen/pointer_conversion.swift
|
13
|
27612
|
// RUN: %target-swift-emit-silgen -module-name pointer_conversion -sdk %S/Inputs -I %S/Inputs -enable-source-import %s -enable-objc-interop | %FileCheck %s
// FIXME: rdar://problem/19648117 Needs splitting objc parts out
// REQUIRES: objc_interop
import Foundation
func sideEffect1() -> Int { return 1 }
func sideEffect2() -> Int { return 2 }
func takesMutablePointer(_ x: UnsafeMutablePointer<Int>) {}
func takesConstPointer(_ x: UnsafePointer<Int>) {}
func takesOptConstPointer(_ x: UnsafePointer<Int>?, and: Int) {}
func takesOptOptConstPointer(_ x: UnsafePointer<Int>??, and: Int) {}
func takesMutablePointer(_ x: UnsafeMutablePointer<Int>, and: Int) {}
func takesConstPointer(_ x: UnsafePointer<Int>, and: Int) {}
func takesMutableVoidPointer(_ x: UnsafeMutableRawPointer) {}
func takesConstVoidPointer(_ x: UnsafeRawPointer) {}
func takesMutableRawPointer(_ x: UnsafeMutableRawPointer) {}
func takesConstRawPointer(_ x: UnsafeRawPointer) {}
func takesOptConstRawPointer(_ x: UnsafeRawPointer?, and: Int) {}
func takesOptOptConstRawPointer(_ x: UnsafeRawPointer??, and: Int) {}
// CHECK-LABEL: sil hidden [ossa] @$s18pointer_conversion0A9ToPointeryySpySiG_SPySiGSvtF
// CHECK: bb0([[MP:%.*]] : $UnsafeMutablePointer<Int>, [[CP:%.*]] : $UnsafePointer<Int>, [[MRP:%.*]] : $UnsafeMutableRawPointer):
func pointerToPointer(_ mp: UnsafeMutablePointer<Int>,
_ cp: UnsafePointer<Int>, _ mrp: UnsafeMutableRawPointer) {
// There should be no conversion here
takesMutablePointer(mp)
// CHECK: [[TAKES_MUTABLE_POINTER:%.*]] = function_ref @$s18pointer_conversion19takesMutablePointer{{[_0-9a-zA-Z]*}}F
// CHECK: apply [[TAKES_MUTABLE_POINTER]]([[MP]])
takesMutableVoidPointer(mp)
// CHECK: [[CONVERT:%.*]] = function_ref @$ss017_convertPointerToB8Argument{{[_0-9a-zA-Z]*}}F
// CHECK: apply [[CONVERT]]<UnsafeMutablePointer<Int>, UnsafeMutableRawPointer>
// CHECK: [[TAKES_MUTABLE_VOID_POINTER:%.*]] = function_ref @$s18pointer_conversion23takesMutableVoidPointer{{[_0-9a-zA-Z]*}}F
// CHECK: apply [[TAKES_MUTABLE_VOID_POINTER]]
takesMutableRawPointer(mp)
// CHECK: [[CONVERT:%.*]] = function_ref @$ss017_convertPointerToB8Argument{{[_0-9a-zA-Z]*}}F
// CHECK: apply [[CONVERT]]<UnsafeMutablePointer<Int>, UnsafeMutableRawPointer>
// CHECK: [[TAKES_MUTABLE_RAW_POINTER:%.*]] = function_ref @$s18pointer_conversion22takesMutableRawPointeryySvF :
// CHECK: apply [[TAKES_MUTABLE_RAW_POINTER]]
takesConstPointer(mp)
// CHECK: [[CONVERT:%.*]] = function_ref @$ss017_convertPointerToB8Argument{{[_0-9a-zA-Z]*}}F
// CHECK: apply [[CONVERT]]<UnsafeMutablePointer<Int>, UnsafePointer<Int>>
// CHECK: [[TAKES_CONST_POINTER:%.*]] = function_ref @$s18pointer_conversion17takesConstPointeryySPySiGF
// CHECK: apply [[TAKES_CONST_POINTER]]
takesConstVoidPointer(mp)
// CHECK: [[CONVERT:%.*]] = function_ref @$ss017_convertPointerToB8Argument{{[_0-9a-zA-Z]*}}F
// CHECK: apply [[CONVERT]]<UnsafeMutablePointer<Int>, UnsafeRawPointer>
// CHECK: [[TAKES_CONST_VOID_POINTER:%.*]] = function_ref @$s18pointer_conversion21takesConstVoidPointeryySVF
// CHECK: apply [[TAKES_CONST_VOID_POINTER]]
takesConstRawPointer(mp)
// CHECK: [[CONVERT:%.*]] = function_ref @$ss017_convertPointerToB8Argument{{[_0-9a-zA-Z]*}}F
// CHECK: apply [[CONVERT]]<UnsafeMutablePointer<Int>, UnsafeRawPointer>
// CHECK: [[TAKES_CONST_RAW_POINTER:%.*]] = function_ref @$s18pointer_conversion20takesConstRawPointeryySVF :
// CHECK: apply [[TAKES_CONST_RAW_POINTER]]
takesConstPointer(cp)
// CHECK: [[TAKES_CONST_POINTER:%.*]] = function_ref @$s18pointer_conversion17takesConstPointeryySPySiGF
// CHECK: apply [[TAKES_CONST_POINTER]]([[CP]])
takesConstVoidPointer(cp)
// CHECK: [[CONVERT:%.*]] = function_ref @$ss017_convertPointerToB8Argument{{[_0-9a-zA-Z]*}}F
// CHECK: apply [[CONVERT]]<UnsafePointer<Int>, UnsafeRawPointer>
// CHECK: [[TAKES_CONST_VOID_POINTER:%.*]] = function_ref @$s18pointer_conversion21takesConstVoidPointeryySVF
// CHECK: apply [[TAKES_CONST_VOID_POINTER]]
takesConstRawPointer(cp)
// CHECK: [[CONVERT:%.*]] = function_ref @$ss017_convertPointerToB8Argument{{[_0-9a-zA-Z]*}}F
// CHECK: apply [[CONVERT]]<UnsafePointer<Int>, UnsafeRawPointer>
// CHECK: [[TAKES_CONST_RAW_POINTER:%.*]] = function_ref @$s18pointer_conversion20takesConstRawPointeryySVF
// CHECK: apply [[TAKES_CONST_RAW_POINTER]]
takesConstRawPointer(mrp)
// CHECK: [[CONVERT:%.*]] = function_ref @$ss017_convertPointerToB8Argument{{[_0-9a-zA-Z]*}}F
// CHECK: apply [[CONVERT]]<UnsafeMutableRawPointer, UnsafeRawPointer>
// CHECK: [[TAKES_CONST_RAW_POINTER:%.*]] = function_ref @$s18pointer_conversion20takesConstRawPointeryySVF
// CHECK: apply [[TAKES_CONST_RAW_POINTER]]
}
// CHECK-LABEL: sil hidden [ossa] @$s18pointer_conversion14arrayToPointeryyF
func arrayToPointer() {
var ints = [1,2,3]
takesMutablePointer(&ints)
// CHECK: [[CONVERT_MUTABLE:%.*]] = function_ref @$ss37_convertMutableArrayToPointerArgument{{[_0-9a-zA-Z]*}}F
// CHECK: [[OWNER:%.*]] = apply [[CONVERT_MUTABLE]]<Int, UnsafeMutablePointer<Int>>([[POINTER_BUF:%[0-9]*]],
// CHECK: [[POINTER:%.*]] = load [trivial] [[POINTER_BUF]]
// CHECK: [[DEPENDENT:%.*]] = mark_dependence [[POINTER]] : $UnsafeMutablePointer<Int> on [[OWNER]]
// CHECK: [[TAKES_MUTABLE_POINTER:%.*]] = function_ref @$s18pointer_conversion19takesMutablePointer{{[_0-9a-zA-Z]*}}F
// CHECK: apply [[TAKES_MUTABLE_POINTER]]([[DEPENDENT]])
// CHECK: destroy_value [[OWNER]]
takesConstPointer(ints)
// CHECK: [[CONVERT_CONST:%.*]] = function_ref @$ss35_convertConstArrayToPointerArgument{{[_0-9a-zA-Z]*}}F
// CHECK: [[OWNER:%.*]] = apply [[CONVERT_CONST]]<Int, UnsafePointer<Int>>([[POINTER_BUF:%[0-9]*]],
// CHECK: [[POINTER:%.*]] = load [trivial] [[POINTER_BUF]]
// CHECK: [[DEPENDENT:%.*]] = mark_dependence [[POINTER]] : $UnsafePointer<Int> on [[OWNER]]
// CHECK: [[TAKES_CONST_POINTER:%.*]] = function_ref @$s18pointer_conversion17takesConstPointeryySPySiGF
// CHECK: apply [[TAKES_CONST_POINTER]]([[DEPENDENT]])
// CHECK: destroy_value [[OWNER]]
takesMutableRawPointer(&ints)
// CHECK: [[CONVERT_MUTABLE:%.*]] = function_ref @$ss37_convertMutableArrayToPointerArgument{{[_0-9a-zA-Z]*}}F
// CHECK: [[OWNER:%.*]] = apply [[CONVERT_MUTABLE]]<Int, UnsafeMutableRawPointer>([[POINTER_BUF:%[0-9]*]],
// CHECK: [[POINTER:%.*]] = load [trivial] [[POINTER_BUF]]
// CHECK: [[DEPENDENT:%.*]] = mark_dependence [[POINTER]] : $UnsafeMutableRawPointer on [[OWNER]]
// CHECK: [[TAKES_MUTABLE_RAW_POINTER:%.*]] = function_ref @$s18pointer_conversion22takesMutableRawPointeryySvF :
// CHECK: apply [[TAKES_MUTABLE_RAW_POINTER]]([[DEPENDENT]])
// CHECK: destroy_value [[OWNER]]
takesConstRawPointer(ints)
// CHECK: [[CONVERT_CONST:%.*]] = function_ref @$ss35_convertConstArrayToPointerArgument{{[_0-9a-zA-Z]*}}F
// CHECK: [[OWNER:%.*]] = apply [[CONVERT_CONST]]<Int, UnsafeRawPointer>([[POINTER_BUF:%[0-9]*]],
// CHECK: [[POINTER:%.*]] = load [trivial] [[POINTER_BUF]]
// CHECK: [[DEPENDENT:%.*]] = mark_dependence [[POINTER]] : $UnsafeRawPointer on [[OWNER]]
// CHECK: [[TAKES_CONST_RAW_POINTER:%.*]] = function_ref @$s18pointer_conversion20takesConstRawPointeryySVF :
// CHECK: apply [[TAKES_CONST_RAW_POINTER]]([[DEPENDENT]])
// CHECK: destroy_value [[OWNER]]
takesOptConstPointer(ints, and: sideEffect1())
// CHECK: [[SIDE1:%.*]] = function_ref @$s18pointer_conversion11sideEffect1SiyF
// CHECK: [[RESULT1:%.*]] = apply [[SIDE1]]()
// CHECK: [[CONVERT_CONST:%.*]] = function_ref @$ss35_convertConstArrayToPointerArgument{{[_0-9a-zA-Z]*}}F
// CHECK: [[OWNER:%.*]] = apply [[CONVERT_CONST]]<Int, UnsafePointer<Int>>([[POINTER_BUF:%[0-9]*]],
// CHECK: [[POINTER:%.*]] = load [trivial] [[POINTER_BUF]]
// CHECK: [[DEPENDENT:%.*]] = mark_dependence [[POINTER]] : $UnsafePointer<Int> on [[OWNER]]
// CHECK: [[OPTPTR:%.*]] = enum $Optional<UnsafePointer<Int>>, #Optional.some!enumelt, [[DEPENDENT]]
// CHECK: [[TAKES_OPT_CONST_POINTER:%.*]] = function_ref @$s18pointer_conversion20takesOptConstPointer_3andySPySiGSg_SitF :
// CHECK: apply [[TAKES_OPT_CONST_POINTER]]([[OPTPTR]], [[RESULT1]])
// CHECK: destroy_value [[OWNER]]
}
// CHECK-LABEL: sil hidden [ossa] @$s18pointer_conversion15stringToPointeryySSF
func stringToPointer(_ s: String) {
takesConstVoidPointer(s)
// CHECK: [[CONVERT_STRING:%.*]] = function_ref @$ss40_convertConstStringToUTF8PointerArgument{{[_0-9a-zA-Z]*}}F
// CHECK: [[OWNER:%.*]] = apply [[CONVERT_STRING]]<UnsafeRawPointer>([[POINTER_BUF:%[0-9]*]],
// CHECK: [[POINTER:%.*]] = load [trivial] [[POINTER_BUF]]
// CHECK: [[DEPENDENT:%.*]] = mark_dependence [[POINTER]] : $UnsafeRawPointer on [[OWNER]]
// CHECK: [[TAKES_CONST_VOID_POINTER:%.*]] = function_ref @$s18pointer_conversion21takesConstVoidPointeryySV{{[_0-9a-zA-Z]*}}F
// CHECK: apply [[TAKES_CONST_VOID_POINTER]]([[DEPENDENT]])
// CHECK: destroy_value [[OWNER]]
takesConstRawPointer(s)
// CHECK: [[CONVERT_STRING:%.*]] = function_ref @$ss40_convertConstStringToUTF8PointerArgument{{[_0-9a-zA-Z]*}}F
// CHECK: [[OWNER:%.*]] = apply [[CONVERT_STRING]]<UnsafeRawPointer>([[POINTER_BUF:%[0-9]*]],
// CHECK: [[POINTER:%.*]] = load [trivial] [[POINTER_BUF]]
// CHECK: [[DEPENDENT:%.*]] = mark_dependence [[POINTER]] : $UnsafeRawPointer on [[OWNER]]
// CHECK: [[TAKES_CONST_RAW_POINTER:%.*]] = function_ref @$s18pointer_conversion20takesConstRawPointeryySV{{[_0-9a-zA-Z]*}}F
// CHECK: apply [[TAKES_CONST_RAW_POINTER]]([[DEPENDENT]])
// CHECK: destroy_value [[OWNER]]
takesOptConstRawPointer(s, and: sideEffect1())
// CHECK: [[SIDE1:%.*]] = function_ref @$s18pointer_conversion11sideEffect1SiyF
// CHECK: [[RESULT1:%.*]] = apply [[SIDE1]]()
// CHECK: [[CONVERT_STRING:%.*]] = function_ref @$ss40_convertConstStringToUTF8PointerArgument{{[_0-9a-zA-Z]*}}F
// CHECK: [[OWNER:%.*]] = apply [[CONVERT_STRING]]<UnsafeRawPointer>([[POINTER_BUF:%[0-9]*]],
// CHECK: [[POINTER:%.*]] = load [trivial] [[POINTER_BUF]]
// CHECK: [[DEPENDENT:%.*]] = mark_dependence [[POINTER]] : $UnsafeRawPointer on [[OWNER]]
// CHECK: [[OPTPTR:%.*]] = enum $Optional<UnsafeRawPointer>, #Optional.some!enumelt, [[DEPENDENT]]
// CHECK: [[TAKES_OPT_CONST_RAW_POINTER:%.*]] = function_ref @$s18pointer_conversion23takesOptConstRawPointer_3andySVSg_SitF :
// CHECK: apply [[TAKES_OPT_CONST_RAW_POINTER]]([[OPTPTR]], [[RESULT1]])
// CHECK: destroy_value [[OWNER]]
}
// CHECK-LABEL: sil hidden [ossa] @$s18pointer_conversion14inoutToPointeryyF
func inoutToPointer() {
var int = 0
// CHECK: [[INT:%.*]] = alloc_box ${ var Int }
// CHECK: [[PB:%.*]] = project_box [[INT]]
takesMutablePointer(&int)
// CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] [[PB]]
// CHECK: [[POINTER:%.*]] = address_to_pointer [[WRITE]]
// CHECK: [[CONVERT:%.*]] = function_ref @$ss30_convertInOutToPointerArgument{{[_0-9a-zA-Z]*}}F
// CHECK: apply [[CONVERT]]<UnsafeMutablePointer<Int>>({{%.*}}, [[POINTER]])
// CHECK: [[TAKES_MUTABLE:%.*]] = function_ref @$s18pointer_conversion19takesMutablePointer{{[_0-9a-zA-Z]*}}F
// CHECK: apply [[TAKES_MUTABLE]]
var logicalInt: Int {
get { return 0 }
set { }
}
takesMutablePointer(&logicalInt)
// CHECK: [[GETTER:%.*]] = function_ref @$s18pointer_conversion14inoutToPointeryyF10logicalIntL_Sivg
// CHECK: apply [[GETTER]]
// CHECK: [[CONVERT:%.*]] = function_ref @$ss30_convertInOutToPointerArgument{{[_0-9a-zA-Z]*}}F
// CHECK: apply [[CONVERT]]<UnsafeMutablePointer<Int>>
// CHECK: [[TAKES_MUTABLE:%.*]] = function_ref @$s18pointer_conversion19takesMutablePointer{{[_0-9a-zA-Z]*}}F
// CHECK: apply [[TAKES_MUTABLE]]
// CHECK: [[SETTER:%.*]] = function_ref @$s18pointer_conversion14inoutToPointeryyF10logicalIntL_Sivs
// CHECK: apply [[SETTER]]
takesMutableRawPointer(&int)
// CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] [[PB]]
// CHECK: [[POINTER:%.*]] = address_to_pointer [[WRITE]]
// CHECK: [[CONVERT:%.*]] = function_ref @$ss30_convertInOutToPointerArgument{{[_0-9a-zA-Z]*}}F
// CHECK: apply [[CONVERT]]<UnsafeMutableRawPointer>({{%.*}}, [[POINTER]])
// CHECK: [[TAKES_MUTABLE:%.*]] = function_ref @$s18pointer_conversion22takesMutableRawPointer{{[_0-9a-zA-Z]*}}F
// CHECK: apply [[TAKES_MUTABLE]]
takesMutableRawPointer(&logicalInt)
// CHECK: [[GETTER:%.*]] = function_ref @$s18pointer_conversion14inoutToPointeryyF10logicalIntL_Sivg
// CHECK: apply [[GETTER]]
// CHECK: [[CONVERT:%.*]] = function_ref @$ss30_convertInOutToPointerArgument{{[_0-9a-zA-Z]*}}F
// CHECK: apply [[CONVERT]]<UnsafeMutableRawPointer>
// CHECK: [[TAKES_MUTABLE:%.*]] = function_ref @$s18pointer_conversion22takesMutableRawPointer{{[_0-9a-zA-Z]*}}F
// CHECK: apply [[TAKES_MUTABLE]]
// CHECK: [[SETTER:%.*]] = function_ref @$s18pointer_conversion14inoutToPointeryyF10logicalIntL_Sivs
// CHECK: apply [[SETTER]]
}
class C {}
func takesPlusOnePointer(_ x: UnsafeMutablePointer<C>) {}
func takesPlusZeroPointer(_ x: AutoreleasingUnsafeMutablePointer<C>) {}
func takesPlusZeroOptionalPointer(_ x: AutoreleasingUnsafeMutablePointer<C?>) {}
// CHECK-LABEL: sil hidden [ossa] @$s18pointer_conversion19classInoutToPointeryyF
func classInoutToPointer() {
var c = C()
// CHECK: [[VAR:%.*]] = alloc_box ${ var C }
// CHECK: [[PB:%.*]] = project_box [[VAR]]
takesPlusOnePointer(&c)
// CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] [[PB]]
// CHECK: [[POINTER:%.*]] = address_to_pointer [[WRITE]]
// CHECK: [[CONVERT:%.*]] = function_ref @$ss30_convertInOutToPointerArgument{{[_0-9a-zA-Z]*}}F
// CHECK: apply [[CONVERT]]<UnsafeMutablePointer<C>>({{%.*}}, [[POINTER]])
// CHECK: [[TAKES_PLUS_ONE:%.*]] = function_ref @$s18pointer_conversion19takesPlusOnePointer{{[_0-9a-zA-Z]*}}F
// CHECK: apply [[TAKES_PLUS_ONE]]
takesPlusZeroPointer(&c)
// CHECK: [[WRITEBACK:%.*]] = alloc_stack $@sil_unmanaged C
// CHECK: [[OWNED:%.*]] = load_borrow [[PB]]
// CHECK: [[UNOWNED:%.*]] = ref_to_unmanaged [[OWNED]]
// CHECK: store [[UNOWNED]] to [trivial] [[WRITEBACK]]
// CHECK: [[POINTER:%.*]] = address_to_pointer [[WRITEBACK]]
// CHECK: [[CONVERT:%.*]] = function_ref @$ss30_convertInOutToPointerArgument{{[_0-9a-zA-Z]*}}F
// CHECK: apply [[CONVERT]]<AutoreleasingUnsafeMutablePointer<C>>({{%.*}}, [[POINTER]])
// CHECK: [[TAKES_PLUS_ZERO:%.*]] = function_ref @$s18pointer_conversion20takesPlusZeroPointeryySAyAA1CCGF
// CHECK: apply [[TAKES_PLUS_ZERO]]
// CHECK: [[UNOWNED_OUT:%.*]] = load [trivial] [[WRITEBACK]]
// CHECK: [[OWNED_OUT:%.*]] = unmanaged_to_ref [[UNOWNED_OUT]]
// CHECK: [[OWNED_OUT_COPY:%.*]] = copy_value [[OWNED_OUT]]
// CHECK: assign [[OWNED_OUT_COPY]] to [[PB]]
var cq: C? = C()
takesPlusZeroOptionalPointer(&cq)
}
// Check that pointer types don't bridge anymore.
@objc class ObjCMethodBridging : NSObject {
// CHECK-LABEL: sil hidden [thunk] [ossa] @$s18pointer_conversion18ObjCMethodBridgingC0A4Args{{[_0-9a-zA-Z]*}}FTo : $@convention(objc_method) (UnsafeMutablePointer<Int>, UnsafePointer<Int>, AutoreleasingUnsafeMutablePointer<ObjCMethodBridging>, ObjCMethodBridging)
@objc func pointerArgs(_ x: UnsafeMutablePointer<Int>,
y: UnsafePointer<Int>,
z: AutoreleasingUnsafeMutablePointer<ObjCMethodBridging>) {}
}
// rdar://problem/21505805
// CHECK-LABEL: sil hidden [ossa] @$s18pointer_conversion22functionInoutToPointeryyF
func functionInoutToPointer() {
// CHECK: [[BOX:%.*]] = alloc_box ${ var @callee_guaranteed () -> () }
var f: () -> () = {}
// CHECK: [[REABSTRACT_BUF:%.*]] = alloc_stack $@callee_guaranteed @substituted <τ_0_0> () -> @out τ_0_0 for <()>
// CHECK: address_to_pointer [[REABSTRACT_BUF]]
takesMutableVoidPointer(&f)
}
// rdar://problem/31781386
// CHECK-LABEL: sil hidden [ossa] @$s18pointer_conversion20inoutPointerOrderingyyF
func inoutPointerOrdering() {
// CHECK: [[ARRAY_BOX:%.*]] = alloc_box ${ var Array<Int> }
// CHECK: [[ARRAY:%.*]] = project_box [[ARRAY_BOX]] :
// CHECK: store {{.*}} to [init] [[ARRAY]]
var array = [Int]()
// CHECK: [[SIDE1:%.*]] = function_ref @$s18pointer_conversion11sideEffect1SiyF
// CHECK: [[RESULT1:%.*]] = apply [[SIDE1]]()
// CHECK: [[SIDE2:%.*]] = function_ref @$s18pointer_conversion11sideEffect2SiyF
// CHECK: [[RESULT2:%.*]] = apply [[SIDE2]]()
// CHECK: [[ACCESS:%.*]] = begin_access [modify] [unknown] [[ARRAY]] : $*Array<Int>
// CHECK: [[TAKES_MUTABLE:%.*]] = function_ref @$s18pointer_conversion19takesMutablePointer_3andySpySiG_SitF
// CHECK: apply [[TAKES_MUTABLE]]({{.*}}, [[RESULT2]])
// CHECK: end_access [[ACCESS]]
takesMutablePointer(&array[sideEffect1()], and: sideEffect2())
// CHECK: [[SIDE1:%.*]] = function_ref @$s18pointer_conversion11sideEffect1SiyF
// CHECK: [[RESULT1:%.*]] = apply [[SIDE1]]()
// CHECK: [[SIDE2:%.*]] = function_ref @$s18pointer_conversion11sideEffect2SiyF
// CHECK: [[RESULT2:%.*]] = apply [[SIDE2]]()
// CHECK: [[ACCESS:%.*]] = begin_access [read] [unknown] [[ARRAY]] : $*Array<Int>
// CHECK: [[TAKES_CONST:%.*]] = function_ref @$s18pointer_conversion17takesConstPointer_3andySPySiG_SitF
// CHECK: apply [[TAKES_CONST]]({{.*}}, [[RESULT2]])
// CHECK: end_access [[ACCESS]]
takesConstPointer(&array[sideEffect1()], and: sideEffect2())
}
// rdar://problem/31542269
// CHECK-LABEL: sil hidden [ossa] @$s18pointer_conversion20optArrayToOptPointer5arrayySaySiGSg_tF
func optArrayToOptPointer(array: [Int]?) {
// CHECK: [[COPY:%.*]] = copy_value %0
// CHECK: [[SIDE1:%.*]] = function_ref @$s18pointer_conversion11sideEffect1SiyF
// CHECK: [[RESULT1:%.*]] = apply [[SIDE1]]()
// CHECK: switch_enum [[COPY]] : $Optional<Array<Int>>, case #Optional.some!enumelt: [[SOME_BB:bb[0-9]+]], case #Optional.none!enumelt: [[NONE_BB:bb[0-9]+]]
//
// CHECK: [[SOME_BB]]([[SOME_VALUE:%.*]] :
// CHECK: [[CONVERT:%.*]] = function_ref @$ss35_convertConstArrayToPointerArgumentyyXlSg_q_tSayxGs01_E0R_r0_lF
// CHECK: [[TEMP:%.*]] = alloc_stack $UnsafePointer<Int>
// CHECK: [[OWNER:%.*]] = apply [[CONVERT]]<Int, UnsafePointer<Int>>([[TEMP:%.*]], [[SOME_VALUE]])
// CHECK: [[PTR:%.*]] = load [trivial] [[TEMP]]
// CHECK: [[DEP:%.*]] = mark_dependence [[PTR]] : $UnsafePointer<Int> on [[OWNER]]
// CHECK: [[OPTPTR:%.*]] = enum $Optional<UnsafePointer<Int>>, #Optional.some!enumelt, [[DEP]]
// CHECK: dealloc_stack [[TEMP]]
// CHECK: br [[CONT_BB:bb[0-9]+]]([[OPTPTR]] : $Optional<UnsafePointer<Int>>, [[OWNER]] : $Optional<AnyObject>)
// CHECK: [[CONT_BB]]([[OPTPTR:%.*]] : $Optional<UnsafePointer<Int>>, [[OWNER:%.*]] : @owned $Optional<AnyObject>):
// CHECK: [[OPTDEP:%.*]] = mark_dependence [[OPTPTR]] : $Optional<UnsafePointer<Int>> on [[OWNER]]
// CHECK: [[TAKES:%.*]] = function_ref @$s18pointer_conversion20takesOptConstPointer_3andySPySiGSg_SitF
// CHECK: apply [[TAKES]]([[OPTDEP]], [[RESULT1]])
// CHECK: destroy_value [[OWNER]]
// CHECK-NOT: destroy_value %0
// CHECK: [[NONE_BB]]:
// CHECK: [[NO_VALUE:%.*]] = enum $Optional<UnsafePointer<Int>>, #Optional.none
// CHECK: [[NO_OWNER:%.*]] = enum $Optional<AnyObject>, #Optional.none
// CHECK: br [[CONT_BB]]([[NO_VALUE]] : $Optional<UnsafePointer<Int>>, [[NO_OWNER]] : $Optional<AnyObject>)
takesOptConstPointer(array, and: sideEffect1())
}
// CHECK-LABEL: sil hidden [ossa] @$s18pointer_conversion013optOptArrayTodD7Pointer5arrayySaySiGSgSg_tF
func optOptArrayToOptOptPointer(array: [Int]??) {
// CHECK: [[COPY:%.*]] = copy_value %0
// CHECK: [[SIDE1:%.*]] = function_ref @$s18pointer_conversion11sideEffect1SiyF
// CHECK: [[RESULT1:%.*]] = apply [[SIDE1]]()
// CHECK: switch_enum [[COPY]] : $Optional<Optional<Array<Int>>>, case #Optional.some!enumelt: [[SOME_BB:bb[0-9]+]], case #Optional.none!enumelt: [[NONE_BB:bb[0-9]+]]
//
// CHECK: [[SOME_BB]]([[SOME_VALUE:%.*]] :
// CHECK: switch_enum [[SOME_VALUE]] : $Optional<Array<Int>>, case #Optional.some!enumelt: [[SOME_SOME_BB:bb[0-9]+]], case #Optional.none!enumelt: [[SOME_NONE_BB:bb[0-9]+]]
//
// CHECK: [[SOME_SOME_BB]]([[SOME_SOME_VALUE:%.*]] :
// CHECK: [[CONVERT:%.*]] = function_ref @$ss35_convertConstArrayToPointerArgumentyyXlSg_q_tSayxGs01_E0R_r0_lF
// CHECK: [[TEMP:%.*]] = alloc_stack $UnsafePointer<Int>
// CHECK: [[OWNER:%.*]] = apply [[CONVERT]]<Int, UnsafePointer<Int>>([[TEMP:%.*]], [[SOME_SOME_VALUE]])
// CHECK: [[PTR:%.*]] = load [trivial] [[TEMP]]
// CHECK: [[DEP:%.*]] = mark_dependence [[PTR]] : $UnsafePointer<Int> on [[OWNER]]
// CHECK: [[OPTPTR:%.*]] = enum $Optional<UnsafePointer<Int>>, #Optional.some!enumelt, [[DEP]]
// CHECK: dealloc_stack [[TEMP]]
// CHECK: br [[SOME_SOME_CONT_BB:bb[0-9]+]]([[OPTPTR]] : $Optional<UnsafePointer<Int>>, [[OWNER]] : $Optional<AnyObject>)
// CHECK: [[SOME_SOME_CONT_BB]]([[OPTPTR:%.*]] : $Optional<UnsafePointer<Int>>, [[OWNER:%.*]] : @owned $Optional<AnyObject>):
// CHECK: [[OPTDEP:%.*]] = mark_dependence [[OPTPTR]] : $Optional<UnsafePointer<Int>> on [[OWNER]]
// CHECK: [[OPTOPTPTR:%.*]] = enum $Optional<Optional<UnsafePointer<Int>>>, #Optional.some!enumelt, [[OPTDEP]]
// CHECK: br [[SOME_CONT_BB:bb[0-9]+]]([[OPTOPTPTR]] : $Optional<Optional<UnsafePointer<Int>>>, [[OWNER]] : $Optional<AnyObject>)
// CHECK: [[SOME_CONT_BB]]([[OPTOPTPTR:%.*]] : $Optional<Optional<UnsafePointer<Int>>>, [[OWNER:%.*]] : @owned $Optional<AnyObject>):
// CHECK: [[OPTOPTDEP:%.*]] = mark_dependence [[OPTOPTPTR]] : $Optional<Optional<UnsafePointer<Int>>> on [[OWNER]]
// CHECK: [[TAKES:%.*]] = function_ref @$s18pointer_conversion08takesOptD12ConstPointer_3andySPySiGSgSg_SitF
// CHECK: apply [[TAKES]]([[OPTOPTDEP]], [[RESULT1]])
// CHECK: destroy_value [[OWNER]]
// CHECK-NOT: destroy_value %0
// CHECK: [[SOME_NONE_BB]]:
// CHECK: [[NO_VALUE:%.*]] = enum $Optional<UnsafePointer<Int>>, #Optional.none
// CHECK: [[NO_OWNER:%.*]] = enum $Optional<AnyObject>, #Optional.none
// CHECK: br [[SOME_SOME_CONT_BB]]([[NO_VALUE]] : $Optional<UnsafePointer<Int>>, [[NO_OWNER]] : $Optional<AnyObject>)
// CHECK: [[NONE_BB]]:
// CHECK: [[NO_VALUE:%.*]] = enum $Optional<Optional<UnsafePointer<Int>>>, #Optional.none
// CHECK: [[NO_OWNER:%.*]] = enum $Optional<AnyObject>, #Optional.none
// CHECK: br [[SOME_CONT_BB]]([[NO_VALUE]] : $Optional<Optional<UnsafePointer<Int>>>, [[NO_OWNER]] : $Optional<AnyObject>)
takesOptOptConstPointer(array, and: sideEffect1())
}
// CHECK-LABEL: sil hidden [ossa] @$s18pointer_conversion21optStringToOptPointer6stringySSSg_tF
func optStringToOptPointer(string: String?) {
// CHECK: [[COPY:%.*]] = copy_value %0
// CHECK: [[SIDE1:%.*]] = function_ref @$s18pointer_conversion11sideEffect1SiyF
// CHECK: [[RESULT1:%.*]] = apply [[SIDE1]]()
// CHECK: switch_enum [[COPY]] : $Optional<String>, case #Optional.some!enumelt: [[SOME_BB:bb[0-9]+]], case #Optional.none!enumelt: [[NONE_BB:bb[0-9]+]]
//
// CHECK: [[SOME_BB]]([[SOME_VALUE:%.*]] :
// CHECK: [[CONVERT:%.*]] = function_ref @$ss40_convertConstStringToUTF8PointerArgumentyyXlSg_xtSSs01_F0RzlF
// CHECK: [[TEMP:%.*]] = alloc_stack $UnsafeRawPointer
// CHECK: [[OWNER:%.*]] = apply [[CONVERT]]<UnsafeRawPointer>([[TEMP:%.*]], [[SOME_VALUE]])
// CHECK: [[PTR:%.*]] = load [trivial] [[TEMP]]
// CHECK: [[DEP:%.*]] = mark_dependence [[PTR]] : $UnsafeRawPointer on [[OWNER]]
// CHECK: [[OPTPTR:%.*]] = enum $Optional<UnsafeRawPointer>, #Optional.some!enumelt, [[DEP]]
// CHECK: dealloc_stack [[TEMP]]
// CHECK: br [[CONT_BB:bb[0-9]+]]([[OPTPTR]] : $Optional<UnsafeRawPointer>, [[OWNER]] : $Optional<AnyObject>)
// CHECK: [[CONT_BB]]([[OPTPTR:%.*]] : $Optional<UnsafeRawPointer>, [[OWNER:%.*]] : @owned $Optional<AnyObject>):
// CHECK: [[OPTDEP:%.*]] = mark_dependence [[OPTPTR]] : $Optional<UnsafeRawPointer> on [[OWNER]]
// CHECK: [[TAKES:%.*]] = function_ref @$s18pointer_conversion23takesOptConstRawPointer_3andySVSg_SitF
// CHECK: apply [[TAKES]]([[OPTDEP]], [[RESULT1]])
// CHECK: destroy_value [[OWNER]]
// CHECK-NOT: destroy_value %0
// CHECK: [[NONE_BB]]:
// CHECK: [[NO_VALUE:%.*]] = enum $Optional<UnsafeRawPointer>, #Optional.none
// CHECK: [[NO_OWNER:%.*]] = enum $Optional<AnyObject>, #Optional.none
// CHECK: br [[CONT_BB]]([[NO_VALUE]] : $Optional<UnsafeRawPointer>, [[NO_OWNER]] : $Optional<AnyObject>)
takesOptConstRawPointer(string, and: sideEffect1())
}
// CHECK-LABEL: sil hidden [ossa] @$s18pointer_conversion014optOptStringTodD7Pointer6stringySSSgSg_tF
func optOptStringToOptOptPointer(string: String??) {
// CHECK: [[COPY:%.*]] = copy_value %0
// CHECK: [[SIDE1:%.*]] = function_ref @$s18pointer_conversion11sideEffect1SiyF
// CHECK: [[RESULT1:%.*]] = apply [[SIDE1]]()
// FIXME: this should really go somewhere that will make nil, not some(nil)
// CHECK: switch_enum [[COPY]] : $Optional<Optional<String>>, case #Optional.some!enumelt: [[SOME_BB:bb[0-9]+]], case #Optional.none!enumelt: [[NONE_BB:bb[0-9]+]]
//
// CHECK: [[SOME_BB]]([[SOME_VALUE:%.*]] :
// CHECK: switch_enum [[SOME_VALUE]] : $Optional<String>, case #Optional.some!enumelt: [[SOME_SOME_BB:bb[0-9]+]], case #Optional.none!enumelt: [[SOME_NONE_BB:bb[0-9]+]]
// CHECK: [[SOME_SOME_BB]]([[SOME_SOME_VALUE:%.*]] :
// CHECK: [[CONVERT:%.*]] = function_ref @$ss40_convertConstStringToUTF8PointerArgumentyyXlSg_xtSSs01_F0RzlF
// CHECK: [[TEMP:%.*]] = alloc_stack $UnsafeRawPointer
// CHECK: [[OWNER:%.*]] = apply [[CONVERT]]<UnsafeRawPointer>([[TEMP:%.*]], [[SOME_SOME_VALUE]])
// CHECK: [[PTR:%.*]] = load [trivial] [[TEMP]]
// CHECK: [[DEP:%.*]] = mark_dependence [[PTR]] : $UnsafeRawPointer on [[OWNER]]
// CHECK: [[OPTPTR:%.*]] = enum $Optional<UnsafeRawPointer>, #Optional.some!enumelt, [[DEP]]
// CHECK: dealloc_stack [[TEMP]]
// CHECK: br [[SOME_SOME_CONT_BB:bb[0-9]+]]([[OPTPTR]] : $Optional<UnsafeRawPointer>, [[OWNER]] : $Optional<AnyObject>)
// CHECK: [[SOME_SOME_CONT_BB]]([[OPTPTR:%.*]] : $Optional<UnsafeRawPointer>, [[OWNER:%.*]] : @owned $Optional<AnyObject>):
// CHECK: [[OPTDEP:%.*]] = mark_dependence [[OPTPTR]] : $Optional<UnsafeRawPointer> on [[OWNER]]
// CHECK: [[OPTOPTPTR:%.*]] = enum $Optional<Optional<UnsafeRawPointer>>, #Optional.some!enumelt, [[OPTDEP]]
// CHECK: br [[SOME_CONT_BB:bb[0-9]+]]([[OPTOPTPTR]] : $Optional<Optional<UnsafeRawPointer>>, [[OWNER]] : $Optional<AnyObject>)
// CHECK: [[SOME_CONT_BB]]([[OPTOPTPTR:%.*]] : $Optional<Optional<UnsafeRawPointer>>, [[OWNER:%.*]] : @owned $Optional<AnyObject>):
// CHECK: [[OPTOPTDEP:%.*]] = mark_dependence [[OPTOPTPTR]] : $Optional<Optional<UnsafeRawPointer>> on [[OWNER]]
// CHECK: [[TAKES:%.*]] = function_ref @$s18pointer_conversion08takesOptD15ConstRawPointer_3andySVSgSg_SitF
// CHECK: apply [[TAKES]]([[OPTOPTDEP]], [[RESULT1]])
// CHECK: destroy_value [[OWNER]]
// CHECK-NOT: destroy_value %0
// CHECK: [[SOME_NONE_BB]]:
// CHECK: [[NO_VALUE:%.*]] = enum $Optional<UnsafeRawPointer>, #Optional.none
// CHECK: [[NO_OWNER:%.*]] = enum $Optional<AnyObject>, #Optional.none
// CHECK: br [[SOME_SOME_CONT_BB]]([[NO_VALUE]] : $Optional<UnsafeRawPointer>, [[NO_OWNER]] : $Optional<AnyObject>)
// CHECK: [[NONE_BB]]:
// CHECK: [[NO_VALUE:%.*]] = enum $Optional<Optional<UnsafeRawPointer>>, #Optional.none
// CHECK: [[NO_OWNER:%.*]] = enum $Optional<AnyObject>, #Optional.none
// CHECK: br [[SOME_CONT_BB]]([[NO_VALUE]] : $Optional<Optional<UnsafeRawPointer>>, [[NO_OWNER]] : $Optional<AnyObject>)
takesOptOptConstRawPointer(string, and: sideEffect1())
}
|
apache-2.0
|
282d4b4fb48157ca09442546c9ca6f2b
| 61.466063 | 266 | 0.650634 | 3.693645 | false | false | false | false |
minikin/Algorithmics
|
Pods/Charts/Charts/Classes/Renderers/ChartLegendRenderer.swift
|
6
|
15438
|
//
// ChartLegendRenderer.swift
// Charts
//
// Created by Daniel Cohen Gindi on 4/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
#if !os(OSX)
import UIKit
#endif
public class ChartLegendRenderer: ChartRendererBase
{
/// the legend object this renderer renders
public var legend: ChartLegend?
public init(viewPortHandler: ChartViewPortHandler, legend: ChartLegend?)
{
super.init(viewPortHandler: viewPortHandler)
self.legend = legend
}
/// Prepares the legend and calculates all needed forms, labels and colors.
public func computeLegend(data: ChartData)
{
guard let legend = legend else { return }
if (!legend.isLegendCustom)
{
var labels = [String?]()
var colors = [NSUIColor?]()
// loop for building up the colors and labels used in the legend
for i in 0..<data.dataSetCount
{
let dataSet = data.getDataSetByIndex(i)!
var clrs: [NSUIColor] = dataSet.colors
let entryCount = dataSet.entryCount
// if we have a barchart with stacked bars
if (dataSet is IBarChartDataSet && (dataSet as! IBarChartDataSet).isStacked)
{
let bds = dataSet as! IBarChartDataSet
var sLabels = bds.stackLabels
for j in 0..<min(clrs.count, bds.stackSize)
{
labels.append(sLabels[j % sLabels.count])
colors.append(clrs[j])
}
if (bds.label != nil)
{
// add the legend description label
colors.append(nil)
labels.append(bds.label)
}
}
else if (dataSet is IPieChartDataSet)
{
var xVals = data.xVals
let pds = dataSet as! IPieChartDataSet
for j in 0..<min(clrs.count, entryCount, xVals.count)
{
labels.append(xVals[j])
colors.append(clrs[j])
}
if (pds.label != nil)
{
// add the legend description label
colors.append(nil)
labels.append(pds.label)
}
}
else if (dataSet is ICandleChartDataSet
&& (dataSet as! ICandleChartDataSet).decreasingColor != nil)
{
colors.append((dataSet as! ICandleChartDataSet).decreasingColor)
colors.append((dataSet as! ICandleChartDataSet).increasingColor)
labels.append(nil)
labels.append(dataSet.label)
}
else
{ // all others
for j in 0..<min(clrs.count, entryCount)
{
// if multiple colors are set for a DataSet, group them
if (j < clrs.count - 1 && j < entryCount - 1)
{
labels.append(nil)
}
else
{ // add label to the last entry
labels.append(dataSet.label)
}
colors.append(clrs[j])
}
}
}
legend.colors = colors + legend._extraColors
legend.labels = labels + legend._extraLabels
}
// calculate all dimensions of the legend
legend.calculateDimensions(labelFont: legend.font, viewPortHandler: viewPortHandler)
}
public func renderLegend(context context: CGContext)
{
guard let legend = legend else { return }
if !legend.enabled
{
return
}
let labelFont = legend.font
let labelTextColor = legend.textColor
let labelLineHeight = labelFont.lineHeight
let formYOffset = labelLineHeight / 2.0
var labels = legend.labels
var colors = legend.colors
let formSize = legend.formSize
let formToTextSpace = legend.formToTextSpace
let xEntrySpace = legend.xEntrySpace
let direction = legend.direction
// space between the entries
let stackSpace = legend.stackSpace
let yoffset = legend.yOffset
let xoffset = legend.xOffset
let legendPosition = legend.position
switch (legendPosition)
{
case
.BelowChartLeft,
.BelowChartRight,
.BelowChartCenter,
.AboveChartLeft,
.AboveChartRight,
.AboveChartCenter:
let contentWidth: CGFloat = viewPortHandler.contentWidth
var originPosX: CGFloat
if (legendPosition == .BelowChartLeft || legendPosition == .AboveChartLeft)
{
originPosX = viewPortHandler.contentLeft + xoffset
if (direction == .RightToLeft)
{
originPosX += legend.neededWidth
}
}
else if (legendPosition == .BelowChartRight || legendPosition == .AboveChartRight)
{
originPosX = viewPortHandler.contentRight - xoffset
if (direction == .LeftToRight)
{
originPosX -= legend.neededWidth
}
}
else // .BelowChartCenter || .AboveChartCenter
{
originPosX = viewPortHandler.contentLeft + contentWidth / 2.0
}
var calculatedLineSizes = legend.calculatedLineSizes
var calculatedLabelSizes = legend.calculatedLabelSizes
var calculatedLabelBreakPoints = legend.calculatedLabelBreakPoints
var posX: CGFloat = originPosX
var posY: CGFloat
if (legendPosition == .AboveChartLeft
|| legendPosition == .AboveChartRight
|| legendPosition == .AboveChartCenter)
{
posY = 0
}
else
{
posY = viewPortHandler.chartHeight - yoffset - legend.neededHeight
}
var lineIndex: Int = 0
for i in 0..<labels.count
{
if (i < calculatedLabelBreakPoints.count && calculatedLabelBreakPoints[i])
{
posX = originPosX
posY += labelLineHeight
}
if (posX == originPosX && legendPosition == .BelowChartCenter && lineIndex < calculatedLineSizes.count)
{
posX += (direction == .RightToLeft ? calculatedLineSizes[lineIndex].width : -calculatedLineSizes[lineIndex].width) / 2.0
lineIndex++
}
let drawingForm = colors[i] != nil
let isStacked = labels[i] == nil // grouped forms have null labels
if (drawingForm)
{
if (direction == .RightToLeft)
{
posX -= formSize
}
drawForm(context: context, x: posX, y: posY + formYOffset, colorIndex: i, legend: legend)
if (direction == .LeftToRight)
{
posX += formSize
}
}
if (!isStacked)
{
if (drawingForm)
{
posX += direction == .RightToLeft ? -formToTextSpace : formToTextSpace
}
if (direction == .RightToLeft)
{
posX -= calculatedLabelSizes[i].width
}
drawLabel(context: context, x: posX, y: posY, label: labels[i]!, font: labelFont, textColor: labelTextColor)
if (direction == .LeftToRight)
{
posX += calculatedLabelSizes[i].width
}
posX += direction == .RightToLeft ? -xEntrySpace : xEntrySpace
}
else
{
posX += direction == .RightToLeft ? -stackSpace : stackSpace
}
}
case
.PiechartCenter,
.RightOfChart,
.RightOfChartCenter,
.RightOfChartInside,
.LeftOfChart,
.LeftOfChartCenter,
.LeftOfChartInside:
// contains the stacked legend size in pixels
var stack = CGFloat(0.0)
var wasStacked = false
var posX: CGFloat = 0.0, posY: CGFloat = 0.0
if (legendPosition == .PiechartCenter)
{
posX = viewPortHandler.chartWidth / 2.0 + (direction == .LeftToRight ? -legend.textWidthMax / 2.0 : legend.textWidthMax / 2.0)
posY = viewPortHandler.chartHeight / 2.0 - legend.neededHeight / 2.0 + legend.yOffset
}
else
{
let isRightAligned = legendPosition == .RightOfChart ||
legendPosition == .RightOfChartCenter ||
legendPosition == .RightOfChartInside
if (isRightAligned)
{
posX = viewPortHandler.chartWidth - xoffset
if (direction == .LeftToRight)
{
posX -= legend.textWidthMax
}
}
else
{
posX = xoffset
if (direction == .RightToLeft)
{
posX += legend.textWidthMax
}
}
switch legendPosition
{
case .RightOfChart, .LeftOfChart:
posY = viewPortHandler.contentTop + yoffset
case .RightOfChartCenter, .LeftOfChartCenter:
posY = viewPortHandler.chartHeight / 2.0 - legend.neededHeight / 2.0
default: // case .RightOfChartInside, .LeftOfChartInside
posY = viewPortHandler.contentTop + yoffset
}
}
for i in 0..<labels.count
{
let drawingForm = colors[i] != nil
var x = posX
if (drawingForm)
{
if (direction == .LeftToRight)
{
x += stack
}
else
{
x -= formSize - stack
}
drawForm(context: context, x: x, y: posY + formYOffset, colorIndex: i, legend: legend)
if (direction == .LeftToRight)
{
x += formSize
}
}
if (labels[i] != nil)
{
if (drawingForm && !wasStacked)
{
x += direction == .LeftToRight ? formToTextSpace : -formToTextSpace
}
else if (wasStacked)
{
x = posX
}
if (direction == .RightToLeft)
{
x -= (labels[i] as NSString!).sizeWithAttributes([NSFontAttributeName: labelFont]).width
}
if (!wasStacked)
{
drawLabel(context: context, x: x, y: posY, label: labels[i]!, font: labelFont, textColor: labelTextColor)
}
else
{
posY += labelLineHeight
drawLabel(context: context, x: x, y: posY, label: labels[i]!, font: labelFont, textColor: labelTextColor)
}
// make a step down
posY += labelLineHeight
stack = 0.0
}
else
{
stack += formSize + stackSpace
wasStacked = true
}
}
}
}
private var _formLineSegmentsBuffer = [CGPoint](count: 2, repeatedValue: CGPoint())
/// Draws the Legend-form at the given position with the color at the given index.
public func drawForm(context context: CGContext, x: CGFloat, y: CGFloat, colorIndex: Int, legend: ChartLegend)
{
guard let formColor = legend.colors[colorIndex] where formColor != NSUIColor.clearColor() else {
return
}
let formsize = legend.formSize
CGContextSaveGState(context)
defer { CGContextRestoreGState(context) }
switch (legend.form)
{
case .Circle:
CGContextSetFillColorWithColor(context, formColor.CGColor)
CGContextFillEllipseInRect(context, CGRect(x: x, y: y - formsize / 2.0, width: formsize, height: formsize))
case .Square:
CGContextSetFillColorWithColor(context, formColor.CGColor)
CGContextFillRect(context, CGRect(x: x, y: y - formsize / 2.0, width: formsize, height: formsize))
case .Line:
CGContextSetLineWidth(context, legend.formLineWidth)
CGContextSetStrokeColorWithColor(context, formColor.CGColor)
_formLineSegmentsBuffer[0].x = x
_formLineSegmentsBuffer[0].y = y
_formLineSegmentsBuffer[1].x = x + formsize
_formLineSegmentsBuffer[1].y = y
CGContextStrokeLineSegments(context, _formLineSegmentsBuffer, 2)
}
}
/// Draws the provided label at the given position.
public func drawLabel(context context: CGContext, x: CGFloat, y: CGFloat, label: String, font: NSUIFont, textColor: NSUIColor)
{
ChartUtils.drawText(context: context, text: label, point: CGPoint(x: x, y: y), align: .Left, attributes: [NSFontAttributeName: font, NSForegroundColorAttributeName: textColor])
}
}
|
mit
|
2ae44e0fcd3f71f419d1c779a2e12f89
| 34.988345 | 184 | 0.458738 | 6.489281 | false | false | false | false |
arvedviehweger/swift
|
test/SILGen/cf_members.swift
|
1
|
12673
|
// RUN: %target-swift-frontend -emit-silgen -I %S/../IDE/Inputs/custom-modules %s | %FileCheck %s
// REQUIRES: objc_interop
import ImportAsMember
func makeMetatype() -> Struct1.Type { return Struct1.self }
// CHECK-LABEL: sil @_T010cf_members17importAsUnaryInityyF
public func importAsUnaryInit() {
// CHECK: function_ref @CCPowerSupplyCreateDangerous : $@convention(c) () -> @owned CCPowerSupply
var a = CCPowerSupply(dangerous: ())
let f: () -> CCPowerSupply = CCPowerSupply.init(dangerous:)
a = f()
}
// CHECK-LABEL: sil @_T010cf_members3foo{{[_0-9a-zA-Z]*}}F
public func foo(_ x: Double) {
// CHECK: bb0([[X:%.*]] : $Double):
// CHECK: [[GLOBALVAR:%.*]] = global_addr @IAMStruct1GlobalVar
// CHECK: [[ZZ:%.*]] = load [trivial] [[GLOBALVAR]]
let zz = Struct1.globalVar
// CHECK: assign [[ZZ]] to [[GLOBALVAR]]
Struct1.globalVar = zz
// CHECK: [[Z:%.*]] = project_box
// CHECK: [[FN:%.*]] = function_ref @IAMStruct1CreateSimple
// CHECK: apply [[FN]]([[X]])
var z = Struct1(value: x)
// The metatype expression should still be evaluated even if it isn't
// used.
// CHECK: [[FN:%.*]] = function_ref @IAMStruct1CreateSimple
// CHECK: [[MAKE_METATYPE:%.*]] = function_ref @_T010cf_members12makeMetatype{{[_0-9a-zA-Z]*}}F
// CHECK: apply [[MAKE_METATYPE]]()
// CHECK: apply [[FN]]([[X]])
z = makeMetatype().init(value: x)
// CHECK: [[THUNK:%.*]] = function_ref @_T0So7Struct1VABSd5value_tcfCTcTO
// CHECK: [[SELF_META:%.*]] = metatype $@thin Struct1.Type
// CHECK: [[A:%.*]] = apply [[THUNK]]([[SELF_META]])
// CHECK: [[BORROWED_A:%.*]] = begin_borrow [[A]]
// CHECK: [[A_COPY:%.*]] = copy_value [[BORROWED_A]]
let a: (Double) -> Struct1 = Struct1.init(value:)
// CHECK: apply [[A_COPY]]([[X]])
// CHECK: end_borrow [[BORROWED_A]] from [[A]]
z = a(x)
// TODO: Support @convention(c) references that only capture thin metatype
// let b: @convention(c) (Double) -> Struct1 = Struct1.init(value:)
// z = b(x)
// CHECK: [[FN:%.*]] = function_ref @IAMStruct1InvertInPlace
// CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] [[Z]] : $*Struct1
// CHECK: apply [[FN]]([[WRITE]])
z.invert()
// CHECK: [[FN:%.*]] = function_ref @IAMStruct1Rotate : $@convention(c) (@in Struct1, Double) -> Struct1
// CHECK: [[WRITE:%.*]] = begin_access [read] [unknown] [[Z]] : $*Struct1
// CHECK: [[ZVAL:%.*]] = load [trivial] [[WRITE]]
// CHECK: store [[ZVAL]] to [trivial] [[ZTMP:%.*]] :
// CHECK: apply [[FN]]([[ZTMP]], [[X]])
z = z.translate(radians: x)
// CHECK: [[THUNK:%.*]] = function_ref [[THUNK_NAME:@_T0So7Struct1V9translateABSd7radians_tFTcTO]]
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[Z]] : $*Struct1
// CHECK: [[ZVAL:%.*]] = load [trivial] [[READ]]
// CHECK: [[C:%.*]] = apply [[THUNK]]([[ZVAL]])
// CHECK: [[BORROWED_C:%.*]] = begin_borrow [[C]]
// CHECK: [[C_COPY:%.*]] = copy_value [[BORROWED_C]]
let c: (Double) -> Struct1 = z.translate(radians:)
// CHECK: apply [[C_COPY]]([[X]])
// CHECK: end_borrow [[BORROWED_C]] from [[C]]
z = c(x)
// CHECK: [[THUNK:%.*]] = function_ref [[THUNK_NAME]]
// CHECK: thin_to_thick_function [[THUNK]]
let d: (Struct1) -> (Double) -> Struct1 = Struct1.translate(radians:)
z = d(z)(x)
// TODO: If we implement SE-0042, this should thunk the value Struct1 param
// to a const* param to the underlying C symbol.
//
// let e: @convention(c) (Struct1, Double) -> Struct1
// = Struct1.translate(radians:)
// z = e(z, x)
// CHECK: [[FN:%.*]] = function_ref @IAMStruct1Scale
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[Z]] : $*Struct1
// CHECK: [[ZVAL:%.*]] = load [trivial] [[READ]]
// CHECK: apply [[FN]]([[ZVAL]], [[X]])
z = z.scale(x)
// CHECK: [[THUNK:%.*]] = function_ref @_T0So7Struct1V5scaleABSdFTcTO
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[Z]] : $*Struct1
// CHECK: [[ZVAL:%.*]] = load [trivial] [[READ]]
// CHECK: [[F:%.*]] = apply [[THUNK]]([[ZVAL]])
// CHECK: [[BORROWED_F:%.*]] = begin_borrow [[F]]
// CHECK: [[F_COPY:%.*]] = copy_value [[BORROWED_F]]
let f = z.scale
// CHECK: apply [[F_COPY]]([[X]])
// CHECK: end_borrow [[BORROWED_F]] from [[F]]
z = f(x)
// CHECK: [[THUNK:%.*]] = function_ref @_T0So7Struct1V5scaleABSdFTcTO
// CHECK: thin_to_thick_function [[THUNK]]
let g = Struct1.scale
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[Z]] : $*Struct1
// CHECK: [[ZVAL:%.*]] = load [trivial] [[READ]]
z = g(z)(x)
// TODO: If we implement SE-0042, this should directly reference the
// underlying C function.
// let h: @convention(c) (Struct1, Double) -> Struct1 = Struct1.scale
// z = h(z, x)
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[Z]] : $*Struct1
// CHECK: [[ZVAL:%.*]] = load [trivial] [[READ]]
// CHECK: store [[ZVAL]] to [trivial] [[ZTMP:%.*]] :
// CHECK: [[GET:%.*]] = function_ref @IAMStruct1GetRadius : $@convention(c) (@in Struct1) -> Double
// CHECK: apply [[GET]]([[ZTMP]])
_ = z.radius
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[Z]] : $*Struct1
// CHECK: [[ZVAL:%.*]] = load [trivial] [[READ]]
// CHECK: [[SET:%.*]] = function_ref @IAMStruct1SetRadius : $@convention(c) (Struct1, Double) -> ()
// CHECK: apply [[SET]]([[ZVAL]], [[X]])
z.radius = x
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[Z]] : $*Struct1
// CHECK: [[ZVAL:%.*]] = load [trivial] [[READ]]
// CHECK: [[GET:%.*]] = function_ref @IAMStruct1GetAltitude : $@convention(c) (Struct1) -> Double
// CHECK: apply [[GET]]([[ZVAL]])
_ = z.altitude
// CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] [[Z]] : $*Struct1
// CHECK: [[SET:%.*]] = function_ref @IAMStruct1SetAltitude : $@convention(c) (@inout Struct1, Double) -> ()
// CHECK: apply [[SET]]([[WRITE]], [[X]])
z.altitude = x
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[Z]] : $*Struct1
// CHECK: [[ZVAL:%.*]] = load [trivial] [[READ]]
// CHECK: [[GET:%.*]] = function_ref @IAMStruct1GetMagnitude : $@convention(c) (Struct1) -> Double
// CHECK: apply [[GET]]([[ZVAL]])
_ = z.magnitude
// CHECK: [[FN:%.*]] = function_ref @IAMStruct1StaticMethod
// CHECK: apply [[FN]]()
var y = Struct1.staticMethod()
// CHECK: [[THUNK:%.*]] = function_ref @_T0So7Struct1V12staticMethods5Int32VyFZTcTO
// CHECK: [[SELF:%.*]] = metatype
// CHECK: [[I:%.*]] = apply [[THUNK]]([[SELF]])
// CHECK: [[BORROWED_I:%.*]] = begin_borrow [[I]]
// CHECK: [[I_COPY:%.*]] = copy_value [[BORROWED_I]]
let i = Struct1.staticMethod
// CHECK: apply [[I_COPY]]()
// CHECK: end_borrow [[BORROWED_I]] from [[I]]
y = i()
// TODO: Support @convention(c) references that only capture thin metatype
// let j: @convention(c) () -> Int32 = Struct1.staticMethod
// y = j()
// CHECK: [[GET:%.*]] = function_ref @IAMStruct1StaticGetProperty
// CHECK: apply [[GET]]()
_ = Struct1.property
// CHECK: [[SET:%.*]] = function_ref @IAMStruct1StaticSetProperty
// CHECK: apply [[SET]](%{{[0-9]+}})
Struct1.property = y
// CHECK: [[GET:%.*]] = function_ref @IAMStruct1StaticGetOnlyProperty
// CHECK: apply [[GET]]()
_ = Struct1.getOnlyProperty
// CHECK: [[MAKE_METATYPE:%.*]] = function_ref @_T010cf_members12makeMetatype{{[_0-9a-zA-Z]*}}F
// CHECK: apply [[MAKE_METATYPE]]()
// CHECK: [[GET:%.*]] = function_ref @IAMStruct1StaticGetProperty
// CHECK: apply [[GET]]()
_ = makeMetatype().property
// CHECK: [[MAKE_METATYPE:%.*]] = function_ref @_T010cf_members12makeMetatype{{[_0-9a-zA-Z]*}}F
// CHECK: apply [[MAKE_METATYPE]]()
// CHECK: [[SET:%.*]] = function_ref @IAMStruct1StaticSetProperty
// CHECK: apply [[SET]](%{{[0-9]+}})
makeMetatype().property = y
// CHECK: [[MAKE_METATYPE:%.*]] = function_ref @_T010cf_members12makeMetatype{{[_0-9a-zA-Z]*}}F
// CHECK: apply [[MAKE_METATYPE]]()
// CHECK: [[GET:%.*]] = function_ref @IAMStruct1StaticGetOnlyProperty
// CHECK: apply [[GET]]()
_ = makeMetatype().getOnlyProperty
// CHECK: [[FN:%.*]] = function_ref @IAMStruct1SelfComesLast : $@convention(c) (Double, Struct1) -> ()
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[Z]] : $*Struct1
// CHECK: [[ZVAL:%.*]] = load [trivial] [[READ]]
// CHECK: apply [[FN]]([[X]], [[ZVAL]])
z.selfComesLast(x: x)
let k: (Double) -> () = z.selfComesLast(x:)
k(x)
let l: (Struct1) -> (Double) -> () = Struct1.selfComesLast(x:)
l(z)(x)
// TODO: If we implement SE-0042, this should thunk to reorder the arguments.
// let m: @convention(c) (Struct1, Double) -> () = Struct1.selfComesLast(x:)
// m(z, x)
// CHECK: [[FN:%.*]] = function_ref @IAMStruct1SelfComesThird : $@convention(c) (Int32, Float, Struct1, Double) -> ()
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[Z]] : $*Struct1
// CHECK: [[ZVAL:%.*]] = load [trivial] [[READ]]
// CHECK: apply [[FN]]({{.*}}, {{.*}}, [[ZVAL]], [[X]])
z.selfComesThird(a: y, b: 0, x: x)
let n: (Int32, Float, Double) -> () = z.selfComesThird(a:b:x:)
n(y, 0, x)
let o: (Struct1) -> (Int32, Float, Double) -> ()
= Struct1.selfComesThird(a:b:x:)
o(z)(y, 0, x)
// TODO: If we implement SE-0042, this should thunk to reorder the arguments.
// let p: @convention(c) (Struct1, Int, Float, Double) -> ()
// = Struct1.selfComesThird(a:b:x:)
// p(z, y, 0, x)
}
// CHECK: } // end sil function '_T010cf_members3foo{{[_0-9a-zA-Z]*}}F'
// CHECK-LABEL: sil shared [serializable] [thunk] @_T0So7Struct1VABSd5value_tcfCTO
// CHECK: bb0([[X:%.*]] : $Double, [[SELF:%.*]] : $@thin Struct1.Type):
// CHECK: [[CFUNC:%.*]] = function_ref @IAMStruct1CreateSimple
// CHECK: [[RET:%.*]] = apply [[CFUNC]]([[X]])
// CHECK: return [[RET]]
// CHECK-LABEL: sil shared [serializable] [thunk] @_T0So7Struct1V9translateABSd7radians_tFTO
// CHECK: bb0([[X:%.*]] : $Double, [[SELF:%.*]] : $Struct1):
// CHECK: store [[SELF]] to [trivial] [[TMP:%.*]] :
// CHECK: [[CFUNC:%.*]] = function_ref @IAMStruct1Rotate
// CHECK: [[RET:%.*]] = apply [[CFUNC]]([[TMP]], [[X]])
// CHECK: return [[RET]]
// CHECK-LABEL: sil shared [serializable] [thunk] @_T0So7Struct1V5scaleABSdFTO
// CHECK: bb0([[X:%.*]] : $Double, [[SELF:%.*]] : $Struct1):
// CHECK: [[CFUNC:%.*]] = function_ref @IAMStruct1Scale
// CHECK: [[RET:%.*]] = apply [[CFUNC]]([[SELF]], [[X]])
// CHECK: return [[RET]]
// CHECK-LABEL: sil shared [serializable] [thunk] @_T0So7Struct1V12staticMethods5Int32VyFZTO
// CHECK: bb0([[SELF:%.*]] : $@thin Struct1.Type):
// CHECK: [[CFUNC:%.*]] = function_ref @IAMStruct1StaticMethod
// CHECK: [[RET:%.*]] = apply [[CFUNC]]()
// CHECK: return [[RET]]
// CHECK-LABEL: sil shared [serializable] [thunk] @_T0So7Struct1V13selfComesLastySd1x_tFTO
// CHECK: bb0([[X:%.*]] : $Double, [[SELF:%.*]] : $Struct1):
// CHECK: [[CFUNC:%.*]] = function_ref @IAMStruct1SelfComesLast
// CHECK: apply [[CFUNC]]([[X]], [[SELF]])
// CHECK-LABEL: sil shared [serializable] [thunk] @_T0So7Struct1V14selfComesThirdys5Int32V1a_Sf1bSd1xtFTO
// CHECK: bb0([[X:%.*]] : $Int32, [[Y:%.*]] : $Float, [[Z:%.*]] : $Double, [[SELF:%.*]] : $Struct1):
// CHECK: [[CFUNC:%.*]] = function_ref @IAMStruct1SelfComesThird
// CHECK: apply [[CFUNC]]([[X]], [[Y]], [[SELF]], [[Z]])
// CHECK-LABEL: sil @_T010cf_members3bar{{[_0-9a-zA-Z]*}}F
public func bar(_ x: Double) {
// CHECK: function_ref @CCPowerSupplyCreate : $@convention(c) (Double) -> @owned CCPowerSupply
let ps = CCPowerSupply(watts: x)
// CHECK: function_ref @CCRefrigeratorCreate : $@convention(c) (CCPowerSupply) -> @owned CCRefrigerator
let fridge = CCRefrigerator(powerSupply: ps)
// CHECK: function_ref @CCRefrigeratorOpen : $@convention(c) (CCRefrigerator) -> ()
fridge.open()
// CHECK: function_ref @CCRefrigeratorGetPowerSupply : $@convention(c) (CCRefrigerator) -> @autoreleased CCPowerSupply
let ps2 = fridge.powerSupply
// CHECK: function_ref @CCRefrigeratorSetPowerSupply : $@convention(c) (CCRefrigerator, CCPowerSupply) -> ()
fridge.powerSupply = ps2
let a: (Double) -> CCPowerSupply = CCPowerSupply.init(watts:)
let _ = a(x)
let b: (CCRefrigerator) -> () -> () = CCRefrigerator.open
b(fridge)()
let c = fridge.open
c()
}
// CHECK-LABEL: sil @_T010cf_members28importGlobalVarsAsProperties{{[_0-9a-zA-Z]*}}F
public func importGlobalVarsAsProperties()
-> (Double, CCPowerSupply, CCPowerSupply?) {
// CHECK: global_addr @kCCPowerSupplyDC
// CHECK: global_addr @kCCPowerSupplyAC
// CHECK: global_addr @kCCPowerSupplyDefaultPower
return (CCPowerSupply.defaultPower, CCPowerSupply.AC, CCPowerSupply.DC)
}
|
apache-2.0
|
6a09cc0f593a5ba49833a84c7f67e04c
| 44.099644 | 120 | 0.588574 | 3.330618 | false | false | false | false |
piscoTech/Workout
|
Workout/Controller/Settings/RouteTypeTVC.swift
|
1
|
1375
|
//
// RouteTypeTableViewController.swift
// Workout
//
// Created by Marco Boschi on 22/12/2019.
// Copyright © 2019 Marco Boschi. All rights reserved.
//
import UIKit
import WorkoutCore
class RouteTypeTableViewController: UITableViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return RouteType.allCases.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "type", for: indexPath)
let type = RouteType.allCases[indexPath.row]
cell.textLabel?.text = type.displayName
cell.accessoryType = preferences.routeType == type ? .checkmark : .none
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
preferences.routeType = RouteType.allCases[indexPath.row]
for i in 0 ..< RouteType.allCases.count {
if let cell = tableView.cellForRow(at: IndexPath(row: i, section: 0)) {
cell.accessoryType = i == indexPath.row ? .checkmark : .none
}
}
tableView.deselectRow(at: indexPath, animated: true)
}
}
|
mit
|
90eaa75ac308c86e3819ee1d0ecd6952
| 27.625 | 106 | 0.719796 | 4.267081 | false | false | false | false |
eurofurence/ef-app_ios
|
Packages/EurofurenceKit/Tests/EurofurenceKitTests/Model Ingestion/Deletions/DeletingKnowledgeGroupTests.swift
|
1
|
2193
|
import CoreData
@testable import EurofurenceKit
import EurofurenceWebAPI
import XCTAsyncAssertions
import XCTest
class DeletingKnowledgeGroupTests: EurofurenceKitTestCase {
func testDeletingKnowledgeGroupDeletesEntriesAssociatedWithGroup() async throws {
let scenario = await EurofurenceModelTestBuilder().build()
let payload = try SampleResponse.ef26.loadResponse()
await scenario.stubSyncResponse(with: .success(payload))
try await scenario.updateLocalStore()
// Assert once the knowledge group has been deleted, the models invariants continue to be satisfied *and* the
// entries associated with the group have been deleted.
let deletedKnowledgeGroupIdentifier = "92cdf214-7e9f-6bfa-0370-dfadd5e76493"
let knowledgeEntryIdentifiers = try autoreleasepool { () -> [String] in
let fetchRequest: NSFetchRequest<EurofurenceKit.KnowledgeGroup> = EurofurenceKit
.KnowledgeGroup
.fetchRequestForExistingEntity(identifier: deletedKnowledgeGroupIdentifier)
let results = try scenario.viewContext.fetch(fetchRequest)
let knowledgeGroup = try XCTUnwrap(results.first)
return knowledgeGroup.orderedKnowledgeEntries.map(\.identifier)
}
// Ensure each knowledge entry is available before processing the deletion
for knowledgeEntryIdentifier in knowledgeEntryIdentifiers {
XCTAssertNoThrow(try scenario.model.knowledgeEntry(identifiedBy: knowledgeEntryIdentifier))
}
let deleteKnowledgeGroupPayload = try SampleResponse.deletedKnowledgeGroup.loadResponse()
await scenario.stubSyncResponse(with: .success(deleteKnowledgeGroupPayload), for: payload.synchronizationToken)
try await scenario.updateLocalStore()
for knowledgeEntryIdentifier in knowledgeEntryIdentifiers {
XCTAssertThrowsSpecificError(
EurofurenceError.invalidKnowledgeEntry(knowledgeEntryIdentifier),
try scenario.model.knowledgeEntry(identifiedBy: knowledgeEntryIdentifier)
)
}
}
}
|
mit
|
467392242a6e1203b18882a9f6ac4f0b
| 46.673913 | 119 | 0.714546 | 6.091667 | false | true | false | false |
TouchInstinct/LeadKit
|
TIGoogleMapUtils/Sources/GoogleClusterPlacemarkManager.swift
|
1
|
5360
|
//
// Copyright (c) 2022 Touch Instinct
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the Software), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED AS IS, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import TIMapUtils
import GoogleMapsUtils
import GoogleMaps
open class GoogleClusterPlacemarkManager<Model>: BasePlacemarkManager<GMSMarker, [GooglePlacemarkManager<Model>], GMSCoordinateBounds>,
GMUClusterRendererDelegate,
GMUClusterManagerDelegate,
GMUClusterIconGenerator {
public var mapDelegate: GMSMapViewDelegate? {
didSet {
clusterManager?.setMapDelegate(mapDelegate)
}
}
public private(set) var clusterManager: GMUClusterManager?
public var defaultClusterIconGenerator = GMUDefaultClusterIconGenerator()
public init<IF: MarkerIconFactory>(placemarkManagers: [GooglePlacemarkManager<Model>],
iconFactory: IF?,
mapDelegate: GMSMapViewDelegate? = nil,
tapHandler: TapHandlerClosure?) where IF.Model == [Model] {
super.init(dataModel: placemarkManagers,
iconFactory: iconFactory?.asAnyMarkerIconFactory { $0.map { $0.dataModel } },
tapHandler: tapHandler)
self.mapDelegate = mapDelegate
}
open func clusterAlgorithm() -> GMUClusterAlgorithm {
GMUNonHierarchicalDistanceBasedAlgorithm()
}
open func clusterRenderer(for map: GMSMapView) -> GMUClusterRenderer {
let renderer = GMUDefaultClusterRenderer(mapView: map,
clusterIconGenerator: self)
renderer.delegate = self
return renderer
}
open func addMarkers(to map: GMSMapView) {
clusterManager = GMUClusterManager(map: map,
algorithm: clusterAlgorithm(),
renderer: clusterRenderer(for: map))
clusterManager?.setDelegate(self, mapDelegate: mapDelegate)
clusterManager?.add(dataModel)
clusterManager?.cluster()
}
open func removeMarkers() {
clusterManager?.clearItems()
}
// MARK: - GMUClusterRendererDelegate
open func renderer(_ renderer: GMUClusterRenderer, markerFor object: Any) -> GMSMarker? {
nil
}
open func renderer(_ renderer: GMUClusterRenderer, willRenderMarker marker: GMSMarker) {
switch marker.userData {
case let cluster as GMUCluster:
guard let placemarkManagers = cluster.items as? [GooglePlacemarkManager<Model>] else {
return
}
marker.icon = iconFactory?.markerIcon(for: placemarkManagers)
?? defaultClusterIconGenerator.icon(forSize: UInt(placemarkManagers.count))
case let clusterItem as GooglePlacemarkManager<Model>:
clusterItem.configure(placemark: marker)
default:
break
}
}
open func renderer(_ renderer: GMUClusterRenderer, didRenderMarker marker: GMSMarker) {
// nothing
}
// MARK: - GMUClusterManagerDelegate
open func clusterManager(_ clusterManager: GMUClusterManager, didTap cluster: GMUCluster) -> Bool {
guard let placemarkManagers = cluster.items as? [GooglePlacemarkManager<Model>] else {
return false
}
return tapHandler?(placemarkManagers, .from(coordinates: placemarkManagers.map { $0.position }) ?? .init()) ?? false
}
open func clusterManager(_ clusterManager: GMUClusterManager, didTap clusterItem: GMUClusterItem) -> Bool {
guard let placemarkManager = clusterItem as? GooglePlacemarkManager<Model> else {
return false
}
return placemarkManager.tapHandler?(placemarkManager.dataModel, clusterItem.position) ?? false
}
// MARK: - GMUClusterIconGenerator
open func icon(forSize size: UInt) -> UIImage? {
nil // icon generation will be performed in GMUClusterRendererDelegate callback
}
}
extension GMSCoordinateBounds: CoordinateBounds {
public static func of(southWest: CLLocationCoordinate2D, northEast: CLLocationCoordinate2D) -> Self {
.init(coordinate: southWest, coordinate: northEast)
}
}
|
apache-2.0
|
36f90ec3beb4b10597beda19d6bd0aa0
| 38.411765 | 135 | 0.656157 | 5.219085 | false | false | false | false |
NewAmsterdamLabs/stripe-ios
|
Example/Stripe iOS Example (Simple)/Buttons.swift
|
2
|
1454
|
//
// Buttons.swift
// Stripe iOS Example (Simple)
//
// Created by Ben Guo on 4/25/16.
// Copyright © 2016 Stripe. All rights reserved.
//
import UIKit
import Stripe
class HighlightingButton: UIButton {
var highlightColor = UIColor(white: 0, alpha: 0.05)
convenience init(highlightColor: UIColor) {
self.init()
self.highlightColor = highlightColor
}
override var isHighlighted: Bool {
didSet {
if isHighlighted {
self.backgroundColor = self.highlightColor
} else {
self.backgroundColor = UIColor.clear
}
}
}
}
class BuyButton: HighlightingButton {
var disabledColor = UIColor.lightGray
var enabledColor = UIColor(red:0.22, green:0.65, blue:0.91, alpha:1.00)
override var isEnabled: Bool {
didSet {
let color = isEnabled ? enabledColor : disabledColor
self.setTitleColor(color, for: UIControlState())
self.layer.borderColor = color.cgColor
self.highlightColor = color.withAlphaComponent(0.5)
}
}
convenience init(enabled: Bool, theme: STPTheme) {
self.init()
self.layer.borderWidth = 2
self.layer.cornerRadius = 10
self.setTitle("Buy", for: UIControlState())
self.disabledColor = theme.secondaryForegroundColor
self.enabledColor = theme.accentColor
self.isEnabled = enabled
}
}
|
mit
|
3521e7923bdead666415cf6cbd0b7ae7
| 26.415094 | 75 | 0.621473 | 4.540625 | false | false | false | false |
iabudiab/gdg-devfestka-2015-swift
|
Swift Intro.playground/Pages/Optionals.xcplaygroundpage/Contents.swift
|
1
|
821
|
//: [Previous](@previous)
var languages = [
"Swift": 1,
"Java": 2,
"Objective-C": 3,
"C++": 4,
"JS": 5
]
var possible: Int? = languages["Go"]
if possible != nil {
print("Go is \(possible!)")
} else {
print("It's a no Go")
}
possible = languages["Swift"]
if let actualValue = possible {
print("Swift is \(actualValue)")
} else {
print("It's a no Go")
}
var movies: [String]? = ["Rambo", "Matrix", "Snatch"]
if let count = movies?.count {
print("I have \(count) movies")
} else {
print("Movies collection is undefined")
}
var x = Int("1000")
let y = Int("337")
let z = Int("11")
if let a = x {
if let b = y {
if let c = z {
if c != 0 {
print("(x + y) / z = \((a + b) / c)")
}
}
}
}
if let a = x, b = y, c = z where c != 0
{
print("(x + y) / z = \((a + b) / c)")
}
//: [Next](@next)
|
mit
|
3023c56429414a12d56c7f7f621969e8
| 13.660714 | 53 | 0.518879 | 2.503049 | false | false | false | false |
RizanHa/RHImgPicker
|
Example/RHImgPicker/ViewController.swift
|
1
|
5865
|
//
// ViewController.swift
// RHImgPicker
//
// Created by Rizan Hamza on 08/31/2016.
// Copyright (c) 2016 Rizan Hamza. All rights reserved.
//
import UIKit
import RHImgPicker
import Photos
class ViewController: UIViewController, RHImgPickerDelegate {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
setupRHImgPicker()
setupDemoView()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override var preferredStatusBarStyle : UIStatusBarStyle {
return UIStatusBarStyle.lightContent
}
fileprivate let imgPicker = RHImgPickerViewController()
fileprivate func setupRHImgPicker() {
imgPicker.settings.maxNumberOfSelections = 1
///imgPicker.settings.selectionCharacter = Character(" ")
imgPicker.settings.setAlbumCellAnimation { (layer) in
let PI : CGFloat = 3.145
var rotation : CATransform3D
rotation = CATransform3DMakeRotation( (90.0*PI)/180, 0.0, 0.7, 0.4)
rotation.m34 = 1.0 / -600;
layer.shadowColor = UIColor.black.cgColor
layer.shadowOffset = CGSize(width: 10, height: 10);
layer.opacity = 0;
layer.transform = rotation;
layer.anchorPoint = CGPoint(x: 0, y: 0.5);
UIView.animate(withDuration: 0.5, animations: {
layer.transform = CATransform3DIdentity;
layer.opacity = 1;
layer.shadowOffset = CGSize(width: 0, height: 0);
}, completion: { (finish) in
layer.transform = CATransform3DIdentity;
})
}
}
fileprivate let imgViews : [UIImageView] = [UIImageView(),UIImageView(),UIImageView(),UIImageView(),UIImageView(),UIImageView()] /// 6 UIImageViews
fileprivate func setupDemoView() {
self.view.backgroundColor = UIColor.darkGray
let offset : CGFloat = UIScreen.main.bounds.size.height * 0.2
let maxImgsInARow : CGFloat = 3
let imgSizeXY : CGFloat = UIScreen.main.bounds.size.width / maxImgsInARow
var rowIndex : CGFloat = 0
var columnIndex : CGFloat = 0
var index = 0
for imgView in imgViews {
imgView.frame = CGRect(x: imgSizeXY*columnIndex, y: imgSizeXY*rowIndex + offset, width: imgSizeXY, height: imgSizeXY)
imgView.backgroundColor = UIColor.clear
imgView.contentMode = .scaleAspectFit
imgView.layer.borderWidth = 1
imgView.layer.borderColor = UIColor.lightText.cgColor
self.view.addSubview(imgView)
let lbl : UILabel = UILabel(frame: imgView.bounds)
lbl.text = String(index+1)
lbl.textColor = UIColor.lightText
lbl.frame = lbl.frame.offsetBy(dx: 0, dy: -lbl.frame.size.height*0.6 )
lbl.textAlignment = .center
imgView.addSubview(lbl)
index = index + 1
columnIndex = columnIndex + 1
if columnIndex == maxImgsInARow {
columnIndex = 0
rowIndex = rowIndex + 1.5
}
}
}
@IBAction func buttonDidPressed(_ sender: AnyObject) {
self.rh_presentRHImgPickerController(imgPicker, delegate: self, animated: true) {
// done...
}
}
fileprivate func getAssetThumbnail(_ asset: PHAsset) -> UIImage {
let manager = PHImageManager.default()
let option = PHImageRequestOptions()
option.isSynchronous = true
var thumbnail = UIImage()
let maxSizeImg : Double = 200
manager.requestImage(for: asset, targetSize: CGSize(width: Int(maxSizeImg), height: Int(maxSizeImg) ), contentMode: .aspectFit , options: option, resultHandler: {(result, info)->Void in
thumbnail = result!
})
return thumbnail
}
@IBAction func selectionLimitDidChange(_ sender: AnyObject) {
if let sender : UISegmentedControl = sender as? UISegmentedControl {
if let value = sender.titleForSegment(at: sender.selectedSegmentIndex), let intValue = Int(value) {
imgPicker.settings.maxNumberOfSelections = intValue
imgPicker.clearSelection()
}
}
}
//MARK: - RHImgPicker Delegate
func RHImgPickerDidFinishPickingAssets(_ assets: [PHAsset]) {
// clear all
for imgView in imgViews {
imgView.image = nil
}
// update with curent selection
for (curentIndex ,item ) in assets.enumerated() {
if curentIndex < imgViews.count {
let img : UIImage = self.getAssetThumbnail(item)
imgViews[curentIndex].image = img
}
}
}
func RHImgPickerDidClearAllSelectedAssets() {
}
func RHImgPickerDidSelectAsset(_ asset: PHAsset) {
}
func RHImgPickerDidDeselectAsset(_ asset: PHAsset) {
}
}
|
mit
|
9a17709efb8216606ad4cf9bcfc7ffef
| 25.90367 | 193 | 0.532992 | 5.420518 | false | false | false | false |
silence0201/Swift-Study
|
AdvancedSwift/结构体/Memory - Capture Lists.playgroundpage/Contents.swift
|
1
|
1508
|
/*:
### Capture Lists
*/
//#-hidden-code
class View {
var window: Window
init(window: Window) {
self.window = window
}
deinit {
print("Deinit View")
}
}
class Window {
weak var rootView: View?
deinit {
print("Deinit Window")
}
var onRotate: (() -> ())?
}
//#-end-hidden-code
//#-hidden-code
var window: Window? = Window()
var view: View? = View(window: window!)
window?.rootView = view!
//#-end-hidden-code
/*:
To break the cycle above, we want to make sure the closure won't reference the
view. We can do this by using a *capture list* and marking the captured variable
(`view`) as either `weak` or `unowned`:
*/
//#-editable-code
window?.onRotate = { [weak view] in
print("We now also need to update the view: \(view)")
}
//#-end-editable-code
/*:
Capture lists can also be used to initialize new variables. For example, if we
wanted to have a weak variable that refers to the window, we could initialize it
in the capture list, or we could even define completely unrelated variables,
like so:
*/
//#-editable-code
window?.onRotate = { [weak view, weak myWindow=window, x=5*5] in
print("We now also need to update the view: \(view)")
print("Because the window \(myWindow) changed")
}
//#-end-editable-code
/*:
This is almost the same as defining the variable just above the closure, except
that with capture lists, the scope of the variable is just the scope of the
closure; it's not available outside of the closure.
*/
|
mit
|
edf34a517e8ebc72ee913b39b6844d66
| 21.848485 | 80 | 0.670424 | 3.687042 | false | false | false | false |
milot/BoxFinder
|
BoxFinder/MasterViewController.swift
|
1
|
4410
|
//
// MasterViewController.swift
// BoxFinder
//
// Created by Milot Shala on 4/7/17.
// Copyright © 2017 Milot Shala. All rights reserved.
//
import UIKit
import RealmSwift
class MasterViewController: UITableViewController {
var detailViewController: DetailViewController? = nil
var objects = [Any]()
var realm: Realm!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .camera, target: self, action: #selector(scanQrCode(_:)))
let addButton = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(insertNewObject(_:)))
navigationItem.rightBarButtonItem = addButton
if let split = splitViewController {
let controllers = split.viewControllers
detailViewController = (controllers[controllers.count-1] as! UINavigationController).topViewController as? DetailViewController
}
do {
self.realm = try Realm()
} catch {
}
let boxes = self.realm.objects(Box.self)
for box in boxes {
objects.append(box)
}
}
func scanQrCode(_ sender: Any) {
print("Show QR code")
}
override func viewWillAppear(_ animated: Bool) {
clearsSelectionOnViewWillAppear = splitViewController!.isCollapsed
super.viewWillAppear(animated)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func insertNewObject(_ sender: Any) {
let addItemAlert = UIAlertController(title: "Box name", message: nil, preferredStyle: .alert)
let actionAdd = UIAlertAction(title: "Add", style: .default) { (alertAction: UIAlertAction) in
if let text = addItemAlert.textFields?.first?.text {
let box = Box(value: ["name": text, "date": NSDate()])
try! self.realm.write {
self.realm.add(box)
}
self.objects.append(box)
self.tableView.reloadData()
}
}
let actionCancel = UIAlertAction(title: "Cancel", style: .cancel) { (alertAction: UIAlertAction) in
}
addItemAlert.addTextField { (textField: UITextField) in
textField.placeholder = "Enter your box name"
}
addItemAlert.addAction(actionAdd)
addItemAlert.addAction(actionCancel)
present(addItemAlert, animated: true, completion: nil)
}
// MARK: - Segues
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "showDetail" {
if let indexPath = tableView.indexPathForSelectedRow {
let object = objects[indexPath.row] as! Box
let controller = (segue.destination as! UINavigationController).topViewController as! DetailViewController
controller.boxId = "\(object.name)\(object.date)".trimmingCharacters(in: .whitespaces)
controller.navigationItem.leftBarButtonItem = splitViewController?.displayModeButtonItem
controller.navigationItem.leftItemsSupplementBackButton = true
}
}
}
// MARK: - Table View
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return objects.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
let object = objects[indexPath.row] as! Box
cell.textLabel!.text = Box(value: object).name
return cell
}
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
let predicate = NSPredicate(format: "name == %@", Box(value: objects[indexPath.row]).name)
let boxes = self.realm.objects(Box.self).filter(predicate)
try! self.realm.write {
if let boxToDelete = boxes.first {
self.realm.delete(boxToDelete)
}
}
objects.remove(at: indexPath.row)
tableView.deleteRows(at: [indexPath], with: .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.
}
}
}
|
mit
|
60dff07e8bae933cbb26e32d38dee5a4
| 28.590604 | 133 | 0.71785 | 4.155514 | false | false | false | false |
domenicosolazzo/practice-swift
|
playgrounds/Animations/Animation1.playground/Contents.swift
|
1
|
1236
|
//: Playground - noun: a place where people can play
import UIKit
import XCPlayground
let containerView = UIView(frame: CGRect(x: 0.0, y: 0.0, width: 375.0, height: 667.0))
let circle = UIView(frame: CGRect(x: 0.0, y: 0.0, width: 50.0, height: 50.0))
circle.center = containerView.center
circle.layer.cornerRadius = 25.0
let startingColor = UIColor(red: (253.0/255.0), green: (159.0/255.0), blue: (47.0/255.0), alpha: 1.0)
circle.backgroundColor = startingColor
containerView.addSubview(circle);
let rectangle = UIView(frame: CGRect(x: 0.0, y: 0.0, width: 50.0, height: 50.0))
rectangle.center = containerView.center
rectangle.layer.cornerRadius = 5.0
rectangle.backgroundColor = UIColor.whiteColor()
containerView.addSubview(rectangle)
UIView.animateWithDuration(2.0, animations: { () -> Void in
let endingColor = UIColor(red: (255.0/255.0), green: (61.0/255.0), blue: (24.0/255.0), alpha: 1.0)
circle.backgroundColor = endingColor
let scaleTransform = CGAffineTransformMakeScale(5.0, 5.0)
circle.transform = scaleTransform
let rotationTransform = CGAffineTransformMakeRotation(3.14)
rectangle.transform = rotationTransform
})
XCPlaygroundPage.currentPage.liveView = containerView
|
mit
|
be1859c2335be9052cc0c6869e7314b1
| 30.717949 | 102 | 0.723301 | 3.452514 | false | false | false | false |
PomTTcat/SourceCodeGuideRead_JEFF
|
RxSwiftGuideRead/RxSwift-master/RxExample/RxDataSources/RxDataSources/CollectionViewSectionedDataSource.swift
|
3
|
5744
|
//
// CollectionViewSectionedDataSource.swift
// RxDataSources
//
// Created by Krunoslav Zaher on 7/2/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
#if os(iOS) || os(tvOS)
import Foundation
import UIKit
import RxCocoa
open class CollectionViewSectionedDataSource<Section: SectionModelType>
: NSObject
, UICollectionViewDataSource
, SectionedViewDataSourceType {
public typealias ConfigureCell = (CollectionViewSectionedDataSource<Section>, UICollectionView, IndexPath, Section.Item) -> UICollectionViewCell
public typealias ConfigureSupplementaryView = (CollectionViewSectionedDataSource<Section>, UICollectionView, String, IndexPath) -> UICollectionReusableView
public typealias MoveItem = (CollectionViewSectionedDataSource<Section>, _ sourceIndexPath:IndexPath, _ destinationIndexPath:IndexPath) -> Void
public typealias CanMoveItemAtIndexPath = (CollectionViewSectionedDataSource<Section>, IndexPath) -> Bool
public init(
configureCell: @escaping ConfigureCell,
configureSupplementaryView: @escaping ConfigureSupplementaryView,
moveItem: @escaping MoveItem = { _, _, _ in () },
canMoveItemAtIndexPath: @escaping CanMoveItemAtIndexPath = { _, _ in false }
) {
self.configureCell = configureCell
self.configureSupplementaryView = configureSupplementaryView
self.moveItem = moveItem
self.canMoveItemAtIndexPath = canMoveItemAtIndexPath
}
#if DEBUG
// If data source has already been bound, then mutating it
// afterwards isn't something desired.
// This simulates immutability after binding
var _dataSourceBound: Bool = false
private func ensureNotMutatedAfterBinding() {
assert(!_dataSourceBound, "Data source is already bound. Please write this line before binding call (`bindTo`, `drive`). Data source must first be completely configured, and then bound after that, otherwise there could be runtime bugs, glitches, or partial malfunctions.")
}
#endif
// This structure exists because model can be mutable
// In that case current state value should be preserved.
// The state that needs to be preserved is ordering of items in section
// and their relationship with section.
// If particular item is mutable, that is irrelevant for this logic to function
// properly.
public typealias SectionModelSnapshot = SectionModel<Section, Section.Item>
private var _sectionModels: [SectionModelSnapshot] = []
open var sectionModels: [Section] {
return _sectionModels.map { Section(original: $0.model, items: $0.items) }
}
open subscript(section: Int) -> Section {
let sectionModel = self._sectionModels[section]
return Section(original: sectionModel.model, items: sectionModel.items)
}
open subscript(indexPath: IndexPath) -> Section.Item {
get {
return self._sectionModels[indexPath.section].items[indexPath.item]
}
set(item) {
var section = self._sectionModels[indexPath.section]
section.items[indexPath.item] = item
self._sectionModels[indexPath.section] = section
}
}
open func model(at indexPath: IndexPath) throws -> Any {
return self[indexPath]
}
open func setSections(_ sections: [Section]) {
self._sectionModels = sections.map { SectionModelSnapshot(model: $0, items: $0.items) }
}
open var configureCell: ConfigureCell {
didSet {
#if DEBUG
ensureNotMutatedAfterBinding()
#endif
}
}
open var configureSupplementaryView: ConfigureSupplementaryView {
didSet {
#if DEBUG
ensureNotMutatedAfterBinding()
#endif
}
}
open var moveItem: MoveItem {
didSet {
#if DEBUG
ensureNotMutatedAfterBinding()
#endif
}
}
open var canMoveItemAtIndexPath: ((CollectionViewSectionedDataSource<Section>, IndexPath) -> Bool)? {
didSet {
#if DEBUG
ensureNotMutatedAfterBinding()
#endif
}
}
// UICollectionViewDataSource
open func numberOfSections(in collectionView: UICollectionView) -> Int {
return _sectionModels.count
}
open func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return _sectionModels[section].items.count
}
open func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
precondition(indexPath.item < _sectionModels[indexPath.section].items.count)
return configureCell(self, collectionView, indexPath, self[indexPath])
}
open func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
return configureSupplementaryView(self, collectionView, kind, indexPath)
}
open func collectionView(_ collectionView: UICollectionView, canMoveItemAt indexPath: IndexPath) -> Bool {
guard let canMoveItem = canMoveItemAtIndexPath?(self, indexPath) else {
return false
}
return canMoveItem
}
open func collectionView(_ collectionView: UICollectionView, moveItemAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
self._sectionModels.moveFromSourceIndexPath(sourceIndexPath, destinationIndexPath: destinationIndexPath)
self.moveItem(self, sourceIndexPath, destinationIndexPath)
}
}
#endif
|
mit
|
c51e7efcbfbbfda5c498aa63a5ef94ab
| 37.033113 | 280 | 0.687271 | 5.766064 | false | true | false | false |
alblue/swift-corelibs-foundation
|
Foundation/XMLParser.swift
|
1
|
36569
|
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
// It is necessary to explicitly cast strlen to UInt to match the type
// of prefixLen because currently, strlen (and other functions that
// rely on swift_ssize_t) use the machine word size (int on 32 bit and
// long in on 64 bit). I've filed a bug at bugs.swift.org:
// https://bugs.swift.org/browse/SR-314
#if os(macOS) || os(iOS)
import Darwin
#elseif os(Linux) || CYGWIN
import Glibc
#endif
import CoreFoundation
extension XMLParser {
public enum ExternalEntityResolvingPolicy : UInt {
case never // default
case noNetwork
case sameOriginOnly //only applies to NSXMLParser instances initialized with -initWithContentsOfURL:
case always
}
}
extension _CFXMLInterface {
var parser: XMLParser {
return unsafeBitCast(self, to: XMLParser.self)
}
}
extension XMLParser {
internal var interface: _CFXMLInterface {
return unsafeBitCast(self, to: _CFXMLInterface.self)
}
}
private func UTF8STRING(_ bytes: UnsafePointer<UInt8>?) -> String? {
guard let bytes = bytes else {
return nil
}
if let (str, _) = String.decodeCString(bytes, as: UTF8.self,
repairingInvalidCodeUnits: false) {
return str
}
return nil
}
internal func _NSXMLParserCurrentParser() -> _CFXMLInterface? {
if let parser = XMLParser.currentParser() {
return parser.interface
} else {
return nil
}
}
internal func _NSXMLParserExternalEntityWithURL(_ interface: _CFXMLInterface, urlStr: UnsafePointer<Int8>, identifier: UnsafePointer<Int8>, context: _CFXMLInterfaceParserContext, originalLoaderFunction: _CFXMLInterfaceExternalEntityLoader) -> _CFXMLInterfaceParserInput? {
let parser = interface.parser
let policy = parser.externalEntityResolvingPolicy
var a: URL?
if let allowedEntityURLs = parser.allowedExternalEntityURLs {
if let url = URL(string: String(describing: urlStr)) {
a = url
if let scheme = url.scheme {
if scheme == "file" {
a = URL(fileURLWithPath: url.path)
}
}
}
if let url = a {
let allowed = allowedEntityURLs.contains(url)
if allowed || policy != .sameOriginOnly {
if allowed {
return originalLoaderFunction(urlStr, identifier, context)
}
}
}
}
switch policy {
case .sameOriginOnly:
guard let url = parser._url else { break }
if a == nil {
a = URL(string: String(describing: urlStr))
}
guard let aUrl = a else { break }
var matches: Bool
if let aHost = aUrl.host, let host = url.host {
matches = host == aHost
} else {
return nil
}
if matches {
if let aPort = aUrl.port, let port = url.port {
matches = port == aPort
} else {
return nil
}
}
if matches {
if let aScheme = aUrl.scheme, let scheme = url.scheme {
matches = scheme == aScheme
} else {
return nil
}
}
if !matches {
return nil
}
case .always:
break
case .never:
return nil
case .noNetwork:
return _CFXMLInterfaceNoNetExternalEntityLoader(urlStr, identifier, context)
}
return originalLoaderFunction(urlStr, identifier, context)
}
internal func _NSXMLParserGetContext(_ ctx: _CFXMLInterface) -> _CFXMLInterfaceParserContext {
return ctx.parser._parserContext!
}
internal func _NSXMLParserInternalSubset(_ ctx: _CFXMLInterface, name: UnsafePointer<UInt8>, ExternalID: UnsafePointer<UInt8>, SystemID: UnsafePointer<UInt8>) -> Void {
_CFXMLInterfaceSAX2InternalSubset(ctx.parser._parserContext, name, ExternalID, SystemID)
}
internal func _NSXMLParserIsStandalone(_ ctx: _CFXMLInterface) -> Int32 {
return _CFXMLInterfaceIsStandalone(ctx.parser._parserContext)
}
internal func _NSXMLParserHasInternalSubset(_ ctx: _CFXMLInterface) -> Int32 {
return _CFXMLInterfaceHasInternalSubset(ctx.parser._parserContext)
}
internal func _NSXMLParserHasExternalSubset(_ ctx: _CFXMLInterface) -> Int32 {
return _CFXMLInterfaceHasExternalSubset(ctx.parser._parserContext)
}
internal func _NSXMLParserGetEntity(_ ctx: _CFXMLInterface, name: UnsafePointer<UInt8>) -> _CFXMLInterfaceEntity? {
let parser = ctx.parser
let context = _NSXMLParserGetContext(ctx)
var entity = _CFXMLInterfaceGetPredefinedEntity(name)
if entity == nil {
entity = _CFXMLInterfaceSAX2GetEntity(context, name)
}
if entity == nil {
if let delegate = parser.delegate {
let entityName = UTF8STRING(name)!
// if the systemID was valid, we would already have the correct entity (since we're loading external dtds) so this callback is a bit of a misnomer
let result = delegate.parser(parser, resolveExternalEntityName: entityName, systemID: nil)
if _CFXMLInterfaceHasDocument(context) != 0 {
if let data = result {
// unfortunately we can't add the entity to the doc to avoid further lookup since the delegate can change under us
data.withUnsafeBytes { (bytes: UnsafePointer<UInt8>) -> Void in
_NSXMLParserCharacters(ctx, ch: bytes, len: Int32(data.count))
}
}
}
}
}
return entity
}
internal func _NSXMLParserNotationDecl(_ ctx: _CFXMLInterface, name: UnsafePointer<UInt8>, publicId: UnsafePointer<UInt8>, systemId: UnsafePointer<UInt8>) -> Void {
let parser = ctx.parser
if let delegate = parser.delegate {
let notationName = UTF8STRING(name)!
let publicIDString = UTF8STRING(publicId)
let systemIDString = UTF8STRING(systemId)
delegate.parser(parser, foundNotationDeclarationWithName: notationName, publicID: publicIDString, systemID: systemIDString)
}
}
internal func _NSXMLParserAttributeDecl(_ ctx: _CFXMLInterface, elem: UnsafePointer<UInt8>, fullname: UnsafePointer<UInt8>, type: Int32, def: Int32, defaultValue: UnsafePointer<UInt8>, tree: _CFXMLInterfaceEnumeration) -> Void {
let parser = ctx.parser
if let delegate = parser.delegate {
let elementString = UTF8STRING(elem)!
let nameString = UTF8STRING(fullname)!
let typeString = "" // FIXME!
let defaultValueString = UTF8STRING(defaultValue)
delegate.parser(parser, foundAttributeDeclarationWithName: nameString, forElement: elementString, type: typeString, defaultValue: defaultValueString)
}
// in a regular sax implementation tree is added to an attribute, which takes ownership of it; in our case we need to make sure to release it
_CFXMLInterfaceFreeEnumeration(tree)
}
internal func _NSXMLParserElementDecl(_ ctx: _CFXMLInterface, name: UnsafePointer<UInt8>, type: Int32, content: _CFXMLInterfaceElementContent) -> Void {
let parser = ctx.parser
if let delegate = parser.delegate {
let nameString = UTF8STRING(name)!
let modelString = "" // FIXME!
delegate.parser(parser, foundElementDeclarationWithName: nameString, model: modelString)
}
}
internal func _NSXMLParserUnparsedEntityDecl(_ ctx: _CFXMLInterface, name: UnsafePointer<UInt8>, publicId: UnsafePointer<UInt8>, systemId: UnsafePointer<UInt8>, notationName: UnsafePointer<UInt8>) -> Void {
let parser = ctx.parser
let context = _NSXMLParserGetContext(ctx)
// Add entities to the libxml2 doc so they'll resolve properly
_CFXMLInterfaceSAX2UnparsedEntityDecl(context, name, publicId, systemId, notationName)
if let delegate = parser.delegate {
let declName = UTF8STRING(name)!
let publicIDString = UTF8STRING(publicId)
let systemIDString = UTF8STRING(systemId)
let notationNameString = UTF8STRING(notationName)
delegate.parser(parser, foundUnparsedEntityDeclarationWithName: declName, publicID: publicIDString, systemID: systemIDString, notationName: notationNameString)
}
}
internal func _NSXMLParserStartDocument(_ ctx: _CFXMLInterface) -> Void {
let parser = ctx.parser
if let delegate = parser.delegate {
delegate.parserDidStartDocument(parser)
}
}
internal func _NSXMLParserEndDocument(_ ctx: _CFXMLInterface) -> Void {
let parser = ctx.parser
if let delegate = parser.delegate {
delegate.parserDidEndDocument(parser)
}
}
internal func _NSXMLParserStartElementNs(_ ctx: _CFXMLInterface, localname: UnsafePointer<UInt8>, prefix: UnsafePointer<UInt8>?, URI: UnsafePointer<UInt8>?, nb_namespaces: Int32, namespaces: UnsafeMutablePointer<UnsafePointer<UInt8>?>, nb_attributes: Int32, nb_defaulted: Int32, attributes: UnsafeMutablePointer<UnsafePointer<UInt8>?>) -> Void {
let parser = ctx.parser
let reportNamespaces = parser.shouldReportNamespacePrefixes
var nsDict = [String:String]()
var attrDict = [String:String]()
if nb_attributes + nb_namespaces > 0 {
for idx in stride(from: 0, to: Int(nb_namespaces) * 2, by: 2) {
var namespaceNameString: String?
var asAttrNamespaceNameString: String?
if let ns = namespaces[idx] {
namespaceNameString = UTF8STRING(ns)
asAttrNamespaceNameString = "xmlns:" + namespaceNameString!
} else {
namespaceNameString = ""
asAttrNamespaceNameString = "xmlns"
}
let namespaceValueString = namespaces[idx + 1] != nil ? UTF8STRING(namespaces[idx + 1]!) : ""
if reportNamespaces {
if let k = namespaceNameString, let v = namespaceValueString {
nsDict[k] = v
}
}
if !parser.shouldProcessNamespaces {
if let k = asAttrNamespaceNameString,
let v = namespaceValueString {
attrDict[k] = v
}
}
}
}
if reportNamespaces {
parser._pushNamespaces(nsDict)
}
for idx in stride(from: 0, to: Int(nb_attributes) * 5, by: 5) {
if attributes[idx] == nil {
continue
}
var attributeQName: String
let attrLocalName = attributes[idx]!
let attrLocalNameString = UTF8STRING(attrLocalName)!
let attrPrefix = attributes[idx + 1]
if let attrPrefixString = UTF8STRING(attrPrefix), !attrPrefixString.isEmpty {
attributeQName = attrPrefixString + ":" + attrLocalNameString
} else {
attributeQName = attrLocalNameString
}
// idx+2 = URI, which we throw away
// idx+3 = value, i+4 = endvalue
// By using XML_PARSE_NOENT the attribute value string will already have entities resolved
var attributeValue = ""
if let value = attributes[idx + 3], let endvalue = attributes[idx + 4] {
let numBytesWithoutTerminator = endvalue - value
if numBytesWithoutTerminator > 0 {
let buffer = UnsafeBufferPointer(start: value,
count: numBytesWithoutTerminator)
attributeValue = String(decoding: buffer, as: UTF8.self)
}
attrDict[attributeQName] = attributeValue
}
}
var elementName: String = UTF8STRING(localname)!
var namespaceURI: String? = nil
var qualifiedName: String? = nil
if parser.shouldProcessNamespaces {
namespaceURI = UTF8STRING(URI) ?? ""
qualifiedName = elementName
if let prefix = UTF8STRING(prefix) {
qualifiedName = elementName + ":" + prefix
}
}
else if let prefix = UTF8STRING(prefix) {
elementName = elementName + ":" + prefix
}
parser.delegate?.parser(parser, didStartElement: elementName, namespaceURI: namespaceURI, qualifiedName: qualifiedName, attributes: attrDict)
}
internal func _NSXMLParserEndElementNs(_ ctx: _CFXMLInterface , localname: UnsafePointer<UInt8>, prefix: UnsafePointer<UInt8>?, URI: UnsafePointer<UInt8>?) -> Void {
let parser = ctx.parser
var elementName: String = UTF8STRING(localname)!
var namespaceURI: String? = nil
var qualifiedName: String? = nil
if parser.shouldProcessNamespaces {
namespaceURI = UTF8STRING(URI) ?? ""
qualifiedName = elementName
if let prefix = UTF8STRING(prefix) {
qualifiedName = elementName + ":" + prefix
}
}
else if let prefix = UTF8STRING(prefix) {
elementName = elementName + ":" + prefix
}
parser.delegate?.parser(parser, didEndElement: elementName, namespaceURI: namespaceURI, qualifiedName: qualifiedName)
// Pop the last namespaces that were pushed (safe since XML is balanced)
if parser.shouldReportNamespacePrefixes {
parser._popNamespaces()
}
}
internal func _NSXMLParserCharacters(_ ctx: _CFXMLInterface, ch: UnsafePointer<UInt8>, len: Int32) -> Void {
let parser = ctx.parser
let context = parser._parserContext!
if _CFXMLInterfaceInRecursiveState(context) != 0 {
_CFXMLInterfaceResetRecursiveState(context)
} else {
if let delegate = parser.delegate {
let str = String(decoding: UnsafeBufferPointer(start: ch, count: Int(len)), as: UTF8.self)
delegate.parser(parser, foundCharacters: str)
}
}
}
internal func _NSXMLParserProcessingInstruction(_ ctx: _CFXMLInterface, target: UnsafePointer<UInt8>, data: UnsafePointer<UInt8>) -> Void {
let parser = ctx.parser
if let delegate = parser.delegate {
let targetString = UTF8STRING(target)!
let dataString = UTF8STRING(data)
delegate.parser(parser, foundProcessingInstructionWithTarget: targetString, data: dataString)
}
}
internal func _NSXMLParserCdataBlock(_ ctx: _CFXMLInterface, value: UnsafePointer<UInt8>, len: Int32) -> Void {
let parser = ctx.parser
if let delegate = parser.delegate {
delegate.parser(parser, foundCDATA: Data(bytes: value, count: Int(len)))
}
}
internal func _NSXMLParserComment(_ ctx: _CFXMLInterface, value: UnsafePointer<UInt8>) -> Void {
let parser = ctx.parser
if let delegate = parser.delegate {
let comment = UTF8STRING(value)!
delegate.parser(parser, foundComment: comment)
}
}
internal func _NSXMLParserExternalSubset(_ ctx: _CFXMLInterface, name: UnsafePointer<UInt8>, ExternalID: UnsafePointer<UInt8>, SystemID: UnsafePointer<UInt8>) -> Void {
_CFXMLInterfaceSAX2ExternalSubset(ctx.parser._parserContext, name, ExternalID, SystemID)
}
internal func _structuredErrorFunc(_ interface: _CFXMLInterface, error: _CFXMLInterfaceError) {
let err = _CFErrorCreateFromXMLInterface(error)._nsObject
let parser = interface.parser
parser._parserError = err
if let delegate = parser.delegate {
delegate.parser(parser, parseErrorOccurred: err)
}
}
open class XMLParser : NSObject {
private var _handler: _CFXMLInterfaceSAXHandler
internal var _stream: InputStream?
internal var _data: Data?
internal var _chunkSize = Int(4096 * 32) // a suitably large number for a decent chunk size
// This chunk of data stores the head of the stream. We know we have enough information for encoding
// when there are atleast 4 bytes in here.
internal var _bomChunk: Data?
fileprivate var _parserContext: _CFXMLInterfaceParserContext?
internal var _delegateAborted = false
internal var _url: URL?
internal var _namespaces = [[String:String]]()
// initializes the parser with the specified URL.
public convenience init?(contentsOf url: URL) {
if url.isFileURL {
if let stream = InputStream(url: url) {
self.init(stream: stream)
_url = url
} else {
return nil
}
} else {
do {
let data = try Data(contentsOf: url)
self.init(data: data)
self._url = url
} catch {
return nil
}
}
}
// create the parser from data
public init(data: Data) {
_CFSetupXMLInterface()
_data = data
_handler = _CFXMLInterfaceCreateSAXHandler()
_parserContext = nil
}
deinit {
_CFXMLInterfaceDestroySAXHandler(_handler)
_CFXMLInterfaceDestroyContext(_parserContext)
}
//create a parser that incrementally pulls data from the specified stream and parses it.
public init(stream: InputStream) {
_CFSetupXMLInterface()
_stream = stream
_handler = _CFXMLInterfaceCreateSAXHandler()
_parserContext = nil
}
open weak var delegate: XMLParserDelegate?
open var shouldProcessNamespaces: Bool = false
open var shouldReportNamespacePrefixes: Bool = false
//defaults to XMLNode.ExternalEntityResolvingPolicy.never
open var externalEntityResolvingPolicy: ExternalEntityResolvingPolicy = .never
open var allowedExternalEntityURLs: Set<URL>?
internal static func currentParser() -> XMLParser? {
if let current = Thread.current.threadDictionary["__CurrentNSXMLParser"] {
return current as? XMLParser
} else {
return nil
}
}
internal static func setCurrentParser(_ parser: XMLParser?) {
if let p = parser {
Thread.current.threadDictionary["__CurrentNSXMLParser"] = p
} else {
Thread.current.threadDictionary.removeValue(forKey: "__CurrentNSXMLParser")
}
}
internal func _handleParseResult(_ parseResult: Int32) -> Bool {
return true
/*
var result = true
if parseResult != 0 {
if parseResult != -1 {
// TODO: determine if this result is a fatal error from libxml via the CF implementations
}
}
return result
*/
}
internal func parseData(_ data: Data) -> Bool {
_CFXMLInterfaceSetStructuredErrorFunc(interface, _structuredErrorFunc)
let handler: _CFXMLInterfaceSAXHandler? = (delegate != nil ? _handler : nil)
let unparsedData: Data
// If the parser context is nil, we have not received enough bytes to create the push parser
if _parserContext == nil {
// Look at the bomChunk and this data
let bomChunk: Data = {
guard var bomChunk = _bomChunk else {
return data
}
bomChunk.append(data)
return bomChunk
}()
// If we have not received 4 bytes, save the bomChunk for next pass
if bomChunk.count < 4 {
_bomChunk = bomChunk
return false
}
// Prepare options (substitute entities, recover on errors)
var options = _kCFXMLInterfaceRecover | _kCFXMLInterfaceNoEnt
if shouldResolveExternalEntities {
options |= _kCFXMLInterfaceDTDLoad
}
if handler == nil {
options |= (_kCFXMLInterfaceNoError | _kCFXMLInterfaceNoWarning)
}
// Create the push context with the first 4 bytes
bomChunk.withUnsafeBytes { bytes in
_parserContext = _CFXMLInterfaceCreatePushParserCtxt(handler, interface, bytes, 4, nil)
}
_CFXMLInterfaceCtxtUseOptions(_parserContext, options)
// Prepare the remaining data for parsing
let dataRange = bomChunk.indices
let unparsed = Range(uncheckedBounds: (dataRange.startIndex.advanced(by: 4), dataRange.endIndex))
unparsedData = bomChunk.subdata(in: unparsed)
}
else {
unparsedData = data
}
let parseResult = unparsedData.withUnsafeBytes { (bytes: UnsafePointer<Int8>) -> Int32 in
return _CFXMLInterfaceParseChunk(_parserContext, bytes, Int32(unparsedData.count), 0)
}
let result = _handleParseResult(parseResult)
_CFXMLInterfaceSetStructuredErrorFunc(interface, nil)
return result
}
internal func parseFromStream() -> Bool {
var result = true
XMLParser.setCurrentParser(self)
defer { XMLParser.setCurrentParser(nil) }
if let stream = _stream {
stream.open()
defer { stream.close() }
let buffer = malloc(_chunkSize)!.bindMemory(to: UInt8.self, capacity: _chunkSize)
defer { free(buffer) }
var len = stream.read(buffer, maxLength: _chunkSize)
if len != -1 {
while len > 0 {
let data = Data(bytesNoCopy: buffer, count: len, deallocator: .none)
result = parseData(data)
len = stream.read(buffer, maxLength: _chunkSize)
}
} else {
result = false
}
} else if let data = _data {
let buffer = malloc(_chunkSize)!.bindMemory(to: UInt8.self, capacity: _chunkSize)
defer { free(buffer) }
var range = NSRange(location: 0, length: min(_chunkSize, data.count))
while result {
let chunk = data.withUnsafeBytes { (buffer: UnsafePointer<UInt8>) -> Data in
let ptr = buffer.advanced(by: range.location)
return Data(bytesNoCopy: UnsafeMutablePointer(mutating: ptr), count: range.length, deallocator: .none)
}
result = parseData(chunk)
if range.location + range.length >= data.count {
break
}
range = NSRange(location: range.location + range.length, length: min(_chunkSize, data.count - (range.location + range.length)))
}
} else {
result = false
}
return result
}
// called to start the event-driven parse. Returns YES in the event of a successful parse, and NO in case of error.
open func parse() -> Bool {
return parseFromStream()
}
// called by the delegate to stop the parse. The delegate will get an error message sent to it.
open func abortParsing() {
if let context = _parserContext {
_CFXMLInterfaceStopParser(context)
_delegateAborted = true
}
}
internal var _parserError: Error?
// can be called after a parse is over to determine parser state.
open var parserError: Error? {
return _parserError
}
//Toggles between disabling external entities entirely, and the current setting of the 'externalEntityResolvingPolicy'.
//The 'externalEntityResolvingPolicy' property should be used instead of this, unless targeting 10.9/7.0 or earlier
open var shouldResolveExternalEntities: Bool = false
// Once a parse has begun, the delegate may be interested in certain parser state. These methods will only return meaningful information during parsing, or after an error has occurred.
open var publicID: String? {
return nil
}
open var systemID: String? {
return nil
}
open var lineNumber: Int {
return Int(_CFXMLInterfaceSAX2GetLineNumber(_parserContext))
}
open var columnNumber: Int {
return Int(_CFXMLInterfaceSAX2GetColumnNumber(_parserContext))
}
internal func _pushNamespaces(_ ns: [String:String]) {
_namespaces.append(ns)
if let del = self.delegate {
ns.forEach {
del.parser(self, didStartMappingPrefix: $0.0, toURI: $0.1)
}
}
}
internal func _popNamespaces() {
let ns = _namespaces.removeLast()
if let del = self.delegate {
ns.forEach {
del.parser(self, didEndMappingPrefix: $0.0)
}
}
}
}
/*
For the discussion of event methods, assume the following XML:
<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type='text/css' href='cvslog.css'?>
<!DOCTYPE cvslog SYSTEM "cvslog.dtd">
<cvslog xmlns="http://xml.apple.com/cvslog">
<radar:radar xmlns:radar="http://xml.apple.com/radar">
<radar:bugID>2920186</radar:bugID>
<radar:title>API/NSXMLParser: there ought to be an NSXMLParser</radar:title>
</radar:radar>
</cvslog>
*/
// The parser's delegate is informed of events through the methods in the NSXMLParserDelegateEventAdditions category.
public protocol XMLParserDelegate: class {
// Document handling methods
func parserDidStartDocument(_ parser: XMLParser)
// sent when the parser begins parsing of the document.
func parserDidEndDocument(_ parser: XMLParser)
// sent when the parser has completed parsing. If this is encountered, the parse was successful.
// DTD handling methods for various declarations.
func parser(_ parser: XMLParser, foundNotationDeclarationWithName name: String, publicID: String?, systemID: String?)
func parser(_ parser: XMLParser, foundUnparsedEntityDeclarationWithName name: String, publicID: String?, systemID: String?, notationName: String?)
func parser(_ parser: XMLParser, foundAttributeDeclarationWithName attributeName: String, forElement elementName: String, type: String?, defaultValue: String?)
func parser(_ parser: XMLParser, foundElementDeclarationWithName elementName: String, model: String)
func parser(_ parser: XMLParser, foundInternalEntityDeclarationWithName name: String, value: String?)
func parser(_ parser: XMLParser, foundExternalEntityDeclarationWithName name: String, publicID: String?, systemID: String?)
func parser(_ parser: XMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String])
// sent when the parser finds an element start tag.
// In the case of the cvslog tag, the following is what the delegate receives:
// elementName == cvslog, namespaceURI == http://xml.apple.com/cvslog, qualifiedName == cvslog
// In the case of the radar tag, the following is what's passed in:
// elementName == radar, namespaceURI == http://xml.apple.com/radar, qualifiedName == radar:radar
// If namespace processing >isn't< on, the xmlns:radar="http://xml.apple.com/radar" is returned as an attribute pair, the elementName is 'radar:radar' and there is no qualifiedName.
func parser(_ parser: XMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?)
// sent when an end tag is encountered. The various parameters are supplied as above.
func parser(_ parser: XMLParser, didStartMappingPrefix prefix: String, toURI namespaceURI: String)
// sent when the parser first sees a namespace attribute.
// In the case of the cvslog tag, before the didStartElement:, you'd get one of these with prefix == @"" and namespaceURI == @"http://xml.apple.com/cvslog" (i.e. the default namespace)
// In the case of the radar:radar tag, before the didStartElement: you'd get one of these with prefix == @"radar" and namespaceURI == @"http://xml.apple.com/radar"
func parser(_ parser: XMLParser, didEndMappingPrefix prefix: String)
// sent when the namespace prefix in question goes out of scope.
func parser(_ parser: XMLParser, foundCharacters string: String)
// This returns the string of the characters encountered thus far. You may not necessarily get the longest character run. The parser reserves the right to hand these to the delegate as potentially many calls in a row to -parser:foundCharacters:
func parser(_ parser: XMLParser, foundIgnorableWhitespace whitespaceString: String)
// The parser reports ignorable whitespace in the same way as characters it's found.
func parser(_ parser: XMLParser, foundProcessingInstructionWithTarget target: String, data: String?)
// The parser reports a processing instruction to you using this method. In the case above, target == @"xml-stylesheet" and data == @"type='text/css' href='cvslog.css'"
func parser(_ parser: XMLParser, foundComment comment: String)
// A comment (Text in a <!-- --> block) is reported to the delegate as a single string
func parser(_ parser: XMLParser, foundCDATA CDATABlock: Data)
// this reports a CDATA block to the delegate as an NSData.
func parser(_ parser: XMLParser, resolveExternalEntityName name: String, systemID: String?) -> Data?
// this gives the delegate an opportunity to resolve an external entity itself and reply with the resulting data.
func parser(_ parser: XMLParser, parseErrorOccurred parseError: Error)
// ...and this reports a fatal error to the delegate. The parser will stop parsing.
func parser(_ parser: XMLParser, validationErrorOccurred validationError: Error)
}
public extension XMLParserDelegate {
func parserDidStartDocument(_ parser: XMLParser) { }
func parserDidEndDocument(_ parser: XMLParser) { }
func parser(_ parser: XMLParser, foundNotationDeclarationWithName name: String, publicID: String?, systemID: String?) { }
func parser(_ parser: XMLParser, foundUnparsedEntityDeclarationWithName name: String, publicID: String?, systemID: String?, notationName: String?) { }
func parser(_ parser: XMLParser, foundAttributeDeclarationWithName attributeName: String, forElement elementName: String, type: String?, defaultValue: String?) { }
func parser(_ parser: XMLParser, foundElementDeclarationWithName elementName: String, model: String) { }
func parser(_ parser: XMLParser, foundInternalEntityDeclarationWithName name: String, value: String?) { }
func parser(_ parser: XMLParser, foundExternalEntityDeclarationWithName name: String, publicID: String?, systemID: String?) { }
func parser(_ parser: XMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String]) { }
func parser(_ parser: XMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) { }
func parser(_ parser: XMLParser, didStartMappingPrefix prefix: String, toURI namespaceURI: String) { }
func parser(_ parser: XMLParser, didEndMappingPrefix prefix: String) { }
func parser(_ parser: XMLParser, foundCharacters string: String) { }
func parser(_ parser: XMLParser, foundIgnorableWhitespace whitespaceString: String) { }
func parser(_ parser: XMLParser, foundProcessingInstructionWithTarget target: String, data: String?) { }
func parser(_ parser: XMLParser, foundComment comment: String) { }
func parser(_ parser: XMLParser, foundCDATA CDATABlock: Data) { }
func parser(_ parser: XMLParser, resolveExternalEntityName name: String, systemID: String?) -> Data? { return nil }
func parser(_ parser: XMLParser, parseErrorOccurred parseError: Error) { }
func parser(_ parser: XMLParser, validationErrorOccurred validationError: Error) { }
}
extension XMLParser {
// If validation is on, this will report a fatal validation error to the delegate. The parser will stop parsing.
public static let errorDomain: String = "NSXMLParserErrorDomain" // for use with NSError.
// Error reporting
public enum ErrorCode : Int {
case internalError
case outOfMemoryError
case documentStartError
case emptyDocumentError
case prematureDocumentEndError
case invalidHexCharacterRefError
case invalidDecimalCharacterRefError
case invalidCharacterRefError
case invalidCharacterError
case characterRefAtEOFError
case characterRefInPrologError
case characterRefInEpilogError
case characterRefInDTDError
case entityRefAtEOFError
case entityRefInPrologError
case entityRefInEpilogError
case entityRefInDTDError
case parsedEntityRefAtEOFError
case parsedEntityRefInPrologError
case parsedEntityRefInEpilogError
case parsedEntityRefInInternalSubsetError
case entityReferenceWithoutNameError
case entityReferenceMissingSemiError
case parsedEntityRefNoNameError
case parsedEntityRefMissingSemiError
case undeclaredEntityError
case unparsedEntityError
case entityIsExternalError
case entityIsParameterError
case unknownEncodingError
case encodingNotSupportedError
case stringNotStartedError
case stringNotClosedError
case namespaceDeclarationError
case entityNotStartedError
case entityNotFinishedError
case lessThanSymbolInAttributeError
case attributeNotStartedError
case attributeNotFinishedError
case attributeHasNoValueError
case attributeRedefinedError
case literalNotStartedError
case literalNotFinishedError
case commentNotFinishedError
case processingInstructionNotStartedError
case processingInstructionNotFinishedError
case notationNotStartedError
case notationNotFinishedError
case attributeListNotStartedError
case attributeListNotFinishedError
case mixedContentDeclNotStartedError
case mixedContentDeclNotFinishedError
case elementContentDeclNotStartedError
case elementContentDeclNotFinishedError
case xmlDeclNotStartedError
case xmlDeclNotFinishedError
case conditionalSectionNotStartedError
case conditionalSectionNotFinishedError
case externalSubsetNotFinishedError
case doctypeDeclNotFinishedError
case misplacedCDATAEndStringError
case cdataNotFinishedError
case misplacedXMLDeclarationError
case spaceRequiredError
case separatorRequiredError
case nmtokenRequiredError
case nameRequiredError
case pcdataRequiredError
case uriRequiredError
case publicIdentifierRequiredError
case ltRequiredError
case gtRequiredError
case ltSlashRequiredError
case equalExpectedError
case tagNameMismatchError
case unfinishedTagError
case standaloneValueError
case invalidEncodingNameError
case commentContainsDoubleHyphenError
case invalidEncodingError
case externalStandaloneEntityError
case invalidConditionalSectionError
case entityValueRequiredError
case notWellBalancedError
case extraContentError
case invalidCharacterInEntityError
case parsedEntityRefInInternalError
case entityRefLoopError
case entityBoundaryError
case invalidURIError
case uriFragmentError
case noDTDError
case delegateAbortedParseError
}
}
|
apache-2.0
|
98da9cf726706180c92ee3d0b327126f
| 37.092708 | 345 | 0.645137 | 5.136096 | false | false | false | false |
alblue/swift-corelibs-foundation
|
Foundation/Measurement.swift
|
3
|
15156
|
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
#if DEPLOYMENT_RUNTIME_SWIFT
import CoreFoundation
#else
@_exported import Foundation // Clang module
import _SwiftCoreFoundationOverlayShims
#endif
/// A `Measurement` is a model type that holds a `Double` value associated with a `Unit`.
///
/// Measurements support a large set of operators, including `+`, `-`, `*`, `/`, and a full set of comparison operators.
@available(macOS 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *)
public struct Measurement<UnitType : Unit> : ReferenceConvertible, Comparable, Equatable {
public typealias ReferenceType = NSMeasurement
/// The unit component of the `Measurement`.
public let unit: UnitType
/// The value component of the `Measurement`.
public var value: Double
/// Create a `Measurement` given a specified value and unit.
public init(value: Double, unit: UnitType) {
self.value = value
self.unit = unit
}
public var hashValue: Int {
return Int(bitPattern: __CFHashDouble(value))
}
}
@available(macOS 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *)
extension Measurement : CustomStringConvertible, CustomDebugStringConvertible, CustomReflectable {
public var description: String {
return "\(value) \(unit.symbol)"
}
public var debugDescription: String {
return "\(value) \(unit.symbol)"
}
public var customMirror: Mirror {
var c: [(label: String?, value: Any)] = []
c.append((label: "value", value: value))
c.append((label: "unit", value: unit.symbol))
return Mirror(self, children: c, displayStyle: .struct)
}
}
/// When a `Measurement` contains a `Dimension` unit, it gains the ability to convert between the kinds of units in that dimension.
@available(macOS 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *)
extension Measurement where UnitType : Dimension {
/// Returns a new measurement created by converting to the specified unit.
///
/// - parameter otherUnit: A unit of the same `Dimension`.
/// - returns: A converted measurement.
public func converted(to otherUnit: UnitType) -> Measurement<UnitType> {
if unit.isEqual(otherUnit) {
return Measurement(value: value, unit: otherUnit)
} else {
let valueInTermsOfBase = unit.converter.baseUnitValue(fromValue: value)
if otherUnit.isEqual(type(of: unit).baseUnit()) {
return Measurement(value: valueInTermsOfBase, unit: otherUnit)
} else {
let otherValueFromTermsOfBase = otherUnit.converter.value(fromBaseUnitValue: valueInTermsOfBase)
return Measurement(value: otherValueFromTermsOfBase, unit: otherUnit)
}
}
}
/// Converts the measurement to the specified unit.
///
/// - parameter otherUnit: A unit of the same `Dimension`.
public mutating func convert(to otherUnit: UnitType) {
self = converted(to: otherUnit)
}
/// Add two measurements of the same Dimension.
///
/// If the `unit` of the `lhs` and `rhs` are `isEqual`, then this returns the result of adding the `value` of each `Measurement`. If they are not equal, then this will convert both to the base unit of the `Dimension` and return the result as a `Measurement` of that base unit.
/// - returns: The result of adding the two measurements.
public static func +(lhs: Measurement<UnitType>, rhs: Measurement<UnitType>) -> Measurement<UnitType> {
if lhs.unit.isEqual(rhs.unit) {
return Measurement(value: lhs.value + rhs.value, unit: lhs.unit)
} else {
let lhsValueInTermsOfBase = lhs.unit.converter.baseUnitValue(fromValue: lhs.value)
let rhsValueInTermsOfBase = rhs.unit.converter.baseUnitValue(fromValue: rhs.value)
return Measurement(value: lhsValueInTermsOfBase + rhsValueInTermsOfBase, unit: type(of: lhs.unit).baseUnit())
}
}
/// Subtract two measurements of the same Dimension.
///
/// If the `unit` of the `lhs` and `rhs` are `==`, then this returns the result of subtracting the `value` of each `Measurement`. If they are not equal, then this will convert both to the base unit of the `Dimension` and return the result as a `Measurement` of that base unit.
/// - returns: The result of adding the two measurements.
public static func -(lhs: Measurement<UnitType>, rhs: Measurement<UnitType>) -> Measurement<UnitType> {
if lhs.unit == rhs.unit {
return Measurement(value: lhs.value - rhs.value, unit: lhs.unit)
} else {
let lhsValueInTermsOfBase = lhs.unit.converter.baseUnitValue(fromValue: lhs.value)
let rhsValueInTermsOfBase = rhs.unit.converter.baseUnitValue(fromValue: rhs.value)
return Measurement(value: lhsValueInTermsOfBase - rhsValueInTermsOfBase, unit: type(of: lhs.unit).baseUnit())
}
}
}
@available(macOS 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *)
extension Measurement {
/// Add two measurements of the same Unit.
/// - precondition: The `unit` of `lhs` and `rhs` must be `isEqual`.
/// - returns: A measurement of value `lhs.value + rhs.value` and unit `lhs.unit`.
public static func +(lhs: Measurement<UnitType>, rhs: Measurement<UnitType>) -> Measurement<UnitType> {
if lhs.unit.isEqual(rhs.unit) {
return Measurement(value: lhs.value + rhs.value, unit: lhs.unit)
} else {
fatalError("Attempt to add measurements with non-equal units")
}
}
/// Subtract two measurements of the same Unit.
/// - precondition: The `unit` of `lhs` and `rhs` must be `isEqual`.
/// - returns: A measurement of value `lhs.value - rhs.value` and unit `lhs.unit`.
public static func -(lhs: Measurement<UnitType>, rhs: Measurement<UnitType>) -> Measurement<UnitType> {
if lhs.unit.isEqual(rhs.unit) {
return Measurement(value: lhs.value - rhs.value, unit: lhs.unit)
} else {
fatalError("Attempt to subtract measurements with non-equal units")
}
}
/// Multiply a measurement by a scalar value.
/// - returns: A measurement of value `lhs.value * rhs` with the same unit as `lhs`.
public static func *(lhs: Measurement<UnitType>, rhs: Double) -> Measurement<UnitType> {
return Measurement(value: lhs.value * rhs, unit: lhs.unit)
}
/// Multiply a scalar value by a measurement.
/// - returns: A measurement of value `lhs * rhs.value` with the same unit as `rhs`.
public static func *(lhs: Double, rhs: Measurement<UnitType>) -> Measurement<UnitType> {
return Measurement(value: lhs * rhs.value, unit: rhs.unit)
}
/// Divide a measurement by a scalar value.
/// - returns: A measurement of value `lhs.value / rhs` with the same unit as `lhs`.
public static func /(lhs: Measurement<UnitType>, rhs: Double) -> Measurement<UnitType> {
return Measurement(value: lhs.value / rhs, unit: lhs.unit)
}
/// Divide a scalar value by a measurement.
/// - returns: A measurement of value `lhs / rhs.value` with the same unit as `rhs`.
public static func /(lhs: Double, rhs: Measurement<UnitType>) -> Measurement<UnitType> {
return Measurement(value: lhs / rhs.value, unit: rhs.unit)
}
/// Compare two measurements of the same `Dimension`.
///
/// If `lhs.unit == rhs.unit`, returns `lhs.value == rhs.value`. Otherwise, converts `rhs` to the same unit as `lhs` and then compares the resulting values.
/// - returns: `true` if the measurements are equal.
public static func ==<LeftHandSideType, RightHandSideType>(_ lhs: Measurement<LeftHandSideType>, _ rhs: Measurement<RightHandSideType>) -> Bool {
if lhs.unit == rhs.unit {
return lhs.value == rhs.value
} else {
if let lhsDimensionalUnit = lhs.unit as? Dimension,
let rhsDimensionalUnit = rhs.unit as? Dimension {
if type(of: lhsDimensionalUnit).baseUnit() == type(of: rhsDimensionalUnit).baseUnit() {
let lhsValueInTermsOfBase = lhsDimensionalUnit.converter.baseUnitValue(fromValue: lhs.value)
let rhsValueInTermsOfBase = rhsDimensionalUnit.converter.baseUnitValue(fromValue: rhs.value)
return lhsValueInTermsOfBase == rhsValueInTermsOfBase
}
}
return false
}
}
/// Compare two measurements of the same `Unit`.
/// - returns: `true` if the measurements can be compared and the `lhs` is less than the `rhs` converted value.
public static func <<LeftHandSideType, RightHandSideType>(lhs: Measurement<LeftHandSideType>, rhs: Measurement<RightHandSideType>) -> Bool {
if lhs.unit == rhs.unit {
return lhs.value < rhs.value
} else {
if let lhsDimensionalUnit = lhs.unit as? Dimension,
let rhsDimensionalUnit = rhs.unit as? Dimension {
if type(of: lhsDimensionalUnit).baseUnit() == type(of: rhsDimensionalUnit).baseUnit() {
let lhsValueInTermsOfBase = lhsDimensionalUnit.converter.baseUnitValue(fromValue: lhs.value)
let rhsValueInTermsOfBase = rhsDimensionalUnit.converter.baseUnitValue(fromValue: rhs.value)
return lhsValueInTermsOfBase < rhsValueInTermsOfBase
}
}
fatalError("Attempt to compare measurements with non-equal dimensions")
}
}
}
// Implementation note: similar to NSArray, NSDictionary, etc., NSMeasurement's import as an ObjC generic type is suppressed by the importer. Eventually we will need a more general purpose mechanism to correctly import generic types.
@available(macOS 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *)
extension Measurement : _ObjectiveCBridgeable {
@_semantics("convertToObjectiveC")
public func _bridgeToObjectiveC() -> NSMeasurement {
return NSMeasurement(doubleValue: value, unit: unit)
}
public static func _forceBridgeFromObjectiveC(_ source: NSMeasurement, result: inout Measurement?) {
result = Measurement(value: source.doubleValue, unit: source.unit as! UnitType)
}
public static func _conditionallyBridgeFromObjectiveC(_ source: NSMeasurement, result: inout Measurement?) -> Bool {
if let u = source.unit as? UnitType {
result = Measurement(value: source.doubleValue, unit: u)
return true
} else {
return false
}
}
public static func _unconditionallyBridgeFromObjectiveC(_ source: NSMeasurement?) -> Measurement {
let u = source!.unit as! UnitType
return Measurement(value: source!.doubleValue, unit: u)
}
}
@available(macOS 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *)
extension NSMeasurement : _HasCustomAnyHashableRepresentation {
// Must be @nonobjc to avoid infinite recursion during bridging.
@nonobjc
public func _toCustomAnyHashable() -> AnyHashable? {
#if DEPLOYMENT_RUNTIME_SWIFT
return AnyHashable(Measurement._unconditionallyBridgeFromObjectiveC(self))
#else
return AnyHashable(self as Measurement)
#endif
}
}
// This workaround is required for the time being, because Swift doesn't support covariance for Measurement (26607639)
@available(macOS 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *)
extension MeasurementFormatter {
public func string<UnitType>(from measurement: Measurement<UnitType>) -> String {
if let result = string(for: measurement) {
return result
} else {
return ""
}
}
}
// @available(macOS 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *)
// extension Unit : Codable {
// public convenience init(from decoder: Decoder) throws {
// let container = try decoder.singleValueContainer()
// let symbol = try container.decode(String.self)
// self.init(symbol: symbol)
// }
// public func encode(to encoder: Encoder) throws {
// var container = encoder.singleValueContainer()
// try container.encode(self.symbol)
// }
// }
@available(macOS 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *)
extension Measurement : Codable {
private enum CodingKeys : Int, CodingKey {
case value
case unit
}
private enum UnitCodingKeys : Int, CodingKey {
case symbol
case converter
}
private enum LinearConverterCodingKeys : Int, CodingKey {
case coefficient
case constant
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
let value = try container.decode(Double.self, forKey: .value)
let unitContainer = try container.nestedContainer(keyedBy: UnitCodingKeys.self, forKey: .unit)
let symbol = try unitContainer.decode(String.self, forKey: .symbol)
let unit: UnitType
if UnitType.self is Dimension.Type {
let converterContainer = try unitContainer.nestedContainer(keyedBy: LinearConverterCodingKeys.self, forKey: .converter)
let coefficient = try converterContainer.decode(Double.self, forKey: .coefficient)
let constant = try converterContainer.decode(Double.self, forKey: .constant)
let unitMetaType = (UnitType.self as! Dimension.Type)
unit = (unitMetaType.init(symbol: symbol, converter: UnitConverterLinear(coefficient: coefficient, constant: constant)) as! UnitType)
} else {
unit = UnitType(symbol: symbol)
}
self.init(value: value, unit: unit)
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(self.value, forKey: .value)
var unitContainer = container.nestedContainer(keyedBy: UnitCodingKeys.self, forKey: .unit)
try unitContainer.encode(self.unit.symbol, forKey: .symbol)
if UnitType.self is Dimension.Type {
guard type(of: (self.unit as! Dimension).converter) is UnitConverterLinear.Type else {
preconditionFailure("Cannot encode a Measurement whose UnitType has a non-linear unit converter.")
}
let converter = (self.unit as! Dimension).converter as! UnitConverterLinear
var converterContainer = unitContainer.nestedContainer(keyedBy: LinearConverterCodingKeys.self, forKey: .converter)
try converterContainer.encode(converter.coefficient, forKey: .coefficient)
try converterContainer.encode(converter.constant, forKey: .constant)
}
}
}
|
apache-2.0
|
9234fae6cd6492fa0ee585d1318bc859
| 44.927273 | 280 | 0.658023 | 4.667693 | false | false | false | false |
shuoli84/RxSwift
|
RxCocoa/RxCocoa/Common/Observables/Implementations/ControlTarget.swift
|
3
|
2107
|
//
// ControlTarget.swift
// RxCocoa
//
// Created by Krunoslav Zaher on 2/21/15.
// Copyright (c) 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
import RxSwift
#if os(iOS)
import UIKit
typealias Control = UIKit.UIControl
typealias ControlEvents = UIKit.UIControlEvents
#elseif os(OSX)
import Cocoa
typealias Control = Cocoa.NSControl
#endif
// This should be only used from `MainScheduler`
class ControlTarget: RxTarget {
typealias Callback = (Control) -> Void
let selector: Selector = "eventHandler:"
unowned let control: Control
#if os(iOS)
let controlEvents: UIControlEvents
#endif
var callback: Callback?
#if os(iOS)
init(control: Control, controlEvents: UIControlEvents, callback: Callback) {
MainScheduler.ensureExecutingOnScheduler()
self.control = control
self.controlEvents = controlEvents
self.callback = callback
super.init()
control.addTarget(self, action: selector, forControlEvents: controlEvents)
let method = self.methodForSelector(selector)
if method == nil {
rxFatalError("Can't find method")
}
}
#elseif os(OSX)
init(control: Control, callback: Callback) {
MainScheduler.ensureExecutingOnScheduler()
self.control = control
self.callback = callback
super.init()
control.target = self
control.action = selector
let method = self.methodForSelector(selector)
if method == nil {
rxFatalError("Can't find method")
}
}
#endif
func eventHandler(sender: Control!) {
if let callback = self.callback {
callback(control)
}
}
override func dispose() {
super.dispose()
#if os(iOS)
self.control.removeTarget(self, action: self.selector, forControlEvents: self.controlEvents)
#elseif os(OSX)
self.control.target = nil
self.control.action = nil
#endif
self.callback = nil
}
}
|
mit
|
b63f427505adcf688c3c25834bd3ab6c
| 23.511628 | 100 | 0.622686 | 4.766968 | false | false | false | false |
nalexn/ViewInspector
|
Sources/ViewInspector/PopupPresenter.swift
|
1
|
6369
|
import SwiftUI
@available(iOS 13.0, macOS 10.15, tvOS 13.0, *)
public protocol BasePopupPresenter {
func buildPopup() throws -> Any
func dismissPopup()
func content() throws -> ViewInspector.Content
var isAlertPresenter: Bool { get }
var isActionSheetPresenter: Bool { get }
var isPopoverPresenter: Bool { get }
var isSheetPresenter: Bool { get }
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, *)
public protocol PopupPresenter: BasePopupPresenter {
associatedtype Popup
var isPresented: Binding<Bool> { get }
var popupBuilder: () -> Popup { get }
var onDismiss: (() -> Void)? { get }
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, *)
public protocol ItemPopupPresenter: BasePopupPresenter {
associatedtype Popup
associatedtype Item: Identifiable
var item: Binding<Item?> { get }
var popupBuilder: (Item) -> Popup { get }
var onDismiss: (() -> Void)? { get }
}
// MARK: - Extensions
@available(iOS 13.0, macOS 10.15, tvOS 13.0, *)
extension BasePopupPresenter {
func subject<T>(_ type: T.Type) -> String {
if isPopoverPresenter { return "Popover" }
if isSheetPresenter { return "Sheet" }
return Inspector.typeName(type: T.self)
}
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, *)
public extension PopupPresenter {
func buildPopup() throws -> Any {
guard isPresented.wrappedValue else {
throw InspectionError.viewNotFound(parent: subject(Popup.self))
}
return popupBuilder()
}
func dismissPopup() {
isPresented.wrappedValue = false
onDismiss?()
}
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, *)
public extension ItemPopupPresenter {
func buildPopup() throws -> Any {
guard let value = item.wrappedValue else {
throw InspectionError.viewNotFound(parent: subject(Popup.self))
}
return popupBuilder(value)
}
func dismissPopup() {
item.wrappedValue = nil
onDismiss?()
}
}
// MARK: - Alert
@available(iOS 13.0, macOS 10.15, tvOS 13.0, *)
public extension PopupPresenter where Popup == Alert {
var isAlertPresenter: Bool { true }
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, *)
public extension ItemPopupPresenter where Popup == Alert {
var isAlertPresenter: Bool { true }
}
// MARK: - ActionSheet
@available(iOS 13.0, tvOS 13.0, *)
@available(macOS, unavailable)
public extension PopupPresenter where Popup == ActionSheet {
var isActionSheetPresenter: Bool { true }
}
@available(iOS 13.0, tvOS 13.0, *)
@available(macOS, unavailable)
public extension ItemPopupPresenter where Popup == ActionSheet {
var isActionSheetPresenter: Bool { true }
}
// MARK: - Popover, Sheet & FullScreenCover
@available(iOS 13.0, macOS 10.15, tvOS 13.0, *)
public extension ViewModifier where Self: BasePopupPresenter {
func content() throws -> ViewInspector.Content {
let view = body(content: _ViewModifier_Content())
return try view.inspect().viewModifierContent().content
}
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, *)
public extension ViewModifier where Self: PopupPresenter {
var isPopoverPresenter: Bool {
return (try? content().standardPopoverModifier()) != nil
}
var isSheetPresenter: Bool {
return (try? content().standardSheetModifier()) != nil
}
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, *)
public extension ViewModifier where Self: ItemPopupPresenter {
var isPopoverPresenter: Bool {
return (try? content().standardPopoverModifier()) != nil
}
var isSheetPresenter: Bool {
return (try? content().standardSheetModifier()) != nil
}
}
// MARK: - Default
@available(iOS 13.0, macOS 10.15, tvOS 13.0, *)
public extension BasePopupPresenter {
var isAlertPresenter: Bool { false }
var isActionSheetPresenter: Bool { false }
var isPopoverPresenter: Bool { false }
var isSheetPresenter: Bool { false }
}
// MARK: - PopupContainer
@available(iOS 13.0, macOS 10.15, tvOS 13.0, *)
internal extension ViewType {
struct PopupContainer<Popup: KnownViewType>: CustomViewIdentityMapping {
let popup: Any
let presenter: BasePopupPresenter
var viewTypeForSearch: KnownViewType.Type { Popup.self }
}
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, *)
internal extension ViewType {
static var popupContainerTypePrefix = "ViewInspector.ViewType.PopupContainer"
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, *)
internal extension ViewType.PopupContainer {
static var typePrefix: String {
return ViewType.popupContainerTypePrefix +
"<ViewInspector.ViewType.\(Inspector.typeName(type: Popup.self))>"
}
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, *)
internal extension Content {
func popup<Popup: KnownViewType>(
parent: UnwrappedView, index: Int?,
name: String = Inspector.typeName(type: Popup.self),
modifierPredicate: ModifierLookupClosure,
standardPredicate: (String) throws -> Any
) throws -> InspectableView<Popup> {
guard let popupPresenter = try? self.modifierAttribute(
modifierLookup: modifierPredicate, path: "modifier",
type: BasePopupPresenter.self, call: "", index: index ?? 0)
else {
_ = try standardPredicate(name)
throw InspectionError.notSupported(
"""
Please refer to the Guide for inspecting the \(name): \
https://github.com/nalexn/ViewInspector/blob/master/guide_popups.md#\(name.lowercased())
""")
}
let popup: Any = try {
do {
return try popupPresenter.buildPopup()
} catch {
if case InspectionError.viewNotFound = error {
throw InspectionError.viewNotFound(parent: name)
}
throw error
}
}()
let container = ViewType.PopupContainer<Popup>(popup: popup, presenter: popupPresenter)
let medium = self.medium.resettingViewModifiers()
let content = Content(container, medium: medium)
let call = ViewType.inspectionCall(
base: Popup.inspectionCall(typeName: name), index: index)
return try .init(content, parent: parent, call: call, index: index)
}
}
|
mit
|
d9de314b9e395f8c34ab566fa5fb188c
| 31.166667 | 104 | 0.651751 | 4.138402 | false | false | false | false |
YauheniYarotski/APOD
|
APOD/ApodVCRowAdapter.swift
|
1
|
2450
|
//
// ApodVCRowAdapter.swift
// APOD
//
// Created by Yauheni Yarotski on 10/22/16.
// Copyright © 2016 Yauheni_Yarotski. All rights reserved.
//
import UIKit
class ApodVCRowAdapter: NSObject {
struct Settings {
static let kAmountOfFakeAddedRowsToCreateInfiniteSroll = 4
static let kHalfOfAmountOfFakeAddedRowsToCreateInfiniteSroll = Settings.kAmountOfFakeAddedRowsToCreateInfiniteSroll/2
}
static let apodManager = ApodManager.sharedInstance
static func apodDateForRow(_ row: Int) -> Date {
let date = CalendarManager.sharedInstance.nasaCalendar.date(byAdding: .day, value: -row, to: apodManager.lastApodDate())!
return date
}
static func apodDateForCollectionRow(_ row: Int) -> Date {
let apodRow = convertCollectionViewRowToApodRow(row)
let date = CalendarManager.sharedInstance.nasaCalendar.date(byAdding: .day, value: -apodRow, to: apodManager.lastApodDate())!
return date
}
static func apodRowForDate(_ date: Date) -> Int {
let difference = CalendarManager.sharedInstance.nasaCalendar.dateComponents([.day], from: date, to: apodManager.lastApodDate())
return difference.day!
}
static func collectionViewRowForDate(_ date: Date) -> Int {
let difference = CalendarManager.sharedInstance.nasaCalendar.dateComponents([.day], from: date, to: apodManager.lastApodDate())
let apodRow = difference.day
let collectionViewRow = convertApodRowToCollectionViewRow(apodRow!)
return collectionViewRow
}
static func convertCollectionViewRowToApodRow(_ row: NSInteger) -> NSInteger {
var newRow = row
let amountOfItems = apodManager.totalAmountOfApods()
let amountOfFakeRows = Settings.kHalfOfAmountOfFakeAddedRowsToCreateInfiniteSroll
if row < amountOfFakeRows {
newRow = row + (amountOfItems - amountOfFakeRows)
} else if row >= amountOfFakeRows && row < amountOfItems + amountOfFakeRows {
newRow = row - amountOfFakeRows
} else if row >= amountOfItems + amountOfFakeRows {
newRow = row - (amountOfItems + amountOfFakeRows)
}
return newRow
}
static func convertApodRowToCollectionViewRow(_ apodRow: NSInteger) -> NSInteger {
let newRow = apodRow + Settings.kHalfOfAmountOfFakeAddedRowsToCreateInfiniteSroll
return newRow
}
}
|
mit
|
052296f7a773a6e26670358482062790
| 38.5 | 135 | 0.692528 | 4.06136 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.