repo_name
stringlengths 7
91
| path
stringlengths 8
658
| copies
stringclasses 125
values | size
stringlengths 3
6
| content
stringlengths 118
674k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6.09
99.2
| line_max
int64 17
995
| alpha_frac
float64 0.3
0.9
| ratio
float64 2
9.18
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
PraveenSakthivel/BRGO-IOS | BRGO/Planner.swift | 1 | 1733 | //
// Planner.swift
// BRGO
//
// Created by Praveen Sakthivel on 7/25/16.
// Copyright © 2016 TBLE Technologies. All rights reserved.
//
import UIKit
class Planner: UIViewController, CGCalendarViewDelegate{
var calendarView: CGCalendarView!
let dateformat: NSDateFormatter! = nil
let calendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)!
override func viewDidLoad() {
super.viewDidLoad()
calendarSetUp()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func calendarSetUp() {
calendarView = (CGCalendarView)(frame: CGRectMake(0,20,320,50))
calendarView.calendar = calendar
calendarView.backgroundColor = UIColor.init(red: 241/255, green: 241/255, blue: 242/255, alpha: 1)
calendarView.rowCellClass = CGCalendarCell.classForCoder()
calendarView.firstDate = NSDate.init(timeInterval: -60 * 60 * 24 * 30, sinceDate: NSDate())
calendarView.lastDate = NSDate.init(timeInterval: -60 * 60 * 24 * 30, sinceDate: NSDate())
calendarView.delegate = self
self.view.addSubview(calendarView)
calendarView.selectedDate = NSDate()
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| mit | 75bd83ad6610ce062c272e09450abcd6 | 34.346939 | 107 | 0.676674 | 4.78453 | false | false | false | false |
BarlowTucker/DevChallenges | DevChallenges/DevChallenges/Controllers/ChallengeDetailViewController.swift | 1 | 1120 | //
// ChallengeDetailViewController.swift
// DevChallenges
//
// Created by Barlow Tucker on 5/6/16.
// Copyright © 2016 Barlow Tucker. All rights reserved.
//
import UIKit
class ChallengeDetailViewController: UIViewController {
@IBOutlet weak var challengeImageView: UIImageView!
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var subtitleLabel: UILabel!
@IBOutlet weak var descriptionLabel: UILabel!
@IBOutlet weak var actionButton: UIButton!
var challenge:Challenge?
override func viewDidLoad() {
super.viewDidLoad()
guard let challenge = self.challenge else { return }
self.challengeImageView.image = challenge.image
self.titleLabel.text = challenge.title
self.descriptionLabel.text = challenge.description
self.subtitleLabel.text = challenge.subtitle
self.actionButton.hidden = challenge.appURL == nil
}
@IBAction func actionTapped(sender: AnyObject) {
guard let url = self.challenge?.appURL else { return }
UIApplication.sharedApplication().openURL(url)
}
}
| mit | f0debc29f3a42d3ebe45cc892309d693 | 30.083333 | 62 | 0.692583 | 4.823276 | false | false | false | false |
briandw/SwiftPack | Unpacker/AppDelegate.swift | 2 | 2780 | //
// AppDelegate.swift
// Unpacker
//
// Created by brian on 11/29/14.
// Copyright (c) 2014 Rantlab. All rights reserved.
//
import Cocoa
import SwiftPack
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate
{
@IBOutlet weak var window: NSWindow!
@IBOutlet var decodedView: NSTextView!
func applicationDidFinishLaunching(aNotification: NSNotification)
{
// Insert code here to initialize your application
// let simpleHex = "82 A3 66 6F 6F A3 62 61 72 A3 62 61 7A 01"
// let msgPackCaseHex = "C2 C3 C0 00 CC 00 CD 00 00 CE 00 00 00 00 CF 00 00 00 00 00 00 00 00 D0 00 D1 00 00 D2 00 00 00 00 D3 00 00 00 00 00 00 00 00 FF D0 FF D1 FF FF D2 FF FF FF FF D3 FF FF FF FF FF FF FF FF 7F CC 7F CD 00 FF CE 00 00 FF FF CF 00 00 00 00 FF FF FF FF E0 D0 E0 D1 FF 80 D2 FF FF 80 00 D3 FF FF FF FF 80 00 00 00 CB 00 00 00 00 00 00 00 00 CB 80 00 00 00 00 00 00 00 CB 3F F0 00 00 00 00 00 00 CB BF F0 00 00 00 00 00 00 A1 61 DA 00 01 61 DB 00 00 00 01 61 A0 DA 00 00 DB 00 00 00 00 91 00 DC 00 01 00 DD 00 00 00 01 00 90 DC 00 00 DD 00 00 00 00 80 DE 00 00 DF 00 00 00 00 81 A1 61 61 DE 00 01 A1 61 61 DF 00 00 00 01 A1 61 61 91 90 91 91 A1 61"
// let simple = Unpacker.hexStringToByteArray(msgPackCaseHex)
// let text1 = Describer.describeBytes(simple);
// println(text1.description)
}
func applicationWillTerminate(aNotification: NSNotification)
{
// Insert code here to tear down your application
}
func classFromType<T:NSObject>(type: T.Type) -> AnyObject!
{
return T.valueForKey("self")
}
@IBAction func readPasteBoard(x:AnyObject)
{
let pb = NSPasteboard.generalPasteboard()
let clazz:AnyObject = classFromType(NSString.self)
var output = ""
if let items = pb.readObjectsForClasses([clazz], options:nil)
{
for hexString in items
{
let bytes:Array<UInt8> = Unpacker.hexStringToByteArray(hexString as! String)
if (bytes.count > 0)
{
var result = Describer.describeBytes(bytes)
var descriptions:Array<String> = result.descriptions
if (descriptions.count == 0)
{
output = "unparsable"
}
for str in descriptions
{
output += "\(str)\n"
}
}
else
{
output += "empty"
}
output += "\n"
}
}
decodedView.string = output
}
}
| mit | af1a701c5fbae620edcf81a5b31f7e83 | 33.75 | 671 | 0.554676 | 4.064327 | false | false | false | false |
gg4acrossover/swiftForFun | Project 02 - GGProgressHUD/GGProgressHUD/Hud/GGProgressHUD.swift | 1 | 3149 | //
// GGProgressHUD.swift
// GGProgressHUD
//
// Created by viethq on 5/5/17.
// Copyright © 2017 viethq. All rights reserved.
//
import UIKit
import NVActivityIndicatorView
/// config
fileprivate let kRectProgressView = CGRect(x: 0.0, y: 0.0, width: 100.0, height: 100.0)
fileprivate let kRectIconView = CGRect(x: 0.0, y: 0.0, width: kRectProgressView.width * 0.5, height: kRectProgressView.height * 0.5)
class GGProgressHUD {
///MARK: - Properties
static let share = GGProgressHUD()
var rootWindow : UIWindow?
fileprivate let iconView : NVActivityIndicatorView
fileprivate let keyWindow = UIApplication.shared.keyWindow
fileprivate let window = UIWindow(frame: UIScreen.main.bounds)
private let progressView : UIView = {
let view = UIView(frame:kRectProgressView)
view.backgroundColor = UIColor.white
view.layer.cornerRadius = 4.0
view.center = CGPoint(x: UIScreen.main.bounds.width * 0.5,
y: UIScreen.main.bounds.height * 0.5)
return view
}()
/// init of singleton
private init() {
// add icon to center of progress view
self.iconView = NVActivityIndicatorView( frame: kRectIconView,
type: .audioEqualizer,
color: UIColor.red,
padding: 0.0)
self.iconView.center = CGPoint( x: kRectProgressView.width * 0.5,
y: kRectProgressView.height * 0.5)
self.progressView.addSubview(self.iconView)
// always show in center of view even when rotate
// can use constraints instead
self.progressView.autoresizingMask = [ .flexibleBottomMargin,
.flexibleLeftMargin,
.flexibleRightMargin,
.flexibleTopMargin]
// add progress to container which is a viewcontroller
let container = GGHUDViewController()
container.view.addSubview(self.progressView)
self.window.rootViewController = container
}
//MARK: - Public method
class func show() {
GGProgressHUD.share.startAnim()
}
class func hide() {
GGProgressHUD.share.stopAnim()
}
//MARK: - Private method
private func startAnim() {
// save root window of app
if let root = UIApplication.shared.keyWindow {
self.rootWindow = root
}
self.window.alpha = 0
self.window.makeKeyAndVisible()
self.iconView.startAnimating()
UIView.animate(withDuration: 0.5) {
self.window.alpha = 1.0
}
}
private func stopAnim() {
// set root window to key
self.rootWindow?.makeKey()
UIView.animate(withDuration: 0.5, animations: {
self.window.alpha = 0.0
}) { (_) in
self.iconView.stopAnimating()
}
}
}
| mit | f76a681edc903922a6f0b5c3fe8d56a3 | 32.136842 | 132 | 0.559085 | 4.858025 | false | false | false | false |
Rostmen/TimelineController | RZTimelineCollection/RZTimelineController.swift | 1 | 7947 | //
// ViewController.swift
// RZTimelineCollection
//
// Created by Rostyslav Kobizsky on 12/18/14.
// Copyright (c) 2014 Rozdoum. All rights reserved.
//
import UIKit
class RZTimelineController: UIViewController, RZPostCollectionViewDataSource, RZPostCollectionViewDelegateFlowLayout, RZPostCollectionViewCellDelegate {
@IBOutlet weak var collectionView: RZPostCollectionView!
@IBOutlet weak var toolbar: UIToolbar!
/**
* Asks the data source for the current sender's display name, that is, the current user who is sending post.
*
* @return An initialized string describing the current sender to display in a `RZPostCollectionViewCell`.
*
* @warning You must not return `nil` from this method. This value does not need to be unique.
*/
var senderDisplayName: String!
/**
* Asks the data source for the current sender's unique identifier, that is, the current user who is sending post.
*
* @return An initialized string identifier that uniquely identifies the current sender.
*
* @warning You must not return `nil` from this method. This value must be unique.
*/
var senderId: String!
var cellReuseIdentifier = RZPostCollectionViewCell.cellReuseIdentifier()
var mediaCellReuseIdentifier = RZPostCollectionViewCell.mediaCellReuseIdentifier()
class func nib() -> UINib {
return UINib(nibName: "RZTimelineController", bundle: NSBundle.mainBundle())
}
// required init(coder aDecoder: NSCoder) {
// super.init(coder: aDecoder)
// self.configureCollectionView()
// }
override func viewDidLoad() {
super.viewDidLoad()
RZTimelineController.nib().instantiateWithOwner(self, options: nil)
self.configureCollectionView()
}
func configureCollectionView() {
collectionView.dataSource = self
collectionView.delegate = self
collectionView.registerNib(RZPostCollectionViewCell.nib(), forCellWithReuseIdentifier: RZPostCollectionViewCell.cellReuseIdentifier())
collectionView.registerClass(RZGridline.self, forSupplementaryViewOfKind: RZCollectionElementKindTimeLine, withReuseIdentifier: RZGridline.elementReuseIndetifier())
senderId = "RozdoumID"
senderDisplayName = "Rozdoum ltd"
updateCollectionViewInsets()
}
func updateCollectionViewInsets() {
setCollectionViewInsetsTopValue(topLayoutGuide.length, bottomValue: CGRectGetMaxY(collectionView.frame) - CGRectGetMinY(toolbar.frame))
}
func setCollectionViewInsetsTopValue(top: CGFloat, bottomValue bottom: CGFloat) {
let insets = UIEdgeInsets(top: top, left: 0, bottom: bottom, right: 0)
collectionView.contentInset = insets
collectionView.scrollIndicatorInsets = insets
}
// MARK: UICollectionViewDataSource
func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 0
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let postObject = (collectionView.dataSource as RZPostCollectionViewDataSource).collectionView((collectionView as RZPostCollectionView), postDataForIndexPath: indexPath)
let cellIdentifier = postObject.isMediaPost ? mediaCellReuseIdentifier : cellReuseIdentifier
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(cellIdentifier, forIndexPath: indexPath) as RZPostCollectionViewCell
cell.delegate = self
if postObject.isMediaPost {
cell.mediaView = postObject.media?.mediaView != nil ? postObject.media?.mediaView : postObject.media?.mediaPlaceholderView
} else {
cell.textView.text = postObject.text
if let backgroundImageDataSource = (collectionView.dataSource as RZPostCollectionViewDataSource).collectionView((collectionView as RZPostCollectionView), backgroundImageDataAtIndexPath: indexPath) {
cell.postBackgroundImageView.image = backgroundImageDataSource.postBackgroundImage
cell.postBackgroundImageView.highlightedImage = backgroundImageDataSource.postBackgroundHighlightedImage
}
}
var labelInsets: CGFloat = 15
let avatarSize = (collectionView.collectionViewLayout as RZTimelineCollectionLayout).avatarSize
let needsAvatar = !CGSizeEqualToSize(avatarSize, CGSizeZero)
if needsAvatar {
if let avatarDataSource = (collectionView.dataSource as RZPostCollectionViewDataSource).collectionView!((collectionView as RZPostCollectionView), avatarImageDataAtIndexPath: indexPath) {
if let avatarImage = avatarDataSource.avatarImage {
cell.avatarImageView.image = avatarImage
cell.avatarImageView.highlightedImage = avatarDataSource.avatarHighlightedImage
} else {
cell.avatarImageView.image = avatarDataSource.avatarPlaceholderImage
cell.avatarImageView.highlightedImage = nil
}
labelInsets = avatarSize.width / 2
}
}
cell.cellTopLabel.attributedText = (collectionView.dataSource as RZPostCollectionViewDataSource).collectionView?((collectionView as RZPostCollectionView), attributedTextForCellTopLabelAtIndexPath: indexPath)
cell.cellBottomLabel.attributedText = (collectionView.dataSource as RZPostCollectionViewDataSource).collectionView?((collectionView as RZPostCollectionView), attributedTextForCellBottomLabelAtIndexPath: indexPath)
cell.cellTopLabel.textInsets = UIEdgeInsets(top: 0, left: labelInsets, bottom: 0, right: 0)
cell.cellBottomLabel.textInsets = UIEdgeInsets(top: 0, left: labelInsets, bottom: 0, right: 0)
cell.textView.dataDetectorTypes = UIDataDetectorTypes.All
cell.layer.rasterizationScale = UIScreen.mainScreen().scale
cell.layer.shouldRasterize = true
return cell
}
func collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView {
return collectionView.dequeueReusableSupplementaryViewOfKind(kind, withReuseIdentifier: RZGridline.elementReuseIndetifier(), forIndexPath: indexPath) as RZGridline
}
// MARK: RZPostCollectionViewDelegateFlowLayout
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
return (collectionViewLayout as RZTimelineCollectionLayout).sizeForItemAtIndexPath(indexPath)
}
func collectionView(collectionView: RZPostCollectionView, layout: RZTimelineCollectionLayout, heightForCellBottomLabelAtIndexPath idnexPath: NSIndexPath) -> CGFloat {
return 1
}
func collectionView(collectionView: RZPostCollectionView, layout: RZTimelineCollectionLayout, heightForCellTopLabelAtIndexPath idnexPath: NSIndexPath) -> CGFloat {
return 1
}
// MARK: RZPostCollectionViewDataSource
func collectionView(collectionView: RZPostCollectionView, postDataForIndexPath indexPath: NSIndexPath) -> RZPostData {
assert(false, "ERROR: required method not implemented: \(__FUNCTION__)")
}
func collectionView(collectionView: RZPostCollectionView, backgroundImageDataAtIndexPath indexPath: NSIndexPath) -> RZPostBackgroundImageSource? {
return nil
}
func collectionView(collectionView: RZPostCollectionView, avatarImageDataAtIndexPath indexPath: NSIndexPath) -> RZAvatarImageDataSource? {
return nil
}
}
| apache-2.0 | 6c85da751f7dde35a202feb5d7b203b9 | 47.754601 | 221 | 0.730716 | 6.057165 | false | false | false | false |
bzatrok/iOSAssessment | BestBuy/Classes/Managers/BBRequestManager.swift | 1 | 5950 | //
// BBRequestManager.swift
// BestBuy
//
// Created by Ben Zatrok on 26/02/17.
// Copyright © 2017 AmberGlass. All rights reserved.
//
import UIKit
class BBRequestManager
{
//MARK: Variables
//MARK: Initialization
static let shared = BBRequestManager()
private init() {}
//MARK: Functions
//MARK: PRODUCTS
func queryProducts(withURL url: URL, completion: @escaping (_ success: Bool, _ responseProductList: [BBProduct]?) -> Void)
{
let task = URLSession.shared.dataTask(with: url) { data, response, error in
guard error == nil, let responseData = data else
{
print(error)
completion(false, nil)
return
}
do
{
guard let productsDict = try JSONSerialization.jsonObject(with: responseData, options: []) as? [String: AnyObject] else
{
print("error trying to convert data to JSON")
completion(false, nil)
return
}
if let productsArray = productsDict["products"] as? [[String : AnyObject]], productsArray.count > 0
{
let productsList = BBObjectFactory.createProductsList(fromProductArray: productsArray)
completion(true, productsList)
}
else
{
completion(true, nil)
}
}
catch
{
print("error trying to convert data to JSON")
completion(false, nil)
}
}
task.resume()
}
/**
Queries Products from Best Buy API using Search String
- parameter searchString: search string to search products against (optional)
- parameter selectedCategoryID: category ID to filter products search into (optional)
- parameter currentPageNumber: page number of search results, for pagination
- parameter completion: completion block with success bool and optinal array of BBProducts return
*/
func queryProducts(withSearchString searchString: String?, selectedCategoryID: String?, currentPageNumber: Int, completion: @escaping (_ success: Bool, _ responseProductList: [BBProduct]?) -> Void)
{
var URLString : String?
if let searchString = searchString, let selectedCategoryID = selectedCategoryID
{
URLString = BBURLRoutes.productSearchAPIURL(searchString: searchString, selectedCategoryID: selectedCategoryID, currentPageNumber: currentPageNumber)
}
else if let searchString = searchString
{
URLString = BBURLRoutes.productSearchAPIURL(searchString: searchString, selectedCategoryID: nil, currentPageNumber: currentPageNumber)
}
else if let selectedCategoryID = selectedCategoryID
{
URLString = BBURLRoutes.productSearchAPIURL(searchString: nil, selectedCategoryID: selectedCategoryID, currentPageNumber: currentPageNumber)
}
guard let strongURLString = URLString,
strongURLString.characters.count > 0,
let URL = URL(string: strongURLString) else
{
completion(false, nil)
return
}
queryProducts(withURL: URL, completion: completion)
}
/**
Queries Products replated to a specific SKU, from the Best Buy API using an URL String
- parameter completion: completion block with success bool and optinal array of BBProducts return
*/
func queryProducts(withSKUs SKUs: [Int], completion: @escaping (_ success: Bool, _ responseProductList: [BBProduct]?) -> Void)
{
let URLString = BBURLRoutes.productsWithSKUs(skuList: SKUs)
guard let URL = URL(string: URLString) else
{
completion(false, nil)
return
}
queryProducts(withURL: URL, completion: completion)
}
//MARK: CATEGORIES
/**
Queries all top level Categories from Best Buy API
- parameter completion: completion block with success bool and optinal array of BBCategories return
*/
func queryCategories(currentPageNumber: Int, completion: @escaping (_ success: Bool, _ responseCategoryList: [BBCategory]?) -> Void)
{
guard let URL = URL(string: BBURLRoutes.allTopLevelCategoriesAPIURLWithPagination(currentPageNumber: currentPageNumber)) else
{
completion(false, nil)
return
}
let task = URLSession.shared.dataTask(with: URL) { data, response, error in
guard error == nil, let responseData = data else
{
print(error)
completion(false, nil)
return
}
do
{
guard let categoriesDict = try JSONSerialization.jsonObject(with: responseData, options: []) as? [String: AnyObject] else
{
print("error trying to convert data to JSON")
completion(false, nil)
return
}
if let categoriesArray = categoriesDict["categories"] as? [[String : AnyObject]]
{
let categoriesList = BBObjectFactory.createCategoriesList(fromCategoriesArray: categoriesArray)
completion(true, categoriesList)
}
else
{
completion(false, nil)
}
}
catch
{
print("error trying to convert data to JSON")
completion(false, nil)
}
}
task.resume()
}
}
| mit | 76cf4599e7e35249f7a56e36c688bb64 | 33.789474 | 201 | 0.566314 | 5.518553 | false | false | false | false |
huangboju/Moots | 优雅处理/Result-master/Result/Result.swift | 1 | 7074 | // Copyright (c) 2015 Rob Rix. All rights reserved.
/// An enum representing either a failure with an explanatory error, or a success with a result value.
public enum Result<T, Error: Swift.Error>: ResultProtocol, CustomStringConvertible, CustomDebugStringConvertible {
case success(T)
case failure(Error)
// MARK: Constructors
/// Constructs a success wrapping a `value`.
public init(value: T) {
self = .success(value)
}
/// Constructs a failure wrapping an `error`.
public init(error: Error) {
self = .failure(error)
}
/// Constructs a result from an `Optional`, failing with `Error` if `nil`.
public init(_ value: T?, failWith: @autoclosure () -> Error) {
self = value.map(Result.success) ?? .failure(failWith())
}
/// Constructs a result from a function that uses `throw`, failing with `Error` if throws.
public init(_ f: @autoclosure () throws -> T) {
self.init(attempt: f)
}
/// Constructs a result from a function that uses `throw`, failing with `Error` if throws.
public init(attempt f: () throws -> T) {
do {
self = .success(try f())
} catch var error {
if Error.self == AnyError.self {
error = AnyError(error)
}
self = .failure(error as! Error)
}
}
// MARK: Deconstruction
/// Returns the value from `success` Results or `throw`s the error.
public func dematerialize() throws -> T {
switch self {
case let .success(value):
return value
case let .failure(error):
throw error
}
}
/// Case analysis for Result.
///
/// Returns the value produced by applying `ifFailure` to `failure` Results, or `ifSuccess` to `success` Results.
public func analysis<Result>(ifSuccess: (T) -> Result, ifFailure: (Error) -> Result) -> Result {
switch self {
case let .success(value):
return ifSuccess(value)
case let .failure(value):
return ifFailure(value)
}
}
// MARK: Errors
/// The domain for errors constructed by Result.
public static var errorDomain: String { return "com.antitypical.Result" }
/// The userInfo key for source functions in errors constructed by Result.
public static var functionKey: String { return "\(errorDomain).function" }
/// The userInfo key for source file paths in errors constructed by Result.
public static var fileKey: String { return "\(errorDomain).file" }
/// The userInfo key for source file line numbers in errors constructed by Result.
public static var lineKey: String { return "\(errorDomain).line" }
/// Constructs an error.
public static func error(_ message: String? = nil, function: String = #function, file: String = #file, line: Int = #line) -> NSError {
var userInfo: [String: Any] = [
functionKey: function,
fileKey: file,
lineKey: line,
]
if let message = message {
userInfo[NSLocalizedDescriptionKey] = message
}
return NSError(domain: errorDomain, code: 0, userInfo: userInfo)
}
// MARK: CustomStringConvertible
public var description: String {
return analysis(
ifSuccess: { ".success(\($0))" },
ifFailure: { ".failure(\($0))" })
}
// MARK: CustomDebugStringConvertible
public var debugDescription: String {
return description
}
}
// MARK: - Derive result from failable closure
public func materialize<T>(_ f: () throws -> T) -> Result<T, AnyError> {
return materialize(try f())
}
public func materialize<T>(_ f: @autoclosure () throws -> T) -> Result<T, AnyError> {
do {
return .success(try f())
} catch {
return .failure(AnyError(error))
}
}
// MARK: - Cocoa API conveniences
#if !os(Linux)
/// Constructs a `Result` with the result of calling `try` with an error pointer.
///
/// This is convenient for wrapping Cocoa API which returns an object or `nil` + an error, by reference. e.g.:
///
/// Result.try { NSData(contentsOfURL: URL, options: .dataReadingMapped, error: $0) }
public func `try`<T>(_ function: String = #function, file: String = #file, line: Int = #line, `try`: (NSErrorPointer) -> T?) -> Result<T, NSError> {
var error: NSError?
return `try`(&error).map(Result.success) ?? .failure(error ?? Result<T, NSError>.error(function: function, file: file, line: line))
}
/// Constructs a `Result` with the result of calling `try` with an error pointer.
///
/// This is convenient for wrapping Cocoa API which returns a `Bool` + an error, by reference. e.g.:
///
/// Result.try { NSFileManager.defaultManager().removeItemAtURL(URL, error: $0) }
public func `try`(_ function: String = #function, file: String = #file, line: Int = #line, `try`: (NSErrorPointer) -> Bool) -> Result<(), NSError> {
var error: NSError?
return `try`(&error) ?
.success(())
: .failure(error ?? Result<(), NSError>.error(function: function, file: file, line: line))
}
#endif
// MARK: - ErrorProtocolConvertible conformance
extension NSError: ErrorProtocolConvertible {
public static func error(from error: Swift.Error) -> Self {
func cast<T: NSError>(_ error: Swift.Error) -> T {
return error as! T
}
return cast(error)
}
}
// MARK: - Errors
/// An “error” that is impossible to construct.
///
/// This can be used to describe `Result`s where failures will never
/// be generated. For example, `Result<Int, NoError>` describes a result that
/// contains an `Int`eger and is guaranteed never to be a `failure`.
public enum NoError: Swift.Error, Equatable {
public static func ==(lhs: NoError, rhs: NoError) -> Bool {
return true
}
}
/// A type-erased error which wraps an arbitrary error instance. This should be
/// useful for generic contexts.
public struct AnyError: Swift.Error {
/// The underlying error.
public let error: Swift.Error
public init(_ error: Swift.Error) {
if let anyError = error as? AnyError {
self = anyError
} else {
self.error = error
}
}
}
extension AnyError: ErrorProtocolConvertible {
public static func error(from error: Error) -> AnyError {
return AnyError(error)
}
}
extension AnyError: CustomStringConvertible {
public var description: String {
return String(describing: error)
}
}
// There appears to be a bug in Foundation on Linux which prevents this from working:
// https://bugs.swift.org/browse/SR-3565
// Don't forget to comment the tests back in when removing this check when it's fixed!
#if !os(Linux)
extension AnyError: LocalizedError {
public var errorDescription: String? {
return error.localizedDescription
}
public var failureReason: String? {
return (error as? LocalizedError)?.failureReason
}
public var helpAnchor: String? {
return (error as? LocalizedError)?.helpAnchor
}
public var recoverySuggestion: String? {
return (error as? LocalizedError)?.recoverySuggestion
}
}
#endif
// MARK: - migration support
@available(*, unavailable, message: "Use the overload which returns `Result<T, AnyError>` instead")
public func materialize<T>(_ f: () throws -> T) -> Result<T, NSError> {
fatalError()
}
@available(*, unavailable, message: "Use the overload which returns `Result<T, AnyError>` instead")
public func materialize<T>(_ f: @autoclosure () throws -> T) -> Result<T, NSError> {
fatalError()
}
// MARK: -
import Foundation
| mit | d31a4727421f99ca21b0e00790290b05 | 27.857143 | 148 | 0.689675 | 3.633094 | false | false | false | false |
IBM-MIL/IBM-Ready-App-for-Venue | iOS/VenueUITests/VenueMapUITests.swift | 1 | 16206 | /*
Licensed Materials - Property of IBM
© Copyright IBM Corporation 2015. All Rights Reserved.
*/
import XCTest
class VenueMapUITests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
// In UI tests it is usually best to stop immediately when a failure occurs.
continueAfterFailure = false
let app = XCUIApplication()
// UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method.
app.launch()
NSThread.sleepForTimeInterval(4)
if(app.tables["Users List"].exists){
app.swipeUp()
app.tables["Users List"].staticTexts["Milbuild"].tap()
}
if(app.pageIndicators["page 1 of 5"].exists){
app.buttons["Skip Tutorial"].tap()
}
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
/**
provides async waiting to make sure the UI components needed
are on screen when necessary
*/
func expectData(obj: NSObject){
let exists = NSPredicate(format: "exists == 1")
expectationForPredicate(exists, evaluatedWithObject: obj, handler: nil)
waitForExpectationsWithTimeout(10, handler: nil)
}
/**
Verifies that the location of the current user is shown
*/
func testUserCurrentLocation() {
let app = XCUIApplication()
let mapButton = app.tabBars.buttons["Map"]
expectData(mapButton)
mapButton.tap()
XCTAssertNotNil(app.buttons["your location"])
}
/**
Verifies the people labels match with bottom detail when tapped
*/
func testPeopleLocation(){
let app = XCUIApplication()
let mapButton = app.tabBars.buttons["Map"]
expectData(mapButton)
mapButton.tap()
var peopleCount: Int = 0
app.scrollViews.containingType(.Button, identifier:"Vortex Map Pin Dining").element.swipeRight()
app.buttons["Andrew Jacobs"].tap()
XCTAssertEqual("Andrew Jacobs", app.staticTexts["POIName"].label)
peopleCount++
app.buttons["Lauren Akers"].tap()
XCTAssertEqual("Lauren Akers", app.staticTexts["POIName"].label)
peopleCount++
app.buttons["Tony Ballands"].tap()
XCTAssertEqual("Tony Ballands", app.staticTexts["POIName"].label)
peopleCount++
app.buttons["Bart Black"].tap()
XCTAssertEqual("Bart Black", app.staticTexts["POIName"].label)
peopleCount++
app.buttons["Alicia Clark"].tap()
XCTAssertEqual("Alicia Clark", app.staticTexts["POIName"].label)
app.buttons["Tall Tex"].tap()
app.buttons["Anaconda"].tap()
peopleCount++
app.buttons["Security"].tap()
app.buttons["Melvin Hallam"].tap()
XCTAssertEqual("Melvin Hallam", app.staticTexts["POIName"].label)
peopleCount++
app.buttons["Ned Greyson"].tap()
XCTAssertEqual("Ned Greyson", app.staticTexts["POIName"].label)
peopleCount++
app.buttons["Dylan Dunham"].tap()
XCTAssertEqual("Dylan Dunham", app.staticTexts["POIName"].label)
peopleCount++
app.buttons["Francesca Cortez"].tap()
XCTAssertEqual("Francesca Cortez", app.staticTexts["POIName"].label)
app.buttons["Dylan Dunham"].tap()
app.buttons["Melvin Hallam"].tap()
peopleCount++
app.buttons["Amir Tiwari"].tap()
XCTAssertEqual("Amir Tiwari", app.staticTexts["POIName"].label)
peopleCount++
app.buttons["Tori Thomas"].tap()
XCTAssertEqual("Tori Thomas", app.staticTexts["POIName"].label)
peopleCount++
XCTAssertEqual(peopleCount, 11)
}
/**
Verifies that each POI type corresponds to the actual count
*/
func testMapPOICounts(){
let app = XCUIApplication()
let mapButton = app.tabBars.buttons["Map"]
expectData(mapButton)
mapButton.tap()
XCTAssertEqual(getRideCount(), 8)
XCTAssertEqual(getDiningCount(), 12)
XCTAssertEqual(getGameCount(), 6)
let lockerCount = app.scrollViews.childrenMatchingType(.Button).matchingIdentifier("Vortex Map Pin Lockers").count
XCTAssertEqual(lockerCount, 1)
let waterRideCount = XCUIApplication().scrollViews.childrenMatchingType(.Button).matchingIdentifier("Vortex Map Pin WaterRides").count
XCTAssertEqual(waterRideCount, 1)
let lostFoundCount = app.scrollViews.childrenMatchingType(.Button).matchingIdentifier("Vortex Map Pin LostAndFound").count
XCTAssertEqual(lostFoundCount, 1)
let guestServicesCount = app.scrollViews.childrenMatchingType(.Button).matchingIdentifier("Vortex Map Pin GuestServices").count
XCTAssertEqual(guestServicesCount, 1)
let firstAidCount = app.scrollViews.childrenMatchingType(.Button).matchingIdentifier("Vortex Map Pin FirstAid").count
XCTAssertEqual(firstAidCount, 1)
let securityCount = app.scrollViews.childrenMatchingType(.Button).matchingIdentifier("Vortex Map Pin Security").count
XCTAssertEqual(securityCount, 1)
let entertainmentCount = app.scrollViews.childrenMatchingType(.Button).matchingIdentifier("Vortex Map Pin Entertainment").count
XCTAssertEqual(entertainmentCount, 1)
let shopCount = app.scrollViews.childrenMatchingType(.Button).matchingIdentifier("Vortex Map Pin Shopping").count
XCTAssertEqual(shopCount, 1)
XCTAssertEqual(getRestroomCount(), 4)
}
/**
Helper function to get ride count
*/
func getRideCount()->UInt{
let rideCount = XCUIApplication().scrollViews.childrenMatchingType(.Button).matchingIdentifier("Vortex Map Pin Rides").count
return rideCount
}
/**
Helper function to get game count
*/
func getGameCount()->UInt{
let gameCount = XCUIApplication().scrollViews.childrenMatchingType(.Button).matchingIdentifier("Vortex Map Pin Games").count
return gameCount
}
/**
Helper function to get dining count
*/
func getDiningCount()->UInt{
let getDiningCount = XCUIApplication().scrollViews.childrenMatchingType(.Button).matchingIdentifier("Vortex Map Pin Dining").count
return getDiningCount
}
/**
Helper function to get restroom count
*/
func getRestroomCount()->UInt{
let restroomCount = XCUIApplication().scrollViews.childrenMatchingType(.Button).matchingIdentifier("Vortex Map Pin Restrooms").count
return restroomCount
}
/**
verifies the map filter functionality
*/
func testMapFilter(){
let app = XCUIApplication()
let mapButton = app.tabBars.buttons["Map"]
expectData(mapButton)
mapButton.tap()
app.buttons["Vortex Map Filter"].tap()
let cellsQuery = app.collectionViews.cells
cellsQuery.otherElements.containingType(.StaticText, identifier:"Rides").images["filterImage"].tap()
cellsQuery.otherElements.containingType(.StaticText, identifier:"Dining").images["filterImage"].tap()
app.buttons["Apply"].tap()
//verify number of Rides
//verify that other all filtered pins are shown
XCTAssertEqual(getRideCount(), 8)
checkAllRides(app)
XCTAssertEqual(getDiningCount(), 12)
checkAllDining()
app.buttons["Vortex Map Filter"].tap()
cellsQuery.otherElements.containingType(.StaticText, identifier:"Entertainment").images["filterImage"].tap()
cellsQuery.otherElements.containingType(.StaticText, identifier:"Water Rides").images["filterImage"].tap()
cellsQuery.otherElements.containingType(.StaticText, identifier:"Rides").images["filterImage"].tap()
cellsQuery.otherElements.containingType(.StaticText, identifier:"Dining").images["filterImage"].tap()
app.buttons["Apply"].tap()
//verify that all filtered pins are shown
app.buttons["Anaconda"].tap()
XCTAssertEqual(app.buttons["Anaconda"].identifier, app.staticTexts["POIName"].label)
app.swipeRight()
app.buttons["Ye Olde Brickland Theater"].tap()
XCTAssertEqual(app.buttons["Ye Olde Brickland Theater"].identifier, app.staticTexts["POIName"].label)
app.buttons["Vortex Map Filter"].tap()
cellsQuery.otherElements.containingType(.StaticText, identifier:"Clear Filters").images["filterImage"].tap()
cellsQuery.otherElements.containingType(.StaticText, identifier:"People").images["filterImage"].tap()
cellsQuery.otherElements.containingType(.StaticText, identifier:"Security").images["filterImage"].tap()
app.buttons["Apply"].tap()
//verify that all filtered pins are shown
testPeopleLocation()
}
/**
Helper function to verify ride and dinning pin details
*/
func testPOIRidesAndDinning(){
let app = XCUIApplication()
let mapButton = app.tabBars.buttons["Map"]
expectData(mapButton)
mapButton.tap()
checkAllRides(app)
checkAllDining()
}
/**
Helper function to verify ride details on the map
*/
func checkAllRides(app: XCUIElement){
//check all the Rides and verify Bottom Bar name
let rides = app.scrollViews.childrenMatchingType(.Button).matchingIdentifier("Vortex Map Pin Rides")
for(var index: UInt = 0; index<rides.count; ++index){
let ride = rides.elementBoundByIndex(index)
XCTAssertTrue(ride.exists)
ride.tap()
XCTAssertEqual(ride.identifier, app.staticTexts["POIName"].label)
switch index{
case 0:
app.swipeRight()
case 1:
app.buttons["Cup O' Joe 2 Go"].tap()
case 3:
app.buttons["Merry Go Round"].tap()
case 5:
app.buttons["Pete's Pretzels"].tap()
case 6:
app.buttons["Pete's Pretzels"].tap()
app.buttons["Merry Go Round"].tap()
app.buttons["Brick Blaster"].tap()
default:
print("Other Options")
}
}
}
/**
Helper function to verify dining details on the map
*/
func checkAllDining(){
let app = XCUIApplication()
//check all the Dining Pins and verify Bottom Bar name
let dining = app.scrollViews.childrenMatchingType(.Button).matchingIdentifier("Vortex Map Pin Dining")
var dinerID: NSString
for(var index: UInt = 0; index<dining.count; ++index){
switch index{
case 0:
app.swipeDown()
case 1:
app.buttons["Cup O' Joe 2 Go"].tap()
case 4:
app.buttons["Funnel Cake Fever"].tap()
app.buttons["Cup O' Joe 2 Go"].tap()
case 6:
app.buttons["Cactus Canyon"].tap()
app.buttons["Tall Tex"].tap()
app.buttons["Tejas Twister"].tap()
case 8:
app.buttons["Pete's Pretzels"].tap()
app.buttons["Merry Go Round"].tap()
app.scrollViews.childrenMatchingType(.Button).matchingIdentifier("Frosty Freeze").elementBoundByIndex(3).tap()
app.buttons["Sweets 'N' Treats"].tap()
case 10:
app.buttons["Merry Go Round"].tap()
case 11:
app.buttons["Tejas Twister"].tap()
default:
print("Other Options")
}
let diner = dining.elementBoundByIndex(index)
dinerID = diner.identifier
XCTAssertTrue(diner.exists)
dining.elementBoundByIndex(index).tap()
XCTAssertEqual(dinerID, app.staticTexts["POIName"].label)
}
}
/**
Helper function to verify game pin details
*/
func testPOIGames(){
let app = XCUIApplication()
let mapButton = app.tabBars.buttons["Map"]
expectData(mapButton)
mapButton.tap()
//check all the Games and verify Bottom Bar name
let rides = app.scrollViews.childrenMatchingType(.Button).matchingIdentifier("Vortex Map Pin Games")
for(var index: UInt = 0; index<rides.count; ++index){
switch index{
case 0:
app.buttons["Anaconda"].tap()
//check Water Ride category
XCTAssertEqual(app.buttons["Anaconda"].identifier, app.staticTexts["POIName"].label)
case 1:
app.buttons["Anaconda"].tap()
app.buttons["Tall Tex"].tap()
app.buttons["Cactus Canyon"].tap()
app.buttons["Brick Blaster"].tap()
case 2,5:
app.swipeLeft()
case 3:
app.buttons["Tall Tex"].tap()
case 4:
app.buttons["Wonder Wheel"].tap()
default:
print("Other Options")
}
let ride = rides.elementBoundByIndex(index)
ride.tap()
XCTAssertEqual(ride.identifier, app.staticTexts["POIName"].label)
}
}
/**
Helper function to verify pin details in small categories
*/
func testPOIOther(){
let app = XCUIApplication()
let mapButton = app.tabBars.buttons["Map"]
expectData(mapButton)
mapButton.tap()
//check all the Games and verify Bottom Bar name
let pois = app.scrollViews.childrenMatchingType(.Button).matchingIdentifier("Vortex Map Pin Restrooms")
for(var index: UInt = 0; index<pois.count; ++index){
switch index{
case 0:
app.buttons["Tall Tex"].tap()
app.buttons["Brickland Bazaar"].tap()
//check Shopping category
XCTAssertEqual(app.buttons["Brickland Bazaar"].identifier, app.staticTexts["POIName"].label)
case 1:
app.swipeLeft()
case 2:
app.swipeRight()
case 3:
app.buttons["Brick Blaster"].tap()
app.buttons["First Aid"].tap()
//check First Aid category
XCTAssertEqual(app.buttons["First Aid"].identifier, app.staticTexts["POIName"].label)
default:
print("Other Options")
}
let poi = pois.elementBoundByIndex(index)
poi.tap()
XCTAssertEqual(poi.identifier, app.staticTexts["POIName"].label)
}
//check Guest Services category
app.buttons["Guest Services"].tap()
XCTAssertEqual(app.buttons["Guest Services"].identifier, app.staticTexts["POIName"].label)
//check Lost & Found category
app.buttons["Lost & Found"].tap()
XCTAssertEqual(app.buttons["Lost & Found"].identifier, app.staticTexts["POIName"].label)
//check Security category
app.buttons["Security"].tap()
XCTAssertEqual(app.buttons["Security"].identifier, app.staticTexts["POIName"].label)
//check Lockers category
app.buttons["Lockers"].tap()
XCTAssertEqual(app.buttons["Lockers"].identifier, app.staticTexts["POIName"].label)
//check Entertainment category
app.buttons["Wonder Wheel"].tap()
app.buttons["Ye Olde Brickland Theater"].tap()
XCTAssertEqual(app.buttons["Ye Olde Brickland Theater"].identifier, app.staticTexts["POIName"].label)
}
}
| epl-1.0 | 6b4543b8840e40b74fdfe0c285f47fb1 | 36.86215 | 142 | 0.602098 | 4.872219 | false | false | false | false |
davoda/Localide | Localide/Classes/NSUserDetauls+Localide.swift | 1 | 1889 | //
// NSUserDetauls+Localide.swift
// Localide
//
// Created by David Elsonbaty on 5/29/16.
// Copyright © 2016 David Elsonbaty. All rights reserved.
//
import Foundation
internal extension UserDefaults {
fileprivate static let PreferredMapAppKey = "Localide.Preferred-Map-App"
fileprivate static let MapAppChoicesKey = "Localide.Installed-Map-Apps"
internal class func didSetPrefferedMapApp(fromChoices choices: [LocalideMapApp]) -> Bool {
return (self.preferredMapApp(fromChoices: choices) != nil)
}
internal class func preferredMapApp(fromChoices choices: [LocalideMapApp]) -> LocalideMapApp? {
// Ensure a preferred map app is set
guard let preferredMapAppIndex = UserDefaults.standard.object(forKey: UserDefaults.PreferredMapAppKey) as? Int else { return nil }
// Ensure there were no changes to the previous state of installed apps.
guard previousMapAppChoices() == choices else { return nil }
return LocalideMapApp(rawValue: preferredMapAppIndex)
}
internal class func setPreferredMapApp(_ app: LocalideMapApp, fromMapAppChoices choices: [LocalideMapApp]) {
// Save the preferred map app
UserDefaults.standard.set(app.rawValue, forKey: UserDefaults.PreferredMapAppKey)
// Save the current state of map app choices
UserDefaults.standard.set(choices.map({ $0.rawValue }), forKey: UserDefaults.MapAppChoicesKey)
}
internal class func resetMapAppPreferences() {
UserDefaults.standard.removeObject(forKey: UserDefaults.PreferredMapAppKey)
UserDefaults.standard.removeObject(forKey: UserDefaults.MapAppChoicesKey)
}
fileprivate class func previousMapAppChoices() -> [LocalideMapApp] {
return (UserDefaults.standard.object(forKey: UserDefaults.MapAppChoicesKey) as! [Int]).map({ return LocalideMapApp(rawValue: $0)! })
}
}
| mit | 01a01edc6539a96b5e2b5701906af99a | 41.909091 | 140 | 0.731462 | 4.214286 | false | false | false | false |
PekanMmd/Pokemon-XD-Code | Objects/file formats/PKXModel.swift | 1 | 4139 | //
// PKXModel.swift
// GoD Tool
//
// Created by Stars Momodu on 08/04/2021.
//
import Foundation
class PKXModel {
var data: XGMutableData
var gameFormat: XGGame {
return data.getWordAtOffset(0x20) == 0xFFFFFFFF ? .XD : .Colosseum
}
var isTrainer: Bool {
// I've only looked at a few so not sure how accuracte this is
// I haven't seen a clear pattern for distinguishing the two
// And it's possible there isn't really a difference
return data.getByteAtOffset(0x1c) == 0 && data.get4BytesAtOffset(0x14) == 0
}
var pokemonSpecies: XGPokemon? {
// Not all pokemon have this set
let index = data.get2BytesAtOffset(0x18)
guard index > 0 else { return nil }
return .index(index)
}
lazy var shinyFilter: (modifiers: (red: Int, green: Int, blue: Int, unused: Int), colour: XGColour) = {
let shinyStartOffset = game == .XD ? 0x70 : data.length - 0x14
let mods = data.getWordStreamFromOffset(shinyStartOffset, length: 16).map{$0.int}
var rawColour = data.getWordAtOffset(shinyStartOffset + 16)
if game == .Colosseum {
// ARGB
rawColour = ((rawColour & 0xFF000000) >> 24) + ((rawColour & 0xFFFFFF) << 8)
}
return (
modifiers: (red: mods[0], green: mods[1], blue: mods[2], unused: 0),
colour: XGColour(raw: rawColour, format:.RGBA32)
)
}()
lazy var particleData: XGMutableData? = {
let gpt1Length = data.get4BytesAtOffset(gameFormat == .XD ? 8 : 4)
guard gpt1Length > 0 else { return nil }
var datLength = data.get4BytesAtOffset(0)
while datLength % 0x20 != 0 {
datLength += 1
}
var gpt1Start = gameFormat == .XD ? 0xE60 : 0x40 + datLength
let gpt1Data = data.getSubDataFromOffset(gpt1Start, length: gpt1Length)
gpt1Data.file = .nameAndFolder(data.file.fileName + ".gpt1", data.file.folder)
return gpt1Data
}()
lazy var datModel: DATModel = {
let datLength = data.get4BytesAtOffset(0)
var gpt1Length = data.get4BytesAtOffset(gameFormat == .XD ? 8 : 4)
while gpt1Length % 0x20 != 0 {
gpt1Length += 1
}
var datStart = gameFormat == .XD ? 0xE60 + gpt1Length : 0x40
let datData = data.getSubDataFromOffset(datStart, length: datLength)
datData.file = .nameAndFolder(data.file.fileName + ".dat", data.file.folder)
return DATModel(data: datData)
}()
lazy var animationsMetaData: [String: Int] = {
var gpt1Length = data.get4BytesAtOffset(gameFormat == .XD ? 8 : 4)
while gpt1Length % 0x20 != 0 {
gpt1Length += 1
}
var datLength = data.get4BytesAtOffset(0)
while datLength % 0x20 != 0 {
datLength += 1
}
let firstMetaDataOffset = gameFormat == .XD ? 0x84 : 0x40 + datLength + gpt1Length
let kSizeOfAnimationMetaData = 0xD0
let kAnimationMetaDataAnimationIndexOffset = 0x90
let names = isTrainer ? pkxMetaDataTrainerAnimationNames : pkxMetaDataPokemonAnimationNames
var metaData = [String: Int]()
for i in 0 ..< names.count {
let offset = firstMetaDataOffset + (i * kSizeOfAnimationMetaData)
if offset + kSizeOfAnimationMetaData <= data.length {
metaData[names[i]] = data.getByteAtOffset(offset + kAnimationMetaDataAnimationIndexOffset)
}
}
return metaData
}()
convenience init?(file: XGFiles) {
guard let data = file.data else { return nil }
self.init(data: data)
}
init(data: XGMutableData) {
self.data = data
}
var pkxMetaDataPokemonAnimationNames: [String] {
if gameFormat == .XD {
return [
""
]
} else {
return [
""
]
}
}
var pkxMetaDataTrainerAnimationNames: [String] {
if gameFormat == .XD {
return [
"Idle",
"Pokeball Throw",
"Victory",
"Battle Intro",
"Frustrated",
"Victory",
"Unused 1",
"Unused 2",
"Unused 3",
"Unused 4",
"Defeat",
"Unused 5",
"Unused 6",
"Unused 7",
"Unused 8",
"Unused 9",
"Unused 10",
]
} else {
return [
"Idle",
"Pokeball Throw",
"Victory",
"Unknown 1",
"Unknown 2",
"Victory",
"Battle Intro",
"Unused 1",
"Unused 2",
"Hit by Shadow Pokemon 1",
"Hit by Shadow Pokemon 2",
"Defeat",
"Unused 3",
"Unused 4",
"Unused 5",
"Unused 6",
"Unused 7",
"Unused 8",
]
}
}
}
| gpl-2.0 | 86d29209b3435c25c5209659ce10f87c | 24.549383 | 104 | 0.651365 | 2.931303 | false | false | false | false |
fvaldez/score_point_ios | scorePoint/RequestsVC.swift | 1 | 3383 | //
// RequestsVC.swift
// scorePoint
//
// Created by Adriana Gonzalez on 4/4/16.
// Copyright © 2016 Adriana Gonzalez. All rights reserved.
//
import UIKit
class RequestsVC: UIViewController, UITableViewDelegate, UITableViewDataSource, requestSelectedDelegate {
@IBOutlet weak var tableView: UITableView!
var requestsArray = ["Some Player", "Some Player"]
var requestsSentArray = ["Some Player", "Some Player"]
override func viewDidLoad() {
super.viewDidLoad()
self.title = "Match Requests"
self.tabBarItem.title = ""
tableView.delegate = self
tableView.dataSource = self
let nibName = UINib(nibName: "RequestCell", bundle:nil)
self.tableView.register(nibName, forCellReuseIdentifier: "RequestCell")
}
override func viewWillAppear(_ animated: Bool) {
UIApplication.shared.statusBarStyle = UIStatusBarStyle.lightContent
}
func numberOfSections(in tableView: UITableView) -> Int {
return 2
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
if(section == 0){
return "Received"
}else{
return "Sent"
}
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if(section == 0){
return requestsArray.count
}else{
return requestsSentArray.count
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let player = requestsArray[indexPath.row]
let playerSent = requestsSentArray[indexPath.row]
if let cell = tableView.dequeueReusableCell(withIdentifier: "RequestCell") as? RequestCell {
cell.delegate = self
cell.mainBtn.tag = indexPath.row
if(indexPath.section == 0){
cell.configureCell(player, received: true )
}else{
cell.configureCell(playerSent, received: false)
}
cell.selectionStyle = .none
return cell
}else {
let cell = RequestCell()
cell.delegate = self
cell.mainBtn.tag = indexPath.row
if(indexPath.section == 0){
cell.configureCell(player, received: true )
}else{
cell.configureCell(playerSent, received: false)
}
cell.selectionStyle = .none
return cell
}
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 80.0
}
func requestSelected(delete: Bool, index: Int) {
let indexPath = IndexPath(row: index, section: 1)
let indexSet = IndexSet(integer: 1)
if(delete == true){
requestsSentArray.remove(at: indexPath.row)
tableView.beginUpdates()
tableView.reloadSections(indexSet, with: .fade)
tableView.endUpdates()
}else{
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let vc = storyboard.instantiateViewController(withIdentifier: "GameSetupVC") as! GameSetupVC
vc.sendingRequest = false
self.present(vc, animated: true, completion: nil)
}
}
}
| mit | cc3d9036d2f486714fa5484230e6ded4 | 30.90566 | 106 | 0.598758 | 5.017804 | false | false | false | false |
kylef/Curassow | Sources/Curassow/Signals.swift | 1 | 1687 | #if os(Linux)
import Glibc
#else
import Darwin.C
#endif
import fd
var sharedHandler: SignalHandler?
class SignalHandler {
enum Signal {
case interrupt
case quit
case ttin
case ttou
case terminate
case child
}
class func registerSignals() {
signal(SIGTERM) { _ in sharedHandler?.handle(.terminate) }
signal(SIGINT) { _ in sharedHandler?.handle(.interrupt) }
signal(SIGQUIT) { _ in sharedHandler?.handle(.quit) }
signal(SIGTTIN) { _ in sharedHandler?.handle(.ttin) }
signal(SIGTTOU) { _ in sharedHandler?.handle(.ttou) }
signal(SIGCHLD) { _ in sharedHandler?.handle(.child) }
}
class func reset() {
signal(SIGTERM, SIG_DFL)
signal(SIGINT, SIG_DFL)
signal(SIGQUIT, SIG_DFL)
signal(SIGTTIN, SIG_DFL)
signal(SIGTTOU, SIG_DFL)
signal(SIGCHLD, SIG_DFL)
}
var pipe: (reader: ReadableFileDescriptor, writer: WritableFileDescriptor)
var signalQueue: [Signal] = []
init() throws {
pipe = try fd.pipe()
pipe.reader.closeOnExec = true
pipe.reader.blocking = false
pipe.writer.closeOnExec = true
pipe.writer.blocking = false
}
// Wake up the process by writing to the pipe
func wakeup() {
_ = try? pipe.writer.write([46])
}
func handle(_ signal: Signal) {
signalQueue.append(signal)
wakeup()
}
var callbacks: [Signal: () -> ()] = [:]
func register(_ signal: Signal, _ callback: @escaping () -> ()) {
callbacks[signal] = callback
}
func process() -> Bool {
let result = !signalQueue.isEmpty
if !signalQueue.isEmpty {
if let handler = callbacks[signalQueue.removeFirst()] {
handler()
}
}
return result
}
}
| bsd-2-clause | 740d1470a10526b71c6ed801f35de579 | 21.197368 | 76 | 0.638411 | 3.5 | false | false | false | false |
scoremedia/Fisticuffs | Sources/Fisticuffs/UIKit/UIControl+Binding.swift | 1 | 3108 | // The MIT License (MIT)
//
// Copyright (c) 2015 theScore Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
private var b_enabled_key = 0
private var b_onTap_key = 0
private var trampolines_key = 0
public extension UIControl {
var b_enabled: BindableProperty<UIControl, Bool> {
associatedObjectProperty(self, &b_enabled_key) { _ in
BindableProperty(self, setter: { control, value -> Void in
control.isEnabled = value
})
}
}
var b_onTap: Fisticuffs.Event<Void> {
associatedObjectProperty(self, &b_onTap_key) { _ in
self.addTarget(self, action: #selector(self.b_receivedOnTap(_:)), for: .touchUpInside)
return Fisticuffs.Event<Void>()
}
}
@objc fileprivate func b_receivedOnTap(_ sender: AnyObject) {
b_onTap.fire(())
}
}
public extension UIControl {
/**
Get an Event<UIEvent?> for the specified events
- parameter controlEvents: Control events to subscribe to
- returns: The Event object
*/
func b_controlEvent(_ controlEvents: UIControl.Event) -> Fisticuffs.Event<UIEvent?> {
let trampolinesCollection = associatedObjectProperty(self, &trampolines_key) { _ in ControlEventTrampolineCollection() }
if let trampoline = trampolinesCollection.trampolines[controlEvents.rawValue] {
return trampoline.event
} else {
let trampoline = ControlEventTrampoline()
addTarget(trampoline, action: #selector(ControlEventTrampoline.receivedEvent(_:uiEvent:)), for: controlEvents)
trampolinesCollection.trampolines[controlEvents.rawValue] = trampoline
return trampoline.event
}
}
}
private class ControlEventTrampolineCollection: NSObject {
var trampolines: [UInt: ControlEventTrampoline] = [:]
}
private class ControlEventTrampoline: NSObject {
let event = Event<UIEvent?>()
@objc func receivedEvent(_ sender: AnyObject?, uiEvent: UIEvent?) {
event.fire(uiEvent)
}
}
| mit | 1dc595ea39279c1988c4c4ace96ab01f | 33.153846 | 128 | 0.691763 | 4.334728 | false | false | false | false |
ishkawa/DIKit | Sources/DIGenKit/Structure/Import.swift | 1 | 1720 | //
// Import.swift
// DIGenKit
//
// Created by Yosuke Ishikawa on 2017/11/13.
//
import Foundation
import SourceKittenFramework
struct Import {
let moduleName: String
static func imports(from file: File) throws -> [Import] {
let syntaxMap = try SyntaxMap(file: file)
let importTokenIndices = syntaxMap.tokens.enumerated()
.compactMap { index, token -> Int? in
guard token.type == "source.lang.swift.syntaxtype.keyword" else {
return nil
}
let view = file.contents.utf8
let startIndex = view.index(view.startIndex, offsetBy: Int(token.offset))
let endIndex = view.index(startIndex, offsetBy: Int(token.length))
let value = String(view[startIndex..<endIndex])!
return value == "import" ? index : nil
}
let importedModuleNames = importTokenIndices
.compactMap { index -> String? in
let identifierIndex = index + 1
guard identifierIndex < syntaxMap.tokens.count else {
return nil
}
let token = syntaxMap.tokens[identifierIndex]
guard token.type == "source.lang.swift.syntaxtype.identifier" else {
return nil
}
let view = file.contents.utf8
let startIndex = view.index(view.startIndex, offsetBy: Int(token.offset))
let endIndex = view.index(startIndex, offsetBy: Int(token.length))
return String(view[startIndex..<endIndex])!
}
return importedModuleNames.map(Import.init(moduleName:))
}
}
| mit | 48f94c30f8c50c517b13c20a063ad10f | 34.102041 | 89 | 0.568605 | 4.858757 | false | false | false | false |
coderMONSTER/iosstar | iOSStar/Scenes/Market/CustomView/PubInfoHeaderView.swift | 1 | 1862 | //
// PubInfoHeaderView.swift
// iOSStar
//
// Created by J-bb on 17/5/10.
// Copyright © 2017年 YunDian. All rights reserved.
//
import UIKit
class PubInfoHeaderView: UITableViewHeaderFooterView {
lazy var lineView: UIView = {
let view = UIView()
view.backgroundColor = UIColor(hexString: AppConst.Color.main)
return view
}()
lazy var titleLabel: UILabel = {
let label = UILabel()
label.text = "个人简介"
label.font = UIFont.systemFont(ofSize: 16)
label.textColor = UIColor(hexString: "333333")
return label
}()
override init(reuseIdentifier: String?) {
super.init(reuseIdentifier: reuseIdentifier)
contentView.backgroundColor = UIColor(hexString: "fafafa")
addSubview(lineView)
addSubview(titleLabel)
lineView.snp.makeConstraints { (make) in
make.left.equalTo(12)
make.width.equalTo(3)
make.height.equalTo(17)
make.centerY.equalTo(self)
}
titleLabel.snp.makeConstraints { (make) in
make.left.equalTo(lineView.snp.right).offset(7)
make.centerY.equalTo(lineView)
make.height.equalTo(15)
}
let bottomLineView = UIView()
bottomLineView.backgroundColor = UIColor(hexString: "E5E5E5")
addSubview(bottomLineView)
bottomLineView.snp.makeConstraints { (make) in
make.bottom.equalTo(-1)
make.height.equalTo(1)
make.left.equalTo(lineView)
make.right.equalTo(-12)
}
bringSubview(toFront: bottomLineView)
}
func setTitle(title:String) {
titleLabel.text = title
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| gpl-3.0 | b0eeec369996a2af7e27b8e6a9ebbeb5 | 27.476923 | 70 | 0.602917 | 4.438849 | false | false | false | false |
ymkil/LKImagePicker | LKImagePicker/Configuration.swift | 1 | 10594 | //
// Configuration.swift
// LKImagePicker
//
// Created by Mkil on 19/12/2016.
// Copyright © 2016 黎宁康. All rights reserved.
//
import UIKit
import Photos
internal enum LKOscillatoryAnimationType {
case bigger
case smaller
}
@objc public protocol LKImagePickerControllerDelegate: class {
@objc optional func imagePickerControllerDidFinish(_ picker:LKImagePickerController, _ photos:[UIImage], _ assets:[Any], _ isSelectOriginalPhoto:Bool)
@objc optional func imagePickerControllerDidCancel(_ picker:LKImagePickerController)
}
public struct ImagePickerConfig {
/// 默认最大可选9张图片
public var maxImagesCount = 9 {
didSet {
if maxImagesCount > 1 {
showSelectBtn = true
}
}
}
/// 最小图片必选张数,默认是0
public var minImagesCount = 0
/// 默认按修改时间升序,默认为true,如果设置为false,最新照片会显示在最前面,内部拍照按钮会排在第一个
public var sortAscendingByModificationDate = true
/// 默认为true,如果设置为false,原图按钮将隐藏
public var allowPickingOriginImage = true
// TODO: 暂时不支持播放视频,会尽快完善
/// 默认为true,如果设置为false,将不能选择发送视频
public var allowPickingVideo = true {
didSet {
if !allowPickingVideo {
allowPickingImage = true
}
}
}
/// 默认为true,如果设置为false,将不能选择发送图片
public var allowPickingImage = true {
didSet {
if !allowPickingImage {
allowPickingVideo = true
}
}
}
/// 默认为true,如果设置为false,将不能在选择器中拍照
public var allowTakePicture = true
// 默认为true,如果设置为false,预览按钮将隐藏,用户将不能取预览照片
public var allowPreview = true
/// 默认为false,如果设置true,会自动修正图片
public var shouldFixOrientation = false
/// 默认为true,图片展示列表自动滑动到底部
public var shouldScrollToBottom = true
/// 默认为true,如果设置为false,选择器将不会自动dismiss
public var autoDismiss = true
/// 默认828像素宽
public var photoWidth: CGFloat = 828
/// 取图片超过15秒还没有成功时,会自动dis missHUD
public var timeout:Int = 15
/// collection list 一行显示的个数(2 <= columnNumber <= 6),默认为4
public var columnNumber:Int = 4 {
didSet {
if columnNumber <= 2 {
columnNumber = 2
} else if columnNumber >= 6 {
columnNumber = 6
}
}
}
/// 在单选模式
public var showSelectBtn = true {
didSet {
// 多选模式下,不允许showSelectBtn为false
if !showSelectBtn && maxImagesCount > 1 {
showSelectBtn = true
}
}
}
public var pushPicturePickerVc = true
}
public struct Configuration {
public static let ScreenWinth = UIScreen.main.bounds.size.width
public static let ScreenHeight = UIScreen.main.bounds.size.height
public static let NavBarHeight = CGFloat(64)
public static let LKScreenScale: CGFloat = {
var scale:CGFloat = 2.0
if UIScreen.main.bounds.size.width > 700 {
scale = 1.5
}
return scale
}()
public static let LKScreenWidth: CGFloat = {
let width = UIScreen.main.bounds.size.width
return width
}()
internal static let photoPreviewMaxWidth:CGFloat = 600
//MARK: Colors
public static var navBarBackgroundColor = UIColor(red: 34/255.0, green: 34/255.0, blue: 34/255.0, alpha: 1)
public static var buttonBackgroundColorNormal = UIColor(red: 83/255.0, green: 179/255.0, blue: 17/255.0, alpha: 1)
public static var bottomBarBackgrounddColor = UIColor(red: 253/255.0, green: 253/255.0, blue: 253/255.0, alpha: 1)
public static var okButtonTitleColorNormal = UIColor(red: 83/255.0, green: 179/255.0, blue: 17/255.0, alpha: 1.0)
public static var okButtonTitleColorDisabled = UIColor(red: 83/255.0, green: 179/255.0, blue: 17/255.0, alpha: 0.5)
public static var previewBarBackgroundColor = UIColor(red: 34/255.0, green: 34/255.0, blue: 34/255.0, alpha: 0.7)
// MARK: Fonts
public static var bigFont = UIFont.systemFont(ofSize: 16)
public static var middleFont = UIFont.systemFont(ofSize: 14)
public static var smallFont = UIFont.systemFont(ofSize: 12)
// MARK: Image
public static var photoOriginDefImageName = "photo_original_def"
public static var photoOriginSelImageName = "photo_original_sel"
public static var photoNumberIconImageName = "preview_number_icon"
public static var previewNavBarBackImageName = "navi_back"
public static var photoDefImageName = "photo_photoPickerVc_def"
public static var photoSelImageName = "photo_sel_photoPickerVc"
public static var photoAssetCameraName = "picture"
public static var videoSendIconName = "VideoSendIcon"
}
//MARK: - extension
internal extension String {
var toFloat: Float {
let numberFormatter = NumberFormatter()
return numberFormatter.number(from: self)?.floatValue ?? 0
}
var toDouble: Double {
let numberFormatter = NumberFormatter()
return numberFormatter.number(from: self)?.doubleValue ?? 0
}
var toInt: Int {
let numberFormatter = NumberFormatter()
return numberFormatter.number(from: self)?.intValue ?? 0
}
}
internal extension UIView {
var lk_left: CGFloat{
return frame.origin.x
}
func setLk_left(_ x: CGFloat) -> Void{
var rect = frame
rect.origin.x = x;
frame = rect
}
var lk_top: CGFloat {
return frame.origin.y
}
func setLk_top(_ y: CGFloat) -> Void {
var rect = frame
rect.origin.y = y
frame = rect
}
var lk_right: CGFloat {
return frame.origin.x + frame.size.width
}
func setLk_right(_ right: CGFloat) -> Void {
var rect = frame
rect.origin.x = right - rect.size.width
frame = rect
}
var lk_bottom: CGFloat {
return frame.origin.y + frame.size.height
}
func setLk_bottom(_ bottom: CGFloat) -> Void {
var rect = frame
rect.origin.y = bottom - rect.size.height
frame = rect
}
var lk_width:CGFloat {
return frame.size.width
}
func setLk_width(_ width: CGFloat) -> Void {
var rect = frame
rect.size.width = width
frame = rect
}
var lk_height: CGFloat {
return frame.size.height
}
func setLk_height(_ height: CGFloat) -> Void {
var rect = frame
rect.size.height = height
frame = rect
}
var lk_centerX: CGFloat {
return center.x
}
func setLk_centerX(_ centerX: CGFloat) -> Void {
center = CGPoint(x: centerX, y: center.y)
}
var lk_centerY: CGFloat{
return center.y
}
func setLk_centerY(_ centerY: CGFloat) -> Void {
center = CGPoint(x: center.x, y: centerY)
}
var lk_origin: CGPoint {
return frame.origin
}
func setLk_origin(_ origin: CGPoint) -> Void {
var rect = frame
rect.origin = origin
frame = rect
}
var lk_size: CGSize {
return frame.size
}
func setLk_size(_ size: CGSize) -> Void {
var rect = frame
rect.size = size
frame = rect
}
class func showOscillatoryAnimationWithLayer(layer:CALayer, type:LKOscillatoryAnimationType) {
let scale1 = type == .bigger ? 1.15 : 0.5
let scale2 = type == .bigger ? 0.92 : 1.15
UIView.animate(withDuration: 0.15, delay: 0, options: .beginFromCurrentState, animations: {
layer.setValue(scale1, forKeyPath: "transform.scale")
}) { (finished) in
UIView.animate(withDuration: 0.15, delay: 0, options: [.beginFromCurrentState,.curveEaseOut], animations: {
layer.setValue(scale2, forKeyPath: "transform.scale")
}, completion: { (finished) in
UIView.animate(withDuration: 0.1, delay: 0, options: [.beginFromCurrentState,.curveEaseOut], animations: {
layer.setValue(1.0, forKeyPath: "transform.scale")
}, completion: nil)
})
}
}
}
internal extension UIImage {
class func imageNamedFromMyBundle(name:String) -> UIImage? {
var image = UIImage(named: "LKImagePicker.bundle/".appending(name))
if image == nil {
image = UIImage(named: "Frameworks/LKImagePicker.framework/LKImagePicker.bundle/".appending(name))
if image == nil {
image = UIImage(named: name)
}
}
return image
}
}
private var lkBundle: Bundle? = nil
private var localizedBundle: Bundle? = nil
internal extension Bundle {
static var lk_imagePickerBundle:Bundle {
if lkBundle == nil {
var path = Bundle.main.path(forResource: "LKImagePicker", ofType: "bundle")
if path == nil {
path = Bundle.main.path(forResource: "LKImagePicker", ofType: "bundle", inDirectory: "Frameworks/LKImagePicker.framework/")
}
lkBundle = Bundle(path: path!)
}
return lkBundle!
}
class func lk_localizedString(key: String, _ value: String = "") -> String {
if localizedBundle == nil {
var language = NSLocale.preferredLanguages.first
if let tempLanguage = language {
if tempLanguage.range(of: "zh-Hans") != nil {
language = "zh-Hans"
} else {
language = "en"
}
}
localizedBundle = Bundle(path: Bundle.lk_imagePickerBundle.path(forResource: language, ofType: "lproj")!)
}
if let bundle = localizedBundle {
return bundle.localizedString(forKey: key, value: value, table: nil)
}
return ""
}
}
| mit | 2acd5f45feb9fc0f828872fa4e771815 | 27.160112 | 153 | 0.59192 | 4.26233 | false | false | false | false |
4faramita/TweeBox | TweeBox/SearchTimelineTableViewController.swift | 1 | 3142 | //
// Created by 4faramita on 2017/8/24.
// Copyright (c) 2017 4faramita. All rights reserved.
//
import Foundation
import UIKit
class SearchTimelineTableViewController: TimelineTableViewController {
var query: String? {
didSet {
refreshTimeline(handler: nil)
}
}
var resultType: SearchResultType {
return .recent
}
@IBAction func done(_ sender: UIBarButtonItem) {
dismiss(animated: true, completion: nil)
}
override func setAndPerformSegueForHashtag() {
let destinationViewController = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "SearchTimelineViewController")
let segue = UIStoryboardSegue(identifier: "Show Tweets with Hashtag", source: self, destination: destinationViewController) {
self.navigationController?.show(destinationViewController, sender: self)
}
self.prepare(for: segue, sender: self)
segue.perform()
}
override func refreshTimeline(handler: (() -> Void)?) {
let replyTimelineParams = SearchTweetParams(
query: self.query ?? "",
resultType: self.resultType,
until: nil,
sinceID: nil, // this two will be managed
maxID: nil, // in timeline data retriever
includeEntities: true,
resourceURL: ResourceURL.search_tweets
)
let searchTimeline = SearchTimeline(
maxID: maxID,
sinceID: sinceID,
fetchNewer: fetchNewer,
resourceURL: replyTimelineParams.resourceURL,
params: replyTimelineParams
)
searchTimeline.fetchData { [weak self] (maxID, sinceID, tweets) in
if (self?.maxID == nil) && (self?.sinceID == nil) {
if let sinceID = sinceID {
self?.sinceID = sinceID
}
if let maxID = maxID {
self?.maxID = maxID
}
} else {
if (self?.fetchNewer)! {
if let sinceID = sinceID {
self?.sinceID = sinceID
}
} else {
if let maxID = maxID {
self?.maxID = maxID
}
}
}
print(">>> tweets >> \(tweets.count)")
if tweets.count > 0 {
self?.insertNewTweets(with: tweets)
let cells = self?.tableView.visibleCells
if cells != nil {
for cell in cells! {
let indexPath = self?.tableView.indexPath(for: cell)
if let tweetCell = cell as? GeneralTweetTableViewCell {
tweetCell.section = indexPath?.section
}
}
}
}
if let handler = handler {
handler()
}
}
}
}
| mit | 6131f6b74e4baadb261d0a5532e1e124 | 29.211538 | 153 | 0.497454 | 5.610714 | false | false | false | false |
soapyigu/Swift30Projects | Project 03 - FacebookMe/FacebookMe/Specs.swift | 1 | 1937 | //
// Specs.swift
// FacebookMe
//
// Copyright © 2017 Yi Gu. All rights reserved.
//
import UIKit
public struct Specs {
public struct Color {
public let tint = UIColor(hex: 0x3b5998)
public let red = UIColor.red
public let white = UIColor.white
public let black = UIColor.black
public let gray = UIColor.lightGray
}
public struct FontSize {
public let tiny: CGFloat = 10
public let small: CGFloat = 12
public let regular: CGFloat = 14
public let large: CGFloat = 16
}
public struct Font {
private static let regularName = "Helvetica Neue"
private static let boldName = "Helvetica Neue Bold"
public let tiny = UIFont(name: regularName, size: Specs.fontSize.tiny)
public let small = UIFont(name: regularName, size: Specs.fontSize.small)
public let regular = UIFont(name: regularName, size: Specs.fontSize.regular)
public let large = UIFont(name: regularName, size: Specs.fontSize.large)
public let smallBold = UIFont(name: boldName, size: Specs.fontSize.small)
public let regularBold = UIFont(name: boldName, size: Specs.fontSize.regular)
public let largeBold = UIFont(name: boldName, size: Specs.fontSize.large)
}
public struct ImageName {
public let friends = "fb_friends"
public let events = "fb_events"
public let groups = "fb_groups"
public let education = "fb_education"
public let townHall = "fb_town_hall"
public let instantGames = "fb_games"
public let settings = "fb_settings"
public let privacyShortcuts = "fb_privacy_shortcuts"
public let helpSupport = "fb_help_and_support"
public let placeholder = "fb_placeholder"
}
public static var color: Color {
return Color()
}
public static var fontSize: FontSize {
return FontSize()
}
public static var font: Font {
return Font()
}
public static var imageName: ImageName {
return ImageName()
}
}
| apache-2.0 | f4134461e5fbb25211dda923db5414aa | 28.333333 | 81 | 0.68595 | 3.975359 | false | false | false | false |
blockchain/My-Wallet-V3-iOS | Modules/Platform/Sources/PlatformUIKit/Foundation/Accessibility/Accessibility+LineItem.swift | 1 | 2605 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
import Foundation
extension Accessibility.Identifier {
public enum LineItem {
public enum Base {}
public enum Transactional {}
}
}
extension Accessibility.Identifier.LineItem.Base {
private static let prefix = "LineItem."
public static let titleLabel = "\(prefix)titleLabel"
public static let descriptionLabel = "\(prefix)descriptionLabel"
public static let disclaimerLabel = "\(prefix)disclaimerLabel"
public static let disclaimerImage = "\(prefix)disclaimerImage"
}
extension Accessibility.Identifier.LineItem.Transactional {
private static let prefix = "LineItem."
public static let themeBackgroundImageView = "\(prefix)themeBackgroundImageView"
public static let bankName = "\(prefix)bankName"
public static let iban = "\(prefix)iban"
public static let bankCountry = "\(prefix)bankCountry"
public static let accountNumber = "\(prefix)accountNumber"
public static let sortCode = "\(prefix)sortCode"
public static let bankCode = "\(prefix)bankCode"
public static let routingNumber = "\(prefix)routingNumber"
public static let recipient = "\(prefix)recipient"
public static let amountToSend = "\(prefix)amountToSend"
public static let date = "\(prefix)date"
public static let totalCost = "\(prefix)totalCost"
public static let total = "\(prefix)total"
public static let gasFor = "\(prefix)gasFor"
public static let memo = "\(prefix)memo"
public static let from = "\(prefix)from"
public static let to = "\(prefix)to"
public static let estimatedAmount = "\(prefix)estimatedAmount"
public static let amount = "\(prefix)amount"
public static let `for` = "\(prefix)for"
public static let buyingFee = "\(prefix)buyingFee"
public static let networkFee = "\(prefix)networkFee"
public static let exchangeRate = "\(prefix)exchangeRate"
public static let paymentMethod = "\(prefix)paymentMethod"
public static let orderId = "\(prefix)orderId"
public static let sendingTo = "\(prefix)sendingTo"
public static let status = "\(prefix)status"
public static let bankTransfer = "\(prefix)bankTransfer"
public static let pending = "\(prefix)pending"
public static let cryptoAmount = "\(prefix)cryptoAmount"
public static let fiatAmount = "\(prefix)fiatAmount"
public static let value = "\(prefix)value"
public static let fee = "\(prefix)fee"
public static let availableToTrade = "\(prefix)availableToTrade"
public static let cryptoPrice = "\(prefix)cryptoPrice"
}
| lgpl-3.0 | 20ab693ccb282fb675a342a4c41588d0 | 43.135593 | 84 | 0.713902 | 4.666667 | false | false | false | false |
gouyz/GYZBaking | baking/Pods/IQKeyboardManagerSwift/IQKeyboardManagerSwift/IQKeyboardManager.swift | 2 | 105100 | //
// IQKeyboardManager.swift
// https://github.com/hackiftekhar/IQKeyboardManager
// Copyright (c) 2013-16 Iftekhar Qurashi.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
import CoreGraphics
import UIKit
import QuartzCore
///---------------------
/// MARK: IQToolbar tags
///---------------------
/**
Codeless drop-in universal library allows to prevent issues of keyboard sliding up and cover UITextField/UITextView. Neither need to write any code nor any setup required and much more. A generic version of KeyboardManagement. https://developer.apple.com/library/ios/documentation/StringsTextFonts/Conceptual/TextAndWebiPhoneOS/KeyboardManagement/KeyboardManagement.html
*/
open class IQKeyboardManager: NSObject, UIGestureRecognizerDelegate {
/**
Default tag for toolbar with Done button -1002.
*/
fileprivate static let kIQDoneButtonToolbarTag = -1002
/**
Default tag for toolbar with Previous/Next buttons -1005.
*/
fileprivate static let kIQPreviousNextButtonToolbarTag = -1005
///---------------------------
/// MARK: UIKeyboard handling
///---------------------------
/**
Registered classes list with library.
*/
fileprivate var registeredClasses = [UIView.Type]()
/**
Enable/disable managing distance between keyboard and textField. Default is YES(Enabled when class loads in `+(void)load` method).
*/
open var enable = false {
didSet {
//If not enable, enable it.
if enable == true &&
oldValue == false {
//If keyboard is currently showing. Sending a fake notification for keyboardWillShow to adjust view according to keyboard.
if _kbShowNotification != nil {
keyboardWillShow(_kbShowNotification)
}
showLog("enabled")
} else if enable == false &&
oldValue == true { //If not disable, desable it.
keyboardWillHide(nil)
showLog("disabled")
}
}
}
fileprivate func privateIsEnabled()-> Bool {
var isEnabled = enable
if let textFieldViewController = _textFieldView?.viewController() {
if isEnabled == false {
//If viewController is kind of enable viewController class, then assuming it's enabled.
for enabledClass in enabledDistanceHandlingClasses {
if textFieldViewController.isKind(of: enabledClass) {
isEnabled = true
break
}
}
}
if isEnabled == true {
//If viewController is kind of disabled viewController class, then assuming it's disabled.
for disabledClass in disabledDistanceHandlingClasses {
if textFieldViewController.isKind(of: disabledClass) {
isEnabled = false
break
}
}
//Special Controllers
if isEnabled == true {
let classNameString = NSStringFromClass(type(of:textFieldViewController.self))
//_UIAlertControllerTextFieldViewController
if (classNameString.contains("UIAlertController") && classNameString.hasSuffix("TextFieldViewController")) {
isEnabled = false
}
}
}
}
return isEnabled
}
/**
To set keyboard distance from textField. can't be less than zero. Default is 10.0.
*/
open var keyboardDistanceFromTextField: CGFloat {
set {
_privateKeyboardDistanceFromTextField = max(0, newValue)
showLog("keyboardDistanceFromTextField: \(_privateKeyboardDistanceFromTextField)")
}
get {
return _privateKeyboardDistanceFromTextField
}
}
/**
Boolean to know if keyboard is showing.
*/
open var keyboardShowing: Bool {
get {
return _privateIsKeyboardShowing
}
}
/**
moved distance to the top used to maintain distance between keyboard and textField. Most of the time this will be a positive value.
*/
open var movedDistance: CGFloat {
get {
return _privateMovedDistance
}
}
/**
Prevent keyboard manager to slide up the rootView to more than keyboard height. Default is YES.
*/
open var preventShowingBottomBlankSpace = true
/**
Returns the default singleton instance.
*/
open class func sharedManager() -> IQKeyboardManager {
struct Static {
//Singleton instance. Initializing keyboard manger.
static let kbManager = IQKeyboardManager()
}
/** @return Returns the default singleton instance. */
return Static.kbManager
}
///-------------------------
/// MARK: IQToolbar handling
///-------------------------
/**
Automatic add the IQToolbar functionality. Default is YES.
*/
open var enableAutoToolbar = true {
didSet {
privateIsEnableAutoToolbar() ?addToolbarIfRequired():removeToolbarIfRequired()
let enableToolbar = enableAutoToolbar ? "Yes" : "NO"
showLog("enableAutoToolbar: \(enableToolbar)")
}
}
fileprivate func privateIsEnableAutoToolbar() -> Bool {
var enableToolbar = enableAutoToolbar
if let textFieldViewController = _textFieldView?.viewController() {
if enableToolbar == false {
//If found any toolbar enabled classes then return.
for enabledClass in enabledToolbarClasses {
if textFieldViewController.isKind(of: enabledClass) {
enableToolbar = true
break
}
}
}
if enableToolbar == true {
//If found any toolbar disabled classes then return.
for disabledClass in disabledToolbarClasses {
if textFieldViewController.isKind(of: disabledClass) {
enableToolbar = false
break
}
}
//Special Controllers
if enableToolbar == true {
let classNameString = NSStringFromClass(type(of:textFieldViewController.self))
//_UIAlertControllerTextFieldViewController
if (classNameString.contains("UIAlertController") && classNameString.hasSuffix("TextFieldViewController")) {
enableToolbar = false
}
}
}
}
return enableToolbar
}
/**
/**
IQAutoToolbarBySubviews: Creates Toolbar according to subview's hirarchy of Textfield's in view.
IQAutoToolbarByTag: Creates Toolbar according to tag property of TextField's.
IQAutoToolbarByPosition: Creates Toolbar according to the y,x position of textField in it's superview coordinate.
Default is IQAutoToolbarBySubviews.
*/
AutoToolbar managing behaviour. Default is IQAutoToolbarBySubviews.
*/
open var toolbarManageBehaviour = IQAutoToolbarManageBehaviour.bySubviews
/**
If YES, then uses textField's tintColor property for IQToolbar, otherwise tint color is black. Default is NO.
*/
open var shouldToolbarUsesTextFieldTintColor = false
/**
This is used for toolbar.tintColor when textfield.keyboardAppearance is UIKeyboardAppearanceDefault. If shouldToolbarUsesTextFieldTintColor is YES then this property is ignored. Default is nil and uses black color.
*/
open var toolbarTintColor : UIColor?
/**
This is used for toolbar.barTintColor. Default is nil and uses white color.
*/
open var toolbarBarTintColor : UIColor?
/**
IQPreviousNextDisplayModeDefault: Show NextPrevious when there are more than 1 textField otherwise hide.
IQPreviousNextDisplayModeAlwaysHide: Do not show NextPrevious buttons in any case.
IQPreviousNextDisplayModeAlwaysShow: Always show nextPrevious buttons, if there are more than 1 textField then both buttons will be visible but will be shown as disabled.
*/
open var previousNextDisplayMode = IQPreviousNextDisplayMode.Default
/**
Toolbar done button icon, If nothing is provided then check toolbarDoneBarButtonItemText to draw done button.
*/
open var toolbarDoneBarButtonItemImage : UIImage?
/**
Toolbar done button text, If nothing is provided then system default 'UIBarButtonSystemItemDone' will be used.
*/
open var toolbarDoneBarButtonItemText : String?
/**
If YES, then it add the textField's placeholder text on IQToolbar. Default is YES.
*/
@available(*,deprecated, message: "This is renamed to `shouldShowToolbarPlaceholder` for more clear naming.")
open var shouldShowTextFieldPlaceholder: Bool {
set {
shouldShowToolbarPlaceholder = newValue
}
get {
return shouldShowToolbarPlaceholder
}
}
open var shouldShowToolbarPlaceholder = true
/**
Placeholder Font. Default is nil.
*/
open var placeholderFont: UIFont?
///--------------------------
/// MARK: UITextView handling
///--------------------------
/** used to adjust contentInset of UITextView. */
fileprivate var startingTextViewContentInsets = UIEdgeInsets.zero
/** used to adjust scrollIndicatorInsets of UITextView. */
fileprivate var startingTextViewScrollIndicatorInsets = UIEdgeInsets.zero
/** used with textView to detect a textFieldView contentInset is changed or not. (Bug ID: #92)*/
fileprivate var isTextViewContentInsetChanged = false
///---------------------------------------
/// MARK: UIKeyboard appearance overriding
///---------------------------------------
/**
Override the keyboardAppearance for all textField/textView. Default is NO.
*/
open var overrideKeyboardAppearance = false
/**
If overrideKeyboardAppearance is YES, then all the textField keyboardAppearance is set using this property.
*/
open var keyboardAppearance = UIKeyboardAppearance.default
///-----------------------------------------------------------
/// MARK: UITextField/UITextView Next/Previous/Resign handling
///-----------------------------------------------------------
/**
Resigns Keyboard on touching outside of UITextField/View. Default is NO.
*/
open var shouldResignOnTouchOutside = false {
didSet {
_tapGesture.isEnabled = privateShouldResignOnTouchOutside()
let shouldResign = shouldResignOnTouchOutside ? "Yes" : "NO"
showLog("shouldResignOnTouchOutside: \(shouldResign)")
}
}
/** TapGesture to resign keyboard on view's touch. It's a readonly property and exposed only for adding/removing dependencies if your added gesture does have collision with this one */
fileprivate var _tapGesture: UITapGestureRecognizer!
open var resignFirstResponderGesture: UITapGestureRecognizer {
get {
return _tapGesture
}
}
/*******************************************/
fileprivate func privateShouldResignOnTouchOutside() -> Bool {
var shouldResign = shouldResignOnTouchOutside
if let textFieldViewController = _textFieldView?.viewController() {
if shouldResign == false {
//If viewController is kind of enable viewController class, then assuming shouldResignOnTouchOutside is enabled.
for enabledClass in enabledTouchResignedClasses {
if textFieldViewController.isKind(of: enabledClass) {
shouldResign = true
break
}
}
}
if shouldResign == true {
//If viewController is kind of disable viewController class, then assuming shouldResignOnTouchOutside is disable.
for disabledClass in disabledTouchResignedClasses {
if textFieldViewController.isKind(of: disabledClass) {
shouldResign = false
break
}
}
//Special Controllers
if shouldResign == true {
let classNameString = NSStringFromClass(type(of:textFieldViewController.self))
//_UIAlertControllerTextFieldViewController
if (classNameString.contains("UIAlertController") && classNameString.hasSuffix("TextFieldViewController")) {
shouldResign = false
}
}
}
}
return shouldResign
}
/**
Resigns currently first responder field.
*/
@discardableResult open func resignFirstResponder()-> Bool {
if let textFieldRetain = _textFieldView {
//Resigning first responder
let isResignFirstResponder = textFieldRetain.resignFirstResponder()
// If it refuses then becoming it as first responder again. (Bug ID: #96)
if isResignFirstResponder == false {
//If it refuses to resign then becoming it first responder again for getting notifications callback.
textFieldRetain.becomeFirstResponder()
showLog("Refuses to resign first responder: \(String(describing: _textFieldView?._IQDescription()))")
}
return isResignFirstResponder
}
return false
}
/**
Returns YES if can navigate to previous responder textField/textView, otherwise NO.
*/
open var canGoPrevious: Bool {
//Getting all responder view's.
if let textFields = responderViews() {
if let textFieldRetain = _textFieldView {
//Getting index of current textField.
if let index = textFields.index(of: textFieldRetain) {
//If it is not first textField. then it's previous object canBecomeFirstResponder.
if index > 0 {
return true
}
}
}
}
return false
}
/**
Returns YES if can navigate to next responder textField/textView, otherwise NO.
*/
open var canGoNext: Bool {
//Getting all responder view's.
if let textFields = responderViews() {
if let textFieldRetain = _textFieldView {
//Getting index of current textField.
if let index = textFields.index(of: textFieldRetain) {
//If it is not first textField. then it's previous object canBecomeFirstResponder.
if index < textFields.count-1 {
return true
}
}
}
}
return false
}
/**
Navigate to previous responder textField/textView.
*/
@discardableResult open func goPrevious()-> Bool {
//Getting all responder view's.
if let textFieldRetain = _textFieldView {
if let textFields = responderViews() {
//Getting index of current textField.
if let index = textFields.index(of: textFieldRetain) {
//If it is not first textField. then it's previous object becomeFirstResponder.
if index > 0 {
let nextTextField = textFields[index-1]
let isAcceptAsFirstResponder = nextTextField.becomeFirstResponder()
// If it refuses then becoming previous textFieldView as first responder again. (Bug ID: #96)
if isAcceptAsFirstResponder == false {
//If next field refuses to become first responder then restoring old textField as first responder.
textFieldRetain.becomeFirstResponder()
showLog("Refuses to become first responder: \(nextTextField._IQDescription())")
}
return isAcceptAsFirstResponder
}
}
}
}
return false
}
/**
Navigate to next responder textField/textView.
*/
@discardableResult open func goNext()-> Bool {
//Getting all responder view's.
if let textFieldRetain = _textFieldView {
if let textFields = responderViews() {
//Getting index of current textField.
if let index = textFields.index(of: textFieldRetain) {
//If it is not last textField. then it's next object becomeFirstResponder.
if index < textFields.count-1 {
let nextTextField = textFields[index+1]
let isAcceptAsFirstResponder = nextTextField.becomeFirstResponder()
// If it refuses then becoming previous textFieldView as first responder again. (Bug ID: #96)
if isAcceptAsFirstResponder == false {
//If next field refuses to become first responder then restoring old textField as first responder.
textFieldRetain.becomeFirstResponder()
showLog("Refuses to become first responder: \(nextTextField._IQDescription())")
}
return isAcceptAsFirstResponder
}
}
}
}
return false
}
/** previousAction. */
internal func previousAction (_ barButton : IQBarButtonItem) {
//If user wants to play input Click sound.
if shouldPlayInputClicks == true {
//Play Input Click Sound.
UIDevice.current.playInputClick()
}
if canGoPrevious == true {
if let textFieldRetain = _textFieldView {
let isAcceptAsFirstResponder = goPrevious()
if isAcceptAsFirstResponder &&
barButton.invocation.target != nil &&
barButton.invocation.action != nil {
UIApplication.shared.sendAction(barButton.invocation.action!, to: barButton.invocation.target, from: textFieldRetain, for: UIEvent())
}
}
}
}
/** nextAction. */
internal func nextAction (_ barButton : IQBarButtonItem) {
//If user wants to play input Click sound.
if shouldPlayInputClicks == true {
//Play Input Click Sound.
UIDevice.current.playInputClick()
}
if canGoNext == true {
if let textFieldRetain = _textFieldView {
let isAcceptAsFirstResponder = goNext()
if isAcceptAsFirstResponder &&
barButton.invocation.target != nil &&
barButton.invocation.action != nil {
UIApplication.shared.sendAction(barButton.invocation.action!, to: barButton.invocation.target, from: textFieldRetain, for: UIEvent())
}
}
}
}
/** doneAction. Resigning current textField. */
internal func doneAction (_ barButton : IQBarButtonItem) {
//If user wants to play input Click sound.
if shouldPlayInputClicks == true {
//Play Input Click Sound.
UIDevice.current.playInputClick()
}
if let textFieldRetain = _textFieldView {
//Resign textFieldView.
let isResignedFirstResponder = resignFirstResponder()
if isResignedFirstResponder &&
barButton.invocation.target != nil &&
barButton.invocation.action != nil{
UIApplication.shared.sendAction(barButton.invocation.action!, to: barButton.invocation.target, from: textFieldRetain, for: UIEvent())
}
}
}
/** Resigning on tap gesture. (Enhancement ID: #14)*/
internal func tapRecognized(_ gesture: UITapGestureRecognizer) {
if gesture.state == UIGestureRecognizerState.ended {
//Resigning currently responder textField.
_ = resignFirstResponder()
}
}
/** Note: returning YES is guaranteed to allow simultaneous recognition. returning NO is not guaranteed to prevent simultaneous recognition, as the other gesture's delegate may return YES. */
open func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
return false
}
/** To not detect touch events in a subclass of UIControl, these may have added their own selector for specific work */
open func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
// Should not recognize gesture if the clicked view is either UIControl or UINavigationBar(<Back button etc...) (Bug ID: #145)
for ignoreClass in touchResignedGestureIgnoreClasses {
if touch.view?.isKind(of: ignoreClass) == true {
return false
}
}
return true
}
///-----------------------
/// MARK: UISound handling
///-----------------------
/**
If YES, then it plays inputClick sound on next/previous/done click.
*/
open var shouldPlayInputClicks = true
///---------------------------
/// MARK: UIAnimation handling
///---------------------------
/**
If YES, then calls 'setNeedsLayout' and 'layoutIfNeeded' on any frame update of to viewController's view.
*/
open var layoutIfNeededOnUpdate = false
///-----------------------------------------------
/// @name InteractivePopGestureRecognizer handling
///-----------------------------------------------
/**
If YES, then always consider UINavigationController.view begin point as {0,0}, this is a workaround to fix a bug #464 because there are no notification mechanism exist when UINavigationController.view.frame gets changed internally.
*/
open var shouldFixInteractivePopGestureRecognizer = true
///------------------------------------
/// MARK: Class Level disabling methods
///------------------------------------
/**
Disable distance handling within the scope of disabled distance handling viewControllers classes. Within this scope, 'enabled' property is ignored. Class should be kind of UIViewController.
*/
open var disabledDistanceHandlingClasses = [UIViewController.Type]()
/**
Enable distance handling within the scope of enabled distance handling viewControllers classes. Within this scope, 'enabled' property is ignored. Class should be kind of UIViewController. If same Class is added in disabledDistanceHandlingClasses list, then enabledDistanceHandlingClasses will be ignored.
*/
open var enabledDistanceHandlingClasses = [UIViewController.Type]()
/**
Disable automatic toolbar creation within the scope of disabled toolbar viewControllers classes. Within this scope, 'enableAutoToolbar' property is ignored. Class should be kind of UIViewController.
*/
open var disabledToolbarClasses = [UIViewController.Type]()
/**
Enable automatic toolbar creation within the scope of enabled toolbar viewControllers classes. Within this scope, 'enableAutoToolbar' property is ignored. Class should be kind of UIViewController. If same Class is added in disabledToolbarClasses list, then enabledToolbarClasses will be ignore.
*/
open var enabledToolbarClasses = [UIViewController.Type]()
/**
Allowed subclasses of UIView to add all inner textField, this will allow to navigate between textField contains in different superview. Class should be kind of UIView.
*/
open var toolbarPreviousNextAllowedClasses = [UIView.Type]()
/**
Disabled classes to ignore 'shouldResignOnTouchOutside' property, Class should be kind of UIViewController.
*/
open var disabledTouchResignedClasses = [UIViewController.Type]()
/**
Enabled classes to forcefully enable 'shouldResignOnTouchOutsite' property. Class should be kind of UIViewController. If same Class is added in disabledTouchResignedClasses list, then enabledTouchResignedClasses will be ignored.
*/
open var enabledTouchResignedClasses = [UIViewController.Type]()
/**
if shouldResignOnTouchOutside is enabled then you can customise the behaviour to not recognise gesture touches on some specific view subclasses. Class should be kind of UIView. Default is [UIControl, UINavigationBar]
*/
open var touchResignedGestureIgnoreClasses = [UIView.Type]()
///-------------------------------------------
/// MARK: Third Party Library support
/// Add TextField/TextView Notifications customised NSNotifications. For example while using YYTextView https://github.com/ibireme/YYText
///-------------------------------------------
/**
Add/Remove customised Notification for third party customised TextField/TextView. Please be aware that the NSNotification object must be idential to UITextField/UITextView NSNotification objects and customised TextField/TextView support must be idential to UITextField/UITextView.
@param didBeginEditingNotificationName This should be identical to UITextViewTextDidBeginEditingNotification
@param didEndEditingNotificationName This should be identical to UITextViewTextDidEndEditingNotification
*/
open func registerTextFieldViewClass(_ aClass: UIView.Type, didBeginEditingNotificationName : String, didEndEditingNotificationName : String) {
registeredClasses.append(aClass)
NotificationCenter.default.addObserver(self, selector: #selector(self.textFieldViewDidBeginEditing(_:)), name: NSNotification.Name(rawValue: didBeginEditingNotificationName), object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(self.textFieldViewDidEndEditing(_:)), name: NSNotification.Name(rawValue: didEndEditingNotificationName), object: nil)
}
open func unregisterTextFieldViewClass(_ aClass: UIView.Type, didBeginEditingNotificationName : String, didEndEditingNotificationName : String) {
if let index = registeredClasses.index(where: { element in
return element == aClass.self
}) {
registeredClasses.remove(at: index)
}
NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: didBeginEditingNotificationName), object: nil)
NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: didEndEditingNotificationName), object: nil)
}
/**************************************************************************************/
///------------------------
/// MARK: Private variables
///------------------------
/*******************************************/
/** To save UITextField/UITextView object voa textField/textView notifications. */
fileprivate weak var _textFieldView: UIView?
/** To save rootViewController.view.frame. */
fileprivate var _topViewBeginRect = CGRect.zero
/** To save rootViewController */
fileprivate weak var _rootViewController: UIViewController?
/** To save topBottomLayoutConstraint original constant */
fileprivate var _layoutGuideConstraintInitialConstant: CGFloat = 0
/** To save topBottomLayoutConstraint original constraint reference */
fileprivate weak var _layoutGuideConstraint: NSLayoutConstraint?
/*******************************************/
/** Variable to save lastScrollView that was scrolled. */
fileprivate weak var _lastScrollView: UIScrollView?
/** LastScrollView's initial contentOffset. */
fileprivate var _startingContentOffset = CGPoint.zero
/** LastScrollView's initial scrollIndicatorInsets. */
fileprivate var _startingScrollIndicatorInsets = UIEdgeInsets.zero
/** LastScrollView's initial contentInsets. */
fileprivate var _startingContentInsets = UIEdgeInsets.zero
/*******************************************/
/** To save keyboardWillShowNotification. Needed for enable keyboard functionality. */
fileprivate var _kbShowNotification: Notification?
/** To save keyboard size. */
fileprivate var _kbSize = CGSize.zero
/** To save Status Bar size. */
fileprivate var _statusBarFrame = CGRect.zero
/** To save keyboard animation duration. */
fileprivate var _animationDuration = 0.25
/** To mimic the keyboard animation */
fileprivate var _animationCurve = UIViewAnimationOptions.curveEaseOut
/*******************************************/
/** Boolean to maintain keyboard is showing or it is hide. To solve rootViewController.view.frame calculations. */
fileprivate var _privateIsKeyboardShowing = false
fileprivate var _privateMovedDistance : CGFloat = 0.0
/** To use with keyboardDistanceFromTextField. */
fileprivate var _privateKeyboardDistanceFromTextField: CGFloat = 10.0
/**************************************************************************************/
///--------------------------------------
/// MARK: Initialization/Deinitialization
///--------------------------------------
/* Singleton Object Initialization. */
override init() {
super.init()
self.registerAllNotifications()
//Creating gesture for @shouldResignOnTouchOutside. (Enhancement ID: #14)
_tapGesture = UITapGestureRecognizer(target: self, action: #selector(self.tapRecognized(_:)))
_tapGesture.cancelsTouchesInView = false
_tapGesture.delegate = self
_tapGesture.isEnabled = shouldResignOnTouchOutside
//Loading IQToolbar, IQTitleBarButtonItem, IQBarButtonItem to fix first time keyboard appearance delay (Bug ID: #550)
let textField = UITextField()
textField.addDoneOnKeyboardWithTarget(nil, action: #selector(self.doneAction(_:)))
textField.addPreviousNextDoneOnKeyboardWithTarget(nil, previousAction: #selector(self.previousAction(_:)), nextAction: #selector(self.nextAction(_:)), doneAction: #selector(self.doneAction(_:)))
disabledDistanceHandlingClasses.append(UITableViewController.self)
disabledDistanceHandlingClasses.append(UIAlertController.self)
disabledToolbarClasses.append(UIAlertController.self)
disabledTouchResignedClasses.append(UIAlertController.self)
toolbarPreviousNextAllowedClasses.append(UITableView.self)
toolbarPreviousNextAllowedClasses.append(UICollectionView.self)
toolbarPreviousNextAllowedClasses.append(IQPreviousNextView.self)
touchResignedGestureIgnoreClasses.append(UIControl.self)
touchResignedGestureIgnoreClasses.append(UINavigationBar.self)
}
/** Override +load method to enable KeyboardManager when class loader load IQKeyboardManager. Enabling when app starts (No need to write any code) */
/** It doesn't work from Swift 1.2 */
// override public class func load() {
// super.load()
//
// //Enabling IQKeyboardManager.
// IQKeyboardManager.sharedManager().enable = true
// }
deinit {
// Disable the keyboard manager.
enable = false
//Removing notification observers on dealloc.
NotificationCenter.default.removeObserver(self)
}
/** Getting keyWindow. */
fileprivate func keyWindow() -> UIWindow? {
if let keyWindow = _textFieldView?.window {
return keyWindow
} else {
struct Static {
/** @abstract Save keyWindow object for reuse.
@discussion Sometimes [[UIApplication sharedApplication] keyWindow] is returning nil between the app. */
static var keyWindow : UIWindow?
}
/* (Bug ID: #23, #25, #73) */
let originalKeyWindow = UIApplication.shared.keyWindow
//If original key window is not nil and the cached keywindow is also not original keywindow then changing keywindow.
if originalKeyWindow != nil &&
(Static.keyWindow == nil || Static.keyWindow != originalKeyWindow) {
Static.keyWindow = originalKeyWindow
}
//Return KeyWindow
return Static.keyWindow
}
}
///-----------------------
/// MARK: Helper Functions
///-----------------------
/* Helper function to manipulate RootViewController's frame with animation. */
fileprivate func setRootViewFrame(_ frame: CGRect) {
// Getting topMost ViewController.
var controller = _textFieldView?.topMostController()
if controller == nil {
controller = keyWindow()?.topMostWindowController()
}
if let unwrappedController = controller {
var newFrame = frame
//frame size needs to be adjusted on iOS8 due to orientation structure changes.
newFrame.size = unwrappedController.view.frame.size
//Used UIViewAnimationOptionBeginFromCurrentState to minimize strange animations.
UIView.animate(withDuration: _animationDuration, delay: 0, options: UIViewAnimationOptions.beginFromCurrentState.union(_animationCurve), animations: { () -> Void in
// Setting it's new frame
unwrappedController.view.frame = newFrame
self.showLog("Set \(String(describing: controller?._IQDescription())) frame to : \(newFrame)")
//Animating content if needed (Bug ID: #204)
if self.layoutIfNeededOnUpdate == true {
//Animating content (Bug ID: #160)
unwrappedController.view.setNeedsLayout()
unwrappedController.view.layoutIfNeeded()
}
}) { (animated:Bool) -> Void in}
} else { // If can't get rootViewController then printing warning to user.
showLog("You must set UIWindow.rootViewController in your AppDelegate to work with IQKeyboardManager")
}
}
/* Adjusting RootViewController's frame according to interface orientation. */
fileprivate func adjustFrame() {
// We are unable to get textField object while keyboard showing on UIWebView's textField. (Bug ID: #11)
if _textFieldView == nil {
return
}
let textFieldView = _textFieldView!
let startTime = CACurrentMediaTime()
showLog("****** \(#function) started ******")
// Getting KeyWindow object.
let optionalWindow = keyWindow()
// Getting RootViewController. (Bug ID: #1, #4)
var optionalRootController = _textFieldView?.topMostController()
if optionalRootController == nil {
optionalRootController = keyWindow()?.topMostWindowController()
}
// Converting Rectangle according to window bounds.
let optionalTextFieldViewRect = textFieldView.superview?.convert(textFieldView.frame, to: optionalWindow)
if optionalRootController == nil ||
optionalWindow == nil ||
optionalTextFieldViewRect == nil {
return
}
let rootController = optionalRootController!
let window = optionalWindow!
let textFieldViewRect = optionalTextFieldViewRect!
// Getting RootViewRect.
var rootViewRect = rootController.view.frame
//Getting statusBarFrame
//Maintain keyboardDistanceFromTextField
var specialKeyboardDistanceFromTextField = textFieldView.keyboardDistanceFromTextField
if textFieldView.isSearchBarTextField() {
if let searchBar = textFieldView.superviewOfClassType(UISearchBar.self) {
specialKeyboardDistanceFromTextField = searchBar.keyboardDistanceFromTextField
}
}
let newKeyboardDistanceFromTextField = (specialKeyboardDistanceFromTextField == kIQUseDefaultKeyboardDistance) ? keyboardDistanceFromTextField : specialKeyboardDistanceFromTextField
var kbSize = _kbSize
kbSize.height += newKeyboardDistanceFromTextField
let statusBarFrame = UIApplication.shared.statusBarFrame
// (Bug ID: #250)
var layoutGuidePosition = IQLayoutGuidePosition.none
if let viewController = textFieldView.viewController() {
if let constraint = _layoutGuideConstraint {
var layoutGuide : UILayoutSupport?
if let itemLayoutGuide = constraint.firstItem as? UILayoutSupport {
layoutGuide = itemLayoutGuide
} else if let itemLayoutGuide = constraint.secondItem as? UILayoutSupport {
layoutGuide = itemLayoutGuide
}
if let itemLayoutGuide : UILayoutSupport = layoutGuide {
if (itemLayoutGuide === viewController.topLayoutGuide) //If topLayoutGuide constraint
{
layoutGuidePosition = .top
}
else if (itemLayoutGuide === viewController.bottomLayoutGuide) //If bottomLayoutGuice constraint
{
layoutGuidePosition = .bottom
}
}
}
}
let topLayoutGuide : CGFloat = statusBarFrame.height
var move : CGFloat = 0.0
// Move positive = textField is hidden.
// Move negative = textField is showing.
// Checking if there is bottomLayoutGuide attached (Bug ID: #250)
if layoutGuidePosition == .bottom {
// Calculating move position.
move = textFieldViewRect.maxY-(window.frame.height-kbSize.height)
} else {
// Calculating move position. Common for both normal and special cases.
move = min(textFieldViewRect.minY-(topLayoutGuide+5), textFieldViewRect.maxY-(window.frame.height-kbSize.height))
}
showLog("Need to move: \(move)")
var superScrollView : UIScrollView? = nil
var superView = textFieldView.superviewOfClassType(UIScrollView.self) as? UIScrollView
//Getting UIScrollView whose scrolling is enabled. // (Bug ID: #285)
while let view = superView {
if (view.isScrollEnabled) {
superScrollView = view
break
}
else {
// Getting it's superScrollView. // (Enhancement ID: #21, #24)
superView = view.superviewOfClassType(UIScrollView.self) as? UIScrollView
}
}
//If there was a lastScrollView. // (Bug ID: #34)
if let lastScrollView = _lastScrollView {
//If we can't find current superScrollView, then setting lastScrollView to it's original form.
if superScrollView == nil {
showLog("Restoring \(lastScrollView._IQDescription()) contentInset to : \(_startingContentInsets) and contentOffset to : \(_startingContentOffset)")
UIView.animate(withDuration: _animationDuration, delay: 0, options: UIViewAnimationOptions.beginFromCurrentState.union(_animationCurve), animations: { () -> Void in
lastScrollView.contentInset = self._startingContentInsets
lastScrollView.scrollIndicatorInsets = self._startingScrollIndicatorInsets
}) { (animated:Bool) -> Void in }
if lastScrollView.shouldRestoreScrollViewContentOffset == true {
lastScrollView.setContentOffset(_startingContentOffset, animated: true)
}
_startingContentInsets = UIEdgeInsets.zero
_startingScrollIndicatorInsets = UIEdgeInsets.zero
_startingContentOffset = CGPoint.zero
_lastScrollView = nil
} else if superScrollView != lastScrollView { //If both scrollView's are different, then reset lastScrollView to it's original frame and setting current scrollView as last scrollView.
showLog("Restoring \(lastScrollView._IQDescription()) contentInset to : \(_startingContentInsets) and contentOffset to : \(_startingContentOffset)")
UIView.animate(withDuration: _animationDuration, delay: 0, options: UIViewAnimationOptions.beginFromCurrentState.union(_animationCurve), animations: { () -> Void in
lastScrollView.contentInset = self._startingContentInsets
lastScrollView.scrollIndicatorInsets = self._startingScrollIndicatorInsets
}) { (animated:Bool) -> Void in }
if lastScrollView.shouldRestoreScrollViewContentOffset == true {
lastScrollView.setContentOffset(_startingContentOffset, animated: true)
}
_lastScrollView = superScrollView
_startingContentInsets = superScrollView!.contentInset
_startingScrollIndicatorInsets = superScrollView!.scrollIndicatorInsets
_startingContentOffset = superScrollView!.contentOffset
showLog("Saving New \(lastScrollView._IQDescription()) contentInset : \(_startingContentInsets) and contentOffset : \(_startingContentOffset)")
}
//Else the case where superScrollView == lastScrollView means we are on same scrollView after switching to different textField. So doing nothing, going ahead
} else if let unwrappedSuperScrollView = superScrollView { //If there was no lastScrollView and we found a current scrollView. then setting it as lastScrollView.
_lastScrollView = unwrappedSuperScrollView
_startingContentInsets = unwrappedSuperScrollView.contentInset
_startingScrollIndicatorInsets = unwrappedSuperScrollView.scrollIndicatorInsets
_startingContentOffset = unwrappedSuperScrollView.contentOffset
showLog("Saving \(unwrappedSuperScrollView._IQDescription()) contentInset : \(_startingContentInsets) and contentOffset : \(_startingContentOffset)")
}
// Special case for ScrollView.
// If we found lastScrollView then setting it's contentOffset to show textField.
if let lastScrollView = _lastScrollView {
//Saving
var lastView = textFieldView
var superScrollView = _lastScrollView
while let scrollView = superScrollView {
//Looping in upper hierarchy until we don't found any scrollView in it's upper hirarchy till UIWindow object.
if move > 0 ? (move > (-scrollView.contentOffset.y - scrollView.contentInset.top)) : scrollView.contentOffset.y>0 {
var tempScrollView = scrollView.superviewOfClassType(UIScrollView.self) as? UIScrollView
var nextScrollView : UIScrollView? = nil
while let view = tempScrollView {
if (view.isScrollEnabled) {
nextScrollView = view
break
} else {
tempScrollView = view.superviewOfClassType(UIScrollView.self) as? UIScrollView
}
}
//Getting lastViewRect.
if let lastViewRect = lastView.superview?.convert(lastView.frame, to: scrollView) {
//Calculating the expected Y offset from move and scrollView's contentOffset.
var shouldOffsetY = scrollView.contentOffset.y - min(scrollView.contentOffset.y,-move)
//Rearranging the expected Y offset according to the view.
shouldOffsetY = min(shouldOffsetY, lastViewRect.origin.y /*-5*/) //-5 is for good UI.//Commenting -5 (Bug ID: #69)
//[_textFieldView isKindOfClass:[UITextView class]] If is a UITextView type
//nextScrollView == nil If processing scrollView is last scrollView in upper hierarchy (there is no other scrollView upper hierrchy.)
//[_textFieldView isKindOfClass:[UITextView class]] If is a UITextView type
//shouldOffsetY >= 0 shouldOffsetY must be greater than in order to keep distance from navigationBar (Bug ID: #92)
if textFieldView is UITextView == true &&
nextScrollView == nil &&
shouldOffsetY >= 0 {
var maintainTopLayout : CGFloat = 0
if let navigationBarFrame = textFieldView.viewController()?.navigationController?.navigationBar.frame {
maintainTopLayout = navigationBarFrame.maxY
}
maintainTopLayout += 10.0 //For good UI
// Converting Rectangle according to window bounds.
if let currentTextFieldViewRect = textFieldView.superview?.convert(textFieldView.frame, to: window) {
//Calculating expected fix distance which needs to be managed from navigation bar
let expectedFixDistance = currentTextFieldViewRect.minY - maintainTopLayout
//Now if expectedOffsetY (superScrollView.contentOffset.y + expectedFixDistance) is lower than current shouldOffsetY, which means we're in a position where navigationBar up and hide, then reducing shouldOffsetY with expectedOffsetY (superScrollView.contentOffset.y + expectedFixDistance)
shouldOffsetY = min(shouldOffsetY, scrollView.contentOffset.y + expectedFixDistance)
//Setting move to 0 because now we don't want to move any view anymore (All will be managed by our contentInset logic.
move = 0
}
else {
//Subtracting the Y offset from the move variable, because we are going to change scrollView's contentOffset.y to shouldOffsetY.
move -= (shouldOffsetY-scrollView.contentOffset.y)
}
}
else
{
//Subtracting the Y offset from the move variable, because we are going to change scrollView's contentOffset.y to shouldOffsetY.
move -= (shouldOffsetY-scrollView.contentOffset.y)
}
//Getting problem while using `setContentOffset:animated:`, So I used animation API.
UIView.animate(withDuration: _animationDuration, delay: 0, options: UIViewAnimationOptions.beginFromCurrentState.union(_animationCurve), animations: { () -> Void in
self.showLog("Adjusting \(scrollView.contentOffset.y-shouldOffsetY) to \(scrollView._IQDescription()) ContentOffset")
self.showLog("Remaining Move: \(move)")
scrollView.contentOffset = CGPoint(x: scrollView.contentOffset.x, y: shouldOffsetY)
}) { (animated:Bool) -> Void in }
}
// Getting next lastView & superScrollView.
lastView = scrollView
superScrollView = nextScrollView
} else {
break
}
}
//Updating contentInset
if let lastScrollViewRect = lastScrollView.superview?.convert(lastScrollView.frame, to: window) {
let bottom : CGFloat = kbSize.height-newKeyboardDistanceFromTextField-(window.frame.height-lastScrollViewRect.maxY)
// Update the insets so that the scroll vew doesn't shift incorrectly when the offset is near the bottom of the scroll view.
var movedInsets = lastScrollView.contentInset
movedInsets.bottom = max(_startingContentInsets.bottom, bottom)
showLog("\(lastScrollView._IQDescription()) old ContentInset : \(lastScrollView.contentInset)")
//Getting problem while using `setContentOffset:animated:`, So I used animation API.
UIView.animate(withDuration: _animationDuration, delay: 0, options: UIViewAnimationOptions.beginFromCurrentState.union(_animationCurve), animations: { () -> Void in
lastScrollView.contentInset = movedInsets
var newInset = lastScrollView.scrollIndicatorInsets
newInset.bottom = movedInsets.bottom
lastScrollView.scrollIndicatorInsets = newInset
}) { (animated:Bool) -> Void in }
showLog("\(lastScrollView._IQDescription()) new ContentInset : \(lastScrollView.contentInset)")
}
}
//Going ahead. No else if.
if layoutGuidePosition == .top {
if let constraint = _layoutGuideConstraint {
let constant = min(_layoutGuideConstraintInitialConstant, constraint.constant-move)
UIView.animate(withDuration: _animationDuration, delay: 0, options: (_animationCurve.union(UIViewAnimationOptions.beginFromCurrentState)), animations: { () -> Void in
constraint.constant = constant
self._rootViewController?.view.setNeedsLayout()
self._rootViewController?.view.layoutIfNeeded()
}, completion: { (finished) -> Void in })
}
} else if layoutGuidePosition == .bottom {
if let constraint = _layoutGuideConstraint {
let constant = max(_layoutGuideConstraintInitialConstant, constraint.constant+move)
UIView.animate(withDuration: _animationDuration, delay: 0, options: (_animationCurve.union(UIViewAnimationOptions.beginFromCurrentState)), animations: { () -> Void in
constraint.constant = constant
self._rootViewController?.view.setNeedsLayout()
self._rootViewController?.view.layoutIfNeeded()
}, completion: { (finished) -> Void in })
}
} else {
//Special case for UITextView(Readjusting textView.contentInset when textView hight is too big to fit on screen)
//_lastScrollView If not having inside any scrollView, (now contentInset manages the full screen textView.
//[_textFieldView isKindOfClass:[UITextView class]] If is a UITextView type
if let textView = textFieldView as? UITextView {
let textViewHeight = min(textView.frame.height, (window.frame.height-kbSize.height-(topLayoutGuide)))
if (textView.frame.size.height-textView.contentInset.bottom>textViewHeight)
{
UIView.animate(withDuration: _animationDuration, delay: 0, options: (_animationCurve.union(UIViewAnimationOptions.beginFromCurrentState)), animations: { () -> Void in
self.showLog("\(textFieldView._IQDescription()) Old UITextView.contentInset : \(textView.contentInset)")
//_isTextViewContentInsetChanged, If frame is not change by library in past, then saving user textView properties (Bug ID: #92)
if (self.isTextViewContentInsetChanged == false)
{
self.startingTextViewContentInsets = textView.contentInset
self.startingTextViewScrollIndicatorInsets = textView.scrollIndicatorInsets
}
var newContentInset = textView.contentInset
newContentInset.bottom = textView.frame.size.height-textViewHeight
textView.contentInset = newContentInset
textView.scrollIndicatorInsets = newContentInset
self.isTextViewContentInsetChanged = true
self.showLog("\(textFieldView._IQDescription()) Old UITextView.contentInset : \(textView.contentInset)")
}, completion: { (finished) -> Void in })
}
}
// Special case for iPad modalPresentationStyle.
if rootController.modalPresentationStyle == UIModalPresentationStyle.formSheet ||
rootController.modalPresentationStyle == UIModalPresentationStyle.pageSheet {
showLog("Found Special case for Model Presentation Style: \(rootController.modalPresentationStyle)")
// +Positive or zero.
if move >= 0 {
// We should only manipulate y.
rootViewRect.origin.y -= move
// From now prevent keyboard manager to slide up the rootView to more than keyboard height. (Bug ID: #93)
if preventShowingBottomBlankSpace == true {
let minimumY: CGFloat = (window.frame.height-rootViewRect.size.height-topLayoutGuide)/2-(kbSize.height-newKeyboardDistanceFromTextField)
rootViewRect.origin.y = max(rootViewRect.minY, minimumY)
}
showLog("Moving Upward")
// Setting adjusted rootViewRect
setRootViewFrame(rootViewRect)
_privateMovedDistance = (_topViewBeginRect.origin.y-rootViewRect.origin.y)
} else { // -Negative
// Calculating disturbed distance. Pull Request #3
let disturbDistance = rootViewRect.minY-_topViewBeginRect.minY
// disturbDistance Negative = frame disturbed.
// disturbDistance positive = frame not disturbed.
if disturbDistance < 0 {
// We should only manipulate y.
rootViewRect.origin.y -= max(move, disturbDistance)
showLog("Moving Downward")
// Setting adjusted rootViewRect
setRootViewFrame(rootViewRect)
_privateMovedDistance = (_topViewBeginRect.origin.y-rootViewRect.origin.y)
}
}
} else { //If presentation style is neither UIModalPresentationFormSheet nor UIModalPresentationPageSheet then going ahead.(General case)
// +Positive or zero.
if move >= 0 {
rootViewRect.origin.y -= move
// From now prevent keyboard manager to slide up the rootView to more than keyboard height. (Bug ID: #93)
if preventShowingBottomBlankSpace == true {
rootViewRect.origin.y = max(rootViewRect.origin.y, min(0, -kbSize.height+newKeyboardDistanceFromTextField))
}
showLog("Moving Upward")
// Setting adjusted rootViewRect
setRootViewFrame(rootViewRect)
_privateMovedDistance = (_topViewBeginRect.origin.y-rootViewRect.origin.y)
} else { // -Negative
let disturbDistance : CGFloat = rootViewRect.minY-_topViewBeginRect.minY
// disturbDistance Negative = frame disturbed.
// disturbDistance positive = frame not disturbed.
if disturbDistance < 0 {
rootViewRect.origin.y -= max(move, disturbDistance)
showLog("Moving Downward")
// Setting adjusted rootViewRect
// Setting adjusted rootViewRect
setRootViewFrame(rootViewRect)
_privateMovedDistance = (_topViewBeginRect.origin.y-rootViewRect.origin.y)
}
}
}
}
let elapsedTime = CACurrentMediaTime() - startTime
showLog("****** \(#function) ended: \(elapsedTime) seconds ******")
}
///---------------------
/// MARK: Public Methods
///---------------------
/* Refreshes textField/textView position if any external changes is explicitly made by user. */
open func reloadLayoutIfNeeded() -> Void {
if privateIsEnabled() == true {
if _textFieldView != nil &&
_privateIsKeyboardShowing == true &&
_topViewBeginRect.equalTo(CGRect.zero) == false &&
_textFieldView?.isAlertViewTextField() == false {
adjustFrame()
}
}
}
///-------------------------------
/// MARK: UIKeyboard Notifications
///-------------------------------
/* UIKeyboardWillShowNotification. */
internal func keyboardWillShow(_ notification : Notification?) -> Void {
_kbShowNotification = notification
// Boolean to know keyboard is showing/hiding
_privateIsKeyboardShowing = true
let oldKBSize = _kbSize
if let info = (notification as NSNotification?)?.userInfo {
// Getting keyboard animation.
if let curve = (info[UIKeyboardAnimationCurveUserInfoKey] as? NSNumber)?.uintValue {
_animationCurve = UIViewAnimationOptions(rawValue: curve)
} else {
_animationCurve = UIViewAnimationOptions.curveEaseOut
}
// Getting keyboard animation duration
if let duration = (info[UIKeyboardAnimationDurationUserInfoKey] as? NSNumber)?.doubleValue {
//Saving animation duration
if duration != 0.0 {
_animationDuration = duration
}
} else {
_animationDuration = 0.25
}
// Getting UIKeyboardSize.
if let kbFrame = (info[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue {
let screenSize = UIScreen.main.bounds
//Calculating actual keyboard displayed size, keyboard frame may be different when hardware keyboard is attached (Bug ID: #469) (Bug ID: #381)
let intersectRect = kbFrame.intersection(screenSize)
if intersectRect.isNull {
_kbSize = CGSize(width: screenSize.size.width, height: 0)
} else {
_kbSize = intersectRect.size
}
showLog("UIKeyboard Size : \(_kbSize)")
}
}
if privateIsEnabled() == false {
return
}
let startTime = CACurrentMediaTime()
showLog("****** \(#function) started ******")
// (Bug ID: #5)
if _textFieldView != nil && _topViewBeginRect.equalTo(CGRect.zero) == true {
// keyboard is not showing(At the beginning only). We should save rootViewRect.
if let constraint = _textFieldView?.viewController()?.IQLayoutGuideConstraint {
_layoutGuideConstraint = constraint
_layoutGuideConstraintInitialConstant = constraint.constant
}
// keyboard is not showing(At the beginning only). We should save rootViewRect.
_rootViewController = _textFieldView?.topMostController()
if _rootViewController == nil {
_rootViewController = keyWindow()?.topMostWindowController()
}
if let unwrappedRootController = _rootViewController {
_topViewBeginRect = unwrappedRootController.view.frame
if shouldFixInteractivePopGestureRecognizer == true &&
unwrappedRootController is UINavigationController &&
unwrappedRootController.modalPresentationStyle != UIModalPresentationStyle.formSheet &&
unwrappedRootController.modalPresentationStyle != UIModalPresentationStyle.pageSheet {
if let window = keyWindow() {
_topViewBeginRect.origin = CGPoint(x: 0,y: window.frame.size.height-unwrappedRootController.view.frame.size.height)
} else {
_topViewBeginRect.origin = CGPoint.zero
}
}
showLog("Saving \(unwrappedRootController._IQDescription()) beginning Frame: \(_topViewBeginRect)")
} else {
_topViewBeginRect = CGRect.zero
}
}
// Getting topMost ViewController.
var topMostController = _textFieldView?.topMostController()
if topMostController == nil {
topMostController = keyWindow()?.topMostWindowController()
}
//If last restored keyboard size is different(any orientation accure), then refresh. otherwise not.
if _kbSize.equalTo(oldKBSize) == false {
//If _textFieldView is inside UITableViewController then let UITableViewController to handle it (Bug ID: #37) (Bug ID: #76) See note:- https://developer.apple.com/library/ios/documentation/StringsTextFonts/Conceptual/TextAndWebiPhoneOS/KeyboardManagement/KeyboardManagement.html If it is UIAlertView textField then do not affect anything (Bug ID: #70).
if _privateIsKeyboardShowing == true &&
_textFieldView != nil &&
_textFieldView?.isAlertViewTextField() == false {
// keyboard is already showing. adjust frame.
adjustFrame()
}
}
let elapsedTime = CACurrentMediaTime() - startTime
showLog("****** \(#function) ended: \(elapsedTime) seconds ******")
}
/* UIKeyboardDidShowNotification. */
internal func keyboardDidShow(_ notification : Notification?) -> Void {
if privateIsEnabled() == false {
return
}
let startTime = CACurrentMediaTime()
showLog("****** \(#function) started ******")
// Getting topMost ViewController.
var topMostController = _textFieldView?.topMostController()
if topMostController == nil {
topMostController = keyWindow()?.topMostWindowController()
}
if _textFieldView != nil &&
(topMostController?.modalPresentationStyle == UIModalPresentationStyle.formSheet || topMostController?.modalPresentationStyle == UIModalPresentationStyle.pageSheet) &&
_textFieldView?.isAlertViewTextField() == false {
//In case of form sheet or page sheet, we'll add adjustFrame call in main queue to perform it when UI thread will do all framing updation so adjustFrame will be executed after all internal operations.
OperationQueue.main.addOperation {
self.adjustFrame()
}
}
let elapsedTime = CACurrentMediaTime() - startTime
showLog("****** \(#function) ended: \(elapsedTime) seconds ******")
}
/* UIKeyboardWillHideNotification. So setting rootViewController to it's default frame. */
internal func keyboardWillHide(_ notification : Notification?) -> Void {
//If it's not a fake notification generated by [self setEnable:NO].
if notification != nil {
_kbShowNotification = nil
}
// Boolean to know keyboard is showing/hiding
_privateIsKeyboardShowing = false
let info : [AnyHashable: Any]? = (notification as NSNotification?)?.userInfo
// Getting keyboard animation duration
if let duration = (info?[UIKeyboardAnimationDurationUserInfoKey] as? NSNumber)?.doubleValue {
if duration != 0 {
// Setitng keyboard animation duration
_animationDuration = duration
}
}
//If not enabled then do nothing.
if privateIsEnabled() == false {
return
}
let startTime = CACurrentMediaTime()
showLog("****** \(#function) started ******")
//Commented due to #56. Added all the conditions below to handle UIWebView's textFields. (Bug ID: #56)
// We are unable to get textField object while keyboard showing on UIWebView's textField. (Bug ID: #11)
// if (_textFieldView == nil) return
//Restoring the contentOffset of the lastScrollView
if let lastScrollView = _lastScrollView {
UIView.animate(withDuration: _animationDuration, delay: 0, options: UIViewAnimationOptions.beginFromCurrentState.union(_animationCurve), animations: { () -> Void in
lastScrollView.contentInset = self._startingContentInsets
lastScrollView.scrollIndicatorInsets = self._startingScrollIndicatorInsets
if lastScrollView.shouldRestoreScrollViewContentOffset == true {
lastScrollView.contentOffset = self._startingContentOffset
}
self.showLog("Restoring \(lastScrollView._IQDescription()) contentInset to : \(self._startingContentInsets) and contentOffset to : \(self._startingContentOffset)")
// TODO: restore scrollView state
// This is temporary solution. Have to implement the save and restore scrollView state
var superScrollView : UIScrollView? = lastScrollView
while let scrollView = superScrollView {
let contentSize = CGSize(width: max(scrollView.contentSize.width, scrollView.frame.width), height: max(scrollView.contentSize.height, scrollView.frame.height))
let minimumY = contentSize.height - scrollView.frame.height
if minimumY < scrollView.contentOffset.y {
scrollView.contentOffset = CGPoint(x: scrollView.contentOffset.x, y: minimumY)
self.showLog("Restoring \(scrollView._IQDescription()) contentOffset to : \(self._startingContentOffset)")
}
superScrollView = scrollView.superviewOfClassType(UIScrollView.self) as? UIScrollView
}
}) { (finished) -> Void in }
}
// Setting rootViewController frame to it's original position. // (Bug ID: #18)
if _topViewBeginRect.equalTo(CGRect.zero) == false {
if let rootViewController = _rootViewController {
//frame size needs to be adjusted on iOS8 due to orientation API changes.
_topViewBeginRect.size = rootViewController.view.frame.size
//Used UIViewAnimationOptionBeginFromCurrentState to minimize strange animations.
UIView.animate(withDuration: _animationDuration, delay: 0, options: UIViewAnimationOptions.beginFromCurrentState.union(_animationCurve), animations: { () -> Void in
if let constraint = self._layoutGuideConstraint {
constraint.constant = self._layoutGuideConstraintInitialConstant
rootViewController.view.setNeedsLayout()
rootViewController.view.layoutIfNeeded()
}
else {
self.showLog("Restoring \(rootViewController._IQDescription()) frame to : \(self._topViewBeginRect)")
// Setting it's new frame
rootViewController.view.frame = self._topViewBeginRect
self._privateMovedDistance = 0
//Animating content if needed (Bug ID: #204)
if self.layoutIfNeededOnUpdate == true {
//Animating content (Bug ID: #160)
rootViewController.view.setNeedsLayout()
rootViewController.view.layoutIfNeeded()
}
}
}) { (finished) -> Void in }
_rootViewController = nil
}
} else if let constraint = self._layoutGuideConstraint {
if let rootViewController = _rootViewController {
UIView.animate(withDuration: _animationDuration, delay: 0, options: UIViewAnimationOptions.beginFromCurrentState.union(_animationCurve), animations: { () -> Void in
constraint.constant = self._layoutGuideConstraintInitialConstant
rootViewController.view.setNeedsLayout()
rootViewController.view.layoutIfNeeded()
}) { (finished) -> Void in }
}
}
//Reset all values
_lastScrollView = nil
_kbSize = CGSize.zero
_layoutGuideConstraint = nil
_layoutGuideConstraintInitialConstant = 0
_startingContentInsets = UIEdgeInsets.zero
_startingScrollIndicatorInsets = UIEdgeInsets.zero
_startingContentOffset = CGPoint.zero
// topViewBeginRect = CGRectZero //Commented due to #82
let elapsedTime = CACurrentMediaTime() - startTime
showLog("****** \(#function) ended: \(elapsedTime) seconds ******")
}
internal func keyboardDidHide(_ notification:Notification) {
let startTime = CACurrentMediaTime()
showLog("****** \(#function) started ******")
_topViewBeginRect = CGRect.zero
_kbSize = CGSize.zero
let elapsedTime = CACurrentMediaTime() - startTime
showLog("****** \(#function) ended: \(elapsedTime) seconds ******")
}
///-------------------------------------------
/// MARK: UITextField/UITextView Notifications
///-------------------------------------------
/** UITextFieldTextDidBeginEditingNotification, UITextViewTextDidBeginEditingNotification. Fetching UITextFieldView object. */
internal func textFieldViewDidBeginEditing(_ notification:Notification) {
let startTime = CACurrentMediaTime()
showLog("****** \(#function) started ******")
// Getting object
_textFieldView = notification.object as? UIView
if overrideKeyboardAppearance == true {
if let textFieldView = _textFieldView as? UITextField {
//If keyboard appearance is not like the provided appearance
if textFieldView.keyboardAppearance != keyboardAppearance {
//Setting textField keyboard appearance and reloading inputViews.
textFieldView.keyboardAppearance = keyboardAppearance
textFieldView.reloadInputViews()
}
} else if let textFieldView = _textFieldView as? UITextView {
//If keyboard appearance is not like the provided appearance
if textFieldView.keyboardAppearance != keyboardAppearance {
//Setting textField keyboard appearance and reloading inputViews.
textFieldView.keyboardAppearance = keyboardAppearance
textFieldView.reloadInputViews()
}
}
}
//If autoToolbar enable, then add toolbar on all the UITextField/UITextView's if required.
if privateIsEnableAutoToolbar() == true {
//UITextView special case. Keyboard Notification is firing before textView notification so we need to resign it first and then again set it as first responder to add toolbar on it.
if _textFieldView is UITextView == true &&
_textFieldView?.inputAccessoryView == nil {
UIView.animate(withDuration: 0.00001, delay: 0, options: UIViewAnimationOptions.beginFromCurrentState.union(_animationCurve), animations: { () -> Void in
self.addToolbarIfRequired()
}, completion: { (finished) -> Void in
//On textView toolbar didn't appear on first time, so forcing textView to reload it's inputViews.
self._textFieldView?.reloadInputViews()
})
} else {
//Adding toolbar
addToolbarIfRequired()
}
} else {
removeToolbarIfRequired()
}
resignFirstResponderGesture.isEnabled = privateShouldResignOnTouchOutside()
_textFieldView?.window?.addGestureRecognizer(resignFirstResponderGesture) // (Enhancement ID: #14)
if privateIsEnabled() == true {
if _topViewBeginRect.equalTo(CGRect.zero) == true { // (Bug ID: #5)
// keyboard is not showing(At the beginning only). We should save rootViewRect.
if let constraint = _textFieldView?.viewController()?.IQLayoutGuideConstraint {
_layoutGuideConstraint = constraint
_layoutGuideConstraintInitialConstant = constraint.constant
}
_rootViewController = _textFieldView?.topMostController()
if _rootViewController == nil {
_rootViewController = keyWindow()?.topMostWindowController()
}
if let rootViewController = _rootViewController {
_topViewBeginRect = rootViewController.view.frame
if shouldFixInteractivePopGestureRecognizer == true &&
rootViewController is UINavigationController &&
rootViewController.modalPresentationStyle != UIModalPresentationStyle.formSheet &&
rootViewController.modalPresentationStyle != UIModalPresentationStyle.pageSheet {
if let window = keyWindow() {
_topViewBeginRect.origin = CGPoint(x: 0,y: window.frame.size.height-rootViewController.view.frame.size.height)
} else {
_topViewBeginRect.origin = CGPoint.zero
}
}
showLog("Saving \(rootViewController._IQDescription()) beginning frame : \(_topViewBeginRect)")
}
}
//If _textFieldView is inside ignored responder then do nothing. (Bug ID: #37, #74, #76)
//See notes:- https://developer.apple.com/library/ios/documentation/StringsTextFonts/Conceptual/TextAndWebiPhoneOS/KeyboardManagement/KeyboardManagement.html If it is UIAlertView textField then do not affect anything (Bug ID: #70).
if _privateIsKeyboardShowing == true &&
_textFieldView != nil &&
_textFieldView?.isAlertViewTextField() == false {
// keyboard is already showing. adjust frame.
adjustFrame()
}
}
let elapsedTime = CACurrentMediaTime() - startTime
showLog("****** \(#function) ended: \(elapsedTime) seconds ******")
}
/** UITextFieldTextDidEndEditingNotification, UITextViewTextDidEndEditingNotification. Removing fetched object. */
internal func textFieldViewDidEndEditing(_ notification:Notification) {
let startTime = CACurrentMediaTime()
showLog("****** \(#function) started ******")
//Removing gesture recognizer (Enhancement ID: #14)
_textFieldView?.window?.removeGestureRecognizer(resignFirstResponderGesture)
// We check if there's a change in original frame or not.
if let textView = _textFieldView as? UITextView {
if isTextViewContentInsetChanged == true {
UIView.animate(withDuration: _animationDuration, delay: 0, options: UIViewAnimationOptions.beginFromCurrentState.union(_animationCurve), animations: { () -> Void in
self.isTextViewContentInsetChanged = false
self.showLog("Restoring \(textView._IQDescription()) textView.contentInset to : \(self.startingTextViewContentInsets)")
//Setting textField to it's initial contentInset
textView.contentInset = self.startingTextViewContentInsets
textView.scrollIndicatorInsets = self.startingTextViewScrollIndicatorInsets
}, completion: { (finished) -> Void in })
}
}
//Setting object to nil
_textFieldView = nil
let elapsedTime = CACurrentMediaTime() - startTime
showLog("****** \(#function) ended: \(elapsedTime) seconds ******")
}
///------------------------------------------
/// MARK: UIStatusBar Notification methods
///------------------------------------------
/** UIApplicationWillChangeStatusBarOrientationNotification. Need to set the textView to it's original position. If any frame changes made. (Bug ID: #92)*/
internal func willChangeStatusBarOrientation(_ notification:Notification) {
let startTime = CACurrentMediaTime()
showLog("****** \(#function) started ******")
//If textViewContentInsetChanged is saved then restore it.
if let textView = _textFieldView as? UITextView {
if isTextViewContentInsetChanged == true {
UIView.animate(withDuration: _animationDuration, delay: 0, options: UIViewAnimationOptions.beginFromCurrentState.union(_animationCurve), animations: { () -> Void in
self.isTextViewContentInsetChanged = false
self.showLog("Restoring \(textView._IQDescription()) textView.contentInset to : \(self.startingTextViewContentInsets)")
//Setting textField to it's initial contentInset
textView.contentInset = self.startingTextViewContentInsets
textView.scrollIndicatorInsets = self.startingTextViewScrollIndicatorInsets
}, completion: { (finished) -> Void in })
}
}
let elapsedTime = CACurrentMediaTime() - startTime
showLog("****** \(#function) ended: \(elapsedTime) seconds ******")
}
/** UIApplicationDidChangeStatusBarFrameNotification. Need to refresh view position and update _topViewBeginRect. (Bug ID: #446)*/
internal func didChangeStatusBarFrame(_ notification : Notification?) -> Void {
let oldStatusBarFrame = _statusBarFrame
// Getting keyboard animation duration
if let newFrame = ((notification as NSNotification?)?.userInfo?[UIApplicationStatusBarFrameUserInfoKey] as? NSNumber)?.cgRectValue {
_statusBarFrame = newFrame
}
if privateIsEnabled() == false {
return
}
let startTime = CACurrentMediaTime()
showLog("****** \(#function) started ******")
if _rootViewController != nil &&
!_topViewBeginRect.equalTo(_rootViewController!.view.frame) == true {
if let unwrappedRootController = _rootViewController {
_topViewBeginRect = unwrappedRootController.view.frame
if shouldFixInteractivePopGestureRecognizer == true &&
unwrappedRootController is UINavigationController &&
unwrappedRootController.modalPresentationStyle != UIModalPresentationStyle.formSheet &&
unwrappedRootController.modalPresentationStyle != UIModalPresentationStyle.pageSheet {
if let window = keyWindow() {
_topViewBeginRect.origin = CGPoint(x: 0,y: window.frame.size.height-unwrappedRootController.view.frame.size.height)
} else {
_topViewBeginRect.origin = CGPoint.zero
}
}
showLog("Saving \(unwrappedRootController._IQDescription()) beginning Frame: \(_topViewBeginRect)")
} else {
_topViewBeginRect = CGRect.zero
}
}
//If _textFieldView is inside UITableViewController then let UITableViewController to handle it (Bug ID: #37) (Bug ID: #76) See note:- https://developer.apple.com/library/ios/documentation/StringsTextFonts/Conceptual/TextAndWebiPhoneOS/KeyboardManagement/KeyboardManagement.html If it is UIAlertView textField then do not affect anything (Bug ID: #70).
if _privateIsKeyboardShowing == true &&
_textFieldView != nil &&
_statusBarFrame.size.equalTo(oldStatusBarFrame.size) == false &&
_textFieldView?.isAlertViewTextField() == false {
// keyboard is already showing. adjust frame.
adjustFrame()
}
let elapsedTime = CACurrentMediaTime() - startTime
showLog("****** \(#function) ended: \(elapsedTime) seconds ******")
}
///------------------
/// MARK: AutoToolbar
///------------------
/** Get all UITextField/UITextView siblings of textFieldView. */
fileprivate func responderViews()-> [UIView]? {
var superConsideredView : UIView?
//If find any consider responderView in it's upper hierarchy then will get deepResponderView.
for disabledClass in toolbarPreviousNextAllowedClasses {
superConsideredView = _textFieldView?.superviewOfClassType(disabledClass)
if superConsideredView != nil {
break
}
}
//If there is a superConsideredView in view's hierarchy, then fetching all it's subview that responds. No sorting for superConsideredView, it's by subView position. (Enhancement ID: #22)
if superConsideredView != nil {
return superConsideredView?.deepResponderViews()
} else { //Otherwise fetching all the siblings
if let textFields = _textFieldView?.responderSiblings() {
//Sorting textFields according to behaviour
switch toolbarManageBehaviour {
//If autoToolbar behaviour is bySubviews, then returning it.
case IQAutoToolbarManageBehaviour.bySubviews: return textFields
//If autoToolbar behaviour is by tag, then sorting it according to tag property.
case IQAutoToolbarManageBehaviour.byTag: return textFields.sortedArrayByTag()
//If autoToolbar behaviour is by tag, then sorting it according to tag property.
case IQAutoToolbarManageBehaviour.byPosition: return textFields.sortedArrayByPosition()
}
} else {
return nil
}
}
}
/** Add toolbar if it is required to add on textFields and it's siblings. */
fileprivate func addToolbarIfRequired() {
let startTime = CACurrentMediaTime()
showLog("****** \(#function) started ******")
// Getting all the sibling textFields.
if let siblings = responderViews() {
showLog("Found \(siblings.count) responder sibling(s)")
if let textField = _textFieldView {
//Either there is no inputAccessoryView or if accessoryView is not appropriate for current situation(There is Previous/Next/Done toolbar).
//setInputAccessoryView: check (Bug ID: #307)
if textField.responds(to: #selector(setter: UITextField.inputAccessoryView)) {
if textField.inputAccessoryView == nil ||
textField.inputAccessoryView?.tag == IQKeyboardManager.kIQPreviousNextButtonToolbarTag ||
textField.inputAccessoryView?.tag == IQKeyboardManager.kIQDoneButtonToolbarTag {
// If only one object is found, then adding only Done button.
if (siblings.count == 1 && previousNextDisplayMode == .Default) || previousNextDisplayMode == .alwaysHide {
if let doneBarButtonItemImage = toolbarDoneBarButtonItemImage {
textField.addRightButtonOnKeyboardWithImage(doneBarButtonItemImage, target: self, action: #selector(self.doneAction(_:)), shouldShowPlaceholder: shouldShowToolbarPlaceholder)
}
//Supporting Custom Done button text (Enhancement ID: #209, #411, Bug ID: #376)
else if let doneBarButtonItemText = toolbarDoneBarButtonItemText {
textField.addRightButtonOnKeyboardWithText(doneBarButtonItemText, target: self, action: #selector(self.doneAction(_:)), shouldShowPlaceholder: shouldShowToolbarPlaceholder)
} else {
//Now adding textField placeholder text as title of IQToolbar (Enhancement ID: #27)
textField.addDoneOnKeyboardWithTarget(self, action: #selector(self.doneAction(_:)), shouldShowPlaceholder: shouldShowToolbarPlaceholder)
}
textField.inputAccessoryView?.tag = IQKeyboardManager.kIQDoneButtonToolbarTag // (Bug ID: #78)
} else if (siblings.count > 1 && previousNextDisplayMode == .Default) || previousNextDisplayMode == .alwaysShow {
//Supporting Custom Done button image (Enhancement ID: #366)
if let doneBarButtonItemImage = toolbarDoneBarButtonItemImage {
textField.addPreviousNextRightOnKeyboardWithTarget(self, rightButtonImage: doneBarButtonItemImage, previousAction: #selector(self.previousAction(_:)), nextAction: #selector(self.nextAction(_:)), rightButtonAction: #selector(self.doneAction(_:)), shouldShowPlaceholder: shouldShowToolbarPlaceholder)
}
//Supporting Custom Done button text (Enhancement ID: #209, #411, Bug ID: #376)
else if let doneBarButtonItemText = toolbarDoneBarButtonItemText {
textField.addPreviousNextRightOnKeyboardWithTarget(self, rightButtonTitle: doneBarButtonItemText, previousAction: #selector(self.previousAction(_:)), nextAction: #selector(self.nextAction(_:)), rightButtonAction: #selector(self.doneAction(_:)), shouldShowPlaceholder: shouldShowToolbarPlaceholder)
} else {
//Now adding textField placeholder text as title of IQToolbar (Enhancement ID: #27)
textField.addPreviousNextDoneOnKeyboardWithTarget(self, previousAction: #selector(self.previousAction(_:)), nextAction: #selector(self.nextAction(_:)), doneAction: #selector(self.doneAction(_:)), shouldShowPlaceholder: shouldShowToolbarPlaceholder)
}
textField.inputAccessoryView?.tag = IQKeyboardManager.kIQPreviousNextButtonToolbarTag // (Bug ID: #78)
}
let toolbar = textField.keyboardToolbar
// Setting toolbar to keyboard.
if let _textField = textField as? UITextField {
//Bar style according to keyboard appearance
switch _textField.keyboardAppearance {
case UIKeyboardAppearance.dark:
toolbar.barStyle = UIBarStyle.black
toolbar.tintColor = UIColor.white
toolbar.barTintColor = nil;
default:
toolbar.barStyle = UIBarStyle.default
if let barTintColor = toolbarBarTintColor {
toolbar.barTintColor = barTintColor
} else {
toolbar.barTintColor = nil
}
//Setting toolbar tintColor // (Enhancement ID: #30)
if shouldToolbarUsesTextFieldTintColor {
toolbar.tintColor = _textField.tintColor
} else if let tintColor = toolbarTintColor {
toolbar.tintColor = tintColor
} else {
toolbar.tintColor = UIColor.black
}
}
} else if let _textView = textField as? UITextView {
//Bar style according to keyboard appearance
switch _textView.keyboardAppearance {
case UIKeyboardAppearance.dark:
toolbar.barStyle = UIBarStyle.black
toolbar.tintColor = UIColor.white
toolbar.barTintColor = nil;
default:
toolbar.barStyle = UIBarStyle.default
if let barTintColor = toolbarBarTintColor {
toolbar.barTintColor = barTintColor
} else {
toolbar.barTintColor = nil
}
if shouldToolbarUsesTextFieldTintColor {
toolbar.tintColor = _textView.tintColor
} else if let tintColor = toolbarTintColor {
toolbar.tintColor = tintColor
} else {
toolbar.tintColor = UIColor.black
}
}
}
//Setting toolbar title font. // (Enhancement ID: #30)
if shouldShowToolbarPlaceholder == true &&
textField.shouldHideToolbarPlaceholder == false {
//Updating placeholder font to toolbar. //(Bug ID: #148, #272)
if toolbar.titleBarButton.title == nil ||
toolbar.titleBarButton.title != textField.drawingToolbarPlaceholder {
toolbar.titleBarButton.title = textField.drawingToolbarPlaceholder
}
//Setting toolbar title font. // (Enhancement ID: #30)
if placeholderFont != nil {
toolbar.titleBarButton.titleFont = placeholderFont
}
} else {
toolbar.titleBarButton.title = nil
}
//In case of UITableView (Special), the next/previous buttons has to be refreshed everytime. (Bug ID: #56)
// If firstTextField, then previous should not be enabled.
if siblings.first == textField {
if (siblings.count == 1) {
textField.keyboardToolbar.previousBarButton.isEnabled = false;
textField.keyboardToolbar.nextBarButton.isEnabled = false;
} else {
textField.keyboardToolbar.previousBarButton.isEnabled = false;
textField.keyboardToolbar.nextBarButton.isEnabled = true;
}
} else if siblings.last == textField { // If lastTextField then next should not be enaled.
textField.keyboardToolbar.previousBarButton.isEnabled = true;
textField.keyboardToolbar.nextBarButton.isEnabled = false;
} else {
textField.keyboardToolbar.previousBarButton.isEnabled = true;
textField.keyboardToolbar.nextBarButton.isEnabled = true;
}
}
}
}
}
let elapsedTime = CACurrentMediaTime() - startTime
showLog("****** \(#function) ended: \(elapsedTime) seconds ******")
}
/** Remove any toolbar if it is IQToolbar. */
fileprivate func removeToolbarIfRequired() { // (Bug ID: #18)
let startTime = CACurrentMediaTime()
showLog("****** \(#function) started ******")
// Getting all the sibling textFields.
if let siblings = responderViews() {
showLog("Found \(siblings.count) responder sibling(s)")
for view in siblings {
if let toolbar = view.inputAccessoryView as? IQToolbar {
//setInputAccessoryView: check (Bug ID: #307)
if view.responds(to: #selector(setter: UITextField.inputAccessoryView)) &&
(toolbar.tag == IQKeyboardManager.kIQDoneButtonToolbarTag || toolbar.tag == IQKeyboardManager.kIQPreviousNextButtonToolbarTag) {
if let textField = view as? UITextField {
textField.inputAccessoryView = nil
textField.reloadInputViews();
} else if let textView = view as? UITextView {
textView.inputAccessoryView = nil
textView.reloadInputViews();
}
}
}
}
}
let elapsedTime = CACurrentMediaTime() - startTime
showLog("****** \(#function) ended: \(elapsedTime) seconds ******")
}
/** reloadInputViews to reload toolbar buttons enable/disable state on the fly Enhancement ID #434. */
open func reloadInputViews() {
//If enabled then adding toolbar.
if privateIsEnableAutoToolbar() == true {
self.addToolbarIfRequired()
} else {
self.removeToolbarIfRequired()
}
}
///------------------
/// MARK: Debugging & Developer options
///------------------
open var enableDebugging = false
/**
@warning Use below methods to completely enable/disable notifications registered by library internally. Please keep in mind that library is totally dependent on NSNotification of UITextField, UITextField, Keyboard etc. If you do unregisterAllNotifications then library will not work at all. You should only use below methods if you want to completedly disable all library functions. You should use below methods at your own risk.
*/
open func registerAllNotifications() {
// Registering for keyboard notification.
NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillShow(_:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardDidShow(_:)), name: NSNotification.Name.UIKeyboardDidShow, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillHide(_:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardDidHide(_:)), name: NSNotification.Name.UIKeyboardDidHide, object: nil)
// Registering for UITextField notification.
registerTextFieldViewClass(UITextField.self, didBeginEditingNotificationName: NSNotification.Name.UITextFieldTextDidBeginEditing.rawValue, didEndEditingNotificationName: NSNotification.Name.UITextFieldTextDidEndEditing.rawValue)
// Registering for UITextView notification.
registerTextFieldViewClass(UITextView.self, didBeginEditingNotificationName: NSNotification.Name.UITextViewTextDidBeginEditing.rawValue, didEndEditingNotificationName: NSNotification.Name.UITextViewTextDidEndEditing.rawValue)
// Registering for orientation changes notification
NotificationCenter.default.addObserver(self, selector: #selector(self.willChangeStatusBarOrientation(_:)), name: NSNotification.Name.UIApplicationWillChangeStatusBarOrientation, object: UIApplication.shared)
// Registering for status bar frame change notification
NotificationCenter.default.addObserver(self, selector: #selector(self.didChangeStatusBarFrame(_:)), name: NSNotification.Name.UIApplicationDidChangeStatusBarFrame, object: UIApplication.shared)
}
open func unregisterAllNotifications() {
// Unregistering for keyboard notification.
NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillShow, object: nil)
NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardDidShow, object: nil)
NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillHide, object: nil)
NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardDidHide, object: nil)
// Unregistering for UITextField notification.
unregisterTextFieldViewClass(UITextField.self, didBeginEditingNotificationName: NSNotification.Name.UITextFieldTextDidBeginEditing.rawValue, didEndEditingNotificationName: NSNotification.Name.UITextFieldTextDidEndEditing.rawValue)
// Unregistering for UITextView notification.
unregisterTextFieldViewClass(UITextView.self, didBeginEditingNotificationName: NSNotification.Name.UITextViewTextDidBeginEditing.rawValue, didEndEditingNotificationName: NSNotification.Name.UITextViewTextDidEndEditing.rawValue)
// Unregistering for orientation changes notification
NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIApplicationWillChangeStatusBarOrientation, object: UIApplication.shared)
// Unregistering for status bar frame change notification
NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIApplicationDidChangeStatusBarFrame, object: UIApplication.shared)
}
fileprivate func showLog(_ logString: String) {
if enableDebugging {
print("IQKeyboardManager: " + logString)
}
}
}
| mit | 286b980f8bea50fc88a49a87eda4484f | 46.751022 | 434 | 0.574529 | 7.042348 | false | false | false | false |
itsaboutcode/WordPress-iOS | WordPress/Classes/ViewRelated/Blog/Site Management/SiteTagsViewController.swift | 1 | 19193 | import UIKit
import Gridicons
final class SiteTagsViewController: UITableViewController {
private struct TableConstants {
static let cellIdentifier = "TitleBadgeDisclosureCell"
static let accesibilityIdentifier = "SiteTagsList"
static let numberOfSections = 1
}
private let blog: Blog
private lazy var noResultsViewController = NoResultsViewController.controller()
private var isSearching = false
fileprivate lazy var context: NSManagedObjectContext = {
return ContextManager.sharedInstance().mainContext
}()
fileprivate lazy var defaultPredicate: NSPredicate = {
return NSPredicate(format: "blog.blogID = %@", blog.dotComID!)
}()
private let sortDescriptors: [NSSortDescriptor] = {
return [NSSortDescriptor(key: "name", ascending: true, selector: #selector(NSString.localizedCaseInsensitiveCompare(_:)))]
}()
fileprivate lazy var resultsController: NSFetchedResultsController<NSFetchRequestResult> = {
let request = NSFetchRequest<NSFetchRequestResult>(entityName: "PostTag")
request.sortDescriptors = self.sortDescriptors
let frc = NSFetchedResultsController(fetchRequest: request, managedObjectContext: self.context, sectionNameKeyPath: nil, cacheName: nil)
frc.delegate = self
return frc
}()
fileprivate lazy var searchController: UISearchController = {
let returnValue = UISearchController(searchResultsController: nil)
returnValue.hidesNavigationBarDuringPresentation = false
returnValue.obscuresBackgroundDuringPresentation = false
returnValue.searchResultsUpdater = self
returnValue.delegate = self
WPStyleGuide.configureSearchBar(returnValue.searchBar)
return returnValue
}()
private var isPerformingInitialSync = false
@objc
public init(blog: Blog) {
self.blog = blog
super.init(style: .grouped)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
noResultsViewController.delegate = self
setAccessibilityIdentifier()
applyStyleGuide()
applyTitle()
setupTable()
refreshTags()
refreshResultsController(predicate: defaultPredicate)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
searchController.searchBar.isHidden = false
refreshNoResultsView()
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
// HACK: Normally, to hide the scroll bars we'd define a presentation context.
// This is impacting layout when navigating back from a detail. As a work
// around we can simply hide the search bar.
if searchController.isActive {
searchController.searchBar.isHidden = true
}
}
private func setAccessibilityIdentifier() {
tableView.accessibilityIdentifier = TableConstants.accesibilityIdentifier
}
private func applyStyleGuide() {
WPStyleGuide.configureColors(view: view, tableView: tableView)
WPStyleGuide.configureAutomaticHeightRows(for: tableView)
}
private func applyTitle() {
title = NSLocalizedString("Tags", comment: "Label for the Tags Section in the Blog Settings")
}
private func setupTable() {
tableView.tableFooterView = UIView(frame: .zero)
let nibName = UINib(nibName: TableConstants.cellIdentifier, bundle: nil)
tableView.register(nibName, forCellReuseIdentifier: TableConstants.cellIdentifier)
setupRefreshControl()
}
private func setupRefreshControl() {
if refreshControl == nil {
refreshControl = UIRefreshControl()
refreshControl?.backgroundColor = .basicBackground
refreshControl?.addTarget(self, action: #selector(refreshTags), for: .valueChanged)
}
}
private func deactivateRefreshControl() {
refreshControl = nil
}
@objc private func refreshResultsController(predicate: NSPredicate) {
resultsController.fetchRequest.predicate = predicate
resultsController.fetchRequest.sortDescriptors = sortDescriptors
do {
try resultsController.performFetch()
tableView.reloadData()
refreshNoResultsView()
} catch {
tagsFailedLoading(error: error)
}
}
@objc private func refreshTags() {
isPerformingInitialSync = true
let tagsService = PostTagService(managedObjectContext: ContextManager.sharedInstance().mainContext)
tagsService.syncTags(for: blog, success: { [weak self] tags in
self?.isPerformingInitialSync = false
self?.refreshControl?.endRefreshing()
self?.refreshNoResultsView()
}) { [weak self] error in
self?.tagsFailedLoading(error: error)
}
}
private func showRightBarButton(_ show: Bool) {
if show {
navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .add,
target: self,
action: #selector(createTag))
} else {
navigationItem.rightBarButtonItem = nil
}
}
private func setupSearchBar() {
guard tableView.tableHeaderView == nil else {
return
}
tableView.tableHeaderView = searchController.searchBar
}
private func removeSearchBar() {
tableView.tableHeaderView = nil
}
@objc private func createTag() {
navigate(to: nil)
}
func tagsFailedLoading(error: Error) {
DDLogError("Tag management. Error loading tags for \(String(describing: blog.url)): \(error)")
}
}
// MARK: - Table view datasource
extension SiteTagsViewController {
override func numberOfSections(in tableView: UITableView) -> Int {
return resultsController.sections?.count ?? 0
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return resultsController.sections?[section].numberOfObjects ?? 0
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: TableConstants.cellIdentifier, for: indexPath) as? TitleBadgeDisclosureCell, let tag = tagAtIndexPath(indexPath) else {
return TitleBadgeDisclosureCell()
}
cell.name = tag.name?.stringByDecodingXMLCharacters()
if let count = tag.postCount?.intValue, count > 0 {
cell.count = count
}
return cell
}
fileprivate func tagAtIndexPath(_ indexPath: IndexPath) -> PostTag? {
return resultsController.object(at: indexPath) as? PostTag
}
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
return true
}
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
guard let selectedTag = tagAtIndexPath(indexPath) else {
return
}
delete(selectedTag)
}
private func delete(_ tag: PostTag) {
let tagsService = PostTagService(managedObjectContext: ContextManager.sharedInstance().mainContext)
refreshControl?.beginRefreshing()
tagsService.delete(tag, for: blog, success: { [weak self] in
self?.refreshControl?.endRefreshing()
self?.tableView.reloadData()
}, failure: { [weak self] error in
self?.refreshControl?.endRefreshing()
})
}
private func save(_ tag: PostTag) {
let tagsService = PostTagService(managedObjectContext: ContextManager.sharedInstance().mainContext)
refreshControl?.beginRefreshing()
tagsService.save(tag, for: blog, success: { [weak self] tag in
self?.refreshControl?.endRefreshing()
self?.tableView.reloadData()
}, failure: { error in
self.refreshControl?.endRefreshing()
})
}
}
// MARK: - Table view delegate
extension SiteTagsViewController {
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
guard let selectedTag = tagAtIndexPath(indexPath) else {
return
}
navigate(to: selectedTag)
}
}
// MARK: - Fetched results delegate
extension SiteTagsViewController: NSFetchedResultsControllerDelegate {
func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
refreshNoResultsView()
}
}
// MARK: - Navigation to Tag details
extension SiteTagsViewController {
fileprivate func navigate(to tag: PostTag?) {
let titleSectionHeader = NSLocalizedString("Tag", comment: "Section header for tag name in Tag Details View.")
let subtitleSectionHeader = NSLocalizedString("Description", comment: "Section header for tag name in Tag Details View.")
let titleErrorFooter = NSLocalizedString("Name Required", comment: "Error to be displayed when a tag is empty")
let content = SettingsTitleSubtitleController.Content(title: tag?.name,
subtitle: tag?.tagDescription,
titleHeader: titleSectionHeader,
subtitleHeader: subtitleSectionHeader,
titleErrorFooter: titleErrorFooter)
let confirmationContent = confirmation()
let tagDetailsView = SettingsTitleSubtitleController(content: content, confirmation: confirmationContent)
tagDetailsView.setAction { [weak self] updatedData in
self?.navigationController?.popViewController(animated: true)
guard let tag = tag else {
return
}
self?.delete(tag)
}
tagDetailsView.setUpdate { [weak self] updatedData in
guard let tag = tag else {
self?.addTag(data: updatedData)
return
}
guard self?.tagWasUpdated(tag: tag, updatedTag: updatedData) == true else {
return
}
self?.updateTag(tag, updatedData: updatedData)
}
navigationController?.pushViewController(tagDetailsView, animated: true)
}
private func addTag(data: SettingsTitleSubtitleController.Content) {
if let existingTag = existingTagForData(data) {
displayAlertForExistingTag(existingTag)
return
}
guard let newTag = NSEntityDescription.insertNewObject(forEntityName: "PostTag", into: ContextManager.sharedInstance().mainContext) as? PostTag else {
return
}
newTag.name = data.title
newTag.tagDescription = data.subtitle
save(newTag)
}
private func updateTag(_ tag: PostTag, updatedData: SettingsTitleSubtitleController.Content) {
// Lets check that we are not updating a tag to a name that already exists
if let existingTag = existingTagForData(updatedData),
existingTag != tag {
displayAlertForExistingTag(existingTag)
return
}
tag.name = updatedData.title
tag.tagDescription = updatedData.subtitle
save(tag)
}
private func existingTagForData(_ data: SettingsTitleSubtitleController.Content) -> PostTag? {
guard let title = data.title else {
return nil
}
let request = NSFetchRequest<NSFetchRequestResult>(entityName: "PostTag")
request.predicate = NSPredicate(format: "blog.blogID = %@ AND name = %@", blog.dotComID!, title)
request.fetchLimit = 1
guard let results = (try? context.fetch(request)) as? [PostTag] else {
return nil
}
return results.first
}
fileprivate func displayAlertForExistingTag(_ tag: PostTag) {
let title = NSLocalizedString("Tag already exists",
comment: "Title of the alert indicating that a tag with that name already exists.")
let tagName = tag.name ?? ""
let message = String(format: NSLocalizedString("A tag named '%@' already exists.",
comment: "Message of the alert indicating that a tag with that name already exists. The placeholder is the name of the tag"),
tagName)
let acceptTitle = NSLocalizedString("OK", comment: "Alert dismissal title")
let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
alertController.addDefaultActionWithTitle(acceptTitle)
present(alertController, animated: true)
}
private func tagWasUpdated(tag: PostTag, updatedTag: SettingsTitleSubtitleController.Content) -> Bool {
if tag.name == updatedTag.title && tag.tagDescription == updatedTag.subtitle {
return false
}
return true
}
private func confirmation() -> SettingsTitleSubtitleController.Confirmation {
let confirmationTitle = NSLocalizedString("Delete this tag", comment: "Delete Tag confirmation action title")
let confirmationSubtitle = NSLocalizedString("Are you sure you want to delete this tag?", comment: "Message asking for confirmation on tag deletion")
let actionTitle = NSLocalizedString("Delete", comment: "Delete")
let cancelTitle = NSLocalizedString("Cancel", comment: "Alert dismissal title")
let trashIcon = UIImage.gridicon(.trash)
return SettingsTitleSubtitleController.Confirmation(title: confirmationTitle,
subtitle: confirmationSubtitle,
actionTitle: actionTitle,
cancelTitle: cancelTitle,
icon: trashIcon,
isDestructiveAction: true)
}
}
// MARK: - Empty state handling
private extension SiteTagsViewController {
func refreshNoResultsView() {
let noResults = resultsController.fetchedObjects?.count == 0
showRightBarButton(!noResults)
if noResults {
showNoResults()
} else {
hideNoResults()
}
}
func showNoResults() {
if isSearching {
showNoSearchResultsView()
return
}
if isPerformingInitialSync {
showLoadingView()
return
}
showEmptyResultsView()
}
func showLoadingView() {
configureAndDisplayNoResults(title: NoResultsText.loadingTitle, accessoryView: NoResultsViewController.loadingAccessoryView())
removeSearchBar()
}
func showEmptyResultsView() {
configureAndDisplayNoResults(title: NoResultsText.noTagsTitle, subtitle: NoResultsText.noTagsMessage, buttonTitle: NoResultsText.createButtonTitle)
removeSearchBar()
}
func showNoSearchResultsView() {
// If already shown, don't show again. To prevent the view from "flashing" as the user types.
guard !noResultsShown else {
return
}
configureAndDisplayNoResults(title: NoResultsText.noResultsTitle, forNoSearchResults: true)
}
func configureAndDisplayNoResults(title: String,
subtitle: String? = nil,
buttonTitle: String? = nil,
accessoryView: UIView? = nil,
forNoSearchResults: Bool = false) {
if forNoSearchResults {
noResultsViewController.configureForNoSearchResults(title: title)
} else {
noResultsViewController.configure(title: title, buttonTitle: buttonTitle, subtitle: subtitle, accessoryView: accessoryView)
}
displayNoResults()
}
func displayNoResults() {
addChild(noResultsViewController)
noResultsViewController.view.frame = tableView.frame
// Since the tableView doesn't always start at the top, adjust the NRV accordingly.
if isSearching {
noResultsViewController.view.frame.origin.y = searchController.searchBar.frame.height
} else {
noResultsViewController.view.frame.origin.y = 0
}
tableView.addSubview(withFadeAnimation: noResultsViewController.view)
noResultsViewController.didMove(toParent: self)
}
func hideNoResults() {
noResultsViewController.removeFromView()
setupSearchBar()
tableView.reloadData()
}
var noResultsShown: Bool {
return noResultsViewController.parent != nil
}
struct NoResultsText {
static let noTagsTitle = NSLocalizedString("You don't have any tags", comment: "Empty state. Tags management (Settings > Writing > Tags)")
static let noTagsMessage = NSLocalizedString("Tags created here can be quickly added to new posts", comment: "Displayed when the user views tags in blog settings and there are no tags")
static let createButtonTitle = NSLocalizedString("Create a Tag", comment: "Title of the button in the placeholder for an empty list of blog tags.")
static let loadingTitle = NSLocalizedString("Loading...", comment: "Loading tags.")
static let noResultsTitle = NSLocalizedString("No tags matching your search", comment: "Displayed when the user is searching site tags and there are no matches.")
}
}
// MARK: - NoResultsViewControllerDelegate
extension SiteTagsViewController: NoResultsViewControllerDelegate {
func actionButtonPressed() {
createTag()
}
}
// MARK: - SearchResultsUpdater
extension SiteTagsViewController: UISearchResultsUpdating {
func updateSearchResults(for searchController: UISearchController) {
guard let text = searchController.searchBar.text, text != "" else {
refreshResultsController(predicate: defaultPredicate)
return
}
let filterPredicate = NSPredicate(format: "blog.blogID = %@ AND name contains [cd] %@", blog.dotComID!, text)
refreshResultsController(predicate: filterPredicate)
}
}
// MARK: - UISearchControllerDelegate Conformance
extension SiteTagsViewController: UISearchControllerDelegate {
func willPresentSearchController(_ searchController: UISearchController) {
isSearching = true
deactivateRefreshControl()
}
func willDismissSearchController(_ searchController: UISearchController) {
isSearching = false
setupRefreshControl()
}
}
| gpl-2.0 | f7246efb539bd5be66356214585e07bf | 36.559687 | 193 | 0.646694 | 5.744687 | false | false | false | false |
ivlevAstef/DITranquillity | Sources/Core/Internal/Component.swift | 1 | 2999 | //
// Component.swift
// DITranquillity
//
// Created by Alexander Ivlev on 10/06/16.
// Copyright © 2016 Alexander Ivlev. All rights reserved.
//
typealias Injection = (signature: MethodSignature, cycle: Bool)
// Reference
final class ComponentContainer {
private var map = Dictionary<TypeKey, Set<Component>>()
private var manyMap = Dictionary<ShortTypeKey, Set<Component>>()
func insert(_ key: TypeKey, _ component: Component, otherOperation: (() -> Void)? = nil) {
let shortKey = ShortTypeKey(by: key.type)
mutex.sync {
if nil == map[key]?.insert(component) {
map[key] = [component]
}
if nil == manyMap[shortKey]?.insert(component) {
manyMap[shortKey] = [component]
}
otherOperation?()
}
}
subscript(_ key: TypeKey) -> Set<Component> {
return mutex.sync {
return map[key] ?? []
}
}
subscript(_ key: ShortTypeKey) -> Set<Component> {
return mutex.sync {
return manyMap[key] ?? []
}
}
var components: [Component] {
let values = mutex.sync { map.values.flatMap { $0 } }
let sortedValues = values.sorted(by: { $0.order < $1.order })
var result = sortedValues
// remove dublicates - dublicates generated for `as(Type.self)`
var index = 0
while index + 1 < result.count {
if result[index].order == result[index + 1].order {
result.remove(at: index)
continue
}
index += 1
}
return result
}
private let mutex = PThreadMutex(normal: ())
}
private var componentsCount: Int = 0
private let componentsCountSynchronizer = makeFastLock()
final class Component {
typealias UniqueKey = DIComponentInfo
init(componentInfo: DIComponentInfo, in framework: DIFramework.Type?, _ part: DIPart.Type?) {
self.info = componentInfo
self.framework = framework
self.part = part
componentsCountSynchronizer.lock()
componentsCount += 1
self.order = componentsCount
componentsCountSynchronizer.unlock()
}
let info: DIComponentInfo
let framework: DIFramework.Type?
let part: DIPart.Type?
let order: Int
var lifeTime = DILifeTime.default
var priority: DIComponentPriority = .normal
var alternativeTypes: [ComponentAlternativeType] = []
fileprivate(set) var initial: MethodSignature?
fileprivate(set) var injections: [Injection] = []
var postInit: MethodSignature?
}
extension Component: Hashable {
#if swift(>=5.0)
func hash(into hasher: inout Hasher) {
hasher.combine(info)
}
#else
var hashValue: Int { return info.hashValue }
#endif
static func ==(lhs: Component, rhs: Component) -> Bool {
return lhs.info == rhs.info
}
}
extension Component {
func set(initial signature: MethodSignature) {
initial = signature
}
func append(injection signature: MethodSignature, cycle: Bool) {
injections.append(Injection(signature: signature, cycle: cycle))
}
}
typealias Components = ContiguousArray<Component>
| mit | 35f5f2baaf7cfe3d19c45f62bafd8897 | 23.57377 | 95 | 0.661107 | 3.929227 | false | false | false | false |
dnevera/IMProcessing | IMProcessing/Classes/Base/IMPFilter.swift | 1 | 12173 | //
// IMPFilter.swift
// IMProcessing
//
// Created by denis svinarchuk on 16.12.15.
// Copyright © 2015 IMetalling. All rights reserved.
//
#if os(iOS)
import UIKit
#else
import Cocoa
#endif
import Metal
public protocol IMPFilterProtocol:IMPContextProvider {
var source:IMPImageProvider? {get set}
var destination:IMPImageProvider? {get}
var observersEnabled:Bool {get set}
var dirty:Bool {get set}
func apply() -> IMPImageProvider
}
public class IMPFilter: NSObject,IMPFilterProtocol {
public typealias SourceHandler = ((source:IMPImageProvider) -> Void)
public typealias DestinationHandler = ((destination:IMPImageProvider) -> Void)
public typealias DirtyHandler = (() -> Void)
public var observersEnabled = true {
didSet {
for f in filterList {
f.observersEnabled = observersEnabled
}
}
}
public var context:IMPContext!
public var enabled = true {
didSet{
for filter in filterList {
filter.enabled = enabled
}
dirty = true
if enabled == false && oldValue != enabled {
executeDestinationObservers(source)
}
}
}
public var source:IMPImageProvider?{
didSet{
if let s = source{
s.filter=self
_destination.orientation = s.orientation
}
executeNewSourceObservers(source)
dirty = true
}
}
public var destination:IMPImageProvider?{
get{
if enabled {
return self.apply()
}
else{
return source
}
}
}
public var destinationSize:MTLSize?{
didSet{
if let ov = oldValue{
if ov != destinationSize! {
dirty = true
}
}
else{
dirty = true
}
}
}
public var dirty:Bool{
set(newDirty){
context.dirty = newDirty
for f in filterList{
f.dirty = newDirty
}
if newDirty == true /*&& context.dirty != true*/ {
for o in dirtyHandlers{
o()
}
}
}
get{
return context.dirty
}
}
required public init(context: IMPContext) {
self.context = context
}
private var functionList:[IMPFunction] = [IMPFunction]()
private var filterList:[IMPFilter] = [IMPFilter]()
private var newSourceObservers:[SourceHandler] = [SourceHandler]()
private var sourceObservers:[SourceHandler] = [SourceHandler]()
private var destinationObservers:[DestinationHandler] = [DestinationHandler]()
private var dirtyHandlers:[DirtyHandler] = [DirtyHandler]()
public final func addFunction(function:IMPFunction){
if functionList.contains(function) == false {
functionList.append(function)
self.dirty = true
}
}
public final func removeFunction(function:IMPFunction){
if let index = functionList.indexOf(function) {
functionList.removeAtIndex(index)
self.dirty = true
}
}
public final func removeAllFunctions(){
functionList.removeAll()
self.dirty = true
}
var _root:IMPFilter? = nil
public var root:IMPFilter? {
return _root
}
func updateNewFilterHandlers(filter:IMPFilter) {
filter._root = self
for o in dirtyHandlers{
filter.addDirtyObserver(o)
}
dirty = true
}
func removeFilterHandlers(filter:IMPFilter) {
filter._root = nil
filter.dirtyHandlers.removeAll()
dirty = true
}
public final func addFilter(filter:IMPFilter){
if filterList.contains(filter) == false {
filterList.append(filter)
updateNewFilterHandlers(filter)
}
}
public final func removeFilter(filter:IMPFilter){
if let index = filterList.indexOf(filter) {
removeFilterHandlers(filterList.removeAtIndex(index) as IMPFilter)
}
}
public final func removeFromStack() {
if _root != nil {
_root?.removeFilter(self)
}
}
public final func insertFilter(filter:IMPFilter, index:Int){
if filterList.contains(filter) == false {
var i = index
if i >= filterList.count {
i = filterList.count
}
filterList.insert(filter, atIndex: i)
updateNewFilterHandlers(filter)
}
}
public final func insertFilter(filter:IMPFilter, before:IMPFilter){
if filterList.contains(filter) == false {
if let index = filterList.indexOf(before) {
filterList.insert(filter, atIndex: index)
updateNewFilterHandlers(filter)
}
}
}
public final func insertFilter(filter:IMPFilter, after:IMPFilter){
if filterList.contains(filter) == false {
if let index = filterList.indexOf(after) {
filterList.insert(filter, atIndex: index+1)
updateNewFilterHandlers(filter)
}
}
}
public final func addNewSourceObserver(source observer:SourceHandler){
newSourceObservers.append(observer)
}
public final func addSourceObserver(source observer:SourceHandler){
sourceObservers.append(observer)
}
public final func addDestinationObserver(destination observer:DestinationHandler){
destinationObservers.append(observer)
}
public final func addDirtyObserver(observer:DirtyHandler){
dirtyHandlers.append(observer)
for f in filterList{
f.addDirtyObserver(observer)
}
}
public func configure(function:IMPFunction, command:MTLComputeCommandEncoder){}
internal func executeNewSourceObservers(source:IMPImageProvider?){
if let s = source{
for o in newSourceObservers {
o(source: s)
}
}
}
internal func executeSourceObservers(source:IMPImageProvider?){
if observersEnabled {
if let s = source{
for o in sourceObservers {
o(source: s)
}
}
}
}
internal func executeDestinationObservers(destination:IMPImageProvider?){
if observersEnabled {
if let d = destination {
for o in destinationObservers {
o(destination: d)
}
}
}
}
var passThroughKernel:IMPFunction?
public func apply() -> IMPImageProvider {
return doApply()
}
func newDestinationtexture(destination provider:IMPImageProvider, source input: MTLTexture) -> (MTLTexture, Int, Int) {
var width = input.width
var height = input.height
if let s = self.destinationSize {
width = s.width
height = s.height
}
if provider.texture?.width != width || provider.texture?.height != height
||
provider === source
{
let descriptor = MTLTextureDescriptor.texture2DDescriptorWithPixelFormat(
input.pixelFormat,
width: width, height: height, mipmapped: false)
if provider.texture != nil {
provider.texture?.setPurgeableState(MTLPurgeableState.Empty)
}
return (context.device.newTextureWithDescriptor(descriptor), width, height)
}
else {
return (provider.texture!, provider.texture!.width, provider.texture!.height)
}
}
public func main(source source: IMPImageProvider , destination provider:IMPImageProvider) -> IMPImageProvider? {
return nil
}
func internal_main(source source: IMPImageProvider , destination provider:IMPImageProvider) -> IMPImageProvider {
var currentFilter = self
var currrentProvider:IMPImageProvider = source
if var input = source.texture {
if functionList.count > 0 {
var width:Int
var height:Int
let texture:MTLTexture
(texture, width, height) = self.newDestinationtexture(destination: provider, source: input)
provider.texture = texture
if let output = provider.texture {
//
// Functions
//
for function in self.functionList {
self.context.execute { (commandBuffer) -> Void in
let threadgroupCounts = MTLSizeMake(function.groupSize.width, function.groupSize.height, 1);
let threadgroups = MTLSizeMake(
(width + threadgroupCounts.width ) / threadgroupCounts.width ,
(height + threadgroupCounts.height) / threadgroupCounts.height,
1);
let commandEncoder = commandBuffer.computeCommandEncoder()
commandEncoder.setComputePipelineState(function.pipeline!)
commandEncoder.setTexture(input, atIndex:0)
commandEncoder.setTexture(output, atIndex:1)
self.configure(function, command: commandEncoder)
commandEncoder.dispatchThreadgroups(threadgroups, threadsPerThreadgroup:threadgroupCounts)
commandEncoder.endEncoding()
}
input = output
}
currrentProvider = provider
}
}
if let p = main(source: currrentProvider, destination: provider) {
currrentProvider = p
}
//
// Filter chains...
//
for filter in filterList {
filter.source = currrentProvider
currentFilter = filter
currrentProvider = currentFilter.destination!
}
}
return currrentProvider
}
private lazy var _destination:IMPImageProvider = {
return IMPImageProvider(context: self.context)
}()
func doApply() -> IMPImageProvider {
if let s = self.source{
if dirty {
if functionList.count == 0 && filterList.count == 0 {
//
// copy source to destination
//
//passThroughKernel = passThroughKernel ?? IMPFunction(context: self.context, name: IMPSTD_PASS_KERNEL)
//addFunction(passThroughKernel!)
}
executeSourceObservers(source)
_destination = internal_main(source: s, destination: _destination)
executeDestinationObservers(_destination)
}
}
dirty = false
return _destination
}
deinit {
_destination.texture = nil
source = nil
}
}
| mit | 5003c24c1e21dc6fae3582d50f658d15 | 28.980296 | 123 | 0.517253 | 5.601473 | false | false | false | false |
jarimartens10/wwdc-2015 | Jari Martens/JMClasses.swift | 1 | 5079 | //
// JMClasses.swift
// Jari Martens
//
// Created by Jari Martens on 16-04-15.
// Copyright (c) 2015 Jari Martens. All rights reserved.
//
import Foundation
enum JMClasses {
case MathB
case MathD
case Dutch
case German
case IB
case Latin
case Physics
case Chemistry
case Philosophy
case ANW
case MO
case PE
case RE
case Civics
static var all_values: [JMClasses] {
return [.MathB, .MathD, .Dutch, .German, .IB, .Latin, .Physics, .Chemistry, .Philosophy, .ANW, .MO, .PE, .RE, .Civics]
}
var description: String {
switch self{
case .MathB:
return "Math B is math with the focus on exact sciences, instead of social sciences."
case .MathD:
return "Math D is extra math, and is for example about probability and combinatorics."
case .Dutch:
return "Dutch is my native language, and is a mandatory class."
case .German:
return "German is, well, German."
case .IB:
return "International Baccalaureate, or simple IB, is a higher level of English than most people get taught in the class English. For example, this year we have to write an extended essay about a poem. \nI have a certificate of the Anglia exam, that my level of English is near-native."
case .Latin:
return "Latin is the study of ancient Latin texts, such as translating Caesar's De Bello Gallico. We are also taught about the culture of the Romans."
case .Physics:
return "In Physics we are taught formulas and theory about several subjects, such as electricity, Newton's laws, characteristics of matirials, et cetera."
case .Chemistry:
return "In Chemistry we are taught about atoms, salts, ions and the naming of hydrocarbons and other substances."
case .Philosophy:
return "At Philosophy we study great philosophers of the past. We also develop an own opinion and learn how to support these with valid arguments."
case .ANW:
return "Natural Science is a mandatory class that is all about general information of for example Physics and Chemistry."
case .MO:
return "Management and Organization is all about organizations. Currently, we are learning about non-profit organizations, but next year it will be all about profit organizations. It could be compared with Business Science."
case .PE:
return "Physical Education is a mandatory class."
case .RE:
return "Religious Education is a mandatory class that is comparable with Philosophy, except for the fact that we are taught less about the visions of philosophers, and more about the visions of various religions."
case .Civics:
return "Social Sciences is a mandatory class that is all about the politics in the Netherlands, my home country."
}
}
var name: String {
switch self {
case .MathB:
return "Math B"
case .MathD:
return "Math D"
case .Dutch:
return "Dutch"
case .German:
return "German"
case .IB:
return "International Baccalaureate"
case .Latin:
return "Latin"
case .Physics:
return "Physics"
case .Chemistry:
return "Chemistry"
case .Philosophy:
return "Philosophy"
case .ANW:
return "Natural science"
case .MO:
return "Management & Organization"
case .PE:
return "Physical Education"
case .RE:
return "Religious Education"
case .Civics:
return "Social studies"
}
}
var mark: Double {
switch self {
case .MathB:
return 8.8
case .MathD:
return 8.9
case .Dutch:
return 7.1
case .Latin:
return 7.0
case .German:
return 7.8
case .IB:
return 6.9
case .Physics:
return 7.7
case .Chemistry:
return 8.5
case .Philosophy:
return 8.0
case .MO:
return 9.7
case .PE:
return 6.3
case .Civics:
return 6.0
case .ANW:
return 7.5
case .RE:
return 7.9
}
}
var convertedMark: String {
if mark >= 9.0 {
return "A+"
}
else if mark >= 8.5 {
return "A"
}
else if mark >= 7.8 {
return "B+"
}
else if mark >= 7.3 {
return "B"
}
else if mark >= 6.8 {
return "C+"
}
else if mark >= 6.3 {
return "C"
}
else if mark >= 5.8 {
return "D+"
}
else if mark >= 5.0 {
return "D"
}
else {
return "F"
}
}
} | apache-2.0 | 9fddbe5cb4ced53122ee3f9da35f9614 | 30.552795 | 298 | 0.555424 | 4.300593 | false | false | false | false |
kinyong/KYWeiboDemo-Swfit | AYWeibo/AYWeibo/classes/Home/AYScanView.swift | 2 | 6823 | //
// AYScanView.swift
// AYWeibo
//
// Created by Ayong on 16/6/10.
// Copyright © 2016年 Ayong. All rights reserved.
//
import UIKit
class AYScanView: UIView {
private var borderImgView: UIImageView!
private var scaningImgView: UIImageView!
private var topConstraintScan: NSLayoutConstraint! // 扫描视图的顶部约束
private var heightConstraintBorder: NSLayoutConstraint! // 边框图片的高度约束
private var heightConstraintScan: NSLayoutConstraint! // 扫描视图的高度约束
override init(frame: CGRect) {
super.init(frame: frame)
// 1.添加子视图
setupSubViews()
// 2.布局约束
setupConstraints()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func layoutSubviews() {
heightConstraintBorder.constant = self.frame.height
heightConstraintScan.constant = self.frame.height
}
// MARK: - 内部实现方法
private func setupSubViews() {
// 1.添加边框图片
borderImgView = UIImageView()
borderImgView.image = UIImage(named: "qrcode_border")
addSubview(borderImgView)
// 2.添加扫描视图
scaningImgView = UIImageView()
scaningImgView.image = UIImage(named: "qrcode_scanline_qrcode")
addSubview(scaningImgView)
}
private func setupConstraints() {
borderImgView.translatesAutoresizingMaskIntoConstraints = false
scaningImgView.translatesAutoresizingMaskIntoConstraints = false
// 添加边框图片约束
let widthConstraintBorder = NSLayoutConstraint(item: borderImgView,
attribute: .Width,
relatedBy: .Equal,
toItem: nil,
attribute: .NotAnAttribute,
multiplier: 0.0,
constant: self.frame.width)
heightConstraintBorder = NSLayoutConstraint(item: borderImgView,
attribute: .Height,
relatedBy: .Equal,
toItem: nil,
attribute: .NotAnAttribute,
multiplier: 0.0,
constant: self.frame.width)
let topConstraintBorder = NSLayoutConstraint(item: borderImgView,
attribute: .Top,
relatedBy: .Equal,
toItem: self,
attribute: .Top,
multiplier: 1.0,
constant: 0.0)
let leadingConstraintBorder = NSLayoutConstraint(item: borderImgView,
attribute: .Leading,
relatedBy: .Equal,
toItem: self,
attribute: .Leading,
multiplier: 1.0,
constant: 0.0)
borderImgView.addConstraints([widthConstraintBorder, heightConstraintBorder])
addConstraints([topConstraintBorder, leadingConstraintBorder])
// 添加扫描视图约束
let widthConstraintScan = NSLayoutConstraint(item: scaningImgView,
attribute: .Width,
relatedBy: .Equal,
toItem: nil,
attribute: .NotAnAttribute,
multiplier: 0.0,
constant: self.frame.width)
heightConstraintScan = NSLayoutConstraint(item: scaningImgView,
attribute: .Height,
relatedBy: .Equal,
toItem: nil,
attribute: .NotAnAttribute,
multiplier: 0.0,
constant: self.frame.width)
topConstraintScan = NSLayoutConstraint(item: scaningImgView,
attribute: .Top,
relatedBy: .Equal,
toItem: self,
attribute: .Top,
multiplier: 1.0,
constant: 0.0)
let leadingConstraintScan = NSLayoutConstraint(item: scaningImgView,
attribute: .Leading,
relatedBy: .Equal,
toItem: self,
attribute: .Leading,
multiplier: 1.0,
constant: 0.0)
scaningImgView.addConstraints([widthConstraintScan, heightConstraintScan])
self.addConstraints([topConstraintScan, leadingConstraintScan])
}
// MARK: - 外部实现方法
/// 扫描动画
func animateWithScan() {
// 0. 每次动画开始初始化位置
topConstraintScan.constant = 0.0
// 1.动画开始前的顶部约束位置
topConstraintScan.constant = -self.frame.height
self.layoutIfNeeded()
// 2. 执行动画
UIView.animateWithDuration(2.0) {
UIView.setAnimationRepeatCount(MAXFLOAT)
self.topConstraintScan.constant = self.frame.height
self.layoutIfNeeded()
}
}
}
| apache-2.0 | 5fc954521b0cba0591e2ed31f96d10db | 43.635135 | 85 | 0.40221 | 7.364548 | false | false | false | false |
silt-lang/silt | Sources/Seismography/DeclRef.swift | 1 | 688 | /// DeclRef.swift
///
/// Copyright 2017-2018, The Silt Language Project.
///
/// This project is released under the MIT license, a copy of which is
/// available in the repository.
public struct DeclRef: Hashable {
public enum Kind: Int {
case function = 0
case dataConstructor = 1
}
public let name: String
public let kind: Kind
public init(_ name: String, _ kind: Kind) {
self.name = name
self.kind = kind
}
public static func == (lhs: DeclRef, rhs: DeclRef) -> Bool {
return lhs.name == rhs.name && lhs.kind == rhs.kind
}
public func hash(into hasher: inout Hasher) {
self.name.hash(into: &hasher)
self.kind.hash(into: &hasher)
}
}
| mit | 3d1e909b64829fc198be89eec31fca29 | 22.724138 | 70 | 0.648256 | 3.583333 | false | false | false | false |
IngmarStein/swift | test/SILGen/objc_witnesses.swift | 3 | 3628 | // RUN: %target-swift-frontend -emit-silgen -sdk %S/Inputs -I %S/Inputs -enable-source-import %s | %FileCheck %s
// REQUIRES: objc_interop
import Foundation
import gizmo
protocol Fooable {
func foo() -> String!
}
// Witnesses Fooable.foo with the original ObjC-imported -foo method .
extension Foo: Fooable {}
class Phoûx : NSObject, Fooable {
@objc func foo() -> String! {
return "phoûx!"
}
}
// witness for Foo.foo uses the foreign-to-native thunk:
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWCSo3Foo14objc_witnesses7FooableS0_FS1_3foo
// CHECK: function_ref @_TTOFCSo3Foo3foo
// *NOTE* We have an extra copy here for the time being right
// now. This will change once we teach SILGen how to not emit the
// extra copy.
//
// witness for Phoûx.foo uses the Swift vtable
// CHECK-LABEL: _TFC14objc_witnessesX8Phox_xra3foo
// CHECK: bb0([[IN_ADDR:%.*]] :
// CHECK: [[STACK_SLOT:%.*]] = alloc_stack $Phoûx
// CHECK: copy_addr [[IN_ADDR]] to [initialization] [[STACK_SLOT]]
// CHECK: [[VALUE:%.*]] = load [[STACK_SLOT]]
// CHECK: class_method [[VALUE]] : $Phoûx, #Phoûx.foo!1
protocol Bells {
init(bellsOn: Int)
}
extension Gizmo : Bells {
}
// CHECK: sil hidden [transparent] [thunk] @_TTWCSo5Gizmo14objc_witnesses5BellsS0_FS1_C
// CHECK: bb0([[SELF:%[0-9]+]] : $*Gizmo, [[I:%[0-9]+]] : $Int, [[META:%[0-9]+]] : $@thick Gizmo.Type):
// CHECK: [[INIT:%[0-9]+]] = function_ref @_TFCSo5GizmoC{{.*}} : $@convention(method) (Int, @thick Gizmo.Type) -> @owned Optional<Gizmo>
// CHECK: [[IUO_RESULT:%[0-9]+]] = apply [[INIT]]([[I]], [[META]]) : $@convention(method) (Int, @thick Gizmo.Type) -> @owned Optional<Gizmo>
// CHECK: switch_enum [[IUO_RESULT]]
// CHECK: [[UNWRAPPED_RESULT:%[0-9]+]] = unchecked_enum_data [[IUO_RESULT]]
// CHECK: store [[UNWRAPPED_RESULT]] to [[SELF]] : $*Gizmo
// Test extension of a native @objc class to conform to a protocol with a
// subscript requirement. rdar://problem/20371661
protocol Subscriptable {
subscript(x: Int) -> Any { get }
}
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWCSo7NSArray14objc_witnesses13SubscriptableS0_FS1_g9subscriptFSiP_ : $@convention(witness_method) (Int, @in_guaranteed NSArray) -> @out Any {
// CHECK: function_ref @_TTOFCSo7NSArrayg9subscriptFSiP_ : $@convention(method) (Int, @guaranteed NSArray) -> @out Any
// CHECK-LABEL: sil shared [thunk] @_TTOFCSo7NSArrayg9subscriptFSiP_ : $@convention(method) (Int, @guaranteed NSArray) -> @out Any {
// CHECK: class_method [volatile] {{%.*}} : $NSArray, #NSArray.subscript!getter.1.foreign
extension NSArray: Subscriptable {}
// witness is a dynamic thunk:
protocol Orbital {
var quantumNumber: Int { get set }
}
class Electron : Orbital {
dynamic var quantumNumber: Int = 0
}
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWC14objc_witnesses8ElectronS_7OrbitalS_FS1_g13quantumNumberSi
// CHECK-LABEL: sil shared [transparent] [thunk] @_TTDFC14objc_witnesses8Electrong13quantumNumberSi
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWC14objc_witnesses8ElectronS_7OrbitalS_FS1_s13quantumNumberSi
// CHECK-LABEL: sil shared [transparent] [thunk] @_TTDFC14objc_witnesses8Electrons13quantumNumberSi
// witness is a dynamic thunk and is public:
public protocol Lepton {
var spin: Float { get }
}
public class Positron : Lepton {
public dynamic var spin: Float = 0.5
}
// CHECK-LABEL: sil [transparent] [fragile] [thunk] @_TTWC14objc_witnesses8PositronS_6LeptonS_FS1_g4spinSf
// CHECK-LABEL: sil shared [transparent] [fragile] [thunk] @_TTDFC14objc_witnesses8Positrong4spinSf
| apache-2.0 | f31ce12c7095f4487357203216d8fff6 | 37.946237 | 194 | 0.688294 | 3.263063 | false | false | false | false |
rshankras/WordPress-iOS | WordPress/Classes/ViewRelated/Cells/SwitchTableViewCell.swift | 3 | 2240 | import Foundation
/**
* @class SwitchTableViewCell
* @brief The purpose of this class is to simply display a regular TableViewCell, with a Switch
* on the right hand side.
*/
public class SwitchTableViewCell : WPTableViewCell
{
// MARK: - Public Properties
public var onChange : ((newValue: Bool) -> ())?
public var name : String {
get {
return textLabel?.text ?? String()
}
set {
textLabel?.text = newValue
}
}
public var on : Bool {
get {
return flipSwitch.on
}
set {
flipSwitch.on = newValue
}
}
// MARK: - Initializers
public required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupSubviews()
}
public required override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
setupSubviews()
}
// MARK: - UITapGestureRecognizer Helpers
@IBAction private func rowWasPressed(recognizer: UITapGestureRecognizer) {
// Manually relay the event, since .ValueChanged doesn't get posted if we toggle the switch
// programatically
flipSwitch.setOn(!on, animated: true)
switchDidChange(flipSwitch)
}
// MARK: - UISwitch Helpers
@IBAction private func switchDidChange(theSwitch: UISwitch) {
onChange?(newValue: theSwitch.on)
}
// MARK: - Private Helpers
private func setupSubviews() {
selectionStyle = .None
contentView.addGestureRecognizer(tapGestureRecognizer)
tapGestureRecognizer.addTarget(self, action: "rowWasPressed:")
flipSwitch = UISwitch()
flipSwitch.addTarget(self, action: "switchDidChange:", forControlEvents: .ValueChanged)
accessoryView = flipSwitch
WPStyleGuide.configureTableViewCell(self)
}
// MARK: - Private Properties
private let tapGestureRecognizer = UITapGestureRecognizer()
// MARK: - Private Outlets
private var flipSwitch : UISwitch!
}
| gpl-2.0 | 7f44b70d8b351d38ba2ffd3aae0119dc | 25.046512 | 105 | 0.601786 | 5.517241 | false | false | false | false |
syd24/DouYuZB | DouYu/Pods/Kingfisher/Sources/ImageProcessor.swift | 2 | 14315 | //
// ImageProcessor.swift
// Kingfisher
//
// Created by Wei Wang on 2016/08/26.
//
// Copyright (c) 2016 Wei Wang <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
import CoreGraphics
/// The item which could be processed by an `ImageProcessor`
///
/// - image: Input image
/// - data: Input data
public enum ImageProcessItem {
case image(Image)
case data(Data)
}
/// An `ImageProcessor` would be used to convert some downloaded data to an image.
public protocol ImageProcessor {
/// Identifier of the processor. It will be used to identify the processor when
/// caching and retriving an image. You might want to make sure that processors with
/// same properties/functionality have the same identifiers, so correct processed images
/// could be retrived with proper key.
///
/// - Note: Do not supply an empty string for a customized processor, which is already taken by
/// the `DefaultImageProcessor`. It is recommended to use a reverse domain name notation
/// string of your own for the identifier.
var identifier: String { get }
/// Process an input `ImageProcessItem` item to an image for this processor.
///
/// - parameter item: Input item which will be processed by `self`
/// - parameter options: Options when processing the item.
///
/// - returns: The processed image.
///
/// - Note: The return value will be `nil` if processing failed while converting data to image.
/// If input item is already an image and there is any errors in processing, the input
/// image itself will be returned.
/// - Note: Most processor only supports CG-based images.
/// watchOS is not supported for processers containing filter, the input image will be returned directly on watchOS.
func process(item: ImageProcessItem, options: KingfisherOptionsInfo) -> Image?
}
typealias ProcessorImp = ((ImageProcessItem, KingfisherOptionsInfo) -> Image?)
public extension ImageProcessor {
/// Append an `ImageProcessor` to another. The identifier of the new `ImageProcessor`
/// will be "\(self.identifier)|>\(another.identifier)>".
///
/// - parameter another: An `ImageProcessor` you want to append to `self`.
///
/// - returns: The new `ImageProcessor`. It will process the image in the order
/// of the two processors concatenated.
public func append(another: ImageProcessor) -> ImageProcessor {
let newIdentifier = identifier.appending("|>\(another.identifier)")
return GeneralProcessor(identifier: newIdentifier) {
item, options in
if let image = self.process(item: item, options: options) {
return another.process(item: .image(image), options: options)
} else {
return nil
}
}
}
}
fileprivate struct GeneralProcessor: ImageProcessor {
let identifier: String
let p: ProcessorImp
func process(item: ImageProcessItem, options: KingfisherOptionsInfo) -> Image? {
return p(item, options)
}
}
/// The default processor. It convert the input data to a valid image.
/// Images of .PNG, .JPEG and .GIF format are supported.
/// If an image is given, `DefaultImageProcessor` will do nothing on it and just return that image.
public struct DefaultImageProcessor: ImageProcessor {
/// A default `DefaultImageProcessor` could be used across.
public static let `default` = DefaultImageProcessor()
public let identifier = ""
/// Initialize a `DefaultImageProcessor`
///
/// - returns: An initialized `DefaultImageProcessor`.
public init() {}
public func process(item: ImageProcessItem, options: KingfisherOptionsInfo) -> Image? {
switch item {
case .image(let image):
return image
case .data(let data):
return Image.kf_image(data: data, scale: options.scaleFactor, preloadAllGIFData: options.preloadAllGIFData)
}
}
}
/// Processor for making round corner images. Only CG-based images are supported in macOS,
/// if a non-CG image passed in, the processor will do nothing.
public struct RoundCornerImageProcessor: ImageProcessor {
public let identifier: String
/// Corner radius will be applied in processing.
public let cornerRadius: CGFloat
/// Target size of output image should be. If `nil`, the image will keep its original size after processing.
public let targetSize: CGSize?
/// Initialize a `RoundCornerImageProcessor`
///
/// - parameter cornerRadius: Corner radius will be applied in processing.
/// - parameter targetSize: Target size of output image should be. If `nil`,
/// the image will keep its original size after processing.
/// Default is `nil`.
///
/// - returns: An initialized `RoundCornerImageProcessor`.
public init(cornerRadius: CGFloat, targetSize: CGSize? = nil) {
self.cornerRadius = cornerRadius
self.targetSize = targetSize
if let size = targetSize {
self.identifier = "com.onevcat.Kingfisher.RoundCornerImageProcessor(\(cornerRadius)_\(size))"
} else {
self.identifier = "com.onevcat.Kingfisher.RoundCornerImageProcessor(\(cornerRadius))"
}
}
public func process(item: ImageProcessItem, options: KingfisherOptionsInfo) -> Image? {
switch item {
case .image(let image):
let size = targetSize ?? image.kf_size
return image.kf_image(withRoundRadius: cornerRadius, fit: size, scale: options.scaleFactor)
case .data(_):
return (DefaultImageProcessor() >> self).process(item: item, options: options)
}
}
}
/// Processor for resizing images. Only CG-based images are supported in macOS.
public struct ResizingImageProcessor: ImageProcessor {
public let identifier: String
/// Target size of output image should be.
public let targetSize: CGSize
/// Initialize a `ResizingImageProcessor`
///
/// - parameter targetSize: Target size of output image should be.
///
/// - returns: An initialized `ResizingImageProcessor`.
public init(targetSize: CGSize) {
self.targetSize = targetSize
self.identifier = "com.onevcat.Kingfisher.ResizingImageProcessor(\(targetSize))"
}
public func process(item: ImageProcessItem, options: KingfisherOptionsInfo) -> Image? {
switch item {
case .image(let image):
return image.kf_resize(to: targetSize)
case .data(_):
return (DefaultImageProcessor() >> self).process(item: item, options: options)
}
}
}
/// Processor for adding blur effect to images. `Accelerate.framework` is used underhood for
/// a better performance. A simulated Gaussian blur with specified blur radius will be applied.
public struct BlurImageProcessor: ImageProcessor {
public let identifier: String
/// Blur radius for the simulated Gaussian blur.
public let blurRadius: CGFloat
/// Initialize a `BlurImageProcessor`
///
/// - parameter blurRadius: Blur radius for the simulated Gaussian blur.
///
/// - returns: An initialized `BlurImageProcessor`.
public init(blurRadius: CGFloat) {
self.blurRadius = blurRadius
self.identifier = "com.onevcat.Kingfisher.BlurImageProcessor(\(blurRadius))"
}
public func process(item: ImageProcessItem, options: KingfisherOptionsInfo) -> Image? {
switch item {
case .image(let image):
let radius = blurRadius * options.scaleFactor
return image.kf_blurred(withRadius: radius)
case .data(_):
return (DefaultImageProcessor() >> self).process(item: item, options: options)
}
}
}
/// Processor for adding an overlay to images. Only CG-based images are supported in macOS.
public struct OverlayImageProcessor: ImageProcessor {
public var identifier: String
/// Overlay color will be used to overlay the input image.
public let overlay: Color
/// Fraction will be used when overlay the color to image.
public let fraction: CGFloat
/// Initialize an `OverlayImageProcessor`
///
/// - parameter overlay: Overlay color will be used to overlay the input image.
/// - parameter fraction: Fraction will be used when overlay the color to image.
/// From 0.0 to 1.0. 0.0 means solid color, 1.0 means transparent overlay.
///
/// - returns: An initialized `OverlayImageProcessor`.
public init(overlay: Color, fraction: CGFloat = 0.5) {
self.overlay = overlay
self.fraction = fraction
self.identifier = "com.onevcat.Kingfisher.OverlayImageProcessor(\(overlay.hex)_\(fraction))"
}
public func process(item: ImageProcessItem, options: KingfisherOptionsInfo) -> Image? {
switch item {
case .image(let image):
return image.kf_overlaying(with: overlay, fraction: fraction)
case .data(_):
return (DefaultImageProcessor() >> self).process(item: item, options: options)
}
}
}
/// Processor for tint images with color. Only CG-based images are supported.
public struct TintImageProcessor: ImageProcessor {
public let identifier: String
/// Tint color will be used to tint the input image.
public let tint: Color
/// Initialize a `TintImageProcessor`
///
/// - parameter tint: Tint color will be used to tint the input image.
///
/// - returns: An initialized `TintImageProcessor`.
public init(tint: Color) {
self.tint = tint
self.identifier = "com.onevcat.Kingfisher.TintImageProcessor(\(tint.hex))"
}
public func process(item: ImageProcessItem, options: KingfisherOptionsInfo) -> Image? {
switch item {
case .image(let image):
return image.kf_tinted(with: tint)
case .data(_):
return (DefaultImageProcessor() >> self).process(item: item, options: options)
}
}
}
/// Processor for applying some color control to images. Only CG-based images are supported.
/// watchOS is not supported.
public struct ColorControlsProcessor: ImageProcessor {
public let identifier: String
/// Brightness changing to image.
public let brightness: CGFloat
/// Contrast changing to image.
public let contrast: CGFloat
/// Saturation changing to image.
public let saturation: CGFloat
/// InputEV changing to image.
public let inputEV: CGFloat
/// Initialize a `ColorControlsProcessor`
///
/// - parameter brightness: Brightness changing to image.
/// - parameter contrast: Contrast changing to image.
/// - parameter saturation: Saturation changing to image.
/// - parameter inputEV: InputEV changing to image.
///
/// - returns: An initialized `ColorControlsProcessor`
public init(brightness: CGFloat, contrast: CGFloat, saturation: CGFloat, inputEV: CGFloat) {
self.brightness = brightness
self.contrast = contrast
self.saturation = saturation
self.inputEV = inputEV
self.identifier = "com.onevcat.Kingfisher.ColorControlsProcessor(\(brightness)_\(contrast)_\(saturation)_\(inputEV))"
}
public func process(item: ImageProcessItem, options: KingfisherOptionsInfo) -> Image? {
switch item {
case .image(let image):
return image.kf_adjusted(brightness: brightness, contrast: contrast, saturation: saturation, inputEV: inputEV)
case .data(_):
return (DefaultImageProcessor() >> self).process(item: item, options: options)
}
}
}
/// Processor for applying black and white effect to images. Only CG-based images are supported.
/// watchOS is not supported.
public struct BlackWhiteProcessor: ImageProcessor {
public let identifier = "com.onevcat.Kingfisher.BlackWhiteProcessor"
/// Initialize a `BlackWhiteProcessor`
///
/// - returns: An initialized `BlackWhiteProcessor`
public init() {}
public func process(item: ImageProcessItem, options: KingfisherOptionsInfo) -> Image? {
return ColorControlsProcessor(brightness: 0.0, contrast: 1.0, saturation: 0.0, inputEV: 0.7)
.process(item: item, options: options)
}
}
/// Concatenate two `ImageProcessor`s. `ImageProcessor.appen(another:)` is used internally.
///
/// - parameter left: First processor.
/// - parameter right: Second processor.
///
/// - returns: The concatenated processor.
public func >>(left: ImageProcessor, right: ImageProcessor) -> ImageProcessor {
return left.append(another: right)
}
fileprivate extension Color {
var hex: String {
var r: CGFloat = 0
var g: CGFloat = 0
var b: CGFloat = 0
var a: CGFloat = 0
getRed(&r, green: &g, blue: &b, alpha: &a)
let rgba = Int(r * 255) << 24 | Int(g * 255) << 16 | Int(b * 255) << 8 | Int(a * 255)
return String(format:"#%08x", rgba)
}
}
| mit | a2f82f6605a14a88cde1b7021ce239b9 | 38.219178 | 128 | 0.663709 | 4.816622 | false | false | false | false |
luosheng/OpenSim | OpenSim/SimulatorResetMenuItem.swift | 1 | 1222 | //
// SimulatorResetMenuItem.swift
// OpenSim
//
// Created by Craig Peebles on 14/10/19.
// Copyright © 2019 Luo Sheng. All rights reserved.
//
import Cocoa
class SimulatorResetMenuItem: NSMenuItem {
var device: Device!
init(device:Device) {
self.device = device
let title = "\(UIConstants.strings.menuResetSimulatorButton) \(device.name)"
super.init(title: title, action: #selector(self.resetSimulator(_:)), keyEquivalent: "")
target = self
}
required init(coder decoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
@objc func resetSimulator(_ sender: AnyObject) {
let alert: NSAlert = NSAlert()
alert.messageText = String(format: UIConstants.strings.actionFactoryResetAlertMessage, device.name)
alert.alertStyle = .critical
alert.addButton(withTitle: UIConstants.strings.actionFactoryResetAlertConfirmButton)
alert.addButton(withTitle: UIConstants.strings.actionFactoryResetAlertCancelButton)
let response = alert.runModal()
if response == NSApplication.ModalResponse.alertFirstButtonReturn {
SimulatorController.factoryReset(device)
}
}
}
| mit | 464cec6e184f754308a01af1044a1c4a | 29.525 | 107 | 0.68878 | 4.573034 | false | false | false | false |
mathiasquintero/Sweeft | Sources/Sweeft/Extensions/Dictionary.swift | 3 | 1903 | //
// Dictionary.swift
// Pods
//
// Created by Mathias Quintero on 12/5/16.
//
//
import Foundation
public extension Dictionary {
/// Map Only Values
func mapValues<T>(_ map: @escaping (Value) -> T) -> [Key:T] {
return self >>= mapLast(with: map)
}
/**
Will find a match for in the dictionary by key
- Parameter handler: function that will determine by the key if it's the desired item
- Returns: value found
*/
func match(_ handler: @escaping (Key) -> Bool) -> Value? {
return self ==> nil ** { result, item in
if handler(item.key) {
return item.value
} else {
return result
}
}
}
}
public extension Dictionary where Key: CustomStringConvertible {
/**
Will find a match for in the dictionary by key, checking if
the description of the key contains the query
- Parameter handler: query we're looking for in the key
- Returns: value found
*/
func match(containing query: String) -> Value? {
return match(describe >>> String.contains ** query)
}
}
public extension Dictionary where Value: Hashable {
/// Returns a flipped mapping of the Dictionary.
var flipped: [Value:Key] {
return self >>= flipArguments
}
}
extension Dictionary: Defaultable {
/// Default Value
public static var defaultValue: [Key:Value] {
return .empty
}
}
/// TODO: Find a way to inherit from this particular dict
extension Dictionary where Key: CustomStringConvertible, Value: Serializable {
/// JSON Value
public var json: JSON {
return .dict(self >>= describe <*> JSON.init)
}
}
public extension ExpressibleByDictionaryLiteral {
static var empty: Self {
return Self()
}
}
| mit | f0013e485128a14103f0e059df322917 | 20.873563 | 90 | 0.585917 | 4.552632 | false | false | false | false |
uber/signals-ios | UberSignalsTests/SwiftTests.swift | 1 | 4122 | //
// SwiftTests.swift
// UberSignals
//
// Copyright (c) 2015 Uber Technologies, Inc.
//
// 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 XCTest
class SwiftTests: XCTestCase {
func testEmptyObservation() {
var observed = 0
let observer = UBSignalEmitter()
observer.onEmptySignalSwift.addObserver(self) { (listener) in
observed += 1
}
observer.onEmptySignalSwift.fire()()
XCTAssertEqual(observed, 1, "Should have fired callback")
}
func testPredefinedSignals() {
var observed = 0
let signal = UBDictionarySignal()
signal.addObserver(self) { (listener) in
observed += 1
}
signal.fire()(Dictionary())
let signal2 = UBArraySignal()
signal2.addObserver(self) { (listener, result) in
XCTAssertEqual(result as NSArray, NSArray(objects: "result"), "Should have signaled correct result")
observed += 1
}
signal2.fire()(["result"])
let signal3 = UBFloatSignal()
signal3.addObserver(self) { (listener, result) in
XCTAssertEqual(result, 20.0, "Should have signaled correct result")
observed += 1
}
signal3.fire()(20.0)
let signal4 = UBDoubleSignal()
signal4.addObserver(self) { (listener, result) in
XCTAssertEqual(result, 20.0, "Should have signaled correct result")
observed += 1
}
signal4.fire()(20.0)
let signal5 = UBBooleanSignal()
signal5.addObserver(self) { (listener, result) in
XCTAssertEqual(result, true, "Should have signaled correct result")
observed += 1
}
signal5.fire()(true)
let signal6 = UBIntegerSignal()
signal6.addObserver(self) { (listener, result) in
XCTAssertEqual(result, 10, "Should have signaled correct result")
observed += 1
}
signal6.fire()(10)
let signal7 = UBMutableDictionarySignal()
signal7.addObserver(self) { (listener, result) in
XCTAssertEqual(result, NSMutableDictionary(), "Should have signaled correct result")
observed += 1
}
signal7.fire()(NSMutableDictionary())
XCTAssertEqual(observed, 7, "Should have fired callback")
}
func testObservation() {
var observed = 0
let observer = UBSignalEmitter()
observer.onSwiftSignal.addObserver(self) { (listener, string) in
XCTAssertEqual(string, "1", "Should have received correct value")
observed += 1
}
observer.onSwiftDoubleSignal.addObserver(self) { (listener, string, number) in
observed += 1
XCTAssertEqual(string, "1", "Should have received correct value")
XCTAssertEqual(number, 2, "Should have received correct value")
}
observer.onSwiftSignal.fire()("1")
observer.onSwiftDoubleSignal.fire()("1", 2)
XCTAssertEqual(observed, 2, "Should have fired callback")
}
}
| mit | 7d96c50cc4d42cf0c9217cebda36d7cf | 34.843478 | 112 | 0.641679 | 4.554696 | false | true | false | false |
MaTriXy/androidtool-mac | AndroidTool/DropReceiverView.swift | 1 | 2572 | //
// DropReceiverView.swift
// Shellpad
//
// Created by Morten Just Petersen on 10/30/15.
// Copyright © 2015 Morten Just Petersen. All rights reserved.
//
import Cocoa
protocol DropDelegate {
func dropDragEntered(filePath:String)
func dropDragPerformed(filePath:String)
func dropDragExited()
func dropUpdated(mouseAt:NSPoint)
}
class DropReceiverView: NSView {
var delegate:DropDelegate?
var testVar = "only you can see this";
func removeBackgroundColor(){
layer?.backgroundColor = NSColor.clearColor().CGColor
}
func addBackgroundColor(){
layer?.backgroundColor = NSColor(red:0.267, green:0.251, blue:0.290, alpha:1).CGColor
}
func setup(){
wantsLayer = true
let fileTypes = [
"public.data"
]
registerForDraggedTypes(fileTypes);
}
//https://developer.apple.com/library/mac/documentation/Miscellaneous/Reference/UTIRef/Articles/System-DeclaredUniformTypeIdentifiers.html
override func draggingEntered(sender: NSDraggingInfo) -> NSDragOperation {
// Swift.print("HELLO \(getPathFromBoard(sender.draggingPasteboard()))")
let path = getPathFromBoard(sender.draggingPasteboard())
delegate?.dropDragEntered(path)
addBackgroundColor()
return NSDragOperation.Copy
}
override func performDragOperation(sender: NSDraggingInfo) -> Bool {
return true
}
override func draggingUpdated(sender: NSDraggingInfo) -> NSDragOperation {
delegate?.dropUpdated(sender.draggingLocation())
return NSDragOperation.Copy
}
override func draggingExited(sender: NSDraggingInfo?) {
removeBackgroundColor()
delegate?.dropDragExited()
}
override func concludeDragOperation(sender: NSDraggingInfo?) {
let path = getPathFromBoard((sender?.draggingPasteboard())!)
Swift.print("path is \(path)")
removeBackgroundColor()
delegate?.dropDragPerformed(path)
}
func getPathFromBoard(board:NSPasteboard) -> String {
let url = NSURL(fromPasteboard: board)
let path = url?.path!
return path!;
}
override init(frame frameRect: NSRect) {
super.init(frame: frameRect)
setup()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
setup()
}
override func drawRect(dirtyRect: NSRect) {
super.drawRect(dirtyRect)
// Drawing code here.
}
}
| apache-2.0 | 195a700f6601870252078d3a227bc58e | 27.252747 | 142 | 0.642552 | 4.769944 | false | false | false | false |
PGSSoft/AutoMate | AutoMate/SystemAlert.swift | 1 | 5362 | //
// SystemAlert.swift
// AutoMate
//
// Created by Ewelina Cyło on 20/01/2017.
// Copyright © 2017 PGS Software. All rights reserved.
//
import Foundation
import XCTest
#if os(iOS)
// MARK: - System Messages helper protocol
/// Helper protocol used to reads localized messages from JSON files.
public protocol SystemMessages {
/// Returns all localized texts from a JSON file.
///
/// - Parameter json: JSON file name, without the `json` extension.
/// - Returns: All localized tests read from the JSON.
static func readMessages(from jsonFile: String) -> [String]
}
extension SystemMessages {
/// Returns all localized texts from a JSON file.
///
/// - Parameter json: JSON file name, without the `json` extension.
/// - Returns: All localized tests read from the JSON.
public static func readMessages(from jsonFile: String = String(describing: Self.self)) -> [String] {
guard let url = Bundle.autoMate.url(forResource: jsonFile, withExtension: "json"),
let data = try? Data(contentsOf: url),
let json = try? JSONDecoder().decode(Dictionary<String, [String]>.self, from: data) else {
return []
}
return json.flatMap({ $0.value }).unique()
}
}
// MARK: - System alert protocols
/// Protocol defining system alert allow element.
public protocol SystemAlertAllow: SystemMessages {
/// Allow messages.
static var allow: [String] { get }
/// Allow element.
var allowElement: XCUIElement { get }
}
/// Protocol defining system alert deny element.
public protocol SystemAlertDeny: SystemMessages {
/// Deny messages.
static var deny: [String] { get }
/// Deny element.
var denyElement: XCUIElement { get }
}
/// Protocol defining system alert ok element.
public protocol SystemAlertOk: SystemMessages {
/// OK messages.
static var ok: [String] { get }
/// OK element.
var okElement: XCUIElement { get }
}
/// Protocol defining system alert cancel element.
public protocol SystemAlertCancel: SystemMessages {
/// Cancel messages.
static var cancel: [String] { get }
/// Cancel element.
var cancelElement: XCUIElement { get }
}
/// Protocol defining system service request alert.
/// Provides essential definitions for system alerts giving the ability to handle them in the UI tests.
///
/// System alerts supposed to be used in the handler of the `XCTestCase.addUIInterruptionMonitor(withDescription:handler:)` method.
/// Additional protocols, `SystemAlertAllow`, `SystemAlertDeny`, `SystemAlertOk` and `SystemAlertCancel` provides
/// definition and default implementation for handling buttons on the alert view.
///
/// - note:
/// `AutoMate` provides an implementation for several different system alerts.
/// Check the documentation for full list of supported system alerts.
///
/// **Example:**
///
/// ```swift
/// let token = addUIInterruptionMonitor(withDescription: "Contacts") { (alert) -> Bool in
/// guard let alert = AddressBookAlert(element: alert) else {
/// XCTFail("Cannot create AddressBookAlert object")
/// return false
/// }
///
/// alert.denyElement.tap()
/// return true
/// }
///
/// mainPage.goToPermissionsPageMenu()
/// // Interruption won't happen without some kind of action.
/// app.tap()
/// removeUIInterruptionMonitor(token)
/// ```
///
/// - note:
/// Handlers should return `true` if they handled the UI, `false` if they did not.
public protocol SystemAlert: SystemMessages {
/// Collection of messages possible to receive due to system service request.
static var messages: [String] { get }
/// Alert element.
var alert: XCUIElement { get set }
// MARK: Initializers
/// Initialize system alert with interrupting element.
///
/// - note:
/// Method returns `nil` if the `element` doesn't represent specified system alert.
///
/// - Parameter element: Interrupting element containing system alert.
init?(element: XCUIElement)
}
// MARK: - Default implementation
extension SystemAlertAllow where Self: SystemAlert {
/// Allow element.
public var allowElement: XCUIElement {
guard let button = alert.buttons.elements(withLabelsMatching: type(of: self).allow).first else {
preconditionFailure("Cannot find allow button.")
}
return button
}
}
extension SystemAlertDeny where Self: SystemAlert {
/// Deny element.
public var denyElement: XCUIElement {
guard let button = alert.buttons.elements(withLabelsMatching: type(of: self).deny).first else {
preconditionFailure("Cannot find deny button.")
}
return button
}
}
extension SystemAlertOk where Self: SystemAlert {
/// OK element.
public var okElement: XCUIElement {
guard let button = alert.buttons.elements(withLabelsMatching: type(of: self).ok).first else {
preconditionFailure("Cannot find ok button.")
}
return button
}
}
extension SystemAlertCancel where Self: SystemAlert {
/// Cancel element.
public var cancelElement: XCUIElement {
guard let button = alert.buttons.elements(withLabelsMatching: type(of: self).cancel).first else {
preconditionFailure("Cannot find cancel button.")
}
return button
}
}
#endif
| mit | ea762449ccb315f7128ec608ad0961aa | 31.682927 | 131 | 0.675 | 4.422442 | false | false | false | false |
hellogaojun/Swift-coding | swift学习教材案例/Swifter.playground/Pages/any-anyobject.xcplaygroundpage/Contents.swift | 1 | 314 |
import UIKit
let swiftInt: Int = 1
let swiftString: String = "miao"
var array: [AnyObject] = []
array.append(swiftInt)
array.append(swiftString)
// Without UIKit:
//let swiftInt: Int = 1
//let swiftString: String = "miao"
//
//var array: [Any] = []
//array.append(swiftInt)
//array.append(swiftString)
//array | apache-2.0 | 2e1eb4fe5dea401589d4d5e88c0bdd87 | 15.578947 | 34 | 0.687898 | 2.962264 | false | false | false | false |
yazhenggit/wbtest | 微博项目练习/微博项目练习/Classes/Module/Home/PhotoBrowser/PhotoBrowserCell.swift | 1 | 4615 | //
// PhotoBrowserCell.swift
// 微博项目练习
//
// Created by 王亚征 on 15/10/22.
// Copyright © 2015年 yazheng. All rights reserved.
//
import UIKit
import SDWebImage
class PhotoBrowserCell: UICollectionViewCell {
// 设置图像
var imageURL:NSURL? {
didSet{
self.indicator.startAnimating()
// 清空图像,解决图像缓存的问题
imageView.image = nil
resetScrollView()
// 模拟延时
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(0)), dispatch_get_main_queue(), {
self.imageView.sd_setImageWithURL(self.imageURL) { (image, Error , _ , _ ) -> Void in
self.indicator.stopAnimating()
if image == nil {
print("图像加载失败")
return
}
self.setupImagePosition()
}
})
}
}
private func displaySize(image:UIImage) -> CGSize{
let scale = image.size.height / image.size.width
let h = scale * scrolleView.bounds.width
return CGSize(width: scrolleView.bounds.width, height: h )
}
private func setupImagePosition() {
let size = displaySize(imageView.image!)
if size.height > bounds.height {
imageView.frame = CGRect(origin: CGPointZero, size: size )
scrolleView.contentSize = size
}else {
let y = (bounds.height - size .height)*0.5
imageView.frame = CGRect(origin: CGPointZero, size: size )
scrolleView.contentInset = UIEdgeInsetsMake(y, 0, y, 0)
}
}
override init(frame: CGRect) {
super.init(frame: frame)
setupUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func resetScrollView() {
scrolleView.contentInset = UIEdgeInsetsZero
scrolleView.contentOffset = CGPointZero
scrolleView.contentSize = CGSizeZero
}
private func setupUI() {
contentView.addSubview(scrolleView)
scrolleView.addSubview(imageView)
contentView.addSubview(indicator)
scrolleView.translatesAutoresizingMaskIntoConstraints = false
let dict = ["sv":scrolleView]
contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[sv]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: dict))
contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[sv]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: dict))
indicator.translatesAutoresizingMaskIntoConstraints = false
contentView.addConstraint(NSLayoutConstraint(item: indicator, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: contentView, attribute: NSLayoutAttribute.CenterX, multiplier: 1.0, constant: 0))
contentView.addConstraint(NSLayoutConstraint(item: indicator, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: contentView, attribute: NSLayoutAttribute.CenterY, multiplier: 1.0, constant: 0))
perpareScrollView()
}
private func perpareScrollView() {
scrolleView.delegate = self
scrolleView.minimumZoomScale = 0.5
scrolleView.maximumZoomScale = 2.0
}
private lazy var scrolleView = UIScrollView()
lazy var imageView = UIImageView()
private lazy var indicator = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.WhiteLarge)
}
extension PhotoBrowserCell:UIScrollViewDelegate {
func viewForZoomingInScrollView(scrollView: UIScrollView) -> UIView? {
return imageView
}
// 缩放结束后图片位置调整
func scrollViewDidEndZooming(scrollView: UIScrollView, withView view: UIView?, atScale scale: CGFloat) {
var offSetX = (scrollView.bounds.width - (view?.frame.width)!) - 0.5
offSetX = offSetX < 0 ? 0 : offSetX
var offSetY = (scrollView.bounds.height - (view?.frame.height)!) - 0.5
offSetY = offSetY < 0 ? 0 : offSetY
scrollView.contentInset = UIEdgeInsets(top: offSetY, left: offSetX, bottom: offSetY, right: offSetX)
}
// 只要缩放就会调用
/**
transform
a,d 缩放比例
tx, ty 位移
a,b,c,d 共同决定旋转
*/
func scrollViewDidZoom(scrollView: UIScrollView) {
}
}
| mit | ed7c8b78a113c07ace12b1c720b5e2e0 | 33.96875 | 232 | 0.633155 | 4.812903 | false | false | false | false |
akrio714/Wbm | Wbm/Campaign/List/ViewModel/CampaignListViewModel.swift | 1 | 3427 | //
// CampaignListViewModel.swift
// Wbm
//
// Created by akrio on 2017/7/14.
// Copyright © 2017年 akrio. All rights reserved.
//
import Foundation
import RxSwift
import RxCocoa
import RxDataSources
struct CampaignListViewModel {
fileprivate let campaignService = CampaignService.sharedInstance
fileprivate let disposeBag = DisposeBag()
let data = Variable<[NoSection<CampaignListItemViewModel>]>([NoSection<CampaignListItemViewModel>()])
var dataSource = RxTableViewSectionedAnimatedDataSource<NoSection<CampaignListItemViewModel>>()
init() {
dataSource.configureCell = cellConfig
reload()
}
func reload() {
campaignService
.getList()
.asDriver(onErrorJustReturn: [])
.do(onNext: { self.data.value[0].items = $0.map{ CampaignListItemViewModel($0) } })
.drive()
.addDisposableTo(disposeBag)
}
func loadMore() {
campaignService
.getList()
.asDriver(onErrorJustReturn: [])
.do(onNext: { self.data.value[0].items += $0.map{ CampaignListItemViewModel($0) } })
.drive()
.addDisposableTo(disposeBag)
}
func cellConfig (ds:TableViewSectionedDataSource<NoSection<CampaignListItemViewModel>>, tv:UITableView, ip:IndexPath, item:CampaignListItemViewModel) -> UITableViewCell {
let cell = tv.dequeueReusableCell(withIdentifier: "cell") as! CampaignListItem
cell.publisherImage.kf.setImage(url: item.imageUrl)
cell.publisherNameLabel.text = item.publisherName
cell.priceLabel.text = item.price
cell.publisherNumLabel.text = item.publisherNum
cell.durationsLabel.text = item.durations
cell.createTimeLabel.text = item.createTime
cell.deleteButtonOpenCallback = { self.data.value[ip.section].items[ip.row].deleteButtonOpen = $0}
cell.open.value = (self.data.value[ip.section].items[ip.row].deleteButtonOpen,false)
return cell
}
}
/// cell中所需用户实体
struct CampaignListItemViewModel {
/// 标示
let id:String
/// 图片地址
let imageUrl:String
/// 第一个publisher名字
let publisherName:String
/// 价格
let price:String
/// publisher数量
let publisherNum:String
/// 持续时间
let durations:String
/// 创建时间
let createTime:String
/// 删除按钮是否打开
var deleteButtonOpen = false
init(_ model:CampaignListItemModel) {
self.id = model.id
self.imageUrl = model.imageUrl
self.publisherName = "@\(model.publishers.first ?? "")"
self.price = "$\(model.price)"
self.publisherNum = model.publishers.count.description
self.durations = model.durations.timeDescription()
self.createTime = model.createTime.string(format: .custom("MMM dd, HH:mm"))
}
}
extension CampaignListItemViewModel:IdentifiableType,Equatable {
static func ==(lhs: CampaignListItemViewModel, rhs: CampaignListItemViewModel) -> Bool {
return lhs.id == rhs.id
}
var identity: String { return self.id }
}
extension Int {
func timeDescription() -> String {
var result = ""
let hours = self/60
let mins = self%60
if hours > 0 {
result += "\(hours)hrs "
}
if mins > 0 {
result += "\(mins)mins"
}
return ""
}
}
| apache-2.0 | 66981e85406042fb11a64b980771a439 | 32.48 | 174 | 0.645161 | 4.365059 | false | false | false | false |
kvvzr/Twinkrun | Twinkrun/Controllers/HistoryViewController.swift | 2 | 7462 | //
// HistoryViewController.swift
// Twinkrun
//
// Created by Kawazure on 2014/10/23.
// Copyright (c) 2014年 Twinkrun. All rights reserved.
//
import UIKit
import CoreBluetooth
class HistoryViewController: UITableViewController {
var resultData: [TWRResult]?
var toolbar: UIToolbar?
var selectedRows: [Int] = []
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
let documentsPath = NSURL(string: NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as String)!
let path = documentsPath.URLByAppendingPathComponent("TWRResultData2").path!
resultData = NSKeyedUnarchiver.unarchiveObjectWithFile(path) as? [TWRResult]
dispatch_async(dispatch_get_main_queue(), {
self.tableView.reloadData()
})
}
override func viewDidLoad() {
super.viewDidLoad()
let font = UIFont(name: "HelveticaNeue-Light", size: 22)
if let font = font {
navigationController!.navigationBar.barTintColor = UIColor.twinkrunGreen()
navigationController!.navigationBar.titleTextAttributes = [
NSForegroundColorAttributeName: UIColor.whiteColor(),
NSFontAttributeName: font
]
navigationController!.navigationBar.tintColor = UIColor.whiteColor()
}
navigationItem.rightBarButtonItem = editButtonItem()
tableView.delegate = self
tableView.dataSource = self
tableView.backgroundView = UIView()
tableView.backgroundView!.backgroundColor = UIColor.twinkrunBlack()
tableView.allowsSelection = false
tableView.allowsMultipleSelection = false
tableView.allowsSelectionDuringEditing = true
tableView.allowsMultipleSelectionDuringEditing = true
toolbar = UIToolbar(frame: tabBarController!.tabBar.frame)
toolbar!.backgroundColor = UIColor.twinkrunBlack()
toolbar!.items = [
UIBarButtonItem(barButtonSystemItem: .Action, target: self, action: Selector("onAction:")),
UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: nil, action: nil),
UIBarButtonItem(barButtonSystemItem: .Trash, target: self, action: Selector("onDelete:"))
]
toolbar!.hidden = true
tabBarController!.tabBar.superview!.addSubview(toolbar!)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if let resultData = resultData {
return resultData.count
}
return 0
}
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 240
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("resultCell")! as UITableViewCell
cell.backgroundColor = UIColor.clearColor()
cell.selectedBackgroundView = UIView()
cell.selectedBackgroundView!.backgroundColor = UIColor.clearColor()
let view = cell.viewWithTag(1)! as! ResultView
view.result = self.resultData![indexPath.row]
dispatch_async(dispatch_get_main_queue(), {
view.reload(animated: false)
})
return cell
}
override func tableView(tableView: UITableView, didDeselectRowAtIndexPath indexPath: NSIndexPath) {
selectedRows.removeObject(indexPath.row)
if let toolbar = toolbar {
(toolbar.items!.first! as UIBarButtonItem).enabled = (selectedRows.count == 1)
}
if selectedRows.count == 0 {
tabBarController!.tabBar.hidden = false
if let toolbar = toolbar {
toolbar.hidden = true
}
}
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
selectedRows.append(indexPath.row)
if selectedRows.count > 0 {
tabBarController!.tabBar.hidden = true
if let toolbar = toolbar {
toolbar.hidden = false
(toolbar.items!.first! as UIBarButtonItem).enabled = (selectedRows.count == 1)
}
}
}
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
return true
}
override func setEditing(editing: Bool, animated: Bool) {
super.setEditing(editing, animated: animated)
if !editing {
tabBarController!.tabBar.hidden = false
if let toolbar = toolbar {
toolbar.hidden = true
}
}
selectedRows = []
}
func onDelete(sender: UIBarButtonItem) {
var indexPaths: [NSIndexPath] = []
selectedRows.sortInPlace {$0 > $1}
for row in selectedRows {
indexPaths.append(NSIndexPath(forRow: row, inSection: 0))
resultData!.removeAtIndex(row)
}
tableView.deleteRowsAtIndexPaths(indexPaths, withRowAnimation: UITableViewRowAnimation.None)
let documentsPath = NSURL(string: NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0])!
let path = documentsPath.URLByAppendingPathComponent("TWRResultData2").path!
NSKeyedArchiver.archiveRootObject(resultData!, toFile: path)
self.setEditing(false, animated: true)
}
func onAction(sender: UIBarButtonItem) {
for row in selectedRows {
let result = resultData![row]
let view = UIView(frame: CGRectMake(0, 0, 320, 224))
view.backgroundColor = UIColor.twinkrunBlack()
let resultView = UINib(nibName: "ShareBoard", bundle: nil).instantiateWithOwner(self, options: nil)[0] as! ResultView
resultView.frame = CGRectMake(0, 0, 320, 244)
resultView.result = result
resultView.reload(animated: false)
resultView.back(nil)
view.addSubview(resultView)
let image = viewToImage(view)
let contents = ["I got \(result.score) points in this game! #twinkrun", image]
let controller = UIActivityViewController(activityItems: contents, applicationActivities: nil)
controller.excludedActivityTypes = [UIActivityTypeAddToReadingList, UIActivityTypeAirDrop, UIActivityTypePostToFlickr, UIActivityTypeSaveToCameraRoll, UIActivityTypePrint]
presentViewController(controller, animated: true, completion: {})
}
self.setEditing(false, animated: true)
}
func viewToImage(view: UIView) -> UIImage {
UIGraphicsBeginImageContextWithOptions(view.bounds.size, false, UIScreen.mainScreen().scale)
let context = UIGraphicsGetCurrentContext()
view.layer.renderInContext(context!)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
} | mit | 461a75346880f80021f1eabbf08f5283 | 37.859375 | 183 | 0.642493 | 5.716475 | false | false | false | false |
philipgreat/b2b-swift-app | B2BSimpleApp/B2BSimpleApp/ShippingGroupRemoteManagerImpl.swift | 1 | 2376 | //Domain B2B/ShippingGroup/
import SwiftyJSON
import Alamofire
import ObjectMapper
class ShippingGroupRemoteManagerImpl:RemoteManagerImpl,CustomStringConvertible{
override init(){
//lazy load for all the properties
//This is good for UI applications as it might saves RAM which is very expensive in mobile devices
}
override var remoteURLPrefix:String{
//Every manager need to config their own URL
return "https://philipgreat.github.io/naf/shippingGroupManager/"
}
func loadShippingGroupDetail(shippingGroupId:String,
shippingGroupSuccessAction: (ShippingGroup)->String,
shippingGroupErrorAction: (String)->String){
let methodName = "loadShippingGroupDetail"
let parameters = [shippingGroupId]
let url = compositeCallURL(methodName, parameters: parameters)
Alamofire.request(.GET, url).validate().responseJSON { response in
switch response.result {
case .Success:
if let value = response.result.value {
let json = JSON(value)
if let shippingGroup = self.extractShippingGroupFromJSON(json){
shippingGroupSuccessAction(shippingGroup)
}
}
case .Failure(let error):
print(error)
shippingGroupErrorAction("\(error)")
}
}
}
func extractShippingGroupFromJSON(json:JSON) -> ShippingGroup?{
let jsonTool = SwiftyJSONTool()
let shippingGroup = jsonTool.extractShippingGroup(json)
return shippingGroup
}
//Confirming to the protocol CustomStringConvertible of Foundation
var description: String{
//Need to find out a way to improve this method performance as this method might called to
//debug or log, using + is faster than \(var).
let result = "ShippingGroupRemoteManagerImpl, V1"
return result
}
static var CLASS_VERSION = 1
//This value is for serializer like message pack to identify the versions match between
//local and remote object.
}
//Reference http://grokswift.com/simple-rest-with-swift/
//Reference https://github.com/SwiftyJSON/SwiftyJSON
//Reference https://github.com/Alamofire/Alamofire
//Reference https://github.com/Hearst-DD/ObjectMapper
//let remote = RemoteManagerImpl()
//let result = remote.compositeCallURL(methodName: "getDetail",parameters:["O0000001"])
//print(result)
| mit | cd4ba40420a60cfd39ec5f4f98cff80d | 26.97561 | 100 | 0.705387 | 3.946844 | false | false | false | false |
alessiobrozzi/firefox-ios | Client/Frontend/Reader/ReaderModeUtils.swift | 10 | 2941 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
struct ReaderModeUtils {
static let DomainPrefixesToSimplify = ["www.", "mobile.", "m.", "blog."]
static func simplifyDomain(_ domain: String) -> String {
for prefix in DomainPrefixesToSimplify {
if domain.hasPrefix(prefix) {
return domain.substring(from: domain.characters.index(domain.startIndex, offsetBy: prefix.characters.count))
}
}
return domain
}
static func generateReaderContent(_ readabilityResult: ReadabilityResult, initialStyle: ReaderModeStyle) -> String? {
if let stylePath = Bundle.main.path(forResource: "Reader", ofType: "css") {
do {
let css = try NSString(contentsOfFile: stylePath, encoding: String.Encoding.utf8.rawValue)
if let tmplPath = Bundle.main.path(forResource: "Reader", ofType: "html") {
do {
let tmpl = try NSMutableString(contentsOfFile: tmplPath, encoding: String.Encoding.utf8.rawValue)
tmpl.replaceOccurrences(of: "%READER-CSS%", with: css as String,
options: NSString.CompareOptions(), range: NSRange(location: 0, length: tmpl.length))
tmpl.replaceOccurrences(of: "%READER-STYLE%", with: initialStyle.encode(),
options: NSString.CompareOptions(), range: NSRange(location: 0, length: tmpl.length))
tmpl.replaceOccurrences(of: "%READER-DOMAIN%", with: simplifyDomain(readabilityResult.domain),
options: NSString.CompareOptions(), range: NSRange(location: 0, length: tmpl.length))
tmpl.replaceOccurrences(of: "%READER-URL%", with: readabilityResult.url,
options: NSString.CompareOptions(), range: NSRange(location: 0, length: tmpl.length))
tmpl.replaceOccurrences(of: "%READER-TITLE%", with: readabilityResult.title,
options: NSString.CompareOptions(), range: NSRange(location: 0, length: tmpl.length))
tmpl.replaceOccurrences(of: "%READER-CREDITS%", with: readabilityResult.credits,
options: NSString.CompareOptions(), range: NSRange(location: 0, length: tmpl.length))
tmpl.replaceOccurrences(of: "%READER-CONTENT%", with: readabilityResult.content,
options: NSString.CompareOptions(), range: NSRange(location: 0, length: tmpl.length))
return tmpl as String
} catch _ {
}
}
} catch _ {
}
}
return nil
}
}
| mpl-2.0 | 6adbeacafc95c7ef1ee7a2a4ac1dbe8b | 50.596491 | 124 | 0.586875 | 5.177817 | false | false | false | false |
kay-kim/stitch-examples | todo/ios/Pods/StitchCore/StitchCore/StitchCore/Source/Auth/AuthInfo.swift | 1 | 1850 | import Foundation
/// Auth represents the current authorization state of the client
internal struct AuthInfo: Codable {
enum CodingKeys: String, CodingKey {
case accessToken = "access_token",
userId = "user_id",
deviceId = "device_id",
refreshToken = "refresh_token"
}
// The current access token for this session in decoded JWT form.
// Will be nil if the token was malformed and could not be decoded.
let accessToken: DecodedJWT?
// The user this session was created for.
let deviceId: String
// The user this session was created for.
let userId: String
// The refresh token to refresh an expired access token
internal var refreshToken: String
internal func auth(with updatedAccessToken: String) -> AuthInfo {
return AuthInfo(accessToken: try? DecodedJWT(jwt: updatedAccessToken),
deviceId: deviceId,
userId: userId,
refreshToken: refreshToken)
}
/**
Determines if the access token stored in this Auth object is expired or expiring within
a provided number of seconds.
- parameter withinSeconds: expiration threshold in seconds. 10 by default to account for latency and clock drift
between client and Stitch server
- returns: true if the access token is expired or is going to expire within 'withinSeconds' seconds
false if the access token exists and is not expired nor expiring within 'withinSeconds' seconds
nil if the access token doesn't exist, is malformed, or does not have an 'exp' field.
*/
public func isAccessTokenExpired(withinSeconds: Double = 10.0) -> Bool? {
if let exp = self.accessToken?.expiration {
return Date() >= (exp - TimeInterval(withinSeconds))
}
return nil
}
}
| apache-2.0 | 1fcbec07c4b19b64da41aed78ecd2cae | 37.541667 | 117 | 0.668649 | 4.973118 | false | false | false | false |
anilkumarbp/ringcentral-swift-NEW | ringcentral-swift-develop-anilkumarbp/demo/demo/ViewControllerLog.swift | 1 | 5595 | import Foundation
import UIKit
class ViewControllerLog: UIViewController, UITableViewDataSource, UITableViewDelegate {
@IBOutlet var filter: UITextField!
@IBOutlet var callHistory: UITableView!
var platform: Platform!
@IBOutlet var messageHistory: UITableView!
// @IBOutlet var label: UILabel!
var textArray: NSMutableArray = NSMutableArray()
var messageArray: NSMutableArray = NSMutableArray()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
platform.apiCall([
"method": "GET",
"url": "/restapi/v1.0/account/~/call-log"
]) {
(data, response, error) in
for call in (NSJSONSerialization.JSONObjectWithData(data!, options: nil, error: nil) as! NSDictionary)["records"] as! NSArray {
var part0: String = (call["startTime"] as! String) + "\n"
var part1: String = (call["direction"] as! String) + " (Id: " + (call["id"] as! String) + ")\n"
var part2: String = ((call["from"] as! NSDictionary)["phoneNumber"] as! String) + " --> " + ((call["to"] as! NSDictionary)["phoneNumber"] as! String)
self.textArray.addObject(part0 + part1 + part2)
}
}
platform.apiCall([
"method": "GET",
"url": "/restapi/v1.0/account/~/extension/~/message-store",
"headers": ["Accept": "application/json"],
]) {
(data, response, error) in
// println((NSJSONSerialization.JSONObjectWithData(data!, options: nil, error: nil) as! NSDictionary) ["records"]! as! NSArray)
for message in (NSJSONSerialization.JSONObjectWithData(data!, options: nil, error: nil) as! NSDictionary) ["records"]! as! NSArray {
let direction = message["direction"] as! String
var part0: String = direction
let number: String
if direction == "Outbound" {
number = (message["to"] as! NSArray)[0]["phoneNumber"] as! String
} else {
number = (message["from"] as! NSDictionary) ["phoneNumber"] as! String
}
// var part1: String = (message["subject"] as! String)
var part1: String
if let person = message["subject"] as? String {
part1 = person
} else {
part1 = "UNKNOWN"
}
self.messageArray.addObject(part0 + ": " + number + "\n" + part1)
}
}
self.callHistory.rowHeight = UITableViewAutomaticDimension
self.callHistory.estimatedRowHeight = 44.0
self.messageHistory.reloadData()
self.callHistory.reloadData()
}
@IBAction func press(sender: AnyObject) {
self.textArray.addObject("Hi")
filter(filter.text)
self.callHistory.reloadData()
self.messageHistory.reloadData()
self.callHistory.reloadData()
}
func filter(filter: String) {
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if tableView == callHistory {
return self.textArray.count
}
return self.messageArray.count
}
override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
self.view.endEditing(true)
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
// var cell: UITableViewCell = self.callHistory.dequeueReusableCellWithIdentifier("cell") as! UITableViewCell
if tableView == self.callHistory {
let cellIdentifier = "Cell"
var cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier) as? UITableViewCell
if cell == nil {
cell = UITableViewCell(style: UITableViewCellStyle.Value1, reuseIdentifier: cellIdentifier)
}
// cell.textLabel!.text = "hi"
cell!.textLabel?.text = self.textArray.objectAtIndex(indexPath.row) as? String
cell!.textLabel?.adjustsFontSizeToFitWidth = true
// Setting number of lines to 0 allows for self adaptive lines
cell!.textLabel?.numberOfLines = 0
return cell!
} else {
let cellIdentifier = "Message"
var cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier) as? UITableViewCell
if cell == nil {
cell = UITableViewCell(style: UITableViewCellStyle.Value1, reuseIdentifier: cellIdentifier)
}
// cell.textLabel!.text = "hi"
cell!.textLabel?.text = self.messageArray.objectAtIndex(indexPath.row) as? String
cell!.textLabel?.adjustsFontSizeToFitWidth = true
// Setting number of lines to 0 allows for self adaptive lines
cell!.textLabel?.numberOfLines = 0
return cell!
}
}
} | mit | 78b8000a29c3965af6efd5b485ab5c5b | 39.258993 | 169 | 0.556926 | 5.33874 | false | false | false | false |
631106979/WCLImagePickerController | WCLImagePickerController/WCLImagePickerController/Views/WCLSelectView.swift | 1 | 2698 | //
// WCLSelectView.swift
// WarChat
//
// **************************************************
// * _____ *
// * __ _ __ ___ \ / *
// * \ \/ \/ / / __\ / / *
// * \ _ / | (__ / / *
// * \/ \/ \___/ / /__ *
// * /_____/ *
// * *
// **************************************************
// Github :https://github.com/631106979
// HomePage:https://imwcl.com
// CSDN :http://blog.csdn.net/wang631106979
//
// Created by 王崇磊 on 16/9/14.
// Copyright © 2016年 王崇磊. All rights reserved.
//
// @class WCLSelectView
// @abstract WCLPhotoBrowserController页面的右上角的选择view
// @discussion WCLPhotoBrowserController页面的右上角的选择view
//
import UIKit
internal class WCLSelectView: UIView {
@IBOutlet weak var selectLabel: UILabel!
@IBOutlet weak var selectBt: UIButton!
var selecrIndex: Int = 0 {
willSet {
if newValue == 0 {
selectBt.isSelected = false
selectLabel.isHidden = true
}else {
selectBt.isSelected = true
selectLabel.isHidden = false
selectLabel.text = "\(newValue)"
}
}
}
override func awakeFromNib() {
super.awakeFromNib()
let size = CGSize.init(width: 22, height: 22)
UIGraphicsBeginImageContextWithOptions(size, false, UIScreen.main.scale)
let context = UIGraphicsGetCurrentContext()
if let color = WCLImagePickerOptions.pickerSelectColor {
color.setFill()
}else {
WCLImagePickerOptions.tintColor.setFill()
}
context?.addArc(center: CGPoint.init(x: size.width / 2, y: size.height / 2), radius: size.width / 2, startAngle: 0, endAngle: CGFloat(Double.pi * 2), clockwise: true)
context?.fillPath()
let selectImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
selectBt.setImage(selectImage, for: .selected)
selectBt.setImage(WCLImagePickerBundle.imageFromBundle("image_pickerDefault"), for: .normal)
}
//MARK: init Methods
class func initFormNib() -> WCLSelectView {
let view = UINib.init(nibName: "WCLSelectView", bundle: WCLImagePickerBundle.bundle).instantiate(withOwner: nil, options: nil).first as! WCLSelectView
view.selectBt.isSelected = false
view.selectLabel.isHidden = true
return view
}
}
| mit | 0d79564ba8b7748158463faa1c8ff270 | 34.77027 | 174 | 0.517567 | 4.486441 | false | false | false | false |
LongPF/FaceTube | FaceTube/Tool/Capture/FTCamera.swift | 1 | 9954 | //
// FTCamera.swift
// FaceTube
//
// Created by 龙鹏飞 on 2017/4/5.
// Copyright © 2017年 https://github.com/LongPF/FaceTube. All rights reserved.
//
import UIKit
class FTCamera: NSObject,AVCaptureVideoDataOutputSampleBufferDelegate,AVCaptureAudioDataOutputSampleBufferDelegate {
//捕获会话
public private(set) var captureSession: AVCaptureSession!
public private(set) var cameraQueue: DispatchQueue!
public private(set) var recording: Bool!
public var imageTarget: FTImageTarget?
//视频数据输出设备
fileprivate var videoDataOutput: AVCaptureVideoDataOutput?
//音频数据输出设备
fileprivate var audioDataOutput: AVCaptureAudioDataOutput?
fileprivate var activeVideoInput: AVCaptureDeviceInput?
fileprivate var movieWriter: FTMovieWriter?
override init() {
cameraQueue = DispatchQueue.init(label: "com.facetube.camera")
recording = false
}
//MARK:session
public func setupSession(_ error: NSErrorPointer) -> Bool{
captureSession = AVCaptureSession()
captureSession.sessionPreset = sessionPreset() as String!
if !setupSessinInputs(error) {
return false
}
if !setupSessionOutputs(error){
return false
}
return true
}
public func sessionPreset() -> NSString {
return AVCaptureSessionPreset1280x720 as NSString
}
public func setupSessinInputs(_ error: NSErrorPointer) -> Bool{
let videoDevice: AVCaptureDevice = cameraWithPosition(position: .front)!
let audioDevice: AVCaptureDevice = AVCaptureDevice.defaultDevice(withMediaType: AVMediaTypeAudio)
var videoDeviceInput: AVCaptureDeviceInput?
var audioDeviceInput: AVCaptureDeviceInput?
do{
videoDeviceInput = try AVCaptureDeviceInput.init(device: videoDevice)
audioDeviceInput = try AVCaptureDeviceInput.init(device: audioDevice)
activeVideoInput = videoDeviceInput
}catch let aError as NSError {
error?.pointee = aError
return false
}
if captureSession.canAddInput(videoDeviceInput){
captureSession.addInput(videoDeviceInput)
}else{
error?.pointee = NSError.init(domain: FTCameraErrorDomain, code: FTCameraErrorCode.FTCameraErrorFailedToAddInput.rawValue, userInfo: [NSLocalizedDescriptionKey:"Failed to add video input."])
return false
}
if captureSession.canAddInput(audioDeviceInput){
captureSession.addInput(audioDeviceInput)
}else{
error?.pointee = NSError.init(domain: FTCameraErrorDomain, code: FTCameraErrorCode.FTCameraErrorFailedToAddInput.rawValue, userInfo: [NSLocalizedDescriptionKey:"Failed to add video input."])
return false
}
return true
}
public func setupSessionOutputs(_ error: NSErrorPointer) -> Bool{
videoDataOutput = AVCaptureVideoDataOutput()
//kCVPixelBufferPixelFormatTypeKey用来指定像素的输出格式
videoDataOutput?.videoSettings = [kCVPixelBufferPixelFormatTypeKey as AnyHashable:NSNumber.init(value: kCVPixelFormatType_32BGRA)]
videoDataOutput?.alwaysDiscardsLateVideoFrames = false
videoDataOutput?.setSampleBufferDelegate(self, queue: cameraQueue)
if self.captureSession.canAddOutput(self.videoDataOutput) {
self.captureSession.addOutput(self.videoDataOutput)
}else{
return false
}
audioDataOutput = AVCaptureAudioDataOutput()
audioDataOutput?.setSampleBufferDelegate(self, queue: cameraQueue)
if self.captureSession.canAddOutput(self.audioDataOutput){
self.captureSession.addOutput(self.audioDataOutput)
}else{
return false
}
let videoSettings = videoDataOutput?.recommendedVideoSettingsForAssetWriter(withOutputFileType: AVFileTypeQuickTimeMovie)
let audioSettings = audioDataOutput?.recommendedAudioSettingsForAssetWriter(withOutputFileType: AVFileTypeQuickTimeMovie)
movieWriter = FTMovieWriter.init(videoSettings: videoSettings!, audioSettings: audioSettings!, dispatchQueue: cameraQueue)
movieWriter?.delegate = self
return true
}
/// 开启会话
public func startSession(){
cameraQueue.async {
if !self.captureSession.isRunning{
self.captureSession.startRunning()
}
}
}
/// 停止会话
public func stopSession() {
if self.captureSession.isRunning {
self.captureSession.stopRunning()
}
}
/// 开始录制
public func startRecording(){
movieWriter?.startWriting()
recording = true
}
/// 停止录制
public func stopRecording() {
movieWriter?.stopWriting()
recording = false
}
//MARK:device
///根据摄像头前后位置获取捕获设备
fileprivate func cameraWithPosition(position: AVCaptureDevicePosition) -> AVCaptureDevice? {
let devices: [Any]! = AVCaptureDevice.devices(withMediaType: AVMediaTypeVideo)
for itm in devices {
if let device = itm as? AVCaptureDevice
{
if device.position==position{
return device
}
}
}
return nil
}
///获取正在摄像头
func activeCamera() -> AVCaptureDevice? {
return activeVideoInput?.device
}
///没在使用的摄像头
func inactiveCamera() -> AVCaptureDevice? {
var device: AVCaptureDevice? = nil;
if cameraCount() > 1 {
if activeCamera()?.position == .back {
device = cameraWithPosition(position: .front)
}else{
device = cameraWithPosition(position: .back)
}
}
return device;
}
///摄像头数量
func cameraCount() -> NSInteger {
return AVCaptureDevice.devices(withMediaType: AVMediaTypeVideo).count
}
///是否可以切换摄像头
func canSwitchCameras() -> Bool {
return cameraCount() > 1
}
///切换摄像头
func switchCamers() -> Bool {
if !canSwitchCameras(){
return false
}
//获取改变的摄像头设备
let toggleDevice: AVCaptureDevice? = inactiveCamera()
//获取改变的摄像头输入设备
var toggleDeviceInput: AVCaptureDeviceInput?
do{
try toggleDeviceInput = AVCaptureDeviceInput.init(device: toggleDevice)
}catch{
return false
}
// if (toggleDeviceInput != nil && captureSession.canAddInput(toggleDeviceInput)) {
// }
captureSession.removeInput(activeVideoInput)
captureSession.addInput(toggleDeviceInput)
activeVideoInput = toggleDeviceInput;
return true
}
///正在使用的摄像头是否支持闪光灯
func activeCameraHasFlash() -> Bool {
let currentDevice = activeCamera()
return (currentDevice?.hasFlash)!
}
///正在使用的摄像头的打开或是关闭
func activeCameraSwitchFlash(on: Bool) -> Bool {
if activeCameraHasFlash() {
let currentDevice: AVCaptureDevice! = activeCamera()
do {
try currentDevice.lockForConfiguration()
if on{
if currentDevice.isTorchModeSupported(.on) {
currentDevice.torchMode = .on
}else{
return false
}
if currentDevice.isFlashModeSupported(.on){
currentDevice.flashMode = .on
}
}else{
if currentDevice.isTorchModeSupported(.off){
currentDevice.torchMode = .off
}else{
return false
}
if currentDevice.isFlashModeSupported(.off){
currentDevice.flashMode = .off
}
}
currentDevice.unlockForConfiguration()
}catch{
return false
}
return true
}
return false
}
//MARK:AVCaptureVideoDataOutputSampleBufferDelegate
func captureOutput(_ captureOutput: AVCaptureOutput!, didOutputSampleBuffer sampleBuffer: CMSampleBuffer!, from connection: AVCaptureConnection!) {
// let sourceImage = FTSampleBufferProcessUtils.processSampleBuffer2CIImage(sampleBuffer)
movieWriter?.processSampleBuffer(sampleBuffer: sampleBuffer)
if captureOutput == videoDataOutput{
let imageBuffer: CVPixelBuffer = CMSampleBufferGetImageBuffer(sampleBuffer)!
let sourceImage = CIImage.init(cvPixelBuffer: imageBuffer)
self.imageTarget?.setImage!(image: sourceImage)
}
}
}
extension FTCamera: FTMovieWriterDelegate {
func didWriteMovieAtURL(outputURL: NSURL) {
UISaveVideoAtPathToSavedPhotosAlbum(outputURL.path!, self, #selector(video(videoPath:didFinishSavingWithError:contextInfo:)), nil)
}
func video(videoPath: String, didFinishSavingWithError error: NSError, contextInfo info: UnsafeMutableRawPointer) {
}
}
| mit | 68454353b5341b35f3c8dfc1de3db0ab | 30.844884 | 202 | 0.599544 | 5.912377 | false | false | false | false |
Fenrikur/ef-app_ios | Eurofurence/Modules/Login/Presenter/LoginPresenter.swift | 1 | 5064 | import EurofurenceModel
import Foundation
class LoginPresenter: LoginSceneDelegate {
private let delegate: LoginModuleDelegate
private let scene: LoginScene
private let authenticationService: AuthenticationService
private let alertRouter: AlertRouter
private lazy var validator = LoginValidator(validationHandler: self.loginValidationStateDidChange)
private lazy var validationActions: [LoginResult : () -> Void] = [
.valid: self.scene.enableLoginButton,
.invalid: self.scene.disableLoginButton
]
private enum LoginResult {
case valid
case invalid
}
private struct ValidationError: Swift.Error {}
private class LoginValidator {
var registrationNumber: String? {
didSet { validate() }
}
var username: String? {
didSet { validate() }
}
var password: String? {
didSet { validate() }
}
private let validationHandler: (LoginResult) -> Void
init(validationHandler: @escaping (LoginResult) -> Void) {
self.validationHandler = validationHandler
}
@discardableResult
func makeLoginRequest() throws -> LoginArguments {
return LoginArguments(registrationNumber: try retrieveRegistrationNumber(),
username: try retrieveUsername(),
password: try retrievePassword())
}
private func retrieveUsername() throws -> String {
guard let username = username, !username.isEmpty else { throw ValidationError() }
return username
}
private func retrievePassword() throws -> String {
guard let password = password, !password.isEmpty else { throw ValidationError() }
return password
}
private func retrieveRegistrationNumber() throws -> Int {
guard let registrationNumber = registrationNumber else { throw ValidationError() }
var regNo = 0
guard Scanner(string: registrationNumber).scanInt(®No) else { throw ValidationError() }
return regNo
}
private var isValid: Bool {
do {
try makeLoginRequest()
return true
} catch {
return false
}
}
private func validate() {
validationHandler(isValid ? .valid : .invalid)
}
}
init(delegate: LoginModuleDelegate,
scene: LoginScene,
authenticationService: AuthenticationService,
alertRouter: AlertRouter) {
self.delegate = delegate
self.scene = scene
self.authenticationService = authenticationService
self.alertRouter = alertRouter
scene.delegate = self
scene.setLoginTitle(.login)
}
func loginSceneWillAppear() {
scene.disableLoginButton()
}
func loginSceneDidTapCancelButton() {
delegate.loginModuleDidCancelLogin()
}
func loginSceneDidTapLoginButton() {
guard let request = try? validator.makeLoginRequest() else { return }
var alert = Alert(title: .loggingIn, message: .loggingInDetail)
alert.onCompletedPresentation = { (dismissable) in
self.authenticationService.login(request, completionHandler: { (result) in
dismissable.dismiss {
switch result {
case .success:
self.delegate.loginModuleDidLoginSuccessfully()
case .failure:
let okayAction = AlertAction(title: .ok)
let loginErrorAlert = Alert(title: .loginError,
message: .loginErrorDetail,
actions: [okayAction])
self.alertRouter.show(loginErrorAlert)
}
}
})
}
alertRouter.show(alert)
}
func loginSceneDidUpdateRegistrationNumber(_ registrationNumberString: String) {
validator.registrationNumber = registrationNumberString
let allowedCharacters = CharacterSet(charactersIn: "0123456789")
let currentCharacters = CharacterSet(charactersIn: registrationNumberString)
guard allowedCharacters.isSuperset(of: currentCharacters) == false else { return }
let unacceptableCharacters = currentCharacters.subtracting(allowedCharacters)
let acceptableInput = registrationNumberString.trimmingCharacters(in: unacceptableCharacters)
scene.overrideRegistrationNumber(acceptableInput)
}
func loginSceneDidUpdateUsername(_ username: String) {
validator.username = username
}
func loginSceneDidUpdatePassword(_ password: String) {
validator.password = password
}
private func loginValidationStateDidChange(_ state: LoginResult) {
validationActions[state]?()
}
}
| mit | acbace1258eeb1e4bfb3c513269a2bb7 | 31.883117 | 102 | 0.608412 | 5.908985 | false | false | false | false |
hyperoslo/Tabby | Sources/TabbyController.swift | 1 | 9741 | import UIKit
/**
The protocol that will inform you when an item of the tab bar is tapped.
*/
public protocol TabbyDelegate: class {
func tabbyDidPress(_ item: TabbyBarItem)
}
/**
TabbyController is the controller that will contain all the other controllers.
*/
open class TabbyController: UIViewController, UINavigationControllerDelegate {
public var heightConstraint: NSLayoutConstraint?
/// Used when toggling tabbyBar visibility
private var tabbyBarBottomConstraint: NSLayoutConstraint?
/**
The actual tab bar that will contain the buttons, indicator, separator, etc.
*/
open lazy var tabbyBar: TabbyBar = { [unowned self] in
let tabby = TabbyBar(items: self.items)
tabby.translatesAutoresizingMaskIntoConstraints = false
tabby.delegate = self
return tabby
}()
/// A view behind TabbyBar to patch in the bottom in case of safeArea
fileprivate lazy var patchyView: UIView = {
let view = UIView()
view.backgroundColor = Constant.Color.background
return view
}()
/**
The current selected controller in the tab bar.
*/
open var selectedController: UIViewController {
return items[index].controller
}
/**
Represents if the bar is hidden or not.
*/
open var barHidden: Bool = false {
didSet {
// Delay necessary when changing the whole controller -> UIViewController
// to UINavigationController for instance. The inner constraints change (and break).
let when = DispatchTime.now() + 0.1
DispatchQueue.main.asyncAfter(deadline: when) {
self.toggleBar()
}
}
}
/**
An array of TabbyBarItems. The initializer contains the following parameters:
- Parameter controller: The controller that you set as the one that will appear when tapping the view.
- Parameter image: The image that will appear in the TabbyBarItem.
*/
open var items: [TabbyBarItem] {
didSet {
let currentItem = index < tabbyBar.items.count
? tabbyBar.items[index]
: items[index]
if let index = items.index(of: currentItem) {
self.index = index
}
tabbyBar.items = items
setupDelegate()
}
}
/**
The property to set the current tab bar index.
*/
open var setIndex = 0 {
didSet {
guard setIndex < items.count else { return }
index = setIndex
tabbyBar.selectedItem = index
}
}
/**
Weather the tab bar is translucent or not, this will make you to have to care about the offsets in your controller.
*/
open var translucent: Bool = false {
didSet {
guard index < items.count else { return }
prepareCurrentController()
if !showSeparator {
tabbyBar.layer.shadowOpacity = translucent ? 0 : 1
tabbyBar.translucentView.layer.shadowOpacity = translucent ? 1 : 0
}
}
}
/**
A property indicating weather the tab bar should be visible or not. True by default.
*/
open var barVisible: Bool = true {
didSet {
tabbyBar.alpha = barVisible ? 1 : 0
prepareCurrentController()
}
}
/**
Weather or not it should show the indicator or not to show in which tab the user is in.
*/
open var showIndicator: Bool = true {
didSet {
tabbyBar.indicator.alpha = showIndicator ? 1 : 0
}
}
/**
Weather or not it should display a separator or a shadow.
*/
open var showSeparator: Bool = true {
didSet {
tabbyBar.separator.alpha = showSeparator ? 1 : 0
if showSeparator {
tabbyBar.layer.shadowOpacity = 0
tabbyBar.translucentView.layer.shadowOpacity = 0
} else {
if translucent {
tabbyBar.translucentView.layer.shadowOpacity = 1
} else {
tabbyBar.layer.shadowOpacity = 1
}
}
}
}
var heightConstant: CGFloat = 0
/**
The delegate that will tell you when a tab bar is tapped.
*/
open weak var delegate: TabbyDelegate?
// MARK: - Private variables
fileprivate var index = 0
// MARK: - Initializers
/**
Initializer with a touple of controllers and images for it.
*/
public init(items: [TabbyBarItem]) {
self.items = items
super.init(nibName: nil, bundle: nil)
view.addSubview(patchyView)
view.addSubview(tabbyBar)
setupConstraints()
}
/**
Initializer.
*/
public required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - View lifecycle
/**
Did appear.
*/
open override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
guard childViewControllers.isEmpty else {
return
}
tabbyButtonDidPress(index)
}
open override func didRotate(from fromInterfaceOrientation: UIInterfaceOrientation) {
tabbyBar.collectionView.reloadData()
}
// MARK: - Configurations
open func setBadge(_ value: Int, _ itemImage: String) {
guard !items.filter({ $0.image == itemImage }).isEmpty else { return }
tabbyBar.badges[itemImage] = value
}
// MARK: - Helper methods
func setupDelegate() {
for case let controller as UINavigationController in items.map({ $0.controller }) {
controller.delegate = self
}
}
func prepareCurrentController() {
let controller = items[index].controller
controller.removeFromParentViewController()
controller.view.removeFromSuperview()
controller.view.translatesAutoresizingMaskIntoConstraints = false
addChildViewController(controller)
view.insertSubview(controller.view, belowSubview: patchyView)
tabbyBar.prepareTranslucency(translucent)
applyNewConstraints(controller)
}
func toggleBar() {
animateNewConstraints()
UIView.animate(withDuration: 0.3, animations: {
if self.barHidden {
self.hideTabbar()
} else {
self.showTabbar()
}
}, completion: { _ in
self.tabbyBar.positionIndicator(self.index)
})
}
func animateNewConstraints() {
UIView.animate(withDuration: 0.3, animations: {
self.prepareCurrentController()
self.view.layoutIfNeeded()
})
}
open func applyNewConstraints(_ controller: UIViewController) {
var constant: CGFloat = 0
if barVisible {
constant = -Constant.Dimension.height
}
if translucent {
constant = 0
}
if barHidden {
constant = 0
}
heightConstant = constant
view.constraint(controller.view, attributes: .leading, .trailing, .top)
let constraint = NSLayoutConstraint(
item: controller.view, attribute: .height,
relatedBy: .equal, toItem: view,
attribute: .height, multiplier: 1,
constant: constant)
view.addConstraints([constraint])
heightConstraint = constraint
}
// MARK: - Constraints
func setupConstraints() {
Constraint.on(
tabbyBar.leadingAnchor.constraint(equalTo: view.leadingAnchor),
tabbyBar.trailingAnchor.constraint(equalTo: view.trailingAnchor),
tabbyBar.heightAnchor.constraint(equalToConstant: Constant.Dimension.height),
patchyView.topAnchor.constraint(equalTo: tabbyBar.bottomAnchor),
patchyView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
patchyView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
patchyView.bottomAnchor.constraint(equalTo: view.bottomAnchor)
)
if #available(iOS 11, *) {
tabbyBarBottomConstraint = tabbyBar.bottomAnchor.constraint(
equalTo: view.safeAreaLayoutGuide.bottomAnchor
)
Constraint.on(
tabbyBarBottomConstraint!
)
} else {
tabbyBarBottomConstraint = tabbyBar.bottomAnchor.constraint(
equalTo: view.bottomAnchor
)
Constraint.on(
tabbyBarBottomConstraint!
)
}
}
// MARK: - Tabbar
public func showTabbar() {
tabbyBarBottomConstraint?.constant = 0
tabbyBar.indicator.alpha = showIndicator ? 1 : 0
UIView.animate(withDuration: 0.25) {
self.view.layoutIfNeeded()
}
}
public func hideTabbar() {
tabbyBarBottomConstraint?.constant = 200
tabbyBar.indicator.alpha = 0
UIView.animate(withDuration: 0.25) {
self.view.layoutIfNeeded()
}
}
}
extension TabbyController {
public func navigationController(_ navigationController: UINavigationController, willShow viewController: UIViewController, animated: Bool) {
if viewController.hidesBottomBarWhenPushed {
hideTabbar()
} else {
showTabbar()
}
}
}
extension TabbyController: TabbyBarDelegate {
/**
The delegate method comming from the tab bar.
- Parameter index: The index that was just tapped.
*/
public func tabbyButtonDidPress(_ index: Int) {
self.index = index
guard index < items.count else { return }
let item = items[index]
let controller = item.controller
delegate?.tabbyDidPress(item)
guard item.selection == .systematic else { return }
/// Check if it should do another action rather than removing the view.
guard !view.subviews.contains(controller.view) else {
if let navigationController = controller as? UINavigationController {
navigationController.popViewController(animated: true)
} else {
for case let subview as UIScrollView in controller.view.subviews {
subview.setContentOffset(CGPoint.zero, animated: true)
}
}
return
}
items.forEach {
$0.controller.removeFromParentViewController()
$0.controller.view.removeFromSuperview()
}
controller.view.translatesAutoresizingMaskIntoConstraints = false
addChildViewController(controller)
view.insertSubview(controller.view, belowSubview: patchyView)
applyNewConstraints(controller)
}
}
| mit | 4fb9fe08dd42d41d32afb9bd5156fdfb | 24.10567 | 143 | 0.675803 | 4.553997 | false | false | false | false |
EZ-NET/ESCSVParser | ESCSVParser/Parser/CSVRawLine.swift | 1 | 2178 | //
// CSVRawLine.swift
// ESCSVParser
//
// Created by Tomohiro Kumagai on H27/07/15.
// Copyright © 平成27年 EasyStyle G.K. All rights reserved.
//
/// This struct will be used at the time of parsing.
/// This struct treats each column as raw string value in a row.
/// By using 'column(index:Int)' method, you can convert the value of raw column data to any type that conforms to 'RawColumnConvertible' protocol.
/// An optional<T:RawColumnConvertible> type is also conforms to 'RawColumnConvertible' protocol.
public struct RawLine {
var columns:[RawColumn]
init(columns:RawColumn...) {
self.init(columns: columns)
}
init(columns:[RawColumn]) {
self.columns = columns
}
init(rawLine line:String) throws {
self.columns = try CSVParser.parseRawLine(line).columns
}
}
extension RawLine : CollectionType {
public var startIndex:Int {
return self.columns.startIndex + 1
}
public var endIndex:Int {
return self.columns.endIndex + 1
}
public subscript(index:Int) -> RawColumn {
return self.columns[index - 1]
}
}
extension RawLine {
static func column<R:RawColumnConvertible where R == R.ConvertedType>(rawColumn:RawColumn) throws -> R {
let isNilLiteralConvertibleType = R.self is NilLiteralConvertible.Type
let isRawColumnNullableType = R.self is RawColumnNullable.Type
if isNilLiteralConvertibleType && isRawColumnNullableType {
if (R.self as! RawColumnNullable.Type).isRawColumnNull(rawColumn) {
return (R.self as! NilLiteralConvertible.Type).init(nilLiteral: ()) as! R
}
}
do {
return try R.fromRawColumn(rawColumn)
}
catch let error as FromRawColumnError {
let message = "Failed to convert column type from 'String'(\(rawColumn)) to '\(R.self)'."
let reasonSuffix = error.reason.map { " \($0)" } ?? ""
throw CSVParserError.ConvertError(message + reasonSuffix)
}
}
/// Returns an any type that conforms to 'RawColumnConvertible' protocol that converted from raw column string at 'index'.
public func column<R:RawColumnConvertible where R == R.ConvertedType>(index:Int) throws -> R {
return try RawLine.column(self[index]) as R
}
}
| mit | db2b446c241a023cbf2799b8014bac6c | 24.845238 | 147 | 0.708429 | 3.618333 | false | false | false | false |
sarahspins/Loop | Loop/Managers/LoopDataManager.swift | 1 | 19229 | //
// LoopDataManager.swift
// Naterade
//
// Created by Nathan Racklyeft on 3/12/16.
// Copyright © 2016 Nathan Racklyeft. All rights reserved.
//
import Foundation
import CarbKit
import InsulinKit
import LoopKit
import MinimedKit
import HealthKit
final class LoopDataManager {
enum LoopUpdateContext: Int {
case Bolus
case Carbs
case Glucose
case Preferences
case TempBasal
}
static let LoopDataUpdatedNotification = "com.loudnate.Naterade.notification.LoopDataUpdated"
static let LoopRunningNotification = "com.loudnate.Naterade.notification.LoopRunning"
static let LoopUpdateContextKey = "com.loudnate.Loop.LoopDataManager.LoopUpdateContext"
typealias TempBasalRecommendation = (recommendedDate: NSDate, rate: Double, duration: NSTimeInterval)
unowned let deviceDataManager: DeviceDataManager
var dosingEnabled: Bool {
didSet {
NSUserDefaults.standardUserDefaults().dosingEnabled = dosingEnabled
notify(forChange: .Preferences)
}
}
init(deviceDataManager: DeviceDataManager) {
self.deviceDataManager = deviceDataManager
dosingEnabled = NSUserDefaults.standardUserDefaults().dosingEnabled
observe()
}
// Actions
private func observe() {
let center = NSNotificationCenter.defaultCenter()
notificationObservers = [
center.addObserverForName(DeviceDataManager.GlucoseUpdatedNotification, object: deviceDataManager, queue: nil) { (note) -> Void in
dispatch_async(self.dataAccessQueue) {
self.glucoseMomentumEffect = nil
self.notify(forChange: .Glucose)
}
},
center.addObserverForName(DeviceDataManager.PumpStatusUpdatedNotification, object: deviceDataManager, queue: nil) { (note) -> Void in
dispatch_async(self.dataAccessQueue) {
self.insulinEffect = nil
self.insulinOnBoard = nil
self.loop()
}
}
]
notificationObservers.append(center.addObserverForName(CarbStore.CarbEntriesDidUpdateNotification, object: nil, queue: nil) { (note) -> Void in
dispatch_async(self.dataAccessQueue) {
self.carbEffect = nil
self.notify(forChange: .Carbs)
}
})
}
private func loop() {
NSNotificationCenter.defaultCenter().postNotificationName(self.dynamicType.LoopRunningNotification, object: self)
lastLoopError = nil
do {
try self.update()
if dosingEnabled {
setRecommendedTempBasal { (success, error) -> Void in
self.lastLoopError = error
if let error = error {
self.deviceDataManager.logger.addError(error, fromSource: "TempBasal")
} else {
self.lastLoopCompleted = NSDate()
}
self.notify(forChange: .TempBasal)
}
// Delay the notification until we know the result of the temp basal
return
} else {
lastLoopCompleted = NSDate()
}
} catch let error {
lastLoopError = error
}
notify(forChange: .TempBasal)
}
// References to registered notification center observers
private var notificationObservers: [AnyObject] = []
deinit {
for observer in notificationObservers {
NSNotificationCenter.defaultCenter().removeObserver(observer)
}
}
private func update() throws {
let updateGroup = dispatch_group_create()
if glucoseMomentumEffect == nil {
dispatch_group_enter(updateGroup)
updateGlucoseMomentumEffect { (effects, error) -> Void in
if error == nil {
self.glucoseMomentumEffect = effects
} else {
self.glucoseMomentumEffect = nil
}
dispatch_group_leave(updateGroup)
}
}
if carbEffect == nil {
dispatch_group_enter(updateGroup)
updateCarbEffect { (effects, error) -> Void in
if error == nil {
self.carbEffect = effects
} else {
self.carbEffect = nil
}
dispatch_group_leave(updateGroup)
}
}
if insulinEffect == nil {
dispatch_group_enter(updateGroup)
updateInsulinEffect { (effects, error) -> Void in
if error == nil {
self.insulinEffect = effects
} else {
self.insulinEffect = nil
}
dispatch_group_leave(updateGroup)
}
}
if insulinOnBoard == nil {
dispatch_group_enter(updateGroup)
deviceDataManager.doseStore.insulinOnBoardAtDate(NSDate()) { (value, error) in
if let error = error {
self.deviceDataManager.logger.addError(error, fromSource: "DoseStore")
}
self.insulinOnBoard = value
dispatch_group_leave(updateGroup)
}
}
dispatch_group_wait(updateGroup, DISPATCH_TIME_FOREVER)
if self.predictedGlucose == nil {
do {
try self.updatePredictedGlucoseAndRecommendedBasal()
} catch let error {
self.deviceDataManager.logger.addError(error, fromSource: "PredictGlucose")
throw error
}
}
}
private func notify(forChange context: LoopUpdateContext) {
NSNotificationCenter.defaultCenter().postNotificationName(self.dynamicType.LoopDataUpdatedNotification,
object: self,
userInfo: [self.dynamicType.LoopUpdateContextKey: context.rawValue]
)
}
/**
Retrieves the current state of the loop, calculating
This operation is performed asynchronously and the completion will be executed on an arbitrary background queue.
- parameter resultsHandler: A closure called once the values have been retrieved. The closure takes the following arguments:
- predictedGlucose: The calculated timeline of predicted glucose values
- recommendedTempBasal: The recommended temp basal based on predicted glucose
- lastTempBasal: The last set temp basal
- lastLoopCompleted: The last date at which a loop completed, from prediction to dose (if dosing is enabled)
- insulinOnBoard Current insulin on board
- error: An error in the current state of the loop, or one that happened during the last attempt to loop.
*/
func getLoopStatus(resultsHandler: (predictedGlucose: [GlucoseValue]?, recommendedTempBasal: TempBasalRecommendation?, lastTempBasal: DoseEntry?, lastLoopCompleted: NSDate?, insulinOnBoard: InsulinValue?, error: ErrorType?) -> Void) {
dispatch_async(dataAccessQueue) {
var error: ErrorType?
do {
try self.update()
} catch let updateError {
error = updateError
}
resultsHandler(predictedGlucose: self.predictedGlucose, recommendedTempBasal: self.recommendedTempBasal, lastTempBasal: self.lastTempBasal, lastLoopCompleted: self.lastLoopCompleted, insulinOnBoard: self.insulinOnBoard, error: error ?? self.lastLoopError)
}
}
// Calculation
private let dataAccessQueue: dispatch_queue_t = dispatch_queue_create("com.loudnate.Naterade.LoopDataManager.dataAccessQueue", dispatch_queue_attr_make_with_qos_class(DISPATCH_QUEUE_SERIAL, QOS_CLASS_UTILITY, 0))
private var carbEffect: [GlucoseEffect]? {
didSet {
predictedGlucose = nil
}
}
private var insulinEffect: [GlucoseEffect]? {
didSet {
if let bolusDate = lastBolus?.date where bolusDate.timeIntervalSinceNow < NSTimeInterval(minutes: -5) {
lastBolus = nil
}
predictedGlucose = nil
}
}
private var insulinOnBoard: InsulinValue?
private var glucoseMomentumEffect: [GlucoseEffect]? {
didSet {
predictedGlucose = nil
}
}
private var predictedGlucose: [GlucoseValue]? {
didSet {
recommendedTempBasal = nil
}
}
private var recommendedTempBasal: TempBasalRecommendation?
private var lastTempBasal: DoseEntry?
private var lastBolus: (units: Double, date: NSDate)?
private var lastLoopError: ErrorType? {
didSet {
if lastLoopError != nil {
AnalyticsManager.sharedManager.loopDidError()
}
}
}
private var lastLoopCompleted: NSDate? {
didSet {
NotificationManager.scheduleLoopNotRunningNotifications()
AnalyticsManager.sharedManager.loopDidSucceed()
}
}
private func updateCarbEffect(completionHandler: (effects: [GlucoseEffect]?, error: ErrorType?) -> Void) {
let glucose = deviceDataManager.glucoseStore?.latestGlucose
if let carbStore = deviceDataManager.carbStore {
carbStore.getGlucoseEffects(startDate: glucose?.startDate) { (effects, error) -> Void in
if let error = error {
self.deviceDataManager.logger.addError(error, fromSource: "CarbStore")
}
completionHandler(effects: effects, error: error)
}
} else {
completionHandler(effects: nil, error: LoopError.MissingDataError("CarbStore not available"))
}
}
private func updateInsulinEffect(completionHandler: (effects: [GlucoseEffect]?, error: ErrorType?) -> Void) {
let glucose = deviceDataManager.glucoseStore?.latestGlucose
deviceDataManager.doseStore.getGlucoseEffects(startDate: glucose?.startDate) { (effects, error) -> Void in
if let error = error {
self.deviceDataManager.logger.addError(error, fromSource: "DoseStore")
}
completionHandler(effects: effects, error: error)
}
}
private func updateGlucoseMomentumEffect(completionHandler: (effects: [GlucoseEffect]?, error: ErrorType?) -> Void) {
if let glucoseStore = deviceDataManager.glucoseStore {
glucoseStore.getRecentMomentumEffect { (effects, error) -> Void in
if let error = error {
self.deviceDataManager.logger.addError(error, fromSource: "GlucoseStore")
}
completionHandler(effects: effects, error: error)
}
} else {
completionHandler(effects: nil, error: LoopError.MissingDataError("GlucoseStore not available"))
}
}
/**
Runs the glucose prediction on the latest effect data.
*This method should only be called from the `dataAccessQueue`*
*/
private func updatePredictedGlucoseAndRecommendedBasal() throws {
guard let
glucose = self.deviceDataManager.glucoseStore?.latestGlucose,
pumpStatusDate = self.deviceDataManager.latestReservoirValue?.startDate
else
{
self.predictedGlucose = nil
throw LoopError.MissingDataError("Cannot predict glucose due to missing input data")
}
let startDate = NSDate()
let recencyInterval = NSTimeInterval(minutes: 15)
guard startDate.timeIntervalSinceDate(glucose.startDate) <= recencyInterval &&
startDate.timeIntervalSinceDate(pumpStatusDate) <= recencyInterval
else
{
self.predictedGlucose = nil
throw LoopError.StaleDataError("Glucose Date: \(glucose.startDate) or Pump status date: \(pumpStatusDate) older than \(recencyInterval.minutes) min")
}
guard let
momentum = self.glucoseMomentumEffect,
carbEffect = self.carbEffect,
insulinEffect = self.insulinEffect else
{
self.predictedGlucose = nil
throw LoopError.MissingDataError("Cannot predict glucose due to missing effect data")
}
var error: ErrorType?
defer {
self.deviceDataManager.logger.addLoopStatus(
startDate: startDate,
endDate: NSDate(),
glucose: glucose,
effects: [
"momentum": momentum,
"carbs": carbEffect,
"insulin": insulinEffect
],
error: error,
prediction: prediction,
recommendedTempBasal: recommendedTempBasal
)
}
let prediction = LoopMath.predictGlucose(glucose, momentum: momentum, effects: carbEffect, insulinEffect)
self.predictedGlucose = prediction
guard let
maxBasal = deviceDataManager.maximumBasalRatePerHour,
glucoseTargetRange = deviceDataManager.glucoseTargetRangeSchedule,
insulinSensitivity = deviceDataManager.insulinSensitivitySchedule,
basalRates = deviceDataManager.basalRateSchedule
else {
error = LoopError.MissingDataError("Loop configuration data not set")
throw error!
}
if let tempBasal = DoseMath.recommendTempBasalFromPredictedGlucose(prediction,
lastTempBasal: lastTempBasal,
maxBasalRate: maxBasal,
glucoseTargetRange: glucoseTargetRange,
insulinSensitivity: insulinSensitivity,
basalRateSchedule: basalRates,
allowPredictiveTempBelowRange: true
) {
recommendedTempBasal = (recommendedDate: NSDate(), rate: tempBasal.rate, duration: tempBasal.duration)
} else {
recommendedTempBasal = nil
}
}
func addCarbEntryAndRecommendBolus(carbEntry: CarbEntry, resultsHandler: (units: Double?, error: ErrorType?) -> Void) {
if let carbStore = deviceDataManager.carbStore {
carbStore.addCarbEntry(carbEntry) { (success, _, error) in
dispatch_async(self.dataAccessQueue) {
if success {
self.carbEffect = nil
do {
try self.update()
resultsHandler(units: try self.recommendBolus(), error: nil)
} catch let error {
resultsHandler(units: nil, error: error)
}
} else {
resultsHandler(units: nil, error: error)
}
}
}
} else {
resultsHandler(units: nil, error: LoopError.MissingDataError("CarbStore not configured"))
}
}
private func recommendBolus() throws -> Double {
guard let
glucose = self.predictedGlucose,
maxBolus = self.deviceDataManager.maximumBolus,
glucoseTargetRange = self.deviceDataManager.glucoseTargetRangeSchedule,
insulinSensitivity = self.deviceDataManager.insulinSensitivitySchedule,
basalRates = self.deviceDataManager.basalRateSchedule
else {
throw LoopError.MissingDataError("Bolus prediction and configuration data not found")
}
let recencyInterval = NSTimeInterval(minutes: 15)
guard let predictedInterval = glucose.first?.startDate.timeIntervalSinceNow else {
throw LoopError.MissingDataError("No glucose data found")
}
guard abs(predictedInterval) <= recencyInterval else {
throw LoopError.StaleDataError("Glucose is \(predictedInterval.minutes) min old")
}
let pendingBolusAmount: Double = lastBolus?.units ?? 0
return max(0, DoseMath.recommendBolusFromPredictedGlucose(glucose,
lastTempBasal: self.lastTempBasal,
maxBolus: maxBolus,
glucoseTargetRange: glucoseTargetRange,
insulinSensitivity: insulinSensitivity,
basalRateSchedule: basalRates
) - pendingBolusAmount)
}
func getRecommendedBolus(resultsHandler: (units: Double?, error: ErrorType?) -> Void) {
dispatch_async(dataAccessQueue) {
do {
let units = try self.recommendBolus()
resultsHandler(units: units, error: nil)
} catch let error {
resultsHandler(units: nil, error: error)
}
}
}
private func setRecommendedTempBasal(resultsHandler: (success: Bool, error: ErrorType?) -> Void) {
guard let recommendedTempBasal = self.recommendedTempBasal else {
resultsHandler(success: true, error: nil)
return
}
guard recommendedTempBasal.recommendedDate.timeIntervalSinceNow < NSTimeInterval(minutes: 5) else {
resultsHandler(success: false, error: LoopError.StaleDataError("Recommended temp basal is \(recommendedTempBasal.recommendedDate.timeIntervalSinceNow.minutes) min old"))
return
}
guard let device = self.deviceDataManager.rileyLinkManager.firstConnectedDevice else {
resultsHandler(success: false, error: LoopError.ConnectionError)
return
}
guard let ops = device.ops else {
resultsHandler(success: false, error: LoopError.ConfigurationError)
return
}
ops.setTempBasal(recommendedTempBasal.rate, duration: recommendedTempBasal.duration) { (result) -> Void in
switch result {
case .Success(let body):
dispatch_async(self.dataAccessQueue) {
let now = NSDate()
let endDate = now.dateByAddingTimeInterval(body.timeRemaining)
let startDate = endDate.dateByAddingTimeInterval(-recommendedTempBasal.duration)
self.lastTempBasal = DoseEntry(type: .tempBasal, startDate: startDate, endDate: endDate, value: body.rate, unit: .unitsPerHour)
self.recommendedTempBasal = nil
resultsHandler(success: true, error: nil)
}
case .Failure(let error):
resultsHandler(success: false, error: error)
}
}
}
func enactRecommendedTempBasal(resultsHandler: (success: Bool, error: ErrorType?) -> Void) {
dispatch_async(dataAccessQueue) {
self.setRecommendedTempBasal(resultsHandler)
}
}
/**
Informs the loop algorithm of an enacted bolus
- parameter units: The amount of insulin
- parameter date: The date the bolus was set
*/
func recordBolus(units: Double, atDate date: NSDate) {
dispatch_async(dataAccessQueue) {
self.lastBolus = (units: units, date: date)
self.notify(forChange: .Bolus)
}
}
}
| apache-2.0 | 9e90e9d99dcd8dd5d2e04df07586d6d8 | 36.119691 | 267 | 0.608384 | 5.445483 | false | false | false | false |
rudkx/swift | stdlib/public/core/UnicodeHelpers.swift | 1 | 14189 | //===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
//
// Low-level helper functions and utilities for interpreting Unicode
//
@inlinable
@inline(__always)
internal func _decodeUTF8(_ x: UInt8) -> Unicode.Scalar {
_internalInvariant(UTF8.isASCII(x))
return Unicode.Scalar(_unchecked: UInt32(x))
}
@inlinable
@inline(__always)
internal func _decodeUTF8(_ x: UInt8, _ y: UInt8) -> Unicode.Scalar {
_internalInvariant(_utf8ScalarLength(x) == 2)
_internalInvariant(UTF8.isContinuation(y))
let x = UInt32(x)
let value = ((x & 0b0001_1111) &<< 6) | _continuationPayload(y)
return Unicode.Scalar(_unchecked: value)
}
@inlinable
@inline(__always)
internal func _decodeUTF8(
_ x: UInt8, _ y: UInt8, _ z: UInt8
) -> Unicode.Scalar {
_internalInvariant(_utf8ScalarLength(x) == 3)
_internalInvariant(UTF8.isContinuation(y) && UTF8.isContinuation(z))
let x = UInt32(x)
let value = ((x & 0b0000_1111) &<< 12)
| (_continuationPayload(y) &<< 6)
| _continuationPayload(z)
return Unicode.Scalar(_unchecked: value)
}
@inlinable
@inline(__always)
internal func _decodeUTF8(
_ x: UInt8, _ y: UInt8, _ z: UInt8, _ w: UInt8
) -> Unicode.Scalar {
_internalInvariant(_utf8ScalarLength(x) == 4)
_internalInvariant(
UTF8.isContinuation(y) && UTF8.isContinuation(z)
&& UTF8.isContinuation(w))
let x = UInt32(x)
let value = ((x & 0b0000_1111) &<< 18)
| (_continuationPayload(y) &<< 12)
| (_continuationPayload(z) &<< 6)
| _continuationPayload(w)
return Unicode.Scalar(_unchecked: value)
}
internal func _decodeScalar(
_ utf16: UnsafeBufferPointer<UInt16>, startingAt i: Int
) -> (Unicode.Scalar, scalarLength: Int) {
let high = utf16[i]
if i + 1 >= utf16.count {
_internalInvariant(!UTF16.isLeadSurrogate(high))
_internalInvariant(!UTF16.isTrailSurrogate(high))
return (Unicode.Scalar(_unchecked: UInt32(high)), 1)
}
if !UTF16.isLeadSurrogate(high) {
_internalInvariant(!UTF16.isTrailSurrogate(high))
return (Unicode.Scalar(_unchecked: UInt32(high)), 1)
}
let low = utf16[i+1]
_internalInvariant(UTF16.isLeadSurrogate(high))
_internalInvariant(UTF16.isTrailSurrogate(low))
return (UTF16._decodeSurrogates(high, low), 2)
}
@inlinable
internal func _decodeScalar(
_ utf8: UnsafeBufferPointer<UInt8>, startingAt i: Int
) -> (Unicode.Scalar, scalarLength: Int) {
let cu0 = utf8[_unchecked: i]
let len = _utf8ScalarLength(cu0)
switch len {
case 1: return (_decodeUTF8(cu0), len)
case 2: return (_decodeUTF8(cu0, utf8[_unchecked: i &+ 1]), len)
case 3: return (_decodeUTF8(
cu0, utf8[_unchecked: i &+ 1], utf8[_unchecked: i &+ 2]), len)
case 4:
return (_decodeUTF8(
cu0,
utf8[_unchecked: i &+ 1],
utf8[_unchecked: i &+ 2],
utf8[_unchecked: i &+ 3]),
len)
default: Builtin.unreachable()
}
}
@inlinable
internal func _decodeScalar(
_ utf8: UnsafeBufferPointer<UInt8>, endingAt i: Int
) -> (Unicode.Scalar, scalarLength: Int) {
let len = _utf8ScalarLength(utf8, endingAt: i)
let (scalar, scalarLen) = _decodeScalar(utf8, startingAt: i &- len)
_internalInvariant(len == scalarLen)
return (scalar, len)
}
@inlinable @inline(__always)
internal func _utf8ScalarLength(_ x: UInt8) -> Int {
_internalInvariant(!UTF8.isContinuation(x))
if UTF8.isASCII(x) { return 1 }
// TODO(String micro-performance): check codegen
return (~x).leadingZeroBitCount
}
@inlinable @inline(__always)
internal func _utf8ScalarLength(
_ utf8: UnsafeBufferPointer<UInt8>, endingAt i: Int
) -> Int {
var len = 1
while UTF8.isContinuation(utf8[_unchecked: i &- len]) {
len &+= 1
}
_internalInvariant(len == _utf8ScalarLength(utf8[i &- len]))
return len
}
@inlinable
@inline(__always)
internal func _continuationPayload(_ x: UInt8) -> UInt32 {
return UInt32(x & 0x3F)
}
@inlinable
internal func _scalarAlign(
_ utf8: UnsafeBufferPointer<UInt8>, _ idx: Int
) -> Int {
guard _fastPath(idx != utf8.count) else { return idx }
var i = idx
while _slowPath(UTF8.isContinuation(utf8[_unchecked: i])) {
i &-= 1
_internalInvariant(i >= 0,
"Malformed contents: starts with continuation byte")
}
return i
}
//
// Scalar helpers
//
extension _StringGuts {
@inlinable
@inline(__always) // fast-path: fold common fastUTF8 check
internal func scalarAlign(_ idx: Index) -> Index {
let result: String.Index
if _fastPath(idx._isScalarAligned) {
result = idx
} else {
// TODO(String performance): isASCII check
result = scalarAlignSlow(idx)
}
_internalInvariant(isOnUnicodeScalarBoundary(result),
"Alignment bit is set for non-aligned index")
_internalInvariant_5_1(result._isScalarAligned)
return result
}
@inline(never) // slow-path
@_alwaysEmitIntoClient // Swift 5.1
internal func scalarAlignSlow(_ idx: Index) -> Index {
_internalInvariant_5_1(!idx._isScalarAligned)
if _slowPath(idx.transcodedOffset != 0 || idx._encodedOffset == 0) {
// Transcoded index offsets are already scalar aligned
return String.Index(_encodedOffset: idx._encodedOffset)._scalarAligned
}
if _slowPath(self.isForeign) {
// In 5.1 this check was added to foreignScalarAlign, but when this is
// emitted into a client that then runs against a 5.0 stdlib, it calls
// a version of foreignScalarAlign that doesn't check for this, which
// ends up asking CFString for its endIndex'th character, which throws
// an exception. So we duplicate the check here for back deployment.
guard idx._encodedOffset != self.count else { return idx._scalarAligned }
let foreignIdx = foreignScalarAlign(idx)
_internalInvariant_5_1(foreignIdx._isScalarAligned)
return foreignIdx
}
return String.Index(_encodedOffset:
self.withFastUTF8 { _scalarAlign($0, idx._encodedOffset) }
)._scalarAligned
}
@inlinable
internal func fastUTF8ScalarLength(startingAt i: Int) -> Int {
_internalInvariant(isFastUTF8)
let len = _utf8ScalarLength(self.withFastUTF8 { $0[i] })
_internalInvariant((1...4) ~= len)
return len
}
@inlinable
internal func fastUTF8ScalarLength(endingAt i: Int) -> Int {
_internalInvariant(isFastUTF8)
return self.withFastUTF8 { utf8 in
_internalInvariant(i == utf8.count || !UTF8.isContinuation(utf8[i]))
var len = 1
while UTF8.isContinuation(utf8[i &- len]) {
_internalInvariant(i &- len > 0)
len += 1
}
_internalInvariant(len <= 4)
return len
}
}
@inlinable
internal func fastUTF8Scalar(startingAt i: Int) -> Unicode.Scalar {
_internalInvariant(isFastUTF8)
return self.withFastUTF8 { _decodeScalar($0, startingAt: i).0 }
}
@usableFromInline
@_effects(releasenone)
internal func isOnUnicodeScalarBoundary(_ i: String.Index) -> Bool {
// TODO(String micro-performance): check isASCII
// Beginning and end are always scalar aligned; mid-scalar never is
guard i.transcodedOffset == 0 else { return false }
if i == self.startIndex || i == self.endIndex { return true }
if _fastPath(isFastUTF8) {
return self.withFastUTF8 {
return !UTF8.isContinuation($0[i._encodedOffset])
}
}
return i == foreignScalarAlign(i)
}
}
//
// Error-correcting helpers (U+FFFD for unpaired surrogates) for accessing
// contents of foreign strings
//
extension _StringGuts {
@_effects(releasenone)
private func _getForeignCodeUnit(at i: Int) -> UInt16 {
#if _runtime(_ObjC)
// Currently, foreign means NSString
return _cocoaStringSubscript(_object.cocoaObject, i)
#else
fatalError("No foreign strings on Linux in this version of Swift")
#endif
}
@usableFromInline
@_effects(releasenone)
internal func foreignErrorCorrectedScalar(
startingAt idx: String.Index
) -> (Unicode.Scalar, scalarLength: Int) {
_internalInvariant(idx.transcodedOffset == 0)
_internalInvariant(idx._encodedOffset < self.count)
let start = idx._encodedOffset
let leading = _getForeignCodeUnit(at: start)
if _fastPath(!UTF16.isSurrogate(leading)) {
return (Unicode.Scalar(_unchecked: UInt32(leading)), 1)
}
// Validate foreign strings on-read: trailing surrogates are invalid,
// leading need following trailing
//
// TODO(String performance): Consider having a valid performance flag
// available to check, and assert it's not set in the condition here.
let nextOffset = start &+ 1
if _slowPath(UTF16.isTrailSurrogate(leading) || nextOffset == self.count) {
return (Unicode.Scalar._replacementCharacter, 1)
}
let trailing = _getForeignCodeUnit(at: nextOffset)
if _slowPath(!UTF16.isTrailSurrogate(trailing)) {
return (Unicode.Scalar._replacementCharacter, 1)
}
return (UTF16._decodeSurrogates(leading, trailing), 2)
}
@_effects(releasenone)
internal func foreignErrorCorrectedScalar(
endingAt idx: String.Index
) -> (Unicode.Scalar, scalarLength: Int) {
_internalInvariant(idx.transcodedOffset == 0)
_internalInvariant(idx._encodedOffset <= self.count)
_internalInvariant(idx._encodedOffset > 0)
let end = idx._encodedOffset
let trailing = _getForeignCodeUnit(at: end &- 1)
if _fastPath(!UTF16.isSurrogate(trailing)) {
return (Unicode.Scalar(_unchecked: UInt32(trailing)), 1)
}
// Validate foreign strings on-read: trailing surrogates are invalid,
// leading need following trailing
//
// TODO(String performance): Consider having a valid performance flag
// available to check, and assert it's not set in the condition here.
let priorOffset = end &- 2
if _slowPath(UTF16.isLeadSurrogate(trailing) || priorOffset < 0) {
return (Unicode.Scalar._replacementCharacter, 1)
}
let leading = _getForeignCodeUnit(at: priorOffset)
if _slowPath(!UTF16.isLeadSurrogate(leading)) {
return (Unicode.Scalar._replacementCharacter, 1)
}
return (UTF16._decodeSurrogates(leading, trailing), 2)
}
@_effects(releasenone)
internal func foreignErrorCorrectedUTF16CodeUnit(
at idx: String.Index
) -> UInt16 {
_internalInvariant(idx.transcodedOffset == 0)
_internalInvariant(idx._encodedOffset < self.count)
let start = idx._encodedOffset
let cu = _getForeignCodeUnit(at: start)
if _fastPath(!UTF16.isSurrogate(cu)) {
return cu
}
// Validate foreign strings on-read: trailing surrogates are invalid,
// leading need following trailing
//
// TODO(String performance): Consider having a valid performance flag
// available to check, and assert it's not set in the condition here.
if UTF16.isLeadSurrogate(cu) {
let nextOffset = start &+ 1
guard nextOffset < self.count,
UTF16.isTrailSurrogate(_getForeignCodeUnit(at: nextOffset))
else { return UTF16._replacementCodeUnit }
} else {
let priorOffset = start &- 1
guard priorOffset >= 0,
UTF16.isLeadSurrogate(_getForeignCodeUnit(at: priorOffset))
else { return UTF16._replacementCodeUnit }
}
return cu
}
@usableFromInline @inline(never) // slow-path
@_effects(releasenone)
internal func foreignScalarAlign(_ idx: Index) -> Index {
guard idx._encodedOffset != self.count else { return idx._scalarAligned }
_internalInvariant(idx._encodedOffset < self.count)
let ecCU = foreignErrorCorrectedUTF16CodeUnit(at: idx)
if _fastPath(!UTF16.isTrailSurrogate(ecCU)) {
return idx._scalarAligned
}
_internalInvariant(idx._encodedOffset > 0,
"Error-correction shouldn't give trailing surrogate at position zero")
return String.Index(_encodedOffset: idx._encodedOffset &- 1)._scalarAligned
}
@usableFromInline @inline(never)
@_effects(releasenone)
internal func foreignErrorCorrectedGrapheme(
startingAt start: Int, endingAt end: Int
) -> Character {
#if _runtime(_ObjC)
_internalInvariant(self.isForeign)
// Both a fast-path for single-code-unit graphemes and validation:
// treat isolated surrogates as isolated graphemes
let count = end &- start
if start &- end == 1 {
return Character(String(self.foreignErrorCorrectedScalar(
startingAt: String.Index(_encodedOffset: start)
).0))
}
return withUnsafeTemporaryAllocation(
of: UInt16.self, capacity: count
) { buffer in
_cocoaStringCopyCharacters(
from: self._object.cocoaObject,
range: start..<end,
into: buffer.baseAddress._unsafelyUnwrappedUnchecked
)
return Character(String._uncheckedFromUTF16(UnsafeBufferPointer(buffer)))
}
#else
fatalError("No foreign strings on Linux in this version of Swift")
#endif
}
}
// Higher level aggregate operations. These should only be called when the
// result is the sole operation done by a caller, otherwise it's always more
// efficient to use `withFastUTF8` in the caller.
extension _StringGuts {
@inlinable @inline(__always)
internal func errorCorrectedScalar(
startingAt i: Int
) -> (Unicode.Scalar, scalarLength: Int) {
if _fastPath(isFastUTF8) {
return withFastUTF8 { _decodeScalar($0, startingAt: i) }
}
return foreignErrorCorrectedScalar(
startingAt: String.Index(_encodedOffset: i))
}
@inlinable @inline(__always)
internal func errorCorrectedCharacter(
startingAt start: Int, endingAt end: Int
) -> Character {
if _fastPath(isFastUTF8) {
return withFastUTF8(range: start..<end) { utf8 in
return Character(unchecked: String._uncheckedFromUTF8(utf8))
}
}
return foreignErrorCorrectedGrapheme(startingAt: start, endingAt: end)
}
}
| apache-2.0 | 0de9970d38c95a85260726e52aa8cba0 | 31.174603 | 80 | 0.676017 | 3.992403 | false | false | false | false |
wangjianquan/wjq-weibo | weibo_wjq/Main/VisitorView/VisitorView.swift | 1 | 1411 | //
// VisitorView.swift
// weibo_wjq
//
// Created by landixing on 2017/5/23.
// Copyright © 2017年 WJQ. All rights reserved.
//
import UIKit
class VisitorView: UIView {
//加载xib文件的类方法
// MARK:- 提供快速通过xib创建的类方法
class func loadVisitorView() -> VisitorView {
return Bundle.main.loadNibNamed("VisitorView", owner: nil, options: nil)!.first as! VisitorView
}
//MARK: 控件属性
@IBOutlet var rotationView: UIImageView!
@IBOutlet var iconImgView: UIImageView!
@IBOutlet var tipLabel: UILabel!
@IBOutlet var registerBtn: UIButton!
@IBOutlet var loginBtn: UIButton!
// MARK:- 自定义函数
func setupVisitorViewInfo(iconName : String, title : String) {
iconImgView.image = UIImage(named: iconName)
tipLabel.text = title
rotationView.isHidden = true
}
func addRotationAnim() {
// 1.创建动画
let rotationAnim = CABasicAnimation(keyPath: "transform.rotation.z")
// 2.设置动画的属性
rotationAnim.fromValue = 0
rotationAnim.toValue = Double.pi * 2
rotationAnim.repeatCount = MAXFLOAT
rotationAnim.duration = 5
rotationAnim.isRemovedOnCompletion = false
// 3.将动画添加到layer中
rotationView.layer.add(rotationAnim, forKey: nil)
}
}
| apache-2.0 | 83e25bb6072261b27565f5a0d924f6e0 | 21.271186 | 103 | 0.633942 | 4.424242 | false | false | false | false |
leschlogl/Programming-Contests | Hackerrank/30 Days of Code/day8.swift | 1 | 399 | import Foundation
var qtyInput = Int(readLine()!)!
var i = 0
var map:[String:String] = [:]
while (i < qtyInput) {
let line = (readLine()!).components(separatedBy: " ")
let name = line[0]
let phone = line[1]
map[name] = phone
i+=1
}
while let line = readLine() {
if let phone = map[line] {
print("\(line)=\(phone)")
} else {
print("Not found")
}
}
| mit | 4800d479843d8a6d2c00f8b24c4dfa33 | 17.136364 | 57 | 0.546366 | 3.243902 | false | false | false | false |
xpush/lib-xpush-ios | XpushFramework/SocketConnector.swift | 1 | 6629 | //
// SocketConnector.swift
// XpushFramework
//
// Created by notdol on 8/30/15.
// Copyright (c) 2015 stalk. All rights reserved.
//
import Foundation
public class SocketConnector : Event{
var xpush:Xpush;
var socket:SocketIOClient?;
init(xpush:Xpush){
self.xpush = xpush;
}
func initWithServerInfo(info:JSON, cb:XpushNormalCallback? = nil)->Void{
let serverUrl:String = info[XpushConst.SESSION_SERVER_URL_KEY].string!;
//let token:String = info[XpushConst.TOKEN].string!; // deprecated before version
var serverId:String = info[XpushConst.SERVER].string!;
var parameters:[String:AnyObject] = [String:AnyObject]();
parameters["A"] = xpush.APP_ID;
parameters["U"] = xpush.USER_ID;
parameters["D"] = xpush.DEVICE_ID;
//parameters["TK"] = token;
connect(serverUrl,parameters: parameters,cb:cb);
}
func connect(url:String,parameters:[String:AnyObject],cb:XpushNormalCallback? = nil)->Void{
print("=== xpush : \(url + XpushConst.GLOBAL_NS)");
var params:[String:AnyObject] = [String:AnyObject]();
params["connectParams"] = parameters;
params["nsp"] = XpushConst.GLOBAL_NS;
params["log"] = true;
self.socket = SocketIOClient(socketURL: url,opts : params);
self.socket!.on("connect") {data, ack in
print("socket connected")
if cb != nil {
cb!(nil);
}
}
self.socket!.on("error") {data, ack in
print("socket error: \(data)");
}
self.socket!.on("disconnect") { data, ack in
print("socket disconnected");
}
self.socket!.connect()
}
func initSocket(socket:SocketIOClient)->Void{
socket.on(XpushConst.SS_GLOBAL_EVENT_KEY, callback:{ data , emitter in
var event:String = data[0][XpushConst.SS_EVENT_KEY] as! String;
switch event {
case "NOTIFICATION":
print("a");
case "CONNECT":
print("a");
case "DISCONNECT":
print("a");
case "LOGOUT":
print("a");
default:
print("a");
}
});
}
func emit(key:String, parameters:JSON?, cb:((data:JSON)->Void)? = nil)->Void{
if parameters == nil {
self.socket?.emitWithAck(key)(timeoutAfter: 0){ data in
print("===== emit success");
print(data[0] as! NSDictionary);
if cb != nil{
cb!(data: JSON(data[0]));
}
};
}
else {
self.socket?.emitWithAck(key, parameters!.rawValue)(timeoutAfter: 0){ data in
print("===== emit success");
print(data[0] as! NSDictionary);
if cb != nil{
cb!(data: JSON(data[0]));
}
};
}
}
func signup(userId:String, passwd:String, cb:(()->Void)? = nil)->Void{
}
func createChannel(channelName:String? = nil,var users:[String]? = nil,cb:((data:JSON)->Void)? = nil)->Void{
print("====== start create channel");
var params:JSON = ["A": xpush.APP_ID! /*, "C":"temp_channel"*//*, "U":"notdol"*/];
params["C"].string = channelName == nil ? nil : channelName!;
if(users == nil){
users = [xpush.USER_ID!];
}else{
users?.append(xpush.USER_ID!);
}
params["U"].arrayObject = users;
self.emit(XpushConst.SS_CHANNEL_CREATE, parameters: params, cb: { data in
print("===== channel created");
if cb != nil{
cb!(data: data);
}
});
}
func channelList(cb:((data:JSON)->Void)? = nil)->Void{
//let params:JSON = ["A": xpush.APP_ID!];
self.emit(XpushConst.SS_CHANNEL_LIST, parameters: nil, cb: { data in
print("===== channelList");
if cb != nil{
cb!(data: data);
}
});
}
func channelUpdate(channelName:String, q:String, cb:((data:JSON)->Void)? = nil)->Void{
let params:JSON = ["A": xpush.APP_ID!];
self.emit(XpushConst.SS_CHANNEL_UPDATE, parameters: params, cb: { data in
print("===== channelUpdate");
if cb != nil{
cb!(data: data);
}
});
}
func channelGet(channelName:String, cb:((data:JSON)->Void)? = nil)->Void{
let params:JSON = ["A": xpush.APP_ID!];
self.emit(XpushConst.SS_CHANNEL_GET, parameters: params, cb: { data in
print("===== channelGet");
if cb != nil{
cb!(data: data);
}
});
}
func channelExit(channelName:String,user:String, cb:((data:JSON)->Void)? = nil)->Void{
let params:JSON = ["A": xpush.APP_ID!];
self.emit(XpushConst.SS_CHANNEL_EXIT, parameters: params, cb: { data in
print("===== channelExit");
if cb != nil{
cb!(data: data);
}
});
}
func userList(cb:((data:JSON)->Void)? = nil)->Void{
let params:JSON = ["page": ["num": 1, "size" : 50 ]];
self.emit(XpushConst.SS_USER_LIST, parameters: params, cb: { data in
print("===== userList");
});
}
func userListQuery(query:String, columns:[String], cb:((data:JSON)->Void)? = nil)->Void{
let params:JSON = ["A": xpush.APP_ID!];
self.emit(XpushConst.SS_USER_QUERY, parameters: params, cb: { data in
print("===== userListQuery");
if cb != nil{
cb!(data: data);
}
});
}
func messageUnread(cb:((data:JSON)->Void)? = nil)->Void{
let params:JSON = ["A": xpush.APP_ID!,"U": xpush.USER_ID!, "D":xpush.DEVICE_ID!];
self.emit(XpushConst.SS_MESSAGE_UNREAD, parameters: params, cb: { data in
print("===== messageUnread");
if cb != nil{
cb!(data: data);
}
});
}
func messageReceived(cb:((data:JSON)->Void)? = nil)->Void{
let params:JSON = ["A": xpush.APP_ID!,"U": xpush.USER_ID!, "D":xpush.DEVICE_ID!];
self.emit(XpushConst.SS_MESSAGE_RECEIVED, parameters: params, cb: { data in
print("===== messageReceived");
if cb != nil{
cb!(data: data);
}
});
}
} | mit | 9075f2c2b70168b9a098421d2de92f19 | 31.5 | 112 | 0.49555 | 4.00786 | false | false | false | false |
tdquang/CarlWrite | CVCalendar/CVCalendarViewAnimator.swift | 1 | 4218 | //
// CVCalendarViewAnimator.swift
// CVCalendar
//
// Created by E. Mozharovsky on 12/27/14.
// Copyright (c) 2014 GameApp. All rights reserved.
//
import UIKit
class CVCalendarViewAnimator {
private unowned let calendarView: CalendarView
// MARK: - Public properties
var delegate: CVCalendarViewAnimatorDelegate!
var coordinator: CVCalendarDayViewControlCoordinator {
get {
return calendarView.coordinator
}
}
// MARK: - Init
init(calendarView: CalendarView) {
self.calendarView = calendarView
delegate = self
}
}
// MARK: - Public methods
extension CVCalendarViewAnimator {
func animateSelectionOnDayView(dayView: DayView) {
let selectionAnimation = delegate.selectionAnimation()
dayView.setSelectedWithType(.Single)
selectionAnimation(dayView) { [unowned dayView] _ in
// Something...
}
}
func animateDeselectionOnDayView(dayView: DayView) {
let deselectionAnimation = delegate.deselectionAnimation()
deselectionAnimation(dayView) { [weak dayView] _ in
if let selectedDayView = dayView {
self.coordinator.deselectionPerformedOnDayView(selectedDayView)
}
}
}
}
// MARK: - CVCalendarViewAnimatorDelegate
extension CVCalendarViewAnimator: CVCalendarViewAnimatorDelegate {
@objc func selectionAnimation() -> ((DayView, ((Bool) -> ())) -> ()) {
return selectionWithBounceEffect()
}
@objc func deselectionAnimation() -> ((DayView, ((Bool) -> ())) -> ()) {
return deselectionWithFadeOutEffect()
}
}
// MARK: - Default animations
private extension CVCalendarViewAnimator {
func selectionWithBounceEffect() -> ((DayView, ((Bool) -> ())) -> ()) {
return {
dayView, completion in
dayView.dayLabel?.transform = CGAffineTransformMakeScale(0.5, 0.5)
dayView.circleView?.transform = CGAffineTransformMakeScale(0.5, 0.5)
UIView.animateWithDuration(0.5, delay: 0, usingSpringWithDamping: 0.3, initialSpringVelocity: 0.1, options: UIViewAnimationOptions.BeginFromCurrentState, animations: {
dayView.circleView?.transform = CGAffineTransformMakeScale(1, 1)
dayView.dayLabel?.transform = CGAffineTransformMakeScale(1, 1)
}, completion: completion)
}
}
func deselectionWithBubbleEffect() -> ((DayView, ((Bool) -> ())) -> ()) {
return {
dayView, completion in
UIView.animateWithDuration(0.15, delay: 0, usingSpringWithDamping: 0.6, initialSpringVelocity: 0.8, options: UIViewAnimationOptions.CurveEaseOut, animations: {
dayView.circleView!.transform = CGAffineTransformMakeScale(1.3, 1.3)
}) { _ in
UIView.animateWithDuration(0.2, delay: 0, options: UIViewAnimationOptions.CurveEaseInOut, animations: {
if let circleView = dayView.circleView {
circleView.transform = CGAffineTransformMakeScale(0.1, 0.1)
}
}, completion: completion)
}
}
}
func deselectionWithFadeOutEffect() -> ((DayView, ((Bool) -> ())) -> ()) {
return {
dayView, completion in
UIView.animateWithDuration(0.6, delay: 0, usingSpringWithDamping: 0.6, initialSpringVelocity: 0, options: [], animations: {
dayView.setDeselectedWithClearing(false) // return labels' defaults while circle view disappearing
if let circleView = dayView.circleView {
circleView.alpha = 0
}
}, completion: completion)
}
}
func deselectionWithRollingEffect() -> ((DayView, ((Bool) -> ())) -> ()) {
return {
dayView, completion in
UIView.animateWithDuration(0.25, delay: 0, options: UIViewAnimationOptions.CurveEaseInOut, animations: { () -> Void in
dayView.circleView?.transform = CGAffineTransformMakeScale(0.1, 0.1)
dayView.circleView?.alpha = 0.0
}, completion: completion)
}
}
}
| mit | 6c844788eba010cc323f937fc3e2d58b | 35.678261 | 179 | 0.616406 | 5.137637 | false | false | false | false |
lyft/SwiftLint | Source/SwiftLintFramework/Rules/ValidIBInspectableRule.swift | 1 | 4760 | import Foundation
import SourceKittenFramework
public struct ValidIBInspectableRule: ASTRule, ConfigurationProviderRule {
public var configuration = SeverityConfiguration(.warning)
private static let supportedTypes = ValidIBInspectableRule.createSupportedTypes()
public init() {}
public static let description = RuleDescription(
identifier: "valid_ibinspectable",
name: "Valid IBInspectable",
description: "@IBInspectable should be applied to variables only, have its type explicit " +
"and be of a supported type",
kind: .lint,
nonTriggeringExamples: [
"class Foo {\n @IBInspectable private var x: Int\n}\n",
"class Foo {\n @IBInspectable private var x: String?\n}\n",
"class Foo {\n @IBInspectable private var x: String!\n}\n",
"class Foo {\n @IBInspectable private var count: Int = 0\n}\n",
"class Foo {\n private var notInspectable = 0\n}\n",
"class Foo {\n private let notInspectable: Int\n}\n",
"class Foo {\n private let notInspectable: UInt8\n}\n"
],
triggeringExamples: [
"class Foo {\n @IBInspectable private ↓let count: Int\n}\n",
"class Foo {\n @IBInspectable private ↓var insets: UIEdgeInsets\n}\n",
"class Foo {\n @IBInspectable private ↓var count = 0\n}\n",
"class Foo {\n @IBInspectable private ↓var count: Int?\n}\n",
"class Foo {\n @IBInspectable private ↓var count: Int!\n}\n",
"class Foo {\n @IBInspectable private ↓var x: ImplicitlyUnwrappedOptional<Int>\n}\n",
"class Foo {\n @IBInspectable private ↓var count: Optional<Int>\n}\n",
"class Foo {\n @IBInspectable private ↓var x: Optional<String>\n}\n",
"class Foo {\n @IBInspectable private ↓var x: ImplicitlyUnwrappedOptional<String>\n}\n"
]
)
public func validate(file: File, kind: SwiftDeclarationKind,
dictionary: [String: SourceKitRepresentable]) -> [StyleViolation] {
guard kind == .varInstance else {
return []
}
// Check if IBInspectable
let isIBInspectable = dictionary.enclosedSwiftAttributes.contains(.ibinspectable)
guard isIBInspectable else {
return []
}
let shouldMakeViolation: Bool
if dictionary.setterAccessibility == nil {
// if key.setter_accessibility is nil, it's a `let` declaration
shouldMakeViolation = true
} else if let type = dictionary.typeName,
ValidIBInspectableRule.supportedTypes.contains(type) {
shouldMakeViolation = false
} else {
// Variable should have explicit type or IB won't recognize it
// Variable should be of one of the supported types
shouldMakeViolation = true
}
guard shouldMakeViolation else {
return []
}
let location: Location
if let offset = dictionary.offset {
location = Location(file: file, byteOffset: offset)
} else {
location = Location(file: file.path)
}
return [
StyleViolation(ruleDescription: type(of: self).description,
severity: configuration.severity,
location: location)
]
}
private static func createSupportedTypes() -> [String] {
// "You can add the IBInspectable attribute to any property in a class declaration,
// class extension, or category of type: boolean, integer or floating point number, string,
// localized string, rectangle, point, size, color, range, and nil."
//
// from http://help.apple.com/xcode/mac/8.0/#/devf60c1c514
let referenceTypes = [
"String",
"NSString",
"UIColor",
"NSColor",
"UIImage",
"NSImage"
]
let types = [
"CGFloat",
"Float",
"Double",
"Bool",
"CGPoint",
"NSPoint",
"CGSize",
"NSSize",
"CGRect",
"NSRect"
]
let intTypes: [String] = ["", "8", "16", "32", "64"].flatMap { size in
["U", ""].map { (sign: String) -> String in
"\(sign)Int\(size)"
}
}
let expandToIncludeOptionals: (String) -> [String] = { [$0, $0 + "!", $0 + "?"] }
// It seems that only reference types can be used as ImplicitlyUnwrappedOptional or Optional
return referenceTypes.flatMap(expandToIncludeOptionals) + types + intTypes
}
}
| mit | dd600ca3824b82f67036498a4576f5dd | 37.868852 | 100 | 0.570856 | 4.775428 | false | false | false | false |
artemkalinovsky/PhotoMemories | PhotoMemoriesTests/ModelTests/PhotoMemoryTests.swift | 1 | 1508 | //
// PhotoMemoryTests.swift
// PhotoMemories
//
// Created by Artem Kalinovsky on 8/17/16.
// Copyright © 2016 Artem Kalinovsky. All rights reserved.
//
import XCTest
import JASON
@testable import PhotoMemories
class PhotoMemoryTests: XCTestCase {
override func setUp() {
super.setUp()
}
override func tearDown() {
super.tearDown()
}
func testPhotoMemoryInitWithJson() {
let testUid = "-KPHRbCW2cprj39wVA5p"
let json = JSON([
"comment" : "There are no comments yet.",
"date" : 1471335764,
"photoPath" : "https://firebasestorage.googleapis.com/v0/b/photomemories-e761c.appspot.com/o/images%2F98F34606-11BB-4ADC-BDA0-96F01EA95812.png?alt=media&token=7d184021-73bd-4126-a4ed-009967fb8c22",
"privacy" : 0,
"title" : "Unnamed",
"userUid" : "FbsgoVjH49RxJwrhUBxidWaFWAw2"])
let photoMemory = PhotoMemory(uId: testUid, json: json)
XCTAssertEqual(testUid, photoMemory.uid!)
XCTAssertEqual(json["title"].stringValue, photoMemory.title!)
XCTAssertEqual(json["comment"].stringValue, photoMemory.comment!)
XCTAssertEqual(json["photoPath"].stringValue, photoMemory.photoPath!)
XCTAssertEqual(json["userUid"].stringValue, photoMemory.userUid!)
XCTAssertEqual(json["privacy"].intValue, photoMemory.privacy!.integerValue)
XCTAssertEqual(json["date"].intValue, Int(photoMemory.date!.timeIntervalSince1970))
}
}
| gpl-2.0 | 6c8f2a29dc36b9b7e2108fcccc6caa97 | 33.25 | 209 | 0.668215 | 3.588095 | false | true | false | false |
RocketChat/Rocket.Chat.iOS | Rocket.Chat/Views/Chat/New Chat/Cells/DateSeparatorCell.swift | 1 | 1497 | //
// DateSeparatorCell.swift
// Rocket.Chat
//
// Created by Rafael Streit on 26/09/18.
// Copyright © 2018 Rocket.Chat. All rights reserved.
//
import UIKit
import RocketChatViewController
final class DateSeparatorCell: UICollectionViewCell, ChatCell, SizingCell {
static let identifier = String(describing: DateSeparatorCell.self)
static let sizingCell: UICollectionViewCell & ChatCell = {
guard let cell = DateSeparatorCell.instantiateFromNib() else {
return DateSeparatorCell()
}
return cell
}()
@IBOutlet weak var leftLine: UIView!
@IBOutlet weak var date: UILabel! {
didSet {
date.font = date.font.bold()
}
}
@IBOutlet weak var rightLine: UIView!
var messageWidth: CGFloat = 0
var viewModel: AnyChatItem?
func configure(completeRendering: Bool) {
guard
completeRendering,
let viewModel = viewModel?.base as? DateSeparatorChatItem
else {
return
}
date.text = viewModel.dateFormatted
}
override func prepareForReuse() {
super.prepareForReuse()
date.text = ""
}
}
// MARK: Theming
extension DateSeparatorCell {
override func applyTheme() {
super.applyTheme()
let theme = self.theme ?? .light
date.textColor = theme.auxiliaryText
leftLine.backgroundColor = theme.borderColor
rightLine.backgroundColor = theme.borderColor
}
}
| mit | 642bb6f3e299f55afc1a1b9291831983 | 21.666667 | 75 | 0.639037 | 4.779553 | false | false | false | false |
khizkhiz/swift | test/SILOptimizer/let_propagation.swift | 4 | 7532 | // RUN: %target-swift-frontend -primary-file %s -emit-sil -O | FileCheck %s
// Check that LoadStoreOpts can handle "let" variables properly.
// Such variables should be loaded only once and their loaded values can be reused.
// This is safe, because once assigned, these variables cannot change their value.
// Helper function, which models an external functions with unknown side-effects.
// It is called just to trigger flushing of all known stored in LoadStore optimizations.
@inline(never)
func action() {
print("")
}
final public class A0 {
let x: Int32
let y: Int32
init(_ x: Int32, _ y: Int32) {
self.x = x
self.y = y
}
@inline(never)
func sum1() -> Int32 {
// x and y should be loaded only once.
let n = x + y
action()
let m = x - y
action()
let p = x - y + 1
return n + m + p
}
func sum2() -> Int32 {
// x and y should be loaded only once.
let n = x + y
action()
let m = x - y
action()
let p = x - y + 1
return n + m + p
}
}
/*
// DISABLE THIS TEST CASE FOR NOW. AS RLE GETS BETTER. WILL RE-ENABLE.
//
// Check that counter computation is completely evaluated
// at compile-time, because the value of a.x and a.y are known
// from the initializer and propagated into their uses, because
// we know that action() invocations do not affect their values.
//
// DISABLECHECK-LABEL: sil {{.*}}testAllocAndUseLet
// DISABLECHECK: bb0
// DISABLECHECK-NOT: ref_element_addr
// DISABLECHECK-NOT: struct_element_addr
// DISABLECHECK-NOT: bb1
// DISABLECHECK: function_ref @_TF15let_propagation6actionFT_T_
// DISABLECHECK: apply
// DISABLECHECK: apply
// DISABLECHECK: apply
// DISABLECHECK: apply
// DISABLECHECK: apply
// DISABLECHECK: apply
// DISABLECHECK: apply
// DISABLECHECK: apply
// DISABLECHECK: integer_literal $Builtin.Int32, 36
// DISABLECHECK-NEXT: struct $Int32 ({{.*}} : $Builtin.Int32)
// DISABLECHECK-NEXT: return
@inline(never)
public func testAllocAndUseLet() -> Int32 {
let a = A0(3, 1)
var counter: Int32
// a.x and a.y should be loaded only once.
counter = a.sum2() + a.sum2()
counter += a.sum2() + a.sum2()
return counter
}
*/
/*
// DISABLE THIS TEST CASE FOR NOW. AS RLE GETS BETTER. WILL RE-ENABLE.
//
// Check that a.x and a.y are loaded only once and then reused.
// DISABLECHECK-LABEL: sil {{.*}}testUseLet
// DISABLECHECK: bb0
// DISABLECHECK: ref_element_addr
// DISABLECHECK: struct_element_addr
// DISABLECHECK: load
// DISABLECHECK: ref_element_addr
// DISABLECHECK: struct_element_addr
// DISABLECHECK: load
// DISABLECHECK-NOT: bb1
// DISABLECHECK-NOT: ref_element_addr
// DISABLECHECK-NOT: struct_element_addr
// DISABLECHECK-NOT: load
// DISABLECHECK: return
@inline(never)
public func testUseLet(a:A0) -> Int32 {
var counter: Int32
// a.x and a.y should be loaded only once.
counter = a.sum2() + a.sum2()
counter += a.sum2() + a.sum2()
return counter
}
*/
struct Goo {
var x: Int32
var y: Int32
}
struct Foo {
var g: Goo
}
struct Bar {
let f: Foo
var h: Foo
@inline(never)
mutating func action() {
}
}
@inline(never)
func getVal() -> Int32 {
return 9
}
// Global let
let gx: Int32 = getVal()
let gy: Int32 = getVal()
func sum3() -> Int32 {
// gx and gy should be loaded only once.
let n = gx + gy
action()
let m = gx - gy
action()
let p = gx - gy + 1
return n + m + p
}
/*
// DISABLE THIS TEST CASE FOR NOW. AS RLE GETS BETTER. WILL RE-ENABLE.
//
// Check that gx and gy are loaded only once and then reused.
// DISABLECHECK-LABEL: sil {{.*}}testUseGlobalLet
// DISABLECHECK: bb0
// DISABLECHECK: global_addr @_Tv15let_propagation2gyVs5Int32
// DISABLECHECK: global_addr @_Tv15let_propagation2gxVs5Int32
// DISABLECHECK: struct_element_addr
// DISABLECHECK: load
// DISABLECHECK: struct_element_addr
// DISABLECHECK: load
// DISABLECHECK-NOT: bb1
// DISABLECHECK-NOT: global_addr
// DISABLECHECK-NOT: ref_element_addr
// DISABLECHECK-NOT: struct_element_addr
// DISABLECHECK-NOT: load
// DISABLECHECK: return
@inline(never)
public func testUseGlobalLet() -> Int32 {
var counter: Int32 = 0
// gx and gy should be loaded only once.
counter = sum3() + sum3() + sum3() + sum3()
return counter
}
*/
struct A1 {
let x: Int32
// Propagate the value of the initializer into all instructions
// that use it, which in turn would allow for better constant
// propagation.
let y: Int32 = 100
init(v: Int32) {
if v > 0 {
x = 1
} else {
x = -1
}
}
// CHECK-LABEL: sil hidden @_TFV15let_propagation2A12f1
// CHECK: bb0
// CHECK: struct_extract {{.*}}#A1.x
// CHECK: struct_extract {{.*}}#Int32._value
// CHECK-NOT: load
// CHECK-NOT: struct_extract
// CHECK-NOT: struct_element_addr
// CHECK-NOT: ref_element_addr
// CHECK-NOT: bb1
// CHECK: return
func f1() -> Int32 {
// x should be loaded only once.
return x + x
}
// CHECK-LABEL: sil hidden @_TFV15let_propagation2A12f2
// CHECK: bb0
// CHECK: integer_literal $Builtin.Int32, 200
// CHECK-NEXT: struct $Int32
// CHECK-NEXT: return
func f2() -> Int32 {
// load y only once.
return y + y
}
}
class A2 {
let x: B2 = B2()
// CHECK-LABEL: sil hidden @_TFC15let_propagation2A22af
// bb0
// CHECK: %[[X:[0-9]+]] = ref_element_addr {{.*}}A2.x
// CHECK-NEXT: load %[[X]]
// CHECK: ref_element_addr {{.*}}B2.i
// CHECK: %[[XI:[0-9]+]] = struct_element_addr {{.*}}#Int32._value
// CHECK-NEXT: load %[[XI]]
// return
func af() -> Int32 {
// x and x.i should be loaded only once.
return x.f() + x.f()
}
}
final class B2 {
var i: Int32 = 10
func f() -> Int32 {
return i
}
}
@inline(never)
func oops() {
}
struct S {
let elt : Int32
}
// Check that we can handle reassignments to a variable
// of struct type properly.
// CHECK-LABEL: sil {{.*}}testStructWithLetElement
// CHECK-NOT: function_ref @{{.*}}oops
// CHECK: return
public func testStructWithLetElement() -> Int32 {
var someVar = S(elt: 12)
let tmp1 = someVar.elt
someVar = S(elt: 15)
let tmp2 = someVar.elt
// This check should get eliminated
if (tmp2 == tmp1) {
// If we get here, the compiler has propagated
// the old value someVar.elt into tmp2, which
// is wrong.
oops()
}
return tmp1+tmp2
}
public typealias Tuple3 = (Int32, Int32, Int32)
final public class S3 {
let x: Tuple3
var y: Tuple3
init(x: Tuple3, y:Tuple3) {
self.x = x
self.y = y
}
}
/*
// DISABLE THIS TEST CASE FOR NOW. AS RLE GETS BETTER. WILL RE-ENABLE.
//
// Check that s.x.0 is loaded only once and then reused.
// DISABLECHECK-LABEL: sil {{.*}}testLetTuple
// DISABLECHECK: tuple_element_addr
// DISABLECHECK: %[[X:[0-9]+]] = struct_element_addr
// DISABLECHECK: load %[[X]]
// DISABLECHECK-NOT: load %[[X]]
// DISABLECHECK: return
public func testLetTuple(s: S3) -> Int32 {
var counter: Int32 = 0
counter += s.x.0
action()
counter += s.x.0
action()
counter += s.x.0
action()
counter += s.x.0
action()
return counter
}
*/
// Check that s.x.0 is reloaded every time.
// CHECK-LABEL: sil {{.*}}testVarTuple
// CHECK: tuple_element_addr
// CHECK: %[[X:[0-9]+]] = struct_element_addr
// CHECK: load %[[X]]
// CHECK: load %[[X]]
// CHECK: load %[[X]]
// CHECK: load %[[X]]
// CHECK: return
public func testVarTuple(s: S3) -> Int32 {
var counter: Int32 = 0
counter += s.y.0
action()
counter += s.y.0
action()
counter += s.y.0
action()
counter += s.y.0
action()
return counter
}
| apache-2.0 | 8a37c0822bc8e8a235072c5ed76a8a00 | 21.550898 | 88 | 0.638609 | 3.086885 | false | false | false | false |
mitochrome/complex-gestures-demo | apps/GestureRecognizer/Carthage/Checkouts/RxSwift/RxExample/RxExample/Operators.swift | 5 | 3360 | //
// Operators.swift
// RxExample
//
// Created by Krunoslav Zaher on 12/6/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
#if !RX_NO_MODULE
import RxSwift
import RxCocoa
#endif
import UIKit
// Two way binding operator between control property and variable, that's all it takes {
infix operator <-> : DefaultPrecedence
func nonMarkedText(_ textInput: UITextInput) -> String? {
let start = textInput.beginningOfDocument
let end = textInput.endOfDocument
guard let rangeAll = textInput.textRange(from: start, to: end),
let text = textInput.text(in: rangeAll) else {
return nil
}
guard let markedTextRange = textInput.markedTextRange else {
return text
}
guard let startRange = textInput.textRange(from: start, to: markedTextRange.start),
let endRange = textInput.textRange(from: markedTextRange.end, to: end) else {
return text
}
return (textInput.text(in: startRange) ?? "") + (textInput.text(in: endRange) ?? "")
}
func <-> <Base>(textInput: TextInput<Base>, variable: Variable<String>) -> Disposable {
let bindToUIDisposable = variable.asObservable()
.bind(to: textInput.text)
let bindToVariable = textInput.text
.subscribe(onNext: { [weak base = textInput.base] n in
guard let base = base else {
return
}
let nonMarkedTextValue = nonMarkedText(base)
/**
In some cases `textInput.textRangeFromPosition(start, toPosition: end)` will return nil even though the underlying
value is not nil. This appears to be an Apple bug. If it's not, and we are doing something wrong, please let us know.
The can be reproed easily if replace bottom code with
if nonMarkedTextValue != variable.value {
variable.value = nonMarkedTextValue ?? ""
}
and you hit "Done" button on keyboard.
*/
if let nonMarkedTextValue = nonMarkedTextValue, nonMarkedTextValue != variable.value {
variable.value = nonMarkedTextValue
}
}, onCompleted: {
bindToUIDisposable.dispose()
})
return Disposables.create(bindToUIDisposable, bindToVariable)
}
func <-> <T>(property: ControlProperty<T>, variable: Variable<T>) -> Disposable {
if T.self == String.self {
#if DEBUG
fatalError("It is ok to delete this message, but this is here to warn that you are maybe trying to bind to some `rx.text` property directly to variable.\n" +
"That will usually work ok, but for some languages that use IME, that simplistic method could cause unexpected issues because it will return intermediate results while text is being inputed.\n" +
"REMEDY: Just use `textField <-> variable` instead of `textField.rx.text <-> variable`.\n" +
"Find out more here: https://github.com/ReactiveX/RxSwift/issues/649\n"
)
#endif
}
let bindToUIDisposable = variable.asObservable()
.bind(to: property)
let bindToVariable = property
.subscribe(onNext: { n in
variable.value = n
}, onCompleted: {
bindToUIDisposable.dispose()
})
return Disposables.create(bindToUIDisposable, bindToVariable)
}
// }
| mit | b2df25c0911499515d27f247e5584b89 | 33.628866 | 207 | 0.640965 | 4.551491 | false | false | false | false |
jeffreybergier/Hipstapaper | Hipstapaper/Packages/V3Localize/Sources/V3Localize/Raw/Symbols.swift | 1 | 4932 | //
// Created by Jeffrey Bergier on 2022/06/17.
//
// MIT License
//
// Copyright (c) 2021 Jeffrey Bergier
//
// 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.
//
internal enum Symbol: String {
case tag = "tag"
case plus = "plus"
case website = "doc.text.image"
case openInApp = "safari"
case openExternal = "safari.fill"
case archiveYes = "tray.and.arrow.down"
case archiveNo = "tray.and.arrow.up"
case filterYes = "line.horizontal.3.decrease.circle.fill"
case filterNo = "line.horizontal.3.decrease.circle"
case sort = "arrow.up.arrow.down.circle"
case share = "square.and.arrow.up"
case shareMulti = "square.and.arrow.up.on.square"
case shareError = "square.and.arrow.up.trianglebadge.exclamationmark"
case deleteMinus = "minus"
case deleteTrash = "trash"
case editPencil = "rectangle.and.pencil.and.ellipsis"
case document = "doc.richtext"
case documentFill = "doc.richtext.fill"
case calendar = "calendar.circle"
case calendarFill = "calendar.circle.fill"
case errorGeneric = "exclamationmark.triangle"
case browseBack = "chevron.backward"
case browseForward = "chevron.forward"
case browseReload = "arrow.clockwise"
case browseStop = "xmark"
case javascriptYes = "applescript.fill"
case javascriptNo = "applescript"
case magic = "wand.and.stars"
case minusRectangle = "rectangle.badge.minus"
case checkmark = "checkmark"
case photo = "photo"
case rectangleSlash = "rectangle.on.rectangle.slash"
case tagSlash = "tag.slash"
case iCloudSync = "arrow.clockwise.icloud"
case columnGeneric = "building.columns"
case columnCircleFill = "building.columns.circle.fill"
case columnCircleEmpty = "building.columns.circle"
case tableCellsFill = "tablecells.fill"
case tableCellsEmpty = "tablecells"
case circleGrid = "circle.grid.2x2"
case paperclip = "paperclip"
case menu = "filemenu.and.selection"
}
/*
extension STZ {
public enum ICN: String, View {
public var body: Image { Image(systemName: self.rawValue) }
case share = "square.and.arrow.up"
case unarchive = "tray.and.arrow.up"
case archive = "tray.and.arrow.down"
case openInBrowser = "safari.fill"
case openInApp = "safari"
case filterActive = "line.horizontal.3.decrease.circle.fill"
case filterInactive = "line.horizontal.3.decrease.circle"
case stop = "xmark"
case reload = "arrow.clockwise"
case jsActive = "applescript.fill"
case jsInactive = "applescript"
case goBack = "chevron.backward"
case goForward = "chevron.forward"
case deleteMinus = "minus"
case deleteTrash = "trash"
case editPencil = "rectangle.and.pencil.and.ellipsis"
case clearSearch = "xmark.circle"
case cloudError = "exclamationmark.icloud"
case cloudSyncSuccess = "checkmark.icloud"
case cloudSyncInProgress = "arrow.clockwise.icloud"
case cloudAccountError = "icloud.slash"
case tag = "tag"
case searchInactive = "magnifyingglass"
case searchActive = "magnifyingglass.circle.fill"
case sort = "arrow.up.arrow.down.circle"
case addPlus = "plus"
case web = "globe"
case bug = "ladybug"
case placeholder = "photo"
case sortTitleA = "doc.richtext"
case sortTitleZ = "doc.richtext.fill"
case sortDateNewest = "calendar.circle"
case sortDateOldest = "calendar.circle.fill"
}
}
*/
| mit | b0fd91048461b26f335f3e16688c790e | 43.035714 | 82 | 0.638889 | 4.042623 | false | false | false | false |
Darren-chenchen/yiyiTuYa | testDemoSwift/Category/UIView+Frame.swift | 1 | 2820 | //
// UIView+Frame.swift
// CLKuGou_Swift
//
// Created by Darren on 16/8/6.
// Copyright © 2016年 darren. All rights reserved.
//
import UIKit
extension UIView {
/// 裁剪 view 的圆角
func clipRectCorner(_ direction: UIRectCorner, cornerRadius: CGFloat) {
let cornerSize = CGSize(width: cornerRadius, height: cornerRadius)
let maskPath = UIBezierPath(roundedRect: bounds, byRoundingCorners: direction, cornerRadii: cornerSize)
let maskLayer = CAShapeLayer()
maskLayer.frame = bounds
maskLayer.path = maskPath.cgPath
layer.addSublayer(maskLayer)
layer.mask = maskLayer
}
/// 设置view圆角
func CLViewsBorder(view:UIView, borderWidth:CGFloat, borderColor:UIColor,cornerRadius:CGFloat){
view.layer.borderWidth = 1;
view.layer.borderColor = borderColor.cgColor
view.layer.cornerRadius = cornerRadius
view.layer.masksToBounds = true
}
/// x
var cl_x: CGFloat {
get {
return frame.origin.x
}
set(newValue) {
var tempFrame: CGRect = frame
tempFrame.origin.x = newValue
frame = tempFrame
}
}
/// y
var cl_y: CGFloat {
get {
return frame.origin.y
}
set(newValue) {
var tempFrame: CGRect = frame
tempFrame.origin.y = newValue
frame = tempFrame
}
}
/// height
var cl_height: CGFloat {
get {
return frame.size.height
}
set(newValue) {
var tempFrame: CGRect = frame
tempFrame.size.height = newValue
frame = tempFrame
}
}
/// width
var cl_width: CGFloat {
get {
return frame.size.width
}
set(newValue) {
var tempFrame: CGRect = frame
tempFrame.size.width = newValue
frame = tempFrame
}
}
/// size
var cl_size: CGSize {
get {
return frame.size
}
set(newValue) {
var tempFrame: CGRect = frame
tempFrame.size = newValue
frame = tempFrame
}
}
/// centerX
var cl_centerX: CGFloat {
get {
return center.x
}
set(newValue) {
var tempCenter: CGPoint = center
tempCenter.x = newValue
center = tempCenter
}
}
/// centerY
var cl_centerY: CGFloat {
get {
return center.y
}
set(newValue) {
var tempCenter: CGPoint = center
tempCenter.y = newValue
center = tempCenter;
}
}
}
| apache-2.0 | 6686630b57f7af3e8331e61fd0b32f6b | 23.33913 | 111 | 0.511611 | 4.893357 | false | false | false | false |
WCByrne/CBToolkit | CBApp/CBApp/LoadersCell.swift | 1 | 3791 | //
// LoadersCell.swift
// CBApp
//
// Created by Wes Byrne on 9/7/15.
// Copyright (c) 2015 Type2Designs. All rights reserved.
//
import Foundation
import UIKit
import CBToolkit
class LoadersCell : UICollectionViewCell {
@IBOutlet weak var activityIndicator: CBActivityIndicator!
@IBOutlet weak var progressView: CBProgressView!
@IBOutlet weak var uploadButtonView: CBButtonView!
@IBOutlet weak var progressCompleteImageView: CBImageView!
var progress : CGFloat! = 0
override func awakeFromNib() {
super.awakeFromNib()
self.progressCompleteImageView.alpha = 0
self.progressCompleteImageView.transform = CGAffineTransform(scaleX: 0, y: 0)
}
@IBAction func toggleActivityIndicator(_ sender: CBButton) {
if activityIndicator.animating {
activityIndicator.stopAnimating()
sender.setTitle("Start", for: UIControlState.normal)
sender.tintColor = UIColor.white
}
else {
activityIndicator.startAnimating()
sender.setTitle("Stop", for: UIControlState.normal)
sender.tintColor = UIColor.red
}
}
@IBAction func updateActivityWidth(_ sender: UISlider) {
activityIndicator.lineWidth = CGFloat(sender.value)
activityIndicator.layoutSubviews()
}
@IBAction func updateActivtySize(_ sender: UISlider) {
activityIndicator.indicatorSize = CGFloat(sender.value)
}
@IBAction func updateActivtySpeed(_ sender: UISlider) {
activityIndicator.rotateDuration = CGFloat(sender.value)
}
@IBAction func updateActivityTrackColor(_ sender: UISlider) {
self.activityIndicator.trackColor = UIColor(white: 0, alpha: CGFloat(sender.value))
}
@IBAction func progressButtonSelected(_ sender: CBButtonView) {
if progress == 0 {
progressView.setProgress(0, animated: false)
progressView.setLineWidth(10, animated: true)
progressView.setProgress(0.05, animated: true)
self.uploadButtonView.isEnabled = false
self.incrementProgress()
}
}
func finishProgress() {
self.uploadButtonView.popAnimation()
self.progressView.setLineWidth(0, animated: true)
self.progress = 0
self.uploadButtonView.isEnabled = true
self.progressCompleteImageView.transform = CGAffineTransform(scaleX: 0, y: 0)
UIView.animate(withDuration: 0.4, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 0, options: UIViewAnimationOptions.curveEaseOut, animations: { () -> Void in
self.progressCompleteImageView.alpha = 1
self.progressCompleteImageView.transform = CGAffineTransform(scaleX: 1, y: 1)
}) { (fin) -> Void in
let delayTime = DispatchTime.now() + Double(Int64(1 * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC)
DispatchQueue.main.asyncAfter(deadline: delayTime) {
UIView.animate(withDuration: 0.5, animations: { () -> Void in
self.progressCompleteImageView.alpha = 0
})
return
}
}
}
func incrementProgress() {
let delayTime = DispatchTime.now() + Double(Int64(0.2 * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC)
DispatchQueue.main.asyncAfter(deadline: delayTime) {
self.progress = self.progress + 0.1
if self.progress >= 1 { self.progress = 1 }
self.progressView.setProgress(self.progress, animated: true)
if self.progress == 1 {
self.finishProgress()
}
else {
self.incrementProgress()
}
}
}
}
| mit | ab08c48199dc949b0f3c20b8bdbb4416 | 35.104762 | 178 | 0.62833 | 4.829299 | false | false | false | false |
icecrystal23/ios-charts | ChartsDemo-iOS/Swift/Demos/RadarChartViewController.swift | 1 | 6976 | //
// RadarChartViewController.swift
// ChartsDemo-iOS
//
// Created by Jacob Christie on 2017-07-09.
// Copyright © 2017 jc. All rights reserved.
//
import UIKit
import Charts
class RadarChartViewController: DemoBaseViewController {
@IBOutlet var chartView: RadarChartView!
let activities = ["Burger", "Steak", "Salad", "Pasta", "Pizza"]
var originalBarBgColor: UIColor!
var originalBarTintColor: UIColor!
var originalBarStyle: UIBarStyle!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.title = "Radar Chart"
self.options = [.toggleValues,
.toggleHighlight,
.toggleHighlightCircle,
.toggleXLabels,
.toggleYLabels,
.toggleRotate,
.toggleFilled,
.animateX,
.animateY,
.animateXY,
.spin,
.saveToGallery,
.toggleData]
chartView.delegate = self
chartView.chartDescription?.enabled = false
chartView.webLineWidth = 1
chartView.innerWebLineWidth = 1
chartView.webColor = .lightGray
chartView.innerWebColor = .lightGray
chartView.webAlpha = 1
let marker = RadarMarkerView.viewFromXib()!
marker.chartView = chartView
chartView.marker = marker
let xAxis = chartView.xAxis
xAxis.labelFont = .systemFont(ofSize: 9, weight: .light)
xAxis.xOffset = 0
xAxis.yOffset = 0
xAxis.valueFormatter = self
xAxis.labelTextColor = .white
let yAxis = chartView.yAxis
yAxis.labelFont = .systemFont(ofSize: 9, weight: .light)
yAxis.labelCount = 5
yAxis.axisMinimum = 0
yAxis.axisMaximum = 80
yAxis.drawLabelsEnabled = false
let l = chartView.legend
l.horizontalAlignment = .center
l.verticalAlignment = .top
l.orientation = .horizontal
l.drawInside = false
l.font = .systemFont(ofSize: 10, weight: .light)
l.xEntrySpace = 7
l.yEntrySpace = 5
l.textColor = .white
// chartView.legend = l
self.updateChartData()
chartView.animate(xAxisDuration: 1.4, yAxisDuration: 1.4, easingOption: .easeOutBack)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
UIView.animate(withDuration: 0.15) {
let navBar = self.navigationController!.navigationBar
self.originalBarBgColor = navBar.barTintColor
self.originalBarTintColor = navBar.tintColor
self.originalBarStyle = navBar.barStyle
navBar.barTintColor = self.view.backgroundColor
navBar.tintColor = .white
navBar.barStyle = .black
}
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
UIView.animate(withDuration: 0.15) {
let navBar = self.navigationController!.navigationBar
navBar.barTintColor = self.originalBarBgColor
navBar.tintColor = self.originalBarTintColor
navBar.barStyle = self.originalBarStyle
}
}
override func updateChartData() {
if self.shouldHideData {
chartView.data = nil
return
}
self.setChartData()
}
func setChartData() {
let mult: UInt32 = 80
let min: UInt32 = 20
let cnt = 5
let block: (Int) -> RadarChartDataEntry = { _ in return RadarChartDataEntry(value: Double(arc4random_uniform(mult) + min))}
let entries1 = (0..<cnt).map(block)
let entries2 = (0..<cnt).map(block)
let set1 = RadarChartDataSet(values: entries1, label: "Last Week")
set1.setColor(UIColor(red: 103/255, green: 110/255, blue: 129/255, alpha: 1))
set1.fillColor = UIColor(red: 103/255, green: 110/255, blue: 129/255, alpha: 1)
set1.drawFilledEnabled = true
set1.fillAlpha = 0.7
set1.lineWidth = 2
set1.drawHighlightCircleEnabled = true
set1.setDrawHighlightIndicators(false)
let set2 = RadarChartDataSet(values: entries2, label: "This Week")
set2.setColor(UIColor(red: 121/255, green: 162/255, blue: 175/255, alpha: 1))
set2.fillColor = UIColor(red: 121/255, green: 162/255, blue: 175/255, alpha: 1)
set2.drawFilledEnabled = true
set2.fillAlpha = 0.7
set2.lineWidth = 2
set2.drawHighlightCircleEnabled = true
set2.setDrawHighlightIndicators(false)
let data = RadarChartData(dataSets: [set1, set2])
data.setValueFont(.systemFont(ofSize: 8, weight: .light))
data.setDrawValues(false)
data.setValueTextColor(.white)
chartView.data = data
}
override func optionTapped(_ option: Option) {
switch option {
case .toggleXLabels:
chartView.xAxis.drawLabelsEnabled = !chartView.xAxis.drawLabelsEnabled
chartView.data?.notifyDataChanged()
chartView.notifyDataSetChanged()
chartView.setNeedsDisplay()
case .toggleYLabels:
chartView.yAxis.drawLabelsEnabled = !chartView.yAxis.drawLabelsEnabled
chartView.setNeedsDisplay()
case .toggleRotate:
chartView.rotationEnabled = !chartView.rotationEnabled
case .toggleFilled:
for set in chartView.data!.dataSets as! [RadarChartDataSet] {
set.drawFilledEnabled = !set.drawFilledEnabled
}
chartView.setNeedsDisplay()
case .toggleHighlightCircle:
for set in chartView.data!.dataSets as! [RadarChartDataSet] {
set.drawHighlightCircleEnabled = !set.drawHighlightCircleEnabled
}
chartView.setNeedsDisplay()
case .animateX:
chartView.animate(xAxisDuration: 1.4)
case .animateY:
chartView.animate(yAxisDuration: 1.4)
case .animateXY:
chartView.animate(xAxisDuration: 1.4, yAxisDuration: 1.4)
case .spin:
chartView.spin(duration: 2, fromAngle: chartView.rotationAngle, toAngle: chartView.rotationAngle + 360, easingOption: .easeInCubic)
default:
super.handleOption(option, forChartView: chartView)
}
}
}
extension RadarChartViewController: IAxisValueFormatter {
func stringForValue(_ value: Double, axis: AxisBase?) -> String {
return activities[Int(value) % activities.count]
}
}
| apache-2.0 | adcc1ead8d8cb2e8afdf474df0e65431 | 33.359606 | 143 | 0.589677 | 4.97149 | false | false | false | false |
ZamzamInc/SwiftyPress | Sources/SwiftyPress/Views/UIKit/Controls/DataViews/PostsDataView/Cells/PickedPostCollectionViewCell.swift | 1 | 3501 | //
// PickedPostCollectionViewCell.swift
// Basem Emara
//
// Created by Basem Emara on 2018-06-25.
// Copyright © 2018 Zamzam Inc. All rights reserved.
//
import UIKit
import ZamzamCore
public final class PickedPostCollectionViewCell: UICollectionViewCell {
private let titleLabel = ThemedHeadline().apply {
$0.font = .preferredFont(forTextStyle: .headline)
$0.numberOfLines = 2
}
private let summaryLabel = ThemedSubhead().apply {
$0.font = .preferredFont(forTextStyle: .subheadline)
$0.numberOfLines = 3
}
private let featuredImage = ThemedImageView(imageNamed: .placeholder).apply {
$0.contentMode = .scaleAspectFill
$0.clipsToBounds = true
}
private lazy var favoriteButton = ThemedImageButton().apply {
$0.setImage(UIImage(named: .favoriteEmpty), for: .normal)
$0.setImage(UIImage(named: .favoriteFilled), for: .selected)
$0.imageView?.contentMode = .scaleAspectFit
$0.addTarget(self, action: #selector(didTapFavoriteButton), for: .touchUpInside) // Must be in lazy init
}
private var model: PostsDataViewModel?
private weak var delegate: PostsDataViewDelegate?
public override init(frame: CGRect) {
super.init(frame: frame)
prepare()
}
@available(*, unavailable)
public required init?(coder: NSCoder) { nil }
}
// MARK: - Setup
private extension PickedPostCollectionViewCell {
func prepare() {
let favoriteView = UIView().apply {
$0.backgroundColor = .clear
$0.addSubview(favoriteButton)
}
let stackView = UIStackView(arrangedSubviews: [
featuredImage,
UIStackView(arrangedSubviews: [
titleLabel.apply {
$0.setContentHuggingPriority(.defaultHigh, for: .vertical)
},
summaryLabel,
favoriteView
]).apply {
$0.axis = .vertical
$0.spacing = 5
}
]).apply {
$0.axis = .horizontal
$0.spacing = 8
}
let view = ThemedView().apply {
$0.addSubview(stackView)
}
addSubview(view)
view.edges(to: self)
stackView.edges(to: view, insets: UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 16))
featuredImage.aspectRatioSize()
favoriteView.heightAnchor.constraint(equalTo: favoriteButton.heightAnchor).isActive = true
favoriteButton.heightAnchor.constraint(equalToConstant: 24).isActive = true
favoriteButton.center()
}
}
// MARK: - Interactions
private extension PickedPostCollectionViewCell {
@objc func didTapFavoriteButton() {
favoriteButton.isSelected.toggle()
guard let model = model else { return }
delegate?.postsDataView(toggleFavorite: model)
}
}
// MARK: - Delegates
extension PickedPostCollectionViewCell: PostsDataViewCell {
public func load(_ model: PostsDataViewModel) {
self.model = model
titleLabel.text = model.title
summaryLabel.text = model.summary
featuredImage.setImage(from: model.imageURL)
favoriteButton.isSelected = model.favorite
}
public func load(_ model: PostsDataViewModel, delegate: PostsDataViewDelegate?) {
self.delegate = delegate
load(model)
}
}
| mit | f3b0e5921dd45189d6fb8e6584dffc6c | 28.166667 | 112 | 0.612857 | 4.807692 | false | false | false | false |
Aaron-zheng/yugioh | yugioh/CardSearchViewController.swift | 1 | 18331 | //
// CardSearchViewController.swift
// yugioh
//
// Created by Aaron on 2/11/2016.
// Copyright © 2016 sightcorner. All rights reserved.
//
import Foundation
import UIKit
class CardSearchViewController: UIViewController {
@IBOutlet weak var searchBarView: UIScrollView!
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var cancelButton: UIButton!
@IBOutlet weak var inputField: UITextField!
@IBOutlet weak var attackRangeSlider: RangeSlider!
@IBOutlet weak var attackRangeLabel: UILabel!
@IBOutlet weak var defenseRangeSlider: RangeSlider!
@IBOutlet weak var defenseRangeLabel: UILabel!
@IBOutlet weak var searchBarViewHeightConstraint: NSLayoutConstraint!
@IBOutlet weak var starRangeLabel: UILabel!
@IBOutlet weak var starRangeSlider: RangeSlider!
@IBOutlet weak var searchBarViewTopConstraint: NSLayoutConstraint!
var cardEntitys = Array<CardEntity>()
var searchResult = Array<CardEntity>()
var cardService = CardService()
var attackLow: Int = 0
var attackUp: Int = 10000
var defenseLow: Int = 0
var defenseUp: Int = 10000
var starLow: Int = 0
var starUp: Int = 12
var rootFrame: CGSize = CGSize.zero
var contentHeight: CGFloat = 0
var searchType = NSMutableSet()
var searchProperty = NSMutableSet()
var searchRace = NSMutableSet()
let types = [
"通常","怪兽","特殊召唤",
"效果","反转",
"同盟","同调","灵摆","连接","XYZ","二重","调整","灵魂","卡通",
"陷阱","反击",
"魔法","装备","永续","融合","仪式","速攻","场地"
]
let propertys = ["暗", "地", "神", "光", "风", "水", "炎"]
let races = ["鱼", "幻龙", "兽战士", "岩石", "炎", "恐龙", "兽", "天使", "创造神", "机械", "植物", "魔法师", "龙", "昆虫", "战士", "念动力", "电子界", "鸟兽", "雷", "水", "幻神兽", "不死", "恶魔", "海龙", "爬虫类"]
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
Bundle.main.loadNibNamed("CardSearchViewController", owner: self, options: nil)
}
fileprivate var searchBarViewHeightConstraintValue:CGFloat = 0;
override func viewDidLoad() {
searchBarViewHeightConstraintValue = searchBarViewHeightConstraint.constant
setup()
if isIPhoneX() {
self.searchBarViewTopConstraint.constant = 10
}
}
override func viewDidLayoutSubviews() {
self.searchBarView.contentSize = CGSize.init(width: rootFrame.width, height: contentHeight)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.navigationController?.isNavigationBarHidden = true
nc.addObserver(self, selector: #selector(CardSearchViewController.keyboardWillShow), name: UIResponder.keyboardWillChangeFrameNotification, object: nil)
}
@objc func keyboardWillShow(notification: NSNotification) {
if let keyboardSize = (notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue {
self.searchBarViewHeightConstraint.constant = searchBarViewHeightConstraintValue
}
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
self.navigationController?.isNavigationBarHidden = false
nc.removeObserver(self)
}
private func setup() {
self.cardEntitys = getCardEntity()
//
self.rootFrame = UIScreen.main.bounds.size
self.inputField.returnKeyType = UIReturnKeyType.search
self.searchBarView.contentSize.width = self.rootFrame.width
//
self.view.backgroundColor = darkColor
self.searchBarView.backgroundColor = darkColor
self.cancelButton.tintColor = UIColor.white
self.cancelButton.addTarget(self, action: #selector(CardSearchViewController.clickCancelButton), for: .touchUpInside)
self.inputField.attributedPlaceholder = NSAttributedString(string: "输入搜索(名称,效果,编号)", attributes: [NSAttributedString.Key.foregroundColor: UIColor.white])
self.inputField.textColor = UIColor.white
self.inputField.text = nil
self.inputField.becomeFirstResponder()
self.inputField.delegate = self
self.tableView.delegate = self
self.tableView.dataSource = self
self.tableView.register(CardTableViewCell.NibObject(), forCellReuseIdentifier: CardTableViewCell.identifier())
self.tableView.backgroundColor = greyColor
self.tableView.separatorStyle = .none
self.tableView.tableHeaderView = UIView(frame: CGRect.zero)
self.tableView.tableFooterView = UIView(frame: CGRect.zero)
setupRangeSlider()
setupTypeButtons()
}
private func setupTypeButtons() {
//types
var defaultHeight = 120
defaultHeight = self.addButtons(datas: types, selector: #selector(clickTypeButton), dataWidth: 64, dataHeight: 32, dataDefaultHeight: defaultHeight)
//propertys
defaultHeight = self.addButtons(datas: propertys, selector: #selector(clickPropertyButton), dataWidth: 32, dataHeight: 32, dataDefaultHeight: defaultHeight + 32 + 8)
//races
defaultHeight = self.addButtons(datas: races, selector: #selector(clickRaceButton), dataWidth: 48, dataHeight: 32, dataDefaultHeight: defaultHeight + 32 + 8)
self.contentHeight = CGFloat(defaultHeight + 32 + 16)
}
private func addButtons(datas: [String], selector: Selector,
dataWidth: Int, dataHeight: Int, dataDefaultHeight: Int
) -> Int {
let rootWidth = self.rootFrame.width
let columnGap: Int = 8
let rowGap: Int = 4
var num = Int(rootWidth) / (dataWidth + columnGap)
if num > datas.count {
num = datas.count
}
let gap = (Int(rootWidth) - (dataWidth + columnGap) * num - columnGap) / 2 + columnGap
var row = 0
var column = 0
var lastHeight: Int = 0
for data in datas {
let f = CGRect(x: gap + column * (dataWidth + columnGap), y: dataDefaultHeight + row * (dataHeight + rowGap), width: dataWidth, height: dataHeight)
lastHeight = dataDefaultHeight + row * (dataHeight + rowGap)
let button = DataButton(frame: f)
button.layer.cornerRadius = 4
button.setTitleColor(UIColor.white.withAlphaComponent(0.7), for: .normal)
button.titleLabel?.font = attackRangeLabel.font
button.backgroundColor = greyColor.withAlphaComponent(0.12)
button.data = data
button.setTitle(data, for: .normal)
button.addTarget(self, action: selector, for: .touchUpInside)
self.searchBarView.addSubview(button)
column = column + 1
if column == num {
column = 0
row = row + 1
}
}
return lastHeight
}
private func clickButton(button: DataButton, set: NSMutableSet) {
if button.backgroundColor == greyColor.withAlphaComponent(0.12) {
button.backgroundColor = greyColor.withAlphaComponent(0.38)
set.add(button.data)
} else {
button.backgroundColor = greyColor.withAlphaComponent(0.12)
set.remove(button.data)
}
}
@objc func clickTypeButton(button: DataButton) {
self.clickButton(button: button, set: searchType)
}
@objc func clickPropertyButton(button: DataButton) {
self.clickButton(button: button, set: searchProperty)
}
@objc func clickRaceButton(button: DataButton) {
self.clickButton(button: button, set: searchRace)
}
private func setupRangeSlider() {
setupRangeSliderStyle(rangeSlider: self.attackRangeSlider)
self.attackRangeSlider.addTarget(self, action: #selector(CardSearchViewController.attackRangeSliderHandler), for: .valueChanged)
self.attackRangeLabel.text = "攻 无限制"
setupRangeSliderStyle(rangeSlider: self.defenseRangeSlider)
self.defenseRangeSlider.addTarget(self, action: #selector(CardSearchViewController.defenseRangeSliderHandler), for: .valueChanged)
self.defenseRangeLabel.text = "守 无限制"
setupRangeSliderStyle(rangeSlider: self.starRangeSlider)
self.starRangeSlider.addTarget(self, action: #selector(CardSearchViewController.starRangeSliderHandler), for: .valueChanged)
self.starRangeLabel.text = "星 无限制"
}
private func setupRangeSliderStyle(rangeSlider: RangeSlider) {
rangeSlider.trackTintColor = UIColor.clear
rangeSlider.trackHighlightTintColor = UIColor.white.withAlphaComponent(0.70)
rangeSlider.thumbBorderColor = UIColor.clear
rangeSlider.thumbTintColor = greyColor
}
@objc func clickCancelButton() {
_ = self.navigationController?.popViewController(animated: false)
}
@objc func attackRangeSliderHandler(sender: RangeSlider) {
attackLow = Int(sender.lowerValue / 500) * 500
attackUp = Int(sender.upperValue / 500) * 500
if attackLow == 0 && attackUp == 10000 {
attackRangeLabel.text = "攻 无限制"
} else {
attackRangeLabel.text = "攻 " + attackLow.description + " ~ " + attackUp.description
}
}
@objc func defenseRangeSliderHandler(sender: RangeSlider) {
defenseLow = Int(sender.lowerValue / 500) * 500
defenseUp = Int(sender.upperValue / 500) * 500
if defenseLow == 0 && defenseUp == 10000 {
defenseRangeLabel.text = "守 无限制"
} else {
defenseRangeLabel.text = "守 " + defenseLow.description + " ~ " + defenseUp.description
}
}
@objc func starRangeSliderHandler(sender: RangeSlider) {
starLow = Int(sender.lowerValue)
starUp = Int(sender.upperValue)
if starLow == 0 && starUp == 12 {
starRangeLabel.text = "星 无限制"
} else {
starRangeLabel.text = "星 " + starLow.description + " ~ " + starUp.description
}
}
@objc(tableView:didSelectRowAtIndexPath:)
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
self.tableView.deselectRow(at: indexPath, animated: true)
let controller = CardDetailViewController()
controller.cardEntity = searchResult[indexPath.row]
controller.proxy = self.tableView
controller.hidesBottomBarWhenPushed = true
let back = UIBarButtonItem()
back.title = navigationBarTitleText
self.navigationItem.backBarButtonItem = back
self.navigationController?.pushViewController(controller, animated: true)
}
}
extension CardSearchViewController: UITextFieldDelegate {
func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
hideRangeSlider(flag: false)
return true
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
self.searchBarView.isScrollEnabled = false
textField.resignFirstResponder()
var result: Array<CardEntity> = []
let input = textField.text?.lowercased().trimmingCharacters(in: .whitespacesAndNewlines)
//setLog(event: AnalyticsEventSearch, description: input)
for i in 0 ..< cardEntitys.count {
let c = cardEntitys[i]
//input search
if input != "" {
let inputArray = input?.split(separator: " ")
var inputFound = true
for inputTmp in inputArray! {
// TODO 这里需要找寻日文和英文
if !c.titleName.lowercased().contains(inputTmp.description)
&& !c.effect.lowercased().contains(inputTmp.description)
&& !c.password.lowercased().contains(inputTmp.description) {
inputFound = false
break
}
}
if !inputFound {
continue
}
}
//type search
if searchType.count > 0 {
var searchTypeFound = false
for case let t as String in searchType {
if c.type.split(separator: " ").map(String.init).contains(t) {
searchTypeFound = true
}
}
if !searchTypeFound {
continue
}
}
//race search
if searchRace.count > 0 {
if !searchRace.contains(c.race) {
continue
}
}
//property search
if searchProperty.count > 0 {
if !searchProperty.contains(c.property) {
continue
}
}
//attack search
if attackLow != 0 {
if let attack = Int.init(c.attack) {
if attack < attackLow {
continue
}
} else {
continue
}
}
if attackUp != 10000 {
if let attack = Int.init(c.attack) {
if attack > attackUp {
continue
}
} else {
continue
}
}
//defense search
if defenseLow != 0 {
if let defense = Int.init(c.defense) {
if defense < defenseLow {
continue
}
} else {
continue
}
}
if defenseUp != 10000 {
if let defense = Int.init(c.defense) {
if defense > defenseUp {
continue
}
} else {
continue
}
}
//star search
if starLow != 0 {
if let star = Int.init(c.star) {
if star < starLow {
continue
}
} else {
continue
}
}
if starUp != 12 {
if let star = Int.init(c.star) {
if star > starUp {
continue
}
} else {
continue
}
}
//
result.append(c)
}
if result.count > 0 {
self.searchResult = result
self.tableView.reloadData()
}
hideRangeSlider(flag: true)
self.searchBarViewHeightConstraint.constant = 56
self.searchBarView.setContentOffset(CGPoint.init(x: 0, y: -20), animated: false)
return true
}
func hideRangeSlider(flag: Bool) {
self.attackRangeSlider.isHidden = flag
self.defenseRangeSlider.isHidden = flag
self.starRangeSlider.isHidden = flag
}
func textFieldDidBeginEditing(_ textField: UITextField) {
self.searchResult = []
self.tableView.reloadData()
self.searchBarView.isScrollEnabled = true
}
}
extension CardSearchViewController: UITableViewDataSource {
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return searchResult.count
}
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = self.tableView.dequeueReusableCell(withIdentifier: CardTableViewCell.identifier(), for: indexPath) as! CardTableViewCell
let cardEntity = searchResult[indexPath.row]
cardEntity.isSelected = false
let list = cardService.list()
for i in 0 ..< list.count {
if cardEntity.id == list[i] {
cardEntity.isSelected = true
break
}
}
cell.prepare(cardEntity: cardEntity, tableView: tableView, indexPath: indexPath)
return cell
}
@objc(tableView:heightForRowAtIndexPath:)
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
var ifLastRowWillAddGap: CGFloat = 0
if indexPath.row == searchResult.count - 1 {
ifLastRowWillAddGap = 8
}
var result = (self.view.frame.width - materialGap * 2) / 3 / 160 * 230
result = result + materialGap + ifLastRowWillAddGap
return result
}
@objc(tableView:didEndDisplayingCell:forRowAtIndexPath:)
func tableView(_ tableView: UITableView, didEndDisplaying cell: UITableViewCell, forRowAt indexPath: IndexPath) {
(cell as! CardTableViewCell).card.kf.cancelDownloadTask()
}
@objc(tableView:willDisplayCell:forRowAtIndexPath:)
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
let cell = (cell as! CardTableViewCell)
setImage(card: cell.card, id: searchResult[indexPath.row].id)
}
}
extension CardSearchViewController: UITableViewDelegate {
}
| agpl-3.0 | 42ed96244445ceb9cbb5cdd8509a01c5 | 32.615672 | 173 | 0.570152 | 5.075493 | false | false | false | false |
khoren93/SwiftHub | SwiftHub/Modules/Users/UserCell.swift | 1 | 1373 | //
// UserCell.swift
// SwiftHub
//
// Created by Khoren Markosyan on 6/30/18.
// Copyright © 2018 Khoren Markosyan. All rights reserved.
//
import UIKit
class UserCell: DefaultTableViewCell {
lazy var followButton: Button = {
let view = Button()
view.borderColor = .white
view.borderWidth = Configs.BaseDimensions.borderWidth
view.tintColor = .white
view.cornerRadius = 17
view.snp.remakeConstraints({ (make) in
make.size.equalTo(34)
})
return view
}()
override func makeUI() {
super.makeUI()
stackView.insertArrangedSubview(followButton, at: 2)
}
override func bind(to viewModel: TableViewCellViewModel) {
super.bind(to: viewModel)
guard let viewModel = viewModel as? UserCellViewModel else { return }
viewModel.hidesFollowButton.asDriver().drive(followButton.rx.isHidden).disposed(by: rx.disposeBag)
viewModel.following.asDriver().map { (followed) -> UIImage? in
let image = followed ? R.image.icon_button_user_x() : R.image.icon_button_user_plus()
return image?.template
}.drive(followButton.rx.image()).disposed(by: rx.disposeBag)
viewModel.following.map { $0 ? 1.0: 0.6 }.asDriver(onErrorJustReturn: 0).drive(followButton.rx.alpha).disposed(by: rx.disposeBag)
}
}
| mit | ae6671a3ad6881dcfee9e73f2223bcaa | 32.463415 | 137 | 0.648688 | 4.157576 | false | false | false | false |
whiteshadow-gr/HatForIOS | HAT/Constants/HATAuthenticationConstants.swift | 1 | 2463 | /**
* Copyright (C) 2018 HAT Data Exchange Ltd
*
* SPDX-License-Identifier: MPL2
*
* This file is part of the Hub of All Things project (HAT).
*
* 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/
*/
// MARK: Headers
/**
The request headers used in various network requests
*/
public enum RequestHeaders {
// MARK: - Variables
/// The `x-Auth-Token` name in the header, used to store the user's token
public static let xAuthToken: String = "x-auth-token"
/// The `token` name in the headers
public static let tokenParamName: String = "token"
/// The `x-amz-server-side-encryption` name in the headers
public static let serverEncryption: String = "x-amz-server-side-encryption"
/// The `AES256` value in the headers for `x-amz-server-side-encryption`
public static let serverEncryptionAES256: String = "AES256"
}
// MARK: - Content type
/**
The content type used in various network requests
*/
public enum ContentType {
// MARK: - Variables
/// The `application/json` content type
public static let json: String = "application/json"
/// The `text/plain` content type
public static let text: String = "text/plain"
}
// MARK: - Location Plug Credentials
/**
The authentication data used by location service. Used when enabling the location plug
*/
public enum HATDataPlugCredentials {
// MARK: - Variables
/// market data plug id used for location data plug
static let dataPlugID: String = "c532e122-db4a-44b8-9eaf-18989f214262"
/// market access token used for location data plug
static let locationDataPlugToken: String = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxLVZTUDcrb0RleldPejBTOFd6MHhWM0J2eVNOYzViNnRcLzRKXC85TVlIWTQrVDdsSHdUSDRXMVVEWGFSVnVQeTFPZmtNajNSNDBjeTVERFRhQjZBNE44c3FGSTJmMUE1NzZUYjhiYmhhUT0iLCJpc3MiOiJoYXQtbWFya2V0IiwiZXhwIjoxNTI2OTc4OTkyLCJpYXQiOjE0OTYyMjA1OTIsImp0aSI6ImY0NTQ4NzI5MGRlZTA3NDI5YmQxMGViMWZmNzJkZjZmODdiYzhhZDE0ZThjOGE3NmMyZGJlMjVhNDlmODNkOTNiMDJhMzg3NGI4NTI0NDhlODU0Y2ZmZmE0ZWQyZGY1MTYyZTBiYzRhNDk2NGRhYTlhOTc1M2EyMjA1ZjIzMzc5NWY3N2JiODhlYzQwNjQxZjM4MTk4NTgwYWY0YmExZmJkMDg5ZTlhNmU3NjJjN2NhODlkMDdhOTg3MmY1OTczNjdjYWQyYzA0NTdjZDhlODlmM2FlMWQ2MmRmODY3NTcwNTc3NTdiZDJjYzgzNTgyOTU4ZmZlMDVhNjI2NzBmNGMifQ.TvFs6Zp0E24ChFqn3rBP-cpqxZbvkhph91UILGJvM6U"
}
| mpl-2.0 | 9653d4d45be09d6eb982e2a56cf0c663 | 40.05 | 712 | 0.769387 | 2.837558 | false | false | false | false |
bsmith11/ScoreReporter | ScoreReporter/Game List/GameListDataSource.swift | 1 | 1875 | //
// GameListDataSource.swift
// ScoreReporter
//
// Created by Bradley Smith on 9/25/16.
// Copyright © 2016 Brad Smith. All rights reserved.
//
import Foundation
import CoreData
import ScoreReporterCore
class GameListDataSource: NSObject, FetchedDataSource, FetchedChangable {
typealias ModelType = Game
fileprivate(set) var fetchedResultsController: NSFetchedResultsController<Game>
let title: String?
dynamic var empty = false
var fetchedChangeHandler: FetchedChangeHandler?
init(pool: Pool) {
title = pool.name
fetchedResultsController = Game.fetchedGamesFor(pool: pool)
super.init()
register(fetchedResultsController: fetchedResultsController)
empty = fetchedResultsController.fetchedObjects?.isEmpty ?? true
}
init(clusters: [Cluster]) {
title = "Crossovers"
fetchedResultsController = Game.fetchedGamesFor(clusters: clusters)
super.init()
register(fetchedResultsController: fetchedResultsController)
empty = fetchedResultsController.fetchedObjects?.isEmpty ?? true
}
init(stage: Stage) {
title = stage.name
fetchedResultsController = Game.fetchedGamesFor(stage: stage)
super.init()
register(fetchedResultsController: fetchedResultsController)
empty = fetchedResultsController.fetchedObjects?.isEmpty ?? true
}
deinit {
unregister(fetchedResultsController: fetchedResultsController)
}
}
// MARK: - Public
extension GameListDataSource {
func title(for section: Int) -> String? {
let indexPath = IndexPath(item: 0, section: section)
let game = item(at: indexPath)
let dateFormatter = DateService.gameStartDateFullFormatter
return game?.startDateFull.flatMap { dateFormatter.string(from: $0) }
}
}
| mit | c6621eeb657da1ac5657a38f78d818fc | 26.15942 | 83 | 0.691035 | 5.191136 | false | false | false | false |
openaphid/PureLayout | PureLayout/Example-iOS/Demos/iOSDemo9ViewController.swift | 5 | 3646 | //
// iOSDemo9ViewController.swift
// PureLayout Example-iOS
//
// Copyright (c) 2015 Tyler Fox
// https://github.com/smileyborg/PureLayout
//
import UIKit
import PureLayout
@objc(iOSDemo9ViewController)
class iOSDemo9ViewController: UIViewController {
let blueView: UIView = {
let view = UIView.newAutoLayoutView()
view.backgroundColor = .blueColor()
return view
}()
let redView: UIView = {
let view = UIView.newAutoLayoutView()
view.backgroundColor = .redColor()
return view
}()
let yellowView: UIView = {
let view = UIView.newAutoLayoutView()
view.backgroundColor = .yellowColor()
return view
}()
let greenView: UIView = {
let view = UIView.newAutoLayoutView()
view.backgroundColor = .greenColor()
return view
}()
var didSetupConstraints = false
override func loadView() {
view = UIView()
view.backgroundColor = UIColor(white: 0.1, alpha: 1.0)
view.addSubview(blueView)
blueView.addSubview(redView)
redView.addSubview(yellowView)
yellowView.addSubview(greenView)
view.setNeedsUpdateConstraints() // bootstrap Auto Layout
}
override func updateViewConstraints() {
if (!didSetupConstraints) {
// Before layout margins were introduced, this is a typical way of giving a subview some padding from its superview's edges
blueView.autoPinToTopLayoutGuideOfViewController(self, withInset: 10.0)
blueView.autoPinEdgesToSuperviewEdgesWithInsets(UIEdgeInsets(top: 0, left: 10.0, bottom: 10.0, right: 10.0), excludingEdge: .Top)
// Set the layoutMargins of the blueView, which will have an effect on subviews of the blueView that attach to
// the blueView's margin attributes -- in this case, the redView
blueView.layoutMargins = UIEdgeInsets(top: 10.0, left: 20.0, bottom: 80.0, right: 20.0)
redView.autoPinEdgesToSuperviewMargins()
// Let the redView inherit the values we just set for the blueView's layoutMargins by setting the below property to YES.
// Then, pin the yellowView's edges to the redView's margins, giving the yellowView the same insets from its superview as the redView.
redView.preservesSuperviewLayoutMargins = true
yellowView.autoPinEdgeToSuperviewMargin(.Left)
yellowView.autoPinEdgeToSuperviewMargin(.Right)
// By aligning the yellowView to its superview's horiztonal margin axis, the yellowView will be positioned with its horizontal axis
// in the middle of the redView's top and bottom margins (causing it to be slightly closer to the top of the redView, since the
// redView has a much larger bottom margin than top margin).
yellowView.autoAlignAxisToSuperviewMarginAxis(.Horizontal)
yellowView.autoMatchDimension(.Height, toDimension: .Height, ofView: redView, withMultiplier: 0.5)
// Since yellowView.preservesSuperviewLayoutMargins is NO by default, it will not preserve (inherit) its superview's margins,
// and instead will just have the default margins of: {8.0, 8.0, 8.0, 8.0} which will apply to its subviews (greenView)
greenView.autoPinEdgesToSuperviewMarginsExcludingEdge(.Bottom)
greenView.autoSetDimension(.Height, toSize: 50.0)
didSetupConstraints = true
}
super.updateViewConstraints()
}
}
| mit | 5b64dd183a7b0685753792cb153401e1 | 42.927711 | 146 | 0.656884 | 5.268786 | false | false | false | false |
masbog/iOS-SDK | Examples/nearables/MonitoringExample-Swift/MonitoringExample-Swift/ViewController.swift | 9 | 4450 | //
// ViewController.swift
// MonitoringExample-Swift
//
// Created by Marcin Klimek on 09/01/15.
// Copyright (c) 2015 Estimote. All rights reserved.
//
import UIKit
class ESTTableViewCell: UITableViewCell
{
override init(style: UITableViewCellStyle, reuseIdentifier: String?)
{
super.init(style: UITableViewCellStyle.Subtitle, reuseIdentifier: reuseIdentifier)
}
required init(coder aDecoder: NSCoder)
{
fatalError("init(coder:) has not been implemented")
}
}
class ViewController: UIViewController,
UITableViewDelegate,
UITableViewDataSource,
ESTNearableManagerDelegate
{
var nearables:Array<ESTNearable>!
var nearableManager:ESTNearableManager!
var tableView:UITableView!
override func viewDidLoad()
{
super.viewDidLoad()
self.title = "Pick Nearable to monitor for:";
tableView = UITableView(frame: self.view.frame)
tableView.delegate = self
tableView.dataSource = self
self.view.addSubview(tableView)
tableView.registerClass(ESTTableViewCell.classForCoder(), forCellReuseIdentifier: "CellIdentifier")
nearables = []
nearableManager = ESTNearableManager()
nearableManager.delegate = self
nearableManager .startRangingForType(ESTNearableType.All)
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int
{
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return nearables.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
let cell = tableView.dequeueReusableCellWithIdentifier("CellIdentifier", forIndexPath: indexPath) as ESTTableViewCell
let nearable = nearables[indexPath.row] as ESTNearable
var details:NSString = NSString(format:"Type: %@ RSSI: %zd", ESTNearableDefinitions.nameForType(nearable.type), nearable.rssi);
cell.textLabel?.text = NSString(format:"Identifier: %@", nearable.identifier);
cell.detailTextLabel?.text = details;
var imageView = UIImageView(frame: CGRectMake(self.view.frame.size.width - 60, 30, 30, 30))
imageView.contentMode = UIViewContentMode.ScaleAspectFill
imageView.image = self.imageForNearableType(nearable.type)
cell.contentView.addSubview(imageView)
return cell
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat
{
return 80
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath)
{
self.performSegueWithIdentifier("details", sender: indexPath)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?)
{
if(segue.identifier == "details")
{
var monitVC:MonitoringDetailsViewController = segue.destinationViewController as MonitoringDetailsViewController
monitVC.nearable = self.nearables[(sender as NSIndexPath).row]
}
}
// MARK: - ESTNearableManager delegate
func nearableManager(manager: ESTNearableManager!, didRangeNearables nearables: [AnyObject]!, withType type: ESTNearableType)
{
self.nearables = nearables as Array<ESTNearable>
self.tableView.reloadData()
}
func imageForNearableType(type: ESTNearableType) -> UIImage?
{
switch (type)
{
case ESTNearableType.Bag:
return UIImage(named: "sticker_bag")
case ESTNearableType.Bike:
return UIImage(named: "sticker_bike")
case ESTNearableType.Car:
return UIImage(named: "sticker_car")
case ESTNearableType.Fridge:
return UIImage(named: "sticker_fridge")
case ESTNearableType.Bed:
return UIImage(named: "sticker_bed")
case ESTNearableType.Chair:
return UIImage(named: "sticker_chair")
case ESTNearableType.Shoe:
return UIImage(named: "sticker_shoe")
case ESTNearableType.Door:
return UIImage(named: "sticker_door")
case ESTNearableType.Dog:
return UIImage(named: "sticker_dog")
default:
return UIImage(named: "sticker_grey")
}
}
}
| mit | 0ad1662d1bbc49c470477c8bfbb27a1b | 31.720588 | 135 | 0.661348 | 5.126728 | false | false | false | false |
kenwilcox/StormViewer | StormViewer/AppDelegate.swift | 1 | 3242 | //
// AppDelegate.swift
// StormViewer
//
// Created by Kenneth Wilcox on 10/11/15.
// Copyright © 2015 Kenneth Wilcox. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UISplitViewControllerDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
let splitViewController = self.window!.rootViewController as! UISplitViewController
let navigationController = splitViewController.viewControllers[splitViewController.viewControllers.count-1] as! UINavigationController
navigationController.topViewController!.navigationItem.leftBarButtonItem = splitViewController.displayModeButtonItem
splitViewController.delegate = self
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:.
}
// MARK: - Split view
func splitViewController(_ splitViewController: UISplitViewController, collapseSecondary secondaryViewController:UIViewController, onto primaryViewController:UIViewController) -> Bool {
guard let secondaryAsNavController = secondaryViewController as? UINavigationController else { return false }
guard let topAsDetailController = secondaryAsNavController.topViewController as? DetailViewController else { return false }
if topAsDetailController.detailImageView == nil {
// Return true to indicate that we have handled the collapse by doing nothing; the secondary controller will be discarded.
return true
}
return false
}
}
| mit | dad740145f85e7269d6e721d53264f64 | 52.131148 | 281 | 0.783709 | 6.035382 | false | false | false | false |
lucas34/SwiftQueue | Sources/SwiftQueue/Constraint+Delay.swift | 1 | 2786 | // The MIT License (MIT)
//
// Copyright (c) 2022 Lucas Nelaupe
//
// 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
internal final class DelayConstraint: SimpleConstraint, CodableConstraint {
/// Delay for the first execution of the job
internal let delay: TimeInterval
required init(delay: TimeInterval) {
self.delay = delay
}
convenience init?(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: DelayConstraintKey.self)
if container.contains(.delay) {
try self.init(delay: container.decode(TimeInterval.self, forKey: .delay))
} else { return nil }
}
override func run(operation: SqOperation) -> Bool {
let epoch = Date().timeIntervalSince(operation.info.createTime)
guard epoch < delay else {
// Epoch already greater than delay
return true
}
let time: Double = abs(epoch - delay)
operation.nextRunSchedule = Date().addingTimeInterval(time)
operation.dispatchQueue.runAfter(time, callback: { [weak operation] in
// If the operation in already deInit, it may have been canceled
// It's safe to ignore the nil check
// This is mostly to prevent job retention when cancelling operation with delay
operation?.run()
})
operation.logger.log(.verbose, jobId: operation.name, message: "Job delayed by \(time)s")
return false
}
private enum DelayConstraintKey: String, CodingKey {
case delay
}
func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: DelayConstraintKey.self)
try container.encode(delay, forKey: .delay)
}
}
| mit | fb82d71daa79d8ff806abe60644175b2 | 38.239437 | 97 | 0.694903 | 4.690236 | false | false | false | false |
apple/swift-argument-parser | Tools/generate-manual/DSL/Core/MDocASTNodeWrapper.swift | 1 | 585 | //===----------------------------------------------------------*- swift -*-===//
//
// This source file is part of the Swift Argument Parser open source project
//
// Copyright (c) 2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
struct MDocASTNodeWrapper: MDocComponent {
var ast: [MDocASTNode] { [node] }
var body: MDocComponent { self }
var node: MDocASTNode
}
| apache-2.0 | 7d2a8a6271cf0d4f7ff2267ce9cb4af1 | 35.5625 | 80 | 0.540171 | 4.957627 | false | false | false | false |
kcome/SwiftIB | SwiftIB/Builder.swift | 1 | 2166 | //
// Builder.swift
// SwiftIB
//
// Created by Hanfei Li on 1/01/2015.
// Copyright (c) 2014-2019 Hanfei Li. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
// of the Software, and to permit persons to whom the Software is furnished to
// do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
import Foundation
class Builder : CustomStringConvertible {
fileprivate let SEP: Character = "\0"
fileprivate var stringBuffer: String = ""
func send(_ a: Int) {
send( a == Int.max ? "" : itos(a) )
}
func send(_ a: Double) {
send( a == Double.nan ? "" : dtos(a) )
}
func send(_ a: Bool) {
send( a ? 1 : 0 )
}
func send(_ a: IApiEnum) {
send( a.getApiString() )
}
func send(_ a: String) {
stringBuffer += a
stringBuffer.append(SEP)
}
var description : String {
return stringBuffer
}
var bytes : [UInt8] {
if let sbdata = stringBuffer.data(using: String.Encoding.utf8, allowLossyConversion: false) {
var bytes = [UInt8](repeating: 0, count: sbdata.count)
(sbdata as NSData).getBytes(&bytes, length: sbdata.count)
return bytes
}
return []
}
}
| mit | 912d5d01f889efa2de7c8ca3dcb90611 | 30.852941 | 101 | 0.653278 | 4.141491 | false | false | false | false |
ziligy/JGTapButton | JGTapButton.swift | 1 | 8759 | //
// JGTapButton.swift
//
// Created by Jeff on 8/20/15.
// Copyright © 2015 Jeff Greenberg. All rights reserved.
//
// updated to swift 3 10/23/16
import UIKit
enum TapButtonShape {
case round
case rectangle
}
enum TapButtonStyle {
case raised
case flat
}
enum TapButtonCorners {
case beveled
case squared
}
@IBDesignable
public class JGTapButton: UIButton {
// MARK: Inspectables
// select round or rectangle button shape
@IBInspectable public var round: Bool = true {
didSet {
buttonShape = (round ? .round : .rectangle)
}
}
// select raised or flat style
@IBInspectable public var raised: Bool = true {
didSet {
buttonStyle = (raised ? .raised : .flat)
}
}
// select raised or flat style
@IBInspectable public var squared: Bool = true {
didSet {
buttonCorners = (squared ? .squared : .beveled)
}
}
// set title caption for button
@IBInspectable public var title: String = "JGTapButton" {
didSet {
buttonTitle = title
}
}
// optional button image
@IBInspectable public var image: UIImage=UIImage() {
didSet {
setButtonImage()
}
}
@IBInspectable public var imageInset: CGFloat = 0 {
didSet {
setButtonImage()
}
}
// main background button color
@IBInspectable public var mainColor: UIColor = UIColor.red {
didSet {
buttonColor = mainColor
}
}
// title font size
@IBInspectable public var fontsize: CGFloat = 22.0 {
didSet {
titleFontSize = fontsize
}
}
@IBInspectable public var bevelSize: CGFloat = 7.0 {
didSet {
cornerRadius = bevelSize
}
}
@IBInspectable public var fontColor: UIColor = UIColor.white
// MARK: Private variables
private var buttonShape = TapButtonShape.round
private var buttonStyle = TapButtonStyle.flat
private var buttonCorners = TapButtonCorners.squared
private var buttonTitle = ""
private var buttonColor = UIColor.red
private var titleFontSize: CGFloat = 22.0
private var cornerRadius: CGFloat = 7.0
private var tapButtonFrame = CGRect(x: 0, y: 0, width: 100, height: 100)
// outline shape of button from draw
private var outlinePath = UIBezierPath()
// variables for glow animation
private let tapGlowView = UIView()
private let tapGlowBackgroundView = UIView()
private var tapGlowColor = UIColor(white: 0.9, alpha: 1)
private var tapGlowBackgroundColor = UIColor(white: 0.95, alpha: 1)
private var tapGlowMask: CAShapeLayer? {
get {
let maskLayer = CAShapeLayer()
maskLayer.path = outlinePath.cgPath
return maskLayer
}
}
// optional image for
private var iconImageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 40, height: 40))
// MARK: Initialize
func initMaster() {
self.backgroundColor = UIColor.clear
self.addSubview(iconImageView)
}
override init(frame: CGRect) {
super.init(frame: frame)
initMaster()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
initMaster()
}
convenience init(sideSize: CGFloat) {
self.init(frame: CGRect(x: 0, y: 0, width: sideSize, height: sideSize))
}
override public func prepareForInterfaceBuilder() {
invalidateIntrinsicContentSize()
self.backgroundColor = UIColor.clear
}
// MARK: Layout
override public func layoutSubviews() {
super.layoutSubviews()
iconImageView.layer.mask = tapGlowMask
tapGlowBackgroundView.layer.mask = tapGlowMask
}
override public var intrinsicContentSize: CGSize {
return bounds.size
}
// MARK: draw
override public func draw(_ rect: CGRect) {
outlinePath = drawTapButton(buttonShape, buttonTitle: buttonTitle, fontsize: titleFontSize)
tapGlowSetup()
}
private func tapGlowSetup() {
tapGlowBackgroundView.backgroundColor = tapGlowBackgroundColor
tapGlowBackgroundView.frame = bounds
layer.addSublayer(tapGlowBackgroundView.layer)
tapGlowBackgroundView.layer.addSublayer(tapGlowView.layer)
tapGlowBackgroundView.alpha = 0
}
private func drawTapButton(_ buttonShape: TapButtonShape, buttonTitle: String, fontsize: CGFloat) -> UIBezierPath {
var bezierPath: UIBezierPath!
if buttonStyle == .raised {
tapButtonFrame = CGRect(x: 1, y: 1, width: self.bounds.width - 2, height: self.bounds.height - 2)
} else {
tapButtonFrame = CGRect(x: 0, y: 0, width: self.bounds.width, height: self.bounds.height)
}
let context = UIGraphicsGetCurrentContext()
if buttonShape == .round {
bezierPath = UIBezierPath(ovalIn: tapButtonFrame)
} else {
if buttonCorners == .squared {
bezierPath = UIBezierPath(rect: tapButtonFrame)
} else {
bezierPath = UIBezierPath(roundedRect: tapButtonFrame, cornerRadius: cornerRadius)
}
}
buttonColor.setFill()
bezierPath.fill()
let shadow = UIColor.black.cgColor
let shadowOffset = CGSize(width: 3.1, height: 3.1)
let shadowBlurRadius: CGFloat = 7
if buttonStyle == .raised {
context?.saveGState()
context?.setShadow(offset: shadowOffset, blur: shadowBlurRadius, color: shadow)
fontColor.setStroke()
bezierPath.lineWidth = 1
bezierPath.stroke()
context?.restoreGState()
}
// MARK: Title Text
if let _ = iconImageView.image {
} else {
let buttonTitleTextContent = NSString(string: buttonTitle)
context?.saveGState()
if buttonStyle == .raised {
context?.setShadow(offset: shadowOffset, blur: shadowBlurRadius, color: shadow)
}
let buttonTitleStyle = NSParagraphStyle.default.mutableCopy() as! NSMutableParagraphStyle
buttonTitleStyle.alignment = NSTextAlignment.center
let buttonTitleFontAttributes = [NSFontAttributeName: UIFont(name: "AppleSDGothicNeo-Regular", size: fontsize)!, NSForegroundColorAttributeName: fontColor, NSParagraphStyleAttributeName: buttonTitleStyle] as [String : Any]
let buttonTitleTextHeight: CGFloat = buttonTitleTextContent.boundingRect(with: CGSize(width: tapButtonFrame.width, height: CGFloat.infinity), options: NSStringDrawingOptions.usesLineFragmentOrigin, attributes: buttonTitleFontAttributes, context: nil).size.height
context?.saveGState()
context?.clip(to: tapButtonFrame);
buttonTitleTextContent.draw(in: CGRect(x: tapButtonFrame.minX, y: tapButtonFrame.minY + (tapButtonFrame.height - buttonTitleTextHeight) / 2, width: tapButtonFrame.width, height: buttonTitleTextHeight), withAttributes: buttonTitleFontAttributes)
context?.restoreGState()
context?.restoreGState()
}
return bezierPath
}
private func setButtonImage() {
iconImageView.frame = CGRect(x: imageInset, y: imageInset, width: self.frame.width - imageInset*2, height: self.frame.height - imageInset*2)
iconImageView.image = self.image
}
// MARK: Tap events
override public func beginTracking(_ touch: UITouch,
with event: UIEvent?) -> Bool {
UIView.animate(withDuration: 0.1, animations: {
self.tapGlowBackgroundView.alpha = 1
}, completion: nil)
return super.beginTracking(touch, with: event)
}
override public func endTracking(_ touch: UITouch?,
with event: UIEvent?) {
super.endTracking(touch, with: event)
UIView.animate(withDuration: 0.1, animations: {
self.tapGlowBackgroundView.alpha = 1
}, completion: {(success: Bool) -> () in
UIView.animate(withDuration: 0.6 , animations: {
self.tapGlowBackgroundView.alpha = 0
}, completion: nil)
})
}
}
| mit | 92e0aa83f1705bbb628da0abeff9d2ee | 29.946996 | 274 | 0.600594 | 5.109685 | false | false | false | false |
johnnysay/GoodAccountsMakeGoodFriends | Good Accounts/Views/SynthesisViewCell.swift | 1 | 2182 | //
// SynthesisViewCell.swift
// Good Accounts
//
// Created by Johnny on 22/02/2016.
// Copyright © 2016 fake. All rights reserved.
//
import UIKit
import Reusable
final class SynthesisViewCell: UITableViewCell, NibReusable {
@IBOutlet weak var giverView: UIView!
@IBOutlet weak var giverLabel: UILabel!
@IBOutlet weak var arrowLabel: UILabel!
@IBOutlet weak var receiverView: UIView!
@IBOutlet weak var receiverLabel: UILabel!
var deal = Deal() {
didSet {
updateUI()
}
}
/// Updates user interface.
func updateUI() {
guard let giver = deal.giver,
let receiver = deal.receiver else { return }
updateGiverUI(from: giver)
updateReceiverUI(from: receiver)
if let money = NumberFormatter.currency(from: deal.money) {
arrowLabel.attributedText = formatText(from: money)
}
}
func updateGiverUI(from participant: Participant) {
giverView.layer.cornerRadius = 8
giverView.backgroundColor = participant.color
giverView.clipsToBounds = true
giverLabel.backgroundColor = .clear
giverLabel.text = participant.name
}
func updateReceiverUI(from participant: Participant) {
receiverView.layer.cornerRadius = 8
receiverView.backgroundColor = participant.color
receiverView.clipsToBounds = true
receiverLabel.backgroundColor = .clear
receiverLabel.text = participant.name
}
/// Formats text by making the money value bigger.
///
/// - Parameter money: The money to display.
/// - Returns: The formatted text.
func formatText(from money: String) -> NSMutableAttributedString {
let prefix = NSAttributedString(string: "doit\n")
let moneyString = NSAttributedString(string: ("\(money)\n"),
attributes: [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 20.0)])
let suffix = NSAttributedString(string: "à")
let formattedText = NSMutableAttributedString()
formattedText.append(prefix)
formattedText.append(moneyString)
formattedText.append(suffix)
return formattedText
}
}
| mit | 0bad2345ea31d63a189af9ea9ab88861 | 29.277778 | 120 | 0.666972 | 4.467213 | false | false | false | false |
saraheolson/PokeMongo | PokeMongo/GameViewController.swift | 1 | 1868 | //
// GameViewController.swift
// PokeMongo
//
// Created by Floater on 8/21/16.
// Copyright © 2016 SarahEOlson. All rights reserved.
//
import UIKit
import SpriteKit
import GameplayKit
class GameViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Load 'GameScene.sks' as a GKScene. This provides gameplay related content
// including entities and graphs.
if let scene = GKScene(fileNamed: "GameScene") {
// Get the SKScene from the loaded GKScene
if let sceneNode = scene.rootNode as! GameScene? {
// Copy gameplay related content over to the scene
sceneNode.entities = scene.entities
sceneNode.graphs = scene.graphs
// Set the scale mode to scale to fit the window
sceneNode.scaleMode = .aspectFill
// Present the scene
if let view = self.view as! SKView? {
view.presentScene(sceneNode)
view.ignoresSiblingOrder = true
view.showsFPS = true
view.showsNodeCount = true
}
}
}
}
override var shouldAutorotate: Bool {
return true
}
override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
if UIDevice.current.userInterfaceIdiom == .phone {
return .allButUpsideDown
} else {
return .all
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Release any cached data, images, etc that aren't in use.
}
override var prefersStatusBarHidden: Bool {
return true
}
}
| mit | f56b3c0efb5c832cca1d9726c5922820 | 27.723077 | 84 | 0.554365 | 5.674772 | false | false | false | false |
DumbDuck/VecodeKit | iOS_Mac/QuartzPicture/swift/VKQuartzPicture.swift | 1 | 1678 | import Foundation
import CoreGraphics
public enum VKPictureContentMode {
case center
case scaleToFill
case scaleAspectFit
case scaleAspectFill
}
public struct VKQuartzPicture {
var bounds: CGRect
var drawer: ((CGContext) -> Void)?
}
public func VKQuartzPictureNull() -> VKQuartzPicture {
return VKQuartzPicture(bounds: CGRect.null, drawer: nil)
}
public func VKQuartzPictureDrawInRect(_ picture: VKQuartzPicture, _ rect: CGRect, _ context: CGContext, _ mode: VKPictureContentMode) {
guard let drawer = picture.drawer else { return }
if rect.size.width < CGFloat.ulpOfOne || rect.size.height < CGFloat.ulpOfOne {
return
}
var scaleX: CGFloat = rect.size.width / picture.bounds.size.width
var scaleY: CGFloat = rect.size.height / picture.bounds.size.height
switch mode {
case .scaleAspectFit:
scaleX = min(scaleX, scaleY)
scaleY = scaleX
case .scaleAspectFill:
scaleX = max(scaleX, scaleY)
scaleY = scaleX
case .scaleToFill:
// nothing
break
case .center:
scaleX = 1.0
scaleY = 1.0
}
var pictureSize = picture.bounds.size
pictureSize.width *= scaleX
pictureSize.height *= scaleY
var offset = CGPoint.zero
offset.x = (rect.size.width - pictureSize.width) * 0.5 + rect.origin.x
offset.y = (rect.size.height - pictureSize.height) * 0.5 + rect.origin.y
context.saveGState()
context.translateBy(x: offset.x, y: offset.y)
context.scaleBy(x: scaleX, y: scaleY)
context.translateBy(x: -picture.bounds.origin.x, y: -picture.bounds.origin.y)
drawer(context)
context.restoreGState()
}
| mit | a153374b955d7406f30136c9c741ca04 | 25.634921 | 135 | 0.671633 | 3.902326 | false | false | false | false |
DasHutch/minecraft-castle-challenge | app/_src/CastleChallenge.swift | 1 | 1669 | //
// CastleChallenge.swift
// MC Castle Challenge
//
// Created by Gregory Hutchinson on 9/13/15.
// Copyright © 2015 Gregory Hutchinson. All rights reserved.
//
enum ChallengeStages: Int, CustomStringConvertible {
case WoodenAge = 0
case StoneAge
case IronAge
case GoldAge
case DiamondAge
var description: String {
get {
switch(self) {
case WoodenAge:
return "Wooden"
case StoneAge:
return "Stone"
case IronAge:
return "Iron"
case GoldAge:
return "Gold"
case DiamondAge:
return "Diamond"
}
}
}
}
struct CastleChallengeKeys {
static let Stages = "ages"
static let Requirements = "requirements"
struct RequirementsTypeKeys {
static let Construction = "construction"
static let ConstructionAdditional = "construction_additional"
static let Materials = "materials"
static let Treasure = "treasure"
}
struct StageRequriementItemKeys {
static let Item = "item"
static let Quantity = "quantity"
static let Completed = "completed"
}
}
enum ChallengeStageRequirements: Int, CustomStringConvertible {
case Construction = 0
case Materials
case Treasure
var description: String {
get {
switch(self) {
case Materials:
return "Materials"
case Construction:
return "Construction"
case Treasure:
return "Treasure"
}
}
}
}
| gpl-2.0 | f20f0857c252984d9efe7a1a0e60eaf8 | 22.842857 | 69 | 0.559353 | 4.877193 | false | false | false | false |
svdo/ReRxSwift | Pods/Nimble/Sources/Nimble/Matchers/BeGreaterThanOrEqualTo.swift | 13 | 1720 | /// A Nimble matcher that succeeds when the actual value is greater than
/// or equal to the expected value.
public func beGreaterThanOrEqualTo<T: Comparable>(_ expectedValue: T?) -> Predicate<T> {
let message = "be greater than or equal to <\(stringify(expectedValue))>"
return Predicate.simple(message) { actualExpression in
guard let actual = try actualExpression.evaluate(), let expected = expectedValue else { return .fail }
return PredicateStatus(bool: actual >= expected)
}
}
public func >=<T: Comparable>(lhs: Expectation<T>, rhs: T) {
lhs.to(beGreaterThanOrEqualTo(rhs))
}
#if canImport(Darwin)
import enum Foundation.ComparisonResult
/// A Nimble matcher that succeeds when the actual value is greater than
/// or equal to the expected value.
public func beGreaterThanOrEqualTo<T: NMBComparable>(_ expectedValue: T?) -> Predicate<T> {
let message = "be greater than or equal to <\(stringify(expectedValue))>"
return Predicate.simple(message) { actualExpression in
let actualValue = try actualExpression.evaluate()
let matches = actualValue != nil && actualValue!.NMB_compare(expectedValue) != ComparisonResult.orderedAscending
return PredicateStatus(bool: matches)
}
}
public func >=<T: NMBComparable>(lhs: Expectation<T>, rhs: T) {
lhs.to(beGreaterThanOrEqualTo(rhs))
}
extension NMBPredicate {
@objc public class func beGreaterThanOrEqualToMatcher(_ expected: NMBComparable?) -> NMBPredicate {
return NMBPredicate { actualExpression in
let expr = actualExpression.cast { $0 as? NMBComparable }
return try beGreaterThanOrEqualTo(expected).satisfies(expr).toObjectiveC()
}
}
}
#endif
| mit | bf07f48a0da96643443730089eeac455 | 39.952381 | 120 | 0.713953 | 4.858757 | false | false | false | false |
josephliccini/dijkstra-swift | Dijkstra/PriorityQueue.swift | 1 | 1628 | //
// PriorityQueue.swift
//
// Modified by Joseph Liccini on 8/23/14.
// Created by Bouke Haarsma ( https://www.github.com/Bouke )
// See: https://gist.github.com/Bouke/3dad30b8c7d2b9408b8d
// I am not implying that this code is my own. All rights belong to Bouke Haarsma
//
import Foundation
class PriorityQueue<T> {
var heap = Array<(Int, T)>()
func push(priority: Int, item: T) {
heap.append((priority, item))
if heap.count == 1 {
return
}
var current = heap.count - 1
while current > 0 {
var parent = (current - 1) >> 1
if heap[parent].0 <= heap[current].0 {
break
}
(heap[parent], heap[current]) = (heap[current], heap[parent])
current = parent
}
}
func pop() -> (priority: Int, item: T) {
(heap[0], heap[heap.count - 1]) = (heap[heap.count - 1], heap[0])
var pop = heap.removeLast()
heapify(0)
return pop
}
func heapify(index: Int) {
var left = index * 2 + 1
var right = index * 2 + 2
var smallest = index
if left < heap.count && heap[left].0 < heap[smallest].0 {
smallest = left
}
if right < heap.count && heap[right].0 < heap[smallest].0 {
smallest = right
}
if smallest != index {
(heap[index], heap[smallest]) = (heap[smallest], heap[index])
heapify(smallest)
}
}
var count: Int {
get {
return heap.count
}
}
} | mit | 95f6166e0eebdbbe6a2ad5ccd1a134d7 | 25.274194 | 83 | 0.5 | 3.716895 | false | false | false | false |
practicalswift/swift | test/IRGen/conformance_resilience.swift | 1 | 2417 | // RUN: %empty-directory(%t)
// RUN: %target-swift-frontend -emit-module -enable-resilience -emit-module-path=%t/resilient_protocol.swiftmodule -module-name=resilient_protocol %S/../Inputs/resilient_protocol.swift
// RUN: %target-swift-frontend -I %t -emit-ir -enable-resilience %s | %FileCheck %s -DINT=i%target-ptrsize
// RUN: %target-swift-frontend -I %t -emit-ir -enable-resilience -O %s
import resilient_protocol
// CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} swiftcc void @"$s22conformance_resilience14useConformanceyyx18resilient_protocol22OtherResilientProtocolRzlF"(%swift.opaque* noalias nocapture, %swift.type* %T, i8** %T.OtherResilientProtocol)
public func useConformance<T : OtherResilientProtocol>(_: T) {}
// CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} swiftcc void @"$s22conformance_resilience14getConformanceyy18resilient_protocol7WrapperVyxGlF"(%swift.opaque* noalias nocapture, %swift.type* %T)
public func getConformance<T>(_ w: Wrapper<T>) {
// CHECK: [[RESPONSE:%.*]] = call swiftcc %swift.metadata_response @"$s18resilient_protocol7WrapperVMa"([[INT]] 0, %swift.type* %T)
// CHECK: [[META:%.*]] = extractvalue %swift.metadata_response [[RESPONSE]], 0
// CHECK: [[WTABLE:%.*]] = call i8** @swift_getWitnessTable(%swift.protocol_conformance_descriptor* @"$s18resilient_protocol7WrapperVyxGAA22OtherResilientProtocolAAMc", %swift.type* [[META]], i8*** undef)
// CHECK: call swiftcc void @"$s22conformance_resilience14useConformanceyyx18resilient_protocol22OtherResilientProtocolRzlF"(%swift.opaque* noalias nocapture %0, %swift.type* [[META]], i8** [[WTABLE]])
// CHECK: ret void
useConformance(w)
}
// CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} swiftcc void @"$s22conformance_resilience14getConformanceyy18resilient_protocol15ConcreteWrapperVF"(%swift.opaque* noalias nocapture)
public func getConformance(_ w: ConcreteWrapper) {
// CHECK: [[RESPONSE:%.*]] = call swiftcc %swift.metadata_response @"$s18resilient_protocol15ConcreteWrapperVMa"([[INT]] 0)
// CHECK: [[META:%.*]] = extractvalue %swift.metadata_response [[RESPONSE]], 0
// CHECK: call swiftcc void @"$s22conformance_resilience14useConformanceyyx18resilient_protocol22OtherResilientProtocolRzlF"(%swift.opaque* noalias nocapture %0, %swift.type* [[META]], i8** @"$s18resilient_protocol15ConcreteWrapperVAA22OtherResilientProtocolAAWP")
// CHECK: ret void
useConformance(w)
}
| apache-2.0 | 199c74dc926840d0591e84b5b881e3c9 | 85.321429 | 266 | 0.747621 | 3.95581 | false | false | false | false |
fitpay/fitpay-ios-sdk | FitpaySDKTests/Rest/Models/ResultCollectionTests.swift | 1 | 7749 | import XCTest
import Nimble
@testable import FitpaySDK
class ResultCollectionTests: XCTestCase {
private let mockModels = MockModels()
private var restClient: RestClient!
private let restRequest = MockRestRequest()
override func setUp() {
let session = RestSession(restRequest: restRequest)
session.accessToken = "authorized"
restClient = RestClient(session: session, restRequest: restRequest)
}
func testResultCollectionParsing() {
let resultCollection = mockModels.getResultCollection()
expect(resultCollection?.links).toNot(beNil())
expect(resultCollection?.limit).to(equal(1))
expect(resultCollection?.offset).to(equal(1))
expect(resultCollection?.totalResults).to(equal(1))
expect(resultCollection?.results).toNot(beNil())
expect(resultCollection?.client).to(beNil())
let json = resultCollection?.toJSON()
expect(json?["_links"]).toNot(beNil())
expect(json?["limit"] as? Int).to(equal(1))
expect(json?["offset"] as? Int).to(equal(1))
expect(json?["totalResults"] as? Int).to(equal(1))
}
func testResultCollectionVerificationMethodParsing() {
let resultCollection = mockModels.getResultVerificationMethodCollection()
expect(resultCollection?.totalResults).to(equal(1))
expect(resultCollection?.results).toNot(beNil())
expect(resultCollection?.results?.count).to(equal(1))
}
func testNextAvailable() {
let resultCollection = mockModels.getResultCollection()
let nextAvailable = resultCollection?.nextAvailable
expect(nextAvailable).to(beTrue())
resultCollection?.links = nil
let nextNotAvailable = resultCollection?.nextAvailable
expect(nextNotAvailable).toNot(beTrue())
}
func testLastAvailable() {
let resultCollection = mockModels.getResultCollection()
let lastAvailable = resultCollection?.lastAvailable
expect(lastAvailable).to(beTrue())
resultCollection?.links = nil
let lastNotAvailable = resultCollection?.lastAvailable
expect(lastNotAvailable).toNot(beTrue())
}
func testPreviousAvailable() {
let resultCollection = mockModels.getResultCollection()
let previousAvailable = resultCollection?.previousAvailable
expect(previousAvailable).to(beTrue())
resultCollection?.links = nil
let previousNotAvailable = resultCollection?.previousAvailable
expect(previousNotAvailable).toNot(beTrue())
}
func testClientGetReturnsClientIfClientPresent() {
let resultCollection = mockModels.getResultCollection()
let client = RestClient(session: RestSession())
resultCollection?.client = client
expect(resultCollection?.client).to(equal(client))
}
func testClientGetReturnsClientIfResultsHaveClient() {
let resultCollection = mockModels.getResultCollection()
let client = RestClient(session: RestSession())
expect(resultCollection?.client).to(beNil())
resultCollection?.results?.first?.client = client
expect(resultCollection?.client).to(equal(client))
}
func testClientSetSetsRestClient() {
let resultCollection = mockModels.getResultCollection()
let client = RestClient(session: RestSession())
expect(resultCollection?.results?.first?.client).to(beNil())
resultCollection?.client = client
expect(resultCollection?.results?.first?.client).to(equal(client))
}
func testCollectAllAvailableNoClient() {
let resultCollection = mockModels.getResultCollection()
waitUntil { done in
resultCollection?.collectAllAvailable { (devices, error) in
expect(devices).to(beNil())
expect(error).toNot(beNil())
done()
}
}
}
func testCollectAllAvailableNoNext() {
let resultCollection = mockModels.getResultCollection()
resultCollection?.links?["next"] = nil
waitUntil { done in
resultCollection?.collectAllAvailable { (devices, error) in
expect(devices).toNot(beNil())
expect(devices?.count).to(equal(1))
expect(error).to(beNil())
done()
}
}
}
func testCollectAllAvailable() {
let resultCollection = mockModels.getResultCollection()
resultCollection?.client = restClient
waitUntil { done in
resultCollection?.collectAllAvailable { (devices, error) in
expect(devices).toNot(beNil())
expect(devices?.count).to(equal(2))
expect(error).to(beNil())
done()
}
}
}
func testNextNoClient() {
let resultCollection = mockModels.getResultCollection()
waitUntil { done in
resultCollection?.next { (collection: ResultCollection<Device>?, error: ErrorResponse?) in
expect(collection).to(beNil())
expect(error).toNot(beNil())
done()
}
}
}
func testNext() {
let resultCollection = mockModels.getResultCollection()
resultCollection?.client = restClient
waitUntil { done in
resultCollection?.next { (collection: ResultCollection<Device>?, error: ErrorResponse?) in
expect(collection).toNot(beNil())
expect(collection?.results?.count).to(equal(1))
expect(error).to(beNil())
done()
}
}
}
func testLastNoClient() {
let resultCollection = mockModels.getResultCollection()
waitUntil { done in
resultCollection?.last { (collection: ResultCollection<Device>?, error: ErrorResponse?) in
expect(collection).to(beNil())
expect(error).toNot(beNil())
done()
}
}
}
func testLast() {
let resultCollection = mockModels.getResultCollection()
resultCollection?.client = restClient
waitUntil { done in
resultCollection?.last { (collection: ResultCollection<Device>?, error: ErrorResponse?) in
expect(collection).toNot(beNil())
expect(collection?.results?.count).to(equal(1))
expect(error).to(beNil())
done()
}
}
}
func testPreviousNoClient() {
let resultCollection = mockModels.getResultCollection()
waitUntil { done in
resultCollection?.previous { (collection: ResultCollection<Device>?, error: ErrorResponse?) in
expect(collection).to(beNil())
expect(error).toNot(beNil())
done()
}
}
}
func testPrevious() {
let resultCollection = mockModels.getResultCollection()
resultCollection?.client = restClient
waitUntil { done in
resultCollection?.previous { (collection: ResultCollection<Device>?, error: ErrorResponse?) in
expect(collection).toNot(beNil())
expect(collection?.results?.count).to(equal(1))
expect(error).to(beNil())
done()
}
}
}
}
| mit | 434192ff4ea1b8245e7dd26275484713 | 31.834746 | 106 | 0.588592 | 5.407537 | false | true | false | false |
PigDogBay/Food-Hygiene-Ratings | Food Hygiene Ratings/WebViewController.swift | 1 | 2336 | //
// WebViewController.swift
// Food Hygiene Ratings
//
// Created by Mark Bailey on 12/02/2017.
// Copyright © 2017 MPD Bailey Technology. All rights reserved.
//
import UIKit
import WebKit
class WebViewController: UIViewController, WKNavigationDelegate {
@IBOutlet weak var webContainer: UIView!
@IBOutlet weak var navigationBar: UINavigationItem!
@IBOutlet weak var loadingIndicator: UIActivityIndicatorView!
@IBOutlet weak var loadingLabel: UILabel!
var navTitle : String!
var url : URL!
fileprivate var webView: WKWebView!
override func viewDidLoad() {
super.viewDidLoad()
webView = WKWebView(frame: webContainer.frame)
webView.navigationDelegate = self
webContainer.addSubview(webView)
constrainView(view: webView, toView: webContainer)
navigationBar.title = navTitle
let request = URLRequest(url: url)
webView.load(request)
}
//https://stackoverflow.com/questions/40856112/how-to-create-a-sized-wkwebview-in-swift-3-ios-10
func constrainView(view:UIView, toView contentView:UIView) {
view.translatesAutoresizingMaskIntoConstraints = false
view.leadingAnchor.constraint(equalTo: contentView.leadingAnchor).isActive = true
view.topAnchor.constraint(equalTo: contentView.topAnchor).isActive = true
view.trailingAnchor.constraint(equalTo: contentView.trailingAnchor).isActive = true
view.bottomAnchor.constraint(equalTo: contentView.bottomAnchor).isActive = true
}
override func viewWillDisappear(_ animated: Bool) {
webView.stopLoading()
}
override func didReceiveMemoryWarning()
{
super.didReceiveMemoryWarning()
webView.stopLoading()
}
//MARK:- WKNavigationDelegate
func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
loadingIndicator.startAnimating()
loadingLabel.isHidden=false
}
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
loadingIndicator.stopAnimating()
loadingLabel.isHidden=true
}
func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
loadingIndicator.stopAnimating()
loadingLabel.isHidden=true
}
}
| apache-2.0 | 60621fdc539cca2bc5322e5763ba7bc0 | 32.84058 | 100 | 0.707495 | 5.223714 | false | false | false | false |
timfuqua/Bourgeoisie | Bourgeoisie/Bourgeoisie/Model/BourgAlgorithms.swift | 1 | 38008 | //
// BourgAlgorithms.swift
// Bourgeoisie
//
// Created by Tim Fuqua on 1/4/16.
// Copyright © 2016 FuquaProductions. All rights reserved.
//
import Foundation
import UIKit
// MARK: BourgAlgorithms
/**
A namespace for algorithms relating to Bourgeoisie game logic
*/
final class BourgAlgorithms {
// MARK: class vars
enum FlushRanking: Int {
case NoCards = 0
case OneCardFlushAce
case OneCardFlushTwo
case OneCardFlushThree
case OneCardFlushFour
case OneCardFlushFive
case OneCardFlushSix
case OneCardFlushSeven
case OneCardFlushEight
case OneCardFlushNine
case OneCardFlushTen
case TwoCardFlushAce
case TwoCardFlushTwo
case TwoCardFlushThree
case TwoCardFlushFour
case TwoCardFlushFive
case TwoCardFlushSix
case TwoCardFlushSeven
case TwoCardFlushEight
case TwoCardFlushNine
case TwoCardFlushTen
case ThreeCardFlushTwo
case ThreeCardFlushThree
case ThreeCardFlushFour
case ThreeCardFlushFive
case ThreeCardFlushSix
case ThreeCardFlushSeven
case ThreeCardFlushEight
case ThreeCardFlushNine
case ThreeCardFlushTen
case FourCardFlushThree
case FourCardFlushFour
case FourCardFlushFive
case FourCardFlushSix
case FourCardFlushSeven
case FourCardFlushEight
case FourCardFlushNine
case FourCardFlushTen
case FiveCardFlushFour
case FiveCardFlushFive
case FiveCardFlushSix
case FiveCardFlushSeven
case FiveCardFlushEight
case FiveCardFlushNine
case FiveCardFlushTen
static var Lowest: FlushRanking { get { return OneCardFlushAce } }
static var TierOne: FlushRanking { get { return OneCardFlushAce } }
static var TierTwo: FlushRanking { get { return TwoCardFlushAce } }
static var TierThree: FlushRanking { get { return ThreeCardFlushTwo } }
static var TierFour: FlushRanking { get { return FourCardFlushThree } }
static var TierFive: FlushRanking { get { return FiveCardFlushFour } }
static var Highest: FlushRanking { get { return FiveCardFlushTen } }
func totalRanks() -> Int {
return FlushRanking.Highest.rawValue - FlushRanking.Lowest.rawValue + 1
}
func rankPercentile() -> CGFloat {
return CGFloat(self.rawValue)/CGFloat(totalRanks())*100.0
}
func description() -> String {
switch self.rawValue {
case NoCards.rawValue: return "No card flush"
case OneCardFlushAce.rawValue: return "Ace high one card flush"
case OneCardFlushTwo.rawValue: return "Two high one card flush"
case OneCardFlushThree.rawValue: return "Three high one card flush"
case OneCardFlushFour.rawValue: return "Four high one card flush"
case OneCardFlushFive.rawValue: return "Five high one card flush"
case OneCardFlushSix.rawValue: return "Six high one card flush"
case OneCardFlushSeven.rawValue: return "Seven high one card flush"
case OneCardFlushEight.rawValue: return "Eight high one card flush"
case OneCardFlushNine.rawValue: return "Nine high one card flush"
case OneCardFlushTen.rawValue: return "Ten high one card flush"
case TwoCardFlushAce.rawValue: return "Ace high two card flush"
case TwoCardFlushTwo.rawValue: return "Two high two card flush"
case TwoCardFlushThree.rawValue: return "Three high two card flush"
case TwoCardFlushFour.rawValue: return "Four high two card flush"
case TwoCardFlushFive.rawValue: return "Five high two card flush"
case TwoCardFlushSix.rawValue: return "Six high two card flush"
case TwoCardFlushSeven.rawValue: return "Seven high two card flush"
case TwoCardFlushEight.rawValue: return "Eight high two card flush"
case TwoCardFlushNine.rawValue: return "Nine high two card flush"
case TwoCardFlushTen.rawValue: return "Ten high two card flush"
case ThreeCardFlushTwo.rawValue: return "Two high three card flush"
case ThreeCardFlushThree.rawValue: return "Three high three card flush"
case ThreeCardFlushFour.rawValue: return "Four high three card flush"
case ThreeCardFlushFive.rawValue: return "Five high three card flush"
case ThreeCardFlushSix.rawValue: return "Six high three card flush"
case ThreeCardFlushSeven.rawValue: return "Seven high three card flush"
case ThreeCardFlushEight.rawValue: return "Eight high three card flush"
case ThreeCardFlushNine.rawValue: return "Nine high three card flush"
case ThreeCardFlushTen.rawValue: return "Ten high three card flush"
case FourCardFlushThree.rawValue: return "Three high four card flush"
case FourCardFlushFour.rawValue: return "Four high four card flush"
case FourCardFlushFive.rawValue: return "Five high four card flush"
case FourCardFlushSix.rawValue: return "Six high four card flush"
case FourCardFlushSeven.rawValue: return "Seven high four card flush"
case FourCardFlushEight.rawValue: return "Eight high four card flush"
case FourCardFlushNine.rawValue: return "Nine high four card flush"
case FourCardFlushTen.rawValue: return "Ten high four card flush"
case FiveCardFlushFour.rawValue: return "Four high five card flush"
case FiveCardFlushFive.rawValue: return "Five high five card flush"
case FiveCardFlushSix.rawValue: return "Six high five card flush"
case FiveCardFlushSeven.rawValue: return "Seven high five card flush"
case FiveCardFlushEight.rawValue: return "Eight high five card flush"
case FiveCardFlushNine.rawValue: return "Nine high five card flush"
case FiveCardFlushTen.rawValue: return "Ten high five card flush"
default: fatalError("Not a FlushRanking")
}
}
}
enum StraightRanking: Int {
case NoCards = 0
case OneCardStraightAce
case OneCardStraightTwo
case OneCardStraightThree
case OneCardStraightFour
case OneCardStraightFive
case OneCardStraightSix
case OneCardStraightSeven
case OneCardStraightEight
case OneCardStraightNine
case OneCardStraightTen
case TwoCardStraightTwo
case TwoCardStraightThree
case TwoCardStraightFour
case TwoCardStraightFive
case TwoCardStraightSix
case TwoCardStraightSeven
case TwoCardStraightEight
case TwoCardStraightNine
case TwoCardStraightTen
case ThreeCardStraightThree
case ThreeCardStraightFour
case ThreeCardStraightFive
case ThreeCardStraightSix
case ThreeCardStraightSeven
case ThreeCardStraightEight
case ThreeCardStraightNine
case ThreeCardStraightTen
case FourCardStraightFour
case FourCardStraightFive
case FourCardStraightSix
case FourCardStraightSeven
case FourCardStraightEight
case FourCardStraightNine
case FourCardStraightTen
case FiveCardStraightFive
case FiveCardStraightSix
case FiveCardStraightSeven
case FiveCardStraightEight
case FiveCardStraightNine
case FiveCardStraightTen
static var Lowest: StraightRanking { get { return OneCardStraightAce } }
static var TierOne: StraightRanking { get { return OneCardStraightAce } }
static var TierTwo: StraightRanking { get { return TwoCardStraightTwo } }
static var TierThree: StraightRanking { get { return ThreeCardStraightThree } }
static var TierFour: StraightRanking { get { return FourCardStraightFour } }
static var TierFive: StraightRanking { get { return FiveCardStraightFive } }
static var Highest: StraightRanking { get { return FiveCardStraightTen } }
func totalRanks() -> Int {
return StraightRanking.Highest.rawValue - StraightRanking.Lowest.rawValue + 1
}
func rankPercentile() -> CGFloat {
return CGFloat(self.rawValue)/CGFloat(totalRanks())*100
}
func description() -> String {
switch self.rawValue {
case NoCards.rawValue: return "No card straight"
case OneCardStraightAce.rawValue: return "Ace high one card straight"
case OneCardStraightTwo.rawValue: return "Two high one card straight"
case OneCardStraightThree.rawValue: return "Three high one card straight"
case OneCardStraightFour.rawValue: return "Four high one card straight"
case OneCardStraightFive.rawValue: return "Five high one card straight"
case OneCardStraightSix.rawValue: return "Six high one card straight"
case OneCardStraightSeven.rawValue: return "Seven high one card straight"
case OneCardStraightEight.rawValue: return "Eight high one card straight"
case OneCardStraightNine.rawValue: return "Nine high one card straight"
case OneCardStraightTen.rawValue: return "Ten high one card straight"
case TwoCardStraightTwo.rawValue: return "Two high two card straight"
case TwoCardStraightThree.rawValue: return "Three high two card straight"
case TwoCardStraightFour.rawValue: return "Four high two card straight"
case TwoCardStraightFive.rawValue: return "Five high two card straight"
case TwoCardStraightSix.rawValue: return "Six high two card straight"
case TwoCardStraightSeven.rawValue: return "Seven high two card straight"
case TwoCardStraightEight.rawValue: return "Eight high two card straight"
case TwoCardStraightNine.rawValue: return "Nine high two card straight"
case TwoCardStraightTen.rawValue: return "Ten high two card straight"
case ThreeCardStraightThree.rawValue: return "Three high three card straight"
case ThreeCardStraightFour.rawValue: return "Four high three card straight"
case ThreeCardStraightFive.rawValue: return "Five high three card straight"
case ThreeCardStraightSix.rawValue: return "Six high three card straight"
case ThreeCardStraightSeven.rawValue: return "Seven high three card straight"
case ThreeCardStraightEight.rawValue: return "Eight high three card straight"
case ThreeCardStraightNine.rawValue: return "Nine high three card straight"
case ThreeCardStraightTen.rawValue: return "Ten high three card straight"
case FourCardStraightFour.rawValue: return "Four high four card straight"
case FourCardStraightFive.rawValue: return "Five high four card straight"
case FourCardStraightSix.rawValue: return "Six high four card straight"
case FourCardStraightSeven.rawValue: return "Seven high four card straight"
case FourCardStraightEight.rawValue: return "Eight high four card straight"
case FourCardStraightNine.rawValue: return "Nine high four card straight"
case FourCardStraightTen.rawValue: return "Ten high four card straight"
case FiveCardStraightFive.rawValue: return "Five high five card straight"
case FiveCardStraightSix.rawValue: return "Six high five card straight"
case FiveCardStraightSeven.rawValue: return "Seven high five card straight"
case FiveCardStraightEight.rawValue: return "Eight high five card straight"
case FiveCardStraightNine.rawValue: return "Nine high five card straight"
case FiveCardStraightTen.rawValue: return "Ten high five card straight"
default: fatalError("Not a StraightRanking")
}
}
}
enum BookRanking: Int {
case NoCards = 0
case OneCardBookAce
case OneCardBookTwo
case OneCardBookThree
case OneCardBookFour
case OneCardBookFive
case OneCardBookSix
case OneCardBookSeven
case OneCardBookEight
case OneCardBookNine
case OneCardBookTen
case TwoCardBookAce
case TwoCardBookTwo
case TwoCardBookThree
case TwoCardBookFour
case TwoCardBookFive
case TwoCardBookSix
case TwoCardBookSeven
case TwoCardBookEight
case TwoCardBookNine
case TwoCardBookTen
case TwoPairBookAceTwo
case TwoPairBookAceThree
case TwoPairBookTwoThree
case TwoPairBookAceFour
case TwoPairBookTwoFour
case TwoPairBookThreeFour
case TwoPairBookAceFive
case TwoPairBookTwoFive
case TwoPairBookThreeFive
case TwoPairBookFourFive
case TwoPairBookAceSix
case TwoPairBookTwoSix
case TwoPairBookThreeSix
case TwoPairBookFourSix
case TwoPairBookFiveSix
case TwoPairBookAceSeven
case TwoPairBookTwoSeven
case TwoPairBookThreeSeven
case TwoPairBookFourSeven
case TwoPairBookFiveSeven
case TwoPairBookSixSeven
case TwoPairBookAceEight
case TwoPairBookTwoEight
case TwoPairBookThreeEight
case TwoPairBookFourEight
case TwoPairBookFiveEight
case TwoPairBookSixEight
case TwoPairBookSevenEight
case TwoPairBookAceNine
case TwoPairBookTwoNine
case TwoPairBookThreeNine
case TwoPairBookFourNine
case TwoPairBookFiveNine
case TwoPairBookSixNine
case TwoPairBookSevenNine
case TwoPairBookEightNine
case TwoPairBookAceTen
case TwoPairBookTwoTen
case TwoPairBookThreeTen
case TwoPairBookFourTen
case TwoPairBookFiveTen
case TwoPairBookSixTen
case TwoPairBookSevenTen
case TwoPairBookEightTen
case TwoPairBookNineTen
case ThreeCardBookAce
case ThreeCardBookTwo
case ThreeCardBookThree
case ThreeCardBookFour
case ThreeCardBookFive
case ThreeCardBookSix
case ThreeCardBookSeven
case ThreeCardBookEight
case ThreeCardBookNine
case ThreeCardBookTen
case FullHouseBookAceTwo
case FullHouseBookAceThree
case FullHouseBookAceFour
case FullHouseBookAceFive
case FullHouseBookAceSix
case FullHouseBookAceSeven
case FullHouseBookAceEight
case FullHouseBookAceNine
case FullHouseBookAceTen
case FullHouseBookTwoAce
case FullHouseBookTwoThree
case FullHouseBookTwoFour
case FullHouseBookTwoFive
case FullHouseBookTwoSix
case FullHouseBookTwoSeven
case FullHouseBookTwoEight
case FullHouseBookTwoNine
case FullHouseBookTwoTen
case FullHouseBookThreeAce
case FullHouseBookThreeTwo
case FullHouseBookThreeFour
case FullHouseBookThreeFive
case FullHouseBookThreeSix
case FullHouseBookThreeSeven
case FullHouseBookThreeEight
case FullHouseBookThreeNine
case FullHouseBookThreeTen
case FullHouseBookFourAce
case FullHouseBookFourTwo
case FullHouseBookFourThree
case FullHouseBookFourFive
case FullHouseBookFourSix
case FullHouseBookFourSeven
case FullHouseBookFourEight
case FullHouseBookFourNine
case FullHouseBookFourTen
case FullHouseBookFiveAce
case FullHouseBookFiveTwo
case FullHouseBookFiveThree
case FullHouseBookFiveFour
case FullHouseBookFiveSix
case FullHouseBookFiveSeven
case FullHouseBookFiveEight
case FullHouseBookFiveNine
case FullHouseBookFiveTen
case FullHouseBookSixAce
case FullHouseBookSixTwo
case FullHouseBookSixThree
case FullHouseBookSixFour
case FullHouseBookSixFive
case FullHouseBookSixSeven
case FullHouseBookSixEight
case FullHouseBookSixNine
case FullHouseBookSixTen
case FullHouseBookSevenAce
case FullHouseBookSevenTwo
case FullHouseBookSevenThree
case FullHouseBookSevenFour
case FullHouseBookSevenFive
case FullHouseBookSevenSix
case FullHouseBookSevenEight
case FullHouseBookSevenNine
case FullHouseBookSevenTen
case FullHouseBookEightAce
case FullHouseBookEightTwo
case FullHouseBookEightThree
case FullHouseBookEightFour
case FullHouseBookEightFive
case FullHouseBookEightSix
case FullHouseBookEightSeven
case FullHouseBookEightNine
case FullHouseBookEightTen
case FullHouseBookNineAce
case FullHouseBookNineTwo
case FullHouseBookNineThree
case FullHouseBookNineFour
case FullHouseBookNineFive
case FullHouseBookNineSix
case FullHouseBookNineSeven
case FullHouseBookNineEight
case FullHouseBookNineTen
case FullHouseBookTenAce
case FullHouseBookTenTwo
case FullHouseBookTenThree
case FullHouseBookTenFour
case FullHouseBookTenFive
case FullHouseBookTenSix
case FullHouseBookTenSeven
case FullHouseBookTenEight
case FullHouseBookTenNine
case FourCardBookAce
case FourCardBookTwo
case FourCardBookThree
case FourCardBookFour
case FourCardBookFive
case FourCardBookSix
case FourCardBookSeven
case FourCardBookEight
case FourCardBookNine
case FourCardBookTen
case FiveCardBookAce
case FiveCardBookTwo
case FiveCardBookThree
case FiveCardBookFour
case FiveCardBookFive
case FiveCardBookSix
case FiveCardBookSeven
case FiveCardBookEight
case FiveCardBookNine
case FiveCardBookTen
static var Lowest: BookRanking { get { return OneCardBookAce } }
static var TierOne: BookRanking { get { return OneCardBookAce } }
static var TierTwo: BookRanking { get { return TwoCardBookAce } }
static var TierThree: BookRanking { get { return TwoPairBookAceTwo } }
static var TierFour: BookRanking { get { return ThreeCardBookAce } }
static var TierFive: BookRanking { get { return FullHouseBookAceTwo } }
static var TierSix: BookRanking { get { return FourCardBookAce } }
static var TierSeven: BookRanking { get { return FiveCardBookAce } }
static var Highest: BookRanking { get { return FiveCardBookTen } }
func totalRanks() -> Int {
return BookRanking.Highest.rawValue - BookRanking.Lowest.rawValue + 1
}
func rankPercentile() -> CGFloat {
return CGFloat(self.rawValue)/CGFloat(totalRanks())*100.0
}
func description() -> String {
switch self.rawValue {
case NoCards.rawValue: return "No card book"
case OneCardBookAce.rawValue: return "Ace high one of kind"
case OneCardBookTwo.rawValue: return "Two high one of kind"
case OneCardBookThree.rawValue: return "Three high one of kind"
case OneCardBookFour.rawValue: return "Four high one of kind"
case OneCardBookFive.rawValue: return "Five high one of kind"
case OneCardBookSix.rawValue: return "Six high one of kind"
case OneCardBookSeven.rawValue: return "Seven high one of kind"
case OneCardBookEight.rawValue: return "Eight high one of kind"
case OneCardBookNine.rawValue: return "Nine high one of kind"
case OneCardBookTen.rawValue: return "Ten high one of kind"
case TwoCardBookAce.rawValue: return "Ace high two of a kind"
case TwoCardBookTwo.rawValue: return "Two high two of a kind"
case TwoCardBookThree.rawValue: return "Three high two of a kind"
case TwoCardBookFour.rawValue: return "Four high two of a kind"
case TwoCardBookFive.rawValue: return "Five high two of a kind"
case TwoCardBookSix.rawValue: return "Six high two of a kind"
case TwoCardBookSeven.rawValue: return "Seven high two of a kind"
case TwoCardBookEight.rawValue: return "Eight high two of a kind"
case TwoCardBookNine.rawValue: return "Nine high two of a kind"
case TwoCardBookTen.rawValue: return "Ten high two of a kind"
case TwoPairBookAceTwo.rawValue: return "Two pair of Aces and Twos"
case TwoPairBookAceThree.rawValue: return "Two pair of Aces and Threes"
case TwoPairBookTwoThree.rawValue: return "Two pair of Twos and Threes"
case TwoPairBookAceFour.rawValue: return "Two pair of Aces and Fours"
case TwoPairBookTwoFour.rawValue: return "Two pair of Twos and Fours"
case TwoPairBookThreeFour.rawValue: return "Two pair of Threes and Fours"
case TwoPairBookAceFive.rawValue: return "Two pair of Aces and Fives"
case TwoPairBookTwoFive.rawValue: return "Two pair of Twos and Fives"
case TwoPairBookThreeFive.rawValue: return "Two pair of Threes and Fives"
case TwoPairBookFourFive.rawValue: return "Two pair of Fours and Fives"
case TwoPairBookAceSix.rawValue: return "Two pair of Aces and Sixes"
case TwoPairBookTwoSix.rawValue: return "Two pair of Twos and Sixes"
case TwoPairBookThreeSix.rawValue: return "Two pair of Threes and Sixes"
case TwoPairBookFourSix.rawValue: return "Two pair of Fours and Sixes"
case TwoPairBookFiveSix.rawValue: return "Two pair of Fives and Sixes"
case TwoPairBookAceSeven.rawValue: return "Two pair of Aces and Sevens"
case TwoPairBookTwoSeven.rawValue: return "Two pair of Twos and Sevens"
case TwoPairBookThreeSeven.rawValue: return "Two pair of Threes and Sevens"
case TwoPairBookFourSeven.rawValue: return "Two pair of Fours and Sevens"
case TwoPairBookFiveSeven.rawValue: return "Two pair of Fives and Sevens"
case TwoPairBookSixSeven.rawValue: return "Two pair of Sixes and Sevens"
case TwoPairBookAceEight.rawValue: return "Two pair of Aces and Eights"
case TwoPairBookTwoEight.rawValue: return "Two pair of Twos and Eights"
case TwoPairBookThreeEight.rawValue: return "Two pair of Threes and Eights"
case TwoPairBookFourEight.rawValue: return "Two pair of Fours and Eights"
case TwoPairBookFiveEight.rawValue: return "Two pair of Fives and Eights"
case TwoPairBookSixEight.rawValue: return "Two pair of Sixes and Eights"
case TwoPairBookSevenEight.rawValue: return "Two pair of Sevens and Eights"
case TwoPairBookAceNine.rawValue: return "Two pair of Aces and Nines"
case TwoPairBookTwoNine.rawValue: return "Two pair of Twos and Nines"
case TwoPairBookThreeNine.rawValue: return "Two pair of Threes and Nines"
case TwoPairBookFourNine.rawValue: return "Two pair of Fours and Nines"
case TwoPairBookFiveNine.rawValue: return "Two pair of Fives and Nines"
case TwoPairBookSixNine.rawValue: return "Two pair of Sixes and Nines"
case TwoPairBookSevenNine.rawValue: return "Two pair of Sevens and Nines"
case TwoPairBookEightNine.rawValue: return "Two pair of Eights and Nines"
case TwoPairBookAceTen.rawValue: return "Two pair of Aces and Tens"
case TwoPairBookTwoTen.rawValue: return "Two pair of Twos and Tens"
case TwoPairBookThreeTen.rawValue: return "Two pair of Threes and Tens"
case TwoPairBookFourTen.rawValue: return "Two pair of Fours and Tens"
case TwoPairBookFiveTen.rawValue: return "Two pair of Fives and Tens"
case TwoPairBookSixTen.rawValue: return "Two pair of Sixes and Tens"
case TwoPairBookSevenTen.rawValue: return "Two pair of Sevens and Tens"
case TwoPairBookEightTen.rawValue: return "Two pair of Eights and Tens"
case TwoPairBookNineTen.rawValue: return "Two pair of Nines and Tens"
case ThreeCardBookAce.rawValue: return "Ace high three of a kind"
case ThreeCardBookTwo.rawValue: return "Two high three of a kind"
case ThreeCardBookThree.rawValue: return "Three high three of a kind"
case ThreeCardBookFour.rawValue: return "Four high three of a kind"
case ThreeCardBookFive.rawValue: return "Five high three of a kind"
case ThreeCardBookSix.rawValue: return "Six high three of a kind"
case ThreeCardBookSeven.rawValue: return "Seven high three of a kind"
case ThreeCardBookEight.rawValue: return "Eight high three of a kind"
case ThreeCardBookNine.rawValue: return "Nine high three of a kind"
case ThreeCardBookTen.rawValue: return "Ten high three of a kind"
case FullHouseBookAceTwo.rawValue: return "Full house of Aces over Twos"
case FullHouseBookAceThree.rawValue: return "Full house of Aces over Threes"
case FullHouseBookAceFour.rawValue: return "Full house of Aces over Fours"
case FullHouseBookAceFive.rawValue: return "Full house of Aces over Fives"
case FullHouseBookAceSix.rawValue: return "Full house of Aces over Sixes"
case FullHouseBookAceSeven.rawValue: return "Full house of Aces over Sevens"
case FullHouseBookAceEight.rawValue: return "Full house of Aces over Eights"
case FullHouseBookAceNine.rawValue: return "Full house of Aces over Nines"
case FullHouseBookAceTen.rawValue: return "Full house of Aces over Tens"
case FullHouseBookTwoAce.rawValue: return "Full house of Twos over Aces"
case FullHouseBookTwoThree.rawValue: return "Full house of Twos over Threes"
case FullHouseBookTwoFour.rawValue: return "Full house of Twos over Fours"
case FullHouseBookTwoFive.rawValue: return "Full house of Twos over Fives"
case FullHouseBookTwoSix.rawValue: return "Full house of Twos over Sixes"
case FullHouseBookTwoSeven.rawValue: return "Full house of Twos over Sevens"
case FullHouseBookTwoEight.rawValue: return "Full house of Twos over Eights"
case FullHouseBookTwoNine.rawValue: return "Full house of Twos over Nines"
case FullHouseBookTwoTen.rawValue: return "Full house of Twos over Tens"
case FullHouseBookThreeAce.rawValue: return "Full house of Threes over Aces"
case FullHouseBookThreeTwo.rawValue: return "Full house of Threes over Twos"
case FullHouseBookThreeFour.rawValue: return "Full house of Threes over Fours"
case FullHouseBookThreeFive.rawValue: return "Full house of Threes over Fives"
case FullHouseBookThreeSix.rawValue: return "Full house of Threes over Sixes"
case FullHouseBookThreeSeven.rawValue: return "Full house of Threes over Sevens"
case FullHouseBookThreeEight.rawValue: return "Full house of Threes over Eights"
case FullHouseBookThreeNine.rawValue: return "Full house of Threes over Nines"
case FullHouseBookThreeTen.rawValue: return "Full house of Threes over Tens"
case FullHouseBookFourAce.rawValue: return "Full house of Fours over Aces"
case FullHouseBookFourTwo.rawValue: return "Full house of Fours over Twos"
case FullHouseBookFourThree.rawValue: return "Full house of Fours over Threes"
case FullHouseBookFourFive.rawValue: return "Full house of Fours over Fives"
case FullHouseBookFourSix.rawValue: return "Full house of Fours over Sixes"
case FullHouseBookFourSeven.rawValue: return "Full house of Fours over Sevens"
case FullHouseBookFourEight.rawValue: return "Full house of Fours over Eights"
case FullHouseBookFourNine.rawValue: return "Full house of Fours over Nines"
case FullHouseBookFourTen.rawValue: return "Full house of Fours over Tens"
case FullHouseBookFiveAce.rawValue: return "Full house of Fives over Aces"
case FullHouseBookFiveTwo.rawValue: return "Full house of Fives over Twos"
case FullHouseBookFiveThree.rawValue: return "Full house of Fives over Threes"
case FullHouseBookFiveFour.rawValue: return "Full house of Fives over Fours"
case FullHouseBookFiveSix.rawValue: return "Full house of Fives over Sixes"
case FullHouseBookFiveSeven.rawValue: return "Full house of Fives over Sevens"
case FullHouseBookFiveEight.rawValue: return "Full house of Fives over Eights"
case FullHouseBookFiveNine.rawValue: return "Full house of Fives over Nines"
case FullHouseBookFiveTen.rawValue: return "Full house of Fives over Tens"
case FullHouseBookSixAce.rawValue: return "Full house of Sixes over Aces"
case FullHouseBookSixTwo.rawValue: return "Full house of Sixes over Twos"
case FullHouseBookSixThree.rawValue: return "Full house of Sixes over Threes"
case FullHouseBookSixFour.rawValue: return "Full house of Sixes over Fours"
case FullHouseBookSixFive.rawValue: return "Full house of Sixes over Fives"
case FullHouseBookSixSeven.rawValue: return "Full house of Sixes over Sevens"
case FullHouseBookSixEight.rawValue: return "Full house of Sixes over Eights"
case FullHouseBookSixNine.rawValue: return "Full house of Sixes over Nines"
case FullHouseBookSixTen.rawValue: return "Full house of Sixes over Tens"
case FullHouseBookSevenAce.rawValue: return "Full house of Sevens over Aces"
case FullHouseBookSevenTwo.rawValue: return "Full house of Sevens over Twos"
case FullHouseBookSevenThree.rawValue: return "Full house of Sevens over Threes"
case FullHouseBookSevenFour.rawValue: return "Full house of Sevens over Fours"
case FullHouseBookSevenFive.rawValue: return "Full house of Sevens over Fives"
case FullHouseBookSevenSix.rawValue: return "Full house of Sevens over Sixes"
case FullHouseBookSevenEight.rawValue: return "Full house of Sevens over Eights"
case FullHouseBookSevenNine.rawValue: return "Full house of Sevens over Nines"
case FullHouseBookSevenTen.rawValue: return "Full house of Sevens over Tens"
case FullHouseBookEightAce.rawValue: return "Full house of Eights over Aces"
case FullHouseBookEightTwo.rawValue: return "Full house of Eights over Twos"
case FullHouseBookEightThree.rawValue: return "Full house of Eights over Threes"
case FullHouseBookEightFour.rawValue: return "Full house of Eights over Fours"
case FullHouseBookEightFive.rawValue: return "Full house of Eights over Fives"
case FullHouseBookEightSix.rawValue: return "Full house of Eights over Sixes"
case FullHouseBookEightSeven.rawValue: return "Full house of Eights over Sevens"
case FullHouseBookEightNine.rawValue: return "Full house of Eights over Nines"
case FullHouseBookEightTen.rawValue: return "Full house of Eights over Tens"
case FullHouseBookNineAce.rawValue: return "Full house of Nines over Aces"
case FullHouseBookNineTwo.rawValue: return "Full house of Nines over Twos"
case FullHouseBookNineThree.rawValue: return "Full house of Nines over Threes"
case FullHouseBookNineFour.rawValue: return "Full house of Nines over Fours"
case FullHouseBookNineFive.rawValue: return "Full house of Nines over Fives"
case FullHouseBookNineSix.rawValue: return "Full house of Nines over Sixes"
case FullHouseBookNineSeven.rawValue: return "Full house of Nines over Sevens"
case FullHouseBookNineEight.rawValue: return "Full house of Nines over Eights"
case FullHouseBookNineTen.rawValue: return "Full house of Nines over Tens"
case FullHouseBookTenAce.rawValue: return "Full house of Tens over Aces"
case FullHouseBookTenTwo.rawValue: return "Full house of Tens over Twos"
case FullHouseBookTenThree.rawValue: return "Full house of Tens over Threes"
case FullHouseBookTenFour.rawValue: return "Full house of Tens over Fours"
case FullHouseBookTenFive.rawValue: return "Full house of Tens over Fives"
case FullHouseBookTenSix.rawValue: return "Full house of Tens over Sixes"
case FullHouseBookTenSeven.rawValue: return "Full house of Tens over Sevens"
case FullHouseBookTenEight.rawValue: return "Full house of Tens over Eights"
case FullHouseBookTenNine.rawValue: return "Full house of Tens over Nines"
case FourCardBookAce.rawValue: return "Ace high four of a kind"
case FourCardBookTwo.rawValue: return "Two high four of a kind"
case FourCardBookThree.rawValue: return "Three high four of a kind"
case FourCardBookFour.rawValue: return "Four high four of a kind"
case FourCardBookFive.rawValue: return "Five high four of a kind"
case FourCardBookSix.rawValue: return "Six high four of a kind"
case FourCardBookSeven.rawValue: return "Seven high four of a kind"
case FourCardBookEight.rawValue: return "Eight high four of a kind"
case FourCardBookNine.rawValue: return "Nine high four of a kind"
case FourCardBookTen.rawValue: return "Ten high four of a kind"
case FiveCardBookAce.rawValue: return "Ace high five of a kind"
case FiveCardBookTwo.rawValue: return "Two high five of a kind"
case FiveCardBookThree.rawValue: return "Three high five of a kind"
case FiveCardBookFour.rawValue: return "Four high five of a kind"
case FiveCardBookFive.rawValue: return "Five high five of a kind"
case FiveCardBookSix.rawValue: return "Six high five of a kind"
case FiveCardBookSeven.rawValue: return "Seven high five of a kind"
case FiveCardBookEight.rawValue: return "Eight high five of a kind"
case FiveCardBookNine.rawValue: return "Nine high five of a kind"
case FiveCardBookTen.rawValue: return "Ten high five of a kind"
default: fatalError("Not a BookRanking")
}
}
}
// MARK: private lets
// MARK: private vars (computed)
// MARK: private vars
// MARK: private(set) vars
// MARK: lets
// MARK: vars (computed)
// MARK: vars
// MARK: init
// MARK: public funcs
// MARK: private funcs
private init() {}
// MARK: class funcs
class func isAFlush(cards: [Card]) -> FlushRanking? {
if cards.count > 0 {
if cards.filter({return $0.suit == cards[0].suit}).count == cards.count {
var flushTier: FlushRanking? = nil
var flushTierIndexOffset: Int = 0
switch cards.count {
case 1:
flushTier = FlushRanking.TierOne
case 2:
flushTier = FlushRanking.TierTwo
case 3:
flushTier = FlushRanking.TierThree
flushTierIndexOffset = 1
case 4:
flushTier = FlushRanking.TierFour
flushTierIndexOffset = 2
case 5:
flushTier = FlushRanking.TierFive
flushTierIndexOffset = 3
default:
print("It is a flush, but too many cards for a Bourgeoisie hand. cards.count: \(cards.count)")
}
if flushTier != nil {
return FlushRanking(rawValue: flushTier!.rawValue + cards.sort().last!.rank!.rawValue - flushTierIndexOffset - 1)
}
}
return nil
}
else {
return FlushRanking.NoCards
}
}
class func isAStraight(cards: [Card]) -> StraightRanking? {
if cards.count == 0 {
return StraightRanking.NoCards
}
if cards.count == 1 {
return StraightRanking(rawValue: StraightRanking.NoCards.rawValue + cards[0].rank!.rawValue)
}
var straightVal: StraightRanking? = nil
var straightTier: StraightRanking? = nil
var sortedCards = cards.sort()
var expectedNextValue = sortedCards[0].rank.rawValue + 1
sortedCards.removeFirst()
for card in sortedCards {
if card.rank.rawValue != expectedNextValue {
return nil
}
else {
expectedNextValue++
}
}
switch cards.count {
case 1:
straightTier = StraightRanking.TierOne
case 2:
straightTier = StraightRanking.TierTwo
case 3:
straightTier = StraightRanking.TierThree
case 4:
straightTier = StraightRanking.TierFour
case 5:
straightTier = StraightRanking.TierFive
default:
print("It is a straight, but too many cards for a Bourgeoisie hand. cards.count: \(cards.count)")
}
if straightTier != nil {
let straightTierIndexOffset = cards.count - 1
straightVal = StraightRanking(rawValue: straightTier!.rawValue + sortedCards.last!.rank!.rawValue - straightTierIndexOffset - 1)
}
return straightVal
}
class func isABook(cards: [Card]) -> BookRanking? {
if cards.count == 0 {
return BookRanking.NoCards
}
var bookDict: [Rank:Int] = [:]
for card in cards {
// if card.rank exists as a key in the dictionary
if let rankVal = bookDict[card.rank] {
bookDict.updateValue(rankVal+1, forKey: card.rank)
}
else {
bookDict.updateValue(1, forKey: card.rank)
}
}
var bookVal: BookRanking? = nil
var bookTier: BookRanking? = nil
switch cards.count {
case 1:
bookTier = BookRanking.TierOne
bookVal = BookRanking(rawValue: bookTier!.rawValue + bookDict.keys.first!.rawValue - 1)
case 2:
if bookDict.keys.count == 1 {
bookTier = BookRanking.TierTwo
bookVal = BookRanking(rawValue: bookTier!.rawValue + bookDict.keys.first!.rawValue - 1)
}
case 3:
if bookDict.keys.count == 1 {
bookTier = BookRanking.TierFour
bookVal = BookRanking(rawValue: bookTier!.rawValue + bookDict.keys.first!.rawValue - 1)
}
case 4:
if bookDict.keys.count == 1 {
bookTier = BookRanking.TierSix
bookVal = BookRanking(rawValue: bookTier!.rawValue + bookDict.keys.first!.rawValue - 1)
}
else if bookDict.keys.count == 2 && bookDict.values.first == 2 {
bookTier = BookRanking.TierThree
let pairRanks = bookDict.keys.sort({return $0.rawValue < $1.rawValue})
let firstIndexOffset = (pairRanks[1].rawValue-2)*(pairRanks[1].rawValue-1)/2
let secondIndexOffset = pairRanks[0].rawValue-1
bookVal = BookRanking(rawValue: bookTier!.rawValue + firstIndexOffset + secondIndexOffset)
}
case 5:
if bookDict.keys.count == 1 {
bookTier = BookRanking.TierSeven
bookVal = BookRanking(rawValue: bookTier!.rawValue + bookDict.keys.first!.rawValue - 1)
}
else if bookDict.keys.count == 2 && (bookDict.values.first == 2 || bookDict.values.first == 3) {
bookTier = BookRanking.TierFive
let ofRanks = bookDict.keys.sort({return $0.rawValue < $1.rawValue})
var threeOfRank: Rank!
var twoOfRank: Rank!
if bookDict[ofRanks[0]] == 3 {
threeOfRank = ofRanks[0]
twoOfRank = ofRanks[1]
}
else {
threeOfRank = ofRanks[1]
twoOfRank = ofRanks[0]
}
let firstIndexOffset = 9*(threeOfRank.rawValue - 1)
let secondIndexOffset = (twoOfRank.rawValue < threeOfRank.rawValue) ? (twoOfRank.rawValue - 1) : (twoOfRank.rawValue - 2)
bookVal = BookRanking(rawValue: bookTier!.rawValue + firstIndexOffset + secondIndexOffset)
}
default:
print("Too many cards for a Bourgeoisie hand. cards.count: \(cards.count)")
}
return bookVal
}
}
| mit | 686203f64d0fbfdcafd69fdaa7a70251 | 42.989583 | 134 | 0.730918 | 4.107977 | false | false | false | false |
GTMYang/GTMRefresh | GTMRefresh/GTMRefreshStyle.swift | 1 | 4021 | //
// GTMRefreshStyle.swift
// GTMRefresh
//
// Created by luoyang on 2017/8/8.
// Copyright © 2017年 luoyang. All rights reserved.
//
import UIKit
extension UIScrollView {
// MARK: - 自定义 header 文字
@discardableResult
final public func pullDownToRefreshText(_ text: String) -> UIScrollView {
if let header = self.gtmHeader as? DefaultGTMRefreshHeader {
header.pullDownToRefresh = text
}
return self
}
@discardableResult
final public func releaseToRefreshText(_ text: String) -> UIScrollView {
if let header = self.gtmHeader as? DefaultGTMRefreshHeader {
header.releaseToRefresh = text
}
return self
}
@discardableResult
final public func refreshSuccessText(_ text: String) -> UIScrollView {
if let header = self.gtmHeader as? DefaultGTMRefreshHeader {
header.refreshSuccess = text
}
return self
}
@discardableResult
final public func refreshFailureText(_ text: String) -> UIScrollView {
if let header = self.gtmHeader as? DefaultGTMRefreshHeader {
header.refreshFailure = text
}
return self
}
@discardableResult
final public func refreshingText(_ text: String) -> UIScrollView {
if let header = self.gtmHeader as? DefaultGTMRefreshHeader {
header.refreshing = text
}
return self
}
//MARK: - 自定义 footer 文字
@discardableResult
final public func pullUpToRefreshText(_ text: String) -> UIScrollView {
if let footer = self.gtmFooter as? DefaultGTMLoadMoreFooter {
footer.pullUpToRefreshText = text
}
return self
}
@discardableResult
final public func loaddingText(_ text: String) -> UIScrollView {
if let footer = self.gtmFooter as? DefaultGTMLoadMoreFooter {
footer.loaddingText = text
}
return self
}
@discardableResult
final public func noMoreDataText(_ text: String) -> UIScrollView {
if let footer = self.gtmFooter as? DefaultGTMLoadMoreFooter {
footer.noMoreDataText = text
}
return self
}
@discardableResult
final public func releaseLoadMoreText(_ text: String) -> UIScrollView {
if let footer = self.gtmFooter as? DefaultGTMLoadMoreFooter {
footer.releaseLoadMoreText = text
}
return self
}
//MARK: - 自定义文字颜色
@discardableResult
final public func headerTextColor(_ color: UIColor) -> UIScrollView {
if let header = self.gtmHeader as? DefaultGTMRefreshHeader {
header.txtColor = color
}
return self
}
@discardableResult
final public func footerTextColor(_ color: UIColor) -> UIScrollView {
if let footer = self.gtmFooter as? DefaultGTMLoadMoreFooter {
footer.txtColor = color
}
return self
}
//MARK: - 自定义文图片
// header's
@discardableResult
final public func headerIdleImage(_ image: UIImage?) -> UIScrollView {
if let header = self.gtmHeader as? DefaultGTMRefreshHeader {
header.idleImage = image
}
return self
}
@discardableResult
final public func headerSucImage(_ image: UIImage?) -> UIScrollView {
if let header = self.gtmHeader as? DefaultGTMRefreshHeader {
header.sucImage = image
}
return self
}
@discardableResult
final public func headerFailImage(_ image: UIImage?) -> UIScrollView {
if let header = self.gtmHeader as? DefaultGTMRefreshHeader {
header.failImage = image
}
return self
}
// footer's
@discardableResult
final public func footerIdleImage(_ image: UIImage?) -> UIScrollView {
if let footer = self.gtmFooter as? DefaultGTMLoadMoreFooter {
footer.idleImage = image
}
return self
}
}
| mit | 0ec77572852b85202633781831ffc909 | 29.790698 | 77 | 0.626385 | 4.820388 | false | false | false | false |
minidfx/LabMultimedia | LabMultimedia/AudioController.swift | 1 | 1850 | //
// SecondViewController.swift
// LabMultimedia
//
// Created by Benjamin Burgy on 14.12.15.
// Copyright © 2015 HES-SO Master. All rights reserved.
//
import UIKit
import MediaPlayer
class AudioController: UITableViewController {
var mediaItems: [MPMediaItem]?
@IBOutlet var mainTableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
self.mainTableView.dataSource = self
self.mainTableView.delegate = self
self.mediaItems = MPMediaQuery.songsQuery().items
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if let destinationVC = segue.destinationViewController as? PlayerController {
let mediaItem = self.mediaItems![(self.mainTableView.indexPathForSelectedRow?.row)!]
destinationVC.mediaItem = mediaItem
destinationVC.mediaItems = self.mediaItems
}
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return (self.mediaItems?.count)!
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let mediaItem = self.mediaItems![indexPath.row]
let cell = tableView.dequeueReusableCellWithIdentifier("SongCell", forIndexPath: indexPath)
cell.textLabel?.text = mediaItem.valueForProperty(MPMediaItemPropertyTitle) as? String
cell.imageView?.image = mediaItem.artwork?.imageWithSize(CGSize(width: 20, height: 20))
cell.detailTextLabel?.text = mediaItem.valueForProperty(MPMediaItemPropertyArtist) as? String
return cell
}
}
| mit | c7dd1a4963bdf47de4240f1b1f1dcd23 | 32.618182 | 118 | 0.680909 | 5.375 | false | false | false | false |
allevato/swift | test/expr/delayed-ident/static_var.swift | 1 | 2148 | // RUN: %target-typecheck-verify-swift
// Simple struct types
struct X1 {
static var AnX1 = X1()
static var NotAnX1 = 42
}
func acceptInOutX1(_ x1: inout X1) { }
var x1: X1 = .AnX1
x1 = .AnX1
x1 = .NotAnX1 // expected-error{{member 'NotAnX1' in 'X1' produces result of type 'Int', but context expects 'X1'}}
// Delayed identifier expressions as lvalues
(.AnX1 = x1)
acceptInOutX1(&(.AnX1))
// Generic struct types
struct X2<T> {
static var AnX2 = X2() // expected-error{{static stored properties not supported in generic types}}
static var NotAnX2 = 0 // expected-error {{static stored properties not supported in generic types}}
}
var x2: X2<Int> = .AnX2
x2 = .AnX2 // reference to isInvalid() decl.
x2 = .NotAnX2 // expected-error{{member 'NotAnX2' in 'X2<Int>' produces result of type 'Int', but context expects 'X2<Int>'}}
// Static variables through operators.
struct Foo {
static var Bar = Foo()
static var Wibble = Foo()
}
func & (x: Foo, y: Foo) -> Foo { }
var fooValue: Foo = .Bar & .Wibble
// Static closure variables.
struct HasClosure {
static var factoryNormal: (Int) -> HasClosure = { _ in .init() }
static var factoryReturnOpt: (Int) -> HasClosure? = { _ in .init() }
static var factoryIUO: ((Int) -> HasClosure)! = { _ in .init() }
static var factoryOpt: ((Int) -> HasClosure)? = { _ in .init() }
}
var _: HasClosure = .factoryNormal(0)
var _: HasClosure = .factoryReturnOpt(1)!
var _: HasClosure = .factoryIUO(2)
var _: HasClosure = .factoryOpt(3)
// expected-error@-1 {{value of optional type '((Int) -> HasClosure)?' must be unwrapped to a value of type '(Int) -> HasClosure'}}
// expected-note@-2 {{coalesce}}
// expected-note@-3 {{force-unwrap}}
// FIXME: we should accept this
var _: HasClosure = .factoryOpt!(4) // expected-error {{cannot infer contextual base in reference to member 'factoryOpt'}}
infix operator =%: ComparisonPrecedence
extension Optional {
static func =%(lhs: Self, rhs: Self) -> Bool { return true }
}
struct ImplicitMembers {
static var optional: ImplicitMembers? = ImplicitMembers()
}
func implicit(_ i: inout ImplicitMembers) {
if i =% .optional {}
}
| apache-2.0 | 3c94dae2fd51aedffe06e6fb6f05174c | 30.588235 | 131 | 0.672719 | 3.294479 | false | false | false | false |
nguyenngocnhan90/Restful-Swift | Restful/RestRequest.swift | 2 | 13067 | //
// RESTRequest.swift
// N3Restful-Swift
//
// Created by Nhan Nguyen on 2/19/16.
// Copyright © 2016 Nhan Nguyen. All rights reserved.
//
import HTTPStatusCodes
import Alamofire
import ObjectMapper
class RestRequest: NSObject {
var url: String = ""
var queryParameters: [String: Any] = [:]
var parameters: [String: Any] = [:]
var headers: [String: String] = [:]
var multiparts: [RestMultipart] = []
// MARK: - Manager
fileprivate lazy var sessionManager: SessionManager = {
let config = URLSessionConfiguration.default
config.timeoutIntervalForRequest = RestContant.requestTimeOut
let manager = Alamofire.SessionManager(configuration: config)
return manager
}()
// MARK: - Initial
init(url: String) {
self.url = url
}
static func request(with url: String) -> RestRequest {
let request = RestRequest(url: url)
return request
}
// MARK: - Completions
typealias ObjectCompletion<T: RestObject> = (_ result: T?, _ error: RestError?) -> ()
typealias ArrayCompletion<T: RestObject> = (_ result: [T], _ error: RestError?) -> ()
}
// MARK: - BASE REQUEST
extension RestRequest {
fileprivate func dataRequest(method: Alamofire.HTTPMethod = .get, encoding: ParameterEncoding = URLEncoding.default) -> DataRequest {
appendQueryParamsToURL()
return sessionManager.request(url,
method: method,
parameters: parameters,
encoding: encoding,
headers: headers)
.validate(statusCode: 200..<400)
}
fileprivate func handleResponse<T: RestObject>(_ response: DataResponse<Any>,
_ completion: ObjectCompletion<T>? = nil,
retry: (() -> Void)? = nil) {
let statusCode = HTTPStatusCode(rawValue: (response.response?.statusCode ?? 503))!
switch response.result {
case .success (let json):
guard let dictionary = json as? [String : Any],
let object = Mapper<T>().map(JSON: dictionary) else {
let restObj = RestObject()
restObj.rawValue = "\(json)"
restObj.statusCode = statusCode
completion?(restObj as? T, nil)
return
}
object.statusCode = statusCode
debugPrint(object)
completion?(object, nil)
case .failure (let error):
let restError = RestError(response: response, error: error)
debugPrint(restError.errorMessage ?? "")
var restObject: RestObject?
if let json = restError.responseDictionary {
restObject = Mapper<T>().map(JSON: json)
}
completion?(restObject as? T, restError)
}
}
func handleArrayResponse<T: RestObject>(_ response: DataResponse<Any>,
_ completion: ArrayCompletion<T>?,
retry: (() -> Void)? = nil) {
switch response.result {
case .success (let json):
guard let jsonArr = json as? [[String: Any]] else {
completion?([], nil)
return
}
let objects = Mapper<T>().mapArray(JSONArray: jsonArr)
debugPrint(objects as Any)
completion?(objects, nil)
case .failure (let error):
let restError = RestError(response: response, error: error)
debugPrint(restError.errorMessage ?? "")
completion?([], restError)
}
}
}
// MARK: - GET
extension RestRequest {
/// GET request
///
/// - parameter completion: callback result
func get<T: RestObject>(_ completion: ObjectCompletion<T>? = nil) {
dataRequest().responseJSON { response -> Void in
self.handleResponse(response, completion, retry: { [weak self] in
self?.get(completion)
})
}
}
func getArray<T: RestObject>(_ completion: ArrayCompletion<T>? = nil) {
dataRequest().responseJSON { response -> Void in
self.handleArrayResponse(response, completion, retry: { [weak self] in
self?.getArray(completion)
})
}
}
}
// MARK: - Request with object body
extension RestRequest {
/// POST request
///
/// - parameter objectBody: object param - type RESTParam
/// - parameter completion: callback result
func post<T: RestObject>(bodyParam param: RestParam? = nil, completion: ObjectCompletion<T>? = nil) {
request(bodyParam: param, method: .post) { (object: T?, error) -> () in
completion?(object, error)
}
}
/// PUT request
///
/// - parameter objectBody: object param - type RESTParam
/// - parameter completion: callback result
func put<T: RestObject>(bodyParam param: RestParam? = nil, completion: ObjectCompletion<T>? = nil) {
request(bodyParam: param, method: .put) { (object: T?, error) -> () in
completion?(object, error)
}
}
/// PATCH request
///
/// - parameter objectBody: object param - type RESTParam
/// - parameter completion: callback result
func patch<T: RestObject>(bodyParam param: RestParam? = nil, completion: ObjectCompletion<T>? = nil) {
request(bodyParam: param, method: .patch)
{ (object: T?, error) -> () in
completion?(object, error)
}
}
/// DELETE request
///
///- parameter objectBody: object param - type RESTParam
/// - parameter completion: callback result
func delete<T: RestObject>(bodyParam param: RestParam? = nil, completion: ObjectCompletion<T>? = nil) {
request(bodyParam: param, method: .delete) { (object: T?, error) -> () in
completion?(object, error)
}
}
/// Common request with object boby
///
/// - parameter objectBody: object param - type RESTParam
/// - parameter method:
/// - parameter completion: call back
func request<T: RestObject>(bodyParam objectBody: RestParam? = nil, method: Alamofire.HTTPMethod, completion: ObjectCompletion<T>? = nil) {
let dictionary = objectBody?.toDictionary
request(dictionary: dictionary, method: method) { (result: T?, error) -> () in
completion?(result, error)
}
}
}
// MARK: - Request dictionary body
extension RestRequest {
/// equest with dictionary parameters
///
/// - parameter dictionaryParam: parameters
/// - parameter method: request method
/// - parameter completion: callback result
func request<T: RestObject>(dictionary param: [String: Any]? = nil, method: Alamofire.HTTPMethod, completion: ObjectCompletion<T>? = nil) {
if let param = param {
parameters = param
}
dataRequest(method: method, encoding: JSONEncoding.default)
.responseJSON { (response) -> Void in
self.handleResponse(response, completion, retry: { [weak self] in
self?.request(dictionary: param, method: method, completion: completion)
})
}
}
func requestArray<T: RestObject>(dictionary param: [String: Any]? = nil, method: Alamofire.HTTPMethod, completion: ArrayCompletion<T>? = nil) {
if let param = param {
parameters = param
}
dataRequest(method: method, encoding: JSONEncoding.default)
.responseJSON { (response) -> Void in
self.handleArrayResponse(response, completion, retry: { [weak self] in
self?.requestArray(dictionary: param, method: method, completion: completion)
})
}
}
}
// MARK: - Multiparts: Uploading files
extension RestRequest {
/// POST request with multipart: file, data, string
///
/// - parameter completion: callback result
func postMultipart<T: RestObject>(_ completion: ObjectCompletion<T>? = nil) {
upload(.post) { (object: T?, error) -> () in
completion?(object, error)
}
}
/// PUT request with multipart: file, data, string
///
/// - parameter completion: callback result
func putMultipart<T: RestObject>(_ completion: ObjectCompletion<T>? = nil) {
upload(.put) { (object: T?, error) -> () in
completion?(object, error)
}
}
/// PATCH request with multipart: file, data, string
///
/// - parameter completion: callback result
func patchMultipart<T: RestObject>(_ completion: ObjectCompletion<T>? = nil) {
upload(.patch) { (object: T?, error) -> () in
completion?(object, error)
}
}
/// Upload multipart: file, data, string
///
/// - parameter method: POST, PUT, PATCH
/// - parameter completion: callback result
fileprivate func upload<T: RestObject>(_ method: Alamofire.HTTPMethod, _ completion: ObjectCompletion<T>? = nil) {
appendQueryParamsToURL()
sessionManager.upload(
multipartFormData: { (formData) -> Void in
for part in self.multiparts {
formData.append(part.data,
withName: part.name,
fileName: part.fileName,
mimeType: part.contentType)
}
},
to: url,
method: method,
headers: headers,
encodingCompletion: { (result) -> Void in
switch result {
case .success(let request, _, _):
request.validate(statusCode: 200..<400)
.responseJSON(completionHandler: { (response) -> Void in
self.handleResponse(response, completion, retry: { [weak self] in
self?.upload(method, completion)
})
})
case .failure(let error):
print(error)
let restError = RestError(error: error)
completion?(nil, restError)
}
})
}
}
// MARK: - Add Properties
extension RestRequest {
func addObjectBodyParam(_ objectParam: RestParam) {
parameters = objectParam.toDictionary
}
func addQueryParam(_ name: String, value: Any) {
queryParameters[name] = "\(value)"
}
func addJsonPart(_ name: String, json: NSDictionary) {
let part = RestMultipart.JSONPart(name: name, jsonObject: json)
self.multiparts.append(part)
}
func addFilePart(_ name: String, fileName: String, data: Data!) {
let part = RestMultipart.FilePart(name: name, fileName: fileName, data: data)
self.multiparts.append(part)
}
func addStringPart(_ name: String, string: String) {
let part = RestMultipart.StringPart(name: name, string: string)
self.multiparts.append(part)
}
}
// MARK: - Set header, content type, accept, authorization
extension RestRequest {
func addHeader(_ name: String, value: AnyObject) {
headers[name] = value as? String
}
func setContentType(_ contentType: String) {
headers[RestContant.requestContentTypeKey] = contentType
}
func setAccept(_ accept: String) {
self.headers[RestContant.requestAcceptKey] = accept
}
func setAuthorization(_ authorization: String) {
self.headers[RestContant.requestAuthorizationKey] = authorization
}
}
extension RestRequest {
fileprivate func appendQueryParamsToURL() {
guard !url.isEmpty,
let urlComponents = NSURLComponents(string: url),
!queryParameters.isEmpty else {
return
}
var queryParams: [URLQueryItem] = urlComponents.queryItems ?? []
var dictionary: [String: String] = [:]
queryParams.forEach { (item) in
if let value = item.value, !value.isEmpty {
dictionary[item.name] = value
}
}
queryParameters.forEach { (arg: (key: String, value: Any)) in
let (key, value) = arg
queryParams.append(URLQueryItem(name: key, value: "\(value)"))
}
urlComponents.queryItems = queryParams
url = urlComponents.url?.absoluteString ?? ""
}
}
| mit | 3619f8af8ac2c9075ed842a54672a259 | 31.994949 | 147 | 0.549824 | 4.915726 | false | false | false | false |
IBM-MIL/IBM-Ready-App-for-Venue | iOS/Venue/View Models/HomeViewModel.swift | 1 | 8844 | /*
Licensed Materials - Property of IBM
© Copyright IBM Corporation 2015. All Rights Reserved.
*/
import ReactiveCocoa
/// View Model to handle a user's POI and the POIs near them
class HomeViewModel: NSObject {
var poiArray = [POI]()
var adsArray = [Ad]()
let adDisplayPositions = [4,9,13]
var userPoiList = [POI]()
var userCompletePoiList = [POI]()
var userInvitations = [Invitation]()
var showMyList = true
let videoPath = NSBundle.mainBundle().pathForResource("home_video", ofType: "mp4")!
/// Computes whether we have received any data
var dataPresent: Bool {
return userPoiList.count + userCompletePoiList.count + userInvitations.count > 0
}
override init() {
super.init()
// Ask data manager for array of Ads
AdDataManager.sharedInstance.getAdData() { [weak self] (adData: [Ad]) in
guard let strongSelf = self else {
return
}
strongSelf.adsArray = adData
}
// Ask data manager for array of POIs
PoiDataManager.sharedInstance.getPOIData() { [weak self] (poiData: [POI]) in
guard let strongSelf = self else {
return
}
strongSelf.poiArray = poiData
}
}
private func reloadData() {
let user = UserDataManager.sharedInstance.currentUser
let favorites = user.favorites
self.userPoiList = []
self.userCompletePoiList = []
for favorite in favorites {
if !favorite.isComplete {
self.userPoiList.append(favorite.favoritedPOI)
} else {
self.userCompletePoiList.append(favorite.favoritedPOI)
}
}
// Sort data within sections
self.userPoiList.sortInPlace({ $0.name.localizedCaseInsensitiveCompare($1.name) == NSComparisonResult.OrderedAscending })
self.userCompletePoiList.sortInPlace({ $0.name.localizedCaseInsensitiveCompare($1.name) == NSComparisonResult.OrderedAscending })
// Load a User's invitations
self.userInvitations = user.invitationsAccepted + user.invitationsSent
self.userInvitations.sortInPlace({ $0.timestampToMeet.compare($1.timestampToMeet) == NSComparisonResult.OrderedAscending })
}
/**
Calculates rows in a section, taking logic out of viewController
- parameter section: section to evaluate
- returns: number of rows
*/
func rowsInSection(section: Int) -> Int {
reloadData()
if showMyList {
// first 2 sections are used for UI only
switch(section) {
case 0:
return 0
case 1:
return 0
case 2:
return userInvitations.count
case 3:
return userPoiList.count
case 4:
return userCompletePoiList.count
default:
return 0
}
} else {
return section == 0 ? 0 : poiArray.count + adsArray.count
}
}
/**
Method handles lots of UI logic for all the different types of POIs we can have
- parameter cell: cell to update
- parameter indexPath: indexPath to evaluate data for
*/
func setupPOICell(cell: POITableViewCell, indexPath: NSIndexPath) {
if displaysAd(indexPath) {
let currentAd = adsArray[numberOfAdsPreviouslyDisplayed(indexPath)]
cell.mainTitleLabel.text = currentAd.name
cell.typeImageView.image = UIImage(named: "Icons_Home_Ad")
cell.subtitleLabel.text = currentAd.details
cell.showWaitLabel()
cell.toggleWaitTimeHidden(true)
cell.subtitleLabel.textColor = UIColor.venueLightBlue()
cell.mainTitleLabel.accessibilityIdentifier = "ad"
cell.locationImageView.image = UIImage(named: currentAd.thumbnailUrl)
}
else {
// Based on different views, display correct POI item
let currentPOI = getDisplayedPOI(indexPath)
cell.locationImageView.image = UIImage(named: currentPOI.thumbnailUrl)
cell.mainTitleLabel.text = currentPOI.name
let firstType = currentPOI.types.first!
cell.typeImageView.image = UIImage(named: firstType.home_icon_image_name)
/* Logic to display various label variations, colors, and positions */
let waitString = NSLocalizedString("min wait", comment: "")
if currentPOI.wait_time >= 0 {
// Set text and ensure all labels are visible
cell.subtitleLabel.text = "\(currentPOI.wait_time) \(waitString)"
cell.showWaitLabel()
// if we have a wait time, just append invite time onto it
if indexPath.section == 2 {
configureMeetingTime(cell, indexPath: indexPath, shouldAppend: true)
cell.subtitleLabel.textColor = UIColor.venueLightBlue()
} else {
// Only change color for items not in Invitations
cell.subtitleLabel.updateTextColor(currentPOI.wait_time)
cell.waitTimeImageView.image = cell.waitTimeImageView.image?.imageWithRenderingMode(UIImageRenderingMode.AlwaysTemplate)
cell.waitTimeImageView.tintColor = cell.subtitleLabel.textColor
cell.toggleWaitTimeHidden(false)
}
} else if indexPath.section == 2 {
// Wait time is less than zero, so we ignore that time
configureMeetingTime(cell, indexPath: indexPath, shouldAppend: false)
cell.subtitleLabel.textColor = UIColor.venueLightBlue()
cell.showWaitLabel()
} else {
// There should be no subtitle if no wait time and not an invitation
cell.subtitleLabel.text = ""
cell.toggleWaitTimeHidden(true)
// No wait label content, so we hide
cell.hideWaitLabel()
}
}
}
/**
Convenience method to set subtitle label in the right format
- parameter cell: cell to modify
- parameter indexPath: indexPath for current cell
- parameter shouldAppend: value determining whether new text values should be appended onto the current ones
*/
func configureMeetingTime(cell: POITableViewCell, indexPath: NSIndexPath, shouldAppend: Bool) {
let currentInvite = userInvitations[indexPath.row]
if shouldAppend {
cell.subtitleLabel.text! += " | " + currentInvite.timestampToMeet.localizedStringTime()
} else {
cell.subtitleLabel.text! = currentInvite.timestampToMeet.localizedStringTime()
}
cell.toggleWaitTimeHidden(true)
}
/**
Helper method to retrieve a `POI` object from the various data structures
- parameter indexPath: used to find correct POI
- returns: the desired `POI` object
*/
func getDisplayedPOI(indexPath: NSIndexPath) -> POI {
if showMyList {
switch(indexPath.section) {
case 2:
return userInvitations[indexPath.row].location
case 3:
return userPoiList[indexPath.row]
case 4:
return userCompletePoiList[indexPath.row]
default:
return userCompletePoiList[indexPath.row]
}
} else {
return poiArray[indexPath.row - numberOfAdsPreviouslyDisplayed(indexPath)]
}
}
/**
Calculates number of ads already in POI list
- parameter indexPath: used to check section number
- returns: calculated number of ads
*/
func numberOfAdsPreviouslyDisplayed(indexPath: NSIndexPath) -> Int {
if showMyList || indexPath.section != 1 {
return 0
}
return adDisplayPositions.filter({$0 < indexPath.row}).count
}
/**
Determines if we should display an ad, we have 3 to show
- parameter indexPath: checking for indexPath
- returns: boolean result
*/
func displaysAd(indexPath: NSIndexPath) -> Bool {
if showMyList || indexPath.section != 1 {
return false
}
else {
return adDisplayPositions.indexOf(indexPath.row) != nil
}
}
}
| epl-1.0 | e0103dbf3f6348e963097f0f0bb9dde8 | 34.231076 | 140 | 0.580459 | 5.298382 | false | false | false | false |
rsattar/Voucher | Voucher tvOS App/RootViewController.swift | 1 | 2077 | //
// RootViewController.swift
// Voucher
//
// Created by Rizwan Sattar on 11/9/15.
// Copyright © 2015 Rizwan Sattar. All rights reserved.
//
import UIKit
class RootViewController: UIViewController, AuthViewControllerDelegate {
var isAuthenticated: Bool = false {
didSet {
self.authenticationUI.isHidden = self.isAuthenticated
self.clearAuthenticationButton.isHidden = !self.isAuthenticated
if (isAuthenticated) {
self.authenticationLabel.text = "Authenticated!"
} else {
self.authenticationLabel.text = "Not Authenticated"
}
self.view.setNeedsLayout()
}
}
@IBOutlet weak var authenticationLabel: UILabel!
@IBOutlet weak var clearAuthenticationButton: UIButton!
@IBOutlet weak var authenticationUI: UIView!
override func viewDidLoad() {
super.viewDidLoad()
self.isAuthenticated = false
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
guard let segueIdentifier = segue.identifier else {
return
}
if segueIdentifier == "showVoucher" {
let viewController = segue.destination as! AuthViewController
viewController.delegate = self
}
}
@IBAction func onClearDataTriggered(_ sender: UIButton) {
self.isAuthenticated = false
}
// MARK: - AuthViewControllerDelegate
func authController(_ controller: AuthViewController, didSucceed succeeded: Bool) {
self.isAuthenticated = succeeded
self.dismiss(animated: true, completion: nil)
}
}
| mit | d2b821d767cc2cd8d130721ffe96f17b | 29.529412 | 106 | 0.65896 | 5.295918 | false | false | false | false |
bitboylabs/selluv-ios | selluv-ios/selluv-ios/Classes/Controller/UI/Tabs/Tab3Sell/SLV_316_SellDirectStep1PhotoContoller.swift | 1 | 14246 | //
// SLV_316_SellDirectStep1PhotoContoller.swift
// selluv-ios
//
// Created by 조백근 on 2016. 11. 8..
// Copyright © 2016년 BitBoy Labs. All rights reserved.
//
/*
판매 직접 스탭1 사진촬영 컨트롤러
*/
import Foundation
import UIKit
import AVFoundation
import SwiftyUserDefaults
public enum PhotoControllerMode {
case `default`
case demage
case accessory
case viewer(urlString: String, items: [String])
}
class SLV_316_SellDirectStep1PhotoContoller: SLVBaseStatusHiddenController {
@IBOutlet weak var customNavigationView: UIView!
@IBOutlet weak var customNaviLabel: UILabel!
@IBOutlet weak var backButton: UIButton!
@IBOutlet weak var nextButtonView: UIView!
@IBOutlet weak var nextButton: UIButton!
@IBOutlet weak var cameraRotateButton: UIButton!
@IBOutlet weak var cameraTorchButton: UIButton!
let reuseIdentifier = "SLVPhotoSelectionCell"
@IBOutlet weak var myPhotoCollectionView: UICollectionView!
@IBOutlet weak var guideButton: UIButton!
var photoMode:PhotoControllerMode = .default
var isFrontCamera: Bool = false
var isTorchOn: Bool = false
//카메라 세션정보
var camera: CameraSessionManager?
@IBOutlet weak var preview:AVSessionPreview? { //현재 사용자 카메라와 연결된 출력대상 뷰
didSet {
if preview != nil {
preview?.isHidden = false
}
}
}
var isCameraWorking: Bool = false
//############################################################
func setup() {
let isAllow: Bool = Defaults[.permissionForCameraKey] ?? false
guard isAllow == true && self.preview != nil else { return }
if self.camera == nil {
var position: AVCaptureDevicePosition
if CameraSessionManager.hasBackCamera() { position = .back }
else if CameraSessionManager.hasFrontCamera() { position = .back }
else { position = .unspecified}
self.camera = CameraSessionManager(position: position, previewView: self.preview!)
self.camera?.start()
// self.camera?.delegate = self
self.isCameraWorking = true
self.preview?.setupZoom()
}
}
func stop() {
// self.preview = nil
self.camera?.stop()
self.isCameraWorking = false
}
//############################################################
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
tabController.animationTabBarHidden(true)
tabController.hideFab()
self.myPhotoCollectionView.reloadData()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
self.navigationController?.isNavigationBarHidden = true
self.navigationBar?.barHeight = 0
self.navigationItem.hidesBackButton = true
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
UIView.cancelPreviousPerformRequests(withTarget: self)
}
override func viewDidLoad() {
super.viewDidLoad()
self.navigationController?.isNavigationBarHidden = true
self.navigationBar?.barHeight = 0
self.navigationItem.hidesBackButton = true
let isSimulator = AppSetup.sharedState.isSimulator
if isSimulator == true {
return
}
//카메라 엑세스 체크
CameraSessionManager.checkAndRequestCameraPermissions { (granted) -> Void in
if granted == true {
Defaults[.permissionForCameraKey] = true
if self.isCameraWorking == false {
self.setup()
}
}
}
defer {
if Defaults[.permissionForCameraKey] == true && self.isCameraWorking == false {
self.setup()
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func setupDefaultPhotoMode() {
self.photoMode = .default
self.customNaviLabel.text = ""
self.backButton.isHidden = false
self.guideButton.isHidden = false
self.nextButton.setTitle("다음", for: .normal)
self.myPhotoCollectionView.reloadData()
}
func setupDemagePhotoMode() {
self.photoMode = .demage
self.customNaviLabel.text = "하자 사진 촬영"
self.backButton.isHidden = true
self.guideButton.isHidden = true
self.nextButton.setTitle("확인", for: .normal)
self.myPhotoCollectionView.reloadData()
}
func setupAccessoryPhotoMode() {
self.photoMode = .accessory
self.customNaviLabel.text = "부속품 사진 촬영"
self.backButton.isHidden = true
self.guideButton.isHidden = true
self.nextButton.setTitle("확인", for: .normal)
self.myPhotoCollectionView.reloadData()
}
func setupNextButton() {
let newButton = UIBarButtonItem(title: "Next", style: UIBarButtonItemStyle.plain, target: self, action: #selector(SLV_316_SellDirectStep1PhotoContoller.next(sender:)))
self.navigationItem.rightBarButtonItem = newButton
}
func next(sender: UIBarButtonItem?) {//go step2
switch self.photoMode {
case .default :
let isDirect = TempInputInfoModel.shared.isDirectInput
if isDirect == true {
//직접 판매
//유효성 체크
if TempInputInfoModel.shared.checkInputStepDataValidation(step: .picture1) == false {
return
}
let board = UIStoryboard(name:"Sell", bundle: nil)
let step2Controller = board.instantiateViewController(withIdentifier: "SLV_320_SellDirectStep2ItemInfoController") as! SLV_320_SellDirectStep2ItemInfoController
self.navigationController?.tr_pushViewController(step2Controller, method: TRPushTransitionMethod.default, statusBarStyle: .hide) {
}
} else {
//발렛 판매
}
return
case .demage, .accessory :
_ = self.navigationController?.tr_popViewController() {
}
return
default : break
}
}
// override func prepare(for segue: UIStoryboardSegue?, sender: Any?) {
// if (segue?.identifier == "SLV_313_SellCommonStep03Category2Controller") {
// let viewController:SLV_313_SellCommonStep03Category2Controller = segue!.destination as! SLV_313_SellCommonStep03Category2Controller
// }
// }
//MARK: Event
@IBAction func touchBack(_ sender: Any) {
let model = TempInputInfoModel.shared.currentModel
let restart = model.restartScene
if restart == -1 {
_ = self.navigationController?.tr_popViewController()
} else {
model.restartScene = -1
// TempInputInfoModel.shared.checkInputStepDataValidation(step: .picture1)
// TempInputInfoModel.shared.saveCurrentModel()
self.navigationController?.popToRootViewController(animated: false)
}
}
@IBAction func touchNext(_ sender: Any) {
self.next(sender: nil)
}
@IBAction func touchCameraRotate(_ sender: Any) {
if self.isFrontCamera {
_ = self.camera?.forceBackCamera()
self.isFrontCamera = false
} else {
_ = self.camera?.forceFrontCamera()
self.isFrontCamera = true
}
}
@IBAction func touchCameraTorch(_ sender: Any) {
if self.isTorchOn {
self.isTorchOn = false
self.cameraTorchButton.isSelected = false
_ = self.camera?.changeFlashMode(on: false)
} else {
self.isTorchOn = true
self.cameraTorchButton.isSelected = true
_ = self.camera?.changeFlashMode(on: true)
}
}
@IBAction func touchAlbum(_ sender: Any) {
let board = UIStoryboard(name:"Sell", bundle: nil)
let albumNavigationController = board.instantiateViewController(withIdentifier: "albumNavigationController") as! UINavigationController
self.navigationController?.present(albumNavigationController, animated: true) {
let album = albumNavigationController.viewControllers.first as! SLV_317_SellPhotoGallery
album.photoMode = self.photoMode
album.onUpdateImages({ (list) in
self.updateHorizontalCollectionView(photos: list)
})
}
}
@IBAction func touchPhoto(_ sender: Any) {
self.camera?.slvImage() { (image) in
// UIImageWriteToSavedPhotosAlbum(image!, self, #selector(SLV_316_SellDirectStep1PhotoContoller.image(_:didFinishSavingWithError:contextInfo:)), nil)
let photo = MyPhoto()!
photo.setupDeviceImage(image: image?.fixedOrientation().rotateImage())
photo.photoType = MyPhotoType.camera
let model = TempInputInfoModel.shared.currentModel
switch self.photoMode {
case .default :
model.photoList.insert(photo, at: 0)
break
case .demage :
model.demagePhotoList.insert(photo, at: 0)
break
case .accessory :
model.accessoryPhotoList.insert(photo, at: 0)
break
default : break
}
self.myPhotoCollectionView.reloadData()
self.myPhotoCollectionView.contentOffset = CGPoint(x: 0, y: 0)
}
}
@IBAction func touchGuide(_ sender: Any) {
}
@IBAction func touchClose(_ sender: Any) {
// self.navigationController?.popToRootViewController(animated: true)
let model = TempInputInfoModel.shared.currentModel
let restart = model.restartScene
if restart >= 0 {
model.restartScene = -1
}
AlertHelper.confirm(message: "저장하지 않은 STEP은 나중에 이어서 등록할 수 없습니다.", title: "저장은 하셨어요?", no: "저장 후 닫기", cancel: { (action) in
TempInputInfoModel.shared.checkInputStepDataValidation(step: .picture1)
TempInputInfoModel.shared.saveCurrentModel()
tabController.closePresent {}
}, ok: "바로 닫기", done: { (action) in
tabController.closePresent {}
}) {
}
}
// func image(_ image: UIImage, didFinishSavingWithError error: NSError?, contextInfo: UnsafeRawPointer) {
// }
public func updateHorizontalCollectionView(photos: [MyPhoto]? = nil) {
self.myPhotoCollectionView.reloadData()
self.myPhotoCollectionView.contentOffset = CGPoint(x: 0, y: 0)
}
}
extension SLV_316_SellDirectStep1PhotoContoller: UICollectionViewDataSource {
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
switch self.photoMode {
case .default :
return TempInputInfoModel.shared.currentModel.photoList.count
break
case .demage :
return TempInputInfoModel.shared.currentModel.demagePhotoList.count
break
case .accessory :
return TempInputInfoModel.shared.currentModel.accessoryPhotoList.count
break
default : break
}
return 0
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! SLVPhotoSelectionCell
cell.isViewer = false
let model = TempInputInfoModel.shared.currentModel
let myPhoto: MyPhoto?
switch self.photoMode {
case .default :
myPhoto = model.photoList[indexPath.row]
break
case .demage :
myPhoto = model.demagePhotoList[indexPath.row]
break
case .accessory :
myPhoto = model.accessoryPhotoList[indexPath.row]
break
default :
myPhoto = nil
break
}
if let mPhoto = myPhoto {
if mPhoto.editingImage() == nil {
let img = mPhoto.thumbnailImage()
if let img = img {
cell.thumnail.image = img
}
} else {
let img = mPhoto.editingImage()
if let img = img {
cell.thumnail.image = img
}
}
}
cell.path = indexPath
cell.photoMode = self.photoMode
cell.onControlBlock { (path, isDelete) in
if isDelete == true {//삭제
TempInputInfoModel.shared.currentModel.photoList.remove(at: path.row)
self.delay(time: 0.2, closure: {
self.myPhotoCollectionView.reloadData()
self.myPhotoCollectionView.contentOffset = CGPoint(x: 0, y: 0)
})
} else {//편집
let board = UIStoryboard(name:"Sell", bundle: nil)
let editController = board.instantiateViewController(withIdentifier: "SLV_318_SellPhotoEdit") as! SLV_318_SellPhotoEdit
editController.photoMode = self.photoMode
editController.onUpdateImages({ (photos) in
cell.checkEditingImage()
self.updateHorizontalCollectionView(photos: photos)
})
self.navigationController?.present(editController, animated: true, completion: {
editController.moveCurrentIndex(index: path.row)
})
}
}
return cell
}
}
| mit | 93ac8ff236bd037f49c7b637d774d36b | 34.987147 | 176 | 0.5949 | 4.825577 | false | false | false | false |
NoryCao/zhuishushenqi | zhuishushenqi/RightSide/Category/Controllers/Category/ZSCatelogViewController.swift | 1 | 4166 | //
// CategoryViewController.swift
// zhuishushenqi
//
// Created by Nory Cao on 2017/3/10.
// Copyright © 2017年 QS. All rights reserved.
//
import UIKit
class ZSCatelogViewController:BaseViewController {
var collectionView:UICollectionView!
var viewModel:ZSCatelogViewModel = ZSCatelogViewModel()
override func viewDidLoad() {
super.viewDidLoad()
title = "分类"
configureCollectionView()
request()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
navigationController?.isNavigationBarHidden = false
self.collectionView.frame = self.view.bounds
}
fileprivate func request() {
viewModel.request { (_) in
self.collectionView.reloadData()
}
}
fileprivate func configureCollectionView() {
let layout = UICollectionViewFlowLayout()
layout.minimumLineSpacing = 0.01
layout.minimumInteritemSpacing = 0.01
layout.scrollDirection = .vertical
collectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: layout)
collectionView.dataSource = self
collectionView.delegate = self
// collectionView.isPagingEnabled = true
collectionView.register(ZSCatelogCell.self, forCellWithReuseIdentifier: "ZSCatelogCell")
collectionView.register(ZSCatelogHeaderView.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "ZSCatelogHeaderView")
collectionView.showsHorizontalScrollIndicator = false
collectionView.backgroundColor = UIColor.white
view.addSubview(collectionView)
}
}
extension ZSCatelogViewController:UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {
func numberOfSections(in collectionView: UICollectionView) -> Int {
return viewModel.catelogModel.sections()
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
let items = viewModel.catelogModel.items(at: section)
return items.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ZSCatelogCell", for: indexPath) as? ZSCatelogCell
let items = viewModel.catelogModel.items(at: indexPath.section)
cell?.updateCell(items[indexPath.row])
return cell!
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: self.view.bounds.width/2 - 10, height: 100)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
return CGSize(width: self.collectionView.bounds.width, height: 40)
}
func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
let headerView = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "ZSCatelogHeaderView", for: indexPath) as! ZSCatelogHeaderView
let name = viewModel.catelogModel.name(for: indexPath.section)
headerView.titleLabel.text = name
return headerView
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let catalogDetailVC = ZSCatelogDetailViewController()
let item = viewModel.catelogModel.items(at: indexPath.section)[indexPath.row]
let gender = viewModel.catelogModel.gender(for: indexPath.section)
catalogDetailVC.parameterModel = ZSCatelogParameterModel(major: item.name, gender: gender)
self.navigationController?.pushViewController(catalogDetailVC, animated: true)
}
}
//http://api.zhuishushenqi.com/cats/lv2/statistics
| mit | 245d996d30c8638fd9ff9bc1bab67a8a | 43.244681 | 207 | 0.732628 | 5.422425 | false | false | false | false |
NoryCao/zhuishushenqi | zhuishushenqi/Root/Views/QSHomeDeleteBtn.swift | 1 | 630 | //
// QSHomeDeleteBtn.swift
// zhuishushenqi
//
// Created by yung on 2017/4/26.
// Copyright © 2017年 QS. All rights reserved.
//
import UIKit
class QSHomeDeleteBtn: UIButton {
override func layoutSubviews() {
super.layoutSubviews()
// self.imageView?.frame = CGRect(x: self.bounds.width/2 - 30/2, y: 0, width: 30, height: 30)
// self.imageView?.contentMode = .scaleAspectFit
// self.titleLabel?.frame = CGRect(x: 0, y: 30, width: self.bounds.width, height: 20)
// self.titleLabel?.textAlignment = .center
// self.titleLabel?.font = UIFont.systemFont(ofSize: 9)
}
}
| mit | acb396789104af5f650f50988431256c | 25.125 | 100 | 0.642743 | 3.445055 | false | false | false | false |
diwu/BeijingAirWatch | CommonUtil/CommonUtil.swift | 1 | 4931 | //
// CommonUtil.swift
// BeijingAirWatch
//
// Created by Di Wu on 10/15/15.
// Copyright © 2015 Beijing Air Watch. All rights reserved.
//
import Foundation
let DEBUG_LOCAL_NOTIFICATION : Bool = true
let TIME_OUT_LIMIT: Double = 15.0;
let TIME_OUT_LIMIT_IOS: Double = 30.0;
enum City: String {
case Beijing = "Beijing"
case Chengdu = "Chengdu"
case Guangzhou = "Guangzhou"
case Shanghai = "Shanghai"
case Shenyang = "Shenyang"
}
func parseTime(data: String) -> String {
let escapedString: String? = data.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)
// print("data = \(escapedString)")
if let unwrapped = escapedString {
let arr = unwrapped.components(separatedBy: "%0D%0A%09%09%09%09%09%09%09%09%3C")
for s in arr {
let subArr = s.components(separatedBy: "%3E%0D%0A%09%09%09%09%09%09%09%09%09")
if let tmp = subArr.last {
if (tmp.contains("PM") || tmp.contains("AM")) && tmp.characters.count <= 40 {
return tmp.removingPercentEncoding!
}
}
}
}
return "Invalid Time"
}
func parseAQI(data: String) -> Int {
let escapedString: String? = data.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)
if let unwrapped = escapedString {
let arr = unwrapped.components(separatedBy: "%20AQI%0D%0A")
for s in arr {
let subArr = s.components(separatedBy: "%09%09%09%09%09%09%09%09%09")
if let tmp = subArr.last {
guard let intValue = Int(tmp) else {
continue
}
guard intValue >= 0 else {
continue
}
return intValue
}
}
}
return -1
}
func parseConcentration(data: String) -> Double {
let escapedString: String? = data.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)
if let unwrapped = escapedString {
let arr = unwrapped.components(separatedBy: "%20%C3%82%C2%B5g%2Fm%C3%82%C2%B3%20%0D%0A%09%09%09%09%09%09%09%09")
for s in arr {
let subArr = s.components(separatedBy: "%09%09%09%09%09%09%09%09%09")
if let tmp = subArr.last {
guard let doubleValue = Double(tmp) else {
return -1.0
}
guard doubleValue >= 0.0 else {
return -1
}
return doubleValue
}
}
}
return -1.0
}
func sharedSessionForIOS() -> URLSession {
let session = URLSession.shared
session.configuration.timeoutIntervalForRequest = TIME_OUT_LIMIT_IOS
session.configuration.timeoutIntervalForResource = TIME_OUT_LIMIT_IOS
return session
}
func sessionForWatchExtension() -> URLSession {
let session = URLSession.shared
session.configuration.timeoutIntervalForRequest = TIME_OUT_LIMIT
session.configuration.timeoutIntervalForResource = TIME_OUT_LIMIT
return session
}
func createHttpGetDataTask(session: URLSession?, request: URLRequest!, callback: @escaping (String, String?) -> Void) -> URLSessionDataTask? {
let task = session?.dataTask(with: request){
(data, response, error) -> Void in
if error != nil {
callback("", error!.localizedDescription)
} else {
let result = String(data: data!, encoding: .ascii)!
callback(result, nil)
}
}
return task
}
func createRequest() -> URLRequest {
return URLRequest(url: URL(string: sourceURL(city: selectedCity()))!)
}
func sourceURL(city: City) -> String {
switch city {
case .Beijing:
return "http://www.stateair.net/web/post/1/1.html";
case .Chengdu:
return "http://www.stateair.net/web/post/1/2.html";
case .Guangzhou:
return "http://www.stateair.net/web/post/1/3.html";
case .Shanghai:
return "http://www.stateair.net/web/post/1/4.html";
case .Shenyang:
return "http://www.stateair.net/web/post/1/5.html";
}
}
func selectedCity() -> City {
let sc: String? = UserDefaults.standard.string(forKey:"selected_city")
if sc == nil {
return .Beijing
} else {
return City(rawValue: sc!)!
}
}
func sourceDescription() -> String {
return "\(selectedCity()): \(sourceURL(city:selectedCity()))"
}
let CitiesList: [City] = [.Beijing, .Chengdu, .Guangzhou, .Shanghai, .Shenyang]
func currentHour() -> Int {
let date = Date()
let gregorianCal = Calendar(identifier: .gregorian)
let comps = gregorianCal.dateComponents(in: TimeZone(abbreviation: "HKT")!, from: date)
return comps.hour!
}
func currentMinute() -> Int {
let date = Date()
let gregorianCal = Calendar(identifier: .gregorian)
let comps = gregorianCal.dateComponents(in: TimeZone(abbreviation: "HKT")!, from: date)
return comps.minute!
}
| mit | 418cde855aaf63c65f5436ceaf4a76d0 | 30.806452 | 142 | 0.611359 | 3.833593 | false | false | false | false |
gunan/tensorflow | tensorflow/lite/experimental/swift/Sources/Interpreter.swift | 1 | 12029 | // Copyright 2018 Google Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at:
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import Foundation
import TensorFlowLiteC
/// A TensorFlow Lite interpreter that performs inference from a given model.
public final class Interpreter {
/// The configuration options for the `Interpreter`.
public let options: Options?
/// An `Array` of `Delegate`s for the `Interpreter` to use to perform graph operations.
public let delegates: [Delegate]?
/// The total number of input `Tensor`s associated with the model.
public var inputTensorCount: Int {
return Int(TfLiteInterpreterGetInputTensorCount(cInterpreter))
}
/// The total number of output `Tensor`s associated with the model.
public var outputTensorCount: Int {
return Int(TfLiteInterpreterGetOutputTensorCount(cInterpreter))
}
/// The `TfLiteInterpreter` C pointer type represented as an `UnsafePointer<TfLiteInterpreter>`.
private typealias CInterpreter = OpaquePointer
/// The underlying `TfLiteInterpreter` C pointer.
private var cInterpreter: CInterpreter?
/// Creates a new instance with the given values.
///
/// - Parameters:
/// - modelPath: The local file path to a TensorFlow Lite model.
/// - options: Configurations for the `Interpreter`. The default is `nil` indicating that the
/// `Interpreter` will determine the configuration options.
/// - delegate: `Array` of `Delegate`s for the `Interpreter` to use to peform graph operations.
/// The default is `nil`.
/// - Throws: An error if the model could not be loaded or the interpreter could not be created.
public init(modelPath: String, options: Options? = nil, delegates: [Delegate]? = nil) throws {
guard let model = Model(filePath: modelPath) else { throw InterpreterError.failedToLoadModel }
guard let cInterpreterOptions = TfLiteInterpreterOptionsCreate() else {
throw InterpreterError.failedToCreateInterpreter
}
defer { TfLiteInterpreterOptionsDelete(cInterpreterOptions) }
self.options = options
self.delegates = delegates
options.map {
if let threadCount = $0.threadCount, threadCount > 0 {
TfLiteInterpreterOptionsSetNumThreads(cInterpreterOptions, Int32(threadCount))
}
TfLiteInterpreterOptionsSetErrorReporter(
cInterpreterOptions,
{ (_, format, args) -> Void in
// Workaround for optionality differences for x86_64 (non-optional) and arm64 (optional).
let optionalArgs: CVaListPointer? = args
guard let cFormat = format,
let arguments = optionalArgs,
let message = String(cFormat: cFormat, arguments: arguments)
else {
return
}
print(String(describing: InterpreterError.tensorFlowLiteError(message)))
},
nil
)
}
delegates?.forEach { TfLiteInterpreterOptionsAddDelegate(cInterpreterOptions, $0.cDelegate) }
guard let cInterpreter = TfLiteInterpreterCreate(model.cModel, cInterpreterOptions) else {
throw InterpreterError.failedToCreateInterpreter
}
self.cInterpreter = cInterpreter
}
deinit {
TfLiteInterpreterDelete(cInterpreter)
}
/// Invokes the interpreter to perform inference from the loaded graph.
///
/// - Throws: An error if the model was not ready because the tensors were not allocated.
public func invoke() throws {
guard TfLiteInterpreterInvoke(cInterpreter) == kTfLiteOk else {
throw InterpreterError.allocateTensorsRequired
}
}
/// Returns the input `Tensor` at the given index.
///
/// - Parameters:
/// - index: The index for the input `Tensor`.
/// - Throws: An error if the index is invalid or the tensors have not been allocated.
/// - Returns: The input `Tensor` at the given index.
public func input(at index: Int) throws -> Tensor {
let maxIndex = inputTensorCount - 1
guard case 0...maxIndex = index else {
throw InterpreterError.invalidTensorIndex(index: index, maxIndex: maxIndex)
}
guard let cTensor = TfLiteInterpreterGetInputTensor(cInterpreter, Int32(index)),
let bytes = TfLiteTensorData(cTensor),
let nameCString = TfLiteTensorName(cTensor)
else {
throw InterpreterError.allocateTensorsRequired
}
guard let dataType = Tensor.DataType(type: TfLiteTensorType(cTensor)) else {
throw InterpreterError.invalidTensorDataType
}
let name = String(cString: nameCString)
let rank = TfLiteTensorNumDims(cTensor)
let dimensions = (0..<rank).map { Int(TfLiteTensorDim(cTensor, $0)) }
let shape = Tensor.Shape(dimensions)
let byteCount = TfLiteTensorByteSize(cTensor)
let data = Data(bytes: bytes, count: byteCount)
let cQuantizationParams = TfLiteTensorQuantizationParams(cTensor)
let scale = cQuantizationParams.scale
let zeroPoint = Int(cQuantizationParams.zero_point)
var quantizationParameters: QuantizationParameters? = nil
if scale != 0.0 {
quantizationParameters = QuantizationParameters(scale: scale, zeroPoint: zeroPoint)
}
let tensor = Tensor(
name: name,
dataType: dataType,
shape: shape,
data: data,
quantizationParameters: quantizationParameters
)
return tensor
}
/// Returns the output `Tensor` at the given index.
///
/// - Parameters:
/// - index: The index for the output `Tensor`.
/// - Throws: An error if the index is invalid, tensors haven't been allocated, or interpreter
/// has not been invoked for models that dynamically compute output tensors based on the
/// values of its input tensors.
/// - Returns: The output `Tensor` at the given index.
public func output(at index: Int) throws -> Tensor {
let maxIndex = outputTensorCount - 1
guard case 0...maxIndex = index else {
throw InterpreterError.invalidTensorIndex(index: index, maxIndex: maxIndex)
}
guard let cTensor = TfLiteInterpreterGetOutputTensor(cInterpreter, Int32(index)),
let bytes = TfLiteTensorData(cTensor),
let nameCString = TfLiteTensorName(cTensor)
else {
throw InterpreterError.invokeInterpreterRequired
}
guard let dataType = Tensor.DataType(type: TfLiteTensorType(cTensor)) else {
throw InterpreterError.invalidTensorDataType
}
let name = String(cString: nameCString)
let rank = TfLiteTensorNumDims(cTensor)
let dimensions = (0..<rank).map { Int(TfLiteTensorDim(cTensor, $0)) }
let shape = Tensor.Shape(dimensions)
let byteCount = TfLiteTensorByteSize(cTensor)
let data = Data(bytes: bytes, count: byteCount)
let cQuantizationParams = TfLiteTensorQuantizationParams(cTensor)
let scale = cQuantizationParams.scale
let zeroPoint = Int(cQuantizationParams.zero_point)
var quantizationParameters: QuantizationParameters? = nil
if scale != 0.0 {
quantizationParameters = QuantizationParameters(scale: scale, zeroPoint: zeroPoint)
}
let tensor = Tensor(
name: name,
dataType: dataType,
shape: shape,
data: data,
quantizationParameters: quantizationParameters
)
return tensor
}
/// Resizes the input `Tensor` at the given index to the specified `Tensor.Shape`.
///
/// - Note: After resizing an input tensor, the client **must** explicitly call
/// `allocateTensors()` before attempting to access the resized tensor data or invoking the
/// interpreter to perform inference.
/// - Parameters:
/// - index: The index for the input `Tensor`.
/// - shape: The shape to resize the input `Tensor` to.
/// - Throws: An error if the input tensor at the given index could not be resized.
public func resizeInput(at index: Int, to shape: Tensor.Shape) throws {
let maxIndex = inputTensorCount - 1
guard case 0...maxIndex = index else {
throw InterpreterError.invalidTensorIndex(index: index, maxIndex: maxIndex)
}
guard TfLiteInterpreterResizeInputTensor(
cInterpreter,
Int32(index),
shape.int32Dimensions,
Int32(shape.rank)
) == kTfLiteOk
else {
throw InterpreterError.failedToResizeInputTensor(index: index)
}
}
/// Copies the given data to the input `Tensor` at the given index.
///
/// - Parameters:
/// - data: The data to be copied to the input `Tensor`'s data buffer.
/// - index: The index for the input `Tensor`.
/// - Throws: An error if the `data.count` does not match the input tensor's `data.count` or if
/// the given index is invalid.
/// - Returns: The input `Tensor` with the copied data.
@discardableResult
public func copy(_ data: Data, toInputAt index: Int) throws -> Tensor {
let maxIndex = inputTensorCount - 1
guard case 0...maxIndex = index else {
throw InterpreterError.invalidTensorIndex(index: index, maxIndex: maxIndex)
}
guard let cTensor = TfLiteInterpreterGetInputTensor(cInterpreter, Int32(index)) else {
throw InterpreterError.allocateTensorsRequired
}
let byteCount = TfLiteTensorByteSize(cTensor)
guard data.count == byteCount else {
throw InterpreterError.invalidTensorDataCount(provided: data.count, required: byteCount)
}
#if swift(>=5.0)
let status = data.withUnsafeBytes {
TfLiteTensorCopyFromBuffer(cTensor, $0.baseAddress, data.count)
}
#else
let status = data.withUnsafeBytes { TfLiteTensorCopyFromBuffer(cTensor, $0, data.count) }
#endif // swift(>=5.0)
guard status == kTfLiteOk else { throw InterpreterError.failedToCopyDataToInputTensor }
return try input(at: index)
}
/// Allocates memory for all input `Tensor`s based on their `Tensor.Shape`s.
///
/// - Note: This is a relatively expensive operation and should only be called after creating the
/// interpreter and resizing any input tensors.
/// - Throws: An error if memory could not be allocated for the input tensors.
public func allocateTensors() throws {
guard TfLiteInterpreterAllocateTensors(cInterpreter) == kTfLiteOk else {
throw InterpreterError.failedToAllocateTensors
}
}
}
extension Interpreter {
/// Options for configuring the `Interpreter`.
public struct Options: Equatable, Hashable {
/// The maximum number of CPU threads that the interpreter should run on. The default is `nil`
/// indicating that the `Interpreter` will decide the number of threads to use.
public var threadCount: Int? = nil
/// Creates a new instance with the default values.
public init() {}
}
}
/// A type alias for `Interpreter.Options` to support backwards compatibility with the deprecated
/// `InterpreterOptions` struct.
@available(*, deprecated, renamed: "Interpreter.Options")
public typealias InterpreterOptions = Interpreter.Options
extension String {
/// Returns a new `String` initialized by using the given format C array as a template into which
/// the remaining argument values are substituted according to the user’s default locale.
///
/// - Note: Returns `nil` if a new `String` could not be constructed from the given values.
/// - Parameters:
/// - cFormat: The format C array as a template for substituting values.
/// - arguments: A C pointer to a `va_list` of arguments to substitute into `cFormat`.
init?(cFormat: UnsafePointer<CChar>, arguments: CVaListPointer) {
var buffer: UnsafeMutablePointer<CChar>?
guard vasprintf(&buffer, cFormat, arguments) != 0, let cString = buffer else { return nil }
self.init(validatingUTF8: cString)
}
}
| apache-2.0 | e5cd3dda321a6b9863a776843c0df226 | 40.329897 | 99 | 0.706909 | 4.307665 | false | false | false | false |
TeamProxima/predictive-fault-tracker | mobile/SieHack/Pods/Charts/Source/Charts/Renderers/ScatterChartRenderer.swift | 17 | 7950 | //
// ScatterChartRenderer.swift
// Charts
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/Charts
//
import Foundation
import CoreGraphics
#if !os(OSX)
import UIKit
#endif
open class ScatterChartRenderer: LineScatterCandleRadarRenderer
{
open weak var dataProvider: ScatterChartDataProvider?
public init(dataProvider: ScatterChartDataProvider?, animator: Animator?, viewPortHandler: ViewPortHandler?)
{
super.init(animator: animator, viewPortHandler: viewPortHandler)
self.dataProvider = dataProvider
}
open override func drawData(context: CGContext)
{
guard let scatterData = dataProvider?.scatterData else { return }
for i in 0 ..< scatterData.dataSetCount
{
guard let set = scatterData.getDataSetByIndex(i) else { continue }
if set.isVisible
{
if !(set is IScatterChartDataSet)
{
fatalError("Datasets for ScatterChartRenderer must conform to IScatterChartDataSet")
}
drawDataSet(context: context, dataSet: set as! IScatterChartDataSet)
}
}
}
fileprivate var _lineSegments = [CGPoint](repeating: CGPoint(), count: 2)
open func drawDataSet(context: CGContext, dataSet: IScatterChartDataSet)
{
guard
let dataProvider = dataProvider,
let animator = animator,
let viewPortHandler = self.viewPortHandler
else { return }
let trans = dataProvider.getTransformer(forAxis: dataSet.axisDependency)
let phaseY = animator.phaseY
let entryCount = dataSet.entryCount
var point = CGPoint()
let valueToPixelMatrix = trans.valueToPixelMatrix
if let renderer = dataSet.shapeRenderer
{
context.saveGState()
for j in 0 ..< Int(min(ceil(Double(entryCount) * animator.phaseX), Double(entryCount)))
{
guard let e = dataSet.entryForIndex(j) else { continue }
point.x = CGFloat(e.x)
point.y = CGFloat(e.y * phaseY)
point = point.applying(valueToPixelMatrix)
if !viewPortHandler.isInBoundsRight(point.x)
{
break
}
if !viewPortHandler.isInBoundsLeft(point.x) ||
!viewPortHandler.isInBoundsY(point.y)
{
continue
}
renderer.renderShape(context: context, dataSet: dataSet, viewPortHandler: viewPortHandler, point: point, color: dataSet.color(atIndex: j))
}
context.restoreGState()
}
else
{
print("There's no IShapeRenderer specified for ScatterDataSet", terminator: "\n")
}
}
open override func drawValues(context: CGContext)
{
guard
let dataProvider = dataProvider,
let scatterData = dataProvider.scatterData,
let animator = animator,
let viewPortHandler = self.viewPortHandler
else { return }
// if values are drawn
if isDrawingValuesAllowed(dataProvider: dataProvider)
{
guard let dataSets = scatterData.dataSets as? [IScatterChartDataSet] else { return }
let phaseY = animator.phaseY
var pt = CGPoint()
for i in 0 ..< scatterData.dataSetCount
{
let dataSet = dataSets[i]
if !shouldDrawValues(forDataSet: dataSet)
{
continue
}
let valueFont = dataSet.valueFont
guard let formatter = dataSet.valueFormatter else { continue }
let trans = dataProvider.getTransformer(forAxis: dataSet.axisDependency)
let valueToPixelMatrix = trans.valueToPixelMatrix
let shapeSize = dataSet.scatterShapeSize
let lineHeight = valueFont.lineHeight
_xBounds.set(chart: dataProvider, dataSet: dataSet, animator: animator)
for j in stride(from: _xBounds.min, through: _xBounds.range + _xBounds.min, by: 1)
{
guard let e = dataSet.entryForIndex(j) else { break }
pt.x = CGFloat(e.x)
pt.y = CGFloat(e.y * phaseY)
pt = pt.applying(valueToPixelMatrix)
if (!viewPortHandler.isInBoundsRight(pt.x))
{
break
}
// make sure the lines don't do shitty things outside bounds
if (!viewPortHandler.isInBoundsLeft(pt.x)
|| !viewPortHandler.isInBoundsY(pt.y))
{
continue
}
let text = formatter.stringForValue(
e.y,
entry: e,
dataSetIndex: i,
viewPortHandler: viewPortHandler)
ChartUtils.drawText(
context: context,
text: text,
point: CGPoint(
x: pt.x,
y: pt.y - shapeSize - lineHeight),
align: .center,
attributes: [NSFontAttributeName: valueFont, NSForegroundColorAttributeName: dataSet.valueTextColorAt(j)]
)
}
}
}
}
open override func drawExtras(context: CGContext)
{
}
open override func drawHighlighted(context: CGContext, indices: [Highlight])
{
guard
let dataProvider = dataProvider,
let scatterData = dataProvider.scatterData,
let animator = animator
else { return }
context.saveGState()
for high in indices
{
guard
let set = scatterData.getDataSetByIndex(high.dataSetIndex) as? IScatterChartDataSet,
set.isHighlightEnabled
else { continue }
guard let entry = set.entryForXValue(high.x, closestToY: high.y) else { continue }
if !isInBoundsX(entry: entry, dataSet: set) { continue }
context.setStrokeColor(set.highlightColor.cgColor)
context.setLineWidth(set.highlightLineWidth)
if set.highlightLineDashLengths != nil
{
context.setLineDash(phase: set.highlightLineDashPhase, lengths: set.highlightLineDashLengths!)
}
else
{
context.setLineDash(phase: 0.0, lengths: [])
}
let x = entry.x // get the x-position
let y = entry.y * Double(animator.phaseY)
let trans = dataProvider.getTransformer(forAxis: set.axisDependency)
let pt = trans.pixelForValues(x: x, y: y)
high.setDraw(pt: pt)
// draw the lines
drawHighlightLines(context: context, point: pt, set: set)
}
context.restoreGState()
}
}
| mit | d64e356e03822ce91ae18308c39aaa19 | 32.686441 | 154 | 0.505283 | 6.215794 | false | false | false | false |
pseudomuto/CircuitBreaker | Pod/Classes/Breaker.swift | 1 | 2659 | //
// Breaker.swift
// Pods
//
// Created by David Muto on 2016-02-05.
//
//
public enum StateType {
case Closed
case Open
case HalfOpen
}
public enum Error: ErrorType {
case OpenCircuit
case InvocationTimeout
}
public class Breaker {
private struct Constants {
static let waitTimeout: NSTimeInterval = 0.1
}
private let semaphore = dispatch_semaphore_create(1)
private let options: Options!
private let invoker: Invoker!
// MARK: - States
private var currentState: State!
private lazy var closedState: State = {
ClosedState(
self,
invoker: self.invoker,
errorThreshold: self.options.errorThreshold,
invocationTimeout: self.options.invocationTimeout
)
}()
private lazy var openState: State = {
OpenState(self, invoker: self.invoker, resetTimeout: self.options.resetTimeout)
}()
private lazy var halfOpenState: State = {
HalfOpenState(
self,
invoker: self.invoker,
successThreshold: self.options.successThreshold,
invocationTimeout: self.options.invocationTimeout
)
}()
public var isClosed: Bool { return currentState.type() == .Closed }
public var isHalfOpen: Bool { return currentState.type() == .HalfOpen }
public var isOpen: Bool { return currentState.type() == .Open }
// MARK: - Initializers
public init(_ name: String, withOptions options: Options) {
self.invoker = Invoker(dispatch_queue_create(name, DISPATCH_QUEUE_SERIAL))
self.options = options
currentState = closedState
}
public convenience init(_ name: String) {
self.init(name, withOptions: Options())
}
// MARK: - Invocation
public func invoke<T>(block: () throws -> T) throws -> T {
return try currentState.invoke(block)
}
// MARK: - State Transitions
public func force(state: StateType) {
switch state {
case .Closed:
reset(currentState)
case .Open:
trip(currentState)
case .HalfOpen:
attempt(currentState)
}
}
private func transition(fromState: State, toState: State) {
// TODO: add logging here
dispatch_semaphore_wait(semaphore, Constants.waitTimeout.dispatchTime())
defer { dispatch_semaphore_signal(semaphore) }
currentState = toState
currentState.activate()
}
}
// MARK: - Switch
extension Breaker: Switch {
public func reset(fromState: State) {
transition(currentState, toState: closedState)
}
public func trip(fromState: State) {
transition(currentState, toState: openState)
}
public func attempt(fromState: State) {
transition(currentState, toState: halfOpenState)
}
}
| mit | f2c57dc4ca22b83363345e57936102df | 21.922414 | 83 | 0.673185 | 4.227345 | false | false | false | false |
atl009/WordPress-iOS | WordPress/Classes/ViewRelated/Media/MediaLibraryViewController.swift | 1 | 36822 | import UIKit
import Gridicons
import SVProgressHUD
import WordPressShared
import WPMediaPicker
import MobileCoreServices
/// Displays the user's media library in a grid
///
class MediaLibraryViewController: UIViewController {
fileprivate static let restorationIdentifier = "MediaLibraryViewController"
let blog: Blog
fileprivate let pickerViewController: WPMediaPickerViewController
fileprivate let pickerDataSource: MediaLibraryPickerDataSource
fileprivate var isLoading: Bool = false
fileprivate var noResultsView: WPNoResultsView? = nil
fileprivate var selectedAsset: Media? = nil
fileprivate var capturePresenter: WPMediaCapturePresenter?
lazy fileprivate var searchBarContainer: UIView = {
let view = UIView()
view.translatesAutoresizingMaskIntoConstraints = false
return view
}()
lazy fileprivate var searchBar: UISearchBar = {
let bar = UISearchBar()
WPStyleGuide.configureSearchBar(bar)
bar.delegate = self
bar.autoresizingMask = [.flexibleWidth, .flexibleHeight]
return bar
}()
fileprivate let stackView: UIStackView = {
let stackView = UIStackView()
stackView.translatesAutoresizingMaskIntoConstraints = false
stackView.axis = .vertical
stackView.spacing = 0
return stackView
}()
fileprivate lazy var mediaProgressCoordinator: MediaProgressCoordinator = {
let coordinator = MediaProgressCoordinator()
coordinator.delegate = self
return coordinator
}()
var searchQuery: String? = nil
private var uploadCoordinatorUUID: UUID? = nil
// Only used during testing phase of upload coordinator development.
// Remove when upload coordinator is properly integrated into the media library.
// @frosty 2017-11-01
//
fileprivate var useUploadCoordinator = false
// MARK: - Initializers
init(blog: Blog) {
WPMediaCollectionViewCell.appearance().placeholderTintColor = WPStyleGuide.greyLighten30()
WPMediaCollectionViewCell.appearance().placeholderBackgroundColor = WPStyleGuide.darkGrey()
WPMediaCollectionViewCell.appearance().loadingBackgroundColor = WPStyleGuide.lightGrey()
self.blog = blog
self.pickerViewController = WPMediaPickerViewController()
self.pickerDataSource = MediaLibraryPickerDataSource(blog: blog)
super.init(nibName: nil, bundle: nil)
super.restorationIdentifier = MediaLibraryViewController.restorationIdentifier
restorationClass = MediaLibraryViewController.self
configurePickerViewController()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
deinit {
unregisterChangeObserver()
unregisterUploadCoordinatorObserver()
}
private func configurePickerViewController() {
pickerViewController.mediaPickerDelegate = self
let options = WPMediaPickerOptions()
options.showMostRecentFirst = true
options.filter = [.all]
options.allowMultipleSelection = false
options.allowCaptureOfMedia = false
pickerViewController.options = options
pickerViewController.dataSource = pickerDataSource
}
// MARK: - View Loading
var uploadObserverUUID: UUID?
override func viewDidLoad() {
super.viewDidLoad()
title = NSLocalizedString("Media", comment: "Title for Media Library section of the app.")
automaticallyAdjustsScrollViewInsets = false
addStackView()
addMediaPickerAsChildViewController()
addSearchBarContainer()
addNoResultsView()
registerChangeObserver()
registerUploadCoordinatorObserver()
updateViewState(for: pickerDataSource.totalAssetCount)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
resetNavigationColors()
registerForKeyboardNotifications()
registerForHUDNotifications()
if let searchQuery = searchQuery,
!searchQuery.isEmpty {
// If we deleted the last asset, then clear the search
if pickerDataSource.numberOfAssets() == 0 {
clearSearch()
} else {
searchBar.text = searchQuery
}
}
}
/*
This is to restore the navigation bar colors after the UIDocumentPickerViewController has been dismissed,
either by uploading media or cancelling. Doing this in the UIDocumentPickerDelegate methods either did nothing
or the resetting wasn't permanent.
*/
fileprivate func resetNavigationColors() {
WPStyleGuide.configureNavigationBarAppearance()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
selectedAsset = nil
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
unregisterForKeyboardNotifications()
unregisterForHUDNotifications()
if searchBar.isFirstResponder {
searchQuery = searchBar.text
searchBar.resignFirstResponder()
}
}
private func addStackView() {
view.addSubview(stackView)
NSLayoutConstraint.activate([
view.leadingAnchor.constraint(equalTo: stackView.leadingAnchor),
view.trailingAnchor.constraint(equalTo: stackView.trailingAnchor),
topLayoutGuide.bottomAnchor.constraint(equalTo: stackView.topAnchor),
bottomLayoutGuide.topAnchor.constraint(equalTo: stackView.bottomAnchor)
])
}
private func addMediaPickerAsChildViewController() {
pickerViewController.willMove(toParentViewController: self)
stackView.addArrangedSubview(pickerViewController.view)
pickerViewController.view.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
pickerViewController.view.leadingAnchor.constraint(equalTo: view.leadingAnchor),
pickerViewController.view.trailingAnchor.constraint(equalTo: view.trailingAnchor)
])
addChildViewController(pickerViewController)
pickerViewController.didMove(toParentViewController: self)
}
private func addSearchBarContainer() {
searchBarContainer.backgroundColor = searchBar.barTintColor
stackView.insertArrangedSubview(searchBarContainer, at: 0)
NSLayoutConstraint.activate([
searchBarContainer.leadingAnchor.constraint(equalTo: view.leadingAnchor),
searchBarContainer.trailingAnchor.constraint(equalTo: view.trailingAnchor),
])
wrapSearchBarInPaddingView()
let height = searchBar.intrinsicContentSize.height
let heightConstraint = searchBarContainer.heightAnchor.constraint(equalToConstant: height)
heightConstraint.priority = UILayoutPriorityDefaultLow
heightConstraint.isActive = true
let expandedHeightConstraint = searchBarContainer.heightAnchor.constraint(greaterThanOrEqualToConstant: height)
expandedHeightConstraint.priority = UILayoutPriorityRequired
expandedHeightConstraint.isActive = true
searchBarContainer.layoutIfNeeded()
searchBar.sizeToFit()
}
private func wrapSearchBarInPaddingView() {
let paddingView = UIView()
paddingView.translatesAutoresizingMaskIntoConstraints = false
searchBarContainer.addSubview(paddingView)
paddingView.addSubview(searchBar)
var leading = searchBarContainer.leadingAnchor
var trailing = searchBarContainer.trailingAnchor
if #available(iOS 11.0, *) {
leading = searchBarContainer.safeAreaLayoutGuide.leadingAnchor
trailing = searchBarContainer.safeAreaLayoutGuide.trailingAnchor
}
NSLayoutConstraint.activate([
paddingView.leadingAnchor.constraint(equalTo: leading),
paddingView.trailingAnchor.constraint(equalTo: trailing),
paddingView.topAnchor.constraint(equalTo: searchBarContainer.topAnchor),
paddingView.bottomAnchor.constraint(equalTo: searchBarContainer.bottomAnchor),
])
}
private func addNoResultsView() {
guard let noResultsView = WPNoResultsView(title: nil,
message: nil,
accessoryView: UIImageView(image: UIImage(named: "media-no-results")),
buttonTitle: nil) else { return }
pickerViewController.collectionView?.addSubview(noResultsView)
noResultsView.centerInSuperview()
noResultsView.delegate = self
self.noResultsView = noResultsView
}
// MARK: - Keyboard handling
private func registerForKeyboardNotifications() {
NotificationCenter.default.addObserver(self, selector: #selector(keyboardDidChangeFrame(_:)), name: NSNotification.Name.UIKeyboardDidChangeFrame, object: nil)
}
private func unregisterForKeyboardNotifications() {
NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardDidChangeFrame, object: nil)
}
@objc private func keyboardDidChangeFrame(_ notification: Foundation.Notification) {
let duration = notification.userInfo?[UIKeyboardAnimationDurationUserInfoKey] as? TimeInterval ?? 0.2
UIView.animate(withDuration: duration) {
self.noResultsView?.centerInSuperview()
}
}
// MARK: - HUD handling
private func registerForHUDNotifications() {
NotificationCenter.default.addObserver(self, selector: #selector(statusHUDWasTapped(_:)), name: NSNotification.Name.SVProgressHUDDidTouchDownInside, object: nil)
}
private func unregisterForHUDNotifications() {
NotificationCenter.default.removeObserver(self, name: NSNotification.Name.SVProgressHUDDidTouchDownInside, object: nil)
}
@objc private func statusHUDWasTapped(_ notification: Notification) {
if mediaProgressCoordinator.isRunning {
mediaProgressCoordinator.cancelAllPendingUploads()
SVProgressHUD.dismiss()
}
}
fileprivate func prepareMediaProgressForNumberOfAssets(_ count: Int) {
showPreparingProgressHUD()
mediaProgressCoordinator.track(numberOfItems: count)
// Wait until all assets are uploaded before we update the collection view
pickerDataSource.isPaused = true
}
fileprivate func showPreparingProgressHUD() {
SVProgressHUD.setDefaultMaskType(.clear)
SVProgressHUD.setMinimumDismissTimeInterval(1.0)
SVProgressHUD.show(withStatus: NSLocalizedString("Preparing...\nTap to cancel", comment: "Text displayed in HUD while preparing to upload media items."))
}
// MARK: - Update view state
fileprivate func updateViewState(for assetCount: Int) {
updateNavigationItemButtons(for: assetCount)
updateNoResultsView(for: assetCount)
updateSearchBar(for: assetCount)
}
private func updateNavigationItemButtons(for assetCount: Int) {
if isEditing {
navigationItem.setLeftBarButton(UIBarButtonItem(barButtonSystemItem: .cancel, target: self, action: #selector(editTapped)), animated: false)
let trashButton = UIBarButtonItem(image: Gridicon.iconOfType(.trash), style: .plain, target: self, action: #selector(trashTapped))
navigationItem.setRightBarButtonItems([trashButton], animated: true)
navigationItem.rightBarButtonItem?.isEnabled = false
} else {
navigationItem.setLeftBarButton(nil, animated: false)
var barButtonItems = [UIBarButtonItem]()
if blog.userCanUploadMedia {
let addButton = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(addTapped))
barButtonItems.append(addButton)
}
if blog.supports(.mediaDeletion) && assetCount > 0 {
let editButton = UIBarButtonItem(barButtonSystemItem: .edit, target: self, action: #selector(editTapped))
barButtonItems.append(editButton)
navigationItem.setRightBarButtonItems(barButtonItems, animated: false)
} else {
navigationItem.setRightBarButtonItems(barButtonItems, animated: false)
}
}
}
fileprivate func updateNoResultsView(for assetCount: Int) {
let shouldShowNoResults = (assetCount == 0)
noResultsView?.isHidden = !shouldShowNoResults
guard shouldShowNoResults else { return }
if isLoading {
updateNoResultsForFetching()
} else if hasSearchQuery {
noResultsView?.accessoryView = UIImageView(image: UIImage(named: "media-no-results"))
let text = NSLocalizedString("No media files match your search for %@", comment: "Message displayed when no results are returned from a media library search. Should match Calypso.")
noResultsView?.titleText = String.localizedStringWithFormat(text, pickerDataSource.searchQuery)
noResultsView?.messageText = nil
noResultsView?.buttonTitle = nil
} else {
noResultsView?.accessoryView = UIImageView(image: UIImage(named: "media-no-results"))
noResultsView?.titleText = NSLocalizedString("You don't have any media.", comment: "Title displayed when the user doesn't have any media in their media library. Should match Calypso.")
if blog.userCanUploadMedia {
noResultsView?.messageText = NSLocalizedString("Would you like to upload something?", comment: "Prompt displayed when the user has an empty media library. Should match Calypso.")
noResultsView?.buttonTitle = NSLocalizedString("Upload Media", comment: "Title for button displayed when the user has an empty media library")
}
}
noResultsView?.sizeToFit()
}
func updateNoResultsForFetching() {
noResultsView?.titleText = NSLocalizedString("Fetching media...", comment: "Title displayed whilst fetching media from the user's media library")
noResultsView?.messageText = nil
noResultsView?.buttonTitle = nil
let animatedBox = WPAnimatedBox()
noResultsView?.accessoryView = animatedBox
animatedBox.animate(afterDelay: 0.1)
}
private func updateSearchBar(for assetCount: Int) {
let shouldShowBar = hasSearchQuery || assetCount > 0
if shouldShowBar {
if searchBarContainer.superview != stackView {
stackView.insertArrangedSubview(searchBarContainer, at: 0)
}
} else {
if searchBarContainer.superview == stackView {
searchBarContainer.removeFromSuperview()
}
}
}
private var hasSearchQuery: Bool {
return (pickerDataSource.searchQuery ?? "").count > 0
}
// MARK: - Actions
@objc fileprivate func addTapped() {
if #available(iOS 11, *), FeatureFlag.iCloudFilesSupport.enabled {
showOptionsMenu()
}
else {
showMediaPicker()
}
}
private func showMediaPicker() {
let options = WPMediaPickerOptions()
options.showMostRecentFirst = true
options.filter = [.all]
// If iOS11, media capture is available via showOptionsMenu()
if #available(iOS 11, *) {
// NOTE: once iCloudFilesSupport is permanently enabled, this needs to be false.
options.allowCaptureOfMedia = !(FeatureFlag.iCloudFilesSupport.enabled)
}
let picker = WPNavigationMediaPickerViewController(options: options)
picker.dataSource = WPPHAssetDataSource()
picker.delegate = self
present(picker, animated: true, completion: nil)
}
private func showOptionsMenu() {
let menuAlert = UIAlertController(title: nil, message: nil, preferredStyle: UIAlertControllerStyle.actionSheet)
if WPMediaCapturePresenter.isCaptureAvailable() {
menuAlert.addDefaultActionWithTitle(NSLocalizedString("Take Photo or Video", comment: "Menu option for taking an image or video with the device's camera.")) { _ in
self.presentMediaCapture()
}
}
menuAlert.addDefaultActionWithTitle(NSLocalizedString("Photo Library", comment: "Menu option for selecting media from the device's photo library.")) { _ in
self.showMediaPicker()
}
menuAlert.addDefaultActionWithTitle(NSLocalizedString("Other Apps", comment: "Menu option used for adding media from other applications.")) { _ in
self.showDocumentPicker()
}
if FeatureFlag.asyncUploadsInMediaLibrary.enabled {
menuAlert.addDefaultActionWithTitle("Photo Library (Async - Debug)") { _ in
self.useUploadCoordinator = true
self.showMediaPicker()
}
}
menuAlert.addCancelActionWithTitle(NSLocalizedString("Cancel", comment: "Cancel button"))
// iPad support
menuAlert.popoverPresentationController?.sourceView = view
menuAlert.popoverPresentationController?.barButtonItem = navigationItem.rightBarButtonItem
present(menuAlert, animated: true, completion: nil)
}
@objc private func editTapped() {
isEditing = !isEditing
let options = pickerViewController.options.copy() as! WPMediaPickerOptions
options.allowMultipleSelection = isEditing
pickerViewController.options = options
pickerViewController.clearSelectedAssets(true)
}
@objc private func trashTapped() {
let message: String
if pickerViewController.selectedAssets.count == 1 {
message = NSLocalizedString("Are you sure you want to permanently delete this item?", comment: "Message prompting the user to confirm that they want to permanently delete a media item. Should match Calypso.")
} else {
message = NSLocalizedString("Are you sure you want to permanently delete these items?", comment: "Message prompting the user to confirm that they want to permanently delete a group of media items.")
}
let alertController = UIAlertController(title: nil,
message: message,
preferredStyle: .alert)
alertController.addCancelActionWithTitle(NSLocalizedString("Cancel", comment: ""))
alertController.addDestructiveActionWithTitle(NSLocalizedString("Delete", comment: "Title for button that permanently deletes one or more media items (photos / videos)"), handler: { action in
self.deleteSelectedItems()
})
present(alertController, animated: true, completion: nil)
}
private func deleteSelectedItems() {
guard pickerViewController.selectedAssets.count > 0 else { return }
guard let assets = pickerViewController.selectedAssets as? [Media] else { return }
let deletedItemsCount = assets.count
let updateProgress = { (progress: Progress?) in
let fractionCompleted = progress?.fractionCompleted ?? 0
SVProgressHUD.showProgress(Float(fractionCompleted), status: NSLocalizedString("Deleting...", comment: "Text displayed in HUD while a media item is being deleted."))
}
SVProgressHUD.setDefaultMaskType(.clear)
SVProgressHUD.setMinimumDismissTimeInterval(1.0)
// Initialize the progress HUD before we start
updateProgress(nil)
let service = MediaService(managedObjectContext: ContextManager.sharedInstance().mainContext)
service.deleteMedia(assets,
progress: updateProgress,
success: { [weak self] in
WPAppAnalytics.track(.mediaLibraryDeletedItems, withProperties: ["number_of_items_deleted": deletedItemsCount], with: self?.blog)
SVProgressHUD.showSuccess(withStatus: NSLocalizedString("Deleted!", comment: "Text displayed in HUD after successfully deleting a media item"))
self?.isEditing = false
}, failure: { error in
SVProgressHUD.showError(withStatus: NSLocalizedString("Unable to delete all media items.", comment: "Text displayed in HUD if there was an error attempting to delete a group of media items."))
})
}
override var isEditing: Bool {
didSet {
updateNavigationItemButtons(for: pickerDataSource.totalAssetCount)
}
}
// MARK: - Media Library Change Observer
private var mediaLibraryChangeObserverKey: NSObjectProtocol? = nil
private func registerChangeObserver() {
assert(mediaLibraryChangeObserverKey == nil)
mediaLibraryChangeObserverKey = pickerDataSource.registerChangeObserverBlock({ [weak self] _, _, _, _, _ in
guard let strongSelf = self else { return }
strongSelf.updateViewState(for: strongSelf.pickerDataSource.numberOfAssets())
if strongSelf.pickerDataSource.totalAssetCount > 0 {
strongSelf.updateNavigationItemButtonsForCurrentAssetSelection()
} else {
strongSelf.isEditing = false
}
// If we're presenting an item and it's been deleted, pop the
// detail view off the stack
if let navigationController = strongSelf.navigationController,
navigationController.topViewController != strongSelf,
let asset = strongSelf.selectedAsset,
asset.isDeleted {
_ = strongSelf.navigationController?.popToViewController(strongSelf, animated: true)
}
})
}
private func unregisterChangeObserver() {
if let mediaLibraryChangeObserverKey = mediaLibraryChangeObserverKey {
pickerDataSource.unregisterChangeObserver(mediaLibraryChangeObserverKey)
}
}
// MARK: - Upload Coordinator Observer
private func registerUploadCoordinatorObserver() {
guard FeatureFlag.asyncUploadsInMediaLibrary.enabled else {
return
}
uploadObserverUUID = MediaUploadCoordinator.shared.addObserver({ (media, state) in
print("Media \(String(describing: media.filename)) in state \(String(describing: state))")
}, for: nil)
}
private func unregisterUploadCoordinatorObserver() {
if let uuid = uploadObserverUUID {
MediaUploadCoordinator.shared.removeObserver(withUUID: uuid)
}
}
// MARK: - Document Picker
private func showDocumentPicker() {
let docTypes = [String(kUTTypeImage), String(kUTTypeMovie)]
let docPicker = UIDocumentPickerViewController(documentTypes: docTypes, in: .import)
docPicker.delegate = self
WPStyleGuide.configureDocumentPickerNavBarAppearance()
present(docPicker, animated: true, completion: nil)
}
// MARK: - Upload Media
fileprivate func uploadMedia(_ media: Media?, error: Error?, mediaID: String) {
let service = MediaService(managedObjectContext: ContextManager.sharedInstance().mainContext)
guard let media = media else {
if let error = error as NSError? {
mediaProgressCoordinator.attach(error: error, toMediaID: mediaID)
}
return
}
var uploadProgress: Progress? = nil
service.uploadMedia(media, progress: &uploadProgress, success: { [weak self] in
self?.unpauseDataSource()
self?.trackUploadFor(media)
}, failure: { error in
self.mediaProgressCoordinator.attach(error: error as NSError, toMediaID: mediaID)
self.unpauseDataSource()
})
if let progress = uploadProgress {
mediaProgressCoordinator.track(progress: progress, ofObject: media, withMediaID: mediaID)
}
}
// MARK: - Upload Media from Camera
private func presentMediaCapture() {
capturePresenter = WPMediaCapturePresenter(presenting: self)
capturePresenter!.completionBlock = { [weak self] mediaInfo in
if let mediaInfo = mediaInfo as NSDictionary? {
self?.processMediaCaptured(mediaInfo)
}
self?.capturePresenter = nil
}
capturePresenter!.presentCapture()
}
private func processMediaCaptured(_ mediaInfo: NSDictionary) {
let completionBlock: WPMediaAddedBlock = { [weak self] media, error in
if error != nil || media == nil {
print("Adding media failed: ", error?.localizedDescription ?? "no media")
return
}
self?.addMediaAssets([media!])
}
guard let mediaType = mediaInfo[UIImagePickerControllerMediaType] as? String else { return }
switch mediaType {
case String(kUTTypeImage):
if let image = mediaInfo[UIImagePickerControllerOriginalImage] as? UIImage,
let metadata = mediaInfo[UIImagePickerControllerMediaMetadata] as? [AnyHashable: Any] {
WPPHAssetDataSource().add(image, metadata: metadata, completionBlock: completionBlock)
}
case String(kUTTypeMovie):
if let mediaURL = mediaInfo[UIImagePickerControllerMediaURL] as? URL {
WPPHAssetDataSource().addVideo(from: mediaURL, completionBlock: completionBlock)
}
default:
break
}
}
private func addMediaAssets(_ assets: NSArray) {
guard assets.count > 0 else { return }
prepareMediaProgressForNumberOfAssets(assets.count)
for asset in assets {
if let asset = asset as? PHAsset {
makeAndUploadMediaWith(asset)
}
}
}
}
// MARK: - UIDocumentPickerDelegate
extension MediaLibraryViewController: UIDocumentPickerDelegate {
func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {
prepareMediaProgressForNumberOfAssets(urls.count)
for documentURL in urls {
makeAndUploadMediaWithURL(documentURL)
}
}
private func makeAndUploadMediaWithURL(_ url: URL) {
let service = MediaService(managedObjectContext: ContextManager.sharedInstance().mainContext)
service.createMedia(url: url,
forBlog: blog.objectID,
thumbnailCallback: nil,
completion: { [weak self] media, error in
self?.uploadMedia(media, error: error, mediaID: url.lastPathComponent)
})
}
func documentPickerWasCancelled(_ controller: UIDocumentPickerViewController) {
dismiss(animated: true, completion: nil)
}
}
// MARK: - WPNoResultsViewDelegate
extension MediaLibraryViewController: WPNoResultsViewDelegate {
func didTap(_ noResultsView: WPNoResultsView!) {
addTapped()
}
}
// MARK: - UISearchBarDelegate
extension MediaLibraryViewController: UISearchBarDelegate {
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
pickerDataSource.searchQuery = searchText
pickerViewController.collectionView?.reloadData()
updateNoResultsView(for: pickerDataSource.numberOfAssets())
}
func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
searchBar.setShowsCancelButton(true, animated: true)
}
func searchBarTextDidEndEditing(_ searchBar: UISearchBar) {
searchBar.setShowsCancelButton(false, animated: true)
}
func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
clearSearch()
searchBar.resignFirstResponder()
}
func clearSearch() {
searchQuery = nil
searchBar.text = nil
pickerDataSource.searchQuery = nil
pickerViewController.collectionView?.reloadData()
updateNoResultsView(for: pickerDataSource.numberOfAssets())
}
}
// MARK: - WPMediaPickerViewControllerDelegate
extension MediaLibraryViewController: WPMediaPickerViewControllerDelegate {
func mediaPickerController(_ picker: WPMediaPickerViewController, didFinishPicking assets: [WPMediaAsset]) {
// We're only interested in the upload picker
guard picker != pickerViewController else { return }
dismiss(animated: true, completion: nil)
guard ReachabilityUtils.isInternetReachable() else {
ReachabilityUtils.showAlertNoInternetConnection()
return
}
guard let assets = assets as? [PHAsset],
assets.count > 0 else { return }
if FeatureFlag.asyncUploadsInMediaLibrary.enabled && useUploadCoordinator {
useUploadCoordinator = false
for asset in assets {
MediaUploadCoordinator.shared.addMedia(from: asset, to: blog)
}
return
}
prepareMediaProgressForNumberOfAssets(assets.count)
for asset in assets {
makeAndUploadMediaWith(asset)
}
}
func mediaPickerControllerDidCancel(_ picker: WPMediaPickerViewController) {
useUploadCoordinator = false
dismiss(animated: true, completion: nil)
}
func mediaPickerController(_ picker: WPMediaPickerViewController, previewViewControllerFor asset: WPMediaAsset) -> UIViewController? {
guard picker == pickerViewController else { return WPAssetViewController(asset: asset) }
WPAppAnalytics.track(.mediaLibraryPreviewedItem, with: blog)
return mediaItemViewController(for: asset)
}
func mediaPickerController(_ picker: WPMediaPickerViewController, shouldSelect asset: WPMediaAsset) -> Bool {
guard picker == pickerViewController else { return true }
guard !isEditing else { return true }
if let viewController = mediaItemViewController(for: asset) {
WPAppAnalytics.track(.mediaLibraryPreviewedItem, with: blog)
navigationController?.pushViewController(viewController, animated: true)
}
return false
}
func mediaPickerController(_ picker: WPMediaPickerViewController, didSelect asset: WPMediaAsset) {
guard picker == pickerViewController else { return }
updateNavigationItemButtonsForCurrentAssetSelection()
}
func mediaPickerController(_ picker: WPMediaPickerViewController, didDeselect asset: WPMediaAsset) {
guard picker == pickerViewController else { return }
updateNavigationItemButtonsForCurrentAssetSelection()
}
func updateNavigationItemButtonsForCurrentAssetSelection() {
if isEditing {
// Check that our selected items haven't been deleted – we're notified
// of changes to the data source before the collection view has
// updated its selected assets.
guard let assets = (pickerViewController.selectedAssets as? [Media]) else { return }
let existingAssets = assets.filter({ !$0.isDeleted })
navigationItem.rightBarButtonItem?.isEnabled = (existingAssets.count > 0)
}
}
private func mediaItemViewController(for asset: WPMediaAsset) -> UIViewController? {
if isEditing { return nil }
guard let asset = asset as? Media else {
return nil
}
selectedAsset = asset
return MediaItemViewController(media: asset)
}
func makeAndUploadMediaWith(_ asset: PHAsset) {
let service = MediaService(managedObjectContext: ContextManager.sharedInstance().mainContext)
service.createMedia(with: asset,
forBlogObjectID: blog.objectID,
thumbnailCallback: nil,
completion: { [weak self] media, error in
self?.uploadMedia(media, error: error, mediaID: asset.identifier())
})
}
fileprivate func trackUploadFor(_ media: Media) {
let properties = WPAppAnalytics.properties(for: media)
switch media.mediaType {
case .image:
WPAppAnalytics.track(.mediaLibraryAddedPhoto,
withProperties: properties,
with: blog)
case .video:
WPAppAnalytics.track(.mediaLibraryAddedVideo,
withProperties: properties,
with: blog)
default: break
}
}
fileprivate func unpauseDataSource() {
// If we've finished all uploads, restart the data source
if !mediaProgressCoordinator.isRunning && pickerDataSource.isPaused {
pickerDataSource.isPaused = false
pickerViewController.collectionView?.reloadData()
updateViewState(for: pickerDataSource.numberOfAssets())
}
}
func mediaPickerControllerWillBeginLoadingData(_ picker: WPMediaPickerViewController) {
guard picker == pickerViewController else { return }
isLoading = true
updateNoResultsView(for: pickerDataSource.numberOfAssets())
}
func mediaPickerControllerDidEndLoadingData(_ picker: WPMediaPickerViewController) {
guard picker == pickerViewController else { return }
isLoading = false
updateViewState(for: pickerDataSource.numberOfAssets())
}
}
// MARK: - State restoration
extension MediaLibraryViewController: UIViewControllerRestoration {
enum EncodingKey {
static let blogURL = "blogURL"
}
static func viewController(withRestorationIdentifierPath identifierComponents: [Any], coder: NSCoder) -> UIViewController? {
guard let identifier = identifierComponents.last as? String,
identifier == MediaLibraryViewController.restorationIdentifier else {
return nil
}
guard let blogURL = coder.decodeObject(forKey: EncodingKey.blogURL) as? URL else {
return nil
}
let context = ContextManager.sharedInstance().mainContext
guard let objectID = context.persistentStoreCoordinator?.managedObjectID(forURIRepresentation: blogURL),
let object = try? context.existingObject(with: objectID),
let blog = object as? Blog else {
return nil
}
return MediaLibraryViewController(blog: blog)
}
override func encodeRestorableState(with coder: NSCoder) {
super.encodeRestorableState(with: coder)
coder.encode(blog.objectID.uriRepresentation(), forKey: EncodingKey.blogURL)
}
}
// MARK: - Media Progress Coordinator Delegate
extension MediaLibraryViewController: MediaProgressCoordinatorDelegate {
func mediaProgressCoordinatorDidStartUploading(_ mediaProgressCoordinator: MediaProgressCoordinator) {}
func mediaProgressCoordinatorDidFinishUpload(_ mediaProgressCoordinator: MediaProgressCoordinator) {
guard !mediaProgressCoordinator.hasFailedMedia else {
SVProgressHUD.showError(withStatus: NSLocalizedString("Upload failed", comment: "Text displayed in a HUD when media items have failed to upload."))
mediaProgressCoordinator.stopTrackingOfAllUploads()
return
}
guard let progress = mediaProgressCoordinator.mediaUploadingProgress,
!progress.isCancelled else {
mediaProgressCoordinator.stopTrackingOfAllUploads()
return
}
mediaProgressCoordinator.stopTrackingOfAllUploads()
SVProgressHUD.showSuccess(withStatus: NSLocalizedString("Uploaded!", comment: "Text displayed in a HUD when media items have been uploaded successfully."))
}
func mediaProgressCoordinator(_ mediaProgressCoordinator: MediaProgressCoordinator, progressDidChange progress: Float) {
guard let mediaProgress = mediaProgressCoordinator.mediaUploadingProgress,
!mediaProgress.isCancelled,
mediaProgress.completedUnitCount < mediaProgress.totalUnitCount else {
return
}
SVProgressHUD.showProgress(progress, status: NSLocalizedString("Uploading...\nTap to cancel", comment: "Text displayed in HUD while media items are being uploaded."))
}
}
fileprivate extension Blog {
var userCanUploadMedia: Bool {
// Self-hosted non-Jetpack blogs have no capabilities, so we'll just assume that users can post media
return capabilities != nil ? isUploadingFilesAllowed() : true
}
}
| gpl-2.0 | 758157b77e9ffcc564e1ddcc5628192f | 37.474399 | 220 | 0.673764 | 5.956965 | false | false | false | false |
trill-lang/LLVMSwift | Sources/LLVM/Global.swift | 1 | 8366 | #if SWIFT_PACKAGE
import cllvm
#endif
/// A `Global` represents a region of memory allocated at compile time instead
/// of at runtime. A global variable must either have an initializer, or make
/// reference to an external definition that has an initializer.
public final class Global: IRGlobal {
internal let llvm: LLVMValueRef
internal init(llvm: LLVMValueRef) {
self.llvm = llvm
}
/// Returns whether this global variable has no initializer because it makes
/// reference to an initialized value in another translation unit.
public var isExternallyInitialized: Bool {
get { return LLVMIsExternallyInitialized(llvm) != 0 }
set { LLVMSetExternallyInitialized(llvm, newValue.llvm) }
}
/// Retrieves the initializer for this global variable, if it exists.
public var initializer: IRValue? {
get { return LLVMGetInitializer(asLLVM()) }
set { LLVMSetInitializer(asLLVM(), newValue!.asLLVM()) }
}
/// Returns whether this global variable is a constant, whether or not the
/// final definition of the global is not.
public var isGlobalConstant: Bool {
get { return LLVMIsGlobalConstant(asLLVM()) != 0 }
set { LLVMSetGlobalConstant(asLLVM(), newValue.llvm) }
}
/// Returns whether this global variable is thread-local. That is, returns
/// if this variable is not shared by multiple threads.
public var isThreadLocal: Bool {
get { return LLVMIsThreadLocal(asLLVM()) != 0 }
set { LLVMSetThreadLocal(asLLVM(), newValue.llvm) }
}
/// Accesses the model of reference for this global variable if it is
/// thread-local.
public var threadLocalModel: ThreadLocalModel {
get { return ThreadLocalModel(llvm: LLVMGetThreadLocalMode(asLLVM())) }
set { LLVMSetThreadLocalMode(asLLVM(), newValue.llvm) }
}
/// Retrieves the previous global in the module, if there is one.
public func previous() -> Global? {
guard let previous = LLVMGetPreviousGlobal(llvm) else { return nil }
return Global(llvm: previous)
}
/// Retrieves the next global in the module, if there is one.
public func next() -> Global? {
guard let next = LLVMGetNextGlobal(llvm) else { return nil }
return Global(llvm: next)
}
/// Deletes the global variable from its containing module.
/// - note: This does not remove references to this global from the
/// module. Ensure you have removed all instructions that reference
/// this global before deleting it.
public func delete() {
LLVMDeleteGlobal(llvm)
}
/// Retrieves the underlying LLVM value object.
public func asLLVM() -> LLVMValueRef {
return llvm
}
}
/// Enumerates the supported models of reference of thread-local variables.
///
/// These models are listed from the most general, but least optimized, to the
/// fastest, but most restrictive in general, as architectural differences
/// play a role in determining the access patterns for thread-local storage.
///
/// In general, support for thread-local storage in statically-linked
/// applications is limited: some platforms may not even define the behavior of
/// TLS in such cases. This is usually not an issue as statically-linked code
/// only ever has one TLS block, the offset of the variables within that block
/// is known, and support for additional dynamic loading of code in
/// statically-linked code is limited.
///
/// Computing the thread-specific address of a TLS variable is usually a dynamic
/// process that relies on an ABI-defined function call (usually
/// `__tls_get_addr`) to do the heavy lifting.
///
/// TLS access models fall into two classes: static and dynamic. Regardless of
/// the actual model used, the dynamic linker must process all relocations
/// for thread-local variables whenever the module is loaded. Some models,
/// therefore, provide for a decrease in the overall number of relocations at
/// a cost of restrictions on which modules can access variables.
public enum ThreadLocalModel {
/// The variable is not thread local and hence has no associated model.
case notThreadLocal
/// Allows reference of all thread-local variables, from either a shared
/// object or a dynamic executable. This model also supports the deferred
/// allocation of a block of thread-local storage when the block is first
/// referenced from a specific thread. Note that the linker is free to
/// optimize accesses using this model to one of the more specific models
/// below which may ultimately defeat lazy allocation of the TLS storagee
/// block.
///
/// The code generated for this model does not assume that any information
/// about the module or variable offsets is known at link-time. Instead, the
/// exact value of these variables is computed by the dynamic linker at
/// runtime and passeed to `__tls_get_addr` in an architecture-specific way.
///
/// If possible, this model should be avoided if one of the more specific
/// models applies out of concern for code size and application startup
/// performance.
case generalDynamic
/// This model is an optimization of the `generalDynamic` model. The compiler
/// might determine that a variable is bound locally, or protected, within the
/// object being built. In this case, the compiler instructs the linker
/// to statically bind the dynamic offset of the variable and use this model.
///
/// This model provides a performance benefit over the General Dynamic model.
/// Only one call to `__tls_get_addr` is required per function, to determine
/// the starting address of the variable within the TLS block for its
/// parent module. Additional accesses can add an offset to this address
/// value for repeated accesses.
///
/// The optimization available over the `generalDynamic` model is defeated if
/// a variable is only ever accessed once, as its access would incur the
/// same `__tls_get_addr` call and the additional overhead of the offset
/// calculation.
///
/// The linker cannot, in general, optimize from the general dynamic model
/// to the local dynamic model.
case localDynamic
/// This model can only reference thread-local variables which are available
/// as part of the initial static thread-local template. This template is
/// composed of all thread-local storage blocks that are available at process
/// startup, plus a small backup reservation.
///
/// In this model, the thread pointer-relative offset for a given variable `x`
/// is stored in the GOT entry for x.
///
/// This model can reference a limited number of thread-local variables from
/// shared libraries loaded after initial process startup, such as by means of
/// lazy loading, filters, or `dlopen()`. This access is satisfied from a
/// fixed backup reservation. This reservation can only provide storage for
/// uninitialized thread-local data items. For maximum flexibility, shared
/// objects should reference thread-local variables using a dynamic model of
/// thread-local storage.
case initialExec
/// This model is an optimization of the `localDynamic` model.
///
/// This model can only reference thread-local variables which are part of the
/// thread-local storage block of the dynamic executable. The linker
/// calculates the thread pointer-relative offsets statically, without the
/// need for dynamic relocations, or the extra reference to the GOT. This
/// model can not be used to reference variables outside of the dynamic
/// executable.
case localExec
internal init(llvm: LLVMThreadLocalMode) {
switch llvm {
case LLVMNotThreadLocal: self = .notThreadLocal
case LLVMGeneralDynamicTLSModel: self = .generalDynamic
case LLVMLocalDynamicTLSModel: self = .localDynamic
case LLVMInitialExecTLSModel: self = .initialExec
case LLVMLocalExecTLSModel: self = .localExec
default: fatalError("unknown thread local mode \(llvm)")
}
}
static let modeMapping: [ThreadLocalModel: LLVMThreadLocalMode] = [
.notThreadLocal: LLVMNotThreadLocal,
.generalDynamic: LLVMGeneralDynamicTLSModel,
.localDynamic: LLVMLocalDynamicTLSModel,
.initialExec: LLVMInitialExecTLSModel,
.localExec: LLVMLocalExecTLSModel,
]
/// Retrieves the corresponding `LLVMThreadLocalMode`.
public var llvm: LLVMThreadLocalMode {
return ThreadLocalModel.modeMapping[self]!
}
}
| mit | 6ab8ddfce2edac2aadfb013a85e73e3d | 44.221622 | 80 | 0.73225 | 4.531961 | false | false | false | false |
lorentey/swift | stdlib/public/core/Runtime.swift | 3 | 19005 | //===----------------------------------------------------------*- swift -*-===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2019 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
///
/// This file contains Swift wrappers for functions defined in the C++ runtime.
///
//===----------------------------------------------------------------------===//
import SwiftShims
//===----------------------------------------------------------------------===//
// Atomics
//===----------------------------------------------------------------------===//
@_transparent
public // @testable
func _stdlib_atomicCompareExchangeStrongPtr(
object target: UnsafeMutablePointer<UnsafeRawPointer?>,
expected: UnsafeMutablePointer<UnsafeRawPointer?>,
desired: UnsafeRawPointer?
) -> Bool {
// We use Builtin.Word here because Builtin.RawPointer can't be nil.
let (oldValue, won) = Builtin.cmpxchg_seqcst_seqcst_Word(
target._rawValue,
UInt(bitPattern: expected.pointee)._builtinWordValue,
UInt(bitPattern: desired)._builtinWordValue)
expected.pointee = UnsafeRawPointer(bitPattern: Int(oldValue))
return Bool(won)
}
/// Atomic compare and exchange of `UnsafeMutablePointer<T>` with sequentially
/// consistent memory ordering. Precise semantics are defined in C++11 or C11.
///
/// - Warning: This operation is extremely tricky to use correctly because of
/// writeback semantics.
///
/// It is best to use it directly on an
/// `UnsafeMutablePointer<UnsafeMutablePointer<T>>` that is known to point
/// directly to the memory where the value is stored.
///
/// In a call like this:
///
/// _stdlib_atomicCompareExchangeStrongPtr(&foo.property1.property2, ...)
///
/// you need to manually make sure that:
///
/// - all properties in the chain are physical (to make sure that no writeback
/// happens; the compare-and-exchange instruction should operate on the
/// shared memory); and
///
/// - the shared memory that you are accessing is located inside a heap
/// allocation (a class instance property, a `_BridgingBuffer`, a pointer to
/// an `Array` element etc.)
///
/// If the conditions above are not met, the code will still compile, but the
/// compare-and-exchange instruction will operate on the writeback buffer, and
/// you will get a *race* while doing writeback into shared memory.
@_transparent
public // @testable
func _stdlib_atomicCompareExchangeStrongPtr<T>(
object target: UnsafeMutablePointer<UnsafeMutablePointer<T>>,
expected: UnsafeMutablePointer<UnsafeMutablePointer<T>>,
desired: UnsafeMutablePointer<T>
) -> Bool {
let rawTarget = UnsafeMutableRawPointer(target).assumingMemoryBound(
to: Optional<UnsafeRawPointer>.self)
let rawExpected = UnsafeMutableRawPointer(expected).assumingMemoryBound(
to: Optional<UnsafeRawPointer>.self)
return _stdlib_atomicCompareExchangeStrongPtr(
object: rawTarget,
expected: rawExpected,
desired: UnsafeRawPointer(desired))
}
/// Atomic compare and exchange of `UnsafeMutablePointer<T>` with sequentially
/// consistent memory ordering. Precise semantics are defined in C++11 or C11.
///
/// - Warning: This operation is extremely tricky to use correctly because of
/// writeback semantics.
///
/// It is best to use it directly on an
/// `UnsafeMutablePointer<UnsafeMutablePointer<T>>` that is known to point
/// directly to the memory where the value is stored.
///
/// In a call like this:
///
/// _stdlib_atomicCompareExchangeStrongPtr(&foo.property1.property2, ...)
///
/// you need to manually make sure that:
///
/// - all properties in the chain are physical (to make sure that no writeback
/// happens; the compare-and-exchange instruction should operate on the
/// shared memory); and
///
/// - the shared memory that you are accessing is located inside a heap
/// allocation (a class instance property, a `_BridgingBuffer`, a pointer to
/// an `Array` element etc.)
///
/// If the conditions above are not met, the code will still compile, but the
/// compare-and-exchange instruction will operate on the writeback buffer, and
/// you will get a *race* while doing writeback into shared memory.
@_transparent
public // @testable
func _stdlib_atomicCompareExchangeStrongPtr<T>(
object target: UnsafeMutablePointer<UnsafeMutablePointer<T>?>,
expected: UnsafeMutablePointer<UnsafeMutablePointer<T>?>,
desired: UnsafeMutablePointer<T>?
) -> Bool {
let rawTarget = UnsafeMutableRawPointer(target).assumingMemoryBound(
to: Optional<UnsafeRawPointer>.self)
let rawExpected = UnsafeMutableRawPointer(expected).assumingMemoryBound(
to: Optional<UnsafeRawPointer>.self)
return _stdlib_atomicCompareExchangeStrongPtr(
object: rawTarget,
expected: rawExpected,
desired: UnsafeRawPointer(desired))
}
@_transparent
@discardableResult
public // @testable
func _stdlib_atomicInitializeARCRef(
object target: UnsafeMutablePointer<AnyObject?>,
desired: AnyObject
) -> Bool {
var expected: UnsafeRawPointer?
let desiredPtr = Unmanaged.passRetained(desired).toOpaque()
let rawTarget = UnsafeMutableRawPointer(target).assumingMemoryBound(
to: Optional<UnsafeRawPointer>.self)
let wonRace = _stdlib_atomicCompareExchangeStrongPtr(
object: rawTarget, expected: &expected, desired: desiredPtr)
if !wonRace {
// Some other thread initialized the value. Balance the retain that we
// performed on 'desired'.
Unmanaged.passUnretained(desired).release()
}
return wonRace
}
@_transparent
public // @testable
func _stdlib_atomicLoadARCRef(
object target: UnsafeMutablePointer<AnyObject?>
) -> AnyObject? {
let value = Builtin.atomicload_seqcst_Word(target._rawValue)
if let unwrapped = UnsafeRawPointer(bitPattern: Int(value)) {
return Unmanaged<AnyObject>.fromOpaque(unwrapped).takeUnretainedValue()
}
return nil
}
//===----------------------------------------------------------------------===//
// Conversion of primitive types to `String`
//===----------------------------------------------------------------------===//
/// A 32 byte buffer.
internal struct _Buffer32 {
internal init() {}
internal var _x0: UInt8 = 0
internal var _x1: UInt8 = 0
internal var _x2: UInt8 = 0
internal var _x3: UInt8 = 0
internal var _x4: UInt8 = 0
internal var _x5: UInt8 = 0
internal var _x6: UInt8 = 0
internal var _x7: UInt8 = 0
internal var _x8: UInt8 = 0
internal var _x9: UInt8 = 0
internal var _x10: UInt8 = 0
internal var _x11: UInt8 = 0
internal var _x12: UInt8 = 0
internal var _x13: UInt8 = 0
internal var _x14: UInt8 = 0
internal var _x15: UInt8 = 0
internal var _x16: UInt8 = 0
internal var _x17: UInt8 = 0
internal var _x18: UInt8 = 0
internal var _x19: UInt8 = 0
internal var _x20: UInt8 = 0
internal var _x21: UInt8 = 0
internal var _x22: UInt8 = 0
internal var _x23: UInt8 = 0
internal var _x24: UInt8 = 0
internal var _x25: UInt8 = 0
internal var _x26: UInt8 = 0
internal var _x27: UInt8 = 0
internal var _x28: UInt8 = 0
internal var _x29: UInt8 = 0
internal var _x30: UInt8 = 0
internal var _x31: UInt8 = 0
internal mutating func withBytes<Result>(
_ body: (UnsafeMutablePointer<UInt8>) throws -> Result
) rethrows -> Result {
return try withUnsafeMutablePointer(to: &self) {
try body(UnsafeMutableRawPointer($0).assumingMemoryBound(to: UInt8.self))
}
}
}
/// A 72 byte buffer.
internal struct _Buffer72 {
internal init() {}
internal var _x0: UInt8 = 0
internal var _x1: UInt8 = 0
internal var _x2: UInt8 = 0
internal var _x3: UInt8 = 0
internal var _x4: UInt8 = 0
internal var _x5: UInt8 = 0
internal var _x6: UInt8 = 0
internal var _x7: UInt8 = 0
internal var _x8: UInt8 = 0
internal var _x9: UInt8 = 0
internal var _x10: UInt8 = 0
internal var _x11: UInt8 = 0
internal var _x12: UInt8 = 0
internal var _x13: UInt8 = 0
internal var _x14: UInt8 = 0
internal var _x15: UInt8 = 0
internal var _x16: UInt8 = 0
internal var _x17: UInt8 = 0
internal var _x18: UInt8 = 0
internal var _x19: UInt8 = 0
internal var _x20: UInt8 = 0
internal var _x21: UInt8 = 0
internal var _x22: UInt8 = 0
internal var _x23: UInt8 = 0
internal var _x24: UInt8 = 0
internal var _x25: UInt8 = 0
internal var _x26: UInt8 = 0
internal var _x27: UInt8 = 0
internal var _x28: UInt8 = 0
internal var _x29: UInt8 = 0
internal var _x30: UInt8 = 0
internal var _x31: UInt8 = 0
internal var _x32: UInt8 = 0
internal var _x33: UInt8 = 0
internal var _x34: UInt8 = 0
internal var _x35: UInt8 = 0
internal var _x36: UInt8 = 0
internal var _x37: UInt8 = 0
internal var _x38: UInt8 = 0
internal var _x39: UInt8 = 0
internal var _x40: UInt8 = 0
internal var _x41: UInt8 = 0
internal var _x42: UInt8 = 0
internal var _x43: UInt8 = 0
internal var _x44: UInt8 = 0
internal var _x45: UInt8 = 0
internal var _x46: UInt8 = 0
internal var _x47: UInt8 = 0
internal var _x48: UInt8 = 0
internal var _x49: UInt8 = 0
internal var _x50: UInt8 = 0
internal var _x51: UInt8 = 0
internal var _x52: UInt8 = 0
internal var _x53: UInt8 = 0
internal var _x54: UInt8 = 0
internal var _x55: UInt8 = 0
internal var _x56: UInt8 = 0
internal var _x57: UInt8 = 0
internal var _x58: UInt8 = 0
internal var _x59: UInt8 = 0
internal var _x60: UInt8 = 0
internal var _x61: UInt8 = 0
internal var _x62: UInt8 = 0
internal var _x63: UInt8 = 0
internal var _x64: UInt8 = 0
internal var _x65: UInt8 = 0
internal var _x66: UInt8 = 0
internal var _x67: UInt8 = 0
internal var _x68: UInt8 = 0
internal var _x69: UInt8 = 0
internal var _x70: UInt8 = 0
internal var _x71: UInt8 = 0
internal mutating func withBytes<Result>(
_ body: (UnsafeMutablePointer<UInt8>) throws -> Result
) rethrows -> Result {
return try withUnsafeMutablePointer(to: &self) {
try body(UnsafeMutableRawPointer($0).assumingMemoryBound(to: UInt8.self))
}
}
}
// Returns a UInt64, but that value is the length of the string, so it's
// guaranteed to fit into an Int. This is part of the ABI, so we can't
// trivially change it to Int. Callers can safely convert the result
// to any integer type without checks, however.
@_silgen_name("swift_float32ToString")
internal func _float32ToStringImpl(
_ buffer: UnsafeMutablePointer<UTF8.CodeUnit>,
_ bufferLength: UInt,
_ value: Float32,
_ debug: Bool
) -> UInt64
internal func _float32ToString(
_ value: Float32,
debug: Bool
) -> (buffer: _Buffer32, length: Int) {
_internalInvariant(MemoryLayout<_Buffer32>.size == 32)
var buffer = _Buffer32()
let length = buffer.withBytes { (bufferPtr) in Int(
truncatingIfNeeded: _float32ToStringImpl(bufferPtr, 32, value, debug)
)}
return (buffer, length)
}
// Returns a UInt64, but that value is the length of the string, so it's
// guaranteed to fit into an Int. This is part of the ABI, so we can't
// trivially change it to Int. Callers can safely convert the result
// to any integer type without checks, however.
@_silgen_name("swift_float64ToString")
internal func _float64ToStringImpl(
_ buffer: UnsafeMutablePointer<UTF8.CodeUnit>,
_ bufferLength: UInt,
_ value: Float64,
_ debug: Bool
) -> UInt64
internal func _float64ToString(
_ value: Float64,
debug: Bool
) -> (buffer: _Buffer32, length: Int) {
_internalInvariant(MemoryLayout<_Buffer32>.size == 32)
var buffer = _Buffer32()
let length = buffer.withBytes { (bufferPtr) in Int(
truncatingIfNeeded: _float64ToStringImpl(bufferPtr, 32, value, debug)
)}
return (buffer, length)
}
#if !(os(Windows) || os(Android)) && (arch(i386) || arch(x86_64))
// Returns a UInt64, but that value is the length of the string, so it's
// guaranteed to fit into an Int. This is part of the ABI, so we can't
// trivially change it to Int. Callers can safely convert the result
// to any integer type without checks, however.
@_silgen_name("swift_float80ToString")
internal func _float80ToStringImpl(
_ buffer: UnsafeMutablePointer<UTF8.CodeUnit>,
_ bufferLength: UInt,
_ value: Float80,
_ debug: Bool
) -> UInt64
internal func _float80ToString(
_ value: Float80,
debug: Bool
) -> (buffer: _Buffer32, length: Int) {
_internalInvariant(MemoryLayout<_Buffer32>.size == 32)
var buffer = _Buffer32()
let length = buffer.withBytes { (bufferPtr) in Int(
truncatingIfNeeded: _float80ToStringImpl(bufferPtr, 32, value, debug)
)}
return (buffer, length)
}
#endif
// Returns a UInt64, but that value is the length of the string, so it's
// guaranteed to fit into an Int. This is part of the ABI, so we can't
// trivially change it to Int. Callers can safely convert the result
// to any integer type without checks, however.
@_silgen_name("swift_int64ToString")
internal func _int64ToStringImpl(
_ buffer: UnsafeMutablePointer<UTF8.CodeUnit>,
_ bufferLength: UInt,
_ value: Int64,
_ radix: Int64,
_ uppercase: Bool
) -> UInt64
internal func _int64ToString(
_ value: Int64,
radix: Int64 = 10,
uppercase: Bool = false
) -> String {
if radix >= 10 {
var buffer = _Buffer32()
return buffer.withBytes { (bufferPtr) in
let actualLength = _int64ToStringImpl(bufferPtr, 32, value, radix, uppercase)
return String._fromASCII(UnsafeBufferPointer(
start: bufferPtr, count: Int(truncatingIfNeeded: actualLength)
))
}
} else {
var buffer = _Buffer72()
return buffer.withBytes { (bufferPtr) in
let actualLength = _int64ToStringImpl(bufferPtr, 72, value, radix, uppercase)
return String._fromASCII(UnsafeBufferPointer(
start: bufferPtr, count: Int(truncatingIfNeeded: actualLength)
))
}
}
}
// Returns a UInt64, but that value is the length of the string, so it's
// guaranteed to fit into an Int. This is part of the ABI, so we can't
// trivially change it to Int. Callers can safely convert the result
// to any integer type without checks, however.
@_silgen_name("swift_uint64ToString")
internal func _uint64ToStringImpl(
_ buffer: UnsafeMutablePointer<UTF8.CodeUnit>,
_ bufferLength: UInt,
_ value: UInt64,
_ radix: Int64,
_ uppercase: Bool
) -> UInt64
public // @testable
func _uint64ToString(
_ value: UInt64,
radix: Int64 = 10,
uppercase: Bool = false
) -> String {
if radix >= 10 {
var buffer = _Buffer32()
return buffer.withBytes { (bufferPtr) in
let actualLength = _uint64ToStringImpl(bufferPtr, 32, value, radix, uppercase)
return String._fromASCII(UnsafeBufferPointer(
start: bufferPtr, count: Int(truncatingIfNeeded: actualLength)
))
}
} else {
var buffer = _Buffer72()
return buffer.withBytes { (bufferPtr) in
let actualLength = _uint64ToStringImpl(bufferPtr, 72, value, radix, uppercase)
return String._fromASCII(UnsafeBufferPointer(
start: bufferPtr, count: Int(truncatingIfNeeded: actualLength)
))
}
}
}
@inlinable
internal func _rawPointerToString(_ value: Builtin.RawPointer) -> String {
var result = _uint64ToString(
UInt64(
UInt(bitPattern: UnsafeRawPointer(value))),
radix: 16,
uppercase: false
)
for _ in 0..<(2 * MemoryLayout<UnsafeRawPointer>.size - result.utf16.count) {
result = "0" + result
}
return "0x" + result
}
#if _runtime(_ObjC)
// At runtime, these classes are derived from `__SwiftNativeNSXXXBase`,
// which are derived from `NSXXX`.
//
// The @swift_native_objc_runtime_base attribute
// allows us to subclass an Objective-C class and still use the fast Swift
// memory allocator.
//
// NOTE: older runtimes called these _SwiftNativeNSXXX. The two must
// coexist, so they were renamed. The old names must not be used in the
// new runtime.
@_fixed_layout
@usableFromInline
@objc @_swift_native_objc_runtime_base(__SwiftNativeNSArrayBase)
internal class __SwiftNativeNSArray {
@inlinable
@nonobjc
internal init() {}
// @objc public init(coder: AnyObject) {}
@inlinable
deinit {}
}
@_fixed_layout
@usableFromInline
@objc @_swift_native_objc_runtime_base(__SwiftNativeNSMutableArrayBase)
internal class _SwiftNativeNSMutableArray {
@inlinable
@nonobjc
internal init() {}
// @objc public init(coder: AnyObject) {}
@inlinable
deinit {}
}
@_fixed_layout
@usableFromInline
@objc @_swift_native_objc_runtime_base(__SwiftNativeNSDictionaryBase)
internal class __SwiftNativeNSDictionary {
@nonobjc
internal init() {}
@objc public init(coder: AnyObject) {}
deinit {}
}
@_fixed_layout
@usableFromInline
@objc @_swift_native_objc_runtime_base(__SwiftNativeNSSetBase)
internal class __SwiftNativeNSSet {
@nonobjc
internal init() {}
@objc public init(coder: AnyObject) {}
deinit {}
}
@objc
@_swift_native_objc_runtime_base(__SwiftNativeNSEnumeratorBase)
internal class __SwiftNativeNSEnumerator {
@nonobjc
internal init() {}
@objc public init(coder: AnyObject) {}
deinit {}
}
//===----------------------------------------------------------------------===//
// Support for reliable testing of the return-autoreleased optimization
//===----------------------------------------------------------------------===//
@objc
internal class __stdlib_ReturnAutoreleasedDummy {
@objc
internal init() {}
// Use 'dynamic' to force Objective-C dispatch, which uses the
// return-autoreleased call sequence.
@objc
internal dynamic func returnsAutoreleased(_ x: AnyObject) -> AnyObject {
return x
}
}
/// This function ensures that the return-autoreleased optimization works.
///
/// On some platforms (for example, x86_64), the first call to
/// `objc_autoreleaseReturnValue` will always autorelease because it would fail
/// to verify the instruction sequence in the caller. On x86_64 certain PLT
/// entries would be still pointing to the resolver function, and sniffing
/// the call sequence would fail.
///
/// This code should live in the core stdlib dylib because PLT tables are
/// separate for each dylib.
///
/// Call this function in a fresh autorelease pool.
public func _stdlib_initializeReturnAutoreleased() {
#if arch(x86_64)
// On x86_64 it is sufficient to perform one cycle of return-autoreleased
// call sequence in order to initialize all required PLT entries.
let dummy = __stdlib_ReturnAutoreleasedDummy()
_ = dummy.returnsAutoreleased(dummy)
#endif
}
#else
@_fixed_layout
@usableFromInline
internal class __SwiftNativeNSArray {
@inlinable
internal init() {}
@inlinable
deinit {}
}
@_fixed_layout
@usableFromInline
internal class __SwiftNativeNSDictionary {
@inlinable
internal init() {}
@inlinable
deinit {}
}
@_fixed_layout
@usableFromInline
internal class __SwiftNativeNSSet {
@inlinable
internal init() {}
@inlinable
deinit {}
}
#endif
| apache-2.0 | 940789d621b66b1e68870df5c648bc14 | 31.211864 | 84 | 0.681452 | 3.951143 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.