repo_name
stringlengths 6
91
| ref
stringlengths 12
59
| path
stringlengths 7
936
| license
stringclasses 15
values | copies
stringlengths 1
3
| content
stringlengths 61
714k
| hash
stringlengths 32
32
| line_mean
float64 4.88
60.8
| line_max
int64 12
421
| alpha_frac
float64 0.1
0.92
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
mgadda/typed-operation | refs/heads/master | Sources/Try.swift | apache-2.0 | 1 | //
// Try.swift
// TypedOperation
//
// Created by Matthew Gadda on 5/23/16.
// Copyright © 2016 Matt Gadda. All rights reserved.
//
import Foundation
/// `Try<A>` represents a _synchronous_ computation that may succeed or fail.
public enum Try<A> {
case `return`(A)
case `throw`(Error)
/// Creates a new Try with type parameter `A` equal that of the return value of `f`.
/// `f` is immediately invoked and either resolves to its return value: `Throw(A)`
/// or resolves to an error: `Throw(ErrorType)`.
public init(f: () throws -> A) {
do {
self = Try.`return`(try f())
} catch {
self = Try.`throw`(error)
}
}
/// Invoke `f` with underlying value of type `A` if and only if target has
/// resovled to `Return(A)`. The return value of `f` becomes a new instance of
/// `Try<B>`.
/// If target resolved to `Throw(ErrorType)`, `f` is not invoked and the
/// is error is propogated into the returned `Try<B>` instance.
public func map<B>(_ f: (A) throws -> B) -> Try<B> {
switch self {
case let .return(a):
do {
let b = try f(a)
return .return(b)
} catch {
let fail: Try<B> = .throw(error)
return fail
}
case let .throw(error):
return .throw(error)
}
}
/// Invoke `f` with underlying value of type `A` if and only if target has
/// resovled to `Return(A)`. The return value of `f` is returned from `flatMap`.
/// If target resolved to `Throw(ErrorType)`, `f` is not invoked and the
/// is error is propogated into the returned `Try<B>` instance.
public func flatMap<B>(_ f: (A) throws -> Try<B>) -> Try<B> {
switch self {
case let .return(a):
do {
return try f(a)
} catch {
let fail: Try<B> = .throw(error)
return fail
}
case let .throw(error):
return .throw(error)
}
}
/// Invoke `f` with the underlying error if target resolved to `Throw`.
/// Use this method to recover from a failed computation.
public func handle(_ f: @escaping (Error) -> A) -> Try<A> {
// TODO: return Try<B> where B >: A
switch self {
case .return(_):
return self
case let .throw(error):
return Try { f(error) }
}
}
/// Invoke `f` with the underlying error if target resolved to `Throw`.
/// Use this method to recover from a failed computation.
public func rescue(_ f: (Error) -> Try<A>) -> Try<A> {
// TODO: return Try<B> where B >: A
switch self {
case .return(_):
return self
case let .throw(error):
return f(error)
}
}
/// Invoke `f` with the underlying result if target resolved to `Return`.
/// Use this method for side-effects.
public func onSuccess(_ f: (A) -> ()) -> Try<A> {
switch self {
case let .return(a):
f(a)
case .throw(_):
break
}
return self
}
/// Invoke `f` with the underlying result if target resolved to `Return`.
/// Use this method for side-effects.
public func onFailure(_ f: (Error) -> ()) -> Try<A> {
switch self {
case .return(_): break
case let .throw(error):
f(error)
}
return self
}
/// Force target to return the underlying value if target resolved to `Return`.
/// If target resolved to an error, `get()` rethrows this error.
public func get() throws -> A {
switch self {
case let .return(a):
return a
case let .throw(error):
throw error
}
}
/// Convert target into an `Optional<A>`. If target resolved to `Throw`
/// return `some(underlying)`, otherwise return `some`.
public func liftToOption() -> A? {
switch self {
case let .return(a):
return .some(a)
default:
return .none
}
}
}
/// If `lhs` and `rhs` _both_ resolve to `Return` _and_
/// their underlying values are equal. Otherwise, `lhs` and `rhs` are not
/// considered equal.
/// Because `ErrorType` does not conform to `Equatable`, it is not possible to
/// equate two failed `Try` instances.
public func ==<A: Equatable>(lhs: Try<A>, rhs: Try<A>) -> Bool {
switch (lhs, rhs) {
case let (.return(left), .return(right)):
return left == right
default:
return false
}
}
public func !=<A: Equatable>(lhs: Try<A>, rhs: Try<A>) -> Bool {
return !(lhs == rhs)
}
| cbd09daab7f3cb3a46b262140efbd6c9 | 27.190789 | 86 | 0.595333 | false | false | false | false |
qvacua/vimr | refs/heads/master | Commons/Sources/Commons/FoundationCommons.swift | mit | 1 | /**
* Tae Won Ha - http://taewon.de - @hataewon
* See LICENSE
*/
import Foundation
import os
public extension Array where Element: Hashable {
// From https://stackoverflow.com/a/46354989
func uniqued() -> [Element] {
var seen = Set<Element>()
return self.filter { seen.insert($0).inserted }
}
}
public extension Array {
func data() -> Data { self.withUnsafeBufferPointer(Data.init) }
}
public extension RandomAccessCollection where Index == Int {
func parallelMap<T>(chunkSize: Int = 1, _ transform: @escaping (Element) -> T) -> [T] {
let count = self.count
guard count > chunkSize else { return self.map(transform) }
var result = [T?](repeating: nil, count: count)
// If we don't use Array.withUnsafeMutableBufferPointer,
// then we get crashes.
result.withUnsafeMutableBufferPointer { pointer in
if chunkSize == 1 {
DispatchQueue.concurrentPerform(iterations: count) { i in pointer[i] = transform(self[i]) }
} else {
let chunkCount = Int(ceil(Double(self.count) / Double(chunkSize)))
DispatchQueue.concurrentPerform(iterations: chunkCount) { chunkIndex in
let start = Swift.min(chunkIndex * chunkSize, count)
let end = Swift.min(start + chunkSize, count)
(start..<end).forEach { i in pointer[i] = transform(self[i]) }
}
}
}
return result.map { $0! }
}
func groupedRanges<T: Equatable>(with marker: (Element) -> T) -> [ClosedRange<Index>] {
if self.isEmpty { return [] }
if self.count == 1 { return [self.startIndex...self.startIndex] }
var result = [ClosedRange<Index>]()
result.reserveCapacity(self.count / 2)
let inclusiveEndIndex = self.endIndex - 1
var lastStartIndex = self.startIndex
var lastEndIndex = self.startIndex
var lastMarker = marker(self.first!) // self is not empty!
for i in self.startIndex..<self.endIndex {
let currentMarker = marker(self[i])
if lastMarker == currentMarker {
if i == inclusiveEndIndex { result.append(lastStartIndex...i) }
} else {
result.append(lastStartIndex...lastEndIndex)
lastMarker = currentMarker
lastStartIndex = i
if i == inclusiveEndIndex { result.append(i...i) }
}
lastEndIndex = i
}
return result
}
}
public extension NSRange {
static let notFound = NSRange(location: NSNotFound, length: 0)
var inclusiveEndIndex: Int { self.location + self.length - 1 }
}
public extension URL {
func isParent(of url: URL) -> Bool {
guard self.isFileURL, url.isFileURL else { return false }
let myPathComps = self.pathComponents
let targetPathComps = url.pathComponents
guard targetPathComps.count == myPathComps.count + 1 else { return false }
return Array(targetPathComps[0..<myPathComps.count]) == myPathComps
}
func isAncestor(of url: URL) -> Bool {
guard self.isFileURL, url.isFileURL else { return false }
let myPathComps = self.pathComponents
let targetPathComps = url.pathComponents
guard targetPathComps.count > myPathComps.count else { return false }
return Array(targetPathComps[0..<myPathComps.count]) == myPathComps
}
func isContained(in parentUrl: URL) -> Bool {
if parentUrl == self { return false }
let pathComps = self.pathComponents
let parentPathComps = parentUrl.pathComponents
guard pathComps.count > parentPathComps.count else { return false }
guard Array(pathComps[0..<parentPathComps.endIndex]) == parentPathComps else { return false }
return true
}
var parent: URL {
if self.path == "/" { return self }
return self.deletingLastPathComponent()
}
var shellEscapedPath: String { self.path.shellEscapedPath }
var isRegularFile: Bool {
(try? self.resourceValues(forKeys: [.isRegularFileKey]))?.isRegularFile ?? false
}
var isHidden: Bool { (try? self.resourceValues(forKeys: [.isHiddenKey]))?.isHidden ?? false }
var isPackage: Bool { (try? self.resourceValues(forKeys: [.isPackageKey]))?.isPackage ?? false }
}
private let log = OSLog(subsystem: "com.qvacua.vimr.commons", category: "general")
| f2ab2af1d0aedf7a712aacb648b0826e | 29.255474 | 99 | 0.672376 | false | false | false | false |
sabbek/EasySwift | refs/heads/master | EasySwift/EasySwift/UIImage.swift | mit | 1 | //
// UIImage.swift
// EasySwift
//
// Created by Sabbe on 24/03/17.
// Copyright © 2017 sabbe.kev. All rights reserved.
//
// MIT License
//
// Copyright (c) 2017 sabbek
//
// 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
import UIKit
import QuartzCore
import CoreGraphics
import Accelerate
// MARK: - Extensions
extension UIImage
{
static var shared: NSCache<AnyObject, AnyObject>! {
struct StaticSharedCache {
static var shared: NSCache<AnyObject, AnyObject>? = NSCache()
}
return StaticSharedCache.shared!
}
public func toBase64() -> String
{
let imageData = UIImagePNGRepresentation(self)
return (imageData?.base64EncodedString())!
}
public func resizeWith(percentage: CGFloat) -> UIImage?
{
let imageView = UIImageView(
frame: CGRect(origin: .zero, size: CGSize(
width: size.width * percentage, height: size.height * percentage)))
imageView.contentMode = .scaleAspectFit
imageView.image = self
UIGraphicsBeginImageContextWithOptions(imageView.bounds.size, false, scale)
guard let context = UIGraphicsGetCurrentContext() else { return nil }
imageView.layer.render(in: context)
guard let result = UIGraphicsGetImageFromCurrentImageContext() else { return nil }
UIGraphicsEndImageContext()
return result
}
class func imageWithColor(color: UIColor, size: CGSize) -> UIImage
{
let rect: CGRect = CGRect(x: 0, y: 0, width: size.width, height: size.height)
UIGraphicsBeginImageContextWithOptions(size, false, 0)
color.setFill()
UIRectFill(rect)
let image: UIImage = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
return image
}
class func image(fromURL url: String, placeholder: UIImage, shouldCacheImage: Bool = true, closure: @escaping (_ image: UIImage?) -> ()) -> UIImage? {
if shouldCacheImage {
if let image = UIImage.shared.object(forKey: url as AnyObject) as? UIImage {
closure(nil)
return image
}
}
let session = URLSession(configuration: URLSessionConfiguration.default)
if let nsURL = URL(string: url) {
session.dataTask(with: nsURL, completionHandler: { (data, response, error) -> Void in
if (error != nil) {
DispatchQueue.main.async {
closure(nil)
}
}
if let data = data, let image = UIImage(data: data) {
if shouldCacheImage {
UIImage.shared.setObject(image, forKey: url as AnyObject)
}
DispatchQueue.main.async {
closure(image)
}
}
session.finishTasksAndInvalidate()
}).resume()
}
return placeholder
}
}
// MARK: - Images effects
extension UIImage
{
func applyLightEffect() -> UIImage? {
return applyBlur(withRadius: 30, tintColor: UIColor(white: 1.0, alpha: 0.3), saturationDeltaFactor: 1.8)
}
/**
Applies a extra light blur effect to the image
- Returns New image or nil
*/
func applyExtraLightEffect() -> UIImage? {
return applyBlur(withRadius: 20, tintColor: UIColor(white: 0.97, alpha: 0.82), saturationDeltaFactor: 1.8)
}
/**
Applies a dark blur effect to the image
- Returns New image or nil
*/
func applyDarkEffect() -> UIImage? {
return applyBlur(withRadius: 20, tintColor: UIColor(white: 0.11, alpha: 0.73), saturationDeltaFactor: 1.8)
}
/**
Applies a color tint to an image
- Parameter color: The tint color
- Returns New image or nil
*/
func applyTintEffect(tintColor: UIColor) -> UIImage? {
let effectColorAlpha: CGFloat = 0.6
var effectColor = tintColor
let componentCount = tintColor.cgColor.numberOfComponents
if componentCount == 2 {
var b: CGFloat = 0
if tintColor.getWhite(&b, alpha: nil) {
effectColor = UIColor(white: b, alpha: effectColorAlpha)
}
} else {
var red: CGFloat = 0
var green: CGFloat = 0
var blue: CGFloat = 0
if tintColor.getRed(&red, green: &green, blue: &blue, alpha: nil) {
effectColor = UIColor(red: red, green: green, blue: blue, alpha: effectColorAlpha)
}
}
return applyBlur(withRadius: 10, tintColor: effectColor, saturationDeltaFactor: -1.0)
}
/**
Applies a blur to an image based on the specified radius, tint color saturation and mask image
- Parameter blurRadius: The radius of the blur.
- Parameter tintColor: The optional tint color.
- Parameter saturationDeltaFactor: The detla for saturation.
- Parameter maskImage: The optional image for masking.
- Returns New image or nil
*/
func applyBlur(withRadius blurRadius: CGFloat, tintColor: UIColor?, saturationDeltaFactor: CGFloat, maskImage: UIImage? = nil) -> UIImage? {
guard size.width > 0 && size.height > 0 && cgImage != nil else {
return nil
}
if maskImage != nil {
guard maskImage?.cgImage != nil else {
return nil
}
}
let imageRect = CGRect(origin: CGPoint.zero, size: size)
var effectImage = self
let hasBlur = blurRadius > CGFloat(FLT_EPSILON)
let hasSaturationChange = fabs(saturationDeltaFactor - 1.0) > CGFloat(FLT_EPSILON)
if (hasBlur || hasSaturationChange) {
UIGraphicsBeginImageContextWithOptions(size, false, 0.0)
let effectInContext = UIGraphicsGetCurrentContext()
effectInContext?.scaleBy(x: 1.0, y: -1.0)
effectInContext?.translateBy(x: 0, y: -size.height)
effectInContext?.draw(cgImage!, in: imageRect)
var effectInBuffer = vImage_Buffer(
data: effectInContext?.data,
height: UInt((effectInContext?.height)!),
width: UInt((effectInContext?.width)!),
rowBytes: (effectInContext?.bytesPerRow)!)
UIGraphicsBeginImageContextWithOptions(size, false, 0.0);
let effectOutContext = UIGraphicsGetCurrentContext()
var effectOutBuffer = vImage_Buffer(
data: effectOutContext?.data,
height: UInt((effectOutContext?.height)!),
width: UInt((effectOutContext?.width)!),
rowBytes: (effectOutContext?.bytesPerRow)!)
if hasBlur {
let inputRadius = blurRadius * UIScreen.main.scale
let sqrtPi: CGFloat = CGFloat(sqrt(M_PI * 2.0))
var radius = UInt32(floor(inputRadius * 3.0 * sqrtPi / 4.0 + 0.5))
if radius % 2 != 1 {
radius += 1 // force radius to be odd so that the three box-blur methodology works.
}
let imageEdgeExtendFlags = vImage_Flags(kvImageEdgeExtend)
vImageBoxConvolve_ARGB8888(&effectInBuffer, &effectOutBuffer, nil, 0, 0, radius, radius, nil, imageEdgeExtendFlags)
vImageBoxConvolve_ARGB8888(&effectOutBuffer, &effectInBuffer, nil, 0, 0, radius, radius, nil, imageEdgeExtendFlags)
vImageBoxConvolve_ARGB8888(&effectInBuffer, &effectOutBuffer, nil, 0, 0, radius, radius, nil, imageEdgeExtendFlags)
}
var effectImageBuffersAreSwapped = false
if hasSaturationChange {
let s: CGFloat = saturationDeltaFactor
let floatingPointSaturationMatrix: [CGFloat] = [
0.0722 + 0.9278 * s, 0.0722 - 0.0722 * s, 0.0722 - 0.0722 * s, 0,
0.7152 - 0.7152 * s, 0.7152 + 0.2848 * s, 0.7152 - 0.7152 * s, 0,
0.2126 - 0.2126 * s, 0.2126 - 0.2126 * s, 0.2126 + 0.7873 * s, 0,
0, 0, 0, 1
]
let divisor: CGFloat = 256
let matrixSize = floatingPointSaturationMatrix.count
var saturationMatrix = [Int16](repeating: 0, count: matrixSize)
for i: Int in 0 ..< matrixSize {
saturationMatrix[i] = Int16(round(floatingPointSaturationMatrix[i] * divisor))
}
if hasBlur {
vImageMatrixMultiply_ARGB8888(&effectOutBuffer, &effectInBuffer, saturationMatrix, Int32(divisor), nil, nil, vImage_Flags(kvImageNoFlags))
effectImageBuffersAreSwapped = true
} else {
vImageMatrixMultiply_ARGB8888(&effectInBuffer, &effectOutBuffer, saturationMatrix, Int32(divisor), nil, nil, vImage_Flags(kvImageNoFlags))
}
}
if !effectImageBuffersAreSwapped {
effectImage = UIGraphicsGetImageFromCurrentImageContext()!
}
UIGraphicsEndImageContext()
if effectImageBuffersAreSwapped {
effectImage = UIGraphicsGetImageFromCurrentImageContext()!
}
UIGraphicsEndImageContext()
}
UIGraphicsBeginImageContextWithOptions(size, false, UIScreen.main.scale)
let outputContext = UIGraphicsGetCurrentContext()
outputContext?.scaleBy(x: 1.0, y: -1.0)
outputContext?.translateBy(x: 0, y: -size.height)
outputContext?.draw(self.cgImage!, in: imageRect)
if hasBlur {
outputContext?.saveGState()
if let image = maskImage {
outputContext?.clip(to: imageRect, mask: image.cgImage!);
}
outputContext?.draw(effectImage.cgImage!, in: imageRect)
outputContext?.restoreGState()
}
if let color = tintColor {
outputContext?.saveGState()
outputContext?.setFillColor(color.cgColor)
outputContext?.fill(imageRect)
outputContext?.restoreGState()
}
let outputImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return outputImage
}
}
| d2df80d80bfb878b6bc45d617fa5790f | 38.59322 | 158 | 0.586473 | false | false | false | false |
WrightsCS/watchOS-2-Sampler | refs/heads/master | watchOS2Sampler WatchKit Extension/PickerStylesInterfaceController.swift | mit | 14 | //
// PickerStylesInterfaceController.swift
// watchOS2Sampler
//
// Created by Shuichi Tsutsumi on 2015/06/12.
// Copyright © 2015年 Shuichi Tsutsumi. All rights reserved.
//
import WatchKit
import Foundation
class PickerStylesInterfaceController: WKInterfaceController {
@IBOutlet weak var listPicker: WKInterfacePicker!
@IBOutlet weak var stackPicker: WKInterfacePicker!
@IBOutlet weak var sequencePicker: WKInterfacePicker!
var pickerItems: [WKPickerItem]! = []
override func awakeWithContext(context: AnyObject?) {
super.awakeWithContext(context)
for (var i=1; i<=10; i++) {
let pickerItem = WKPickerItem()
let imageName = "m\(i)"
let image = WKImage(imageName: imageName)
// Text to show when the item is being displayed in a picker with the 'List' style.
pickerItem.title = imageName
// Caption to show for the item when focus style includes a caption callout.
pickerItem.caption = imageName
// An accessory image to show next to the title in a picker with the 'List' style.
// Note that the image will be scaled and centered to fit within an 13×13pt rect.
pickerItem.accessoryImage = image
// A custom image to show for the item, used instead of the title + accessory
// image when more flexibility is needed, or when displaying in the stack or
// sequence style. The image will be scaled and centered to fit within the
// picker's bounds or item row bounds.
pickerItem.contentImage = image
pickerItems.append(pickerItem)
// print("\(pickerItems)")
}
}
override func willActivate() {
// This method is called when watch view controller is about to be visible to user
super.willActivate()
listPicker.setItems(pickerItems)
sequencePicker.setItems(pickerItems)
stackPicker.setItems(pickerItems)
}
override func didDeactivate() {
// This method is called when watch view controller is no longer visible
super.didDeactivate()
}
}
| 36cbc770616a0c7e345612cdd0c528fd | 33.784615 | 95 | 0.631579 | false | false | false | false |
PopcornTimeTV/PopcornTimeTV | refs/heads/master | PopcornTime/Startup/AppDelegate.swift | gpl-3.0 | 1 |
import UIKit
import PopcornKit
import Reachability
import ObjectMapper
#if os(iOS)
import AlamofireNetworkActivityIndicator
import GoogleCast
#endif
#if os(tvOS)
import TVServices
#endif
public let vlcSettingTextEncoding = "subsdec-encoding"
struct ColorPallete {
let primary: UIColor
let secondary: UIColor
let tertiary: UIColor
private init(primary: UIColor, secondary: UIColor, tertiary: UIColor) {
self.primary = primary
self.secondary = secondary
self.tertiary = tertiary
}
static let light = ColorPallete(primary: .white, secondary: UIColor.white.withAlphaComponent(0.667), tertiary: UIColor.white.withAlphaComponent(0.333))
static let dark = ColorPallete(primary: .black, secondary: UIColor.black.withAlphaComponent(0.667), tertiary: UIColor.black.withAlphaComponent(0.333))
}
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UITabBarControllerDelegate {
static var shared: AppDelegate = UIApplication.shared.delegate as! AppDelegate
var window: UIWindow?
var reachability: Reachability = .forInternetConnection()
var tabBarController: UITabBarController {
return window?.rootViewController as! UITabBarController
}
var activeRootViewController: MainViewController? {
guard
let navigationController = tabBarController.selectedViewController as? UINavigationController,
let main = navigationController.viewControllers.compactMap({$0 as? MainViewController}).first
else {
return nil
}
return main
}
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
#if os(tvOS)
if let url = launchOptions?[.url] as? URL {
return self.application(.shared, open: url)
}
NotificationCenter.default.post(name: NSNotification.Name.TVTopShelfItemsDidChange, object: nil)
let font = UIFont.systemFont(ofSize: 38, weight: UIFont.Weight.heavy)
UITabBarItem.appearance().setTitleTextAttributes([NSAttributedString.Key.font: font], for: .normal)
#elseif os(iOS)
NetworkActivityIndicatorManager.shared.isEnabled = true
// SDK throws error if shared instance has already been initialised and doesn't mark function as throwing on Swift. Although this produces a compile time warning, it is necessary for the app to not crash while running on an actual device and should not be removed.
GCKCastContext.setSharedInstanceWith(GCKCastOptions(discoveryCriteria: GCKDiscoveryCriteria(applicationID: kGCKDefaultMediaReceiverApplicationID)))
tabBarController.delegate = self
#endif
if !UserDefaults.standard.bool(forKey: "tosAccepted") {
let vc = UIStoryboard.main.instantiateViewController(withIdentifier: "TermsOfServiceNavigationController")
window?.makeKeyAndVisible()
UserDefaults.standard.set(0.75, forKey: "themeSongVolume")
OperationQueue.main.addOperation {
self.activeRootViewController?.present(vc, animated: false) {
self.activeRootViewController?.environmentsToFocus = [self.tabBarController.tabBar]
}
}
}
reachability.startNotifier()
window?.tintColor = .app
TraktManager.shared.syncUserData()
awakeObjects()
return true
}
func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
if tabBarController.selectedViewController == viewController, let scrollView = viewController.view.recursiveSubviews.compactMap({$0 as? UIScrollView}).first {
let offset = CGPoint(x: 0, y: -scrollView.contentInset.top)
scrollView.setContentOffset(offset, animated: true)
}
return true
}
func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {
#if os(tvOS)
if url.scheme == "PopcornTime" {
guard
let actions = url.absoluteString.removingPercentEncoding?.components(separatedBy: "PopcornTime:?action=").last?.components(separatedBy: "»"),
let type = actions.first, let json = actions.last
else {
return false
}
let media: Media = type == "showMovie" ? Mapper<Movie>().map(JSONString: json)! : Mapper<Show>().map(JSONString: json)!
if let vc = activeRootViewController {
let storyboard = UIStoryboard.main
let loadingViewController = storyboard.instantiateViewController(withIdentifier: "LoadingViewController")
let segue = AutoPlayStoryboardSegue(identifier: type, source: vc, destination: loadingViewController)
vc.prepare(for: segue, sender: media)
tabBarController.tabBar.isHidden = true
vc.navigationController?.push(loadingViewController, animated: true)
}
}
#elseif os(iOS)
if let sourceApplication = options[UIApplication.OpenURLOptionsKey.sourceApplication] as? String, (sourceApplication == "com.apple.SafariViewService" || sourceApplication == "com.apple.mobilesafari") && url.scheme == "popcorntime" {
TraktManager.shared.authenticate(url)
} else if url.scheme == "magnet" || url.isFileURL {
let torrentUrl: String
let id: String
if url.scheme == "magnet" {
torrentUrl = url.absoluteString
id = torrentUrl
} else {
torrentUrl = url.path
id = url.lastPathComponent
}
let torrent = Torrent(url: torrentUrl)
let media: Media = Movie(id: id, torrents: [torrent]) // Type here is arbitrary.
play(media, torrent: torrent)
}
#endif
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
UpdateManager.shared.checkVersion(.daily)
}
func awakeObjects() {
let typeCount = Int(objc_getClassList(nil, 0))
let types = UnsafeMutablePointer<AnyClass?>.allocate(capacity: typeCount)
let autoreleasingTypes = AutoreleasingUnsafeMutablePointer<AnyObject.Type>(types)
objc_getClassList(autoreleasingTypes, Int32(typeCount))
for index in 0 ..< typeCount { (types[index] as? Object.Type)?.awake() }
types.deallocate()
}
}
| 59f0c5bc9181283bb0397ea28d361f1a | 46.122905 | 285 | 0.652638 | false | false | false | false |
SaberVicky/LoveStory | refs/heads/master | LoveStory/Feature/Publish/LSVideoPlayerViewController.swift | mit | 1 | //
// LSVideoPlayerViewController.swift
// LoveStory
//
// Created by songlong on 2017/1/12.
// Copyright © 2017年 com.Saber. All rights reserved.
//
import UIKit
import AVFoundation
class LSVideoPlayerViewController: UIViewController {
var playerItem:AVPlayerItem!
var avplayer:AVPlayer!
var playerLayer:AVPlayerLayer!
var videoUrl: String!
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .white
let playerView = ZZPlayerView(frame: UIScreen.main.bounds)
view.addSubview(playerView)
// Do any additional setup after loading the view.
let url = URL(string: videoUrl)
playerItem = AVPlayerItem(url: url!)
avplayer = AVPlayer(playerItem: playerItem)
playerLayer = AVPlayerLayer(player: avplayer)
playerLayer.videoGravity = AVLayerVideoGravityResizeAspect
playerLayer.contentsScale = UIScreen.main.scale
playerView.playerLayer = playerLayer
playerView.layer.insertSublayer(playerLayer, at: 0)
avplayer.play()
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
dismiss(animated: true, completion: nil)
}
}
class ZZPlayerView: UIView {
var playerLayer:AVPlayerLayer?
override func layoutSubviews() {
super.layoutSubviews()
playerLayer?.frame = bounds
}
}
| be79bf8fd26671eb71f5a568d7be4fb1 | 26.538462 | 79 | 0.668994 | false | false | false | false |
Geor9eLau/WorkHelper | refs/heads/master | WorkoutHelper/MotionViewController.swift | mit | 1 | //
// MotionViewController.swift
// WorkoutHelper
//
// Created by George on 2016/12/26.
// Copyright © 2016年 George. All rights reserved.
//
import UIKit
import Toaster
class MotionViewController: BaseViewController, UINavigationControllerDelegate,CustomChooseViewDelegate, TimerDelegate, InfoRecordViewDelegate{
public var isTimerEnabled: Bool {
return (self.motionBtn.isSelected)
}
public var part: BodyPart
private var chosenMotion: PartMotion? {
didSet{
if let training = DataManager.sharedInstance.getTrainingRecord(motion: chosenMotion! , trainingDate: Date()){
self.recordTable.addRecords(motions: training.motions)
currentGroupNo = training.numberOfGroup + 1
}
}
}
private var motionTitleLbl: UILabel = {
let lbl = UILabel(frame: CGRect(x: 0, y: 69, width: SCREEN_WIDTH, height: 30))
lbl.textAlignment = .center
lbl.text = "Motion"
lbl.textColor = UIColor.black
lbl.font = UIFont.systemFont(ofSize: 26)
return lbl
}()
private lazy var motionBtn: UIButton = {
let btn = UIButton(frame: CGRect(x: (SCREEN_WIDTH - 200) / 2, y: 104, width: 200, height: 40))
btn.setTitle("Choose a motion", for: .normal)
btn.setTitle("Unset", for: .selected)
btn.setTitleColor(UIColor.gray, for: .normal)
btn.setTitleColor(UIColor.blue, for: .selected)
btn.addTarget(self, action: #selector(motionBtnDidClicked), for: .touchUpInside)
return btn
}()
private let recordTitleLbl: UILabel = {
let lbl = UILabel(frame: CGRect(x: 0, y: 160, width: SCREEN_WIDTH, height: 30))
lbl.textAlignment = .center
lbl.text = "Record"
lbl.textColor = UIColor.black
lbl.font = UIFont.systemFont(ofSize: 20)
return lbl
}()
private let recordTable = RecordTable(frame: CGRect(x: 50, y: 190, width: SCREEN_WIDTH - 100, height: 220 * RatioX_47))
private lazy var chooseView: CustomChooseView = {
let tmp = CustomChooseView(self.view.bounds, part:self.part)
tmp.delegate = self
return tmp
}()
private lazy var timerScreen: Timer = {
let tmp = Timer(frame: CGRect(x: (SCREEN_WIDTH - 165) / 2, y: SCREEN_HEIGHT - 250, width: 165, height: 210))
tmp.delegate = self
return tmp
}()
private lazy var infoRecordView: InfoRecordView = {
let tmp = InfoRecordView(frame: UIScreen.main.bounds)
tmp.delegate = self
return tmp
}()
private var tmpTimeConsuming: UInt = 0
private var currentGroupNo: UInt = 1
// private var tmpMotion: Motion?
private var training: Training?
// MARK: - Life cycle
override func viewDidLoad() {
super.viewDidLoad()
title = self.part.rawValue
self.setupUI()
}
// MARK: - Initialize
init(part: BodyPart) {
self.part = part
super.init(nibName: nil, bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - Override
// MARK: - Private
func setupUI() {
view.addSubview(motionTitleLbl)
view.addSubview(motionBtn)
view.addSubview(recordTitleLbl)
view.addSubview(recordTable)
view.addSubview(timerScreen)
let backBtn = UIBarButtonItem.init(title: "<", style: .plain, target: self, action: #selector(backBtnDidClicked))
backBtn.tintColor = UIColor.black
navigationItem.leftBarButtonItem = backBtn
}
// MARK: - Event handler
@objc func backBtnDidClicked() {
_ = SweetAlert().showAlert("Message", subTitle: "Do you finish the training?", style: .warning, buttonTitle: "Yes", buttonColor: UIColor.green, otherButtonTitle: "No") { (isOtherBtn) in
if isOtherBtn{
if let training = self.training{
DataManager.sharedInstance.updateRecord(training: training)
}
_ = self.navigationController?.popViewController(animated: true)
}else{
}
}
}
func motionBtnDidClicked() {
UIApplication.shared.keyWindow?.addSubview(self.chooseView)
}
// MARK: - ChooseViewDelegate
func choose(item: Any) {
if let motion = item as? PartMotion{
if let training = self.training{
DataManager.sharedInstance.updateRecord(training: training)
}
training = nil
currentGroupNo = 1
tmpTimeConsuming = 0
self.chosenMotion = motion
motionBtn.isSelected = true
motionBtn.setTitleColor(UIColor.red, for: .selected)
motionBtn.setTitle(motion.motionName, for: .selected)
}
}
// MARK: - TimerDelegate
func timerDidBegan() {
self.motionBtn.isUserInteractionEnabled = false
}
func timerDidFinished(timeConsuming: String) {
let timeArr = timeConsuming.components(separatedBy: ":")
let min:UInt = UInt(timeArr.first!)!
let sec:UInt = UInt(timeArr[1])!
self.tmpTimeConsuming = 60 * min + sec
self.infoRecordView.show()
}
func showFailureToast() {
guard motionBtn.title(for: .selected) != "Unset" else {
let toast = Toast(text: "Please choose a motion", delay: 0.1, duration: 0.5)
toast.show()
return
}
}
// MARK: - InfoRecordViewDelegate
func recordDidFinished(weight: Double, repeats: Int) {
currentGroupNo = currentGroupNo + 1
let motion = Motion.init(motionId:"\(self.chosenMotion!.motionName) \(Util.transformDateToDateStr(date: Date()))-\(currentGroupNo)", weight: weight, repeats: UInt(repeats), timeConsuming: self.tmpTimeConsuming, motionType: self.chosenMotion!)
DataManager.sharedInstance.addMotionRecord(motion: motion)
if self.training == nil {
self.training = Training.init(motionType: self.chosenMotion!, trainingId: "\(self.chosenMotion!.motionName) \(Util.transformDateToDateStr(date: Date()))")
self.training?.date = motion.date
}
self.training?.addMotion(motion: motion)
self.recordTable.addRecord(motion: motion)
self.motionBtn.isUserInteractionEnabled = true
}
}
| 1372b6de5e25dc10ac6cc0db0a5ebc41 | 33.256545 | 250 | 0.61241 | false | false | false | false |
Masteryyz/CSYMicroBlockSina | refs/heads/master | CSYMicroBlockSina/CSYMicroBlockSina/Classes/Module/OAuth_2.0/LoginViewWithOAUTHViewController.swift | mit | 1 | //
// LoginViewWithOAUTHViewController.swift
// CSYMicroBlockSina
//
// Created by 姚彦兆 on 15/11/9.
// Copyright © 2015年 姚彦兆. All rights reserved.
//
import UIKit
import SVProgressHUD
import AFNetworking
class LoginViewWithOAUTHViewController: UIViewController {
let webView : UIWebView = UIWebView()
override func loadView() {
view = webView
webView.delegate = self
}
override func viewDidLoad() {
super.viewDidLoad()
setUpUI()
loadWebRequest()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
extension LoginViewWithOAUTHViewController{
private func loadWebRequest(){
let urlStr = "https://api.weibo.com/oauth2/authorize?" + "client_id=" + client_id + "&redirect_uri=" + redirect_uri
let request = NSURLRequest(URL: NSURL(string: urlStr)!)
webView.loadRequest(request)
}
}
// MARK: - 界面的设置
extension LoginViewWithOAUTHViewController{
private func setUpUI () {
//print("setUpUI")
self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: UIBarButtonItemStyle.Plain, target: self, action: "closeWebView")
self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动获取", style: UIBarButtonItemStyle.Plain, target: self, action: "autoInput")
}
@objc private func autoInput(){
let js = "document.getElementById('userId').value = '18636706784';" + "document.getElementById('passwd').value = '15343577589Yyz';"
webView.stringByEvaluatingJavaScriptFromString(js)
}
func closeWebView (){
dismissViewControllerAnimated(true) { () -> Void in
//print("Complete")
}
}
}
// MARK: - 代理获得请求的URL
extension LoginViewWithOAUTHViewController : UIWebViewDelegate{
func webViewDidStartLoad(webView: UIWebView) {
//开始载入的时候调用
SVProgressHUD.showWithStatus("请求授权中", maskType: SVProgressHUDMaskType.Black)
}
func webViewDidFinishLoad(webView: UIWebView) {
//结束载入的时候调用
SVProgressHUD.dismiss()
}
func webView(webView: UIWebView, didFailLoadWithError error: NSError?) {
//载入出错的时候调用
//print("----------->\(error)")
}
/*抓取到了网络请求
<NSMutableURLRequest: 0x7fde51e11180> { URL: https://api.weibo.com/oauth2/authorize?client_id=641602405&redirect_uri=http://neihanshequ.com }
LoadSuccess
<NSMutableURLRequest: 0x7fde540d1560> { URL: https://api.weibo.com/oauth2/authorize }
<NSMutableURLRequest: 0x7fde51e54660> { URL: https://api.weibo.com/oauth2/authorize# }
<NSMutableURLRequest: 0x7fde51e593e0> { URL: https://api.weibo.com/oauth2/authorize }
<NSMutableURLRequest: 0x7fde51e63580> { URL: http://neihanshequ.com/?code=6fdc3dfc4cf63982fec4812d55c82e38 }
<NSMutableURLRequest: 0x7fde51ea1ef0> { URL: http://m.neihanshequ.com/ }
<NSMutableURLRequest: 0x7fde540d3cd0> { URL: http://m.neihanshequ.com/?skip_guidence=1 }
*/
func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
//监听WebView的所有网络请求
//如果网页没有获取到有用的请求信息,则拦截一切活动
guard let urlStr = request.URL?.absoluteString else{
//print(request.URL)
print("WebView闲置")
return false
}
//如果授权请求正在执行 ---> 让他继续
if urlStr.hasPrefix("https://api.weibo.com/") {
//print(request.URL)
//print("[请求授权中...]")
return true
}
//如果得到了定义好的域名请求,则代表或取到了自己的code ---> 获得数据[拦住他,不要继续了]
if !urlStr.hasPrefix(redirect_uri) {
//print("[拦截到CODE_URL]\(urlStr)")
return false
}
//程序在获得了code之后被卡住了,执行后续的操作
guard let queryStr = request.URL?.query else {
return false
}
let str = "code="
code = queryStr.substringFromIndex(str.endIndex)
print("--->获得CODE<--- [\(code)]")
//封装好的数据获取
GetUserInfoModel().getTokenWithCode(code!) { (errorMessage) -> () in
self.dismissViewControllerAnimated(true, completion: { () -> Void in
SVProgressHUD.dismiss()
NSNotificationCenter.defaultCenter().postNotificationName(APPDELEGATESHOULDSWITCHROOTVIEWCONTROLLER, object: "welCome")
})
}
return true
}
}
| 8f176d50118db601030fd7a2e16839f6 | 22.276498 | 149 | 0.578103 | false | false | false | false |
LiulietLee/Pick-Color | refs/heads/master | Pick Color/CoreDataModel.swift | mit | 1 | //
// CoreDataModel.swift
// Pick Color
//
// Created by Liuliet.Lee on 27/8/2016.
// Copyright © 2016 Liuliet.Lee. All rights reserved.
//
import UIKit
import CoreData
class CoreDataModel {
fileprivate var context = (UIApplication.shared.delegate as! AppDelegate).managedObjectContext
fileprivate func saveContext() {
do { try context.save() } catch { print("save failed") }
}
func fetchColors() -> [Colors] {
var colorItems = [Colors]()
let fetchRequest = NSFetchRequest<Colors>(entityName: "Colors")
do {
try colorItems = context.fetch(fetchRequest)
} catch {
print("fetch failed")
}
return colorItems
}
func saveNewColor(_ newColor: UIColor, title: String) -> Colors {
let entity = NSEntityDescription.entity(forEntityName: "Colors", in: context)!
let newItem = Colors(entity: entity, insertInto: context)
newItem.title = title
newItem.uiColor = newColor
saveContext()
return newItem
}
func saveEditedColor() {
saveContext()
}
func deleteColor(_ color: Colors) {
context.delete(color)
saveContext()
}
}
| c1f1669d2d3a02c4c555a647811926a8 | 24.877551 | 98 | 0.592271 | false | false | false | false |
Farteen/firefox-ios | refs/heads/master | Client/Frontend/Widgets/AutocompleteTextField.swift | mpl-2.0 | 5 | /* 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/. */
// This code is loosely based on https://github.com/Antol/APAutocompleteTextField
import UIKit
/// Delegate for the text field events. Since AutocompleteTextField owns the UITextFieldDelegate,
/// callers must use this instead.
protocol AutocompleteTextFieldDelegate: class {
func autocompleteTextField(autocompleteTextField: AutocompleteTextField, didTextChange text: String)
func autocompleteTextFieldShouldReturn(autocompleteTextField: AutocompleteTextField) -> Bool
func autocompleteTextFieldShouldClear(autocompleteTextField: AutocompleteTextField) -> Bool
func autocompleteTextFieldDidBeginEditing(autocompleteTextField: AutocompleteTextField)
}
private struct AutocompleteTextFieldUX {
static let HighlightColor = UIColor(rgb: 0xccdded)
}
class AutocompleteTextField: UITextField, UITextFieldDelegate {
var autocompleteDelegate: AutocompleteTextFieldDelegate?
private var completionActive = false
private var enteredTextLength = 0
var active = false
override init(frame: CGRect) {
super.init(frame: frame)
super.delegate = self
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
super.delegate = self
}
func highlightAll() {
if !text.isEmpty {
let attributedString = NSMutableAttributedString(string: text)
attributedString.addAttribute(NSBackgroundColorAttributeName, value: AutocompleteTextFieldUX.HighlightColor, range: NSMakeRange(0, count(text)))
attributedText = attributedString
enteredTextLength = 0
completionActive = true
}
}
private func applyCompletion() {
if completionActive {
self.attributedText = NSAttributedString(string: text)
completionActive = false
}
}
private func removeCompletion() {
if completionActive {
let enteredText = text.substringToIndex(advance(text.startIndex, enteredTextLength, text.endIndex))
// Workaround for stuck highlight bug.
if enteredTextLength == 0 {
attributedText = NSAttributedString(string: " ")
}
attributedText = NSAttributedString(string: enteredText)
completionActive = false
}
}
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
if completionActive && string.isEmpty {
// Characters are being deleted, so clear the autocompletion, but don't change the text.
removeCompletion()
return false
}
return true
}
func setAutocompleteSuggestion(suggestion: String?) {
if let suggestion = suggestion {
// Check that the length of the entered text is shorter than the length of the suggestion.
// This ensures that completionActive is true only if there are remaining characters to
// suggest (which will suppress the caret).
if suggestion.startsWith(text) && count(text) < count(suggestion) {
let endingString = suggestion.substringFromIndex(advance(suggestion.startIndex, count(self.text)))
let completedAndMarkedString = NSMutableAttributedString(string: suggestion)
completedAndMarkedString.addAttribute(NSBackgroundColorAttributeName, value: AutocompleteTextFieldUX.HighlightColor, range: NSMakeRange(enteredTextLength, count(endingString)))
attributedText = completedAndMarkedString
completionActive = true
}
}
}
func textFieldShouldBeginEditing(textField: UITextField) -> Bool {
return true
}
func textFieldDidBeginEditing(textField: UITextField) {
autocompleteDelegate?.autocompleteTextFieldDidBeginEditing(self)
}
func textFieldDidEndEditing(textField: UITextField) {
active = false
}
func textFieldShouldReturn(textField: UITextField) -> Bool {
return autocompleteDelegate?.autocompleteTextFieldShouldReturn(self) ?? true
}
func textFieldShouldClear(textField: UITextField) -> Bool {
removeCompletion()
return autocompleteDelegate?.autocompleteTextFieldShouldClear(self) ?? true
}
override func setMarkedText(markedText: String!, selectedRange: NSRange) {
// Clear the autocompletion if any provisionally inserted text has been
// entered (e.g., a partial composition from a Japanese keyboard).
removeCompletion()
super.setMarkedText(markedText, selectedRange: selectedRange)
}
override func insertText(text: String) {
removeCompletion()
super.insertText(text)
enteredTextLength = count(self.text)
autocompleteDelegate?.autocompleteTextField(self, didTextChange: self.text)
}
override func caretRectForPosition(position: UITextPosition!) -> CGRect {
return completionActive ? CGRectZero : super.caretRectForPosition(position)
}
override func resignFirstResponder() -> Bool {
applyCompletion()
return super.resignFirstResponder()
}
override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
if !completionActive {
super.touchesBegan(touches, withEvent: event)
}
}
override func touchesMoved(touches: Set<NSObject>, withEvent event: UIEvent) {
if !completionActive {
super.touchesMoved(touches, withEvent: event)
}
}
override func touchesEnded(touches: Set<NSObject>, withEvent event: UIEvent) {
if !active || !completionActive {
super.touchesEnded(touches, withEvent: event)
} else {
applyCompletion()
// Set the current position to the end of the text.
selectedTextRange = textRangeFromPosition(endOfDocument, toPosition: endOfDocument)
}
active = self.isFirstResponder()
}
}
| f61792c2460c9060aae0e718db06ca66 | 36.715152 | 192 | 0.687932 | false | false | false | false |
kildevaeld/FALocationManager | refs/heads/master | Pod/Classes/Cache.swift | mit | 1 | //
// Cache.swift
// Pods
//
// Created by Rasmus Kildevæld on 25/06/15.
//
//
import Foundation
import MapKit
class CacheItem : Equatable {
var address: Address
var key: String
init(address: Address) {
self.address = address
self.key = "\(address.city.name), \(address.country.name)"
}
init(key: String, address: Address) {
self.address = address
self.key = key
}
func check(location:CLLocation) -> Bool {
return self.address.location.compare(location, precision: 100)
}
func check(key: String) -> Bool {
if self.key == key {
return true
}
return false
}
}
func ==(lhs:CacheItem, rhs: CacheItem) -> Bool {
return lhs.address.location == rhs.address.location
}
class AddressCache {
var store: [CacheItem] = []
var storePath : String {
return NSTemporaryDirectory().stringByAppendingPathComponent("address_cache.lm")
}
init () {
self.load()
}
func set (address: Address) {
let item = CacheItem(address: address)
if contains(self.store, item) {
return
}
self.store.append(item)
}
func set (key: String, address: Address) {
var addr = self.get(key)
if addr == nil {
var item = CacheItem(key: key, address: address)
self.store.append(item)
}
}
func get (location: CLLocation) -> Address? {
return self.get(location, precision: 20)
}
func get (location: CLLocation, precision: CLLocationDistance) -> Address? {
for item in self.store {
if item.check(location) {
return item.address
}
}
return nil
}
func get(key: String) -> Address? {
for item in self.store {
if item.check(key) {
return item.address
}
}
return nil
}
func save() {
var dict = Dictionary<String,Address>()
for item in self.store {
dict[item.key] = item.address
}
NSKeyedArchiver.archiveRootObject(dict, toFile: self.storePath)
}
func load () {
if !NSFileManager.defaultManager().isReadableFileAtPath(self.storePath) {
return
}
let data: AnyObject? = NSKeyedUnarchiver.unarchiveObjectWithFile(self.storePath)
if let dict = data as? Dictionary<String, Address> {
for (key, item) in dict {
self.set(key, address: item)
}
}
}
}
| 4abbb439518e589150e2048df9852101 | 21.150794 | 88 | 0.513436 | false | false | false | false |
GhostSK/SpriteKitPractice | refs/heads/master | MagicTower/MagicTower/ShopTableView.swift | apache-2.0 | 1 | //
// ShopTableView.swift
// MagicTower
//
// Created by 胡杨林 on 2017/7/10.
// Copyright © 2017年 胡杨林. All rights reserved.
//
import UIKit
import SpriteKit
class ShopTableView: UIView,UITableViewDelegate,UITableViewDataSource {
var ShopName:String = ""
var DataArr:NSMutableArray = NSMutableArray.init()
var tableview:UITableView = UITableView.init()
class func buildView(NodeName:String, isMoneyShop:Bool)->UIView{
let view = ShopTableView.init(frame: CGRect(x: 31, y: 31, width: 352, height: 352))
view.backgroundColor = UIColor.white
//本方法用来构建实例,但是不负责添加到view,view由调用方进行添加,方法内仅实现初始化以及数据配置功能
view.tableview.delegate = view
view.tableview.dataSource = view
view.ShopName = NodeName
view.tag = 10000
view.tableview.delegate = view
view.tableview.dataSource = view
view.tableview.frame = CGRect(x: 0, y: 52, width: 352, height: 300)
view.addSubview(view.tableview)
view.isUserInteractionEnabled = true
let title = UILabel.init(frame: CGRect(x: 20, y: 5, width: 300, height: 35))
title.numberOfLines = 2
title.text = "马化腾爸爸说过,在提出问题之前,先想想自己冲够了钱么?"
title.sizeToFit()
view.addSubview(title)
return view
}
//MARK: tableview代理
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 4
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell.init()
let label = UILabel.init(frame: CGRect(x: 20, y: 20, width: 300, height: 30))
cell.contentView.addSubview(label)
cell.backgroundColor = UIColor(colorLiteralRed: 249.0/255, green: 219.0/255, blue: 222.0/255, alpha: 1.0)
switch indexPath.row {
case 0:
if self.ShopName == "Floor3Shop" {
label.text = "使用25金钱提升4点攻击力"
}else if self.ShopName == "Floor5Shop"{
label.text = "使用30经验提升5点攻击力"
}
break
case 1:
if self.ShopName == "Floor3Shop" {
label.text = "使用25金钱提升4点防御力力"
}else if self.ShopName == "Floor5Shop"{
label.text = "使用30经验提升5点防御力力"
}
break
case 2:
if self.ShopName == "Floor3Shop" {
label.text = "使用25金钱提升800血量"
}else if self.ShopName == "Floor5Shop"{
label.text = "使用100经验提升1个等级"
}
break
default:
label.text = "离开商店"
break
}
cell.selectionStyle = .none
return cell
}
func loadData(NodeName:String){
if NodeName == "Floor3Shop" {
// 3楼金钱商店 25金800血 25金4攻击 25金4防御 退出
}
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 75
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let player = Player.shareInstance()
switch indexPath.row {
case 0:
if self.ShopName == "Floor3Shop" {
if player.money >= 25 {
player.money -= 25
player.attack += 4
let view = refuseView.init(text: "攻击力提升了四点!")
self.addSubview(view)
}else{
let view = refuseView.init(text: "金钱不足")
let vc = UIApplication.shared.keyWindow?.rootViewController
vc?.view.addSubview(view)
}
}else if self.ShopName == "Floor5Shop" {
if player.experience >= 30 {
player.experience -= 30
player.attack += 5
}else{
let view = refuseView.init(text: "经验不足")
let vc = UIApplication.shared.keyWindow?.rootViewController
vc?.view.addSubview(view)
}
}
break
case 1:
if self.ShopName == "Floor3Shop" {
if player.money >= 25 {
player.money -= 25
player.defence += 4
let view = refuseView.init(text: "防御力提升了四点!")
self.addSubview(view)
}else{
let view = refuseView.init(text: "金钱不足")
let vc = UIApplication.shared.keyWindow?.rootViewController
vc?.view.addSubview(view)
}
}else if self.ShopName == "Floor5Shop" {
if player.experience >= 30 {
player.experience -= 30
player.defence += 5
}else{
let view = refuseView.init(text: "经验不足")
let vc = UIApplication.shared.keyWindow?.rootViewController
vc?.view.addSubview(view)
}
}
break
case 2:
if self.ShopName == "Floor3Shop" {
if player.money >= 25 {
player.money -= 25
player.health += 800
let view = refuseView.init(text: "血量提升了八百点!")
self.addSubview(view)
}else{
let view = refuseView.init(text: "金钱不足")
let vc = UIApplication.shared.keyWindow?.rootViewController
vc?.view.addSubview(view)
}
}else if self.ShopName == "Floor5Shop" {
if player.experience >= 100 {
player.experience -= 100
player.attack += 7
player.defence += 7
player.health += 1000
player.level += 1
}else{
let view = refuseView.init(text: "经验不足")
let vc = UIApplication.shared.keyWindow?.rootViewController
vc?.view.addSubview(view)
}
}
break
default:
// let vc = UIApplication.shared.keyWindow?.rootViewController
// let view = vc?.view.viewWithTag(10000)
// view?.removeFromSuperview()
self.removeFromSuperview()
break
}
}
override init(frame: CGRect) {
super.init(frame: frame)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| 7a0703cde156afe3b83a95d553528056 | 33.455959 | 113 | 0.511278 | false | false | false | false |
ronaldbroens/jenkinsapp | refs/heads/master | JenkinsApp/BuildsDatasource.swift | apache-2.0 | 1 | //
// BuildsDatasource.swift
// JenkinsApp
//
// Created by Ronald Broens on 16/02/15.
// Copyright (c) 2015 Ronald Broens. All rights reserved.
//
import Foundation
import UIKit
class BuildsDatasource : NSObject, UITableViewDataSource
{
var builds : Array<JenkinsBuild>
init(builds : Array<JenkinsBuild>)
{
self.builds = builds
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.builds.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell:UITableViewCell = tableView.dequeueReusableCellWithIdentifier("cell")! as UITableViewCell
var build = builds[indexPath.row]
if(cell.textLabel != nil)
{
cell.textLabel?.text = build.FullDisplayName
}
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
}
} | 5b7ab2842b00bcd25ca32831b8f7c137 | 24.317073 | 109 | 0.653809 | false | false | false | false |
tunespeak/AlamoRecord | refs/heads/master | Example/AlamoRecord/BaseTableViewCell.swift | mit | 1 | //
// BaseTableViewCell.swift
// AlamoRecord
//
// Created by Dalton Hinterscher on 7/6/17.
// Copyright © 2017 CocoaPods. All rights reserved.
//
import UIKit
class BaseTableViewCell: UITableViewCell {
class var reuseIdentifier: String {
return NSStringFromClass(self)
}
internal var tableView: UITableView {
var view = superview
while view != nil {
if let tableView = view as? UITableView {
return tableView
}
view = view?.superview
}
fatalError("tableView was not found for instance of BaseTableViewCell")
}
internal var indexPath: IndexPath {
return tableView.indexPathForRow(at: center)!
}
internal var resizableView: UIView!
required init() {
super.init(style: .default, reuseIdentifier: type(of: self).reuseIdentifier)
contentView.backgroundColor = .darkWhite
resizableView = UIView()
resizableView.backgroundColor = .white
contentView.addSubview(resizableView)
resizableView.snp.makeConstraints { (make) -> Void in
make.top.equalToSuperview().offset(10)
make.left.equalToSuperview().offset(10)
make.right.equalToSuperview().offset(-10)
make.bottom.equalToSuperview()
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
internal func autoResize(under bottomView: UIView) {
resizableView.snp.makeConstraints { (make) in
make.top.equalToSuperview().offset(10)
make.left.equalToSuperview().offset(10)
make.right.equalToSuperview().offset(-10)
make.bottom.equalTo(bottomView).offset(10)
}
}
}
| c3777ad0438cdcd0879abdaa99d90118 | 27.640625 | 84 | 0.614839 | false | false | false | false |
Authman2/Pix | refs/heads/master | Eureka-master/Source/Rows/Common/DateInlineFieldRow.swift | apache-2.0 | 5 | // DateInlineFieldRow.swift
// Eureka ( https://github.com/xmartlabs/Eureka )
//
// Copyright (c) 2016 Xmartlabs SRL ( http://xmartlabs.com )
//
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
open class DateInlineCell : Cell<Date>, CellType {
public required init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
open override func setup() {
super.setup()
accessoryType = .none
editingAccessoryType = .none
}
open override func update() {
super.update()
selectionStyle = row.isDisabled ? .none : .default
}
open override func didSelect() {
super.didSelect()
row.deselect()
}
}
open class _DateInlineFieldRow: Row<DateInlineCell>, DatePickerRowProtocol, NoValueDisplayTextConformance {
/// The minimum value for this row's UIDatePicker
open var minimumDate : Date?
/// The maximum value for this row's UIDatePicker
open var maximumDate : Date?
/// The interval between options for this row's UIDatePicker
open var minuteInterval : Int?
/// The formatter for the date picked by the user
open var dateFormatter: DateFormatter?
open var noValueDisplayText: String?
required public init(tag: String?) {
super.init(tag: tag)
dateFormatter = DateFormatter()
dateFormatter?.locale = Locale.current
displayValueFor = { [unowned self] value in
guard let val = value, let formatter = self.dateFormatter else { return nil }
return formatter.string(from: val)
}
}
}
| 5ad4774b5beefd88d5288b6e5e91e121 | 34.246914 | 107 | 0.690368 | false | false | false | false |
jnewc/Swift-FlexBox | refs/heads/master | FlexBox/FlexBox/ViewController.swift | apache-2.0 | 1 | //
// ViewController.swift
// FlexBox
//
// Created by Jack Newcombe on 06/03/2015.
// Copyright (c) 2015 jnewc. All rights reserved.
//
import UIKit
import Foundation
import FlexBoxFramework
func * (color: UIColor, mult: CGFloat) -> UIColor {
let components : UnsafePointer<CGFloat> = CGColorGetComponents(color.CGColor);
return UIColor(red: components[0] * mult, green: components[1] * mult, blue: components[2] * mult, alpha: components[3]);
}
class ViewController: UIViewController {
var iconClock : UIButton = UIButton();
var iconWeather : UIButton = UIButton();
var titleLabel : UILabel = UILabel();
var label1 : UILabel = UILabel();
var label2 : UILabel = UILabel();
var label3 : UILabel = UILabel();
var image : UIImageView = UIImageView();
var link : String = "";
override func loadView() {
let rootFrame = UIScreen.mainScreen().bounds;
self.iconClock.setImage(UIImage(named: "clock"), forState: UIControlState.Normal);
self.iconClock.frame = CGRect(x: 0, y: 0, width: 64, height: 64);
self.iconWeather.setImage(UIImage(named: "weather.png"), forState: UIControlState.Normal);
self.iconWeather.frame = CGRect(x: 0, y: 0, width: 64, height: 64);
self.titleLabel.text = "Select an option";
self.titleLabel.font = UIFont(name: "Helvetica Neue", size: 32);
self.titleLabel.textColor = UIColor.whiteColor();
self.titleLabel.sizeToFit();
self.label1.text = "";
self.label1.font = UIFont(name: "Helvetica Neue", size: 16);
self.label1.textColor = UIColor.whiteColor();
self.label2.text = "";
self.label2.font = UIFont(name: "Helvetica Neue", size: 48);
self.label2.textColor = UIColor.whiteColor();
self.label3.text = "";
self.label3.font = UIFont(name: "Helvetica Neue", size: 16);
self.label3.lineBreakMode = NSLineBreakMode.ByWordWrapping;
self.label3.textColor = UIColor.whiteColor();
let topBar = FlexBox(orient: FlexOrient.Horizontal, align: FlexAlign.Justify, crossAlign: FlexAlign.Justify, flex: 2, views:
self.iconClock, self.iconWeather
);
topBar.backgroundColor = UIColor.brownColor();
let secondBar = FlexBox(orient: FlexOrient.Horizontal, align: FlexAlign.Justify, crossAlign: FlexAlign.Justify, flex: 1, views:
self.titleLabel
);
secondBar.backgroundColor = UIColor.brownColor() * 0.8;
let contentView = FlexBox(orient: FlexOrient.Vertical, align: FlexAlign.Center, crossAlign: FlexAlign.Center, flex: 5, views:
label1,
label2,
label3
)
contentView.backgroundColor = UIColor.brownColor() * 0.6;
view = FlexBox(frame: rootFrame, orient: FlexOrient.Vertical, align: FlexAlign.Flex, crossAlign: FlexAlign.Stretch, views:
// Top bar
topBar,
secondBar,
contentView
) as UIView!;
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.iconClock.addTarget(self, action: "didTapClock:", forControlEvents: UIControlEvents.TouchUpInside)
self.iconWeather.addTarget(self, action: "didTapWeather:", forControlEvents: UIControlEvents.TouchUpInside)
let tap : UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: "didTapLink:");
self.label3.addGestureRecognizer(tap);
self.label3.userInteractionEnabled = true;
}
func didTapClock(sender: UIButton) {
NSLog("Clock");
let date = NSDate();
let timeFormat = NSDateFormatter();
timeFormat.timeStyle = NSDateFormatterStyle.ShortStyle;
let dateFormat = NSDateFormatter();
dateFormat.dateStyle = NSDateFormatterStyle.ShortStyle;
setTitleText("Clock");
setLabels(dateFormat.stringFromDate(date), text2: timeFormat.stringFromDate(date), text3: "", isLink: false);
link = "";
}
func didTapWeather(sender: UIButton) {
let url : NSURL = NSURL(string: "http://api.openweathermap.org/data/2.5/weather?q=London,uk&units=metric")!;
let data = NSData(contentsOfURL: url);
let map : NSDictionary = NSJSONSerialization.JSONObjectWithData(data!, options: nil, error: nil) as NSDictionary;
let main : NSDictionary = map.objectForKey("main") as NSDictionary;
let weather : NSDictionary = (map.objectForKey("weather") as NSArray)[0] as NSDictionary;
setTitleText("Weather");
setLabels(map["name"] as String, text2: String(format: "%.2f", (main["temp"] as NSNumber).floatValue) + "°C", text3: weather["main"] as String, isLink: false);
link = "";
}
func didTapLink(sender: UILabel) {
NSLog("Did tap link: %@", self.link);
if(link != "") {
let url : NSURL = NSURL(string: "https://reddit.com/" + self.link)!;
UIApplication.sharedApplication().openURL(url);
}
var clazz : AnyClass = NSClassFromString("UILabel");
var type : NSObject.Type = clazz as NSObject.Type;
var inst = type();
}
func setLabels(text1: String, text2: String, text3: String, isLink: Bool) {
self.label1.text = text1;
self.label2.text = text2;
self.label3.text = text3;
self.label1.sizeToFit();
self.label2.sizeToFit();
self.label3.sizeToFit();
if(isLink) {
label2.sizeToFit();
label3.textColor = UIColor.blueColor();
} else {
label3.textColor = UIColor.whiteColor();
}
}
func setTitleText(title: String) {
self.titleLabel.text = title;
self.titleLabel.sizeToFit();
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| 4ccd1fe835db827f51c9dad71dd173ae | 36.387879 | 167 | 0.618415 | false | false | false | false |
gongmingqm10/DriftBook | refs/heads/master | DriftReading/DriftReading/ConversationViewController.swift | mit | 1 | //
// ConversationViewController.swift
// DriftReading
//
// Created by Ming Gong on 8/21/15.
// Copyright © 2015 gongmingqm10. All rights reserved.
//
import UIKit
class ConversationViewController: UITableViewController {
@IBOutlet var conversationTable: UITableView!
let driftAPI = DriftAPI()
var conversations: [Conversation] = []
var selectedConversation: Conversation?
override func viewDidLoad() {
self.conversationTable.rowHeight = UITableViewAutomaticDimension
self.conversationTable.estimatedRowHeight = 80.0
}
override func viewDidAppear(animated: Bool) {
let user = DataUtils.sharedInstance.currentUser()
driftAPI.getMessages(user.userId, success: { (conversations) -> Void in
self.conversations = conversations
self.conversationTable.reloadData()
}) { (error) -> Void in
print(error.description)
}
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "ChattingSegue" {
let messageViewController = segue.destinationViewController as! MessageViewController
messageViewController.messages = selectedConversation!.messages
}
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
self.selectedConversation = conversations[indexPath.row]
self.performSegueWithIdentifier("ChattingSegue", sender: self)
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return conversations.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = conversationTable.dequeueReusableCellWithIdentifier("ConversationTableCell", forIndexPath: indexPath) as! ConversationTableCell
let conversation = conversations[indexPath.row]
cell.populate(conversation)
return cell
}
} | 00c65c587f6a2de73acf8b9b200feaf8 | 36.563636 | 146 | 0.701695 | false | false | false | false |
piscoTech/GymTracker | refs/heads/master | Gym Tracker Tests/ExecuteWorkoutControllerTests.swift | mit | 1 | //
// ExecuteWorkoutControllerTests.swift
// Gym Tracker Tests
//
// Created by Marco Boschi on 17/08/2018.
// Copyright © 2018 Marco Boschi. All rights reserved.
//
import XCTest
@testable import GymTrackerCore
class ExecuteWorkoutControllerTests: XCTestCase {
private enum DelegateCalls: Equatable {
case setWorkoutTitle(String)
case setBPM(String)
case setCurrentExerciseViewHidden(Bool)
case setRestViewHidden(Bool)
case setWorkoutDoneViewHidden(Bool)
case setNextUpTextHidden(Bool)
case workoutHasStarted
case askForChoices([GTChoice])
case disableGlobalActions
case exitWorkoutTracking
case endNotifyEndRest
case startTimer(Date)
case setExerciseName(String)
case setCurrentSetViewHidden(Bool)
case setCurrentSetText(String)
case setSetDoneButtonHidden(Bool)
case setOtherSetsViewHidden(Bool)
case setOtherSetsText(String)
case stopRestTimer
case notifyExerciseChange(Bool)
case setNextUpText(String)
case askUpdateSecondaryInfo(UpdateSecondaryInfoData)
case startRestTimer(Date)
case setRestEndButtonHidden(Bool)
case notifyEndRest
case setWorkoutDoneText(String)
case setWorkoutDoneButtonEnabled(Bool)
case stopTimer
case globallyUpdateSecondaryInfoChange
}
private let source = RunningWorkoutSource.phone
private var calls: [DelegateCalls]!
private var expectations = [XCTestExpectation]()
private var w: GTWorkout!
private var e1, e2, e3, e4: GTSimpleSetsExercise!
private var r: GTRest!
override func setUp() {
super.setUp()
calls = []
w = dataManager.newWorkout()
w.set(name: "Wrkt Tests")
var e = dataManager.newExercise()
w.add(parts: e)
e.set(name: "Exercise 1")
var s = dataManager.newSet(for: e)
s.set(mainInfo: 10)
s.set(secondaryInfo: 0)
s.set(rest: 0)
s = dataManager.newSet(for: e)
s.set(mainInfo: 5)
s.set(secondaryInfo: 8)
s.set(rest: 90)
e1 = e
e = dataManager.newExercise()
w.add(parts: e)
e.set(name: "Exercise 2")
s = dataManager.newSet(for: e)
s.set(mainInfo: 12)
s.set(secondaryInfo: 4)
s.set(rest: 30)
s = dataManager.newSet(for: e)
s.set(mainInfo: 10)
s.set(secondaryInfo: 6)
s.set(rest: 60)
e2 = e
r = dataManager.newRest()
w.add(parts: r)
r.set(rest: 60)
e = dataManager.newExercise()
w.add(parts: e)
e.set(name: "Exercise 3")
s = dataManager.newSet(for: e)
s.set(mainInfo: 15)
s.set(secondaryInfo: 0)
s.set(rest: 60)
e3 = e
e = dataManager.newExercise()
w.add(parts: e)
e.set(name: "Exercise 4")
s = dataManager.newSet(for: e)
s.set(mainInfo: 10)
s.set(secondaryInfo: 5)
s.set(rest: 60)
e4 = e
}
private func choicify() {
let ch2 = dataManager.newChoice()
w.add(parts: ch2)
ch2.add(parts: w[3] as! GTSimpleSetsExercise, w[4] as! GTSimpleSetsExercise)
let ch1 = dataManager.newChoice()
w.add(parts: ch1)
ch1.add(parts: w[0] as! GTSimpleSetsExercise, w[1] as! GTSimpleSetsExercise)
w.movePart(at: ch1.order, to: 0)
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
dataManager.setRunningWorkout(nil, fromSource: source)
dataManager.preferences.runningWorkoutSource = nil
dataManager.discardAllChanges()
super.tearDown()
}
func testSimpleStart() {
let data = ExecuteWorkoutData(workout: w, resume: false, choices: [])
_ = ExecuteWorkoutController(data: data, viewController: self, source: source, dataManager: dataManager)
assertCall { c in
if case DelegateCalls.setWorkoutTitle(let n) = c {
XCTAssertEqual(n, w.name)
return true
}
return false
}
assertCall { c in
if case DelegateCalls.setBPM(let h) = c {
XCTAssertFalse(h.isDigit)
return true
}
return false
}
assertCall { c in
if case DelegateCalls.setCurrentExerciseViewHidden(let h) = c {
XCTAssertTrue(h)
return true
}
return false
}
assertCall { c in
if case DelegateCalls.setRestViewHidden(let h) = c {
XCTAssertTrue(h)
return true
}
return false
}
assertCall { c in
if case DelegateCalls.setWorkoutDoneViewHidden(let h) = c {
XCTAssertTrue(h)
return true
}
return false
}
assertCall { c in
if case DelegateCalls.setNextUpTextHidden(let h) = c {
XCTAssertTrue(h)
return true
}
return false
}
XCTAssertTrue(calls.isEmpty)
wait(for: waitCalls(n: 1), timeout: 1)
assertCall { $0 == .workoutHasStarted }
XCTAssertEqual(dataManager.preferences.runningWorkout, w.recordID)
XCTAssertEqual(dataManager.preferences.runningWorkoutSource, source)
XCTAssertEqual(dataManager.preferences.currentChoices, [])
}
func testChoiceStart() {
choicify()
let data = ExecuteWorkoutData(workout: w, resume: false, choices: [])
let ctrl = ExecuteWorkoutController(data: data, viewController: self, source: source, dataManager: dataManager)
assertCall { c in
if case DelegateCalls.setWorkoutTitle(let n) = c {
XCTAssertEqual(n, w.name)
return true
}
return false
}
assertCall { c in
if case DelegateCalls.setBPM(let h) = c {
XCTAssertFalse(h.isDigit)
return true
}
return false
}
assertCall { c in
if case DelegateCalls.setCurrentExerciseViewHidden(let h) = c {
XCTAssertTrue(h)
return true
}
return false
}
assertCall { c in
if case DelegateCalls.setRestViewHidden(let h) = c {
XCTAssertTrue(h)
return true
}
return false
}
assertCall { c in
if case DelegateCalls.setWorkoutDoneViewHidden(let h) = c {
XCTAssertTrue(h)
return true
}
return false
}
assertCall { c in
if case DelegateCalls.setNextUpTextHidden(let h) = c {
XCTAssertTrue(h)
return true
}
return false
}
XCTAssertTrue(calls.isEmpty)
wait(for: waitCalls(n: 1), timeout: 1)
assertCall { c in
if case DelegateCalls.askForChoices(let ch) = c {
XCTAssertEqual(ch.count, 2)
ctrl.reportChoices([ch[0]: 2])
return true
}
return false
}
XCTAssertTrue(calls.isEmpty)
wait(for: waitCalls(n: 1), timeout: 1)
assertCall { c in
if case DelegateCalls.askForChoices(let ch) = c {
XCTAssertEqual(ch.count, 2)
ctrl.reportChoices([ch[0]: 1])
return true
}
return false
}
XCTAssertTrue(calls.isEmpty)
wait(for: waitCalls(n: 1), timeout: 1)
assertCall { c in
if case DelegateCalls.askForChoices(let ch) = c {
XCTAssertEqual(ch.count, 1)
ctrl.reportChoices([ch[0]: 0])
return true
}
return false
}
XCTAssertTrue(calls.isEmpty)
wait(for: waitCalls(n: 1), timeout: 1)
assertCall { $0 == .workoutHasStarted }
XCTAssertEqual(dataManager.preferences.runningWorkout, w.recordID)
XCTAssertEqual(dataManager.preferences.runningWorkoutSource, source)
XCTAssertEqual(dataManager.preferences.currentChoices, [1,0])
}
func testStartSurplusChoices() {
choicify()
let data = ExecuteWorkoutData(workout: w, resume: false, choices: [4,7,8,10])
let ctrl = ExecuteWorkoutController(data: data, viewController: self, source: source, dataManager: dataManager)
XCTAssertFalse(calls.isEmpty)
XCTAssertFalse(calls.contains { c in
if case DelegateCalls.askForChoices(_) = c {
return true
} else {
return false
}
})
calls = []
XCTAssertTrue(calls.isEmpty)
wait(for: waitCalls(n: 1), timeout: 1)
assertCall { c in
if case DelegateCalls.askForChoices(let ch) = c {
XCTAssertEqual(ch.count, 2)
ctrl.reportChoices([ch[0]: 0, ch[1]: 1])
return true
}
return false
}
XCTAssertTrue(calls.isEmpty)
wait(for: waitCalls(n: 1), timeout: 1)
assertCall { $0 == .workoutHasStarted }
XCTAssertTrue(calls.isEmpty)
XCTAssertEqual(dataManager.preferences.runningWorkout, w.recordID)
XCTAssertEqual(dataManager.preferences.runningWorkoutSource, source)
XCTAssertEqual(dataManager.preferences.currentChoices, [0,1])
}
func testCancelStart() {
choicify()
let data = ExecuteWorkoutData(workout: w, resume: false, choices: [])
let ctrl = ExecuteWorkoutController(data: data, viewController: self, source: source, dataManager: dataManager)
XCTAssertFalse(calls.isEmpty)
XCTAssertFalse(calls.contains { c in
if case DelegateCalls.askForChoices(_) = c {
return true
} else {
return false
}
})
calls = []
XCTAssertTrue(calls.isEmpty)
wait(for: waitCalls(n: 1), timeout: 1)
assertCall { c in
if case DelegateCalls.askForChoices(let ch) = c {
XCTAssertFalse(ch.isEmpty)
return true
}
return false
}
ctrl.cancelWorkout()
XCTAssertTrue(calls.isEmpty)
ctrl.cancelStartup()
assertCall { $0 == .disableGlobalActions }
assertCall { $0 == .exitWorkoutTracking }
assertCall { $0 == .endNotifyEndRest }
XCTAssertTrue(calls.isEmpty)
XCTAssertNil(dataManager.preferences.runningWorkout)
XCTAssertEqual(dataManager.preferences.runningWorkoutSource, source)
XCTAssertNil(dataManager.preferences.currentChoices)
}
func testExecution() {
choicify()
let data = ExecuteWorkoutData(workout: w, resume: false, choices: [1, 0])
let ctrl = ExecuteWorkoutController(data: data, viewController: self, source: source, dataManager: dataManager)
XCTAssertFalse(calls.isEmpty)
XCTAssertFalse(calls.contains { c in
if case DelegateCalls.askForChoices(_) = c {
return true
} else {
return false
}
})
calls = []
do { // First set
wait(for: waitCalls(n: 14), timeout: 1)
assertCall { $0 == .workoutHasStarted }
assertCall { c in
if case DelegateCalls.startTimer(let d) = c {
let now = Date()
XCTAssertEqual(d.timeIntervalSince1970, Date().timeIntervalSince1970, accuracy: 2)
return true
}
return false
}
assertCall { c in
if case DelegateCalls.setNextUpTextHidden(let h) = c {
XCTAssertFalse(h)
return true
}
return false
}
assertCall { c in
if case DelegateCalls.setCurrentExerciseViewHidden(let h) = c {
XCTAssertFalse(h)
return true
}
return false
}
assertCall { c in
if case DelegateCalls.setExerciseName(let n) = c {
XCTAssertEqual(n, e2.name)
return true
}
return false
}
assertCall { c in
if case DelegateCalls.setCurrentSetViewHidden(let h) = c {
XCTAssertFalse(h)
return true
}
return false
}
assertCall { c in
if case DelegateCalls.setCurrentSetText(let str) = c {
let s = e2[0]!
assert(string: str, containsInOrder: [s.mainInfo.description, timesSign, s.secondaryInfo.toString(), s.secondaryInfoLabel.string])
return true
}
return false
}
assertCall { c in
if case DelegateCalls.setSetDoneButtonHidden(let h) = c {
XCTAssertFalse(h)
return true
}
return false
}
assertCall { c in
if case DelegateCalls.setOtherSetsViewHidden(let h) = c {
XCTAssertFalse(h)
return true
}
return false
}
assertCall { c in
if case DelegateCalls.setOtherSetsText(let str) = c {
let s = e2[1]!
assert(string: str, containsInOrder: ["1", s.secondaryInfo.toString(), s.secondaryInfoLabel.string])
return true
}
return false
}
assertCall { $0 == .stopRestTimer }
assertCall { c in
if case DelegateCalls.setRestViewHidden(let h) = c {
XCTAssertTrue(h)
return true
}
return false
}
assertCall { c in
if case DelegateCalls.notifyExerciseChange(let r) = c {
XCTAssertFalse(r)
return true
}
return false
}
assertCall { c in
if case DelegateCalls.setNextUpText(let str) = c {
assert(string: str, containsInOrder: [r.rest.getFormattedDuration()])
return true
}
return false
}
XCTAssertTrue(calls.isEmpty)
}
let e2Change = 1.0
func checkE2Rest() {
assertCall { c in
if case DelegateCalls.setCurrentExerciseViewHidden(let h) = c {
XCTAssertFalse(h)
return true
}
return false
}
assertCall { c in
if case DelegateCalls.setExerciseName(let n) = c {
XCTAssertEqual(n, e2.name)
return true
}
return false
}
assertCall { c in
if case DelegateCalls.setCurrentSetViewHidden(let h) = c {
XCTAssertTrue(h)
return true
}
return false
}
assertCall { c in
if case DelegateCalls.setSetDoneButtonHidden(let h) = c {
XCTAssertTrue(h)
return true
}
return false
}
assertCall { c in
if case DelegateCalls.setOtherSetsViewHidden(let h) = c {
XCTAssertFalse(h)
return true
}
return false
}
assertCall { c in
if case DelegateCalls.setOtherSetsText(let str) = c {
let s = e2[1]!
assert(string: str, containsInOrder: ["1", s.secondaryInfo.toString(), s.secondaryInfoLabel.string])
return true
}
return false
}
assertCall { c in
if case DelegateCalls.startRestTimer(let d) = c {
let s = e2[0]!
XCTAssertEqual(d.timeIntervalSince1970, Date().timeIntervalSince1970 + s.rest, accuracy: 2)
return true
}
return false
}
assertCall { c in
if case DelegateCalls.setRestViewHidden(let h) = c {
XCTAssertFalse(h)
return true
}
return false
}
assertCall { c in
if case DelegateCalls.setRestEndButtonHidden(let h) = c {
XCTAssertFalse(h)
return true
}
return false
}
assertCall { c in
if case DelegateCalls.setNextUpText(let str) = c {
assert(string: str, containsInOrder: [r.rest.getFormattedDuration()])
return true
}
return false
}
}
do { // First set rest start
ctrl.endSet()
assertCall { c in
if case DelegateCalls.askUpdateSecondaryInfo(let d) = c {
XCTAssertEqual(d.set, e2[0])
XCTAssertEqual(d.workoutController, ctrl)
return true
}
return false
}
assertCall { $0 == .globallyUpdateSecondaryInfoChange }
checkE2Rest()
assertCall { c in
if case DelegateCalls.notifyExerciseChange(let r) = c {
XCTAssertTrue(r)
return true
}
return false
}
XCTAssertTrue(calls.isEmpty)
}
do { // First set update
ctrl.setSecondaryInfoChange(e2Change, for: e2[0]!)
XCTAssertEqual(ctrl.secondaryInfoChange(for: e2[0]!), 0)
XCTAssertEqual(ctrl.secondaryInfoChange(for: e2[0]!, forProposingChange: true), e2Change)
XCTAssertEqual(ctrl.secondaryInfoChange(for: e2[1]!), e2Change)
XCTAssertEqual(e2[0]!.secondaryInfo, 5)
checkE2Rest()
assertCall { $0 == .globallyUpdateSecondaryInfoChange }
XCTAssertTrue(calls.isEmpty)
}
do { // First set rest end
wait(for: waitCalls(n: 2), timeout: e2[0]!.rest + 5)
assertCall { $0 == .stopRestTimer }
assertCall { $0 == .notifyEndRest }
XCTAssertTrue(calls.isEmpty)
}
do { // Second set
ctrl.endRest()
assertCall { c in
if case DelegateCalls.setCurrentExerciseViewHidden(let h) = c {
XCTAssertFalse(h)
return true
}
return false
}
assertCall { c in
if case DelegateCalls.setExerciseName(let n) = c {
XCTAssertEqual(n, e2.name)
return true
}
return false
}
assertCall { c in
if case DelegateCalls.setCurrentSetViewHidden(let h) = c {
XCTAssertFalse(h)
return true
}
return false
}
assertCall { c in
if case DelegateCalls.setCurrentSetText(let str) = c {
let s = e2[1]!
assert(string: str, containsInOrder: [s.mainInfo.description, timesSign, s.secondaryInfo.toString(), plusSign, e2Change.toString(), s.secondaryInfoLabel.string])
return true
}
return false
}
assertCall { c in
if case DelegateCalls.setSetDoneButtonHidden(let h) = c {
XCTAssertFalse(h)
return true
}
return false
}
assertCall { c in
if case DelegateCalls.setOtherSetsViewHidden(let h) = c {
XCTAssertTrue(h)
return true
}
return false
}
assertCall(count: 2) { $0 == .stopRestTimer }
assertCall { c in
if case DelegateCalls.setRestViewHidden(let h) = c {
XCTAssertTrue(h)
return true
}
return false
}
assertCall { c in
if case DelegateCalls.notifyExerciseChange(let r) = c {
XCTAssertFalse(r)
return true
}
return false
}
assertCall { c in
if case DelegateCalls.setNextUpText(let str) = c {
assert(string: str, containsInOrder: [r.rest.getFormattedDuration()])
return true
}
return false
}
assertCall { $0 == .endNotifyEndRest }
XCTAssertTrue(calls.isEmpty)
}
do { // Rest period start
let restStart = Date().addingTimeInterval(-45)
ctrl.endSet(endTime: restStart, secondaryInfoChange: e2Change * 2)
XCTAssertEqual(ctrl.secondaryInfoChange(for: e2[1]!), 0)
XCTAssertEqual(ctrl.secondaryInfoChange(for: e2[1]!, forProposingChange: true), e2Change * 2)
XCTAssertEqual(e2[1]!.secondaryInfo, 8)
assertCall { c in
if case DelegateCalls.setCurrentExerciseViewHidden(let h) = c {
XCTAssertTrue(h)
return true
}
return false
}
assertCall { c in
if case DelegateCalls.startRestTimer(let d) = c {
XCTAssertEqual(d.timeIntervalSince1970, restStart.timeIntervalSince1970 + r.rest, accuracy: 5)
return true
}
return false
}
assertCall { c in
if case DelegateCalls.setRestViewHidden(let h) = c {
XCTAssertFalse(h)
return true
}
return false
}
assertCall { c in
if case DelegateCalls.setRestEndButtonHidden(let h) = c {
XCTAssertFalse(h)
return true
}
return false
}
assertCall { c in
if case DelegateCalls.notifyExerciseChange(let r) = c {
XCTAssertTrue(r)
return true
}
return false
}
assertCall { c in
if case DelegateCalls.setNextUpText(let str) = c {
assert(string: str, containsInOrder: [e3.name], thenNotContains: e3[0]!.secondaryInfoLabel.string)
return true
}
return false
}
assertCall { $0 == .globallyUpdateSecondaryInfoChange }
XCTAssertTrue(calls.isEmpty)
}
do { // Rest period end
wait(for: waitCalls(n: 2), timeout: 20)
assertCall { $0 == .stopRestTimer }
assertCall { $0 == .notifyEndRest }
XCTAssertTrue(calls.isEmpty)
}
do { // Last set
ctrl.endRest()
assertCall { $0 == .endNotifyEndRest }
assertCall { c in
if case DelegateCalls.setCurrentExerciseViewHidden(let h) = c {
XCTAssertFalse(h)
return true
}
return false
}
assertCall { c in
if case DelegateCalls.setExerciseName(let n) = c {
XCTAssertEqual(n, e3.name)
return true
}
return false
}
assertCall { c in
if case DelegateCalls.setCurrentSetViewHidden(let h) = c {
XCTAssertFalse(h)
return true
}
return false
}
assertCall { c in
if case DelegateCalls.setCurrentSetText(let str) = c {
let s = e3[0]!
assert(string: str, containsInOrder: [s.mainInfo.description], thenNotContains: timesSign)
return true
}
return false
}
assertCall { c in
if case DelegateCalls.setSetDoneButtonHidden(let h) = c {
XCTAssertFalse(h)
return true
}
return false
}
assertCall { c in
if case DelegateCalls.setOtherSetsViewHidden(let h) = c {
XCTAssertTrue(h)
return true
}
return false
}
assertCall(count: 2) { $0 == .stopRestTimer }
assertCall { c in
if case DelegateCalls.setRestViewHidden(let h) = c {
XCTAssertTrue(h)
return true
}
return false
}
assertCall { c in
if case DelegateCalls.notifyExerciseChange(let r) = c {
XCTAssertFalse(r)
return true
}
return false
}
assertCall { c in
if case DelegateCalls.setNextUpText(_) = c {
return true
}
return false
}
XCTAssertTrue(calls.isEmpty)
}
do { // End workout
ctrl.endSet()
assertCall { $0 == .globallyUpdateSecondaryInfoChange }
assertCall { c in
if case DelegateCalls.askUpdateSecondaryInfo(let d) = c {
XCTAssertEqual(d.set, e3[0])
XCTAssertEqual(d.workoutController, ctrl)
return true
}
return false
}
assertCall { c in
if case DelegateCalls.setCurrentExerciseViewHidden(let h) = c {
XCTAssertTrue(h)
return true
}
return false
}
assertCall { c in
if case DelegateCalls.setRestViewHidden(let h) = c {
XCTAssertTrue(h)
return true
}
return false
}
assertCall { c in
if case DelegateCalls.setNextUpTextHidden(let h) = c {
XCTAssertTrue(h)
return true
}
return false
}
assertCall { c in
if case DelegateCalls.setWorkoutDoneButtonEnabled(let e) = c {
XCTAssertFalse(e)
return true
}
return false
}
assertCall { c in
if case DelegateCalls.setWorkoutDoneText(_) = c {
return true
}
return false
}
assertCall { c in
if case DelegateCalls.setWorkoutDoneViewHidden(let h) = c {
XCTAssertFalse(h)
return true
}
return false
}
assertCall { $0 == .stopTimer }
assertCall { $0 == .disableGlobalActions }
assertCall { $0 == .endNotifyEndRest }
XCTAssertTrue(calls.isEmpty)
wait(for: waitCalls(n: 3), timeout: 2)
assertCall { c in
if case DelegateCalls.setWorkoutDoneButtonEnabled(let e) = c {
XCTAssertTrue(e)
return true
}
return false
}
assertCall(count: 2) { c in
if case DelegateCalls.setWorkoutDoneText(_) = c {
return true
}
return false
}
XCTAssertTrue(calls.isEmpty)
XCTAssertNil(dataManager.preferences.runningWorkout)
XCTAssertEqual(dataManager.preferences.runningWorkoutSource, source)
XCTAssertNil(dataManager.preferences.currentChoices)
XCTAssertEqual((w[0] as! GTChoice).lastChosen, 1)
XCTAssertEqual((w[2] as! GTChoice).lastChosen, 0)
}
}
func testUpdateSecondary() {
let ctrl = ExecuteWorkoutController(data: ExecuteWorkoutData(workout: w, resume: false, choices: []), viewController: self, source: source, dataManager: dataManager)
wait(for: waitCalls(n: 14), timeout: 1)
calls = []
ctrl.endSet()
func testSet2Update() {
assertCall { $0 == .globallyUpdateSecondaryInfoChange }
assertCall { c in
if case DelegateCalls.setCurrentExerciseViewHidden(let h) = c {
XCTAssertFalse(h)
return true
}
return false
}
assertCall { c in
if case DelegateCalls.setExerciseName(let n) = c {
XCTAssertEqual(n, e1.name)
return true
}
return false
}
assertCall { c in
if case DelegateCalls.setCurrentSetViewHidden(let h) = c {
XCTAssertFalse(h)
return true
}
return false
}
assertCall { c in
if case DelegateCalls.setCurrentSetText(let str) = c {
let s = e1[1]!
assert(string: str, containsInOrder: [s.mainInfo.description, timesSign, s.secondaryInfo.toString(), s.secondaryInfoLabel.string])
return true
}
return false
}
assertCall { c in
if case DelegateCalls.setSetDoneButtonHidden(let h) = c {
XCTAssertFalse(h)
return true
}
return false
}
assertCall { c in
if case DelegateCalls.setOtherSetsViewHidden(let h) = c {
XCTAssertTrue(h)
return true
}
return false
}
assertCall { $0 == .stopRestTimer }
assertCall { c in
if case DelegateCalls.setRestViewHidden(let h) = c {
XCTAssertTrue(h)
return true
}
return false
}
assertCall { c in
if case DelegateCalls.setNextUpText(let str) = c {
assert(string: str, containsInOrder: [e2.name, e2[0]!.secondaryInfo.toString(), e2[0]!.secondaryInfoLabel.string])
return true
}
return false
}
}
testSet2Update()
assertCall { c in
if case DelegateCalls.askUpdateSecondaryInfo(let d) = c {
XCTAssertEqual(d.set, e1[0])
XCTAssertEqual(d.workoutController, ctrl)
return true
}
return false
}
assertCall { c in
if case DelegateCalls.notifyExerciseChange(let r) = c {
XCTAssertFalse(r)
return true
}
return false
}
XCTAssertTrue(calls.isEmpty)
ctrl.setSecondaryInfoChange(0, for: e1[0]!)
testSet2Update()
XCTAssertTrue(calls.isEmpty)
XCTAssertEqual(e1[0]?.secondaryInfo, 0)
XCTAssertEqual(ctrl.secondaryInfoChange(for: e1[0]!), 0)
XCTAssertEqual(ctrl.secondaryInfoChange(for: e1[1]!), 0)
ctrl.endSet() // End E1 S2
ctrl.endSet() // End E2 S1
calls = []
ctrl.setSecondaryInfoChange(2, for: e2[0]!)
XCTAssertEqual(e2[0]?.secondaryInfo, 6)
XCTAssertEqual(ctrl.secondaryInfoChange(for: e2[0]!), 0)
XCTAssertEqual(ctrl.secondaryInfoChange(for: e2[0]!, forProposingChange: true), 2)
XCTAssertEqual(ctrl.secondaryInfoChange(for: e2[1]!), 2)
assertCall { c in
if case DelegateCalls.setCurrentExerciseViewHidden(let h) = c {
XCTAssertFalse(h)
return true
}
return false
}
assertCall { c in
if case DelegateCalls.setExerciseName(let n) = c {
XCTAssertEqual(n, e2.name)
return true
}
return false
}
assertCall { c in
if case DelegateCalls.setCurrentSetViewHidden(let h) = c {
XCTAssertTrue(h)
return true
}
return false
}
assertCall { c in
if case DelegateCalls.setSetDoneButtonHidden(let h) = c {
XCTAssertTrue(h)
return true
}
return false
}
assertCall { c in
if case DelegateCalls.setOtherSetsViewHidden(let h) = c {
XCTAssertFalse(h)
return true
}
return false
}
assertCall { c in
if case DelegateCalls.setOtherSetsText(let str) = c {
let s = e2[1]!
assert(string: str, containsInOrder: ["1", s.secondaryInfo.toString(), plusSign, "2", s.secondaryInfoLabel.string])
return true
}
return false
}
assertCall { c in
if case DelegateCalls.startRestTimer(let d) = c {
let s = e2[0]!
XCTAssertEqual(d.timeIntervalSince1970, Date().timeIntervalSince1970 + s.rest, accuracy: 2)
return true
}
return false
}
assertCall { c in
if case DelegateCalls.setRestViewHidden(let h) = c {
XCTAssertFalse(h)
return true
}
return false
}
assertCall { c in
if case DelegateCalls.setRestEndButtonHidden(let h) = c {
XCTAssertFalse(h)
return true
}
return false
}
assertCall { c in
if case DelegateCalls.setNextUpText(let str) = c {
assert(string: str, containsInOrder: [r.rest.getFormattedDuration()])
return true
}
return false
}
assertCall { $0 == .globallyUpdateSecondaryInfoChange }
XCTAssertTrue(calls.isEmpty)
ctrl.endRest()
assertCall { c in
if case DelegateCalls.setCurrentSetText(let str) = c {
let s = e2[1]!
assert(string: str, containsInOrder: [s.mainInfo.description, timesSign, s.secondaryInfo.toString(), plusSign, "2", s.secondaryInfoLabel.string])
return true
}
return false
}
XCTAssertFalse(calls.isEmpty)
}
func testNotificationInfo() {
choicify()
let ctrl = ExecuteWorkoutController(data: ExecuteWorkoutData(workout: w, resume: false, choices: [1,0]), viewController: self, source: source, dataManager: dataManager)
wait(for: waitCalls(n: 14), timeout: 1)
XCTAssertNil(ctrl.currentRestTime)
XCTAssertFalse(ctrl.currentIsRestPeriod)
XCTAssertFalse(ctrl.isRestMode)
if let (eName, info, oth) = ctrl.currentSetInfo {
XCTAssertEqual(eName, e2.name)
let s1 = e2[0]!
let s2 = e2[1]!
assert(string: info, containsInOrder: [s1.mainInfo.description, timesSign, s1.secondaryInfo.toString(), s1.secondaryInfoLabel.string])
if let o = oth {
assert(string: o, containsInOrder: ["1", s2.secondaryInfo.toString(), s2.secondaryInfoLabel.string])
} else {
XCTFail("Unexpected nil")
}
} else {
XCTFail("Unexpected nil")
}
XCTAssertFalse(ctrl.isLastPart)
ctrl.endSet()
if let (tot, end) = ctrl.currentRestTime {
XCTAssertEqual(tot, e2[0]!.rest)
XCTAssertEqual(end.timeIntervalSince1970, Date().timeIntervalSince1970 + e2[0]!.rest, accuracy: 2)
} else {
XCTFail("Unexpected nil")
}
XCTAssertFalse(ctrl.currentIsRestPeriod)
XCTAssertTrue(ctrl.isRestMode)
XCTAssertNotNil(ctrl.currentSetInfo)
XCTAssertFalse(ctrl.isLastPart)
ctrl.endRest()
XCTAssertNil(ctrl.currentRestTime)
XCTAssertFalse(ctrl.currentIsRestPeriod)
XCTAssertFalse(ctrl.isRestMode)
XCTAssertNotNil(ctrl.currentSetInfo)
XCTAssertFalse(ctrl.isLastPart)
ctrl.endSet()
XCTAssertNotNil(ctrl.currentRestTime)
XCTAssertTrue(ctrl.currentIsRestPeriod)
XCTAssertTrue(ctrl.isRestMode)
XCTAssertNil(ctrl.currentSetInfo)
XCTAssertFalse(ctrl.isLastPart)
ctrl.endRest()
XCTAssertNil(ctrl.currentRestTime)
XCTAssertFalse(ctrl.currentIsRestPeriod)
XCTAssertFalse(ctrl.isRestMode)
XCTAssertNotNil(ctrl.currentSetInfo)
XCTAssertTrue(ctrl.isLastPart)
}
func testCancelWorkout() {
choicify()
let ctrl = ExecuteWorkoutController(data: ExecuteWorkoutData(workout: w, resume: false, choices: [1,1]), viewController: self, source: source, dataManager: dataManager)
wait(for: waitCalls(n: 14), timeout: 1)
XCTAssertEqual(calls.count, 6 + 14)
calls = []
XCTAssertEqual(dataManager.preferences.runningWorkout, w.recordID)
XCTAssertEqual(dataManager.preferences.runningWorkoutSource, source)
XCTAssertEqual(dataManager.preferences.currentChoices, [1,1])
ctrl.cancelStartup()
XCTAssertTrue(calls.isEmpty)
ctrl.cancelWorkout()
assertCall { c in
if case DelegateCalls.setCurrentExerciseViewHidden(let h) = c {
XCTAssertTrue(h)
return true
}
return false
}
assertCall { c in
if case DelegateCalls.setRestViewHidden(let h) = c {
XCTAssertTrue(h)
return true
}
return false
}
assertCall { c in
if case DelegateCalls.setNextUpTextHidden(let h) = c {
XCTAssertTrue(h)
return true
}
return false
}
assertCall { $0 == .stopTimer }
assertCall { $0 == .disableGlobalActions }
assertCall { $0 == .endNotifyEndRest }
assertCall { c in
if case DelegateCalls.setWorkoutDoneButtonEnabled(let e) = c {
XCTAssertFalse(e)
return true
}
return false
}
assertCall { c in
if case DelegateCalls.setWorkoutDoneText(_) = c {
return true
}
return false
}
assertCall { c in
if case DelegateCalls.setWorkoutDoneViewHidden(let h) = c {
XCTAssertFalse(h)
return true
}
return false
}
assertCall { $0 == .exitWorkoutTracking }
XCTAssertTrue(calls.isEmpty)
XCTAssertNil(dataManager.preferences.runningWorkout)
XCTAssertEqual(dataManager.preferences.runningWorkoutSource, source)
XCTAssertNil(dataManager.preferences.currentChoices)
XCTAssertLessThan((w[0] as! GTChoice).lastChosen, 0)
XCTAssertLessThan((w[2] as! GTChoice).lastChosen, 0)
}
func testEarlyEndSimple() {
let ctrl = ExecuteWorkoutController(data: ExecuteWorkoutData(workout: w, resume: false, choices: []), viewController: self, source: source, dataManager: dataManager)
wait(for: waitCalls(n: 14), timeout: 1)
XCTAssertEqual(calls.count, 6 + 14)
calls = []
XCTAssertEqual(dataManager.preferences.runningWorkout, w.recordID)
XCTAssertEqual(dataManager.preferences.runningWorkoutSource, source)
XCTAssertEqual(dataManager.preferences.currentChoices, [])
ctrl.endWorkout()
assertCall { c in
if case DelegateCalls.setCurrentExerciseViewHidden(let h) = c {
XCTAssertTrue(h)
return true
}
return false
}
assertCall { c in
if case DelegateCalls.setRestViewHidden(let h) = c {
XCTAssertTrue(h)
return true
}
return false
}
assertCall { c in
if case DelegateCalls.setNextUpTextHidden(let h) = c {
XCTAssertTrue(h)
return true
}
return false
}
assertCall { c in
if case DelegateCalls.setWorkoutDoneButtonEnabled(let e) = c {
XCTAssertFalse(e)
return true
}
return false
}
assertCall { c in
if case DelegateCalls.setWorkoutDoneText(_) = c {
return true
}
return false
}
assertCall { c in
if case DelegateCalls.setWorkoutDoneViewHidden(let h) = c {
XCTAssertFalse(h)
return true
}
return false
}
assertCall { $0 == .stopTimer }
assertCall { $0 == .disableGlobalActions }
assertCall { $0 == .endNotifyEndRest }
XCTAssertTrue(calls.isEmpty)
wait(for: waitCalls(n: 2), timeout: 2)
assertCall { c in
if case DelegateCalls.setWorkoutDoneButtonEnabled(let e) = c {
XCTAssertTrue(e)
return true
}
return false
}
assertCall(count: 2) { c in
if case DelegateCalls.setWorkoutDoneText(_) = c {
return true
}
return false
}
XCTAssertTrue(calls.isEmpty)
XCTAssertNil(dataManager.preferences.runningWorkout)
XCTAssertEqual(dataManager.preferences.runningWorkoutSource, source)
XCTAssertNil(dataManager.preferences.currentChoices)
}
func testEarlyEndChoice() {
choicify()
let ctrl = ExecuteWorkoutController(data: ExecuteWorkoutData(workout: w, resume: false, choices: [0, 1]), viewController: self, source: source, dataManager: dataManager)
wait(for: waitCalls(n: 14), timeout: 1)
XCTAssertEqual(calls.count, 6 + 14)
calls = []
XCTAssertEqual(dataManager.preferences.runningWorkout, w.recordID)
XCTAssertEqual(dataManager.preferences.runningWorkoutSource, source)
XCTAssertEqual(dataManager.preferences.currentChoices, [0,1])
ctrl.endWorkout()
assertCall { c in
if case DelegateCalls.setCurrentExerciseViewHidden(let h) = c {
XCTAssertTrue(h)
return true
}
return false
}
assertCall { c in
if case DelegateCalls.setRestViewHidden(let h) = c {
XCTAssertTrue(h)
return true
}
return false
}
assertCall { c in
if case DelegateCalls.setNextUpTextHidden(let h) = c {
XCTAssertTrue(h)
return true
}
return false
}
assertCall { c in
if case DelegateCalls.setWorkoutDoneButtonEnabled(let e) = c {
XCTAssertFalse(e)
return true
}
return false
}
assertCall { c in
if case DelegateCalls.setWorkoutDoneText(_) = c {
return true
}
return false
}
assertCall { c in
if case DelegateCalls.setWorkoutDoneViewHidden(let h) = c {
XCTAssertFalse(h)
return true
}
return false
}
assertCall { $0 == .stopTimer }
assertCall { $0 == .disableGlobalActions }
assertCall { $0 == .endNotifyEndRest }
XCTAssertTrue(calls.isEmpty)
wait(for: waitCalls(n: 2), timeout: 2)
assertCall { c in
if case DelegateCalls.setWorkoutDoneButtonEnabled(let e) = c {
XCTAssertTrue(e)
return true
}
return false
}
assertCall(count: 2) { c in
if case DelegateCalls.setWorkoutDoneText(_) = c {
return true
}
return false
}
XCTAssertTrue(calls.isEmpty)
XCTAssertNil(dataManager.preferences.runningWorkout)
XCTAssertEqual(dataManager.preferences.runningWorkoutSource, source)
XCTAssertNil(dataManager.preferences.currentChoices)
XCTAssertEqual((w[0] as! GTChoice).lastChosen, 0)
XCTAssertEqual((w[2] as! GTChoice).lastChosen, 1)
}
private func assertCall(count: Int = 1, file: StaticString = #file, line: UInt = #line, _ where: (DelegateCalls) -> Bool) {
let n = calls.count
calls.removeAll { `where`($0) }
let diff = n - calls.count
if diff != count {
XCTFail("\(diff) of \(count) expected call(s) found", file: file, line: line)
}
}
private func waitCalls(n: Int) -> [XCTestExpectation] {
let e = (0 ..< n).map { _ in XCTestExpectation() }
expectations = e
return e
}
}
extension ExecuteWorkoutControllerTests: ExecuteWorkoutControllerDelegate {
func setWorkoutTitle(_ text: String) {
self.calls.append(.setWorkoutTitle(text))
expectations.popLast()?.fulfill()
}
func askForChoices(_ choices: [GTChoice]) {
self.calls.append(.askForChoices(choices))
expectations.popLast()?.fulfill()
}
func setBPM(_ text: String) {
self.calls.append(.setBPM(text))
expectations.popLast()?.fulfill()
}
func startTimer(at date: Date) {
self.calls.append(.startTimer(date))
expectations.popLast()?.fulfill()
}
func stopTimer() {
self.calls.append(.stopTimer)
expectations.popLast()?.fulfill()
}
func setCurrentExerciseViewHidden(_ hidden: Bool) {
self.calls.append(.setCurrentExerciseViewHidden(hidden))
expectations.popLast()?.fulfill()
}
func setExerciseName(_ name: String) {
self.calls.append(.setExerciseName(name))
expectations.popLast()?.fulfill()
}
func setCurrentSetViewHidden(_ hidden: Bool) {
self.calls.append(.setCurrentSetViewHidden(hidden))
expectations.popLast()?.fulfill()
}
func setCurrentSetText(_ text: NSAttributedString) {
self.calls.append(.setCurrentSetText(text.string))
expectations.popLast()?.fulfill()
}
func setOtherSetsViewHidden(_ hidden: Bool) {
self.calls.append(.setOtherSetsViewHidden(hidden))
expectations.popLast()?.fulfill()
}
func setOtherSetsText(_ text: NSAttributedString) {
self.calls.append(.setOtherSetsText(text.string))
expectations.popLast()?.fulfill()
}
func setSetDoneButtonHidden(_ hidden: Bool) {
self.calls.append(.setSetDoneButtonHidden(hidden))
expectations.popLast()?.fulfill()
}
func startRestTimer(to date: Date) {
self.calls.append(.startRestTimer(date))
expectations.popLast()?.fulfill()
}
func stopRestTimer() {
self.calls.append(.stopRestTimer)
expectations.popLast()?.fulfill()
}
func setRestViewHidden(_ hidden: Bool) {
self.calls.append(.setRestViewHidden(hidden))
expectations.popLast()?.fulfill()
}
func setRestEndButtonHidden(_ hidden: Bool) {
self.calls.append(.setRestEndButtonHidden(hidden))
expectations.popLast()?.fulfill()
}
func setWorkoutDoneViewHidden(_ hidden: Bool) {
self.calls.append(.setWorkoutDoneViewHidden(hidden))
expectations.popLast()?.fulfill()
}
func setWorkoutDoneText(_ text: String) {
self.calls.append(.setWorkoutDoneText(text))
expectations.popLast()?.fulfill()
}
func setWorkoutDoneButtonEnabled(_ enabled: Bool) {
self.calls.append(.setWorkoutDoneButtonEnabled(enabled))
expectations.popLast()?.fulfill()
}
func disableGlobalActions() {
self.calls.append(.disableGlobalActions)
expectations.popLast()?.fulfill()
}
func setNextUpTextHidden(_ hidden: Bool) {
self.calls.append(.setNextUpTextHidden(hidden))
expectations.popLast()?.fulfill()
}
func setNextUpText(_ text: NSAttributedString) {
self.calls.append(.setNextUpText(text.string))
expectations.popLast()?.fulfill()
}
func notifyEndRest() {
self.calls.append(.notifyEndRest)
expectations.popLast()?.fulfill()
}
func endNotifyEndRest() {
self.calls.append(.endNotifyEndRest)
expectations.popLast()?.fulfill()
}
func notifyExerciseChange(isRest: Bool) {
self.calls.append(.notifyExerciseChange(isRest))
expectations.popLast()?.fulfill()
}
func askUpdateSecondaryInfo(with data: UpdateSecondaryInfoData) {
self.calls.append(.askUpdateSecondaryInfo(data))
expectations.popLast()?.fulfill()
}
func workoutHasStarted() {
self.calls.append(.workoutHasStarted)
expectations.popLast()?.fulfill()
}
func exitWorkoutTracking() {
self.calls.append(.exitWorkoutTracking)
expectations.popLast()?.fulfill()
}
func globallyUpdateSecondaryInfoChange() {
self.calls.append(.globallyUpdateSecondaryInfoChange)
expectations.popLast()?.fulfill()
}
}
| 1fa87bb3c5ba0ddcfa9543d59d4a65c4 | 24.165491 | 171 | 0.681977 | false | false | false | false |
wess/reddift | refs/heads/master | reddiftSample/SubredditsViewController.swift | mit | 1 | //
// SubredditsViewController.swift
// reddift
//
// Created by sonson on 2015/05/04.
// Copyright (c) 2015年 sonson. All rights reserved.
//
import Foundation
import reddift
class SubredditsViewController: BaseSubredditsViewController, UISearchResultsUpdating, UISearchBarDelegate, UISearchControllerDelegate {
var searchController:UISearchController? = nil
var searchResultViewController:SearchSubredditsViewController? = nil
override func viewDidLoad() {
super.viewDidLoad()
sortTypes += [.Popular, .New, .Employee, .Gold]
for sortType in sortTypes {
sortTitles.append(sortType.title)
}
self.title = "Subreddits"
searchResultViewController = SearchSubredditsViewController()
searchResultViewController?.tableView.delegate = self
searchResultViewController?.session = session
searchController = UISearchController(searchResultsController: searchResultViewController)
searchController?.searchResultsUpdater = self
searchController?.searchBar.sizeToFit()
tableView.tableHeaderView = searchController?.searchBar
searchController?.delegate = self
searchController?.dimsBackgroundDuringPresentation = false
searchController?.searchBar.delegate = searchResultViewController
self.definesPresentationContext = true
segmentedControl = UISegmentedControl(items:sortTitles)
segmentedControl?.addTarget(self, action: "segmentChanged:", forControlEvents: UIControlEvents.ValueChanged)
segmentedControl?.frame = CGRect(x: 0, y: 0, width: 300, height: 28)
segmentedControl?.selectedSegmentIndex = 0
let space = UIBarButtonItem(barButtonSystemItem:.FlexibleSpace, target: nil, action: nil)
let item = UIBarButtonItem(customView:self.segmentedControl!)
self.toolbarItems = [space, item, space]
if self.subreddits.count == 0 {
load()
}
self.navigationController?.toolbarHidden = false
}
func load() {
if let seg = self.segmentedControl {
if loading {
return
}
loading = true
session?.getSubreddit(sortTypes[seg.selectedSegmentIndex], paginator:paginator, completion: { (result) in
switch result {
case let .Failure:
println(result.error)
case let .Success:
println(result.value)
if let listing = result.value as? Listing {
for obj in listing.children {
if let subreddit = obj as? Subreddit {
self.subreddits.append(subreddit)
}
}
self.paginator = listing.paginator
}
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.tableView.reloadData()
self.loading = false
})
}
})
}
}
func segmentChanged(sender:AnyObject) {
if let seg = sender as? UISegmentedControl {
self.subreddits.removeAll(keepCapacity: true)
self.tableView.reloadData()
self.paginator = Paginator()
load()
}
}
}
// MARK:
extension SubredditsViewController {
func searchBarSearchButtonClicked(searchBar: UISearchBar) {
}
}
// MARK:
extension SubredditsViewController {
func presentSearchController(searchController: UISearchController) {
}
func willPresentSearchController(searchController: UISearchController) {
}
func didPresentSearchController(searchController: UISearchController) {
}
func willDismissSearchController(searchController: UISearchController) {
}
func didDismissSearchController(searchController: UISearchController) {
}
}
// MARK:
extension SubredditsViewController {
func updateSearchResultsForSearchController(searchController: UISearchController) {
}
}
// MARK:
extension SubredditsViewController {
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return subreddits.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! UITableViewCell
if indices(subreddits) ~= indexPath.row {
let subreddit = subreddits[indexPath.row]
cell.textLabel?.text = subreddit.title
}
return cell
}
}
// MARK:
extension SubredditsViewController {
override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
if tableView == self.tableView {
if indexPath.row == (subreddits.count - 1) {
if paginator != nil {
load()
}
}
}
if let searchResultViewController = searchResultViewController {
if tableView == searchResultViewController.tableView {
if indexPath.row == (searchResultViewController.subreddits.count - 1) {
searchResultViewController.reload()
}
}
}
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
var subreddit:Subreddit? = nil
tableView.deselectRowAtIndexPath(indexPath, animated: true)
if tableView == self.tableView {
if indices(subreddits) ~= indexPath.row {
subreddit = self.subreddits[indexPath.row]
}
}
// if let searchResultViewController = searchResultViewController {
// if tableView == searchResultViewController.tableView {
// if indices(searchResultViewController.contents) ~= indexPath.row {
// subreddit = searchResultViewController.links[indexPath.row]
// }
// }
// }
// if let link = link {
// if let con = self.storyboard?.instantiateViewControllerWithIdentifier("CommentViewController") as? CommentViewController {
// con.session = session
// con.link = link
// self.navigationController?.pushViewController(con, animated: true)
// }
// }
}
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 44
}
} | 23cd00e03c6753d28210194710b443d1 | 33.695 | 136 | 0.618766 | false | false | false | false |
NGeenLibraries/NGeen | refs/heads/master | NGeen/Network/Session/Task/Delegate/SessionTaskDelegate.swift | mit | 1 | //
// SessionTaskDelegate.swift
// Copyright (c) 2014 NGeen
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
class SessionTaskDelegate: NSObject, NSURLSessionDataDelegate, NSURLSessionDownloadDelegate, NSURLSessionTaskDelegate {
private(set) var progress: NSProgress
private(set) var data: NSMutableData
var closure: ((NSData!, NSURLResponse!, NSError!) -> Void)?
var downloadProgressHandler: NGeenProgressTaskClosure
var destinationURL: NSURL?
var streamHandler: ((NSURLSession!, NSURLSessionTask!) -> NSInputStream)?
var uploadProgressHandler: NGeenProgressTaskClosure
override init() {
self.data = NSMutableData()
self.progress = NSProgress(totalUnitCount: 0)
}
// MARK: Instance methods
/**
* The function set the unit count to the progress
*
* @param totalUnitCount The unit count for the progress.
*
*/
func setTotalUnitCount(totalUnitCount: Int64) {
self.progress = NSProgress(totalUnitCount: totalUnitCount)
}
// MARK: NSURLSessionData delegate
func URLSession(session: NSURLSession!, dataTask: NSURLSessionDataTask!, didReceiveData data: NSData!) {
self.data.appendData(data)
}
// MARK: NSURLSessionDownloadTask delegate
func URLSession(session: NSURLSession!, downloadTask: NSURLSessionDownloadTask!, didFinishDownloadingToURL location: NSURL!) {
if self.destinationURL != nil {
var error: NSError?
NSFileManager.defaultManager().moveItemAtURL(location, toURL: self.destinationURL, error: &error)
if error != nil {
NSNotificationCenter.defaultCenter().postNotificationName(kNGeenDownloadTaskDidFailToMoveFileNotification, object: downloadTask, userInfo: error?.userInfo)
}
}
}
func URLSession(session: NSURLSession!, downloadTask: NSURLSessionDownloadTask!, didResumeAtOffset fileOffset: Int64, expectedTotalBytes: Int64) {
self.progress.totalUnitCount = expectedTotalBytes
self.progress.completedUnitCount = fileOffset
}
func URLSession(session: NSURLSession!, downloadTask: NSURLSessionDownloadTask!, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
self.progress.totalUnitCount = totalBytesExpectedToWrite
self.progress.completedUnitCount = totalBytesWritten
self.downloadProgressHandler?(bytesWritten, totalBytesWritten, totalBytesExpectedToWrite)
}
// MARK: NSURLSessionTask delegate
func URLSession(session: NSURLSession!, task: NSURLSessionTask!, didCompleteWithError error: NSError!) {
dispatch_async(dispatch_get_main_queue(), {
if self.closure != nil {
self.closure!(self.data, task.response, error)
}
})
}
func URLSession(session: NSURLSession!, task: NSURLSessionTask!, needNewBodyStream completionHandler: ((NSInputStream!) -> Void)!) {
var inputStream: NSInputStream? = nil
if let stream: NSInputStream = self.streamHandler?(session, task) {
inputStream = stream
} else {
inputStream = task.originalRequest.HTTPBodyStream
}
completionHandler(inputStream)
}
// MARK: NSURLSessionUploadTask delegate
func URLSession(session: NSURLSession!, task: NSURLSessionTask!, didSendBodyData bytesSent: Int64, totalBytesSent: Int64, totalBytesExpectedToSend: Int64) {
self.progress.totalUnitCount = totalBytesExpectedToSend
self.progress.completedUnitCount = totalBytesSent
self.uploadProgressHandler?(bytesSent, totalBytesSent, totalBytesExpectedToSend)
}
}
| 11319a93b61334b949ad50d06dfe65a7 | 42.135135 | 180 | 0.714077 | false | false | false | false |
mumbler/PReVo-iOS | refs/heads/trunk | ReVoDatumbazo/Komunaj/DatumbazAlirado/DatumbazAlirilo.swift | mit | 1 | //
// DatumbazAlirilo.swift
// ReVoDatumbazo
//
// Created by Robin Hill on 8/18/19.
// Copyright © 2019 Robin Hill. All rights reserved.
//
import Foundation
import CoreData
#if os(iOS)
import ReVoModeloj
#elseif os(macOS)
import ReVoModelojOSX
#endif
final class DatumbazAlirilo {
let konteksto: NSManagedObjectContext
public init(konteksto: NSManagedObjectContext) {
self.konteksto = konteksto
}
// MARK: - Serĉi individuajn objektojn
func lingvo(porKodo kodo: String) -> NSManagedObject? {
let serchPeto = NSFetchRequest<NSFetchRequestResult>()
serchPeto.entity = NSEntityDescription.entity(forEntityName: "Lingvo", in: konteksto)
serchPeto.predicate = NSPredicate(format: "kodo == %@", argumentArray: [kodo])
do {
return try konteksto.fetch(serchPeto).first as? NSManagedObject
} catch {
}
return nil
}
func fako(porKodo kodo: String) -> NSManagedObject? {
let serchPeto = NSFetchRequest<NSFetchRequestResult>()
serchPeto.entity = NSEntityDescription.entity(forEntityName: "Fako", in: konteksto)
serchPeto.predicate = NSPredicate(format: "kodo == %@", argumentArray: [kodo])
do {
return try konteksto.fetch(serchPeto).first as? NSManagedObject
} catch {
}
return nil
}
func mallongigo(porKodo kodo: String) -> NSManagedObject? {
let serchPeto = NSFetchRequest<NSFetchRequestResult>()
serchPeto.entity = NSEntityDescription.entity(forEntityName: "Mallongigo", in: konteksto)
serchPeto.predicate = NSPredicate(format: "kodo == %@", argumentArray: [kodo])
do {
return try konteksto.fetch(serchPeto).first as? NSManagedObject
} catch {
}
return nil
}
func oficialeco(porKodo kodo: String) -> NSManagedObject? {
let serchPeto = NSFetchRequest<NSFetchRequestResult>()
serchPeto.entity = NSEntityDescription.entity(forEntityName: "Oficialeco", in: konteksto)
serchPeto.predicate = NSPredicate(format: "kodo == %@", argumentArray: [kodo])
do {
return try konteksto.fetch(serchPeto).first as? NSManagedObject
} catch {
}
return nil
}
func artikolo(porIndekso indekso: String) -> NSManagedObject? {
let serchPeto = NSFetchRequest<NSFetchRequestResult>()
serchPeto.entity = NSEntityDescription.entity(forEntityName: "Artikolo", in: konteksto)
serchPeto.predicate = NSPredicate(format: "indekso == %@", argumentArray: [indekso])
do {
return try konteksto.fetch(serchPeto).first as? NSManagedObject
} catch {
}
return nil
}
// MARK: - Kolekto klasojn da objektoj
public func vortoj(oficialeco: String) -> [NSManagedObject]? {
let serchPeto = NSFetchRequest<NSFetchRequestResult>()
serchPeto.entity = NSEntityDescription.entity(forEntityName: "Artikolo", in: konteksto)
serchPeto.predicate = NSPredicate(format: "ofc == %@", argumentArray: [oficialeco])
do {
return try konteksto.fetch(serchPeto) as? [NSManagedObject]
} catch {
}
return nil
}
public func fakVortoj(porFako kodo: String) -> [NSManagedObject]? {
if let fako = fako(porKodo: kodo) {
let vortoj = fako.mutableSetValue(forKey: "fakvortoj").allObjects as? [NSManagedObject]
return vortoj?.sorted(by: { (unua: NSManagedObject, dua: NSManagedObject) -> Bool in
let unuaNomo = unua.value(forKey: "nomo") as! String
let duaNomo = dua.value(forKey: "nomo") as! String
return unuaNomo.compare(duaNomo, options: .caseInsensitive, range: nil, locale: Locale(identifier: "eo")) == .orderedAscending
})
}
return nil
}
public func ofcVortoj(porOficialeco kodo: String) -> [NSManagedObject]? {
if let oficialeco = oficialeco(porKodo: kodo) {
let vortoj = oficialeco.mutableSetValue(forKey: "ofcvortoj").allObjects as? [NSManagedObject]
return vortoj?.sorted(by: { (unua: NSManagedObject, dua: NSManagedObject) -> Bool in
let unuaNomo = unua.value(forKey: "nomo") as! String
let duaNomo = dua.value(forKey: "nomo") as! String
return unuaNomo.compare(duaNomo, options: .caseInsensitive, range: nil, locale: Locale(identifier: "eo")) == .orderedAscending
})
}
return nil
}
// MARK: - Kolekti ĉiujn objektojn
func chiujLingvoj() -> [NSManagedObject] {
let serchPeto = NSFetchRequest<NSFetchRequestResult>()
serchPeto.entity = NSEntityDescription.entity(forEntityName: "Lingvo", in: konteksto)
do {
if let objektoj = try konteksto.fetch(serchPeto) as? [NSManagedObject] {
return objektoj
}
} catch { }
return []
}
func chiujFakoj() -> [NSManagedObject] {
let serchPeto = NSFetchRequest<NSFetchRequestResult>()
serchPeto.entity = NSEntityDescription.entity(forEntityName: "Fako", in: konteksto)
do {
if let objektoj = try konteksto.fetch(serchPeto) as? [NSManagedObject] {
return objektoj
}
} catch { }
return []
}
func chiujStiloj() -> [NSManagedObject] {
let serchPeto = NSFetchRequest<NSFetchRequestResult>()
serchPeto.entity = NSEntityDescription.entity(forEntityName: "Stilo", in: konteksto)
do {
if let objektoj = try konteksto.fetch(serchPeto) as? [NSManagedObject] {
return objektoj
}
} catch { }
return []
}
func chiujMallongigoj() -> [NSManagedObject] {
let serchPeto = NSFetchRequest<NSFetchRequestResult>()
serchPeto.entity = NSEntityDescription.entity(forEntityName: "Mallongigo", in: konteksto)
do {
if let objektoj = try konteksto.fetch(serchPeto) as? [NSManagedObject] {
return objektoj
}
} catch { }
return []
}
func chiujOficialecoj() -> [NSManagedObject] {
let serchPeto = NSFetchRequest<NSFetchRequestResult>()
serchPeto.entity = NSEntityDescription.entity(forEntityName: "Oficialeco", in: konteksto)
do {
if let objektoj = try konteksto.fetch(serchPeto) as? [NSManagedObject] {
return objektoj
}
} catch { }
return []
}
// MARK: - Aliaj
func iuAjnArtikolo() -> NSManagedObject? {
let kvanto = kvantoDeArtikoloj()
let numero = Int.random(in: 0..<kvanto)
let serchPeto = NSFetchRequest<NSFetchRequestResult>()
serchPeto.entity = NSEntityDescription.entity(forEntityName: "Artikolo", in: konteksto)
serchPeto.predicate = NSPredicate(format: "numero == %@", argumentArray: [numero])
do {
return try konteksto.fetch(serchPeto).first as? NSManagedObject
} catch {}
return nil
}
// MARK: - Helpiloj
private func kvantoDeArtikoloj() -> Int {
let kvantoPeto = NSFetchRequest<NSFetchRequestResult>()
kvantoPeto.entity = NSEntityDescription.entity(forEntityName: "Artikolo", in: konteksto)
do {
return try konteksto.count(for: kvantoPeto)
} catch {}
return 0
}
}
| 096806426591726a70eac1254d280449 | 32.547009 | 142 | 0.592229 | false | false | false | false |
lemonkey/iOS | refs/heads/master | WatchKit/_Apple/ListerforAppleWatchiOSandOSX/Swift/Common/ListItem.swift | mit | 1 | /*
Copyright (C) 2015 Apple Inc. All Rights Reserved.
See LICENSE.txt for this sample’s licensing information
Abstract:
The `ListItem` class represents the text and completion state of a single item in the list.
*/
import Foundation
/**
A `ListItem` object is composed of a text property, a completion status, and an underlying opaque identity
that distinguishes one `ListItem` object from another. `ListItem` objects are copyable and archivable.
To ensure that the `ListItem` class is unarchivable from an instance that was archived in the
Objective-C version of Lister, the `ListItem` class declaration is annotated with @objc(AAPLListItem).
This annotation ensures that the runtime name of the `ListItem` class is the same as the
`AAPLListItem` class defined in the Objective-C version of the app. It also allows the Objective-C
version of Lister to unarchive a `ListItem` instance that was archived in the Swift version.
*/
@objc(AAPLListItem)
final public class ListItem: NSObject, NSCoding, NSCopying, DebugPrintable {
// MARK: Types
/**
String constants that are used to archive the stored properties of a `ListItem`. These
constants are used to help implement `NSCoding`.
*/
private struct SerializationKeys {
static let text = "text"
static let uuid = "uuid"
static let complete = "completed"
}
// MARK: Properties
/// The text content for a `ListItem`.
public var text: String
/// Whether or not this `ListItem` is complete.
public var isComplete: Bool
/// An underlying identifier to distinguish one `ListItem` from another.
private var UUID: NSUUID
// MARK: Initializers
/**
Initializes a `ListItem` instance with the designated text, completion state, and UUID. This
is the designated initializer for `ListItem`. All other initializers are convenience initializers.
However, this is the only private initializer.
:param: text The intended text content of the list item.
:param: complete The item's initial completion state.
:param: UUID The item's initial UUID.
*/
private init(text: String, complete: Bool, UUID: NSUUID) {
self.text = text
self.isComplete = complete
self.UUID = UUID
}
/**
Initializes a `ListItem` instance with the designated text and completion state.
:param: text The text content of the list item.
:param: complete The item's initial completion state.
*/
public convenience init(text: String, complete: Bool) {
self.init(text: text, complete: complete, UUID: NSUUID())
}
/**
Initializes a `ListItem` instance with the designated text and a default value for `isComplete`.
The default value for `isComplete` is false.
:param: text The intended text content of the list item.
*/
public convenience init(text: String) {
self.init(text: text, complete: false)
}
// MARK: NSCopying
public func copyWithZone(zone: NSZone) -> AnyObject {
return ListItem(text: text, complete: isComplete, UUID: UUID)
}
// MARK: NSCoding
public required init(coder aDecoder: NSCoder) {
text = aDecoder.decodeObjectForKey(SerializationKeys.text) as! String
isComplete = aDecoder.decodeBoolForKey(SerializationKeys.complete)
UUID = aDecoder.decodeObjectForKey(SerializationKeys.uuid) as! NSUUID
}
public func encodeWithCoder(encoder: NSCoder) {
encoder.encodeObject(text, forKey: SerializationKeys.text)
encoder.encodeBool(isComplete, forKey: SerializationKeys.complete)
encoder.encodeObject(UUID, forKey: SerializationKeys.uuid)
}
/**
Resets the underlying identity of the `ListItem`. If a copy of this item is made, and a call
to refreshIdentity() is made afterward, the items will no longer be equal.
*/
public func refreshIdentity() {
UUID = NSUUID()
}
// MARK: Overrides
/**
Overrides NSObject's isEqual(_:) instance method to return whether or not the list item is
equal to another list item. A `ListItem` is considered to be equal to another `ListItem` if
the underyling identities of the two list items are equal.
:param: object Any object, or nil.
:returns: `true` if the object is a `ListItem` and it has the same underlying identity as the
receiving instance. `false` otherwise.
*/
override public func isEqual(object: AnyObject?) -> Bool {
if let item = object as? ListItem {
return UUID == item.UUID
}
return false
}
// MARK: DebugPrintable
public override var debugDescription: String {
return "\"\(text)\""
}
}
| 00767e182e699b5a44b38ffd7e653ef1 | 35.748148 | 110 | 0.658738 | false | false | false | false |
hollance/swift-algorithm-club | refs/heads/master | Kth Largest Element/kthLargest.playground/Sources/kthLargest.swift | mit | 2 | import Foundation
/*
Returns the k-th largest value inside of an array a.
This is an O(n log n) solution since we sort the array.
*/
public func kthLargest(_ a: [Int], _ k: Int) -> Int? {
let len = a.count
if k > 0 && k <= len {
let sorted = a.sorted()
return sorted[len - k]
} else {
return nil
}
}
// MARK: - Randomized selection
/*
Returns the i-th smallest element from the array.
This works a bit like quicksort and a bit like binary search.
The partitioning step picks a random pivot and uses Lomuto's scheme to
rearrange the array; afterwards, this pivot is in its final sorted position.
If this pivot index equals i, we're done. If i is smaller, then we continue
with the left side, otherwise we continue with the right side.
Expected running time: O(n) if the elements are distinct.
*/
public func randomizedSelect<T: Comparable>(_ array: [T], order k: Int) -> T {
var a = array
func randomPivot<T: Comparable>(_ a: inout [T], _ low: Int, _ high: Int) -> T {
let pivotIndex = Int.random(in: low...high)
a.swapAt(pivotIndex, high)
return a[high]
}
func randomizedPartition<T: Comparable>(_ a: inout [T], _ low: Int, _ high: Int) -> Int {
let pivot = randomPivot(&a, low, high)
var i = low
for j in low..<high {
if a[j] <= pivot {
a.swapAt(i, j)
i += 1
}
}
a.swapAt(i, high)
return i
}
func randomizedSelect<T: Comparable>(_ a: inout [T], _ low: Int, _ high: Int, _ k: Int) -> T {
if low < high {
let p = randomizedPartition(&a, low, high)
if k == p {
return a[p]
} else if k < p {
return randomizedSelect(&a, low, p - 1, k)
} else {
return randomizedSelect(&a, p + 1, high, k)
}
} else {
return a[low]
}
}
precondition(a.count > 0)
return randomizedSelect(&a, 0, a.count - 1, k)
}
| 711441cb835fdedbab7cbb593a7567d5 | 25.647887 | 96 | 0.600951 | false | false | false | false |
iagapie/Swoxy | refs/heads/master | Swoxy/Classes/MvpDelegate.swift | mit | 1 | //
// MvpDelegate.swift
// Pods
//
// Created by Igor Agapie on 06/07/2016.
//
//
import Foundation
open class MvpDelegate {
fileprivate var isAttached: Bool = false
fileprivate weak var view: MvpView?
public init() {
}
open func onCreate<V: MvpView>(_ view: V) {
self.view = view
isAttached = false
}
open func attachView() {
guard let view = self.view else {
fatalError("You should call attachView() after onCreate(View)")
}
guard false == isAttached else {
return
}
view.presenters.forEach { $0.attach(view: view) }
isAttached = true
}
open func detachView() {
guard let view = self.view else {
return
}
view.presenters.forEach { $0.detach(view: view) }
isAttached = false
}
open func onDestroy() {
guard let view = self.view else {
return
}
if isAttached {
detachView()
}
view.presenters.forEach { $0.onDestroy() }
self.view = nil
}
}
| f94c6b942baf2e7206900ad7c85f546c | 18.883333 | 75 | 0.498743 | false | false | false | false |
sketchytech/matchesInStringWithRange | refs/heads/master | extension.swift | mit | 1 | extension NSRegularExpression {
func matchesInStringWithRange(str:String!,options: NSMatchingOptions,error:NSErrorPointer, range:Range<String.Index>)-> [AnyObject]! {
// Calculate start and end ranges
var num = 0
var firstIndex:Int?
var strLength = 0
for i in range {
if firstIndex == nil {
firstIndex=num
}
else {
strLength = num
}
num++
}
strLength
firstIndex!
// use the NSRegularExpression method matchesInString
let rvalue = self.matchesInString(str, options: options, range: NSRange(location: firstIndex!, length: strLength))
return rvalue
}
}
| 00d1f9c6dfeeaf70954aa00aa4749752 | 28.807692 | 138 | 0.548387 | false | false | false | false |
yankodimitrov/SwiftLayoutKit | refs/heads/master | SwiftLayoutKit/AutoLayoutAttribute.swift | mit | 1 | //
// AutoLayoutAttribute.swift
// SwiftLayoutKit
//
// Created by Yanko Dimitrov on 3/26/15.
// Copyright (c) 2015 Yanko Dimitrov. All rights reserved.
//
import UIKit
struct AutoLayoutAttribute: LayoutAttribute {
let type: NSLayoutAttribute
let view: UIView
let multiplier: CGFloat
let constant: CGFloat
let priority: Float
init(type: NSLayoutAttribute, view: UIView, multiplier: CGFloat = 1, constant: CGFloat = 0, priority: Float = 1000) {
self.type = type
self.view = view
self.multiplier = multiplier
self.constant = constant
self.priority = priority
}
init(attribute: LayoutAttribute, multiplier: CGFloat) {
self.init(type: attribute.type, view: attribute.view, multiplier: multiplier, constant: attribute.constant, priority: attribute.priority)
}
init(attribute: LayoutAttribute, constant: CGFloat) {
self.init(type: attribute.type, view: attribute.view, multiplier: attribute.multiplier, constant: constant, priority: attribute.priority)
}
init(attribute: LayoutAttribute, priority: Float) {
self.init(type: attribute.type, view: attribute.view, multiplier: attribute.multiplier, constant: attribute.constant, priority: priority)
}
func makeConstraintWith(relation relation: NSLayoutRelation, toAttribute: LayoutAttribute?) -> NSLayoutConstraint {
let constraint = NSLayoutConstraint(
item: view,
attribute: type,
relatedBy: relation,
toItem: toAttribute?.view ?? nil,
attribute: toAttribute?.type ?? .NotAnAttribute,
multiplier: toAttribute?.multiplier ?? multiplier,
constant: toAttribute?.constant ?? constant
)
constraint.priority = priority
return constraint
}
}
| dbe8365840c78a812f1665664511d535 | 31.474576 | 145 | 0.64666 | false | false | false | false |
superk589/CGSSGuide | refs/heads/master | DereGuide/Common/CloudKitSync/FavoriteSongsRemote.swift | mit | 2 | //
// FavoriteSongsRemote.swift
// DereGuide
//
// Created by zzk on 29/09/2017.
// Copyright © 2017 zzk. All rights reserved.
//
import Foundation
import CloudKit
final class FavoriteSongsRemote: Remote {
typealias R = RemoteFavoriteSong
typealias L = FavoriteSong
static var subscriptionID: String {
return "My Favorite Songs"
}
func fetchLatestRecords(completion: @escaping ([R], [RemoteError]) -> ()) {
cloudKitContainer.fetchUserRecordID { userRecordID, error in
guard let userID = userRecordID else {
completion([], [RemoteError.init(cloudKitError: error)].compactMap { $0 })
return
}
let query = CKQuery(recordType: R.recordType, predicate: self.predicateOfUser(userID))
query.sortDescriptors = [self.defaultSortDescriptor]
let op = CKQueryOperation(query: query)
// op.resultsLimit = maximumNumberOfUnits
op.fetchAggregateResults(in: self.cloudKitContainer.publicCloudDatabase, previousResults: [], previousErrors: []) { records, errors in
if errors.count > 0 {
print(errors)
}
let rs = records.map { R(record: $0) }.compactMap { $0 }
completion(rs, errors.map(RemoteError.init).compactMap { $0 })
self.remove(rs.redundants { $0.musicID == $1.musicID }.map { $0.id }, completion: { _, _ in })
}
}
}
}
| ee3533463f7c48e415043b51f4da0349 | 36.7 | 146 | 0.596154 | false | false | false | false |
KyleGoddard/KGFloatingDrawer | refs/heads/master | Pod/Classes/KGDrawerSpringAnimator.swift | mit | 1 | //
// KGDrawerAnimator.swift
// KGDrawerViewController
//
// Created by Kyle Goddard on 2015-02-10.
// Copyright (c) 2015 Kyle Goddard. All rights reserved.
//
import UIKit
open class KGDrawerSpringAnimator: NSObject {
let kKGCenterViewDestinationScale:CGFloat = 0.7
open var animationDelay: TimeInterval = 0.0
open var animationDuration: TimeInterval = 0.7
open var initialSpringVelocity: CGFloat = 9.8 // 9.1 m/s == earth gravity accel.
open var springDamping: CGFloat = 0.8
// TODO: can swift have private functions in a protocol?
fileprivate func applyTransforms(_ side: KGDrawerSide, drawerView: UIView, centerView: UIView) {
let direction = side.rawValue
let sideWidth = drawerView.bounds.width
let centerWidth = centerView.bounds.width
let centerHorizontalOffset = direction * sideWidth
let scaledCenterViewHorizontalOffset = direction * (sideWidth - (centerWidth - kKGCenterViewDestinationScale * centerWidth) / 2.0)
let sideTransform = CGAffineTransform(translationX: centerHorizontalOffset, y: 0.0)
drawerView.transform = sideTransform
let centerTranslate = CGAffineTransform(translationX: scaledCenterViewHorizontalOffset, y: 0.0)
let centerScale = CGAffineTransform(scaleX: kKGCenterViewDestinationScale, y: kKGCenterViewDestinationScale)
centerView.transform = centerScale.concatenating(centerTranslate)
}
fileprivate func resetTransforms(_ views: [UIView]) {
for view in views {
view.transform = CGAffineTransform.identity
}
}
}
extension KGDrawerSpringAnimator: KGDrawerAnimating {
public func openDrawer(_ side: KGDrawerSide, drawerView: UIView, centerView: UIView, animated: Bool, complete: @escaping (Bool) -> Void) {
if (animated) {
UIView.animate(withDuration: animationDuration,
delay: animationDelay,
usingSpringWithDamping: springDamping,
initialSpringVelocity: initialSpringVelocity,
options: UIViewAnimationOptions.curveLinear,
animations: {
self.applyTransforms(side, drawerView: drawerView, centerView: centerView)
}, completion: complete)
} else {
self.applyTransforms(side, drawerView: drawerView, centerView: centerView)
}
}
public func dismissDrawer(_ side: KGDrawerSide, drawerView: UIView, centerView: UIView, animated: Bool, complete: @escaping (Bool) -> Void) {
if (animated) {
UIView.animate(withDuration: animationDuration,
delay: animationDelay,
usingSpringWithDamping: springDamping,
initialSpringVelocity: initialSpringVelocity,
options: UIViewAnimationOptions.curveLinear,
animations: {
self.resetTransforms([drawerView, centerView])
}, completion: complete)
} else {
self.resetTransforms([drawerView, centerView])
}
}
public func willRotateWithDrawerOpen(_ side: KGDrawerSide, drawerView: UIView, centerView: UIView) {
}
public func didRotateWithDrawerOpen(_ side: KGDrawerSide, drawerView: UIView, centerView: UIView) {
UIView.animate(withDuration: animationDuration,
delay: animationDelay,
usingSpringWithDamping: springDamping,
initialSpringVelocity: initialSpringVelocity,
options: UIViewAnimationOptions.curveLinear,
animations: {}, completion: nil )
}
}
| 60ab2f2e1ef150ca186841734081ce9a | 39.51087 | 145 | 0.650926 | false | false | false | false |
myTargetSDK/mytarget-ios | refs/heads/master | myTargetDemoSwift/myTargetDemo/Controllers/InstreamViewController.swift | lgpl-3.0 | 1 | //
// InstreamViewController.swift
// myTargetDemo
//
// Created by Andrey Seredkin on 06/08/2019.
// Copyright © 2019 Mail.Ru Group. All rights reserved.
//
import UIKit
import MyTargetSDK
class InstreamViewController: UIViewController, AdViewController, MTRGInstreamAdDelegate, VideoPlayerViewDelegate
{
var query: [String : String]?
var slotId: UInt?
private var instreamAd: MTRGInstreamAd?
private var notificationView: NotificationView?
private static let mainVideoUrl = "https://r.mradx.net/img/ED/518795.mp4"
private static let mainVideoDuration = 124.055
private let adContainerView = UIView()
private let mainVideoView = VideoPlayerView()
private let videoProgressView = VideoProgressView(duration: InstreamViewController.mainVideoDuration)
private let ctaButton = UIButton()
private let skipButton = UIButton()
private let skipAllButton = UIButton()
private var mainVideoDuration: TimeInterval = InstreamViewController.mainVideoDuration
private var mainVideoPosition: TimeInterval = 0
private var activeMidpoints = [Float]()
private var customMidPoints = [NSNumber]()
private var customMidPointsP = [NSNumber]()
private var midpoints = [NSNumber]()
private var skipAll = false
private var isModalActive = false
private var isMainVideoActive = false
private var isMainVideoStarted = false
private var isMainVideoFinished = false
private var isPrerollActive = false
private var isMidrollActive = false
private var isPauserollActive = false
private var isPostrollActive = false
private var isAdActive: Bool
{
return isPrerollActive || isPrerollActive || isPauserollActive || isPostrollActive
}
private var timer: Timer?
@IBOutlet weak var scrollView: UIScrollView!
@IBOutlet weak var contentView: UIView!
@IBOutlet weak var statusLabel: UILabel!
@IBOutlet weak var containerView: UIView!
@IBOutlet weak var progressView: UIView!
@IBOutlet weak var fullscreenLabel: UILabel!
@IBOutlet weak var qualityLabel: UILabel!
@IBOutlet weak var timeoutLabel: UILabel!
@IBOutlet weak var volumeLabel: UILabel!
@IBOutlet weak var durationLabel: UILabel!
@IBOutlet weak var positionLabel: UILabel!
@IBOutlet weak var dimensionsLabel: UILabel!
@IBOutlet weak var allowPauseLabel: UILabel!
@IBOutlet weak var allowCloseLabel: UILabel!
@IBOutlet weak var closeDelayLabel: UILabel!
@IBOutlet weak var playButton: CustomButton!
@IBOutlet weak var pauseButton: CustomButton!
@IBOutlet weak var resumeButton: CustomButton!
@IBOutlet weak var stopButton: CustomButton!
@IBOutlet weak var loadButton: CustomButton!
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?)
{
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
setupObservers()
}
required init?(coder: NSCoder)
{
super.init(coder: coder)
setupObservers()
}
private func setupObservers()
{
NotificationCenter.default.addObserver(self, selector: #selector(applicationWillResignActive), name: UIApplication.willResignActiveNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(applicationDidBecomeActive), name: UIApplication.didBecomeActiveNotification, object: nil)
}
deinit
{
NotificationCenter.default.removeObserver(self)
}
@objc private func applicationWillResignActive(notification: Notification)
{
doPause()
}
@objc private func applicationDidBecomeActive(notification: Notification)
{
doResume()
}
override func viewDidLoad()
{
super.viewDidLoad()
navigationItem.title = "Instream"
notificationView = NotificationView.create(view: view)
notificationView?.navigationBarHeight = navigationController?.navigationBar.frame.height ?? 0.0
mainVideoView.isHidden = true
mainVideoView.delegate = self
mainVideoView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
mainVideoView.frame = containerView.bounds
containerView.addSubview(mainVideoView)
ctaButton.isHidden = true
skipButton.isHidden = true
skipAllButton.isHidden = true
ctaButton.addTarget(self, action: #selector(ctaButtonClick), for: .touchUpInside)
ctaButton.translatesAutoresizingMaskIntoConstraints = false
configureButton(ctaButton, title: "Proceed")
containerView.addSubview(ctaButton)
skipButton.addTarget(self, action: #selector(skipButtonClick), for: .touchUpInside)
skipButton.translatesAutoresizingMaskIntoConstraints = false
configureButton(skipButton, title: "Skip")
containerView.addSubview(skipButton)
skipAllButton.addTarget(self, action: #selector(skipAllButtonClick), for: .touchUpInside)
skipAllButton.translatesAutoresizingMaskIntoConstraints = false
configureButton(skipAllButton, title: "Skip All")
containerView.addSubview(skipAllButton)
videoProgressView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
videoProgressView.frame = progressView.bounds
progressView.addSubview(videoProgressView)
}
override func viewWillAppear(_ animated: Bool)
{
super.viewWillAppear(animated)
notificationView?.view = view
var contentSize = scrollView.contentSize
contentSize.height = contentView.frame.height
scrollView.contentSize = contentSize
}
override func viewWillDisappear(_ animated: Bool)
{
super.viewWillDisappear(animated)
guard !isModalActive else { return }
doStop()
}
@IBAction func load(_ sender: CustomButton)
{
doLoad()
}
@IBAction func play(_ sender: CustomButton)
{
doPlay()
}
@IBAction func pause(_ sender: CustomButton)
{
doPause()
}
@IBAction func resume(_ sender: CustomButton)
{
doResume()
}
@IBAction func stop(_ sender: CustomButton)
{
doStop()
}
// MARK: - private
private func configureMidrolls()
{
guard let instreamAd = instreamAd else { return }
if !customMidPoints.isEmpty
{
instreamAd.configureMidpoints(customMidPoints, forVideoDuration: InstreamViewController.mainVideoDuration)
}
else if !customMidPointsP.isEmpty
{
instreamAd.configureMidpointsP(customMidPoints, forVideoDuration: InstreamViewController.mainVideoDuration)
}
else
{
instreamAd.configureMidpoints(forVideoDuration: InstreamViewController.mainVideoDuration)
}
}
private func setupButtons()
{
guard let adPlayerView = instreamAd?.player?.adPlayerView else { return }
let width: CGFloat = 75.0
let height: CGFloat = 30.0
let insets = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
ctaButton.removeFromSuperview()
skipButton.removeFromSuperview()
skipAllButton.removeFromSuperview()
adPlayerView.addSubview(ctaButton)
adPlayerView.addSubview(skipButton)
adPlayerView.addSubview(skipAllButton)
let views: [String : Any] = ["ctaButton" : ctaButton, "skipButton" : skipButton, "skipAllButton" : skipAllButton]
let metrics: [String : Any] = ["top" : insets.top, "bottom" : insets.bottom, "left" : insets.left, "right" : insets.right, "width" : width, "height" : height]
adPlayerView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-left-[ctaButton]-(>=right)-|", options: [], metrics: metrics, views: views))
adPlayerView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-top-[ctaButton(height)]", options: [], metrics: metrics, views: views))
adPlayerView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-left-[skipButton(width)]", options: [], metrics: metrics, views: views))
adPlayerView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:[skipButton(height)]-bottom-|", options: [], metrics: metrics, views: views))
adPlayerView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:[skipAllButton(width)]-right-|", options: [], metrics: metrics, views: views))
adPlayerView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:[skipAllButton(height)]-bottom-|", options: [], metrics: metrics, views: views))
}
private func configureButton(_ button: UIButton, title: String)
{
button.setTitle(title, for: .normal)
button.setTitleColor(UIColor.foregroundColor(), for: .normal)
button.setTitleColor(UIColor.disabledColor(), for: .disabled)
button.titleLabel?.font = UIFont.systemFont(ofSize: 12)
button.titleLabel?.lineBreakMode = .byTruncatingTail
button.contentEdgeInsets = UIEdgeInsets(top: 5, left: 10, bottom: 5, right: 10)
button.backgroundColor = UIColor.backgroundColor().withAlphaComponent(0.3)
button.layer.borderColor = UIColor.foregroundColor().cgColor
button.layer.borderWidth = 1
button.layer.cornerRadius = 5
}
// MARK: - actions
private func doLoad()
{
if isMainVideoStarted
{
mainVideoView.stop()
videoProgressView.position = 0
}
if let instreamAd = instreamAd
{
instreamAd.stop()
instreamAd.player?.adPlayerView.removeFromSuperview()
self.instreamAd = nil
}
let slotId = self.slotId ?? Slot.instreamVideo.rawValue
instreamAd = MTRGInstreamAd(slotId: slotId)
guard let instreamAd = instreamAd else { return }
instreamAd.useDefaultPlayer()
instreamAd.delegate = self
mainVideoPosition = 0
isMainVideoStarted = false
isMainVideoActive = false
isMainVideoFinished = false
isModalActive = false
isPrerollActive = false
isMidrollActive = false
isPostrollActive = false
isPauserollActive = false
skipAll = false
ctaButton.removeFromSuperview()
skipButton.removeFromSuperview()
skipAllButton.removeFromSuperview()
statusLabel.text = "Loading..."
loadButton.isEnabled = false
configureMidrolls()
instreamAd.customParams.age = 100
instreamAd.customParams.gender = MTRGGenderUnknown
self.setQueryParams(for: instreamAd)
instreamAd.load()
}
private func doPlay()
{
if isMainVideoStarted && isMainVideoActive
{
playMainVideo()
}
else
{
playPreroll()
}
}
private func doPause()
{
if isMainVideoStarted && isMainVideoActive
{
playPauseroll()
}
else if isAdActive, let instreamAd = instreamAd
{
instreamAd.pause()
}
}
private func doResume()
{
if isMainVideoStarted && isMainVideoActive
{
mainVideoView.resume()
}
else if isAdActive, let instreamAd = instreamAd
{
instreamAd.resume()
}
}
private func doStop()
{
if isMainVideoStarted && isMainVideoActive
{
mainVideoView.stop()
videoProgressView.position = 0
}
else if isAdActive, let instreamAd = instreamAd
{
instreamAd.stop()
}
timerStop()
}
private func doFullscreen(isFullscreen: Bool)
{
guard let instreamAd = instreamAd else { return }
instreamAd.fullscreen = isFullscreen
}
private func doSkip()
{
guard isAdActive, let instreamAd = instreamAd else { return }
instreamAd.skipBanner()
}
private func doSkipAll()
{
guard isAdActive, let instreamAd = instreamAd else { return }
activeMidpoints.removeAll()
skipAll = true
instreamAd.skip()
}
private func doBannerClick()
{
guard isAdActive, let instreamAd = instreamAd else { return }
instreamAd.handleClick(with: self)
}
// MARK: - video
private func playMainVideo()
{
guard let url = URL(string: InstreamViewController.mainVideoUrl) else { return }
setVisibility(mainPlayerVisible: true, adPlayerVisible: false)
statusLabel.text = "Main video"
isMainVideoActive = true
mainVideoView.isHidden = false
mainVideoView.start(with: url, position: mainVideoPosition)
}
private func playPreroll()
{
guard let instreamAd = instreamAd else { return }
isPrerollActive = true
statusLabel.text = "Preroll"
setVisibility(mainPlayerVisible: false, adPlayerVisible: true)
instreamAd.startPreroll()
}
private func playPauseroll()
{
guard let instreamAd = instreamAd else { return }
mainVideoPosition = mainVideoView.currentTime
mainVideoView.pause()
setVisibility(mainPlayerVisible: false, adPlayerVisible: true)
isPauserollActive = true
isMainVideoActive = false
statusLabel.text = "Pauseroll"
instreamAd.startPauseroll()
}
private func playMidroll(_ midpoint: Float)
{
guard let instreamAd = instreamAd else { return }
mainVideoPosition = mainVideoView.currentTime
mainVideoView.pause()
setVisibility(mainPlayerVisible: false, adPlayerVisible: true)
isMidrollActive = true
isMainVideoActive = false
statusLabel.text = "Midroll"
instreamAd.startMidroll(withPoint: NSNumber(value: midpoint))
}
private func playPostroll()
{
guard let instreamAd = instreamAd else { return }
isPostrollActive = true
statusLabel.text = "Postroll"
setVisibility(mainPlayerVisible: false, adPlayerVisible: true)
instreamAd.startPostroll()
}
private func setVisibility(mainPlayerVisible: Bool, adPlayerVisible: Bool)
{
mainVideoView.isHidden = !mainPlayerVisible
ctaButton.isHidden = !adPlayerVisible
skipButton.isHidden = !adPlayerVisible
skipAllButton.isHidden = !adPlayerVisible
videoProgressView.isHidden = !mainPlayerVisible && !adPlayerVisible
guard let instreamAd = instreamAd, let player = instreamAd.player else { return }
player.adPlayerView.isHidden = !adPlayerVisible
}
// MARK: - main video
private func midpoint(for position: TimeInterval) -> Float?
{
guard !activeMidpoints.isEmpty, let midpoint = activeMidpoints.first else { return nil }
guard position >= Double(midpoint) else { return nil }
activeMidpoints.removeFirst()
return midpoint
}
private func updateStateByTimer()
{
guard isMainVideoActive else { return }
let currentTime = mainVideoView.currentTime
if currentTime > InstreamViewController.mainVideoDuration
{
timerStop()
mainVideoView.stop()
return
}
videoProgressView.position = currentTime
if let midpoint = midpoint(for: currentTime)
{
playMidroll(midpoint)
timerStop()
}
else
{
timerStart()
}
}
// MARK: - timer
private func timerStart()
{
timerStop()
timer = Timer.scheduledTimer(timeInterval: 0.1, target: self, selector: #selector(timerFire), userInfo: nil, repeats: false)
}
private func timerStop()
{
guard let timer = timer else { return }
if timer.isValid
{
timer.invalidate()
}
self.timer = nil
}
@objc private func timerFire()
{
timerStop()
updateStateByTimer()
}
// MARK: - buttons
@objc private func ctaButtonClick()
{
doBannerClick()
}
@objc private func skipButtonClick()
{
doSkip()
}
@objc private func skipAllButtonClick()
{
doSkipAll()
}
// MARK: - VideoPlayerViewDelegate
func onVideoStarted(url: URL)
{
guard isMainVideoActive else { return }
isMainVideoStarted = true
mainVideoDuration = mainVideoView.duration
timerStart()
}
func onVideoComplete()
{
guard isMainVideoActive else { return }
timerStop()
isMainVideoActive = false
if skipAll
{
statusLabel.text = "Complete"
setVisibility(mainPlayerVisible: false, adPlayerVisible: false)
}
else
{
playPostroll()
}
}
func onVideoFinished(error: String)
{
notificationView?.showMessage("Error: \(error)")
isMainVideoActive = false
}
// MARK: - MTRGInstreamAdDelegate
func onLoad(with instreamAd: MTRGInstreamAd)
{
loadButton.isEnabled = true
notificationView?.showMessage("onLoad() called")
statusLabel.text = "Ready"
midpoints = instreamAd.midpoints
activeMidpoints.removeAll()
if !midpoints.isEmpty
{
activeMidpoints.append(contentsOf: midpoints.map({ return $0.floatValue }))
}
videoProgressView.points = activeMidpoints
qualityLabel.text = "\(instreamAd.videoQuality)"
timeoutLabel.text = "\(instreamAd.loadingTimeout)"
volumeLabel.text = String(format: "%.2f", instreamAd.volume)
fullscreenLabel.text = instreamAd.fullscreen ? "true" : "false"
guard let adPlayerView = instreamAd.player?.adPlayerView else { return }
adPlayerView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
adPlayerView.frame = containerView.bounds
containerView.addSubview(adPlayerView)
}
func onNoAd(withReason reason: String, instreamAd: MTRGInstreamAd)
{
loadButton.isEnabled = true
notificationView?.showMessage("onNoAd(\(reason)) called")
statusLabel.text = "No ad"
self.instreamAd = nil
playMainVideo()
}
func onError(withReason reason: String, instreamAd: MTRGInstreamAd)
{
notificationView?.showMessage("onError(\(reason)) called")
statusLabel.text = "Error: \(reason)"
playMainVideo()
}
func onBannerStart(_ banner: MTRGInstreamAdBanner, instreamAd: MTRGInstreamAd)
{
notificationView?.showMessage("onBannerStart() called")
ctaButton.setTitle(banner.ctaText, for: .normal)
setupButtons()
durationLabel.text = String(format: "%.2f", banner.duration)
positionLabel.text = "0"
dimensionsLabel.text = String(format: "%.fx%.f", banner.size.width, banner.size.height)
allowPauseLabel.text = banner.allowPause ? "true" : "false"
allowCloseLabel.text = banner.allowClose ? "true" : "false"
closeDelayLabel.text = String(format: "%.2f", banner.allowCloseDelay)
}
func onBannerComplete(_ banner: MTRGInstreamAdBanner, instreamAd: MTRGInstreamAd)
{
notificationView?.showMessage("onBannerComplete() called")
}
func onBannerTimeLeftChange(_ timeLeft: TimeInterval, duration: TimeInterval, instreamAd: MTRGInstreamAd)
{
positionLabel.text = String(format: "%.2f", duration - timeLeft)
print("onBannerTimeLeftChange(" + String(format: "timeLeft: %.2f", timeLeft) + ", " + String(format: "duration: %.2f", duration) + ") called")
}
func onComplete(withSection section: String, instreamAd: MTRGInstreamAd)
{
notificationView?.showMessage("onComplete() called")
durationLabel.text = "n/a"
positionLabel.text = "n/a"
dimensionsLabel.text = "n/a"
allowPauseLabel.text = "n/a"
allowCloseLabel.text = "n/a"
closeDelayLabel.text = "n/a"
if isPrerollActive
{
isPrerollActive = false
playMainVideo()
}
if isMidrollActive
{
isMidrollActive = false
timerStart()
playMainVideo()
}
if isPauserollActive
{
isPauserollActive = false
timerStart()
playMainVideo()
}
if isPostrollActive
{
isPostrollActive = false
notificationView?.showMessage("Complete")
setVisibility(mainPlayerVisible: false, adPlayerVisible: false)
}
}
func onShowModal(with instreamAd: MTRGInstreamAd)
{
isModalActive = true
doPause()
notificationView?.showMessage("onShowModal() called")
}
func onDismissModal(with instreamAd: MTRGInstreamAd)
{
isModalActive = false
doResume()
notificationView?.showMessage("onDismissModal() called")
}
func onLeaveApplication(with instreamAd: MTRGInstreamAd)
{
notificationView?.showMessage("onLeaveApplication() called")
}
}
| 922132486f0a28ddcfbb9d814a9f1a8f | 25.922515 | 162 | 0.750801 | false | false | false | false |
druva/dSwiftUtils | refs/heads/master | Shared/IntExtensions.swift | mit | 1 | //
// IntExtensions.swift
// MobiCoreFramework
//
// Created by Druva Yarlagadda on 4/26/18.
// Copyright © 2018 Druva Yarlagadda. All rights reserved.
//
import Foundation
extension Int {
/**
Generates Random Number from the given range
- parameter min: default value 0
- parameter max: provide integer
- returns: Integer between given range
*/
public static func random(min: Int = 0, max: Int) -> Int {
return Int(arc4random_uniform(UInt32((max - min) + 1))) + min
}
/**
Checks if given number is Even or not
- returns: returns true of false
*/
public var isEven: Bool {
return (self % 2) == 0
}
/**
Checks if given number is Odd or not
- returns: returns true of false
*/
public var isOdd: Bool {
return (self % 2) == 1
}
}
| cdb5b82922802be0f1ab9db9eb76b23d | 20.512195 | 69 | 0.577098 | false | false | false | false |
uasys/swift | refs/heads/master | stdlib/public/core/Reverse.swift | apache-2.0 | 1 | //===--- Reverse.swift - Sequence and collection reversal -----------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
extension MutableCollection where Self : BidirectionalCollection {
/// Reverses the elements of the collection in place.
///
/// The following example reverses the elements of an array of characters:
///
/// var characters: [Character] = ["C", "a", "f", "é"]
/// characters.reverse()
/// print(characters)
/// // Prints "["é", "f", "a", "C"]
///
/// - Complexity: O(*n*), where *n* is the number of elements in the
/// collection.
public mutating func reverse() {
if isEmpty { return }
var f = startIndex
var l = index(before: endIndex)
while f < l {
swapAt(f, l)
formIndex(after: &f)
formIndex(before: &l)
}
}
}
/// An iterator that can be much faster than the iterator of a reversed slice.
// TODO: See about using this in more places
@_fixed_layout
public struct _ReverseIndexingIterator<
Elements : BidirectionalCollection
> : IteratorProtocol, Sequence {
@_inlineable
@inline(__always)
/// Creates an iterator over the given collection.
public /// @testable
init(_elements: Elements, _position: Elements.Index) {
self._elements = _elements
self._position = _position
}
@_inlineable
@inline(__always)
public mutating func next() -> Elements.Element? {
guard _fastPath(_position != _elements.startIndex) else { return nil }
_position = _elements.index(before: _position)
return _elements[_position]
}
@_versioned
internal let _elements: Elements
@_versioned
internal var _position: Elements.Index
}
// FIXME(ABI)#59 (Conditional Conformance): we should have just one type,
// `ReversedCollection`, that has conditional conformances to
// `RandomAccessCollection`, and possibly `MutableCollection` and
// `RangeReplaceableCollection`.
// rdar://problem/17144340
// FIXME: swift-3-indexing-model - should gyb ReversedXxx & ReversedRandomAccessXxx
/// An index that traverses the same positions as an underlying index,
/// with inverted traversal direction.
@_fixed_layout
public struct ReversedIndex<Base : Collection> : Comparable {
/// Creates a new index into a reversed collection for the position before
/// the specified index.
///
/// When you create an index into a reversed collection using `base`, an
/// index from the underlying collection, the resulting index is the
/// position of the element *before* the element referenced by `base`. The
/// following example creates a new `ReversedIndex` from the index of the
/// `"a"` character in a string's character view.
///
/// let name = "Horatio"
/// let aIndex = name.index(of: "a")!
/// // name[aIndex] == "a"
///
/// let reversedName = name.reversed()
/// let i = ReversedIndex<String>(aIndex)
/// // reversedName[i] == "r"
///
/// The element at the position created using `ReversedIndex<...>(aIndex)` is
/// `"r"`, the character before `"a"` in the `name` string.
///
/// - Parameter base: The position after the element to create an index for.
@_inlineable
public init(_ base: Base.Index) {
self.base = base
}
/// The position after this position in the underlying collection.
///
/// To find the position that corresponds with this index in the original,
/// underlying collection, use that collection's `index(before:)` method
/// with the `base` property.
///
/// The following example declares a function that returns the index of the
/// last even number in the passed array, if one is found. First, the
/// function finds the position of the last even number as a `ReversedIndex`
/// in a reversed view of the array of numbers. Next, the function calls the
/// array's `index(before:)` method to return the correct position in the
/// passed array.
///
/// func indexOfLastEven(_ numbers: [Int]) -> Int? {
/// let reversedNumbers = numbers.reversed()
/// guard let i = reversedNumbers.index(where: { $0 % 2 == 0 })
/// else { return nil }
///
/// return numbers.index(before: i.base)
/// }
///
/// let numbers = [10, 20, 13, 19, 30, 52, 17, 40, 51]
/// if let lastEven = indexOfLastEven(numbers) {
/// print("Last even number: \(numbers[lastEven])")
/// }
/// // Prints "Last even number: 40"
public let base: Base.Index
@_inlineable
public static func == (
lhs: ReversedIndex<Base>,
rhs: ReversedIndex<Base>
) -> Bool {
return lhs.base == rhs.base
}
@_inlineable
public static func < (
lhs: ReversedIndex<Base>,
rhs: ReversedIndex<Base>
) -> Bool {
// Note ReversedIndex has inverted logic compared to base Base.Index
return lhs.base > rhs.base
}
}
/// A collection that presents the elements of its base collection
/// in reverse order.
///
/// - Note: This type is the result of `x.reversed()` where `x` is a
/// collection having bidirectional indices.
///
/// The `reversed()` method is always lazy when applied to a collection
/// with bidirectional indices, but does not implicitly confer
/// laziness on algorithms applied to its result. In other words, for
/// ordinary collections `c` having bidirectional indices:
///
/// * `c.reversed()` does not create new storage
/// * `c.reversed().map(f)` maps eagerly and returns a new array
/// * `c.lazy.reversed().map(f)` maps lazily and returns a `LazyMapCollection`
///
/// - See also: `ReversedRandomAccessCollection`
@_fixed_layout
public struct ReversedCollection<
Base : BidirectionalCollection
> : BidirectionalCollection {
/// Creates an instance that presents the elements of `base` in
/// reverse order.
///
/// - Complexity: O(1)
@_versioned
@_inlineable
internal init(_base: Base) {
self._base = _base
}
/// A type that represents a valid position in the collection.
///
/// Valid indices consist of the position of every element and a
/// "past the end" position that's not valid for use as a subscript.
public typealias Index = ReversedIndex<Base>
public typealias IndexDistance = Base.IndexDistance
@_fixed_layout
public struct Iterator : IteratorProtocol, Sequence {
@_inlineable
@inline(__always)
public /// @testable
init(elements: Base, endPosition: Base.Index) {
self._elements = elements
self._position = endPosition
}
@_inlineable
@inline(__always)
public mutating func next() -> Base.Iterator.Element? {
guard _fastPath(_position != _elements.startIndex) else { return nil }
_position = _elements.index(before: _position)
return _elements[_position]
}
@_versioned
internal let _elements: Base
@_versioned
internal var _position: Base.Index
}
@_inlineable
@inline(__always)
public func makeIterator() -> Iterator {
return Iterator(elements: _base, endPosition: _base.endIndex)
}
@_inlineable
public var startIndex: Index {
return ReversedIndex(_base.endIndex)
}
@_inlineable
public var endIndex: Index {
return ReversedIndex(_base.startIndex)
}
@_inlineable
public func index(after i: Index) -> Index {
return ReversedIndex(_base.index(before: i.base))
}
@_inlineable
public func index(before i: Index) -> Index {
return ReversedIndex(_base.index(after: i.base))
}
@_inlineable
public func index(_ i: Index, offsetBy n: IndexDistance) -> Index {
// FIXME: swift-3-indexing-model: `-n` can trap on Int.min.
return ReversedIndex(_base.index(i.base, offsetBy: -n))
}
@_inlineable
public func index(
_ i: Index, offsetBy n: IndexDistance, limitedBy limit: Index
) -> Index? {
// FIXME: swift-3-indexing-model: `-n` can trap on Int.min.
return _base.index(i.base, offsetBy: -n, limitedBy: limit.base).map { ReversedIndex($0) }
}
@_inlineable
public func distance(from start: Index, to end: Index) -> IndexDistance {
return _base.distance(from: end.base, to: start.base)
}
@_inlineable
public subscript(position: Index) -> Base.Element {
return _base[_base.index(before: position.base)]
}
@_inlineable
public subscript(bounds: Range<Index>) -> BidirectionalSlice<ReversedCollection> {
return BidirectionalSlice(base: self, bounds: bounds)
}
public let _base: Base
}
/// An index that traverses the same positions as an underlying index,
/// with inverted traversal direction.
@_fixed_layout
public struct ReversedRandomAccessIndex<
Base : RandomAccessCollection
> : Comparable {
/// Creates a new index into a reversed collection for the position before
/// the specified index.
///
/// When you create an index into a reversed collection using the index
/// passed as `base`, an index from the underlying collection, the resulting
/// index is the position of the element *before* the element referenced by
/// `base`. The following example creates a new `ReversedIndex` from the
/// index of the `"a"` character in a string's character view.
///
/// let name = "Horatio"
/// let aIndex = name.index(of: "a")!
/// // name[aIndex] == "a"
///
/// let reversedName = name.reversed()
/// let i = ReversedIndex<String>(aIndex)
/// // reversedName[i] == "r"
///
/// The element at the position created using `ReversedIndex<...>(aIndex)` is
/// `"r"`, the character before `"a"` in the `name` string. Viewed from the
/// perspective of the `reversedCharacters` collection, of course, `"r"` is
/// the element *after* `"a"`.
///
/// - Parameter base: The position after the element to create an index for.
@_inlineable
public init(_ base: Base.Index) {
self.base = base
}
/// The position after this position in the underlying collection.
///
/// To find the position that corresponds with this index in the original,
/// underlying collection, use that collection's `index(before:)` method
/// with this index's `base` property.
///
/// The following example declares a function that returns the index of the
/// last even number in the passed array, if one is found. First, the
/// function finds the position of the last even number as a `ReversedIndex`
/// in a reversed view of the array of numbers. Next, the function calls the
/// array's `index(before:)` method to return the correct position in the
/// passed array.
///
/// func indexOfLastEven(_ numbers: [Int]) -> Int? {
/// let reversedNumbers = numbers.reversed()
/// guard let i = reversedNumbers.index(where: { $0 % 2 == 0 })
/// else { return nil }
///
/// return numbers.index(before: i.base)
/// }
///
/// let numbers = [10, 20, 13, 19, 30, 52, 17, 40, 51]
/// if let lastEven = indexOfLastEven(numbers) {
/// print("Last even number: \(numbers[lastEven])")
/// }
/// // Prints "Last even number: 40"
public let base: Base.Index
@_inlineable
public static func == (
lhs: ReversedRandomAccessIndex<Base>,
rhs: ReversedRandomAccessIndex<Base>
) -> Bool {
return lhs.base == rhs.base
}
@_inlineable
public static func < (
lhs: ReversedRandomAccessIndex<Base>,
rhs: ReversedRandomAccessIndex<Base>
) -> Bool {
// Note ReversedRandomAccessIndex has inverted logic compared to base Base.Index
return lhs.base > rhs.base
}
}
/// A collection that presents the elements of its base collection
/// in reverse order.
///
/// - Note: This type is the result of `x.reversed()` where `x` is a
/// collection having random access indices.
/// - See also: `ReversedCollection`
@_fixed_layout
public struct ReversedRandomAccessCollection<
Base : RandomAccessCollection
> : RandomAccessCollection {
// FIXME: swift-3-indexing-model: tests for ReversedRandomAccessIndex and
// ReversedRandomAccessCollection.
/// Creates an instance that presents the elements of `base` in
/// reverse order.
///
/// - Complexity: O(1)
@_versioned
@_inlineable
internal init(_base: Base) {
self._base = _base
}
/// A type that represents a valid position in the collection.
///
/// Valid indices consist of the position of every element and a
/// "past the end" position that's not valid for use as a subscript.
public typealias Index = ReversedRandomAccessIndex<Base>
public typealias IndexDistance = Base.IndexDistance
/// A type that provides the sequence's iteration interface and
/// encapsulates its iteration state.
public typealias Iterator = IndexingIterator<
ReversedRandomAccessCollection
>
@_inlineable
public var startIndex: Index {
return ReversedRandomAccessIndex(_base.endIndex)
}
@_inlineable
public var endIndex: Index {
return ReversedRandomAccessIndex(_base.startIndex)
}
@_inlineable
public func index(after i: Index) -> Index {
return ReversedRandomAccessIndex(_base.index(before: i.base))
}
@_inlineable
public func index(before i: Index) -> Index {
return ReversedRandomAccessIndex(_base.index(after: i.base))
}
@_inlineable
public func index(_ i: Index, offsetBy n: IndexDistance) -> Index {
// FIXME: swift-3-indexing-model: `-n` can trap on Int.min.
// FIXME: swift-3-indexing-model: tests.
return ReversedRandomAccessIndex(_base.index(i.base, offsetBy: -n))
}
@_inlineable
public func index(
_ i: Index, offsetBy n: IndexDistance, limitedBy limit: Index
) -> Index? {
// FIXME: swift-3-indexing-model: `-n` can trap on Int.min.
// FIXME: swift-3-indexing-model: tests.
return _base.index(i.base, offsetBy: -n, limitedBy: limit.base).map { Index($0) }
}
@_inlineable
public func distance(from start: Index, to end: Index) -> IndexDistance {
// FIXME: swift-3-indexing-model: tests.
return _base.distance(from: end.base, to: start.base)
}
@_inlineable
public subscript(position: Index) -> Base.Element {
return _base[_base.index(before: position.base)]
}
// FIXME: swift-3-indexing-model: the rest of methods.
public let _base: Base
}
extension BidirectionalCollection {
/// Returns a view presenting the elements of the collection in reverse
/// order.
///
/// You can reverse a collection without allocating new space for its
/// elements by calling this `reversed()` method. A `ReversedCollection`
/// instance wraps an underlying collection and provides access to its
/// elements in reverse order. This example prints the characters of a
/// string in reverse order:
///
/// let word = "Backwards"
/// for char in word.reversed() {
/// print(char, terminator: "")
/// }
/// // Prints "sdrawkcaB"
///
/// If you need a reversed collection of the same type, you may be able to
/// use the collection's sequence-based or collection-based initializer. For
/// example, to get the reversed version of a string, reverse its
/// characters and initialize a new `String` instance from the result.
///
/// let reversedWord = String(word.reversed())
/// print(reversedWord)
/// // Prints "sdrawkcaB"
///
/// - Complexity: O(1)
@_inlineable
public func reversed() -> ReversedCollection<Self> {
return ReversedCollection(_base: self)
}
}
extension RandomAccessCollection {
/// Returns a view presenting the elements of the collection in reverse
/// order.
///
/// You can reverse a collection without allocating new space for its
/// elements by calling this `reversed()` method. A
/// `ReversedRandomAccessCollection` instance wraps an underlying collection
/// and provides access to its elements in reverse order. This example
/// prints the elements of an array in reverse order:
///
/// let numbers = [3, 5, 7]
/// for number in numbers.reversed() {
/// print(number)
/// }
/// // Prints "7"
/// // Prints "5"
/// // Prints "3"
///
/// If you need a reversed collection of the same type, you may be able to
/// use the collection's sequence-based or collection-based initializer. For
/// example, to get the reversed version of an array, initialize a new
/// `Array` instance from the result of this `reversed()` method.
///
/// let reversedNumbers = Array(numbers.reversed())
/// print(reversedNumbers)
/// // Prints "[7, 5, 3]"
///
/// - Complexity: O(1)
@_inlineable
public func reversed() -> ReversedRandomAccessCollection<Self> {
return ReversedRandomAccessCollection(_base: self)
}
}
extension LazyCollectionProtocol
where
Self : BidirectionalCollection,
Elements : BidirectionalCollection {
/// Returns the elements of the collection in reverse order.
///
/// - Complexity: O(1)
@_inlineable
public func reversed() -> LazyBidirectionalCollection<
ReversedCollection<Elements>
> {
return ReversedCollection(_base: elements).lazy
}
}
extension LazyCollectionProtocol
where
Self : RandomAccessCollection,
Elements : RandomAccessCollection {
/// Returns the elements of the collection in reverse order.
///
/// - Complexity: O(1)
@_inlineable
public func reversed() -> LazyRandomAccessCollection<
ReversedRandomAccessCollection<Elements>
> {
return ReversedRandomAccessCollection(_base: elements).lazy
}
}
// ${'Local Variables'}:
// eval: (read-only-mode 1)
// End:
| 349de9c5bc8f23594c389c3b39bfeca9 | 32.031481 | 93 | 0.662051 | false | false | false | false |
mrackwitz/SwiftHamcrest | refs/heads/master | HamcrestTests/MatcherMocks.swift | bsd-3-clause | 2 | import XCTest
import Hamcrest
func succeedingMatcher<T: Equatable>(expectingValue: T, description: String = "description",
file: String = __FILE__, line: UInt = __LINE__) -> Matcher<T> {
return Matcher<T>(description) {
(value: T) -> Bool in
XCTAssertEqual(value, expectingValue, file: file, line: line)
return true
}
}
func succeedingMatcher<T>(type: T.Type = T.self, description: String = "description")
-> Matcher<T> {
return Matcher<T>(description) {value in true}
}
func failingMatcher<T>(type: T.Type = T.self, description: String = "description",
mismatchDescription: String? = nil) -> Matcher<T> {
return Matcher<T>(description) {value in .Mismatch(mismatchDescription)}
}
func failingMatcherWithMismatchDescription<T>(type: T.Type = T.self,
description: String = "description") -> Matcher<T> {
return failingMatcher(type: type, description: description, mismatchDescription: "mismatch description")
} | a797ba1902fe1e2b9a9a0b81f6955f91 | 35.931034 | 108 | 0.629907 | false | false | false | false |
ello/ello-ios | refs/heads/master | Specs/Networking/MultipartRequestBuilderSpec.swift | mit | 1 | ////
/// MultipartRequestBuilderSpec.swift
//
@testable import Ello
import Quick
import Nimble
class MultipartRequestBuilderSpec: QuickSpec {
override func spec() {
let url = URL(string: "http://ello.co")!
var request = URLRequest(
url: url,
cachePolicy: .reloadIgnoringLocalCacheData,
timeoutInterval: 10.0
)
var content = ""
var builder: MultipartRequestBuilder!
describe("MultipartRequestBuilder") {
beforeEach {
builder = MultipartRequestBuilder(url: url, capacity: 100)
builder.addParam("foo", value: "bar")
builder.addParam("baz", value: "a\nb\nc")
request = builder.buildRequest()
content = String(data: request.httpBody!, encoding: String.Encoding.utf8) ?? ""
}
it("can build a multipart request") {
let boundaryConstant = builder.boundaryConstant
var expected = ""
expected += "--\(boundaryConstant)\r\n"
expected += "Content-Disposition: form-data; name=\"foo\"\r\n"
expected += "\r\n"
expected += "bar\r\n"
expected += "--\(boundaryConstant)\r\n"
expected += "Content-Disposition: form-data; name=\"baz\"\r\n"
expected += "\r\n"
expected += "a\nb\nc\r\n"
expected += "--\(boundaryConstant)--\r\n"
expect(content).to(equal(expected))
}
}
}
}
| 6c70ca7dd9bd9d60c56489c5326bf10c | 32.595745 | 95 | 0.523749 | false | false | false | false |
cocoaswifty/V2EX | refs/heads/master | V2EX/UIImageView.swift | apache-2.0 | 1 | //
// UIImageView.swift
// EngineerMaster_iOS_APP
//
// Created by tracetw on 2016/3/24.
// Copyright © 2016年 mycena. All rights reserved.
//
import UIKit
extension UIImageView {
func setRandomDownloadImage(_ width: Int, height: Int) {
if self.image != nil {
self.alpha = 1
return
}
self.alpha = 0
let url = URL(string: "https://ssl.webpack.de/lorempixel.com/\(width)/\(height)/")!
let configuration = URLSessionConfiguration.default
configuration.timeoutIntervalForRequest = 15
configuration.timeoutIntervalForResource = 15
configuration.requestCachePolicy = NSURLRequest.CachePolicy.reloadIgnoringLocalCacheData
let session = URLSession(configuration: configuration)
let task = session.dataTask(with: url, completionHandler: { (data: Data?, response: URLResponse?, error: NSError?) -> Void in
if error != nil {
return
}
if let response = response as? HTTPURLResponse {
if response.statusCode / 100 != 2 {
return
}
if let data = data, let image = UIImage(data: data) {
DispatchQueue.main.async(execute: { () -> Void in
self.image = image
UIView.animate(withDuration: 0.3, animations: { () -> Void in
self.alpha = 1
}, completion: { (finished: Bool) -> Void in
})
})
}
}
} as! (Data?, URLResponse?, Error?) -> Void)
task.resume()
}
func clipParallaxEffect(_ baseImage: UIImage?, screenSize: CGSize, displayHeight: CGFloat) {
if let baseImage = baseImage {
if displayHeight < 0 {
return
}
let aspect: CGFloat = screenSize.width / screenSize.height
let imageSize = baseImage.size
let imageScale: CGFloat = imageSize.height / screenSize.height
let cropWidth: CGFloat = floor(aspect < 1.0 ? imageSize.width * aspect : imageSize.width)
let cropHeight: CGFloat = floor(displayHeight * imageScale)
let left: CGFloat = (imageSize.width - cropWidth) / 2
let top: CGFloat = (imageSize.height - cropHeight) / 2
let trimRect : CGRect = CGRect(x: left, y: top, width: cropWidth, height: cropHeight)
self.image = baseImage.trim(trimRect: trimRect)
self.frame = CGRect(x: 0, y: 0, width: screenSize.width, height: displayHeight)
}
}
func downloadedFrom(link:String, contentMode mode: UIViewContentMode) {
guard
let url = URL(string: link)
else {return}
contentMode = mode
URLSession.shared.dataTask(with: url, completionHandler: { (data, response, error) -> Void in
guard
let httpURLResponse = response as? HTTPURLResponse , httpURLResponse.statusCode == 200,
let mimeType = response?.mimeType , mimeType.hasPrefix("image"),
let data = data , error == nil,
let image = UIImage(data: data)
else { return }
DispatchQueue.main.async { () -> Void in
self.image = image
}
}).resume()
}
}
| 2f8b54346803170621fc0ce653b04b88 | 37.318681 | 133 | 0.543734 | false | true | false | false |
apple/swift-nio-http2 | refs/heads/main | Sources/NIOHTTP2/ConnectionStateMachine/StateMachineResult.swift | apache-2.0 | 1 | //===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2017-2018 Apple Inc. and the SwiftNIO project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
/// The event triggered by this state transition attempt.
///
/// All state transition attempts trigger one of three results. Firstly, they succeed, in which case
/// the frame may be passed on (either outwards, to the serializer, or inwards, to the user).
/// Alternatively, the frame itself may trigger an error.
///
/// Errors triggered by frames come in two types: connection errors, and stream errors. This refers
/// to the scope at which the error occurs. Stream errors occur at stream scope, and therefore should
/// lead to the teardown of only the affected stream (e.g. RST_STREAM frame emission). Connection errors
/// occur at connection scope: either there is no stream available to tear down, or the error is so
/// foundational that the connection can not be recovered. In either case, the mechanism for tolerating
/// that is to tear the entire connection down, via GOAWAY frame.
///
/// In both cases, there is an associated kind of error as represented by a `HTTP2ErrorCode`, that
/// should be reported to the remote peer. Additionally, there is an error fired by the internal state
/// machine that can be reported to the user. This enum ensures that both can be propagated out.
enum StateMachineResult {
/// An error that transitions the stream into a fatal error state. This should cause emission of
/// RST_STREAM frames.
case streamError(streamID: HTTP2StreamID, underlyingError: Error, type: HTTP2ErrorCode)
/// An error that transitions the entire connection into a fatal error state. This should cause
/// emission of GOAWAY frames.
case connectionError(underlyingError: Error, type: HTTP2ErrorCode)
/// The frame itself was not valid, but it is also not an error. Drop the frame.
case ignoreFrame
/// The state transition succeeded, the frame may be passed on.
case succeed
}
/// Operations that may need to be performed after receiving a frame.
enum PostFrameOperation {
/// An appropriate ACK must be sent.
case sendAck
/// No operation is needed.
case nothing
}
/// An encapsulation of a state machine result along with a possible triggered state change.
struct StateMachineResultWithEffect {
var result: StateMachineResult
var effect: NIOHTTP2ConnectionStateChange?
init(result: StateMachineResult, effect: NIOHTTP2ConnectionStateChange?) {
self.result = result
self.effect = effect
}
init(_ streamEffect: StateMachineResultWithStreamEffect,
inboundFlowControlWindow: HTTP2FlowControlWindow,
outboundFlowControlWindow: HTTP2FlowControlWindow) {
self.result = streamEffect.result
self.effect = streamEffect.effect.map {
NIOHTTP2ConnectionStateChange($0, inboundFlowControlWindow: inboundFlowControlWindow, outboundFlowControlWindow: outboundFlowControlWindow)
}
}
}
/// An encapsulation of a state machine result along with a state change on a single stream.
struct StateMachineResultWithStreamEffect {
var result: StateMachineResult
var effect: StreamStateChange?
}
| aca6183db7e53f21588cdc1adc498b8b | 41.464286 | 151 | 0.711522 | false | false | false | false |
Fitbit/RxBluetoothKit | refs/heads/master | Tests/Autogenerated/_Peripheral.generated.swift | apache-2.0 | 1 | import Foundation
import RxSwift
import CoreBluetooth
@testable import RxBluetoothKit
// swiftlint:disable line_length
// swiftlint:disable type_body_length
/// _Peripheral is a class implementing ReactiveX API which wraps all Core Bluetooth functions
/// allowing to talk to peripheral like discovering characteristics, services and all of the read/write calls.
class _Peripheral {
/// Intance of _CentralManager which is used to the bluetooth communication
unowned let manager: _CentralManager
/// Implementation of peripheral
let peripheral: CBPeripheralMock
/// Object responsible for characteristic notification observing
private let notificationManager: CharacteristicNotificationManagerMock
let delegateWrapper: CBPeripheralDelegateWrapperMock
private let remainingServicesDiscoveryRequest = ThreadSafeBox<Int>(value: 0)
private let peripheralDidDiscoverServices = PublishSubject<([CBServiceMock]?, Error?)>()
private let remainingIncludedServicesDiscoveryRequest = ThreadSafeBox<[CBUUID: Int]>(value: [CBUUID: Int]())
private let peripheralDidDiscoverIncludedServicesForService = PublishSubject<(CBServiceMock, Error?)>()
private let remainingCharacteristicsDiscoveryRequest = ThreadSafeBox<[CBUUID: Int]>(value: [CBUUID: Int]())
private let peripheralDidDiscoverCharacteristicsForService = PublishSubject<(CBServiceMock, Error?)>()
private let disposeBag = DisposeBag()
/// Creates new `_Peripheral`
/// - parameter manager: Central instance which is used to perform all of the necessary operations.
/// - parameter peripheral: Instance representing specific peripheral allowing to perform operations on it.
/// - parameter delegateWrapper: Rx wrapper for `CBPeripheralDelegate`.
/// - parameter notificationManager: Instance used to observe characteristics notification
init(
manager: _CentralManager,
peripheral: CBPeripheralMock,
delegateWrapper: CBPeripheralDelegateWrapperMock,
notificationManager: CharacteristicNotificationManagerMock
) {
self.manager = manager
self.peripheral = peripheral
self.delegateWrapper = delegateWrapper
self.notificationManager = notificationManager
peripheral.delegate = self.delegateWrapper
setupSubjects()
}
convenience init(manager: _CentralManager,
peripheral: CBPeripheralMock,
delegateWrapper: CBPeripheralDelegateWrapperMock) {
let notificationManager = CharacteristicNotificationManagerMock(peripheral: peripheral, delegateWrapper: delegateWrapper)
self.init(manager: manager,
peripheral: peripheral,
delegateWrapper: delegateWrapper,
notificationManager: notificationManager)
}
private func setupSubjects() {
manager.delegateWrapper
.didDisconnectPeripheral
.filter { [weak self] peripheral, _ in
peripheral.uuidIdentifier == self?.peripheral.uuidIdentifier
}
.subscribe(onNext: { [weak self] _ in
self?.remainingServicesDiscoveryRequest.writeSync { value in
value = 0
}
self?.remainingIncludedServicesDiscoveryRequest.writeSync { array in
array.removeAll()
}
self?.remainingCharacteristicsDiscoveryRequest.writeSync { array in
array.removeAll()
}
})
.disposed(by: disposeBag)
delegateWrapper.peripheralDidDiscoverServices.subscribe { [weak self] event in
self?.remainingServicesDiscoveryRequest.writeSync { value in
if value > 0 {
value -= 1
}
}
self?.peripheralDidDiscoverServices.on(event)
}.disposed(by: disposeBag)
delegateWrapper.peripheralDidDiscoverIncludedServicesForService.subscribe { [weak self] event in
self?.remainingIncludedServicesDiscoveryRequest.writeSync { array in
if let element = event.element {
let oldValue = array[element.0.uuid] ?? 1
if oldValue > 0 {
array[element.0.uuid] = oldValue - 1
}
}
}
self?.peripheralDidDiscoverIncludedServicesForService.on(event)
}.disposed(by: disposeBag)
delegateWrapper.peripheralDidDiscoverCharacteristicsForService.subscribe { [weak self] event in
self?.remainingCharacteristicsDiscoveryRequest.writeSync { array in
if let element = event.element {
let oldValue = array[element.0.uuid] ?? 1
if oldValue > 0 {
array[element.0.uuid] = oldValue - 1
}
}
}
self?.peripheralDidDiscoverCharacteristicsForService.on(event)
}.disposed(by: disposeBag)
}
/// Attaches RxBluetoothKit delegate to CBPeripheralMock.
/// This method is useful in cases when delegate of CBPeripheralMock was reassigned outside of
/// RxBluetoothKit library (e.g. CBPeripheralMock was used in some other library or used in non-reactive way)
func attach() {
peripheral.delegate = delegateWrapper
}
/// Value indicating if peripheral is currently in connected state.
var isConnected: Bool {
return peripheral.state == .connected
}
/// Current state of `_Peripheral` instance described by [CBPeripheralState](https://developer.apple.com/documentation/corebluetooth/cbperipheralstate).
/// - returns: Current state of `_Peripheral` as `CBPeripheralState`.
var state: CBPeripheralState {
return peripheral.state
}
/// Current name of `_Peripheral` instance. Analogous to [name](https://developer.apple.com/documentation/corebluetooth/cbperipheral/1519029-name) of `CBPeripheralMock`.
var name: String? {
return peripheral.name
}
/// Unique identifier of `_Peripheral` instance. Assigned once peripheral is discovered by the system.
var identifier: UUID {
return peripheral.uuidIdentifier
}
/// A list of services that have been discovered. Analogous to [services](https://developer.apple.com/documentation/corebluetooth/cbperipheral/1518978-services) of `CBPeripheralMock`.
var services: [_Service]? {
return peripheral.services?.map {
_Service(peripheral: self, service: $0)
}
}
/// YES if the remote device has space to send a write without response. If this value is NO,
/// the value will be set to YES after the current writes have been flushed, and
/// `peripheralIsReadyToSendWriteWithoutResponse:` will be called.
var canSendWriteWithoutResponse: Bool {
if #available(iOS 11.0, macOS 10.13, tvOS 11.0, watchOS 4.0, *) {
return peripheral.canSendWriteWithoutResponse
} else {
return true
}
}
// MARK: Connecting
/// Continuous value indicating if peripheral is in connected state. This is continuous value, which emits `.next` whenever state change occurs
/// - returns Observable which emits next events when `_Peripheral` is connected or disconnected.
/// It's **infinite** stream, so `.complete` is never called.
///
/// Observable can ends with following errors:
/// * `_BluetoothError.destroyed`
/// * `_BluetoothError.bluetoothUnsupported`
/// * `_BluetoothError.bluetoothUnauthorized`
/// * `_BluetoothError.bluetoothPoweredOff`
/// * `_BluetoothError.bluetoothInUnknownState`
/// * `_BluetoothError.bluetoothResetting`
func observeConnection() -> Observable<Bool> {
let disconnected = manager.observeDisconnect(for: self).map { _ in false }
let connected = manager.observeConnect(for: self).map { _ in true }
return Observable.of(disconnected, connected).merge()
}
/// Establishes connection with a given `_Peripheral`.
/// For more information look into `_CentralManager.establishConnection(with:options:)` because this method calls it directly.
/// - parameter options: Dictionary to customise the behaviour of connection.
/// - returns: `Observable` which emits `next` event after connection is established.
///
/// Observable can ends with following errors:
/// * `_BluetoothError.peripheralIsAlreadyObservingConnection`
/// * `_BluetoothError.peripheralConnectionFailed`
/// * `_BluetoothError.peripheralDisconnected`
/// * `_BluetoothError.destroyed`
/// * `_BluetoothError.bluetoothUnsupported`
/// * `_BluetoothError.bluetoothUnauthorized`
/// * `_BluetoothError.bluetoothPoweredOff`
/// * `_BluetoothError.bluetoothInUnknownState`
/// * `_BluetoothError.bluetoothResetting`
func establishConnection(options: [String: Any]? = nil) -> Observable<_Peripheral> {
return manager.establishConnection(self, options: options)
}
// MARK: Services
/// Triggers discover of specified services of peripheral. If the servicesUUIDs parameter is nil, all the available services of the
/// peripheral are returned; setting the parameter to nil is considerably slower and is not recommended.
/// If all of the specified services are already discovered - these are returned without doing any underlying Bluetooth operations.
///
/// - Parameter serviceUUIDs: An array of [CBUUID](https://developer.apple.com/library/ios/documentation/CoreBluetooth/Reference/CBUUID_Class/)
/// objects that you are interested in. Here, each [CBUUID](https://developer.apple.com/library/ios/documentation/CoreBluetooth/Reference/CBUUID_Class/)
/// object represents a UUID that identifies the type of service you want to discover.
/// - Returns: `Single` that emits `next` with array of `_Service` instances, once they're discovered.
///
/// Observable can ends with following errors:
/// * `_BluetoothError.servicesDiscoveryFailed`
/// * `_BluetoothError.peripheralDisconnected`
/// * `_BluetoothError.destroyed`
/// * `_BluetoothError.bluetoothUnsupported`
/// * `_BluetoothError.bluetoothUnauthorized`
/// * `_BluetoothError.bluetoothPoweredOff`
/// * `_BluetoothError.bluetoothInUnknownState`
/// * `_BluetoothError.bluetoothResetting`
func discoverServices(_ serviceUUIDs: [CBUUID]?) -> Single<[_Service]> {
if let identifiers = serviceUUIDs, !identifiers.isEmpty,
let cachedServices = self.services,
let filteredServices = filterUUIDItems(uuids: serviceUUIDs, items: cachedServices, requireAll: true) {
return ensureValidPeripheralState(for: .just(filteredServices)).asSingle()
}
let observable = peripheralDidDiscoverServices
.filter { [weak self] (services, error) in
guard let strongSelf = self else { throw _BluetoothError.destroyed }
guard let cachedServices = strongSelf.services, error == nil else { return true }
let foundRequestedServices = serviceUUIDs != nil && filterUUIDItems(uuids: serviceUUIDs, items: cachedServices, requireAll: true) != nil
return foundRequestedServices || strongSelf.remainingServicesDiscoveryRequest.read { $0 == 0 }
}
.flatMap { [weak self] (_, error) -> Observable<[_Service]> in
guard let strongSelf = self else { throw _BluetoothError.destroyed }
guard let cachedServices = strongSelf.services, error == nil else {
throw _BluetoothError.servicesDiscoveryFailed(strongSelf, error)
}
if let filteredServices = filterUUIDItems(uuids: serviceUUIDs, items: cachedServices, requireAll: false) {
return .just(filteredServices)
}
return .empty()
}
.take(1)
return ensureValidPeripheralStateAndCallIfSucceeded(
for: observable,
postSubscriptionCall: { [weak self] in
self?.remainingServicesDiscoveryRequest.writeSync { value in
value += 1
}
self?.peripheral.discoverServices(serviceUUIDs)
}
)
.asSingle()
}
/// Function that triggers included services discovery for specified services. Discovery is called after
/// subscribtion to `Observable` is made.
/// If all of the specified included services are already discovered - these are returned without doing any underlying Bluetooth
/// operations.
///
/// - Parameter includedServiceUUIDs: Identifiers of included services that should be discovered. If `nil` - all of the
/// included services will be discovered. If you'll pass empty array - none of them will be discovered.
/// - Parameter service: _Service of which included services should be discovered.
/// - Returns: `Single` that emits `next` with array of `_Service` instances, once they're discovered.
///
/// Observable can ends with following errors:
/// * `_BluetoothError.includedServicesDiscoveryFailed`
/// * `_BluetoothError.peripheralDisconnected`
/// * `_BluetoothError.destroyed`
/// * `_BluetoothError.bluetoothUnsupported`
/// * `_BluetoothError.bluetoothUnauthorized`
/// * `_BluetoothError.bluetoothPoweredOff`
/// * `_BluetoothError.bluetoothInUnknownState`
/// * `_BluetoothError.bluetoothResetting`
func discoverIncludedServices(_ includedServiceUUIDs: [CBUUID]?, for service: _Service) -> Single<[_Service]> {
if let identifiers = includedServiceUUIDs, !identifiers.isEmpty,
let services = service.includedServices,
let filteredServices = filterUUIDItems(uuids: includedServiceUUIDs, items: services, requireAll: true) {
return ensureValidPeripheralState(for: .just(filteredServices)).asSingle()
}
let observable = peripheralDidDiscoverIncludedServicesForService
.filter { $0.0 == service.service }
.filter { [weak self] (cbService, error) in
guard let strongSelf = self else { throw _BluetoothError.destroyed }
guard let includedCBServices = cbService.includedServices, error == nil else { return true }
let includedServices = includedCBServices.map { _Service(peripheral: strongSelf, service: $0) }
let foundRequestedServices = includedServiceUUIDs != nil && filterUUIDItems(uuids: includedServiceUUIDs, items: includedServices, requireAll: true) != nil
return foundRequestedServices || strongSelf.remainingIncludedServicesDiscoveryRequest.read { array in
return (array[cbService.uuid] ?? 0) == 0
}
}
.flatMap { [weak self] (cbService, error) -> Observable<[_Service]> in
guard let strongSelf = self else { throw _BluetoothError.destroyed }
guard let includedRxServices = cbService.includedServices, error == nil else {
throw _BluetoothError.includedServicesDiscoveryFailed(strongSelf, error)
}
let includedServices = includedRxServices.map { _Service(peripheral: strongSelf, service: $0) }
if let filteredServices = filterUUIDItems(uuids: includedServiceUUIDs, items: includedServices, requireAll: false) {
return .just(filteredServices)
}
return .empty()
}
.take(1)
return ensureValidPeripheralStateAndCallIfSucceeded(
for: observable,
postSubscriptionCall: { [weak self] in
self?.remainingIncludedServicesDiscoveryRequest.writeSync { array in
let oldValue = array[service.uuid] ?? 0
array[service.uuid] = oldValue + 1
}
self?.peripheral.discoverIncludedServices(includedServiceUUIDs, for: service.service)
}
)
.asSingle()
}
// MARK: Characteristics
/// Function that triggers characteristics discovery for specified Services and identifiers. Discovery is called after
/// subscribtion to `Observable` is made.
/// If all of the specified characteristics are already discovered - these are returned without doing any underlying Bluetooth operations.
///
/// - Parameter characteristicUUIDs: Identifiers of characteristics that should be discovered. If `nil` - all of the
/// characteristics will be discovered. If you'll pass empty array - none of them will be discovered.
/// - Parameter service: _Service of which characteristics should be discovered.
/// - Returns: `Single` that emits `next` with array of `_Characteristic` instances, once they're discovered.
///
/// Observable can ends with following errors:
/// * `_BluetoothError.characteristicsDiscoveryFailed`
/// * `_BluetoothError.peripheralDisconnected`
/// * `_BluetoothError.destroyed`
/// * `_BluetoothError.bluetoothUnsupported`
/// * `_BluetoothError.bluetoothUnauthorized`
/// * `_BluetoothError.bluetoothPoweredOff`
/// * `_BluetoothError.bluetoothInUnknownState`
/// * `_BluetoothError.bluetoothResetting`
func discoverCharacteristics(_ characteristicUUIDs: [CBUUID]?, for service: _Service) -> Single<[_Characteristic]> {
if let identifiers = characteristicUUIDs, !identifiers.isEmpty,
let characteristics = service.characteristics,
let filteredCharacteristics = filterUUIDItems(uuids: characteristicUUIDs, items: characteristics, requireAll: true) {
return ensureValidPeripheralState(for: .just(filteredCharacteristics)).asSingle()
}
let observable = peripheralDidDiscoverCharacteristicsForService
.filter { $0.0 == service.service }
.filter { [weak self] (cbService, error) in
guard let strongSelf = self else { throw _BluetoothError.destroyed }
guard let cbCharacteristics = cbService.characteristics, error == nil else { return true }
let characteristics = cbCharacteristics.map { _Characteristic(characteristic: $0, service: service) }
let foundRequestedCharacteristis = characteristicUUIDs != nil && filterUUIDItems(uuids: characteristicUUIDs, items: characteristics, requireAll: true) != nil
return foundRequestedCharacteristis || strongSelf.remainingCharacteristicsDiscoveryRequest.read { array in
return (array[cbService.uuid] ?? 0) == 0
}
}
.flatMap { (cbService, error) -> Observable<[_Characteristic]> in
guard let cbCharacteristics = cbService.characteristics, error == nil else {
throw _BluetoothError.characteristicsDiscoveryFailed(service, error)
}
let characteristics = cbCharacteristics.map { _Characteristic(characteristic: $0, service: service) }
if let filteredCharacteristics = filterUUIDItems(uuids: characteristicUUIDs, items: characteristics, requireAll: false) {
return .just(filteredCharacteristics)
}
return .empty()
}
.take(1)
return ensureValidPeripheralStateAndCallIfSucceeded(
for: observable,
postSubscriptionCall: { [weak self] in
self?.remainingCharacteristicsDiscoveryRequest.writeSync { array in
let oldValue = array[service.uuid] ?? 0
array[service.uuid] = oldValue + 1
}
self?.peripheral.discoverCharacteristics(characteristicUUIDs, for: service.service)
}
).asSingle()
}
/// Function that allow to observe writes that happened for characteristic.
/// - Parameter characteristic: Optional `_Characteristic` of which value changes should be observed. When not specified it will observe for any `_Characteristic`.
/// - Returns: Observable that emits `next` with `_Characteristic` instance every time when write has happened.
/// It's **infinite** stream, so `.complete` is never called.
///
/// Observable can ends with following errors:
/// * `_BluetoothError.characteristicWriteFailed`
/// * `_BluetoothError.peripheralDisconnected`
/// * `_BluetoothError.destroyed`
/// * `_BluetoothError.bluetoothUnsupported`
/// * `_BluetoothError.bluetoothUnauthorized`
/// * `_BluetoothError.bluetoothPoweredOff`
/// * `_BluetoothError.bluetoothInUnknownState`
/// * `_BluetoothError.bluetoothResetting`
func observeWrite(for characteristic: _Characteristic? = nil) -> Observable<_Characteristic> {
let observable = delegateWrapper
.peripheralDidWriteValueForCharacteristic
.filter { characteristic != nil ? ($0.0 == characteristic!.characteristic) : true }
.map { [weak self] (cbCharacteristic, error) -> _Characteristic in
guard let strongSelf = self else { throw _BluetoothError.destroyed }
let characteristic = try characteristic ?? _Characteristic(characteristic: cbCharacteristic, peripheral: strongSelf)
if let error = error {
throw _BluetoothError.characteristicWriteFailed(characteristic, error)
}
return characteristic
}
return ensureValidPeripheralState(for: observable)
}
/// The maximum amount of data, in bytes, that can be sent to a characteristic in a single write.
/// - parameter type: Type of write operation. Possible values: `.withResponse`, `.withoutResponse`
/// - seealso: `writeValue(_:for:type:)`
@available(OSX 10.12, iOS 9.0, *)
func maximumWriteValueLength(for type: CBCharacteristicWriteType) -> Int {
return peripheral.maximumWriteValueLength(for: type)
}
/// Function that triggers write of data to characteristic. Write is called after subscribtion to `Observable` is made.
/// Behavior of this function strongly depends on [CBCharacteristicWriteType](https://developer.apple.com/documentation/corebluetooth/cbcharacteristicwritetype),
/// so be sure to check this out before usage of the method.
///
/// Behavior is following:
/// - `withResponse` - Observable emits `next` with `_Characteristic` instance write was confirmed without any errors.
/// Immediately after that `complete` is called. If any problem has happened, errors are emitted.
/// - `withoutResponse` - Observable emits `next` with `_Characteristic` instance once write was called.
/// Immediately after that `.complete` is called. Result of this call is not checked, so as a user you are not sure
/// if everything completed successfully. Errors are not emitted. It ensures that peripheral is ready to write
/// without response by listening to the proper delegate method
///
/// - parameter data: Data that'll be written to `_Characteristic` instance
/// - parameter characteristic: `_Characteristic` instance to write value to.
/// - parameter type: Type of write operation. Possible values: `.withResponse`, `.withoutResponse`
/// - parameter canSendWriteWithoutResponseCheckEnabled: check if canSendWriteWithoutResponse should be enabled. Done because of internal MacOS bug.
/// - returns: Observable that emission depends on `CBCharacteristicWriteType` passed to the function call.
///
/// Observable can ends with following errors:
/// * `_BluetoothError.characteristicWriteFailed`
/// * `_BluetoothError.peripheralDisconnected`
/// * `_BluetoothError.destroyed`
/// * `_BluetoothError.bluetoothUnsupported`
/// * `_BluetoothError.bluetoothUnauthorized`
/// * `_BluetoothError.bluetoothPoweredOff`
/// * `_BluetoothError.bluetoothInUnknownState`
/// * `_BluetoothError.bluetoothResetting`
func writeValue(_ data: Data,
for characteristic: _Characteristic,
type: CBCharacteristicWriteType,
canSendWriteWithoutResponseCheckEnabled: Bool = true) -> Single<_Characteristic> {
let writeOperationPerformingAndListeningObservable = { [weak self] (observable: Observable<_Characteristic>)
-> Observable<_Characteristic> in
guard let strongSelf = self else { return Observable.error(_BluetoothError.destroyed) }
return strongSelf.ensureValidPeripheralStateAndCallIfSucceeded(
for: observable,
postSubscriptionCall: { [weak self] in
self?.peripheral.writeValue(data, for: characteristic.characteristic, type: type)
}
)
}
switch type {
case .withoutResponse:
return observeWriteWithoutResponseReadiness()
.map { _ in true }
.startWith(canSendWriteWithoutResponseCheckEnabled ? canSendWriteWithoutResponse : true)
.filter { $0 }
.take(1)
.flatMap { _ in
writeOperationPerformingAndListeningObservable(Observable.just(characteristic))
}.asSingle()
case .withResponse:
return writeOperationPerformingAndListeningObservable(observeWrite(for: characteristic).take(1))
.asSingle()
@unknown default:
return .error(_BluetoothError.unknownWriteType)
}
}
/// Function that allow to observe value updates for `_Characteristic` instance.
/// - Parameter characteristic: Optional `_Characteristic` of which value changes should be observed. When not specified it will observe for any `_Characteristic`.
/// - Returns: Observable that emits `next` with `_Characteristic` instance every time when value has changed.
/// It's **infinite** stream, so `.complete` is never called.
///
/// Observable can ends with following errors:
/// * `_BluetoothError.characteristicReadFailed`
/// * `_BluetoothError.peripheralDisconnected`
/// * `_BluetoothError.destroyed`
/// * `_BluetoothError.bluetoothUnsupported`
/// * `_BluetoothError.bluetoothUnauthorized`
/// * `_BluetoothError.bluetoothPoweredOff`
/// * `_BluetoothError.bluetoothInUnknownState`
/// * `_BluetoothError.bluetoothResetting`
func observeValueUpdate(for characteristic: _Characteristic? = nil) -> Observable<_Characteristic> {
let observable = delegateWrapper
.peripheralDidUpdateValueForCharacteristic
.filter { characteristic != nil ? ($0.0 == characteristic!.characteristic) : true }
.map { [weak self] (cbCharacteristic, error) -> _Characteristic in
guard let strongSelf = self else { throw _BluetoothError.destroyed }
let characteristic = try characteristic ?? _Characteristic(characteristic: cbCharacteristic, peripheral: strongSelf)
if let error = error {
throw _BluetoothError.characteristicReadFailed(characteristic, error)
}
return characteristic
}
return ensureValidPeripheralState(for: observable)
}
/// Function that triggers read of current value of the `_Characteristic` instance.
/// Read is called after subscription to `Observable` is made.
/// - Parameter characteristic: `_Characteristic` to read value from
/// - Returns: `Single` which emits `next` with given characteristic when value is ready to read.
///
/// Observable can ends with following errors:
/// * `_BluetoothError.characteristicReadFailed`
func readValue(for characteristic: _Characteristic) -> Single<_Characteristic> {
let observable = observeValueUpdate(for: characteristic).take(1)
return ensureValidPeripheralStateAndCallIfSucceeded(
for: observable,
postSubscriptionCall: { [weak self] in
self?.peripheral.readValue(for: characteristic.characteristic)
}
).asSingle()
}
/// Setup characteristic notification in order to receive callbacks when given characteristic has been changed.
/// Returned observable will emit `_Characteristic` on every notification change.
/// It is possible to setup more observables for the same characteristic and the lifecycle of the notification will be shared among them.
///
/// Notification is automaticaly unregistered once this observable is unsubscribed
///
/// - parameter characteristic: `_Characteristic` for notification setup.
/// - returns: `Observable` emitting `_Characteristic` when given characteristic has been changed.
///
/// This is **infinite** stream of values.
///
/// Observable can ends with following errors:
/// * `_BluetoothError.characteristicReadFailed`
/// * `_BluetoothError.peripheralDisconnected`
/// * `_BluetoothError.destroyed`
/// * `_BluetoothError.bluetoothUnsupported`
/// * `_BluetoothError.bluetoothUnauthorized`
/// * `_BluetoothError.bluetoothPoweredOff`
/// * `_BluetoothError.bluetoothInUnknownState`
/// * `_BluetoothError.bluetoothResetting`
func observeValueUpdateAndSetNotification(for characteristic: _Characteristic) -> Observable<_Characteristic> {
let observable = notificationManager.observeValueUpdateAndSetNotification(for: characteristic)
return ensureValidPeripheralState(for: observable)
}
/// Use this function in order to know the exact time, when isNotyfing value has changed on a _Characteristic.
///
/// - parameter characteristic: `_Characteristic` which you observe for isNotyfing changes.
/// - returns: `Observable` emitting `_Characteristic` when given characteristic has changed it's isNoytfing value.
///
/// Observable can ends with following errors:
/// * `_BluetoothError.characteristicSetNotifyValueFailed`
/// * `_BluetoothError.peripheralDisconnected`
/// * `_BluetoothError.destroyed`
/// * `_BluetoothError.bluetoothUnsupported`
/// * `_BluetoothError.bluetoothUnauthorized`
/// * `_BluetoothError.bluetoothPoweredOff`
/// * `_BluetoothError.bluetoothInUnknownState`
/// * `_BluetoothError.bluetoothResetting`
func observeNotifyValue(for characteristic: _Characteristic) -> Observable<_Characteristic> {
return delegateWrapper.peripheralDidUpdateNotificationStateForCharacteristic
.filter { $0.0 == characteristic.characteristic }
.map { [weak self] (cbCharacteristic, error) -> _Characteristic in
guard let strongSelf = self else { throw _BluetoothError.destroyed }
let characteristic = try _Characteristic(characteristic: cbCharacteristic, peripheral: strongSelf)
if let error = error {
throw _BluetoothError.characteristicSetNotifyValueFailed(characteristic, error)
}
return characteristic
}
}
// MARK: Descriptors
/// Function that triggers descriptors discovery for characteristic
/// If all of the descriptors are already discovered - these are returned without doing any underlying Bluetooth operations.
/// - Parameter characteristic: `_Characteristic` instance for which descriptors should be discovered.
/// - Returns: `Single` that emits `next` with array of `_Descriptor` instances, once they're discovered.
///
/// Observable can ends with following errors:
/// * `_BluetoothError.descriptorsDiscoveryFailed`
/// * `_BluetoothError.peripheralDisconnected`
/// * `_BluetoothError.destroyed`
/// * `_BluetoothError.bluetoothUnsupported`
/// * `_BluetoothError.bluetoothUnauthorized`
/// * `_BluetoothError.bluetoothPoweredOff`
/// * `_BluetoothError.bluetoothInUnknownState`
/// * `_BluetoothError.bluetoothResetting`
func discoverDescriptors(for characteristic: _Characteristic) -> Single<[_Descriptor]> {
if let descriptors = characteristic.descriptors {
let resultDescriptors = descriptors.map { _Descriptor(descriptor: $0.descriptor, characteristic: characteristic) }
return ensureValidPeripheralState(for: .just(resultDescriptors)).asSingle()
}
let observable = delegateWrapper
.peripheralDidDiscoverDescriptorsForCharacteristic
.filter { $0.0 == characteristic.characteristic }
.take(1)
.map { (cbCharacteristic, error) -> [_Descriptor] in
if let descriptors = cbCharacteristic.descriptors, error == nil {
return descriptors.map {
_Descriptor(descriptor: $0, characteristic: characteristic) }
}
throw _BluetoothError.descriptorsDiscoveryFailed(characteristic, error)
}
return ensureValidPeripheralStateAndCallIfSucceeded(
for: observable,
postSubscriptionCall: { [weak self] in
self?.peripheral.discoverDescriptors(for: characteristic.characteristic)
}
).asSingle()
}
/// Function that allow to observe writes that happened for descriptor.
/// - Parameter descriptor: Optional `_Descriptor` of which value changes should be observed. When not specified it will observe for any `_Descriptor`.
/// - Returns: Observable that emits `next` with `_Descriptor` instance every time when write has happened.
/// It's **infinite** stream, so `.complete` is never called.
///
/// Observable can ends with following errors:
/// * `_BluetoothError.descriptorWriteFailed`
/// * `_BluetoothError.peripheralDisconnected`
/// * `_BluetoothError.destroyed`
/// * `_BluetoothError.bluetoothUnsupported`
/// * `_BluetoothError.bluetoothUnauthorized`
/// * `_BluetoothError.bluetoothPoweredOff`
/// * `_BluetoothError.bluetoothInUnknownState`
/// * `_BluetoothError.bluetoothResetting`
func observeWrite(for descriptor: _Descriptor? = nil) -> Observable<_Descriptor> {
let observable = delegateWrapper
.peripheralDidWriteValueForDescriptor
.filter { descriptor != nil ? ($0.0 == descriptor!.descriptor) : true }
.map { [weak self] (cbDescriptor, error) -> _Descriptor in
guard let strongSelf = self else { throw _BluetoothError.destroyed }
let descriptor = try descriptor ?? _Descriptor(descriptor: cbDescriptor, peripheral: strongSelf)
if let error = error {
throw _BluetoothError.descriptorWriteFailed(descriptor, error)
}
return descriptor
}
return ensureValidPeripheralState(for: observable)
}
/// Function that allow to observe value updates for `_Descriptor` instance.
/// - Parameter descriptor: Optional `_Descriptor` of which value changes should be observed. When not specified it will observe for any `_Descriptor`.
/// - Returns: Observable that emits `next` with `_Descriptor` instance every time when value has changed.
/// It's **infinite** stream, so `.complete` is never called.
///
/// Observable can ends with following errors:
/// * `_BluetoothError.descriptorReadFailed`
/// * `_BluetoothError.peripheralDisconnected`
/// * `_BluetoothError.destroyed`
/// * `_BluetoothError.bluetoothUnsupported`
/// * `_BluetoothError.bluetoothUnauthorized`
/// * `_BluetoothError.bluetoothPoweredOff`
/// * `_BluetoothError.bluetoothInUnknownState`
/// * `_BluetoothError.bluetoothResetting`
func observeValueUpdate(for descriptor: _Descriptor? = nil) -> Observable<_Descriptor> {
let observable = delegateWrapper
.peripheralDidUpdateValueForDescriptor
.filter { descriptor != nil ? ($0.0 == descriptor!.descriptor) : true }
.map { [weak self] (cbDescriptor, error) -> _Descriptor in
guard let strongSelf = self else { throw _BluetoothError.destroyed }
let descriptor = try descriptor ?? _Descriptor(descriptor: cbDescriptor, peripheral: strongSelf)
if let error = error {
throw _BluetoothError.descriptorReadFailed(descriptor, error)
}
return descriptor
}
return ensureValidPeripheralState(for: observable)
}
/// Function that triggers read of current value of the `_Descriptor` instance.
/// Read is called after subscription to `Observable` is made.
/// - Parameter descriptor: `_Descriptor` to read value from
/// - Returns: `Single` which emits `next` with given descriptor when value is ready to read.
///
/// Observable can ends with following errors:
/// * `_BluetoothError.descriptorReadFailed`
/// * `_BluetoothError.peripheralDisconnected`
/// * `_BluetoothError.destroyed`
/// * `_BluetoothError.bluetoothUnsupported`
/// * `_BluetoothError.bluetoothUnauthorized`
/// * `_BluetoothError.bluetoothPoweredOff`
/// * `_BluetoothError.bluetoothInUnknownState`
/// * `_BluetoothError.bluetoothResetting`
func readValue(for descriptor: _Descriptor) -> Single<_Descriptor> {
let observable = observeValueUpdate(for: descriptor).take(1)
return ensureValidPeripheralStateAndCallIfSucceeded(
for: observable,
postSubscriptionCall: { [weak self] in
self?.peripheral.readValue(for: descriptor.descriptor) }
)
.asSingle()
}
/// Function that triggers write of data to descriptor. Write is called after subscribtion to `Observable` is made.
/// - Parameter data: `Data` that'll be written to `_Descriptor` instance
/// - Parameter descriptor: `_Descriptor` instance to write value to.
/// - Returns: `Single` that emits `next` with `_Descriptor` instance, once value is written successfully.
///
/// Observable can ends with following errors:
/// * `_BluetoothError.descriptorWriteFailed`
/// * `_BluetoothError.peripheralDisconnected`
/// * `_BluetoothError.destroyed`
/// * `_BluetoothError.bluetoothUnsupported`
/// * `_BluetoothError.bluetoothUnauthorized`
/// * `_BluetoothError.bluetoothPoweredOff`
/// * `_BluetoothError.bluetoothInUnknownState`
/// * `_BluetoothError.bluetoothResetting`
func writeValue(_ data: Data, for descriptor: _Descriptor) -> Single<_Descriptor> {
let observeWrite = self.observeWrite(for: descriptor).take(1)
return ensureValidPeripheralStateAndCallIfSucceeded(
for: observeWrite,
postSubscriptionCall: { [weak self] in
self?.peripheral.writeValue(data, for: descriptor.descriptor) }
)
.asSingle()
}
// MARK: Other methods
/// Function that triggers read of `_Peripheral` RSSI value. Read is called after subscription to `Observable` is made.
/// - returns: `Single` that emits tuple: `(_Peripheral, Int)` once new RSSI value is read.
/// `Int` is new RSSI value, `_Peripheral` is returned to allow easier chaining.
///
/// Observable can ends with following errors:
/// * `_BluetoothError.peripheralRSSIReadFailed`
/// * `_BluetoothError.peripheralDisconnected`
/// * `_BluetoothError.destroyed`
/// * `_BluetoothError.bluetoothUnsupported`
/// * `_BluetoothError.bluetoothUnauthorized`
/// * `_BluetoothError.bluetoothPoweredOff`
/// * `_BluetoothError.bluetoothInUnknownState`
/// * `_BluetoothError.bluetoothResetting`
func readRSSI() -> Single<(_Peripheral, Int)> {
let observable = delegateWrapper
.peripheralDidReadRSSI
.take(1)
.map { [weak self] (rssi, error) -> (_Peripheral, Int) in
guard let strongSelf = self else { throw _BluetoothError.destroyed }
if let error = error {
throw _BluetoothError.peripheralRSSIReadFailed(strongSelf, error)
}
return (strongSelf, rssi)
}
return ensureValidPeripheralStateAndCallIfSucceeded(
for: observable,
postSubscriptionCall: { [weak self] in
self?.peripheral.readRSSI()
}
).asSingle()
}
/// Function that allow user to observe incoming `name` property changes of `_Peripheral` instance.
/// - returns: `Observable` that emits tuples: `(_Peripheral, String?)` when name has changed.
/// It's `optional String` because peripheral could also lost his name.
/// It's **infinite** stream of values, so `.complete` is never emitted.
///
/// Observable can ends with following errors:
/// * `_BluetoothError.peripheralDisconnected`
/// * `_BluetoothError.destroyed`
/// * `_BluetoothError.bluetoothUnsupported`
/// * `_BluetoothError.bluetoothUnauthorized`
/// * `_BluetoothError.bluetoothPoweredOff`
/// * `_BluetoothError.bluetoothInUnknownState`
/// * `_BluetoothError.bluetoothResetting`
func observeNameUpdate() -> Observable<(_Peripheral, String?)> {
let observable = delegateWrapper.peripheralDidUpdateName.map { [weak self] name -> (_Peripheral, String?) in
guard let strongSelf = self else { throw _BluetoothError.destroyed }
return (strongSelf, name)
}
return ensureValidPeripheralState(for: observable)
}
/// Function that allow to observe incoming service modifications for `_Peripheral` instance.
/// In case you're interested what exact changes might occur - please refer to
/// [Apple Documentation](https://developer.apple.com/documentation/corebluetooth/cbperipheraldelegate/1518865-peripheral)
///
/// - returns: `Observable` that emits tuples: `(_Peripheral, [_Service])` when services were modified.
/// It's **infinite** stream of values, so `.complete` is never emitted.
///
/// Observable can ends with following errors:
/// * `_BluetoothError.peripheralDisconnected`
/// * `_BluetoothError.destroyed`
/// * `_BluetoothError.bluetoothUnsupported`
/// * `_BluetoothError.bluetoothUnauthorized`
/// * `_BluetoothError.bluetoothPoweredOff`
/// * `_BluetoothError.bluetoothInUnknownState`
/// * `_BluetoothError.bluetoothResetting`
func observeServicesModification() -> Observable<(_Peripheral, [_Service])> {
let observable = delegateWrapper.peripheralDidModifyServices
.map { [weak self] services -> [_Service] in
guard let strongSelf = self else { throw _BluetoothError.destroyed }
return services.map { _Service(peripheral: strongSelf, service: $0) } }
.map { [weak self] services -> (_Peripheral, [_Service]) in
guard let strongSelf = self else { throw _BluetoothError.destroyed }
return (strongSelf, services)
}
return ensureValidPeripheralState(for: observable)
}
/// Resulting observable emits next element if call to `writeValue:forCharacteristic:type:` has failed,
/// to indicate when peripheral is again ready to send characteristic value updates again.
func observeWriteWithoutResponseReadiness() -> Observable<Void> {
return delegateWrapper.peripheralIsReadyToSendWriteWithoutResponse.asObservable()
}
/// Function that allow to open L2CAP channel for `_Peripheral` instance.
/// For more information, please refer to
/// [What’s New in CoreBluetooth, 712, WWDC 2017](https://developer.apple.com/videos/play/wwdc2017/712/)
///
/// - parameter PSM: `PSM` (Protocol/_Service Multiplexer) of the channel
/// - returns: `Single` that emits `CBL2CAPChannelMock` when channel has opened
/// - since: iOS 11, tvOS 11, watchOS 4
///
/// Observable can ends with following errors:
/// * `_BluetoothError.openingL2CAPChannelFailed`
/// * `_BluetoothError.peripheralDisconnected`
/// * `_BluetoothError.destroyed`
/// * `_BluetoothError.bluetoothUnsupported`
/// * `_BluetoothError.bluetoothUnauthorized`
/// * `_BluetoothError.bluetoothPoweredOff`
/// * `_BluetoothError.bluetoothInUnknownState`
/// * `_BluetoothError.bluetoothResetting`
@available(iOS 11, macOS 10.14, tvOS 11, watchOS 4, *)
func openL2CAPChannel(PSM: CBL2CAPPSM) -> Single<CBL2CAPChannelMock> {
let observable = delegateWrapper
.peripheralDidOpenL2CAPChannel
.map {($0.0 as? CBL2CAPChannelMock, $0.1)}
.take(1)
.flatMap { [weak self] (channel, error) -> Observable<CBL2CAPChannelMock> in
guard let strongSelf = self else { throw _BluetoothError.destroyed }
if let channel = channel, error == nil {
return .just(channel)
} else {
throw _BluetoothError.openingL2CAPChannelFailed(strongSelf, error)
}
}
return ensureValidPeripheralStateAndCallIfSucceeded(for: observable, postSubscriptionCall: { [weak self] in
self?.peripheral.openL2CAPChannel(PSM)
}).asSingle()
}
// MARK: Internal functions
func ensureValidPeripheralStateAndCallIfSucceeded<T>(for observable: Observable<T>,
postSubscriptionCall call: @escaping () -> Void
) -> Observable<T> {
let operation = Observable<T>.deferred {
call()
return .empty()
}
return ensureValidPeripheralState(for: Observable.merge([observable, operation]))
}
/// Function that merges given observable with error streams of invalid Central Manager states.
/// - parameter observable: `Observable` to be transformed
/// - returns: Source `Observable` which listens on state change errors as well
func ensureValidPeripheralState<T>(for observable: Observable<T>) -> Observable<T> {
return Observable<T>.absorb(
manager.ensurePeripheralIsConnected(self),
manager.ensure(.poweredOn, observable: observable)
)
}
}
extension _Peripheral: CustomStringConvertible {
var description: String {
return "\(type(of: self)) \(peripheral.name ?? "nil") (\(peripheral.identifier))"
}
}
extension _Peripheral: Equatable {}
/// Compare two peripherals which are the same when theirs identifiers are equal.
///
/// - parameter lhs: First peripheral to compare
/// - parameter rhs: Second peripheral to compare
/// - returns: True if both peripherals are the same
func == (lhs: _Peripheral, rhs: _Peripheral) -> Bool {
return lhs.peripheral == rhs.peripheral
}
extension CBServiceMock {
/// Unwrap the parent peripheral or throw if the peripheral is nil
func unwrapPeripheral() throws -> CBPeripheralMock {
guard let cbPeripheral = peripheral as CBPeripheralMock? else {
throw _BluetoothError.peripheralDeallocated
}
return cbPeripheral
}
}
| 41a71764081c04dbb774c0c9b9f2a16a | 51.480044 | 187 | 0.664913 | false | false | false | false |
jobrunner/FeedbackCards | refs/heads/master | FeedbackCards/MainViewController.swift | mit | 1 | // Copyright (c) 2017 Jo Brunner
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import UIKit
class MainViewController: UIViewController {
@IBOutlet var collectionView: UICollectionView!
@IBOutlet weak var appTitleLabel: UILabel!
@IBOutlet weak var appSubtitleLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
appTitleLabel.text = NSLocalizedString("Feedback Karten", comment: "Short title of App")
let font = appSubtitleLabel.font
let fontSize = appSubtitleLabel.font.pointSize * 0.56
let attributedString = NSMutableAttributedString(
string:"No-Device-Policy-HackTM",
attributes:[
NSAttributedStringKey.font: font!
])
attributedString.setAttributes([
NSAttributedStringKey.font: font!.withSize(fontSize),
NSAttributedStringKey.baselineOffset: fontSize
],
range: NSRange(
location: attributedString.length - 2,
length: 2
))
appSubtitleLabel.attributedText = attributedString
NotificationCenter.default.addObserver(
self,
selector: #selector(reloadData),
name: UserDefaults.didChangeNotification,
object: nil
)
registerNibs()
reloadData()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override var prefersStatusBarHidden: Bool {
return true
}
override func viewWillLayoutSubviews() {
collectionView.collectionViewLayout.invalidateLayout()
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "InfoSegue" {
let destinationViewController = segue.destination as UIViewController
destinationViewController.modalTransitionStyle = .crossDissolve
destinationViewController.modalPresentationStyle = .overCurrentContext
// self.present(destinationViewController,
// animated: true,
// completion: nil)
return
}
}
@IBAction func settingsButtonTouchUpInside(_ sender: UIButton) {
UIApplication.shared.openURL(URL(string:UIApplicationOpenSettingsURLString)!)
}
}
extension MainViewController {
func registerNibs() {
let nib = UINib.init(nibName: "MenuCardCollectionViewCell", bundle: Bundle.main)
collectionView!.register(nib, forCellWithReuseIdentifier: "MenuCardCollectionViewCell")
}
@objc func reloadData() {
CardDeck.reset()
collectionView.reloadData()
}
}
| 1cabf3a4796445be53b3b49797dd729c | 32.798246 | 96 | 0.657669 | false | false | false | false |
mruvim/SimpleLoadingButton | refs/heads/master | SimpleLoadingButton/Classes/SimpleLoadingButton.swift | mit | 1 | //
// SimpleLoadingButton.swift
// SimpleLoadingButton
//
// Created by Ruva on 7/1/16.
// Copyright (c) 2016 Ruva. All rights reserved.
//
import UIKit
@IBDesignable
public class SimpleLoadingButton: UIControl {
/**
Button internal states
- Normal: Title label is displayed, button background color is normalBackgroundColor
- Highlighted: Title label is displayed, button background color changes to highlightedBackgroundColor
- Loading: Loading animation is displayed, background color changes to normalBackgroundColor
*/
fileprivate enum ButtonState {
case normal
case highlighted
case loading
}
//MARK: - Private
fileprivate var currentlyVisibleView:UIView?
fileprivate var buttonState:ButtonState = .normal { didSet { if oldValue != buttonState { updateUI(forState:buttonState) } } }
/// Font for the title label (IB does not allow UIFont to be inspected therefore font must be set programmatically)
public var titleFont:UIFont = UIFont.systemFont(ofSize: 16) {
didSet {
guard let titleLabel = currentlyVisibleView as? UILabel else { return }
titleLabel.font = titleFont
}
}
//MARK: - Inspectable / Designable properties
/// Button title
@IBInspectable var title:String = NSLocalizedString("Button", comment:"Button") {
didSet {
guard let titleLabel = currentlyVisibleView as? UILabel else { return }
titleLabel.text = title
}
}
/// Title color
@IBInspectable var titleColor:UIColor = UIColor.white {
didSet {
guard let titleLabel = currentlyVisibleView as? UILabel else { return }
titleLabel.textColor = titleColor
}
}
/// Loading indicator color
@IBInspectable var loadingIndicatorColor:UIColor = UIColor.white {
didSet{
updateUI(forState: buttonState)
}
}
/// Border width
@IBInspectable var borderWidth:CGFloat = 0 {
didSet { updateStyle() }
}
/// Border color
@IBInspectable var borderColor:UIColor = UIColor.white {
didSet { updateStyle() }
}
/// Corner radius
@IBInspectable var cornerRadius:CGFloat = 0 {
didSet { updateStyle() }
}
/// Background color for normal state
@IBInspectable var normalBackgroundColor:UIColor = UIColor.lightGray {
didSet { updateStyle() }
}
/// Background color for highlighted state
@IBInspectable var highlightedBackgroundColor:UIColor = UIColor.darkGray {
didSet { updateStyle() }
}
/// Duration of one animation cycle
@IBInspectable var loadingAnimationDuration:Double = 2.0
/// Size of the animating shape
@IBInspectable var loadingShapeSize:CGSize = CGSize(width: 10, height: 10)
//MARK: - Init
override init(frame: CGRect) {
super.init(frame: frame)
setupButton()
updateStyle()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupButton()
updateStyle()
}
/**
Setup button to initial state
*/
private func setupButton() -> Void {
let titleLabel = createTitleLabel(withFrame:CGRect(x: 0, y: 0, width: frame.width, height: frame.height))
titleLabel.translatesAutoresizingMaskIntoConstraints = false
addSubview(titleLabel)
titleLabel.leftAnchor.constraint(equalTo: leftAnchor).isActive = true
titleLabel.topAnchor.constraint(equalTo: topAnchor).isActive = true
titleLabel.rightAnchor.constraint(equalTo: rightAnchor).isActive = true
titleLabel.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true
currentlyVisibleView = titleLabel
}
/**
Button style update
*/
private func updateStyle() -> Void {
backgroundColor = normalBackgroundColor
layer.cornerRadius = cornerRadius
layer.masksToBounds = cornerRadius > 0
layer.borderWidth = borderWidth
layer.borderColor = borderColor.cgColor
}
/**
Update button UI as a result of state change
- parameter buttonState: new button state
*/
private func updateUI(forState buttonState:ButtonState) -> Void {
var buttonBackgroundColor:UIColor
switch buttonState {
case .normal:
buttonBackgroundColor = normalBackgroundColor
showLabelView()
case .highlighted:
buttonBackgroundColor = highlightedBackgroundColor
case .loading:
buttonBackgroundColor = normalBackgroundColor
showLoadingView()
}
UIView.animate(withDuration: 0.15, animations: { [unowned self] in self.backgroundColor = buttonBackgroundColor })
}
/**
Create title label
- parameter frame: Label frame
- returns: instance of UILabel
*/
fileprivate func createTitleLabel(withFrame frame:CGRect) -> UILabel {
let titleLabel = UILabel(frame:frame)
titleLabel.text = title
titleLabel.textAlignment = .center
titleLabel.textColor = titleColor
titleLabel.font = titleFont
return titleLabel
}
}
extension SimpleLoadingButton {
//MARK: - Touch handling
override public func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
guard buttonState == .normal,
let touchLocation = touches.first?.location(in: self),
bounds.contains(touchLocation) else {
super.touchesBegan(touches, with: event)
return
}
buttonState = .highlighted
}
override public func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
guard buttonState != .loading,
let touchLocation = touches.first?.location(in: self) else {
super.touchesMoved(touches, with: event)
return
}
buttonState = bounds.contains(touchLocation) ? .highlighted : .normal
}
override public func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
guard buttonState == .highlighted,
let touchLocation = touches.first?.location(in: self),
bounds.contains(touchLocation) else {
super.touchesEnded(touches, with: event)
return
}
buttonState = .loading
sendActions(for: .touchUpInside)
}
}
extension SimpleLoadingButton {
//MARK: - View transitions
/**
Transition to title label
*/
fileprivate func showLabelView() -> Void {
guard let loadingView = currentlyVisibleView as? SimpleLoadingView else { return }
let titleLabel = createTitleLabel(withFrame:loadingView.frame)
addSubview(titleLabel)
currentlyVisibleView = titleLabel
titleLabel.translatesAutoresizingMaskIntoConstraints = false
titleLabel.leftAnchor.constraint(equalTo: leftAnchor).isActive = true
titleLabel.topAnchor.constraint(equalTo: topAnchor).isActive = true
titleLabel.rightAnchor.constraint(equalTo: rightAnchor).isActive = true
titleLabel.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true
UIView.transition(from: loadingView, to:titleLabel, duration:0.15, options:.transitionCrossDissolve) { (_) in
loadingView.removeFromSuperview()
}
}
/**
Transition to loading animation
*/
fileprivate func showLoadingView() -> Void {
guard let titleLabel = currentlyVisibleView as? UILabel else { return }
let loadingView = SimpleLoadingView(withFrame:titleLabel.frame, animationDuration: loadingAnimationDuration, animatingShapeSize:loadingShapeSize, loadingIndicatorColor:loadingIndicatorColor)
loadingView.translatesAutoresizingMaskIntoConstraints = false
addSubview(loadingView)
currentlyVisibleView = loadingView
loadingView.leftAnchor.constraint(equalTo: leftAnchor).isActive = true
loadingView.topAnchor.constraint(equalTo: topAnchor).isActive = true
loadingView.rightAnchor.constraint(equalTo: rightAnchor).isActive = true
loadingView.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true
loadingView.startAnimation()
UIView.transition(from: titleLabel, to: loadingView, duration:0.15, options:.transitionCrossDissolve) { (_) in
titleLabel.removeFromSuperview()
}
}
}
extension SimpleLoadingButton {
/**
Start loading animation
*/
public func animate() -> Void {
buttonState = .loading
}
/**
Stop loading animation
*/
public func stop() -> Void {
buttonState = .normal
}
}
| e261cd69808db383ec40ba48a9991052 | 29.938776 | 198 | 0.635884 | false | false | false | false |
WhisperSystems/Signal-iOS | refs/heads/master | SignalMessaging/ViewModels/ContactShareViewModel.swift | gpl-3.0 | 1 | //
// Copyright (c) 2019 Open Whisper Systems. All rights reserved.
//
import Foundation
@objc
public class ContactShareViewModel: NSObject {
@objc
public let dbRecord: OWSContact
@objc
public var avatarImageData: Data? {
didSet {
self.cachedAvatarImage = nil
}
}
private var cachedAvatarImage: UIImage?
@objc
public var avatarImage: UIImage? {
if self.cachedAvatarImage != nil {
return self.cachedAvatarImage
}
guard let avatarImageData = self.avatarImageData else {
return nil
}
self.cachedAvatarImage = UIImage(data: avatarImageData)
return cachedAvatarImage
}
@objc
public required init(contactShareRecord: OWSContact, avatarImageData: Data?) {
self.dbRecord = contactShareRecord
self.avatarImageData = avatarImageData
}
@objc
public convenience init(contactShareRecord: OWSContact, transaction: SDSAnyReadTransaction) {
if let avatarAttachment = contactShareRecord.avatarAttachment(with: transaction) as? TSAttachmentStream {
self.init(contactShareRecord: contactShareRecord, avatarImageData: avatarAttachment.validStillImageData())
} else {
self.init(contactShareRecord: contactShareRecord, avatarImageData: nil)
}
}
@objc
public func getAvatarImage(diameter: CGFloat, contactsManager: OWSContactsManager) -> UIImage? {
if let avatarImage = avatarImage {
return avatarImage
}
var colorSeed = name.displayName
let recipientIds = systemContactsWithSignalAccountPhoneNumbers(contactsManager)
if let firstRecipientId = recipientIds.first {
// Try to use the first signal id as the default
// avatar's color seed, so that it is as consistent
// as possible with the user's avatar in other views.
colorSeed = firstRecipientId
}
let avatarBuilder = OWSContactAvatarBuilder(nonSignalName: displayName,
colorSeed: colorSeed,
diameter: UInt(diameter))
// Note: we use buildDefaultImage() and not build() so that contact
// share views always reflect the contents of the contact share.
// build() might return an avatar from a corresponding system
// contact or profile. This could mislead the user into thinking
// that an avatar they did not share was in fact included in the
// contact share.
return avatarBuilder.buildDefaultImage()
}
// MARK: Delegated -> dbRecord
@objc
public var name: OWSContactName {
get {
return dbRecord.name
}
set {
return dbRecord.name = newValue
}
}
@objc
public var addresses: [OWSContactAddress] {
get {
return dbRecord.addresses
}
set {
return dbRecord.addresses = newValue
}
}
@objc
public var emails: [OWSContactEmail] {
get {
return dbRecord.emails
}
set {
dbRecord.emails = newValue
}
}
@objc
public var phoneNumbers: [OWSContactPhoneNumber] {
get {
return dbRecord.phoneNumbers
}
set {
dbRecord.phoneNumbers = newValue
}
}
@objc
public func systemContactsWithSignalAccountPhoneNumbers(_ contactsManager: ContactsManagerProtocol) -> [String] {
return dbRecord.systemContactsWithSignalAccountPhoneNumbers(contactsManager)
}
@objc
public func systemContactPhoneNumbers(_ contactsManager: ContactsManagerProtocol) -> [String] {
return dbRecord.systemContactPhoneNumbers(contactsManager)
}
@objc
public func e164PhoneNumbers() -> [String] {
return dbRecord.e164PhoneNumbers()
}
@objc
public var displayName: String {
return dbRecord.name.displayName
}
@objc
public var ows_isValid: Bool {
return dbRecord.ows_isValid()
}
@objc
public var isProfileAvatar: Bool {
return dbRecord.isProfileAvatar
}
@objc
public func copy(withName name: OWSContactName) -> ContactShareViewModel {
// TODO move the `copy` logic into the view model?
let newDbRecord = dbRecord.copy(with: name)
return ContactShareViewModel(contactShareRecord: newDbRecord, avatarImageData: self.avatarImageData)
}
@objc
public func newContact(withName name: OWSContactName) -> ContactShareViewModel {
// TODO move the `newContact` logic into the view model?
let newDbRecord = dbRecord.newContact(with: name)
// If we want to keep the avatar image, the caller will need to re-apply it.
return ContactShareViewModel(contactShareRecord: newDbRecord, avatarImageData: nil)
}
}
| 4adf8fd4df814ae193b721e7b0b15bf1 | 28.660714 | 118 | 0.633955 | false | false | false | false |
3DprintFIT/octoprint-ios-client | refs/heads/dev | OctoPhone/View Related/Detail/DetailViewModel.swift | mit | 1 | //
// DetailViewModel.swift
// OctoPhone
//
// Created by Josef Dolezal on 30/04/2017.
// Copyright © 2017 Josef Dolezal. All rights reserved.
//
import ReactiveSwift
import Result
import class UIKit.UIImage
import Moya
import Icons
// MARK: - Inputs
/// Printer detail logic inputs
protocol DetailViewModelInputs {
/// Call when screen is about to appear
func viewWillAppear()
/// Call when user tap on controls button
func controlsButtonTapped()
/// Call when user tap on connect printer button
func connectButtonTapped()
/// Call when user want to cancel current print job
func cancelJobButtonTapped()
/// Call when user tapped on bed temperature cell to display temperature settings
func bedCellTapped()
}
// MARK: - Outputs
/// Printer detail logic outputs
protocol DetailViewModelOutputs {
/// Screen title
var title: Property<String> { get }
/// Indicates whether the content is currently available
var contentIsAvailable: Property<Bool> { get }
/// Text representation of printer state
var printerState: Property<String> { get }
/// Preview image of job or placeholder if it's not available
var jobPreview: Property<UIImage> { get }
/// Title of current job
var jobTitle: Property<String> { get }
/// Name of currently printed file
var fileName: Property<String> { get }
/// Indicates for how long is file beeing printed
var printTime: Property<String> { get }
/// Estimated timed of print end
var estimatedPrintTime: Property<String> { get }
/// Current temperature of printer bed
var bedTemperature: Property<String> { get }
/// Target temperature of printer bed
var bedTemperaturTarget: Property<String> { get }
/// Printer bed offset temperature
var bedTemperatureOffset: Property<String> { get }
/// Current temperature of printer tool
var toolTemperature: Property<String> { get }
/// Target temperature of printer tool
var toolTemperaturTarget: Property<String> { get }
/// Printer tool offset temperature
var toolTemperatureOffset: Property<String> { get }
/// Indicates whether the current job is cancellable
var jobCancellable: Property<Bool> { get }
/// Streams which indicates when data should be reloaded
var dataChanged: SignalProducer<(), NoError> { get }
/// Stream of errors displayable to user
var displayError: SignalProducer<DisplayableError, NoError> { get }
}
// MARK: - Common public interface
/// Common interface for detail View Models
protocol DetailViewModelType {
/// Available inputs
var inputs: DetailViewModelInputs { get }
/// Available outputs
var outputs: DetailViewModelOutputs { get }
}
// MARK: - View Model implementation
/// Printer detail logic
final class DetailViewModel: DetailViewModelType, DetailViewModelInputs, DetailViewModelOutputs {
var inputs: DetailViewModelInputs { return self }
var outputs: DetailViewModelOutputs { return self }
// MARK: Inputs
// MARK: Outputs
let title = Property(value: tr(.printerDetail))
let contentIsAvailable: Property<Bool>
let printerState: Property<String>
let jobPreview: Property<UIImage>
let jobTitle: Property<String>
let fileName: Property<String>
let printTime: Property<String>
let estimatedPrintTime: Property<String>
let bedTemperature: Property<String>
let bedTemperaturTarget: Property<String>
let bedTemperatureOffset: Property<String>
let toolTemperature: Property<String>
let toolTemperaturTarget: Property<String>
let toolTemperatureOffset: Property<String>
let jobCancellable: Property<Bool>
let dataChanged: SignalProducer<(), NoError>
let displayError: SignalProducer<DisplayableError, NoError>
// MARK: Private properties
/// Current printer value
private let printerProperty = MutableProperty<Printer?>(nil)
/// Indicates whether the content is available, broadcasts its value
private let contentIsAvailableProperty = MutableProperty(false)
/// Current bed value
private let bedProperty = MutableProperty<Bed?>(nil)
/// Current job value
private let jobProperty = MutableProperty<Job?>(nil)
/// Current state value
private let stateProperty = MutableProperty<PrinterState?>(nil)
/// Holds last value of tool property
private let toolProperty = MutableProperty<Tool?>(nil)
/// Last error occured
private let displayErrorProperty = MutableProperty<DisplayableError?>(nil)
/// Stream image
private let imageProperty = MutableProperty<UIImage?>(nil)
/// Printer requests provider
private let provider: OctoPrintProvider
/// Push events from OctoPrint
private var sockets: Disposable?
/// User content requests provider
private let staticProvider = StaticContentProvider()
/// Database connection manager
private let contextManager: ContextManagerType
/// Timer to download stream image
private var streamTimerDisposable: Disposable?
/// Detail flow delegate
private weak var delegate: DetailViewControllerDelegate?
// MARK: Initializers
// swiftlint:disable function_body_length
init(delegate: DetailViewControllerDelegate, provider: OctoPrintProvider,
contextManager: ContextManagerType, printerID: String) {
self.delegate = delegate
self.provider = provider
self.contextManager = contextManager
let streamTimer = timer(interval: DispatchTimeInterval.seconds(10), on: QueueScheduler.main)
let stateProducer = stateProperty.producer.skipNil()
let jobProducer = jobProperty.producer.skipNil()
let bedProducer = bedProperty.producer.skipNil()
let printerProducer = printerProperty.producer.skipNil()
let toolProducer = toolProperty.producer.skipNil()
let imageProducer = imageProperty.producer.skipNil()
self.displayError = displayErrorProperty.producer.skipNil()
self.contentIsAvailable = Property(capturing: contentIsAvailableProperty)
self.printerState = Property(initial: tr(.unknown), then: stateProducer.map({ $0.state }))
self.jobTitle = Property(initial: tr(.unknown),
then: jobProducer.map({ $0.fileName }).skipNil())
self.fileName = Property(initial: tr(.unknown),
then: jobProducer.map({ $0.fileName }).skipNil())
self.printTime = Property(initial: tr(.unknown),
then: jobProducer.map({ $0.printTime.value }).skipNil().formatDuration())
self.estimatedPrintTime = Property(initial: tr(.unknown),
then: jobProducer.map({ $0.printTimeLeft.value }).skipNil().formatDuration())
self.bedTemperature = Property(initial: tr(.unknown),
then: bedProducer.map({ $0.actualTemperature }).formatTemperature())
self.bedTemperaturTarget = Property(initial: tr(.unknown),
then: bedProducer.map({ $0.targetTemperature }).formatTemperature())
self.bedTemperatureOffset = Property(initial: tr(.unknown),
then: bedProducer.map({ $0.offsetTemperature }).formatTemperature())
self.toolTemperature = Property(initial: tr(.unknown),
then: toolProducer.map({ $0.actualTemperature }).formatTemperature())
self.toolTemperaturTarget = Property(initial: tr(.unknown),
then: toolProducer.map({ $0.targetTemperature }).formatTemperature())
self.toolTemperatureOffset = Property(initial: tr(.unknown),
then: toolProducer.map({ $0.offsetTemperature }).formatTemperature())
self.jobPreview = Property(initial: FontAwesomeIcon.lightBulbIcon.image(ofSize: CGSize(width: 60, height: 60),
color: Colors.Pallete.greyHue3),
then: imageProducer)
let dataChanged = SignalProducer.combineLatest(stateProducer, jobProducer, bedProducer,
printerProperty.producer).ignoreValues()
let jobCancellable = SignalProducer.combineLatest(
jobProducer.map(DetailViewModel.validJob),
contentIsAvailable.producer
).map({ return $0 && $1 })
self.jobCancellable = Property(initial: false, then: jobCancellable)
self.dataChanged = SignalProducer.merge([dataChanged, contentIsAvailable.producer.ignoreValues()])
printerProducer.map({ $0.streamUrl }).skipNil().flatMap(.latest) { url in
return self.staticProvider.request(.get(url))
}
.startWithResult { [weak self] result in
switch result {
case let .success(response): self?.imageProperty.value = UIImage(data: response.data)
case .failure: self?.displayErrorProperty.value = (tr(.anErrorOccured),
tr(.couldNotLoadPrinterStream))
}
}
self.streamTimerDisposable = streamTimer.startWithValues { [weak self] _ in
self?.printerProperty.value = self?.printerProperty.value
}
loadPrinter(with: printerID)
requestData()
watchData()
}
// MARK: Input methods
func controlsButtonTapped() {
delegate?.controlsButtonTapped()
}
func connectButtonTapped() {
delegate?.connectButtonTapped()
}
func viewWillAppear() {
requestData()
}
func cancelJobButtonTapped() {
cancelPrintJob()
}
func bedCellTapped() {
delegate?.bedCellTapped()
}
// MARK: Output methods
// MARK: Internal logic
/// Loads printer object from local storage by it's identifier
///
/// - Parameter printerID: Identifier of printer which will be loaded
private func loadPrinter(with printerID: String) {
self.contextManager.createObservableContext()
.fetch(Printer.self, forPrimaryKey: printerID)
.startWithResult { [weak self] result in
switch result {
case let .success(printer): self?.printerProperty.value = printer
case .failure: self?.displayErrorProperty.value = (tr(.anErrorOccured),
tr(.couldNotLoadPrinter))
}
}
}
/// Requests all needed data for printer detail screen,
/// chains PrinterState, CurrentJob and CurrentBedState requests
private func requestData() {
provider.request(.currentPrinterState)
.filterSuccessfulStatusCodes()
.mapJSON()
.mapTo(object: PrinterState.self)
.flatMap(.latest) { state -> SignalProducer<Any, MoyaError> in
self.stateProperty.value = state
return self.provider.request(.currentJob).filterSuccessfulStatusCodes().mapJSON()
}
.mapTo(object: Job.self)
.flatMap(.latest) { job -> SignalProducer<Any, MoyaError> in
self.jobProperty.value = job
return self.provider.request(.currentToolState).filterSuccessfulStatusCodes().mapJSON()
}
.mapDictionary(collectionOf: Tool.self)
.flatMap(.latest) { tools -> SignalProducer<Any, MoyaError> in
self.toolProperty.value = tools.first
return self.provider.request(.currentBedState).filterSuccessfulStatusCodes().mapJSON()
}
.mapTo(object: Bed.self, forKeyPath: "bed")
.startWithResult { result in
if case let .success(bed) = result {
self.bedProperty.value = bed
self.contentIsAvailableProperty.value = true
}
if case .failure = result {
self.contentIsAvailableProperty.value = false
}
}
}
/// Cancels current print job and refreshes current data screen
private func cancelPrintJob() {
provider.request(.cancelJob)
.startWithResult { [weak self] _ in
self?.requestData()
}
}
/// Determines whether the job is valid
///
/// - Parameter job: Job to be validated
/// - Returns: True if job is valid, false otherwise
private static func validJob(_ job: Job) -> Bool {
return job.fileName != nil && job.fileSize.value != nil && job.printTimeLeft.value != nil
}
/// Setup temperatures watch
private func watchData() {
sockets = OctoPrintPushEvents(url: provider.baseURL)
.temperatures()
.startWithValues({ [weak self] bed, tool in
self?.bedProperty.value = bed
self?.toolProperty.value = tool
})
}
deinit {
streamTimerDisposable?.dispose()
sockets?.dispose()
}
}
| 26da64ceffc1bdf8817aba714ea7a375 | 34.50134 | 120 | 0.637593 | false | false | false | false |
bridger/SwiftVisualFormat | refs/heads/master | SwiftVisualFormat/ViewController.swift | mit | 1 | //
// ViewController.swift
// SwiftVisualFormat
//
// Created by Bridger Maxwell on 8/1/14.
// Copyright (c) 2014 Bridger Maxwell. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let redView = UIView()
redView.backgroundColor = UIColor.redColor()
redView.translatesAutoresizingMaskIntoConstraints = false
self.view.addSubview(redView)
let greenView = UIView()
greenView.backgroundColor = UIColor.greenColor()
greenView.translatesAutoresizingMaskIntoConstraints = false
self.view.addSubview(greenView)
let blueView = UIView()
blueView.backgroundColor = UIColor.blueColor()
blueView.translatesAutoresizingMaskIntoConstraints = false
self.view.addSubview(blueView)
self.view.addConstraints(horizontalConstraints( |-5-[redView]-0-[greenView]-0-[blueView]-5-| ))
self.view.addConstraints(horizontalConstraints( [redView == greenView] ))
self.view.addConstraints(horizontalConstraints( [blueView == greenView] ))
self.view.addConstraints(verticalConstraints( |-5-[redView]-5-| ))
self.view.addConstraints(verticalConstraints( |-5-[greenView]-5-| ))
self.view.addConstraints(verticalConstraints( |-5-[blueView]-5-| ))
}
}
| 8e59b44699ffd08875d0eaa51a780f03 | 34.439024 | 103 | 0.651067 | false | false | false | false |
Pyroh/Fluor | refs/heads/main | Fluor/Controllers/ViewControllers/RulesEditorViewController.swift | mit | 1 | //
// RulesEditorViewController.swift
//
// Fluor
//
// MIT License
//
// Copyright (c) 2020 Pierre Tacchi
//
// 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 Cocoa
class RulesEditorViewController: NSViewController, BehaviorDidChangeObserver {
@IBOutlet weak var tableView: NSTableView!
@IBOutlet var itemsArrayController: NSArrayController!
@IBOutlet weak var contentActionSegmentedControl: NSSegmentedControl!
@objc dynamic var rulesSet = Set<Rule>()
@objc dynamic var searchPredicate: NSPredicate?
@objc dynamic var sortDescriptors: [NSSortDescriptor] = [.init(key: "name", ascending: true, selector: #selector(NSString.caseInsensitiveCompare(_:)))]
private var tableContentAnimator: TableViewContentAnimator<Rule>!
override func viewDidLoad() {
super.viewDidLoad()
self.startObservingBehaviorDidChange()
itemsArrayController.addObserver(self, forKeyPath: "canRemove", options: [], context: nil)
itemsArrayController.addObserver(self, forKeyPath: "canAdd", options: [], context: nil)
self.rulesSet = AppManager.default.rules
self.tableContentAnimator = TableViewContentAnimator(tableView: tableView, arrayController: itemsArrayController)
}
deinit {
stopObservingBehaviorDidChange()
itemsArrayController.removeObserver(self, forKeyPath: "canRemove")
itemsArrayController.removeObserver(self, forKeyPath: "canAdd")
}
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
guard (object as? NSArrayController) == itemsArrayController, let keyPath = keyPath else { return }
switch keyPath {
case "canAdd":
contentActionSegmentedControl.setEnabled(itemsArrayController.canAdd, forSegment: 0)
case "canRemove":
contentActionSegmentedControl.setEnabled(itemsArrayController.canRemove, forSegment: 1)
default:
return
}
}
// MARK: - BehaviorDidChangeObserver
/// Called when a rule change for an application.
///
/// - parameter notification: The notification.
func behaviorDidChangeForApp(notification: Notification) {
guard let userInfo = notification.userInfo as? [String: Any], userInfo["source"] as? NotificationSource != .rule else { return }
guard let id = userInfo["id"] as? String, let behavior = userInfo["behavior"] as? AppBehavior, let url = userInfo["url"] as? URL else { return }
if let item = rulesSet.first(where: { $0.id == id }) {
if case .inferred = behavior {
itemsArrayController.removeObject(item)
} else {
item.behavior = behavior
}
} else if behavior != .inferred {
let item = Rule(id: id, url: url, behavior: behavior)
rulesSet.insert(item)
}
}
// MARK: - Private functions
/// Add a rule for an application.
private func addRule() {
let openPanel = NSOpenPanel()
openPanel.allowsMultipleSelection = true
openPanel.allowedFileTypes = ["com.apple.bundle"]
openPanel.canChooseDirectories = false
openPanel.directoryURL = URL(fileURLWithPath: "/Applications")
openPanel.runModal()
let items = openPanel.urls.map { (url) -> Rule in
let bundle = Bundle(url: url)!
let id = bundle.bundleIdentifier!
AppManager.default.propagate(behavior: .media, forApp: id, at: url, from: .rule)
return Rule(id: id, url: url, behavior: .media)
}
rulesSet.formUnion(items)
}
/// Remove a rule for a given application.
private func removeRule() {
guard let items = itemsArrayController.selectedObjects as? [Rule] else { return }
items.forEach { (item) in
AppManager.default.propagate(behavior: .inferred, forApp: item.id, at: item.url, from: .rule)
}
itemsArrayController.remove(self)
}
// MARK: - Actions
@IBAction func operateRuleCollection(_ sender: NSSegmentedControl) {
switch sender.selectedSegment {
case 0:
self.addRule()
default:
self.removeRule()
}
}
}
| 73f1a2d4b7a9cee87b895f3583f33064 | 39.348148 | 155 | 0.664953 | false | false | false | false |
ali-zahedi/AZViewer | refs/heads/master | AZViewer/AZHeader.swift | apache-2.0 | 1 | //
// AZHeader.swift
// AZViewer
//
// Created by Ali Zahedi on 1/14/1396 AP.
// Copyright © 1396 AP Ali Zahedi. All rights reserved.
//
import Foundation
public enum AZHeaderType {
case title
case success
}
public class AZHeader: AZBaseView{
// MARK: Public
public var title: String = ""{
didSet{
self.titleLabel.text = self.title
}
}
public var type: AZHeaderType! {
didSet{
let hiddenTitle: Bool = self.type == .success ? true : false
self.successButton.isHidden = !hiddenTitle
self.titleLabel.aZConstraints.right?.isActive = false
if hiddenTitle {
_ = self.titleLabel.aZConstraints.right(to: self.successButton, toAttribute: .left,constant: -self.style.sectionGeneralConstant)
}else{
_ = self.titleLabel.aZConstraints.right(constant: -self.style.sectionGeneralConstant)
}
}
}
public var rightButtonTintColor: UIColor! {
didSet{
self.successButton.tintColor = self.rightButtonTintColor
}
}
public var leftButtonTintColor: UIColor! {
didSet{
self.closeButton.tintColor = self.leftButtonTintColor
}
}
// MARK: Internal
internal var delegate: AZPopupViewDelegate?
// MARK: Private
fileprivate var titleLabel: AZLabel = AZLabel()
fileprivate var closeButton: AZButton = AZButton()
fileprivate var successButton: AZButton = AZButton()
// MARK: Override
override init(frame: CGRect) {
super.init(frame: frame)
self.defaultInit()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.defaultInit()
}
// MARK: Function
fileprivate func defaultInit(){
self.backgroundColor = self.style.sectionHeaderBackgroundColor
for v in [titleLabel, closeButton, successButton] as [UIView]{
v.translatesAutoresizingMaskIntoConstraints = false
self.addSubview(v)
}
// title
self.prepareTitle()
// close button
self.prepareCloseButton()
// success button
self.prepareSuccessButton()
// init
self.type = .title
}
// cancell action
func cancelButtonAction(_ sender: AZButton){
self.delegate?.cancelPopupView()
}
// success action
func successButtonAction(_ sender: AZButton){
self.delegate?.submitPopupView()
}
}
// prepare
extension AZHeader{
// title
fileprivate func prepareTitle(){
_ = self.titleLabel.aZConstraints.parent(parent: self).centerY().right(constant: -self.style.sectionGeneralConstant).left(multiplier: 0.7)
self.titleLabel.textColor = self.style.sectionHeaderTitleColor
self.titleLabel.font = self.style.sectionHeaderTitleFont
}
// close
fileprivate func prepareCloseButton(){
let height = self.style.sectionHeaderHeight * 0.65
_ = self.closeButton.aZConstraints.parent(parent: self).centerY().left(constant: self.style.sectionGeneralConstant).width(constant: height).height(to: self.closeButton, toAttribute: .width)
self.closeButton.setImage(AZAssets.closeImage, for: .normal)
self.closeButton.tintColor = self.style.sectionHeaderLeftButtonTintColor
self.closeButton.addTarget(self, action: #selector(cancelButtonAction(_:)), for: .touchUpInside)
}
// success
fileprivate func prepareSuccessButton(){
let height = self.style.sectionHeaderHeight * 0.65
_ = self.successButton.aZConstraints.parent(parent: self).centerY().right(constant: -self.style.sectionGeneralConstant).width(constant: height).height(to: self.closeButton, toAttribute: .width)
self.successButton.setImage(AZAssets.tickImage, for: .normal)
self.successButton.tintColor = self.style.sectionHeaderRightButtonTintColor
self.successButton.addTarget(self, action: #selector(successButtonAction(_:)), for: .touchUpInside)
}
}
| 557a7ea8047e5693c5a24483d902db5b | 29.366197 | 201 | 0.622913 | false | false | false | false |
mattiasjahnke/arduino-projects | refs/heads/master | music-controller/Mac app/NowPlayingTest/MusicController.swift | mit | 1 | //
// MusicApps.swift
// SerialController
//
// Created by Mattias Jähnke on 2017-06-10.
// Copyright © 2017 Mattias Jähnke. All rights reserved.
//
import Foundation
private let apps = [MusicApp("Spotify", notification: "com.spotify.client.PlaybackStateChanged"),
MusicApp("iTunes", notification: "com.apple.iTunes.playerInfo")]
class MusicController {
private var listeners = [NSObjectProtocol]()
private var changed: (Track?) -> ()
var currentTrack: Track? {
for app in apps {
if let components = app.nowPlaying?.components(separatedBy: ":€:"), components.count == 2 {
return Track(artist: components[0], song: components[1])
}
}
return nil
}
private var app: MusicApp? {
return apps.first { $0.isOpen }
}
static var systemVolume: Int {
get { return 0 }
set { "set volume output volume (\(newValue))".execute() }
}
init(changed: @escaping (Track?) -> ()) {
self.changed = changed
for name in apps.map({ $0.notification }) {
let o = DistributedNotificationCenter.default.addObserver(forName: name, object: nil, queue: nil) { _ in
let track = self.currentTrack
print(nowPlayingString(for: track))
self.changed(track)
}
listeners.append(o)
}
}
func togglePlayPause() {
app?.togglePlayPause()
}
func nextTrack() {
app?.playNext()
}
func previousTrack() {
app?.playPrevious()
}
deinit {
for listener in listeners {
DistributedNotificationCenter.default.removeObserver(listener)
}
}
}
struct Track {
let artist: String
let song: String
}
private struct MusicApp {
let applicationName: String
let notification: NSNotification.Name
init(_ applicationName: String, notification: String) {
self.applicationName = applicationName
self.notification = NSNotification.Name(rawValue: notification)
}
var nowPlaying: String? {
let script = """
if application "\(applicationName)\" is running then
tell application "\(applicationName)"
if player state is playing then
return (get artist of current track) & ":€:" & (get name of current track)
else
return ""
end if
end tell
else
return ""
end if
"""
return script.execute().stringValue.flatMap { $0.isEmpty ? nil : $0 }
}
var isOpen: Bool {
return "return application \"\(applicationName)\" is running".execute().booleanValue
}
func togglePlayPause() {
"tell application \"\(applicationName)\" to playpause".execute()
}
func playNext() {
"tell application \"\(applicationName)\" to play next track".execute()
}
func playPrevious() {
"tell application \"\(applicationName)\" to play previous track".execute()
}
}
private extension String {
@discardableResult
func execute() -> NSAppleEventDescriptor {
return NSAppleScript(source: self)!.executeAndReturnError(nil)
}
}
| 5f0d9a57b6450818bc4b00fd6dcee195 | 26.446281 | 116 | 0.578741 | false | false | false | false |
Jens-G/thrift | refs/heads/master | test/swift/CrossTests/Sources/Common/Parameters.swift | apache-2.0 | 3 | // Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you 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 Thrift
public enum Protocol: String {
case binary
case compact
case header
case json
}
public enum Transport: String {
case buffered
case framed
case http
case anonpipe
case zlib
}
public enum ServerType: String {
case simple
case threadPool = "thread-pool"
case threaded
case nonblocking
}
public enum ParserError: Error {
case unknownArgument(argument: String)
case missingParameter(argument: String)
case invalidParameter(argument: String, parameter: String)
case unsupportedOption
}
public class ParametersBase {
public var showHelp = false
public var port: Int?
public var domainSocket: String?
public var namedPipe: String?
public var proto: Protocol?
public var transport: Transport?
public var multiplex = false
public var abstractNamespace = false
public var ssl = false
public var zlib = false
public init (arguments: [String]) throws {
if arguments.count > 1 {
for argument in arguments[1...] {
let equalSignPos = argument.firstIndex(of: "=") ?? argument.endIndex
let name = String(argument[..<equalSignPos])
let value: String? = (equalSignPos < argument.endIndex) ? String(argument[argument.index(equalSignPos, offsetBy: 1)..<argument.endIndex]) : nil
try processArgument(name: name, value: value)
}
}
fillDefaults()
try checkSupported()
}
open func processArgument(name: String, value: String?) throws {
switch name {
case "-h", "--help":
showHelp = true
case "--port":
guard value != nil else { throw ParserError.missingParameter(argument: name) }
port = Int(value!)
guard port != nil else { throw ParserError.invalidParameter(argument: name, parameter: value!) }
case "--domain-socket":
guard value != nil else { throw ParserError.missingParameter(argument: name) }
domainSocket = value!
case "--named-pipe":
guard value != nil else { throw ParserError.missingParameter(argument: name) }
namedPipe = value!
case "--transport":
guard value != nil else { throw ParserError.missingParameter(argument: name) }
transport = Transport(rawValue: value!)
guard transport != nil else { throw ParserError.invalidParameter(argument: name, parameter: value!) }
case "--protocol":
guard value != nil else { throw ParserError.missingParameter(argument: name) }
proto = Protocol(rawValue: value!)
guard proto != nil else { throw ParserError.invalidParameter(argument: name, parameter: value!) }
case "--multiplex":
multiplex = true
case "--abstract-namespace":
abstractNamespace = true
case "--ssl":
ssl = true
case "--zlib":
zlib = true
default:
throw ParserError.unknownArgument(argument: name)
}
}
open func fillDefaults() {
if port == nil && domainSocket == nil && namedPipe == nil {
port = 9090
}
if transport == nil {
transport = .buffered
}
if proto == nil {
proto = .binary
}
}
open func checkSupported() throws {
guard transport == .buffered || transport == .framed else { throw ParserError.unsupportedOption }
guard proto == .binary || proto == .compact else { throw ParserError.unsupportedOption }
}
}
public class TestClientParameters: ParametersBase {
public var host: String?
public var testLoops: Int?
public var threads: Int?
public func printHelp() {
print("""
Allowed options:
-h | --help produce help message
--host=arg (localhost) Host to connect
--port=arg (9090) Port number to connect
--domain-socket=arg Domain Socket (e.g. /tmp/ThriftTest.thrift),
instead of host and port
--named-pipe=arg Windows Named Pipe (e.g. MyThriftPipe)
--anon-pipes hRead hWrite Windows Anonymous Pipes pair (handles)
--abstract-namespace Create the domain socket in the Abstract Namespace
(no connection with filesystem pathnames)
--transport=arg (buffered) Transport: buffered, framed, http, evhttp, zlib
--protocol=arg (binary) Protocol: binary, compact, header, json
--multiplex Add TMultiplexedProtocol service name "ThriftTest"
--ssl Encrypted Transport using SSL
--zlib Wrap Transport with Zlib
-n=arg | --testloops=arg (1) Number of Tests
-t=arg | --threads=arg (1) Number of Test threads
""")
}
open override func processArgument(name: String, value: String?) throws {
switch name {
case "--host":
guard value != nil else { throw ParserError.missingParameter(argument: name) }
host = value!
case "-n", "--testloops":
guard value != nil else { throw ParserError.missingParameter(argument: name) }
testLoops = Int(value!)
guard testLoops != nil else { throw ParserError.invalidParameter(argument: name, parameter: value!) }
case "-t", "--threads":
guard value != nil else { throw ParserError.missingParameter(argument: name) }
threads = Int(value!)
guard threads != nil else { throw ParserError.invalidParameter(argument: name, parameter: value!) }
default:
try super.processArgument(name: name, value: value)
}
}
open override func fillDefaults() {
super.fillDefaults()
if host == nil {
host = "localhost"
}
if testLoops == nil {
testLoops = 1
}
if threads == nil {
threads = 4
}
}
}
public class TestServerParameters: ParametersBase {
public var serverType: ServerType?
public var processorEvents = false
public var workers: Int?
public func printHelp() {
print("""
Allowed options:
-h | --help produce help message
--port=arg (=9090) Port number to listen
--domain-socket=arg Unix Domain Socket (e.g. /tmp/ThriftTest.thrift)
--named-pipe=arg Windows Named Pipe (e.g. MyThriftPipe)
--server-type=arg (=simple) type of server, "simple", "thread-pool",
"threaded", or "nonblocking"
--transport=arg (=buffered) transport: buffered, framed, http, anonpipe, zlib
--protocol=arg (=binary) protocol: binary, compact, header, json
--multiplex Add TMultiplexedProtocol service name "ThriftTest"
--abstract-namespace Create the domain socket in the Abstract Namespace
(no connection with filesystem pathnames)
--ssl Encrypted Transport using SSL
--zlib Wrapped Transport using Zlib
--processor-events processor-events
-n=arg | --workers=arg (=4) Number of thread pools workers. Only valid for
thread-pool server type
""")
}
open override func processArgument(name: String, value: String?) throws {
switch name {
case "--server-type":
guard value != nil else { throw ParserError.missingParameter(argument: name) }
serverType = ServerType(rawValue: value!)
guard serverType != nil else { throw ParserError.invalidParameter(argument: name, parameter: value!) }
case "--processor-events":
processorEvents = true
case "-n", "--workers":
guard value != nil else { throw ParserError.missingParameter(argument: name) }
workers = Int(value!)
guard workers != nil else { throw ParserError.invalidParameter(argument: name, parameter: value!) }
default:
try super.processArgument(name: name, value: value)
}
}
open override func fillDefaults() {
super.fillDefaults()
if serverType == nil {
serverType = .simple
}
if workers == nil {
workers = 4
}
}
open override func checkSupported() throws {
try super.checkSupported()
guard serverType == .simple else { throw ParserError.unsupportedOption }
}
}
| 65d141566032a6de4569313efc528aa7 | 33.472656 | 151 | 0.647932 | false | true | false | false |
kmikiy/SpotMenu | refs/heads/master | SpotMenu/StatusBar/StatusItemBuilder.swift | mit | 1 | //
// StatusItemBuilder.swift
// SpotMenu
//
// Created by Miklós Kristyán on 2017. 05. 01..
// Copyright © 2017. KM. All rights reserved.
//
import Foundation
final class StatusItemBuilder {
// MARK: - Properties
private var title = ""
private var artist = ""
private var albumName = ""
private var playingIcon = ""
private var isPlaying: Bool = false
private var hideWhenPaused = false
// MARK: - Lifecycle method
init(title: String?, artist: String?, albumName: String?, isPlaying: Bool) {
if let v = title {
self.title = v
}
if let v = artist {
self.artist = v
}
if let v = albumName {
self.albumName = v
}
self.isPlaying = isPlaying
}
// MARK: - Methods
func hideWhenPaused(v: Bool) -> StatusItemBuilder {
hideWhenPaused = v
return self
}
func showTitle(v: Bool) -> StatusItemBuilder {
if !v {
title = ""
return self
}
if !isPlaying && hideWhenPaused {
title = ""
return self
}
return self
}
func showArtist(v: Bool) -> StatusItemBuilder {
if !v {
artist = ""
return self
}
if !isPlaying && hideWhenPaused {
artist = ""
return self
}
return self
}
func showAlbumName(v: Bool) -> StatusItemBuilder {
if !v {
albumName = ""
return self
}
if !isPlaying && hideWhenPaused {
albumName = ""
return self
}
return self
}
func showPlayingIcon(v: Bool) -> StatusItemBuilder {
if !v {
playingIcon = ""
return self
}
if isPlaying {
playingIcon = "♫ "
} else {
playingIcon = ""
}
return self
}
func getString() -> String {
if artist.count != 0 && title.count != 0 && albumName.count != 0 {
return "\(playingIcon)\(artist) - \(title) - \(albumName)"
} else if artist.count != 0 && title.count != 0 {
return "\(playingIcon)\(artist) - \(title)"
}
return "\(playingIcon)\(artist)\(title)"
}
}
| 53736eb1b59056ada8d6959825ddeca7 | 21.920792 | 80 | 0.493305 | false | false | false | false |
TeamYYZ/DineApp | refs/heads/master | Dine/DescriptionEditViewController.swift | gpl-3.0 | 1 | //
// DescriptionEditViewController.swift
// Dine
//
// Created by Senyang Zhuang on 4/6/16.
// Copyright © 2016 YYZ. All rights reserved.
//
import UIKit
@objc protocol DescriptionEditViewControllerDelegate {
optional func descriptionEditting(descriptionEditting: DescriptionEditViewController, didUpdateDescription updatedDescription: String?)
}
class DescriptionEditViewController: UITableViewController, UITextViewDelegate{
@IBOutlet weak var contentTextView: UITextView!
@IBOutlet weak var countDownLabel: UILabel!
weak var delegate: DescriptionEditViewControllerDelegate?
let user = User.currentUser!
var placeholderLabel = UILabel()
override func viewDidLoad() {
super.viewDidLoad()
self.contentTextView.delegate = self
let cancelButton = UIBarButtonItem(title: "Cancel", style: UIBarButtonItemStyle.Plain, target: self, action: #selector(DescriptionEditViewController.cancelButtonOnClick))
navigationItem.leftBarButtonItem = cancelButton
let doneButton = UIBarButtonItem(title: "Done", style: UIBarButtonItemStyle.Plain, target: self, action: #selector(DescriptionEditViewController.doneButtonOnClick))
navigationItem.rightBarButtonItem = doneButton
self.contentTextView.text = user.profileDescription
placeholderLabel.text = "Let's Dine"
placeholderLabel.font = UIFont.italicSystemFontOfSize(contentTextView.font!.pointSize)
placeholderLabel.sizeToFit()
contentTextView.addSubview(placeholderLabel)
placeholderLabel.frame.origin = CGPointMake(5, contentTextView.font!.pointSize / 2)
placeholderLabel.textColor = UIColor(white: 0, alpha: 0.3)
placeholderLabel.hidden = !contentTextView.text.isEmpty
if !self.contentTextView.text.isEmpty{
let textLength = contentTextView.text.characters.count
let leftChar = String(30 - textLength)
self.countDownLabel.text = leftChar
}
}
func textViewDidChange(textView: UITextView) {
placeholderLabel.hidden = !textView.text.isEmpty
if !textView.text.isEmpty{
let textLength = textView.text.characters.count
let leftChar = String(30 - textLength)
self.countDownLabel.text = leftChar
if leftChar == "0"{
}
}
}
func textView(textView: UITextView, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool {
if self.countDownLabel.text == "0" && range.length <= 0{
return false
}
else{
return true
}
}
func cancelButtonOnClick(){
self.dismissViewControllerAnimated(true, completion: nil)
}
func doneButtonOnClick(){
let text = self.contentTextView.text
self.user.updateDescription(text, withCompletion: { (success: Bool, error: NSError?) in
if success == true && error == nil{
self.delegate?.descriptionEditting!(self, didUpdateDescription: text)
self.dismissViewControllerAnimated(true, completion: nil)
}else{
print(error)
}
})
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return 1
}
/*
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath)
// Configure the cell...
return cell
}
*/
/*
// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
// Delete the row from the data source
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| 9f4059f12c5dd388a29e5efae61708cb | 31.586957 | 178 | 0.661441 | false | false | false | false |
gribozavr/swift | refs/heads/master | stdlib/public/core/UnsafeRawPointer.swift | apache-2.0 | 3 | //===--- UnsafeRawPointer.swift -------------------------------*- swift -*-===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
/// A raw pointer for accessing
/// untyped data.
///
/// The `UnsafeRawPointer` type provides no automated memory management, no type safety,
/// and no alignment guarantees. You are responsible for handling the life
/// cycle of any memory you work with through unsafe pointers, to avoid leaks
/// or undefined behavior.
///
/// Memory that you manually manage can be either *untyped* or *bound* to a
/// specific type. You use the `UnsafeRawPointer` type to access and
/// manage raw bytes in memory, whether or not that memory has been bound to a
/// specific type.
///
/// Understanding a Pointer's Memory State
/// ======================================
///
/// The memory referenced by an `UnsafeRawPointer` instance can be in one of several
/// states. Many pointer operations must only be applied to pointers with
/// memory in a specific state---you must keep track of the state of the
/// memory you are working with and understand the changes to that state that
/// different operations perform. Memory can be untyped and uninitialized,
/// bound to a type and uninitialized, or bound to a type and initialized to a
/// value. Finally, memory that was allocated previously may have been
/// deallocated, leaving existing pointers referencing unallocated memory.
///
/// Raw, Uninitialized Memory
/// -------------------------
///
/// Raw memory that has just been allocated is in an *uninitialized, untyped*
/// state. Uninitialized memory must be initialized with values of a type
/// before it can be used with any typed operations.
///
/// To bind uninitialized memory to a type without initializing it, use the
/// `bindMemory(to:count:)` method. This method returns a typed pointer
/// for further typed access to the memory.
///
/// Typed Memory
/// ------------
///
/// Memory that has been bound to a type, whether it is initialized or
/// uninitialized, is typically accessed using typed pointers---instances of
/// `UnsafePointer` and `UnsafeMutablePointer`. Initialization, assignment,
/// and deinitialization can be performed using `UnsafeMutablePointer`
/// methods.
///
/// Memory that has been bound to a type can be rebound to a different type
/// only after it has been deinitialized or if the bound type is a *trivial
/// type*. Deinitializing typed memory does not unbind that memory's type. The
/// deinitialized memory can be reinitialized with values of the same type,
/// bound to a new type, or deallocated.
///
/// - Note: A trivial type can be copied bit for bit with no indirection or
/// reference-counting operations. Generally, native Swift types that do not
/// contain strong or weak references or other forms of indirection are
/// trivial, as are imported C structs and enumerations.
///
/// When reading from memory as raw
/// bytes when that memory is bound to a type, you must ensure that you
/// satisfy any alignment requirements.
///
/// Raw Pointer Arithmetic
/// ======================
///
/// Pointer arithmetic with raw pointers is performed at the byte level. When
/// you add to or subtract from a raw pointer, the result is a new raw pointer
/// offset by that number of bytes. The following example allocates four bytes
/// of memory and stores `0xFF` in all four bytes:
///
/// let bytesPointer = UnsafeMutableRawPointer.allocate(byteCount: 4, alignment: 4)
/// bytesPointer.storeBytes(of: 0xFFFF_FFFF, as: UInt32.self)
///
/// // Load a value from the memory referenced by 'bytesPointer'
/// let x = bytesPointer.load(as: UInt8.self) // 255
///
/// // Load a value from the last two allocated bytes
/// let offsetPointer = bytesPointer + 2
/// let y = offsetPointer.load(as: UInt16.self) // 65535
///
/// The code above stores the value `0xFFFF_FFFF` into the four newly allocated
/// bytes, and then loads the first byte as a `UInt8` instance and the third
/// and fourth bytes as a `UInt16` instance.
///
/// Always remember to deallocate any memory that you allocate yourself.
///
/// bytesPointer.deallocate()
///
/// Implicit Casting and Bridging
/// =============================
///
/// When calling a function or method with an `UnsafeRawPointer` parameter, you can pass
/// an instance of that specific pointer type, pass an instance of a
/// compatible pointer type, or use Swift's implicit bridging to pass a
/// compatible pointer.
///
/// For example, the `print(address:as:)` function in the following code sample
/// takes an `UnsafeRawPointer` instance as its first parameter:
///
/// func print<T>(address p: UnsafeRawPointer, as type: T.Type) {
/// let value = p.load(as: type)
/// print(value)
/// }
///
/// As is typical in Swift, you can call the `print(address:as:)` function with
/// an `UnsafeRawPointer` instance. This example passes `rawPointer` as the initial
/// parameter.
///
/// // 'rawPointer' points to memory initialized with `Int` values.
/// let rawPointer: UnsafeRawPointer = ...
/// print(address: rawPointer, as: Int.self)
/// // Prints "42"
///
/// Because typed pointers can be implicitly cast to raw pointers when passed
/// as a parameter, you can also call `print(address:as:)` with any mutable or
/// immutable typed pointer instance.
///
/// let intPointer: UnsafePointer<Int> = ...
/// print(address: intPointer, as: Int.self)
/// // Prints "42"
///
/// let mutableIntPointer = UnsafeMutablePointer(mutating: intPointer)
/// print(address: mutableIntPointer, as: Int.self)
/// // Prints "42"
///
/// Alternatively, you can use Swift's *implicit bridging* to pass a pointer to
/// an instance or to the elements of an array. Use inout syntax to implicitly
/// create a pointer to an instance of any type. The following example uses
/// implicit bridging to pass a pointer to `value` when calling
/// `print(address:as:)`:
///
/// var value: Int = 23
/// print(address: &value, as: Int.self)
/// // Prints "23"
///
/// An immutable pointer to the elements of an array is implicitly created when
/// you pass the array as an argument. This example uses implicit bridging to
/// pass a pointer to the elements of `numbers` when calling
/// `print(address:as:)`.
///
/// let numbers = [5, 10, 15, 20]
/// print(address: numbers, as: Int.self)
/// // Prints "5"
///
/// You can also use inout syntax to pass a mutable pointer to the elements of
/// an array. Because `print(address:as:)` requires an immutable pointer,
/// although this is syntactically valid, it isn't necessary.
///
/// var mutableNumbers = numbers
/// print(address: &mutableNumbers, as: Int.self)
///
/// - Important: The pointer created through implicit bridging of an instance
/// or of an array's elements is only valid during the execution of the
/// called function. Escaping the pointer to use after the execution of the
/// function is undefined behavior. In particular, do not use implicit
/// bridging when calling an `UnsafeRawPointer` initializer.
///
/// var number = 5
/// let numberPointer = UnsafeRawPointer(&number)
/// // Accessing 'numberPointer' is undefined behavior.
@frozen
public struct UnsafeRawPointer: _Pointer {
public typealias Pointee = UInt8
/// The underlying raw pointer.
/// Implements conformance to the public protocol `_Pointer`.
public let _rawValue: Builtin.RawPointer
/// Creates a new raw pointer from a builtin raw pointer.
@_transparent
public init(_ _rawValue: Builtin.RawPointer) {
self._rawValue = _rawValue
}
/// Creates a new raw pointer from the given typed pointer.
///
/// Use this initializer to explicitly convert `other` to an `UnsafeRawPointer`
/// instance. This initializer creates a new pointer to the same address as
/// `other` and performs no allocation or copying.
///
/// - Parameter other: The typed pointer to convert.
@_transparent
public init<T>(@_nonEphemeral _ other: UnsafePointer<T>) {
_rawValue = other._rawValue
}
/// Creates a new raw pointer from the given typed pointer.
///
/// Use this initializer to explicitly convert `other` to an `UnsafeRawPointer`
/// instance. This initializer creates a new pointer to the same address as
/// `other` and performs no allocation or copying.
///
/// - Parameter other: The typed pointer to convert. If `other` is `nil`, the
/// result is `nil`.
@_transparent
public init?<T>(@_nonEphemeral _ other: UnsafePointer<T>?) {
guard let unwrapped = other else { return nil }
_rawValue = unwrapped._rawValue
}
/// Creates a new raw pointer from the given mutable raw pointer.
///
/// Use this initializer to explicitly convert `other` to an `UnsafeRawPointer`
/// instance. This initializer creates a new pointer to the same address as
/// `other` and performs no allocation or copying.
///
/// - Parameter other: The mutable raw pointer to convert.
@_transparent
public init(@_nonEphemeral _ other: UnsafeMutableRawPointer) {
_rawValue = other._rawValue
}
/// Creates a new raw pointer from the given mutable raw pointer.
///
/// Use this initializer to explicitly convert `other` to an `UnsafeRawPointer`
/// instance. This initializer creates a new pointer to the same address as
/// `other` and performs no allocation or copying.
///
/// - Parameter other: The mutable raw pointer to convert. If `other` is
/// `nil`, the result is `nil`.
@_transparent
public init?(@_nonEphemeral _ other: UnsafeMutableRawPointer?) {
guard let unwrapped = other else { return nil }
_rawValue = unwrapped._rawValue
}
/// Creates a new raw pointer from the given typed pointer.
///
/// Use this initializer to explicitly convert `other` to an `UnsafeRawPointer`
/// instance. This initializer creates a new pointer to the same address as
/// `other` and performs no allocation or copying.
///
/// - Parameter other: The typed pointer to convert.
@_transparent
public init<T>(@_nonEphemeral _ other: UnsafeMutablePointer<T>) {
_rawValue = other._rawValue
}
/// Creates a new raw pointer from the given typed pointer.
///
/// Use this initializer to explicitly convert `other` to an `UnsafeRawPointer`
/// instance. This initializer creates a new pointer to the same address as
/// `other` and performs no allocation or copying.
///
/// - Parameter other: The typed pointer to convert. If `other` is `nil`, the
/// result is `nil`.
@_transparent
public init?<T>(@_nonEphemeral _ other: UnsafeMutablePointer<T>?) {
guard let unwrapped = other else { return nil }
_rawValue = unwrapped._rawValue
}
/// Deallocates the previously allocated memory block referenced by this pointer.
///
/// The memory to be deallocated must be uninitialized or initialized to a
/// trivial type.
@inlinable
public func deallocate() {
// Passing zero alignment to the runtime forces "aligned
// deallocation". Since allocation via `UnsafeMutable[Raw][Buffer]Pointer`
// always uses the "aligned allocation" path, this ensures that the
// runtime's allocation and deallocation paths are compatible.
Builtin.deallocRaw(_rawValue, (-1)._builtinWordValue, (0)._builtinWordValue)
}
/// Binds the memory to the specified type and returns a typed pointer to the
/// bound memory.
///
/// Use the `bindMemory(to:capacity:)` method to bind the memory referenced
/// by this pointer to the type `T`. The memory must be uninitialized or
/// initialized to a type that is layout compatible with `T`. If the memory
/// is uninitialized, it is still uninitialized after being bound to `T`.
///
/// In this example, 100 bytes of raw memory are allocated for the pointer
/// `bytesPointer`, and then the first four bytes are bound to the `Int8`
/// type.
///
/// let count = 4
/// let bytesPointer = UnsafeMutableRawPointer.allocate(
/// bytes: 100,
/// alignedTo: MemoryLayout<Int8>.alignment)
/// let int8Pointer = bytesPointer.bindMemory(to: Int8.self, capacity: count)
///
/// After calling `bindMemory(to:capacity:)`, the first four bytes of the
/// memory referenced by `bytesPointer` are bound to the `Int8` type, though
/// they remain uninitialized. The remainder of the allocated region is
/// unbound raw memory. All 100 bytes of memory must eventually be
/// deallocated.
///
/// - Warning: A memory location may only be bound to one type at a time. The
/// behavior of accessing memory as a type unrelated to its bound type is
/// undefined.
///
/// - Parameters:
/// - type: The type `T` to bind the memory to.
/// - count: The amount of memory to bind to type `T`, counted as instances
/// of `T`.
/// - Returns: A typed pointer to the newly bound memory. The memory in this
/// region is bound to `T`, but has not been modified in any other way.
/// The number of bytes in this region is
/// `count * MemoryLayout<T>.stride`.
@_transparent
@discardableResult
public func bindMemory<T>(
to type: T.Type, capacity count: Int
) -> UnsafePointer<T> {
Builtin.bindMemory(_rawValue, count._builtinWordValue, type)
return UnsafePointer<T>(_rawValue)
}
/// Returns a typed pointer to the memory referenced by this pointer,
/// assuming that the memory is already bound to the specified type.
///
/// Use this method when you have a raw pointer to memory that has *already*
/// been bound to the specified type. The memory starting at this pointer
/// must be bound to the type `T`. Accessing memory through the returned
/// pointer is undefined if the memory has not been bound to `T`. To bind
/// memory to `T`, use `bindMemory(to:capacity:)` instead of this method.
///
/// - Parameter to: The type `T` that the memory has already been bound to.
/// - Returns: A typed pointer to the same memory as this raw pointer.
@_transparent
public func assumingMemoryBound<T>(to: T.Type) -> UnsafePointer<T> {
return UnsafePointer<T>(_rawValue)
}
/// Returns a new instance of the given type, constructed from the raw memory
/// at the specified offset.
///
/// The memory at this pointer plus `offset` must be properly aligned for
/// accessing `T` and initialized to `T` or another type that is layout
/// compatible with `T`.
///
/// - Parameters:
/// - offset: The offset from this pointer, in bytes. `offset` must be
/// nonnegative. The default is zero.
/// - type: The type of the instance to create.
/// - Returns: A new instance of type `T`, read from the raw bytes at
/// `offset`. The returned instance is memory-managed and unassociated
/// with the value in the memory referenced by this pointer.
@inlinable
public func load<T>(fromByteOffset offset: Int = 0, as type: T.Type) -> T {
_debugPrecondition(0 == (UInt(bitPattern: self + offset)
& (UInt(MemoryLayout<T>.alignment) - 1)),
"load from misaligned raw pointer")
return Builtin.loadRaw((self + offset)._rawValue)
}
}
extension UnsafeRawPointer: Strideable {
// custom version for raw pointers
@_transparent
public func advanced(by n: Int) -> UnsafeRawPointer {
return UnsafeRawPointer(Builtin.gepRaw_Word(_rawValue, n._builtinWordValue))
}
}
/// A raw pointer for accessing and manipulating
/// untyped data.
///
/// The `UnsafeMutableRawPointer` type provides no automated memory management, no type safety,
/// and no alignment guarantees. You are responsible for handling the life
/// cycle of any memory you work with through unsafe pointers, to avoid leaks
/// or undefined behavior.
///
/// Memory that you manually manage can be either *untyped* or *bound* to a
/// specific type. You use the `UnsafeMutableRawPointer` type to access and
/// manage raw bytes in memory, whether or not that memory has been bound to a
/// specific type.
///
/// Understanding a Pointer's Memory State
/// ======================================
///
/// The memory referenced by an `UnsafeMutableRawPointer` instance can be in one of several
/// states. Many pointer operations must only be applied to pointers with
/// memory in a specific state---you must keep track of the state of the
/// memory you are working with and understand the changes to that state that
/// different operations perform. Memory can be untyped and uninitialized,
/// bound to a type and uninitialized, or bound to a type and initialized to a
/// value. Finally, memory that was allocated previously may have been
/// deallocated, leaving existing pointers referencing unallocated memory.
///
/// Raw, Uninitialized Memory
/// -------------------------
///
/// Raw memory that has just been allocated is in an *uninitialized, untyped*
/// state. Uninitialized memory must be initialized with values of a type
/// before it can be used with any typed operations.
///
/// You can use methods like `initializeMemory(as:from:)` and
/// `moveInitializeMemory(as:from:count:)` to bind raw memory to a type and
/// initialize it with a value or series of values. To bind uninitialized
/// memory to a type without initializing it, use the `bindMemory(to:count:)`
/// method. These methods all return typed pointers for further typed access
/// to the memory.
///
/// Typed Memory
/// ------------
///
/// Memory that has been bound to a type, whether it is initialized or
/// uninitialized, is typically accessed using typed pointers---instances of
/// `UnsafePointer` and `UnsafeMutablePointer`. Initialization, assignment,
/// and deinitialization can be performed using `UnsafeMutablePointer`
/// methods.
///
/// Memory that has been bound to a type can be rebound to a different type
/// only after it has been deinitialized or if the bound type is a *trivial
/// type*. Deinitializing typed memory does not unbind that memory's type. The
/// deinitialized memory can be reinitialized with values of the same type,
/// bound to a new type, or deallocated.
///
/// - Note: A trivial type can be copied bit for bit with no indirection or
/// reference-counting operations. Generally, native Swift types that do not
/// contain strong or weak references or other forms of indirection are
/// trivial, as are imported C structs and enumerations.
///
/// When reading from or writing to memory as raw
/// bytes when that memory is bound to a type, you must ensure that you
/// satisfy any alignment requirements.
/// Writing to typed memory as raw bytes must only be performed when the bound
/// type is a trivial type.
///
/// Raw Pointer Arithmetic
/// ======================
///
/// Pointer arithmetic with raw pointers is performed at the byte level. When
/// you add to or subtract from a raw pointer, the result is a new raw pointer
/// offset by that number of bytes. The following example allocates four bytes
/// of memory and stores `0xFF` in all four bytes:
///
/// let bytesPointer = UnsafeMutableRawPointer.allocate(byteCount: 4, alignment: 1)
/// bytesPointer.storeBytes(of: 0xFFFF_FFFF, as: UInt32.self)
///
/// // Load a value from the memory referenced by 'bytesPointer'
/// let x = bytesPointer.load(as: UInt8.self) // 255
///
/// // Load a value from the last two allocated bytes
/// let offsetPointer = bytesPointer + 2
/// let y = offsetPointer.load(as: UInt16.self) // 65535
///
/// The code above stores the value `0xFFFF_FFFF` into the four newly allocated
/// bytes, and then loads the first byte as a `UInt8` instance and the third
/// and fourth bytes as a `UInt16` instance.
///
/// Always remember to deallocate any memory that you allocate yourself.
///
/// bytesPointer.deallocate()
///
/// Implicit Casting and Bridging
/// =============================
///
/// When calling a function or method with an `UnsafeMutableRawPointer` parameter, you can pass
/// an instance of that specific pointer type, pass an instance of a
/// compatible pointer type, or use Swift's implicit bridging to pass a
/// compatible pointer.
///
/// For example, the `print(address:as:)` function in the following code sample
/// takes an `UnsafeMutableRawPointer` instance as its first parameter:
///
/// func print<T>(address p: UnsafeMutableRawPointer, as type: T.Type) {
/// let value = p.load(as: type)
/// print(value)
/// }
///
/// As is typical in Swift, you can call the `print(address:as:)` function with
/// an `UnsafeMutableRawPointer` instance. This example passes `rawPointer` as the initial
/// parameter.
///
/// // 'rawPointer' points to memory initialized with `Int` values.
/// let rawPointer: UnsafeMutableRawPointer = ...
/// print(address: rawPointer, as: Int.self)
/// // Prints "42"
///
/// Because typed pointers can be implicitly cast to raw pointers when passed
/// as a parameter, you can also call `print(address:as:)` with any mutable
/// typed pointer instance.
///
/// let intPointer: UnsafeMutablePointer<Int> = ...
/// print(address: intPointer, as: Int.self)
/// // Prints "42"
///
/// Alternatively, you can use Swift's *implicit bridging* to pass a pointer to
/// an instance or to the elements of an array. Use inout syntax to implicitly
/// create a pointer to an instance of any type. The following example uses
/// implicit bridging to pass a pointer to `value` when calling
/// `print(address:as:)`:
///
/// var value: Int = 23
/// print(address: &value, as: Int.self)
/// // Prints "23"
///
/// A mutable pointer to the elements of an array is implicitly created when
/// you pass the array using inout syntax. This example uses implicit bridging
/// to pass a pointer to the elements of `numbers` when calling
/// `print(address:as:)`.
///
/// var numbers = [5, 10, 15, 20]
/// print(address: &numbers, as: Int.self)
/// // Prints "5"
///
/// - Important: The pointer created through implicit bridging of an instance
/// or of an array's elements is only valid during the execution of the
/// called function. Escaping the pointer to use after the execution of the
/// function is undefined behavior. In particular, do not use implicit
/// bridging when calling an `UnsafeMutableRawPointer` initializer.
///
/// var number = 5
/// let numberPointer = UnsafeMutableRawPointer(&number)
/// // Accessing 'numberPointer' is undefined behavior.
@frozen
public struct UnsafeMutableRawPointer: _Pointer {
public typealias Pointee = UInt8
/// The underlying raw pointer.
/// Implements conformance to the public protocol `_Pointer`.
public let _rawValue: Builtin.RawPointer
/// Creates a new raw pointer from a builtin raw pointer.
@_transparent
public init(_ _rawValue: Builtin.RawPointer) {
self._rawValue = _rawValue
}
/// Creates a new raw pointer from the given typed pointer.
///
/// Use this initializer to explicitly convert `other` to an `UnsafeMutableRawPointer`
/// instance. This initializer creates a new pointer to the same address as
/// `other` and performs no allocation or copying.
///
/// - Parameter other: The typed pointer to convert.
@_transparent
public init<T>(@_nonEphemeral _ other: UnsafeMutablePointer<T>) {
_rawValue = other._rawValue
}
/// Creates a new raw pointer from the given typed pointer.
///
/// Use this initializer to explicitly convert `other` to an `UnsafeMutableRawPointer`
/// instance. This initializer creates a new pointer to the same address as
/// `other` and performs no allocation or copying.
///
/// - Parameter other: The typed pointer to convert. If `other` is `nil`, the
/// result is `nil`.
@_transparent
public init?<T>(@_nonEphemeral _ other: UnsafeMutablePointer<T>?) {
guard let unwrapped = other else { return nil }
_rawValue = unwrapped._rawValue
}
/// Creates a new mutable raw pointer from the given immutable raw pointer.
///
/// Use this initializer to explicitly convert `other` to an `UnsafeMutableRawPointer`
/// instance. This initializer creates a new pointer to the same address as
/// `other` and performs no allocation or copying.
///
/// - Parameter other: The immutable raw pointer to convert.
@_transparent
public init(@_nonEphemeral mutating other: UnsafeRawPointer) {
_rawValue = other._rawValue
}
/// Creates a new mutable raw pointer from the given immutable raw pointer.
///
/// Use this initializer to explicitly convert `other` to an `UnsafeMutableRawPointer`
/// instance. This initializer creates a new pointer to the same address as
/// `other` and performs no allocation or copying.
///
/// - Parameter other: The immutable raw pointer to convert. If `other` is
/// `nil`, the result is `nil`.
@_transparent
public init?(@_nonEphemeral mutating other: UnsafeRawPointer?) {
guard let unwrapped = other else { return nil }
_rawValue = unwrapped._rawValue
}
/// Allocates uninitialized memory with the specified size and alignment.
///
/// You are in charge of managing the allocated memory. Be sure to deallocate
/// any memory that you manually allocate.
///
/// The allocated memory is not bound to any specific type and must be bound
/// before performing any typed operations. If you are using the memory for
/// a specific type, allocate memory using the
/// `UnsafeMutablePointer.allocate(capacity:)` static method instead.
///
/// - Parameters:
/// - byteCount: The number of bytes to allocate. `byteCount` must not be negative.
/// - alignment: The alignment of the new region of allocated memory, in
/// bytes.
/// - Returns: A pointer to a newly allocated region of memory. The memory is
/// allocated, but not initialized.
@inlinable
public static func allocate(
byteCount: Int, alignment: Int
) -> UnsafeMutableRawPointer {
// For any alignment <= _minAllocationAlignment, force alignment = 0.
// This forces the runtime's "aligned" allocation path so that
// deallocation does not require the original alignment.
//
// The runtime guarantees:
//
// align == 0 || align > _minAllocationAlignment:
// Runtime uses "aligned allocation".
//
// 0 < align <= _minAllocationAlignment:
// Runtime may use either malloc or "aligned allocation".
var alignment = alignment
if alignment <= _minAllocationAlignment() {
alignment = 0
}
return UnsafeMutableRawPointer(Builtin.allocRaw(
byteCount._builtinWordValue, alignment._builtinWordValue))
}
/// Deallocates the previously allocated memory block referenced by this pointer.
///
/// The memory to be deallocated must be uninitialized or initialized to a
/// trivial type.
@inlinable
public func deallocate() {
// Passing zero alignment to the runtime forces "aligned
// deallocation". Since allocation via `UnsafeMutable[Raw][Buffer]Pointer`
// always uses the "aligned allocation" path, this ensures that the
// runtime's allocation and deallocation paths are compatible.
Builtin.deallocRaw(_rawValue, (-1)._builtinWordValue, (0)._builtinWordValue)
}
/// Binds the memory to the specified type and returns a typed pointer to the
/// bound memory.
///
/// Use the `bindMemory(to:capacity:)` method to bind the memory referenced
/// by this pointer to the type `T`. The memory must be uninitialized or
/// initialized to a type that is layout compatible with `T`. If the memory
/// is uninitialized, it is still uninitialized after being bound to `T`.
///
/// In this example, 100 bytes of raw memory are allocated for the pointer
/// `bytesPointer`, and then the first four bytes are bound to the `Int8`
/// type.
///
/// let count = 4
/// let bytesPointer = UnsafeMutableRawPointer.allocate(
/// bytes: 100,
/// alignedTo: MemoryLayout<Int8>.alignment)
/// let int8Pointer = bytesPointer.bindMemory(to: Int8.self, capacity: count)
///
/// After calling `bindMemory(to:capacity:)`, the first four bytes of the
/// memory referenced by `bytesPointer` are bound to the `Int8` type, though
/// they remain uninitialized. The remainder of the allocated region is
/// unbound raw memory. All 100 bytes of memory must eventually be
/// deallocated.
///
/// - Warning: A memory location may only be bound to one type at a time. The
/// behavior of accessing memory as a type unrelated to its bound type is
/// undefined.
///
/// - Parameters:
/// - type: The type `T` to bind the memory to.
/// - count: The amount of memory to bind to type `T`, counted as instances
/// of `T`.
/// - Returns: A typed pointer to the newly bound memory. The memory in this
/// region is bound to `T`, but has not been modified in any other way.
/// The number of bytes in this region is
/// `count * MemoryLayout<T>.stride`.
@_transparent
@discardableResult
public func bindMemory<T>(
to type: T.Type, capacity count: Int
) -> UnsafeMutablePointer<T> {
Builtin.bindMemory(_rawValue, count._builtinWordValue, type)
return UnsafeMutablePointer<T>(_rawValue)
}
/// Returns a typed pointer to the memory referenced by this pointer,
/// assuming that the memory is already bound to the specified type.
///
/// Use this method when you have a raw pointer to memory that has *already*
/// been bound to the specified type. The memory starting at this pointer
/// must be bound to the type `T`. Accessing memory through the returned
/// pointer is undefined if the memory has not been bound to `T`. To bind
/// memory to `T`, use `bindMemory(to:capacity:)` instead of this method.
///
/// - Parameter to: The type `T` that the memory has already been bound to.
/// - Returns: A typed pointer to the same memory as this raw pointer.
@_transparent
public func assumingMemoryBound<T>(to: T.Type) -> UnsafeMutablePointer<T> {
return UnsafeMutablePointer<T>(_rawValue)
}
/// Initializes the memory referenced by this pointer with the given value,
/// binds the memory to the value's type, and returns a typed pointer to the
/// initialized memory.
///
/// The memory referenced by this pointer must be uninitialized or
/// initialized to a trivial type, and must be properly aligned for
/// accessing `T`.
///
/// The following example allocates enough raw memory to hold four instances
/// of `Int8`, and then uses the `initializeMemory(as:repeating:count:)` method
/// to initialize the allocated memory.
///
/// let count = 4
/// let bytesPointer = UnsafeMutableRawPointer.allocate(
/// byteCount: count * MemoryLayout<Int8>.stride,
/// alignment: MemoryLayout<Int8>.alignment)
/// let int8Pointer = myBytes.initializeMemory(
/// as: Int8.self, repeating: 0, count: count)
///
/// // After using 'int8Pointer':
/// int8Pointer.deallocate()
///
/// After calling this method on a raw pointer `p`, the region starting at
/// `self` and continuing up to `p + count * MemoryLayout<T>.stride` is bound
/// to type `T` and initialized. If `T` is a nontrivial type, you must
/// eventually deinitialize or move from the values in this region to avoid leaks.
///
/// - Parameters:
/// - type: The type to bind this memory to.
/// - repeatedValue: The instance to copy into memory.
/// - count: The number of copies of `value` to copy into memory. `count`
/// must not be negative.
/// - Returns: A typed pointer to the memory referenced by this raw pointer.
@inlinable
@discardableResult
public func initializeMemory<T>(
as type: T.Type, repeating repeatedValue: T, count: Int
) -> UnsafeMutablePointer<T> {
_debugPrecondition(count >= 0,
"UnsafeMutableRawPointer.initializeMemory: negative count")
Builtin.bindMemory(_rawValue, count._builtinWordValue, type)
var nextPtr = self
for _ in 0..<count {
Builtin.initialize(repeatedValue, nextPtr._rawValue)
nextPtr += MemoryLayout<T>.stride
}
return UnsafeMutablePointer(_rawValue)
}
/// Initializes the memory referenced by this pointer with the values
/// starting at the given pointer, binds the memory to the values' type, and
/// returns a typed pointer to the initialized memory.
///
/// The memory referenced by this pointer must be uninitialized or
/// initialized to a trivial type, and must be properly aligned for
/// accessing `T`.
///
/// The following example allocates enough raw memory to hold four instances
/// of `Int8`, and then uses the `initializeMemory(as:from:count:)` method
/// to initialize the allocated memory.
///
/// let count = 4
/// let bytesPointer = UnsafeMutableRawPointer.allocate(
/// bytes: count * MemoryLayout<Int8>.stride,
/// alignedTo: MemoryLayout<Int8>.alignment)
/// let values: [Int8] = [1, 2, 3, 4]
/// let int8Pointer = values.withUnsafeBufferPointer { buffer in
/// return bytesPointer.initializeMemory(as: Int8.self,
/// from: buffer.baseAddress!,
/// count: buffer.count)
/// }
/// // int8Pointer.pointee == 1
/// // (int8Pointer + 3).pointee == 4
///
/// // After using 'int8Pointer':
/// int8Pointer.deallocate(count)
///
/// After calling this method on a raw pointer `p`, the region starting at
/// `p` and continuing up to `p + count * MemoryLayout<T>.stride` is bound
/// to type `T` and initialized. If `T` is a nontrivial type, you must
/// eventually deinitialize or move from the values in this region to avoid
/// leaks. The instances in the region `source..<(source + count)` are
/// unaffected.
///
/// - Parameters:
/// - type: The type to bind this memory to.
/// - source: A pointer to the values to copy. The memory in the region
/// `source..<(source + count)` must be initialized to type `T` and must
/// not overlap the destination region.
/// - count: The number of copies of `value` to copy into memory. `count`
/// must not be negative.
/// - Returns: A typed pointer to the memory referenced by this raw pointer.
@inlinable
@discardableResult
public func initializeMemory<T>(
as type: T.Type, from source: UnsafePointer<T>, count: Int
) -> UnsafeMutablePointer<T> {
_debugPrecondition(
count >= 0,
"UnsafeMutableRawPointer.initializeMemory with negative count")
_debugPrecondition(
(UnsafeRawPointer(self + count * MemoryLayout<T>.stride)
<= UnsafeRawPointer(source))
|| UnsafeRawPointer(source + count) <= UnsafeRawPointer(self),
"UnsafeMutableRawPointer.initializeMemory overlapping range")
Builtin.bindMemory(_rawValue, count._builtinWordValue, type)
Builtin.copyArray(
T.self, self._rawValue, source._rawValue, count._builtinWordValue)
// This builtin is equivalent to:
// for i in 0..<count {
// (self.assumingMemoryBound(to: T.self) + i).initialize(to: source[i])
// }
return UnsafeMutablePointer(_rawValue)
}
/// Initializes the memory referenced by this pointer with the values
/// starting at the given pointer, binds the memory to the values' type,
/// deinitializes the source memory, and returns a typed pointer to the
/// newly initialized memory.
///
/// The memory referenced by this pointer must be uninitialized or
/// initialized to a trivial type, and must be properly aligned for
/// accessing `T`.
///
/// The memory in the region `source..<(source + count)` may overlap with the
/// destination region. The `moveInitializeMemory(as:from:count:)` method
/// automatically performs a forward or backward copy of all instances from
/// the source region to their destination.
///
/// After calling this method on a raw pointer `p`, the region starting at
/// `p` and continuing up to `p + count * MemoryLayout<T>.stride` is bound
/// to type `T` and initialized. If `T` is a nontrivial type, you must
/// eventually deinitialize or move from the values in this region to avoid
/// leaks. Any memory in the region `source..<(source + count)` that does
/// not overlap with the destination region is returned to an uninitialized
/// state.
///
/// - Parameters:
/// - type: The type to bind this memory to.
/// - source: A pointer to the values to copy. The memory in the region
/// `source..<(source + count)` must be initialized to type `T`.
/// - count: The number of copies of `value` to copy into memory. `count`
/// must not be negative.
/// - Returns: A typed pointer to the memory referenced by this raw pointer.
@inlinable
@discardableResult
public func moveInitializeMemory<T>(
as type: T.Type, from source: UnsafeMutablePointer<T>, count: Int
) -> UnsafeMutablePointer<T> {
_debugPrecondition(
count >= 0,
"UnsafeMutableRawPointer.moveInitializeMemory with negative count")
Builtin.bindMemory(_rawValue, count._builtinWordValue, type)
if self < UnsafeMutableRawPointer(source)
|| self >= UnsafeMutableRawPointer(source + count) {
// initialize forward from a disjoint or following overlapping range.
Builtin.takeArrayFrontToBack(
T.self, self._rawValue, source._rawValue, count._builtinWordValue)
// This builtin is equivalent to:
// for i in 0..<count {
// (self.assumingMemoryBound(to: T.self) + i)
// .initialize(to: (source + i).move())
// }
}
else {
// initialize backward from a non-following overlapping range.
Builtin.takeArrayBackToFront(
T.self, self._rawValue, source._rawValue, count._builtinWordValue)
// This builtin is equivalent to:
// var src = source + count
// var dst = self.assumingMemoryBound(to: T.self) + count
// while dst != self {
// (--dst).initialize(to: (--src).move())
// }
}
return UnsafeMutablePointer(_rawValue)
}
/// Returns a new instance of the given type, constructed from the raw memory
/// at the specified offset.
///
/// The memory at this pointer plus `offset` must be properly aligned for
/// accessing `T` and initialized to `T` or another type that is layout
/// compatible with `T`.
///
/// - Parameters:
/// - offset: The offset from this pointer, in bytes. `offset` must be
/// nonnegative. The default is zero.
/// - type: The type of the instance to create.
/// - Returns: A new instance of type `T`, read from the raw bytes at
/// `offset`. The returned instance is memory-managed and unassociated
/// with the value in the memory referenced by this pointer.
@inlinable
public func load<T>(fromByteOffset offset: Int = 0, as type: T.Type) -> T {
_debugPrecondition(0 == (UInt(bitPattern: self + offset)
& (UInt(MemoryLayout<T>.alignment) - 1)),
"load from misaligned raw pointer")
return Builtin.loadRaw((self + offset)._rawValue)
}
/// Stores the given value's bytes into raw memory at the specified offset.
///
/// The type `T` to be stored must be a trivial type. The memory at this
/// pointer plus `offset` must be properly aligned for accessing `T`. The
/// memory must also be uninitialized, initialized to `T`, or initialized to
/// another trivial type that is layout compatible with `T`.
///
/// After calling `storeBytes(of:toByteOffset:as:)`, the memory is
/// initialized to the raw bytes of `value`. If the memory is bound to a
/// type `U` that is layout compatible with `T`, then it contains a value of
/// type `U`. Calling `storeBytes(of:toByteOffset:as:)` does not change the
/// bound type of the memory.
///
/// - Note: A trivial type can be copied with just a bit-for-bit copy without
/// any indirection or reference-counting operations. Generally, native
/// Swift types that do not contain strong or weak references or other
/// forms of indirection are trivial, as are imported C structs and enums.
///
/// If you need to store a copy of a nontrivial value into memory, or to
/// store a value into memory that contains a nontrivial value, you cannot
/// use the `storeBytes(of:toByteOffset:as:)` method. Instead, you must know
/// the type of value previously in memory and initialize or assign the
/// memory. For example, to replace a value stored in a raw pointer `p`,
/// where `U` is the current type and `T` is the new type, use a typed
/// pointer to access and deinitialize the current value before initializing
/// the memory with a new value.
///
/// let typedPointer = p.bindMemory(to: U.self, capacity: 1)
/// typedPointer.deinitialize(count: 1)
/// p.initializeMemory(as: T.self, to: newValue)
///
/// - Parameters:
/// - value: The value to store as raw bytes.
/// - offset: The offset from this pointer, in bytes. `offset` must be
/// nonnegative. The default is zero.
/// - type: The type of `value`.
@inlinable
public func storeBytes<T>(
of value: T, toByteOffset offset: Int = 0, as type: T.Type
) {
_debugPrecondition(0 == (UInt(bitPattern: self + offset)
& (UInt(MemoryLayout<T>.alignment) - 1)),
"storeBytes to misaligned raw pointer")
var temp = value
withUnsafeMutablePointer(to: &temp) { source in
let rawSrc = UnsafeMutableRawPointer(source)._rawValue
// FIXME: to be replaced by _memcpy when conversions are implemented.
Builtin.int_memcpy_RawPointer_RawPointer_Int64(
(self + offset)._rawValue, rawSrc, UInt64(MemoryLayout<T>.size)._value,
/*volatile:*/ false._value)
}
}
/// Copies the specified number of bytes from the given raw pointer's memory
/// into this pointer's memory.
///
/// If the `byteCount` bytes of memory referenced by this pointer are bound to
/// a type `T`, then `T` must be a trivial type, this pointer and `source`
/// must be properly aligned for accessing `T`, and `byteCount` must be a
/// multiple of `MemoryLayout<T>.stride`.
///
/// The memory in the region `source..<(source + byteCount)` may overlap with
/// the memory referenced by this pointer.
///
/// After calling `copyMemory(from:byteCount:)`, the `byteCount` bytes of
/// memory referenced by this pointer are initialized to raw bytes. If the
/// memory is bound to type `T`, then it contains values of type `T`.
///
/// - Parameters:
/// - source: A pointer to the memory to copy bytes from. The memory in the
/// region `source..<(source + byteCount)` must be initialized to a
/// trivial type.
/// - byteCount: The number of bytes to copy. `byteCount` must not be negative.
@inlinable
public func copyMemory(from source: UnsafeRawPointer, byteCount: Int) {
_debugPrecondition(
byteCount >= 0, "UnsafeMutableRawPointer.copyMemory with negative count")
_memmove(dest: self, src: source, size: UInt(byteCount))
}
}
extension UnsafeMutableRawPointer: Strideable {
// custom version for raw pointers
@_transparent
public func advanced(by n: Int) -> UnsafeMutableRawPointer {
return UnsafeMutableRawPointer(Builtin.gepRaw_Word(_rawValue, n._builtinWordValue))
}
}
extension OpaquePointer {
@_transparent
public init(@_nonEphemeral _ from: UnsafeMutableRawPointer) {
self._rawValue = from._rawValue
}
@_transparent
public init?(@_nonEphemeral _ from: UnsafeMutableRawPointer?) {
guard let unwrapped = from else { return nil }
self._rawValue = unwrapped._rawValue
}
@_transparent
public init(@_nonEphemeral _ from: UnsafeRawPointer) {
self._rawValue = from._rawValue
}
@_transparent
public init?(@_nonEphemeral _ from: UnsafeRawPointer?) {
guard let unwrapped = from else { return nil }
self._rawValue = unwrapped._rawValue
}
}
| 4233049533e9f2edbbb1424ee9a9b458 | 42.611765 | 95 | 0.680582 | false | false | false | false |
J3D1-WARR10R/WikiRaces | refs/heads/master | WikiRaces/Shared/Race View Controllers/ResultsViewController/ResultsViewController+KB.swift | mit | 2 | //
// ResultsViewController+KB.swift
// WikiRaces
//
// Created by Andrew Finke on 9/15/18.
// Copyright © 2018 Andrew Finke. All rights reserved.
//
import UIKit
extension ResultsViewController {
// MARK: - Keyboard Support -
override var keyCommands: [UIKeyCommand]? {
var commands = [UIKeyCommand]()
if model.buttonEnabled {
let command = UIKeyCommand(title: "Ready Up",
action: #selector(keyboardAttemptReadyUp),
input: " ",
modifierFlags: [])
commands.append(command)
}
if navigationItem.rightBarButtonItem?.isEnabled ?? false {
let command = UIKeyCommand(title: "Return to Menu",
action: #selector(keyboardAttemptQuit),
input: "q",
modifierFlags: .command)
commands.append(command)
}
return commands
}
@objc
private func keyboardAttemptReadyUp() {
guard model.buttonEnabled else { return }
readyUpButtonPressed()
}
@objc
private func keyboardAttemptQuit(_ keyCommand: UIKeyCommand) {
guard presentedViewController == nil, navigationItem.rightBarButtonItem?.isEnabled ?? false else { return }
doneButtonPressed()
}
}
| 7308ddb7efa65c7c173840889e42ff28 | 30.108696 | 115 | 0.546471 | false | false | false | false |
realexpayments-developers/rxp-ios | refs/heads/master | Pod/Classes/RealexComponent/Dictionary+URLDictionary.swift | mit | 2 | //
// Dictionary+URLDictionary.swift
// rxp-ios
//
import Foundation
extension Dictionary {
/**
Build string representation of HTTP parameter dictionary of keys and objects
This percent escapes in compliance with RFC 3986
- returns: The string representation in the form of key1=value1&key2=value2 where the keys and values are percent escaped
*/
func stringFromHttpParameters() -> String {
let parameterArray = self.map { (key, value) -> String in
let percentEscapedKey = (key as! String).stringByAddingPercentEncodingForURLQueryValue()!
let percentEscapedValue = (value as! String).stringByAddingPercentEncodingForURLQueryValue()!
return "\(percentEscapedKey)=\(percentEscapedValue)"
}
return parameterArray.joined(separator: "&")
}
}
| e72613d8f321fa8eb8a2616ca96493b5 | 31.038462 | 125 | 0.698679 | false | false | false | false |
Miridescen/M_365key | refs/heads/master | 365KEY_swift/365KEY_swift/MainController/Class/News/controller/SKNewsVC.swift | apache-2.0 | 1 | //
// SKNewsVC.swift
// 365KEY_swift
//
// Created by 牟松 on 2016/11/25.
// Copyright © 2016年 DoNews. All rights reserved.
//
import UIKit
private let newsCellID = "newsCellID"
class SKNewsVC: UIViewController {
var refControl: UIRefreshControl?
var navBar: UINavigationBar?
var navItem: UINavigationItem?
var searchView: SKProduceSearchView?
var tableView: UITableView?
var activityView: UIActivityIndicatorView?
// 用于判断是否是上啦加载
var isPullUp = false
var newsViewModel = SKNewsViewModel()
lazy var noInfoLabel = UILabel(frame: CGRect(x: 0, y: 50, width: SKScreenWidth, height: 50))
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(forName: NSNotification.Name(rawValue: SKNoUserLoginNotifiction), object: nil, queue: OperationQueue.main) { notifiction in
self.present(SKNavigationController(rootViewController: SKLoginController()), animated: true, completion: nil)
}
NotificationCenter.default.addObserver(self, selector: #selector(userLoginSuccess), name: NSNotification.Name(rawValue: SKUserLoginSuccessNotifiction), object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(userLoginSuccess), name: NSNotification.Name(rawValue: SKUserLogoutNotifiction), object: nil)
addSubView()
loadData()
}
deinit {
NotificationCenter.default.removeObserver(self)
}
func userLoginSuccess() {
loadData()
}
func loadData() {
print("新闻加载数据")
newsViewModel.loadNewsData(isPullUp: isPullUp){ isSuccess in
if isSuccess{
self.tableView?.reloadData()
self.noInfoLabel.removeFromSuperview()
self.tableView?.tableFooterView?.isHidden = false
} else {
if self.newsViewModel.newsDataArray.count == 0{
self.addNoInfoView(with: "暂无内容")
}
}
if #available(iOS 10.0, *) {
self.tableView?.refreshControl?.endRefreshing()
} else {
self.refControl?.endRefreshing()
}
self.activityView?.stopAnimating()
}
isPullUp = false
}
}
extension SKNewsVC {
@objc private func searchButtonDidclick(){
// MARK: 添加searchBar
searchView = SKProduceSearchView(withAnimation: true)
searchView?.searchTF?.delegate = self
navBar?.addSubview(searchView!)
}
func addSubView() {
navBar = UINavigationBar(frame: CGRect(x: 0, y: 0, width: SKScreenWidth, height: 64))
navBar?.isTranslucent = false
navBar?.barTintColor = UIColor().mainColor
navBar?.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.white]
view.addSubview(navBar!)
navItem = UINavigationItem()
navItem?.title = "365KEY"
navItem?.leftBarButtonItem = UIBarButtonItem(SK_barButtonItem: UIImage(named:"icon_search"), selectorImage: UIImage(named:"icon_search"), tragtic: self, action: #selector(searchButtonDidclick))
navBar?.items = [navItem!]
tableView = UITableView(frame: view.bounds)
tableView?.delegate = self
tableView?.dataSource = self
tableView?.separatorStyle = .none
tableView?.register(UINib(nibName: "SKNewsCell", bundle: nil), forCellReuseIdentifier: newsCellID)
tableView?.contentInset = UIEdgeInsets(top: 44, left: 0, bottom: tabBarController?.tabBar.bounds.height ?? 49, right: 0)
tableView?.scrollIndicatorInsets = UIEdgeInsets(top: 44, left: 0, bottom: 0, right: 0)
tableView?.rowHeight = UITableViewAutomaticDimension
tableView?.estimatedRowHeight = 100
view.insertSubview(tableView!, at: 0)
refControl = UIRefreshControl()
refControl?.tintColor = UIColor.gray
refControl?.attributedTitle = NSAttributedString(string: "下拉刷新")
refControl?.addTarget(self, action: #selector(loadData), for: .valueChanged)
if #available(iOS 10.0, *) {
tableView?.refreshControl = refControl
} else {
tableView?.addSubview(refControl!)
}
let footView = UIButton()
footView.frame = CGRect(x: 0, y: 0, width: SKScreenWidth, height: 60)
footView.setTitle("点击加载更多", for: .normal)
footView.setTitleColor(UIColor.black, for: .normal)
footView.addTarget(self, action: #selector(touchFooterView), for: .touchUpInside)
tableView?.tableFooterView = footView
tableView?.tableFooterView?.isHidden = true
activityView = UIActivityIndicatorView(activityIndicatorStyle: .gray)
activityView?.center = CGPoint(x: (view?.centerX)!, y: (view?.centerY)!)
activityView?.startAnimating()
activityView?.hidesWhenStopped = true
activityView?.color = UIColor.gray
view.addSubview(activityView!)
view.bringSubview(toFront: activityView!)
}
@objc func touchFooterView(){
isPullUp = true
loadData()
}
// MARK: 没有内容时显示
func addNoInfoView(with string: String) {
noInfoLabel.text = string
noInfoLabel.textAlignment = .center
noInfoLabel.textColor = UIColor(red: 225/255.0, green: 225/255.0, blue: 225/255.0, alpha: 1)
noInfoLabel.font = UIFont.systemFont(ofSize: 20)
tableView?.addSubview(self.noInfoLabel)
}
}
extension SKNewsVC: UITableViewDelegate, UITableViewDataSource{
func numberOfSections(in tableView: UITableView) -> Int {
return newsViewModel.newsDataArray.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let dic = newsViewModel.newsDataArray[section] as [String : [SKNewsListModel]]
let keyValue = dic[dic.startIndex]
let value = keyValue.1
return value.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: newsCellID, for: indexPath) as! SKNewsCell
let dic = newsViewModel.newsDataArray[indexPath.section]
let keyValue = dic[dic.startIndex]
let value = keyValue.1
cell.newsListModel = value[indexPath.row]
return cell
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let view = UIView()
view.frame = CGRect(x: 0, y: -10, width: SKScreenWidth, height: 40)
view.backgroundColor = UIColor.white
let todayDate = Date().description
let strIndex = todayDate.index(todayDate.startIndex, offsetBy: 10)
let todayDateStr = todayDate.substring(to: strIndex)
let dic = newsViewModel.newsDataArray[section] as [String : [SKNewsListModel]]
let keyValue = dic[dic.startIndex]
let value = keyValue.0
let titleText = value == todayDateStr ? "Today":value
let titleLabel = UILabel()
titleLabel.frame = CGRect(x: 16, y: 20, width: SKScreenWidth-10, height: 20)
titleLabel.textAlignment = .left
titleLabel.textColor = UIColor(red: 254/255.0, green: 216/255.0, blue: 203/255.0, alpha: 1.0)
titleLabel.font = UIFont.systemFont(ofSize: 19)
titleLabel.text = titleText
view.addSubview(titleLabel)
return view
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 40
}
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
if indexPath.section == newsViewModel.newsDataArray.count-1 && !isPullUp && indexPath.row == 0{
isPullUp = true
loadData()
}
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 113
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let dic = newsViewModel.newsDataArray[indexPath.section]
let keyValue = dic[dic.startIndex]
let value = keyValue.1
let newsDetailVC = SKNewsDetailController()
newsDetailVC.newsListModel = value[indexPath.row]
navigationController?.pushViewController(newsDetailVC, animated: true)
}
}
extension SKNewsVC: UITextFieldDelegate{
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
var parames = [String: AnyObject]()
parames["title"] = textField.text as AnyObject
parames["uid"] = SKUserShared.getUserShared()?.uid as AnyObject
NSURLConnection.connection.searchNewsRequest(params: parames) { (bool, anyData) in
if bool {
let searchNewsVC = SKNewsSearchVC()
searchNewsVC.data = anyData!
self.navigationController?.pushViewController(searchNewsVC, animated: true)
} else {
SKProgressHUD.setErrorString(with: "没有搜索的资讯")
}
}
return true
}
}
| 9d35b247747305a10277264048620e83 | 35.117424 | 201 | 0.627268 | false | false | false | false |
swifty-iOS/MBNetworkManager | refs/heads/master | Sample/MBNetwokManager/MBNetworkManager+Task.swift | mit | 1 | //
// MBNetworkManager+Task.swift
// MBNetworkManager
//
// Created by Manish Bhande on 30/12/16.
// Copyright © 2016 Manish Bhande. All rights reserved.
//
import Foundation
extension Task {
class func sampleTask() -> Task {
let newTask = Task(url: "https://www.google.com")
// newTask.method = .post
// newTask.headers = ["Key": "HeaderText" as AnyObject]
// newTask.requestBody = ["boby" : "bodyText" as AnyObject]
newTask.timeout = 30
return newTask
}
class func samplePDF() -> Task {
let newTask = Task(url: "http://www.ebooksbucket.com/uploads/itprogramming/iosappdevelopment/Core_Data_Storage_and_Management_for_iOS.pdf")
newTask.timeout = 30
return newTask
}
}
| 88b5b0d95857ecd768e2bc49b0cf530e | 26.172414 | 147 | 0.61802 | false | false | false | false |
bitjammer/swift | refs/heads/master | test/SILGen/objc_thunks.swift | apache-2.0 | 1 | // RUN: %target-swift-frontend -Xllvm -sil-full-demangle -sdk %S/Inputs -I %S/Inputs -enable-source-import %s -emit-silgen -emit-verbose-sil | %FileCheck %s
// REQUIRES: objc_interop
import gizmo
import ansible
class Hoozit : Gizmo {
func typical(_ x: Int, y: Gizmo) -> Gizmo { return y }
// CHECK-LABEL: sil hidden [thunk] @_T011objc_thunks6HoozitC7typicalSo5GizmoCSi_AF1ytFTo : $@convention(objc_method) (Int, Gizmo, Hoozit) -> @autoreleased Gizmo {
// CHECK: bb0([[X:%.*]] : $Int, [[Y:%.*]] : $Gizmo, [[THIS:%.*]] : $Hoozit):
// CHECK-NEXT: [[Y_COPY:%.*]] = copy_value [[Y]]
// CHECK-NEXT: [[THIS_COPY:%.*]] = copy_value [[THIS]]
// CHECK-NEXT: [[BORROWED_THIS_COPY:%.*]] = begin_borrow [[THIS_COPY]]
// CHECK-NEXT: // function_ref objc_thunks.Hoozit.typical
// CHECK-NEXT: [[NATIVE:%.*]] = function_ref @_T011objc_thunks6HoozitC7typicalSo5GizmoCSi_AF1ytF : $@convention(method) (Int, @owned Gizmo, @guaranteed Hoozit) -> @owned Gizmo
// CHECK-NEXT: [[RES:%.*]] = apply [[NATIVE]]([[X]], [[Y_COPY]], [[BORROWED_THIS_COPY]]) {{.*}} line:[[@LINE-8]]:8:auto_gen
// CHECK-NEXT: end_borrow [[BORROWED_THIS_COPY]] from [[THIS_COPY]]
// CHECK-NEXT: destroy_value [[THIS_COPY]] : $Hoozit
// CHECK-NEXT: return [[RES]] : $Gizmo{{.*}} line:[[@LINE-11]]:8:auto_gen
// CHECK-NEXT: } // end sil function '_T011objc_thunks6HoozitC7typicalSo5GizmoCSi_AF1ytFTo'
// NS_CONSUMES_SELF by inheritance
override func fork() { }
// CHECK-LABEL: sil hidden [thunk] @_T011objc_thunks6HoozitC4forkyyFTo : $@convention(objc_method) (@owned Hoozit) -> () {
// CHECK: bb0([[THIS:%.*]] : $Hoozit):
// CHECK-NEXT: [[BORROWED_THIS:%.*]] = begin_borrow [[THIS]]
// CHECK-NEXT: // function_ref
// CHECK-NEXT: [[NATIVE:%.*]] = function_ref @_T011objc_thunks6HoozitC4forkyyF : $@convention(method) (@guaranteed Hoozit) -> ()
// CHECK-NEXT: apply [[NATIVE]]([[BORROWED_THIS]])
// CHECK-NEXT: end_borrow [[BORROWED_THIS]] from [[THIS]]
// CHECK-NEXT: destroy_value [[THIS]]
// CHECK-NEXT: return
// CHECK-NEXT: }
// NS_CONSUMED 'gizmo' argument by inheritance
override class func consume(_ gizmo: Gizmo?) { }
// CHECK-LABEL: sil hidden [thunk] @_T011objc_thunks6HoozitC7consumeySo5GizmoCSgFZTo : $@convention(objc_method) (@owned Optional<Gizmo>, @objc_metatype Hoozit.Type) -> () {
// CHECK: bb0([[GIZMO:%.*]] : $Optional<Gizmo>, [[THIS:%.*]] : $@objc_metatype Hoozit.Type):
// CHECK-NEXT: [[THICK_THIS:%[0-9]+]] = objc_to_thick_metatype [[THIS]] : $@objc_metatype Hoozit.Type to $@thick Hoozit.Type
// CHECK: [[NATIVE:%.*]] = function_ref @_T011objc_thunks6HoozitC7consumeySo5GizmoCSgFZ : $@convention(method) (@owned Optional<Gizmo>, @thick Hoozit.Type) -> ()
// CHECK-NEXT: apply [[NATIVE]]([[GIZMO]], [[THICK_THIS]])
// CHECK-NEXT: return
// CHECK-NEXT: }
// NS_RETURNS_RETAINED by family (-copy)
func copyFoo() -> Gizmo { return self }
// CHECK-LABEL: sil hidden [thunk] @_T011objc_thunks6HoozitC7copyFooSo5GizmoCyFTo : $@convention(objc_method) (Hoozit) -> @owned Gizmo
// CHECK: bb0([[THIS:%.*]] : $Hoozit):
// CHECK-NEXT: [[THIS_COPY:%.*]] = copy_value [[THIS]]
// CHECK-NEXT: [[BORROWED_THIS_COPY:%.*]] = begin_borrow [[THIS_COPY]]
// CHECK-NEXT: // function_ref
// CHECK-NEXT: [[NATIVE:%.*]] = function_ref @_T011objc_thunks6HoozitC7copyFooSo5GizmoCyF : $@convention(method) (@guaranteed Hoozit) -> @owned Gizmo
// CHECK-NEXT: [[RES:%.*]] = apply [[NATIVE]]([[BORROWED_THIS_COPY]])
// CHECK-NEXT: end_borrow [[BORROWED_THIS_COPY]] from [[THIS_COPY]]
// CHECK-NEXT: destroy_value [[THIS_COPY]]
// CHECK-NEXT: return [[RES]]
// CHECK-NEXT: }
// Override the normal family conventions to make this non-consuming and
// returning at +0.
func initFoo() -> Gizmo { return self }
// CHECK-LABEL: sil hidden [thunk] @_T011objc_thunks6HoozitC7initFooSo5GizmoCyFTo : $@convention(objc_method) (Hoozit) -> @autoreleased Gizmo
// CHECK: bb0([[THIS:%.*]] : $Hoozit):
// CHECK-NEXT: [[THIS_COPY:%.*]] = copy_value [[THIS]]
// CHECK-NEXT: [[BORROWED_THIS_COPY:%.*]] = begin_borrow [[THIS_COPY]]
// CHECK-NEXT: // function_ref
// CHECK-NEXT: [[NATIVE:%.*]] = function_ref @_T011objc_thunks6HoozitC7initFooSo5GizmoCyF : $@convention(method) (@guaranteed Hoozit) -> @owned Gizmo
// CHECK-NEXT: [[RES:%.*]] = apply [[NATIVE]]([[BORROWED_THIS_COPY]])
// CHECK-NEXT: end_borrow [[BORROWED_THIS_COPY]] from [[THIS_COPY]]
// CHECK-NEXT: destroy_value [[THIS_COPY]]
// CHECK-NEXT: return [[RES]]
// CHECK-NEXT: }
var typicalProperty: Gizmo
// -- getter
// CHECK-LABEL: sil hidden [thunk] @_T011objc_thunks6HoozitC15typicalPropertySo5GizmoCfgTo : $@convention(objc_method) (Hoozit) -> @autoreleased Gizmo {
// CHECK: bb0([[SELF:%.*]] : $Hoozit):
// CHECK-NEXT: [[SELF_COPY:%.*]] = copy_value [[SELF]]
// CHECK-NEXT: [[BORROWED_SELF_COPY:%.*]] = begin_borrow [[SELF_COPY]]
// CHECK-NEXT: // function_ref objc_thunks.Hoozit.typicalProperty.getter
// CHECK-NEXT: [[GETIMPL:%.*]] = function_ref @_T011objc_thunks6HoozitC15typicalPropertySo5GizmoCfg
// CHECK-NEXT: [[RES:%.*]] = apply [[GETIMPL]]([[BORROWED_SELF_COPY]])
// CHECK-NEXT: end_borrow [[BORROWED_SELF_COPY]] from [[SELF_COPY]]
// CHECK-NEXT: destroy_value [[SELF_COPY]]
// CHECK-NEXT: return [[RES]] : $Gizmo
// CHECK-NEXT: }
// CHECK-LABEL: sil hidden @_T011objc_thunks6HoozitC15typicalPropertySo5GizmoCfg : $@convention(method) (@guaranteed Hoozit) -> @owned Gizmo
// CHECK: bb0(%0 : $Hoozit):
// CHECK-NEXT: debug_value %0
// CHECK-NEXT: [[ADDR:%.*]] = ref_element_addr %0 : {{.*}}, #Hoozit.typicalProperty
// CHECK-NEXT: [[RES:%.*]] = load [copy] [[ADDR]] {{.*}}
// CHECK-NEXT: return [[RES]]
// -- setter
// CHECK-LABEL: sil hidden [thunk] @_T011objc_thunks6HoozitC15typicalPropertySo5GizmoCfsTo : $@convention(objc_method) (Gizmo, Hoozit) -> () {
// CHECK: bb0([[VALUE:%.*]] : $Gizmo, [[THIS:%.*]] : $Hoozit):
// CHECK: [[VALUE_COPY:%.*]] = copy_value [[VALUE]] : $Gizmo
// CHECK: [[THIS_COPY:%.*]] = copy_value [[THIS]] : $Hoozit
// CHECK: [[BORROWED_THIS_COPY:%.*]] = begin_borrow [[THIS_COPY]]
// CHECK: // function_ref objc_thunks.Hoozit.typicalProperty.setter
// CHECK: [[FR:%.*]] = function_ref @_T011objc_thunks6HoozitC15typicalPropertySo5GizmoCfs
// CHECK: [[RES:%.*]] = apply [[FR]]([[VALUE_COPY]], [[BORROWED_THIS_COPY]])
// CHECK: end_borrow [[BORROWED_THIS_COPY]] from [[THIS_COPY]]
// CHECK: destroy_value [[THIS_COPY]]
// CHECK: return [[RES]] : $(), scope {{.*}} // id: {{.*}} line:[[@LINE-32]]:7:auto_gen
// CHECK: } // end sil function '_T011objc_thunks6HoozitC15typicalPropertySo5GizmoCfsTo'
// CHECK-LABEL: sil hidden @_T011objc_thunks6HoozitC15typicalPropertySo5GizmoCfs
// CHECK: bb0([[ARG0:%.*]] : $Gizmo, [[ARG1:%.*]] : $Hoozit):
// CHECK: [[BORROWED_ARG0:%.*]] = begin_borrow [[ARG0]]
// CHECK: [[ARG0_COPY:%.*]] = copy_value [[BORROWED_ARG0]]
// CHECK: [[ADDR:%.*]] = ref_element_addr [[ARG1]] : {{.*}}, #Hoozit.typicalProperty
// CHECK: assign [[ARG0_COPY]] to [[ADDR]] : $*Gizmo
// CHECK: end_borrow [[BORROWED_ARG0]] from [[ARG0]]
// CHECK: destroy_value [[ARG0]]
// CHECK: } // end sil function '_T011objc_thunks6HoozitC15typicalPropertySo5GizmoCfs'
// NS_RETURNS_RETAINED getter by family (-copy)
var copyProperty: Gizmo
// -- getter
// CHECK-LABEL: sil hidden [thunk] @_T011objc_thunks6HoozitC12copyPropertySo5GizmoCfgTo : $@convention(objc_method) (Hoozit) -> @owned Gizmo {
// CHECK: bb0([[SELF:%.*]] : $Hoozit):
// CHECK-NEXT: [[SELF_COPY:%.*]] = copy_value [[SELF]]
// CHECK-NEXT: [[BORROWED_SELF_COPY:%.*]] = begin_borrow [[SELF_COPY]]
// CHECK-NEXT: // function_ref objc_thunks.Hoozit.copyProperty.getter
// CHECK-NEXT: [[FR:%.*]] = function_ref @_T011objc_thunks6HoozitC12copyPropertySo5GizmoCfg
// CHECK-NEXT: [[RES:%.*]] = apply [[FR]]([[BORROWED_SELF_COPY]])
// CHECK-NEXT: end_borrow [[BORROWED_SELF_COPY]] from [[SELF_COPY]]
// CHECK-NEXT: destroy_value [[SELF_COPY]]
// CHECK-NEXT: return [[RES]]
// CHECK-NEXT: }
// CHECK-LABEL: sil hidden @_T011objc_thunks6HoozitC12copyPropertySo5GizmoCfg
// CHECK: bb0(%0 : $Hoozit):
// CHECK: [[ADDR:%.*]] = ref_element_addr %0 : {{.*}}, #Hoozit.copyProperty
// CHECK-NEXT: [[RES:%.*]] = load [copy] [[ADDR]]
// CHECK-NEXT: return [[RES]]
// -- setter is normal
// CHECK-LABEL: sil hidden [thunk] @_T011objc_thunks6HoozitC12copyPropertySo5GizmoCfsTo : $@convention(objc_method) (Gizmo, Hoozit) -> () {
// CHECK: bb0([[VALUE:%.*]] : $Gizmo, [[THIS:%.*]] : $Hoozit):
// CHECK-NEXT: [[VALUE_COPY:%.*]] = copy_value [[VALUE]]
// CHECK-NEXT: [[THIS_COPY:%.*]] = copy_value [[THIS]]
// CHECK-NEXT: [[BORROWED_THIS_COPY:%.*]] = begin_borrow [[THIS_COPY]]
// CHECK-NEXT: // function_ref objc_thunks.Hoozit.copyProperty.setter
// CHECK-NEXT: [[FR:%.*]] = function_ref @_T011objc_thunks6HoozitC12copyPropertySo5GizmoCfs
// CHECK-NEXT: [[RES:%.*]] = apply [[FR]]([[VALUE_COPY]], [[BORROWED_THIS_COPY]])
// CHECK-NEXT: end_borrow [[BORROWED_THIS_COPY]] from [[THIS_COPY]]
// CHECK-NEXT: destroy_value [[THIS_COPY]]
// CHECK-NEXT: return [[RES]]
// CHECK-LABEL: sil hidden @_T011objc_thunks6HoozitC12copyPropertySo5GizmoCfs
// CHECK: bb0([[ARG1:%.*]] : $Gizmo, [[SELF:%.*]] : $Hoozit):
// CHECK: [[BORROWED_ARG1:%.*]] = begin_borrow [[ARG1]]
// CHECK: [[ARG1_COPY:%.*]] = copy_value [[BORROWED_ARG1]]
// CHECK: [[ADDR:%.*]] = ref_element_addr [[SELF]] : {{.*}}, #Hoozit.copyProperty
// CHECK: assign [[ARG1_COPY]] to [[ADDR]]
// CHECK: end_borrow [[BORROWED_ARG1]] from [[ARG1]]
// CHECK: destroy_value [[ARG1]]
// CHECK: } // end sil function '_T011objc_thunks6HoozitC12copyPropertySo5GizmoCfs'
var roProperty: Gizmo { return self }
// -- getter
// CHECK-LABEL: sil hidden [thunk] @_T011objc_thunks6HoozitC10roPropertySo5GizmoCfgTo : $@convention(objc_method) (Hoozit) -> @autoreleased Gizmo {
// CHECK: bb0([[THIS:%.*]] : $Hoozit):
// CHECK-NEXT: [[THIS_COPY:%.*]] = copy_value [[THIS]]
// CHECK-NEXT: [[BORROWED_THIS_COPY:%.*]] = begin_borrow [[THIS_COPY]]
// CHECK-NEXT: // function_ref
// CHECK-NEXT: [[NATIVE:%.*]] = function_ref @_T011objc_thunks6HoozitC10roPropertySo5GizmoCfg : $@convention(method) (@guaranteed Hoozit) -> @owned Gizmo
// CHECK-NEXT: [[RES:%.*]] = apply [[NATIVE]]([[BORROWED_THIS_COPY]])
// CHECK-NEXT: end_borrow [[BORROWED_THIS_COPY]] from [[THIS_COPY]]
// CHECK-NEXT: destroy_value [[THIS_COPY]] : $Hoozit
// CHECK-NEXT: return [[RES]] : $Gizmo
// CHECK-NEXT: } // end sil function '_T011objc_thunks6HoozitC10roPropertySo5GizmoCfgTo'
// -- no setter
// CHECK-NOT: sil hidden [thunk] @_T011objc_thunks6HoozitC10roPropertySo5GizmoCfsTo
var rwProperty: Gizmo {
get {
return self
}
set {}
}
// -- getter
// CHECK-LABEL: sil hidden [thunk] @_T011objc_thunks6HoozitC10rwPropertySo5GizmoCfgTo : $@convention(objc_method) (Hoozit) -> @autoreleased Gizmo
// -- setter
// CHECK-LABEL: sil hidden [thunk] @_T011objc_thunks6HoozitC10rwPropertySo5GizmoCfsTo : $@convention(objc_method) (Gizmo, Hoozit) -> () {
// CHECK: bb0([[VALUE:%.*]] : $Gizmo, [[THIS:%.*]] : $Hoozit):
// CHECK-NEXT: [[VALUE_COPY:%.*]] = copy_value [[VALUE]]
// CHECK-NEXT: [[THIS_COPY:%.*]] = copy_value [[THIS]]
// CHECK-NEXT: [[BORROWED_THIS_COPY:%.*]] = begin_borrow [[THIS_COPY]]
// CHECK-NEXT: // function_ref
// CHECK-NEXT: [[NATIVE:%.*]] = function_ref @_T011objc_thunks6HoozitC10rwPropertySo5GizmoCfs : $@convention(method) (@owned Gizmo, @guaranteed Hoozit) -> ()
// CHECK-NEXT: apply [[NATIVE]]([[VALUE_COPY]], [[BORROWED_THIS_COPY]])
// CHECK-NEXT: end_borrow [[BORROWED_THIS_COPY]] from [[THIS_COPY]]
// CHECK-NEXT: destroy_value [[THIS_COPY]]
// CHECK-NEXT: return
// CHECK-NEXT: }
var copyRWProperty: Gizmo {
get {
return self
}
set {}
}
// -- getter
// CHECK-LABEL: sil hidden [thunk] @_T011objc_thunks6HoozitC14copyRWPropertySo5GizmoCfgTo : $@convention(objc_method) (Hoozit) -> @owned Gizmo {
// CHECK: bb0([[THIS:%.*]] : $Hoozit):
// CHECK-NEXT: [[THIS_COPY:%.*]] = copy_value [[THIS]]
// CHECK-NEXT: [[BORROWED_THIS_COPY:%.*]] = begin_borrow [[THIS_COPY]]
// CHECK-NEXT: // function_ref
// CHECK-NEXT: [[NATIVE:%.*]] = function_ref @_T011objc_thunks6HoozitC14copyRWPropertySo5GizmoCfg : $@convention(method) (@guaranteed Hoozit) -> @owned Gizmo
// CHECK-NEXT: [[RES:%.*]] = apply [[NATIVE]]([[BORROWED_THIS_COPY]])
// CHECK-NEXT: end_borrow [[BORROWED_THIS_COPY]] from [[THIS_COPY]]
// CHECK-NEXT: destroy_value [[THIS_COPY]]
// CHECK-NOT: return
// CHECK-NEXT: return [[RES]]
// CHECK-NEXT: }
// -- setter is normal
// CHECK-LABEL: sil hidden [thunk] @_T011objc_thunks6HoozitC14copyRWPropertySo5GizmoCfsTo : $@convention(objc_method) (Gizmo, Hoozit) -> () {
// CHECK: bb0([[VALUE:%.*]] : $Gizmo, [[THIS:%.*]] : $Hoozit):
// CHECK-NEXT: [[VALUE_COPY:%.*]] = copy_value [[VALUE]]
// CHECK-NEXT: [[THIS_COPY:%.*]] = copy_value [[THIS]]
// CHECK-NEXT: [[BORROWED_THIS_COPY:%.*]] = begin_borrow [[THIS_COPY]]
// CHECK-NEXT: // function_ref
// CHECK-NEXT: [[NATIVE:%.*]] = function_ref @_T011objc_thunks6HoozitC14copyRWPropertySo5GizmoCfs : $@convention(method) (@owned Gizmo, @guaranteed Hoozit) -> ()
// CHECK-NEXT: apply [[NATIVE]]([[VALUE_COPY]], [[BORROWED_THIS_COPY]])
// CHECK-NEXT: end_borrow [[BORROWED_THIS_COPY]] from [[THIS_COPY]]
// CHECK-NEXT: destroy_value [[THIS_COPY]]
// CHECK-NEXT: return
// CHECK-NEXT: }
var initProperty: Gizmo
// -- getter
// CHECK-LABEL: sil hidden [thunk] @_T011objc_thunks6HoozitC12initPropertySo5GizmoCfgTo : $@convention(objc_method) (Hoozit) -> @autoreleased Gizmo {
// CHECK: bb0([[THIS:%.*]] : $Hoozit):
// CHECK-NEXT: [[THIS_COPY:%.*]] = copy_value [[THIS]]
// CHECK-NEXT: [[BORROWED_THIS_COPY:%.*]] = begin_borrow [[THIS_COPY]]
// CHECK-NEXT: // function_ref
// CHECK-NEXT: [[NATIVE:%.*]] = function_ref @_T011objc_thunks6HoozitC12initPropertySo5GizmoCfg : $@convention(method) (@guaranteed Hoozit) -> @owned Gizmo
// CHECK-NEXT: [[RES:%.*]] = apply [[NATIVE]]([[BORROWED_THIS_COPY]])
// CHECK-NEXT: end_borrow [[BORROWED_THIS_COPY]] from [[THIS_COPY]]
// CHECK-NEXT: destroy_value [[THIS_COPY]]
// CHECK-NEXT: return [[RES]]
// CHECK-NEXT: }
// -- setter
// CHECK-LABEL: sil hidden [thunk] @_T011objc_thunks6HoozitC12initPropertySo5GizmoCfsTo : $@convention(objc_method) (Gizmo, Hoozit) -> () {
// CHECK: bb0([[VALUE:%.*]] : $Gizmo, [[THIS:%.*]] : $Hoozit):
// CHECK-NEXT: [[VALUE_COPY:%.*]] = copy_value [[VALUE]]
// CHECK-NEXT: [[THIS_COPY:%.*]] = copy_value [[THIS]]
// CHECK-NEXT: [[BORROWED_THIS_COPY:%.*]] = begin_borrow [[THIS_COPY]]
// CHECK-NEXT: // function_ref
// CHECK-NEXT: [[NATIVE:%.*]] = function_ref @_T011objc_thunks6HoozitC12initPropertySo5GizmoCfs : $@convention(method) (@owned Gizmo, @guaranteed Hoozit) -> ()
// CHECK-NEXT: apply [[NATIVE]]([[VALUE_COPY]], [[BORROWED_THIS_COPY]])
// CHECK-NEXT: end_borrow [[BORROWED_THIS_COPY]] from [[THIS_COPY]]
// CHECK-NEXT: destroy_value [[THIS_COPY]]
// CHECK-NEXT: return
// CHECK-NEXT: }
var propComputed: Gizmo {
@objc(initPropComputedGetter) get { return self }
@objc(initPropComputedSetter:) set {}
}
// -- getter
// CHECK-LABEL: sil hidden [thunk] @_T011objc_thunks6HoozitC12propComputedSo5GizmoCfgTo : $@convention(objc_method) (Hoozit) -> @autoreleased Gizmo {
// CHECK: bb0([[THIS:%.*]] : $Hoozit):
// CHECK-NEXT: [[THIS_COPY:%.*]] = copy_value [[THIS]]
// CHECK-NEXT: [[BORROWED_THIS_COPY:%.*]] = begin_borrow [[THIS_COPY]]
// CHECK-NEXT: // function_ref
// CHECK-NEXT: [[NATIVE:%.*]] = function_ref @_T011objc_thunks6HoozitC12propComputedSo5GizmoCfg : $@convention(method) (@guaranteed Hoozit) -> @owned Gizmo
// CHECK-NEXT: [[RES:%.*]] = apply [[NATIVE]]([[BORROWED_THIS_COPY]])
// CHECK-NEXT: end_borrow [[BORROWED_THIS_COPY]] from [[THIS_COPY]]
// CHECK-NEXT: destroy_value [[THIS_COPY]]
// CHECK-NEXT: return [[RES]]
// CHECK-NEXT: }
// -- setter
// CHECK-LABEL: sil hidden [thunk] @_T011objc_thunks6HoozitC12propComputedSo5GizmoCfsTo : $@convention(objc_method) (Gizmo, Hoozit) -> () {
// CHECK: bb0([[VALUE:%.*]] : $Gizmo, [[THIS:%.*]] : $Hoozit):
// CHECK-NEXT: [[VALUE_COPY:%.*]] = copy_value [[VALUE]]
// CHECK-NEXT: [[THIS_COPY:%.*]] = copy_value [[THIS]]
// CHECK-NEXT: [[BORROWED_THIS_COPY:%.*]] = begin_borrow [[THIS_COPY]]
// CHECK-NEXT: // function_ref
// CHECK-NEXT: [[NATIVE:%.*]] = function_ref @_T011objc_thunks6HoozitC12propComputedSo5GizmoCfs : $@convention(method) (@owned Gizmo, @guaranteed Hoozit) -> ()
// CHECK-NEXT: apply [[NATIVE]]([[VALUE_COPY]], [[BORROWED_THIS_COPY]])
// CHECK-NEXT: end_borrow [[BORROWED_THIS_COPY]] from [[THIS_COPY]]
// CHECK-NEXT: destroy_value [[THIS_COPY]]
// CHECK-NEXT: return
// CHECK-NEXT: }
// Don't export generics to ObjC yet
func generic<T>(_ x: T) {}
// CHECK-NOT: sil hidden [thunk] @_TToFC11objc_thunks6Hoozit7generic{{.*}}
// Constructor.
// CHECK-LABEL: sil hidden @_T011objc_thunks6HoozitCACSi7bellsOn_tcfc : $@convention(method) (Int, @owned Hoozit) -> @owned Hoozit {
// CHECK: [[SELF_BOX:%[0-9]+]] = alloc_box ${ var Hoozit }
// CHECK: [[PB:%.*]] = project_box [[SELF_BOX]]
// CHECK: [[SELFMUI:%[0-9]+]] = mark_uninitialized [derivedself] [[PB]]
// CHECK: [[GIZMO:%[0-9]+]] = upcast [[SELF:%[0-9]+]] : $Hoozit to $Gizmo
// CHECK: [[SUPERMETHOD:%[0-9]+]] = super_method [volatile] [[SELF]] : $Hoozit, #Gizmo.init!initializer.1.foreign : (Gizmo.Type) -> (Int) -> Gizmo!, $@convention(objc_method) (Int, @owned Gizmo) -> @owned Optional<Gizmo>
// CHECK-NEXT: [[SELF_REPLACED:%[0-9]+]] = apply [[SUPERMETHOD]](%0, [[X:%[0-9]+]]) : $@convention(objc_method) (Int, @owned Gizmo) -> @owned Optional<Gizmo>
// CHECK-NOT: unconditional_checked_cast downcast [[SELF_REPLACED]] : $Gizmo to $Hoozit
// CHECK: unchecked_ref_cast
// CHECK: return
override init(bellsOn x : Int) {
super.init(bellsOn: x)
other()
}
// Subscript
subscript (i: Int) -> Hoozit {
// Getter
// CHECK-LABEL: sil hidden [thunk] @_T011objc_thunks6HoozitC9subscriptACSicfgTo : $@convention(objc_method) (Int, Hoozit) -> @autoreleased Hoozit
// CHECK: bb0([[I:%[0-9]+]] : $Int, [[SELF:%[0-9]+]] : $Hoozit):
// CHECK-NEXT: [[SELF_COPY:%.*]] = copy_value [[SELF]] : $Hoozit
// CHECK-NEXT: [[BORROWED_SELF_COPY:%.*]] = begin_borrow [[SELF_COPY]]
// CHECK-NEXT: // function_ref
// CHECK-NEXT: [[NATIVE:%[0-9]+]] = function_ref @_T011objc_thunks6HoozitC9subscriptACSicfg : $@convention(method) (Int, @guaranteed Hoozit) -> @owned Hoozit
// CHECK-NEXT: [[RESULT:%[0-9]+]] = apply [[NATIVE]]([[I]], [[BORROWED_SELF_COPY]]) : $@convention(method) (Int, @guaranteed Hoozit) -> @owned Hoozit
// CHECK-NEXT: end_borrow [[BORROWED_SELF_COPY]] from [[SELF_COPY]]
// CHECK-NEXT: destroy_value [[SELF_COPY]]
// CHECK-NEXT: return [[RESULT]] : $Hoozit
get {
return self
}
// Setter
// CHECK-LABEL: sil hidden [thunk] @_T011objc_thunks6HoozitC9subscriptACSicfsTo : $@convention(objc_method) (Hoozit, Int, Hoozit) -> ()
// CHECK: bb0([[VALUE:%[0-9]+]] : $Hoozit, [[I:%[0-9]+]] : $Int, [[SELF:%[0-9]+]] : $Hoozit):
// CHECK: [[VALUE_COPY:%.*]] = copy_value [[VALUE]] : $Hoozit
// CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]] : $Hoozit
// CHECK: [[BORROWED_SELF_COPY:%.*]] = begin_borrow [[SELF_COPY]]
// CHECK: [[NATIVE:%[0-9]+]] = function_ref @_T011objc_thunks6HoozitC9subscriptACSicfs : $@convention(method) (@owned Hoozit, Int, @guaranteed Hoozit) -> ()
// CHECK: [[RESULT:%[0-9]+]] = apply [[NATIVE]]([[VALUE_COPY]], [[I]], [[BORROWED_SELF_COPY]]) : $@convention(method) (@owned Hoozit, Int, @guaranteed Hoozit) -> ()
// CHECK: end_borrow [[BORROWED_SELF_COPY]] from [[SELF_COPY]]
// CHECK: destroy_value [[SELF_COPY]]
// CHECK: return [[RESULT]] : $()
// CHECK: } // end sil function '_T011objc_thunks6HoozitC9subscriptACSicfsTo'
set {}
}
}
class Wotsit<T> : Gizmo {
// CHECK-LABEL: sil hidden [thunk] @_T011objc_thunks6WotsitC5plainyyFTo : $@convention(objc_method) <T> (Wotsit<T>) -> () {
// CHECK: bb0([[SELF:%.*]] : $Wotsit<T>):
// CHECK-NEXT: [[SELF_COPY:%.*]] = copy_value [[SELF]] : $Wotsit<T>
// CHECK-NEXT: [[BORROWED_SELF_COPY:%.*]] = begin_borrow [[SELF_COPY]]
// CHECK-NEXT: // function_ref
// CHECK-NEXT: [[NATIVE:%.*]] = function_ref @_T011objc_thunks6WotsitC5plainyyF : $@convention(method) <τ_0_0> (@guaranteed Wotsit<τ_0_0>) -> ()
// CHECK-NEXT: [[RESULT:%.*]] = apply [[NATIVE]]<T>([[BORROWED_SELF_COPY]]) : $@convention(method) <τ_0_0> (@guaranteed Wotsit<τ_0_0>) -> ()
// CHECK-NEXT: end_borrow [[BORROWED_SELF_COPY]] from [[SELF_COPY]]
// CHECK-NEXT: destroy_value [[SELF_COPY]] : $Wotsit<T>
// CHECK-NEXT: return [[RESULT]] : $()
// CHECK-NEXT: }
func plain() { }
func generic<U>(_ x: U) {}
var property : T
init(t: T) {
self.property = t
super.init()
}
// CHECK-LABEL: sil hidden [thunk] @_T011objc_thunks6WotsitC11descriptionSSfgTo : $@convention(objc_method) <T> (Wotsit<T>) -> @autoreleased NSString {
// CHECK: bb0([[SELF:%.*]] : $Wotsit<T>):
// CHECK-NEXT: [[SELF_COPY:%.*]] = copy_value [[SELF]] : $Wotsit<T>
// CHECK-NEXT: [[BORROWED_SELF_COPY:%.*]] = begin_borrow [[SELF_COPY]]
// CHECK-NEXT: // function_ref
// CHECK-NEXT: [[NATIVE:%.*]] = function_ref @_T011objc_thunks6WotsitC11descriptionSSfg : $@convention(method) <τ_0_0> (@guaranteed Wotsit<τ_0_0>) -> @owned String
// CHECK-NEXT: [[RESULT:%.*]] = apply [[NATIVE:%.*]]<T>([[BORROWED_SELF_COPY]]) : $@convention(method) <τ_0_0> (@guaranteed Wotsit<τ_0_0>) -> @owned String
// CHECK-NEXT: end_borrow [[BORROWED_SELF_COPY]] from [[SELF_COPY]]
// CHECK-NEXT: destroy_value [[SELF_COPY]] : $Wotsit<T>
// CHECK-NEXT: // function_ref
// CHECK-NEXT: [[BRIDGE:%.*]] = function_ref @_T0SS10FoundationE19_bridgeToObjectiveCSo8NSStringCyF
// CHECK-NEXT: [[BORROWED_RESULT:%.*]] = begin_borrow [[RESULT]]
// CHECK-NEXT: [[NSRESULT:%.*]] = apply [[BRIDGE]]([[BORROWED_RESULT]]) : $@convention(method) (@guaranteed String) -> @owned NSString
// CHECK-NEXT: end_borrow [[BORROWED_RESULT]] from [[RESULT]]
// CHECK-NEXT: destroy_value [[RESULT]]
// CHECK-NEXT: return [[NSRESULT]] : $NSString
// CHECK-NEXT: }
override var description : String {
return "Hello, world."
}
// Ivar destroyer
// CHECK: sil hidden @_T011objc_thunks6WotsitCfETo
// CHECK-LABEL: sil hidden [thunk] @_T011objc_thunks6WotsitCSQyACyxGGycfcTo : $@convention(objc_method) <T> (@owned Wotsit<T>) -> @owned Optional<Wotsit<T>>
// CHECK-LABEL: sil hidden [thunk] @_T011objc_thunks6WotsitCSQyACyxGGSi7bellsOn_tcfcTo : $@convention(objc_method) <T> (Int, @owned Wotsit<T>) -> @owned Optional<Wotsit<T>>
}
// CHECK-NOT: sil hidden [thunk] @_TToF{{.*}}Wotsit{{.*}}
// Extension initializers, properties and methods need thunks too.
extension Hoozit {
// CHECK-LABEL: sil hidden [thunk] @_T011objc_thunks6HoozitCACSi3int_tcfcTo : $@convention(objc_method) (Int, @owned Hoozit) -> @owned Hoozit
dynamic convenience init(int i: Int) { self.init(bellsOn: i) }
// CHECK-LABEL: sil hidden @_T011objc_thunks6HoozitCACSd6double_tcfc : $@convention(method) (Double, @owned Hoozit) -> @owned Hoozit
convenience init(double d: Double) {
// CHECK: [[SELF_BOX:%[0-9]+]] = alloc_box ${ var Hoozit }
// CHECK: [[PB:%.*]] = project_box [[SELF_BOX]]
// CHECK: [[SELFMUI:%[0-9]+]] = mark_uninitialized [delegatingself] [[PB]]
// CHECK: [[X_BOX:%[0-9]+]] = alloc_box ${ var X }
var x = X()
// CHECK: [[CTOR:%[0-9]+]] = class_method [volatile] [[SELF:%[0-9]+]] : $Hoozit, #Hoozit.init!initializer.1.foreign : (Hoozit.Type) -> (Int) -> Hoozit, $@convention(objc_method) (Int, @owned Hoozit) -> @owned Hoozit
// CHECK: [[NEW_SELF:%[0-9]+]] = apply [[CTOR]]
// CHECK: store [[NEW_SELF]] to [init] [[SELFMUI]] : $*Hoozit
// CHECK: [[NONNULL:%[0-9]+]] = is_nonnull [[NEW_SELF]] : $Hoozit
// CHECK-NEXT: cond_br [[NONNULL]], [[NONNULL_BB:bb[0-9]+]], [[NULL_BB:bb[0-9]+]]
// CHECK: [[NULL_BB]]:
// CHECK-NEXT: destroy_value [[X_BOX]] : ${ var X }
// CHECK-NEXT: br [[EPILOG_BB:bb[0-9]+]]
// CHECK: [[NONNULL_BB]]:
// CHECK: [[OTHER_REF:%[0-9]+]] = function_ref @_T011objc_thunks5otheryyF : $@convention(thin) () -> ()
// CHECK-NEXT: apply [[OTHER_REF]]() : $@convention(thin) () -> ()
// CHECK-NEXT: destroy_value [[X_BOX]] : ${ var X }
// CHECK-NEXT: br [[EPILOG_BB]]
// CHECK: [[EPILOG_BB]]:
// CHECK-NOT: super_method
// CHECK: return
self.init(int:Int(d))
other()
}
func foof() {}
// CHECK-LABEL: sil hidden [thunk] @_T011objc_thunks6HoozitC4foofyyFTo : $@convention(objc_method) (Hoozit) -> () {
var extensionProperty: Int { return 0 }
// CHECK-LABEL: sil hidden @_T011objc_thunks6HoozitC17extensionPropertySifg : $@convention(method) (@guaranteed Hoozit) -> Int
}
// Calling objc methods of subclass should go through native entry points
func useHoozit(_ h: Hoozit) {
// sil @_T011objc_thunks9useHoozityAA0D0C1h_tF
// In the class decl, gets dynamically dispatched
h.fork()
// CHECK: class_method {{%.*}} : {{.*}}, #Hoozit.fork!1 :
// In an extension, 'dynamic' was inferred.
h.foof()
// CHECK: class_method [volatile] {{%.*}} : {{.*}}, #Hoozit.foof!1.foreign
}
func useWotsit(_ w: Wotsit<String>) {
// sil @_T011objc_thunks9useWotsitySo0D0CySSG1w_tF
w.plain()
// CHECK: class_method {{%.*}} : {{.*}}, #Wotsit.plain!1 :
w.generic(2)
// CHECK: class_method {{%.*}} : {{.*}}, #Wotsit.generic!1 :
// Inherited methods only have objc entry points
w.clone()
// CHECK: class_method [volatile] {{%.*}} : {{.*}}, #Gizmo.clone!1.foreign
}
func other() { }
class X { }
// CHECK-LABEL: sil hidden @_T011objc_thunks8propertySiSo5GizmoCF
func property(_ g: Gizmo) -> Int {
// CHECK: bb0([[ARG:%.*]] : $Gizmo):
// CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]]
// CHECK: class_method [volatile] [[BORROWED_ARG]] : $Gizmo, #Gizmo.count!getter.1.foreign
return g.count
}
// CHECK-LABEL: sil hidden @_T011objc_thunks13blockPropertyySo5GizmoCF
func blockProperty(_ g: Gizmo) {
// CHECK: bb0([[ARG:%.*]] : $Gizmo):
// CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]]
// CHECK: class_method [volatile] [[BORROWED_ARG]] : $Gizmo, #Gizmo.block!setter.1.foreign
g.block = { }
// CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]]
// CHECK: class_method [volatile] [[BORROWED_ARG]] : $Gizmo, #Gizmo.block!getter.1.foreign
g.block()
}
class DesignatedStubs : Gizmo {
var i: Int
override init() { i = 5 }
// CHECK-LABEL: sil hidden @_T011objc_thunks15DesignatedStubsCSQyACGSi7bellsOn_tcfc
// CHECK: function_ref @_T0s25_unimplementedInitializers5NeverOs12StaticStringV9className_AE04initG0AE4fileSu4lineSu6columntF
// CHECK: string_literal utf8 "objc_thunks.DesignatedStubs"
// CHECK: string_literal utf8 "init(bellsOn:)"
// CHECK: string_literal utf8 "{{.*}}objc_thunks.swift"
// CHECK: return
// CHECK-NOT: sil hidden @_TFCSo15DesignatedStubsc{{.*}}
}
class DesignatedOverrides : Gizmo {
var i: Int = 5
// CHECK-LABEL: sil hidden @_T011objc_thunks19DesignatedOverridesCSQyACGycfc
// CHECK-NOT: return
// CHECK: function_ref @_T011objc_thunks19DesignatedOverridesC1iSivfi : $@convention(thin) () -> Int
// CHECK: super_method [volatile] [[SELF:%[0-9]+]] : $DesignatedOverrides, #Gizmo.init!initializer.1.foreign : (Gizmo.Type) -> () -> Gizmo!, $@convention(objc_method) (@owned Gizmo) -> @owned Optional<Gizmo>
// CHECK: return
// CHECK-LABEL: sil hidden @_T011objc_thunks19DesignatedOverridesCSQyACGSi7bellsOn_tcfc
// CHECK: function_ref @_T011objc_thunks19DesignatedOverridesC1iSivfi : $@convention(thin) () -> Int
// CHECK: super_method [volatile] [[SELF:%[0-9]+]] : $DesignatedOverrides, #Gizmo.init!initializer.1.foreign : (Gizmo.Type) -> (Int) -> Gizmo!, $@convention(objc_method) (Int, @owned Gizmo) -> @owned Optional<Gizmo>
// CHECK: return
}
// Make sure we copy blocks passed in as IUOs - <rdar://problem/22471309>
func registerAnsible() {
// CHECK: function_ref @_T011objc_thunks15registerAnsibleyyFyyycSgcfU_
Ansible.anseAsync({ completion in completion!() })
}
| ab87e2d0744a062e6ead25441b3b63cc | 53.258065 | 222 | 0.625236 | false | false | false | false |
ibari/ios-twitter | refs/heads/master | Pods/RelativeFormatter/Source/RelativeFormatter.swift | gpl-2.0 | 1 | //
// RelativeFormatter.swift
// RelativeFormatter
//
// Created by David Collado Sela on 12/5/15.
// Copyright (c) 2015 David Collado Sela. All rights reserved.
//
import Foundation
public enum Precision{
case Year,Month,Week,Day,Hour,Minute,Second
}
extension NSDate{
public func relativeFormatted(idiomatic:Bool=false,precision:Precision=Precision.Second)->String{
let calendar = NSCalendar.currentCalendar()
let unitFlags = NSCalendarUnit.CalendarUnitMinute | NSCalendarUnit.CalendarUnitHour | NSCalendarUnit.CalendarUnitDay | NSCalendarUnit.CalendarUnitWeekOfYear | NSCalendarUnit.CalendarUnitMonth | NSCalendarUnit.CalendarUnitYear | NSCalendarUnit.CalendarUnitSecond
let now = NSDate()
let formattedDateData:(key:String,count:Int?)
if(self.timeIntervalSince1970 < now.timeIntervalSince1970){
let components:NSDateComponents = calendar.components(unitFlags, fromDate: self, toDate: now, options: nil)
formattedDateData = RelativeFormatter.getPastKeyAndCount(components,idiomatic:idiomatic,precision:precision)
}else{
let components:NSDateComponents = calendar.components(unitFlags, fromDate: now, toDate: self, options: nil)
formattedDateData = RelativeFormatter.getFutureKeyAndCount(components,idiomatic:idiomatic,precision:precision)
}
return LocalizationHelper.localize(formattedDateData.key,count:formattedDateData.count)
}
}
class RelativeFormatter {
class func getPastKeyAndCount(components:NSDateComponents,idiomatic:Bool,precision:Precision)->(key:String,count:Int?){
var key = ""
var count:Int?
if(components.year >= 2){
count = components.year
key = "yearsago"
}
else if(components.year >= 1){
key = "yearago"
}
else if(components.year == 0 && precision == Precision.Year){
return ("thisyear",nil)
}
else if(components.month >= 2){
count = components.month
key = "monthsago"
}
else if(components.month >= 1){
key = "monthago"
}
else if(components.month == 0 && precision == Precision.Month){
return ("thismonth",nil)
}
else if(components.weekOfYear >= 2){
count = components.weekOfYear
key = "weeksago"
}
else if(components.weekOfYear >= 1){
key = "weekago"
}
else if(components.weekOfYear == 0 && precision == Precision.Week){
return ("thisweek",nil)
}
else if(components.day >= 2){
count = components.day
key = "daysago"
}
else if(components.day >= 1){
key = "dayago"
if(idiomatic){
key = key + "-idiomatic"
}
}
else if(components.day == 0 && precision == Precision.Day){
return ("today",nil)
}
else if(components.hour >= 2){
count = components.hour
key = "hoursago"
}
else if(components.hour >= 1){
key = "hourago"
}
else if(components.hour == 0 && precision == Precision.Hour){
return ("thishour",nil)
}
else if(components.minute >= 2){
count = components.minute
key = "minutesago"
}
else if(components.minute >= 1){
key = "minuteago"
}
else if(components.minute == 0 && precision == Precision.Minute){
return ("thisminute",nil)
}
else if(components.second >= 2){
count = components.second
key = "secondsago"
if(idiomatic){
key = key + "-idiomatic"
}
}
else{
key = "secondago"
if(idiomatic){
key = "now"
}
}
return (key,count)
}
class func getFutureKeyAndCount(components:NSDateComponents,idiomatic:Bool,precision:Precision)->(key:String,count:Int?){
var key = ""
var count:Int?
println(components.year)
if(components.year >= 2){
println(components.year)
count = components.year
key = "yearsahead"
}
else if(components.year >= 1){
key = "yearahead"
}
else if(components.year == 0 && precision == Precision.Year){
return ("thisyear",nil)
}
else if(components.month >= 2){
count = components.month
key = "monthsahead"
}
else if(components.month >= 1){
key = "monthahead"
}
else if(components.month == 0 && precision == Precision.Month){
return ("thismonth",nil)
}
else if(components.weekOfYear >= 2){
count = components.weekOfYear
key = "weeksahead"
}
else if(components.weekOfYear >= 1){
key = "weekahead"
}
else if(components.weekOfYear == 0 && precision == Precision.Week){
return ("thisweek",nil)
}
else if(components.day >= 2){
count = components.day
key = "daysahead"
}
else if(components.day >= 1){
key = "dayahead"
if(idiomatic){
key = key + "-idiomatic"
}
}
else if(components.day == 0 && precision == Precision.Day){
return ("today",nil)
}
else if(components.hour >= 2){
count = components.hour
key = "hoursahead"
}
else if(components.hour >= 1){
key = "hourahead"
}
else if(components.hour == 0 && precision == Precision.Hour){
return ("thishour",nil)
}
else if(components.minute >= 2){
count = components.minute
key = "minutesahead"
}
else if(components.minute >= 1){
key = "minuteahead"
}
else if(components.minute == 0 && precision == Precision.Minute){
return ("thisminute",nil)
}
else if(components.second >= 2){
count = components.second
key = "secondsahead"
if(idiomatic){
key = key + "-idiomatic"
}
}
else{
key = "secondahead"
if(idiomatic){
key = "now"
}
}
return (key,count)
}
}
| d815adfd8d742ad16a66da8b7e02b80f | 31.551724 | 269 | 0.533444 | false | false | false | false |
JoniVR/VerticalCardSwiper | refs/heads/main | Example/ExampleCardCell.swift | mit | 1 | // MIT License
//
// Copyright (c) 2017 Joni Van Roost
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import Foundation
import UIKit
import VerticalCardSwiper
class ExampleCardCell: CardCell {
@IBOutlet weak var nameLbl: UILabel!
@IBOutlet weak var ageLbl: UILabel!
/**
We use this function to calculate and set a random backgroundcolor.
*/
public func setRandomBackgroundColor() {
let randomRed: CGFloat = CGFloat(arc4random()) / CGFloat(UInt32.max)
let randomGreen: CGFloat = CGFloat(arc4random()) / CGFloat(UInt32.max)
let randomBlue: CGFloat = CGFloat(arc4random()) / CGFloat(UInt32.max)
self.backgroundColor = UIColor(red: randomRed, green: randomGreen, blue: randomBlue, alpha: 1.0)
}
override func prepareForReuse() {
super.prepareForReuse()
}
override func layoutSubviews() {
self.layer.cornerRadius = 12
super.layoutSubviews()
}
}
| 8cdc22155c4871ea0cde10fbe40080d3 | 36.339623 | 104 | 0.726124 | false | false | false | false |
greenSyntax/AWS-RaspberryPi | refs/heads/master | IotApp/IotApp/Presenter/ReportPresenter.swift | mit | 1 | //
// ReportPresenter.swift
// IotApp
//
// Created by Abhishek Ravi on 06/06/17.
// Copyright © 2017 Abhishek Ravi. All rights reserved.
//
import Foundation
import JSONParserSwift
struct ReportViewModel{
var temperature:Double?
var humidity:Double?
var pressure:Double?
var dateOfRecord:Date?
}
struct ChartsData {
var temperatureLog:[Double] = []
var humidityLog:[Double] = []
var pressureLog:[Double] = []
var time: [String] = []
}
class ReportPresenter{
//MARK:- Private Methods
private static func getTwoPlacesDecimal(value:NSNumber)->Double{
return Double(round(1000 * Double(value))/1000)
}
private static func prepareChartsLog(data:[ReportModel])->ChartsData{
var charts = ChartsData()
for dataum in data{
if let temp = dataum.temperature, let humdidty = dataum.humidity, let pressure = dataum.pressure, let time = dataum.createddate {
charts.temperatureLog.append(temp.doubleValue)
charts.humidityLog.append(humdidty.doubleValue)
charts.pressureLog.append(pressure.doubleValue)
if var timestamp = Double(time) {
timestamp = timestamp / 1000
let date = Date(timeIntervalSince1970: timestamp)
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "hh:mm:ss"
charts.time.append(dateFormatter.string(from: date))
}
}
}
return charts
}
private static func prepareViewModel(data:[ReportModel])->[ReportViewModel]{
var arrayOfViewModel:[ReportViewModel] = []
for dataum in data{
var viewModel = ReportViewModel()
if let temp = dataum.temperature, let humidty = dataum.humidity, let pressure = dataum.pressure{
viewModel.temperature = getTwoPlacesDecimal(value: temp)
viewModel.humidity = getTwoPlacesDecimal(value: humidty)
viewModel.pressure = getTwoPlacesDecimal(value: pressure)
viewModel.dateOfRecord = DateHelper.getRawDate(dataum.createddate ?? "")
arrayOfViewModel.append(viewModel)
}
}
return arrayOfViewModel
}
static func getRecord(onSuccess:@escaping (([ReportViewModel], ChartsData)->Void), onError:@escaping ((ErrorModel)->Void)){
//Structure
let api = ApiStruct(endPoint: Constants.Attributes.getenvdata, type: .get, body: nil, headers: nil)
WSManager.shared.getResponse(api: api, onSuccess: { (reportsData) in
let data:ReportArrayModel = JSONParserSwift.parse(dictionary: (reportsData as? [String:Any])!)
if let data = data.envDetails{
let chartData = prepareChartsLog(data: data)
let reportData = prepareViewModel(data: data)
onSuccess(reportData, chartData)
}
}) { (error) in
//Error Occured
onError(error)
}
}
}
| 43c3ab2e71ec2030f3ec4e89ed1043b8 | 30.082569 | 141 | 0.560508 | false | false | false | false |
woshishui1243/LYCustomEmoticonKeyboard | refs/heads/master | Source/EmoticonsAttachment.swift | mit | 1 | //
// EmoticonsAttachment.swift
// LYCustomEmotionKeyboard
//
// Created by 李禹 on 15/11/26.
// Copyright © 2015年 dayu. All rights reserved.
//
import UIKit
class EmoticonsAttachment: NSTextAttachment {
var emoticon: Emoticon!;
class func emoticonString(emo: Emoticon, height: CGFloat) -> NSAttributedString {
let attachment = EmoticonsAttachment();
let bundlePath = (NSBundle.mainBundle().pathForResource("Emoticons.bundle", ofType: nil) as NSString!);
let name = (bundlePath.stringByAppendingPathComponent(emo.emoticon_group_path!) as NSString).stringByAppendingPathComponent(emo.png!);
attachment.emoticon = emo;
let image = UIImage(named: name)
attachment.image = image;
attachment.bounds = CGRectMake(0, -4, height, height);
let attributedStr = NSAttributedString(attachment: attachment);
return attributedStr;
}
}
| 2c8696e1d4325de635d5d10af67f7103 | 32.962963 | 142 | 0.696838 | false | false | false | false |
DAloG/BlueCap | refs/heads/master | BlueCap/Utils/ConfigStore.swift | mit | 1 | //
// ConfigStore.swift
// BlueCap
//
// Created by Troy Stribling on 8/29/14.
// Copyright (c) 2014 Troy Stribling. The MIT License (MIT).
//
import Foundation
import BlueCapKit
import CoreBluetooth
import CoreLocation
class ConfigStore {
// scan mode
class func getScanMode() -> String {
if let scanMode = NSUserDefaults.standardUserDefaults().stringForKey("scanMode") {
return scanMode
} else {
return "Promiscuous"
}
}
class func setScanMode(scanMode:String) {
NSUserDefaults.standardUserDefaults().setObject(scanMode, forKey:"scanMode")
}
// scan timeout
class func getScanTimeoutEnabled() -> Bool {
return NSUserDefaults.standardUserDefaults().boolForKey("scanTimeoutEnabled")
}
class func setScanTimeoutEnabled(timeoutEnabled:Bool) {
NSUserDefaults.standardUserDefaults().setBool(timeoutEnabled, forKey:"scanTimeoutEnabled")
}
class func getScanTimeout() -> Int {
let timeout = NSUserDefaults.standardUserDefaults().integerForKey("scanTimeout")
if timeout == 0 {
return 10
} else {
return timeout
}
}
class func setScanTimeout(timeout:Int) {
NSUserDefaults.standardUserDefaults().setInteger(timeout, forKey:"scanTimeout")
}
// peripheral connection timeout
class func getPeripheralConnectionTimeout() -> Int {
let peripheralConnectionTimeout = NSUserDefaults.standardUserDefaults().integerForKey("peripheralConnectionTimeout")
if peripheralConnectionTimeout == 0 {
return 10
} else {
return peripheralConnectionTimeout
}
}
class func setPeripheralConnectionTimeout(peripheralConnectionTimeout:Int) {
NSUserDefaults.standardUserDefaults().setInteger(peripheralConnectionTimeout, forKey:"peripheralConnectionTimeout")
}
// characteristic read write timeout
class func getCharacteristicReadWriteTimeout() -> Int {
let characteristicReadWriteTimeout = NSUserDefaults.standardUserDefaults().integerForKey("characteristicReadWriteTimeout")
if characteristicReadWriteTimeout == 0 {
return 10
} else {
return characteristicReadWriteTimeout
}
}
class func setCharacteristicReadWriteTimeout(characteristicReadWriteTimeout:Int) {
NSUserDefaults.standardUserDefaults().setInteger(characteristicReadWriteTimeout, forKey:"characteristicReadWriteTimeout")
}
// maximum reconnections
class func getMaximumReconnections() -> UInt {
let maximumReconnetions = NSUserDefaults.standardUserDefaults().integerForKey("maximumReconnections")
if maximumReconnetions == 0 {
return 5
} else {
return UInt(maximumReconnetions)
}
}
class func setMaximumReconnections(maximumReconnetions:UInt) {
NSUserDefaults.standardUserDefaults().setInteger(Int(maximumReconnetions), forKey:"maximumReconnections")
}
// scanned services
class func getScannedServices() -> [String:CBUUID] {
if let storedServices = NSUserDefaults.standardUserDefaults().dictionaryForKey("services") {
var services = [String:CBUUID]()
for (name, uuid) in storedServices {
if let uuid = uuid as? String {
services[name] = CBUUID(string: uuid)
}
}
return services
} else {
return [:]
}
}
class func getScannedServiceNames() -> [String] {
return self.getScannedServices().keys.array
}
class func getScannedServiceUUIDs() -> [CBUUID] {
return self.getScannedServices().values.array
}
class func getScannedServiceUUID(name:String) -> CBUUID? {
let services = self.getScannedServices()
if let uuid = services[name] {
return uuid
} else {
return nil
}
}
class func setScannedServices(services:[String:CBUUID]) {
var storedServices = [String:String]()
for (name, uuid) in services {
storedServices[name] = uuid.UUIDString
}
NSUserDefaults.standardUserDefaults().setObject(storedServices, forKey:"services")
}
class func addScannedService(name:String, uuid:CBUUID) {
var services = self.getScannedServices()
services[name] = uuid
self.setScannedServices(services)
}
class func removeScannedService(name:String) {
var beacons = self.getScannedServices()
beacons.removeValueForKey(name)
self.setScannedServices(beacons)
}
} | 94e462627cbcf07c66364fc7317a62ef | 31.806897 | 130 | 0.649916 | false | false | false | false |
cwwise/CWWeChat | refs/heads/master | CWWeChat/ChatModule/CWInput/Emoticon/EmoticonGroup.swift | mit | 3 | //
// EmojiGroup.swift
// Keyboard
//
// Created by chenwei on 2017/3/26.
// Copyright © 2017年 cwcoder. All rights reserved.
//
import UIKit
import SwiftyJSON
public class EmoticonGroup: NSObject {
// id
var id: String
// 表情组 名称
var name: String
// 标签类型
var type: EmoticonType = .normal
/// 表情图像路径
var iconPath: String
/// 表情数组
var emoticons: [Emoticon] = []
var count: Int {
return emoticons.count
}
init(id: String,
name: String = "",
icon: String,
emoticons: [Emoticon]) {
self.id = id
self.name = name
self.iconPath = icon
self.emoticons = emoticons
}
}
public extension EmoticonGroup {
convenience init?(identifier : String) {
let bundle = Bundle.main
guard let path = bundle.path(forResource: "emoticons.bundle/\(identifier)/Info", ofType: "plist"),
let dict = NSDictionary(contentsOfFile: path) else {
return nil
}
let json = JSON(dict)
let emoticonsArray = json["emoticons"].arrayValue
let directory = URL(fileURLWithPath: path).deletingLastPathComponent().path
let id = json["id"].stringValue
let icon = json["image"].stringValue
var emoticons: [Emoticon] = []
let type = json["type"].intValue
let emoticonType = EmoticonType(rawValue: type) ?? .normal
for item in emoticonsArray {
let id = item["id"].stringValue
let title = item["title"].stringValue
let _ = item["type"].stringValue
// 需要添加@2x
let imagePath = directory + "/" + id + "@2x.png"
let emoticon = Emoticon(id: id, title: title, path: URL(fileURLWithPath: imagePath))
emoticon.type = emoticonType
emoticons.append(emoticon)
}
self.init(id: id, icon: directory + "/" + icon, emoticons: emoticons)
}
}
| 1309fb7a8e9fb59de5dd693979ce4e26 | 26.162162 | 106 | 0.563682 | false | false | false | false |
Touchwonders/veggies | refs/heads/master | Veggies/SpriteKit/Nodes/Dot.swift | mit | 1 | //
// Dot.swift
// Veggies
//
// Created by RHLJH Hooijmans on 22/08/15.
// Copyright © 2015 Robert-Hein Hooijmans. All rights reserved.
//
import Foundation
import UIKit
import SpriteKit
protocol DotDelegate: class {
func tappedDot(dot: Dot)
}
class Dot: SKSpriteNode {
weak var delegate: DotDelegate?
var imageIndex: Int = 0
var initialRadius: CGFloat = 0.0
var multiplier: Int = 0
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
init(radius: CGFloat, index: Int){
super.init(texture: SKTexture(imageNamed: "veggie\(index)"), color: .blackColor(), size: CGSizeMake(radius * 2.0, radius * 2.0))
imageIndex = index
initialRadius = radius
let randomValue = CGFloat(Int(arc4random()) % 100) / 100.0
name = Statics.Nodes.Dot
userInteractionEnabled = true
physicsBody = SKPhysicsBody(circleOfRadius: radius + 1.0)
if let physicsBody = physicsBody {
physicsBody.dynamic = true
physicsBody.usesPreciseCollisionDetection = false
physicsBody.allowsRotation = true
physicsBody.pinned = false
physicsBody.resting = false
physicsBody.friction = 0.01
physicsBody.restitution = 0.1
physicsBody.linearDamping = randomValue * 10.0
physicsBody.angularDamping = 0.01
physicsBody.mass = randomValue
physicsBody.affectedByGravity = true
}
}
func addToShoppingList() -> SKAction {
multiplier = multiplier == 0 ? 1 : 0
let initialScale: CGFloat = xScale
let duration: NSTimeInterval = 0.2
let scale: CGFloat = 1.0 + (CGFloat(multiplier) * 0.5)
let growToNewScale = SKAction.customActionWithDuration(duration) { (node, elapsedTime) -> Void in
let t: CGFloat = elapsedTime / CGFloat(duration)
let p: CGFloat = t * t
let s: CGFloat = initialScale * (1.0 - p) + scale * p
node.setScale(s)
}
return growToNewScale
}
override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
delegate?.tappedDot(self)
}
} | 50777be9fc74e95b00dcadf5ca1ad8fe | 27.743902 | 136 | 0.59253 | false | false | false | false |
digitwolf/SwiftFerrySkill | refs/heads/master | Sources/Ferry/Models/DepartingSpaces.swift | apache-2.0 | 1 | //
// DepartingSpaces.swift
// FerrySkill
//
// Created by Shakenova, Galiya on 3/3/17.
//
//
import Foundation
import SwiftyJSON
public class DepartingSpaces {
public var departure : Date? = Date()
public var isCancelled : Bool? = false
public var vesselID : Int? = 0
public var vesselName : String? = ""
public var maxSpaceCount : Int? = 0
public var spaceForArrivalTerminals : [SpaceForArrivalTerminals] = []
init() {
}
public init(_ json: JSON) {
departure = Date.init(jsonDate: json["Departure"].stringValue)!
isCancelled = json["IsCancelled"].boolValue
vesselID = json["VesselID"].intValue
vesselName = json["VesselName"].stringValue
maxSpaceCount = json["MaxSpaceCount"].intValue
for space in json["SpaceForArrivalTerminals"].arrayValue {
spaceForArrivalTerminals.append(SpaceForArrivalTerminals.init(space))
}
}
public func toJson() -> JSON {
var json = JSON([])
json["Departure"].double = departure?.timeIntervalSince1970
json["IsCancelled"].boolValue = isCancelled!
json["VesselID"].intValue = vesselID!
json["VesselName"].stringValue = vesselName!
json["MaxSpaceCount"].intValue = maxSpaceCount!
var arrivals: [SpaceForArrivalTerminals] = []
for space in spaceForArrivalTerminals {
arrivals.append(space)
}
json["SpaceForArrivalTerminals"] = JSON(arrivals)
return json
}
}
| 6020c541a0b83d199b50eba275a8d20a | 27.836735 | 77 | 0.689314 | false | false | false | false |
kriscarle/dev4outdoors-parkbook | refs/heads/master | Parkbook/SecondViewController.swift | mit | 1 | //
// SecondViewController.swift
// Parkbook
//
// Created by Kristofor Carle on 4/12/15.
// Copyright (c) 2015 Kristofor Carle. All rights reserved.
//
import UIKit
import TwitterKit
class SecondViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let logInButton = TWTRLogInButton(logInCompletion: {
(session: TWTRSession!, error: NSError!) in
// play with Twitter session
})
var bounds: CGRect = UIScreen.mainScreen().bounds
var width:CGFloat = bounds.size.width
var height:CGFloat = bounds.size.height
logInButton.center.x = self.view.frame.origin.x + (width / 2)
logInButton.center.y = self.view.frame.origin.y + 50
self.view.addSubview(logInButton)
var commentButton = UIButton.buttonWithType(UIButtonType.System) as! UIButton
commentButton.frame = CGRectMake(16, 116, 288, 30)
commentButton.center.x = self.view.frame.origin.x + (width / 2)
commentButton.center.y = self.view.frame.origin.y + 150
commentButton.backgroundColor = UIColor.lightGrayColor()
commentButton.setTitle("Comment on Twitter", forState: UIControlState.Normal)
commentButton.addTarget(self, action: "commentOnTwitter:", forControlEvents: UIControlEvents.TouchUpInside)
self.view.addSubview(commentButton)
var feedButton = UIButton.buttonWithType(UIButtonType.System) as! UIButton
feedButton.frame = CGRectMake(16, 116, 288, 30)
feedButton.center.x = self.view.frame.origin.x + (width / 2)
feedButton.center.y = self.view.frame.origin.y + 250
feedButton.backgroundColor = UIColor.lightGrayColor()
feedButton.setTitle("View Twitter Comments", forState: UIControlState.Normal)
feedButton.addTarget(self, action: "showFeed:", forControlEvents: UIControlEvents.TouchUpInside)
self.view.addSubview(feedButton)
// Do any additional setup after loading the view, typically from a nib.
}
func commentOnTwitter(sender: UIButton!)
{
let composer = TWTRComposer()
composer.setText("#NationalMall")
composer.setImage(UIImage(named: "fabric"))
composer.showWithCompletion { (result) -> Void in
if (result == TWTRComposerResult.Cancelled) {
println("Tweet composition cancelled")
}
else {
println("Sending tweet!")
}
}
}
func showFeed(sender: UIButton!)
{
Twitter.sharedInstance().logInGuestWithCompletion { (session: TWTRGuestSession!, error: NSError!) in
//let client = Twitter.sharedInstance().APIClient
//let dataSource = TWTRSearchTimelineDataSource(searchQuery: "#dev4outdoors", APIClient: client)
//let viewController = TWTRTimelineViewController(dataSource: dataSource)
let storyboard = UIStoryboard(name: "Main", bundle: NSBundle.mainBundle())
let viewController = storyboard.instantiateViewControllerWithIdentifier("CommentsViewController") as! CommentsViewController
self.parentViewController?.navigationController?.pushViewController(viewController, animated: true)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| 94ac18119115b82ca5ef6ae79a6eb3f8 | 36.382979 | 136 | 0.656801 | false | false | false | false |
diegosanchezr/Chatto | refs/heads/master | Chatto/Source/ChatController/ChatCollectionViewLayout.swift | mit | 1 | /*
The MIT License (MIT)
Copyright (c) 2015-present Badoo Trading Limited.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
import UIKit
public protocol ChatCollectionViewLayoutDelegate: class {
func chatCollectionViewLayoutModel() -> ChatCollectionViewLayoutModel
}
public struct ChatCollectionViewLayoutModel {
let contentSize: CGSize
let layoutAttributes: [UICollectionViewLayoutAttributes]
let layoutAttributesBySectionAndItem: [[UICollectionViewLayoutAttributes]]
let calculatedForWidth: CGFloat
public static func createModel(collectionViewWidth: CGFloat, itemsLayoutData: [(height: CGFloat, bottomMargin: CGFloat)]) -> ChatCollectionViewLayoutModel {
var layoutAttributes = [UICollectionViewLayoutAttributes]()
var layoutAttributesBySectionAndItem = [[UICollectionViewLayoutAttributes]]()
layoutAttributesBySectionAndItem.append([UICollectionViewLayoutAttributes]())
var verticalOffset: CGFloat = 0
for (index, layoutData) in itemsLayoutData.enumerate() {
let indexPath = NSIndexPath(forItem: index, inSection: 0)
let (height, bottomMargin) = layoutData
let itemSize = CGSize(width: collectionViewWidth, height: height)
let frame = CGRect(origin: CGPoint(x: 0, y: verticalOffset), size: itemSize)
let attributes = UICollectionViewLayoutAttributes(forCellWithIndexPath: indexPath)
attributes.frame = frame
layoutAttributes.append(attributes)
layoutAttributesBySectionAndItem[0].append(attributes)
verticalOffset += itemSize.height
verticalOffset += bottomMargin
}
return ChatCollectionViewLayoutModel(
contentSize: CGSize(width: collectionViewWidth, height: verticalOffset),
layoutAttributes: layoutAttributes,
layoutAttributesBySectionAndItem: layoutAttributesBySectionAndItem,
calculatedForWidth: collectionViewWidth
)
}
}
public class ChatCollectionViewLayout: UICollectionViewLayout {
var layoutModel: ChatCollectionViewLayoutModel!
public weak var delegate: ChatCollectionViewLayoutDelegate?
// Optimization: after reloadData we'll get invalidateLayout, but prepareLayout will be delayed until next run loop.
// Client may need to force prepareLayout after reloadData, but we don't want to compute layout again in the next run loop.
private var layoutNeedsUpdate = true
public override func invalidateLayout() {
super.invalidateLayout()
self.layoutNeedsUpdate = true
}
public override func prepareLayout() {
super.prepareLayout()
guard self.layoutNeedsUpdate else { return }
guard let delegate = self.delegate else { return }
var oldLayoutModel = self.layoutModel
self.layoutModel = delegate.chatCollectionViewLayoutModel()
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) { () -> Void in
// Dealloc of layout with 5000 items take 25 ms on tests on iPhone 4s
// This moves dealloc out of main thread
if oldLayoutModel != nil {
// Use nil check above to remove compiler warning: Variable 'oldLayoutModel' was written to, but never read
oldLayoutModel = nil
}
}
}
public override func collectionViewContentSize() -> CGSize {
if self.layoutNeedsUpdate {
self.prepareLayout()
}
return self.layoutModel.contentSize
}
override public func layoutAttributesForElementsInRect(rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
return self.layoutModel.layoutAttributes.filter { $0.frame.intersects(rect) }
}
public override func layoutAttributesForItemAtIndexPath(indexPath: NSIndexPath) -> UICollectionViewLayoutAttributes? {
if indexPath.section < self.layoutModel.layoutAttributesBySectionAndItem.count && indexPath.item < self.layoutModel.layoutAttributesBySectionAndItem[indexPath.section].count {
return self.layoutModel.layoutAttributesBySectionAndItem[indexPath.section][indexPath.item]
}
assert(false, "Unexpected indexPath requested:\(indexPath)")
return nil
}
public override func shouldInvalidateLayoutForBoundsChange(newBounds: CGRect) -> Bool {
return self.layoutModel.calculatedForWidth != newBounds.width
}
}
| 1a1cd751e706bd97ebaa6ee67920de4e | 45.939655 | 183 | 0.730579 | false | false | false | false |
ripventura/VCUIKit | refs/heads/master | VCUIKit/Classes/VCTheme/VCToolbar.swift | mit | 1 | //
// VCToolbar.swift
// VCUIKit
//
// Created by Vitor Cesco on 02/10/17.
//
import UIKit
@IBDesignable class VCToolbar: UIToolbar {
/** Whether the appearance is being set manually on Storyboard */
@IBInspectable var storyboardAppearance: Bool = false
override public init(frame: CGRect) {
super.init(frame: frame)
self.applyAppearance()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
open override func awakeFromNib() {
super.awakeFromNib()
self.applyAppearance()
}
open override func prepareForInterfaceBuilder() {
super.prepareForInterfaceBuilder()
self.applyAppearance()
}
override open func applyAppearance() -> Void {
super.applyAppearance()
if !storyboardAppearance {
print(sharedAppearanceManager.appearance.toolbarTintColor)
self.tintColor = sharedAppearanceManager.appearance.toolbarTintColor
}
self.items?.forEach({buttonItem in
if buttonItem.style == .plain {
if let customFont = sharedAppearanceManager.appearance.navigationBarItemsPlainFont {
buttonItem.setTitleTextAttributes([NSAttributedStringKey.font: customFont], for: .normal)
}
}
else if buttonItem.style == .done {
if let customFont = sharedAppearanceManager.appearance.navigationBarItemsDoneFont {
buttonItem.setTitleTextAttributes([NSAttributedStringKey.font: customFont], for: .normal)
}
}
})
}
}
| 30cd23038c4ddd2a9961dc76852f17eb | 29.321429 | 109 | 0.613074 | false | false | false | false |
capstone411/SHAF | refs/heads/master | Capstone/IOS_app/SHAF/SHAF/BTDiscovery.swift | mit | 1 | //
// BTDiscovery.swift
// SHAF
//
// Created by Ahmed Abdulkareem on 4/13/16.
// Copyright © 2016 Ahmed Abdulkareem. All rights reserved.
//
import UIKit
import CoreBluetooth
let BLEDiscovery = BTDiscovery()
// define UUIDs
let SHAF_SERVICE_UUID = CBUUID(string: "180D")
let REC_CALIB_ERR_CHARACTERISTIC_UUID = CBUUID(string: "2a37")
let REC_CALIB_DONE_CHARACTERISTIC_UUID = CBUUID(string: "2a38")
let REC_REP_COUNT_CHARACTERISTIC_UUID = CBUUID(string: "2a39")
let REC_FATIGUE_CHARACTERISTIC_UUID = CBUUID(string: "2a3a")
let REC_TIMEOUT_CHARACTERISTIC_UUID = CBUUID(string: "2a3b")
let SEND_CALIB_START_CHARACTERISTIC_UUID = CBUUID(string: "2a3c")
let SEND_START_CHARACTERISTIC_UUID = CBUUID(string: "2a3d")
let SEND_STOP_CHARACTERISTIC_UUID = CBUUID(string: "2a3e")
class BTDiscovery: NSObject, CBCentralManagerDelegate, CBPeripheralDelegate {
private var centralManager: CBCentralManager? // BLE central manager
private var peripheralBLE: CBPeripheral?
private var discoveredDevices = [String]() // a list of discovered devices
private var peripherals = [CBPeripheral]() // a list of all peripheral objects
private var isConnected: Bool? // flag to indicate connection
private var service: CBService?
var characteristics = [String: CBCharacteristic]() // a dicrionary of characteristics
var weightAmount = 0
var devicesDiscovered: [String] {
return self.discoveredDevices
}
var periphs: [CBPeripheral] {
return self.peripherals
}
override init() {
super.init()
let centralQueue = dispatch_queue_create("SHAF", DISPATCH_QUEUE_SERIAL)
centralManager = CBCentralManager(delegate: self, queue: centralQueue)
}
// this function assigns characteristics into a dictionary so
// they can be referred to later easily without looping into the
// array every time
func assignCharacteristics() {
dispatch_async(dispatch_get_main_queue()) {
// get characteristic from current service
let chars = self.service?.characteristics
// make sure its not empty
if chars == nil {
return
}
// loop through characteristics to find the right one
for characteristic in chars! {
if characteristic.UUID == SEND_CALIB_START_CHARACTERISTIC_UUID {
self.characteristics["SEND_CALIB_START_CHARACTERISTIC"] = characteristic
}
else if characteristic.UUID == SEND_START_CHARACTERISTIC_UUID {
self.characteristics["SEND_START_CHARACTERISTIC"] = characteristic
}
else if characteristic.UUID == SEND_STOP_CHARACTERISTIC_UUID {
self.characteristics["SEND_STOP_CHARACTERISTIC"] = characteristic
}
else if characteristic.UUID == REC_REP_COUNT_CHARACTERISTIC_UUID {
self.characteristics["REC_REP_COUNT_CHARACTERISTIC"] = characteristic
}
else if characteristic.UUID == REC_FATIGUE_CHARACTERISTIC_UUID {
self.characteristics["REC_FATIGUE_CHARACTERISTIC"] = characteristic
}
else if characteristic.UUID == REC_TIMEOUT_CHARACTERISTIC_UUID {
self.characteristics["REC_TIMEOUT_CHARACTERISTIC"] = characteristic
}
else if characteristic.UUID == REC_CALIB_ERR_CHARACTERISTIC_UUID {
self.characteristics["REC_CALIB_ERR_CHARACTERISTIC"] = characteristic
}
else if characteristic.UUID == REC_CALIB_DONE_CHARACTERISTIC_UUID {
self.characteristics["REC_CALIB_DONE_CHARACTERISTIC"] = characteristic
}
}
}
}
func stopScan() {
self.centralManager?.stopScan()
}
func connect(peripheral: Int) {
// stop scanning to save power
self.centralManager!.stopScan()
self.peripheralBLE = self.peripherals[peripheral]
self.peripheralBLE?.delegate = self;
self.centralManager?.connectPeripheral(self.peripheralBLE!, options: nil)
}
func startStopData(start: Bool) {
var startValue = 1
if !start {
startValue = 0
}
let startByte = NSData(bytes: &startValue, length: sizeof(UInt8))
print("Start flag: ", startValue)
self.peripheralBLE?.writeValue(startByte, forCharacteristic: self.characteristics["SEND_START_CHARACTERISTIC"]!, type: CBCharacteristicWriteType.WithResponse)
}
// asserts the stop flag when called
func assertStop(deassert: Bool) {
var stopValue = 1
if deassert {
stopValue = 0
}
let stopByte = NSData(bytes: &stopValue, length: sizeof(UInt8))
// update characteristic
self.peripheralBLE?.writeValue(stopByte, forCharacteristic: self.characteristics["SEND_STOP_CHARACTERISTIC"]!, type: CBCharacteristicWriteType.WithResponse)
}
// function used to set or clear calibrate flag
func calibrate(set: Bool) {
var startValue = 1
var startByte = NSData(bytes: &startValue, length: sizeof(UInt8))
if !set {
startValue = 0
startByte = NSData(bytes: &startValue, length: sizeof(UInt8))
}
print("calib start value:", startValue)
self.peripheralBLE?.writeValue(startByte, forCharacteristic: self.characteristics["SEND_CALIB_START_CHARACTERISTIC"]!, type: CBCharacteristicWriteType.WithResponse)
}
func centralManagerDidUpdateState(central: CBCentralManager) {
// if bluetooth is on, start searching
if central.state == CBCentralManagerState.PoweredOn {
central.scanForPeripheralsWithServices(nil, options: nil)
}
}
func centralManager(central: CBCentralManager, didDiscoverPeripheral peripheral: CBPeripheral, advertisementData: [String : AnyObject], RSSI: NSNumber) {
let discoveredDeviceName = peripheral.name
if ((discoveredDeviceName != nil) && !(self.discoveredDevices.contains(discoveredDeviceName!))) {
self.discoveredDevices += [discoveredDeviceName as String!]
self.peripherals += [peripheral];
NSNotificationCenter.defaultCenter().postNotificationName("discoveredPeriph", object: nil)
}
}
func centralManager(central: CBCentralManager, didConnectPeripheral peripheral: CBPeripheral) {
self.isConnected = true
print("Connected to ", peripheral.name);
peripheral.discoverServices(nil) // discover services
NSNotificationCenter.defaultCenter().postNotificationName("periphConnected", object: nil)
}
func centralManager(central: CBCentralManager, didFailToConnectPeripheral peripheral: CBPeripheral, error: NSError?) {
self.isConnected = false
print("Failed to connect to peripheral -> ", error?.description)
}
func centralManager(central: CBCentralManager, didDisconnectPeripheral peripheral: CBPeripheral, error: NSError?) {
// display and error
// then go back to first view controller
print("Peripheral disconnected, error -->", error)
/*
let navigationController = UIApplication.sharedApplication().keyWindow?.rootViewController as? UINavigationController
let storyBoard = UIStoryboard(name: "Main", bundle: nil)
let destinationViewController = storyBoard.instantiateViewControllerWithIdentifier("FirstViewController")
navigationController?.viewControllers[0].presentViewController(destinationViewController, animated: true, completion: nil)
*/
}
func peripheral(peripheral: CBPeripheral, didDiscoverServices error: NSError?) {
print("Discovered services for peripheral -> ", peripheral.name)
// go through services and find the one we want
// then discover the characteristics of that service
for service in peripheral.services! {
if service.UUID == SHAF_SERVICE_UUID {
self.service = service
peripheral.discoverCharacteristics(nil, forService: service)
}
}
}
func peripheral(peripheral: CBPeripheral, didDiscoverCharacteristicsForService service: CBService, error: NSError?) {
for characteristic in service.characteristics! {
// get notified every time any of the receiving characteristics change value
if characteristic.UUID == REC_REP_COUNT_CHARACTERISTIC_UUID || characteristic.UUID == REC_FATIGUE_CHARACTERISTIC_UUID || characteristic.UUID == REC_CALIB_ERR_CHARACTERISTIC_UUID || characteristic.UUID == REC_CALIB_DONE_CHARACTERISTIC_UUID || characteristic.UUID == REC_TIMEOUT_CHARACTERISTIC_UUID {
self.peripheralBLE?.setNotifyValue(true, forCharacteristic: characteristic)
}
}
// assign characteristics into a dictionary
self.assignCharacteristics()
}
func peripheral(peripheral: CBPeripheral, didWriteValueForCharacteristic characteristic: CBCharacteristic, error: NSError?) {
if (error != nil) {
print("Error writing a value --> ", error?.description.debugDescription)
}
else {
print("Successfully wrote value to", characteristic.UUID)
}
}
func peripheral(peripheral: CBPeripheral, didUpdateValueForCharacteristic characteristic: CBCharacteristic, error: NSError?) {
print("Characteristic --> ", characteristic.UUID.description, " Just updated value")
if characteristic.UUID == REC_REP_COUNT_CHARACTERISTIC_UUID {
let data = characteristic.value
let dataLength = data?.length
var repsArray = [UInt8](count: dataLength!, repeatedValue: 0)
data!.getBytes(&repsArray, length: dataLength! * sizeof(UInt8))
print("Rep Count: ", repsArray)
let repValue = Double(repsArray[1])
let repString = NSString(format: "%.0f", repValue)
NSNotificationCenter.defaultCenter().postNotificationName("repCountChanged", object: nil, userInfo: ["repCount": repString])
}
else if characteristic.UUID == REC_FATIGUE_CHARACTERISTIC_UUID {
print("Fatigue Reached")
NSNotificationCenter.defaultCenter().postNotificationName("fatigue", object: nil)
}
else if characteristic.UUID == REC_CALIB_DONE_CHARACTERISTIC_UUID {
let data = characteristic.value
let dataLength = data?.length
var repsArray = [UInt8](count: dataLength!, repeatedValue: 0)
data!.getBytes(&repsArray, length: dataLength! * sizeof(UInt8))
print("Calibration COmplete")
print("Value:", repsArray)
NSNotificationCenter.defaultCenter().postNotificationName("calibComplete", object: nil)
}
else if characteristic.UUID == REC_CALIB_ERR_CHARACTERISTIC_UUID {
print("Calibration Failed")
NSNotificationCenter.defaultCenter().postNotificationName("calibFailed", object: nil)
}
else if characteristic.UUID == REC_TIMEOUT_CHARACTERISTIC_UUID {
print("Time out")
NSNotificationCenter.defaultCenter().postNotificationName("repTimeOut", object: nil)
}
}
func showDisconnectAlert() {
}
}
| 9bdde524336768a1368222964d7b6fd3 | 40.130282 | 310 | 0.648917 | false | false | false | false |
charleshkang/Coffee-Mapper | refs/heads/master | Coffee Mapper/AppDelegate.swift | mit | 1 |
// AppDelegate.swift
// Coffee Mapper
//
// Created by Charles Kang on 4/13/16.
// Copyright © 2016 Charles Kang. All rights reserved.
//
import UIKit
import Firebase
import RealmSwift
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate
{
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool
{
if NSUserDefaults.standardUserDefaults().valueForKey("uid") == nil {
let loginVC = UIStoryboard(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier("loginIdentifier")
window?.rootViewController = loginVC
} else if NSUserDefaults.standardUserDefaults().valueForKey("uid") != nil && DataService.dataService.CURRENT_USER_REF.authData != nil {
let homeVC = UIStoryboard(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier("homeIdentifier")
let navigationController = UINavigationController(rootViewController: homeVC)
window?.rootViewController = navigationController
}
let config = Realm.Configuration(
schemaVersion: 3,
migrationBlock: { migration, oldSchemaVersion in
if (oldSchemaVersion < 1) {
}
})
Realm.Configuration.defaultConfiguration = config
_ = try! Realm()
return true
}
} | 1f13aca40725a9dbf78fe2357faf1e4c | 35.2 | 143 | 0.669661 | false | true | false | false |
JeeLiu/DKStickyHeaderView | refs/heads/master | DKStickyHeaderView/DKStickyHeaderView/DKStickyHeaderView.swift | mit | 1 | //
// DKStickyHeaderView.swift
// DKStickyHeaderView
//
// Created by Bannings on 15/5/4.
// Copyright (c) 2015年 ZhangAo. All rights reserved.
//
import UIKit
private let KEY_PATH_CONTENTOFFSET = "contentOffset"
class DKStickyHeaderView: UIView {
private var minHeight: CGFloat
init(minHeight: CGFloat) {
self.minHeight = minHeight
super.init(frame: CGRect(x: 0, y: 0, width: 0, height: minHeight))
self.clipsToBounds = true
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func willMoveToSuperview(newSuperview: UIView?) {
super.willMoveToSuperview(newSuperview)
self.superview?.removeObserver(self, forKeyPath: KEY_PATH_CONTENTOFFSET)
if newSuperview != nil {
assert(newSuperview!.self.isKindOfClass(UIScrollView.self), "superview must be UIScrollView!")
var newFrame = self.frame
newFrame.size.width = newSuperview!.bounds.size.width
self.frame = newFrame
self.autoresizingMask = .FlexibleWidth
newSuperview?.addObserver(self, forKeyPath: KEY_PATH_CONTENTOFFSET, options: .New, context: nil)
}
}
override func observeValueForKeyPath(keyPath: String, ofObject object: AnyObject, change: [NSObject : AnyObject], context: UnsafeMutablePointer<Void>) {
if keyPath == KEY_PATH_CONTENTOFFSET {
let scrollView = self.superview as! UIScrollView
var delta: CGFloat = 0.0
if scrollView.contentOffset.y < 0.0 {
delta = fabs(min(0.0, scrollView.contentOffset.y))
}
var newFrame = self.frame
newFrame.origin.y = -delta
newFrame.size.height = self.minHeight + delta
self.frame = newFrame
} else {
super.observeValueForKeyPath(keyPath, ofObject: object, change: change, context: context)
}
}
} | 7cf505a646977f6ee86a8774617f56a2 | 32.322581 | 156 | 0.615496 | false | false | false | false |
michals92/iOS_skautIS | refs/heads/master | skautIS/AddressBookShowVC.swift | bsd-3-clause | 1 | //
// AddressBookShowVC.swift
// skautIS
//
// Copyright (c) 2015, Michal Simik
// All rights reserved.
//
import UIKit
import SWXMLHash
class AddressBookShowVC: UITableViewController, UITextFieldDelegate{
var stringData = ""
var xml = SWXMLHash.parse("")
var idDetail:String = ""
override func viewDidLoad() {
super.viewDidLoad()
xml = SWXMLHash.parse(stringData)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewWillAppear(animated: Bool){
super.viewWillAppear(animated)
self.navigationController?.setToolbarHidden(true, animated: animated)
}
/**
Tableview methods
*/
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return xml["soap:Envelope"]["soap:Body"]["PersonAllCatalogResponse"]["PersonAllCatalogResult"]["PersonAllCatalogOutput"].all.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell: AddressBookShowCell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! AddressBookShowCell
cell.setCell(xml["soap:Envelope"]["soap:Body"]["PersonAllCatalogResponse"]["PersonAllCatalogResult"]["PersonAllCatalogOutput"][indexPath.row]["DisplayName"].element!.text! as String!)
cell.textLabel?.font = UIFont.systemFontOfSize(14)
return cell
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
idDetail = xml["soap:Envelope"]["soap:Body"]["PersonAllCatalogResponse"]["PersonAllCatalogResult"]["PersonAllCatalogOutput"][indexPath.row]["ID"].element!.text! as String!
dispatch_async(dispatch_get_main_queue()) {
self.performSegueWithIdentifier("detailVC", sender: self)
}
}
/**
Prepare for segue method.
*/
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {
if (segue.identifier == "detailVC"){
let vc = segue.destinationViewController as! PersonsByRoleDetail
vc.id = idDetail
}
}
}
| 6f16ac76f1787c8445218876cb3faa1e | 31.736111 | 191 | 0.669919 | false | false | false | false |
Jigsaw-Code/outline-client | refs/heads/master | src/cordova/plugin/apple/src/OutlineVpn.swift | apache-2.0 | 1 | // Copyright 2018 The Outline Authors
//
// 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 CocoaLumberjack
import CocoaLumberjackSwift
import NetworkExtension
// Manages the system's VPN tunnel through the VpnExtension process.
@objcMembers
class OutlineVpn: NSObject {
static let shared = OutlineVpn()
private static let kVpnExtensionBundleId = "\(Bundle.main.bundleIdentifier!).VpnExtension"
typealias Callback = (ErrorCode) -> Void
typealias VpnStatusObserver = (NEVPNStatus, String) -> Void
public private(set) var activeTunnelId: String?
private var tunnelManager: NETunnelProviderManager?
private var vpnStatusObserver: VpnStatusObserver?
private let connectivity: OutlineConnectivity
private enum Action {
static let start = "start"
static let restart = "restart"
static let stop = "stop"
static let getTunnelId = "getTunnelId"
static let isServerReachable = "isServerReachable"
}
private enum MessageKey {
static let action = "action"
static let tunnelId = "tunnelId"
static let config = "config"
static let errorCode = "errorCode"
static let host = "host"
static let port = "port"
static let isOnDemand = "is-on-demand"
}
// This must be kept in sync with:
// - cordova-plugin-outline/apple/vpn/PacketTunnelProvider.h#NS_ENUM
// - www/model/errors.ts
@objc
public enum ErrorCode: Int {
case noError = 0
case undefined = 1
case vpnPermissionNotGranted = 2
case invalidServerCredentials = 3
case udpRelayNotEnabled = 4
case serverUnreachable = 5
case vpnStartFailure = 6
case illegalServerConfiguration = 7
case shadowsocksStartFailure = 8
case configureSystemProxyFailure = 9
case noAdminPermissions = 10
case unsupportedRoutingTable = 11
case systemMisconfigured = 12
}
override private init() {
connectivity = OutlineConnectivity()
super.init()
getTunnelManager() { manager in
guard manager != nil else {
return DDLogInfo("Tunnel manager not active. VPN not configured.")
}
self.tunnelManager = manager!
self.observeVpnStatusChange(self.tunnelManager!)
if self.isVpnConnected() {
self.retrieveActiveTunnelId()
}
}
}
// MARK: Interface
// Starts a VPN tunnel as specified in the OutlineTunnel object.
func start(_ tunnel: OutlineTunnel, _ completion: @escaping (Callback)) {
guard let tunnelId = tunnel.id else {
DDLogError("Missing tunnel ID")
return completion(ErrorCode.illegalServerConfiguration)
}
if isActive(tunnelId) {
return completion(ErrorCode.noError)
} else if isVpnConnected() {
return restartVpn(tunnelId, config: tunnel.config, completion: completion)
}
self.startVpn(tunnel, isAutoConnect: false, completion)
}
// Starts the last successful VPN tunnel.
func startLastSuccessfulTunnel(_ completion: @escaping (Callback)) {
// Explicitly pass an empty tunnel's configuration, so the VpnExtension process retrieves
// the last configuration from disk.
self.startVpn(OutlineTunnel(), isAutoConnect: true, completion)
}
// Tears down the VPN if the tunnel with id |tunnelId| is active.
func stop(_ tunnelId: String) {
if !isActive(tunnelId) {
return DDLogWarn("Cannot stop VPN, tunnel ID \(tunnelId)")
}
stopVpn()
}
// Determines whether a server is reachable via TCP.
func isServerReachable(host: String, port: UInt16, _ completion: @escaping Callback) {
if isVpnConnected() {
// All the device's traffic, including the Outline app, go through the VpnExtension process.
// Performing a reachability test, opening a TCP socket to a host/port, will succeed
// unconditionally as the request will not leave the device. Send a message to the
// VpnExtension process to perform the reachability test.
let message = [MessageKey.action: Action.isServerReachable, MessageKey.host: host,
MessageKey.port: port] as [String : Any]
sendVpnExtensionMessage(message) { response in
guard response != nil else {
return completion(ErrorCode.serverUnreachable)
}
let rawCode = response?[MessageKey.errorCode] as? Int ?? ErrorCode.serverUnreachable.rawValue
completion(ErrorCode(rawValue: rawCode) ?? ErrorCode.serverUnreachable)
}
} else {
connectivity.isServerReachable(host: host, port: port) { isReachable in
completion(isReachable ? ErrorCode.noError : ErrorCode.serverUnreachable)
}
}
}
// Calls |observer| when the VPN's status changes.
func onVpnStatusChange(_ observer: @escaping(VpnStatusObserver)) {
vpnStatusObserver = observer
}
// Returns whether |tunnelId| is actively proxying through the VPN.
func isActive(_ tunnelId: String?) -> Bool {
if self.activeTunnelId == nil {
return false
}
return self.activeTunnelId == tunnelId && isVpnConnected()
}
// MARK: Helpers
private func startVpn(
_ tunnel: OutlineTunnel, isAutoConnect: Bool, _ completion: @escaping(Callback)) {
let tunnelId = tunnel.id
setupVpn() { error in
if error != nil {
DDLogError("Failed to setup VPN: \(String(describing: error))")
return completion(ErrorCode.vpnPermissionNotGranted);
}
let message = [MessageKey.action: Action.start, MessageKey.tunnelId: tunnelId ?? ""];
self.sendVpnExtensionMessage(message) { response in
self.onStartVpnExtensionMessage(response, completion: completion)
}
var config: [String: String]? = nil
if !isAutoConnect {
config = tunnel.config
config?[MessageKey.tunnelId] = tunnelId
} else {
// macOS app was started by launcher.
config = [MessageKey.isOnDemand: "true"];
}
let session = self.tunnelManager?.connection as! NETunnelProviderSession
do {
try session.startTunnel(options: config)
} catch let error as NSError {
DDLogError("Failed to start VPN: \(error)")
completion(ErrorCode.vpnStartFailure)
}
}
}
private func stopVpn() {
let session: NETunnelProviderSession = tunnelManager?.connection as! NETunnelProviderSession
session.stopTunnel()
setConnectVpnOnDemand(false) // Disable on demand so the VPN does not connect automatically.
self.activeTunnelId = nil
}
// Sends message to extension to restart the tunnel without tearing down the VPN.
private func restartVpn(_ tunnelId: String, config: [String: String],
completion: @escaping(Callback)) {
if activeTunnelId != nil {
vpnStatusObserver?(.disconnected, activeTunnelId!)
}
let message = [MessageKey.action: Action.restart, MessageKey.tunnelId: tunnelId,
MessageKey.config:config] as [String : Any]
self.sendVpnExtensionMessage(message) { response in
self.onStartVpnExtensionMessage(response, completion: completion)
}
}
// Adds a VPN configuration to the user preferences if no Outline profile is present. Otherwise
// enables the existing configuration.
private func setupVpn(completion: @escaping(Error?) -> Void) {
NETunnelProviderManager.loadAllFromPreferences() { (managers, error) in
if let error = error {
DDLogError("Failed to load VPN configuration: \(error)")
return completion(error)
}
var manager: NETunnelProviderManager!
if let managers = managers, managers.count > 0 {
manager = managers.first
let hasOnDemandRules = !(manager.onDemandRules?.isEmpty ?? true)
if manager.isEnabled && hasOnDemandRules {
self.tunnelManager = manager
return completion(nil)
}
} else {
let config = NETunnelProviderProtocol()
config.providerBundleIdentifier = OutlineVpn.kVpnExtensionBundleId
config.serverAddress = "Outline"
manager = NETunnelProviderManager()
manager.protocolConfiguration = config
}
// Set an on-demand rule to connect to any available network to implement auto-connect on boot
let connectRule = NEOnDemandRuleConnect()
connectRule.interfaceTypeMatch = .any
manager.onDemandRules = [connectRule]
manager.isEnabled = true
manager.saveToPreferences() { error in
if let error = error {
DDLogError("Failed to save VPN configuration: \(error)")
return completion(error)
}
self.observeVpnStatusChange(manager!)
self.tunnelManager = manager
NotificationCenter.default.post(name: .NEVPNConfigurationChange, object: nil)
// Workaround for https://forums.developer.apple.com/thread/25928
self.tunnelManager?.loadFromPreferences() { error in
completion(error)
}
}
}
}
private func setConnectVpnOnDemand(_ enabled: Bool) {
self.tunnelManager?.isOnDemandEnabled = enabled
self.tunnelManager?.saveToPreferences { error in
if let error = error {
return DDLogError("Failed to set VPN on demand to \(enabled): \(error)")
}
}
}
// Retrieves the application's tunnel provider manager from the VPN preferences.
private func getTunnelManager(_ completion: @escaping ((NETunnelProviderManager?) -> Void)) {
NETunnelProviderManager.loadAllFromPreferences() { (managers, error) in
guard error == nil, managers != nil else {
completion(nil)
return DDLogError("Failed to get tunnel manager: \(String(describing: error))")
}
var manager: NETunnelProviderManager?
if managers!.count > 0 {
manager = managers!.first
}
completion(manager)
}
}
// Retrieves the active tunnel ID from the VPN extension.
private func retrieveActiveTunnelId() {
if tunnelManager == nil {
return
}
self.sendVpnExtensionMessage([MessageKey.action: Action.getTunnelId]) { response in
guard response != nil else {
return DDLogError("Failed to retrieve the active tunnel ID")
}
guard let activeTunnelId = response?[MessageKey.tunnelId] as? String else {
return DDLogError("Failed to retrieve the active tunnel ID")
}
DDLogInfo("Got active tunnel ID: \(activeTunnelId)")
self.activeTunnelId = activeTunnelId
self.vpnStatusObserver?(.connected, self.activeTunnelId!)
}
}
// Returns whether the VPN is connected or (re)connecting by querying |tunnelManager|.
private func isVpnConnected() -> Bool {
if tunnelManager == nil {
return false
}
let vpnStatus = tunnelManager?.connection.status
return vpnStatus == .connected || vpnStatus == .connecting || vpnStatus == .reasserting
}
// Listen for changes in the VPN status.
private func observeVpnStatusChange(_ manager: NETunnelProviderManager) {
// Remove self to guard against receiving duplicate notifications due to page reloads.
NotificationCenter.default.removeObserver(self, name: .NEVPNStatusDidChange,
object: manager.connection)
NotificationCenter.default.addObserver(self, selector: #selector(self.vpnStatusChanged),
name: .NEVPNStatusDidChange, object: manager.connection)
}
// Receives NEVPNStatusDidChange notifications. Calls onTunnelStatusChange for the active
// tunnel.
@objc func vpnStatusChanged() {
if let vpnStatus = tunnelManager?.connection.status {
if let tunnelId = activeTunnelId {
if (vpnStatus == .disconnected) {
activeTunnelId = nil
}
vpnStatusObserver?(vpnStatus, tunnelId)
} else if vpnStatus == .connected {
// The VPN was connected from the settings app while the UI was in the background.
// Retrieve the tunnel ID to update the UI.
retrieveActiveTunnelId()
}
}
}
// MARK: VPN extension IPC
/**
Sends a message to the VPN extension if the VPN has been setup. Sets a
callback to be invoked by the extension once the message has been processed.
*/
private func sendVpnExtensionMessage(_ message: [String: Any],
callback: @escaping (([String: Any]?) -> Void)) {
if tunnelManager == nil {
return DDLogError("Cannot set an extension callback without a tunnel manager")
}
var data: Data
do {
data = try JSONSerialization.data(withJSONObject: message, options: [])
} catch {
return DDLogError("Failed to serialize message to VpnExtension as JSON")
}
let completionHandler: (Data?) -> Void = { data in
guard let responseData = data else {
return callback(nil)
}
do {
if let response = try JSONSerialization.jsonObject(with: responseData,
options: []) as? [String: Any] {
DDLogInfo("Received extension message: \(String(describing: response))")
return callback(response)
}
} catch {
DDLogError("Failed to deserialize the VpnExtension response")
}
callback(nil)
}
let session: NETunnelProviderSession = tunnelManager?.connection as! NETunnelProviderSession
do {
try session.sendProviderMessage(data, responseHandler: completionHandler)
} catch {
DDLogError("Failed to send message to VpnExtension")
}
}
func onStartVpnExtensionMessage(_ message: [String:Any]?, completion: Callback) {
guard let response = message else {
return completion(ErrorCode.vpnStartFailure)
}
let rawErrorCode = response[MessageKey.errorCode] as? Int ?? ErrorCode.undefined.rawValue
if rawErrorCode == ErrorCode.noError.rawValue,
let tunnelId = response[MessageKey.tunnelId] as? String {
self.activeTunnelId = tunnelId
// Enable on demand to connect automatically on boot if the VPN was connected on shutdown
self.setConnectVpnOnDemand(true)
}
completion(ErrorCode(rawValue: rawErrorCode) ?? ErrorCode.noError)
}
}
| d474071e217b678262c9af578b0a9e9a | 37.157068 | 101 | 0.680159 | false | true | false | false |
JGiola/swift | refs/heads/main | benchmark/single-source/RemoveWhere.swift | apache-2.0 | 10 | //===--- RemoveWhere.swift ------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import TestsUtils
public let benchmarks = [
// tests repeated remove(at:) calls in generic code
BenchmarkInfo(name: "RemoveWhereQuadraticStrings", runFunction: run_RemoveWhereQuadraticStrings, tags: [.validation, .api], setUpFunction: buildWorkload),
BenchmarkInfo(name: "RemoveWhereQuadraticInts", runFunction: run_RemoveWhereQuadraticInts, tags: [.validation, .api], setUpFunction: buildWorkload),
// tests performance of RangeReplaceableCollection.filter
BenchmarkInfo(name: "RemoveWhereFilterStrings", runFunction: run_RemoveWhereFilterStrings, tags: [.validation, .api], setUpFunction: buildWorkload),
BenchmarkInfo(name: "RemoveWhereFilterInts", runFunction: run_RemoveWhereFilterInts, tags: [.validation, .api], setUpFunction: buildWorkload),
// these two variants test the impact of reference counting and
// swapping/moving
BenchmarkInfo(name: "RemoveWhereMoveStrings", runFunction: run_RemoveWhereMoveStrings, tags: [.validation, .api], setUpFunction: buildWorkload),
BenchmarkInfo(name: "RemoveWhereMoveInts", runFunction: run_RemoveWhereMoveInts, tags: [.validation, .api], setUpFunction: buildWorkload),
BenchmarkInfo(name: "RemoveWhereSwapStrings", runFunction: run_RemoveWhereSwapStrings, tags: [.validation, .api], setUpFunction: buildWorkload),
BenchmarkInfo(name: "RemoveWhereSwapInts", runFunction: run_RemoveWhereSwapInts, tags: [.validation, .api], setUpFunction: buildWorkload),
// these test performance of filter, character iteration/comparison
BenchmarkInfo(name: "RemoveWhereFilterString", runFunction: run_RemoveWhereFilterString, tags: [.validation, .api], setUpFunction: buildWorkload),
BenchmarkInfo(name: "RemoveWhereQuadraticString", runFunction: run_RemoveWhereQuadraticString, tags: [.validation, .api], setUpFunction: buildWorkload),
]
extension RangeReplaceableCollection {
mutating func removeWhere_quadratic(where match: (Element) throws -> Bool) rethrows {
for i in indices.reversed() {
if try match(self[i]) {
remove(at: i)
}
}
}
mutating func removeWhere_filter(where match: (Element) throws -> Bool) rethrows {
try self = self.filter { try !match($0) }
}
}
extension RangeReplaceableCollection where Self: MutableCollection {
mutating func removeWhere_move(where match: (Element) throws -> Bool) rethrows {
guard var i = try firstIndex(where: match) else { return }
var j = index(after: i)
while j != endIndex {
let element = self[j]
if try !match(element) {
self[i] = element
formIndex(after: &i)
}
formIndex(after: &j)
}
removeSubrange(i...)
}
mutating func removeWhere_swap(where match: (Element) throws -> Bool) rethrows {
guard var i = try firstIndex(where: match) else { return }
var j = index(after: i)
while j != endIndex {
if try !match(self[i]) {
self.swapAt(i,j)
formIndex(after: &i)
}
formIndex(after: &j)
}
removeSubrange(i...)
}
}
func testQuadratic<C: RangeReplaceableCollection>(workload: inout C) {
var i = 0
workload.removeWhere_quadratic { _ in
i = i &+ 1
return i%8 == 0
}
}
func testFilter<C: RangeReplaceableCollection>(workload: inout C) {
var i = 0
workload.removeWhere_filter { _ in
i = i &+ 1
return i%8 == 0
}
}
func testMove<C: RangeReplaceableCollection & MutableCollection>(workload: inout C) {
var i = 0
workload.removeWhere_move { _ in
i = i &+ 1
return i%8 == 0
}
}
func testSwap<C: RangeReplaceableCollection & MutableCollection>(workload: inout C) {
var i = 0
workload.removeWhere_swap { _ in
i = i &+ 1
return i%8 == 0
}
}
let n = 10_000
let strings = (0..<n).map({ "\($0): A long enough string to defeat the SSO" })
let ints = Array(0..<n)
let str = String(repeating: "A very long ASCII string.", count: n/50)
func buildWorkload() {
blackHole(strings)
blackHole(ints)
blackHole(str)
}
@inline(never)
func run_RemoveWhereQuadraticStrings(_ scale: Int) {
for _ in 0..<scale {
var workload = strings; workload.swapAt(0,1)
testQuadratic(workload: &workload)
}
}
@inline(never)
func run_RemoveWhereQuadraticInts(_ scale: Int) {
for _ in 0..<scale {
var workload = ints; workload.swapAt(0,1)
testQuadratic(workload: &workload)
}
}
@inline(never)
func run_RemoveWhereFilterStrings(_ scale: Int) {
for _ in 0..<scale {
var workload = strings; workload.swapAt(0,1)
testFilter(workload: &workload)
}
}
@inline(never)
func run_RemoveWhereFilterInts(_ scale: Int) {
for _ in 0..<scale {
var workload = ints; workload.swapAt(0,1)
testFilter(workload: &workload)
}
}
@inline(never)
func run_RemoveWhereMoveStrings(_ scale: Int) {
for _ in 0..<scale {
var workload = strings; workload.swapAt(0,1)
testMove(workload: &workload)
}
}
@inline(never)
func run_RemoveWhereMoveInts(_ scale: Int) {
for _ in 0..<scale {
var workload = ints; workload.swapAt(0,1)
testMove(workload: &workload)
}
}
@inline(never)
func run_RemoveWhereSwapStrings(_ scale: Int) {
for _ in 0..<scale {
var workload = strings; workload.swapAt(0,1)
testSwap(workload: &workload)
}
}
@inline(never)
func run_RemoveWhereSwapInts(_ scale: Int) {
for _ in 0..<scale {
var workload = ints; workload.swapAt(0,1)
testSwap(workload: &workload)
}
}
@inline(never)
func run_RemoveWhereFilterString(_ scale: Int) {
for _ in 0..<scale {
var workload = str
workload.append("!")
testFilter(workload: &workload)
}
}
@inline(never)
func run_RemoveWhereQuadraticString(_ scale: Int) {
for _ in 0..<scale {
var workload = str
workload.append("!")
testQuadratic(workload: &workload)
}
}
| 2d3526b0abb72fd38c38de3b3c26e1be | 29.395122 | 156 | 0.678061 | false | true | false | false |
asp2insp/Twittercism | refs/heads/master | Twittercism/StreamStore.swift | mit | 1 | //
// StreamStore.swift
// Twittercism
//
// Created by Josiah Gaskin on 5/18/15.
// Copyright (c) 2015 Josiah Gaskin. All rights reserved.
//
import Foundation
class StreamStore : Store {
override func initialize() {
self.on("setTweets", handler: { (state, new, action) -> Immutable.State in
return Immutable.toState(new as! AnyObject)
})
self.on("toggleFavoriteTweet", handler: {(state, tweetId, action) -> Immutable.State in
return state.map({(one, key) -> Immutable.State in
if one.getIn(["id_str"]).toSwift() as! String == tweetId as! String {
let currentlyFavorited = one.getIn(["favorited"]).toSwift() as! Bool
let currentFavoriteCount = one.getIn(["favorite_count"]).toSwift() as! Int
let diff = currentlyFavorited ? -1 : 1
if currentlyFavorited {
TwitterApi.unfavoriteTweet(tweetId as! String)
} else {
TwitterApi.favoriteTweet(tweetId as! String)
}
return one.setIn(["favorited"], withValue: Immutable.toState(!currentlyFavorited)).setIn(["favorite_count"], withValue: Immutable.toState(currentFavoriteCount + diff))
} else {
return one
}
})
})
self.on("retweet", handler: {(state, tweetId, action) -> Immutable.State in
return state.map({(one, key) -> Immutable.State in
if one.getIn(["id_str"]).toSwift() as! String == tweetId as! String {
let currentlyRetweeted = one.getIn(["retweeted"]).toSwift() as! Bool
if !currentlyRetweeted {
TwitterApi.retweet(tweetId as! String)
let newCount = one.getIn(["retweet_count"]).toSwift() as! Int + 1
return one.setIn(["retweeted"], withValue: Immutable.toState(true)).setIn(["retweet_count"], withValue: Immutable.toState(newCount))
}
}
return one
})
})
}
override func getInitialState() -> Immutable.State {
return Immutable.toState([])
}
} | b57244f1dd1c4c082d44d4d4c4c0d56a | 43.096154 | 187 | 0.536649 | false | false | false | false |
hanjoes/Smashtag | refs/heads/master | RecentsTableViewController.swift | mit | 1 | //
// RecentsTableViewController.swift
// Smashtag
//
// Created by Hanzhou Shi on 1/14/16.
// Copyright © 2016 USF. All rights reserved.
//
import UIKit
class RecentsTableViewController: UITableViewController {
var recents = Recents()
override func viewWillAppear(animated: Bool) {
self.tableView.reloadData()
}
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return recents.allHistory.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(Constants.CellReuseIdentifier, forIndexPath: indexPath)
cell.textLabel?.text = recents.allHistory[indexPath.row]
return cell
}
override func tableView(tableView: UITableView, editingStyleForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCellEditingStyle {
return UITableViewCellEditingStyle.Delete
}
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == UITableViewCellEditingStyle.Delete {
recents.removeAtIndex(indexPath.row)
tableView.reloadData()
}
}
/*
// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
// Delete the row from the data source
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
let destination = segue.destinationViewController
if segue.identifier == Constants.ShowHistorySegue {
if let cell = sender as? UITableViewCell {
if let ttvc = destination as? TweetTableViewController {
ttvc.searchText = cell.textLabel?.text
}
}
}
// Pass the selected object to the new view controller.
}
// MARK: - Private
private struct Constants {
static let CellReuseIdentifier = "Recent"
static let ShowHistorySegue = "ShowHistoryData"
}
}
| 7668a87da3161cc9ddbfade5d8dd5801 | 35.491379 | 157 | 0.68533 | false | false | false | false |
legendecas/Rocket.Chat.iOS | refs/heads/sdk | Rocket.Chat.SDK/Managers/LivechatManager.swift | mit | 1 | //
// LivechatManager.swift
// Rocket.Chat
//
// Created by Lucas Woo on 5/18/17.
// Copyright © 2017 Rocket.Chat. All rights reserved.
//
import Foundation
import RealmSwift
/// A manager that manages all livechat related actions
public class LivechatManager: SocketManagerInjected, AuthManagerInjected, SubscriptionManagerInjected {
public var initiated = false
public var loggedIn = false
var visitorToken = ""
var userId = ""
var token = ""
public var title = ""
public var enabled = false
/// If is there any agents online
public var online = false
/// The
public var room = String.random()
/// If a form is required for registration
public var registrationForm = false
/// If a form should be displayed while no agents are online
public var displayOfflineForm = false
public var offlineTitle = "Offline Support"
public var offlineMessage = ""
public var offlineUnavailableMessage = ""
public var offlineSuccessMessage = ""
/// All available deparments can be talked to
public var departments: [Department] = []
/// Initiate livechat settings and retrieve settings from remote server
///
/// - Parameter completion: completion callback
public func initiate(completion: @escaping () -> Void) {
visitorToken = String.random()
let params = [
"msg": "method",
"method": "livechat:getInitialData",
"params": [visitorToken]
] as [String : Any]
socketManager.send(params) { response in
let json = response.result["result"]
self.title = json["title"].stringValue
self.enabled = json["enabled"].boolValue
self.online = json["online"].boolValue
self.registrationForm = json["registrationForm"].boolValue
self.displayOfflineForm = json["displayOfflineForm"].boolValue
self.offlineTitle = json["offlineTitle"].stringValue
self.offlineMessage = json["offlineMessage"].stringValue
self.offlineUnavailableMessage = json["offlineUnavailableMessage"].stringValue
self.offlineSuccessMessage = json["offlineSuccessMessage"].stringValue
if let rid = json["room"].string {
self.room = rid
}
self.departments = json["departments"].map { (_, json) in
return Department(withJSON: json)
}
self.initiated = true
DispatchQueue.main.async(execute: completion)
}
}
/// Register a new guest with given email and name to given department, `LivechatManager` should be initiated first
///
/// - Parameters:
/// - email: guest's email
/// - name: guest's name
/// - department: target department
/// - messageText: initial text
/// - completion: completion callback
public func registerGuestAndLogin(withEmail email: String, name: String, toDepartment department: Department, message messageText: String, completion: @escaping () -> Void) {
guard self.initiated else {
fatalError("LiveChatManager methods called before properly initiated.")
}
let params = [
"msg": "method",
"method": "livechat:registerGuest",
"params": [[
"token": visitorToken,
"name": name,
"email": email,
"department": department.id
]]
] as [String : Any]
socketManager.send(params) { response in
let json = response.result["result"]
self.userId = json["userId"].stringValue
self.token = json["token"].stringValue
self.login {
let roomSubscription = Subscription()
roomSubscription.identifier = UUID().uuidString
roomSubscription.rid = self.room
roomSubscription.name = department.name
roomSubscription.type = .livechat
let message = Message()
message.internalType = ""
message.createdAt = Date()
message.text = messageText
message.identifier = UUID().uuidString
message.subscription = roomSubscription
message.temporary = true
message.user = self.authManager.currentUser()
let realm = try? Realm()
try? realm?.write {
realm?.add(roomSubscription)
realm?.add(message)
}
self.subscriptionManager.sendTextMessage(message) { _ in
DispatchQueue.main.async(execute: completion)
}
}
}
}
/// Login with previous registered user
///
/// - Parameter completion: completion callback
public func login(completion: @escaping () -> Void) {
guard self.initiated else {
fatalError("LiveChatManager methods called before properly initiated.")
}
let params = ["resume": token] as [String : Any]
authManager.auth(params: params) { _ in
self.loggedIn = true
DispatchQueue.main.async(execute: completion)
}
}
public func presentSupportViewController() {
let storyboard = UIStoryboard(name: "Support", bundle: Bundle.rocketChat)
if online {
guard let navigationViewController = storyboard.instantiateInitialViewController() as? UINavigationController else {
fatalError("Unexpected view hierachy: initial view controller is not a navigation controller")
}
guard navigationViewController.viewControllers.first is SupportViewController else {
fatalError("Unexpected view hierachy: navigation controller's root view controller is not support view controller")
}
navigationViewController.modalPresentationStyle = .formSheet
DispatchQueue.main.async {
UIApplication.shared.delegate?.window??.rootViewController?.present(navigationViewController, animated: true, completion: nil)
}
} else {
guard let navigationViewController = storyboard.instantiateViewController(withIdentifier: "offlineSupport") as? UINavigationController else {
fatalError("Unexpected view hierachy: `offlineSupport` is not a navigation controller")
}
guard navigationViewController.viewControllers.first is OfflineFormViewController else {
fatalError("Unexpected view hierachy: navigation controller's root view controller is not offline form view controller")
}
navigationViewController.modalPresentationStyle = .formSheet
DispatchQueue.main.async {
UIApplication.shared.delegate?.window??.rootViewController?.present(navigationViewController, animated: true, completion: nil)
}
}
}
/// After user is registrated or logged in, get the actual `ChatViewController` to start conversation
///
/// - Returns: a `ChatViewController` initiated with livechat settings
public func getLiveChatViewController() -> ChatViewController? {
guard self.loggedIn else {
fatalError("LiveChatManager methods called before properly logged in.")
}
let storyboard = UIStoryboard(name: "Chatting", bundle: Bundle.rocketChat)
let chatViewController = storyboard.instantiateViewController(withIdentifier: "ChatViewController") as? ChatViewController
guard let realm = try? Realm() else { return nil }
guard let subscription = Subscription.find(rid: room, realm: realm) else { return nil }
chatViewController?.subscription = subscription
chatViewController?.leftButton.setImage(nil, for: .normal)
chatViewController?.messageCellStyle = .bubble
return chatViewController
}
func sendOfflineMessage(email: String, name: String, message: String, completion: @escaping () -> Void) {
let params = [
"msg": "method",
"method": "livechat:sendOfflineMessage",
"params": [[
"name": name,
"email": email,
"message": message
]]
] as [String : Any]
socketManager.send(params) { _ in
DispatchQueue.main.async {
completion()
}
}
}
}
| c54e439dca8185d8cb29d18eeebb0233 | 39.614286 | 178 | 0.617071 | false | false | false | false |
ken0nek/swift | refs/heads/master | stdlib/public/core/Mirror.swift | apache-2.0 | 1 | //===--- Mirror.swift -----------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
// FIXME: ExistentialCollection needs to be supported before this will work
// without the ObjC Runtime.
/// Representation of the sub-structure and optional "display style"
/// of any arbitrary subject instance.
///
/// Describes the parts---such as stored properties, collection
/// elements, tuple elements, or the active enumeration case---that
/// make up a particular instance. May also supply a "display style"
/// property that suggests how this structure might be rendered.
///
/// Mirrors are used by playgrounds and the debugger.
public struct Mirror {
/// Representation of descendant classes that don't override
/// `customMirror`.
///
/// Note that the effect of this setting goes no deeper than the
/// nearest descendant class that overrides `customMirror`, which
/// in turn can determine representation of *its* descendants.
internal enum _DefaultDescendantRepresentation {
/// Generate a default mirror for descendant classes that don't
/// override `customMirror`.
///
/// This case is the default.
case generated
/// Suppress the representation of descendant classes that don't
/// override `customMirror`.
///
/// This option may be useful at the root of a class cluster, where
/// implementation details of descendants should generally not be
/// visible to clients.
case suppressed
}
/// Representation of ancestor classes.
///
/// A `CustomReflectable` class can control how its mirror will
/// represent ancestor classes by initializing the mirror with a
/// `AncestorRepresentation`. This setting has no effect on mirrors
/// reflecting value type instances.
public enum AncestorRepresentation {
/// Generate a default mirror for all ancestor classes.
///
/// This case is the default.
///
/// - Note: This option generates default mirrors even for
/// ancestor classes that may implement `CustomReflectable`'s
/// `customMirror` requirement. To avoid dropping an ancestor class
/// customization, an override of `customMirror` should pass
/// `ancestorRepresentation: .Customized(super.customMirror)` when
/// initializing its `Mirror`.
case generated
/// Use the nearest ancestor's implementation of `customMirror` to
/// create a mirror for that ancestor. Other classes derived from
/// such an ancestor are given a default mirror.
///
/// The payload for this option should always be
/// "`{ super.customMirror }`":
///
/// var customMirror: Mirror {
/// return Mirror(
/// self,
/// children: ["someProperty": self.someProperty],
/// ancestorRepresentation: .Customized({ super.customMirror })) // <==
/// }
case customized(() -> Mirror)
/// Suppress the representation of all ancestor classes. The
/// resulting `Mirror`'s `superclassMirror` is `nil`.
case suppressed
}
/// Reflect upon the given `subject`.
///
/// If the dynamic type of `subject` conforms to `CustomReflectable`,
/// the resulting mirror is determined by its `customMirror` property.
/// Otherwise, the result is generated by the language.
///
/// - Note: If the dynamic type of `subject` has value semantics,
/// subsequent mutations of `subject` will not observable in
/// `Mirror`. In general, though, the observability of such
/// mutations is unspecified.
public init(reflecting subject: Any) {
if case let customized as CustomReflectable = subject {
self = customized.customMirror
} else {
self = Mirror(
legacy: _reflect(subject),
subjectType: subject.dynamicType)
}
}
/// An element of the reflected instance's structure. The optional
/// `label` may be used when appropriate, e.g. to represent the name
/// of a stored property or of an active `enum` case, and will be
/// used for lookup when `String`s are passed to the `descendant`
/// method.
public typealias Child = (label: String?, value: Any)
/// The type used to represent sub-structure.
///
/// Depending on your needs, you may find it useful to "upgrade"
/// instances of this type to `AnyBidirectionalCollection` or
/// `AnyRandomAccessCollection`. For example, to display the last
/// 20 children of a mirror if they can be accessed efficiently, you
/// might write:
///
/// if let b = AnyBidirectionalCollection(someMirror.children) {
/// var i = xs.index(b.endIndex, offsetBy: -20,
/// limitedBy: b.startIndex) ?? b.startIndex
/// while i != xs.endIndex {
/// print(b[i])
/// b.formIndex(after: &i)
/// }
/// }
public typealias Children = AnyCollection<Child>
/// A suggestion of how a `Mirror`'s is to be interpreted.
///
/// Playgrounds and the debugger will show a representation similar
/// to the one used for instances of the kind indicated by the
/// `DisplayStyle` case name when the `Mirror` is used for display.
public enum DisplayStyle {
case `struct`, `class`, `enum`, tuple, optional, collection
case dictionary, `set`
}
static func _noSuperclassMirror() -> Mirror? { return nil }
/// Returns the legacy mirror representing the part of `subject`
/// corresponding to the superclass of `staticSubclass`.
internal static func _legacyMirror(
_ subject: AnyObject, asClass targetSuperclass: AnyClass) -> _Mirror? {
// get a legacy mirror and the most-derived type
var cls: AnyClass = subject.dynamicType
var clsMirror = _reflect(subject)
// Walk up the chain of mirrors/classes until we find staticSubclass
while let superclass: AnyClass = _getSuperclass(cls) {
guard let superclassMirror = clsMirror._superMirror() else { break }
if superclass == targetSuperclass { return superclassMirror }
clsMirror = superclassMirror
cls = superclass
}
return nil
}
internal static func _superclassIterator<Subject : Any>(
_ subject: Subject, _ ancestorRepresentation: AncestorRepresentation
) -> () -> Mirror? {
if let subject = subject as? AnyObject,
let subjectClass = Subject.self as? AnyClass,
let superclass = _getSuperclass(subjectClass) {
switch ancestorRepresentation {
case .generated:
return {
self._legacyMirror(subject, asClass: superclass).map {
Mirror(legacy: $0, subjectType: superclass)
}
}
case .customized(let makeAncestor):
return {
Mirror(subject, subjectClass: superclass, ancestor: makeAncestor())
}
case .suppressed:
break
}
}
return Mirror._noSuperclassMirror
}
/// Represent `subject` with structure described by `children`,
/// using an optional `displayStyle`.
///
/// If `subject` is not a class instance, `ancestorRepresentation`
/// is ignored. Otherwise, `ancestorRepresentation` determines
/// whether ancestor classes will be represented and whether their
/// `customMirror` implementations will be used. By default, a
/// representation is automatically generated and any `customMirror`
/// implementation is bypassed. To prevent bypassing customized
/// ancestors, `customMirror` overrides should initialize the
/// `Mirror` with:
///
/// ancestorRepresentation: .customized({ super.customMirror })
///
/// - Note: The traversal protocol modeled by `children`'s indices
/// (`ForwardIndex`, `BidirectionalIndex`, or
/// `RandomAccessIndex`) is captured so that the resulting
/// `Mirror`'s `children` may be upgraded later. See the failable
/// initializers of `AnyBidirectionalCollection` and
/// `AnyRandomAccessCollection` for details.
public init<
Subject,
C : Collection
where
C.Iterator.Element == Child,
// FIXME(ABI)(compiler limitation): these constraints should be applied to
// associated types of Collection.
C.SubSequence : Collection,
C.SubSequence.Iterator.Element == Child,
C.SubSequence.Index == C.Index,
C.SubSequence.Indices : Collection,
C.SubSequence.Indices.Iterator.Element == C.Index,
C.SubSequence.Indices.Index == C.Index,
C.SubSequence.Indices.SubSequence == C.SubSequence.Indices,
C.SubSequence.SubSequence == C.SubSequence,
C.Indices : Collection,
C.Indices.Iterator.Element == C.Index,
C.Indices.Index == C.Index,
C.Indices.SubSequence == C.Indices
>(
_ subject: Subject,
children: C,
displayStyle: DisplayStyle? = nil,
ancestorRepresentation: AncestorRepresentation = .generated
) {
self.subjectType = Subject.self
self._makeSuperclassMirror = Mirror._superclassIterator(
subject, ancestorRepresentation)
self.children = Children(children)
self.displayStyle = displayStyle
self._defaultDescendantRepresentation
= subject is CustomLeafReflectable ? .suppressed : .generated
}
/// Represent `subject` with child values given by
/// `unlabeledChildren`, using an optional `displayStyle`. The
/// result's child labels will all be `nil`.
///
/// This initializer is especially useful for the mirrors of
/// collections, e.g.:
///
/// extension MyArray : CustomReflectable {
/// var customMirror: Mirror {
/// return Mirror(self, unlabeledChildren: self, displayStyle: .collection)
/// }
/// }
///
/// If `subject` is not a class instance, `ancestorRepresentation`
/// is ignored. Otherwise, `ancestorRepresentation` determines
/// whether ancestor classes will be represented and whether their
/// `customMirror` implementations will be used. By default, a
/// representation is automatically generated and any `customMirror`
/// implementation is bypassed. To prevent bypassing customized
/// ancestors, `customMirror` overrides should initialize the
/// `Mirror` with:
///
/// ancestorRepresentation: .Customized({ super.customMirror })
///
/// - Note: The traversal protocol modeled by `children`'s indices
/// (`ForwardIndex`, `BidirectionalIndex`, or
/// `RandomAccessIndex`) is captured so that the resulting
/// `Mirror`'s `children` may be upgraded later. See the failable
/// initializers of `AnyBidirectionalCollection` and
/// `AnyRandomAccessCollection` for details.
public init<
Subject,
C : Collection
where
// FIXME(ABI)(compiler limitation): these constraints should be applied to
// associated types of Collection.
C.SubSequence : Collection,
C.SubSequence.SubSequence == C.SubSequence,
C.Indices : Collection,
C.Indices.Iterator.Element == C.Index,
C.Indices.Index == C.Index,
C.Indices.SubSequence == C.Indices
>(
_ subject: Subject,
unlabeledChildren: C,
displayStyle: DisplayStyle? = nil,
ancestorRepresentation: AncestorRepresentation = .generated
) {
self.subjectType = Subject.self
self._makeSuperclassMirror = Mirror._superclassIterator(
subject, ancestorRepresentation)
self.children = Children(
unlabeledChildren.lazy.map { Child(label: nil, value: $0) }
)
self.displayStyle = displayStyle
self._defaultDescendantRepresentation
= subject is CustomLeafReflectable ? .suppressed : .generated
}
/// Represent `subject` with labeled structure described by
/// `children`, using an optional `displayStyle`.
///
/// Pass a dictionary literal with `String` keys as `children`. Be
/// aware that although an *actual* `Dictionary` is
/// arbitrarily-ordered, the ordering of the `Mirror`'s `children`
/// will exactly match that of the literal you pass.
///
/// If `subject` is not a class instance, `ancestorRepresentation`
/// is ignored. Otherwise, `ancestorRepresentation` determines
/// whether ancestor classes will be represented and whether their
/// `customMirror` implementations will be used. By default, a
/// representation is automatically generated and any `customMirror`
/// implementation is bypassed. To prevent bypassing customized
/// ancestors, `customMirror` overrides should initialize the
/// `Mirror` with:
///
/// ancestorRepresentation: .customized({ super.customMirror })
///
/// - Note: The resulting `Mirror`'s `children` may be upgraded to
/// `AnyRandomAccessCollection` later. See the failable
/// initializers of `AnyBidirectionalCollection` and
/// `AnyRandomAccessCollection` for details.
public init<Subject>(
_ subject: Subject,
children: DictionaryLiteral<String, Any>,
displayStyle: DisplayStyle? = nil,
ancestorRepresentation: AncestorRepresentation = .generated
) {
self.subjectType = Subject.self
self._makeSuperclassMirror = Mirror._superclassIterator(
subject, ancestorRepresentation)
let lazyChildren = children.lazy.map { Child(label: $0.0, value: $0.1) }
self.children = Children(lazyChildren)
self.displayStyle = displayStyle
self._defaultDescendantRepresentation
= subject is CustomLeafReflectable ? .suppressed : .generated
}
/// The static type of the subject being reflected.
///
/// This type may differ from the subject's dynamic type when `self`
/// is the `superclassMirror` of another mirror.
public let subjectType: Any.Type
/// A collection of `Child` elements describing the structure of the
/// reflected subject.
public let children: Children
/// Suggests a display style for the reflected subject.
public let displayStyle: DisplayStyle?
public var superclassMirror: Mirror? {
return _makeSuperclassMirror()
}
internal let _makeSuperclassMirror: () -> Mirror?
internal let _defaultDescendantRepresentation: _DefaultDescendantRepresentation
}
/// A type that explicitly supplies its own mirror.
///
/// You can create a mirror for any type using the `Mirror(reflect:)`
/// initializer, but if you are not satisfied with the mirror supplied for
/// your type by default, you can make it conform to `CustomReflectable` and
/// return a custom `Mirror` instance.
public protocol CustomReflectable {
/// The custom mirror for this instance.
///
/// If this type has value semantics, the mirror should be unaffected by
/// subsequent mutations of the instance.
var customMirror: Mirror { get }
}
/// A type that explicitly supplies its own mirror, but whose
/// descendant classes are not represented in the mirror unless they
/// also override `customMirror`.
public protocol CustomLeafReflectable : CustomReflectable {}
//===--- Addressing -------------------------------------------------------===//
/// A protocol for legitimate arguments to `Mirror`'s `descendant`
/// method.
///
/// Do not declare new conformances to this protocol; they will not
/// work as expected.
public protocol MirrorPath {}
extension IntMax : MirrorPath {}
extension Int : MirrorPath {}
extension String : MirrorPath {}
extension Mirror {
internal struct _Dummy : CustomReflectable {
var mirror: Mirror
var customMirror: Mirror { return mirror }
}
/// Return a specific descendant of the reflected subject, or `nil`
/// Returns a specific descendant of the reflected subject, or `nil`
/// if no such descendant exists.
///
/// A `String` argument selects the first `Child` with a matching label.
/// An integer argument *n* select the *n*th `Child`. For example:
///
/// var d = Mirror(reflecting: x).descendant(1, "two", 3)
///
/// is equivalent to:
///
/// var d = nil
/// let children = Mirror(reflecting: x).children
/// if let p0 = children.index(children.startIndex,
/// offsetBy: 1, limitedBy: children.endIndex) {
/// let grandChildren = Mirror(reflecting: children[p0].value).children
/// SeekTwo: for g in grandChildren {
/// if g.label == "two" {
/// let greatGrandChildren = Mirror(reflecting: g.value).children
/// if let p1 = greatGrandChildren.index(
/// greatGrandChildren.startIndex,
/// offsetBy: 3, limitedBy: greatGrandChildren.endIndex) {
/// d = greatGrandChildren[p1].value
/// }
/// break SeekTwo
/// }
/// }
/// }
///
/// As you can see, complexity for each element of the argument list
/// depends on the argument type and capabilities of the collection
/// used to initialize the corresponding subject's parent's mirror.
/// Each `String` argument results in a linear search. In short,
/// this function is suitable for exploring the structure of a
/// `Mirror` in a REPL or playground, but don't expect it to be
/// efficient.
public func descendant(
_ first: MirrorPath, _ rest: MirrorPath...
) -> Any? {
var result: Any = _Dummy(mirror: self)
for e in [first] + rest {
let children = Mirror(reflecting: result).children
let position: Children.Index
if case let label as String = e {
position = children.index { $0.label == label } ?? children.endIndex
}
else if let offset = (e as? Int).map({ IntMax($0) }) ?? (e as? IntMax) {
position = children.index(children.startIndex,
offsetBy: offset,
limitedBy: children.endIndex) ?? children.endIndex
}
else {
_preconditionFailure(
"Someone added a conformance to MirrorPath; that privilege is reserved to the standard library")
}
if position == children.endIndex { return nil }
result = children[position].value
}
return result
}
}
//===--- Legacy _Mirror Support -------------------------------------------===//
extension Mirror.DisplayStyle {
/// Construct from a legacy `_MirrorDisposition`
internal init?(legacy: _MirrorDisposition) {
switch legacy {
case .`struct`: self = .`struct`
case .`class`: self = .`class`
case .`enum`: self = .`enum`
case .tuple: self = .tuple
case .aggregate: return nil
case .indexContainer: self = .collection
case .keyContainer: self = .dictionary
case .membershipContainer: self = .`set`
case .container: preconditionFailure("unused!")
case .optional: self = .optional
case .objCObject: self = .`class`
}
}
}
internal func _isClassSuperMirror(_ t: Any.Type) -> Bool {
#if _runtime(_ObjC)
return t == _ClassSuperMirror.self || t == _ObjCSuperMirror.self
#else
return t == _ClassSuperMirror.self
#endif
}
extension _Mirror {
internal func _superMirror() -> _Mirror? {
if self.count > 0 {
let childMirror = self[0].1
if _isClassSuperMirror(childMirror.dynamicType) {
return childMirror
}
}
return nil
}
}
/// When constructed using the legacy reflection infrastructure, the
/// resulting `Mirror`'s `children` collection will always be
/// upgradable to `AnyRandomAccessCollection` even if it doesn't
/// exhibit appropriate performance. To avoid this pitfall, convert
/// mirrors to use the new style, which only present forward
/// traversal in general.
internal extension Mirror {
/// An adapter that represents a legacy `_Mirror`'s children as
/// a `Collection` with integer `Index`. Note that the performance
/// characteristics of the underlying `_Mirror` may not be
/// appropriate for random access! To avoid this pitfall, convert
/// mirrors to use the new style, which only present forward
/// traversal in general.
internal struct LegacyChildren : RandomAccessCollection {
typealias Indices = CountableRange<Int>
init(_ oldMirror: _Mirror) {
self._oldMirror = oldMirror
}
var startIndex: Int {
return _oldMirror._superMirror() == nil ? 0 : 1
}
var endIndex: Int { return _oldMirror.count }
subscript(position: Int) -> Child {
let (label, childMirror) = _oldMirror[position]
return (label: label, value: childMirror.value)
}
internal let _oldMirror: _Mirror
}
/// Initialize for a view of `subject` as `subjectClass`.
///
/// - parameter ancestor: A Mirror for a (non-strict) ancestor of
/// `subjectClass`, to be injected into the resulting hierarchy.
///
/// - parameter legacy: Either `nil`, or a legacy mirror for `subject`
/// as `subjectClass`.
internal init(
_ subject: AnyObject,
subjectClass: AnyClass,
ancestor: Mirror,
legacy legacyMirror: _Mirror? = nil
) {
if ancestor.subjectType == subjectClass
|| ancestor._defaultDescendantRepresentation == .suppressed {
self = ancestor
}
else {
let legacyMirror = legacyMirror ?? Mirror._legacyMirror(
subject, asClass: subjectClass)!
self = Mirror(
legacy: legacyMirror,
subjectType: subjectClass,
makeSuperclassMirror: {
_getSuperclass(subjectClass).map {
Mirror(
subject,
subjectClass: $0,
ancestor: ancestor,
legacy: legacyMirror._superMirror())
}
})
}
}
internal init(
legacy legacyMirror: _Mirror,
subjectType: Any.Type,
makeSuperclassMirror: (() -> Mirror?)? = nil
) {
if let makeSuperclassMirror = makeSuperclassMirror {
self._makeSuperclassMirror = makeSuperclassMirror
}
else if let subjectSuperclass = _getSuperclass(subjectType) {
self._makeSuperclassMirror = {
legacyMirror._superMirror().map {
Mirror(legacy: $0, subjectType: subjectSuperclass) }
}
}
else {
self._makeSuperclassMirror = Mirror._noSuperclassMirror
}
self.subjectType = subjectType
self.children = Children(LegacyChildren(legacyMirror))
self.displayStyle = DisplayStyle(legacy: legacyMirror.disposition)
self._defaultDescendantRepresentation = .generated
}
}
//===--- QuickLooks -------------------------------------------------------===//
/// The sum of types that can be used as a quick look representation.
public enum PlaygroundQuickLook {
/// Plain text.
case text(String)
/// An integer numeric value.
case int(Int64)
/// An unsigned integer numeric value.
case uInt(UInt64)
/// A single precision floating-point numeric value.
case float(Float32)
/// A double precision floating-point numeric value.
case double(Float64)
// FIXME: Uses an Any to avoid coupling a particular Cocoa type.
/// An image.
case image(Any)
// FIXME: Uses an Any to avoid coupling a particular Cocoa type.
/// A sound.
case sound(Any)
// FIXME: Uses an Any to avoid coupling a particular Cocoa type.
/// A color.
case color(Any)
// FIXME: Uses an Any to avoid coupling a particular Cocoa type.
/// A bezier path.
case bezierPath(Any)
// FIXME: Uses an Any to avoid coupling a particular Cocoa type.
/// An attributed string.
case attributedString(Any)
// FIXME: Uses explicit coordinates to avoid coupling a particular Cocoa type.
/// A rectangle.
case rectangle(Float64, Float64, Float64, Float64)
// FIXME: Uses explicit coordinates to avoid coupling a particular Cocoa type.
/// A point.
case point(Float64, Float64)
// FIXME: Uses explicit coordinates to avoid coupling a particular Cocoa type.
/// A size.
case size(Float64, Float64)
/// A boolean value.
case bool(Bool)
// FIXME: Uses explicit values to avoid coupling a particular Cocoa type.
/// A range.
case range(Int64, Int64)
// FIXME: Uses an Any to avoid coupling a particular Cocoa type.
/// A GUI view.
case view(Any)
// FIXME: Uses an Any to avoid coupling a particular Cocoa type.
/// A graphical sprite.
case sprite(Any)
/// A Uniform Resource Locator.
case url(String)
/// Raw data that has already been encoded in a format the IDE understands.
case _raw([UInt8], String)
}
extension PlaygroundQuickLook {
/// Initialize for the given `subject`.
///
/// If the dynamic type of `subject` conforms to
/// `CustomPlaygroundQuickLookable`, returns the result of calling
/// its `customPlaygroundQuickLook` property. Otherwise, returns
/// a `PlaygroundQuickLook` synthesized for `subject` by the
/// language. Note that in some cases the result may be
/// `.Text(String(reflecting: subject))`.
///
/// - Note: If the dynamic type of `subject` has value semantics,
/// subsequent mutations of `subject` will not observable in
/// `Mirror`. In general, though, the observability of such
/// mutations is unspecified.
public init(reflecting subject: Any) {
if let customized = subject as? CustomPlaygroundQuickLookable {
self = customized.customPlaygroundQuickLook
}
else if let customized = subject as? _DefaultCustomPlaygroundQuickLookable {
self = customized._defaultCustomPlaygroundQuickLook
}
else {
if let q = _reflect(subject).quickLookObject {
self = q
}
else {
self = .text(String(reflecting: subject))
}
}
}
}
/// A type that explicitly supplies its own PlaygroundQuickLook.
///
/// Instances of any type can be `PlaygroundQuickLook(reflect:)`'ed
/// upon, but if you are not satisfied with the `PlaygroundQuickLook`
/// supplied for your type by default, you can make it conform to
/// `CustomPlaygroundQuickLookable` and return a custom
/// `PlaygroundQuickLook`.
public protocol CustomPlaygroundQuickLookable {
/// A custom playground quick look for this instance.
///
/// If this type has value semantics, the `PlaygroundQuickLook` instance
/// should be unaffected by subsequent mutations.
var customPlaygroundQuickLook: PlaygroundQuickLook { get }
}
// A workaround for <rdar://problem/25971264>
// FIXME(ABI)
public protocol _DefaultCustomPlaygroundQuickLookable {
var _defaultCustomPlaygroundQuickLook: PlaygroundQuickLook { get }
}
//===--- General Utilities ------------------------------------------------===//
// This component could stand alone, but is used in Mirror's public interface.
/// A lightweight collection of key-value pairs.
///
/// Use a `DictionaryLiteral` instance when you need an ordered collection of
/// key-value pairs and don't require the fast key lookup that the
/// `Dictionary` type provides. Unlike key-value pairs in a true dictionary,
/// neither the key nor the value of a `DictionaryLiteral` instance must
/// conform to the `Hashable` protocol.
///
/// You initialize a `DictionaryLiteral` instance using a Swift dictionary
/// literal. Besides maintaining the order of the original dictionary literal,
/// `DictionaryLiteral` also allows duplicates keys. For example:
///
/// let recordTimes: DictionaryLiteral = ["Florence Griffith-Joyner": 10.49,
/// "Evelyn Ashford": 10.76,
/// "Evelyn Ashford": 10.79,
/// "Marlies Gohr": 10.81]
/// print(recordTimes.first!)
/// // Prints "("Florence Griffith-Joyner", 10.49)"
///
/// Some operations that are efficient on a dictionary are slower when using
/// `DictionaryLiteral`. In particular, to find the value matching a key, you
/// must search through every element of the collection. The call to
/// `index(where:)` in the following example must traverse the whole
/// collection to make sure that no element matches the given predicate:
///
/// let runner = "Marlies Gohr"
/// if let index = recordTimes.index(where: { $0.0 == runner }) {
/// let time = recordTimes[index].1
/// print("\(runner) set a 100m record of \(time) seconds.")
/// } else {
/// print("\(runner) couldn't be found in the records.")
/// }
/// // Prints "Marlies Gohr set a 100m record of 10.81 seconds."
///
/// Dictionary Literals as Function Parameters
/// ------------------------------------------
///
/// When calling a function with a `DictionaryLiteral` parameter, you can pass
/// a Swift dictionary literal without causing a `Dictionary` to be created.
/// This capability can be especially important when the order of elements in
/// the literal is significant.
///
/// For example, you could create an `IntPairs` structure that holds a list of
/// two-integer tuples and use an initializer that accepts a
/// `DictionaryLiteral` instance.
///
/// struct IntPairs {
/// var elements: [(Int, Int)]
///
/// init(_ elements: DictionaryLiteral<Int, Int>) {
/// self.elements = Array(elements)
/// }
/// }
///
/// When you're ready to create a new `IntPairs` instance, use a dictionary
/// literal as the parameter to the `IntPairs` initializer. The
/// `DictionaryLiteral` instance preserves the order of the elements as
/// passed.
///
/// let pairs = IntPairs([1: 2, 1: 1, 3: 4, 2: 1])
/// print(pairs.elements)
/// // Prints "[(1, 2), (1, 1), (3, 4), (2, 1)]"
public struct DictionaryLiteral<Key, Value> : DictionaryLiteralConvertible {
/// Creates a new `DictionaryLiteral` instance from the given dictionary
/// literal.
///
/// The order of the key-value pairs is kept intact in the resulting
/// `DictionaryLiteral` instance.
public init(dictionaryLiteral elements: (Key, Value)...) {
self._elements = elements
}
internal let _elements: [(Key, Value)]
}
/// `Collection` conformance that allows `DictionaryLiteral` to
/// interoperate with the rest of the standard library.
extension DictionaryLiteral : RandomAccessCollection {
public typealias Indices = CountableRange<Int>
/// The position of the first element in a nonempty collection.
///
/// If the `DictionaryLiteral` instance is empty, `startIndex` is equal to
/// `endIndex`.
public var startIndex: Int { return 0 }
/// The collection's "past the end" position---that is, the position one
/// greater than the last valid subscript argument.
///
/// If the `DictionaryLiteral` instance is empty, `endIndex` is equal to
/// `startIndex`.
public var endIndex: Int { return _elements.endIndex }
// FIXME: a typealias is needed to prevent <rdar://20248032>
/// The element type of a `DictionaryLiteral`: a tuple containing an
/// individual key-value pair.
public typealias Element = (key: Key, value: Value)
/// Accesses the element at the specified position.
///
/// - Parameter position: The position of the element to access. `position`
/// must be a valid index of the collection that is not equal to the
/// `endIndex` property.
/// - Returns: The key-value pair at position `position`.
public subscript(position: Int) -> Element {
return _elements[position]
}
}
extension String {
/// Creates a string representing the given value.
///
/// Use this initializer to convert an instance of any type to its preferred
/// representation as a `String` instance. The initializer creates the
/// string representation of `instance` in one of the following ways,
/// depending on its protocol conformance:
///
/// - If `instance` conforms to the `Streamable` protocol, the result is
/// obtained by calling `instance.write(to: s)` on an empty string `s`.
/// - If `instance` conforms to the `CustomStringConvertible` protocol, the
/// result is `instance.description`.
/// - If `instance` conforms to the `CustomDebugStringConvertible` protocol,
/// the result is `instance.debugDescription`.
/// - An unspecified result is supplied automatically by the Swift standard
/// library.
///
/// For example, this custom `Point` struct uses the default representation
/// supplied by the standard library.
///
/// struct Point {
/// let x: Int, y: Int
/// }
///
/// let p = Point(x: 21, y: 30)
/// print(String(p))
/// // Prints "Point(x: 21, y: 30)"
///
/// After adding `CustomStringConvertible` conformance by implementing the
/// `description` property, `Point` provides its own custom representation.
///
/// extension Point: CustomStringConvertible {
/// var description: String {
/// return "(\(x), \(y))"
/// }
/// }
///
/// print(String(p))
/// // Prints "(21, 30)"
///
/// - SeeAlso: `String.init<Subject>(reflecting: Subject)`
public init<Subject>(_ instance: Subject) {
self.init()
_print_unlocked(instance, &self)
}
/// Creates a string with a detailed representation of the given value,
/// suitable for debugging.
///
/// Use this initializer to convert an instance of any type to its custom
/// debugging representation. The initializer creates the string
/// representation of `instance` in one of the following ways, depending on
/// its protocol conformance:
///
/// - If `subject` conforms to the `CustomDebugStringConvertible` protocol,
/// the result is `subject.debugDescription`.
/// - If `subject` conforms to the `CustomStringConvertible` protocol, the
/// result is `subject.description`.
/// - If `subject` conforms to the `Streamable` protocol, the result is
/// obtained by calling `subject.write(to: s)` on an empty string `s`.
/// - An unspecified result is supplied automatically by the Swift standard
/// library.
///
/// For example, this custom `Point` struct uses the default representation
/// supplied by the standard library.
///
/// struct Point {
/// let x: Int, y: Int
/// }
///
/// let p = Point(x: 21, y: 30)
/// print(String(reflecting: p))
/// // Prints "p: Point = {
/// // x = 21
/// // y = 30
/// // }"
///
/// After adding `CustomDebugStringConvertible` conformance by implementing
/// the `debugDescription` property, `Point` provides its own custom
/// debugging representation.
///
/// extension Point: CustomDebugStringConvertible {
/// var debugDescription: String {
/// return "Point(x: \(x), y: \(y))"
/// }
/// }
///
/// print(String(reflecting: p))
/// // Prints "Point(x: 21, y: 30)"
///
/// - SeeAlso: `String.init<Subject>(Subject)`
public init<Subject>(reflecting subject: Subject) {
self.init()
_debugPrint_unlocked(subject, &self)
}
}
/// Reflection for `Mirror` itself.
extension Mirror : CustomStringConvertible {
public var description: String {
return "Mirror for \(self.subjectType)"
}
}
extension Mirror : CustomReflectable {
public var customMirror: Mirror {
return Mirror(self, children: [:])
}
}
@available(*, unavailable, renamed: "MirrorPath")
public typealias MirrorPathType = MirrorPath
| 524724bbdd679bfc9c379833c8805282 | 35.912815 | 106 | 0.661563 | false | false | false | false |
Tj3n/TVNExtensions | refs/heads/master | Foundation/Error.swift | mit | 1 | //
// ErrorExtension.swift
// Alamofire
//
// Created by Tien Nhat Vu on 11/24/17.
//
import Foundation
public let TVNErrorDomain = "com.tvn.errorDomain"
public extension NSError {
func show() {
ErrorAlertView.shared.showError(self)
}
var jsonString: String? {
get {
let dict = ["code": String(self.code),
"description": self.localizedDescription]
if let jsonData = try? JSONSerialization.data(withJSONObject: dict, options: []) {
if let jsonString = String(data: jsonData, encoding: .utf8) {
return jsonString
}
}
return nil
}
}
}
public extension Error {
func show() {
ErrorAlertView.shared.showError(self)
}
var jsonString: String? {
get {
let err = self as NSError
var dict = ["code": String(err.code)]
if let localizedDescription = err.userInfo[NSLocalizedDescriptionKey] as? String {
dict["description"] = localizedDescription
} else {
dict["description"] = "Unknow error"
}
if let jsonData = try? JSONSerialization.data(withJSONObject: dict, options: []) {
if let jsonString = String(data: jsonData, encoding: .utf8) {
return jsonString
}
}
return nil
}
}
}
private class ErrorAlertView {
static let shared = ErrorAlertView()
var alert: UIAlertController?
func showError(_ error: Error?) {
DispatchQueue.main.async(execute: {
guard (error as NSError?)?.code != NSURLErrorCancelled && UIApplication.shared.applicationState == .active else {
return
}
if let alert = self.alert, let _ = alert.presentingViewController {
alert.message = error?.localizedDescription
} else {
self.alert = UIAlertController(title: "Error", message: error?.localizedDescription, preferredStyle: .alert, cancelTitle: "OK")
self.alert?.show()
}
})
}
}
| 9900239d3d95e16bb167847b3e1b1dff | 28.8 | 143 | 0.541387 | false | false | false | false |
hamin/FayeSwift | refs/heads/master | Sources/FayeClient.swift | mit | 1 | //
// FayeClient.swift
// FayeSwift
//
// Created by Haris Amin on 8/31/14.
// Copyright (c) 2014 Haris Amin. All rights reserved.
//
import Foundation
import SwiftyJSON
// MARK: Subscription State
public enum FayeSubscriptionState {
case pending(FayeSubscriptionModel)
case subscribed(FayeSubscriptionModel)
case queued(FayeSubscriptionModel)
case subscribingTo(FayeSubscriptionModel)
case unknown(FayeSubscriptionModel?)
}
// MARK: Type Aliases
public typealias ChannelSubscriptionBlock = (NSDictionary) -> Void
// MARK: FayeClient
open class FayeClient : TransportDelegate {
open var fayeURLString:String {
didSet {
if let transport = self.transport {
transport.urlString = fayeURLString
}
}
}
open var fayeClientId:String?
open weak var delegate:FayeClientDelegate?
var transport:WebsocketTransport?
open var transportHeaders: [String: String]? = nil {
didSet {
if let transport = self.transport {
transport.headers = self.transportHeaders
}
}
}
open internal(set) var fayeConnected:Bool? {
didSet {
if fayeConnected == false {
unsubscribeAllSubscriptions()
}
}
}
var connectionInitiated:Bool?
var messageNumber:UInt32 = 0
var queuedSubscriptions = Array<FayeSubscriptionModel>()
var pendingSubscriptions = Array<FayeSubscriptionModel>()
var openSubscriptions = Array<FayeSubscriptionModel>()
var channelSubscriptionBlocks = Dictionary<String, ChannelSubscriptionBlock>()
lazy var pendingSubscriptionSchedule: Timer = {
return Timer.scheduledTimer(
timeInterval: 45,
target: self,
selector: #selector(pendingSubscriptionsAction(_:)),
userInfo: nil,
repeats: true
)
}()
/// Default in 10 seconds
let timeOut: Int
let readOperationQueue = DispatchQueue(label: "com.hamin.fayeclient.read", attributes: [])
let writeOperationQueue = DispatchQueue(label: "com.hamin.fayeclient.write", attributes: DispatchQueue.Attributes.concurrent)
let queuedSubsLockQueue = DispatchQueue(label:"com.fayeclient.queuedSubscriptionsLockQueue")
let pendingSubsLockQueue = DispatchQueue(label:"com.fayeclient.pendingSubscriptionsLockQueue")
let openSubsLockQueue = DispatchQueue(label:"com.fayeclient.openSubscriptionsLockQueue")
// MARK: Init
public init(aFayeURLString:String, channel:String?, timeoutAdvice:Int=10000) {
self.fayeURLString = aFayeURLString
self.fayeConnected = false;
self.timeOut = timeoutAdvice
self.transport = WebsocketTransport(url: aFayeURLString)
self.transport!.headers = self.transportHeaders
self.transport!.delegate = self;
if let channel = channel {
self.queuedSubscriptions.append(FayeSubscriptionModel(subscription: channel, clientId: fayeClientId))
}
}
public convenience init(aFayeURLString:String, channel:String, channelBlock:@escaping ChannelSubscriptionBlock) {
self.init(aFayeURLString: aFayeURLString, channel: channel)
self.channelSubscriptionBlocks[channel] = channelBlock;
}
deinit {
pendingSubscriptionSchedule.invalidate()
}
// MARK: Client
open func connectToServer() {
if self.connectionInitiated != true {
self.transport?.openConnection()
self.connectionInitiated = true;
} else {
print("Faye: Connection established")
}
}
open func disconnectFromServer() {
unsubscribeAllSubscriptions()
self.disconnect()
}
open func sendMessage(_ messageDict: NSDictionary, channel:String) {
self.publish(messageDict as! Dictionary, channel: channel)
}
open func sendMessage(_ messageDict:[String:AnyObject], channel:String) {
self.publish(messageDict, channel: channel)
}
open func sendPing(_ data: Data, completion: (() -> ())?) {
writeOperationQueue.async { [unowned self] in
self.transport?.sendPing(data, completion: completion)
}
}
open func subscribeToChannel(_ model:FayeSubscriptionModel, block:ChannelSubscriptionBlock?=nil) -> FayeSubscriptionState {
guard !self.isSubscribedToChannel(model.subscription) else {
return .subscribed(model)
}
guard !self.pendingSubscriptions.contains(where: { $0 == model }) else {
return .pending(model)
}
if let block = block {
self.channelSubscriptionBlocks[model.subscription] = block;
}
if self.fayeConnected == false {
self.queuedSubscriptions.append(model)
return .queued(model)
}
self.subscribe(model)
return .subscribingTo(model)
}
open func subscribeToChannel(_ channel:String, block:ChannelSubscriptionBlock?=nil) -> FayeSubscriptionState {
return subscribeToChannel(
FayeSubscriptionModel(subscription: channel, clientId: fayeClientId),
block: block
)
}
open func unsubscribeFromChannel(_ channel:String) {
_ = removeChannelFromQueuedSubscriptions(channel)
self.unsubscribe(channel)
self.channelSubscriptionBlocks[channel] = nil;
_ = removeChannelFromOpenSubscriptions(channel)
_ = removeChannelFromPendingSubscriptions(channel)
}
}
| fcf425071c47118900f463c075963cd7 | 28.661017 | 127 | 0.702476 | false | false | false | false |
jianghuihon/DYZB | refs/heads/master | DYZB/Classes/Home/View/AmuseMenViewCell.swift | mit | 1 | //
// AmuseMenViewCell.swift
// DYZB
//
// Created by Enjoy on 2017/4/2.
// Copyright © 2017年 SZCE. All rights reserved.
//
import UIKit
private let itemWidth = kScreenW / 4
private let cellID = "CollectionGameViewCell"
class AmuseMenViewCell: UICollectionViewCell {
var anthorGroups : [AuthorGroup]? {
didSet{
collectionView.reloadData()
}
}
@IBOutlet weak var collectionView: UICollectionView!
override func awakeFromNib() {
super.awakeFromNib()
collectionView.register(UINib.init(nibName: cellID, bundle: nil), forCellWithReuseIdentifier: cellID)
}
override func layoutSubviews() {
super.layoutSubviews()
let layout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout
layout.itemSize = CGSize(width: itemWidth, height: itemWidth)
layout.minimumLineSpacing = 0
layout.minimumInteritemSpacing = 0
}
}
extension AmuseMenViewCell : UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return anthorGroups?.count ?? 0
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellID, for: indexPath) as! CollectionGameViewCell
cell.baseModel = anthorGroups![indexPath.item]
cell.clipsToBounds = true
return cell
}
}
| 0119d5d7101b829fa91e560ea80fa5e4 | 25.183333 | 126 | 0.683641 | false | false | false | false |
grandiere/box | refs/heads/master | box/Model/Store/Base/MStore.swift | mit | 1 | import Foundation
import StoreKit
class MStore
{
private(set) var mapItems:[String:MStoreItem]
private(set) var references:[String]
private let priceFormatter:NumberFormatter
var error:String?
init()
{
priceFormatter = NumberFormatter()
priceFormatter.numberStyle = NumberFormatter.Style.currencyISOCode
mapItems = [:]
references = []
let itemPlusRange:MStorePurchasePlusRange = MStorePurchasePlusRange()
let itemEnergy:MStorePurchaseEnergy = MStorePurchaseEnergy()
let itemMemory:MStorePurchaseMemory = MStorePurchaseMemory()
let itemNetwork:MStorePurchaseNetwork = MStorePurchaseNetwork()
let itemProcessor:MStorePurchaseProcessor = MStorePurchaseProcessor()
let itemSkill:MStorePurchaseSkill = MStorePurchaseSkill()
addPurchase(item:itemPlusRange)
addPurchase(item:itemEnergy)
addPurchase(item:itemMemory)
addPurchase(item:itemNetwork)
addPurchase(item:itemProcessor)
addPurchase(item:itemSkill)
}
//MARK: private
private func addPurchase(item:MStoreItem)
{
let purchaseId:String = item.purchaseId
mapItems[purchaseId] = item
references.append(purchaseId)
}
//MARK: public
func loadSkProduct(skProduct:SKProduct)
{
let productId:String = skProduct.productIdentifier
guard
let mappedItem:MStoreItem = mapItems[productId]
else
{
return
}
mappedItem.skProduct = skProduct
priceFormatter.locale = skProduct.priceLocale
let priceNumber:NSDecimalNumber = skProduct.price
guard
let priceString:String = priceFormatter.string(from:priceNumber)
else
{
return
}
mappedItem.foundPurchase(price:priceString)
}
func updateTransactions(transactions:[SKPaymentTransaction])
{
for skPaymentTransaction:SKPaymentTransaction in transactions
{
let productId:String = skPaymentTransaction.payment.productIdentifier
guard
let mappedItem:MStoreItem = mapItems[productId]
else
{
continue
}
switch skPaymentTransaction.transactionState
{
case SKPaymentTransactionState.deferred:
mappedItem.statusDeferred()
break
case SKPaymentTransactionState.failed:
mappedItem.statusNew()
SKPaymentQueue.default().finishTransaction(skPaymentTransaction)
break
case SKPaymentTransactionState.purchased,
SKPaymentTransactionState.restored:
mappedItem.statusPurchased(callAction:true)
SKPaymentQueue.default().finishTransaction(skPaymentTransaction)
break
case SKPaymentTransactionState.purchasing:
mappedItem.statusPurchasing()
break
}
}
}
}
| 8f200d0470951bdbccbdec1605c1b337 | 27.595041 | 81 | 0.564451 | false | false | false | false |
Clipy/Magnet | refs/heads/master | Lib/Magnet/Extensions/NSEventExtension.swift | mit | 1 | //
// NSEventExtension.swift
//
// Magnet
// GitHub: https://github.com/clipy
// HP: https://clipy-app.com
//
// Copyright © 2015-2020 Clipy Project.
//
import Cocoa
import Carbon
import Sauce
public extension NSEvent.ModifierFlags {
var containsSupportModifiers: Bool {
return contains(.command) || contains(.option) || contains(.control) || contains(.shift) || contains(.function)
}
var isSingleFlags: Bool {
let commandSelected = contains(.command)
let optionSelected = contains(.option)
let controlSelected = contains(.control)
let shiftSelected = contains(.shift)
return [commandSelected, optionSelected, controlSelected, shiftSelected].trueCount == 1
}
func filterUnsupportModifiers() -> NSEvent.ModifierFlags {
var filterdModifierFlags = NSEvent.ModifierFlags(rawValue: 0)
if contains(.command) {
filterdModifierFlags.insert(.command)
}
if contains(.option) {
filterdModifierFlags.insert(.option)
}
if contains(.control) {
filterdModifierFlags.insert(.control)
}
if contains(.shift) {
filterdModifierFlags.insert(.shift)
}
return filterdModifierFlags
}
func filterNotShiftModifiers() -> NSEvent.ModifierFlags {
guard contains(.shift) else { return NSEvent.ModifierFlags(rawValue: 0) }
return .shift
}
func keyEquivalentStrings() -> [String] {
var strings = [String]()
if contains(.control) {
strings.append("⌃")
}
if contains(.option) {
strings.append("⌥")
}
if contains(.shift) {
strings.append("⇧")
}
if contains(.command) {
strings.append("⌘")
}
return strings
}
}
public extension NSEvent.ModifierFlags {
init(carbonModifiers: Int) {
var result = NSEvent.ModifierFlags(rawValue: 0)
if (carbonModifiers & cmdKey) != 0 {
result.insert(.command)
}
if (carbonModifiers & optionKey) != 0 {
result.insert(.option)
}
if (carbonModifiers & controlKey) != 0 {
result.insert(.control)
}
if (carbonModifiers & shiftKey) != 0 {
result.insert(.shift)
}
self = result
}
func carbonModifiers(isSupportFunctionKey: Bool = false) -> Int {
var carbonModifiers: Int = 0
if contains(.command) {
carbonModifiers |= cmdKey
}
if contains(.option) {
carbonModifiers |= optionKey
}
if contains(.control) {
carbonModifiers |= controlKey
}
if contains(.shift) {
carbonModifiers |= shiftKey
}
if contains(.function) && isSupportFunctionKey {
carbonModifiers |= Int(NSEvent.ModifierFlags.function.rawValue)
}
return carbonModifiers
}
}
extension NSEvent.EventType {
fileprivate var isKeyboardEvent: Bool {
return [.keyUp, .keyDown, .flagsChanged].contains(self)
}
}
extension NSEvent {
/// Returns a matching `KeyCombo` for the event, if the event is a keyboard event and the key is recognized.
public var keyCombo: KeyCombo? {
guard self.type.isKeyboardEvent else { return nil }
guard let key = Sauce.shared.key(for: Int(self.keyCode)) else { return nil }
return KeyCombo(key: key, cocoaModifiers: self.modifierFlags)
}
}
| 99944a5c0748e1f8bc40a62436368d50 | 28.45 | 119 | 0.595642 | false | false | false | false |
1457792186/JWSwift | refs/heads/master | SwiftWX/LGWeChatKit/LGChatKit/conversion/view/LGShareMoreView.swift | apache-2.0 | 1 | //
// LGMoreView.swift
// LGChatViewController
//
// Created by jamy on 10/16/15.
// Copyright © 2015 jamy. All rights reserved.
//
import UIKit
enum shareMoreType: Int {
case picture = 1, video, location, record, timeSpeak, hongbao, personCard, store
func imageForType() -> (UIImage, String) {
var image = UIImage()
var title = ""
switch self {
case .picture:
image = UIImage(named: "sharemore_pic")!
title = "照片"
case .video:
image = UIImage(named: "sharemore_videovoip")!
title = "拍摄"
case .location:
image = UIImage(named: "sharemore_location")!
title = "位置"
case .record:
image = UIImage(named: "sharemore_sight")!
title = "小视频"
case .timeSpeak:
image = UIImage(named: "sharemore_wxtalk")!
title = "语音输入"
case .hongbao:
image = UIImage(named: "sharemorePay")!
title = "红包"
case .personCard:
image = UIImage(named: "sharemore_friendcard")!
title = "个人名片"
case .store:
image = UIImage(named: "sharemore_myfav")!
title = "收藏"
}
return (image, title)
}
}
class LGShareMoreView: UIView {
let shareCount = 8
let marginW = 30
let marginH = 20
let buttonH: CGFloat = 59
convenience init(frame: CGRect, selector: Selector, target: AnyObject) {
self.init(frame: frame)
backgroundColor = UIColor(hexString: "F4F4F6")
let marginX = (bounds.width - CGFloat(2 * marginW) - CGFloat(4 * buttonH)) / 3
for i in 0...shareCount - 1 {
let row = i / 4
let column = i % 4
let button = UIButton(type: .custom)
button.tag = i + 1
button.addTarget(target, action: selector, for: .touchUpInside)
let image = shareMoreType(rawValue: i + 1)?.imageForType().0
let title = shareMoreType(rawValue: i + 1)?.imageForType().1
button.setImage(image, for: UIControlState())
button.setTitleColor(UIColor.black, for: UIControlState())
button.setTitle(title, for: UIControlState())
// button.titleEdgeInsets = UIEdgeInsetsMake(53, -59, 0, 0)
// button.imageEdgeInsets = UIEdgeInsetsMake(0, 0, 21, 0)
button.setBackgroundImage(UIImage(named: "sharemore_otherDown"), for: UIControlState())
button.setBackgroundImage(UIImage(named: "sharemore_otherDownHL"), for: .highlighted)
let buttonX = CGFloat(marginW) + (buttonH + marginX) * CGFloat(column)
let buttonY = CGFloat(marginH) + (buttonH + CGFloat(marginH)) * CGFloat(row)
button.frame = CGRect(x: buttonX, y: buttonY, width: buttonH, height: buttonH)
addSubview(button)
}
}
override init(frame: CGRect) {
super.init(frame: frame)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| 0bc7bba7c73897bac2b8b4096e891e0e | 30.067961 | 99 | 0.552813 | false | false | false | false |
marty-suzuki/FluxCapacitor | refs/heads/master | FluxCapacitor/Internal/ValueNotifyCenter.swift | mit | 1 | //
// ValueNotifyCenter.swift
// FluxCapacitor
//
// Created by marty-suzuki on 2018/02/04.
// Copyright © 2018年 marty-suzuki. All rights reserved.
//
import Foundation
/// Notify changes of values.
final class ValueNotifyCenter<Element> {
private struct Observer {
fileprivate struct Token {
let value = UUID().uuidString
}
fileprivate let token: Token
fileprivate let excuteQueue: ExecuteQueue
fileprivate let changes: (Element) -> ()
}
private var observers: [Observer] = []
private let mutex = PThreadMutex()
func addObserver(excuteQueue: ExecuteQueue, changes: @escaping (Element) -> Void) -> Dust {
mutex.lock()
let observer = Observer(token: .init(), excuteQueue: excuteQueue, changes: changes)
observers.append(observer)
let token = observer.token
mutex.unlock()
return Dust { [weak self] in
guard let me = self else { return }
defer { me.mutex.unlock() }; me.mutex.lock()
me.observers = me.observers.filter { $0.token.value != token.value }
}
}
func notifyChanges(value: Element) {
observers.forEach { observer in
let execute: () -> Void = {
observer.changes(value)
}
switch observer.excuteQueue {
case .current:
execute()
case .main:
if Thread.isMainThread {
execute()
} else {
DispatchQueue.main.async(execute: execute)
}
case .queue(let queue):
queue.async(execute: execute)
}
}
}
}
| 3f927dcd510a8352d914654b47c78c12 | 26.758065 | 95 | 0.553167 | false | false | false | false |
chromatic-seashell/weibo | refs/heads/master | 新浪微博/新浪微博/classes/home/PhotoBrowser/GDWPhotoBroserAnimationManager.swift | apache-2.0 | 1 | //
// GDWPhotoBroserAnimationManager.swift
// 新浪微博
//
// Created by apple on 16/3/18.
// Copyright © 2016年 apple. All rights reserved.
//
import UIKit
// MARK: - 定义协议
protocol GDWPhotoBroserAnimationManagerDelegate : NSObjectProtocol{
/// 返回和点击的UIImageView一模一样的UIImageView
func photoBrowserImageView(path: NSIndexPath) -> UIImageView
/// 返回被点击的UIImageView相对于keywindow的frame
func photoBrowserFromRect(path: NSIndexPath) -> CGRect
/// 返回被点击的UIImageView最终在图片浏览器中显示的尺寸
func photoBrowserToRect(path: NSIndexPath) -> CGRect
}
class GDWPhotoBroserAnimationManager: UIPresentationController {
/// 当前被点击图片的索引
private var path: NSIndexPath?
/// 记录当前是否是展现
private var isPresent = false
/// 负责展现动画的代理
weak var photoBrowserDelegate : GDWPhotoBroserAnimationManagerDelegate?
/// 初始化方法
func setDefaultInfo(path: NSIndexPath)
{
self.path = path
}
}
extension GDWPhotoBroserAnimationManager : UIViewControllerTransitioningDelegate,UIViewControllerAnimatedTransitioning{
// MARK: - UIViewControllerTransitioningDelegate
func presentationControllerForPresentedViewController(presented: UIViewController, presentingViewController presenting: UIViewController, sourceViewController source: UIViewController) -> UIPresentationController?
{
return UIPresentationController(presentedViewController: presented, presentingViewController: presenting)
}
/// 告诉系统谁来负责展现的样式
func animationControllerForPresentedController(presented: UIViewController, presentingController presenting: UIViewController, sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning?
{
isPresent = true
return self
}
/// 告诉系统谁来负责消失的样式
func animationControllerForDismissedController(dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning?
{
isPresent = false
return self
}
// MARK: - UIViewControllerAnimatedTransitioning
/// 该方法用于告诉系统展现或者消失动画的时长
func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval
{
return 0.5
}
/// 无论是展现还是消失都会调用这个方法
func animateTransition(transitionContext: UIViewControllerContextTransitioning)
{
// 1.拿到菜单, 将菜单添加到容器视图上
if isPresent
{
// 1.1获取图片浏览器
let toView = transitionContext.viewForKey(UITransitionContextToViewKey)
transitionContext.containerView()?.addSubview(toView!)
toView?.alpha = 0.0
// 1.2获取需要添加到容器视图上的UIImageView
// 该方法必须返回一个UIImageView
let iv = photoBrowserDelegate!.photoBrowserImageView(path!)
// 1.3获取需要添加到容器视图上的UIImageView的frame
let fromRect = photoBrowserDelegate!.photoBrowserFromRect(path!)
iv.frame = fromRect
transitionContext.containerView()?.addSubview(iv)
// 1.4获取需要添加到容器仕途上的UIImageView最终的frame
let toRect = photoBrowserDelegate!.photoBrowserToRect(path!)
// 2.执行动画
UIView.animateWithDuration(transitionDuration(transitionContext), animations: { () -> Void in
iv.frame = toRect
}, completion: { (_) -> Void in
// 删除iv
iv.removeFromSuperview()
// 显示图片浏览器
toView?.alpha = 1.0
// 告诉系统动画执行完毕
transitionContext.completeTransition(true)
})
}else
{
// 消失
// 1.1获取图片浏览器
let fromVc = transitionContext.viewControllerForKey(UITransitionContextFromViewControllerKey)
//将图片浏览器的view从容器view中移除
fromVc?.view.removeFromSuperview()
// 1.2获取需要添加到容器视图上的UIImageView
// 该方法必须返回一个UIImageView
let iv = photoBrowserDelegate!.photoBrowserImageView(path!)
// 1.3获取需要添加到容器视图上的UIImageView的frame
let fromRect = photoBrowserDelegate!.photoBrowserToRect(path!)
// 1.4获取需要添加到容器视图上的UIImageView最终的frame
let toRect = photoBrowserDelegate!.photoBrowserFromRect(path!)
iv.frame = fromRect
transitionContext.containerView()?.addSubview(iv)
// 2.执行动画
UIView.animateWithDuration(transitionDuration(transitionContext), animations: { () -> Void in
iv.frame = toRect
}, completion: { (_) -> Void in
// 删除iv
iv.removeFromSuperview()
// 告诉系统动画执行完毕
transitionContext.completeTransition(true)
})
}
}
} | b0982755856e050a47d04c3ab6cf62b3 | 32.187919 | 217 | 0.622371 | false | false | false | false |
sora0077/DribbbleKit | refs/heads/master | DribbbleKit/Sources/Transformer.swift | mit | 1 | //
// Transformer.swift
// DribbbleKit
//
// Created by 林達也 on 2017/04/15.
// Copyright © 2017年 jp.sora0077. All rights reserved.
//
import Foundation
import Alter
struct Transformer {
static let date: (String) throws -> Date = {
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZZ"
return {
guard let date = formatter.date(from: $0) else {
throw typeMismatch(expected: Date.self, actual: $0)
}
return date
}
}()
static let url: (String) throws -> URL = {
guard let url = URL(string: $0.trimmingCharacters(in: .whitespacesAndNewlines)) else {
throw typeMismatch(expected: URL.self, actual: $0)
}
return url
}
private static func typeMismatch(expected: Any.Type, actual: Any) -> Error {
return DecodeError.typeMismatch(expected: expected, actual: actual, keyPath: .empty)
}
private init() {}
}
struct ParameterTransformer {
static let date: (Date) -> String = {
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd"
return formatter.string
}()
private init() {}
}
| a8fd8bb6eee509b8ec848d3ac1717808 | 25.888889 | 94 | 0.603306 | false | false | false | false |
WickedColdfront/Slide-iOS | refs/heads/master | Slide for Reddit/SubredditLinkViewController.swift | apache-2.0 | 1 | //
// SubredditLinkViewController.swift
// Slide for Reddit
//
// Created by Carlos Crane on 12/22/16.
// Copyright © 2016 Haptic Apps. All rights reserved.
//
import UIKit
import reddift
import SDWebImage
import SideMenu
import KCFloatingActionButton
import UZTextView
import RealmSwift
import PagingMenuController
import MaterialComponents.MaterialSnackbar
import MaterialComponents.MDCActivityIndicator
import TTTAttributedLabel
import SloppySwiper
class SubredditLinkViewController: MediaViewController, UICollectionViewDelegate, UICollectionViewDataSource, LinkCellViewDelegate, ColorPickerDelegate, KCFloatingActionButtonDelegate, UIGestureRecognizerDelegate, WrappingFlowLayoutDelegate, UINavigationControllerDelegate {
func openComments(id: String) {
var index = 0
for s in links {
if(s.getId() == id){
break
}
index += 1
}
var newLinks : [RSubmission] = []
for i in index...links.count - 1{
newLinks.append(links[i])
}
let comment = PagingCommentViewController.init(submissions: newLinks)
if(UIScreen.main.traitCollection.userInterfaceIdiom == .pad && Int(round(self.view.bounds.width / CGFloat(320))) > 1 && SettingValues.multiColumn){
let navigationController = UINavigationController(rootViewController: comment)
navigationController.modalPresentationStyle = .pageSheet
navigationController.modalTransitionStyle = .crossDissolve
self.present(navigationController, animated: true, completion: nil)
} else if(UIScreen.main.traitCollection.userInterfaceIdiom != .pad){
self.navigationController?.pushViewController(comment, animated: true)
} else {
let nav = UINavigationController.init(rootViewController: comment)
self.splitViewController?.showDetailViewController(nav, sender: self)
}
}
let margin: CGFloat = 10
let cellsPerRow = 3
func collectionView(_ collectionView: UICollectionView, width: CGFloat, indexPath: IndexPath) -> CGSize {
var itemWidth = width
if(SettingValues.postViewMode == .CARD ){
itemWidth -= 10
}
let submission = links[indexPath.row]
var thumb = submission.thumbnail
var big = submission.banner
var type = ContentType.getContentType(baseUrl: submission.url!)
if(submission.isSelf){
type = .SELF
}
if(SettingValues.bannerHidden){
big = false
thumb = true
}
let fullImage = ContentType.fullImage(t: type)
var submissionHeight = submission.height
if(!fullImage && submissionHeight < 50){
big = false
thumb = true
} else if(big && (SettingValues.bigPicCropped )){
submissionHeight = 200
} else if(big){
let ratio = Double(submissionHeight)/Double(submission.width)
let width = Double(itemWidth);
let h = width*ratio
if(h == 0){
submissionHeight = 200
} else {
submissionHeight = Int(h)
}
}
if(type == .SELF && SettingValues.hideImageSelftext || SettingValues.hideImageSelftext && !big){
big = false
thumb = false
}
if(submissionHeight < 50){
thumb = true
big = false
}
if(big || !submission.thumbnail){
thumb = false
}
if(!big && !thumb && submission.type != .SELF && submission.type != .NONE){ //If a submission has a link but no images, still show the web thumbnail
thumb = true
}
if(submission.nsfw && !SettingValues.nsfwPreviews){
big = false
thumb = true
}
if(submission.nsfw && SettingValues.hideNSFWCollection && (sub == "all" || sub == "frontpage" || sub == "popular")){
big = false
thumb = true
}
if(SettingValues.noImages){
big = false
thumb = false
}
if(thumb && type == .SELF){
thumb = false
}
let he = CachedTitle.getTitle(submission: submission, full: false, false).boundingRect(with: CGSize.init(width: itemWidth - 24 - (thumb ? (SettingValues.largerThumbnail ? 75 : 50) + 28 : 0), height:10000), options: [.usesLineFragmentOrigin , .usesFontLeading], context: nil).height
let thumbheight = CGFloat(SettingValues.largerThumbnail ? 83 : 58)
let estimatedHeight = CGFloat((he < thumbheight && thumb || he < thumbheight && !big) ? thumbheight : he) + CGFloat(48) + (SettingValues.hideButtonActionbar ? -28 : 0) + CGFloat(big && !thumb ? (submissionHeight + 20) : 0)
return CGSize(width: itemWidth, height: estimatedHeight)
}
var parentController: SubredditsViewController?
var accentChosen: UIColor?
func valueChanged(_ value: CGFloat, accent: Bool) {
if(accent){
let c = UIColor.init(cgColor: GMPalette.allAccentCGColor()[Int(value * CGFloat(GMPalette.allAccentCGColor().count))])
accentChosen = c
hide.backgroundColor = c
} else {
let c = UIColor.init(cgColor: GMPalette.allCGColor()[Int(value * CGFloat(GMPalette.allCGColor().count))])
self.navigationController?.navigationBar.barTintColor = c
sideView.backgroundColor = c
add.backgroundColor = c
sideView.backgroundColor = c
if(parentController != nil){
parentController?.colorChanged()
}
}
}
func reply(_ cell: LinkCellView){
}
func save(_ cell: LinkCellView) {
do {
try session?.setSave(!ActionStates.isSaved(s: cell.link!), name: (cell.link?.getId())!, completion: { (result) in
})
ActionStates.setSaved(s: cell.link!, saved: !ActionStates.isSaved(s: cell.link!))
History.addSeen(s: cell.link!)
cell.refresh()
} catch {
}
}
func collectionView(_ collectionView: UICollectionView, didEndDisplaying cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
if(SettingValues.markReadOnScroll){
History.addSeen(s: links[indexPath.row])
}
}
func upvote(_ cell: LinkCellView) {
do{
try session?.setVote(ActionStates.getVoteDirection(s: cell.link!) == .up ? .none : .up, name: (cell.link?.getId())!, completion: { (result) in
})
ActionStates.setVoteDirection(s: cell.link!, direction: ActionStates.getVoteDirection(s: cell.link!) == .up ? .none : .up)
History.addSeen(s: cell.link!)
cell.refresh()
} catch {
}
}
func downvote(_ cell: LinkCellView) {
do {
try session?.setVote(ActionStates.getVoteDirection(s: cell.link!) == .down ? .none : .down, name: (cell.link?.getId())!, completion: { (result) in
})
ActionStates.setVoteDirection(s: cell.link!, direction: ActionStates.getVoteDirection(s: cell.link!) == .down ? .none : .down)
History.addSeen(s: cell.link!)
cell.refresh()
} catch {
}
}
func hide(_ cell: LinkCellView) {
do {
try session?.setHide(true, name: cell.link!.getId(), completion: {(result) in })
let id = cell.link!.getId()
var location = 0
var item = links[0]
for submission in links {
if(submission.getId() == id){
item = links[location]
links.remove(at: location)
break
}
location += 1
}
tableView.performBatchUpdates({
self.tableView.deleteItems(at: [IndexPath.init(item: location, section: 0)])
self.flowLayout.reset()
let message = MDCSnackbarMessage.init(text: "Submission hidden forever")
let action = MDCSnackbarMessageAction()
let actionHandler = {() in
self.links.insert(item, at: location)
self.tableView.insertItems(at: [IndexPath.init(item: location, section: 0)])
do {
try self.session?.setHide(false, name: cell.link!.getId(), completion: {(result) in })
}catch {
}
}
action.handler = actionHandler
action.title = "UNDO"
message!.action = action
MDCSnackbarManager.show(message)
}, completion: nil)
} catch {
}
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
let currentY = scrollView.contentOffset.y;
let headerHeight = CGFloat(70);
var didHide = false
if(currentY > lastYUsed ) {
hideUI(inHeader: (currentY > headerHeight) )
didHide = true
} else if(currentY < lastYUsed + 20 && ((currentY > headerHeight))){
showUI()
}
lastYUsed = currentY
if ((lastY <= headerHeight) && (currentY > headerHeight) && (navigationController?.isNavigationBarHidden)! && !didHide) {
(navigationController)?.setNavigationBarHidden(false, animated: true)
if(ColorUtil.theme == .LIGHT || ColorUtil.theme == .SEPIA){
UIApplication.shared.statusBarStyle = .lightContent
}
}
if ((lastY > headerHeight) && (currentY <= headerHeight) && !(navigationController?.isNavigationBarHidden)!) {
(navigationController)?.setNavigationBarHidden(true, animated: true)
if(ColorUtil.theme == .LIGHT || ColorUtil.theme == .SEPIA){
UIApplication.shared.statusBarStyle = .default
}
}
lastY = currentY
}
func hideUI(inHeader: Bool){
(navigationController)?.setNavigationBarHidden(true, animated: true)
if(inHeader){
hide.isHidden = true
add.isHidden = true
}
}
func showUI(){
(navigationController)?.setNavigationBarHidden(false, animated: true)
hide.isHidden = false
add.isHidden = false
}
func more(_ cell: LinkCellView){
let link = cell.link!
let actionSheetController: UIAlertController = UIAlertController(title: link.title, message: "", preferredStyle: .actionSheet)
var cancelActionButton: UIAlertAction = UIAlertAction(title: "Cancel", style: .cancel) { action -> Void in
print("Cancel")
}
actionSheetController.addAction(cancelActionButton)
cancelActionButton = UIAlertAction(title: "/u/\(link.author)", style: .default) { action -> Void in
self.show(ProfileViewController.init(name: link.author), sender: self)
}
actionSheetController.addAction(cancelActionButton)
cancelActionButton = UIAlertAction(title: "/r/\(link.subreddit)", style: .default) { action -> Void in
self.show(SubredditLinkViewController.init(subName: link.subreddit, single: true), sender: self)
}
actionSheetController.addAction(cancelActionButton)
if(AccountController.isLoggedIn){
cancelActionButton = UIAlertAction(title: "Save", style: .default) { action -> Void in
self.save(cell)
}
actionSheetController.addAction(cancelActionButton)
}
cancelActionButton = UIAlertAction(title: "Report", style: .default) { action -> Void in
self.report(cell.link!)
}
actionSheetController.addAction(cancelActionButton)
cancelActionButton = UIAlertAction(title: "Hide", style: .default) { action -> Void in
//todo hide
}
actionSheetController.addAction(cancelActionButton)
let open = OpenInChromeController.init()
if(open.isChromeInstalled()){
cancelActionButton = UIAlertAction(title: "Open in Chrome", style: .default) { action -> Void in
open.openInChrome(link.url!, callbackURL: nil, createNewTab: true)
}
actionSheetController.addAction(cancelActionButton)
}
cancelActionButton = UIAlertAction(title: "Open in Safari", style: .default) { action -> Void in
if #available(iOS 10.0, *) {
UIApplication.shared.open(link.url!, options: [:], completionHandler: nil)
} else {
UIApplication.shared.openURL(link.url!)
}
}
actionSheetController.addAction(cancelActionButton)
cancelActionButton = UIAlertAction(title: "Share content", style: .default) { action -> Void in
let activityViewController: UIActivityViewController = UIActivityViewController(activityItems: [link.url!], applicationActivities: nil);
let currentViewController:UIViewController = UIApplication.shared.keyWindow!.rootViewController!
currentViewController.present(activityViewController, animated: true, completion: nil);
}
actionSheetController.addAction(cancelActionButton)
cancelActionButton = UIAlertAction(title: "Share comments", style: .default) { action -> Void in
let activityViewController: UIActivityViewController = UIActivityViewController(activityItems: [URL.init(string: "https://reddit.com" + link.permalink)!], applicationActivities: nil);
let currentViewController:UIViewController = UIApplication.shared.keyWindow!.rootViewController!
currentViewController.present(activityViewController, animated: true, completion: nil);
}
actionSheetController.addAction(cancelActionButton)
cancelActionButton = UIAlertAction(title: "Fiter this content", style: .default) { action -> Void in
self.showFilterMenu(link)
}
actionSheetController.addAction(cancelActionButton)
actionSheetController.modalPresentationStyle = .popover
if let presenter = actionSheetController.popoverPresentationController {
presenter.sourceView = cell.contentView
presenter.sourceRect = cell.contentView.bounds
}
self.present(actionSheetController, animated: true, completion: nil)
}
func report(_ thing: Object){
let alert = UIAlertController(title: "Report this content", message: "Enter a reason (not required)", preferredStyle: .alert)
alert.addTextField { (textField) in
textField.text = ""
}
alert.addAction(UIAlertAction(title: "Report", style: .destructive, handler: { [weak alert] (_) in
let textField = alert?.textFields![0] // Force unwrapping because we know it exists.
do {
let name = (thing is RComment) ? (thing as! RComment).name : (thing as! RSubmission).name
try self.session?.report(name, reason: (textField?.text!)!, otherReason: "", completion: { (result) in
DispatchQueue.main.async{
let message = MDCSnackbarMessage()
message.text = "Report sent"
MDCSnackbarManager.show(message)
}
})
} catch {
DispatchQueue.main.async{
let message = MDCSnackbarMessage()
message.text = "Error sending report"
MDCSnackbarManager.show(message)
}
}
}))
alert.addAction(UIAlertAction.init(title: "Cancel", style: .cancel, handler: nil))
self.present(alert, animated: true, completion: nil)
}
func showFilterMenu(_ link: RSubmission){
let actionSheetController: UIAlertController = UIAlertController(title: "What would you like to filter?", message: "", preferredStyle: .actionSheet)
var cancelActionButton: UIAlertAction = UIAlertAction(title: "Cancel", style: .cancel) { action -> Void in
print("Cancel")
}
actionSheetController.addAction(cancelActionButton)
cancelActionButton = UIAlertAction(title: "Posts by /u/\(link.author)", style: .default) { action -> Void in
PostFilter.profiles.append(link.author as NSString)
PostFilter.saveAndUpdate()
self.links = PostFilter.filter(self.links, previous: nil)
self.reloadDataReset()
}
actionSheetController.addAction(cancelActionButton)
cancelActionButton = UIAlertAction(title: "Posts from /r/\(link.subreddit)", style: .default) { action -> Void in
PostFilter.subreddits.append(link.subreddit as NSString)
PostFilter.saveAndUpdate()
self.links = PostFilter.filter(self.links, previous: nil)
self.reloadDataReset()
}
actionSheetController.addAction(cancelActionButton)
cancelActionButton = UIAlertAction(title: "Posts linking to \(link.domain)", style: .default) { action -> Void in
PostFilter.domains.append(link.domain as NSString)
PostFilter.saveAndUpdate()
self.links = PostFilter.filter(self.links, previous: nil)
self.reloadDataReset()
}
actionSheetController.addAction(cancelActionButton)
self.present(actionSheetController, animated: true, completion: nil)
}
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
tableView.collectionViewLayout.invalidateLayout()
super.viewWillTransition(to: size, with: coordinator)
}
var links: [RSubmission] = []
var paginator = Paginator()
var sub : String
var session: Session? = nil
var tableView : UICollectionView = UICollectionView.init(frame: CGRect.zero, collectionViewLayout: UICollectionViewLayout.init())
var displayMode: MenuItemDisplayMode
var single: Bool = false
/* override func previewActionItems() -> [UIPreviewActionItem] {
let regularAction = UIPreviewAction(title: "Regular", style: .Default) { (action: UIPreviewAction, vc: UIViewController) -> Void in
}
let destructiveAction = UIPreviewAction(title: "Destructive", style: .Destructive) { (action: UIPreviewAction, vc: UIViewController) -> Void in
}
let actionGroup = UIPreviewActionGroup(title: "Group...", style: .Default, actions: [regularAction, destructiveAction])
return [regularAction, destructiveAction, actionGroup]
}*/
init(subName: String, parent: SubredditsViewController){
sub = subName;
self.parentController = parent
displayMode = MenuItemDisplayMode.text(title: MenuItemText.init(text: sub, color: ColorUtil.fontColor, selectedColor: ColorUtil.fontColor, font: UIFont.boldSystemFont(ofSize: 16), selectedFont: UIFont.boldSystemFont(ofSize: 25)))
super.init(nibName:nil, bundle:nil)
setBarColors(color: ColorUtil.getColorForSub(sub: subName))
}
init(subName: String, single: Bool){
sub = subName
self.single = true
displayMode = MenuItemDisplayMode.text(title: MenuItemText.init(text: sub, color: ColorUtil.fontColor, selectedColor: ColorUtil.fontColor, font: UIFont.boldSystemFont(ofSize: 16), selectedFont: UIFont.boldSystemFont(ofSize: 25)))
super.init(nibName:nil, bundle:nil)
setBarColors(color: ColorUtil.getColorForSub(sub: subName))
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func show(_ animated: Bool = true) {
if(fab != nil){
if animated == true {
fab!.isHidden = false
UIView.animate(withDuration: 0.3, animations: { () -> Void in
self.fab!.alpha = 1
})
} else {
fab!.isHidden = false
}
}
}
func hideFab(_ animated: Bool = true) {
if(fab != nil){
if animated == true {
UIView.animate(withDuration: 0.3, animations: { () -> Void in
self.fab!.alpha = 0
}, completion: { finished in
self.fab!.isHidden = true
})
} else {
fab!.isHidden = true
}
}
}
var sideView: UIView = UIView()
var subb: UIButton = UIButton()
func drefresh(_ sender:AnyObject) {
load(reset: true)
}
var heightAtIndexPath = NSMutableDictionary()
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableViewAutomaticDimension
/*
if let height = heightAtIndexPath.object(forKey: indexPath) as? NSNumber {
return CGFloat(height.floatValue)
} else {
return UITableViewAutomaticDimension
}*/
}
func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
return true
}
var sideMenu: UISideMenuNavigationController?
// var menuNav: SubSidebarViewController?
var subInfo: Subreddit?
var flowLayout: WrappingFlowLayout = WrappingFlowLayout.init()
override func viewDidLoad() {
super.viewDidLoad()
flowLayout.delegate = self
self.tableView = UICollectionView(frame: self.view.bounds, collectionViewLayout: flowLayout)
self.view = UIView.init(frame: CGRect.zero)
self.view.addSubview(tableView)
self.tableView.delegate = self
self.tableView.dataSource = self
refreshControl = UIRefreshControl()
self.tableView.contentOffset = CGPoint.init(x: 0, y: -self.refreshControl.frame.size.height)
indicator = MDCActivityIndicator.init(frame: CGRect.init(x: CGFloat(0), y: CGFloat(0), width: CGFloat(80), height: CGFloat(80)))
indicator.strokeWidth = 5
indicator.radius = 20
indicator.indicatorMode = .indeterminate
indicator.cycleColors = [ColorUtil.getColorForSub(sub: sub), ColorUtil.accentColorForSub(sub: sub)]
indicator.center = self.tableView.center
self.tableView.addSubview(indicator)
indicator.startAnimating()
reloadNeedingColor()
if(!SettingValues.viewType || single){
tableView.contentInset = UIEdgeInsetsMake(40 + (single ? 70 : 40), 0, 0, 0)
}
if(single){
var swiper = SloppySwiper.init(navigationController: self.navigationController!)
self.navigationController!.delegate = swiper!
}
}
static var firstPresented = true
func reloadNeedingColor(){
tableView.backgroundColor = ColorUtil.backgroundColor
refreshControl.tintColor = ColorUtil.fontColor
refreshControl.attributedTitle = NSAttributedString(string: "")
refreshControl.addTarget(self, action: #selector(self.drefresh(_:)), for: UIControlEvents.valueChanged)
tableView.addSubview(refreshControl) // not required when using UITableViewController
let label = UILabel.init(frame: CGRect.init(x: 5, y: -1 * (single ? 90 : 60), width: 375, height: !SettingValues.viewType || single ? 70 : 40))
if(!SettingValues.viewType || single){
label.text = " \(sub)"
}
label.textColor = ColorUtil.fontColor
label.adjustsFontSizeToFitWidth = true
label.font = UIFont.boldSystemFont(ofSize: 35)
let shadowbox = UIButton.init(type: .custom)
shadowbox.setImage(UIImage.init(named: "shadowbox")?.withColor(tintColor: ColorUtil.fontColor), for: UIControlState.normal)
shadowbox.addTarget(self, action: #selector(self.shadowboxMode), for: UIControlEvents.touchUpInside)
shadowbox.frame = CGRect.init(x: 0, y: 20, width: 30, height: 30)
shadowbox.translatesAutoresizingMaskIntoConstraints = false
label.addSubview(shadowbox)
let sort = UIButton.init(type: .custom)
sort.setImage(UIImage.init(named: "ic_sort_white")?.withColor(tintColor: ColorUtil.fontColor), for: UIControlState.normal)
sort.addTarget(self, action: #selector(self.showMenu(_:)), for: UIControlEvents.touchUpInside)
sort.frame = CGRect.init(x: 0, y: 20, width: 30, height: 30)
sort.translatesAutoresizingMaskIntoConstraints = false
label.addSubview(sort)
let more = UIButton.init(type: .custom)
more.setImage(UIImage.init(named: "ic_more_vert_white")?.withColor(tintColor: ColorUtil.fontColor), for: UIControlState.normal)
more.addTarget(self, action: #selector(self.showMoreNone(_:)), for: UIControlEvents.touchUpInside)
more.frame = CGRect.init(x: 0, y: 20, width: 30, height: 30)
more.translatesAutoresizingMaskIntoConstraints = false
label.addSubview(more)
label.isUserInteractionEnabled = true
sort.isUserInteractionEnabled = true
more.isUserInteractionEnabled = true
subb = UIButton.init(type: .custom)
subb.setImage(UIImage.init(named: "addcircle")?.withColor(tintColor: ColorUtil.fontColor), for: UIControlState.normal)
subb.addTarget(self, action: #selector(self.subscribeSingle(_:)), for: UIControlEvents.touchUpInside)
subb.frame = CGRect.init(x: 0, y: 0, width: 25, height: 25)
subb.translatesAutoresizingMaskIntoConstraints = false
if(sub == "all" || sub == "frontpage" || sub == "friends" || sub == "popular" || sub.startsWith("/m/")){
subb.isHidden = true
}
label.addSubview(subb)
if(Subscriptions.isSubscriber(sub)){
subb.setImage(UIImage.init(named: "subbed")?.withColor(tintColor: ColorUtil.fontColor), for: UIControlState.normal)
}
add = MDCFloatingButton.init(shape: .default)
add.backgroundColor = ColorUtil.getColorForSub(sub: sub)
add.setImage(UIImage.init(named: "plus"), for: .normal)
add.sizeToFit()
add.translatesAutoresizingMaskIntoConstraints = false
self.view.addSubview(add)
hide = MDCFloatingButton.init(shape: .mini)
hide.backgroundColor = ColorUtil.accentColorForSub(sub: sub)
hide.setImage(UIImage.init(named: "hide")?.imageResize(sizeChange: CGSize.init(width: 20, height: 20)), for: .normal)
hide.sizeToFit()
hide.addTarget(self, action:#selector(self.hideAll(_:)), for: .touchUpInside)
hide.translatesAutoresizingMaskIntoConstraints = false
self.view.addSubview(hide)
sideView = UIView()
sideView = UIView(frame: CGRect(x: 0, y: 0, width: 8, height: CGFloat.greatestFiniteMagnitude))
sideView.backgroundColor = ColorUtil.getColorForSub(sub: sub)
sideView.translatesAutoresizingMaskIntoConstraints = false
label.addSubview(sideView)
let metrics=["topMargin": !SettingValues.viewType || single ? 20 : 5,"topMarginS":!SettingValues.viewType || single ? 22.5 : 7.5,"topMarginSS":!SettingValues.viewType || single ? 25 : 10]
let views=["more": more, "add": add, "hide": hide, "superview": view, "shadowbox":shadowbox, "sort":sort, "sub": subb, "side":sideView, "label" : label] as [String : Any]
var constraint:[NSLayoutConstraint] = []
constraint = NSLayoutConstraint.constraints(withVisualFormat: "V:[superview]-(<=1)-[add]",
options: NSLayoutFormatOptions.alignAllCenterX,
metrics: metrics,
views: views)
constraint.append(contentsOf: NSLayoutConstraint.constraints(withVisualFormat: "V:[add]-5-|",
options: NSLayoutFormatOptions(rawValue: 0),
metrics: metrics,
views: views))
constraint.append(contentsOf: NSLayoutConstraint.constraints(withVisualFormat: "V:[hide]-10-|",
options: NSLayoutFormatOptions(rawValue: 0),
metrics: metrics,
views: views))
constraint.append(contentsOf: NSLayoutConstraint.constraints(withVisualFormat: "H:[hide]-20-|",
options: NSLayoutFormatOptions(rawValue: 0),
metrics: metrics,
views: views))
self.view.addConstraints(constraint)
constraint = NSLayoutConstraint.constraints(withVisualFormat: "H:|-8-[side(20)]-8-[label]",
options: NSLayoutFormatOptions(rawValue: 0),
metrics: metrics,
views: views)
constraint.append(contentsOf: NSLayoutConstraint.constraints(withVisualFormat: "H:[sub(25)]-8-[shadowbox(30)]-4-[sort]-4-[more]-8-|",
options: NSLayoutFormatOptions(rawValue: 0),
metrics: metrics,
views: views))
constraint.append(contentsOf:NSLayoutConstraint.constraints(withVisualFormat: "V:|-(topMargin)-[more]-(topMargin)-|",
options: NSLayoutFormatOptions(rawValue: 0),
metrics: metrics,
views: views))
constraint.append(contentsOf:NSLayoutConstraint.constraints(withVisualFormat: "V:|-(topMargin)-[shadowbox]-(topMargin)-|",
options: NSLayoutFormatOptions(rawValue: 0),
metrics: metrics,
views: views))
constraint.append(contentsOf:NSLayoutConstraint.constraints(withVisualFormat: "V:|-(topMarginS)-[sub(25)]-(topMarginS)-|",
options: NSLayoutFormatOptions(rawValue: 0),
metrics: metrics,
views: views))
constraint.append(contentsOf:NSLayoutConstraint.constraints(withVisualFormat: "V:|-(topMargin)-[sort]-(topMargin)-|",
options: NSLayoutFormatOptions(rawValue: 0),
metrics: metrics,
views: views))
constraint.append(contentsOf:NSLayoutConstraint.constraints(withVisualFormat: "V:|-(topMarginSS)-[side(20)]-(topMarginSS)-|",
options: NSLayoutFormatOptions(rawValue: 0),
metrics: metrics,
views: views))
label.addConstraints(constraint)
sideView.layer.cornerRadius = 10
sideView.clipsToBounds = true
tableView.addSubview(label)
self.automaticallyAdjustsScrollViewInsets = false
self.tableView.register(BannerLinkCellView.classForCoder(), forCellWithReuseIdentifier: "banner")
self.tableView.register(ThumbnailLinkCellView.classForCoder(), forCellWithReuseIdentifier: "thumb")
self.tableView.register(TextLinkCellView.classForCoder(), forCellWithReuseIdentifier: "text")
session = (UIApplication.shared.delegate as! AppDelegate).session
if (SubredditLinkViewController.firstPresented && !single) || (self.links.count == 0 && !single && !SettingValues.viewType) {
load(reset: true)
SubredditLinkViewController.firstPresented = false
}
if(single){
sideMenu = UISideMenuNavigationController()
do {
try (UIApplication.shared.delegate as! AppDelegate).session?.about(sub, completion: { (result) in
switch result {
case .failure:
print(result.error!.description)
DispatchQueue.main.async {
if(self.sub == ("all") || self.sub == ("frontpage") || self.sub.hasPrefix("/m/") || self.sub.contains("+")){
self.load(reset: true)
} else {
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 2) {
let alert = UIAlertController.init(title: "Subreddit not found", message: "/r/\(self.sub) could not be found, is it spelled correctly?", preferredStyle: .alert)
alert.addAction(UIAlertAction.init(title: "Close", style: .default, handler: { (_) in
self.navigationController?.popViewController(animated: true)
self.dismiss(animated: true, completion: nil)
}))
self.present(alert, animated: true, completion: nil)
}
}
}
case .success(let r):
self.subInfo = r
DispatchQueue.main.async {
if(self.subInfo!.over18 && !SettingValues.nsfwEnabled){
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 2) {
let alert = UIAlertController.init(title: "/r/\(self.sub) is NSFW", message: "If you are 18 and willing to see adult content, enable NSFW content in Settings > Content", preferredStyle: .alert)
alert.addAction(UIAlertAction.init(title: "Close", style: .default, handler: { (_) in
self.navigationController?.popViewController(animated: true)
self.dismiss(animated: true, completion: nil)
}))
self.present(alert, animated: true, completion: nil)
}
} else {
if(self.sub != ("all") && self.sub != ("frontpage") && !self.sub.hasPrefix("/m/")){
if(SettingValues.saveHistory){
if(SettingValues.saveNSFWHistory && self.subInfo!.over18){
Subscriptions.addHistorySub(name: AccountController.currentName, sub: self.subInfo!.displayName)
} else if(!self.subInfo!.over18){
Subscriptions.addHistorySub(name: AccountController.currentName, sub: self.subInfo!.displayName)
}
}
}
print("Loading")
self.load(reset: true)
}
}
}
})
} catch {
}
}
if(false && SettingValues.hiddenFAB){
fab = KCFloatingActionButton()
fab!.buttonColor = ColorUtil.accentColorForSub(sub: sub)
fab!.buttonImage = UIImage.init(named: "hide")?.imageResize(sizeChange: CGSize.init(width: 30, height: 30))
fab!.fabDelegate = self
fab!.sticky = true
self.view.addSubview(fab!)
}
}
var lastY: CGFloat = CGFloat(0)
var add : MDCFloatingButton = MDCFloatingButton()
var hide : MDCFloatingButton = MDCFloatingButton()
var lastYUsed = CGFloat(0)
func hideAll(_ sender: AnyObject){
for submission in links {
if(History.getSeen(s: submission)){
let index = links.index(of: submission)!
links.remove(at: index)
}
}
tableView.reloadData()
self.flowLayout.reset()
}
func doDisplayMultiSidebar(_ sub: Multireddit){
let alrController = UIAlertController(title: sub.displayName, message: sub.descriptionMd, preferredStyle: UIAlertControllerStyle.actionSheet)
for s in sub.subreddits {
let somethingAction = UIAlertAction(title: "/r/" + s, style: UIAlertActionStyle.default, handler: {(alert: UIAlertAction!) in
self.show(SubredditLinkViewController.init(subName: s, single: true), sender: self)
})
let color = ColorUtil.getColorForSub(sub: s)
if(color != ColorUtil.baseColor){
somethingAction.setValue(color, forKey: "titleTextColor")
}
alrController.addAction(somethingAction)
}
var somethingAction = UIAlertAction(title: "Edit multireddit", style: UIAlertActionStyle.default, handler: {(alert: UIAlertAction!) in print("something")})
alrController.addAction(somethingAction)
somethingAction = UIAlertAction(title: "Delete multireddit", style: UIAlertActionStyle.destructive, handler: {(alert: UIAlertAction!) in print("something")})
alrController.addAction(somethingAction)
let cancelAction = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.cancel, handler: {(alert: UIAlertAction!) in print("cancel")})
alrController.addAction(cancelAction)
self.present(alrController, animated: true, completion:{})
}
func subscribeSingle(_ selector: AnyObject){
if(subChanged && !Subscriptions.isSubscriber(sub) || Subscriptions.isSubscriber(sub)){
//was not subscriber, changed, and unsubscribing again
Subscriptions.unsubscribe(sub, session: session!)
subChanged = false
let message = MDCSnackbarMessage()
message.text = "Unsubscribed"
MDCSnackbarManager.show(message)
subb.setImage(UIImage.init(named: "addcircle")?.withColor(tintColor: ColorUtil.fontColor), for: UIControlState.normal)
} else {
let alrController = UIAlertController.init(title: "Subscribe to \(sub)", message: nil, preferredStyle: .actionSheet)
if(AccountController.isLoggedIn){
let somethingAction = UIAlertAction(title: "Add to sub list and subscribe", style: UIAlertActionStyle.default, handler: {(alert: UIAlertAction!) in
Subscriptions.subscribe(self.sub, true, session: self.session!)
self.subChanged = true
let message = MDCSnackbarMessage()
message.text = "Subscribed"
MDCSnackbarManager.show(message)
self.subb.setImage(UIImage.init(named: "subbed")?.withColor(tintColor: ColorUtil.fontColor), for: UIControlState.normal)
})
alrController.addAction(somethingAction)
}
let somethingAction = UIAlertAction(title: "Add to sub list", style: UIAlertActionStyle.default, handler: {(alert: UIAlertAction!) in
Subscriptions.subscribe(self.sub, false, session: self.session!)
self.subChanged = true
let message = MDCSnackbarMessage()
message.text = "Added"
MDCSnackbarManager.show(message)
self.subb.setImage(UIImage.init(named: "subbed")?.withColor(tintColor: ColorUtil.fontColor), for: UIControlState.normal)
})
alrController.addAction(somethingAction)
let cancelAction = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.cancel, handler: {(alert: UIAlertAction!) in print("cancel")})
alrController.addAction(cancelAction)
alrController.modalPresentationStyle = .fullScreen
if let presenter = alrController.popoverPresentationController {
presenter.sourceView = subb
presenter.sourceRect = subb.bounds
}
self.present(alrController, animated: true, completion:{})
}
}
func displayMultiredditSidebar(){
do {
print("Getting \(sub.substring(3, length: sub.length - 3))")
try (UIApplication.shared.delegate as! AppDelegate).session?.getMultireddit(Multireddit.init(name: sub.substring(3, length: sub.length - 3), user: AccountController.currentName), completion: { (result) in
switch result {
case .success(let r):
DispatchQueue.main.async {
self.doDisplayMultiSidebar(r)
}
default:
DispatchQueue.main.async{
let message = MDCSnackbarMessage()
message.text = "Multireddit info not found"
MDCSnackbarManager.show(message)
}
break
}
})
} catch {
}
}
var listingId: String = "" //a random id for use in Realm
func emptyKCFABSelected(_ fab: KCFloatingActionButton) {
var indexPaths : [IndexPath] = []
var newLinks : [RSubmission] = []
var count = 0
for submission in links {
if(History.getSeen(s: submission)){
indexPaths.append(IndexPath(row: count, section: 0))
} else {
newLinks.append(submission)
}
count += 1
}
links = newLinks
//todo save realm
tableView.deleteItems(at: indexPaths)
print("Empty")
}
var fab : KCFloatingActionButton?
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
UIApplication.shared.statusBarStyle = .lightContent
if(navigationController?.isNavigationBarHidden ?? false && single){
navigationController?.setNavigationBarHidden(false, animated: true)
}
}
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
let height = NSNumber(value: Float(cell.frame.size.height))
heightAtIndexPath.setObject(height, forKey: indexPath as NSCopying)
}
func pickTheme(parent: SubredditsViewController?){
parentController = parent
let alertController = UIAlertController(title: "\n\n\n\n\n\n", message: nil, preferredStyle: UIAlertControllerStyle.actionSheet)
let margin:CGFloat = 10.0
let rect = CGRect(x: margin, y: margin, width: alertController.view.bounds.size.width - margin * 4.0, height: 120)
let customView = ColorPicker(frame: rect)
customView.delegate = self
customView.backgroundColor = ColorUtil.backgroundColor
alertController.view.addSubview(customView)
let somethingAction = UIAlertAction(title: "Save", style: .default, handler: {(alert: UIAlertAction!) in
ColorUtil.setColorForSub(sub: self.sub, color: (self.navigationController?.navigationBar.barTintColor)!)
self.reloadDataReset()
})
let accentAction = UIAlertAction(title: "Accent color", style: .default, handler: {(alert: UIAlertAction!) in
ColorUtil.setColorForSub(sub: self.sub, color: (self.navigationController?.navigationBar.barTintColor)!)
self.pickAccent(parent: parent)
self.reloadDataReset()
})
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: {(alert: UIAlertAction!) in
if(parent != nil){
parent?.resetColors()
}
})
alertController.addAction(accentAction)
alertController.addAction(somethingAction)
alertController.addAction(cancelAction)
present(alertController, animated: true, completion: nil)
}
func pickAccent(parent: SubredditsViewController?){
parentController = parent
let alertController = UIAlertController(title: "\n\n\n\n\n\n", message: nil, preferredStyle: UIAlertControllerStyle.actionSheet)
let margin:CGFloat = 10.0
let rect = CGRect(x: margin, y: margin, width: alertController.view.bounds.size.width - margin * 4.0, height: 120)
let customView = ColorPicker(frame: rect)
customView.setAccent(accent: true)
customView.delegate = self
customView.backgroundColor = ColorUtil.backgroundColor
alertController.view.addSubview(customView)
let somethingAction = UIAlertAction(title: "Save", style: .default, handler: {(alert: UIAlertAction!) in
if self.accentChosen != nil {
ColorUtil.setAccentColorForSub(sub: self.sub, color: self.accentChosen!)
}
self.reloadDataReset()
})
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: {(alert: UIAlertAction!) in
if(parent != nil){
parent?.resetColors()
self.sideView.backgroundColor = ColorUtil.getColorForSub(sub: self.sub)
self.add.backgroundColor = ColorUtil.getColorForSub(sub: self.sub)
self.hide.backgroundColor = ColorUtil.accentColorForSub(sub: self.sub)
}
})
alertController.addAction(somethingAction)
alertController.addAction(cancelAction)
present(alertController, animated: true, completion: nil)
}
var first = true
var indicator: MDCActivityIndicator = MDCActivityIndicator()
override func viewWillAppear(_ animated: Bool) {
if(SubredditReorderViewController.changed){
self.reloadNeedingColor()
self.tableView.reloadData()
SubredditReorderViewController.changed = false
}
navigationController?.navigationBar.isTranslucent = false
self.navigationController?.delegate = self
self.automaticallyAdjustsScrollViewInsets = false
self.edgesForExtendedLayout = UIRectEdge.all
self.extendedLayoutIncludesOpaqueBars = true
self.navigationController?.interactivePopGestureRecognizer?.delegate = self
first = false
tableView.delegate = self
if(single){
self.navigationController?.navigationBar.barTintColor = UIColor.white
if(navigationController != nil){
self.title = sub
let sort = UIButton.init(type: .custom)
sort.setImage(UIImage.init(named: "ic_sort_white"), for: UIControlState.normal)
sort.addTarget(self, action: #selector(self.showMenu(_:)), for: UIControlEvents.touchUpInside)
sort.frame = CGRect.init(x: 0, y: 0, width: 30, height: 30)
let sortB = UIBarButtonItem.init(customView: sort)
let more = UIButton.init(type: .custom)
more.setImage(UIImage.init(named: "ic_more_vert_white"), for: UIControlState.normal)
more.addTarget(self, action: #selector(self.showMoreNone(_:)), for: UIControlEvents.touchUpInside)
more.frame = CGRect.init(x: -15, y: 0, width: 30, height: 30)
let moreB = UIBarButtonItem.init(customView: more)
navigationItem.rightBarButtonItems = [ moreB, sortB]
} else if parentController != nil && parentController?.navigationController != nil{
parentController?.navigationController?.title = sub
let sort = UIButton.init(type: .custom)
sort.setImage(UIImage.init(named: "ic_sort_white"), for: UIControlState.normal)
sort.addTarget(self, action: #selector(self.showMenu(_:)), for: UIControlEvents.touchUpInside)
sort.frame = CGRect.init(x: 0, y: 0, width: 30, height: 30)
let sortB = UIBarButtonItem.init(customView: sort)
let more = UIButton.init(type: .custom)
more.setImage(UIImage.init(named: "ic_more_vert_white"), for: UIControlState.normal)
more.addTarget(self, action: #selector(self.showMoreNone(_:)), for: UIControlEvents.touchUpInside)
more.frame = CGRect.init(x: -15, y: 0, width: 30, height: 30)
let moreB = UIBarButtonItem.init(customView: more)
parentController?.navigationItem.rightBarButtonItems = [ moreB, sortB]
}
}
super.viewWillAppear(animated)
if(savedIndex != nil){
tableView.reloadItems(at: [savedIndex!])
} else {
tableView.reloadData()
}
(navigationController)?.setNavigationBarHidden(true, animated: true)
if(ColorUtil.theme == .LIGHT || ColorUtil.theme == .SEPIA){
UIApplication.shared.statusBarStyle = .default
}
}
func reloadDataReset(){
heightAtIndexPath.removeAllObjects()
tableView.reloadData()
}
func showMoreNone(_ sender: AnyObject){
showMore(sender, parentVC: nil)
}
func search(){
let alert = UIAlertController(title: "Search", message: "", preferredStyle: .alert)
alert.addTextField { (textField) in
textField.text = ""
}
alert.addAction(UIAlertAction(title: "Search All", style: .default, handler: { [weak alert] (_) in
let textField = alert?.textFields![0] // Force unwrapping because we know it exists.
let search = SearchViewController.init(subreddit: "all", searchFor: (textField?.text!)!)
self.parentController?.show(search, sender: self.parentController)
}))
if(sub != "all" && sub != "frontpage" && sub != "friends" && !sub.startsWith("/m/")){
alert.addAction(UIAlertAction(title: "Search \(sub)", style: .default, handler: { [weak alert] (_) in
let textField = alert?.textFields![0] // Force unwrapping because we know it exists.
let search = SearchViewController.init(subreddit: self.sub, searchFor: (textField?.text!)!)
self.parentController?.show(search, sender: self.parentController)
}))
}
alert.addAction(UIAlertAction.init(title: "Cancel", style: .cancel, handler: nil))
parentController?.present(alert, animated: true, completion: nil)
}
func showMore(_ sender: AnyObject, parentVC: SubredditsViewController? = nil){
let actionSheetController: UIAlertController = UIAlertController(title: "", message: "", preferredStyle: .actionSheet)
var cancelActionButton: UIAlertAction = UIAlertAction(title: "Cancel", style: .cancel) { action -> Void in
print("Cancel")
}
actionSheetController.addAction(cancelActionButton)
cancelActionButton = UIAlertAction(title: "Search", style: .default) { action -> Void in
self.search()
}
actionSheetController.addAction(cancelActionButton)
if(sub.contains("/m/")){
cancelActionButton = UIAlertAction(title: "Manage multireddit", style: .default) { action -> Void in
self.displayMultiredditSidebar()
}
} else {
cancelActionButton = UIAlertAction(title: "Sidebar", style: .default) { action -> Void in
Sidebar.init(parent: self, subname: self.sub).displaySidebar()
}
}
actionSheetController.addAction(cancelActionButton)
cancelActionButton = UIAlertAction(title: "Refresh", style: .default) { action -> Void in
self.refresh()
}
actionSheetController.addAction(cancelActionButton)
cancelActionButton = UIAlertAction(title: "Gallery mode", style: .default) { action -> Void in
self.galleryMode()
}
actionSheetController.addAction(cancelActionButton)
cancelActionButton = UIAlertAction(title: "Shadowbox mode", style: .default) { action -> Void in
self.shadowboxMode()
}
actionSheetController.addAction(cancelActionButton)
cancelActionButton = UIAlertAction(title: "Subreddit Theme", style: .default) { action -> Void in
if(parentVC != nil){
let p = (parentVC!)
self.pickTheme(parent: p)
} else {
self.pickTheme(parent: nil)
}
}
actionSheetController.addAction(cancelActionButton)
if(!single){
cancelActionButton = UIAlertAction(title: "Base Theme", style: .default) { action -> Void in
if(parentVC != nil){
(parentVC)!.showThemeMenu()
}
}
actionSheetController.addAction(cancelActionButton)
}
cancelActionButton = UIAlertAction(title: "Filter", style: .default) { action -> Void in
print("Filter")
}
actionSheetController.addAction(cancelActionButton)
actionSheetController.modalPresentationStyle = .fullScreen
if let presenter = actionSheetController.popoverPresentationController {
presenter.sourceView = self.view
presenter.sourceRect = self.view.bounds
}
actionSheetController.modalPresentationStyle = .popover
if let presenter = actionSheetController.popoverPresentationController {
presenter.sourceView = subb
presenter.sourceRect = subb.bounds
}
self.present(actionSheetController, animated: true, completion: nil)
}
func galleryMode(){
let controller = GalleryTableViewController()
var gLinks:[RSubmission] = []
for l in links{
if l.banner {
gLinks.append(l)
}
}
controller.setLinks(links: gLinks)
show(controller, sender: self)
}
func shadowboxMode(){
var gLinks:[RSubmission] = []
for l in links{
if l.banner {
gLinks.append(l)
}
}
let controller = ShadowboxViewController.init(submissions: gLinks)
controller.modalPresentationStyle = .overCurrentContext
present(controller, animated: true, completion: nil)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return links.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
var target = CurrentType.none
let submission = self.links[(indexPath as NSIndexPath).row]
var thumb = submission.thumbnail
var big = submission.banner
let height = submission.height
var type = ContentType.getContentType(baseUrl: submission.url!)
if(submission.isSelf){
type = .SELF
}
if(SettingValues.bannerHidden){
big = false
thumb = true
}
let fullImage = ContentType.fullImage(t: type)
if(!fullImage && height < 50){
big = false
thumb = true
}
if(type == .SELF && SettingValues.hideImageSelftext || SettingValues.hideImageSelftext && !big){
big = false
thumb = false
}
if(height < 50){
thumb = true
big = false
}
if (type == ContentType.CType.SELF && SettingValues.hideImageSelftext
|| SettingValues.noImages && submission.isSelf) {
big = false
thumb = false
}
if(big || !submission.thumbnail){
thumb = false
}
if(!big && !thumb && submission.type != .SELF && submission.type != .NONE){ //If a submission has a link but no images, still show the web thumbnail
thumb = true
}
if(submission.nsfw && (!SettingValues.nsfwPreviews || SettingValues.hideNSFWCollection && (sub == "all" || sub == "frontpage" || sub.contains("/m/") || sub.contains("+") || sub == "popular"))){
big = false
thumb = true
}
if(SettingValues.noImages){
big = false
thumb = false
}
if(thumb && type == .SELF){
thumb = false
}
if(thumb && !big){
target = .thumb
} else if(big){
target = .banner
} else {
target = .text
}
var cell: LinkCellView?
if(target == .thumb){
cell = tableView.dequeueReusableCell(withReuseIdentifier: "thumb", for: indexPath) as! ThumbnailLinkCellView
} else if(target == .banner){
cell = tableView.dequeueReusableCell(withReuseIdentifier: "banner", for: indexPath) as! BannerLinkCellView
} else {
cell = tableView.dequeueReusableCell(withReuseIdentifier: "text", for: indexPath) as! TextLinkCellView
}
cell?.preservesSuperviewLayoutMargins = false
cell?.del = self
if indexPath.row == self.links.count - 1 && !loading && !nomore {
self.loadMore()
}
(cell)!.setLink(submission: submission, parent: self, nav: self.navigationController, baseSub: sub)
cell?.layer.shouldRasterize = true
cell?.layer.rasterizationScale = UIScreen.main.scale
return cell!
}
var loading = false
var nomore = false
func loadMore(){
if(!showing){
showLoader()
}
load(reset: false)
}
var showing = false
func showLoader() {
showing = true
//todo maybe?
}
var sort = SettingValues.defaultSorting
var time = SettingValues.defaultTimePeriod
func showMenu(_ selector: AnyObject){
let actionSheetController: UIAlertController = UIAlertController(title: "Sorting", message: "", preferredStyle: .actionSheet)
let cancelActionButton: UIAlertAction = UIAlertAction(title: "Cancel", style: .cancel) { action -> Void in
print("Cancel")
}
actionSheetController.addAction(cancelActionButton)
for link in LinkSortType.cases {
let saveActionButton: UIAlertAction = UIAlertAction(title: link.description, style: .default)
{ action -> Void in
self.showTimeMenu(s: link)
}
actionSheetController.addAction(saveActionButton)
}
self.present(actionSheetController, animated: true, completion: nil)
}
func showTimeMenu(s: LinkSortType){
if(s == .hot || s == .new){
sort = s
refresh()
return
} else {
let actionSheetController: UIAlertController = UIAlertController(title: "Sorting", message: "", preferredStyle: .actionSheet)
let cancelActionButton: UIAlertAction = UIAlertAction(title: "Cancel", style: .cancel) { action -> Void in
print("Cancel")
}
actionSheetController.addAction(cancelActionButton)
for t in TimeFilterWithin.cases {
let saveActionButton: UIAlertAction = UIAlertAction(title: t.param, style: .default)
{ action -> Void in
print("Sort is \(s) and time is \(t)")
self.sort = s
self.time = t
self.refresh()
}
actionSheetController.addAction(saveActionButton)
}
self.present(actionSheetController, animated: true, completion: nil)
}
}
var refreshControl: UIRefreshControl!
func refresh(){
self.links = []
load(reset: true)
}
var savedIndex: IndexPath?
var realmListing: RListing?
func load(reset: Bool){
if(!loading){
do {
loading = true
if(reset){
paginator = Paginator()
}
var subreddit: SubredditURLPath = Subreddit.init(subreddit: sub)
if(sub.hasPrefix("/m/")){
subreddit = Multireddit.init(name: sub.substring(3, length: sub.length - 3), user: AccountController.currentName)
}
print("Sort is \(self.sort) and time is \(self.time)")
try session?.getList(paginator, subreddit: subreddit, sort: sort, timeFilterWithin: time, completion: { (result) in
switch result {
case .failure:
//test if realm exists and show that
DispatchQueue.main.async {
print("Getting realm data")
do {
let realm = try Realm()
var updated = NSDate()
if let listing = realm.objects(RListing.self).filter({ (item) -> Bool in
return item.subreddit == self.sub
}).first {
self.links = []
for i in listing.links {
self.links.append(i)
}
updated = listing.updated
self.flowLayout.reset()
self.reloadDataReset()
}
self.refreshControl.endRefreshing()
self.indicator.stopAnimating()
self.loading = false
if(self.links.isEmpty){
let message = MDCSnackbarMessage()
message.text = "No offline content found"
MDCSnackbarManager.show(message)
} else {
let message = MDCSnackbarMessage()
message.text = "Showing offline content (\(DateFormatter().timeSince(from: updated, numericDates: true)))"
MDCSnackbarManager.show(message)
}
} catch {
}
}
print(result.error!)
case .success(let listing):
if(reset){
self.links = []
}
let before = self.links.count
if(self.realmListing == nil){
self.realmListing = RListing()
self.realmListing!.subreddit = self.sub
self.realmListing!.updated = NSDate()
}
if(reset && self.realmListing!.links.count > 0){
self.realmListing!.links.removeAll()
}
let links = listing.children.flatMap({$0 as? Link})
var converted : [RSubmission] = []
for link in links {
let newRS = RealmDataWrapper.linkToRSubmission(submission: link)
converted.append(newRS)
CachedTitle.addTitle(s: newRS)
}
let values = PostFilter.filter(converted, previous: self.links)
self.links += values
self.paginator = listing.paginator
self.nomore = !listing.paginator.hasMore() || values.isEmpty
DispatchQueue.main.async{
do {
let realm = try! Realm()
//todo insert
realm.beginWrite()
for submission in self.links {
realm.create(type(of: submission), value: submission, update: true)
self.realmListing!.links.append(submission)
}
realm.create(type(of: self.realmListing!), value: self.realmListing!, update: true)
try realm.commitWrite()
} catch {
}
//todo if(reset){
self.tableView.reloadData()
self.flowLayout.reset()
//} else {
// var paths : [IndexPath] = []
// self.tableView.performBatchUpdates({
// for i in (before)...(self.links.count - 1) {
// self.tableView.insertItems(at: [IndexPath.init(row: i, section: 0)])
// }
// }, completion: nil)
//}
self.refreshControl.endRefreshing()
self.indicator.stopAnimating()
self.loading = false
}
}
})
} catch {
print(error)
}
}
}
func preloadImages(_ values: [RSubmission]){
var urls : [URL] = []
for submission in values {
var thumb = submission.thumbnail
var big = submission.banner
var height = submission.height
var type = ContentType.getContentType(baseUrl: submission.url!)
if(submission.isSelf){
type = .SELF
}
if(thumb && type == .SELF){
thumb = false
}
let fullImage = ContentType.fullImage(t: type)
if(!fullImage && height < 50){
big = false
thumb = true
} else if(big && (SettingValues.bigPicCropped)){
height = 200
}
if(type == .SELF && SettingValues.hideImageSelftext || SettingValues.hideImageSelftext && !big || type == .SELF ){
big = false
thumb = false
}
if(height < 50){
thumb = true
big = false
}
let shouldShowLq = SettingValues.dataSavingEnabled && submission.lQ && !(SettingValues.dataSavingDisableWiFi && LinkCellView.checkWiFi())
if (type == ContentType.CType.SELF && SettingValues.hideImageSelftext
|| SettingValues.noImages && submission.isSelf) {
big = false
thumb = false
}
if(big || !submission.thumbnail){
thumb = false
}
if(!big && !thumb && submission.type != .SELF && submission.type != .NONE){
thumb = true
}
if(thumb && !big){
if(submission.thumbnailUrl == "nsfw"){
} else if(submission.thumbnailUrl == "web" || submission.thumbnailUrl.isEmpty){
} else {
if let url = URL.init(string: submission.thumbnailUrl) {
urls.append(url)
}
}
}
if(big){
if(shouldShowLq){
if let url = URL.init(string: submission.lqUrl) {
urls.append(url)
}
} else {
if let url = URL.init(string: submission.bannerUrl) {
urls.append(url)
}
}
}
}
SDWebImagePrefetcher.init().prefetchURLs(urls)
}
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
tableView.frame = self.view.bounds
flowLayout.invalidateLayout()
}
}
extension UIViewController {
func topMostViewController() -> UIViewController {
// Handling Modal views/Users/carloscrane/Desktop/Slide for Reddit/Slide for Reddit/SettingValues.swift
if let presentedViewController = self.presentedViewController {
return presentedViewController.topMostViewController()
}
// Handling UIViewController's added as subviews to some other views.
else {
for view in self.view.subviews
{
// Key property which most of us are unaware of / rarely use.
if let subViewController = view.next {
if subViewController is UIViewController {
let viewController = subViewController as! UIViewController
return viewController.topMostViewController()
}
}
}
return self
}
}
}
extension UITabBarController {
override func topMostViewController() -> UIViewController {
return self.selectedViewController!.topMostViewController()
}
}
extension UINavigationController {
override func topMostViewController() -> UIViewController {
return self.visibleViewController!.topMostViewController()
}
}
extension UILabel {
func fitFontForSize( minFontSize : CGFloat = 5.0, maxFontSize : CGFloat = 300.0, accuracy : CGFloat = 1.0) {
var minFontSize = minFontSize
var maxFontSize = maxFontSize
assert(maxFontSize > minFontSize)
layoutIfNeeded()
let constrainedSize = bounds.size
while maxFontSize - minFontSize > accuracy {
let midFontSize : CGFloat = ((minFontSize + maxFontSize) / 2)
font = font.withSize(midFontSize)
sizeToFit()
let checkSize : CGSize = bounds.size
if checkSize.height < constrainedSize.height && checkSize.width < constrainedSize.width {
minFontSize = midFontSize
} else {
maxFontSize = midFontSize
}
}
font = font.withSize(minFontSize)
sizeToFit()
layoutIfNeeded()
}
}
| f89a9fb6615ae6c3a472381eed32f6ea | 42.71648 | 289 | 0.549816 | false | false | false | false |
DragonCherry/AssetsPickerViewController | refs/heads/master | Example/AssetsPickerViewController/ExampleUsages/CustomAssetCellController.swift | mit | 1 | //
// CustomAssetCellController.swift
// AssetsPickerViewController
//
// Created by DragonCherry on 5/31/17.
// Copyright © 2017 CocoaPods. All rights reserved.
//
import UIKit
import Photos
import AssetsPickerViewController
class CustomAssetCellOverlay: UIView {
private let countSize = CGSize(width: 40, height: 40)
lazy var circleView: UIView = {
let view = UIView()
view.backgroundColor = .black
view.layer.cornerRadius = self.countSize.width / 2
view.alpha = 0.4
return view
}()
let countLabel: UILabel = {
let label = UILabel()
let font = UIFont.preferredFont(forTextStyle: .headline)
label.font = UIFont.systemFont(ofSize: font.pointSize, weight: UIFont.Weight.bold)
label.textAlignment = .center
label.textColor = .white
label.adjustsFontSizeToFitWidth = true
return label
}()
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
private func commonInit() {
dmr_dim(animated: false, color: .white, alpha: 0.25)
addSubview(circleView)
addSubview(countLabel)
circleView.snp.makeConstraints { (make) in
make.size.equalTo(countSize)
make.center.equalToSuperview()
}
countLabel.snp.makeConstraints { (make) in
make.size.equalTo(countSize)
make.center.equalToSuperview()
}
}
}
class CustomAssetCell: UICollectionViewCell, AssetsPhotoCellProtocol {
// MARK: - AssetsAlbumCellProtocol
var asset: PHAsset? {
didSet {}
}
var isVideo: Bool = false {
didSet {
durationLabel.isHidden = !isVideo
}
}
override var isSelected: Bool {
didSet { overlay.isHidden = !isSelected }
}
var imageView: UIImageView = {
let view = UIImageView()
view.clipsToBounds = true
view.contentMode = .scaleAspectFill
view.backgroundColor = UIColor(rgbHex: 0xF0F0F0)
return view
}()
var count: Int = 0 {
didSet { overlay.countLabel.text = "\(count)" }
}
var duration: TimeInterval = 0 {
didSet {
let hour = Int(duration / 3600)
let min = Int((duration / 60).truncatingRemainder(dividingBy: 60))
let sec = Int(duration.truncatingRemainder(dividingBy: 60))
var durationString = hour > 0 ? "\(hour)" : ""
durationString.append(min > 0 ? "\(min):" : "0:")
durationString.append(String(format: "%02d", sec))
durationLabel.text = durationString
}
}
// MARK: - At your service
let overlay: CustomAssetCellOverlay = {
let view = CustomAssetCellOverlay()
view.isHidden = true
return view
}()
private let durationLabel: UILabel = {
let label = UILabel()
label.textColor = .white
label.textAlignment = .right
label.font = UIFont.boldSystemFont(ofSize: 20)
return label
}()
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
private func commonInit() {
contentView.addSubview(imageView)
contentView.addSubview(overlay)
contentView.addSubview(durationLabel)
imageView.snp.makeConstraints { (make) in
make.edges.equalToSuperview()
}
overlay.snp.makeConstraints { (make) in
make.edges.equalToSuperview()
}
durationLabel.snp.makeConstraints { (make) in
make.height.equalTo(durationLabel.font.pointSize + 10)
make.leading.equalToSuperview().offset(8)
make.trailing.equalToSuperview().inset(8)
make.bottom.equalToSuperview()
}
}
}
class CustomAssetCellController: CommonExampleController {
override func pressedPick(_ sender: Any) {
let pickerConfig = AssetsPickerConfig()
pickerConfig.assetCellType = CustomAssetCell.classForCoder()
pickerConfig.assetPortraitColumnCount = 3
pickerConfig.assetLandscapeColumnCount = 5
pickerConfig.assetsMaximumSelectionCount = 10
let picker = AssetsPickerViewController()
picker.pickerConfig = pickerConfig
picker.pickerDelegate = self
present(picker, animated: true, completion: nil)
}
}
| 32251ce305c458b936ee9364b4654164 | 27.907975 | 90 | 0.602716 | false | false | false | false |
cdtschange/SwiftMKit | refs/heads/master | SwiftMKit/UI/View/TextField/NoMenuTextField.swift | mit | 1 | //
// NoMenuTextField.swift
// Merak
//
// Created by Mao on 6/23/16.
// Copyright © 2016. All rights reserved.
//
import Foundation
import UIKit
public class NoMenuTextField: UITextField {
public override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
if action == #selector(UIResponder.paste(_:)) || action == #selector(UIResponder.copy(_:)) || action == #selector(UIResponder.selectAll(_:)) || action == #selector(UIResponder.select(_:)) {
return false
}
return super.canPerformAction(action, withSender: sender)
}
}
public class NoPasteTextField: UITextField {
public override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
if action == #selector(UIResponder.paste(_:)) {
return false
}
return super.canPerformAction(action, withSender: sender)
}
}
| c4aa2f24005d97858ffd91d0c01640b9 | 30.655172 | 197 | 0.649237 | false | false | false | false |
mumbler/PReVo-iOS | refs/heads/trunk | ReVoDatumbazo/Komunaj/ModelAldonoj/Mallongigo+ReVoDatumbazo.swift | mit | 1 | //
// Mallongigo+ReVoDatumbazo.swift
// ReVoDatumbazo
//
// Created by Robin Hill on 7/4/20.
// Copyright © 2020 Robin Hill. All rights reserved.
//
import CoreData
#if os(iOS)
import ReVoModeloj
#elseif os(macOS)
import ReVoModelojOSX
#endif
extension Mallongigo {
public static func elDatumbazObjekto(_ objekto: NSManagedObject) -> Mallongigo? {
if let kodo = objekto.value(forKey: "kodo") as? String,
let nomo = objekto.value(forKey: "nomo") as? String {
return Mallongigo(kodo: kodo, nomo: nomo)
}
return nil
}
}
// MARK: - Equatable
extension Mallongigo: Equatable {
public static func ==(lhs: Mallongigo, rhs: Mallongigo) -> Bool {
return lhs.kodo == rhs.kodo && lhs.nomo == rhs.nomo
}
}
// MARK: - Comparable
extension Mallongigo: Comparable {
public static func < (lhs: Mallongigo, rhs: Mallongigo) -> Bool {
return lhs.nomo.compare(rhs.nomo, options: .caseInsensitive, range: nil, locale: Locale(identifier: "eo")) == .orderedAscending
}
}
| be9dad6a8af8b85cc59e884ef525de45 | 23.674419 | 135 | 0.648445 | false | false | false | false |
ibm-bluemix-push-notifications/bms-samples-swift-login | refs/heads/master | userIdBasedSwift/ViewController.swift | apache-2.0 | 1 | //
// ViewController.swift
// userIdBasedSwift
//
// Created by Anantha Krishnan K G on 20/07/16.
// Copyright © 2016 Ananth. All rights reserved.
//
import UIKit
class ViewController: UIViewController,UITextFieldDelegate {
@IBOutlet var userIdText: UITextField!
@IBOutlet var passwordtext: UITextField!
@IBOutlet var loginButton: UIButton!
@IBOutlet var vieww: UIView!
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
override func viewDidLoad() {
super.viewDidLoad()
userIdText.delegate = self;
passwordtext.delegate = self;
// Do any additional setup after loading the view, typically from a nib.
}
func pushMessage(notification: NSNotification){
PopupController
.create(self)
.show(MessageViewController.instance())
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewWillAppear(animated: Bool) {
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(ViewController.keyboardWillShow(_:)), name:UIKeyboardWillShowNotification, object: nil);
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(ViewController.keyboardWillHide(_:)), name:UIKeyboardWillHideNotification, object: nil);
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(ViewController.pushMessage(_:)), name:"pushMessage", object: nil);
}
override func viewWillDisappear(animated: Bool) {
NSNotificationCenter.defaultCenter().removeObserver(self)
}
@IBAction func LoginAction(sender: AnyObject) {
if (!(userIdText.text?.isEmpty)! && !(passwordtext.text?.isEmpty)!) {
appDelegate.userid = userIdText.text!;
self.performSegueWithIdentifier("register", sender: nil)
}
}
func textFieldShouldReturn(textField: UITextField) -> Bool {
if(textField == userIdText){
passwordtext.becomeFirstResponder()
}
else {
passwordtext.resignFirstResponder()
}
return false
}
func keyboardWillShow(notification: NSNotification) {
self.view.frame.origin.y = -150
}
func keyboardWillHide(notification: NSNotification) {
self.view.frame.origin.y = 0
}
}
| f58c48850c8a6b95a3cc5d9a26a36b78 | 30.308642 | 171 | 0.65418 | false | false | false | false |
Obisoft2017/BeautyTeamiOS | refs/heads/master | BeautyTeam/BeautyTeam/AddPersonalTaskVC.swift | apache-2.0 | 1 | //
// AddPersonalTaskVC.swift
// BeautyTeam
//
// Created by Carl Lee on 4/21/16.
// Copyright © 2016 Shenyang Obisoft Technology Co.Ltd. All rights reserved.
//
import UIKit
class AddPersonalTaskVC: UITableViewController {
override func viewDidLoad() {
super.viewDidLoad()
self.navigationItem.title = "Add Personal Task"
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 0
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return 0
}
/*
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath)
// Configure the cell...
return cell
}
*/
/*
// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
// Delete the row from the data source
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| 549a6081790be7f1d1bdaace9e235f8f | 33.789474 | 157 | 0.687443 | false | false | false | false |
mapzen/ios | refs/heads/master | MapzenSDK/UIColorExtensions.swift | apache-2.0 | 1 | //
// UIColorExtensions.swift
// ios-sdk
//
// Created by Sarah Lensing on 3/22/17.
// Copyright © 2017 Mapzen. All rights reserved.
//
import UIKit
import CoreGraphics
extension UIColor {
func hexValue() -> String {
var r: CGFloat = 1
var g: CGFloat = 1
var b: CGFloat = 1
var a: CGFloat = 1
getRed(&r, green: &g, blue: &b, alpha: &a)
let red = Float(r * 255)
let green = Float(g * 255)
let blue = Float(b * 255)
let alpha = Float(a * 255)
return String.init(format: "#%02lX%02lX%02lX%02lX", lroundf(alpha), lroundf(red), lroundf(green), lroundf(blue))
}
}
| 35443063344d0bab47e7552302b3e593 | 24.291667 | 116 | 0.617792 | false | false | false | false |
Ferrick90/Fusuma | refs/heads/master | Carthage/Checkouts/Fusuma/Sources/FSImageCropView.swift | mit | 6 | //
// FZImageCropView.swift
// Fusuma
//
// Created by Yuta Akizuki on 2015/11/16.
// Copyright © 2015年 ytakzk. All rights reserved.
//
import UIKit
final class FSImageCropView: UIScrollView, UIScrollViewDelegate {
var imageView = UIImageView()
var imageSize: CGSize?
var image: UIImage! = nil {
didSet {
if image != nil {
if !imageView.isDescendant(of: self) {
self.imageView.alpha = 1.0
self.addSubview(imageView)
}
} else {
imageView.image = nil
return
}
if !fusumaCropImage {
// Disable scroll view and set image to fit in view
imageView.frame = self.frame
imageView.contentMode = .scaleAspectFit
self.isUserInteractionEnabled = false
imageView.image = image
return
}
let imageSize = self.imageSize ?? image.size
if imageSize.width < self.frame.width || imageSize.height < self.frame.height {
// The width or height of the image is smaller than the frame size
if imageSize.width > imageSize.height {
// Width > Height
let ratio = self.frame.width / imageSize.width
imageView.frame = CGRect(
origin: CGPoint.zero,
size: CGSize(width: self.frame.width, height: imageSize.height * ratio)
)
} else {
// Width <= Height
let ratio = self.frame.height / imageSize.height
imageView.frame = CGRect(
origin: CGPoint.zero,
size: CGSize(width: imageSize.width * ratio, height: self.frame.size.height)
)
}
imageView.center = self.center
} else {
// The width or height of the image is bigger than the frame size
if imageSize.width > imageSize.height {
// Width > Height
let ratio = self.frame.height / imageSize.height
imageView.frame = CGRect(
origin: CGPoint.zero,
size: CGSize(width: imageSize.width * ratio, height: self.frame.height)
)
} else {
// Width <= Height
let ratio = self.frame.width / imageSize.width
imageView.frame = CGRect(
origin: CGPoint.zero,
size: CGSize(width: self.frame.width, height: imageSize.height * ratio)
)
}
self.contentOffset = CGPoint(
x: imageView.center.x - self.center.x,
y: imageView.center.y - self.center.y
)
}
self.contentSize = CGSize(width: imageView.frame.width + 1, height: imageView.frame.height + 1)
imageView.image = image
self.zoomScale = 1.0
}
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)!
self.backgroundColor = fusumaBackgroundColor
self.frame.size = CGSize.zero
self.clipsToBounds = true
self.imageView.alpha = 0.0
imageView.frame = CGRect(origin: CGPoint.zero, size: CGSize.zero)
self.maximumZoomScale = 2.0
self.minimumZoomScale = 0.8
self.showsHorizontalScrollIndicator = false
self.showsVerticalScrollIndicator = false
self.bouncesZoom = true
self.bounces = true
self.delegate = self
}
func changeScrollable(_ isScrollable: Bool) {
self.isScrollEnabled = isScrollable
}
// MARK: UIScrollViewDelegate Protocol
func viewForZooming(in scrollView: UIScrollView) -> UIView? {
return imageView
}
func scrollViewDidZoom(_ scrollView: UIScrollView) {
let boundsSize = scrollView.bounds.size
var contentsFrame = imageView.frame
if contentsFrame.size.width < boundsSize.width {
contentsFrame.origin.x = (boundsSize.width - contentsFrame.size.width) / 2.0
} else {
contentsFrame.origin.x = 0.0
}
if contentsFrame.size.height < boundsSize.height {
contentsFrame.origin.y = (boundsSize.height - contentsFrame.size.height) / 2.0
} else {
contentsFrame.origin.y = 0.0
}
imageView.frame = contentsFrame
}
func scrollViewDidEndZooming(_ scrollView: UIScrollView, with view: UIView?, atScale scale: CGFloat) {
self.contentSize = CGSize(width: imageView.frame.width + 1, height: imageView.frame.height + 1)
}
}
| 80476222c65797977a41b7655cb43abf | 29.777174 | 107 | 0.464771 | false | false | false | false |
khizkhiz/swift | refs/heads/master | validation-test/compiler_crashers_fixed/25966-llvm-densemap-swift-normalprotocolconformance.swift | apache-2.0 | 1 | // RUN: not %target-swift-frontend %s -parse
// Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
}
( ")enum S<a
struct B
Void{
var a: A : A
protocol c : A
}
class var e : a {
protocol a : a {
struct B<String
in
}struct B<T where k : A
func a
func a=e
protocol P {
func f<h = object {
protocol c B
a Foundation
}
protocol a {
class A? = compose("
}
{
class A : a
class d
class B<String, C>("
class d>()
typealias e : a: a :d
protocol P {
struct A
class A {
struct B
func a {
class A<T.e
func a {
}
struct b<d
}
}
class B
protocol a {
var "
case c,
let end = compose("
}
in
}
case c
typealias e : A
extension g:Boolean{
class A {}
extension NSFileManager {
return E.c{ enum b {
}
typealias e = compose()enum C {
{struct A
var d {
{
func a :Boolean{
let b{struct B<T:C>()
let h : A {
case c
}
protocol P {
}
struct c {
}
{
protocol A {
}
}
return E.e
func a {
}
atic var d {
class B<T where T? {{
protocol a {
class B< {
}
class A {
enum S<b{
class A {
}
}}
}
Void{{
if
struct c,
func c{ enum S<h : a
typealias e : A {
class d}
struct b: a {enum b = F>() {
}
}
( "
func a {
class A : A
func a:Boolean{
var f = compose(n: Dictionary<String, C>())
struct b: A
protocol A {
class A {
static let f = e
}
let end = [
| 9f753dc64485a452786f12c4be133c68 | 11.054545 | 87 | 0.634238 | false | false | false | false |
aerogear/aerogear-ios-http | refs/heads/master | AeroGearHttp/JsonRequestSerializer.swift | apache-2.0 | 2 | /*
* JBoss, Home of Professional Open Source.
* Copyright Red Hat, Inc., and individual contributors
*
* 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 request serializer to JSON objects/
*/
open class JsonRequestSerializer: HttpRequestSerializer {
/**
Build an request using the specified params passed in.
:param: url the url of the resource.
:param: method the method to be used.
:param: parameters the request parameters.
:param: headers any headers to be used on this request.
:returns: the URLRequest object.
*/
open override func request(url: URL, method: HttpMethod, parameters: [String: Any]?, headers: [String: String]? = nil) -> URLRequest {
if method == .get || method == .head || method == .delete {
return super.request(url: url, method: method, parameters: parameters, headers: headers)
} else {
var request = URLRequest(url: url, cachePolicy: cachePolicy, timeoutInterval: timeoutInterval)
request.httpMethod = method.rawValue
// set type
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
// set body
if (parameters != nil) {
var body: Data?
do {
body = try JSONSerialization.data(withJSONObject: parameters!, options: [])
} catch _ {
body = nil
}
// set body
if (body != nil) {
request.setValue("\(String(describing: body?.count))", forHTTPHeaderField: "Content-Length")
request.httpBody = body
}
}
// apply headers to new request
if(headers != nil) {
for (key,val) in headers! {
request.addValue(val, forHTTPHeaderField: key)
}
}
return request
}
}
}
| 59156bb410fa9ee3d67006fff502665e | 35.676471 | 138 | 0.597434 | false | false | false | false |
MrSuperJJ/JJSwiftNews | refs/heads/master | JJSwiftNews/AppDelegate.swift | mit | 1 | //
// AppDelegate.swift
// JJSwiftNews
//
// Created by yejiajun on 2017/6/15.
// Copyright © 2017年 yejiajun. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
self.window = UIWindow.init(frame: UIScreen.main.bounds)
self.window?.backgroundColor = UIColor.white
let mainViewController = NewsMainViewController()
let navigationController = UINavigationController(rootViewController: mainViewController)
self.window?.rootViewController = navigationController
self.window?.makeKeyAndVisible()
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| e8a08264e568b61221b1cbc116529ce6 | 45.690909 | 285 | 0.746106 | false | false | false | false |
larryhou/swift | refs/heads/master | LocateMe/LocateMe/SetupViewController.swift | mit | 1 | //
// SetupViewController.swift
// LocateMe
//
// Created by doudou on 8/16/14.
// Copyright (c) 2014 larryhou. All rights reserved.
//
import Foundation
import UIKit
import CoreLocation
@objc protocol SetupSettingReceiver {
func setupSetting(setting: LocateSettingInfo)
}
class LocateSettingInfo: NSObject {
let accuracy: CLLocationAccuracy
let sliderValue: Float
init(accuracy: CLLocationAccuracy, sliderValue: Float) {
self.accuracy = accuracy
self.sliderValue = sliderValue
}
override var description: String {
return super.description + "{accuracy:\(accuracy), sliderValue:\(sliderValue)}"
}
}
class SetupViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource {
struct AccuracyOption {
var label: String
var value: CLLocationAccuracy
}
struct InitialSetupValue {
let selectedIndex: Int
let sliderValue: Float
}
@IBOutlet weak var accuracyPicker: UIPickerView!
@IBOutlet weak var slider: UISlider!
@IBOutlet weak var label: UILabel!
private var options: [AccuracyOption]!
private var formater: NSNumberFormatter!
private var selectedPickerIndex: Int!
private var initial: InitialSetupValue!
var setting: LocateSettingInfo {
return LocateSettingInfo(accuracy: options[selectedPickerIndex].value, sliderValue: slider.value)
}
override func viewDidLoad() {
options = []
options.append(AccuracyOption(label: localizeString("AccuracyBest"), value: kCLLocationAccuracyBest))
options.append(AccuracyOption(label: localizeString("Accuracy10"), value: kCLLocationAccuracyNearestTenMeters))
options.append(AccuracyOption(label: localizeString("Accuracy100"), value: kCLLocationAccuracyHundredMeters))
options.append(AccuracyOption(label: localizeString("Accuracy1000"), value: kCLLocationAccuracyKilometer))
options.append(AccuracyOption(label: localizeString("Accuracy3000"), value: kCLLocationAccuracyThreeKilometers))
formater = NSNumberFormatter()
formater.minimumFractionDigits = 1
formater.minimumIntegerDigits = 1
initial = InitialSetupValue(selectedIndex: 2, sliderValue: slider.value)
selectedPickerIndex = initial.selectedIndex
}
override func viewWillAppear(animated: Bool) {
accuracyPicker.selectRow(selectedPickerIndex, inComponent: 0, animated: true)
slider.value = setting.sliderValue
sliderChangedValue(slider)
}
override func prepareForSegue(segue: UIStoryboardSegue!, sender: AnyObject!) {
if segue.identifier == "SettingSegue" {
if segue.destinationViewController is SetupSettingReceiver {
var reciever: SetupSettingReceiver = segue.destinationViewController as SetupSettingReceiver
reciever.setupSetting(setting)
}
}
}
@IBAction func reset(segue: UIStoryboardSegue) {
accuracyPicker.selectRow(initial.selectedIndex, inComponent: 0, animated: true)
slider.value = initial.sliderValue
sliderChangedValue(slider)
}
@IBAction func sliderChangedValue(sender: UISlider) {
label.text = formater.stringFromNumber(sender.value)
}
func numberOfComponentsInPickerView(pickerView: UIPickerView!) -> Int {
return 1
}
func pickerView(pickerView: UIPickerView!, numberOfRowsInComponent component: Int) -> Int {
return options.count
}
func pickerView(pickerView: UIPickerView!, titleForRow row: Int, forComponent component: Int) -> String! {
return options[row].label
}
func pickerView(pickerView: UIPickerView!, didSelectRow row: Int, inComponent component: Int) {
selectedPickerIndex = row
}
}
| a1b18ee4c1e7facd877d46ce547b6dc8 | 32.707965 | 120 | 0.711473 | false | false | false | false |
hsavit1/LeetCode-Solutions-in-Swift | refs/heads/master | Solutions/Solutions/Medium/Medium_002_Add_Two_Numbers.swift | mit | 4 | /*
https://oj.leetcode.com/problems/add-two-numbers/
#2 Add Two Numbers
Level: medium
You are given two linked lists representing two non-negative numbers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Inspired by @potpie at https://oj.leetcode.com/discuss/2308/is-this-algorithm-optimal-or-what
*/
class Medium_002_Add_Two_Numbers {
// Linked List Data Structure
class ListNode {
var value: Int
var next: ListNode?
init () {
value = 0
next = nil
}
init (nodeValue: Int, nodeNext: ListNode?) {
value = nodeValue
next = nodeNext
}
}
// Solution
// O (N)
class func addNumbers(node1: ListNode?, node2: ListNode?) -> ListNode? {
var tmp1: ListNode? = node1
var tmp2: ListNode? = node2
let dummy: ListNode = ListNode()
var curr: ListNode = dummy
var sum: Int = 0
while tmp1 != nil || tmp2 != nil {
sum /= 10
if let n = tmp1 {
sum += n.value
tmp1 = n.next
}
if let n = tmp2 {
sum += n.value
tmp2 = n.next
}
curr.next = ListNode(nodeValue: sum%10, nodeNext: nil)
if let n = curr.next {
curr = n
}
}
if sum / 10 == 1 {
curr.next = ListNode(nodeValue: 1, nodeNext: nil)
}
return dummy.next
}
} | 92ab3e3cb52554d13de1522df1f3c8d9 | 24.75 | 208 | 0.514876 | false | false | false | false |
dmitryrybakov/19test | refs/heads/master | 19test/AppDelegate.swift | artistic-2.0 | 1 | //
// AppDelegate.swift
// 19test
//
// Created by Dmitry Rybakov on 5/8/16.
// Copyright © 2016 Dmitry Rybakov. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Core Data stack
lazy var applicationDocumentsDirectory: NSURL = {
// The directory the application uses to store the Core Data store file. This code uses a directory named "home._9test" in the application's documents Application Support directory.
let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
return urls[urls.count-1]
}()
lazy var managedObjectModel: NSManagedObjectModel = {
// The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
let modelURL = NSBundle.mainBundle().URLForResource("_9test", withExtension: "momd")!
return NSManagedObjectModel(contentsOfURL: modelURL)!
}()
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = {
// The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail.
// Create the coordinator and store
let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("SingleViewCoreData.sqlite")
var failureReason = "There was an error creating or loading the application's saved data."
do {
try coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil)
} catch {
// Report any error we got.
var dict = [String: AnyObject]()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
dict[NSLocalizedFailureReasonErrorKey] = failureReason
dict[NSUnderlyingErrorKey] = error as NSError
let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
// Replace this with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)")
abort()
}
return coordinator
}()
lazy var managedObjectContext: NSManagedObjectContext = {
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
let coordinator = self.persistentStoreCoordinator
var managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType)
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
// MARK: - Core Data Saving support
func saveContext () {
if managedObjectContext.hasChanges {
do {
try managedObjectContext.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
NSLog("Unresolved error \(nserror), \(nserror.userInfo)")
abort()
}
}
}
}
| e861b229e1fb1c01c78c8b23c27fcee8 | 53.792793 | 291 | 0.718842 | false | false | false | false |
luismatute/RAM-Activity | refs/heads/master | RAM Activity/RAM Activity/AppDelegate.swift | mit | 70 | //
// AppDelegate.swift
// RAM Activity
//
// Created by Luis Matute on 11/5/14.
// Copyright (c) 2014 Luis Matute. All rights reserved.
//
import Cocoa
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
@IBOutlet weak var window: NSWindow!
@IBOutlet weak var statusMenu: NSMenu!
// Items used as labels
@IBOutlet weak var freeLabel: NSMenuItem!
@IBOutlet weak var usedLabel: NSMenuItem!
let statusItem = NSStatusBar.systemStatusBar().statusItemWithLength(-1)
func applicationDidFinishLaunching(aNotification: NSNotification?) {
let icon = NSImage(named: "menuIcon")
icon.setTemplate(true)
statusItem.image = icon
statusItem.menu = statusMenu
refreshValues()
}
@IBAction func refreshAction(sender: AnyObject) {
}
func refreshValues() -> (String,String) {
// let topTask = NSTask(),
// grepTask = NSTask()
//
// topTask.launchPath = "/usr/bin/top"
// grepTask.launchPath = "/usr/bin/grep"
//
// topTask.arguments = ["-l","1"]
//
// topTask.launch()
// topTask.waitUntilExit()
//
// grepTask.arguments = ["-i","PhysMem:",topTask.value()]
// grepTask.launch()
// grepTask.waitUntilExit()
// println(grepTask)
let buildTask = NSTask()
let dir = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as String
// let path = dir.stringByAppendingPathComponent("MemLookup.sh")
var error:NSError?
var myDict: NSDictionary?
if let path = NSBundle.mainBundle().pathForResource("AppDelegate",ofType: "swift") {
myDict = NSDictionary(contentsOfFile: path)
println(path)
}
return ("Used", "Free")
}
}
| c6ac12034641cf5a9a85dcc64e373187 | 27.333333 | 109 | 0.609626 | false | false | false | false |
xcodeswift/xcproj | refs/heads/master | Sources/XcodeProj/Workspace/XCWorkspace.swift | mit | 1 | import Foundation
import PathKit
/// Model that represents a Xcode workspace.
public final class XCWorkspace: Writable, Equatable {
/// Workspace data
public var data: XCWorkspaceData
// MARK: - Init
/// Initializes the workspace with the path where the workspace is.
/// The initializer will try to find an .xcworkspacedata inside the workspace.
/// If the .xcworkspacedata cannot be found, the init will fail.
///
/// - Parameter path: .xcworkspace path.
/// - Throws: throws an error if the workspace cannot be initialized.
public convenience init(path: Path) throws {
if !path.exists {
throw XCWorkspaceError.notFound(path: path)
}
let xcworkspaceDataPaths = path.glob("*.xcworkspacedata")
if xcworkspaceDataPaths.isEmpty {
self.init()
} else {
try self.init(data: XCWorkspaceData(path: xcworkspaceDataPaths.first!))
}
}
/// Initializes a default workspace with a single reference that points to self:
public convenience init() {
let data = XCWorkspaceData(children: [.file(.init(location: .self("")))])
self.init(data: data)
}
/// Initializes the workspace with the path string.
///
/// - Parameter pathString: path string.
/// - Throws: throws an error if the initialization fails.
public convenience init(pathString: String) throws {
try self.init(path: Path(pathString))
}
/// Initializes the workspace with its properties.
///
/// - Parameters:
/// - data: workspace data.
public init(data: XCWorkspaceData) {
self.data = data
}
// MARK: - Writable
public func write(path: Path, override: Bool = true) throws {
let dataPath = path + "contents.xcworkspacedata"
if override, dataPath.exists {
try dataPath.delete()
}
try dataPath.mkpath()
try data.write(path: dataPath)
}
// MARK: - Equatable
public static func == (lhs: XCWorkspace, rhs: XCWorkspace) -> Bool {
lhs.data == rhs.data
}
}
| a1032a62218b300e82b49bc02f149982 | 30.492537 | 84 | 0.627488 | false | false | false | false |
yannickl/Reactions | refs/heads/master | Sources/Reaction.swift | mit | 1 | /*
* Reactions
*
* Copyright 2016-present Yannick Loriot.
* http://yannickloriot.com
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
import UIKit
/**
The `Reaction` struct defines several attributes like the title, the icon or the color of the reaction.
A `Reaction` can be used with objects like `ReactionSelector`, `ReactionButton` and `ReactionSummary`.
*/
public struct Reaction {
/// The reaction's identifier.
public let id: String
/// The reaction's title.
public let title: String
/// The reaction's color.
public let color: UIColor
/// The reaction's icon image.
public let icon: UIImage
/**
The reaction's alternative icon image.
The alternative icon is only used by the `ReactionButton`. It tries to display the alternative as icon and if it fails it uses the `icon`.
*/
public let alternativeIcon: UIImage?
/**
Creates and returns a new reaction using the specified properties.
- Parameter id: The reaction's identifier.
- Parameter title: The reaction's title.
- Parameter color: The reaction's color.
- Parameter icon: The reaction's icon image.
- Parameter alternativeIcon: The reaction's alternative icon image.
- Returns: Newly initialized reaction with the specified properties.
*/
public init(id: String, title: String, color: UIColor, icon: UIImage, alternativeIcon: UIImage? = nil) {
self.id = id
self.title = title
self.color = color
self.icon = icon
self.alternativeIcon = alternativeIcon
}
}
extension Reaction: Equatable {
/// Returns a Boolean value indicating whether two values are equal.
public static func ==(lhs: Reaction, rhs: Reaction) -> Bool {
return lhs.id == rhs.id
}
}
extension Reaction: Hashable {
public func hash(into hasher: inout Hasher) {
hasher.combine(id)
}
}
extension Reaction: CustomStringConvertible {
/// A textual representation of this instance.
public var description: String {
return "<Reaction id=\(id) title=\(title)>"
}
}
| 42f0e5a8e3b7fd7c5c3a763cf2f64620 | 32.945055 | 141 | 0.715118 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.