repo_name
stringlengths 6
91
| ref
stringlengths 12
59
| path
stringlengths 7
936
| license
stringclasses 15
values | copies
stringlengths 1
3
| content
stringlengths 61
711k
| hash
stringlengths 32
32
| line_mean
float64 4.88
60.8
| line_max
int64 12
421
| alpha_frac
float64 0.1
0.92
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
carping/Postal
|
refs/heads/master
|
Postal/Libetpan+Util.swift
|
mit
|
1
|
//
// The MIT License (MIT)
//
// Copyright (c) 2017 Snips
//
// 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 libetpan
extension String {
static func fromZeroSizedCStringMimeHeader(_ bytes: UnsafeMutablePointer<Int8>?) -> String? {
guard bytes != nil else { return nil }
let length = Int(strlen(bytes))
return fromCStringMimeHeader(bytes, length: length)
}
static func fromCStringMimeHeader(_ bytes: UnsafeMutablePointer<Int8>?, length: Int) -> String? {
let DEFAULT_INCOMING_CHARSET = "iso-8859-1"
let DEFAULT_DISPLAY_CHARSET = "utf-8"
guard let bytes = bytes, bytes[0] != 0 else { return nil }
var hasEncoding = false
if strstr(bytes, "=?") != nil {
if strcasestr(bytes, "?Q?") != nil || strcasestr(bytes, "?B?") != nil {
hasEncoding = true
}
}
if !hasEncoding {
return String.stringFromCStringDetectingEncoding(bytes, length: length)?.string
}
var decoded: UnsafeMutablePointer<CChar>? = nil
var cur_token: size_t = 0
mailmime_encoded_phrase_parse(DEFAULT_INCOMING_CHARSET, bytes, Int(strlen(bytes)), &cur_token, DEFAULT_DISPLAY_CHARSET, &decoded)
defer { free(decoded) }
guard let actuallyDecoded = decoded else { return nil }
return String.fromUTF8CString(actuallyDecoded)
}
}
// MARK: Sequences
extension Sequence {
func unreleasedClist<T>(_ transferOwnership: (Iterator.Element) -> UnsafeMutablePointer<T>) -> UnsafeMutablePointer<clist> {
let list = clist_new()
map(transferOwnership).forEach { (item: UnsafeMutablePointer<T>) in
clist_append(list, item)
}
return list!
}
}
private func pointerListGenerator<Element>(unsafeList list: UnsafePointer<clist>, of: Element.Type) -> AnyIterator<UnsafePointer<Element>> {
var current = list.pointee.first?.pointee
return AnyIterator<UnsafePointer<Element>> {
while current != nil && current?.data == nil { // while data is unavailable skip to next
current = current?.next?.pointee
}
guard let cur = current else { return nil } // if iterator is nil, list is over, just finish
defer { current = current?.next?.pointee } // after returning move current to next
return UnsafePointer<Element>(cur.data.assumingMemoryBound(to: Element.self)) // return current data as Element (unsafe: type cannot be checked because of C)
}
}
private func listGenerator<Element>(unsafeList list: UnsafePointer<clist>, of: Element.Type) -> AnyIterator<Element> {
let gen = pointerListGenerator(unsafeList: list, of: of)
return AnyIterator {
return gen.next()?.pointee
}
}
private func arrayGenerator<Element>(unsafeArray array: UnsafePointer<carray>, of: Element.Type) -> AnyIterator<Element> {
var idx: UInt32 = 0
let len = carray_count(array)
return AnyIterator {
guard idx < len else { return nil }
defer { idx = idx + 1 }
return carray_get(array, idx).assumingMemoryBound(to: Element.self).pointee
}
}
func sequence<Element>(_ unsafeList: UnsafePointer<clist>, of: Element.Type) -> AnySequence<Element> {
return AnySequence { return listGenerator(unsafeList: unsafeList, of: of) }
}
func pointerSequence<Element>(_ unsafeList: UnsafePointer<clist>, of: Element.Type) -> AnySequence<UnsafePointer<Element>> {
return AnySequence { return pointerListGenerator(unsafeList: unsafeList, of: of) }
}
func sequence<Element>(_ unsafeArray: UnsafePointer<carray>, of: Element.Type) -> AnySequence<Element> {
return AnySequence { return arrayGenerator(unsafeArray: unsafeArray, of: of) }
}
// MARK: Dates
extension Date {
var unreleasedMailimapDate: UnsafeMutablePointer<mailimap_date>? {
let calendar = Calendar(identifier: .gregorian)
let components = calendar.dateComponents([ .year, .month, .day ], from: self)
guard let day = components.day, let month = components.month, let year = components.year else { return nil }
return mailimap_date_new(Int32(day), Int32(month), Int32(year))
}
}
extension mailimf_date_time {
var date: Date? {
var dateComponent = DateComponents()
dateComponent.calendar = Calendar(identifier: .gregorian)
dateComponent.second = Int(dt_sec)
dateComponent.minute = Int(dt_min)
dateComponent.hour = Int(dt_min)
dateComponent.hour = Int(dt_hour)
dateComponent.day = Int(dt_day)
dateComponent.month = Int(dt_month)
if dt_year < 1000 {
// workaround when century is not given in year
dateComponent.year = Int(dt_year + 2000)
} else {
dateComponent.year = Int(dt_year)
}
let zoneHour: Int
let zoneMin: Int
if dt_zone >= 0 {
zoneHour = Int(dt_zone / 100)
zoneMin = Int(dt_zone % 100)
} else {
zoneHour = Int(-((-dt_zone) / 100))
zoneMin = Int(-((-dt_zone) % 100))
}
dateComponent.timeZone = TimeZone(secondsFromGMT: zoneHour * 3600 + zoneMin * 60)
return dateComponent.date
}
}
extension mailimap_date_time {
var date: Date? {
var dateComponent = DateComponents()
dateComponent.calendar = Calendar(identifier: .gregorian)
dateComponent.second = Int(dt_sec)
dateComponent.minute = Int(dt_min)
dateComponent.hour = Int(dt_min)
dateComponent.hour = Int(dt_hour)
dateComponent.day = Int(dt_day)
dateComponent.month = Int(dt_month)
if dt_year < 1000 {
// workaround when century is not given in year
dateComponent.year = Int(dt_year + 2000)
} else {
dateComponent.year = Int(dt_year)
}
let zoneHour: Int
let zoneMin: Int
if dt_zone >= 0 {
zoneHour = Int(dt_zone / 100)
zoneMin = Int(dt_zone % 100)
} else {
zoneHour = Int(-((-dt_zone) / 100))
zoneMin = Int(-((-dt_zone) % 100))
}
dateComponent.timeZone = TimeZone(secondsFromGMT: zoneHour * 3600 + zoneMin * 60)
return dateComponent.date
}
}
// MARK: Set
extension mailimap_set {
var indexSet: IndexSet {
var result: IndexSet = IndexSet()
sequence(set_list, of: mailimap_set_item.self)
.map { (item: mailimap_set_item) -> CountableClosedRange<Int> in
return Int(item.set_first)...Int(item.set_last)
}
.forEach { (range: CountableClosedRange<Int>) in
result.insert(integersIn: range)
}
return result
}
var array: [Int] {
var result: [Int] = []
sequence(set_list, of: mailimap_set_item.self)
.map { (item: mailimap_set_item) -> CountableClosedRange<Int> in
return Int(item.set_first)...Int(item.set_last)
}
.forEach { (range: CountableClosedRange<Int>) in
result.append(contentsOf: range)
}
return result
}
}
|
8f7e21138a5e58566edf82dfc369be50
| 36.334821 | 165 | 0.627646 | false | false | false | false |
nunosans/currency
|
refs/heads/master
|
Currency/UI Classes/CalculatorButton.swift
|
mit
|
1
|
//
// CalculatorButton.swift
// Currency
//
// Created by Nuno Coelho Santos on 25/02/2016.
// Copyright © 2016 Nuno Coelho Santos. All rights reserved.
//
import Foundation
import UIKit
class CalculatorButton: UIButton {
let borderColor: CGColor! = UIColor(red:0.85, green:0.85, blue:0.85, alpha:1.00).cgColor
let normalStateColor: CGColor! = UIColor(red:0, green:0, blue:0, alpha:0).cgColor
let highlightStateColor: CGColor! = UIColor(red:0, green:0, blue:0, alpha:0.08).cgColor
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)!
self.layer.borderWidth = 0.25
self.layer.borderColor = borderColor
self.layer.masksToBounds = true
self.backgroundColor = UIColor(cgColor: normalStateColor)
}
override var isHighlighted: Bool {
get {
return super.isHighlighted
}
set {
if newValue {
let fadeIn = CABasicAnimation(keyPath: "backgroundColor")
fadeIn.fromValue = normalStateColor
fadeIn.toValue = highlightStateColor
fadeIn.duration = 0.12
fadeIn.autoreverses = false
fadeIn.repeatCount = 1
self.layer.add(fadeIn, forKey: "fadeIn")
self.backgroundColor = UIColor(cgColor: highlightStateColor)
}
else {
let fadeOut = CABasicAnimation(keyPath: "backgroundColor")
fadeOut.fromValue = highlightStateColor
fadeOut.toValue = normalStateColor
fadeOut.duration = 0.12
fadeOut.autoreverses = false
fadeOut.repeatCount = 1
self.layer.add(fadeOut, forKey: "fadeOut")
self.backgroundColor = UIColor(cgColor: normalStateColor)
}
super.isHighlighted = newValue
}
}
}
|
9f6c9e13d1b8f2d21459a10b9e80a990
| 32.305085 | 92 | 0.581679 | false | false | false | false |
JasonPan/ADSSocialFeedScrollView
|
refs/heads/master
|
ADSSocialFeedScrollView/Providers/Facebook/Data/FacebookPage.swift
|
mit
|
1
|
//
// FacebookPage.swift
// ADSSocialFeedScrollView
//
// Created by Jason Pan on 13/02/2016.
// Copyright © 2016 ANT Development Studios. All rights reserved.
//
import UIKit
import FBSDKCoreKit
class FacebookPage: PostCollectionProtocol {
private(set) var id : String!
private(set) var name : String!
private(set) var profilePhotoURL : String!
private(set) var coverPhotoURL : String!
var feed : Array<FacebookPost>!
//*********************************************************************************************************
// MARK: - Constructors
//*********************************************************************************************************
init(id: String) {
self.id = id
}
//*********************************************************************************************************
// MARK: - Data retrievers
//*********************************************************************************************************
func fetchProfileInfoInBackgroundWithCompletionHandler(block: (() -> Void)?) {
//SIDENOTE: Facebook iOS SDK requires requests to be sent from main queue?? Bug?
dispatch_async(dispatch_get_main_queue(), {
FBSDKGraphRequest.init(graphPath: self.id, parameters: ["access_token": ADSSocialFeedFacebookAccountProvider.authKey, "fields": "name, picture, cover"]).startWithCompletionHandler({
connection, result, error in
if error == nil {
if let dictionary = result as? Dictionary<String, AnyObject> {
let name = dictionary["name"] as? String
let picture = dictionary["picture"]?["data"]??["url"] as? String
let cover = dictionary["cover"]?["source"] as? String
self.name = name
self.profilePhotoURL = picture
self.coverPhotoURL = cover
}
}else {
NSLog("[ADSSocialFeedScrollView][Facebook] An error occurred while fetching profile info: \(error?.description)");
}
self.fetchPostsInBackgroundWithCompletionHandler(block)
})
})
}
private func fetchPostsInBackgroundWithCompletionHandler(block: (() -> Void)?) {
//SIDENOTE: Facebook iOS SDK requires requests to be sent from main queue?? Bug?
dispatch_async(dispatch_get_main_queue(), {
FBSDKGraphRequest.init(graphPath: self.id + "/posts", parameters: ["access_token": ADSSocialFeedFacebookAccountProvider.authKey, "fields": "created_time, id, message, picture, attachments"]).startWithCompletionHandler({
connection, result, error in
if error == nil {
let JSON_data: Dictionary<String, AnyObject>? = result as? Dictionary<String, AnyObject>
guard JSON_data != nil else {
return
}
if let feedData_JSON: Array<Dictionary<String, AnyObject>> = JSON_data?["data"] as? Array<Dictionary<String, AnyObject>> {
var feedArray: Array<FacebookPost> = Array<FacebookPost>()
for dictionary in feedData_JSON {
let id = dictionary["id"] as? String
let created_time = dictionary["created_time"] as? String
let message = dictionary["message"] as? String
var picture = dictionary["picture"] as? String
if let attachments = dictionary["attachments"] as? NSDictionary {
if let data = attachments["data"] as? NSArray {
if let media = data[0]["media"] as? NSDictionary {
if let image = media["image"] {
if let src = image["src"] as? String {
picture = src
}
}
}
}
}
let facebookPost: FacebookPost = FacebookPost(id: id!, createdTime: created_time!, message: message, image: picture, owner: self)
feedArray.append(facebookPost)
}
self.feed = feedArray
}
}else {
NSLog("[ADSSocialFeedScrollView][Facebook] An error occurred while fetching posts: \(error?.description)");
self.feed = Array<FacebookPost>()
}
block?()
})
})
}
//*********************************************************************************************************
// MARK: - PostCollectionProtocol
//*********************************************************************************************************
var postItems: [PostProtocol]? {
// See: https://stackoverflow.com/a/30101004/699963
return self.feed.map({ $0 as PostProtocol })
}
}
|
f2ea63c47b13a7e1d3603cb7b79ef02a
| 46.35 | 231 | 0.421331 | false | false | false | false |
agconti/good-as-old-phones
|
refs/heads/master
|
GoodAsOldPhones/ProductsTableViewController.swift
|
mit
|
1
|
//
// ProductsTableViewController.swift
// GoodAsOldPhones
//
// Created by Andrew Conti on 1/14/16.
// Copyright © 2016 agconit. All rights reserved.
//
import UIKit
class ProductsTableViewController: UITableViewController {
let productCellIdentifier: String = "ProductCell"
let numVisibleCells: Int = 5
var products: [Product]?
override func viewDidLoad() {
super.viewDidLoad()
products = [ Product(name: "1927 Hand Dial Phone", productImage: "phone-fullscreen1", cellImage: "image-cell1")
, Product(name: "1950 Office Phone", productImage: "phone-fullscreen2", cellImage: "image-cell2")
, Product(name: "1980 Car Phone", productImage: "phone-fullscreen3", cellImage: "image-cell3")
, Product(name: "1940 Military Phone", productImage: "phone-fullscreen4", cellImage: "image-cell4")
]
}
override func tableView(tabelView: UITableView, numberOfRowsInSection section: Int) -> Int {
if let products = products {
return products.count
}
return 0
}
override func tableView(tabelView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(productCellIdentifier, forIndexPath: indexPath)
let product = products?[indexPath.row]
cell.textLabel?.text = product?.name
if let cellImage = product?.cellImage{
cell.imageView?.image = UIImage(named: cellImage)
}
return cell
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "ShowProduct" {
guard let vc = segue.destinationViewController as? ProductViewController,
let cell = sender as? UITableViewCell,
let indexPath = tableView.indexPathForCell(cell) else {
return
}
vc.product = products?[indexPath.row]
}
}
}
|
9e474e67a48b853caaf79fbb1199422f
| 32.65625 | 120 | 0.607242 | false | false | false | false |
ElectricWizardry/iSub
|
refs/heads/master
|
Classes/StoreViewController.swift
|
gpl-3.0
|
2
|
//
// StoreViewController.swift
// iSub
//
// Created by Ben Baron on 12/15/10.
// Copyright 2010 Ben Baron. All rights reserved.
//
import Foundation
import UIKit
public class StoreViewController : CustomUITableViewController {
private lazy var _appDelegate = iSubAppDelegate.sharedInstance()
private let _settings = SavedSettings.sharedInstance()
private let _viewObjects = ViewObjectsSingleton.sharedInstance()
private let _reuseIdentifier = "Store Cell"
private let _storeManager: MKStoreManager = MKStoreManager.sharedManager()
private var _storeItems: [AnyObject] = MKStoreManager.sharedManager().purchasableObjects
private var _checkProductsTimer: NSTimer?
// MARK: - Rotation -
public override func shouldAutorotate() -> Bool {
if _settings.isRotationLockEnabled && UIDevice.currentDevice().orientation != UIDeviceOrientation.Portrait {
return false
}
return true
}
public override func didRotateFromInterfaceOrientation(fromInterfaceOrientation: UIInterfaceOrientation) {
self.tableView.reloadData()
}
// MARK: - LifeCycle -
public override func viewDidLoad() {
super.viewDidLoad()
NSNotificationCenter.defaultCenter().addObserver(self, selector: "_storePurchaseComplete:", name: ISMSNotification_StorePurchaseComplete, object: nil)
if _storeItems.count == 0 {
_viewObjects.showAlbumLoadingScreen(_appDelegate.window, sender: self)
self._checkProductsTimer = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: "a_checkProducts", userInfo: nil, repeats: true)
self.a_checkProducts(nil)
} else {
self._organizeList()
self.tableView.reloadData()
}
}
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self, name: ISMSNotification_StorePurchaseComplete, object: nil)
}
// MARK: - Notifications -
func _storePurchaseComplete(notification: NSNotification?) {
self.tableView.reloadData()
}
// MARK: - Actions -
func a_checkProducts(sender: AnyObject?) {
_storeItems = _storeManager.purchasableObjects
if _storeItems.count > 0 {
_checkProductsTimer?.invalidate()
_checkProductsTimer = nil
_viewObjects.hideLoadingScreen()
self._organizeList()
self.tableView.reloadData()
}
}
// MARK: - Loading -
public func cancelLoad() {
_checkProductsTimer?.invalidate()
_checkProductsTimer = nil
_viewObjects.hideLoadingScreen()
}
func _organizeList() {
// Place purchased products at the the end of the list
var sorted: [SKProduct] = []
var purchased: [SKProduct] = []
for item in _storeItems {
if let product = item as? SKProduct {
var array = MKStoreManager.isFeaturePurchased(product.productIdentifier) ? purchased : sorted
array.append(product)
}
}
sorted.extend(purchased)
_storeItems = sorted
}
}
// MARK: - Table view data source
extension StoreViewController : UITableViewDelegate, UITableViewDataSource {
public override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return indexPath.row == 0 ? 75.0 : 150.0
}
public override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
public override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return _storeItems.count + 1
}
public override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
if indexPath.row == 0 {
let cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "NoReuse")
cell.textLabel?.text = "Restore previous purchases"
return cell
} else {
let adjustedRow = indexPath.row - 1
let cell = StoreUITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "NoReuse")
cell.product = _storeItems[adjustedRow] as? SKProduct
return cell
}
}
public override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
if indexPath.row == 0 {
_storeManager.restorePreviousTransactions()
} else {
let adjustedRow = indexPath.row - 1
let product: SKProduct = _storeItems[adjustedRow] as SKProduct
let identifier: String = product.productIdentifier
if !MKStoreManager.isFeaturePurchased(identifier) {
_storeManager.buyFeature(identifier)
self.navigationController?.popToRootViewControllerAnimated(true)
}
}
self.tableView.deselectRowAtIndexPath(indexPath, animated: true)
}
}
|
1a7b24cf33f44c3fe10b6c85a3a63bb4
| 32.242038 | 158 | 0.636451 | false | false | false | false |
harenbrs/swix
|
refs/heads/master
|
swixUseCases/swix-iOS/swix/matrix/image.swift
|
mit
|
4
|
//
// twoD-image.swift
// swix
//
// Created by Scott Sievert on 7/30/14.
// Copyright (c) 2014 com.scott. All rights reserved.
//
/*
* some other useful tips that need an iOS app to use:
* 1. UIImage to raw array[0]:
* 2. raw array to UIImage[1]:
*
* for a working implementation, see[2] (to be published shortly)
*
* [0]:http://stackoverflow.com/a/1262893/1141256
* [1]:http://stackoverflow.com/a/12868860/1141256
* [2]:https://github.com/scottsievert/saliency/blob/master/AVCam/AVCam/saliency/imageToRawArray.m
*
*
*/
import Foundation
func rgb2hsv_pixel(R:Double, G:Double, B:Double)->(Double, Double, Double){
// tested against wikipedia/HSL_and_HSV. returns (H, S_hsv, V)
var M = max(array(R, G, B))
var m = min(array(R, G, B))
var C = M - m
var Hp:Double = 0
if M==R {Hp = ((G-B)/C) % 6}
else if M==G {Hp = ((B-R)/C) + 2}
else if M==B {Hp = ((R-G)/C) + 4}
var H = 60 * Hp
var V = M
var S = 0.0
if !(V==0) {S = C/V}
return (H, S, V)
}
func rgb2hsv(r:matrix, g:matrix, b:matrix)->(matrix, matrix, matrix){
assert(r.shape.0 == g.shape.0)
assert(b.shape.0 == g.shape.0)
assert(r.shape.1 == g.shape.1)
assert(b.shape.1 == g.shape.1)
var h = zeros_like(r)
var s = zeros_like(g)
var v = zeros_like(b)
for i in 0..<r.shape.0{
for j in 0..<r.shape.1{
var (h_p, s_p, v_p) = rgb2hsv_pixel(r[i,j], g[i,j], b[i,j])
h[i,j] = h_p
s[i,j] = s_p
v[i,j] = v_p
}
}
return (h, s, v)
}
func rgb2_hsv_vplane(r:matrix, g:matrix, b:matrix)->matrix{
return max(max(r, g), b)
}
func savefig(x:matrix, filename:String, save:Bool=true, show:Bool=false){
// assumes Python is on your $PATH and pylab/etc are installed
// prefix should point to the swix folder!
// prefix is defined in numbers.swift
// assumes python is on your path
write_csv(x, filename:"swix/temp.csv")
system("cd "+S2_PREFIX+"; "+PYTHON_PATH + " imshow.py \(filename) \(save) \(show)")
system("rm "+S2_PREFIX+"temp.csv")
}
func imshow(x: matrix){
savefig(x, "junk", save:false, show:true)
}
//func UIImageToRGBA(image:UIImage)->(matrix, matrix, matrix, matrix){
// // returns red, green, blue and alpha channels
//
// // init'ing
// var imageRef = image.CGImage
// var width = CGImageGetWidth(imageRef)
// var height = CGImageGetHeight(imageRef)
// var colorSpace = CGColorSpaceCreateDeviceRGB()
// var bytesPerPixel = 4
// var bytesPerRow:UInt = UInt(bytesPerPixel) * UInt(width)
// var bitsPerComponent:UInt = 8
// var pix = Int(width) * Int(height)
// var count:Int = 4*Int(pix)
//
// // pulling the color out of the image
// var rawData:[CUnsignedChar] = Array(count:count, repeatedValue:0)
// var bitmapInfo = CGBitmapInfo.fromRaw(CGImageAlphaInfo.PremultipliedLast.toRaw())!
// var context = CGBitmapContextCreate(&rawData, UInt(width), UInt(height), bitsPerComponent, bytesPerRow, colorSpace, bitmapInfo)
// CGContextDrawImage(context, CGRectMake(0,0,CGFloat(width), CGFloat(height)), imageRef)
//
//
// // unsigned char to double conversion
// var rawDataArray = zeros(count)-1
// vDSP_vfltu8D(&rawData, 1, &rawDataArray.grid, 1, count.length)
//
// // pulling the RGBA channels out of the color
// var i = arange(pix)
// var r = zeros((Int(height), Int(width)))-1;
// r.flat = rawDataArray[4*i+0]
//
// var g = zeros((Int(height), Int(width)));
// g.flat = rawDataArray[4*i+1]
//
// var b = zeros((Int(height), Int(width)));
// b.flat = rawDataArray[4*i+2]
//
// var a = zeros((Int(height), Int(width)));
// a.flat = rawDataArray[4*i+3]
// return (r, g, b, a)
//}
//func RGBAToUIImage(r:matrix, g:matrix, b:matrix, a:matrix)->UIImage{
// // setup
// var height = r.shape.0
// var width = r.shape.1
// var area = height * width
// var componentsPerPixel = 4 // rgba
// var compressedPixelData = zeros(4*area)
// var N = width * height
//
// // double to unsigned int
// var i = arange(N)
// compressedPixelData[4*i+0] = r.flat
// compressedPixelData[4*i+1] = g.flat
// compressedPixelData[4*i+2] = b.flat
// compressedPixelData[4*i+3] = a.flat
// var pixelData:[CUnsignedChar] = Array(count:area*componentsPerPixel, repeatedValue:0)
// vDSP_vfixu8D(&compressedPixelData.grid, 1, &pixelData, 1, vDSP_Length(componentsPerPixel*area))
//
// // creating the bitmap context
// var colorSpace = CGColorSpaceCreateDeviceRGB()
// var bitsPerComponent = 8
// var bytesPerRow = ((bitsPerComponent * width) / 8) * componentsPerPixel
// var bitmapInfo = CGBitmapInfo.fromRaw(CGImageAlphaInfo.PremultipliedLast.toRaw())!
// var context = CGBitmapContextCreate(&pixelData, UInt(width), UInt(height), UInt(bitsPerComponent), UInt(bytesPerRow), colorSpace, bitmapInfo)
//
// // creating the image
// var toCGImage = CGBitmapContextCreateImage(context)
// var image:UIImage = UIImage.init(CGImage:toCGImage)
// return image
//}
//func resizeImage(image:UIImage, shape:(Int, Int)) -> UIImage{
// // nice variables
// var (height, width) = shape
// var cgSize = CGSizeMake(width, height)
//
// // draw on new CGSize
// UIGraphicsBeginImageContextWithOptions(cgSize, false, 0.0)
// image.drawInRect(CGRectMake(0, 0, width, height))
// var newImage = UIGraphicsGetImageFromCurrentImageContext()
// UIGraphicsEndImageContext()
// return newImage
//}
|
1b86895b6b6af50a414e45e2f2c1f271
| 33.8125 | 147 | 0.623339 | false | false | false | false |
Arcovv/CleanArchitectureRxSwift
|
refs/heads/master
|
Network/Network/NetworkProvider.swift
|
mit
|
2
|
//
// NetworkProvider.swift
// CleanArchitectureRxSwift
//
// Created by Andrey Yastrebov on 16.03.17.
// Copyright © 2017 sergdort. All rights reserved.
//
import Domain
final class NetworkProvider {
private let apiEndpoint: String
public init() {
apiEndpoint = "https://jsonplaceholder.typicode.com"
}
public func makeAlbumsNetwork() -> AlbumsNetwork {
let network = Network<Album>(apiEndpoint)
return AlbumsNetwork(network: network)
}
public func makeCommentsNetwork() -> CommentsNetwork {
let network = Network<Comment>(apiEndpoint)
return CommentsNetwork(network: network)
}
public func makePhotosNetwork() -> PhotosNetwork {
let network = Network<Photo>(apiEndpoint)
return PhotosNetwork(network: network)
}
public func makePostsNetwork() -> PostsNetwork {
let network = Network<Post>(apiEndpoint)
return PostsNetwork(network: network)
}
public func makeTodosNetwork() -> TodosNetwork {
let network = Network<Todo>(apiEndpoint)
return TodosNetwork(network: network)
}
public func makeUsersNetwork() -> UsersNetwork {
let network = Network<User>(apiEndpoint)
return UsersNetwork(network: network)
}
}
|
76a546befcf5f9bd84050728697cce16
| 26.297872 | 60 | 0.671863 | false | false | false | false |
WeMadeCode/ZXPageView
|
refs/heads/master
|
Example/ZXPageView/ZXHorizontalViewController.swift
|
mit
|
1
|
//
// ZXWaterViewController.swift
// ZXPageView_Example
//
// Created by Anthony on 2019/3/15.
// Copyright © 2019 CocoaPods. All rights reserved.
//
import UIKit
import ZXPageView
import SwifterSwift
private let kCollectionViewCellID = "kCollectionViewCellID"
class ZXHorizontalViewController: ViewController {
override func viewDidLoad() {
super.viewDidLoad()
automaticallyAdjustsScrollViewInsets = false
self.view.backgroundColor = UIColor.white
// 1.创建需要的样式
let style = ZXPageStyle()
style.isLongStyle = false
// 2.获取所有的标题
let titles = ["推荐", "游戏游戏游戏游戏", "热门"] //, "趣玩"
// 3.创建布局
let layout = ZXHorizontalViewLayout()
layout.sectionInset = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
layout.lineSpacing = 10
layout.itemSpacing = 10
layout.cols = 4
layout.rows = 2
// 4.创建Water
let pageFrame = CGRect(x: 0, y: self.safeY, width: self.view.bounds.width, height: 300)
let pageView = ZXHorizontalView(frame: pageFrame, style: style, titles: titles, layout : layout)
pageView.dataSource = self
pageView.delegate = self
pageView.registerCell(UICollectionViewCell.self, identifier: kCollectionViewCellID)
pageView.backgroundColor = UIColor.orange
view.addSubview(pageView)
}
deinit {
print("deinit")
}
}
extension ZXHorizontalViewController : ZXHorizontalViewDataSource {
func numberOfSectionsInWaterView(_ waterView: ZXHorizontalView) -> Int {
return 3
}
func waterView(_ waterView: ZXHorizontalView, numberOfItemsInSection section: Int) -> Int {
if section == 0 {
return 12
} else if section == 1 {
return 30
} else if section == 2 {
return 7
}else{
return 13
}
}
func waterView(_ waterView: ZXHorizontalView, cellForItemAtIndexPath indexPath: IndexPath) -> UICollectionViewCell {
let cell = waterView.dequeueReusableCell(withReuseIdentifier: kCollectionViewCellID, for: indexPath)
cell.backgroundColor = UIColor.random
return cell
}
}
extension ZXHorizontalViewController : ZXHorizontalViewDelegate {
func waterView(_ waterView: ZXHorizontalView, didSelectedAtIndexPath indexPath: IndexPath) {
print(indexPath)
}
}
|
79265dd67e5cd112c6d9c8fd894a98a1
| 23.401961 | 120 | 0.6364 | false | false | false | false |
LuckyChen73/CW_WEIBO_SWIFT
|
refs/heads/master
|
WeiBo/WeiBo/Classes/Tools(工具类)/UIButton+convenience.swift
|
mit
|
1
|
//
// UIButton+extension.swift
// WeiBo
//
// Created by chenWei on 2017/4/2.
// Copyright © 2017年 陈伟. All rights reserved.
//
import UIKit
extension UIButton {
convenience init(title: String?,
titleColor: UIColor? = UIColor.gray,
fontSize: CGFloat? = 15,
target: AnyObject? = nil,
selector: Selector? = nil,
events: UIControlEvents? = .touchUpInside,
image: String? = nil,
bgImage: String? = nil) {
self.init()
self.setTitle(title, for: .normal)
self.setTitleColor(titleColor, for: .normal)
if let fontSize = fontSize {
self.titleLabel?.font = UIFont.systemFont(ofSize: fontSize)
}
if let target = target, let selector = selector {
self.addTarget(target, action: selector, for: events!)
}
if let image = image {
self.setImage(UIImage(named: "\(image)"), for: .normal)
self.setImage(UIImage(named: "\(image)_highlighted"), for: .highlighted)
}
if let bgImage = bgImage {
self.setBackgroundImage(UIImage(named: "\(bgImage)"), for: .normal)
self.setBackgroundImage(UIImage(named: "\(bgImage)_highlighted"), for: .highlighted)
}
}
}
|
74f3a5e128248efb03c82d56abb7d057
| 27.78 | 96 | 0.516331 | false | false | false | false |
xzhflying/IOS_Calculator
|
refs/heads/master
|
Calculator/ViewController.swift
|
mit
|
1
|
//
// ViewController.swift
// Calculator
//
// Created by xzhflying on 15/11/5.
// Copyright © 2015年 xzhflying. All rights reserved.
//
import UIKit
class ViewController: UIViewController
{
@IBOutlet weak var display: UILabel!
var userIsInputing: Bool = false
var theCore = CalculatorCore()
@IBAction func appendDigit(sender: UIButton) {
let digit = firstButtonValue(sender.currentTitle!)
appendToLabel(digit)
}
@IBAction func addButtonOptionalValue(sender :UILongPressGestureRecognizer) {
if(sender.state == .Ended)
{
appendToLabel("(")
}
}
@IBAction func minusButtonOptionalValue(sender :UILongPressGestureRecognizer) {
if(sender.state == .Ended)
{
appendToLabel(")")
}
}
@IBAction func clearInput(sender: UIButton) {
display.text = "0"
userIsInputing = false
theCore.digitStack.removeAll()
theCore.operatorStack.removeAll()
}
@IBAction func deleteLastInput(sender: UIButton) {
if (userIsInputing && display.text!.characters.count > 1)
{
display.text!.removeAtIndex(display.text!.endIndex.predecessor())
}
else if (userIsInputing)
{
display.text! = "0"
userIsInputing = false
}
}
@IBAction func theResult(sender: AnyObject) {
let result = theCore.calculate()
if result != nil
{
display.text = String(result!)
}
}
func appendToLabel(str :String){
if( userIsInputing )
{
display.text = display.text! + str
}
else
{
display.text = str
userIsInputing = true
}
}
func firstButtonValue(str :String) -> String{
if (str.containsString("/"))
{
let index = str.startIndex.advancedBy(1)
return str.substringToIndex(index)
}
else
{
return str
}
}
// Unused for now
func secondButtonValue(str :String) -> String?{
if (str.containsString("/"))
{
let startIndex = str.startIndex.advancedBy(1)
let endIndex = str.startIndex.advancedBy(2)
let range = Range(start: startIndex, end: endIndex)
return str.substringWithRange(range)
}
else
{
return nil
}
}
}
|
5bffd521ae1eb12be9d68f12fd655cd4
| 23.153846 | 83 | 0.548169 | false | false | false | false |
wireapp/wire-ios-sync-engine
|
refs/heads/develop
|
Tests/Source/Data Model/ServiceUserTests.swift
|
gpl-3.0
|
1
|
//
// Wire
// Copyright (C) 2021 Wire Swiss GmbH
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
import XCTest
@testable import WireSyncEngine
final class DummyServiceUser: NSObject, ServiceUser {
func cancelConnectionRequest(completion: @escaping (Error?) -> Void) {
}
func connect(completion: @escaping (Error?) -> Void) {
}
func block(completion: @escaping (Error?) -> Void) {
}
func accept(completion: @escaping (Error?) -> Void) {
}
func ignore(completion: @escaping (Error?) -> Void) {
}
var remoteIdentifier: UUID?
var isIgnored: Bool = false
var hasTeam: Bool = false
var isTrusted: Bool = false
var hasLegalHoldRequest: Bool = false
var needsRichProfileUpdate: Bool = false
var availability: AvailabilityKind = .none
var teamName: String?
var isBlocked: Bool = false
var blockState: ZMBlockState = .none
var isExpired: Bool = false
var isPendingApprovalBySelfUser: Bool = false
var isPendingApprovalByOtherUser: Bool = false
var isWirelessUser: Bool = false
var isUnderLegalHold: Bool = false
var allClients: [UserClientType] = []
var expiresAfter: TimeInterval = 0
var readReceiptsEnabled: Bool = true
var isVerified: Bool = false
var richProfile: [UserRichProfileField] = []
/// Whether the user can create conversations.
@objc
func canCreateConversation(type: ZMConversationType) -> Bool {
return true
}
var canCreateService: Bool = false
var canManageTeam: Bool = false
func canAccessCompanyInformation(of user: UserType) -> Bool {
return false
}
func canAddUser(to conversation: ConversationLike) -> Bool {
return false
}
func canRemoveUser(from conversation: ZMConversation) -> Bool {
return false
}
func canAddService(to conversation: ZMConversation) -> Bool {
return false
}
func canDeleteConversation(_ conversation: ZMConversation) -> Bool {
return false
}
func canRemoveService(from conversation: ZMConversation) -> Bool {
return false
}
func canModifyReadReceiptSettings(in conversation: ConversationLike) -> Bool {
return false
}
func canModifyEphemeralSettings(in conversation: ConversationLike) -> Bool {
return false
}
func canModifyNotificationSettings(in conversation: ConversationLike) -> Bool {
return false
}
func canModifyAccessControlSettings(in conversation: ConversationLike) -> Bool {
return false
}
func canModifyTitle(in conversation: ConversationLike) -> Bool {
return false
}
func canModifyOtherMember(in conversation: ZMConversation) -> Bool {
return false
}
func canLeave(_ conversation: ZMConversation) -> Bool {
return false
}
func isGroupAdmin(in conversation: ConversationLike) -> Bool {
return false
}
var domain: String?
var previewImageData: Data?
var completeImageData: Data?
var name: String? = "Service user"
var displayName: String = "Service"
var initials: String? = "S"
var handle: String? = "service"
var emailAddress: String? = "dummy@email.com"
var phoneNumber: String?
var isSelfUser: Bool = false
var smallProfileImageCacheKey: String? = ""
var mediumProfileImageCacheKey: String? = ""
var isConnected: Bool = false
var oneToOneConversation: ZMConversation?
var accentColorValue: ZMAccentColor = ZMAccentColor.brightOrange
var imageMediumData: Data! = Data()
var imageSmallProfileData: Data! = Data()
var imageSmallProfileIdentifier: String! = ""
var imageMediumIdentifier: String! = ""
var isTeamMember: Bool = false
var hasDigitalSignatureEnabled: Bool = false
var teamRole: TeamRole = .member
var canBeConnected: Bool = false
var isServiceUser: Bool = true
var isFederated: Bool = false
var usesCompanyLogin: Bool = false
var isAccountDeleted: Bool = false
var managedByWire: Bool = true
var extendedMetadata: [[String: String]]?
var activeConversations: Set<ZMConversation> = Set()
func requestPreviewProfileImage() {
}
func requestCompleteProfileImage() {
}
func imageData(for size: ProfileImageSize, queue: DispatchQueue, completion: @escaping (Data?) -> Void) {
}
func refreshData() {
}
func refreshRichProfile() {
}
func refreshMembership() {
}
func refreshTeamData() {
}
func isGuest(in conversation: ConversationLike) -> Bool {
return false
}
var connectionRequestMessage: String? = ""
var totalCommonConnections: UInt = 0
var serviceIdentifier: String?
var providerIdentifier: String?
init(serviceIdentifier: String, providerIdentifier: String) {
self.serviceIdentifier = serviceIdentifier
self.providerIdentifier = providerIdentifier
super.init()
}
}
final class ServiceUserTests: IntegrationTest {
public override func setUp() {
super.setUp()
self.createSelfUserAndConversation()
self.createExtraUsersAndConversations()
XCTAssertTrue(self.login())
XCTAssertTrue(self.waitForAllGroupsToBeEmpty(withTimeout: 0.5))
}
func createService() -> ServiceUser {
var mockServiceId: String!
var mockProviderId: String!
mockTransportSession.performRemoteChanges { (remoteChanges) in
let mockService = remoteChanges.insertService(withName: "Service A",
identifier: UUID().transportString(),
provider: UUID().transportString())
mockServiceId = mockService.identifier
mockProviderId = mockService.provider
}
XCTAssertTrue(self.waitForAllGroupsToBeEmpty(withTimeout: 0.5))
return DummyServiceUser(serviceIdentifier: mockServiceId, providerIdentifier: mockProviderId)
}
func testThatItAddsServiceToExistingConversation() throws {
// given
let jobIsDone = expectation(description: "service is added")
let service = self.createService()
let conversation = self.conversation(for: self.groupConversation)!
// when
conversation.add(serviceUser: service, in: userSession!) { (result) in
XCTAssertNil(result.error)
jobIsDone.fulfill()
}
XCTAssert(waitForAllGroupsToBeEmpty(withTimeout: 0.5))
// then
XCTAssertTrue(waitForCustomExpectations(withTimeout: 0.5))
}
func testThatItCreatesConversationAndAddsUser() {
// given
let jobIsDone = expectation(description: "service is added")
let service = self.createService()
// when
service.createConversation(in: userSession!) { (result) in
XCTAssertNotNil(result.value)
jobIsDone.fulfill()
}
XCTAssert(waitForAllGroupsToBeEmpty(withTimeout: 0.5))
// then
XCTAssertTrue(waitForCustomExpectations(withTimeout: 0.5))
}
func testThatItDetectsTheConversationFullResponse() {
// GIVEN
let response = ZMTransportResponse(payload: nil, httpStatus: 403, transportSessionError: nil, apiVersion: APIVersion.v0.rawValue)
// WHEN
let error = AddBotError(response: response)
// THEN
XCTAssertEqual(error, .tooManyParticipants)
}
func testThatItDetectsBotRejectedResponse() {
// GIVEN
let response = ZMTransportResponse(payload: nil, httpStatus: 419, transportSessionError: nil, apiVersion: APIVersion.v0.rawValue)
// WHEN
let error = AddBotError(response: response)
// THEN
XCTAssertEqual(error, .botRejected)
}
func testThatItDetectsBotNotResponding() {
// GIVEN
let response = ZMTransportResponse(payload: nil, httpStatus: 502, transportSessionError: nil, apiVersion: APIVersion.v0.rawValue)
// WHEN
let error = AddBotError(response: response)
// THEN
XCTAssertEqual(error, .botNotResponding)
}
func testThatItDetectsGeneralError() {
// GIVEN
let response = ZMTransportResponse(payload: nil, httpStatus: 500, transportSessionError: nil, apiVersion: APIVersion.v0.rawValue)
// WHEN
let error = AddBotError(response: response)
// THEN
XCTAssertEqual(error, .general)
}
}
|
406a06c1be85eeaf79ff06c8cc355dc5
| 25.065341 | 137 | 0.663433 | false | false | false | false |
alldne/PolarKit
|
refs/heads/master
|
Example/Tests/Tests.swift
|
mit
|
1
|
// https://github.com/Quick/Quick
import Quick
import Nimble
@testable import PolarKit
class TableOfContentsSpec: QuickSpec {
override func spec() {
describe("math") {
describe("CGVector extension") {
it("can calculate the angle between two vectors") {
let v1 = CGVector(dx: 1, dy: 1)
let v2 = CGVector(dx: 1, dy: 1)
expect(v1.getAngle(v2)).to(beCloseTo(0))
}
it("can calculate the angle between two vectors") {
let v1 = CGVector(dx: -1.333343505859375, dy: -2.5)
let v2 = CGVector(dx: -1.333343505859375, dy: -2.5)
expect(v1.getAngle(v2)).to(beCloseTo(0))
}
it("can calculate the angle between two vectors which is nearby with given hint") {
let v1 = CGVector(dx: 1, dy: 1)
let v2 = CGVector(dx: 1, dy: 1)
let hint = 0.0
expect(v1.getNearbyAngle(v2, hint: hint)).to(beCloseTo(0))
}
it("can calculate the angle between two vectors which is nearby with given hint") {
let v1 = CGVector(dx: -1.333343505859375, dy: -2.5)
let v2 = CGVector(dx: -1.333343505859375, dy: -2.5)
let hint = 0.0
expect(v1.getNearbyAngle(v2, hint: hint)).to(beCloseTo(0))
}
it("can calculate the angle between two vectors which is nearby with given hint") {
let v1 = CGVector(dx: 1, dy: 1)
let v2 = CGVector(dx: 1, dy: 1)
let hint = 3 * Double.pi - 1
expect(v1.getNearbyAngle(v2, hint: hint)).to(beCloseTo(2 * .pi))
}
it("can calculate the angle between two vectors which is nearby with given hint") {
let v1 = CGVector(dx: 1, dy: 0)
let v2 = CGVector(dx: 0, dy: 1)
let hint = -2 * Double.pi
expect(v1.getNearbyAngle(v2, hint: hint)).to(beCloseTo(-.pi * 3 / 2))
}
}
describe("bound function") {
describe("bound input") {
context("range [0, 10] with margin 2") {
let bound = makeBoundFunction(lower: 0, upper: 10, margin: 2).bound
it("bypass input in range") {
expect(bound(5)).to(beCloseTo(5))
}
it("bypass input in range") {
expect(bound(10)).to(beCloseTo(10))
}
it("returns smaller value than input within the margin") {
expect(bound(11)).to(beLessThanOrEqualTo(11))
}
it("returns smaller value than input within the margin") {
expect(bound(10.0001)).to(beLessThanOrEqualTo(10.0001))
}
it("should not return the value bigger than upper bound + margin") {
expect(bound(15)).to(beLessThanOrEqualTo(12))
}
it("should not return the value bigger than upper bound + margin") {
expect(bound(20)).to(beLessThanOrEqualTo(12))
}
it("should not return the value bigger than upper bound + margin") {
expect(bound(10*1000000)).to(beLessThanOrEqualTo(12))
}
it("should not return the value smaller than lower bound - margin") {
expect(bound(-10*1000000)).to(beGreaterThanOrEqualTo(-2))
}
}
context("range [-100, 10] with margin 10") {
let bound = makeBoundFunction(lower: -100, upper: 10, margin: 10).bound
it("bypass input in range") {
expect(bound(5)).to(beCloseTo(5))
}
it("bypass input in range") {
expect(bound(-100)).to(beCloseTo(-100))
}
it("bypass input in range") {
expect(bound(10)).to(beCloseTo(10))
}
it("should not return the value bigger than upper bound + margin") {
expect(bound(10*1000000)).to(beLessThanOrEqualTo(20))
}
it("should not return the value smaller than lower bound - margin") {
expect(bound(-10*1000000)).to(beGreaterThanOrEqualTo(-110))
}
}
}
describe("inverse of bound function") {
let functions = makeBoundFunction(lower: 0, upper: 10, margin: 2)
let bound = functions.bound
let inverse = functions.inverse
it("should work in the opposite way to the bound") {
expect(inverse(bound(10))).to(beCloseTo(10))
}
it("should work in the opposite way to the bound") {
expect(inverse(bound(11))).to(beCloseTo(11))
}
it("should work in the opposite way to the bound") {
expect(inverse(bound(11.999))).to(beCloseTo(11.999))
}
it("should work in the opposite way to the bound") {
expect(inverse(bound(-1.999))).to(beCloseTo(-1.999))
}
it("should work in the opposite way to the bound") {
expect(inverse(bound(10*1000))).to(beCloseTo(10*1000))
}
it("should work in the opposite way to the bound") {
expect(inverse(bound(-10*1000))).to(beCloseTo(-10*1000))
}
}
}
}
}
}
|
87214d0bcc1e1b76f742bdf78fac1e67
| 41.904762 | 99 | 0.445378 | false | false | false | false |
grpc/grpc-swift
|
refs/heads/main
|
Sources/protoc-gen-grpc-swift/main.swift
|
apache-2.0
|
1
|
/*
* Copyright 2017, gRPC Authors 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 SwiftProtobuf
import SwiftProtobufPluginLibrary
func Log(_ message: String) {
FileHandle.standardError.write((message + "\n").data(using: .utf8)!)
}
// from apple/swift-protobuf/Sources/protoc-gen-swift/StringUtils.swift
func splitPath(pathname: String) -> (dir: String, base: String, suffix: String) {
var dir = ""
var base = ""
var suffix = ""
#if swift(>=3.2)
let pathnameChars = pathname
#else
let pathnameChars = pathname.characters
#endif
for c in pathnameChars {
if c == "/" {
dir += base + suffix + String(c)
base = ""
suffix = ""
} else if c == "." {
base += suffix
suffix = String(c)
} else {
suffix += String(c)
}
}
#if swift(>=3.2)
let validSuffix = suffix.isEmpty || suffix.first == "."
#else
let validSuffix = suffix.isEmpty || suffix.characters.first == "."
#endif
if !validSuffix {
base += suffix
suffix = ""
}
return (dir: dir, base: base, suffix: suffix)
}
enum FileNaming: String {
case FullPath
case PathToUnderscores
case DropPath
}
func outputFileName(
component: String,
fileDescriptor: FileDescriptor,
fileNamingOption: FileNaming
) -> String {
let ext = "." + component + ".swift"
let pathParts = splitPath(pathname: fileDescriptor.name)
switch fileNamingOption {
case .FullPath:
return pathParts.dir + pathParts.base + ext
case .PathToUnderscores:
let dirWithUnderscores =
pathParts.dir.replacingOccurrences(of: "/", with: "_")
return dirWithUnderscores + pathParts.base + ext
case .DropPath:
return pathParts.base + ext
}
}
func uniqueOutputFileName(
component: String,
fileDescriptor: FileDescriptor,
fileNamingOption: FileNaming,
generatedFiles: inout [String: Int]
) -> String {
let defaultName = outputFileName(
component: component,
fileDescriptor: fileDescriptor,
fileNamingOption: fileNamingOption
)
if let count = generatedFiles[defaultName] {
generatedFiles[defaultName] = count + 1
return outputFileName(
component: "\(count)." + component,
fileDescriptor: fileDescriptor,
fileNamingOption: fileNamingOption
)
} else {
generatedFiles[defaultName] = 1
return defaultName
}
}
func main() throws {
// initialize responses
var response = Google_Protobuf_Compiler_CodeGeneratorResponse(
files: [],
supportedFeatures: [.proto3Optional]
)
// read plugin input
let rawRequest = FileHandle.standardInput.readDataToEndOfFile()
let request = try Google_Protobuf_Compiler_CodeGeneratorRequest(serializedData: rawRequest)
let options = try GeneratorOptions(parameter: request.parameter)
// Build the SwiftProtobufPluginLibrary model of the plugin input
let descriptorSet = DescriptorSet(protos: request.protoFile)
// A count of generated files by desired name (actual name may differ to avoid collisions).
var generatedFiles: [String: Int] = [:]
// Only generate output for services.
for name in request.fileToGenerate {
if let fileDescriptor = descriptorSet.fileDescriptor(named: name),
!fileDescriptor.services.isEmpty {
let grpcFileName = uniqueOutputFileName(
component: "grpc",
fileDescriptor: fileDescriptor,
fileNamingOption: options.fileNaming,
generatedFiles: &generatedFiles
)
let grpcGenerator = Generator(fileDescriptor, options: options)
var grpcFile = Google_Protobuf_Compiler_CodeGeneratorResponse.File()
grpcFile.name = grpcFileName
grpcFile.content = grpcGenerator.code
response.file.append(grpcFile)
}
}
// return everything to the caller
let serializedResponse = try response.serializedData()
FileHandle.standardOutput.write(serializedResponse)
}
do {
try main()
} catch {
Log("ERROR: \(error)")
}
|
3899ef96022658776acf6965fd22b586
| 28.058824 | 93 | 0.70108 | false | false | false | false |
ProfileCreator/ProfileCreator
|
refs/heads/master
|
ProfileCreator/ProfileCreator/Profile Editor Toolbar/ProfileEditorWindowToolbarItemExport.swift
|
mit
|
1
|
//
// ProfileEditorWindowToolbarItemExport.swift
// ProfileCreator
//
// Created by Erik Berglund.
// Copyright © 2018 Erik Berglund. All rights reserved.
//
import Cocoa
class ProfileEditorWindowToolbarItemExport: NSView {
// MARK: -
// MARK: Variables
let toolbarItem: NSToolbarItem
let disclosureTriangle: NSImageView
// MARK: -
// MARK: Initialization
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
init(profile: Profile, editor: ProfileEditor) {
// ---------------------------------------------------------------------
// Create the size of the toolbar item
// ---------------------------------------------------------------------
let rect = NSRect(x: 0, y: 0, width: 40, height: 32)
// ---------------------------------------------------------------------
// Create the actual toolbar item
// ---------------------------------------------------------------------
self.toolbarItem = NSToolbarItem(itemIdentifier: .editorExport)
self.toolbarItem.toolTip = NSLocalizedString("Export profile", comment: "")
// ---------------------------------------------------------------------
// Create the disclosure triangle overlay
// ---------------------------------------------------------------------
self.disclosureTriangle = NSImageView()
self.disclosureTriangle.translatesAutoresizingMaskIntoConstraints = false
self.disclosureTriangle.image = NSImage(named: "ArrowDown")
self.disclosureTriangle.imageScaling = .scaleProportionallyUpOrDown
self.disclosureTriangle.isHidden = true
// ---------------------------------------------------------------------
// Initialize self after the class variables have been instantiated
// ---------------------------------------------------------------------
super.init(frame: rect)
// ---------------------------------------------------------------------
// Create the button instance and add it to the toolbar item view
// ---------------------------------------------------------------------
self.addSubview(ProfileEditorWindowToolbarItemExportButton(frame: rect, profile: profile))
// ---------------------------------------------------------------------
// Add disclosure triangle to the toolbar item view
// ---------------------------------------------------------------------
self.addSubview(self.disclosureTriangle)
// ---------------------------------------------------------------------
// Setup the disclosure triangle constraints
// ---------------------------------------------------------------------
self.addConstraintsForDisclosureTriangle()
// ---------------------------------------------------------------------
// Set the toolbar item view
// ---------------------------------------------------------------------
self.toolbarItem.view = self
}
func disclosureTriangle(show: Bool) {
self.disclosureTriangle.isHidden = !show
}
func addConstraintsForDisclosureTriangle() {
var constraints = [NSLayoutConstraint]()
// Width
constraints.append(NSLayoutConstraint(item: self.disclosureTriangle,
attribute: .width,
relatedBy: .equal,
toItem: nil,
attribute: .notAnAttribute,
multiplier: 1,
constant: 9))
// Height == Width
constraints.append(NSLayoutConstraint(item: self.disclosureTriangle,
attribute: .height,
relatedBy: .equal,
toItem: self.disclosureTriangle,
attribute: .width,
multiplier: 1,
constant: 0))
// Bottom
constraints.append(NSLayoutConstraint(item: self,
attribute: .bottom,
relatedBy: .equal,
toItem: self.disclosureTriangle,
attribute: .bottom,
multiplier: 1,
constant: 6))
// Trailing
constraints.append(NSLayoutConstraint(item: self,
attribute: .trailing,
relatedBy: .equal,
toItem: self.disclosureTriangle,
attribute: .trailing,
multiplier: 1,
constant: 3))
NSLayoutConstraint.activate(constraints)
}
}
class ProfileEditorWindowToolbarItemExportButton: NSButton {
// MARK: -
// MARK: Variables
weak var profile: Profile?
let buttonMenu = NSMenu()
let menuDelay = 0.2
var trackingArea: NSTrackingArea?
var mouseIsDown = false
var menuWasShownForLastMouseDown = false
var mouseDownUniquenessCounter = 0
// MARK: -
// MARK: Initialization
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
convenience init(frame frameRect: NSRect, profile: Profile) {
self.init(frame: frameRect)
// ---------------------------------------------------------------------
// Setup Variables
// ---------------------------------------------------------------------
self.profile = profile
}
override init(frame frameRect: NSRect) {
super.init(frame: frameRect)
// ---------------------------------------------------------------------
// Setup Self (Toolbar Item)
// ---------------------------------------------------------------------
self.bezelStyle = .texturedRounded
self.image = NSImage(named: NSImage.shareTemplateName)
self.target = self
self.action = #selector(self.clicked(button:))
self.imageScaling = .scaleProportionallyDown
self.imagePosition = .imageOnly
self.isEnabled = true
// ---------------------------------------------------------------------
// Setup the button menu
// ---------------------------------------------------------------------
self.setupButtonMenu()
}
func setupButtonMenu() {
self.buttonMenu.delegate = self
// ---------------------------------------------------------------------
// Add item: "Export Profile"
// ---------------------------------------------------------------------
let menuItemExportProfile = NSMenuItem()
menuItemExportProfile.identifier = NSUserInterfaceItemIdentifier("export")
menuItemExportProfile.title = NSLocalizedString("Export Profile", comment: "")
menuItemExportProfile.isEnabled = true
menuItemExportProfile.target = self
menuItemExportProfile.action = #selector(self.exportProfile(menuItem:))
self.buttonMenu.addItem(menuItemExportProfile)
// ---------------------------------------------------------------------
// Add item: "Export Plist"
// ---------------------------------------------------------------------
let menuItemExportPlist = NSMenuItem()
menuItemExportPlist.identifier = NSUserInterfaceItemIdentifier("exportPlist")
menuItemExportPlist.title = NSLocalizedString("Export Plist", comment: "")
menuItemExportPlist.isEnabled = true
menuItemExportPlist.target = self
menuItemExportPlist.action = #selector(self.exportPlist(menuItem:))
self.buttonMenu.addItem(menuItemExportPlist)
}
// MARK: -
// MARK: Button/Menu Actions
@objc func clicked(button: NSButton) {
if self.isEnabled {
// -----------------------------------------------------------------
// If only button was clicked, call 'exportProfile'
// -----------------------------------------------------------------
self.exportProfile(menuItem: nil)
}
}
@objc func exportPlist(menuItem: NSMenuItem?) {
guard
let profile = self.profile,
let windowController = profile.windowControllers.first as? ProfileEditorWindowController,
let window = windowController.window else { return }
ProfileController.sharedInstance.exportPlist(profile: profile, promptWindow: window)
}
@objc func exportProfile(menuItem: NSMenuItem?) {
guard
let profile = self.profile,
let windowController = profile.windowControllers.first as? ProfileEditorWindowController,
let window = windowController.window else { return }
ProfileController.sharedInstance.export(profile: profile, promptWindow: window)
}
/*
func validateMenuItem(_ menuItem: NSMenuItem) -> Bool {
guard let mainWindowController = self.window?.windowController as? MainWindowController else { return false }
// FIXME: Add a constant for each menuItem
switch menuItem.identifier?.rawValue {
case "export":
return mainWindowController.splitView.tableViewController.selectedProfileIdentitifers?.count == 1
default:
return true
}
}
*/
// MARK: -
// MARK: NSControl/NSResponder Methods
override func mouseEntered(with event: NSEvent) {
if self.isEnabled, let parent = self.superview, let toolbarItemExport = parent as? ProfileEditorWindowToolbarItemExport {
toolbarItemExport.disclosureTriangle(show: true)
}
}
override func mouseExited(with event: NSEvent) {
if !self.mouseIsDown {
if let parent = self.superview, let toolbarItemExport = parent as? ProfileEditorWindowToolbarItemExport {
toolbarItemExport.disclosureTriangle(show: false)
}
}
}
override func mouseDown(with event: NSEvent) {
// ---------------------------------------------------------------------
// Reset mouse variables
// ---------------------------------------------------------------------
self.mouseIsDown = true
self.menuWasShownForLastMouseDown = false
self.mouseDownUniquenessCounter += 1
let mouseDownUniquenessCounterCopy = self.mouseDownUniquenessCounter
// ---------------------------------------------------------------------
// Show the button is being pressed
// ---------------------------------------------------------------------
self.highlight(true)
// ---------------------------------------------------------------------
// Wait 'menuDelay' before showing the context menu
// If button has been released before time runs out, it's considered a normal button press
// ---------------------------------------------------------------------
DispatchQueue.main.asyncAfter(deadline: .now() + self.menuDelay) {
if self.mouseIsDown && mouseDownUniquenessCounterCopy == self.mouseDownUniquenessCounter {
self.menuWasShownForLastMouseDown = true
guard let menuOrigin = self.superview?.convert(NSPoint(x: self.frame.origin.x + self.frame.size.width - 16,
y: self.frame.origin.y + 2), to: nil) else {
return
}
guard let event = NSEvent.mouseEvent(with: event.type,
location: menuOrigin,
modifierFlags: event.modifierFlags,
timestamp: event.timestamp,
windowNumber: event.windowNumber,
context: nil,
eventNumber: event.eventNumber,
clickCount: event.clickCount,
pressure: event.pressure) else {
return
}
NSMenu.popUpContextMenu(self.buttonMenu, with: event, for: self)
}
}
}
override func mouseUp(with event: NSEvent) {
// ---------------------------------------------------------------------
// Reset mouse variables
// ---------------------------------------------------------------------
self.mouseIsDown = false
if !self.menuWasShownForLastMouseDown {
if let parent = self.superview, let toolbarItemExport = parent as? ProfileEditorWindowToolbarItemExport {
toolbarItemExport.disclosureTriangle(show: false)
}
self.sendAction(self.action, to: self.target)
}
// ---------------------------------------------------------------------
// Hide the button is being pressed
// ---------------------------------------------------------------------
self.highlight(false)
}
// MARK: -
// MARK: NSView Methods
override func updateTrackingAreas() {
// ---------------------------------------------------------------------
// Remove previous tracking area if it was set
// ---------------------------------------------------------------------
if let trackingArea = self.trackingArea {
self.removeTrackingArea(trackingArea)
}
// ---------------------------------------------------------------------
// Create a new tracking area
// ---------------------------------------------------------------------
let trackingOptions = NSTrackingArea.Options(rawValue: (NSTrackingArea.Options.mouseEnteredAndExited.rawValue | NSTrackingArea.Options.activeAlways.rawValue))
self.trackingArea = NSTrackingArea(rect: self.bounds, options: trackingOptions, owner: self, userInfo: nil)
// ---------------------------------------------------------------------
// Add the new tracking area to the button
// ---------------------------------------------------------------------
self.addTrackingArea(self.trackingArea!)
}
}
// MARK: -
// MARK: NSMenuDelegate
extension ProfileEditorWindowToolbarItemExportButton: NSMenuDelegate {
func menuDidClose(_ menu: NSMenu) {
// ---------------------------------------------------------------------
// Reset mouse variables
// ---------------------------------------------------------------------
self.mouseIsDown = false
self.menuWasShownForLastMouseDown = false
self.mouseDownUniquenessCounter = 0
// ---------------------------------------------------------------------
// Turn of highlighting and disclosure triangle when the menu closes
// ---------------------------------------------------------------------
self.highlight(false)
if let parent = self.superview, let toolbarItemExport = parent as? ProfileEditorWindowToolbarItemExport {
toolbarItemExport.disclosureTriangle(show: false)
}
}
}
|
87d46c392168fbf04b1addbe98f0d375
| 42.483696 | 166 | 0.437945 | false | false | false | false |
Draveness/RbSwift
|
refs/heads/master
|
RbSwift/String/String+Case.swift
|
mit
|
2
|
//
// Case.swift
// RbSwift
//
// Created by draveness on 19/03/2017.
// Copyright © 2017 draveness. All rights reserved.
//
import Foundation
// MARK: - Case
public extension String {
/// Returns a copy of str with all uppercase letters replaced with their lowercase counterparts.
///
/// "Hello".downcase #=> "hello"
/// "HellHEo".downcase #=> "hellheo"
///
var downcase: String {
return self.lowercased()
}
/// Downcases the contents of the receiver
///
/// var hello = "Hello"
/// hello.downcased() #=> "hello"
/// hello #=> "hello"
///
/// - Returns: Self
@discardableResult
mutating func downcased() -> String {
self = downcase
return self
}
/// Returns a copy of str with all lowercase letters replaced with their uppercase counterparts.
///
/// "Hello".upcase #=> "HELLO"
/// "HellHEo".upcase #=> "HELLHEO"
///
var upcase: String {
return self.uppercased()
}
/// Upcases the contents of the receiver
///
/// var hello = "Hello"
/// hello.upcased() #=> "HELLO"
/// hello #=> "HELLO"
///
/// - Returns: Self
@discardableResult
mutating func upcased() -> String {
self = upcase
return self
}
/// Returns a copy of str with uppercase alphabetic characters converted to lowercase and lowercase characters converted to uppercase.
///
/// "HellHEo".swapcase #=> "hELLheO"
///
var swapcase: String {
return self.chars.map { $0.isUpcase ? $0.downcase : $0.upcase }.joined()
}
/// Equivalent to `swapcase`, but modifies the receiver in place.
///
/// let hello = "HellHEo"
/// hello.swapcased() #=> "hELLheO"
/// hello #=> "hELLheO"
///
/// - Returns: Self
@discardableResult
mutating func swapcased() -> String {
self = swapcase
return self
}
}
|
374289ae3dd3b59d4b8c38d869e9b235
| 25.844156 | 138 | 0.53314 | false | false | false | false |
colemancda/HTTP-Server
|
refs/heads/master
|
Mustache/Goodies/JavascriptEscape.swift
|
mit
|
3
|
// The MIT License
//
// Copyright (c) 2015 Gwendal Roué
//
// 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.
class JavascriptEscape : MustacheBoxable {
var mustacheBox: MustacheBox {
// Return a multi-facetted box, because JavascriptEscape interacts in
// various ways with Mustache rendering.
return Box(
// It has a value:
value: self,
// JavascriptEscape can be used as a filter: {{ javascriptEscape(x) }}:
filter: Filter(filter),
// JavascriptEscape escapes all variable tags: {{# javascriptEscape }}...{{ x }}...{{/ javascriptEscape }}
willRender: willRender)
}
// This function is used for evaluating `javascriptEscape(x)` expressions.
private func filter(rendering: Rendering) throws -> Rendering {
return Rendering(JavascriptEscape.escapeJavascript(rendering.string), rendering.contentType)
}
// A WillRenderFunction: this function lets JavascriptEscape change values that
// are about to be rendered to their escaped counterpart.
//
// It is activated as soon as the formatter enters the context stack, when
// used in a section {{# javascriptEscape }}...{{/ javascriptEscape }}.
private func willRender(tag: Tag, box: MustacheBox) -> MustacheBox {
switch tag.type {
case .Variable:
// We don't know if the box contains a String, so let's escape its
// rendering.
return Box(render: { (info: RenderingInfo) -> Rendering in
let rendering = try box.render(info: info)
return try self.filter(rendering)
})
case .Section:
return box
}
}
private class func escapeJavascript(string: String) -> String {
// This table comes from https://github.com/django/django/commit/8c4a525871df19163d5bfdf5939eff33b544c2e2#django/template/defaultfilters.py
//
// Quoting Malcolm Tredinnick:
// > Added extra robustness to the escapejs filter so that all invalid
// > characters are correctly escaped. This avoids any chance to inject
// > raw HTML inside <script> tags. Thanks to Mike Wiacek for the patch
// > and Collin Grady for the tests.
//
// Quoting Mike Wiacek from https://code.djangoproject.com/ticket/7177
// > The escapejs filter currently escapes a small subset of characters
// > to prevent JavaScript injection. However, the resulting strings can
// > still contain valid HTML, leading to XSS vulnerabilities. Using hex
// > encoding as opposed to backslash escaping, effectively prevents
// > Javascript injection and also helps prevent XSS. Attached is a
// > small patch that modifies the _js_escapes tuple to use hex encoding
// > on an expanded set of characters.
//
// The initial django commit used `\xNN` syntax. The \u syntax was
// introduced later for JSON compatibility.
let escapeTable: [Character: String] = [
"\0": "\\u0000",
"\u{01}": "\\u0001",
"\u{02}": "\\u0002",
"\u{03}": "\\u0003",
"\u{04}": "\\u0004",
"\u{05}": "\\u0005",
"\u{06}": "\\u0006",
"\u{07}": "\\u0007",
"\u{08}": "\\u0008",
"\u{09}": "\\u0009",
"\u{0A}": "\\u000A",
"\u{0B}": "\\u000B",
"\u{0C}": "\\u000C",
"\u{0D}": "\\u000D",
"\u{0E}": "\\u000E",
"\u{0F}": "\\u000F",
"\u{10}": "\\u0010",
"\u{11}": "\\u0011",
"\u{12}": "\\u0012",
"\u{13}": "\\u0013",
"\u{14}": "\\u0014",
"\u{15}": "\\u0015",
"\u{16}": "\\u0016",
"\u{17}": "\\u0017",
"\u{18}": "\\u0018",
"\u{19}": "\\u0019",
"\u{1A}": "\\u001A",
"\u{1B}": "\\u001B",
"\u{1C}": "\\u001C",
"\u{1D}": "\\u001D",
"\u{1E}": "\\u001E",
"\u{1F}": "\\u001F",
"\\": "\\u005C",
"'": "\\u0027",
"\"": "\\u0022",
">": "\\u003E",
"<": "\\u003C",
"&": "\\u0026",
"=": "\\u003D",
"-": "\\u002D",
";": "\\u003B",
"\u{2028}": "\\u2028",
"\u{2029}": "\\u2029",
// Required to pass GRMustache suite test "`javascript.escape` escapes control characters"
"\r\n": "\\u000D\\u000A",
]
var escaped = ""
for c in string.characters {
if let escapedString = escapeTable[c] {
escaped += escapedString
} else {
escaped.append(c)
}
}
return escaped
}
}
|
dcbcff2548661d4caad7d02e530ef1a2
| 41.120567 | 147 | 0.55447 | false | false | false | false |
TsvetanMilanov/BG-Tourist-Guide
|
refs/heads/master
|
BG-Tourist-Guide/ViewControllers/VisitTouristSiteViewController.swift
|
mit
|
1
|
//
// VisitTouristSiteViewController.swift
// BG-Tourist-Guide
//
// Created by Hakintosh on 2/7/16.
// Copyright © 2016 Hakintosh. All rights reserved.
//
import UIKit
import AVFoundation
import QRCodeReader
import CoreLocation
class VisitTouristSiteViewController: UIViewController, QRCodeReaderViewControllerDelegate, CLLocationManagerDelegate {
var locationManager : CLLocationManager = CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
}
@IBAction func btnScanQRCodeTap(sender: AnyObject) {
if (UIImagePickerController.isSourceTypeAvailable(.Camera))
{
let reader: QRCodeReaderViewController = {
let builder = QRCodeViewControllerBuilder { builder in
builder.reader = QRCodeReader(metadataObjectTypes: [AVMetadataObjectTypeQRCode])
builder.showTorchButton = true
}
return QRCodeReaderViewController(builder: builder)
}()
if QRCodeReader.supportsMetadataObjectTypes() {
reader.modalPresentationStyle = .FormSheet
reader.delegate = self
reader.completionBlock = { (result: QRCodeReaderResult?) in
if let result = result {
print("Completion with result: \(result.value) of type \(result.metadataType)")
}
}
presentViewController(reader, animated: true, completion: nil)
}
else {
TMAlertControllerFactory.showAlertDialogWithTitle("Error", message: "Your device does not have a camera. Please ask for the code of the tourist site and enter it.", uiViewController: self, andHandler: nil);
}
}
else {
TMAlertControllerFactory.showAlertDialogWithTitle("Error", message: "Your device does not have a camera. Please ask for the code of the tourist site and enter it.", uiViewController: self, andHandler: nil)
}
}
@IBAction func btnEnterCodeTap(sender: AnyObject) {
let weakSelf = self
TMAlertControllerFactory.showTextInputDialogWithTitle("Enter the code:", controller: self) { (text) in
weakSelf.locationManager.requestWhenInUseAuthorization()
weakSelf.locationManager.requestLocation()
let requester = TMRequester()
let loadingBar = TMActivityIndicatorFactory.activityIndicatorWithParentView(self.view)
loadingBar.startAnimating()
requester.postJSONWithUrl("/api/TouristSites/Visit?id=\(text)", data: nil, andBlock: { (err, result) in
loadingBar.stopAnimating()
if err != nil {
TMAlertControllerFactory.showAlertDialogWithTitle("Error", message: "There was an error on the server. Please try again later.", uiViewController: self, andHandler: nil)
return;
}
TMAlertControllerFactory.showAlertDialogWithTitle("Success", message: "The tourist site was visited successsfully.", uiViewController: self, andHandler: nil)
})
}
}
func reader(reader: QRCodeReaderViewController, didScanResult result: QRCodeReaderResult) {
self.dismissViewControllerAnimated(true, completion: { [weak self] in
let requester = TMRequester()
let loadingBar = TMActivityIndicatorFactory.activityIndicatorWithParentView(self!.view)
requester.postJSONWithUrl(result.value, data: nil, andBlock: { (err, result) in
loadingBar.stopAnimating()
if err != nil {
TMAlertControllerFactory.showAlertDialogWithTitle("Error", message: "There was an error on the server. Please try again later.", uiViewController: self!, andHandler: nil)
return;
}
TMAlertControllerFactory.showAlertDialogWithTitle("Success", message: "The tourist site was visited successsfully.", uiViewController: self!, andHandler: nil)
})
})
}
func readerDidCancel(reader: QRCodeReaderViewController) {
self.dismissViewControllerAnimated(true, completion: nil)
}
func locationManager(manager: CLLocationManager, didUpdateToLocation newLocation: CLLocation, fromLocation oldLocation: CLLocation) {
print("\(newLocation)")
}
func locationManager(manager: CLLocationManager, didFailWithError error: NSError) {
print("\(error)")
}
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
for location in locations {
print("\(location)")
}
}
}
|
3d363688931975fb102d4b46b551c89b
| 40.75 | 222 | 0.623141 | false | false | false | false |
coderwjq/swiftweibo
|
refs/heads/master
|
SwiftWeibo/SwiftWeibo/Classes/Compose/PicPicker/PicPickerCollectionView.swift
|
apache-2.0
|
1
|
//
// PicPickerCollectionView.swift
// SwiftWeibo
//
// Created by mzzdxt on 2016/11/9.
// Copyright © 2016年 wjq. All rights reserved.
//
import UIKit
private let picPickerCell = "picPickerCell"
private let edgeMargin: CGFloat = 15
class PicPickerCollectionView: UICollectionView {
// MARK:- 定义属性
var images: [UIImage] = [UIImage]() {
didSet {
reloadData()
}
}
// MARK:- 系统回调函数
override func awakeFromNib() {
super.awakeFromNib()
// 设置collectionView的layout
let layout = collectionViewLayout as! UICollectionViewFlowLayout
let itemWH = (UIScreen.main.bounds.width - 4 * edgeMargin) / 3
layout.itemSize = CGSize(width: itemWH, height: itemWH)
layout.minimumLineSpacing = edgeMargin
layout.minimumInteritemSpacing = edgeMargin
// 设置collectionView的属性
register(UINib(nibName: "PicPickerViewCell", bundle: nil), forCellWithReuseIdentifier: picPickerCell)
dataSource = self
// 设置collectionView的内边距
contentInset = UIEdgeInsets(top: edgeMargin, left: edgeMargin, bottom: edgeMargin, right: edgeMargin)
}
}
// MARK:- 数据源代理方法
extension PicPickerCollectionView: UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return images.count + 1
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
// 创建cell
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: picPickerCell, for: indexPath) as! PicPickerViewCell
// 给cell设置数据
cell.backgroundColor = UIColor.red
cell.image = (indexPath as NSIndexPath).item <= images.count - 1 ? images[(indexPath as NSIndexPath).item] : nil
// 返回cell
return cell
}
}
|
07821be38a719a3e6a29c44f60a6b975
| 30.786885 | 127 | 0.66426 | false | false | false | false |
yoheiMune/swift-sample-code
|
refs/heads/master
|
swift-sample-code/ViewController.swift
|
mit
|
1
|
//
// ViewController.swift
// swift-sample-code
//
// Created by Munesada Yohei on 2015/04/26.
// Copyright (c) 2015 Munesada Yohei. All rights reserved.
//
import UIKit
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
var tableView = UITableView()
//MARK: View Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
self.addUIComponents()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
//MARK : UITableViewDataSource
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 10
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = UITableViewCell()
cell.textLabel?.text = String(indexPath.row)
return cell
}
//MARK : Private Functions
/**
UIコンポーネントをViewに配置する
*/
private func addUIComponents() {
tableView.frame = self.view.frame
tableView.dataSource = self
tableView.delegate = self
self.view.addSubview(tableView)
}
}
|
27dc9a6e0512ec42050a1ca482f077b4
| 21.634615 | 109 | 0.659303 | false | false | false | false |
ulidev/WWDC2015
|
refs/heads/master
|
Joan Molinas/Joan Molinas/LeftCustomSegue.swift
|
mit
|
1
|
//
// LeftCustomSegue.swift
// Joan Molinas
//
// Created by Joan Molinas on 14/4/15.
// Copyright (c) 2015 Joan. All rights reserved.
//
import UIKit
class LeftCustomSegue: UIStoryboardSegue {
override func perform() {
var firstVC = self.sourceViewController.view as UIView!
var secondVC = self.destinationViewController.view as UIView!
let screenWidth = UIScreen.mainScreen().bounds.size.width
let screenHeight = UIScreen.mainScreen().bounds.size.height
secondVC.frame = CGRectMake(-screenWidth, 0, screenWidth, screenHeight)
let window = UIApplication.sharedApplication().keyWindow
window?.insertSubview(secondVC, aboveSubview: firstVC)
UIView.animateWithDuration(0.4, animations: { () -> Void in
firstVC.frame = CGRectMake(+screenWidth, 0, screenWidth, screenHeight)
secondVC.frame = CGRectMake(0, 0, screenWidth, screenHeight)
}) { (Finished) -> Void in
self.sourceViewController.presentViewController(self.destinationViewController as! UIViewController,
animated: false,
completion: nil)
}
}
}
|
75cee998f9b919adb7fa913784fb0d7d
| 34.2 | 116 | 0.637987 | false | false | false | false |
matthewpurcell/firefox-ios
|
refs/heads/master
|
Storage/SQL/SQLiteLogins.swift
|
mpl-2.0
|
1
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import Shared
import XCGLogger
import Deferred
private let log = Logger.syncLogger
let TableLoginsMirror = "loginsM"
let TableLoginsLocal = "loginsL"
let IndexLoginsOverrideHostname = "idx_loginsM_is_overridden_hostname"
let IndexLoginsDeletedHostname = "idx_loginsL_is_deleted_hostname"
let AllLoginTables: [String] = [TableLoginsMirror, TableLoginsLocal]
private let OverriddenHostnameIndexQuery =
"CREATE INDEX IF NOT EXISTS \(IndexLoginsOverrideHostname) ON \(TableLoginsMirror) (is_overridden, hostname)"
private let DeletedHostnameIndexQuery =
"CREATE INDEX IF NOT EXISTS \(IndexLoginsDeletedHostname) ON \(TableLoginsLocal) (is_deleted, hostname)"
private class LoginsTable: Table {
var name: String { return "LOGINS" }
var version: Int { return 3 }
func run(db: SQLiteDBConnection, sql: String, args: Args? = nil) -> Bool {
let err = db.executeChange(sql, withArgs: args)
if err != nil {
log.error("Error running SQL in LoginsTable. \(err?.localizedDescription)")
log.error("SQL was \(sql)")
}
return err == nil
}
// TODO: transaction.
func run(db: SQLiteDBConnection, queries: [String]) -> Bool {
for sql in queries {
if !run(db, sql: sql, args: nil) {
return false
}
}
return true
}
func create(db: SQLiteDBConnection) -> Bool {
let common =
"id INTEGER PRIMARY KEY AUTOINCREMENT" +
", hostname TEXT NOT NULL" +
", httpRealm TEXT" +
", formSubmitURL TEXT" +
", usernameField TEXT" +
", passwordField TEXT" +
", timesUsed INTEGER NOT NULL DEFAULT 0" +
", timeCreated INTEGER NOT NULL" +
", timeLastUsed INTEGER" +
", timePasswordChanged INTEGER NOT NULL" +
", username TEXT" +
", password TEXT NOT NULL"
let mirror = "CREATE TABLE IF NOT EXISTS \(TableLoginsMirror) (" +
common +
", guid TEXT NOT NULL UNIQUE" +
", server_modified INTEGER NOT NULL" + // Integer milliseconds.
", is_overridden TINYINT NOT NULL DEFAULT 0" +
")"
let local = "CREATE TABLE IF NOT EXISTS \(TableLoginsLocal) (" +
common +
", guid TEXT NOT NULL UNIQUE " + // Typically overlaps one in the mirror unless locally new.
", local_modified INTEGER" + // Can be null. Client clock. In extremis only.
", is_deleted TINYINT NOT NULL DEFAULT 0" + // Boolean. Locally deleted.
", sync_status TINYINT " + // SyncStatus enum. Set when changed or created.
"NOT NULL DEFAULT \(SyncStatus.Synced.rawValue)" +
")"
return self.run(db, queries: [mirror, local, OverriddenHostnameIndexQuery, DeletedHostnameIndexQuery])
}
func updateTable(db: SQLiteDBConnection, from: Int) -> Bool {
let to = self.version
if from == to {
log.debug("Skipping update from \(from) to \(to).")
return true
}
if from == 0 {
// This is likely an upgrade from before Bug 1160399.
log.debug("Updating logins tables from zero. Assuming drop and recreate.")
return drop(db) && create(db)
}
if from < 3 && to >= 3 {
log.debug("Updating logins tables to include version 3 indices")
return self.run(db, queries: [OverriddenHostnameIndexQuery, DeletedHostnameIndexQuery])
}
// TODO: real update!
log.debug("Updating logins table from \(from) to \(to).")
return drop(db) && create(db)
}
func exists(db: SQLiteDBConnection) -> Bool {
return db.tablesExist(AllLoginTables)
}
func drop(db: SQLiteDBConnection) -> Bool {
log.debug("Dropping logins table.")
let err = db.executeChange("DROP TABLE IF EXISTS \(name)", withArgs: nil)
return err == nil
}
}
public class SQLiteLogins: BrowserLogins {
private let db: BrowserDB
private static let MainColumns = "guid, username, password, hostname, httpRealm, formSubmitURL, usernameField, passwordField"
private static let MainWithLastUsedColumns = MainColumns + ", timeLastUsed, timesUsed"
private static let LoginColumns = MainColumns + ", timeCreated, timeLastUsed, timePasswordChanged, timesUsed"
public init(db: BrowserDB) {
self.db = db
db.createOrUpdate(LoginsTable())
}
private class func populateLogin(login: Login, row: SDRow) {
login.formSubmitURL = row["formSubmitURL"] as? String
login.usernameField = row["usernameField"] as? String
login.passwordField = row["passwordField"] as? String
login.guid = row["guid"] as! String
if let timeCreated = row.getTimestamp("timeCreated"),
let timeLastUsed = row.getTimestamp("timeLastUsed"),
let timePasswordChanged = row.getTimestamp("timePasswordChanged"),
let timesUsed = row["timesUsed"] as? Int {
login.timeCreated = timeCreated
login.timeLastUsed = timeLastUsed
login.timePasswordChanged = timePasswordChanged
login.timesUsed = timesUsed
}
}
private class func constructLogin<T: Login>(row: SDRow, c: T.Type) -> T {
let credential = NSURLCredential(user: row["username"] as? String ?? "",
password: row["password"] as! String,
persistence: NSURLCredentialPersistence.None)
// There was a bug in previous versions of the app where we saved only the hostname and not the
// scheme and port in the DB. To work with these scheme-less hostnames, we try to extract the scheme and
// hostname by converting to a URL first. If there is no valid hostname or scheme for the URL,
// fallback to returning the raw hostname value from the DB as the host and allow NSURLProtectionSpace
// to use the default (http) scheme. See https://bugzilla.mozilla.org/show_bug.cgi?id=1238103.
let hostnameString = (row["hostname"] as? String) ?? ""
let hostnameURL = hostnameString.asURL
let scheme = hostnameURL?.scheme
let port = hostnameURL?.port?.integerValue ?? 0
// Check for malformed hostname urls in the DB
let host: String
var malformedHostname = false
if let h = hostnameURL?.host {
host = h
} else {
host = hostnameString
malformedHostname = true
}
let protectionSpace = NSURLProtectionSpace(host: host,
port: port,
`protocol`: scheme,
realm: row["httpRealm"] as? String,
authenticationMethod: nil)
let login = T(credential: credential, protectionSpace: protectionSpace)
self.populateLogin(login, row: row)
login.hasMalformedHostname = malformedHostname
return login
}
class func LocalLoginFactory(row: SDRow) -> LocalLogin {
let login = self.constructLogin(row, c: LocalLogin.self)
login.localModified = row.getTimestamp("local_modified")!
login.isDeleted = row.getBoolean("is_deleted")
login.syncStatus = SyncStatus(rawValue: row["sync_status"] as! Int)!
return login
}
class func MirrorLoginFactory(row: SDRow) -> MirrorLogin {
let login = self.constructLogin(row, c: MirrorLogin.self)
login.serverModified = row.getTimestamp("server_modified")!
login.isOverridden = row.getBoolean("is_overridden")
return login
}
private class func LoginFactory(row: SDRow) -> Login {
return self.constructLogin(row, c: Login.self)
}
private class func LoginDataFactory(row: SDRow) -> LoginData {
return LoginFactory(row) as LoginData
}
private class func LoginUsageDataFactory(row: SDRow) -> LoginUsageData {
return LoginFactory(row) as LoginUsageData
}
func notifyLoginDidChange() {
log.debug("Notifying login did change.")
// For now we don't care about the contents.
// This posts immediately to the shared notification center.
let notification = NSNotification(name: NotificationDataLoginDidChange, object: nil)
NSNotificationCenter.defaultCenter().postNotification(notification)
}
public func getUsageDataForLoginByGUID(guid: GUID) -> Deferred<Maybe<LoginUsageData>> {
let projection = SQLiteLogins.LoginColumns
let sql =
"SELECT \(projection) FROM " +
"\(TableLoginsLocal) WHERE is_deleted = 0 AND guid = ? " +
"UNION ALL " +
"SELECT \(projection) FROM " +
"\(TableLoginsMirror) WHERE is_overridden = 0 AND guid = ? " +
"LIMIT 1"
let args: Args = [guid, guid]
return db.runQuery(sql, args: args, factory: SQLiteLogins.LoginUsageDataFactory)
>>== { value in
deferMaybe(value[0]!)
}
}
public func getLoginDataForGUID(guid: GUID) -> Deferred<Maybe<Login>> {
let projection = SQLiteLogins.LoginColumns
let sql =
"SELECT \(projection) FROM " +
"\(TableLoginsLocal) WHERE is_deleted = 0 AND guid = ? " +
"UNION ALL " +
"SELECT \(projection) FROM " +
"\(TableLoginsMirror) WHERE is_overriden IS NOT 1 AND guid = ? " +
"ORDER BY hostname ASC " +
"LIMIT 1"
let args: Args = [guid, guid]
return db.runQuery(sql, args: args, factory: SQLiteLogins.LoginFactory)
>>== { value in
if let login = value[0] {
return deferMaybe(login)
} else {
return deferMaybe(LoginDataError(description: "Login not found for GUID \(guid)"))
}
}
}
public func getLoginsForProtectionSpace(protectionSpace: NSURLProtectionSpace) -> Deferred<Maybe<Cursor<LoginData>>> {
let projection = SQLiteLogins.MainWithLastUsedColumns
let sql =
"SELECT \(projection) FROM " +
"\(TableLoginsLocal) WHERE is_deleted = 0 AND hostname IS ? OR hostname IS ?" +
"UNION ALL " +
"SELECT \(projection) FROM " +
"\(TableLoginsMirror) WHERE is_overridden = 0 AND hostname IS ? OR hostname IS ?" +
"ORDER BY timeLastUsed DESC"
// Since we store hostnames as the full scheme/protocol + host, combine the two to look up in our DB.
// In the case of https://bugzilla.mozilla.org/show_bug.cgi?id=1238103, there may be hostnames without
// a scheme. Check for these as well.
let args: Args = [
protectionSpace.urlString(),
protectionSpace.host,
protectionSpace.urlString(),
protectionSpace.host,
]
if Logger.logPII {
log.debug("Looking for login: \(protectionSpace.urlString()) && \(protectionSpace.host)")
}
return db.runQuery(sql, args: args, factory: SQLiteLogins.LoginDataFactory)
}
// username is really Either<String, NULL>; we explicitly match no username.
public func getLoginsForProtectionSpace(protectionSpace: NSURLProtectionSpace, withUsername username: String?) -> Deferred<Maybe<Cursor<LoginData>>> {
let projection = SQLiteLogins.MainWithLastUsedColumns
let args: Args
let usernameMatch: String
if let username = username {
args = [
protectionSpace.urlString(), username, protectionSpace.host,
protectionSpace.urlString(), username, protectionSpace.host
]
usernameMatch = "username = ?"
} else {
args = [
protectionSpace.urlString(), protectionSpace.host,
protectionSpace.urlString(), protectionSpace.host
]
usernameMatch = "username IS NULL"
}
if Logger.logPII {
log.debug("Looking for login: \(username), \(args[0])")
}
let sql =
"SELECT \(projection) FROM " +
"\(TableLoginsLocal) WHERE is_deleted = 0 AND hostname IS ? AND \(usernameMatch) OR hostname IS ?" +
"UNION ALL " +
"SELECT \(projection) FROM " +
"\(TableLoginsMirror) WHERE is_overridden = 0 AND hostname IS ? AND \(usernameMatch) OR hostname IS ?" +
"ORDER BY timeLastUsed DESC"
return db.runQuery(sql, args: args, factory: SQLiteLogins.LoginDataFactory)
}
public func getAllLogins() -> Deferred<Maybe<Cursor<Login>>> {
return searchLoginsWithQuery(nil)
}
public func searchLoginsWithQuery(query: String?) -> Deferred<Maybe<Cursor<Login>>> {
let projection = SQLiteLogins.LoginColumns
var searchClauses = [String]()
var args: Args? = nil
if let query = query where !query.isEmpty {
// Add wildcards to change query to 'contains in' and add them to args. We need 6 args because
// we include the where clause twice: Once for the local table and another for the remote.
args = (0..<6).map { _ in
return "%\(query)%" as String?
}
searchClauses.append(" username LIKE ? ")
searchClauses.append(" password LIKE ? ")
searchClauses.append(" hostname LIKE ? ")
}
let whereSearchClause = searchClauses.count > 0 ? "AND" + searchClauses.joinWithSeparator("OR") : ""
let sql =
"SELECT \(projection) FROM " +
"\(TableLoginsLocal) WHERE is_deleted = 0 " + whereSearchClause +
"UNION ALL " +
"SELECT \(projection) FROM " +
"\(TableLoginsMirror) WHERE is_overridden = 0 " + whereSearchClause +
"ORDER BY hostname ASC"
return db.runQuery(sql, args: args, factory: SQLiteLogins.LoginFactory)
}
public func addLogin(login: LoginData) -> Success {
if let error = login.isValid.failureValue {
return deferMaybe(error)
}
let nowMicro = NSDate.nowMicroseconds()
let nowMilli = nowMicro / 1000
let dateMicro = NSNumber(unsignedLongLong: nowMicro)
let dateMilli = NSNumber(unsignedLongLong: nowMilli)
let args: Args = [
login.hostname,
login.httpRealm,
login.formSubmitURL,
login.usernameField,
login.passwordField,
login.username,
login.password,
login.guid,
dateMicro, // timeCreated
dateMicro, // timeLastUsed
dateMicro, // timePasswordChanged
dateMilli, // localModified
]
let sql =
"INSERT OR IGNORE INTO \(TableLoginsLocal) " +
// Shared fields.
"( hostname" +
", httpRealm" +
", formSubmitURL" +
", usernameField" +
", passwordField" +
", timesUsed" +
", username" +
", password " +
// Local metadata.
", guid " +
", timeCreated" +
", timeLastUsed" +
", timePasswordChanged" +
", local_modified " +
", is_deleted " +
", sync_status " +
") " +
"VALUES (?,?,?,?,?,1,?,?,?,?,?, " +
"?, ?, 0, \(SyncStatus.New.rawValue)" + // Metadata.
")"
return db.run(sql, withArgs: args)
>>> effect(self.notifyLoginDidChange)
}
private func cloneMirrorToOverlay(whereClause whereClause: String?, args: Args?) -> Deferred<Maybe<Int>> {
let shared = "guid, hostname, httpRealm, formSubmitURL, usernameField, passwordField, timeCreated, timeLastUsed, timePasswordChanged, timesUsed, username, password "
let local = ", local_modified, is_deleted, sync_status "
let sql = "INSERT OR IGNORE INTO \(TableLoginsLocal) (\(shared)\(local)) SELECT \(shared), NULL AS local_modified, 0 AS is_deleted, 0 AS sync_status FROM \(TableLoginsMirror) \(whereClause ?? "")"
return self.db.write(sql, withArgs: args)
}
/**
* Returns success if either a local row already existed, or
* one could be copied from the mirror.
*/
private func ensureLocalOverlayExistsForGUID(guid: GUID) -> Success {
let sql = "SELECT guid FROM \(TableLoginsLocal) WHERE guid = ?"
let args: Args = [guid]
let c = db.runQuery(sql, args: args, factory: { row in 1 })
return c >>== { rows in
if rows.count > 0 {
return succeed()
}
log.debug("No overlay; cloning one for GUID \(guid).")
return self.cloneMirrorToOverlay(guid)
>>== { count in
if count > 0 {
return succeed()
}
log.warning("Failed to create local overlay for GUID \(guid).")
return deferMaybe(NoSuchRecordError(guid: guid))
}
}
}
private func cloneMirrorToOverlay(guid: GUID) -> Deferred<Maybe<Int>> {
let whereClause = "WHERE guid = ?"
let args: Args = [guid]
return self.cloneMirrorToOverlay(whereClause: whereClause, args: args)
}
private func markMirrorAsOverridden(guid: GUID) -> Success {
let args: Args = [guid]
let sql =
"UPDATE \(TableLoginsMirror) SET " +
"is_overridden = 1 " +
"WHERE guid = ?"
return self.db.run(sql, withArgs: args)
}
/**
* Replace the local DB row with the provided GUID.
* If no local overlay exists, one is first created.
*
* If `significant` is `true`, the `sync_status` of the row is bumped to at least `Changed`.
* If it's already `New`, it remains marked as `New`.
*
* This flag allows callers to make minor changes (such as incrementing a usage count)
* without triggering an upload or a conflict.
*/
public func updateLoginByGUID(guid: GUID, new: LoginData, significant: Bool) -> Success {
if let error = new.isValid.failureValue {
return deferMaybe(error)
}
// Right now this method is only ever called if the password changes at
// point of use, so we always set `timePasswordChanged` and `timeLastUsed`.
// We can (but don't) also assume that `significant` will always be `true`,
// at least for the time being.
let nowMicro = NSDate.nowMicroseconds()
let nowMilli = nowMicro / 1000
let dateMicro = NSNumber(unsignedLongLong: nowMicro)
let dateMilli = NSNumber(unsignedLongLong: nowMilli)
let args: Args = [
dateMilli, // local_modified
dateMicro, // timeLastUsed
dateMicro, // timePasswordChanged
new.httpRealm,
new.formSubmitURL,
new.usernameField,
new.passwordField,
new.password,
new.hostname,
new.username,
guid,
]
let update =
"UPDATE \(TableLoginsLocal) SET " +
" local_modified = ?, timeLastUsed = ?, timePasswordChanged = ?" +
", httpRealm = ?, formSubmitURL = ?, usernameField = ?" +
", passwordField = ?, timesUsed = timesUsed + 1" +
", password = ?, hostname = ?, username = ?" +
// We keep rows marked as New in preference to marking them as changed. This allows us to
// delete them immediately if they don't reach the server.
(significant ? ", sync_status = max(sync_status, 1) " : "") +
" WHERE guid = ?"
return self.ensureLocalOverlayExistsForGUID(guid)
>>> { self.markMirrorAsOverridden(guid) }
>>> { self.db.run(update, withArgs: args) }
>>> effect(self.notifyLoginDidChange)
}
public func addUseOfLoginByGUID(guid: GUID) -> Success {
let sql =
"UPDATE \(TableLoginsLocal) SET " +
"timesUsed = timesUsed + 1, timeLastUsed = ?, local_modified = ? " +
"WHERE guid = ? AND is_deleted = 0"
// For now, mere use is not enough to flip sync_status to Changed.
let nowMicro = NSDate.nowMicroseconds()
let nowMilli = nowMicro / 1000
let args: Args = [NSNumber(unsignedLongLong: nowMicro), NSNumber(unsignedLongLong: nowMilli), guid]
return self.ensureLocalOverlayExistsForGUID(guid)
>>> { self.markMirrorAsOverridden(guid) }
>>> { self.db.run(sql, withArgs: args) }
}
public func removeLoginByGUID(guid: GUID) -> Success {
return removeLoginsWithGUIDs([guid])
}
public func removeLoginsWithGUIDs(guids: [GUID]) -> Success {
if guids.isEmpty {
return succeed()
}
let nowMillis = NSDate.now()
let inClause = BrowserDB.varlist(guids.count)
// Immediately delete anything that's marked as new -- i.e., it's never reached
// the server.
let delete =
"DELETE FROM \(TableLoginsLocal) WHERE guid IN \(inClause) AND sync_status = \(SyncStatus.New.rawValue)"
// Otherwise, mark it as changed.
let update =
"UPDATE \(TableLoginsLocal) SET " +
" local_modified = \(nowMillis)" +
", sync_status = \(SyncStatus.Changed.rawValue)" +
", is_deleted = 1" +
", password = ''" +
", hostname = ''" +
", username = ''" +
" WHERE guid IN \(inClause)"
let markMirrorAsOverridden =
"UPDATE \(TableLoginsMirror) SET " +
"is_overridden = 1 " +
"WHERE guid IN \(inClause)"
let insert =
"INSERT OR IGNORE INTO \(TableLoginsLocal) " +
"(guid, local_modified, is_deleted, sync_status, hostname, timeCreated, timePasswordChanged, password, username) " +
"SELECT guid, \(nowMillis), 1, \(SyncStatus.Changed.rawValue), '', timeCreated, \(nowMillis)000, '', '' FROM \(TableLoginsMirror) WHERE guid IN \(inClause)"
let args: Args = guids.map { $0 as AnyObject }
return self.db.run([
(delete, args),
(update, args),
(markMirrorAsOverridden, args),
(insert, args)
]) >>> effect(self.notifyLoginDidChange)
}
public func removeAll() -> Success {
// Immediately delete anything that's marked as new -- i.e., it's never reached
// the server. If Sync isn't set up, this will be everything.
let delete =
"DELETE FROM \(TableLoginsLocal) WHERE sync_status = \(SyncStatus.New.rawValue)"
let nowMillis = NSDate.now()
// Mark anything we haven't already deleted.
let update =
"UPDATE \(TableLoginsLocal) SET local_modified = \(nowMillis), sync_status = \(SyncStatus.Changed.rawValue), is_deleted = 1, password = '', hostname = '', username = '' WHERE is_deleted = 0"
// Copy all the remaining rows from our mirror, marking them as locally deleted. The
// OR IGNORE will cause conflicts due to non-unique guids to be dropped, preserving
// anything we already deleted.
let insert =
"INSERT OR IGNORE INTO \(TableLoginsLocal) (guid, local_modified, is_deleted, sync_status, hostname, timeCreated, timePasswordChanged, password, username) " +
"SELECT guid, \(nowMillis), 1, \(SyncStatus.Changed.rawValue), '', timeCreated, \(nowMillis)000, '', '' FROM \(TableLoginsMirror)"
// After that, we mark all of the mirror rows as overridden.
return self.db.run(delete)
>>> { self.db.run(update) }
>>> { self.db.run("UPDATE \(TableLoginsMirror) SET is_overridden = 1") }
>>> { self.db.run(insert) }
>>> effect(self.notifyLoginDidChange)
}
}
// When a server change is detected (e.g., syncID changes), we should consider shifting the contents
// of the mirror into the local overlay, allowing a content-based reconciliation to occur on the next
// full sync. Or we could flag the mirror as to-clear, download the server records and un-clear, and
// resolve the remainder on completion. This assumes that a fresh start will typically end up with
// the exact same records, so we might as well keep the shared parents around and double-check.
extension SQLiteLogins: SyncableLogins {
/**
* Delete the login with the provided GUID. Succeeds if the GUID is unknown.
*/
public func deleteByGUID(guid: GUID, deletedAt: Timestamp) -> Success {
// Simply ignore the possibility of a conflicting local change for now.
let local = "DELETE FROM \(TableLoginsLocal) WHERE guid = ?"
let remote = "DELETE FROM \(TableLoginsMirror) WHERE guid = ?"
let args: Args = [guid]
return self.db.run(local, withArgs: args) >>> { self.db.run(remote, withArgs: args) }
}
func getExistingMirrorRecordByGUID(guid: GUID) -> Deferred<Maybe<MirrorLogin?>> {
let sql = "SELECT * FROM \(TableLoginsMirror) WHERE guid = ? LIMIT 1"
let args: Args = [guid]
return self.db.runQuery(sql, args: args, factory: SQLiteLogins.MirrorLoginFactory) >>== { deferMaybe($0[0]) }
}
func getExistingLocalRecordByGUID(guid: GUID) -> Deferred<Maybe<LocalLogin?>> {
let sql = "SELECT * FROM \(TableLoginsLocal) WHERE guid = ? LIMIT 1"
let args: Args = [guid]
return self.db.runQuery(sql, args: args, factory: SQLiteLogins.LocalLoginFactory) >>== { deferMaybe($0[0]) }
}
private func storeReconciledLogin(login: Login) -> Success {
let dateMilli = NSNumber(unsignedLongLong: NSDate.now())
let args: Args = [
dateMilli, // local_modified
login.httpRealm,
login.formSubmitURL,
login.usernameField,
login.passwordField,
NSNumber(unsignedLongLong: login.timeLastUsed),
NSNumber(unsignedLongLong: login.timePasswordChanged),
login.timesUsed,
login.password,
login.hostname,
login.username,
login.guid,
]
let update =
"UPDATE \(TableLoginsLocal) SET " +
" local_modified = ?" +
", httpRealm = ?, formSubmitURL = ?, usernameField = ?" +
", passwordField = ?, timeLastUsed = ?, timePasswordChanged = ?, timesUsed = ?" +
", password = ?" +
", hostname = ?, username = ?" +
", sync_status = \(SyncStatus.Changed.rawValue) " +
" WHERE guid = ?"
return self.db.run(update, withArgs: args)
}
public func applyChangedLogin(upstream: ServerLogin) -> Success {
// Our login storage tracks the shared parent from the last sync (the "mirror").
// This allows us to conclusively determine what changed in the case of conflict.
//
// Our first step is to determine whether the record is changed or new: i.e., whether
// or not it's present in the mirror.
//
// TODO: these steps can be done in a single query. Make it work, make it right, make it fast.
// TODO: if there's no mirror record, all incoming records can be applied in one go; the only
// reason we need to fetch first is to establish the shared parent. That would be nice.
let guid = upstream.guid
return self.getExistingMirrorRecordByGUID(guid) >>== { mirror in
return self.getExistingLocalRecordByGUID(guid) >>== { local in
return self.applyChangedLogin(upstream, local: local, mirror: mirror)
}
}
}
private func applyChangedLogin(upstream: ServerLogin, local: LocalLogin?, mirror: MirrorLogin?) -> Success {
// Once we have the server record, the mirror record (if any), and the local overlay (if any),
// we can always know which state a record is in.
// If it's present in the mirror, then we can proceed directly to handling the change;
// we assume that once a record makes it into the mirror, that the local record association
// has already taken place, and we're tracking local changes correctly.
if let mirror = mirror {
log.debug("Mirror record found for changed record \(mirror.guid).")
if let local = local {
log.debug("Changed local overlay found for \(local.guid). Resolving conflict with 3WM.")
// * Changed remotely and locally (conflict). Resolve the conflict using a three-way merge: the
// local mirror is the shared parent of both the local overlay and the new remote record.
// Apply results as in the co-creation case.
return self.resolveConflictBetween(local: local, upstream: upstream, shared: mirror)
}
log.debug("No local overlay found. Updating mirror to upstream.")
// * Changed remotely but not locally. Apply the remote changes to the mirror.
// There is no local overlay to discard or resolve against.
return self.updateMirrorToLogin(upstream, fromPrevious: mirror)
}
// * New both locally and remotely with no shared parent (cocreation).
// Or we matched the GUID, and we're assuming we just forgot the mirror.
//
// Merge and apply the results remotely, writing the result into the mirror and discarding the overlay
// if the upload succeeded. (Doing it in this order allows us to safely replay on failure.)
//
// If the local and remote record are the same, this is trivial.
// At this point we also switch our local GUID to match the remote.
if let local = local {
// We might have randomly computed the same GUID on two devices connected
// to the same Sync account.
// With our 9-byte GUIDs, the chance of that happening is very small, so we
// assume that this device has previously connected to this account, and we
// go right ahead with a merge.
log.debug("Local record with GUID \(local.guid) but no mirror. This is unusual; assuming disconnect-reconnect scenario. Smushing.")
return self.resolveConflictWithoutParentBetween(local: local, upstream: upstream)
}
// If it's not present, we must first check whether we have a local record that's substantially
// the same -- the co-creation or re-sync case.
//
// In this case, we apply the server record to the mirror, change the local record's GUID,
// and proceed to reconcile the change on a content basis.
return self.findLocalRecordByContent(upstream) >>== { local in
if let local = local {
log.debug("Local record \(local.guid) content-matches new remote record \(upstream.guid). Smushing.")
return self.resolveConflictWithoutParentBetween(local: local, upstream: upstream)
}
// * New upstream only; no local overlay, content-based merge,
// or shared parent in the mirror. Insert it in the mirror.
log.debug("Never seen remote record \(upstream.guid). Mirroring.")
return self.insertNewMirror(upstream)
}
}
// N.B., the final guid is sometimes a WHERE and sometimes inserted.
private func mirrorArgs(login: ServerLogin) -> Args {
let args: Args = [
NSNumber(unsignedLongLong: login.serverModified),
login.httpRealm,
login.formSubmitURL,
login.usernameField,
login.passwordField,
login.timesUsed,
NSNumber(unsignedLongLong: login.timeLastUsed),
NSNumber(unsignedLongLong: login.timePasswordChanged),
NSNumber(unsignedLongLong: login.timeCreated),
login.password,
login.hostname,
login.username,
login.guid,
]
return args
}
/**
* Called when we have a changed upstream record and no local changes.
* There's no need to flip the is_overridden flag.
*/
private func updateMirrorToLogin(login: ServerLogin, fromPrevious previous: Login) -> Success {
let args = self.mirrorArgs(login)
let sql =
"UPDATE \(TableLoginsMirror) SET " +
" server_modified = ?" +
", httpRealm = ?, formSubmitURL = ?, usernameField = ?" +
", passwordField = ?" +
// These we need to coalesce, because we might be supplying zeroes if the remote has
// been overwritten by an older client. In this case, preserve the old value in the
// mirror.
", timesUsed = coalesce(nullif(?, 0), timesUsed)" +
", timeLastUsed = coalesce(nullif(?, 0), timeLastUsed)" +
", timePasswordChanged = coalesce(nullif(?, 0), timePasswordChanged)" +
", timeCreated = coalesce(nullif(?, 0), timeCreated)" +
", password = ?, hostname = ?, username = ?" +
" WHERE guid = ?"
return self.db.run(sql, withArgs: args)
}
/**
* Called when we have a completely new record. Naturally the new record
* is marked as non-overridden.
*/
private func insertNewMirror(login: ServerLogin, isOverridden: Int = 0) -> Success {
let args = self.mirrorArgs(login)
let sql =
"INSERT OR IGNORE INTO \(TableLoginsMirror) (" +
" is_overridden, server_modified" +
", httpRealm, formSubmitURL, usernameField" +
", passwordField, timesUsed, timeLastUsed, timePasswordChanged, timeCreated" +
", password, hostname, username, guid" +
") VALUES (\(isOverridden), ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"
return self.db.run(sql, withArgs: args)
}
/**
* We assume a local record matches if it has the same username (password can differ),
* hostname, httpRealm. We also check that the formSubmitURLs are either blank or have the
* same host and port.
*
* This is roughly the same as desktop's .matches():
* <https://mxr.mozilla.org/mozilla-central/source/toolkit/components/passwordmgr/nsLoginInfo.js#41>
*/
private func findLocalRecordByContent(login: Login) -> Deferred<Maybe<LocalLogin?>> {
let primary =
"SELECT * FROM \(TableLoginsLocal) WHERE " +
"hostname IS ? AND httpRealm IS ? AND username IS ?"
var args: Args = [login.hostname, login.httpRealm, login.username]
let sql: String
if login.formSubmitURL == nil {
sql = primary + " AND formSubmitURL IS NULL"
} else if login.formSubmitURL!.isEmpty {
sql = primary
} else {
if let hostPort = login.formSubmitURL?.asURL?.hostPort {
// Substring check will suffice for now. TODO: proper host/port check after fetching the cursor.
sql = primary + " AND (formSubmitURL = '' OR (instr(formSubmitURL, ?) > 0))"
args.append(hostPort)
} else {
log.warning("Incoming formSubmitURL is non-empty but is not a valid URL with a host. Not matching local.")
return deferMaybe(nil)
}
}
return self.db.runQuery(sql, args: args, factory: SQLiteLogins.LocalLoginFactory)
>>== { cursor in
switch (cursor.count) {
case 0:
return deferMaybe(nil)
case 1:
// Great!
return deferMaybe(cursor[0])
default:
// TODO: join against the mirror table to exclude local logins that
// already match a server record.
// Right now just take the first.
log.warning("Got \(cursor.count) local logins with matching details! This is most unexpected.")
return deferMaybe(cursor[0])
}
}
}
private func resolveConflictBetween(local local: LocalLogin, upstream: ServerLogin, shared: Login) -> Success {
// Attempt to compute two delta sets by comparing each new record to the shared record.
// Then we can merge the two delta sets -- either perfectly or by picking a winner in the case
// of a true conflict -- and produce a resultant record.
let localDeltas = (local.localModified, local.deltas(from: shared))
let upstreamDeltas = (upstream.serverModified, upstream.deltas(from: shared))
let mergedDeltas = Login.mergeDeltas(a: localDeltas, b: upstreamDeltas)
// Not all Sync clients handle the optional timestamp fields introduced in Bug 555755.
// We might get a server record with no timestamps, and it will differ from the original
// mirror!
// We solve that by refusing to generate deltas that discard information. We'll preserve
// the local values -- either from the local record or from the last shared parent that
// still included them -- and propagate them back to the server.
// It's OK for us to reconcile and reupload; it causes extra work for every client, but
// should not cause looping.
let resultant = shared.applyDeltas(mergedDeltas)
// We can immediately write the downloaded upstream record -- the old one -- to
// the mirror store.
// We then apply this record to the local store, and mark it as needing upload.
// When the reconciled record is uploaded, it'll be flushed into the mirror
// with the correct modified time.
return self.updateMirrorToLogin(upstream, fromPrevious: shared)
>>> { self.storeReconciledLogin(resultant) }
}
private func resolveConflictWithoutParentBetween(local local: LocalLogin, upstream: ServerLogin) -> Success {
// Do the best we can. Either the local wins and will be
// uploaded, or the remote wins and we delete our overlay.
if local.timePasswordChanged > upstream.timePasswordChanged {
log.debug("Conflicting records with no shared parent. Using newer local record.")
return self.insertNewMirror(upstream, isOverridden: 1)
}
log.debug("Conflicting records with no shared parent. Using newer remote record.")
let args: Args = [local.guid]
return self.insertNewMirror(upstream, isOverridden: 0)
>>> { self.db.run("DELETE FROM \(TableLoginsLocal) WHERE guid = ?", withArgs: args) }
}
public func getModifiedLoginsToUpload() -> Deferred<Maybe<[Login]>> {
let sql =
"SELECT * FROM \(TableLoginsLocal) " +
"WHERE sync_status IS NOT \(SyncStatus.Synced.rawValue) AND is_deleted = 0"
// Swift 2.0: use Cursor.asArray directly.
return self.db.runQuery(sql, args: nil, factory: SQLiteLogins.LoginFactory)
>>== { deferMaybe($0.asArray()) }
}
public func getDeletedLoginsToUpload() -> Deferred<Maybe<[GUID]>> {
// There are no logins that are marked as deleted that were not originally synced --
// others are deleted immediately.
let sql =
"SELECT guid FROM \(TableLoginsLocal) " +
"WHERE is_deleted = 1"
// Swift 2.0: use Cursor.asArray directly.
return self.db.runQuery(sql, args: nil, factory: { return $0["guid"] as! GUID })
>>== { deferMaybe($0.asArray()) }
}
/**
* Chains through the provided timestamp.
*/
public func markAsSynchronized(guids: [GUID], modified: Timestamp) -> Deferred<Maybe<Timestamp>> {
// Update the mirror from the local record that we just uploaded.
// sqlite doesn't support UPDATE FROM, so instead of running 10 subqueries * n GUIDs,
// we issue a single DELETE and a single INSERT on the mirror, then throw away the
// local overlay that we just uploaded with another DELETE.
log.debug("Marking \(guids.count) GUIDs as synchronized.")
// TODO: transaction!
let args: Args = guids.map { $0 as AnyObject }
let inClause = BrowserDB.varlist(args.count)
let delMirror = "DELETE FROM \(TableLoginsMirror) WHERE guid IN \(inClause)"
let insMirror =
"INSERT OR IGNORE INTO \(TableLoginsMirror) (" +
" is_overridden, server_modified" +
", httpRealm, formSubmitURL, usernameField" +
", passwordField, timesUsed, timeLastUsed, timePasswordChanged, timeCreated" +
", password, hostname, username, guid" +
") SELECT 0, \(modified)" +
", httpRealm, formSubmitURL, usernameField" +
", passwordField, timesUsed, timeLastUsed, timePasswordChanged, timeCreated" +
", password, hostname, username, guid " +
"FROM \(TableLoginsLocal) " +
"WHERE guid IN \(inClause)"
let delLocal = "DELETE FROM \(TableLoginsLocal) WHERE guid IN \(inClause)"
return self.db.run(delMirror, withArgs: args)
>>> { self.db.run(insMirror, withArgs: args) }
>>> { self.db.run(delLocal, withArgs: args) }
>>> always(modified)
}
public func markAsDeleted(guids: [GUID]) -> Success {
log.debug("Marking \(guids.count) GUIDs as deleted.")
let args: Args = guids.map { $0 as AnyObject }
let inClause = BrowserDB.varlist(args.count)
return self.db.run("DELETE FROM \(TableLoginsMirror) WHERE guid IN \(inClause)", withArgs: args)
>>> { self.db.run("DELETE FROM \(TableLoginsLocal) WHERE guid IN \(inClause)", withArgs: args) }
}
public func hasSyncedLogins() -> Deferred<Maybe<Bool>> {
let checkLoginsMirror = "SELECT 1 FROM \(TableLoginsMirror)"
let checkLoginsLocal = "SELECT 1 FROM \(TableLoginsLocal) WHERE sync_status IS NOT \(SyncStatus.New.rawValue)"
let sql = "\(checkLoginsMirror) UNION ALL \(checkLoginsLocal)"
return self.db.queryReturnsResults(sql)
}
}
extension SQLiteLogins: ResettableSyncStorage {
/**
* Clean up any metadata.
* TODO: is this safe for a regular reset? It forces a content-based merge.
*/
public func resetClient() -> Success {
// Clone all the mirrors so we don't lose data.
return self.cloneMirrorToOverlay(whereClause: nil, args: nil)
// Drop all of the mirror data.
>>> { self.db.run("DELETE FROM \(TableLoginsMirror)") }
// Mark all of the local data as new.
>>> { self.db.run("UPDATE \(TableLoginsLocal) SET sync_status = \(SyncStatus.New.rawValue)") }
}
}
extension SQLiteLogins: AccountRemovalDelegate {
public func onRemovedAccount() -> Success {
return self.resetClient()
}
}
|
ec5c809be8f2dc0af9a7c745c541e2ad
| 42.104418 | 204 | 0.61092 | false | false | false | false |
yarshure/Surf
|
refs/heads/UIKitForMac
|
Surf/CountrySelectController.swift
|
bsd-3-clause
|
1
|
//
// CountrySelectController.swift
// Surf
//
// Created by yarshure on 16/2/22.
// Copyright © 2016年 yarshure. All rights reserved.
//
import UIKit
protocol CountryDelegate:class {
func countrySelected(controller: CountrySelectController, code:String)//
}
class CountrySelectController: SFTableViewController {
var list:[String] = []
weak var delegate:CountryDelegate?
//var code:String!
func loadCountrys(){
let path = Bundle.main.path(forResource: "ISO_3166.txt", ofType: nil)
do {
let str = try String.init(contentsOfFile: path!, encoding: .utf8)
list = str.components(separatedBy: "\n")
}catch let error {
alertMessageAction("\(error.localizedDescription)",complete: nil)
}
}
override func viewDidLoad() {
self.title = "Select Country"
loadCountrys()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return list.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
cell.textLabel?.text = list[indexPath.row]
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
self.delegate?.countrySelected(controller: self, code: list[indexPath.row])
_ = self.navigationController?.popViewController(animated: true)
}
}
|
60369e27489dade238039a69a58d7c58
| 34.528302 | 109 | 0.667552 | false | false | false | false |
RayTW/Swift8ComicSDK
|
refs/heads/master
|
Pods/Swift8ComicSDK/Swift8ComicSDK/Classes/StringUtility.swift
|
mit
|
2
|
//
// File.swift
// Pods
//
// Created by ray.lee on 2017/6/12.
//
//
import Foundation
open class StringUtility{
open static let ENCODE_BIG5 = CFStringConvertEncodingToNSStringEncoding(CFStringEncoding(CFStringEncodings.big5_HKSCS_1999.rawValue))
open static let ENCODE_GB2312 = CFStringConvertEncodingToNSStringEncoding(CFStringEncoding(CFStringEncodings.GB_18030_2000.rawValue))
public init() {
}
open class func count(_ source : String) -> Int{
return source.characters.count
}
open class func indexOf(source : String, search : String) -> Range<String.Index>?{
return source.range(of: search)
}
open class func lastIndexOf( source : String, target: String) -> Int {
let ret = source.range(of: target, options: .backwards)
if( ret != nil){
let result = source.characters.distance(from: source.characters.startIndex, to: (ret?.lowerBound)!)
return result
}
return -1
}
open class func indexOfInt(_ source : String, _ search : String) -> Int{
let range = source.range(of: search)
let result = source.characters.distance(from: source.characters.startIndex, to: (range?.lowerBound)!)
return result;
}
open class func indexOfUpper(source : String, search : String) -> String.Index?{
let range = source.range(of: search)
guard range != nil else {
return nil
}
return range?.upperBound;
}
open class func indexOfLower(source : String, search : String) -> String.Index?{
let range = source.range(of: search)
guard range != nil else {
return nil
}
return range?.lowerBound;
}
open class func substring(source : String, upper : String.Index, lower : String.Index) -> String{
let range = upper ..< lower
return String(source[range])
}
open class func substring(_ source : String,_ upperString : String,_ lowerString : String ) -> String?{
let upper : String.Index? = indexOfUpper(source: source, search: upperString)
let lower : String.Index? = indexOfLower(source: source, search: lowerString)
if(upper != nil && lower != nil){
let range = upper! ..< lower!
return String(source[range])
}
return nil
}
open class func lastSubstring(_ source : String,_ upperString : String,_ lowerString : String ) -> String?{
let upperIndex = lastIndexOf(source: source, target: upperString)
let lowerIndex = lastIndexOf(source: source, target: lowerString)
if(upperIndex != -1 && lowerIndex != -1){
return substring(source, upperIndex + upperString.characters.count, lowerIndex)
}
return nil
}
open class func substring(source : String, beginIndex : String.Index) -> String{
return String(source[beginIndex...])
//source.substring(from: beginIndex)
}
//like JAVA String.substring(beginIndex, endIndex)
open class func substring(_ source : String, _ beginIndex : Int, _ endIndex : Int ) -> String{
let subLen : Int = endIndex - beginIndex
if(subLen < 0){
return ""
}
let beginInx = source.index(source.startIndex, offsetBy: beginIndex)
let endInx = source.index(source.startIndex, offsetBy: endIndex)
let range = beginInx ..< endInx
return String(source[range])
}
open class func dataToStringBig5(data : Data) -> String{
let string = NSString.init(data: data, encoding: ENCODE_BIG5)
return string! as String;
}
open class func dataToStringGB2312(data : Data) -> String{
let string = NSString.init(data: data, encoding: ENCODE_GB2312)
return string! as String;
}
open class func split(_ source : String, separatedBy : String) -> [String]{
return source.components(separatedBy: separatedBy)
}
open class func trim(_ source : String) -> String{
return source.trimmingCharacters(in: .whitespaces)
}
open class func replace(_ source : String, _ of : String,_ with : String) -> String{
return source.replacingOccurrences(of: of, with: with)
}
open class func urlEncodeUsingBIG5(_ source : String) -> String{
return urlEncode(source, ENCODE_BIG5)
}
open class func urlEncodeUsingGB2312(_ source : String) -> String{
return urlEncode(source, ENCODE_GB2312)
}
open class func urlEncode(_ source : String,_ encode: UInt) -> String{
let encodeUrlString = source.data(using: String.Encoding(rawValue: encode), allowLossyConversion: true)
return encodeUrlString!.hexEncodedString()
}
}
extension Data {
func hexEncodedString() -> String {
return map { String(format: "%%%02hhX", $0) }.joined()
}
}
|
3a0204c499ebafb3ce4e45f8f60ad742
| 31.443038 | 137 | 0.602224 | false | false | false | false |
pinterest/PINCache
|
refs/heads/master
|
Carthage/Checkouts/PINCache/Carthage/Checkouts/PINOperation/Example/PINOperationExample/AppDelegate.swift
|
apache-2.0
|
4
|
//
// AppDelegate.swift
// PINOperationExample
//
// Created by Martin Púčik on 02/05/2020.
// Copyright © 2020 Pinterest. All rights reserved.
//
import UIKit
@UIApplicationMain
final class AppDelegate: UIResponder, UIApplicationDelegate {
private let queue: PINOperationQueue = PINOperationQueue(maxConcurrentOperations: 5)
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
let operationCount = 100
let group = DispatchGroup()
for _ in 0..<operationCount {
group.enter()
queue.scheduleOperation({
group.leave()
}, with: .default)
}
let success = group.wait(timeout: .now() + 20)
if success != .success {
fatalError("Timed out before completing 100 operations")
}
return true
}
}
|
31ce758508ab6a83542f4b62355d80e2
| 28.709677 | 145 | 0.643865 | false | false | false | false |
ubclaunchpad/RocketCast
|
refs/heads/master
|
RocketCast/EpisodeHeaderTableViewCell.swift
|
mit
|
1
|
//
// EpisodeHeaderTableViewCell.swift
// RocketCast
//
// Created by Milton Leung on 2016-11-08.
// Copyright © 2016 UBCLaunchPad. All rights reserved.
//
import UIKit
class EpisodeHeaderTableViewCell: UITableViewCell {
@IBOutlet weak var podcastTitle: UILabel!
@IBOutlet weak var podcastAuthor: UILabel!
@IBOutlet weak var podcastSummary: UILabel!
@IBOutlet weak var coverPhotoView: UIView!
var listOfEpisodes = [Episode]()
var podcast: Podcast! {
didSet {
setupPodcastInfo()
}
}
func setupPodcastInfo() {
let effectsLayer = coverPhotoView.layer
effectsLayer.cornerRadius = 18
effectsLayer.shadowColor = UIColor.black.cgColor
effectsLayer.shadowOffset = CGSize(width: 0, height: 0)
effectsLayer.shadowRadius = 4
effectsLayer.shadowOpacity = 0.4
effectsLayer.shadowPath = UIBezierPath(roundedRect: coverPhotoView.bounds, cornerRadius: coverPhotoView.layer.cornerRadius).cgPath
podcastTitle.text = podcast.title
podcastAuthor.text = podcast.author
podcastSummary.text = podcast.summary
let url = URL(string: (podcast.imageURL)!)
DispatchQueue.global().async {
do {
let data = try Data(contentsOf: url!)
let coverPhoto = UIImageView()
coverPhoto.frame = self.coverPhotoView.bounds
coverPhoto.layer.cornerRadius = 18
coverPhoto.layer.masksToBounds = true
DispatchQueue.main.async {
coverPhoto.image = UIImage(data: data)
self.coverPhotoView.addSubview(coverPhoto)
}
} catch let error as NSError{
Log.error("Error: " + error.debugDescription)
}
}
}
}
|
f7bda305d45322eb24aa864f16738062
| 32.428571 | 138 | 0.612714 | false | false | false | false |
mortorqrobotics/MorTeam-ios
|
refs/heads/master
|
MorTeam/User.swift
|
mit
|
1
|
//
// User.swift
// MorTeam
//
// Created by arvin zadeh on 10/1/16.
// Copyright © 2016 MorTorq. All rights reserved.
//
import Foundation
class User {
let _id: String
let firstname: String
let lastname: String
let username: String
let email: String
let phone: String
let position: String
let team: String?
let profPicPath: String
let groups: [String]? //maybe populate later, how to make optional
init(userJSON: JSON){
var allGroupIds = [String]()
self._id = String( describing: userJSON["_id"] )
self.firstname = String( describing: userJSON["firstname"] )
self.lastname = String( describing: userJSON["lastname"] )
self.username = String( describing: userJSON["username"] )
self.position = String( describing: userJSON["position"] )
self.team = String( describing: userJSON["team"] )
self.email = String( describing: userJSON["email"] )
self.phone = String( describing: userJSON["phone"] )
self.profPicPath = String( describing: userJSON["profpicpath"] )
for(_, json):(String, JSON) in userJSON["groups"] {
allGroupIds.append(String(describing: json))
}
self.groups = allGroupIds
}
init(_id: String, firstname: String, lastname: String, username: String, email: String, phone: String, profPicPath: String, team: String, position: String){
self._id = _id
self.firstname = firstname
self.lastname = lastname
self.username = username
self.team = team
self.email = email
self.position = position
self.phone = phone
self.profPicPath = profPicPath
self.groups = [String]() //hmm
}
}
|
c96d1ad86c8b918edb51d319573dfde4
| 33.196078 | 160 | 0.62328 | false | false | false | false |
abeschneider/stem
|
refs/heads/master
|
Sources/Op/TanhOp.swift
|
mit
|
1
|
//
// tanh.swift
// stem
//
// Created by Schneider, Abraham R. on 11/12/16.
// Copyright © 2016 none. All rights reserved.
//
import Foundation
import Tensor
open class TanhOp<S:Storage>: Op<S> where S.ElementType:FloatNumericType {
var _input:Tensor<S> { return inputs[0].output }
public init() {
super.init(inputs: ["input"], outputs: ["output"])
outputs["output"] = [Tensor<S>()]
setAction("input", action: self.inputSet)
}
public init(size:Int) {
super.init(inputs: ["input"], outputs: ["output"])
outputs["output"] = [Tensor<S>(Extent(size))]
setAction("input", action: self.inputSet)
}
// required for Copyable
public required init(op:Op<S>, shared:Bool) {
super.init(inputs: ["input"], outputs: ["output"])
outputs["output"] = [Tensor<S>(op.output.shape)]
}
func inputSet(_ label:String, input:[Source<S>]) {
setInput(to: input[0])
output.resize(input[0].output.shape)
}
open override func apply() {
tanh(_input, output: output)
}
}
open class TanhGrad<S:Storage>: Op<S>, Gradient where S.ElementType:FloatNumericType {
public typealias OpType = TanhOp<S>
open var _tanh:Tensor<S> { return inputs[0].output }
open var _input:Tensor<S> { return inputs[1].output }
open var _gradOutput:Tensor<S> { return inputs[2].output }
public required init(op:TanhOp<S>) {
let input:Source<S> = op.inputs[0]
super.init(inputs: ["op", "input", "gradOutput"], outputs: ["output"])
connect(from: op, "output", to: self, "op")
connect(from: input.op!, "output", to: self, "input")
output = Tensor<S>(op.output.shape)
}
public init(size:Int) {
super.init(inputs: ["op", "input", "gradOutput"], outputs: ["output"])
output = Tensor<S>(Extent(size))
}
public init(op:TanhOp<S>, input:Op<S>, gradInput:Op<S>) {
super.init(inputs: ["op", "input", "gradOutput"], outputs: ["output"])
connect(from: op, "output", to: self, "op")
connect(from: input, "output", to: self, "input")
connect(from: gradInput, to: self, "gradOutput")
output = Tensor<S>(op.output.shape)
}
required public init(op: Op<S>, shared: Bool) {
fatalError("init(op:shared:) has not been implemented")
}
/*
dtanh(x)/dx = (1 - tanh^2 x)*dx
*/
open override func apply() {
let result = _tanh * _tanh
result *= -1
add(S.ElementType(1.0), result, result: result)
result *= _gradOutput
output += result
}
open override func reset() {
fill(output, value: 0)
}
}
extension TanhOp: Differentiable {
public func gradient() -> GradientType {
return TanhGrad<S>(op: self)
}
}
|
c96f2fea6877b42fef13a37465c00de3
| 28.07 | 86 | 0.570003 | false | false | false | false |
einsteinx2/iSub
|
refs/heads/master
|
Carthage/Checkouts/XCGLogger/Sources/XCGLogger/Destinations/AutoRotatingFileDestination.swift
|
gpl-3.0
|
1
|
//
// AutoRotatingFileDestination.swift
// XCGLogger: https://github.com/DaveWoodCom/XCGLogger
//
// Created by Dave Wood on 2017-03-31.
// Copyright © 2017 Dave Wood, Cerebral Gardens.
// Some rights reserved: https://github.com/DaveWoodCom/XCGLogger/blob/master/LICENSE.txt
//
import Foundation
// MARK: - AutoRotatingFileDestination
/// A destination that outputs log details to files in a log folder, with auto-rotate options (by size or by time)
open class AutoRotatingFileDestination: FileDestination {
// MARK: - Constants
static let autoRotatingFileDefaultMaxFileSize: UInt64 = 1_048_576
static let autoRotatingFileDefaultMaxTimeInterval: TimeInterval = 600
// MARK: - Properties
/// Option: desired maximum size of a log file, if 0, no maximum (log files may exceed this, it's a guideline only)
open var targetMaxFileSize: UInt64 = autoRotatingFileDefaultMaxFileSize {
didSet {
if targetMaxFileSize < 1 {
targetMaxFileSize = .max
}
}
}
/// Option: desired maximum time in seconds stored in a log file, if 0, no maximum (log files may exceed this, it's a guideline only)
open var targetMaxTimeInterval: TimeInterval = autoRotatingFileDefaultMaxTimeInterval {
didSet {
if targetMaxTimeInterval < 1 {
targetMaxTimeInterval = 0
}
}
}
/// Option: the desired number of archived log files to keep (number of log files may exceed this, it's a guideline only)
open var targetMaxLogFiles: UInt8 = 10 {
didSet {
cleanUpLogFiles()
}
}
/// Option: the URL of the folder to store archived log files (defaults to the same folder as the initial log file)
open var archiveFolderURL: URL? = nil {
didSet {
guard let archiveFolderURL = archiveFolderURL else { return }
try? FileManager.default.createDirectory(at: archiveFolderURL, withIntermediateDirectories: true)
}
}
/// Option: an optional closure to execute whenever the log is auto rotated
open var autoRotationCompletion: ((_ success: Bool) -> Void)? = nil
/// A custom date formatter object to use as the suffix of archived log files
internal var _customArchiveSuffixDateFormatter: DateFormatter? = nil
/// The date formatter object to use as the suffix of archived log files
open var archiveSuffixDateFormatter: DateFormatter! {
get {
guard _customArchiveSuffixDateFormatter == nil else { return _customArchiveSuffixDateFormatter }
struct Statics {
static var archiveSuffixDateFormatter: DateFormatter = {
let defaultArchiveSuffixDateFormatter = DateFormatter()
defaultArchiveSuffixDateFormatter.locale = NSLocale.current
defaultArchiveSuffixDateFormatter.dateFormat = "_yyyy-MM-dd_HHmmss"
return defaultArchiveSuffixDateFormatter
}()
}
return Statics.archiveSuffixDateFormatter
}
set {
_customArchiveSuffixDateFormatter = newValue
}
}
/// Size of the current log file
internal var currentLogFileSize: UInt64 = 0
/// Start time of the current log file
internal var currentLogStartTimeInterval: TimeInterval = 0
/// The base file name of the log file
internal var baseFileName: String = "xcglogger"
/// The extension of the log file name
internal var fileExtension: String = "log"
// MARK: - Class Properties
/// A default folder for storing archived logs if one isn't supplied
open class var defaultLogFolderURL: URL {
#if os(OSX)
let defaultLogFolderURL = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent("log")
try? FileManager.default.createDirectory(at: defaultLogFolderURL, withIntermediateDirectories: true)
return defaultLogFolderURL
#elseif os(iOS) || os(tvOS) || os(watchOS)
let urls = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask)
let defaultLogFolderURL = urls[urls.endIndex - 1].appendingPathComponent("log")
try? FileManager.default.createDirectory(at: defaultLogFolderURL, withIntermediateDirectories: true)
return defaultLogFolderURL
#endif
}
// MARK: - Life Cycle
public init(owner: XCGLogger? = nil, writeToFile: Any, identifier: String = "", shouldAppend: Bool = false, appendMarker: String? = "-- ** ** ** --", attributes: [String: Any]? = nil, maxFileSize: UInt64 = autoRotatingFileDefaultMaxFileSize, maxTimeInterval: TimeInterval = autoRotatingFileDefaultMaxTimeInterval, archiveSuffixDateFormatter: DateFormatter? = nil) {
super.init(owner: owner, writeToFile: writeToFile, identifier: identifier, shouldAppend: true, appendMarker: shouldAppend ? appendMarker : nil, attributes: attributes)
currentLogStartTimeInterval = Date().timeIntervalSince1970
self.archiveSuffixDateFormatter = archiveSuffixDateFormatter
self.shouldAppend = shouldAppend
self.targetMaxFileSize = maxFileSize
self.targetMaxTimeInterval = maxTimeInterval
guard let writeToFileURL = writeToFileURL else { return }
// Calculate some details for naming archived logs based on the current log file path/name
fileExtension = writeToFileURL.pathExtension
baseFileName = writeToFileURL.lastPathComponent
if let fileExtensionRange: Range = baseFileName.range(of: ".\(fileExtension)", options: .backwards),
fileExtensionRange.upperBound >= baseFileName.endIndex {
baseFileName = baseFileName[baseFileName.startIndex ..< fileExtensionRange.lowerBound]
}
let filePath: String = writeToFileURL.path
let logFileName: String = "\(baseFileName).\(fileExtension)"
if let logFileNameRange: Range = filePath.range(of: logFileName, options: .backwards),
logFileNameRange.upperBound >= filePath.endIndex {
let archiveFolderPath: String = filePath[filePath.startIndex ..< logFileNameRange.lowerBound]
archiveFolderURL = URL(fileURLWithPath: "\(archiveFolderPath)")
}
if archiveFolderURL == nil {
archiveFolderURL = type(of: self).defaultLogFolderURL
}
do {
// Initialize starting values for file size and start time so shouldRotate calculations are valid
let fileAttributes: [FileAttributeKey: Any] = try FileManager.default.attributesOfItem(atPath: filePath)
currentLogFileSize = fileAttributes[.size] as? UInt64 ?? 0
currentLogStartTimeInterval = (fileAttributes[.creationDate] as? Date ?? Date()).timeIntervalSince1970
}
catch let error as NSError {
owner?._logln("Unable to determine current file attributes of log file: \(error.localizedDescription)", level: .warning)
}
// Because we always start by appending, regardless of the shouldAppend setting, we now need to handle the cases where we don't want to append or that we have now reached the rotation threshold for our current log file
if !shouldAppend || shouldRotate() {
rotateFile()
}
}
/// Scan the log folder and delete log files that are no longer relevant.
///
/// - Parameters: None.
///
/// - Returns: Nothing.
///
open func cleanUpLogFiles() {
var archivedFileURLs: [URL] = self.archivedFileURLs()
guard archivedFileURLs.count > Int(targetMaxLogFiles) else { return }
archivedFileURLs.removeFirst(Int(targetMaxLogFiles))
let fileManager: FileManager = FileManager.default
for archivedFileURL in archivedFileURLs {
do {
try fileManager.removeItem(at: archivedFileURL)
}
catch let error as NSError {
owner?._logln("Unable to delete old archived log file \(archivedFileURL.path): \(error.localizedDescription)", level: .error)
}
}
}
/// Delete all archived log files.
///
/// - Parameters: None.
///
/// - Returns: Nothing.
///
open func purgeArchivedLogFiles() {
let fileManager: FileManager = FileManager.default
for archivedFileURL in archivedFileURLs() {
do {
try fileManager.removeItem(at: archivedFileURL)
}
catch let error as NSError {
owner?._logln("Unable to delete old archived log file \(archivedFileURL.path): \(error.localizedDescription)", level: .error)
}
}
}
/// Get the URLs of the archived log files.
///
/// - Parameters: None.
///
/// - Returns: An array of file URLs pointing to previously archived log files, sorted with the most recent logs first.
///
open func archivedFileURLs() -> [URL] {
let archiveFolderURL: URL = (self.archiveFolderURL ?? type(of: self).defaultLogFolderURL)
guard let fileURLs = try? FileManager.default.contentsOfDirectory(at: archiveFolderURL, includingPropertiesForKeys: nil, options: [.skipsHiddenFiles]) else { return [] }
guard let identifierData: Data = identifier.data(using: .utf8) else { return [] }
var archivedDetails: [(url: URL, timestamp: String)] = []
for fileURL in fileURLs {
guard let archivedLogIdentifierOptionalData = try? fileURL.extendedAttribute(forName: XCGLogger.Constants.extendedAttributeArchivedLogIdentifierKey) else { continue }
guard let archivedLogIdentifierData = archivedLogIdentifierOptionalData else { continue }
guard archivedLogIdentifierData == identifierData else { continue }
guard let timestampOptionalData = try? fileURL.extendedAttribute(forName: XCGLogger.Constants.extendedAttributeArchivedLogTimestampKey) else { continue }
guard let timestampData = timestampOptionalData else { continue }
guard let timestamp = String(data: timestampData, encoding: .utf8) else { continue }
archivedDetails.append((fileURL, timestamp))
}
archivedDetails.sort(by: { (lhs, rhs) -> Bool in lhs.timestamp > rhs.timestamp })
var archivedFileURLs: [URL] = []
for archivedDetail in archivedDetails {
archivedFileURLs.append(archivedDetail.url)
}
return archivedFileURLs
}
/// Rotate the current log file.
///
/// - Parameters: None.
///
/// - Returns: Nothing.
///
open func rotateFile() {
var archiveFolderURL: URL = (self.archiveFolderURL ?? type(of: self).defaultLogFolderURL)
archiveFolderURL = archiveFolderURL.appendingPathComponent("\(baseFileName)\(archiveSuffixDateFormatter.string(from: Date()))")
archiveFolderURL = archiveFolderURL.appendingPathExtension(fileExtension)
rotateFile(to: archiveFolderURL, closure: autoRotationCompletion)
currentLogStartTimeInterval = Date().timeIntervalSince1970
currentLogFileSize = 0
cleanUpLogFiles()
}
/// Determine if the log file should be rotated.
///
/// - Parameters: None.
///
/// - Returns:
/// - true: The log file should be rotated.
/// - false: The log file doesn't have to be rotated.
///
open func shouldRotate() -> Bool {
// Do not rotate until critical setup has been completed so that we do not accidentally rotate once to the defaultLogFolderURL before determining the desired log location
guard archiveFolderURL != nil else { return false }
// File Size
guard currentLogFileSize < targetMaxFileSize else { return true }
// Time Interval, zero = never rotate
guard targetMaxTimeInterval > 0 else { return false }
// Time Interval, else check time
guard Date().timeIntervalSince1970 - currentLogStartTimeInterval < targetMaxTimeInterval else { return true }
return false
}
// MARK: - Overridden Methods
/// Write the log to the log file.
///
/// - Parameters:
/// - message: Formatted/processed message ready for output.
///
/// - Returns: Nothing
///
open override func write(message: String) {
currentLogFileSize += UInt64(message.characters.count)
super.write(message: message)
if shouldRotate() {
rotateFile()
}
}
}
|
1bd485918fdd643f729b38492cc03517
| 43.178947 | 369 | 0.662219 | false | false | false | false |
renshu16/DouyuSwift
|
refs/heads/master
|
DouyuSwift/DouyuSwift/Classes/Main/View/PageContentView.swift
|
mit
|
1
|
//
// PageContentView.swift
// DouyuSwift
//
// Created by ToothBond on 16/11/10.
// Copyright © 2016年 ToothBond. All rights reserved.
//
import UIKit
protocol PageContentViewDelegate : class{
func pageContentView(_ contentView : PageContentView, progress : CGFloat, startIndex : Int, targetIndex : Int);
}
private let CollectionCellIdentify : String = "ccIdentify"
class PageContentView: UIView {
fileprivate var childVCs : [UIViewController]
fileprivate var parentViewController : UIViewController
fileprivate var orginScrollX : CGFloat = 0
weak var delegate : PageContentViewDelegate?
fileprivate var isScrollFromClick : Bool = false
fileprivate lazy var collectionView : UICollectionView = {
let layout = UICollectionViewFlowLayout()
layout.itemSize = self.bounds.size
layout.minimumLineSpacing = 0
layout.minimumInteritemSpacing = 0
layout.scrollDirection = .horizontal
let collectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: layout)
collectionView.showsHorizontalScrollIndicator = false
collectionView.isPagingEnabled = true
collectionView.bounces = false
collectionView.dataSource = self
collectionView.delegate = self
collectionView.scrollsToTop = false
collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: CollectionCellIdentify)
return collectionView
}()
init(frame: CGRect, childVCs : [UIViewController], parentViewController: UIViewController) {
self.childVCs = childVCs
self.parentViewController = parentViewController
super.init(frame: frame)
setupUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
extension PageContentView {
fileprivate func setupUI() {
for child in childVCs {
parentViewController.addChildViewController(child)
}
collectionView.frame = self.bounds
addSubview(collectionView)
}
}
extension PageContentView : UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return childVCs.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: CollectionCellIdentify, for: indexPath)
let childVC = childVCs[indexPath.item]
for view in cell.contentView.subviews {
view.removeFromSuperview()
}
childVC.view.frame = cell.contentView.bounds
cell.contentView.addSubview(childVC.view)
return cell
}
}
extension PageContentView : UICollectionViewDelegate {
func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
isScrollFromClick = false
orginScrollX = scrollView.contentOffset.x
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
if isScrollFromClick {
return
}
//判断是左滑 or 右滑
let currentOffsetX = scrollView.contentOffset.x
let scrollViewW = scrollView.bounds.width;
var progress : CGFloat = 0
var startIndex : Int = 0
var targetIndex : Int = 0
if currentOffsetX > orginScrollX {
//左滑
progress = currentOffsetX / scrollViewW - floor(currentOffsetX/scrollViewW)
startIndex = Int(currentOffsetX / scrollViewW)
targetIndex = startIndex + 1
if targetIndex >= childVCs.count {
targetIndex = childVCs.count - 1
}
if currentOffsetX - orginScrollX == scrollViewW {
progress = 1
targetIndex = startIndex
}
} else {
//右滑
progress = (orginScrollX - currentOffsetX)/scrollViewW
targetIndex = Int(currentOffsetX / scrollViewW)
startIndex = targetIndex + 1
if startIndex < 0 {
startIndex = 0
}
if startIndex >= childVCs.count {
startIndex = childVCs.count - 1
}
if orginScrollX - currentOffsetX == scrollViewW {
progress = 1
startIndex = targetIndex
}
}
// print("progress = \(progress); startIndex = \(startIndex); targetIndex = \(targetIndex)")
delegate?.pageContentView(self, progress: progress, startIndex: startIndex, targetIndex: targetIndex)
}
}
extension PageContentView {
func setCurrentIndex(_ currentIndex:Int) {
isScrollFromClick = true
let offsetX = CGFloat(currentIndex) * collectionView.frame.width
collectionView.setContentOffset(CGPoint(x: offsetX, y:0), animated: false)
}
}
|
3b7fe59cff0c4a249e65ad76cd6c7e96
| 31.730769 | 121 | 0.632785 | false | false | false | false |
chromium/chromium
|
refs/heads/main
|
tensorflow_lite_support/ios/test/task/vision/image_segmenter/TFLImageSegmenterTests.swift
|
apache-2.0
|
9
|
/* Copyright 2022 The TensorFlow Authors. 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 GMLImageUtils
import XCTest
@testable import TFLImageSegmenter
class ImageSegmenterTests: XCTestCase {
static let bundle = Bundle(for: ImageSegmenterTests.self)
static let modelPath = bundle.path(
forResource: "deeplabv3",
ofType: "tflite")
// The maximum fraction of pixels in the candidate mask that can have a
// different class than the golden mask for the test to pass.
let kGoldenMaskTolerance: Float = 1e-2
// Magnification factor used when creating the golden category masks to make
// them more human-friendly. Each pixel in the golden masks has its value
// multiplied by this factor, i.e. a value of 10 means class index 1, a value of
// 20 means class index 2, etc.
let kGoldenMaskMagnificationFactor: UInt8 = 10
let deepLabV3SegmentationWidth = 257
let deepLabV3SegmentationHeight = 257
func verifyDeeplabV3PartialSegmentationResult(_ coloredLabels: [ColoredLabel]) {
self.verifyColoredLabel(
coloredLabels[0],
expectedR: 0,
expectedG: 0,
expectedB: 0,
expectedLabel: "background")
self.verifyColoredLabel(
coloredLabels[1],
expectedR: 128,
expectedG: 0,
expectedB: 0,
expectedLabel: "aeroplane")
self.verifyColoredLabel(
coloredLabels[2],
expectedR: 0,
expectedG: 128,
expectedB: 0,
expectedLabel: "bicycle")
self.verifyColoredLabel(
coloredLabels[3],
expectedR: 128,
expectedG: 128,
expectedB: 0,
expectedLabel: "bird")
self.verifyColoredLabel(
coloredLabels[4],
expectedR: 0,
expectedG: 0,
expectedB: 128,
expectedLabel: "boat")
self.verifyColoredLabel(
coloredLabels[5],
expectedR: 128,
expectedG: 0,
expectedB: 128,
expectedLabel: "bottle")
self.verifyColoredLabel(
coloredLabels[6],
expectedR: 0,
expectedG: 128,
expectedB: 128,
expectedLabel: "bus")
self.verifyColoredLabel(
coloredLabels[7],
expectedR: 128,
expectedG: 128,
expectedB: 128,
expectedLabel: "car")
self.verifyColoredLabel(
coloredLabels[8],
expectedR: 64,
expectedG: 0,
expectedB: 0,
expectedLabel: "cat")
self.verifyColoredLabel(
coloredLabels[9],
expectedR: 192,
expectedG: 0,
expectedB: 0,
expectedLabel: "chair")
self.verifyColoredLabel(
coloredLabels[10],
expectedR: 64,
expectedG: 128,
expectedB: 0,
expectedLabel: "cow")
self.verifyColoredLabel(
coloredLabels[11],
expectedR: 192,
expectedG: 128,
expectedB: 0,
expectedLabel: "dining table")
self.verifyColoredLabel(
coloredLabels[12],
expectedR: 64,
expectedG: 0,
expectedB: 128,
expectedLabel: "dog")
self.verifyColoredLabel(
coloredLabels[13],
expectedR: 192,
expectedG: 0,
expectedB: 128,
expectedLabel: "horse")
self.verifyColoredLabel(
coloredLabels[14],
expectedR: 64,
expectedG: 128,
expectedB: 128,
expectedLabel: "motorbike")
self.verifyColoredLabel(
coloredLabels[15],
expectedR: 192,
expectedG: 128,
expectedB: 128,
expectedLabel: "person")
self.verifyColoredLabel(
coloredLabels[16],
expectedR: 0,
expectedG: 64,
expectedB: 0,
expectedLabel: "potted plant")
self.verifyColoredLabel(
coloredLabels[17],
expectedR: 128,
expectedG: 64,
expectedB: 0,
expectedLabel: "sheep")
self.verifyColoredLabel(
coloredLabels[18],
expectedR: 0,
expectedG: 192,
expectedB: 0,
expectedLabel: "sofa")
self.verifyColoredLabel(
coloredLabels[19],
expectedR: 128,
expectedG: 192,
expectedB: 0,
expectedLabel: "train")
self.verifyColoredLabel(
coloredLabels[20],
expectedR: 0,
expectedG: 64,
expectedB: 128,
expectedLabel: "tv")
}
func verifyColoredLabel(
_ coloredLabel: ColoredLabel,
expectedR: UInt,
expectedG: UInt,
expectedB: UInt,
expectedLabel: String
) {
XCTAssertEqual(
coloredLabel.r,
expectedR)
XCTAssertEqual(
coloredLabel.g,
expectedG)
XCTAssertEqual(
coloredLabel.b,
expectedB)
XCTAssertEqual(
coloredLabel.label,
expectedLabel)
}
func testSuccessfullInferenceOnMLImageWithUIImage() throws {
let modelPath = try XCTUnwrap(ImageSegmenterTests.modelPath)
let imageSegmenterOptions = ImageSegmenterOptions(modelPath: modelPath)
let imageSegmenter =
try ImageSegmenter.segmenter(options: imageSegmenterOptions)
let gmlImage = try XCTUnwrap(
MLImage.imageFromBundle(
class: type(of: self),
filename: "segmentation_input_rotation0",
type: "jpg"))
let segmentationResult: SegmentationResult =
try XCTUnwrap(imageSegmenter.segment(mlImage: gmlImage))
XCTAssertEqual(segmentationResult.segmentations.count, 1)
let coloredLabels = try XCTUnwrap(segmentationResult.segmentations[0].coloredLabels)
verifyDeeplabV3PartialSegmentationResult(coloredLabels)
let categoryMask = try XCTUnwrap(segmentationResult.segmentations[0].categoryMask)
XCTAssertEqual(deepLabV3SegmentationWidth, categoryMask.width)
XCTAssertEqual(deepLabV3SegmentationHeight, categoryMask.height)
let goldenMaskImage = try XCTUnwrap(
MLImage.imageFromBundle(
class: type(of: self),
filename: "segmentation_golden_rotation0",
type: "png"))
let pixelBuffer = goldenMaskImage.grayScalePixelBuffer().takeRetainedValue()
CVPixelBufferLockBaseAddress(pixelBuffer, CVPixelBufferLockFlags.readOnly)
let pixelBufferBaseAddress = (try XCTUnwrap(CVPixelBufferGetBaseAddress(pixelBuffer)))
.assumingMemoryBound(to: UInt8.self)
let numPixels = deepLabV3SegmentationWidth * deepLabV3SegmentationHeight
let mask = try XCTUnwrap(categoryMask.mask)
var inconsistentPixels: Float = 0.0
for i in 0..<numPixels {
if mask[i] * kGoldenMaskMagnificationFactor != pixelBufferBaseAddress[i] {
inconsistentPixels += 1
}
}
CVPixelBufferUnlockBaseAddress(pixelBuffer, CVPixelBufferLockFlags.readOnly)
XCTAssertLessThan(inconsistentPixels / Float(numPixels), kGoldenMaskTolerance)
}
}
|
0064af46de696bbbb8c3bc8dd4d537db
| 25.563433 | 90 | 0.672707 | false | false | false | false |
beckjing/contacts
|
refs/heads/master
|
contacts/contacts/contact/View/JYCContactEditBasicInfoTableViewCell/JYCContactEditBasicInfoTableViewCell.swift
|
mit
|
1
|
//
// JYCContactEditBasicInfoTableViewCell.swift
// contacts
//
// Created by yuecheng on 24/06/2017.
// Copyright © 2017 yuecheng. All rights reserved.
//
import UIKit
import AddressBook
typealias openPhotoCallBack = () -> Void
class JYCContactEditBasicInfoTableViewCell: UITableViewCell, UITextFieldDelegate {
@IBOutlet weak var userImageButton: UIButton!
@IBOutlet weak var lastNameTextField: UITextField!
@IBOutlet weak var firstNameTextField: UITextField!
@IBOutlet weak var companyTextField: UITextField!
var record:JYCContactModel?
var originalHashValue:Int?
var openPhoto:openPhotoCallBack?
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
func configView(record:JYCContactModel) {
self.record = record
self.originalHashValue = record.hashValue
self.userImageButton.setBackgroundImage( record.userImage, for: UIControlState.normal)
if record.hasUserImage! {
self.userImageButton.setTitle("", for: UIControlState.normal)
}
else {
self.userImageButton.setTitle("添加\n照片", for: UIControlState.normal)
}
self.firstNameTextField.text = record.firstName
self.lastNameTextField.text = record.lastName
self.companyTextField.text = record.company
self.firstNameTextField.delegate = self
self.lastNameTextField.delegate = self
self.companyTextField.delegate = self
}
@IBAction func clickImageButton(_ sender: UIButton) {
if self.openPhoto != nil {
self.openPhoto!()
}
}
func textFieldDidEndEditing(_ textField: UITextField) {
if textField == self.firstNameTextField {
self.record?.firstName = textField.text
}
else if textField == self.lastNameTextField {
self.record?.lastName = textField.text
}
else if textField == self.companyTextField {
self.record?.company = textField.text
}
}
}
|
660c006adc4fc92d11578aef33ad53d4
| 29.972603 | 94 | 0.66077 | false | false | false | false |
ChristianKienle/highway
|
refs/heads/master
|
Sources/Task/Model/Termination.swift
|
mit
|
1
|
import Foundation
public struct Termination {
// MARK: - Types
public typealias Reason = Process.TerminationReason
// MARK: - Convenience
public static let success = Termination(reason: .exit, status: EXIT_SUCCESS)
public static let failure = Termination(reason: .exit, status: EXIT_FAILURE)
// MARK: - Init
public init(describing process: Process) {
self.init(reason: process.terminationReason, status: process.terminationStatus)
}
init(reason: Reason, status: Int32) {
self.reason = reason
self.status = status
}
// MARK: - Properties
public let reason: Reason
public let status: Int32
public var isSuccess: Bool { return status == EXIT_SUCCESS }
}
extension Termination: CustomStringConvertible, CustomDebugStringConvertible {
public var description: String {
return "[\(isSuccess ? "SUCCESS" : "ERROR")] Status: \(status), Reason: \(reason)"
}
public var debugDescription: String { return description }
}
extension Termination: Equatable {
public static func ==(lhs: Termination, rhs: Termination) -> Bool {
return lhs.status == rhs.status && lhs.reason == rhs.reason
}
}
extension Process.TerminationReason: CustomStringConvertible {
public var description: String {
switch self {
case .exit: return "Exited normally."
case .uncaughtSignal: return "Exited due to an uncaught signal."
}
}
}
|
ca4b16a81c77535f1262fe8007da40ca
| 30.869565 | 90 | 0.670532 | false | false | false | false |
wikimedia/apps-ios-wikipedia
|
refs/heads/twn
|
Wikipedia/Code/DescriptionWelcomePanelViewController.swift
|
mit
|
1
|
class DescriptionWelcomePanelViewController: UIViewController, Themeable {
private var theme = Theme.standard
func apply(theme: Theme) {
self.theme = theme
guard viewIfLoaded != nil else {
return
}
scrollViewGradientView.apply(theme: theme)
titleLabel.textColor = theme.colors.primaryText
bottomLabel.textColor = theme.colors.primaryText
nextButton.backgroundColor = theme.colors.link
}
@IBOutlet private var containerView:UIView!
@IBOutlet private var titleLabel:UILabel!
@IBOutlet private var bottomLabel:UILabel!
@IBOutlet private var nextButton:AutoLayoutSafeMultiLineButton!
@IBOutlet private var scrollView:UIScrollView!
@IBOutlet private var scrollViewGradientView:WelcomePanelScrollViewGradient!
@IBOutlet private var nextButtonContainerView:UIView!
private var viewControllerForContainerView:UIViewController? = nil
var pageType:DescriptionWelcomePageType = .intro
override func viewDidLoad() {
super.viewDidLoad()
apply(theme: theme)
embedContainerControllerView()
updateUIStrings()
// If the button itself was directly an arranged stackview subview we couldn't
// set padding contraints and also get clean collapsing when enabling isHidden.
nextButtonContainerView.isHidden = pageType != .exploration
view.wmf_configureSubviewsForDynamicType()
}
private func embedContainerControllerView() {
let containerController = DescriptionWelcomeContentsViewController.wmf_viewControllerFromDescriptionWelcomeStoryboard()
containerController.pageType = pageType
addChild(containerController)
containerView.wmf_addSubviewWithConstraintsToEdges(containerController.view)
containerController.apply(theme: theme)
containerController.didMove(toParent: self)
}
private func updateUIStrings(){
switch pageType {
case .intro:
titleLabel.text = WMFLocalizedString("description-welcome-descriptions-title", value:"Title descriptions", comment:"Title text explaining title descriptions")
case .exploration:
titleLabel.text = WMFLocalizedString("description-welcome-concise-title", value:"Keep it short", comment:"Title text explaining descriptions should be concise")
}
bottomLabel.text = CommonStrings.welcomePromiseTitle
nextButton.setTitle(WMFLocalizedString("description-welcome-start-editing-button", value:"Start editing", comment:"Text for button for dismissing description editing welcome screens"), for: .normal)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
if scrollView.wmf_contentSizeHeightExceedsBoundsHeight() {
scrollView.wmf_flashVerticalScrollIndicatorAfterDelay(1.5)
}
}
}
private extension UIScrollView {
func wmf_contentSizeHeightExceedsBoundsHeight() -> Bool {
return contentSize.height - bounds.size.height > 0
}
func wmf_flashVerticalScrollIndicatorAfterDelay(_ delay: TimeInterval) {
dispatchOnMainQueueAfterDelayInSeconds(delay) {
self.flashScrollIndicators()
}
}
}
class WelcomePanelScrollViewGradient : UIView, Themeable {
private var theme = Theme.standard
func apply(theme: Theme) {
self.theme = theme
layer.backgroundColor = theme.colors.midBackground.cgColor
}
private let fadeHeight = 6.0
private var normalizedFadeHeight: Double {
return bounds.size.height > 0 ? fadeHeight / Double(bounds.size.height) : 0
}
private lazy var gradientMask: CAGradientLayer = {
let mask = CAGradientLayer()
mask.startPoint = .zero
mask.endPoint = CGPoint(x: 0, y: 1)
mask.colors = [
UIColor.black.cgColor,
UIColor.clear.cgColor,
UIColor.clear.cgColor,
UIColor.black.cgColor
]
layer.mask = mask
return mask
}()
override func layoutSublayers(of layer: CALayer) {
super.layoutSublayers(of: layer)
guard layer == gradientMask.superlayer else {
assertionFailure("Unexpected superlayer")
return
}
gradientMask.locations = [ // Keep fade heights fixed to `fadeHeight` regardless of text view height
0.0,
NSNumber(value: normalizedFadeHeight), // upper stop
NSNumber(value: 1.0 - normalizedFadeHeight), // lower stop
1.0
]
gradientMask.frame = bounds
}
}
|
7a5dfd83652ab22a205d5174e41878f6
| 37.916667 | 206 | 0.682013 | false | false | false | false |
LYM-mg/MGDS_Swift
|
refs/heads/master
|
IQKeyboardManagerSwift/IQTextView/IQTextView.swift
|
mit
|
2
|
//
// IQTextView.swift
// https://github.com/hackiftekhar/IQKeyboardManager
// Copyright (c) 2013-20 Iftekhar Qurashi.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
/** @abstract UITextView with placeholder support */
@available(iOSApplicationExtension, unavailable)
@objc open class IQTextView: UITextView {
@objc required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
NotificationCenter.default.addObserver(self, selector: #selector(self.refreshPlaceholder), name: UITextView.textDidChangeNotification, object: self)
}
@objc override public init(frame: CGRect, textContainer: NSTextContainer?) {
super.init(frame: frame, textContainer: textContainer)
NotificationCenter.default.addObserver(self, selector: #selector(self.refreshPlaceholder), name: UITextView.textDidChangeNotification, object: self)
}
@objc override open func awakeFromNib() {
super.awakeFromNib()
NotificationCenter.default.addObserver(self, selector: #selector(self.refreshPlaceholder), name: UITextView.textDidChangeNotification, object: self)
}
deinit {
IQ_PlaceholderLabel.removeFromSuperview()
}
private var placeholderInsets: UIEdgeInsets {
return UIEdgeInsets(top: self.textContainerInset.top, left: self.textContainerInset.left + self.textContainer.lineFragmentPadding, bottom: self.textContainerInset.bottom, right: self.textContainerInset.right + self.textContainer.lineFragmentPadding)
}
private var placeholderExpectedFrame: CGRect {
let placeholderInsets = self.placeholderInsets
let maxWidth = self.frame.width-placeholderInsets.left-placeholderInsets.right
let expectedSize = IQ_PlaceholderLabel.sizeThatFits(CGSize(width: maxWidth, height: self.frame.height-placeholderInsets.top-placeholderInsets.bottom))
return CGRect(x: placeholderInsets.left, y: placeholderInsets.top, width: maxWidth, height: expectedSize.height)
}
lazy var IQ_PlaceholderLabel: UILabel = {
let label = UILabel()
label.autoresizingMask = [.flexibleWidth, .flexibleHeight]
label.lineBreakMode = .byWordWrapping
label.numberOfLines = 0
label.font = self.font
label.textAlignment = self.textAlignment
label.backgroundColor = UIColor.clear
label.isAccessibilityElement = false
#if swift(>=5.1)
label.textColor = UIColor.systemGray
#else
label.textColor = UIColor.lightText
#endif
label.alpha = 0
self.addSubview(label)
return label
}()
/** @abstract To set textView's placeholder text color. */
@IBInspectable open var placeholderTextColor: UIColor? {
get {
return IQ_PlaceholderLabel.textColor
}
set {
IQ_PlaceholderLabel.textColor = newValue
}
}
/** @abstract To set textView's placeholder text. Default is nil. */
@IBInspectable open var placeholder: String? {
get {
return IQ_PlaceholderLabel.text
}
set {
IQ_PlaceholderLabel.text = newValue
refreshPlaceholder()
}
}
/** @abstract To set textView's placeholder attributed text. Default is nil. */
open var attributedPlaceholder: NSAttributedString? {
get {
return IQ_PlaceholderLabel.attributedText
}
set {
IQ_PlaceholderLabel.attributedText = newValue
refreshPlaceholder()
}
}
@objc override open func layoutSubviews() {
super.layoutSubviews()
IQ_PlaceholderLabel.frame = placeholderExpectedFrame
}
@objc internal func refreshPlaceholder() {
if !text.isEmpty || !attributedText.string.isEmpty {
IQ_PlaceholderLabel.alpha = 0
} else {
IQ_PlaceholderLabel.alpha = 1
}
}
@objc override open var text: String! {
didSet {
refreshPlaceholder()
}
}
open override var attributedText: NSAttributedString! {
didSet {
refreshPlaceholder()
}
}
@objc override open var font: UIFont? {
didSet {
if let unwrappedFont = font {
IQ_PlaceholderLabel.font = unwrappedFont
} else {
IQ_PlaceholderLabel.font = UIFont.systemFont(ofSize: 12)
}
}
}
@objc override open var textAlignment: NSTextAlignment {
didSet {
IQ_PlaceholderLabel.textAlignment = textAlignment
}
}
@objc override weak open var delegate: UITextViewDelegate? {
get {
refreshPlaceholder()
return super.delegate
}
set {
super.delegate = newValue
}
}
@objc override open var intrinsicContentSize: CGSize {
guard !hasText else {
return super.intrinsicContentSize
}
var newSize = super.intrinsicContentSize
let placeholderInsets = self.placeholderInsets
newSize.height = placeholderExpectedFrame.height + placeholderInsets.top + placeholderInsets.bottom
return newSize
}
}
|
4bb04a0da89b4e3a74d394d75c76a82b
| 32.148148 | 257 | 0.669753 | false | false | false | false |
pennlabs/penn-mobile-ios
|
refs/heads/main
|
PennMobile/Dining/SwiftUI/Views/Venue/DiningVenueView.swift
|
mit
|
1
|
//
// DiningVenueView.swift
// PennMobile
//
// Created by CHOI Jongmin on 9/6/2020.
// Copyright © 2020 PennLabs. All rights reserved.
//
import SwiftUI
struct DiningVenueView: View {
@EnvironmentObject var diningVM: DiningViewModelSwiftUI
@StateObject var diningAnalyticsViewModel = DiningAnalyticsViewModel()
var body: some View {
List {
Section(header: CustomHeader(name: "Dining Balance", refreshButton: true).environmentObject(diningAnalyticsViewModel), content: {
Section(header: DiningViewHeader().environmentObject(diningAnalyticsViewModel), content: {})
})
ForEach(diningVM.ordering, id: \.self) { venueType in
Section(header: CustomHeader(name: venueType.fullDisplayName).environmentObject(diningAnalyticsViewModel)) {
ForEach(diningVM.diningVenues[venueType] ?? []) { venue in
NavigationLink(destination: DiningVenueDetailView(for: venue).environmentObject(diningVM)) {
DiningVenueRow(for: venue)
.padding(.vertical, 4)
}
}
}
}
}
.task {
await diningVM.refreshVenues()
await diningVM.refreshBalance()
}
.navigationBarHidden(false)
.listStyle(.plain)
}
}
struct CustomHeader: View {
let name: String
var refreshButton = false
@State var didError = false
@State var showMissingDiningTokenAlert = false
@State var showDiningLoginView = false
@Environment(\.presentationMode) var presentationMode
@EnvironmentObject var diningAnalyticsViewModel: DiningAnalyticsViewModel
func showCorrectAlert () -> Alert {
if !Account.isLoggedIn {
return Alert(title: Text("You must log in to access this feature."), message: Text("Please login on the \"More\" tab."), dismissButton: .default(Text("Ok")))
} else {
return Alert(title: Text("\"Penn Mobile\" requires you to login to Campus Express to use this feature."),
message: Text("Would you like to continue to campus express?"),
primaryButton: .default(Text("Continue"), action: {showDiningLoginView = true}),
secondaryButton: .cancel({ presentationMode.wrappedValue.dismiss() }))
}
}
var body: some View {
HStack {
Text(name)
.font(.system(size: 21, weight: .semibold))
.foregroundColor(.primary)
Spacer()
if refreshButton {
Button(action: {
guard Account.isLoggedIn, KeychainAccessible.instance.getDiningToken() != nil, let diningExpiration = UserDefaults.standard.getDiningTokenExpiration(), Date() <= diningExpiration else {
print("Should show alert")
showMissingDiningTokenAlert = true
return
}
Task.init() {
await DiningViewModelSwiftUI.instance.refreshBalance()
}
}, label: {
Image(systemName: "arrow.counterclockwise")
})
}
}
.padding()
.listRowInsets(EdgeInsets(top: 0, leading: 0, bottom: 0, trailing: 0))
.background(Color(UIColor.uiBackground))
// Default Text Case for Header is Caps Lock
.textCase(nil)
.sheet(isPresented: $showDiningLoginView) {
DiningLoginNavigationView()
.environmentObject(diningAnalyticsViewModel)
}
// Note: The Alert view is soon to be deprecated, but .alert(_:isPresented:presenting:actions:message:) is available in iOS15+
.alert(isPresented: $showMissingDiningTokenAlert) {
showCorrectAlert()
}
// iOS 15+ implementation
/* .alert(Account.isLoggedIn ? "\"Penn Mobile\" requires you to login to Campus Express to use this feature." : "You must log in to access this feature.", isPresented: $showMissingDiningTokenAlert
) {
if (!Account.isLoggedIn) {
Button("OK") {}
} else {
Button("Continue") { showDiningLoginView = true }
Button("Cancel") { presentationMode.wrappedValue.dismiss() }
}
} message: {
if (!Account.isLoggedIn) {
Text("Please login on the \"More\" tab.")
} else {
Text("Would you like to continue to Campus Express?")
}
} */
}
}
|
334e01e58b04357d303b954a0df87b50
| 40.192982 | 205 | 0.57517 | false | false | false | false |
walterscarborough/LibSpacey
|
refs/heads/master
|
platforms/xcode/LibSpaceyTests/FlashcardGraderTests.swift
|
mit
|
1
|
import XCTest
@testable import LibSpacey
class LibSpaceyTests: XCTestCase {
func test_flashcardGrader_canGrade_flashcards() {
let flashcardWrapper = FlashcardWrapper()
if let gradedFlashcardWrapper = FlashcardWrapperGrader.gradeFlashcardWrapper(flashcardWrapper, grade: Grade.Unknown, currentDate: Date()) {
XCTAssertNotNil(gradedFlashcardWrapper)
}
else {
XCTFail()
}
}
func test_flashcardGrader_grade0() {
let october_24_2016 = 1477294292;
let october_25_2016 = 1477380692;
let flashcardWrapper = FlashcardWrapper()
flashcardWrapper.previousDate = Date(timeIntervalSince1970: TimeInterval(october_24_2016))
flashcardWrapper.nextDate = Date(timeIntervalSince1970: TimeInterval(october_24_2016))
let gradedFlashcardWrapper = FlashcardWrapperGrader.gradeFlashcardWrapper(flashcardWrapper, grade: Grade.Unknown, currentDate: Date(timeIntervalSince1970: TimeInterval(october_24_2016)))
XCTAssertEqual(gradedFlashcardWrapper?.repetition, 0)
XCTAssertEqual(gradedFlashcardWrapper?.interval, 1)
XCTAssertEqual(gradedFlashcardWrapper?.easinessFactor, 1.7)
XCTAssertEqual(gradedFlashcardWrapper?.previousDate, Date(timeIntervalSince1970: TimeInterval(october_24_2016)))
XCTAssertEqual(gradedFlashcardWrapper?.nextDate, Date(timeIntervalSince1970: TimeInterval(october_25_2016)))
}
func test_flashcardGrader_grade1() {
let october_23_2016 = 1477207892;
let october_24_2016 = 1477294292;
let flashcardWrapper = FlashcardWrapper()
flashcardWrapper.previousDate = Date(timeIntervalSince1970: TimeInterval(october_23_2016))
flashcardWrapper.nextDate = Date(timeIntervalSince1970: TimeInterval(october_23_2016))
let gradedFlashcardWrapper = FlashcardWrapperGrader.gradeFlashcardWrapper(flashcardWrapper, grade: Grade.VeryHard, currentDate: Date(timeIntervalSince1970: TimeInterval(october_23_2016)))
XCTAssertEqual(gradedFlashcardWrapper?.repetition, 0)
XCTAssertEqual(gradedFlashcardWrapper?.interval, 1)
XCTAssertEqual(gradedFlashcardWrapper?.easinessFactor, 1.96)
XCTAssertEqual(gradedFlashcardWrapper?.previousDate, Date(timeIntervalSince1970: TimeInterval(october_23_2016)))
XCTAssertEqual(gradedFlashcardWrapper?.nextDate, Date(timeIntervalSince1970: TimeInterval(october_24_2016)))
}
func test_flashcardGrader_grade2() {
let october_24_2016 = 1477294292;
let october_25_2016 = 1477380692;
let flashcardWrapper = FlashcardWrapper()
flashcardWrapper.previousDate = Date(timeIntervalSince1970: TimeInterval(october_24_2016))
flashcardWrapper.nextDate = Date(timeIntervalSince1970: TimeInterval(october_24_2016))
let gradedFlashcardWrapper = FlashcardWrapperGrader.gradeFlashcardWrapper(flashcardWrapper, grade: Grade.Hard, currentDate: Date(timeIntervalSince1970: TimeInterval(october_24_2016)))
XCTAssertEqual(gradedFlashcardWrapper?.repetition, 0)
XCTAssertEqual(gradedFlashcardWrapper?.interval, 1)
XCTAssertEqual(gradedFlashcardWrapper?.easinessFactor, 2.18)
XCTAssertEqual(gradedFlashcardWrapper?.previousDate, Date(timeIntervalSince1970: TimeInterval(october_24_2016)))
XCTAssertEqual(gradedFlashcardWrapper?.nextDate, Date(timeIntervalSince1970: TimeInterval(october_25_2016)))
}
func test_flashcardGrader_grade3() {
let october_23_2016 = 1477207892;
let october_24_2016 = 1477294292;
let flashcardWrapper = FlashcardWrapper()
flashcardWrapper.previousDate = Date(timeIntervalSince1970: TimeInterval(october_23_2016))
flashcardWrapper.nextDate = Date(timeIntervalSince1970: TimeInterval(october_23_2016))
let gradedFlashcardWrapper = FlashcardWrapperGrader.gradeFlashcardWrapper(flashcardWrapper, grade: Grade.Medium, currentDate: Date(timeIntervalSince1970: TimeInterval(october_23_2016)))
XCTAssertEqual(gradedFlashcardWrapper?.repetition, 1)
XCTAssertEqual(gradedFlashcardWrapper?.interval, 1)
XCTAssertEqual(gradedFlashcardWrapper?.easinessFactor, 2.36)
XCTAssertEqual(gradedFlashcardWrapper?.previousDate, Date(timeIntervalSince1970: TimeInterval(october_23_2016)))
XCTAssertEqual(gradedFlashcardWrapper?.nextDate, Date(timeIntervalSince1970: TimeInterval(october_24_2016)))
}
func test_flashcardGrader_grade4() {
let october_23_2016 = 1477207892;
let october_24_2016 = 1477294292;
let flashcardWrapper = FlashcardWrapper()
flashcardWrapper.previousDate = Date(timeIntervalSince1970: TimeInterval(october_23_2016))
flashcardWrapper.nextDate = Date(timeIntervalSince1970: TimeInterval(october_23_2016))
let gradedFlashcardWrapper = FlashcardWrapperGrader.gradeFlashcardWrapper(flashcardWrapper, grade: Grade.Easy, currentDate: Date(timeIntervalSince1970: TimeInterval(october_23_2016)))
XCTAssertEqual(gradedFlashcardWrapper?.repetition, 1)
XCTAssertEqual(gradedFlashcardWrapper?.interval, 1)
XCTAssertEqual(gradedFlashcardWrapper?.easinessFactor, 2.5)
XCTAssertEqual(gradedFlashcardWrapper?.previousDate, Date(timeIntervalSince1970: TimeInterval(october_23_2016)))
XCTAssertEqual(gradedFlashcardWrapper?.nextDate, Date(timeIntervalSince1970: TimeInterval(october_24_2016)))
}
func test_flashcardGrader_grade5() {
let october_23_2016 = 1477207892;
let october_24_2016 = 1477294292;
let flashcardWrapper = FlashcardWrapper()
flashcardWrapper.previousDate = Date(timeIntervalSince1970: TimeInterval(october_23_2016))
flashcardWrapper.nextDate = Date(timeIntervalSince1970: TimeInterval(october_23_2016))
let gradedFlashcardWrapper = FlashcardWrapperGrader.gradeFlashcardWrapper(flashcardWrapper, grade: Grade.VeryEasy, currentDate: Date(timeIntervalSince1970: TimeInterval(october_23_2016)))
XCTAssertEqual(gradedFlashcardWrapper?.repetition, 1)
XCTAssertEqual(gradedFlashcardWrapper?.interval, 1)
XCTAssertEqual(gradedFlashcardWrapper?.easinessFactor, 2.6)
XCTAssertEqual(gradedFlashcardWrapper?.previousDate, Date(timeIntervalSince1970: TimeInterval(october_23_2016)))
XCTAssertEqual(gradedFlashcardWrapper?.nextDate, Date(timeIntervalSince1970: TimeInterval(october_24_2016)))
}
func test_flashcardGrader_grade_long_repetition() {
let october_23_2016 = 1477207892;
let october_27_2016 = 1477553492;
let flashcardWrapper = FlashcardWrapper()
flashcardWrapper.interval = 6
flashcardWrapper.repetition = 6
flashcardWrapper.previousDate = Date(timeIntervalSince1970: TimeInterval(october_23_2016))
flashcardWrapper.nextDate = Date(timeIntervalSince1970: TimeInterval(october_23_2016))
let gradedFlashcardWrapper = FlashcardWrapperGrader.gradeFlashcardWrapper(flashcardWrapper, grade: Grade.VeryEasy, currentDate: Date(timeIntervalSince1970: TimeInterval(october_23_2016)))
XCTAssertEqual(gradedFlashcardWrapper?.repetition, 7)
XCTAssertEqual(gradedFlashcardWrapper?.interval, 4)
XCTAssertEqual(gradedFlashcardWrapper?.easinessFactor, 2.6)
XCTAssertEqual(gradedFlashcardWrapper?.previousDate, Date(timeIntervalSince1970: TimeInterval(october_23_2016)))
XCTAssertEqual(gradedFlashcardWrapper?.nextDate, Date(timeIntervalSince1970: TimeInterval(october_27_2016)))
}
}
|
d1e35accccfe8d4a7a577f1b9abb00a8
| 51.506944 | 195 | 0.758101 | false | true | false | false |
hackiftekhar/IQKeyboardManager
|
refs/heads/master
|
IQKeyboardManagerSwift/IQToolbar/IQToolbar.swift
|
mit
|
1
|
//
// IQToolbar.swift
// https://github.com/hackiftekhar/IQKeyboardManager
// Copyright (c) 2013-20 Iftekhar Qurashi.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
/** @abstract IQToolbar for IQKeyboardManager. */
@available(iOSApplicationExtension, unavailable)
@objc open class IQToolbar: UIToolbar, UIInputViewAudioFeedback {
override init(frame: CGRect) {
super.init(frame: frame)
initialize()
}
@objc required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
initialize()
}
private func initialize() {
sizeToFit()
autoresizingMask = .flexibleWidth
self.isTranslucent = true
self.barTintColor = nil
let positions: [UIBarPosition] = [.any, .bottom, .top, .topAttached]
for position in positions {
self.setBackgroundImage(nil, forToolbarPosition: position, barMetrics: .default)
self.setShadowImage(nil, forToolbarPosition: .any)
}
//Background color
self.backgroundColor = nil
}
/**
Previous bar button of toolbar.
*/
private var privatePreviousBarButton: IQBarButtonItem?
@objc open var previousBarButton: IQBarButtonItem {
get {
if privatePreviousBarButton == nil {
privatePreviousBarButton = IQBarButtonItem(image: nil, style: .plain, target: nil, action: nil)
}
return privatePreviousBarButton!
}
set (newValue) {
privatePreviousBarButton = newValue
}
}
/**
Next bar button of toolbar.
*/
private var privateNextBarButton: IQBarButtonItem?
@objc open var nextBarButton: IQBarButtonItem {
get {
if privateNextBarButton == nil {
privateNextBarButton = IQBarButtonItem(image: nil, style: .plain, target: nil, action: nil)
}
return privateNextBarButton!
}
set (newValue) {
privateNextBarButton = newValue
}
}
/**
Title bar button of toolbar.
*/
private var privateTitleBarButton: IQTitleBarButtonItem?
@objc open var titleBarButton: IQTitleBarButtonItem {
get {
if privateTitleBarButton == nil {
privateTitleBarButton = IQTitleBarButtonItem(title: nil)
privateTitleBarButton?.accessibilityLabel = "Title"
privateTitleBarButton?.accessibilityIdentifier = privateTitleBarButton?.accessibilityLabel
}
return privateTitleBarButton!
}
set (newValue) {
privateTitleBarButton = newValue
}
}
/**
Done bar button of toolbar.
*/
private var privateDoneBarButton: IQBarButtonItem?
@objc open var doneBarButton: IQBarButtonItem {
get {
if privateDoneBarButton == nil {
privateDoneBarButton = IQBarButtonItem(title: nil, style: .done, target: nil, action: nil)
}
return privateDoneBarButton!
}
set (newValue) {
privateDoneBarButton = newValue
}
}
/**
Fixed space bar button of toolbar.
*/
private var privateFixedSpaceBarButton: IQBarButtonItem?
@objc open var fixedSpaceBarButton: IQBarButtonItem {
get {
if privateFixedSpaceBarButton == nil {
privateFixedSpaceBarButton = IQBarButtonItem(barButtonSystemItem: .fixedSpace, target: nil, action: nil)
}
privateFixedSpaceBarButton!.isSystemItem = true
if #available(iOS 10, *) {
privateFixedSpaceBarButton!.width = 6
} else {
privateFixedSpaceBarButton!.width = 20
}
return privateFixedSpaceBarButton!
}
set (newValue) {
privateFixedSpaceBarButton = newValue
}
}
@objc override open func sizeThatFits(_ size: CGSize) -> CGSize {
var sizeThatFit = super.sizeThatFits(size)
sizeThatFit.height = 44
return sizeThatFit
}
@objc override open var tintColor: UIColor! {
didSet {
if let unwrappedItems = items {
for item in unwrappedItems {
item.tintColor = tintColor
}
}
}
}
@objc override open func layoutSubviews() {
super.layoutSubviews()
if #available(iOS 11, *) {
return
} else if let customTitleView = titleBarButton.customView {
var leftRect = CGRect.null
var rightRect = CGRect.null
var isTitleBarButtonFound = false
let sortedSubviews = self.subviews.sorted(by: { (view1: UIView, view2: UIView) -> Bool in
if view1.frame.minX != view2.frame.minX {
return view1.frame.minX < view2.frame.minX
} else {
return view1.frame.minY < view2.frame.minY
}
})
for barButtonItemView in sortedSubviews {
if isTitleBarButtonFound {
rightRect = barButtonItemView.frame
break
} else if barButtonItemView === customTitleView {
isTitleBarButtonFound = true
//If it's UIToolbarButton or UIToolbarTextButton (which actually UIBarButtonItem)
} else if barButtonItemView.isKind(of: UIControl.self) {
leftRect = barButtonItemView.frame
}
}
let titleMargin: CGFloat = 16
let maxWidth: CGFloat = self.frame.width - titleMargin*2 - (leftRect.isNull ? 0 : leftRect.maxX) - (rightRect.isNull ? 0 : self.frame.width - rightRect.minX)
let maxHeight = self.frame.height
let sizeThatFits = customTitleView.sizeThatFits(CGSize(width: maxWidth, height: maxHeight))
var titleRect: CGRect
if sizeThatFits.width > 0, sizeThatFits.height > 0 {
let width = min(sizeThatFits.width, maxWidth)
let height = min(sizeThatFits.height, maxHeight)
var xPosition: CGFloat
if !leftRect.isNull {
xPosition = titleMargin + leftRect.maxX + ((maxWidth - width)/2)
} else {
xPosition = titleMargin
}
let yPosition = (maxHeight - height)/2
titleRect = CGRect(x: xPosition, y: yPosition, width: width, height: height)
} else {
var xPosition: CGFloat
if !leftRect.isNull {
xPosition = titleMargin + leftRect.maxX
} else {
xPosition = titleMargin
}
let width: CGFloat = self.frame.width - titleMargin*2 - (leftRect.isNull ? 0 : leftRect.maxX) - (rightRect.isNull ? 0 : self.frame.width - rightRect.minX)
titleRect = CGRect(x: xPosition, y: 0, width: width, height: maxHeight)
}
customTitleView.frame = titleRect
}
}
@objc open var enableInputClicksWhenVisible: Bool {
return true
}
}
|
09835f6ca33d25e7f19b7401544940c4
| 31.948413 | 170 | 0.599061 | false | false | false | false |
stefanilie/swift-playground
|
refs/heads/master
|
Swift3 and iOS10/Playgrounds/LearnSwift.playground/Contents.swift
|
mit
|
1
|
//: Playground - noun: a place where people can play
import UIKit
var str = "Hello, playground"
print("Hello Playground")
//this is a constant
let straw = "berry";
//this is a simple variable
var blue = "berry";
//you can it's value
blue = "sofa"
//This is a declaration of a variable containg the type of the variable
var declaredType: Double = 50
//if you want to make combine values, you have to cast them
var combined: String = blue + String(declaredType)
//You can even add the string inline by doing this:
print("The number of sofas is \(String(declaredType))");
//this is a list
var list = ["this", "is", "a", "list"];
//This a dict
var dict = [
"this": 4,
"dict": 4,
"is": 2
]
//ControlFlow
let individualScores = [75, 43, 103, 87, 12]
var teamScore = 0;
for score in individualScores {
if score < 50 {
teamScore += 3
} else {
teamScore += 1
}
}
print(teamScore)
//Optional values
var optionalString: String? = "Hello"
print(optionalString == nil)
var optionalName: String? = "John Appleseed"
var greeting = "Hello!"
if let name = optionalName {
greeting = "Hello \(name)"
}
//The bellow example is a perfect representation of
//how to use the ?? operator
let nickName: String? = nil
let fullName: String = "John Appleseed"
let informalGreeting = "hi \(nickName ?? fullName)"
//Switch
let vegetable = "red pepper"
switch vegetable {
case "celery":
print("Add some raising and make ants on a log")
case "cucumber", "watercress":
print("That would make a good tea sandwich")
case let x where x.hasSuffix("pepper"):
print("It's a nice and spicy \(x)")
default:
print("Everything tastes like soup")
}
// To demonstrate the control flow, here's a simple example of a guess game
//First, here is the number we have to guess
//let diceRoll = Int(arc4random_uniform(20)+1);
//var hasBeenGuessed: Bool = false;
//var numberOfTryes: Float = 0;
//var readNumber: Int;
|
e7e021b2bb7df1b7363cf4363fd1f1a4
| 19.787234 | 75 | 0.676561 | false | false | false | false |
mysangle/algorithm-study
|
refs/heads/master
|
range-sum-query-mutable/FenwickTree.swift
|
mit
|
1
|
/**
* array = [3,9,5,6,10,8,7,1,2,4]의 1 ~ 6 사이의 합을 구하는 예
*
* let fenwick = FenwickTree(array)
* fenwick.range(1, 6)
*/
public class FenwickTree {
var orig: [Int];
var tree: [Int];
init(_ orig: [Int]) {
self.orig = orig
// 0번은 사용하지 않는다. 1번부터 사용한다. 그래야 비트 연산이 가능해진다.
self.tree = [Int](repeating: 0, count: orig.count + 1)
for i in 0..<orig.count {
add(i, orig[i])
}
print(tree)
}
private func add(_ pos: Int, _ val: Int) {
var position = pos + 1
while position < tree.count {
tree[position] += val;
// 가장 하위의 비트값을 더한다.
position += (position & -position)
}
}
public func sum(_ pos: Int) -> Int {
var position = pos + 1
var sum = 0
while position > 0 {
sum += tree[position]
// 가장 하위의 비트값을 뺀다.
position &= (position - 1)
}
return sum
}
public func update(_ pos: Int, _ val: Int) {
let diff = val - orig[pos]
orig[pos] = val
add(pos, diff)
}
public func range(_ leftBound: Int, _ rightBound: Int) -> Int {
return sum(rightBound) - sum(leftBound - 1)
}
}
|
4e8f2ffa747f46479d38bc9f696dece4
| 23.326923 | 67 | 0.472727 | false | false | false | false |
ScoutHarris/WordPress-iOS
|
refs/heads/develop
|
WordPress/Classes/ViewRelated/Reader/ReaderDetailViewController.swift
|
gpl-2.0
|
1
|
import Foundation
import CocoaLumberjack
import WordPressShared
import QuartzCore
open class ReaderDetailViewController: UIViewController, UIViewControllerRestoration {
static let restorablePostObjectURLhKey: String = "RestorablePostObjectURLKey"
// Structs for Constants
fileprivate struct DetailConstants {
static let LikeCountKeyPath = "likeCount"
static let MarginOffset = CGFloat(8.0)
}
fileprivate struct DetailAnalyticsConstants {
static let TypeKey = "post_detail_type"
static let TypeNormal = "normal"
static let TypePreviewSite = "preview_site"
static let OfflineKey = "offline_view"
static let PixelStatReferrer = "https://wordpress.com/"
}
// MARK: - Properties & Accessors
// Footer views
@IBOutlet fileprivate weak var footerView: UIView!
@IBOutlet fileprivate weak var tagButton: UIButton!
@IBOutlet fileprivate weak var commentButton: UIButton!
@IBOutlet fileprivate weak var likeButton: UIButton!
@IBOutlet fileprivate weak var footerViewHeightConstraint: NSLayoutConstraint!
// Wrapper views
@IBOutlet fileprivate weak var textHeaderStackView: UIStackView!
@IBOutlet fileprivate weak var textFooterStackView: UIStackView!
fileprivate weak var textFooterTopConstraint: NSLayoutConstraint!
// Header realated Views
@IBOutlet fileprivate weak var headerView: UIView!
@IBOutlet fileprivate weak var blavatarImageView: UIImageView!
@IBOutlet fileprivate weak var blogNameButton: UIButton!
@IBOutlet fileprivate weak var blogURLLabel: UILabel!
@IBOutlet fileprivate weak var menuButton: UIButton!
// Content views
@IBOutlet fileprivate weak var featuredImageView: UIImageView!
@IBOutlet fileprivate weak var titleLabel: UILabel!
@IBOutlet fileprivate weak var bylineView: UIView!
@IBOutlet fileprivate weak var avatarImageView: CircularImageView!
@IBOutlet fileprivate weak var bylineLabel: UILabel!
@IBOutlet fileprivate weak var textView: WPRichContentView!
@IBOutlet fileprivate weak var attributionView: ReaderCardDiscoverAttributionView!
// Spacers
@IBOutlet fileprivate weak var featuredImageBottomPaddingView: UIView!
@IBOutlet fileprivate weak var titleBottomPaddingView: UIView!
@IBOutlet fileprivate weak var bylineBottomPaddingView: UIView!
open var shouldHideComments = false
fileprivate var didBumpStats = false
fileprivate var didBumpPageViews = false
fileprivate var footerViewHeightConstraintConstant = CGFloat(0.0)
fileprivate let sharingController = PostSharingController()
var currentPreferredStatusBarStyle = UIStatusBarStyle.lightContent {
didSet {
setNeedsStatusBarAppearanceUpdate()
}
}
override open var preferredStatusBarStyle: UIStatusBarStyle {
return currentPreferredStatusBarStyle
}
open var post: ReaderPost? {
didSet {
oldValue?.removeObserver(self, forKeyPath: DetailConstants.LikeCountKeyPath)
oldValue?.inUse = false
if let newPost = post, let context = newPost.managedObjectContext {
newPost.inUse = true
ContextManager.sharedInstance().save(context)
newPost.addObserver(self, forKeyPath: DetailConstants.LikeCountKeyPath, options: .new, context: nil)
}
if isViewLoaded {
configureView()
}
}
}
fileprivate var isLoaded: Bool {
return post != nil
}
// MARK: - Convenience Factories
/// Convenience method for instantiating an instance of ReaderDetailViewController
/// for a particular topic.
///
/// - Parameters:
/// - topic: The reader topic for the list.
///
/// - Return: A ReaderListViewController instance.
///
open class func controllerWithPost(_ post: ReaderPost) -> ReaderDetailViewController {
let storyboard = UIStoryboard(name: "Reader", bundle: Bundle.main)
let controller = storyboard.instantiateViewController(withIdentifier: "ReaderDetailViewController") as! ReaderDetailViewController
controller.post = post
return controller
}
open class func controllerWithPostID(_ postID: NSNumber, siteID: NSNumber) -> ReaderDetailViewController {
let storyboard = UIStoryboard(name: "Reader", bundle: Bundle.main)
let controller = storyboard.instantiateViewController(withIdentifier: "ReaderDetailViewController") as! ReaderDetailViewController
controller.setupWithPostID(postID, siteID: siteID)
return controller
}
// MARK: - State Restoration
open static func viewController(withRestorationIdentifierPath identifierComponents: [Any], coder: NSCoder) -> UIViewController? {
guard let path = coder.decodeObject(forKey: restorablePostObjectURLhKey) as? String else {
return nil
}
let context = ContextManager.sharedInstance().mainContext
guard let url = URL(string: path),
let objectID = context.persistentStoreCoordinator?.managedObjectID(forURIRepresentation: url) else {
return nil
}
guard let post = (try? context.existingObject(with: objectID)) as? ReaderPost else {
return nil
}
return controllerWithPost(post)
}
open override func encodeRestorableState(with coder: NSCoder) {
if let post = post {
coder.encode(post.objectID.uriRepresentation().absoluteString, forKey: type(of: self).restorablePostObjectURLhKey)
}
super.encodeRestorableState(with: coder)
}
// MARK: - LifeCycle Methods
deinit {
if let post = post, let context = post.managedObjectContext {
post.inUse = false
ContextManager.sharedInstance().save(context)
post.removeObserver(self, forKeyPath: DetailConstants.LikeCountKeyPath)
}
NotificationCenter.default.removeObserver(self)
}
open override func awakeAfter(using aDecoder: NSCoder) -> Any? {
restorationClass = type(of: self)
return super.awakeAfter(using: aDecoder)
}
open override func viewDidLoad() {
super.viewDidLoad()
setupContentHeaderAndFooter()
textView.alpha = 0
footerView.isHidden = true
// Hide the featured image and its padding until we know there is one to load.
featuredImageView.isHidden = true
featuredImageBottomPaddingView.isHidden = true
// Styles
applyStyles()
setupNavBar()
if let _ = post {
configureView()
}
}
open override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
// The UIApplicationDidBecomeActiveNotification notification is broadcast
// when the app is resumed as a part of split screen multitasking on the iPad.
NotificationCenter.default.addObserver(self, selector: #selector(ReaderDetailViewController.handleApplicationDidBecomeActive(_:)), name: NSNotification.Name.UIApplicationDidBecomeActive, object: nil)
bumpStats()
bumpPageViewsForPost()
}
open override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
setBarsHidden(false, animated: animated)
NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIApplicationDidBecomeActive, object: nil)
}
open override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection)
// This is something we do to help with the resizing that can occur with
// split screen multitasking on the iPad.
view.layoutIfNeeded()
}
open override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransition(to: size, with: coordinator)
let y = textView.contentOffset.y
let position = textView.closestPosition(to: CGPoint(x: 0.0, y: y))
coordinator.animate(
alongsideTransition: { (_) in
if let position = position, let textRange = self.textView.textRange(from: position, to: position) {
let rect = self.textView.firstRect(for: textRange)
self.textView.setContentOffset(CGPoint(x: 0.0, y: rect.origin.y), animated: false)
}
},
completion: { (_) in
self.updateContentInsets()
self.updateTextViewMargins()
})
// Make sure that the bars are visible after switching from landscape
// to portrait orientation. The content might have been scrollable in landscape
// orientation, but it might not be in portrait orientation. We'll assume the bars
// should be visible for safety sake and for performance since WPRichTextView updates
// its intrinsicContentSize too late for get an accurate scrollWiew.contentSize
// in the completion handler below.
if size.height > size.width {
self.setBarsHidden(false)
}
}
open override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if (object! as! NSObject == post!) && (keyPath! == DetailConstants.LikeCountKeyPath) {
// Note: The intent here is to update the action buttons, specifically the
// like button, *after* both likeCount and isLiked has changed. The order
// of the properties is important.
configureLikeActionButton(true)
}
}
// MARK: - Multitasking Splitview Support
func handleApplicationDidBecomeActive(_ notification: Foundation.Notification) {
view.layoutIfNeeded()
}
// MARK: - Setup
open func setupWithPostID(_ postID: NSNumber, siteID: NSNumber) {
let title = NSLocalizedString("Loading Post...", comment: "Text displayed while loading a post.")
WPNoResultsView.displayAnimatedBox(withTitle: title, message: nil, view: view)
textView.alpha = 0.0
let context = ContextManager.sharedInstance().mainContext
let service = ReaderPostService(managedObjectContext: context)
service.fetchPost(
postID.uintValue,
forSite: siteID.uintValue,
success: {[weak self] (post: ReaderPost?) in
WPNoResultsView.remove(from: self?.view)
self?.textView.alpha = 1.0
self?.post = post
}, failure: {[weak self] (error: Error?) in
DDLogError("Error fetching post for detail: \(String(describing: error?.localizedDescription))")
let title = NSLocalizedString("Error Loading Post", comment: "Text displayed when load post fails.")
WPNoResultsView.displayAnimatedBox(withTitle: title, message: nil, view: self?.view)
}
)
}
/// Composes the views for the post header and Discover attribution.
fileprivate func setupContentHeaderAndFooter() {
// Add the footer first so its behind the header. This way the header
// obscures the footer until its properly positioned.
textView.addSubview(textFooterStackView)
textView.addSubview(textHeaderStackView)
textHeaderStackView.topAnchor.constraint(equalTo: textView.topAnchor).isActive = true
textFooterTopConstraint = NSLayoutConstraint(item: textFooterStackView,
attribute: .top,
relatedBy: .equal,
toItem: textView,
attribute: .top,
multiplier: 1.0,
constant: 0.0)
textView.addConstraint(textFooterTopConstraint)
textFooterTopConstraint.constant = textFooterYOffset()
textView.setContentOffset(CGPoint.zero, animated: false)
}
/// Sets the left and right textContainerInset to preserve readable content margins.
fileprivate func updateContentInsets() {
var insets = textView.textContainerInset
let margin = view.readableContentGuide.layoutFrame.origin.x
insets.left = margin - DetailConstants.MarginOffset
insets.right = margin - DetailConstants.MarginOffset
textView.textContainerInset = insets
textView.layoutIfNeeded()
}
/// Returns the y position for the textfooter. Assign to the textFooter's top
/// constraint constant to correctly position the view.
fileprivate func textFooterYOffset() -> CGFloat {
let length = textView.textStorage.length
if length == 0 {
return textView.contentSize.height - textFooterStackView.frame.height
}
let range = NSRange(location: length - 1, length: 0)
let frame = textView.frameForTextInRange(range)
if frame.minY == CGFloat.infinity {
// A value of infinity can occur when a device is rotated 180 degrees.
// It will sort it self out as the rotation aniation progresses,
// so just return the existing constant.
return textFooterTopConstraint.constant
}
return frame.minY
}
/// Updates the bounds of the placeholder top and bottom text attachments so
/// there is enough vertical space for the text header and footer views.
fileprivate func updateTextViewMargins() {
textView.topMargin = textHeaderStackView.frame.height
textView.bottomMargin = textFooterStackView.frame.height
textFooterTopConstraint.constant = textFooterYOffset()
}
fileprivate func setupNavBar() {
configureNavTitle()
// Don't show 'Reader' in the next-view back button
navigationItem.backBarButtonItem = UIBarButtonItem(title: " ", style: .plain, target: nil, action: nil)
}
// MARK: - Configuration
/**
Applies the default styles to the cell's subviews
*/
fileprivate func applyStyles() {
WPStyleGuide.applyReaderCardSiteButtonStyle(blogNameButton)
WPStyleGuide.applyReaderCardBylineLabelStyle(bylineLabel)
WPStyleGuide.applyReaderCardBylineLabelStyle(blogURLLabel)
WPStyleGuide.applyReaderCardTitleLabelStyle(titleLabel)
WPStyleGuide.applyReaderCardTagButtonStyle(tagButton)
WPStyleGuide.applyReaderCardActionButtonStyle(commentButton)
WPStyleGuide.applyReaderCardActionButtonStyle(likeButton)
}
fileprivate func configureView() {
textView.alpha = 1
configureNavTitle()
configureShareButton()
configureHeader()
configureFeaturedImage()
configureTitle()
configureByLine()
configureRichText()
configureDiscoverAttribution()
configureTag()
configureActionButtons()
configureFooterIfNeeded()
adjustInsetsForTextDirection()
bumpStats()
bumpPageViewsForPost()
NotificationCenter.default.addObserver(self,
selector: #selector(ReaderDetailViewController.handleBlockSiteNotification(_:)),
name: NSNotification.Name(rawValue: ReaderPostMenu.BlockSiteNotification),
object: nil)
view.layoutIfNeeded()
textView.setContentOffset(CGPoint.zero, animated: false)
}
fileprivate func configureNavTitle() {
let placeholder = NSLocalizedString("Post", comment: "Placeholder title for ReaderPostDetails.")
self.title = post?.postTitle ?? placeholder
}
fileprivate func configureShareButton() {
// Share button.
let image = UIImage(named: "icon-posts-share")!.withRenderingMode(UIImageRenderingMode.alwaysTemplate)
let button = CustomHighlightButton(frame: CGRect(x: 0, y: 0, width: image.size.width, height: image.size.height))
button.setImage(image, for: UIControlState())
button.addTarget(self, action: #selector(ReaderDetailViewController.didTapShareButton(_:)), for: .touchUpInside)
let shareButton = UIBarButtonItem(customView: button)
shareButton.accessibilityLabel = NSLocalizedString("Share", comment: "Spoken accessibility label")
WPStyleGuide.setRightBarButtonItemWithCorrectSpacing(shareButton, for: navigationItem)
}
fileprivate func configureHeader() {
// Blavatar
let placeholder = UIImage(named: "post-blavatar-placeholder")
blavatarImageView.image = placeholder
let size = blavatarImageView.frame.size.width * UIScreen.main.scale
if let url = post?.siteIconForDisplay(ofSize: Int(size)) {
blavatarImageView.setImageWith(url, placeholderImage: placeholder)
}
// Site name
let blogName = post?.blogNameForDisplay()
blogNameButton.setTitle(blogName, for: UIControlState())
blogNameButton.setTitle(blogName, for: .highlighted)
blogNameButton.setTitle(blogName, for: .disabled)
// Enable button only if not previewing a site.
if let topic = post!.topic {
blogNameButton.isEnabled = !ReaderHelpers.isTopicSite(topic)
}
// If the button is enabled also listen for taps on the avatar.
if blogNameButton.isEnabled {
let tgr = UITapGestureRecognizer(target: self, action: #selector(ReaderDetailViewController.didTapHeaderAvatar(_:)))
blavatarImageView.addGestureRecognizer(tgr)
}
if let siteURL: NSString = post!.siteURLForDisplay() as NSString? {
blogURLLabel.text = siteURL.components(separatedBy: "//").last
}
}
fileprivate func configureFeaturedImage() {
var url = post!.featuredImageURLForDisplay()
guard url != nil else {
return
}
// Do not display the featured image if it exists in the content.
if post!.contentIncludesFeaturedImage() {
return
}
var request: URLRequest
if !(post!.isPrivate()) {
let size = CGSize(width: featuredImageView.frame.width, height: 0)
url = PhotonImageURLHelper.photonURL(with: size, forImageURL: url)
request = URLRequest(url: url!)
} else if (url?.host != nil) && (url?.host!.hasSuffix("wordpress.com"))! {
// private wpcom image needs special handling.
request = requestForURL(url!)
} else {
// private but not a wpcom hosted image
request = URLRequest(url: url!)
}
// Define a success block to make the image visible and update its aspect ratio constraint
let successBlock: ((URLRequest, HTTPURLResponse?, UIImage) -> Void) = { [weak self] (request: URLRequest, response: HTTPURLResponse?, image: UIImage) in
guard self != nil else {
return
}
self!.configureFeaturedImageWithImage(image)
}
featuredImageView.setImageWith(request, placeholderImage: nil, success: successBlock, failure: nil)
}
open override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
updateContentInsets()
updateTextViewMargins()
}
fileprivate func configureFeaturedImageWithImage(_ image: UIImage) {
// Unhide the views
featuredImageView.isHidden = false
featuredImageBottomPaddingView.isHidden = false
// Now that we have the image, create an aspect ratio constraint for
// the featuredImageView
let ratio = image.size.height / image.size.width
let constraint = NSLayoutConstraint(item: featuredImageView,
attribute: .height,
relatedBy: .equal,
toItem: featuredImageView,
attribute: .width,
multiplier: ratio,
constant: 0)
constraint.priority = UILayoutPriorityDefaultHigh
featuredImageView.addConstraint(constraint)
featuredImageView.setNeedsUpdateConstraints()
featuredImageView.image = image
// Listen for taps so we can display the image detail
let tgr = UITapGestureRecognizer(target: self, action: #selector(ReaderDetailViewController.didTapFeaturedImage(_:)))
featuredImageView.addGestureRecognizer(tgr)
view.layoutIfNeeded()
updateTextViewMargins()
}
fileprivate func requestForURL(_ url: URL) -> URLRequest {
var requestURL = url
let absoluteString = requestURL.absoluteString
if !absoluteString.hasPrefix("https") {
let sslURL = absoluteString.replacingOccurrences(of: "http", with: "https")
requestURL = URL(string: sslURL)!
}
let request = NSMutableURLRequest(url: requestURL)
let acctServ = AccountService(managedObjectContext: ContextManager.sharedInstance().mainContext)
if let account = acctServ.defaultWordPressComAccount() {
let token = account.authToken
let headerValue = String(format: "Bearer %@", token!)
request.addValue(headerValue, forHTTPHeaderField: "Authorization")
}
return request as URLRequest
}
fileprivate func configureTitle() {
if let title = post?.titleForDisplay() {
titleLabel.attributedText = NSAttributedString(string: title, attributes: WPStyleGuide.readerDetailTitleAttributes())
titleLabel.isHidden = false
} else {
titleLabel.attributedText = nil
titleLabel.isHidden = true
}
}
fileprivate func configureByLine() {
// Avatar
let placeholder = UIImage(named: "gravatar")
if let avatarURLString = post?.authorAvatarURL,
let url = URL(string: avatarURLString) {
avatarImageView.setImageWith(url, placeholderImage: placeholder)
}
// Byline
let author = post?.authorForDisplay()
let dateAsString = post?.dateForDisplay()?.mediumString()
let byline: String
if let author = author, let date = dateAsString {
byline = author + " · " + date
} else {
byline = author ?? dateAsString ?? String()
}
bylineLabel.text = byline
}
fileprivate func configureRichText() {
guard let post = post else {
return
}
textView.isPrivate = post.isPrivate()
textView.content = post.contentForDisplay()
updateTextViewMargins()
}
fileprivate func configureDiscoverAttribution() {
if post?.sourceAttributionStyle() == SourceAttributionStyle.none {
attributionView.isHidden = true
} else {
attributionView.configureViewWithVerboseSiteAttribution(post!)
attributionView.delegate = self
}
}
fileprivate func configureTag() {
var tag = ""
if let rawTag = post?.primaryTag {
if rawTag.characters.count > 0 {
tag = "#\(rawTag)"
}
}
tagButton.isHidden = tag.characters.count == 0
tagButton.setTitle(tag, for: UIControlState())
tagButton.setTitle(tag, for: .highlighted)
}
fileprivate func configureActionButtons() {
resetActionButton(likeButton)
resetActionButton(commentButton)
guard let post = post else {
assertionFailure()
return
}
// Show likes if logged in, or if likes exist, but not if external
if (ReaderHelpers.isLoggedIn() || post.likeCount.intValue > 0) && !post.isExternal {
configureLikeActionButton()
}
// Show comments if logged in and comments are enabled, or if comments exist.
// But only if it is from wpcom (jetpack and external is not yet supported).
// Nesting this conditional cos it seems clearer that way
if post.isWPCom && !shouldHideComments {
let commentCount = post.commentCount?.intValue ?? 0
if (ReaderHelpers.isLoggedIn() && post.commentsOpen) || commentCount > 0 {
configureCommentActionButton()
}
}
}
fileprivate func resetActionButton(_ button: UIButton) {
button.setTitle(nil, for: UIControlState())
button.setTitle(nil, for: .highlighted)
button.setTitle(nil, for: .disabled)
button.setImage(nil, for: UIControlState())
button.setImage(nil, for: .highlighted)
button.setImage(nil, for: .disabled)
button.isSelected = false
button.isHidden = true
button.isEnabled = true
}
fileprivate func configureActionButton(_ button: UIButton, title: String?, image: UIImage?, highlightedImage: UIImage?, selected: Bool) {
button.setTitle(title, for: UIControlState())
button.setTitle(title, for: .highlighted)
button.setTitle(title, for: .disabled)
button.setImage(image, for: UIControlState())
button.setImage(highlightedImage, for: .highlighted)
button.setImage(image, for: .disabled)
button.isSelected = selected
button.isHidden = false
}
fileprivate func configureLikeActionButton(_ animated: Bool = false) {
likeButton.isEnabled = ReaderHelpers.isLoggedIn()
let title = post!.likeCountForDisplay()
let imageName = post!.isLiked ? "icon-reader-liked" : "icon-reader-like"
let image = UIImage(named: imageName)
let highlightImage = UIImage(named: "icon-reader-like-highlight")
let selected = post!.isLiked
configureActionButton(likeButton, title: title, image: image, highlightedImage: highlightImage, selected: selected)
if animated {
playLikeButtonAnimation()
}
}
fileprivate func playLikeButtonAnimation() {
let likeImageView = likeButton.imageView!
let frame = likeButton.convert(likeImageView.frame, from: likeImageView)
let imageView = UIImageView(image: UIImage(named: "icon-reader-liked"))
imageView.frame = frame
likeButton.addSubview(imageView)
let animationDuration = 0.3
if likeButton.isSelected {
// Prep a mask to hide the likeButton's image, since changes to visiblility and alpha are ignored
let mask = UIView(frame: frame)
mask.backgroundColor = view.backgroundColor
likeButton.addSubview(mask)
likeButton.bringSubview(toFront: imageView)
// Configure starting state
imageView.alpha = 0.0
let angle = (-270.0 * CGFloat.pi) / 180.0
let rotate = CGAffineTransform(rotationAngle: angle)
let scale = CGAffineTransform(scaleX: 3.0, y: 3.0)
imageView.transform = rotate.concatenating(scale)
// Perform the animations
UIView.animate(withDuration: animationDuration,
animations: { () in
let angle = (1.0 * CGFloat.pi) / 180.0
let rotate = CGAffineTransform(rotationAngle: angle)
let scale = CGAffineTransform(scaleX: 0.75, y: 0.75)
imageView.transform = rotate.concatenating(scale)
imageView.alpha = 1.0
imageView.center = likeImageView.center // In case the button's imageView shifted position
},
completion: { (_) in
UIView.animate(withDuration: animationDuration,
animations: { () in
imageView.transform = CGAffineTransform(scaleX: 1.0, y: 1.0)
},
completion: { (_) in
mask.removeFromSuperview()
imageView.removeFromSuperview()
})
})
} else {
UIView .animate(withDuration: animationDuration,
animations: { () -> Void in
let angle = (120.0 * CGFloat.pi) / 180.0
let rotate = CGAffineTransform(rotationAngle: angle)
let scale = CGAffineTransform(scaleX: 3.0, y: 3.0)
imageView.transform = rotate.concatenating(scale)
imageView.alpha = 0
},
completion: { (_) in
imageView.removeFromSuperview()
})
}
}
fileprivate func configureCommentActionButton() {
let title = post!.commentCount.stringValue
let image = UIImage(named: "icon-reader-comment")
let highlightImage = UIImage(named: "icon-reader-comment-highlight")
configureActionButton(commentButton, title: title, image: image, highlightedImage: highlightImage, selected: false)
}
fileprivate func configureFooterIfNeeded() {
self.footerView.isHidden = tagButton.isHidden && likeButton.isHidden && commentButton.isHidden
if self.footerView.isHidden {
footerViewHeightConstraint.constant = 0
}
footerViewHeightConstraintConstant = footerViewHeightConstraint.constant
}
fileprivate func adjustInsetsForTextDirection() {
let buttonsToAdjust: [UIButton] = [
likeButton,
commentButton]
for button in buttonsToAdjust {
button.flipInsetsForRightToLeftLayoutDirection()
}
}
// MARK: - Instance Methods
func presentWebViewControllerWithURL(_ url: URL) {
var url = url
if url.host == nil {
if let postURLString = post?.permaLink {
let postURL = URL(string: postURLString)
url = URL(string: url.absoluteString, relativeTo: postURL)!
}
}
let controller = WPWebViewController.authenticatedWebViewController(url)
controller.addsWPComReferrer = true
let navController = UINavigationController(rootViewController: controller)
present(navController, animated: true, completion: nil)
}
func previewSite() {
let controller = ReaderStreamViewController.controllerWithSiteID(post!.siteID, isFeed: post!.isExternal)
navigationController?.pushViewController(controller, animated: true)
let properties = ReaderHelpers.statsPropertiesForPost(post!, andValue: post!.blogURL as AnyObject?, forKey: "URL")
WPAppAnalytics.track(.readerSitePreviewed, withProperties: properties)
}
func setBarsHidden(_ hidden: Bool, animated: Bool = true) {
if (navigationController?.isNavigationBarHidden == hidden) {
return
}
if (hidden) {
// Hides the navbar and footer view
navigationController?.setNavigationBarHidden(true, animated: animated)
currentPreferredStatusBarStyle = .default
footerViewHeightConstraint.constant = 0.0
UIView.animate(withDuration: animated ? 0.2 : 0,
delay: 0.0,
options: [.beginFromCurrentState, .allowUserInteraction],
animations: {
self.view.layoutIfNeeded()
}, completion: nil)
} else {
// Shows the navbar and footer view
let pinToBottom = isScrollViewAtBottom()
currentPreferredStatusBarStyle = .lightContent
footerViewHeightConstraint.constant = footerViewHeightConstraintConstant
UIView.animate(withDuration: animated ? 0.2 : 0,
delay: 0.0,
options: [.beginFromCurrentState, .allowUserInteraction],
animations: {
self.view.layoutIfNeeded()
self.navigationController?.setNavigationBarHidden(false, animated: animated)
if pinToBottom {
let y = self.textView.contentSize.height - self.textView.frame.height
self.textView.setContentOffset(CGPoint(x: 0, y: y), animated: false)
}
}, completion: nil)
}
}
func isScrollViewAtBottom() -> Bool {
return textView.contentOffset.y + textView.frame.height == textView.contentSize.height
}
// MARK: - Analytics
fileprivate func bumpStats() {
if didBumpStats {
return
}
guard let readerPost = post, isViewLoaded && view.window != nil else {
return
}
didBumpStats = true
let isOfflineView = ReachabilityUtils.isInternetReachable() ? "no" : "yes"
let detailType = readerPost.topic?.type == ReaderSiteTopic.TopicType ? DetailAnalyticsConstants.TypePreviewSite : DetailAnalyticsConstants.TypeNormal
var properties = ReaderHelpers.statsPropertiesForPost(readerPost, andValue: nil, forKey: nil)
properties[DetailAnalyticsConstants.TypeKey] = detailType
properties[DetailAnalyticsConstants.OfflineKey] = isOfflineView
WPAppAnalytics.track(.readerArticleOpened, withProperties: properties)
// We can remove the nil check and use `if let` when `ReaderPost` adopts nullibility.
let railcar = readerPost.railcarDictionary()
if railcar != nil {
WPAppAnalytics.trackTrainTracksInteraction(.readerArticleOpened, withProperties: railcar)
}
}
fileprivate func bumpPageViewsForPost() {
if didBumpPageViews {
return
}
guard let readerPost = post, isViewLoaded && view.window != nil else {
return
}
didBumpPageViews = true
ReaderHelpers.bumpPageViewForPost(readerPost)
}
// MARK: - Actions
@IBAction func didTapTagButton(_ sender: UIButton) {
if !isLoaded {
return
}
let controller = ReaderStreamViewController.controllerWithTagSlug(post!.primaryTagSlug)
navigationController?.pushViewController(controller, animated: true)
let properties = ReaderHelpers.statsPropertiesForPost(post!, andValue: post!.primaryTagSlug as AnyObject?, forKey: "tag")
WPAppAnalytics.track(.readerTagPreviewed, withProperties: properties)
}
@IBAction func didTapCommentButton(_ sender: UIButton) {
if !isLoaded {
return
}
let controller = ReaderCommentsViewController(post: post)
navigationController?.pushViewController(controller!, animated: true)
}
@IBAction func didTapLikeButton(_ sender: UIButton) {
if !isLoaded {
return
}
guard let post = post else {
return
}
if !post.isLiked {
UINotificationFeedbackGenerator().notificationOccurred(.success)
}
let service = ReaderPostService(managedObjectContext: post.managedObjectContext!)
service.toggleLiked(for: post, success: nil, failure: { (error: Error?) in
if let anError = error {
DDLogError("Error (un)liking post: \(anError.localizedDescription)")
}
})
}
func didTapHeaderAvatar(_ gesture: UITapGestureRecognizer) {
if gesture.state != .ended {
return
}
previewSite()
}
@IBAction func didTapBlogNameButton(_ sender: UIButton) {
previewSite()
}
@IBAction func didTapMenuButton(_ sender: UIButton) {
ReaderPostMenu.showMenuForPost(post!, fromView: menuButton, inViewController: self)
}
func didTapFeaturedImage(_ gesture: UITapGestureRecognizer) {
if gesture.state != .ended {
return
}
let controller = WPImageViewController(image: featuredImageView.image)
controller?.modalTransitionStyle = .crossDissolve
controller?.modalPresentationStyle = .fullScreen
present(controller!, animated: true, completion: nil)
}
func didTapDiscoverAttribution() {
if post?.sourceAttribution == nil {
return
}
if let blogID = post?.sourceAttribution.blogID {
let controller = ReaderStreamViewController.controllerWithSiteID(blogID, isFeed: false)
navigationController?.pushViewController(controller, animated: true)
return
}
var path: String?
if post?.sourceAttribution.attributionType == SourcePostAttributionTypePost {
path = post?.sourceAttribution.permalink
} else {
path = post?.sourceAttribution.blogURL
}
if let linkURL = URL(string: path!) {
presentWebViewControllerWithURL(linkURL)
}
}
func didTapShareButton(_ sender: UIButton) {
sharingController.shareReaderPost(post!, fromView: sender, inViewController: self)
}
func handleBlockSiteNotification(_ notification: Foundation.Notification) {
if let userInfo = notification.userInfo, let aPost = userInfo["post"] as? NSObject {
if aPost == post! {
_ = navigationController?.popViewController(animated: true)
}
}
}
}
// MARK: - ReaderCardDiscoverAttributionView Delegate Methods
extension ReaderDetailViewController : ReaderCardDiscoverAttributionViewDelegate {
public func attributionActionSelectedForVisitingSite(_ view: ReaderCardDiscoverAttributionView) {
didTapDiscoverAttribution()
}
}
// MARK: - UITextView/WPRichContentView Delegate Methods
extension ReaderDetailViewController: WPRichContentViewDelegate {
public func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange) -> Bool {
presentWebViewControllerWithURL(URL)
return false
}
@available(iOS 10, *)
public func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool {
if interaction == .presentActions {
// show
let frame = textView.frameForTextInRange(characterRange)
let shareController = PostSharingController()
shareController.shareURL(url: URL as NSURL, fromRect: frame, inView: textView, inViewController: self)
} else {
presentWebViewControllerWithURL(URL)
}
return false
}
func richContentView(_ richContentView: WPRichContentView, didReceiveImageAction image: WPRichTextImage) {
var controller: WPImageViewController
if WPImageViewController.isUrlSupported(image.linkURL as URL!) {
controller = WPImageViewController(image: image.imageView.image, andURL: image.linkURL as URL!)
} else if let linkURL = image.linkURL {
presentWebViewControllerWithURL(linkURL as URL)
return
} else {
controller = WPImageViewController(image: image.imageView.image)
}
controller.modalTransitionStyle = .crossDissolve
controller.modalPresentationStyle = .fullScreen
present(controller, animated: true, completion: nil)
}
}
// MARK: - UIScrollView Delegate Methods
extension ReaderDetailViewController : UIScrollViewDelegate {
public func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {
if UIDevice.isPad() || footerView.isHidden || !isLoaded {
return
}
// The threshold for hiding the bars is twice the height of the hidden bars.
// This ensures that once the bars are hidden the view can still be scrolled
// and thus can unhide the bars.
var threshold = footerViewHeightConstraintConstant
if let navHeight = navigationController?.navigationBar.frame.height {
threshold += navHeight
}
threshold *= 2.0
let y = targetContentOffset.pointee.y
if y > scrollView.contentOffset.y && y > threshold {
setBarsHidden(true)
} else {
// Velocity will be 0,0 if the user taps to stop an in progress scroll.
// If the bars are already visible its fine but if the bars are hidden
// we don't want to jar the user by having them reappear.
if !velocity.equalTo(CGPoint.zero) {
setBarsHidden(false)
}
}
}
public func scrollViewDidScrollToTop(_ scrollView: UIScrollView) {
setBarsHidden(false)
}
public func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
if isScrollViewAtBottom() {
setBarsHidden(false)
}
}
}
// Expand this view controller to full screen if possible
extension ReaderDetailViewController: PrefersFullscreenDisplay {}
// Let's the split view know this vc changes the status bar style.
extension ReaderDetailViewController: DefinesVariableStatusBarStyle {}
|
1ebfbde92f644b36cd5ebf83c8d8861b
| 35.500443 | 207 | 0.647092 | false | false | false | false |
slavapestov/swift
|
refs/heads/master
|
stdlib/private/StdlibCollectionUnittest/CheckCollectionType.swift
|
apache-2.0
|
1
|
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import StdlibUnittest
public struct SubscriptRangeTest {
public let expected: [OpaqueValue<Int>]
public let collection: [OpaqueValue<Int>]
public let bounds: Range<Int>
public let count: Int
public let loc: SourceLoc
public var isEmpty: Bool { return count == 0 }
public func boundsIn<C : CollectionType>(c: C) -> Range<C.Index> {
let i = c.startIndex
return Range(
start: i.advancedBy(numericCast(bounds.startIndex)),
end: i.advancedBy(numericCast(bounds.endIndex)))
}
public init(
expected: [Int], collection: [Int], bounds: Range<Int>,
count: Int,
file: String = #file, line: UInt = #line
) {
self.expected = expected.map(OpaqueValue.init)
self.collection = collection.map(OpaqueValue.init)
self.bounds = bounds
self.count = count
self.loc = SourceLoc(file, line, comment: "test data")
}
}
public struct PrefixThroughTest {
public var collection: [Int]
public let position: Int
public let expected: [Int]
public let loc: SourceLoc
init(
collection: [Int], position: Int, expected: [Int],
file: String = #file, line: UInt = #line
) {
self.collection = collection
self.position = position
self.expected = expected
self.loc = SourceLoc(file, line, comment: "prefix() test data")
}
}
public struct PrefixUpToTest {
public var collection: [Int]
public let end: Int
public let expected: [Int]
public let loc: SourceLoc
public init(
collection: [Int], end: Int, expected: [Int],
file: String = #file, line: UInt = #line
) {
self.collection = collection
self.end = end
self.expected = expected
self.loc = SourceLoc(file, line, comment: "prefix() test data")
}
}
internal struct RemoveFirstNTest {
let collection: [Int]
let numberToRemove: Int
let expectedCollection: [Int]
let loc: SourceLoc
init(
collection: [Int], numberToRemove: Int, expectedCollection: [Int],
file: String = #file, line: UInt = #line
) {
self.collection = collection
self.numberToRemove = numberToRemove
self.expectedCollection = expectedCollection
self.loc = SourceLoc(file, line, comment: "removeFirst(n: Int) test data")
}
}
public struct SuffixFromTest {
public var collection: [Int]
public let start: Int
public let expected: [Int]
public let loc: SourceLoc
init(
collection: [Int], start: Int, expected: [Int],
file: String = #file, line: UInt = #line
) {
self.collection = collection
self.start = start
self.expected = expected
self.loc = SourceLoc(file, line, comment: "prefix() test data")
}
}
public let subscriptRangeTests = [
// Slice an empty collection.
SubscriptRangeTest(
expected: [],
collection: [],
bounds: 0..<0,
count: 0),
// Slice to the full extent.
SubscriptRangeTest(
expected: [ 1010 ],
collection: [ 1010 ],
bounds: 0..<1,
count: 1),
SubscriptRangeTest(
expected: [ 1010, 2020, 3030 ],
collection: [ 1010, 2020, 3030 ],
bounds: 0..<3,
count: 3),
// Slice an empty prefix.
SubscriptRangeTest(
expected: [],
collection: [ 1010, 2020, 3030 ],
bounds: 0..<0,
count: 3),
// Slice a prefix.
SubscriptRangeTest(
expected: [ 1010, 2020 ],
collection: [ 1010, 2020, 3030 ],
bounds: 0..<2,
count: 3),
// Slice an empty suffix.
SubscriptRangeTest(
expected: [],
collection: [ 1010, 2020, 3030 ],
bounds: 3..<3,
count: 3),
// Slice a suffix.
SubscriptRangeTest(
expected: [ 2020, 3030 ],
collection: [ 1010, 2020, 3030 ],
bounds: 1..<3,
count: 3),
// Slice an empty range in the middle.
SubscriptRangeTest(
expected: [],
collection: [ 1010, 2020, 3030 ],
bounds: 2..<2,
count: 3),
// Slice the middle part.
SubscriptRangeTest(
expected: [ 2020 ],
collection: [ 1010, 2020, 3030 ],
bounds: 1..<2,
count: 3),
SubscriptRangeTest(
expected: [ 2020, 3030, 4040 ],
collection: [ 1010, 2020, 3030, 4040, 5050, 6060 ],
bounds: 1..<4,
count: 6),
]
public let prefixUpToTests = [
PrefixUpToTest(
collection: [],
end: 0,
expected: []
),
PrefixUpToTest(
collection: [1010, 2020, 3030, 4040, 5050],
end: 3,
expected: [1010, 2020, 3030]
),
PrefixUpToTest(
collection: [1010, 2020, 3030, 4040, 5050],
end: 5,
expected: [1010, 2020, 3030, 4040, 5050]
),
]
public let prefixThroughTests = [
PrefixThroughTest(
collection: [1010, 2020, 3030, 4040, 5050],
position: 0,
expected: [1010]
),
PrefixThroughTest(
collection: [1010, 2020, 3030, 4040, 5050],
position: 2,
expected: [1010, 2020, 3030]
),
PrefixThroughTest(
collection: [1010, 2020, 3030, 4040, 5050],
position: 4,
expected: [1010, 2020, 3030, 4040, 5050]
),
]
public let suffixFromTests = [
SuffixFromTest(
collection: [],
start: 0,
expected: []
),
SuffixFromTest(
collection: [1010, 2020, 3030, 4040, 5050],
start: 0,
expected: [1010, 2020, 3030, 4040, 5050]
),
SuffixFromTest(
collection: [1010, 2020, 3030, 4040, 5050],
start: 3,
expected: [4040, 5050]
),
SuffixFromTest(
collection: [1010, 2020, 3030, 4040, 5050],
start: 5,
expected: []
),
]
let removeFirstTests: [RemoveFirstNTest] = [
RemoveFirstNTest(
collection: [1010],
numberToRemove: 0,
expectedCollection: [1010]
),
RemoveFirstNTest(
collection: [1010],
numberToRemove: 1,
expectedCollection: []
),
RemoveFirstNTest(
collection: [1010, 2020, 3030, 4040, 5050],
numberToRemove: 0,
expectedCollection: [1010, 2020, 3030, 4040, 5050]
),
RemoveFirstNTest(
collection: [1010, 2020, 3030, 4040, 5050],
numberToRemove: 1,
expectedCollection: [2020, 3030, 4040, 5050]
),
RemoveFirstNTest(
collection: [1010, 2020, 3030, 4040, 5050],
numberToRemove: 2,
expectedCollection: [3030, 4040, 5050]
),
RemoveFirstNTest(
collection: [1010, 2020, 3030, 4040, 5050],
numberToRemove: 3,
expectedCollection: [4040, 5050]
),
RemoveFirstNTest(
collection: [1010, 2020, 3030, 4040, 5050],
numberToRemove: 4,
expectedCollection: [5050]
),
RemoveFirstNTest(
collection: [1010, 2020, 3030, 4040, 5050],
numberToRemove: 5,
expectedCollection: []
),
]
extension TestSuite {
public func addForwardCollectionTests<
Collection : CollectionType,
CollectionWithEquatableElement : CollectionType
where
Collection.SubSequence : CollectionType,
Collection.SubSequence.Generator.Element == Collection.Generator.Element,
Collection.SubSequence.SubSequence == Collection.SubSequence,
CollectionWithEquatableElement.Generator.Element : Equatable
>(
testNamePrefix: String = "",
makeCollection: ([Collection.Generator.Element]) -> Collection,
wrapValue: (OpaqueValue<Int>) -> Collection.Generator.Element,
extractValue: (Collection.Generator.Element) -> OpaqueValue<Int>,
makeCollectionOfEquatable: ([CollectionWithEquatableElement.Generator.Element]) -> CollectionWithEquatableElement,
wrapValueIntoEquatable: (MinimalEquatableValue) -> CollectionWithEquatableElement.Generator.Element,
extractValueFromEquatable: ((CollectionWithEquatableElement.Generator.Element) -> MinimalEquatableValue),
checksAdded: Box<Set<String>> = Box([]),
resiliencyChecks: CollectionMisuseResiliencyChecks = .all,
outOfBoundsIndexOffset: Int = 1,
outOfBoundsSubscriptOffset: Int = 1
) {
var testNamePrefix = testNamePrefix
if checksAdded.value.contains(#function) {
return
}
checksAdded.value.insert(#function)
addSequenceTests(
testNamePrefix,
makeSequence: makeCollection,
wrapValue: wrapValue,
extractValue: extractValue,
makeSequenceOfEquatable: makeCollectionOfEquatable,
wrapValueIntoEquatable: wrapValueIntoEquatable,
extractValueFromEquatable: extractValueFromEquatable,
checksAdded: checksAdded,
resiliencyChecks: resiliencyChecks)
func makeWrappedCollection(elements: [OpaqueValue<Int>]) -> Collection {
return makeCollection(elements.map(wrapValue))
}
func makeWrappedCollectionWithEquatableElement(
elements: [MinimalEquatableValue]
) -> CollectionWithEquatableElement {
return makeCollectionOfEquatable(elements.map(wrapValueIntoEquatable))
}
testNamePrefix += String(Collection.Type)
//===----------------------------------------------------------------------===//
// generate()
//===----------------------------------------------------------------------===//
self.test("\(testNamePrefix).generate()/semantics") {
for test in subscriptRangeTests {
let c = makeWrappedCollection(test.collection)
for _ in 0..<3 {
checkSequence(
test.collection.map(wrapValue),
c,
resiliencyChecks: .none) {
extractValue($0).value == extractValue($1).value
}
}
}
}
//===----------------------------------------------------------------------===//
// Index
//===----------------------------------------------------------------------===//
if resiliencyChecks.creatingOutOfBoundsIndicesBehavior != .None {
self.test("\(testNamePrefix).Index/OutOfBounds/Right/NonEmpty") {
let c = makeWrappedCollection([ 1010, 2020, 3030 ].map(OpaqueValue.init))
let index = c.endIndex
if resiliencyChecks.creatingOutOfBoundsIndicesBehavior == .Trap {
expectCrashLater()
_blackHole(index.advancedBy(numericCast(outOfBoundsIndexOffset)))
} else {
expectFailure {
_blackHole(index.advancedBy(numericCast(outOfBoundsIndexOffset)))
}
}
}
self.test("\(testNamePrefix).Index/OutOfBounds/Right/Empty") {
let c = makeWrappedCollection([])
let index = c.endIndex
if resiliencyChecks.creatingOutOfBoundsIndicesBehavior == .Trap {
expectCrashLater()
_blackHole(index.advancedBy(numericCast(outOfBoundsIndexOffset)))
} else {
expectFailure {
_blackHole(index.advancedBy(numericCast(outOfBoundsIndexOffset)))
}
}
}
}
//===----------------------------------------------------------------------===//
// subscript(_: Index)
//===----------------------------------------------------------------------===//
if resiliencyChecks.subscriptOnOutOfBoundsIndicesBehavior != .None {
self.test("\(testNamePrefix).subscript(_: Index)/OutOfBounds/Right/NonEmpty/Get") {
let c = makeWrappedCollection([ 1010, 2020, 3030 ].map(OpaqueValue.init))
var index = c.endIndex
if resiliencyChecks.subscriptOnOutOfBoundsIndicesBehavior == .Trap {
expectCrashLater()
index = index.advancedBy(numericCast(outOfBoundsSubscriptOffset))
_blackHole(c[index])
} else {
expectFailure {
index = index.advancedBy(numericCast(outOfBoundsSubscriptOffset))
_blackHole(c[index])
}
}
}
self.test("\(testNamePrefix).subscript(_: Index)/OutOfBounds/Right/Empty/Get") {
let c = makeWrappedCollection([])
var index = c.endIndex
if resiliencyChecks.subscriptOnOutOfBoundsIndicesBehavior == .Trap {
expectCrashLater()
index = index.advancedBy(numericCast(outOfBoundsSubscriptOffset))
_blackHole(c[index])
} else {
expectFailure {
index = index.advancedBy(numericCast(outOfBoundsSubscriptOffset))
_blackHole(c[index])
}
}
}
}
//===----------------------------------------------------------------------===//
// subscript(_: Range)
//===----------------------------------------------------------------------===//
self.test("\(testNamePrefix).subscript(_: Range)/Get/semantics") {
for test in subscriptRangeTests {
let c = makeWrappedCollection(test.collection)
let result = c[test.boundsIn(c)]
// FIXME: improve checkForwardCollection to check the SubSequence type.
checkForwardCollection(
test.expected.map(wrapValue),
result,
resiliencyChecks: .none) {
extractValue($0).value == extractValue($1).value
}
}
}
if resiliencyChecks.subscriptRangeOnOutOfBoundsRangesBehavior != .None {
self.test("\(testNamePrefix).subscript(_: Range)/OutOfBounds/Right/NonEmpty/Get") {
let c = makeWrappedCollection([ 1010, 2020, 3030 ].map(OpaqueValue.init))
var index = c.endIndex
if resiliencyChecks.subscriptRangeOnOutOfBoundsRangesBehavior == .Trap {
expectCrashLater()
index = index.advancedBy(numericCast(outOfBoundsSubscriptOffset))
_blackHole(c[index..<index])
} else {
expectFailure {
index = index.advancedBy(numericCast(outOfBoundsSubscriptOffset))
_blackHole(c[index..<index])
}
}
}
self.test("\(testNamePrefix).subscript(_: Range)/OutOfBounds/Right/Empty/Get") {
let c = makeWrappedCollection([])
var index = c.endIndex
if resiliencyChecks.subscriptRangeOnOutOfBoundsRangesBehavior == .Trap {
expectCrashLater()
index = index.advancedBy(numericCast(outOfBoundsSubscriptOffset))
_blackHole(c[index..<index])
} else {
expectFailure {
index = index.advancedBy(numericCast(outOfBoundsSubscriptOffset))
_blackHole(c[index..<index])
}
}
}
}
//===----------------------------------------------------------------------===//
// isEmpty
//===----------------------------------------------------------------------===//
self.test("\(testNamePrefix).isEmpty/semantics") {
for test in subscriptRangeTests {
let c = makeWrappedCollection(test.collection)
expectEqual(test.isEmpty, c.isEmpty)
}
}
//===----------------------------------------------------------------------===//
// count
//===----------------------------------------------------------------------===//
self.test("\(testNamePrefix).count/semantics") {
for test in subscriptRangeTests {
let c = makeWrappedCollection(test.collection)
expectEqual(test.count, numericCast(c.count) as Int)
}
}
//===----------------------------------------------------------------------===//
// indexOf()
//===----------------------------------------------------------------------===//
self.test("\(testNamePrefix).indexOf()/WhereElementIsEquatable/semantics") {
for test in findTests {
let c = makeWrappedCollectionWithEquatableElement(test.sequence)
var result = c.indexOf(wrapValueIntoEquatable(test.element))
expectType(
Optional<CollectionWithEquatableElement.Index>.self,
&result)
let zeroBasedIndex = result.map {
numericCast(c.startIndex.distanceTo($0)) as Int
}
expectEqual(
test.expected,
zeroBasedIndex,
stackTrace: SourceLocStack().with(test.loc))
}
}
self.test("\(testNamePrefix).indexOf()/Predicate/semantics") {
for test in findTests {
let c = makeWrappedCollectionWithEquatableElement(test.sequence)
let closureLifetimeTracker = LifetimeTracked(0)
expectEqual(1, LifetimeTracked.instances)
let result = c.indexOf {
(candidate) in
_blackHole(closureLifetimeTracker)
return extractValueFromEquatable(candidate).value == test.element.value
}
let zeroBasedIndex = result.map {
numericCast(c.startIndex.distanceTo($0)) as Int
}
expectEqual(
test.expected,
zeroBasedIndex,
stackTrace: SourceLocStack().with(test.loc))
}
}
//===----------------------------------------------------------------------===//
// first
//===----------------------------------------------------------------------===//
self.test("\(testNamePrefix).first") {
for test in subscriptRangeTests {
let c = makeWrappedCollection(test.collection)
let result = c.first
if test.isEmpty {
expectEmpty(result)
} else {
expectOptionalEqual(
test.collection[0],
result.map(extractValue)
) { $0.value == $1.value }
}
}
}
//===----------------------------------------------------------------------===//
// indices
//===----------------------------------------------------------------------===//
self.test("\(testNamePrefix).indices") {
for test in subscriptRangeTests {
let c = makeWrappedCollection(test.collection)
let indices = c.indices
expectEqual(c.startIndex, indices.startIndex)
expectEqual(c.endIndex, indices.endIndex)
}
}
//===----------------------------------------------------------------------===//
// dropFirst()
//===----------------------------------------------------------------------===//
self.test("\(testNamePrefix).dropFirst/semantics") {
for test in dropFirstTests {
let s = makeWrappedCollection(test.sequence.map(OpaqueValue.init))
let result = s.dropFirst(test.dropElements)
expectEqualSequence(
test.expected, result.map(extractValue).map { $0.value },
stackTrace: SourceLocStack().with(test.loc))
}
}
//===----------------------------------------------------------------------===//
// dropLast()
//===----------------------------------------------------------------------===//
self.test("\(testNamePrefix).dropLast/semantics") {
for test in dropLastTests {
let s = makeWrappedCollection(test.sequence.map(OpaqueValue.init))
let result = s.dropLast(test.dropElements)
expectEqualSequence(test.expected, result.map(extractValue).map { $0.value },
stackTrace: SourceLocStack().with(test.loc))
}
}
//===----------------------------------------------------------------------===//
// prefix()
//===----------------------------------------------------------------------===//
self.test("\(testNamePrefix).prefix/semantics") {
for test in prefixTests {
let s = makeWrappedCollection(test.sequence.map(OpaqueValue.init))
let result = s.prefix(test.maxLength)
expectEqualSequence(test.expected, result.map(extractValue).map { $0.value },
stackTrace: SourceLocStack().with(test.loc))
}
}
//===----------------------------------------------------------------------===//
// suffix()
//===----------------------------------------------------------------------===//
self.test("\(testNamePrefix).suffix/semantics") {
for test in suffixTests {
let s = makeWrappedCollection(test.sequence.map(OpaqueValue.init))
let result = s.suffix(test.maxLength)
expectEqualSequence(test.expected, result.map(extractValue).map { $0.value },
stackTrace: SourceLocStack().with(test.loc))
}
}
//===----------------------------------------------------------------------===//
// split()
//===----------------------------------------------------------------------===//
self.test("\(testNamePrefix).split/semantics") {
for test in splitTests {
let s = makeWrappedCollection(test.sequence.map(OpaqueValue.init))
let result = s.split(test.maxSplit,
allowEmptySlices: test.allowEmptySlices) {
extractValue($0).value == test.separator
}
expectEqualSequence(test.expected, result.map {
$0.map {
extractValue($0).value
}
},
stackTrace: SourceLocStack().with(test.loc)) { $0 == $1 }
}
}
//===----------------------------------------------------------------------===//
// prefixThrough()
//===----------------------------------------------------------------------===//
self.test("\(testNamePrefix).prefixThrough/semantics") {
for test in prefixThroughTests {
let c = makeWrappedCollection(test.collection.map(OpaqueValue.init))
let index = c.startIndex.advancedBy(numericCast(test.position))
let result = c.prefixThrough(index)
expectEqualSequence(test.expected, result.map(extractValue).map { $0.value },
stackTrace: SourceLocStack().with(test.loc))
}
}
//===----------------------------------------------------------------------===//
// prefixUpTo()
//===----------------------------------------------------------------------===//
self.test("\(testNamePrefix).prefixUpTo/semantics") {
for test in prefixUpToTests {
let c = makeWrappedCollection(test.collection.map(OpaqueValue.init))
let index = c.startIndex.advancedBy(numericCast(test.end))
let result = c.prefixUpTo(index)
expectEqualSequence(test.expected, result.map(extractValue).map { $0.value },
stackTrace: SourceLocStack().with(test.loc))
}
}
//===----------------------------------------------------------------------===//
// suffixFrom()
//===----------------------------------------------------------------------===//
self.test("\(testNamePrefix).suffixFrom/semantics") {
for test in suffixFromTests {
let c = makeWrappedCollection(test.collection.map(OpaqueValue.init))
let index = c.startIndex.advancedBy(numericCast(test.start))
let result = c.suffixFrom(index)
expectEqualSequence(test.expected, result.map(extractValue).map { $0.value },
stackTrace: SourceLocStack().with(test.loc))
}
}
//===----------------------------------------------------------------------===//
// removeFirst()/slice
//===----------------------------------------------------------------------===//
self.test("\(testNamePrefix).removeFirst()/slice/semantics") {
for test in removeFirstTests.filter({ $0.numberToRemove == 1 }) {
let c = makeWrappedCollection(test.collection.map(OpaqueValue.init))
var slice = c[c.startIndex..<c.endIndex]
let survivingIndices = Array(slice.startIndex.successor()..<slice.endIndex)
let removedElement = slice.removeFirst()
expectEqual(test.collection.first, extractValue(removedElement).value)
expectEqualSequence(
test.expectedCollection,
slice.map { extractValue($0).value },
"removeFirst() shouldn't mutate the tail of the slice",
stackTrace: SourceLocStack().with(test.loc)
)
expectEqualSequence(
test.expectedCollection,
survivingIndices.map { extractValue(slice[$0]).value },
"removeFirst() shouldn't invalidate indices",
stackTrace: SourceLocStack().with(test.loc)
)
expectEqualSequence(
test.collection,
c.map { extractValue($0).value },
"removeFirst() shouldn't mutate the collection that was sliced",
stackTrace: SourceLocStack().with(test.loc))
}
}
self.test("\(testNamePrefix).removeFirst()/slice/empty/semantics") {
let c = makeWrappedCollection(Array<OpaqueValue<Int>>())
var slice = c[c.startIndex..<c.startIndex]
expectCrashLater()
_ = slice.removeFirst() // Should trap.
}
//===----------------------------------------------------------------------===//
// removeFirst(n: Int)/slice
//===----------------------------------------------------------------------===//
self.test("\(testNamePrefix).removeFirst(n: Int)/slice/semantics") {
for test in removeFirstTests {
let c = makeWrappedCollection(test.collection.map(OpaqueValue.init))
var slice = c[c.startIndex..<c.endIndex]
let survivingIndices =
Array(
slice.startIndex.advancedBy(numericCast(test.numberToRemove)) ..<
slice.endIndex
)
slice.removeFirst(test.numberToRemove)
expectEqualSequence(
test.expectedCollection,
slice.map { extractValue($0).value },
"removeFirst() shouldn't mutate the tail of the slice",
stackTrace: SourceLocStack().with(test.loc)
)
expectEqualSequence(
test.expectedCollection,
survivingIndices.map { extractValue(slice[$0]).value },
"removeFirst() shouldn't invalidate indices",
stackTrace: SourceLocStack().with(test.loc)
)
expectEqualSequence(
test.collection,
c.map { extractValue($0).value },
"removeFirst() shouldn't mutate the collection that was sliced",
stackTrace: SourceLocStack().with(test.loc))
}
}
self.test("\(testNamePrefix).removeFirst(n: Int)/slice/empty/semantics") {
let c = makeWrappedCollection(Array<OpaqueValue<Int>>())
var slice = c[c.startIndex..<c.startIndex]
expectCrashLater()
slice.removeFirst(1) // Should trap.
}
self.test("\(testNamePrefix).removeFirst(n: Int)/slice/removeNegative/semantics") {
let c = makeWrappedCollection([1010, 2020].map(OpaqueValue.init))
var slice = c[c.startIndex..<c.startIndex]
expectCrashLater()
slice.removeFirst(-1) // Should trap.
}
self.test("\(testNamePrefix).removeFirst(n: Int)/slice/removeTooMany/semantics") {
let c = makeWrappedCollection([1010, 2020].map(OpaqueValue.init))
var slice = c[c.startIndex..<c.startIndex]
expectCrashLater()
slice.removeFirst(3) // Should trap.
}
//===----------------------------------------------------------------------===//
// popFirst()/slice
//===----------------------------------------------------------------------===//
self.test("\(testNamePrefix).popFirst()/slice/semantics") {
// This can just reuse the test data for removeFirst()
for test in removeFirstTests.filter({ $0.numberToRemove == 1 }) {
let c = makeWrappedCollection(test.collection.map(OpaqueValue.init))
var slice = c[c.startIndex..<c.endIndex]
let survivingIndices = Array(slice.startIndex.successor()..<slice.endIndex)
let removedElement = slice.popFirst()!
expectEqual(test.collection.first, extractValue(removedElement).value)
expectEqualSequence(
test.expectedCollection,
slice.map { extractValue($0).value },
"popFirst() shouldn't mutate the tail of the slice",
stackTrace: SourceLocStack().with(test.loc)
)
expectEqualSequence(
test.expectedCollection,
survivingIndices.map { extractValue(slice[$0]).value },
"popFirst() shouldn't invalidate indices",
stackTrace: SourceLocStack().with(test.loc)
)
expectEqualSequence(
test.collection,
c.map { extractValue($0).value },
"popFirst() shouldn't mutate the collection that was sliced",
stackTrace: SourceLocStack().with(test.loc))
}
}
self.test("\(testNamePrefix).popFirst()/slice/empty/semantics") {
let c = makeWrappedCollection(Array<OpaqueValue<Int>>())
var slice = c[c.startIndex..<c.startIndex]
expectEmpty(slice.popFirst())
}
//===----------------------------------------------------------------------===//
} // addForwardCollectionTests
public func addBidirectionalCollectionTests<
Collection : CollectionType,
CollectionWithEquatableElement : CollectionType
where
Collection.Index : BidirectionalIndexType,
Collection.SubSequence : CollectionType,
Collection.SubSequence.Generator.Element == Collection.Generator.Element,
Collection.SubSequence.Index : BidirectionalIndexType,
Collection.SubSequence.SubSequence == Collection.SubSequence,
CollectionWithEquatableElement.Index : BidirectionalIndexType,
CollectionWithEquatableElement.Generator.Element : Equatable
>(
testNamePrefix: String = "",
makeCollection: ([Collection.Generator.Element]) -> Collection,
wrapValue: (OpaqueValue<Int>) -> Collection.Generator.Element,
extractValue: (Collection.Generator.Element) -> OpaqueValue<Int>,
makeCollectionOfEquatable: ([CollectionWithEquatableElement.Generator.Element]) -> CollectionWithEquatableElement,
wrapValueIntoEquatable: (MinimalEquatableValue) -> CollectionWithEquatableElement.Generator.Element,
extractValueFromEquatable: ((CollectionWithEquatableElement.Generator.Element) -> MinimalEquatableValue),
checksAdded: Box<Set<String>> = Box([]),
resiliencyChecks: CollectionMisuseResiliencyChecks = .all,
outOfBoundsIndexOffset: Int = 1,
outOfBoundsSubscriptOffset: Int = 1
) {
var testNamePrefix = testNamePrefix
if checksAdded.value.contains(#function) {
return
}
checksAdded.value.insert(#function)
addForwardCollectionTests(
testNamePrefix,
makeCollection: makeCollection,
wrapValue: wrapValue,
extractValue: extractValue,
makeCollectionOfEquatable: makeCollectionOfEquatable,
wrapValueIntoEquatable: wrapValueIntoEquatable,
extractValueFromEquatable: extractValueFromEquatable,
checksAdded: checksAdded,
resiliencyChecks: resiliencyChecks,
outOfBoundsIndexOffset: outOfBoundsIndexOffset,
outOfBoundsSubscriptOffset: outOfBoundsSubscriptOffset)
func makeWrappedCollection(elements: [OpaqueValue<Int>]) -> Collection {
return makeCollection(elements.map(wrapValue))
}
testNamePrefix += String(Collection.Type)
//===----------------------------------------------------------------------===//
// last
//===----------------------------------------------------------------------===//
self.test("\(testNamePrefix).last") {
for test in subscriptRangeTests {
let c = makeWrappedCollection(test.collection)
let result = c.last
if test.isEmpty {
expectEmpty(result)
} else {
expectOptionalEqual(
test.collection[test.count - 1],
result.map(extractValue)
) { $0.value == $1.value }
}
}
}
//===----------------------------------------------------------------------===//
// removeLast()/slice
//===----------------------------------------------------------------------===//
self.test("\(testNamePrefix).removeLast()/slice/semantics") {
for test in removeLastTests.filter({ $0.numberToRemove == 1 }) {
let c = makeWrappedCollection(test.collection)
var slice = c[c.startIndex..<c.endIndex]
let survivingIndices =
Array(
slice.startIndex ..<
slice.endIndex.advancedBy(numericCast(-test.numberToRemove))
)
let removedElement = slice.removeLast()
expectEqual(
test.collection.last!.value,
extractValue(removedElement).value)
expectEqualSequence(
test.expectedCollection,
slice.map { extractValue($0).value },
"removeLast() shouldn't mutate the head of the slice",
stackTrace: SourceLocStack().with(test.loc)
)
expectEqualSequence(
test.expectedCollection,
survivingIndices.map { extractValue(slice[$0]).value },
"removeLast() shouldn't invalidate indices",
stackTrace: SourceLocStack().with(test.loc)
)
expectEqualSequence(
test.collection.map { $0.value },
c.map { extractValue($0).value },
"removeLast() shouldn't mutate the collection that was sliced",
stackTrace: SourceLocStack().with(test.loc))
}
}
self.test("\(testNamePrefix).removeLast()/slice/empty/semantics") {
let c = makeWrappedCollection(Array<OpaqueValue<Int>>())
var slice = c[c.startIndex..<c.startIndex]
expectCrashLater()
_ = slice.removeLast() // Should trap.
}
//===----------------------------------------------------------------------===//
// removeLast(n: Int)/slice
//===----------------------------------------------------------------------===//
self.test("\(testNamePrefix).removeLast(n: Int)/slice/semantics") {
for test in removeLastTests {
let c = makeWrappedCollection(test.collection)
var slice = c[c.startIndex..<c.endIndex]
let survivingIndices =
Array(
slice.startIndex ..<
slice.endIndex.advancedBy(numericCast(-test.numberToRemove))
)
slice.removeLast(test.numberToRemove)
expectEqualSequence(
test.expectedCollection,
slice.map { extractValue($0).value },
"removeLast() shouldn't mutate the head of the slice",
stackTrace: SourceLocStack().with(test.loc)
)
expectEqualSequence(
test.expectedCollection,
survivingIndices.map { extractValue(slice[$0]).value },
"removeLast() shouldn't invalidate indices",
stackTrace: SourceLocStack().with(test.loc)
)
expectEqualSequence(
test.collection.map { $0.value },
c.map { extractValue($0).value },
"removeLast() shouldn't mutate the collection that was sliced",
stackTrace: SourceLocStack().with(test.loc))
}
}
self.test("\(testNamePrefix).removeLast(n: Int)/slice/empty/semantics") {
let c = makeWrappedCollection(Array<OpaqueValue<Int>>())
var slice = c[c.startIndex..<c.startIndex]
expectCrashLater()
slice.removeLast(1) // Should trap.
}
self.test("\(testNamePrefix).removeLast(n: Int)/slice/removeNegative/semantics") {
let c = makeWrappedCollection([1010, 2020].map(OpaqueValue.init))
var slice = c[c.startIndex..<c.startIndex]
expectCrashLater()
slice.removeLast(-1) // Should trap.
}
self.test("\(testNamePrefix).removeLast(n: Int)/slice/removeTooMany/semantics") {
let c = makeWrappedCollection([1010, 2020].map(OpaqueValue.init))
var slice = c[c.startIndex..<c.startIndex]
expectCrashLater()
slice.removeLast(3) // Should trap.
}
//===----------------------------------------------------------------------===//
// popLast()/slice
//===----------------------------------------------------------------------===//
self.test("\(testNamePrefix).popLast()/slice/semantics") {
// This can just reuse the test data for removeLast()
for test in removeLastTests.filter({ $0.numberToRemove == 1 }) {
let c = makeWrappedCollection(test.collection)
var slice = c[c.startIndex..<c.endIndex]
let survivingIndices =
Array(
slice.startIndex ..<
slice.endIndex.advancedBy(numericCast(-test.numberToRemove))
)
let removedElement = slice.popLast()!
expectEqual(
test.collection.last!.value,
extractValue(removedElement).value)
expectEqualSequence(
test.expectedCollection,
slice.map { extractValue($0).value },
"popLast() shouldn't mutate the head of the slice",
stackTrace: SourceLocStack().with(test.loc)
)
expectEqualSequence(
test.expectedCollection,
survivingIndices.map { extractValue(slice[$0]).value },
"popLast() shouldn't invalidate indices",
stackTrace: SourceLocStack().with(test.loc)
)
expectEqualSequence(
test.collection.map { $0.value },
c.map { extractValue($0).value },
"popLast() shouldn't mutate the collection that was sliced",
stackTrace: SourceLocStack().with(test.loc))
}
}
self.test("\(testNamePrefix).popLast()/slice/empty/semantics") {
let c = makeWrappedCollection(Array<OpaqueValue<Int>>())
var slice = c[c.startIndex..<c.startIndex]
expectEmpty(slice.popLast())
}
//===----------------------------------------------------------------------===//
// Index
//===----------------------------------------------------------------------===//
if resiliencyChecks.creatingOutOfBoundsIndicesBehavior != .None {
self.test("\(testNamePrefix).Index/OutOfBounds/Left/NonEmpty") {
let c = makeWrappedCollection([ 1010, 2020, 3030 ].map(OpaqueValue.init))
let index = c.startIndex
if resiliencyChecks.creatingOutOfBoundsIndicesBehavior == .Trap {
expectCrashLater()
_blackHole(index.advancedBy(numericCast(-outOfBoundsIndexOffset)))
} else {
expectFailure {
_blackHole(index.advancedBy(numericCast(-outOfBoundsIndexOffset)))
}
}
}
self.test("\(testNamePrefix).Index/OutOfBounds/Left/Empty") {
let c = makeWrappedCollection([])
let index = c.startIndex
if resiliencyChecks.creatingOutOfBoundsIndicesBehavior == .Trap {
expectCrashLater()
_blackHole(index.advancedBy(numericCast(-outOfBoundsIndexOffset)))
} else {
expectFailure {
_blackHole(index.advancedBy(numericCast(-outOfBoundsIndexOffset)))
}
}
}
}
//===----------------------------------------------------------------------===//
// subscript(_: Index)
//===----------------------------------------------------------------------===//
if resiliencyChecks.subscriptOnOutOfBoundsIndicesBehavior != .None {
self.test("\(testNamePrefix).subscript(_: Index)/OutOfBounds/Left/NonEmpty/Get") {
let c = makeWrappedCollection([ 1010, 2020, 3030 ].map(OpaqueValue.init))
var index = c.startIndex
if resiliencyChecks.subscriptOnOutOfBoundsIndicesBehavior == .Trap {
expectCrashLater()
index = index.advancedBy(numericCast(-outOfBoundsSubscriptOffset))
_blackHole(c[index])
} else {
expectFailure {
index = index.advancedBy(numericCast(-outOfBoundsSubscriptOffset))
_blackHole(c[index])
}
}
}
self.test("\(testNamePrefix).subscript(_: Index)/OutOfBounds/Left/Empty/Get") {
let c = makeWrappedCollection([])
var index = c.startIndex
if resiliencyChecks.subscriptOnOutOfBoundsIndicesBehavior == .Trap {
expectCrashLater()
index = index.advancedBy(numericCast(-outOfBoundsSubscriptOffset))
_blackHole(c[index])
} else {
expectFailure {
index = index.advancedBy(numericCast(-outOfBoundsSubscriptOffset))
_blackHole(c[index])
}
}
}
}
//===----------------------------------------------------------------------===//
// subscript(_: Range)
//===----------------------------------------------------------------------===//
if resiliencyChecks.subscriptRangeOnOutOfBoundsRangesBehavior != .None {
self.test("\(testNamePrefix).subscript(_: Range)/OutOfBounds/Left/NonEmpty/Get") {
let c = makeWrappedCollection([ 1010, 2020, 3030 ].map(OpaqueValue.init))
var index = c.startIndex
if resiliencyChecks.subscriptRangeOnOutOfBoundsRangesBehavior == .Trap {
expectCrashLater()
index = index.advancedBy(numericCast(-outOfBoundsSubscriptOffset))
_blackHole(c[index..<index])
} else {
expectFailure {
index = index.advancedBy(numericCast(-outOfBoundsSubscriptOffset))
_blackHole(c[index..<index])
}
}
}
self.test("\(testNamePrefix).subscript(_: Range)/OutOfBounds/Left/Empty/Get") {
let c = makeWrappedCollection([])
var index = c.startIndex
if resiliencyChecks.subscriptRangeOnOutOfBoundsRangesBehavior == .Trap {
expectCrashLater()
index = index.advancedBy(numericCast(-outOfBoundsSubscriptOffset))
_blackHole(c[index..<index])
} else {
expectFailure {
index = index.advancedBy(numericCast(-outOfBoundsSubscriptOffset))
_blackHole(c[index..<index])
}
}
}
}
//===----------------------------------------------------------------------===//
// dropLast()
//===----------------------------------------------------------------------===//
self.test("\(testNamePrefix).dropLast/semantics") {
for test in dropLastTests {
let s = makeWrappedCollection(test.sequence.map(OpaqueValue.init))
let result = s.dropLast(test.dropElements)
expectEqualSequence(test.expected, result.map(extractValue).map { $0.value },
stackTrace: SourceLocStack().with(test.loc))
}
}
//===----------------------------------------------------------------------===//
// suffix()
//===----------------------------------------------------------------------===//
self.test("\(testNamePrefix).suffix/semantics") {
for test in suffixTests {
let s = makeWrappedCollection(test.sequence.map(OpaqueValue.init))
let result = s.suffix(test.maxLength)
expectEqualSequence(test.expected, result.map(extractValue).map { $0.value },
stackTrace: SourceLocStack().with(test.loc))
}
}
//===----------------------------------------------------------------------===//
} // addBidirectionalCollectionTests
public func addRandomAccessCollectionTests<
Collection : CollectionType,
CollectionWithEquatableElement : CollectionType
where
Collection.Index : RandomAccessIndexType,
Collection.SubSequence : CollectionType,
Collection.SubSequence.Generator.Element == Collection.Generator.Element,
Collection.SubSequence.Index : RandomAccessIndexType,
Collection.SubSequence.SubSequence == Collection.SubSequence,
CollectionWithEquatableElement.Index : RandomAccessIndexType,
CollectionWithEquatableElement.Generator.Element : Equatable
>(
testNamePrefix: String = "",
makeCollection: ([Collection.Generator.Element]) -> Collection,
wrapValue: (OpaqueValue<Int>) -> Collection.Generator.Element,
extractValue: (Collection.Generator.Element) -> OpaqueValue<Int>,
makeCollectionOfEquatable: ([CollectionWithEquatableElement.Generator.Element]) -> CollectionWithEquatableElement,
wrapValueIntoEquatable: (MinimalEquatableValue) -> CollectionWithEquatableElement.Generator.Element,
extractValueFromEquatable: ((CollectionWithEquatableElement.Generator.Element) -> MinimalEquatableValue),
checksAdded: Box<Set<String>> = Box([]),
resiliencyChecks: CollectionMisuseResiliencyChecks = .all,
outOfBoundsIndexOffset: Int = 1,
outOfBoundsSubscriptOffset: Int = 1
) {
var testNamePrefix = testNamePrefix
if checksAdded.value.contains(#function) {
return
}
checksAdded.value.insert(#function)
addBidirectionalCollectionTests(
testNamePrefix,
makeCollection: makeCollection,
wrapValue: wrapValue,
extractValue: extractValue,
makeCollectionOfEquatable: makeCollectionOfEquatable,
wrapValueIntoEquatable: wrapValueIntoEquatable,
extractValueFromEquatable: extractValueFromEquatable,
checksAdded: checksAdded,
resiliencyChecks: resiliencyChecks,
outOfBoundsIndexOffset: outOfBoundsIndexOffset,
outOfBoundsSubscriptOffset: outOfBoundsSubscriptOffset)
testNamePrefix += String(Collection.Type)
func makeWrappedCollection(elements: [OpaqueValue<Int>]) -> Collection {
return makeCollection(elements.map(wrapValue))
}
//===----------------------------------------------------------------------===//
// prefix()
//===----------------------------------------------------------------------===//
self.test("\(testNamePrefix).prefix/semantics") {
for test in prefixTests {
let s = makeWrappedCollection(test.sequence.map(OpaqueValue.init))
let result = s.prefix(test.maxLength)
expectEqualSequence(test.expected, result.map(extractValue).map { $0.value },
stackTrace: SourceLocStack().with(test.loc))
}
}
//===----------------------------------------------------------------------===//
// suffix()
//===----------------------------------------------------------------------===//
self.test("\(testNamePrefix).suffix/semantics") {
for test in suffixTests {
let s = makeWrappedCollection(test.sequence.map(OpaqueValue.init))
let result = s.suffix(test.maxLength)
expectEqualSequence(test.expected, result.map(extractValue).map { $0.value },
stackTrace: SourceLocStack().with(test.loc))
}
}
//===----------------------------------------------------------------------===//
} // addRandomAccessCollectionTests
}
|
cf29bc972b726cc13d136305ef51292e
| 33.219727 | 118 | 0.605713 | false | true | false | false |
fleurdeswift/data-structure
|
refs/heads/master
|
ExtraDataStructures/Task+MoveFiles.swift
|
mit
|
1
|
//
// Task+MoveTask.swift
// ExtraDataStructures
//
// Copyright © 2015 Fleur de Swift. All rights reserved.
//
import Foundation
public extension Task {
public class MoveFiles : Task {
public enum ErrorBehavior {
case Revert, Stop, Ignore
}
public func move(urls urls: [NSURL: NSURL], errorBehavior: ErrorBehavior) {
var moves = [NSURL: NSURL]();
var renames = [NSURL: NSURL]();
let errors = ErrorDictionary();
typealias statStruct = stat;
var destinationStats = [NSURL: DarwinStatStruct]();
var bytes: Int64 = 0;
for (source, destination) in urls {
if !source.fileURL {
errors[source] = NSError(domain: NSPOSIXErrorDomain, code: Int(EBADF), userInfo: [NSURLErrorKey: source]);
continue;
}
if !destination.fileURL {
errors[source] = NSError(domain: NSPOSIXErrorDomain, code: Int(EBADF), userInfo: [NSURLErrorKey: source]);
continue;
}
var destinationStat: DarwinStatStruct;
let destinationParent = destination.URLByDeletingLastPathComponent!;
if let cached = destinationStats[destinationParent] {
destinationStat = cached;
}
else {
destinationStat = DarwinStatStruct();
do {
try DarwinStat(destinationParent, &destinationStat);
try DarwinAccess(destinationParent, W_OK);
}
catch {
errors[destinationParent] = error as NSError;
}
}
do {
var sourceStat = DarwinStatStruct();
try DarwinStat(source, &sourceStat);
try DarwinAccess(source, R_OK);
try DarwinAccess(source.URLByDeletingLastPathComponent!, W_OK);
if sourceStat.st_dev != destinationStat.st_dev {
moves[source] = destination;
bytes += sourceStat.st_size;
}
else {
renames[source] = destination;
bytes += 1;
}
}
catch {
errors[source] = error as NSError;
}
}
if errors.count != 0 {
if errorBehavior != .Ignore {
self.error = errors;
return;
}
}
bytes = min(1, bytes);
var results = [NSURL]();
var moved = [NSURL: NSURL]();
var renamed = [NSURL: NSURL]();
var readed: Int64 = 0;
for (source, destination) in renames {
do {
try DarwinRename(old: source, new: destination);
renamed[source] = destination;
readed += 1;
self.progress = Double(readed) / Double(bytes);
results.append(destination);
}
catch {
errors[destination] = error as NSError;
if errorBehavior != .Ignore {
break;
}
}
}
if errors.count != 0 && errorBehavior == .Revert {
MoveFiles.revertRenames(renamed);
self.error = errors;
return;
}
if moves.count > 0 {
let blockSize = 65536 * 4;
let block = Darwin.malloc(blockSize);
defer { Darwin.free(block); }
for (source, destination) in moves {
do {
try moveFile(source, destination, block, blockSize, &readed, bytes);
moved[source] = destination;
results.append(destination);
}
catch {
Darwin.unlink(destination.fileSystemRepresentation);
errors[destination] = error as NSError;
if errorBehavior != .Ignore {
break;
}
}
self.progress = Double(readed) / Double(bytes);
}
}
if errors.count != 0 {
self.error = errors;
if errorBehavior == .Revert {
MoveFiles.revertRenames(renamed);
MoveFiles.revertMoves(moved);
return;
}
}
MoveFiles.deleteMoves(moved);
self.outputs = ["destinationURLs": results];
}
}
private func moveFile(source: NSURL, _ destination: NSURL, _ block: UnsafeMutablePointer<Void>, _ blockSize: Int, inout _ readed: Int64, _ bytes: Int64) throws {
var blockIndex = 0;
let rfd = try DarwinOpen(source, O_RDONLY);
defer { Darwin.close(rfd); }
let wfd = try DarwinOpen(destination, O_WRONLY | O_CREAT | O_EXCL);
defer { Darwin.close(wfd); }
while true {
let blockReaded = try DarwinRead(rfd, block, blockSize);
if blockReaded == 0 {
break;
}
readed += Int64(blockReaded);
try DarwinWrite(wfd, block, blockReaded);
if blockIndex++ > 16 {
blockIndex = 0;
self.progress = Double(readed) / Double(bytes);
}
}
}
private static func revertMoves(moves: [NSURL: NSURL]) {
for (_, destination) in moves {
Darwin.unlink(destination.fileSystemRepresentation);
}
}
private static func deleteMoves(moves: [NSURL: NSURL]) {
for (source, _) in moves {
Darwin.unlink(source.fileSystemRepresentation);
}
}
private static func revertRenames(renames: [NSURL: NSURL]) {
for (source, destination) in renames {
do {
try DarwinRename(old: destination, new: source);
}
catch {
}
}
}
public class func moveFiles(identifier: String, urls: [NSURL: NSURL], errorBehavior: MoveFiles.ErrorBehavior) -> Task.MoveFiles {
return MoveFiles(createWithIdentifier: identifier, description: "Move Files...", dependsOn: nil, queue: dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), barrier: false) { task in
(task as! MoveFiles).move(urls: urls, errorBehavior: errorBehavior);
}
}
}
/*
public class MoveFileTask : NSObject, LongTask {
public var progress: Double?;
public var status: String = "Moving files..."
public func cancel() {
}
public let links: [String: String];
public let moves: [NSURL: NSURL];
public let block: ([NSURL: NSError]?) -> Void
public init(linkMoves: [String: String], manualMoves: [NSURL: NSURL], manualAttributes: [NSURL: [String: AnyObject]], completionBlock: ([NSURL: NSError]?) -> Void) {
self.links = linkMoves;
self.moves = manualMoves;
self.block = completionBlock;
super.init();
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0)) {
var totalBytes: UInt64 = 0;
var readed: UInt64 = 0;
for (_, attributes) in manualAttributes {
if let bytes = attributes[NSFileSize] as? NSNumber {
totalBytes += bytes.unsignedLongLongValue;
}
}
var blockIndex = 0;
let blockSize = 65536;
let block = Darwin.malloc(blockSize);
defer { Darwin.free(block); }
for (sourceURL, destinationURL) in manualMoves {
let input = NSInputStream(URL: sourceURL)!;
let output = NSOutputStream(URL: destinationURL, append: false)!;
input.open();
output.open();
defer {
input.close();
output.close();
}
while true {
let blockReaded = input.read(UnsafeMutablePointer<UInt8>(block), maxLength: blockSize);
if blockReaded == 0 {
break;
}
else if blockReaded < 0 {
self.revert(sourceURL, error: input.streamError);
return;
}
readed += UInt64(blockReaded);
if output.write(UnsafeMutablePointer<UInt8>(block), maxLength: blockReaded) < 0 {
self.revert(destinationURL, error: output.streamError);
return;
}
if blockIndex++ > 16 {
blockIndex = 0;
let up = readed;
let upt = totalBytes;
dispatch_async(dispatch_get_main_queue()) {
self.progress = min(0.999, Double(up) / Double(upt));
NSNotificationCenter.defaultCenter().postNotificationName(LongTaskProgressChanged, object: self);
}
}
}
}
self.commit();
}
}
public class func moveFiles(files: [NSURL: NSURL], presentingViewController: NSViewController, completionBlock: ([NSURL: NSError]?) -> Void) throws {
if let task = try self.moveFiles(files, completionBlock: completionBlock) {
LongTaskSheet.show(task, parent: presentingViewController);
}
}
/// This function returns nil if the move operation can be performed using the POSIX command
/// rename.
public class func moveFiles(files: [NSURL: NSURL], completionBlock: ([NSURL: NSError]?) -> Void) throws -> LongTask? {
let manager = NSFileManager.defaultManager();
var manualMoves = [NSURL: NSURL]();
var linkMoves = [String: String]();
var attributes = [NSURL: [String: AnyObject]]();
for (source, destination) in files {
if source.fileURL && destination.fileURL {
if let sourcePath = source.path, destinationPath = destination.path {
let attr = try manager.attributesOfItemAtPath(sourcePath);
if Darwin.link(sourcePath, destinationPath) == 0 {
linkMoves[sourcePath] = destinationPath;
continue;
}
attributes[source] = attr;
}
}
manualMoves[source] = destination;
}
if manualMoves.count == 0 {
for (sourcePath, _) in linkMoves {
Darwin.unlink(sourcePath);
}
completionBlock(nil);
return nil;
}
return MoveFileTask(linkMoves: linkMoves, manualMoves: manualMoves, manualAttributes: attributes, completionBlock: completionBlock);
}
private func commit() {
for (sourcePath, _) in links {
Darwin.unlink(sourcePath);
}
for (sourceURL, _) in moves {
if sourceURL.fileURL {
if let path = sourceURL.path {
Darwin.unlink(path);
}
}
}
dispatch_async(dispatch_get_main_queue()) {
self.progress = 1.0;
NSNotificationCenter.defaultCenter().postNotificationName(LongTaskProgressChanged, object: self);
self.block(nil);
}
}
private func revert(url: NSURL, error: NSError?) {
for (_, destinationPath) in links {
Darwin.unlink(destinationPath);
}
for (_, destinationURL) in moves {
if destinationURL.fileURL {
if let path = destinationURL.path {
Darwin.unlink(path);
}
else {
assert(false);
}
}
assert(false);
}
dispatch_async(dispatch_get_main_queue()) {
self.progress = 1.0;
NSNotificationCenter.defaultCenter().postNotificationName(LongTaskProgressChanged, object: self);
if let e = error {
self.block([url: e]);
}
else {
self.block([url: NSError(domain: NSPOSIXErrorDomain, code: Int(EFAULT), userInfo: nil)]);
}
}
}
}*/
|
769ccc18a18757183e2a43594b06381e
| 33.584856 | 196 | 0.477427 | false | false | false | false |
macemmi/HBCI4Swift
|
refs/heads/master
|
HBCI4Swift/HBCI4Swift/Source/HBCILog.swift
|
gpl-2.0
|
1
|
//
// HBCILog.swift
// HBCI4Swift
//
// Created by Frank Emminghaus on 02.01.15.
// Copyright (c) 2015 Frank Emminghaus. All rights reserved.
//
import Foundation
func logError(_ message:String?, file:String = #file, function:String = #function, line:Int = #line) {
if let log = _log {
log.logError(message, file: file, function: function, line: line);
}
}
func logWarning(_ message:String?, file:String = #file, function:String = #function, line:Int = #line) {
if let log = _log {
log.logWarning(message, file: file, function: function, line: line);
}
}
func logInfo(_ message:String?, file:String = #file, function:String = #function, line:Int = #line) {
if let log = _log {
log.logInfo(message, file: file, function: function, line: line);
}
}
func logDebug(_ message:String?, file:String = #file, function:String = #function, line:Int = #line, values:Int...) {
if let msg = message {
let m = String(format: msg, arguments: values);
if let log = _log {
log.logDebug(m, file: file, function: function, line: line);
}
}
}
func logDebug(data: Data?, file:String = #file, function:String = #function, line:Int = #line) {
var result = ""
if let data = data {
data.forEach { byte in
if byte < 32 || byte > 126 {
result = result.appendingFormat("<%.02X>", byte)
} else {
result = result + String(Unicode.Scalar(byte)) //Character(Unicode.Scalar(byte))
}
}
}
if let log = _log {
log.logDebug(result, file: file, function: function, line: line);
}
}
public protocol HBCILog {
func logError(_ message:String?, file:String, function:String, line:Int);
func logWarning(_ message:String?, file:String, function:String, line:Int);
func logInfo(_ message:String?, file:String, function:String, line:Int);
func logDebug(_ message:String?, file:String, function:String, line:Int);
}
var _log:HBCILog?;
open class HBCILogManager {
open class func setLog(_ log:HBCILog) {
_log = log;
}
}
open class HBCIConsoleLog: HBCILog {
public init() {}
open func logError(_ message: String?, file:String, function:String, line:Int) {
if let msg = message {
let url = URL(fileURLWithPath: file);
print(url.lastPathComponent+", "+function+" \(line): "+msg);
} else {
let url = URL(fileURLWithPath: file);
print(url.lastPathComponent+", "+function+" \(line): nil message");
}
}
open func logWarning(_ message: String?, file:String, function:String, line:Int) {
if let msg = message {
let url = URL(fileURLWithPath: file);
print("Warning"+url.lastPathComponent+", "+function+" \(line): "+msg);
} else {
let url = URL(fileURLWithPath: file);
print("Warning: "+url.lastPathComponent+", "+function+" \(line): nil message");
}
}
open func logInfo(_ message: String?, file:String, function:String, line:Int) {
if let msg = message {
let url = URL(fileURLWithPath: file);
print("Info"+url.lastPathComponent+", "+function+" \(line): "+msg);
} else {
let url = URL(fileURLWithPath: file);
print("Info"+url.lastPathComponent+", "+function+" \(line): nil message");
}
}
open func logDebug(_ message: String?, file:String, function:String, line:Int) {
if let msg = message {
let url = URL(fileURLWithPath: file);
print("Debug"+url.lastPathComponent+", "+function+" \(line): "+msg);
} else {
let url = URL(fileURLWithPath: file);
print("Debug"+url.lastPathComponent+", "+function+" \(line): nil message");
}
}
}
|
5dc5264933cf77c6ad3799e7ab5e41bf
| 34.190909 | 117 | 0.583828 | false | false | false | false |
djflsdl08/BasicIOS
|
refs/heads/master
|
Image/Image/NasaViewController.swift
|
mit
|
1
|
//
// NasaViewController.swift
// Image
//
// Created by 김예진 on 2017. 10. 13..
// Copyright © 2017년 Kim,Yejin. All rights reserved.
//
import UIKit
class NasaViewController: UIViewController, UISplitViewControllerDelegate {
private struct Storyboard {
static let ShowImageSegue = "Show Image"
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == Storyboard.ShowImageSegue {
if let ivc = (segue.destination.contentViewController as? ImageViewController) {
let imageName = (sender as? UIButton)?.currentTitle
ivc.imageURL = DemoURL.NASAImageNamed(imageName: imageName)
ivc.title = imageName
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
splitViewController?.delegate = self
}
@IBAction func showImage(_ sender: UIButton) {
if let ivc = splitViewController?.viewControllers.last?.contentViewController as? ImageViewController {
let imageName = sender.currentTitle
ivc.imageURL = DemoURL.NASAImageNamed(imageName: imageName)
ivc.title = imageName
} else {
performSegue(withIdentifier: Storyboard.ShowImageSegue, sender: sender)
}
}
func splitViewController(_ splitViewController: UISplitViewController, collapseSecondary secondaryViewController: UIViewController, onto primaryViewController: UIViewController) -> Bool {
if primaryViewController.contentViewController == self {
if let ivc = secondaryViewController.contentViewController as? ImageViewController, ivc.imageURL == nil {
return true
}
}
return false
}
}
extension UIViewController {
var contentViewController : UIViewController {
if let navcon = self as? UINavigationController {
return navcon.visibleViewController ?? self
} else {
return self
}
}
}
|
2a5dbd07cf330083d7ac538354738b50
| 32.311475 | 191 | 0.650098 | false | false | false | false |
samsymons/Photon
|
refs/heads/master
|
Photon/Math/Math.swift
|
mit
|
1
|
// TypeNames.swift
// Copyright (c) 2017 Sam Symons
//
// 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 simd
public typealias Point2D = float2
public typealias Point3D = float3
public typealias Vector3D = float3
public typealias Normal = float3
extension float3 {
public static let zero = float3(0, 0, 0)
public init(point: Point3D) {
self.init(point.x, point.y, point.z)
}
}
extension float2 {
public static let zero = float2(0, 0)
public init(point: Point2D) {
self.init(point.x, point.y)
}
}
// MARK: - Mathematical Utilities
public struct MathUtilities {
public static func randomPointInsideUnitSphere() -> Point3D {
let minimum: Float = -1.0
let maximum: Float = 1.0
var point = Point3D(1, 1, 1)
while length(point) >= 1.0 {
let randomX = (minimum...maximum).random()
let randomY = (minimum...maximum).random()
let randomZ = (minimum...maximum).random()
point = Point3D(randomX, randomY, randomZ)
}
return point
}
}
|
c5af157a94d6d7cff50a22c0583f8e93
| 31.0625 | 80 | 0.721248 | false | false | false | false |
eurofurence/ef-app_ios
|
refs/heads/release/4.0.0
|
Packages/EurofurenceModel/Tests/EurofurenceModelTests/Sync/WhenSyncFinishes_ApplicationShould.swift
|
mit
|
1
|
import EurofurenceModel
import XCTest
import XCTEurofurenceModel
class WhenSyncFinishes_ApplicationShould: XCTestCase {
class SingleTransactionOnlyAllowedDataStore: InMemoryDataStore {
private var transactionCount = 0
override func performTransaction(_ block: @escaping (DataStoreTransaction) -> Void) {
super.performTransaction(block)
transactionCount += 1
}
func verify(file: StaticString = #file, line: UInt = #line) {
XCTAssertEqual(1, transactionCount, file: file, line: line)
}
}
func testNotPerformMultipleTransactions() {
let assertion = SingleTransactionOnlyAllowedDataStore()
let context = EurofurenceSessionTestBuilder().with(assertion).build()
let syncResponse = ModelCharacteristics.randomWithoutDeletions
context.performSuccessfulSync(response: syncResponse)
assertion.verify()
}
}
|
3b2eda2bc9e387772252f978692496aa
| 29.225806 | 93 | 0.702241 | false | true | false | false |
burtherman/StreamBaseKit
|
refs/heads/master
|
StreamBaseKit/UnionStream.swift
|
mit
|
2
|
//
// UnionStream.swift
// StreamBaseKit
//
// Created by Steve Farrell on 8/31/15.
// Copyright (c) 2015 Movem3nt, Inc. All rights reserved.
//
import Foundation
/**
Compose a stream out of other streams. Some example use cases are:
- Placeholders
- Multiple Firebase queries in one view
It's ok for the keys to overlap, and for different substreams to have different
types. The sort order of the first stream is used by the union stream. (The sort orders
of the other streams is ignored.)
*/
public class UnionStream {
private let sources: [StreamBase] // TODO StreamBaseProtocol
private let delegates: [UnionStreamDelegate]
private var timer: NSTimer?
private var numStreamsFinished: Int? = 0
private var union = KeyedArray<BaseItem>()
private var error: NSError?
private var comparator: StreamBase.Comparator {
get {
return sources[0].comparator
}
}
/**
The delegate to notify as the merged stream is updated.
*/
weak public var delegate: StreamBaseDelegate?
/**
Construct a union stream from other streams. The sort order of the first substream
is used for the union.
:param: sources The substreams.
*/
public init(sources: StreamBase...) {
precondition(sources.count > 0)
self.sources = sources
delegates = sources.map{ UnionStreamDelegate(source: $0) }
for (s, d) in zip(sources, delegates) {
d.union = self
s.delegate = d
}
}
private func update() {
var newUnion = [BaseItem]()
var seen = Set<String>()
for source in sources {
for item in source {
if !seen.contains(item.key!) {
newUnion.append(item)
seen.insert(item.key!)
}
}
}
newUnion.sortInPlace(comparator)
StreamBase.applyBatch(union, batch: newUnion, delegate: delegate)
if numStreamsFinished == sources.count {
numStreamsFinished = nil
delegate?.streamDidFinishInitialLoad(error)
}
}
func needsUpdate() {
timer?.invalidate()
timer = NSTimer.schedule(delay: 0.1) { [weak self] timer in
self?.update()
}
}
func didFinishInitialLoad(error: NSError?) {
if let e = error where self.error == nil {
self.error = e
// Any additional errors are ignored.
}
numStreamsFinished?++
needsUpdate()
}
func changed(t: BaseItem) {
if let row = union.find(t.key!) {
delegate?.streamItemsChanged([NSIndexPath(forRow: row, inSection: 0)])
}
}
}
extension UnionStream : Indexable {
public typealias Index = Int
public var startIndex: Index {
return union.startIndex
}
public var endIndex: Index {
return union.startIndex
}
public subscript(i: Index) -> BaseItem {
return union[i]
}
}
extension UnionStream : CollectionType { }
extension UnionStream : StreamBaseProtocol {
public func find(key: String) -> BaseItem? {
if let row = union.find(key) {
return union[row]
}
return nil
}
public func findIndexPath(key: String) -> NSIndexPath? {
if let row = union.find(key) {
return NSIndexPath(forRow: row, inSection: 0)
}
return nil
}
}
private class UnionStreamDelegate: StreamBaseDelegate {
weak var source: StreamBase?
weak var union: UnionStream?
init(source: StreamBase) {
self.source = source
}
func streamWillChange() {
}
func streamDidChange() {
union?.needsUpdate()
}
func streamItemsAdded(paths: [NSIndexPath]) {
}
func streamItemsDeleted(paths: [NSIndexPath]) {
}
func streamItemsChanged(paths: [NSIndexPath]) {
for path in paths {
if let t = source?[path.row] {
union?.changed(t)
}
}
}
func streamDidFinishInitialLoad(error: NSError?) {
union?.didFinishInitialLoad(error)
}
}
|
ed82ec9457e9bd5a280941c185621f1e
| 24.825301 | 94 | 0.580495 | false | false | false | false |
wokalski/Graph.swift
|
refs/heads/master
|
Graph/Graph.swift
|
mit
|
1
|
/**
Node is a building block of any `Graph`.
*/
public protocol Node: Hashable {
var children: [Self] { get }
}
/**
Graph defines basic directed graph. Instances of conforming can leverage basic Graph algorithms defined in the extension.
*/
public protocol Graph {
associatedtype T : Node
var nodes: [T] { get }
}
public extension Graph {
/**
Checks whether a graph contains a cycle. A cycle means that there is a parent-child relation where child is also a predecessor of the parent.
- Complexity: O(N + E) where N is the number of all nodes, and E is the number of connections between them
- returns: `true` if doesn't contain a cycle
*/
func isAcyclic() -> Bool {
var isAcyclic = true
depthSearch(edgeFound: { edge in
isAcyclic = (edge.type() != .Back)
return isAcyclic
}, nodeStatusChanged: nil)
return isAcyclic
}
/**
Topological sort ([Wikipedia link](https://en.wikipedia.org/wiki/Topological_sorting)) is an ordering of graph's nodes such that for every directed edge u->v, u comes before v in the ordering.
- Complexity: O(N + E) where N is the number of all nodes, and E is the number of connections between them
- returns: Ordered array of nodes or nil if it cannot be done (i.e. the graph contains cycles)
*/
func topologicalSort() -> [T]? {
var orderedVertices = [T]()
var isAcyclic = true
let nodeProcessed = { (nodeInfo: NodeInfo<T>) -> Bool in
if nodeInfo.status == .Processed {
orderedVertices.append(nodeInfo.node)
}
return true
}
depthSearch(edgeFound: { edge in
isAcyclic = (edge.type() != .Back)
return isAcyclic
}
, nodeStatusChanged: nodeProcessed)
return isAcyclic ? orderedVertices : nil
}
/**
Breadth First Search ([Wikipedia link](https://en.wikipedia.org/wiki/Breadth-first_search))
- Complexity: O(N + E) where N is the number of all nodes, and E is the number of connections between them
- Parameter edgeFound: Called whenever a new connection between nodes is discovered
- Parameter nodeStatusChanged: Called when a node changes its status. It is called twice for every node
- Note: Search will stop if `false` is returned from any closure.
- Warning: It will only call `nodeStatusChanged:` on tree edges because we don't maintain entry and exit times of nodes. More information about entry and exit times [here](https://courses.csail.mit.edu/6.006/fall11/rec/rec14.pdf). It is very easy to implement them, but might have big influence on memory use.
*/
func breadthSearch(edgeFound edgeFound: (Edge<T> -> Bool)?, nodeStatusChanged: (NodeInfo<T> -> Bool)?) {
var queue = Queue<T>()
var searchInfo = SearchInfo<T>()
for graphRoot in nodes {
if searchInfo.status(graphRoot) == .New {
queue.enqueue(graphRoot)
if updateNodeStatus(&searchInfo, node: graphRoot, status: .Discovered, nodeStatusChanged: nodeStatusChanged) == false { return }
while queue.isEmpty() == false {
let parent = queue.dequeue()
for child in parent.children {
if searchInfo.status(child) == .New {
queue.enqueue(child)
if updateNodeStatus(&searchInfo, node: child, status: .Discovered, nodeStatusChanged: nodeStatusChanged) == false { return }
if let c = edgeFound?(Edge(from: searchInfo.nodeInfo(parent), to: searchInfo.nodeInfo(child))) where c == false { return } // Since we don't maintain entry and exit times, we can only rely on tree edges type.
}
}
if updateNodeStatus(&searchInfo, node: parent, status: .Processed, nodeStatusChanged: nodeStatusChanged) == false { return }
}
}
}
}
/**
Depth First Search ([Wikipedia link](https://en.wikipedia.org/wiki/Depth-first_search))
- Complexity: O(N + E) where N is the number of all nodes, and E is the number of connections between them
- Parameter edgeFound: Called whenever a new connection between nodes is discovered
- Parameter nodeStatusChanged: Called when a node changes its status. It is called twice for every node
- Note: Search will stop if `false` is returned from any closure.
- Warning: This function makes recursive calls. Keep it in mind when operating on big data sets.
*/
func depthSearch(edgeFound edgeFound: (Edge<T> -> Bool)?, nodeStatusChanged: (NodeInfo<T> -> Bool)?) {
var searchInfo = SearchInfo<T>()
for node in nodes {
if searchInfo.status(node) == .New {
if dfsVisit(node, searchInfo: &searchInfo, edgeFound: edgeFound, nodeStatusChanged: nodeStatusChanged) == false {
return
}
}
}
}
private func updateNodeStatus(inout searchInfo: SearchInfo<T>, node: T, status: NodeStatus, nodeStatusChanged: (NodeInfo<T> -> Bool)?) -> Bool {
searchInfo.set(node, status: status)
guard let shouldContinue = nodeStatusChanged?(searchInfo.nodeInfo(node)) else {
return true
}
return shouldContinue
}
private func dfsVisit(node: T, inout searchInfo: SearchInfo<T>, edgeFound: (Edge<T> -> Bool)?, nodeStatusChanged: (NodeInfo<T> -> Bool)?) -> Bool {
if updateNodeStatus(&searchInfo, node: node, status: .Discovered, nodeStatusChanged: nodeStatusChanged) == false { return false }
for child in node.children {
if let c = edgeFound?(Edge(from: searchInfo.nodeInfo(node), to: searchInfo.nodeInfo(child))) where c == false { return false }
if searchInfo.status(child) == .New {
if dfsVisit(child, searchInfo: &searchInfo, edgeFound: edgeFound, nodeStatusChanged: nodeStatusChanged) == false {
return false
}
}
}
if updateNodeStatus(&searchInfo, node: node, status: .Processed, nodeStatusChanged: nodeStatusChanged) == false { return false }
return true
}
}
|
1abfdbaade3986aace1213a340c7cc06
| 45.120567 | 314 | 0.611256 | false | false | false | false |
steve-holmes/music-app-2
|
refs/heads/master
|
MusicApp/Modules/Online/OnlineModule.swift
|
mit
|
1
|
//
// OnlineModule.swift
// MusicApp
//
// Created by Hưng Đỗ on 6/9/17.
// Copyright © 2017 HungDo. All rights reserved.
//
import UIKit
import Swinject
class OnlineModule: Module {
override func register() {
// MARK: Controller
container.register(UINavigationController.self) { [weak self] resolver in
let navigationController = UIStoryboard.online.instantiateViewController(withIdentifier: String(describing: OnlineViewController.self)) as! UINavigationController
if let onlineController = navigationController.viewControllers.first as? OnlineViewController {
onlineController.store = resolver.resolve(OnlineStore.self)!
onlineController.action = resolver.resolve(OnlineAction.self)!
if let searchModule = self?.parent?.searchModule {
onlineController.searchController = searchModule.container.resolve(UISearchController.self)!
}
self?.setupMenu(onlineController)
onlineController.controllers = [
self!.getController(of: HomeViewController.self, in: self!.parent!.homeModule),
self!.getController(of: PlaylistViewController.self, in: self!.parent!.playlistModule),
self!.getController(of: SongViewController.self, in: self!.parent!.songModule),
self!.getController(of: VideoViewController.self, in: self!.parent!.videoModule),
self!.getController(of: RankViewController.self, in: self!.parent!.rankModule),
self!.getController(of: SingerViewController.self, in: self!.parent!.singerModule),
self!.getController(of: TopicViewController.self, in: self!.parent!.topicModule)
]
}
return navigationController
}
container.register(OnlineStore.self) { resolver in
return MAOnlineStore()
}
container.register(OnlineAction.self) { resolver in
return MAOnlineAction(
store: resolver.resolve(OnlineStore.self)!,
service: resolver.resolve(OnlineService.self)!
)
}
// MARK: Domain Model
container.register(OnlineService.self) { resolver in
return MAOnlineService(
coordinator: resolver.resolve(OnlineCoordinator.self)!
)
}
container.register(OnlineCoordinator.self) { resolver in
return MAOnlineCoordinator()
}.initCompleted { [weak self] resolver, coordinator in
let coordinator = coordinator as! MAOnlineCoordinator
coordinator.sourceController = resolver.resolve(UINavigationController.self)?.viewControllers.first as? OnlineViewController
let searchModule = self?.parent?.searchModule
coordinator.getSearchController = { searchModule?.container.resolve(SearchViewController.self) }
}
}
private func setupMenu(_ controller: OnlineViewController) {
let menuColor = UIColor(withIntWhite: 250)
controller.settings.style.buttonBarBackgroundColor = menuColor
controller.settings.style.selectedBarBackgroundColor = .main
controller.settings.style.selectedBarHeight = 3
controller.settings.style.buttonBarBackgroundColor = menuColor
controller.settings.style.buttonBarItemFont = UIFont(name: "AvenirNext-Medium", size: 15)!
controller.settings.style.buttonBarItemTitleColor = .text
controller.buttonBarItemSpec = .cellClass { _ in 80 }
controller.changeCurrentIndexProgressive = { oldCell, newCell, progressPercentage, changeCurrentIndex, animated in
guard changeCurrentIndex == true else { return }
newCell?.label.textColor = .main
oldCell?.label.textColor = .text
newCell?.imageView?.tintColor = .main
oldCell?.imageView?.tintColor = .text
let startScale: CGFloat = 0.9
let endScale: CGFloat = 1.1
if animated {
UIView.animate(withDuration: 0.1) {
newCell?.layer.transform = CATransform3DMakeScale(endScale, endScale, 1)
oldCell?.layer.transform = CATransform3DMakeScale(startScale, startScale, 1)
}
} else {
newCell?.layer.transform = CATransform3DMakeScale(endScale, endScale, 1)
oldCell?.layer.transform = CATransform3DMakeScale(startScale, startScale, 1)
}
}
controller.edgesForExtendedLayout = []
}
}
|
2253ffab7ae14d36fc3ec47e3a539d5d
| 42.327434 | 174 | 0.610703 | false | false | false | false |
vector-im/vector-ios
|
refs/heads/master
|
Riot/Managers/Room/RoomIdComponents.swift
|
apache-2.0
|
1
|
/*
Copyright 2019 New Vector Ltd
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import Foundation
/// A structure that parses Matrix Room ID and constructs their constituent parts.
struct RoomIdComponents {
// MARK: - Constants
private enum Constants {
static let matrixRoomIdPrefix = "!"
static let homeServerSeparator: Character = ":"
}
// MARK: - Properties
let localRoomId: String
let homeServer: String
// MARK: - Setup
init?(matrixID: String) {
guard MXTools.isMatrixRoomIdentifier(matrixID),
let (localRoomId, homeServer) = RoomIdComponents.getLocalRoomIDAndHomeServer(from: matrixID) else {
return nil
}
self.localRoomId = localRoomId
self.homeServer = homeServer
}
// MARK: - Private
/// Extract local room id and homeserver from Matrix ID
///
/// - Parameter matrixID: A Matrix ID
/// - Returns: A tuple with local room ID and homeserver.
private static func getLocalRoomIDAndHomeServer(from matrixID: String) -> (String, String)? {
let matrixIDParts = matrixID.split(separator: Constants.homeServerSeparator)
guard matrixIDParts.count == 2 else {
return nil
}
let localRoomID = matrixIDParts[0].replacingOccurrences(of: Constants.matrixRoomIdPrefix, with: "")
let homeServer = String(matrixIDParts[1])
return (localRoomID, homeServer)
}
}
|
7a84de0e7013e2bc2caefb8217a72a0c
| 30.359375 | 111 | 0.670154 | false | false | false | false |
flodolo/firefox-ios
|
refs/heads/main
|
Sync/SyncStateMachine.swift
|
mpl-2.0
|
2
|
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0
import Foundation
import Shared
import Account
private let log = Logger.syncLogger
private let StorageVersionCurrent = 5
// Names of collections that can be enabled/disabled locally.
public let TogglableEngines: [String] = [
"bookmarks",
"history",
"tabs",
"passwords"
]
// Names of collections for which a synchronizer is implemented locally.
private let LocalEngines: [String] = TogglableEngines + ["clients"]
// Names of collections which will appear in a default meta/global produced locally.
// Map collection name to engine version. See http://docs.services.mozilla.com/sync/objectformats.html.
private let DefaultEngines: [String: Int] = [
"bookmarks": 2,
"clients": ClientsStorageVersion,
"history": HistoryStorageVersion,
"tabs": 1,
// We opt-in to syncing collections we don't know about, since no client offers to sync non-enabled,
// non-declined engines yet. See Bug 969669.
"passwords": 1,
"forms": 1,
"addons": 1,
"prefs": 2,
"addresses": 1,
"creditcards": 1,
]
// Names of collections which will appear as declined in a default
// meta/global produced locally.
private let DefaultDeclined: [String] = [String]()
public func computeNewEngines(_ engineConfiguration: EngineConfiguration, enginesEnablements: [String: Bool]?) -> (engines: [String: EngineMeta], declined: [String]) {
var enabled: Set<String> = Set(engineConfiguration.enabled)
var declined: Set<String> = Set(engineConfiguration.declined)
var engines: [String: EngineMeta] = [:]
if let enginesEnablements = enginesEnablements {
let enabledLocally = Set(enginesEnablements.filter { $0.value }.map { $0.key })
let declinedLocally = Set(enginesEnablements.filter { !$0.value }.map { $0.key })
enabled.subtract(declinedLocally)
declined.subtract(enabledLocally)
enabled.formUnion(enabledLocally)
declined.formUnion(declinedLocally)
}
for engine in enabled {
// We take this device's version, or, if we don't know the correct version, 0. Another client should recognize
// the engine, see an old version, wipe and start again.
// TODO: this client does not yet do this wipe-and-update itself!
let version = DefaultEngines[engine] ?? 0
engines[engine] = EngineMeta(version: version, syncID: Bytes.generateGUID())
}
return (engines: engines, declined: Array(declined))
}
// public for testing.
public func createMetaGlobalWithEngineConfiguration(_ engineConfiguration: EngineConfiguration, enginesEnablements: [String: Bool]?) -> MetaGlobal {
let (engines, declined) = computeNewEngines(engineConfiguration, enginesEnablements: enginesEnablements)
return MetaGlobal(syncID: Bytes.generateGUID(), storageVersion: StorageVersionCurrent, engines: engines, declined: declined)
}
public func createMetaGlobal(enginesEnablements: [String: Bool]?) -> MetaGlobal {
let engineConfiguration = EngineConfiguration(enabled: Array(DefaultEngines.keys), declined: DefaultDeclined)
return createMetaGlobalWithEngineConfiguration(engineConfiguration, enginesEnablements: enginesEnablements)
}
public typealias TokenSource = () -> Deferred<Maybe<TokenServerToken>>
public typealias ReadyDeferred = Deferred<Maybe<Ready>>
// See docs in docs/sync.md.
// You might be wondering why this doesn't have a Sync15StorageClient like FxALoginStateMachine
// does. Well, such a client is pinned to a particular server, and this state machine must
// acknowledge that a Sync client occasionally must migrate between two servers, preserving
// some state from the last.
// The resultant 'Ready' will be able to provide a suitably initialized storage client.
open class SyncStateMachine {
// The keys are used as a set, to prevent cycles in the state machine.
var stateLabelsSeen = [SyncStateLabel: Bool]()
var stateLabelSequence = [SyncStateLabel]()
let stateLabelsAllowed: Set<SyncStateLabel>
let scratchpadPrefs: Prefs
/// Use this set of states to constrain the state machine to attempt the barest
/// minimum to get to Ready. This is suitable for extension uses. If it is not possible,
/// then no destructive or expensive actions are taken (e.g. total HTTP requests,
/// duration, records processed, database writes, fsyncs, blanking any local collections)
public static let OptimisticStates = Set(SyncStateLabel.optimisticValues)
/// The default set of states that the state machine is allowed to use.
public static let AllStates = Set(SyncStateLabel.allValues)
public init(prefs: Prefs, allowingStates labels: Set<SyncStateLabel> = SyncStateMachine.AllStates) {
self.scratchpadPrefs = prefs.branch("scratchpad")
self.stateLabelsAllowed = labels
}
open class func clearStateFromPrefs(_ prefs: Prefs) {
log.debug("Clearing all Sync prefs.")
Scratchpad.clearFromPrefs(prefs.branch("scratchpad")) // XXX this is convoluted.
prefs.clearAll()
}
fileprivate func advanceFromState(_ state: SyncState) -> ReadyDeferred {
log.info("advanceFromState: \(state.label)")
// Record visibility before taking any action.
let labelAlreadySeen = self.stateLabelsSeen.updateValue(true, forKey: state.label) != nil
stateLabelSequence.append(state.label)
if let ready = state as? Ready {
// Sweet, we made it!
return deferMaybe(ready)
}
// Cycles are not necessarily a problem, but seeing the same (recoverable) error condition is a problem.
if state is RecoverableSyncState && labelAlreadySeen {
return deferMaybe(StateMachineCycleError())
}
guard stateLabelsAllowed.contains(state.label) else {
return deferMaybe(DisallowedStateError(state.label, allowedStates: stateLabelsAllowed))
}
return state.advance() >>== self.advanceFromState
}
open func toReady(_ authState: SyncAuthState) -> ReadyDeferred {
let readyDeferred = ReadyDeferred()
RustFirefoxAccounts.shared.accountManager.uponQueue(.main) { accountManager in
authState.token(Date.now(), canBeExpired: false).uponQueue(.main) { success in
guard let (token, kSync) = success.successValue else {
readyDeferred.fill(Maybe(failure: success.failureValue ?? FxAClientError.local(NSError())))
return
}
log.debug("Got token from auth state.")
if Logger.logPII {
log.debug("Server is \(token.api_endpoint).")
}
let prior = Scratchpad.restoreFromPrefs(self.scratchpadPrefs, syncKeyBundle: KeyBundle.fromKSync(kSync))
if prior == nil {
log.info("No persisted Sync state. Starting over.")
}
var scratchpad = prior ?? Scratchpad(b: KeyBundle.fromKSync(kSync), persistingTo: self.scratchpadPrefs)
// Take the scratchpad and add the fxaDeviceId from the state, and hashedUID from the token
let b = Scratchpad.Builder(p: scratchpad)
if let deviceID = accountManager.deviceConstellation()?.state()?.localDevice?.id {
b.fxaDeviceId = deviceID
} else {
// Either deviceRegistration hasn't occurred yet (our bug) or
// FxA has given us an UnknownDevice error.
log.warning("Device registration has not taken place before sync.")
}
b.hashedUID = token.hashedFxAUID
if let enginesEnablements = authState.enginesEnablements,
!enginesEnablements.isEmpty {
b.enginesEnablements = enginesEnablements
}
if let clientName = authState.clientName {
b.clientName = clientName
}
// Detect if we've changed anything in our client record from the last time we synced…
let ourClientUnchanged = (b.fxaDeviceId == scratchpad.fxaDeviceId)
// …and if so, trigger a reset of clients.
if !ourClientUnchanged {
b.localCommands.insert(LocalCommand.resetEngine(engine: "clients"))
}
scratchpad = b.build()
log.info("Advancing to InitialWithLiveToken.")
let state = InitialWithLiveToken(scratchpad: scratchpad, token: token)
// Start with fresh visibility data.
self.stateLabelsSeen = [:]
self.stateLabelSequence = []
self.advanceFromState(state).uponQueue(.main) { success in
readyDeferred.fill(success)
}
}
}
return readyDeferred
}
}
public enum SyncStateLabel: String {
case Stub = "STUB" // For 'abstract' base classes.
case InitialWithExpiredToken = "initialWithExpiredToken"
case InitialWithExpiredTokenAndInfo = "initialWithExpiredTokenAndInfo"
case InitialWithLiveToken = "initialWithLiveToken"
case InitialWithLiveTokenAndInfo = "initialWithLiveTokenAndInfo"
case ResolveMetaGlobalVersion = "resolveMetaGlobalVersion"
case ResolveMetaGlobalContent = "resolveMetaGlobalContent"
case NeedsFreshMetaGlobal = "needsFreshMetaGlobal"
case NewMetaGlobal = "newMetaGlobal"
case HasMetaGlobal = "hasMetaGlobal"
case NeedsFreshCryptoKeys = "needsFreshCryptoKeys"
case HasFreshCryptoKeys = "hasFreshCryptoKeys"
case Ready = "ready"
case FreshStartRequired = "freshStartRequired" // Go around again... once only, perhaps.
case ServerConfigurationRequired = "serverConfigurationRequired"
case ChangedServer = "changedServer"
case MissingMetaGlobal = "missingMetaGlobal"
case MissingCryptoKeys = "missingCryptoKeys"
case MalformedCryptoKeys = "malformedCryptoKeys"
case SyncIDChanged = "syncIDChanged"
case RemoteUpgradeRequired = "remoteUpgradeRequired"
case ClientUpgradeRequired = "clientUpgradeRequired"
static let allValues: [SyncStateLabel] = [
InitialWithExpiredToken,
InitialWithExpiredTokenAndInfo,
InitialWithLiveToken,
InitialWithLiveTokenAndInfo,
NeedsFreshMetaGlobal,
ResolveMetaGlobalVersion,
ResolveMetaGlobalContent,
NewMetaGlobal,
HasMetaGlobal,
NeedsFreshCryptoKeys,
HasFreshCryptoKeys,
Ready,
FreshStartRequired,
ServerConfigurationRequired,
ChangedServer,
MissingMetaGlobal,
MissingCryptoKeys,
MalformedCryptoKeys,
SyncIDChanged,
RemoteUpgradeRequired,
ClientUpgradeRequired,
]
// This is the list of states needed to get to Ready, or failing.
// This is useful in circumstances where it is important to conserve time and/or battery, and failure
// to timely sync is acceptable.
static let optimisticValues: [SyncStateLabel] = [
InitialWithLiveToken,
InitialWithLiveTokenAndInfo,
HasMetaGlobal,
HasFreshCryptoKeys,
Ready,
]
}
/**
* States in this state machine all implement SyncState.
*
* States are either successful main-flow states, or (recoverable) error states.
* Errors that aren't recoverable are simply errors.
* Main-flow states flow one to one.
*
* (Terminal failure states might be introduced at some point.)
*
* Multiple error states (but typically only one) can arise from each main state transition.
* For example, parsing meta/global can result in a number of different non-routine situations.
*
* For these reasons, and the lack of useful ADTs in Swift, we model the main flow as
* the success branch of a Result, and the recovery flows as a part of the failure branch.
*
* We could just as easily use a ternary Either-style operator, but thanks to Swift's
* optional-cast-let it's no saving to do so.
*
* Because of the lack of type system support, all RecoverableSyncStates must have the same
* signature. That signature implies a possibly multi-state transition; individual states
* will have richer type signatures.
*/
public protocol SyncState {
var label: SyncStateLabel { get }
func advance() -> Deferred<Maybe<SyncState>>
}
/*
* Base classes to avoid repeating initializers all over the place.
*/
open class BaseSyncState: SyncState {
open var label: SyncStateLabel { return SyncStateLabel.Stub }
public let client: Sync15StorageClient!
let token: TokenServerToken // Maybe expired.
var scratchpad: Scratchpad
// TODO: 304 for i/c.
open func getInfoCollections() -> Deferred<Maybe<InfoCollections>> {
return chain(self.client.getInfoCollections(), f: {
return $0.value
})
}
public init(client: Sync15StorageClient, scratchpad: Scratchpad, token: TokenServerToken) {
self.scratchpad = scratchpad
self.token = token
self.client = client
log.info("Inited \(self.label.rawValue)")
}
open func synchronizer<T: Synchronizer>(_ synchronizerClass: T.Type, delegate: SyncDelegate, prefs: Prefs, why: SyncReason) -> T {
return T(scratchpad: self.scratchpad, delegate: delegate, basePrefs: prefs, why: why)
}
// This isn't a convenience initializer 'cos subclasses can't call convenience initializers.
public init(scratchpad: Scratchpad, token: TokenServerToken) {
let workQueue = DispatchQueue.global()
let resultQueue = DispatchQueue.main
let backoff = scratchpad.backoffStorage
let client = Sync15StorageClient(token: token, workQueue: workQueue, resultQueue: resultQueue, backoff: backoff)
self.scratchpad = scratchpad
self.token = token
self.client = client
log.info("Inited \(self.label.rawValue)")
}
open func advance() -> Deferred<Maybe<SyncState>> {
return deferMaybe(StubStateError())
}
}
open class BaseSyncStateWithInfo: BaseSyncState {
public let info: InfoCollections
init(client: Sync15StorageClient, scratchpad: Scratchpad, token: TokenServerToken, info: InfoCollections) {
self.info = info
super.init(client: client, scratchpad: scratchpad, token: token)
}
init(scratchpad: Scratchpad, token: TokenServerToken, info: InfoCollections) {
self.info = info
super.init(scratchpad: scratchpad, token: token)
}
}
/*
* Error types.
*/
public protocol SyncError: MaybeErrorType, SyncPingFailureFormattable {}
extension SyncError {
public var failureReasonName: SyncPingFailureReasonName {
return .unexpectedError
}
}
open class UnknownError: SyncError {
open var description: String {
return "Unknown error."
}
}
open class StateMachineCycleError: SyncError {
open var description: String {
return "The Sync state machine encountered a cycle. This is a coding error."
}
}
open class CouldNotFetchMetaGlobalError: SyncError {
open var description: String {
return "Could not fetch meta/global."
}
}
open class CouldNotFetchKeysError: SyncError {
open var description: String {
return "Could not fetch crypto/keys."
}
}
open class StubStateError: SyncError {
open var description: String {
return "Unexpectedly reached a stub state. This is a coding error."
}
}
open class ClientUpgradeRequiredError: SyncError {
let targetStorageVersion: Int
public init(target: Int) {
self.targetStorageVersion = target
}
open var description: String {
return "Client upgrade required to work with storage version \(self.targetStorageVersion)."
}
}
open class InvalidKeysError: SyncError {
let keys: Keys
public init(_ keys: Keys) {
self.keys = keys
}
open var description: String {
return "Downloaded crypto/keys, but couldn't parse them."
}
}
open class DisallowedStateError: SyncError {
let state: SyncStateLabel
let allowedStates: Set<SyncStateLabel>
public init(_ state: SyncStateLabel, allowedStates: Set<SyncStateLabel>) {
self.state = state
self.allowedStates = allowedStates
}
open var description: String {
return "Sync state machine reached \(String(describing: state)) state, which is disallowed. Legal states are: \(String(describing: allowedStates))"
}
}
/**
* Error states. These are errors that can be recovered from by taking actions. We use RecoverableSyncState as a
* sentinel: if we see the same recoverable state twice, we bail out and complain that we've seen a cycle. (Seeing
* some states -- principally initial states -- twice is fine.)
*/
public protocol RecoverableSyncState: SyncState {
}
/**
* Recovery: discard our local timestamps and sync states; discard caches.
* Be prepared to handle a conflict between our selected engines and the new
* server's meta/global; if an engine is selected locally but not declined
* remotely, then we'll need to upload a new meta/global and sync that engine.
*/
open class ChangedServerError: RecoverableSyncState {
open var label: SyncStateLabel { return SyncStateLabel.ChangedServer }
let newToken: TokenServerToken
let newScratchpad: Scratchpad
public init(scratchpad: Scratchpad, token: TokenServerToken) {
self.newToken = token
self.newScratchpad = Scratchpad(b: scratchpad.syncKeyBundle, persistingTo: scratchpad.prefs)
}
open func advance() -> Deferred<Maybe<SyncState>> {
// TODO: mutate local storage to allow for a fresh start.
let state = InitialWithLiveToken(scratchpad: newScratchpad.checkpoint(), token: newToken)
return deferMaybe(state)
}
}
/**
* Recovery: same as for changed server, but no need to upload a new meta/global.
*/
open class SyncIDChangedError: RecoverableSyncState {
open var label: SyncStateLabel { return SyncStateLabel.SyncIDChanged }
fileprivate let previousState: BaseSyncStateWithInfo
fileprivate let newMetaGlobal: Fetched<MetaGlobal>
public init(previousState: BaseSyncStateWithInfo, newMetaGlobal: Fetched<MetaGlobal>) {
self.previousState = previousState
self.newMetaGlobal = newMetaGlobal
}
open func advance() -> Deferred<Maybe<SyncState>> {
// TODO: mutate local storage to allow for a fresh start.
let s = self.previousState.scratchpad.evolve().setGlobal(self.newMetaGlobal).setKeys(nil).build().checkpoint()
let state = HasMetaGlobal(client: self.previousState.client, scratchpad: s, token: self.previousState.token, info: self.previousState.info)
return deferMaybe(state)
}
}
/**
* Recovery: configure the server.
*/
open class ServerConfigurationRequiredError: RecoverableSyncState {
open var label: SyncStateLabel { return SyncStateLabel.ServerConfigurationRequired }
fileprivate let previousState: BaseSyncStateWithInfo
public init(previousState: BaseSyncStateWithInfo) {
self.previousState = previousState
}
open func advance() -> Deferred<Maybe<SyncState>> {
let client = self.previousState.client!
let oldScratchpad = self.previousState.scratchpad
let enginesEnablements = oldScratchpad.enginesEnablements
let s = oldScratchpad.evolve()
.setGlobal(nil)
.addLocalCommandsFromKeys(nil)
.setKeys(nil)
.clearEnginesEnablements()
.build().checkpoint()
// Upload a new meta/global ...
let metaGlobal: MetaGlobal
if let oldEngineConfiguration = s.engineConfiguration {
metaGlobal = createMetaGlobalWithEngineConfiguration(oldEngineConfiguration, enginesEnablements: enginesEnablements)
} else {
metaGlobal = createMetaGlobal(enginesEnablements: enginesEnablements)
}
return client.uploadMetaGlobal(metaGlobal, ifUnmodifiedSince: nil)
// ... and a new crypto/keys.
>>> { return client.uploadCryptoKeys(Keys.random(), withSyncKeyBundle: s.syncKeyBundle, ifUnmodifiedSince: nil) }
>>> { return deferMaybe(InitialWithLiveToken(client: client, scratchpad: s, token: self.previousState.token)) }
}
}
/**
* Recovery: wipe the server (perhaps unnecessarily) and proceed to configure the server.
*/
open class FreshStartRequiredError: RecoverableSyncState {
open var label: SyncStateLabel { return SyncStateLabel.FreshStartRequired }
fileprivate let previousState: BaseSyncStateWithInfo
public init(previousState: BaseSyncStateWithInfo) {
self.previousState = previousState
}
open func advance() -> Deferred<Maybe<SyncState>> {
let client = self.previousState.client!
return client.wipeStorage()
>>> { return deferMaybe(ServerConfigurationRequiredError(previousState: self.previousState)) }
}
}
open class MissingMetaGlobalError: RecoverableSyncState {
open var label: SyncStateLabel { return SyncStateLabel.MissingMetaGlobal }
fileprivate let previousState: BaseSyncStateWithInfo
public init(previousState: BaseSyncStateWithInfo) {
self.previousState = previousState
}
open func advance() -> Deferred<Maybe<SyncState>> {
return deferMaybe(FreshStartRequiredError(previousState: self.previousState))
}
}
open class MissingCryptoKeysError: RecoverableSyncState {
open var label: SyncStateLabel { return SyncStateLabel.MissingCryptoKeys }
fileprivate let previousState: BaseSyncStateWithInfo
public init(previousState: BaseSyncStateWithInfo) {
self.previousState = previousState
}
open func advance() -> Deferred<Maybe<SyncState>> {
return deferMaybe(FreshStartRequiredError(previousState: self.previousState))
}
}
open class RemoteUpgradeRequired: RecoverableSyncState {
open var label: SyncStateLabel { return SyncStateLabel.RemoteUpgradeRequired }
fileprivate let previousState: BaseSyncStateWithInfo
public init(previousState: BaseSyncStateWithInfo) {
self.previousState = previousState
}
open func advance() -> Deferred<Maybe<SyncState>> {
return deferMaybe(FreshStartRequiredError(previousState: self.previousState))
}
}
open class ClientUpgradeRequired: RecoverableSyncState {
open var label: SyncStateLabel { return SyncStateLabel.ClientUpgradeRequired }
fileprivate let previousState: BaseSyncStateWithInfo
let targetStorageVersion: Int
public init(previousState: BaseSyncStateWithInfo, target: Int) {
self.previousState = previousState
self.targetStorageVersion = target
}
open func advance() -> Deferred<Maybe<SyncState>> {
return deferMaybe(ClientUpgradeRequiredError(target: self.targetStorageVersion))
}
}
/*
* Non-error states.
*/
open class InitialWithLiveToken: BaseSyncState {
open override var label: SyncStateLabel { return SyncStateLabel.InitialWithLiveToken }
// This looks totally redundant, but try taking it out, I dare you.
public override init(scratchpad: Scratchpad, token: TokenServerToken) {
super.init(scratchpad: scratchpad, token: token)
}
// This looks totally redundant, but try taking it out, I dare you.
public override init(client: Sync15StorageClient, scratchpad: Scratchpad, token: TokenServerToken) {
super.init(client: client, scratchpad: scratchpad, token: token)
}
func advanceWithInfo(_ info: InfoCollections) -> SyncState {
return InitialWithLiveTokenAndInfo(scratchpad: self.scratchpad, token: self.token, info: info)
}
override open func advance() -> Deferred<Maybe<SyncState>> {
return chain(getInfoCollections(), f: self.advanceWithInfo)
}
}
/**
* Each time we fetch a new meta/global, we need to reconcile it with our
* current state.
*
* It might be identical to our current meta/global, in which case we can short-circuit.
*
* We might have no previous meta/global at all, in which case this state
* simply configures local storage to be ready to sync according to the
* supplied meta/global. (Not necessarily datatype elections: those will be per-device.)
*
* Or it might be different. In this case the previous m/g and our local user preferences
* are compared to the new, resulting in some actions and a final state.
*
* This states are similar in purpose to GlobalSession.processMetaGlobal in Android Sync.
*/
open class ResolveMetaGlobalVersion: BaseSyncStateWithInfo {
let fetched: Fetched<MetaGlobal>
init(fetched: Fetched<MetaGlobal>, client: Sync15StorageClient, scratchpad: Scratchpad, token: TokenServerToken, info: InfoCollections) {
self.fetched = fetched
super.init(client: client, scratchpad: scratchpad, token: token, info: info)
}
open override var label: SyncStateLabel { return SyncStateLabel.ResolveMetaGlobalVersion }
class func fromState(_ state: BaseSyncStateWithInfo, fetched: Fetched<MetaGlobal>) -> ResolveMetaGlobalVersion {
return ResolveMetaGlobalVersion(fetched: fetched, client: state.client, scratchpad: state.scratchpad, token: state.token, info: state.info)
}
override open func advance() -> Deferred<Maybe<SyncState>> {
// First: check storage version.
let v = fetched.value.storageVersion
if v > StorageVersionCurrent {
// New storage version? Uh-oh. No recovery possible here.
log.info("Client upgrade required for storage version \(v)")
return deferMaybe(ClientUpgradeRequired(previousState: self, target: v))
}
if v < StorageVersionCurrent {
// Old storage version? Uh-oh. Wipe and upload both meta/global and crypto/keys.
log.info("Server storage version \(v) is outdated.")
return deferMaybe(RemoteUpgradeRequired(previousState: self))
}
return deferMaybe(ResolveMetaGlobalContent.fromState(self, fetched: self.fetched))
}
}
open class ResolveMetaGlobalContent: BaseSyncStateWithInfo {
let fetched: Fetched<MetaGlobal>
init(fetched: Fetched<MetaGlobal>, client: Sync15StorageClient, scratchpad: Scratchpad, token: TokenServerToken, info: InfoCollections) {
self.fetched = fetched
super.init(client: client, scratchpad: scratchpad, token: token, info: info)
}
open override var label: SyncStateLabel { return SyncStateLabel.ResolveMetaGlobalContent }
class func fromState(_ state: BaseSyncStateWithInfo, fetched: Fetched<MetaGlobal>) -> ResolveMetaGlobalContent {
return ResolveMetaGlobalContent(fetched: fetched, client: state.client, scratchpad: state.scratchpad, token: state.token, info: state.info)
}
override open func advance() -> Deferred<Maybe<SyncState>> {
// Check global syncID and contents.
if let previous = self.scratchpad.global?.value {
// Do checks that only apply when we're coming from a previous meta/global.
if previous.syncID != fetched.value.syncID {
log.info("Remote global sync ID has changed. Dropping keys and resetting all local collections.")
let s = self.scratchpad.freshStartWithGlobal(fetched).checkpoint()
return deferMaybe(HasMetaGlobal.fromState(self, scratchpad: s))
}
let b = self.scratchpad.evolve()
.setGlobal(fetched) // We always adopt the upstream meta/global record.
let previousEngines = Set(previous.engines.keys)
let remoteEngines = Set(fetched.value.engines.keys)
for engine in previousEngines.subtracting(remoteEngines) {
log.info("Remote meta/global disabled previously enabled engine \(engine).")
b.localCommands.insert(.disableEngine(engine: engine))
}
for engine in remoteEngines.subtracting(previousEngines) {
log.info("Remote meta/global enabled previously disabled engine \(engine).")
b.localCommands.insert(.enableEngine(engine: engine))
}
for engine in remoteEngines.intersection(previousEngines) {
let remoteEngine = fetched.value.engines[engine]!
let previousEngine = previous.engines[engine]!
if previousEngine.syncID != remoteEngine.syncID {
log.info("Remote sync ID for \(engine) has changed. Resetting local.")
b.localCommands.insert(.resetEngine(engine: engine))
}
}
let s = b.build().checkpoint()
return deferMaybe(HasMetaGlobal.fromState(self, scratchpad: s))
}
// No previous meta/global. Adopt the new meta/global.
let s = self.scratchpad.freshStartWithGlobal(fetched).checkpoint()
return deferMaybe(HasMetaGlobal.fromState(self, scratchpad: s))
}
}
private func processFailure(_ failure: MaybeErrorType?) -> MaybeErrorType {
if let failure = failure as? ServerInBackoffError {
log.warning("Server in backoff. Bailing out. \(failure.description)")
return failure
}
// TODO: backoff etc. for all of these.
if let failure = failure as? ServerError<HTTPURLResponse> {
// Be passive.
log.error("Server error. Bailing out. \(failure.description)")
return failure
}
if let failure = failure as? BadRequestError<HTTPURLResponse> {
// Uh oh.
log.error("Bad request. Bailing out. \(failure.description)")
return failure
}
log.error("Unexpected failure. \(failure?.description ?? "nil")")
return failure ?? UnknownError()
}
open class InitialWithLiveTokenAndInfo: BaseSyncStateWithInfo {
open override var label: SyncStateLabel { return SyncStateLabel.InitialWithLiveTokenAndInfo }
// This method basically hops over HasMetaGlobal, because it's not a state
// that we expect consumers to know about.
override open func advance() -> Deferred<Maybe<SyncState>> {
// Either m/g and c/k are in our local cache, and they're up-to-date with i/c,
// or we need to fetch them.
// Cached and not changed in i/c? Use that.
// This check would be inaccurate if any other fields were stored in meta/; this
// has been the case in the past, with the Sync 1.1 migration indicator.
if let global = self.scratchpad.global {
if let metaModified = self.info.modified("meta") {
// We check the last time we fetched the record, and that can be
// later than the collection timestamp. All we care about here is if the
// server might have a newer record.
if global.timestamp >= metaModified {
log.debug("Cached meta/global fetched at \(global.timestamp), newer than server modified \(metaModified). Using cached meta/global.")
// Strictly speaking we can avoid fetching if this condition is not true,
// but if meta/ is modified for a different reason -- store timestamps
// for the last collection fetch. This will do for now.
return deferMaybe(HasMetaGlobal.fromState(self))
}
log.info("Cached meta/global fetched at \(global.timestamp) older than server modified \(metaModified). Fetching fresh meta/global.")
} else {
// No known modified time for meta/. That means the server has no meta/global.
// Drop our cached value and fall through; we'll try to fetch, fail, and
// go through the usual failure flow.
log.warning("Local meta/global fetched at \(global.timestamp) found, but no meta collection on server. Dropping cached meta/global.")
// If we bail because we've been overly optimistic, then we nil out the current (broken)
// meta/global. Next time around, we end up in the "No cached meta/global found" branch.
self.scratchpad = self.scratchpad.evolve().setGlobal(nil).setKeys(nil).build().checkpoint()
}
} else {
log.debug("No cached meta/global found. Fetching fresh meta/global.")
}
return deferMaybe(NeedsFreshMetaGlobal.fromState(self))
}
}
/*
* We've reached NeedsFreshMetaGlobal somehow, but we haven't yet done anything about it
* (e.g. fetch a new one with GET /storage/meta/global ).
*
* If we don't want to hit the network (e.g. from an extension), we should stop if we get to this state.
*/
open class NeedsFreshMetaGlobal: BaseSyncStateWithInfo {
open override var label: SyncStateLabel { return SyncStateLabel.NeedsFreshMetaGlobal }
class func fromState(_ state: BaseSyncStateWithInfo) -> NeedsFreshMetaGlobal {
return NeedsFreshMetaGlobal(client: state.client, scratchpad: state.scratchpad, token: state.token, info: state.info)
}
override open func advance() -> Deferred<Maybe<SyncState>> {
// Fetch.
return self.client.getMetaGlobal().bind { result in
if let resp = result.successValue {
// We use the server's timestamp, rather than the record's modified field.
// Either can be made to work, but the latter has suffered from bugs: see Bug 1210625.
let fetched = Fetched(value: resp.value, timestamp: resp.metadata.timestampMilliseconds)
return deferMaybe(ResolveMetaGlobalVersion.fromState(self, fetched: fetched))
}
if result.failureValue as? NotFound<HTTPURLResponse> != nil {
// OK, this is easy.
// This state is responsible for creating the new m/g, uploading it, and
// restarting with a clean scratchpad.
return deferMaybe(MissingMetaGlobalError(previousState: self))
}
// Otherwise, we have a failure state. Die on the sword!
return deferMaybe(processFailure(result.failureValue))
}
}
}
open class HasMetaGlobal: BaseSyncStateWithInfo {
open override var label: SyncStateLabel { return SyncStateLabel.HasMetaGlobal }
class func fromState(_ state: BaseSyncStateWithInfo) -> HasMetaGlobal {
return HasMetaGlobal(client: state.client, scratchpad: state.scratchpad, token: state.token, info: state.info)
}
class func fromState(_ state: BaseSyncStateWithInfo, scratchpad: Scratchpad) -> HasMetaGlobal {
return HasMetaGlobal(client: state.client, scratchpad: scratchpad, token: state.token, info: state.info)
}
override open func advance() -> Deferred<Maybe<SyncState>> {
// Check if we have enabled/disabled some engines.
if let enginesEnablements = self.scratchpad.enginesEnablements,
let oldMetaGlobal = self.scratchpad.global {
let (engines, declined) = computeNewEngines(oldMetaGlobal.value.engineConfiguration(), enginesEnablements: enginesEnablements)
let newMetaGlobal = MetaGlobal(syncID: oldMetaGlobal.value.syncID, storageVersion: oldMetaGlobal.value.storageVersion, engines: engines, declined: declined)
return self.client.uploadMetaGlobal(newMetaGlobal, ifUnmodifiedSince: oldMetaGlobal.timestamp) >>> {
self.scratchpad = self.scratchpad.evolve().clearEnginesEnablements().build().checkpoint()
return deferMaybe(NeedsFreshMetaGlobal.fromState(self))
}
}
// Check if crypto/keys is fresh in the cache already.
if let keys = self.scratchpad.keys, keys.value.valid {
if let cryptoModified = self.info.modified("crypto") {
// Both of these are server timestamps. If the record we stored was
// fetched after the last time the record was modified, as represented
// by the "crypto" entry in info/collections, and we're fetching from the
// same server, then the record must be identical, and we can use it
// directly. If are ever additional records in the crypto collection,
// this will fetch keys too frequently. In that case, we should use
// X-I-U-S and expect some 304 responses.
if keys.timestamp >= cryptoModified {
log.debug("Cached keys fetched at \(keys.timestamp), newer than server modified \(cryptoModified). Using cached keys.")
return deferMaybe(HasFreshCryptoKeys.fromState(self, scratchpad: self.scratchpad, collectionKeys: keys.value))
}
// The server timestamp is newer, so there might be new keys.
// Re-fetch keys and check to see if the actual contents differ.
// If the keys are the same, we can ignore this change. If they differ,
// we need to re-sync any collection whose keys just changed.
log.info("Cached keys fetched at \(keys.timestamp) older than server modified \(cryptoModified). Fetching fresh keys.")
return deferMaybe(NeedsFreshCryptoKeys.fromState(self, scratchpad: self.scratchpad, staleCollectionKeys: keys.value))
} else {
// No known modified time for crypto/. That likely means the server has no keys.
// Drop our cached value and fall through; we'll try to fetch, fail, and
// go through the usual failure flow.
log.warning("Local keys fetched at \(keys.timestamp) found, but no crypto collection on server. Dropping cached keys.")
self.scratchpad = self.scratchpad.evolve().setKeys(nil).build().checkpoint()
}
} else {
log.debug("No cached keys found. Fetching fresh keys.")
}
return deferMaybe(NeedsFreshCryptoKeys.fromState(self, scratchpad: self.scratchpad, staleCollectionKeys: nil))
}
}
open class NeedsFreshCryptoKeys: BaseSyncStateWithInfo {
open override var label: SyncStateLabel { return SyncStateLabel.NeedsFreshCryptoKeys }
let staleCollectionKeys: Keys?
class func fromState(_ state: BaseSyncStateWithInfo, scratchpad: Scratchpad, staleCollectionKeys: Keys?) -> NeedsFreshCryptoKeys {
return NeedsFreshCryptoKeys(client: state.client, scratchpad: scratchpad, token: state.token, info: state.info, keys: staleCollectionKeys)
}
public init(client: Sync15StorageClient, scratchpad: Scratchpad, token: TokenServerToken, info: InfoCollections, keys: Keys?) {
self.staleCollectionKeys = keys
super.init(client: client, scratchpad: scratchpad, token: token, info: info)
}
override open func advance() -> Deferred<Maybe<SyncState>> {
// Fetch crypto/keys.
return self.client.getCryptoKeys(self.scratchpad.syncKeyBundle, ifUnmodifiedSince: nil).bind { result in
if let resp = result.successValue {
let collectionKeys = Keys(payload: resp.value.payload)
if !collectionKeys.valid {
log.error("Unexpectedly invalid crypto/keys during a successful fetch.")
return Deferred(value: Maybe(failure: InvalidKeysError(collectionKeys)))
}
let fetched = Fetched(value: collectionKeys, timestamp: resp.metadata.timestampMilliseconds)
let s = self.scratchpad.evolve()
.addLocalCommandsFromKeys(fetched)
.setKeys(fetched)
.build().checkpoint()
return deferMaybe(HasFreshCryptoKeys.fromState(self, scratchpad: s, collectionKeys: collectionKeys))
}
if result.failureValue as? NotFound<HTTPURLResponse> != nil {
// No crypto/keys? We can handle this. Wipe and upload both meta/global and crypto/keys.
return deferMaybe(MissingCryptoKeysError(previousState: self))
}
// Otherwise, we have a failure state.
return deferMaybe(processFailure(result.failureValue))
}
}
}
open class HasFreshCryptoKeys: BaseSyncStateWithInfo {
open override var label: SyncStateLabel { return SyncStateLabel.HasFreshCryptoKeys }
let collectionKeys: Keys
class func fromState(_ state: BaseSyncStateWithInfo, scratchpad: Scratchpad, collectionKeys: Keys) -> HasFreshCryptoKeys {
return HasFreshCryptoKeys(client: state.client, scratchpad: scratchpad, token: state.token, info: state.info, keys: collectionKeys)
}
public init(client: Sync15StorageClient, scratchpad: Scratchpad, token: TokenServerToken, info: InfoCollections, keys: Keys) {
self.collectionKeys = keys
super.init(client: client, scratchpad: scratchpad, token: token, info: info)
}
override open func advance() -> Deferred<Maybe<SyncState>> {
return deferMaybe(Ready(client: self.client, scratchpad: self.scratchpad, token: self.token, info: self.info, keys: self.collectionKeys))
}
}
public protocol EngineStateChanges {
func collectionsThatNeedLocalReset() -> [String]
func enginesEnabled() -> [String]
func enginesDisabled() -> [String]
func clearLocalCommands()
}
open class Ready: BaseSyncStateWithInfo {
open override var label: SyncStateLabel { return SyncStateLabel.Ready }
let collectionKeys: Keys
public var hashedFxADeviceID: String {
return (scratchpad.fxaDeviceId + token.hashedFxAUID).sha256.hexEncodedString
}
public var engineConfiguration: EngineConfiguration? {
return scratchpad.engineConfiguration
}
public init(client: Sync15StorageClient, scratchpad: Scratchpad, token: TokenServerToken, info: InfoCollections, keys: Keys) {
self.collectionKeys = keys
super.init(client: client, scratchpad: scratchpad, token: token, info: info)
}
}
extension Ready: EngineStateChanges {
public func collectionsThatNeedLocalReset() -> [String] {
var needReset: Set<String> = Set()
for command in self.scratchpad.localCommands {
switch command {
case let .resetAllEngines(except: except):
needReset.formUnion(Set(LocalEngines).subtracting(except))
case let .resetEngine(engine):
needReset.insert(engine)
case .enableEngine, .disableEngine:
break
}
}
return needReset.sorted()
}
public func enginesEnabled() -> [String] {
var engines: Set<String> = Set()
for command in self.scratchpad.localCommands {
switch command {
case let .enableEngine(engine):
engines.insert(engine)
default:
break
}
}
return engines.sorted()
}
public func enginesDisabled() -> [String] {
var engines: Set<String> = Set()
for command in self.scratchpad.localCommands {
switch command {
case let .disableEngine(engine):
engines.insert(engine)
default:
break
}
}
return engines.sorted()
}
public func clearLocalCommands() {
self.scratchpad = self.scratchpad.evolve().clearLocalCommands().build().checkpoint()
}
}
|
b87fa8be9b4a9375c502b340847ded4e
| 41.511673 | 168 | 0.679076 | false | false | false | false |
UncleJoke/Spiral
|
refs/heads/master
|
Spiral/PlayerContactVisitor.swift
|
mit
|
1
|
//
// PlayerContactVisitor.swift
// Spiral
//
// Created by 杨萧玉 on 14-7-14.
// Copyright (c) 2014年 杨萧玉. All rights reserved.
//
import Foundation
import SpriteKit
class PlayerContactVisitor:ContactVisitor{
func visitPlayer(body:SKPhysicsBody){
// let thisNode = self.body.node
// let otherNode = body.node
// println(thisNode.name+"->"+otherNode.name)
}
func visitKiller(body:SKPhysicsBody){
let thisNode = self.body.node as! Player
// let otherNode = body.node
if thisNode.shield {
thisNode.shield = false
Data.sharedData.score++
let achievement = GameKitHelper.sharedGameKitHelper.getAchievementForIdentifier(kClean100KillerAchievementID)
if achievement.percentComplete <= 99.0{
achievement.percentComplete += 1
}
GameKitHelper.sharedGameKitHelper.updateAchievement(achievement, identifier: kClean100KillerAchievementID)
(thisNode.parent as! GameScene).soundManager.playKiller()
}
else {
thisNode.removeAllActions()
Data.sharedData.gameOver = true
}
}
func visitScore(body:SKPhysicsBody){
let thisNode = self.body.node as! Player
// let otherNode = body.node
Data.sharedData.score += 2
let achievement = GameKitHelper.sharedGameKitHelper.getAchievementForIdentifier(kCatch500ScoreAchievementID)
if achievement.percentComplete <= 99.8{
achievement.percentComplete += 0.2
}
GameKitHelper.sharedGameKitHelper.updateAchievement(achievement, identifier: kCatch500ScoreAchievementID)
(thisNode.parent as! GameScene).soundManager.playScore()
}
func visitShield(body:SKPhysicsBody){
let thisNode = self.body.node as! Player
// let otherNode = body.node
thisNode.shield = true
Data.sharedData.score++
let achievement = GameKitHelper.sharedGameKitHelper.getAchievementForIdentifier(kCatch500ShieldAchievementID)
if achievement.percentComplete <= 99.8{
achievement.percentComplete += 0.2
}
GameKitHelper.sharedGameKitHelper.updateAchievement(achievement, identifier: kCatch500ShieldAchievementID)
(thisNode.parent as! GameScene).soundManager.playShield()
}
}
|
efff682f5018e0d3fba240510b161e7e
| 35.307692 | 121 | 0.672319 | false | false | false | false |
phatblat/realm-cocoa
|
refs/heads/master
|
Realm/Tests/Swift/SwiftUnicodeTests.swift
|
apache-2.0
|
2
|
////////////////////////////////////////////////////////////////////////////
//
// Copyright 2014 Realm Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////
import XCTest
import Realm
#if canImport(RealmTestSupport)
import RealmTestSupport
#endif
let utf8TestString = "值значен™👍☞⎠‱௹♣︎☐▼❒∑⨌⧭иеمرحبا"
class SwiftRLMUnicodeTests: RLMTestCase {
// Swift models
func testUTF8StringContents() {
let realm = realmWithTestPath()
realm.beginWriteTransaction()
_ = SwiftRLMStringObject.create(in: realm, withValue: [utf8TestString])
try! realm.commitWriteTransaction()
let obj1 = SwiftRLMStringObject.allObjects(in: realm).firstObject() as! SwiftRLMStringObject
XCTAssertEqual(obj1.stringCol, utf8TestString, "Storing and retrieving a string with UTF8 content should work")
let obj2 = SwiftRLMStringObject.objects(in: realm, where: "stringCol == %@", utf8TestString).firstObject() as! SwiftRLMStringObject
XCTAssertTrue(obj1.isEqual(to: obj2), "Querying a realm searching for a string with UTF8 content should work")
}
func testUTF8PropertyWithUTF8StringContents() {
let realm = realmWithTestPath()
realm.beginWriteTransaction()
_ = SwiftRLMUTF8Object.create(in: realm, withValue: [utf8TestString])
try! realm.commitWriteTransaction()
let obj1 = SwiftRLMUTF8Object.allObjects(in: realm).firstObject() as! SwiftRLMUTF8Object
XCTAssertEqual(obj1.柱колоéнǢкƱаم👍, utf8TestString, "Storing and retrieving a string with UTF8 content should work")
// Test fails because of rdar://17735684
// let obj2 = SwiftRLMUTF8Object.objectsInRealm(realm, "柱колоéнǢкƱаم👍 == %@", utf8TestString).firstObject() as SwiftRLMUTF8Object
// XCTAssertEqual(obj1, obj2, "Querying a realm searching for a string with UTF8 content should work")
}
// Objective-C models
func testUTF8StringContents_objc() {
let realm = realmWithTestPath()
realm.beginWriteTransaction()
_ = StringObject.create(in: realm, withValue: [utf8TestString])
try! realm.commitWriteTransaction()
let obj1 = StringObject.allObjects(in: realm).firstObject() as! StringObject
XCTAssertEqual(obj1.stringCol, utf8TestString, "Storing and retrieving a string with UTF8 content should work")
// Temporarily commented out because variadic import seems broken
let obj2 = StringObject.objects(in: realm, where: "stringCol == %@", utf8TestString).firstObject() as! StringObject
XCTAssertTrue(obj1.isEqual(to: obj2), "Querying a realm searching for a string with UTF8 content should work")
}
func testUTF8PropertyWithUTF8StringContents_objc() {
let realm = realmWithTestPath()
realm.beginWriteTransaction()
_ = UTF8Object.create(in: realm, withValue: [utf8TestString])
try! realm.commitWriteTransaction()
let obj1 = UTF8Object.allObjects(in: realm).firstObject() as! UTF8Object
XCTAssertEqual(obj1.柱колоéнǢкƱаم, utf8TestString, "Storing and retrieving a string with UTF8 content should work")
// Test fails because of rdar://17735684
// let obj2 = UTF8Object.objectsInRealm(realm, "柱колоéнǢкƱаم == %@", utf8TestString).firstObject() as UTF8Object
// XCTAssertEqual(obj1, obj2, "Querying a realm searching for a string with UTF8 content should work")
}
}
|
b31557155f8f2c0a5bb4d7c7e1c5b2de
| 44.375 | 139 | 0.688956 | false | true | false | false |
toshiapp/toshi-ios-client
|
refs/heads/master
|
Toshi/Controllers/Payments/View/PaymentAddressInputView.swift
|
gpl-3.0
|
1
|
import Foundation
import UIKit
import TinyConstraints
protocol PaymentAddressInputDelegate: class {
func didRequestScanner()
func didRequestSendPayment()
func didChangeAddress(_ text: String)
}
final class PaymentAddressInputView: UIView {
weak var delegate: PaymentAddressInputDelegate?
var paymentAddress: String? {
didSet {
addressTextField.text = paymentAddress
}
}
private lazy var topDivider: UIView = {
let view = UIView()
view.backgroundColor = Theme.borderColor
return view
}()
private(set) lazy var addressTextField: UITextField = {
let view = UITextField()
view.font = Theme.preferredRegular()
view.delegate = self
view.placeholder = Localized.payment_input_placeholder
view.returnKeyType = .send
view.adjustsFontForContentSizeCategory = true
return view
}()
private lazy var qrButton: UIButton = {
let image = ImageAsset.qr_icon.withRenderingMode(.alwaysTemplate)
let view = UIButton()
view.contentMode = .center
view.tintColor = Theme.darkTextColor
view.setImage(image, for: .normal)
view.addTarget(self, action: #selector(qrButtonTapped(_:)), for: .touchUpInside)
return view
}()
private lazy var bottomDivider: UIView = {
let view = UIView()
view.backgroundColor = Theme.borderColor
return view
}()
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override init(frame: CGRect) {
super.init(frame: frame)
addSubview(topDivider)
addSubview(addressTextField)
addSubview(qrButton)
addSubview(bottomDivider)
topDivider.top(to: self)
topDivider.left(to: self)
topDivider.right(to: self)
topDivider.height(.lineHeight)
addressTextField.left(to: self, offset: 16)
addressTextField.centerY(to: self)
qrButton.topToBottom(of: topDivider)
qrButton.leftToRight(of: addressTextField)
qrButton.bottomToTop(of: bottomDivider)
qrButton.right(to: self)
qrButton.width(50)
qrButton.height(58)
bottomDivider.left(to: self, offset: 16)
bottomDivider.bottom(to: self)
bottomDivider.right(to: self, offset: -16)
bottomDivider.height(.lineHeight)
}
@objc func qrButtonTapped(_ button: UIButton) {
delegate?.didRequestScanner()
}
}
extension PaymentAddressInputView: UITextFieldDelegate {
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
delegate?.didRequestSendPayment()
return false
}
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
let textFieldText: NSString = String.contentsOrEmpty(for: textField.text) as NSString
let textAfterUpdate = textFieldText.replacingCharacters(in: range, with: string)
delegate?.didChangeAddress(textAfterUpdate)
return true
}
}
|
fbb07603520f8885e1ace6fb3ffcbc55
| 27.481818 | 129 | 0.661028 | false | false | false | false |
LYM-mg/MGOFO
|
refs/heads/master
|
MGOFO/MGOFO/Class/Home/Controller/ManuallyEnterLicenseVC.swift
|
mit
|
1
|
//
// ManuallyEnterLicenseVC.swift
// MGOFO
//
// Created by i-Techsys.com on 2017/5/15.
// Copyright © 2017年 i-Techsys. All rights reserved.
// 手动输入车牌号解锁
import UIKit
/*
import AVKit
import AudioToolbox
import CoreAudioKit
import CoreAudio
*/
class ManuallyEnterLicenseVC: UIViewController {
weak var superVC: EnterLicenseViewController?
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor(white: 0.97, alpha: 1.0)
setUpNavgationItem()
setUpMainView()
}
fileprivate func setUpNavgationItem() {
self.title = "车辆解锁"
self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "扫码用车", style: .done, target: self, action: #selector(backToScan))
self.navigationItem.leftBarButtonItem = UIBarButtonItem(image: #imageLiteral(resourceName: "navigationButtonReturnClick"), highImage: #imageLiteral(resourceName: "navigationButtonReturnClick"), norColor: UIColor.darkGray, selColor: UIColor.lightGray, title: "返回", target: self, action: #selector(ManuallyEnterLicenseVC.popClick(_:)))
}
@objc fileprivate func popClick(_ sender: UIButton) {
let _ = superVC?.navigationController?.popViewController(animated: true)
}
@objc fileprivate func backToScan() {
let _ = superVC?.navigationController?.popViewController(animated: true)
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesBegan(touches, with: event)
self.view.endEditing(true)
}
}
// MARK: - setUpMainView
extension ManuallyEnterLicenseVC {
// MARK: setUpMainView
fileprivate func setUpMainView() {
self.automaticallyAdjustsScrollViewInsets = false
setUpNavgationItem()
/// 顶部
let topView = TopView()
topView.resultLabel.isHidden = true
let bottomView = BottomView()
view.addSubview(topView)
view.addSubview(bottomView)
topView.sureBtnBlock = {
let secondController: UINavigationController? = self.superVC?.childViewControllers[1] as? UINavigationController
let oldController: UIViewController = (self.superVC?.currentViewController)!
self.superVC?.transition(from: oldController, to: secondController!, duration: 1, options: .transitionFlipFromLeft, animations: {() -> Void in
}, completion: {(_ finished: Bool) -> Void in
if finished {
// 隐藏返回(这时候无法pop回去上一个界面,否则就无法正常计费,导致BUG)
(self.superVC?.navigationController as! BaseNavigationController).popBtn.isHidden = true
(self.superVC?.navigationController as! BaseNavigationController).removeGlobalPanGes()
(secondController?.childViewControllers[0] as! GetLicensePlateNumberVC).byeCycleNumber = topView.inputTextField.text!
(secondController?.childViewControllers[0] as! GetLicensePlateNumberVC).startPlay()
self.superVC?.currentViewController = secondController
self.superVC?.view.addSubview((self.superVC?.currentViewController.view)!)
}
else {
self.superVC?.currentViewController = oldController
}
})
}
/// 布局
topView.snp.makeConstraints { (make) in
make.top.equalToSuperview().offset(navHeight+MGGloabalMargin)
make.left.equalToSuperview().offset(MGGloabalMargin)
make.right.equalToSuperview().offset(-MGGloabalMargin)
// make.height.equalTo(240)
}
bottomView.snp.makeConstraints { (make) in
make.top.equalTo(topView.snp.bottom).offset(MGGloabalMargin)
make.centerX.equalToSuperview()
make.height.equalTo(80)
make.width.equalTo(220)
}
}
}
|
937c7ce90d149e928818b98b5459f437
| 38.89899 | 341 | 0.648101 | false | false | false | false |
antonio081014/LeeCode-CodeBase
|
refs/heads/main
|
Swift/top-k-frequent-elements.swift
|
mit
|
2
|
/**
* https://leetcode.com/problems/top-k-frequent-elements/
*
*
*/
class Solution {
func topKFrequent(_ nums: [Int], _ k: Int) -> [Int] {
let map = nums.reduce([Int:Int](), {
var dict = $0
if dict[$1]==nil {
dict[$1] = 1
} else {
dict[$1] = 1 + dict[$1]!
}
return dict
}).reduce([Int:[Int]](), {
dict, item in
var dict_r = dict
if dict_r[item.value]==nil{
dict_r[item.value] = [item.key]
} else {
dict_r[item.value] = dict_r[item.value]! + [item.key]
}
return dict_r
})
var count = k
var maxn = nums.count
var ret = [Int]()
while count>0, maxn>0 {
if let list = map[maxn] {
var i = 0
while i<count, i<list.count {
ret += [list[i]]
i += 1
}
count -= i
}
maxn -= 1
}
return ret
}
}
/**
* https://leetcode.com/problems/top-k-frequent-elements/
*
*
*/
// Date: Fri Jul 17 10:16:22 PDT 2020
class Solution {
func topKFrequent(_ nums: [Int], _ k: Int) -> [Int] {
// 1. count the freq of each num in nums.
var count: [Int: Int] = [:]
for n in nums {
count[n] = 1 + count[n, default: 0]
}
// 2. Turn the dictionary into an Array.
var list: [(Int, Int)] = []
for (key, value) in count {
list.append((key, value))
}
// 3. Sort the array by the freq.
list = list.sorted(by: {
$0.1 > $1.1
})
// 4. Return first k elements with first value in the tuple.
return Array(list[0 ..< k].map { $0.0 })
}
}
/**
* https://leetcode.com/problems/top-k-frequent-elements/
*
*
*/
// Date: Fri Jul 17 10:49:12 PDT 2020
class Solution {
/// Bucket Sort
/// - Complexity:
/// - Time: O(n), n is the number of elements in nums.
/// - Space: O(n), n is the number of elements in nums
///
func topKFrequent(_ nums: [Int], _ k: Int) -> [Int] {
var count: [Int: Int] = [:]
for n in nums {
count[n] = 1 + count[n, default: 0]
}
var bucket: [[Int]] = Array(repeating: [], count: nums.count + 1)
for (key, value) in count {
if bucket[value] == nil {
bucket[value] = []
}
bucket[value].append(key)
}
var result: [Int] = []
for index in stride(from: nums.count, through: 0, by: -1) {
if bucket[index] != nil, bucket[index].isEmpty == false {
result += bucket[index]
}
if result.count >= k {
return result
}
}
return result
}
}
|
ea3eb18100df1b15e17a7678b44ec9fd
| 27.028571 | 73 | 0.432892 | false | false | false | false |
evering7/Speak
|
refs/heads/master
|
iSpeaking/SpeakData.swift
|
mit
|
1
|
//
// Data.swift
// iSpeaking
//
// Created by JianFei Li on 05/05/2017.
// Copyright © 2017 JianFei Li. All rights reserved.
//
import Foundation
import UIKit
import CoreData
class SpeakData: NSObject {
var sourceFeedList : [SourceFeedMem] = []
var feedSubItemList : [FeedSubItemMem] = []
// var sourceRSSList_totalCount : Int = 0
// var sourceRSSList_downloadedCount : Int = 0
func checkFeedURLAddedBefore_InDisk(feedURL: String) -> Bool {
// check if the URL exist in the db
// if it does, return true
// if it doesn't, return false
// if some error, return true
// 1. get context
guard let app = UIApplication.shared.delegate as? AppDelegate else {
return false
}
let context = app.coreDataStack.persistentContainer.newBackgroundContext()
// 2. declare the request for the data
let fetchRequest:NSFetchRequest<NSFetchRequestResult> = NSFetchRequest()
fetchRequest.fetchLimit = 2
// 3. declare an entity structure
let EntityName = "SourceFeedDisk"
let entity:NSEntityDescription? = NSEntityDescription.entity(forEntityName: EntityName, in: context)
fetchRequest.entity = entity
// Todo:done save the url in utf8 encoding, and use utf8 encoding to compare
// jianfei 2017 May 18th
// 4. set the conditional for query
let tempFeedURL : String = feedURL.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed)!
let predicate = NSPredicate.init(format: "feed_URL = %@ ", tempFeedURL)
fetchRequest.predicate = predicate
// 5. Query operation
do {
let fetchedObjects = try context.fetch(fetchRequest) as! [SourceFeedDisk]
if fetchedObjects.count == 1 {
return true
}else if fetchedObjects.count >= 2 {
printLog(message: "There are more than 2 records for a same feed URL. \(feedURL)")
return true
}else { return false } // no record
}catch {
let nsError = error as NSError
fatalError("Query error \(nsError), \(nsError.userInfo)")
// return true
}
}
func AddlySaveFeed_FromMem_ToDisk(sourceFeed: SourceFeedMem){
// check 1 thing the feed url is unique
let tempFeedURL = sourceFeed.feed_URL
if checkFeedURLAddedBefore_InDisk(feedURL: tempFeedURL){
printLog(message: "Failed to verify the feed URL never added before, in other words, the url exist in the database. \(sourceFeed.feed_URL)")
return
}
// first get db_ID
let db_ID = getMinimumAvailableFeedDBid_InDisk()
if db_ID < 0 {
fatalError("Can't get an effective minimum available db_ID for Feeds")
}
guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else {
return
}
// 1
let managedContext = appDelegate.coreDataStack.persistentContainer.newBackgroundContext()
// add two things
// check 1 thing
// the feed url is unique
// get minimum id auto, without need to manually set it
// 2
let entity = NSEntityDescription.entity(forEntityName: "SourceFeedDisk", in: managedContext)
let managedSourceFeed = NSManagedObject(entity: entity!, insertInto: managedContext)
// 3
managedSourceFeed.setValue(sourceFeed.feed_Title, forKey: "feed_Title")
managedSourceFeed.setValue(sourceFeed.feed_Language, forKey: "feed_Language")
// first let feed_URL converted to a utf8 encoding string
let tmpFeedURL : String = sourceFeed.feed_URL.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed)!
managedSourceFeed.setValue(tmpFeedURL, forKey: "feed_URL")
managedSourceFeed.setValue(sourceFeed.feed_Author, forKey: "feed_Author")
managedSourceFeed.setValue(sourceFeed.feed_Tags, forKey: "feed_Tags") // important
managedSourceFeed.setValue(sourceFeed.svr_Likes, forKey: "svr_Likes")
managedSourceFeed.setValue(sourceFeed.svr_Dislikes, forKey: "svr_Dislikes")
managedSourceFeed.setValue(sourceFeed.svr_SubscribeCount, forKey: "svr_SubscribeCount")
managedSourceFeed.setValue(db_ID, forKey: "db_ID")
managedSourceFeed.setValue(sourceFeed.db_DownloadedXMLFileName, forKey: "db_DownloadedXMLFileName")
managedSourceFeed.setValue(sourceFeed.feed_UpdateTime, forKey: "feed_UpdateTime")
// managedSourceFeed.setValue(sourceFeed.isLastUpdateSuccess, forKey:"isLastUpdateSuccess")
managedSourceFeed.setValue((sourceFeed.feed_IsDownloadSuccess), forKey: "feed_IsDownloadSuccess")
managedSourceFeed.setValue(sourceFeed.feed_DownloadTime, forKey:"feed_DownloadTime")
// could this line be executed correctly? need checking!
managedSourceFeed.setValue((sourceFeed.feed_IsRSSorAtom), forKey: "feed_IsRSSorAtom")
// total 14, db 2, feed 9, server 3
// 4
do {
try managedContext.save()
}catch let error as NSError {
printLog(message: "Could not save. \(error), \(error.userInfo)")
}
}
func getMinimumAvailableFeedDBid_InDisk() -> Int64 {
// 1. get context
guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else {
return -1
}
// 1-2.
let managedContext = appDelegate.coreDataStack.persistentContainer.newBackgroundContext()
// 2. declare the request for data
let fetchRequest: NSFetchRequest<NSFetchRequestResult> = NSFetchRequest()
// fetchRequest.fetchLimit = 10
let highestSortDescriptor = NSSortDescriptor(key: "db_ID",ascending: false)
fetchRequest.sortDescriptors = [highestSortDescriptor]
// 3. declare an entity
let EntityName = "SourceFeedDisk"
let entity: NSEntityDescription? = NSEntityDescription.entity(forEntityName: EntityName, in: managedContext)
fetchRequest.entity = entity
// 4. setup query condition
let predicate = NSPredicate.init(format: " %K >= %@ ", "db_ID", "0")
fetchRequest.predicate = predicate
// 5. do query operation
do {
let fetchedObjects = try managedContext.fetch(fetchRequest) as! [SourceFeedDisk]
if fetchedObjects.count == 0 {
return 0 // no field exist before
} else {
return (fetchedObjects[0].db_ID + 1)
}
}catch {
let nsError = error as NSError
fatalError("query error: \(nsError), \(nsError.userInfo)")
}
}
func getFeedSubItem_FromDisk_PendingToMemory() -> [FeedSubItemDisk]{
// get the feed sub item to memory
// 1. get a new context
guard let app = UIApplication.shared.delegate as? AppDelegate else {
printLog(message: "can not get an appDelegate object")
return []
}
let context = app.coreDataStack.privateUserContext
// 2. get fetch request
let fetchRequest = NSFetchRequest<FeedSubItemDisk>(entityName: "FeedSubItemDisk")
// 3. do the fetch
var localFeedSubItemList : [FeedSubItemDisk] = []
do {
localFeedSubItemList = try context.fetch(fetchRequest)
return localFeedSubItemList
}catch {
printLog(message: "Could not fetch. \(error.localizedDescription)")
return []
}
}
// todo: delete ? for better running
func getSourceFeed_FromDisk_PendingToMemory() -> [SourceFeedDisk] {
// 1
guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else {
return []
}
let managedContext = appDelegate.coreDataStack.privateUserContext
// 2
let fetchRequest = NSFetchRequest<SourceFeedDisk>(entityName: "SourceFeedDisk")
var localFeedList: [SourceFeedDisk] = []
// 3
do {
localFeedList = try managedContext.fetch(fetchRequest)
return localFeedList
}catch let error as NSError {
printLog(message: "Could not fetch. \(error), \(error.userInfo)")
return []
}
}
func getSourceRSSCount() -> Int? {
// 1
guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else {
return nil
}
let managedContext = appDelegate.coreDataStack.privateUserContext
let fetchRequest: NSFetchRequest<SourceFeedDisk> = SourceFeedDisk.fetchRequest()
do {
// go get the results
let searchResults = try managedContext.fetch(fetchRequest)
// Todo, more simplified solution to search for
// I like to check the size of the returned results
printLog(message: "num of results = \(searchResults.count)")
return searchResults.count
// You need to convert to NSManagedObject to use for loops
// for source in searchResults as [NSManagedObject] {
// // get the Key Value pairs
// print("\(String(describing: source.value(forKey: "author")))")
// }
}catch {
print("Error with request : \(error)")
return nil
}
}
func insertSomeDefaultSourceFeed(){
// Add code to save coredata
let sourceFeedObject : SourceFeedMem = SourceFeedMem()
// sourceFeedObject.initialize()
// sourceFeedObject.db_ID = 1
sourceFeedObject.feed_URL = "http://blog.sina.com.cn/rss/1462466974.xml"
// test if could check the exist record
self.AddlySaveFeed_FromMem_ToDisk(sourceFeed: sourceFeedObject)
// 20170520. Test ok of the addly save feed
// self.AddlySaveFeed_FromMem_ToDisk(sourceFeed: sourceFeedObject)
//sourceFeedObject.db_ID = 2
sourceFeedObject.feed_URL = "https://lijinghe.com/feed/"
self.AddlySaveFeed_FromMem_ToDisk(sourceFeed: sourceFeedObject)
// sourceFeedObject.db_ID = 3
sourceFeedObject.feed_URL = "http://www.767stock.com/feed"
self.AddlySaveFeed_FromMem_ToDisk(sourceFeed: sourceFeedObject)
// sourceFeedObject.db_ID = 4
sourceFeedObject.feed_URL = "http://www.huxiu.com/rss/"
self.AddlySaveFeed_FromMem_ToDisk(sourceFeed: sourceFeedObject)
// sourceFeedObject.db_ID = 5
sourceFeedObject.feed_URL = "http://blog.caixin.com/feed"
self.AddlySaveFeed_FromMem_ToDisk(sourceFeed: sourceFeedObject)
// sourceFeedObject.db_ID = 6
sourceFeedObject.feed_URL = "http://next.36kr.com/feed"
self.AddlySaveFeed_FromMem_ToDisk(sourceFeed: sourceFeedObject)
// sourceFeedObject.db_ID = 7
sourceFeedObject.feed_URL = "http://www.goingconcern.cn/feed.xml"
self.AddlySaveFeed_FromMem_ToDisk(sourceFeed: sourceFeedObject)
// sourceFeedObject.db_ID = 8
sourceFeedObject.feed_URL = "http://feeds.appinn.com/appinns/"
self.AddlySaveFeed_FromMem_ToDisk(sourceFeed: sourceFeedObject)
// sourceFeedObject.db_ID = 9
sourceFeedObject.feed_URL = "http://sspai.com/feed"
self.AddlySaveFeed_FromMem_ToDisk(sourceFeed: sourceFeedObject)
// sourceFeedObject.db_ID = 10
sourceFeedObject.feed_URL = "http://zhan.renren.com/zhihujx/rss"
self.AddlySaveFeed_FromMem_ToDisk(sourceFeed: sourceFeedObject)
// sourceFeedObject.db_ID = 11
sourceFeedObject.feed_URL = "http://www.ifanr.com/feed"
self.AddlySaveFeed_FromMem_ToDisk(sourceFeed: sourceFeedObject)
//Todo: add more from a text file, so the usability improved
// Finally, should get the content again.
}
func loadFeedList_FromDisk_ToMemory(diskList: [SourceFeedDisk], memList: inout [SourceFeedMem]){
if diskList.count == 0 {
printLog(message: "No need to copy, disklist is 0-length")
return
}
for sourceFeed: SourceFeedDisk in diskList {
let memSourceFeed = sourceFeed.loadSourceFeed_FromDisk_ToMemory()
memList.append(memSourceFeed)
}
}
func loadFeedSubItemList_FromDisk_ToMemory(diskList: [FeedSubItemDisk], memList: inout [FeedSubItemMem]){
// load
// load feed sub item list one by one from disk db to memory
// check count of disk list
if diskList.count == 0 {
printLog(message: "No need to copy, feed sub item disklist is 0-length")
return
}
// iteration through the disk list to get full new list
for feedSubItem: FeedSubItemDisk in diskList {
let memFeedSubItem = feedSubItem.loadFeedSubItemClass_FromDisk_ToMemory()
memList.append(memFeedSubItem)
}
}
func UpdatelySaveFeedMemData_ToDisk(sourceFeedClass: SourceFeedMem) -> Bool
{
// TODO: simplify these two lines as a func
guard let app = UIApplication.shared.delegate as? AppDelegate else {
printLog(message: "Return failure because cannot get appDelegate")
return false // failure
}
// let managedContext =
let managedContext = app.coreDataStack.privateUserContext
// let fetchRequest = NSFetchRequest<SourceFeed>(entityName: "SourceFeed")
let fetchRequest: NSFetchRequest<NSFetchRequestResult> = NSFetchRequest()
fetchRequest.fetchLimit = 2
// fetchRequest.fetchOffset = 0
let EntityName = "SourceFeedDisk"
let entity: NSEntityDescription? = NSEntityDescription.entity(forEntityName: EntityName, in: managedContext)
fetchRequest.entity = entity
let predicate = NSPredicate(format: "db_ID = %lld", sourceFeedClass.db_ID)
fetchRequest.predicate = predicate
do {
let fetchResults = try managedContext.fetch(fetchRequest) as! [SourceFeedDisk]
if fetchResults.count == 1 {
// Here, Modify the data
// let sourceFeed: SourceFeed = fetchResults[0]
// todo: add feed_SubItemCount = 10 in the future
fetchResults[0].db_DownloadedXMLFileName = sourceFeedClass.db_DownloadedXMLFileName
// sourceFeed.db_ID
fetchResults[0].feed_Author = sourceFeedClass.feed_Author
fetchResults[0].feed_DownloadTime = sourceFeedClass.feed_DownloadTime as NSDate
fetchResults[0].feed_IsDownloadSuccessBool = sourceFeedClass.feed_IsDownloadSuccess
fetchResults[0].feed_IsRSSorAtomBool = sourceFeedClass.feed_IsRSSorAtom
fetchResults[0].feed_Language = sourceFeedClass.feed_Language
fetchResults[0].feed_Tags = sourceFeedClass.feed_Tags
fetchResults[0].feed_Title = sourceFeedClass.feed_Title
fetchResults[0].feed_UpdateTime = sourceFeedClass.feed_UpdateTime as NSDate
fetchResults[0].feed_URL = sourceFeedClass.feed_URL
fetchResults[0].svr_Likes = sourceFeedClass.svr_Likes
fetchResults[0].svr_Dislikes = sourceFeedClass.svr_Dislikes
fetchResults[0].svr_SubscribeCount = sourceFeedClass.svr_SubscribeCount
app.coreDataStack.saveContext()
printLog(message: "return as success truely")
return true // success
}else {
printLog(message: "return because fields count not equal 1")
return false // failure
}
// }else {
// printLog(message: "unwrap the fetchResults failure")
// return false
// }
}catch {
printLog(message: "\(error.localizedDescription)")
return false
}
// let entity = NSEntityDescription.entity(forEntityName: "SourceFeed", in: managedContext)
//
// let managedSourceFeed = NSManagedObject(entity: entity!, insertInto: managedContext)
}
// todo: From here 2017.5.10. still working on name modification
func UpdateOrAdd_SaveFeedSubItemData_ToDisk(sourceFeedClass: SourceFeedMem) -> Bool {
// Steps: It should be circle
// 1. Do a query, check if exist a title-same article / subitem or not
// 2. if exist, update the feed sub item
// 3. if not exist, add the feed sub item
// 4. if success, return true
// frame 1. a check for rss or atom
// frame 2. loop
// Step 1. Do a query, to check if exist a title-same article.
if sourceFeedClass.feed_IsRSSorAtom == true {
// rss feed
// do a loop
if let items = sourceFeedClass.mem_rssFeed.items{
for item: RSSFeedItem in items {
let db_SubItemID = getCurrentlyExistIDForItem_InMem(subItem: item) // query mem data
if db_SubItemID < 0 {
// indicating no sub item id
Addly_SaveFeedSubItemData_ToDisk(rssFeedItem: item, sourceFeedClass: sourceFeedClass)
} else {
// indicating existing the sub item id
// todo here
Update_SaveFeedSubItemData_ToDisk(rssFeedItem: item, sourceFeedClass: sourceFeedClass)
}
}
}
}else{
// atom
}
return false
}
func getCurrentlyExistIDForItem_InMem(subItem: RSSFeedItem) -> Int64 {
// For use of RSSFeed
// get the existing id from
// search the maximum id
if self.feedSubItemList.count == 0 {
return -1 // no exist the id
}
// search for the exist id
for feedSubItem : FeedSubItemMem in self.feedSubItemList {
// search the Article URL
if let subLink = subItem.link {
if feedSubItem.item_ArticleURL == subLink {
return feedSubItem.db_SubItemID
}
}
}
return -2 // search but no exist
}
func getCurrentlyExistIDForItem_InDisk(subItem: RSSFeedItem ) -> Int64 {
// return -1 means unsuccessful to get an existing FeedItem
// do a query by title and link
// step 1. get the data context
// TODO: simplify these two lines as a func
guard let app = UIApplication.shared.delegate as? AppDelegate else {
printLog(message: "Return failure because cannot get appDelegate")
return -1 // failure
}
let context = app.coreDataStack.privateUserContext
// step 2. declare the data search request
let fetchRequest:NSFetchRequest<NSFetchRequestResult> = NSFetchRequest()
fetchRequest.fetchLimit = 2
fetchRequest.fetchOffset = 0
// step 3. declare an entity
let EntityName = "FeedSubItemDisk"
let entity:NSEntityDescription? = NSEntityDescription.entity(forEntityName: EntityName, in: context)
fetchRequest.entity = entity
// step 4. setup conditional form for search
let predicate = NSPredicate.init(format: "item_ArticleURL = %@ ", subItem.link!)
fetchRequest.predicate = predicate
// step 5. query operation
do {
let fetchedObjects = try context.fetch(fetchRequest) as! [FeedSubItemDisk]
// iterate the query results
if fetchedObjects.count == 1 {
// Only one is the correct state
return fetchedObjects[0].db_SubItemID
}else if fetchedObjects.count >= 2 {
printLog(message: "Unexpected: the query results count exceed 1. \(fetchedObjects.count)")
return fetchedObjects[0].db_SubItemID
}else {
// return -1 indicate no records are found
return -1
}
}catch {
fatalError("Query Error: \(error.localizedDescription)")
// return -2 // means error indeed
}
}
func Update_SaveFeedSubItemData_ToDisk(rssFeedItem: RSSFeedItem, sourceFeedClass: SourceFeedMem) -> Bool{
return true
}
func Addly_SaveFeedSubItemData_ToDisk(rssFeedItem: RSSFeedItem, sourceFeedClass: SourceFeedMem) -> Bool{
// function: add a feeditem to feeditem disk database
// step 1. get the data context
// TODO: simplify these two lines as a func
guard let app = UIApplication.shared.delegate as? AppDelegate else {
printLog(message: "Return failure because cannot get appDelegate")
return false // failure
}
let context = app.coreDataStack.privateUserContext
// step 2. create a FeedSubItem object
let EntityName = "FeedSubItemDisk"
let oneItem = NSEntityDescription.insertNewObject(forEntityName: EntityName, into: context) as! FeedSubItemDisk
// step 3. assign value to the object
// TODO: add a real file name
oneItem.db_DownloadedHtmlFileName = ""
oneItem.db_SubItemID = getAvailableMinimumSubItemID() // TODO: Add this function
return false
}
func getAvailableMinimumSubItemID() -> Int64 {
// Todo
return 1
}
func parseFeedXmlAndUpdateMemData(sourceFeedClass: SourceFeedMem){
// let singleSourceRSS = speakData.sourceRSSList[0]
let fileURL = getRSSxmlFileURLfromLastComponent(lastPathCompo:
sourceFeedClass.db_DownloadedXMLFileName)
let feedParser = FeedParser(URL: fileURL)
let result = feedParser?.parse()
if let newResult = result {
switch newResult {
case Result.rss (let rssFeed):
printLog(message: "url: \(sourceFeedClass.feed_URL)")
printLog(message: "link \(String(describing: rssFeed.link))")
// Start to convert things in rssfeed
sourceFeedClass.feed_Title = rssFeed.title ?? "no title"
sourceFeedClass.feed_Language = rssFeed.language ?? "no specified lang"
// url blank
sourceFeedClass.feed_Author = rssFeed.managingEditor ?? "no editor/author"
sourceFeedClass.feed_Tags = String(describing: rssFeed.categories)
// skip: likes, dislikes, subscribeCount, id, downloadedXMLFileName,
let upDate: Date
if rssFeed.pubDate != nil {
upDate = (rssFeed.pubDate)!
}else{
upDate = getDefaultTime()
}
sourceFeedClass.feed_UpdateTime = upDate
sourceFeedClass.feed_IsRSSorAtom = true
sourceFeedClass.mem_rssFeed = rssFeed
// sourceFeedClass.isLastUpdateSuccess = true
// skip: isDownloadSuccess, lastDownloadTime
// Here: should convert items into RSSArticleItem
if let rssFeedItems = rssFeed.items {
let isSuccess = self.addFeedSubItems_FromNetFeed_ToMemoryList(rssFeedItems: rssFeedItems)
if !isSuccess {
printLog(message: "fail to add RSS Feed Item to MemList")
}
}
case Result.atom (let atomFeed):
printLog(message: "url: \(sourceFeedClass.feed_URL)")
printLog(message: "link: \(String(describing: atomFeed.links))")
sourceFeedClass.feed_Title = atomFeed.title ?? "no title"
sourceFeedClass.feed_Language = "unkown language"
sourceFeedClass.feed_Author = String(describing: atomFeed.authors)
sourceFeedClass.feed_Tags = String(describing: atomFeed.categories)
sourceFeedClass.feed_UpdateTime = (atomFeed.updated) ?? getDefaultTime()
sourceFeedClass.feed_IsRSSorAtom = false
sourceFeedClass.mem_atomFeed = atomFeed
// sourceFeedClass.isLastUpdateSuccess = true
if let atomFeedItems = atomFeed.entries {
let isSuccess = self.addFeedSubItems_FromNetFeed_ToMemoryList(atomFeedItems: atomFeedItems)
if !isSuccess {
printLog(message: "fail to add atom feed to MemList")
}
}
// atomFeed.links?[0].attributes?.title
case Result.failure(let error):
printLog(message: error)
}
}else { // result is nil
printLog(message: "error in parsing the result: the result is nil")
}
}
func addFeedSubItems_FromNetFeed_ToMemoryList(rssFeedItems: [RSSFeedItem]) -> Bool{
// from rssFeedItmes to articleOfRSSList
for singleRSSFeedItem: RSSFeedItem in rssFeedItems {
let feedSubItemClass = singleRSSFeedItem.loadFeedSubItem_FromNetFeed_ToMemory()
self.feedSubItemList.append(feedSubItemClass)
}
return true
}
func addFeedSubItems_FromNetFeed_ToMemoryList(atomFeedItems: [AtomFeedEntry]) -> Bool {
for singleAtomFeedItem: AtomFeedEntry in atomFeedItems{
let feedSubItemClass = singleAtomFeedItem.loadFeedSubItem_FromNetFeed_ToMemory()
self.feedSubItemList.append(feedSubItemClass)
}
return true
}
class func getAvailabeMinimumIDofFeedSubItem_InMem() -> Int64 {
// todo: may be here need to add disk id
let appDelegate = UIApplication.shared.delegate as! AppDelegate
var maxID: Int64 = 0
for singleArticleItem in appDelegate.speakData.feedSubItemList {
if maxID < (singleArticleItem.db_SubItemID) {
maxID = (singleArticleItem.db_SubItemID)
}
}
return (maxID + 1) // minimum available id
}
class func getAvailableMinimumSubItemID() -> Int64 {
// ToDo: Add this function
return 1
}
}
|
f5be837f5c5c2d06de39b0b2eb70dae0
| 36.644684 | 152 | 0.582159 | false | false | false | false |
vnu/vTweetz
|
refs/heads/master
|
Pods/SwiftDate/SwiftDate/Dictionary+SwiftDate.swift
|
apache-2.0
|
2
|
//
// SwiftDate, an handy tool to manage date and timezones in swift
// Created by: Daniele Margutti
// Main contributors: Jeroen Houtzager
//
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
// MARK: - Generate a Date from a Dictionary of NSCalendarUnit:Value
public typealias DateComponentDictionary = [ NSCalendarUnit: AnyObject ]
//MARK: - Extension: NSCalendarUnit -
protocol CalendarAsDictionaryKey: Hashable {}
extension NSCalendarUnit: CalendarAsDictionaryKey {
public var hashValue: Int {
get {
return Int(self.rawValue)
}
}
}
extension Dictionary where Value: AnyObject, Key: CalendarAsDictionaryKey {
func components() -> NSDateComponents {
let components = NSDateComponents()
for (key, value) in self {
if let value = value as? Int {
components.setValue(value, forComponent: key as! NSCalendarUnit)
} else if let value = value as? NSCalendar {
components.calendar = value
} else if let value = value as? NSTimeZone {
components.timeZone = value
}
}
return components
}
/**
Convert a dictionary of <NSCalendarUnit,Value> in a DateInRegion. Both timeZone and calendar must be specified into the dictionary. You can also specify a locale; if nil UTCRegion()'s locale will be used instead.
- parameter locale: optional locale (Region().locale if nil)
- returns: DateInRegion if date components are complete, nil if cannot be used to generate a valid date
*/
func dateInRegion() -> DateInRegion? {
return DateInRegion(self.components())
}
func dateRegion() -> Region? {
let components = self.components()
let calendar = components.calendar ?? NSCalendar.currentCalendar()
let timeZone = components.timeZone ?? NSTimeZone.defaultTimeZone()
let locale = calendar.locale ?? NSLocale.currentLocale()
return Region(calendar: calendar, timeZone: timeZone, locale: locale)
}
/**
Convert a dictionary of <NSCalendarUnit,Value> in absolute time NSDate instance. Both timeZone and calendar must be specified into the dictionary. You can also specify a locale; if nil UTCRegion()'s locale will be used instead.
- returns: absolute time NSDate object, nil if dictionary values cannot be used to generate a valid date
*/
func absoluteTime() -> NSDate? {
let date = self.dateInRegion()
return date?.absoluteTime
}
}
|
ef6dfc09caf57df15e102ec9c40bf1de
| 38.413043 | 232 | 0.691395 | false | false | false | false |
wibosco/WhiteBoardCodingChallenges
|
refs/heads/main
|
WhiteBoardCodingChallenges/Challenges/CrackingTheCodingInterview/ValidateBST/ValidateBSTFactory.swift
|
mit
|
1
|
//
// ValidateBSTFactory.swift
// WhiteBoardCodingChallenges
//
// Created by William Boles on 02/07/2016.
// Copyright © 2016 Boles. All rights reserved.
//
import UIKit
class ValidateBSTFactory: NSObject {
// MARK: Build
class func buildBinaryTree(relationships: [[Int]]) -> ValidateBSTNode {
var nodes = [Int: ValidateBSTNode]()
for relationship in relationships {
let parentNodeValue = relationship[0]
let childNodeValue = relationship[1]
var parentNode = nodes[parentNodeValue]
var childNode = nodes[childNodeValue]
if parentNode == nil {
parentNode = ValidateBSTNode(value: parentNodeValue)
nodes[parentNodeValue] = parentNode
}
if childNode == nil {
childNode = ValidateBSTNode(value: childNodeValue)
nodes[childNodeValue] = childNode
}
parentNode!.addNodeAsChild(node: childNode!)
}
return rootNode(nodes: nodes)
}
class func rootNode(nodes: [Int: ValidateBSTNode]) -> ValidateBSTNode {
var rootNode: ValidateBSTNode?
for node in nodes.values {
if node.parent == nil {
rootNode = node
break
}
}
return rootNode!
}
}
|
e6f6fbfda2bd49bdcb9554000ca0eb3e
| 25.851852 | 75 | 0.541379 | false | false | false | false |
strike65/SwiftyStats
|
refs/heads/master
|
SwiftyStats/CommonSource/ProbDist/ProbDist-Gamma.swift
|
gpl-3.0
|
1
|
//
// Created by VT on 20.07.18.
// Copyright © 2018 strike65. All rights reserved.
/*
Copyright (2017-2019) strike65
GNU GPL 3+
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, version 3 of the License.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import Foundation
#if os(macOS) || os(iOS)
import os.log
#endif
extension SSProbDist {
/// Gamma distribution
public enum Gamma {
/// Returns a SSProbDistParams struct containing mean, variance, kurtosis and skewness of the Gamma distribution.
/// - Parameter a: Shape parameter
/// - Parameter b: Scale parameter
/// - Throws: SSSwiftyStatsError if a <= 0 || b <= 0
public static func para<FPT: SSFloatingPoint & Codable>(shape a: FPT, scale b: FPT) throws -> SSProbDistParams<FPT> {
if (a <= 0) {
#if os(macOS) || os(iOS)
if #available(macOS 10.12, iOS 13, *) {
os_log("scale parameter a is expected to be > 0", log: .log_stat, type: .error)
}
#endif
throw SSSwiftyStatsError.init(type: .functionNotDefinedInDomainProvided, file: #file, line: #line, function: #function)
}
if (b <= 0) {
#if os(macOS) || os(iOS)
if #available(macOS 10.12, iOS 13, *) {
os_log("scale parameter a is expected to be > 0", log: .log_stat, type: .error)
}
#endif
throw SSSwiftyStatsError.init(type: .functionNotDefinedInDomainProvided, file: #file, line: #line, function: #function)
}
var result: SSProbDistParams<FPT> = SSProbDistParams<FPT>()
result.mean = a * b
result.variance = a * b * b
result.kurtosis = 3 + 6 / a
result.skewness = 2 / sqrt(a)
return result
}
/// Returns the pdf of the Gamma distribution.
/// - Parameter x: x
/// - Parameter a: Shape parameter
/// - Parameter b: Scale parameter
/// - Throws: SSSwiftyStatsError if a <= 0 || b <= 0
public static func pdf<FPT: SSFloatingPoint & Codable>(x: FPT, shape a: FPT, scale b: FPT) throws -> FPT {
if (a <= 0) {
#if os(macOS) || os(iOS)
if #available(macOS 10.12, iOS 13, *) {
os_log("scale parameter a is expected to be > 0", log: .log_stat, type: .error)
}
#endif
throw SSSwiftyStatsError.init(type: .functionNotDefinedInDomainProvided, file: #file, line: #line, function: #function)
}
if (b <= 0) {
#if os(macOS) || os(iOS)
if #available(macOS 10.12, iOS 13, *) {
os_log("scale parameter a is expected to be > 0", log: .log_stat, type: .error)
}
#endif
throw SSSwiftyStatsError.init(type: .functionNotDefinedInDomainProvided, file: #file, line: #line, function: #function)
}
var ex1: FPT
var ex2: FPT
if x <= 0 {
return 0
}
else {
let a1: FPT = -a * SSMath.log1(b)
let a2: FPT = -x / b
let a3: FPT = -1 + a
ex1 = a1 + a2
ex2 = ex1 + a3 * SSMath.log1(x)
let a4: FPT = ex2 - SSMath.lgamma1(a)
let result = SSMath.exp1(a4)
return result
}
}
/// Returns the cdf of the Gamma distribution.
/// - Parameter x: x
/// - Parameter a: Shape parameter
/// - Parameter b: Scale parameter
/// - Throws: SSSwiftyStatsError if a <= 0 || b <= 0
public static func cdf<FPT: SSFloatingPoint & Codable>(x: FPT, shape a: FPT, scale b: FPT) throws -> FPT {
if (a <= 0) {
#if os(macOS) || os(iOS)
if #available(macOS 10.12, iOS 13, *) {
os_log("scale parameter a is expected to be > 0", log: .log_stat, type: .error)
}
#endif
throw SSSwiftyStatsError.init(type: .functionNotDefinedInDomainProvided, file: #file, line: #line, function: #function)
}
if (b <= 0) {
#if os(macOS) || os(iOS)
if #available(macOS 10.12, iOS 13, *) {
os_log("scale parameter a is expected to be > 0", log: .log_stat, type: .error)
}
#endif
throw SSSwiftyStatsError.init(type: .functionNotDefinedInDomainProvided, file: #file, line: #line, function: #function)
}
if x < 0 {
return 0
}
var cv: Bool = false
let result = SSSpecialFunctions.gammaNormalizedP(x: x / b, a: a, converged: &cv)
if cv {
return result
}
else {
#if os(macOS) || os(iOS)
if #available(macOS 10.12, iOS 13, *) {
os_log("unable to retrieve a result", log: .log_stat, type: .error)
}
#endif
throw SSSwiftyStatsError.init(type: .maxNumberOfIterationReached, file: #file, line: #line, function: #function)
}
}
/// Returns the quantile of the Gamma distribution.
/// - Parameter p: p
/// - Parameter a: Shape parameter
/// - Parameter b: Scale parameter
/// - Throws: SSSwiftyStatsError if a <= 0 || b <= 0 || p < 0 || p > 1
public static func quantile<FPT: SSFloatingPoint & Codable>(p: FPT, shape a: FPT, scale b: FPT) throws -> FPT {
if (a <= 0) {
#if os(macOS) || os(iOS)
if #available(macOS 10.12, iOS 13, *) {
os_log("scale parameter a is expected to be > 0", log: .log_stat, type: .error)
}
#endif
throw SSSwiftyStatsError.init(type: .functionNotDefinedInDomainProvided, file: #file, line: #line, function: #function)
}
if (b <= 0) {
#if os(macOS) || os(iOS)
if #available(macOS 10.12, iOS 13, *) {
os_log("scale parameter a is expected to be > 0", log: .log_stat, type: .error)
}
#endif
throw SSSwiftyStatsError.init(type: .functionNotDefinedInDomainProvided, file: #file, line: #line, function: #function)
}
if p < 0 || p > 1 {
#if os(macOS) || os(iOS)
if #available(macOS 10.12, iOS 13, *) {
os_log("p is expected to be >= 0 and <= 1 ", log: .log_stat, type: .error)
}
#endif
throw SSSwiftyStatsError.init(type: .functionNotDefinedInDomainProvided, file: #file, line: #line, function: #function)
}
if p == 0 {
return 0
}
if p == 1 {
return FPT.infinity
}
var gVal: FPT = 0
var maxG: FPT = 0
var minG: FPT = 0
maxG = a * b + 4000
minG = 0
gVal = a * b
var test: FPT
var i = 1
while((maxG - minG) > Helpers.makeFP(1.0E-14)) {
test = try! cdf(x: gVal, shape: a, scale: b)
if test > p {
maxG = gVal
}
else {
minG = gVal
}
gVal = (maxG + minG) * Helpers.makeFP(0.5 )
i = i + 1
if i >= 7500 {
break
}
}
if((a * b) > 10000) {
let t1: FPT = gVal * Helpers.makeFP(1E07)
let ri: FPT = floor(t1)
let rd: FPT = ri / Helpers.makeFP(1E07)
return rd
}
else {
return gVal
}
}
}
}
|
513cb359ec67151430f5ade5b941d894
| 36.710744 | 135 | 0.458799 | false | false | false | false |
charlesmwang/Yukina
|
refs/heads/master
|
Yukina/YKHelper_Internal.swift
|
mit
|
1
|
import Foundation
func mergeDictionary<K,V>(dict1: [K:V], dict2: [K:V]) -> [K:V] {
var dict:[K:V] = dict1
for (key, value) in dict2 {
dict.updateValue(value, forKey: key)
}
return dict
}
func extractQueryItems(queryItems:[AnyObject]?) -> [String:String]{
let dictQueryItems:[[String:String]]? = queryItems?.map({ (queryItem) -> [String:String] in
if let queryItem = queryItem as? NSURLQueryItem, let value = queryItem.value {
return [queryItem.name: value]
}
else {
return [:]
}
})
if let dictQueryItems = dictQueryItems {
let dictQueryItem:[String:String] = dictQueryItems.reduce([:], combine: { (queryItem1, queryItem2) -> [String:String] in
return mergeDictionary(queryItem1, queryItem2)
})
return dictQueryItem
}
return [String:String]()
}
|
8089708f94ed163873045848667f67ee
| 27.967742 | 128 | 0.596882 | false | false | false | false |
simplyzhao/ForecastIO
|
refs/heads/master
|
ForecastIO/AlertObject.swift
|
mit
|
1
|
//
// AlertObject.swift
// Weather
//
// Created by Alex Zhao on 11/25/15.
// Copyright © 2015 Alex Zhao. All rights reserved.
//
import Foundation
public struct AlertObject {
public let title: String?
public let expires: NSTimeInterval?
public let description: String?
public let uri: NSURL?
init(data: [String: AnyObject]) {
self.title = data["title"] as? String
self.expires = data["expires"] as? NSTimeInterval
self.description = data["description"] as? String
if let uriString = data["uri"] as? String {
self.uri = NSURL(string: uriString)
} else {
self.uri = nil
}
}
}
|
c577f8ebcdf733ef786741ae4c663246
| 23.678571 | 57 | 0.598551 | false | false | false | false |
daniel-barros/TV-Calendar
|
refs/heads/master
|
TraktKit/Common/TraktWatchedShow.swift
|
gpl-3.0
|
1
|
//
// TraktWatchedShow.swift
// TraktKit
//
// Created by Maximilian Litteral on 4/13/16.
// Copyright © 2016 Maximilian Litteral. All rights reserved.
//
import Foundation
public struct TraktWatchedShow: TraktProtocol {
// Extended: Min
public let plays: Int // Total number of plays
public let lastWatchedAt: Date
public let show: TraktShow
public let seasons: [TraktWatchedSeason]
// Initialize
public init?(json: RawJSON?) {
guard
let json = json,
let plays = json["plays"] as? Int,
let lastWatchedAt = Date.dateFromString(json["last_watched_at"]),
let show = TraktShow(json: json["show"] as? RawJSON) else { return nil }
self.plays = plays
self.lastWatchedAt = lastWatchedAt
self.show = show
var tempSeasons: [TraktWatchedSeason] = []
let jsonSeasons = json["seasons"] as? [RawJSON] ?? []
for jsonSeason in jsonSeasons {
guard
let season = TraktWatchedSeason(json: jsonSeason) else { continue }
tempSeasons.append(season)
}
seasons = tempSeasons
}
}
|
20e56fd51839bb0e285968a6c7483acf
| 29.666667 | 84 | 0.596154 | false | false | false | false |
omise/omise-ios
|
refs/heads/master
|
OmiseSDK/TrueMoneyFormViewController.swift
|
mit
|
1
|
import UIKit
@objc(OMSTrueMoneyFormViewController)
class TrueMoneyFormViewController: UIViewController, PaymentSourceChooser, PaymentChooserUI, PaymentFormUIController {
var flowSession: PaymentCreatorFlowSession?
private var client: Client?
private var isInputDataValid: Bool {
return formFields.reduce(into: true) { (valid, field) in
valid = valid && field.isValid
}
}
@IBInspectable var preferredPrimaryColor: UIColor? {
didSet {
applyPrimaryColor()
}
}
@IBInspectable var preferredSecondaryColor: UIColor? {
didSet {
applySecondaryColor()
}
}
var currentEditingTextField: OmiseTextField?
@IBOutlet var contentView: UIScrollView!
@IBOutlet private var phoneNumberTextField: OmiseTextField!
@IBOutlet private var submitButton: MainActionButton!
@IBOutlet private var requestingIndicatorView: UIActivityIndicatorView!
@IBOutlet private var errorLabel: UILabel!
@IBOutlet var formLabels: [UILabel]!
@IBOutlet var formFields: [OmiseTextField]!
@IBOutlet var formFieldsAccessoryView: UIToolbar!
@IBOutlet var gotoPreviousFieldBarButtonItem: UIBarButtonItem!
@IBOutlet var gotoNextFieldBarButtonItem: UIBarButtonItem!
@IBOutlet var doneEditingBarButtonItem: UIBarButtonItem!
// need to refactor loadView, removing super results in crash
// swiftlint:disable prohibited_super_call
override func loadView() {
super.loadView()
view.backgroundColor = .background
formFieldsAccessoryView.barTintColor = .formAccessoryBarTintColor
submitButton.defaultBackgroundColor = .omise
submitButton.disabledBackgroundColor = .line
}
override func viewDidLoad() {
super.viewDidLoad()
applyPrimaryColor()
applySecondaryColor()
navigationItem.backBarButtonItem = UIBarButtonItem(title: "", style: .plain, target: nil, action: nil)
formFields.forEach {
$0.inputAccessoryView = formFieldsAccessoryView
}
formFields.forEach {
$0.adjustsFontForContentSizeCategory = true
}
formLabels.forEach {
$0.adjustsFontForContentSizeCategory = true
}
submitButton.titleLabel?.adjustsFontForContentSizeCategory = true
if #available(iOS 11, *) {
// We'll leave the adjusting scroll view insets job for iOS 11 and later to the layoutMargins + safeAreaInsets here
} else {
automaticallyAdjustsScrollViewInsets = true
}
NotificationCenter.default.addObserver(
self,
selector: #selector(keyboardWillChangeFrame(_:)),
name: NotificationKeyboardWillChangeFrameNotification,
object: nil
)
NotificationCenter.default.addObserver(
self,
selector: #selector(keyboardWillHide(_:)),
name: NotificationKeyboardWillHideFrameNotification,
object: nil
)
phoneNumberTextField.validator = try? NSRegularExpression(pattern: "\\d{10,11}\\s?", options: [])
}
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
if #available(iOS 11, *) {
// There's a bug in iOS 10 and earlier which the text field's intrinsicContentSize is returned the value
// that doesn't take the result of textRect(forBounds:) method into an account for the initial value
// So we need to invalidate the intrinsic content size here to ask those text fields to calculate their
// intrinsic content size again
} else {
formFields.forEach {
$0.invalidateIntrinsicContentSize()
}
}
}
@IBAction private func submitForm(_ sender: AnyObject) {
guard let phoneNumber = phoneNumberTextField.text?.trimmingCharacters(in: CharacterSet.whitespaces) else {
return
}
let trueMoneyInformation = PaymentInformation.TrueMoney(phoneNumber: phoneNumber)
requestingIndicatorView.startAnimating()
view.isUserInteractionEnabled = false
view.tintAdjustmentMode = .dimmed
submitButton.isEnabled = false
flowSession?.requestCreateSource(.truemoney(trueMoneyInformation)) { _ in
self.requestingIndicatorView.stopAnimating()
self.view.isUserInteractionEnabled = true
self.view.tintAdjustmentMode = .automatic
self.submitButton.isEnabled = true
}
}
@IBAction private func validateFieldData(_ textField: OmiseTextField) {
submitButton.isEnabled = isInputDataValid
}
@IBAction private func validateTextFieldDataOf(_ sender: OmiseTextField) {
let duration = TimeInterval(NavigationControllerHideShowBarDuration)
UIView.animate(withDuration: duration,
delay: 0.0,
options: [.curveEaseInOut, .allowUserInteraction, .beginFromCurrentState, .layoutSubviews]) {
self.validateField(sender)
}
sender.borderColor = currentSecondaryColor
}
@IBAction private func updateInputAccessoryViewFor(_ sender: OmiseTextField) {
let duration = TimeInterval(NavigationControllerHideShowBarDuration)
UIView.animate(withDuration: duration,
delay: 0.0,
options: [.curveEaseInOut, .allowUserInteraction, .beginFromCurrentState, .layoutSubviews]) {
self.errorLabel.alpha = 0.0
}
updateInputAccessoryViewWithFirstResponder(sender)
sender.borderColor = view.tintColor
}
@IBAction private func doneEditing(_ button: UIBarButtonItem?) {
doneEditing()
}
private func validateField(_ textField: OmiseTextField) {
do {
try textField.validate()
errorLabel.alpha = 0.0
} catch {
switch error {
case OmiseTextFieldValidationError.emptyText:
errorLabel.text = "-" // We need to set the error label some string in order to have it retains its height
case OmiseTextFieldValidationError.invalidData:
errorLabel.text = NSLocalizedString(
"truemoney-form.phone-number-field.invalid-data.error.text",
tableName: "Error",
bundle: .module,
value: "Phone number is invalid",
comment: "An error text in the TrueMoney form displayed when the phone number is invalid"
)
default:
errorLabel.text = error.localizedDescription
}
errorLabel.alpha = errorLabel.text != "-" ? 1.0 : 0.0
}
}
@objc func keyboardWillChangeFrame(_ notification: NSNotification) {
guard let frameEnd = notification.userInfo?[NotificationKeyboardFrameEndUserInfoKey] as? CGRect,
let frameStart = notification.userInfo?[NotificationKeyboardFrameBeginUserInfoKey] as? CGRect,
frameEnd != frameStart else {
return
}
let intersectedFrame = contentView.convert(frameEnd, from: nil)
contentView.contentInset.bottom = intersectedFrame.height
let bottomScrollIndicatorInset: CGFloat
if #available(iOS 11.0, *) {
bottomScrollIndicatorInset = intersectedFrame.height - contentView.safeAreaInsets.bottom
} else {
bottomScrollIndicatorInset = intersectedFrame.height
}
contentView.scrollIndicatorInsets.bottom = bottomScrollIndicatorInset
}
@objc func keyboardWillHide(_ notification: NSNotification) {
contentView.contentInset.bottom = 0.0
contentView.scrollIndicatorInsets.bottom = 0.0
}
}
|
9fba63485272d4f7fd57b38eb20c292f
| 37.199052 | 127 | 0.638586 | false | false | false | false |
Authman2/Pix
|
refs/heads/master
|
Eureka-master/Source/Core/Cell.swift
|
apache-2.0
|
5
|
// Cell.swift
// Eureka ( https://github.com/xmartlabs/Eureka )
//
// Copyright (c) 2016 Xmartlabs ( http://xmartlabs.com )
//
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
/// Base class for the Eureka cells
open class BaseCell : UITableViewCell, BaseCellType {
/// Untyped row associated to this cell.
public var baseRow: BaseRow! { return nil }
/// Block that returns the height for this cell.
public var height: (()->CGFloat)?
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
public required override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
}
/**
Function that returns the FormViewController this cell belongs to.
*/
public func formViewController() -> FormViewController? {
var responder : AnyObject? = self
while responder != nil {
if responder! is FormViewController {
return responder as? FormViewController
}
responder = responder?.next
}
return nil
}
open func setup(){}
open func update() {}
open func didSelect() {}
/**
If the cell can become first responder. By default returns false
*/
open func cellCanBecomeFirstResponder() -> Bool {
return false
}
/**
Called when the cell becomes first responder
*/
@discardableResult
open func cellBecomeFirstResponder(withDirection: Direction = .down) -> Bool {
return becomeFirstResponder()
}
/**
Called when the cell resigns first responder
*/
@discardableResult
open func cellResignFirstResponder() -> Bool {
return resignFirstResponder()
}
}
/// Generic class that represents the Eureka cells.
open class Cell<T: Equatable> : BaseCell, TypedCellType {
public typealias Value = T
/// The row associated to this cell
public weak var row : RowOf<T>!
/// Returns the navigationAccessoryView if it is defined or calls super if not.
override open var inputAccessoryView: UIView? {
if let v = formViewController()?.inputAccessoryView(for: row){
return v
}
return super.inputAccessoryView
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
required public init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
height = { UITableViewAutomaticDimension }
}
/**
Function responsible for setting up the cell at creation time.
*/
open override func setup(){
super.setup()
}
/**
Function responsible for updating the cell each time it is reloaded.
*/
open override func update(){
super.update()
textLabel?.text = row.title
textLabel?.textColor = row.isDisabled ? .gray : .black
detailTextLabel?.text = row.displayValueFor?(row.value) ?? (row as? NoValueDisplayTextConformance)?.noValueDisplayText
}
/**
Called when the cell was selected.
*/
open override func didSelect() {}
override open var canBecomeFirstResponder: Bool {
get { return false }
}
open override func becomeFirstResponder() -> Bool {
let result = super.becomeFirstResponder()
if result {
formViewController()?.beginEditing(of: self)
}
return result
}
open override func resignFirstResponder() -> Bool {
let result = super.resignFirstResponder()
if result {
formViewController()?.endEditing(of: self)
}
return result
}
/// The untyped row associated to this cell.
public override var baseRow : BaseRow! { return row }
}
|
29a3528830e32c16409dc14f8df8bf06
| 30.248408 | 126 | 0.665104 | false | false | false | false |
ddgold/Cathedral
|
refs/heads/master
|
Cathedral/Controllers/GameViewController.swift
|
apache-2.0
|
1
|
//
// GameViewController.swift
// Cathedral
//
// Created by Doug Goldstein on 1/29/19.
// Copyright © 2019 Doug Goldstein. All rights reserved.
//
import UIKit
import AVFoundation
/// A cathedral game controller.
class GameViewController: UIViewController
{
//MARK: - Properties
/// The game model
var game: Game!
/// The static sub views of the game.
private var boardView: BoardView!
private var topPoolView: PoolView!
private var bottomPoolView: PoolView!
private var messageLabel: UILabel!
private var buildButton: UIButton!
/// The light player.
private var lightPlayer: Player!
/// The dark player.
private var darkPlayer: Player!
/// The active piece.
private var activePiece: PieceView?
/// The actice pool.
private var activePool: PoolView?
/// The point of a pan gesture's start.
private var panStart: CGPoint?
/// The offset of a pan gesture into the active piece.
private var panOffset: CGPoint?
/// The rotation of the active piece before the rotation gesture.
private var rotateStart: CGFloat?
/// The piece that the long press gestures is touching.
private var pressedPiece: PieceView?
/// The point of a long press gesture's start.
private var pressStart: CGPoint?
/// The offset of a long press gesture into the pressed piece.
private var pressOffset: CGPoint?
/// The player assigned to the top pool.
private let topPoolPlayer = Owner.dark
/// The completion handler that return the game to calling controller when this controller disappears.
var completionHandler: ((Game?, Bool) -> Void)?
/// The calculate size of a tile based on controller's safe space.
var tileSize: CGFloat
{
let totalSafeHeight = view.frame.height - 180
let maxHeightSize = (totalSafeHeight - 40) / 18
let totalSafeWidth = view.frame.width
let maxWidthSize = totalSafeWidth / 12
return min(maxHeightSize, maxWidthSize)
}
//MARK: - ViewController Lifecycle
/// Initialze the controller's sub views once the controller has loaded.
override func viewDidLoad()
{
super.viewDidLoad()
navigationItem.title = "Cathedral"
// Initialize subviews
boardView = buildBoard()
topPoolView = buildPool(top: true)
bottomPoolView = buildPool(top: false)
messageLabel = buildMessageLabel()
buildButton = buildBuildButton()
// Initialize player
lightPlayer = game.playerType(for: .light).init(game: game, owner: .light)
darkPlayer = game.playerType(for: .dark).init(game: game, owner: .dark)
// Bring board view to front and set background color
self.view.bringSubviewToFront(boardView)
self.view.backgroundColor = .white
// Listen for theme changes
Theme.subscribe(self, selector: #selector(updateTheme(_:)))
updateTheme(nil)
// Start / resume Game
nextTurn()
}
/// This game controller is disappearing, return the game via the completion handler.
///
/// - Parameter animated: Whether or not the disappearing is animated.
override func viewDidDisappear(_ animated: Bool)
{
completionHandler?(game, false)
}
//MARK: - Button and Gesture Recognizer Actions
/// Handle a pan gesture accross the game board view.
///
/// - Parameter sender: The pan gesture recognizer.
@objc func handleBoardPanGesture(_ sender: UIPanGestureRecognizer)
{
if let activePiece = self.activePiece
{
switch sender.state
{
// Began dragging piece
case .began:
if activePiece.contains(point: sender.location(in: activePiece))
{
let touchLocation = sender.location(in: boardView)
panStart = activePiece.frame.origin
panOffset = CGPoint(x: touchLocation.x - panStart!.x, y: touchLocation.y - panStart!.y)
pickupActivePiece()
}
// Dragged piece
case .changed:
if let panOffset = self.panOffset
{
let boardTouchLocation = sender.location(in: boardView)
let offsetLocation = CGPoint(x: boardTouchLocation.x - panOffset.x, y: boardTouchLocation.y - panOffset.y)
activePiece.move(to: offsetLocation)
}
// Stopped dragging piece
case .ended:
if let panOffset = self.panOffset
{
let boardTouchLocation = sender.location(in: boardView)
let offsetLocation = CGPoint(x: boardTouchLocation.x - panOffset.x, y: boardTouchLocation.y - panOffset.y)
if let activePool = self.activePool
{
if (activePool == topPoolView) && (boardTouchLocation.y < 0) ||
(activePool == bottomPoolView) && (boardTouchLocation.y > boardView.frame.height)
{
activePool.addPiece(activePiece, at: boardTouchLocation)
self.activePiece = nil
self.panStart = nil
self.panOffset = nil
return
}
}
activePiece.move(to: offsetLocation)
putdownActivePiece()
self.panStart = nil
self.panOffset = nil
}
// Cancel dragging piece
case .cancelled:
if let panStart = self.panStart
{
activePiece.move(to: panStart)
putdownActivePiece()
self.panStart = nil
self.panOffset = nil
}
// Other unapplicable states
default:
break
}
}
}
/// Handle a rotation gesture on the game board view.
///
/// - Parameter sender: The rotation gesture recognizer.
@objc func handleBoardRotation(_ sender: UIRotationGestureRecognizer)
{
if let activePiece = self.activePiece
{
switch sender.state
{
// Begin Spinning Piece
case .began:
// Record starting angle
self.rotateStart = activePiece.angle
pickupActivePiece()
// Spin Piece
case .changed:
if let rotateStart = self.rotateStart
{
// Spin active piece
activePiece.rotate(to: rotateStart + sender.rotation)
}
// End Spinning Piece
case .ended:
if let rotateStart = self.rotateStart
{
// Set active piece direction then snap to 90º angle and board grid
activePiece.rotate(to: rotateStart + sender.rotation)
putdownActivePiece()
self.rotateStart = nil
}
// Cancel Spinning Piece
case .cancelled:
if let rotateStart = self.rotateStart
{
// Reset active piece rotation
activePiece.rotate(to: rotateStart)
putdownActivePiece()
self.rotateStart = nil
}
// Do nothing
default:
break
}
}
}
/// Handle a double tap gesture on the game board view.
///
/// - Parameter sender: The double tap gesture recognizer.
@objc func handleBoardDoubleTap(_ sender: UITapGestureRecognizer)
{
if let activePiece = self.activePiece
{
if activePiece.contains(point: sender.location(in: activePiece))
{
let start = activePiece.frame.origin
activePiece.rotate(to: activePiece.angle + (CGFloat.pi / 2))
activePiece.move(to: start)
putdownActivePiece()
}
}
}
/// Handle a long press on one of the pool views.
///
/// - Parameter sender: The long press gesture recognizer.
@objc func handlePoolLongPress(_ sender: UILongPressGestureRecognizer)
{
// There's already an active piece
if self.activePiece != nil
{
return
}
if let activePool = self.activePool
{
switch sender.state
{
// Began dragging piece
case .began:
let poolTouchLocation = sender.location(in: activePool)
if let (index, selectedPiece) = activePool.selectPiece(at: poolTouchLocation)
{
let boardTouchLocation = sender.location(in: boardView)
if (!canBuildPiece(selectedPiece))
{
AudioServicesPlaySystemSound(kSystemSoundID_Vibrate)
}
else
{
pressStart = activePool.convert(selectedPiece.frame, to: boardView).origin
pressOffset = CGPoint(x: boardTouchLocation.x - pressStart!.x, y: boardTouchLocation.y - pressStart!.y)
pressedPiece = selectedPiece
activePool.removePiece(at: index)
boardView.buildPiece(pressedPiece!)
pressedPiece!.frame = CGRect(origin: pressStart!, size: pressedPiece!.frame.size)
}
}
// Dragged piece
case .changed:
if let pressedPiece = self.pressedPiece, let pressOffset = self.pressOffset
{
let boardTouchLocation = sender.location(in: boardView)
let offsetLocation = CGPoint(x: boardTouchLocation.x - pressOffset.x, y: boardTouchLocation.y - pressOffset.y)
pressedPiece.move(to: offsetLocation)
}
// Stopped dragging piece
case .ended:
if let pressedPiece = self.pressedPiece, let pressOffset = self.pressOffset
{
let boardTouchLocation = sender.location(in: boardView)
let offsetLocation = CGPoint(x: boardTouchLocation.x - pressOffset.x, y: boardTouchLocation.y - pressOffset.y)
if (activePool == topPoolView) && (boardTouchLocation.y < 0) ||
(activePool == bottomPoolView) && (boardTouchLocation.y > boardView.frame.height)
{
activePool.addPiece(pressedPiece, at: boardTouchLocation)
self.pressStart = nil
self.pressOffset = nil
self.pressedPiece = nil
return
}
boardView.buildPiece(pressedPiece)
activePiece = pressedPiece
activePiece!.move(to: offsetLocation)
putdownActivePiece()
self.pressStart = nil
self.pressOffset = nil
self.pressedPiece = nil
}
// Cancel dragging piece
case .cancelled:
if let pressedPiece = self.pressedPiece
{
activePool.addPiece(pressedPiece)
self.pressStart = nil
self.pressOffset = nil
self.pressedPiece = nil
}
// Do nothing
default:
break
}
}
}
/// Handle the buildButton being pressed.
///
/// - Parameter sender: The button press sender.
@objc func buildButtonPressed(_ sender: UIButton)
{
assert(activePiece != nil, "There isn't an active piece")
// Build Piece in modal
buildPiece(activePiece!)
// Update view
activePiece!.state = .standard
activePiece = nil
nextTurn()
}
/// Rematch button has been pressed.
///
/// - Parameter sender: The button press sender.
@objc func rematchButtonPressed(_ sender: UIButton)
{
completionHandler?(game, true)
}
//MARK: - Functions
/// Builds a new board.
///
/// - Returns: The new board.
private func buildBoard() -> BoardView
{
let newBoard = BoardView(tileSize: tileSize)
view.addSubview(newBoard)
newBoard.translatesAutoresizingMaskIntoConstraints = false
newBoard.heightAnchor.constraint(equalToConstant: tileSize * 12).isActive = true
newBoard.widthAnchor.constraint(equalToConstant: tileSize * 12).isActive = true
newBoard.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
newBoard.centerYAnchor.constraint(equalTo: view.centerYAnchor, constant: 30).isActive = true
let boardPanRecognizer = UIPanGestureRecognizer(target: self, action: #selector(handleBoardPanGesture))
newBoard.addGestureRecognizer(boardPanRecognizer)
let boardDoubleTapRecognizer = UITapGestureRecognizer(target: self, action: #selector(handleBoardDoubleTap))
boardDoubleTapRecognizer.numberOfTapsRequired = 2
newBoard.addGestureRecognizer(boardDoubleTapRecognizer)
let boardRotationRecognizer = UIRotationGestureRecognizer(target: self, action: #selector(handleBoardRotation))
newBoard.addGestureRecognizer(boardRotationRecognizer)
// Build existing pieces
for piece in game.builtPieces
{
let pieceView = PieceView(piece, tileSize: tileSize)
newBoard.buildPiece(pieceView)
}
// Build claimed tiles
for claimedAddress in game.lightClaimedAddresses
{
let claimedTile = ClaimedTileView(owner: .light, address: claimedAddress, tileSize: tileSize)
newBoard.claimTile(claimedTile)
}
for claimedAddress in game.darkClaimedAddresses
{
let claimedTile = ClaimedTileView(owner: .dark, address: claimedAddress, tileSize: tileSize)
newBoard.claimTile(claimedTile)
}
return newBoard
}
/// Builds a new pool.
///
/// - Parameter top: Whether to build a top pool or a bottom pool.
/// - Returns: The new pool.
private func buildPool(top: Bool) -> PoolView
{
let owner = top ? topPoolPlayer : topPoolPlayer.opponent
let newPool = PoolView(owner: owner, buildings: game.unbuiltBuildings(for: owner), tileSize: tileSize)
view.addSubview(newPool)
newPool.translatesAutoresizingMaskIntoConstraints = false
newPool.heightAnchor.constraint(equalToConstant: (tileSize * 3) + 20).isActive = true
newPool.leftAnchor.constraint(equalTo: view.leftAnchor, constant: 0).isActive = true
newPool.rightAnchor.constraint(equalTo: view.rightAnchor, constant: 0).isActive = true
if top
{
newPool.bottomAnchor.constraint(equalTo: boardView.topAnchor, constant: 0).isActive = true
}
else
{
newPool.topAnchor.constraint(equalTo: boardView.bottomAnchor, constant: 0).isActive = true
}
let poolTapRecognizer = UILongPressGestureRecognizer(target: self, action: #selector(handlePoolLongPress))
newPool.addGestureRecognizer(poolTapRecognizer)
return newPool
}
/// Builds a new messageLabel.
///
/// - Returns: The new label.
private func buildMessageLabel() -> UILabel
{
let newLabel = UILabel(frame: CGRect(x: 0, y: 0, width: 500, height: 100))
view.addSubview(newLabel)
newLabel.text = "Place Holder"
newLabel.textAlignment = .center
newLabel.translatesAutoresizingMaskIntoConstraints = false
newLabel.heightAnchor.constraint(equalToConstant: 60).isActive = true
newLabel.leftAnchor.constraint(equalTo: view.leftAnchor, constant: 0).isActive = true
newLabel.rightAnchor.constraint(equalTo: view.rightAnchor, constant: 0).isActive = true
newLabel.bottomAnchor.constraint(equalTo: topPoolView.topAnchor, constant: 0).isActive = true
return newLabel
}
/// Builds a new buildButton.
///
/// - Returns: The new button.
private func buildBuildButton() -> UIButton
{
let newButton = UIButton(type: .system)
view.addSubview(newButton)
newButton.setTitle("Build Building", for: .normal)
newButton.translatesAutoresizingMaskIntoConstraints = false
newButton.heightAnchor.constraint(equalToConstant: 60).isActive = true
newButton.leftAnchor.constraint(equalTo: view.leftAnchor, constant: 0).isActive = true
newButton.rightAnchor.constraint(equalTo: view.rightAnchor, constant: 0).isActive = true
newButton.topAnchor.constraint(equalTo: bottomPoolView.bottomAnchor, constant: 0).isActive = true
newButton.addTarget(self, action: #selector(buildButtonPressed), for: .touchUpInside)
return newButton
}
/// Start moving the active piece.
/// - Note: There must be an active piece.
private func pickupActivePiece()
{
guard let activePiece = self.activePiece else
{
fatalError("There is no active piece")
}
buildButton.isEnabled = false
activePiece.state = .standard
}
/// Stop moving the active piece, snapping it to the board, or putting back into the active pool.
/// - Note: There must be an active piece.
private func putdownActivePiece()
{
guard let activePiece = self.activePiece else
{
fatalError("There is no active piece")
}
activePiece.snapToBoard()
// Update state
if canBuildPiece(activePiece)
{
buildButton.isEnabled = true
activePiece.state = .success
}
else
{
buildButton.isEnabled = false
activePiece.state = .failure
}
}
/// Determines if a given piece view can be built.
/// - Note: If the piece's address or direction is not set, checks if the piece can be built anywhere.
///
/// - Parameter piece: The piece view.
/// - Returns: Whether the given piece can be built.
private func canBuildPiece(_ piece: PieceView) -> Bool
{
if (piece.address == nil) || (piece.direction == nil)
{
return game!.canBuildBuilding(piece.building, for: piece.owner)
}
else
{
return game!.canBuildBuilding(piece.building, for: piece.owner, facing: piece.direction!, at: piece.address!)
}
}
/// Build a given piece view at its current position.
/// - Note: Piece must have address and direction set, and be in a valid position.
///
/// - Parameter piece: The piece view.
private func buildPiece(_ piece: PieceView)
{
assert((piece.address != nil) && (piece.direction != nil), "Must set piece's address and direciton before building it")
assert(canBuildPiece(piece), "Piece at an invalid position")
let (claimant, destroyed) = game!.buildBuilding(piece.building, for: piece.owner, facing: piece.direction!, at: piece.address!)
for address in claimant
{
let claimedTile = ClaimedTileView(owner: piece.owner, address: address, tileSize: tileSize)
boardView.claimTile(claimedTile)
}
for piece in destroyed
{
let pieceView = boardView.destroyPiece(piece)
// If Cathedral piece, remove from superviews, else return to pool
switch piece.owner
{
case .church:
pieceView.removeFromSuperview()
default:
poolForOwner(piece.owner).addPiece(pieceView)
}
}
}
/// Get the correct pool for a given player owner.
///
/// - Parameter owner: The player owner, must be light or dark.
/// - Returns: The pool for the given owner.
private func poolForOwner(_ owner: Owner) -> PoolView
{
assert(!owner.isChurch, "The church does not have pool")
if (owner == topPoolPlayer)
{
return topPoolView
}
else
{
return bottomPoolView
}
}
/// Move on to the next turn.
private func nextTurn()
{
// Turn off build button
buildButton.isEnabled = false
// Set message and potential active piece (for Cathedral turn) or pool (for player turn)
if let nextOwner = game!.nextTurn
{
if (nextOwner == .church)
{
let player = lightPlayer
if let computerPlayer = player as? Computer
{
let piece = computerPlayer.nextMove()
let pieceView = PieceView(piece, tileSize: tileSize)
boardView.buildPiece(pieceView)
buildPiece(pieceView)
self.nextTurn()
}
else
{
messageLabel.text = "Build the Cathedral"
activePool = nil
activePiece = PieceView(owner: .church, building: .cathedral, tileSize: tileSize)
activePiece!.move(to: CGPoint(x: tileSize * 4, y: tileSize * 4))
putdownActivePiece()
boardView.buildPiece(activePiece!)
}
}
else
{
let pool = poolForOwner(nextOwner)
let player = (nextOwner == .light) ? lightPlayer! : darkPlayer!
if let computerPlayer = player as? Computer
{
let piece = computerPlayer.nextMove()
pool.removePiece(piece.building)
let pieceView = PieceView(piece, tileSize: tileSize)
boardView.buildPiece(pieceView)
buildPiece(pieceView)
self.nextTurn()
}
else
{
messageLabel.text = "It's \(player.name)'s turn to build."
activePool = poolForOwner(nextOwner)
}
}
}
else
{
let (winner, _) = game!.calculateWinner()!
if let winner = winner
{
messageLabel.text = "Game is over, \(winner) is the winner!"
}
else
{
messageLabel.text = "Game is over, it was a tie."
}
let rematchButton = UIBarButtonItem(title: "Rematch", style: .plain, target: self, action: #selector(rematchButtonPressed))
self.navigationItem.rightBarButtonItem = rematchButton
game = nil
activePool = nil
}
// Update which building in pools can be built
for targetPool in [topPoolView!, bottomPoolView!]
{
if (targetPool == activePool)
{
enablePool(targetPool)
}
else
{
disablePool(targetPool)
}
}
}
/// Enable a given pool, updating highlighting.
///
/// - Parameter poolView: The pool view.
private func enablePool(_ poolView: PoolView)
{
for case let piece as PieceView in poolView.subviews
{
if (canBuildPiece(piece))
{
piece.state = .standard
}
else
{
piece.state = .failure
}
}
}
/// Disable a given pool, darkening all pieces.
///
/// - Parameter poolView: The pool view.
private func disablePool(_ poolView: PoolView)
{
for case let piece as PieceView in poolView.subviews
{
piece.state = .disabled
}
}
/// Updates the view to the current theme.
///
/// - Parameters:
/// - notification: Unused.
@objc private func updateTheme(_: Notification?)
{
let theme = Theme.activeTheme
messageLabel.textColor = theme.textColor
buildButton.tintColor = theme.tintColor
view.backgroundColor = theme.backgroundColor
}
}
|
92afc733e14692d05f2467d63655a649
| 34.327891 | 135 | 0.541362 | false | false | false | false |
esttorhe/RxSwift
|
refs/heads/feature/swift2.0
|
RxCocoa/RxCocoa/Common/Observables/Implementations/ControlTarget.swift
|
mit
|
3
|
//
// ControlTarget.swift
// RxCocoa
//
// Created by Krunoslav Zaher on 2/21/15.
// Copyright (c) 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
import RxSwift
#if os(iOS)
import UIKit
typealias Control = UIKit.UIControl
typealias ControlEvents = UIKit.UIControlEvents
#elseif os(OSX)
import Cocoa
typealias Control = Cocoa.NSControl
#endif
// This should be only used from `MainScheduler`
class ControlTarget: RxTarget {
typealias Callback = (Control) -> Void
let selector: Selector = "eventHandler:"
unowned let control: Control
#if os(iOS)
let controlEvents: UIControlEvents
#endif
var callback: Callback?
#if os(iOS)
init(control: Control, controlEvents: UIControlEvents, callback: Callback) {
MainScheduler.ensureExecutingOnScheduler()
self.control = control
self.controlEvents = controlEvents
self.callback = callback
super.init()
control.addTarget(self, action: selector, forControlEvents: controlEvents)
let method = self.methodForSelector(selector)
if method == nil {
rxFatalError("Can't find method")
}
}
#elseif os(OSX)
init(control: Control, callback: Callback) {
MainScheduler.ensureExecutingOnScheduler()
self.control = control
self.callback = callback
super.init()
control.target = self
control.action = selector
let method = self.methodForSelector(selector)
if method == nil {
rxFatalError("Can't find method")
}
}
#endif
func eventHandler(sender: Control!) {
if let callback = self.callback {
callback(control)
}
}
override func dispose() {
super.dispose()
#if os(iOS)
self.control.removeTarget(self, action: self.selector, forControlEvents: self.controlEvents)
#elseif os(OSX)
self.control.target = nil
self.control.action = nil
#endif
self.callback = nil
}
}
|
b63f427505adcf688c3c25834bd3ab6c
| 23.511628 | 100 | 0.622686 | false | false | false | false |
amraboelela/swift
|
refs/heads/master
|
test/attr/attr_native_dynamic.swift
|
apache-2.0
|
12
|
// RUN: %target-swift-frontend -swift-version 5 -typecheck -dump-ast %s | %FileCheck %s
struct Strukt {
// CHECK: (struct_decl {{.*}} "Strukt"
// CHECK: (var_decl {{.*}} "dynamicStorageOnlyVar" type='Int' interface type='Int' access=internal dynamic readImpl=stored writeImpl=stored readWriteImpl=stored
// CHECK: (accessor_decl {{.*}} access=internal dynamic get_for=dynamicStorageOnlyVar
// CHECK: (accessor_decl {{.*}} access=internal dynamic set_for=dynamicStorageOnlyVar
// CHECK: (accessor_decl {{.*}} access=internal _modify_for=dynamicStorageOnlyVar
dynamic var dynamicStorageOnlyVar : Int = 0
// CHECK: (var_decl {{.*}} "computedVar" type='Int' interface type='Int' access=internal dynamic readImpl=getter immutable
// CHECK: (accessor_decl {{.*}} access=internal dynamic get_for=computedVar
dynamic var computedVar : Int {
return 0
}
// CHECK: (var_decl {{.*}} "computedVar2" type='Int' interface type='Int' access=internal dynamic readImpl=getter immutable
// CHECK: (accessor_decl {{.*}} access=internal dynamic get_for=computedVar2
dynamic var computedVar2 : Int {
get {
return 0
}
}
// CHECK: (var_decl {{.*}} "computedVarGetterSetter" type='Int' interface type='Int' access=internal dynamic readImpl=getter writeImpl=setter readWriteImpl=materialize_to_temporary
// CHECK: (accessor_decl {{.*}} access=internal dynamic get_for=computedVarGetterSetter
// CHECK: (accessor_decl {{.*}} access=internal dynamic set_for=computedVarGetterSetter
// CHECK: (accessor_decl {{.*}} access=internal _modify_for=computedVarGetterSetter
dynamic var computedVarGetterSetter : Int {
get {
return 0
}
set {
}
}
// CHECK: (var_decl {{.*}} "computedVarGetterModify" type='Int' interface type='Int' access=internal dynamic readImpl=getter writeImpl=modify_coroutine readWriteImpl=modify_coroutine
// CHECK: (accessor_decl {{.*}} access=internal dynamic get_for=computedVarGetterModify
// CHECK: (accessor_decl {{.*}} access=internal dynamic _modify_for=computedVarGetterModify
// CHECK: (accessor_decl {{.*}} access=internal set_for=computedVarGetterModify
dynamic var computedVarGetterModify : Int {
get {
return 0
}
_modify {
}
}
// CHECK: (var_decl {{.*}} "computedVarReadSet" type='Int' interface type='Int' access=internal dynamic readImpl=read_coroutine writeImpl=setter readWriteImpl=materialize_to_temporary
// CHECK: (accessor_decl {{.*}} access=internal dynamic _read_for=computedVarReadSet
// CHECK: (accessor_decl {{.*}} access=internal dynamic set_for=computedVarReadSet
// CHECK: (accessor_decl {{.*}} access=internal get_for=computedVarReadSet
// CHECK: (accessor_decl {{.*}} access=internal _modify_for=computedVarReadSet
dynamic var computedVarReadSet : Int {
_read {
}
set {
}
}
// CHECK: (var_decl {{.*}} "computedVarReadModify" type='Int' interface type='Int' access=internal dynamic readImpl=read_coroutine writeImpl=modify_coroutine readWriteImpl=modify_coroutine
// CHECK: (accessor_decl {{.*}} access=internal dynamic _read_for=computedVarReadModify
// CHECK: (accessor_decl {{.*}} access=internal dynamic _modify_for=computedVarReadModify
// CHECK: (accessor_decl {{.*}} access=internal get_for=computedVarReadModify
// CHECK: (accessor_decl {{.*}} access=internal set_for=computedVarReadModify
dynamic var computedVarReadModify : Int {
_read {
}
_modify {
}
}
// CHECK: (var_decl {{.*}} "storedWithObserver" type='Int' interface type='Int' access=internal dynamic readImpl=stored writeImpl=stored_with_observers readWriteImpl=materialize_to_temporary
// CHECK: (accessor_decl {{.*}}access=private dynamic didSet_for=storedWithObserver
// CHECK: (accessor_decl {{.*}}access=internal dynamic get_for=storedWithObserver
// CHECK: (accessor_decl {{.*}}access=internal set_for=storedWithObserver
// CHECK: (accessor_decl {{.*}}access=internal _modify_for=storedWithObserver
dynamic var storedWithObserver : Int {
didSet {
}
}
// CHECK: (func_decl {{.*}} access=internal dynamic
dynamic func aMethod(arg: Int) -> Int {
return arg
}
// CHECK: (subscript_decl {{.*}} "subscript(_:)" {{.*}} access=internal dynamic readImpl=getter writeImpl=setter readWriteImpl=materialize_to_temporary
// CHECK: (accessor_decl {{.*}} access=internal dynamic get_for=subscript(_:)
// CHECK: (accessor_decl {{.*}} access=internal dynamic set_for=subscript(_:)
// CHECK: (accessor_decl {{.*}} access=internal _modify_for=subscript(_:)
dynamic subscript(_ index: Int) -> Int {
get {
return 1
}
set {
}
}
// CHECK: (subscript_decl {{.*}} "subscript(_:)" {{.*}} access=internal dynamic readImpl=getter writeImpl=modify_coroutine readWriteImpl=modify_coroutine
// CHECK: (accessor_decl {{.*}} access=internal dynamic get_for=subscript(_:)
// CHECK: (accessor_decl {{.*}} access=internal dynamic _modify_for=subscript(_:)
// CHECK: (accessor_decl {{.*}} access=internal set_for=subscript(_:)
dynamic subscript(_ index: Float) -> Int {
get {
return 1
}
_modify {
}
}
// CHECK: (subscript_decl {{.*}} "subscript(_:)" {{.*}} access=internal dynamic readImpl=read_coroutine writeImpl=modify_coroutine readWriteImpl=modify_coroutine
// CHECK: (accessor_decl {{.*}} access=internal dynamic _read_for=subscript(_:)
// CHECK: (accessor_decl {{.*}} access=internal dynamic _modify_for=subscript(_:)
// CHECK: (accessor_decl {{.*}} access=internal get_for=subscript(_:)
// CHECK: (accessor_decl {{.*}} access=internal set_for=subscript(_:)
dynamic subscript(_ index: Double) -> Int {
_read {
}
_modify {
}
}
// CHECK: (subscript_decl {{.*}} "subscript(_:)" {{.*}} access=internal dynamic readImpl=read_coroutine writeImpl=setter readWriteImpl=materialize_to_temporary
// CHECK: (accessor_decl {{.*}} access=internal dynamic _read_for=subscript(_:)
// CHECK: (accessor_decl {{.*}} access=internal dynamic set_for=subscript(_:)
// CHECK: (accessor_decl {{.*}} access=internal get_for=subscript(_:)
// CHECK: (accessor_decl {{.*}} access=internal _modify_for=subscript(_:)
dynamic subscript(_ index: Strukt) -> Int {
_read {
}
set {
}
}
}
class Klass {
// CHECK: (class_decl {{.*}} "Klass"
// CHECK: (var_decl {{.*}} "dynamicStorageOnlyVar" type='Int' interface type='Int' access=internal dynamic readImpl=stored writeImpl=stored readWriteImpl=stored
// CHECK: (accessor_decl {{.*}} access=internal dynamic get_for=dynamicStorageOnlyVar
// CHECK: (accessor_decl {{.*}} access=internal dynamic set_for=dynamicStorageOnlyVar
// CHECK: (accessor_decl {{.*}} access=internal _modify_for=dynamicStorageOnlyVar
dynamic var dynamicStorageOnlyVar : Int = 0
// CHECK: (var_decl {{.*}} "computedVar" type='Int' interface type='Int' access=internal dynamic readImpl=getter immutable
// CHECK: (accessor_decl {{.*}} access=internal dynamic get_for=computedVar
dynamic var computedVar : Int {
return 0
}
// CHECK: (var_decl {{.*}} "computedVar2" type='Int' interface type='Int' access=internal dynamic readImpl=getter immutable
// CHECK: (accessor_decl {{.*}} access=internal dynamic get_for=computedVar2
dynamic var computedVar2 : Int {
get {
return 0
}
}
// CHECK: (var_decl {{.*}} "computedVarGetterSetter" type='Int' interface type='Int' access=internal dynamic readImpl=getter writeImpl=setter readWriteImpl=materialize_to_temporary
// CHECK: (accessor_decl {{.*}} access=internal dynamic get_for=computedVarGetterSetter
// CHECK: (accessor_decl {{.*}} access=internal dynamic set_for=computedVarGetterSetter
// CHECK: (accessor_decl {{.*}} access=internal _modify_for=computedVarGetterSetter
dynamic var computedVarGetterSetter : Int {
get {
return 0
}
set {
}
}
// CHECK: (var_decl {{.*}} "computedVarGetterModify" type='Int' interface type='Int' access=internal dynamic readImpl=getter writeImpl=modify_coroutine readWriteImpl=modify_coroutine
// CHECK: (accessor_decl {{.*}} access=internal dynamic get_for=computedVarGetterModify
// CHECK: (accessor_decl {{.*}} access=internal dynamic _modify_for=computedVarGetterModify
// CHECK: (accessor_decl {{.*}} access=internal set_for=computedVarGetterModify
dynamic var computedVarGetterModify : Int {
get {
return 0
}
_modify {
}
}
// CHECK: (var_decl {{.*}} "computedVarReadSet" type='Int' interface type='Int' access=internal dynamic readImpl=read_coroutine writeImpl=setter readWriteImpl=materialize_to_temporary
// CHECK: (accessor_decl {{.*}} access=internal dynamic _read_for=computedVarReadSet
// CHECK: (accessor_decl {{.*}} access=internal dynamic set_for=computedVarReadSet
// CHECK: (accessor_decl {{.*}} access=internal get_for=computedVarReadSet
// CHECK: (accessor_decl {{.*}} access=internal _modify_for=computedVarReadSet
dynamic var computedVarReadSet : Int {
_read {
}
set {
}
}
// CHECK: (var_decl {{.*}} "computedVarReadModify" type='Int' interface type='Int' access=internal dynamic readImpl=read_coroutine writeImpl=modify_coroutine readWriteImpl=modify_coroutine
// CHECK: (accessor_decl {{.*}} access=internal dynamic _read_for=computedVarReadModify
// CHECK: (accessor_decl {{.*}} access=internal dynamic _modify_for=computedVarReadModify
// CHECK: (accessor_decl {{.*}} access=internal get_for=computedVarReadModify
// CHECK: (accessor_decl {{.*}} access=internal set_for=computedVarReadModify
dynamic var computedVarReadModify : Int {
_read {
}
_modify {
}
}
// CHECK: (func_decl {{.*}} "aMethod(arg:)" {{.*}} access=internal dynamic
dynamic func aMethod(arg: Int) -> Int {
return arg
}
// CHECK-NOT: (func_decl {{.*}} "anotherMethod()" {{.*}} access=internal{{.*}} dynamic
func anotherMethod() -> Int {
return 3
}
// CHECK: (subscript_decl {{.*}} "subscript(_:)" {{.*}} access=internal dynamic readImpl=addressor writeImpl=mutable_addressor readWriteImpl=mutable_addressor
// CHECK: (accessor_decl {{.*}} access=internal dynamic unsafeAddress_for=subscript(_:)
// CHECK: (accessor_decl {{.*}} access=internal dynamic unsafeMutableAddress_for=subscript(_:)
// CHECK: (accessor_decl {{.*}} access=internal get_for=subscript(_:)
// CHECK: (accessor_decl {{.*}} access=internal set_for=subscript(_:)
dynamic subscript(_ index: Int) -> Int {
unsafeAddress {
fatalError()
}
unsafeMutableAddress {
fatalError()
}
}
// CHECK: (subscript_decl {{.*}} "subscript(_:)" {{.*}} access=internal dynamic readImpl=getter writeImpl=mutable_addressor readWriteImpl=mutable_addressor
// CHECK: (accessor_decl {{.*}} access=internal dynamic get_for=subscript(_:)
// CHECK: (accessor_decl {{.*}} access=internal dynamic unsafeMutableAddress_for=subscript(_:)
// CHECK: (accessor_decl {{.*}} access=internal set_for=subscript(_:)
// CHECK: (accessor_decl {{.*}} access=internal _modify_for=subscript(_:)
dynamic subscript(_ index: Float) -> Int {
get {
return 1
}
unsafeMutableAddress {
fatalError()
}
}
// CHECK: (subscript_decl {{.*}} "subscript(_:)" {{.*}} access=internal dynamic readImpl=read_coroutine writeImpl=mutable_addressor readWriteImpl=mutable_addressor
// CHECK: (accessor_decl {{.*}} access=internal dynamic _read_for=subscript(_:)
// CHECK: (accessor_decl {{.*}} access=internal dynamic unsafeMutableAddress_for=subscript(_:)
// CHECK: (accessor_decl {{.*}} access=internal get_for=subscript(_:)
// CHECK: (accessor_decl {{.*}} access=internal set_for=subscript(_:)
// CHECK: (accessor_decl {{.*}} access=internal _modify_for=subscript(_:)
dynamic subscript(_ index: Double) -> Int {
_read {
}
unsafeMutableAddress {
fatalError()
}
}
// CHECK: (subscript_decl {{.*}} "subscript(_:)" {{.*}} access=internal dynamic readImpl=addressor writeImpl=setter readWriteImpl=materialize_to_temporary
// CHECK: (accessor_decl {{.*}} access=internal dynamic unsafeAddress_for=subscript(_:)
// CHECK: (accessor_decl {{.*}} access=internal dynamic set_for=subscript(_:)
// CHECK: (accessor_decl {{.*}} access=internal get_for=subscript(_:)
// CHECK: (accessor_decl {{.*}} access=internal _modify_for=subscript(_:)
dynamic subscript(_ index: Int8) -> Int {
unsafeAddress {
fatalError()
}
set {
}
}
// CHECK: (subscript_decl {{.*}} "subscript(_:)" {{.*}} access=internal dynamic readImpl=addressor writeImpl=modify_coroutine readWriteImpl=modify_coroutine
// CHECK: (accessor_decl {{.*}} access=internal dynamic unsafeAddress_for=subscript(_:)
// CHECK: (accessor_decl {{.*}} access=internal dynamic _modify_for=subscript(_:)
// CHECK: (accessor_decl {{.*}} access=internal get_for=subscript(_:)
// CHECK: (accessor_decl {{.*}} access=internal set_for=subscript(_:)
dynamic subscript(_ index: Int16) -> Int {
unsafeAddress {
fatalError()
}
_modify {
}
}
}
class SubKlass : Klass {
// CHECK: (class_decl {{.*}} "SubKlass"
// CHECK: (func_decl {{.*}} "aMethod(arg:)" interface type='(SubKlass) -> (Int) -> Int' access=internal {{.*}} dynamic
override dynamic func aMethod(arg: Int) -> Int {
return 23
}
// CHECK: (func_decl {{.*}} "anotherMethod()" interface type='(SubKlass) -> () -> Int' access=internal {{.*}} dynamic
override dynamic func anotherMethod() -> Int {
return 23
}
}
|
932af1cfdeaca008cbdea85f27e25f83
| 44.37037 | 192 | 0.678813 | false | false | false | false |
objecthub/swift-lispkit
|
refs/heads/master
|
Sources/LispKit/Base/MethodProfiler.swift
|
apache-2.0
|
1
|
//
// MethodProfiler.swift
// LispKit
//
// Created by Matthias Zenger on 01/01/2022.
// Copyright © 2022 ObjectHub. 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
public final class MethodProfiler {
let className: String
var open: [Double] = []
var stats: [String : (Int, Double)] = [:]
init(_ className: String) {
self.className = className
}
func enter() {
open.append(Timer.absoluteTimeInSec)
}
func exit(_ name: String) {
let time = Timer.absoluteTimeInSec - open.last!
open.removeLast()
if let (count, average) = stats[name] {
stats[name] = (count + 1, (average * Double(count) + time)/Double(count + 1))
} else {
stats[name] = (1, time)
}
}
public func printStats() {
Swift.print("==== \(self.className) ================")
for (name, (count, average)) in self.stats {
Swift.print("\(name),\(count),\(average),\(average * Double(count))")
}
}
}
|
aed9ecb7798e9b25775b8c92d3712e7d
| 28.057692 | 83 | 0.645268 | false | false | false | false |
ZeldaIV/TDC2015-FP
|
refs/heads/master
|
Demo 2/Sequences/Pods/RxSwift/RxSwift/Observables/Implementations/Zip+CollectionType.swift
|
gpl-3.0
|
28
|
//
// Zip+CollectionType.swift
// Rx
//
// Created by Krunoslav Zaher on 8/30/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
class ZipCollectionTypeSink<C: CollectionType, R, O: ObserverType where C.Generator.Element : ObservableType, O.E == R> : Sink<O> {
typealias Parent = ZipCollectionType<C, R>
typealias SourceElement = C.Generator.Element.E
let parent: Parent
let lock = NSRecursiveLock()
// state
var numberOfValues = 0
var values: [Queue<SourceElement>]
var isDone: [Bool]
var numberOfDone = 0
var subscriptions: [SingleAssignmentDisposable]
init(parent: Parent, observer: O, cancel: Disposable) {
self.parent = parent
self.values = [Queue<SourceElement>](count: parent.count, repeatedValue: Queue(capacity: 4))
self.isDone = [Bool](count: parent.count, repeatedValue: false)
self.subscriptions = Array<SingleAssignmentDisposable>()
self.subscriptions.reserveCapacity(parent.count)
for _ in 0 ..< parent.count {
self.subscriptions.append(SingleAssignmentDisposable())
}
super.init(observer: observer, cancel: cancel)
}
func on(event: Event<SourceElement>, atIndex: Int) {
lock.performLocked {
switch event {
case .Next(let element):
values[atIndex].enqueue(element)
if values[atIndex].count == 1 {
numberOfValues++
}
if numberOfValues < parent.count {
let numberOfOthersThatAreDone = self.numberOfDone - (isDone[atIndex] ? 1 : 0)
if numberOfOthersThatAreDone == self.parent.count - 1 {
self.observer?.on(.Completed)
self.dispose()
}
return
}
do {
var arguments = [SourceElement]()
arguments.reserveCapacity(parent.count)
// recalculate number of values
numberOfValues = 0
for i in 0 ..< values.count {
arguments.append(values[i].dequeue())
if values[i].count > 0 {
numberOfValues++
}
}
let result = try parent.resultSelector(arguments)
self.observer?.on(.Next(result))
}
catch let error {
self.observer?.on(.Error(error))
self.dispose()
}
case .Error(let error):
self.observer?.on(.Error(error))
self.dispose()
case .Completed:
if isDone[atIndex] {
return
}
isDone[atIndex] = true
numberOfDone++
if numberOfDone == self.parent.count {
self.observer?.on(.Completed)
self.dispose()
}
else {
self.subscriptions[atIndex].dispose()
}
}
}
}
func run() -> Disposable {
var j = 0
for i in parent.sources.startIndex ..< parent.sources.endIndex {
let index = j
self.subscriptions[j].disposable = self.parent.sources[i].subscribeSafe(ObserverOf { event in
self.on(event, atIndex: index)
})
j++
}
return CompositeDisposable(disposables: self.subscriptions.map { $0 })
}
}
class ZipCollectionType<C: CollectionType, R where C.Generator.Element : ObservableType> : Producer<R> {
typealias ResultSelector = [C.Generator.Element.E] throws -> R
let sources: C
let resultSelector: ResultSelector
let count: Int
init(sources: C, resultSelector: ResultSelector) {
self.sources = sources
self.resultSelector = resultSelector
self.count = Int(self.sources.count.toIntMax())
}
override func run<O : ObserverType where O.E == R>(observer: O, cancel: Disposable, setSink: (Disposable) -> Void) -> Disposable {
let sink = ZipCollectionTypeSink(parent: self, observer: observer, cancel: cancel)
setSink(sink)
return sink.run()
}
}
|
fea3263058e268420312460047837261
| 33.22963 | 134 | 0.511905 | false | false | false | false |
swernimo/iOS
|
refs/heads/master
|
VirtualTourist/VirtualTourist/Photo.swift
|
mit
|
1
|
//
// Photo.swift
// VirtualTourist
//
// Created by Sean Wernimont on 2/27/16.
// Copyright © 2016 Just One Guy. All rights reserved.
//
import Foundation
import CoreData
@objc(Photo)
class Photo : NSManagedObject {
@NSManaged var imageData: NSData?
@NSManaged var filePath: String?
@NSManaged var pin: Pin
@NSManaged var id: String
init(pin: Pin, image: NSData, path: String, context: NSManagedObjectContext){
let entity = NSEntityDescription.entityForName("Photo", inManagedObjectContext: context)!
super.init(entity: entity, insertIntoManagedObjectContext: context)
self.pin = pin
imageData = image
id = NSUUID().UUIDString
filePath = path
}
override init(entity: NSEntityDescription, insertIntoManagedObjectContext context: NSManagedObjectContext?) {
super.init(entity: entity, insertIntoManagedObjectContext: context)
}
}
|
e62d68d3f5bbc86948d2f02d1608b3c8
| 27.606061 | 113 | 0.688229 | false | false | false | false |
grzegorzleszek/algorithms-swift
|
refs/heads/master
|
Sources/Graph+TravelingSalesman.swift
|
mit
|
1
|
//
// Graph+TravelingSalesman.swift
//
// Copyright © 2018 Grzegorz.Leszek. All rights reserved.
//
// Permission is hereby granted, free of charge, to first 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 WpathANTY OF first KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WpathANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR first CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
struct Path {
var vertices: [Vertex]
var weight: Int
}
extension Graph {
/// Traveling Salesman
/// Initialize: T [ S ,v ] - the shortest path, which:
/// * Starts in vertex 1
/// * Visits each vertex from S – {v}
/// * End in v
/// 1. T [ {v},v ] = w ( 1,v )
/// 2. T[S,v] = min( T [ S – {v}, x ] + w ( x,v )), where x∈S - {v}
/// 3. to find cycle we need to T[V(G)-{1},v] + w(v,1)
func tsp(start: Vertex, goal: Vertex? = nil, graph: Graph) -> Path {
if graph._vertices.count <= 1 {
return Path(vertices: graph._vertices, weight: 0)
}
let singlePaths = graph._edges.map { Path(vertices: [$0.left, $0.right], weight: $0.weight) }
var bestPaths = makeBestPath(from: singlePaths, start: start)
for _ in 0..<graph._vertices.count
{
for i in 0..<bestPaths.count
{
addSinglePath(graph, &bestPaths, i)
}
}
let size = bestPaths.map { $0.vertices.count }.max()
let filteredPaths = bestPaths.filter { $0.vertices.count == size }
guard let anyPath = filteredPaths.first else { return Path(vertices: [], weight: 0) }
var theBestPath: Path = anyPath
for path in filteredPaths
{
if (theBestPath.weight >= path.weight)
{
theBestPath = path
}
}
return theBestPath
}
func addSinglePath(_ graph: Graph, _ bestPaths: inout [Path], _ index: Int) {
guard let lastVertex = bestPaths[index].vertices.last else { return }
var _neighbors = graph.neighborsOf(lastVertex, withGiven: graph._edges)
for vertex in bestPaths[index].vertices {
if contain(vertex, onArray: _neighbors) {
_neighbors = _neighbors.filter { $0.id != vertex.id }
}
}
for vertex in _neighbors {
var path = bestPaths[index]
let pathWeight = graph.findEdge(vertex, (path.vertices.last ?? vertex))?.weight ?? 0
path.vertices.append(vertex)
path.weight = path.weight + pathWeight
bestPaths.append(path)
}
}
func makeBestPath(from singlePaths: [Path], start: Vertex) -> [Path] {
return singlePaths.filter { (path) -> Bool in
return path.vertices.contains { (vertex) -> Bool in
return vertex == start
}
}
}
}
|
7eea7f82ea76eee0db488900c9cf3ccc
| 37.322917 | 101 | 0.609948 | false | false | false | false |
studyYF/Weibo-swift-
|
refs/heads/master
|
WeiBo/WeiBo/CLasses/Home(首页)/HomeModel/StatusViewModel.swift
|
apache-2.0
|
1
|
//
// StatusViewModel.swift
// Weibo
//
// Created by YF on 16/10/5.
// Copyright © 2016年 YF. All rights reserved.
//
import UIKit
//MARK: - 把所有的要显示的属性都放在这里处理
class StatusViewModel: NSObject {
//MARK: - 定义属性
var status : StatusModel?
///来源text
var sourceText : String?
///创建时间text
var createAtText : String?
///用户类型图片
var verified_image : UIImage?
///会员等级图片
var mbrank_image : UIImage?
///用户头像地址
var profileURL : NSURL?
///微博配图的url数组
var pictureURLs : [NSURL] = [NSURL]()
//MARK: - 自定义构造函数
init(status : StatusModel) {
super.init()
self.status = status
handleViewModel(status)
}
}
//MARK: - 处理模型数据
extension StatusViewModel {
private func handleViewModel(status : StatusModel) {
//1.处理微博创建时间
if let create_at = status.created_at {
createAtText = NSDate.createDateString(create_at)
}
//2.处理微博来源
//where 表示两个条件都需要满足
if let source = status.source where source != "" {
let startIndex = (source as NSString).rangeOfString(">").location + 1
let length = (source as NSString).rangeOfString("</").location - startIndex
sourceText = (source as NSString).substringWithRange(NSRange(location: startIndex, length: length))
}
//3.处理认证图标
let verified_type = status.user?.verified_type ?? -1
switch verified_type {
case 0 :
verified_image = UIImage(named: "avatar_vip")
case 2,3,5 :
verified_image = UIImage(named: "avatar_enterprise_vip")
case 220 :
verified_image = UIImage(named: "avatar_grassroot")
default :
verified_image = nil
}
//4.处理用户等级图标
let mbrank = status.user?.mbrank ?? 0
if mbrank > 0 && mbrank <= 6 {
mbrank_image = UIImage(named: "common_icon_membership_level\(mbrank)")
}
//5.处理用户头像url
let profile_image_url = status.user?.profile_image_url ?? ""
profileURL = NSURL(string: profile_image_url)
//6.处理微博配图url
let picURls = status.pic_urls!.count != 0 ? status.pic_urls : status.retweeted_status?.pic_urls
if let pic_urls = picURls {
for picDict in pic_urls {
guard let urlString = picDict["thumbnail_pic"] else {
continue
}
pictureURLs.append((NSURL(string: urlString))!)
}
}
}
}
|
f84458a841ae96a40dfd0e565b898a09
| 29.083333 | 111 | 0.566284 | false | false | false | false |
KristopherGBaker/RubiParser
|
refs/heads/master
|
RubiParserTests/RubiParserTestCase.swift
|
mit
|
1
|
//
// RubiParserTestCase.swift
// RubiParser
//
// Created by Kris Baker on 12/18/16.
// Copyright © 2016 Empyreal Night, LLC. All rights reserved.
//
@testable import RubiParser
import XCTest
/// Tests for RubiParser.
class RubiParserTestCase: XCTestCase {
/// The parser.
internal var parser: RubiParser!
/// The document.
internal var doc: RubiDocument!
/// Initialize parser.
override func setUp() {
super.setUp()
parser = RubiScannerParser()
}
/// Tests parse for the EasyNews1 example.
func testParse() {
guard let html = loadExample(name: "EasyNews1") else {
XCTFail("unable to load EasyNews1 example")
return
}
doc = parser.parse(html)
assertEasyNews1()
}
// Tests parse for the EasyNews2 example.
func testParseWithImage() {
guard let html = loadExample(name: "EasyNews2") else {
XCTFail("unable to load EasyNews2 example")
return
}
doc = parser.parse(html)
assertEasyNews2()
print(doc.kanjiString)
print(doc.kanaString)
doc.items.forEach { printNode(node: $0) }
func printNode(node: RubiNode) {
if case RubiNode.ruby(let kanji, let reading) = node {
print("Kanji: \(kanji) \(reading)")
}
else if case RubiNode.word(let text) = node {
print(text)
}
else if case RubiNode.text(let text) = node {
print(text)
}
else if case RubiNode.image(let url) = node {
print(url)
}
else if case RubiNode.paragraph(let children) = node {
children.forEach { printNode(node: $0) }
}
}
}
/// Asserts the parsed EasyNews1 document is correct.
func assertEasyNews1() {
XCTAssertEqual(doc.items.count, 6)
if case RubiNode.paragraph(children: let children) = doc.items[0] {
XCTAssert(children.count == 33)
if case RubiNode.text(text: let text) = children[0] {
XCTAssert(text == "アメリカ")
} else {
XCTFail("unexpected items")
}
} else {
XCTFail("unexpected items")
}
if case RubiNode.paragraph(children: let children) = doc.items[3] {
XCTAssert(children.count == 25)
if case RubiNode.ruby(kanji: let kanji, reading: let reading) = children[0] {
XCTAssert(kanji == "東京都")
XCTAssert(reading == "とうきょうと")
} else {
XCTFail("unexpected items")
}
} else {
XCTFail("unexpected items")
}
}
func assertEasyNews2() {
XCTAssert(doc.items.count == 4)
if case RubiNode.image(url: let url) = doc.items[0] {
XCTAssert(url == URL(string: "http://www3.nhk.or.jp/news/easy/manu_still/baby.jpg"))
}
}
}
|
cfe6a772ca66c72f0d4f57323fc85ad2
| 26.709091 | 96 | 0.538058 | false | true | false | false |
kaizeiyimi/Phantom
|
refs/heads/master
|
Phantom/codes/Tracker.swift
|
mit
|
1
|
//
// Tracker.swift
// Phantom
//
// Created by kaizei on 16/1/26.
// Copyright © 2016年 kaizei. All rights reserved.
//
import Foundation
// MARK: - Task Tracking
final public class TrackingToken: Hashable {
public var hashValue: Int {
return "\(unsafeAddressOf(self))".hashValue
}
}
public func ==(lhs: TrackingToken, rhs: TrackingToken) -> Bool {
return lhs === rhs
}
// MARK: - TaskTracker.
final public class TaskTracker {
struct TrackingItem {
let queue: dispatch_queue_t?
let progress: (ProgressInfo -> Void)?
let decoderCompletion: (decoder: (NSURL, NSData) -> DecodeResult<Any>, completion: Result<Any> -> Void)?
}
public private(set) var task: Task!
public private(set) var progressInfo: ProgressInfo?
public private(set) var result: Result<NSData>?
private var lock = OS_SPINLOCK_INIT
private var trackings: [TrackingToken: TrackingItem] = [:]
private let trackerQueue: dispatch_queue_t
init(trackerQueue: dispatch_queue_t? = nil) {
self.trackerQueue = trackerQueue ?? dispatch_queue_create("Phantom.TaskTracker.queue", DISPATCH_QUEUE_CONCURRENT)
}
public static func track(url: NSURL, trackerQueue: dispatch_queue_t? = nil, downloader: Downloader = sharedDownloader, cache: DownloaderCache? = nil) -> TaskTracker {
let tracker = TaskTracker()
tracker.task = downloader.download(url, cache: cache, queue: tracker.trackerQueue,
progress: tracker.notifyProgress, decoder: tracker.decoder, completion: tracker.notifyCompletion)
return tracker
}
// MARK: tracking
/// `queue` default to trackerQueue.
public func addTracking(queue: dispatch_queue_t? = nil, progress: (ProgressInfo -> Void)) -> TrackingToken {
return addTracking(TrackingItem(queue: queue, progress: progress, decoderCompletion: nil))
}
public func addTracking<T>(queue: dispatch_queue_t? = nil, progress: (ProgressInfo -> Void)?, decoder: (NSURL, NSData) -> DecodeResult<T> , completion: Result<T> -> Void) -> TrackingToken {
return addTracking(TrackingItem(queue: queue, progress: progress, decoderCompletion: (wrapDecoder(decoder), wrapCompletion(completion))))
}
public func removeTracking(token: TrackingToken?) {
if let token = token {
OSSpinLockLock(&lock)
trackings.removeValueForKey(token)
OSSpinLockUnlock(&lock)
}
}
// MARK: progress, decoder and completion wrappers.
func notifyProgress(progressInfo: ProgressInfo) {
OSSpinLockLock(&lock)
self.progressInfo = progressInfo
let items = trackings.values
OSSpinLockUnlock(&lock)
items.forEach{ notifyProgrss($0, progressInfo: progressInfo) }
}
private func decoder(url: NSURL, data: NSData) -> DecodeResult<NSData> {
return .Success(data: data)
}
func notifyCompletion(result: Result<NSData>) {
OSSpinLockLock(&lock)
self.result = result
let items = trackings.values
OSSpinLockUnlock(&lock)
items.forEach{ notifyCompletion($0, result: result) }
}
// MARK: private methods
private func addTracking(item: TrackingItem) -> TrackingToken {
OSSpinLockLock(&lock)
let token = TrackingToken()
trackings[token] = item
let progressInfo = self.progressInfo
let result = self.result
OSSpinLockUnlock(&lock)
if let progressInfo = progressInfo {
notifyProgrss(item, progressInfo: progressInfo)
}
if let result = result {
notifyCompletion(item, result: result)
}
return token
}
private func notifyProgrss(item: TrackingItem, progressInfo: ProgressInfo) {
guard let progress = item.progress else { return }
dispatch_async(item.queue ?? trackerQueue){ progress(progressInfo) }
}
private func notifyCompletion(item: TrackingItem, result: Result<NSData>) {
guard let decoderCompletion = item.decoderCompletion else { return }
switch result {
case .Success(_, _):
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {[trackerQueue] in
let decoded = decode(result, decoder: decoderCompletion.decoder)
dispatch_async(item.queue ?? trackerQueue) {
decoderCompletion.completion(decoded)
}
}
case .Failed(_, _):
dispatch_async(item.queue ?? trackerQueue) {
decoderCompletion.completion(decode(result, decoder: decoderCompletion.decoder))
}
}
}
}
// MARK: - ResultTracker. only track progress and result
struct ResultTrackingItem<T> {
let queue: dispatch_queue_t?
let progress: (ProgressInfo -> Void)?
let completion: (Result<T> -> Void)?
}
final public class ResultTracker<T> {
public private(set) var task: Task!
public private(set) var progressInfo: ProgressInfo?
public private(set) var result: Result<T>?
private var lock = OS_SPINLOCK_INIT
private var trackings: [TrackingToken: ResultTrackingItem<T>] = [:]
private let trackerQueue: dispatch_queue_t
init(trackerQueue: dispatch_queue_t? = nil) {
self.trackerQueue = trackerQueue ?? dispatch_queue_create("Phantom.ResultTracker.queue", DISPATCH_QUEUE_CONCURRENT)
}
public static func track(url: NSURL, trackerQueue: dispatch_queue_t? = nil, downloader: Downloader = sharedDownloader, cache: DownloaderCache? = nil, decoder: (NSURL, NSData) -> DecodeResult<T>) -> ResultTracker<T> {
let tracker = ResultTracker<T>(trackerQueue: trackerQueue)
tracker.task = downloader.download(url, cache: cache, queue: tracker.trackerQueue,
progress: tracker.notifyProgress, decoder: decoder, completion: tracker.notifyCompletion)
return tracker
}
// MARK: tracking
/// `queue` default to trackerQueue.
public func addTracking(queue: dispatch_queue_t? = nil, progress: (ProgressInfo -> Void)) -> TrackingToken {
return addTracking(ResultTrackingItem<T>(queue: queue, progress: progress, completion: nil))
}
public func addTracking(queue: dispatch_queue_t? = nil, progress: (ProgressInfo -> Void)?, completion: Result<T> -> Void) -> TrackingToken {
return addTracking(ResultTrackingItem(queue: queue, progress: progress, completion: completion))
}
public func removeTracking(token: TrackingToken?) {
if let token = token {
OSSpinLockLock(&lock)
trackings.removeValueForKey(token)
OSSpinLockUnlock(&lock)
}
}
// MARK: progress, decoder and completion wrappers.
func notifyProgress(progressInfo: ProgressInfo) {
OSSpinLockLock(&lock)
self.progressInfo = progressInfo
let items = trackings.values
OSSpinLockUnlock(&lock)
items.forEach{ notifyProgrss($0, progressInfo: progressInfo) }
}
func notifyCompletion(result: Result<T>) {
OSSpinLockLock(&lock)
self.result = result
let items = trackings.values
OSSpinLockUnlock(&lock)
items.forEach{ notifyCompletion($0, result: result) }
}
// MARK: private methods
private func addTracking(item: ResultTrackingItem<T>) -> TrackingToken {
OSSpinLockLock(&lock)
let token = TrackingToken()
trackings[token] = item
let progressInfo = self.progressInfo
let result = self.result
OSSpinLockUnlock(&lock)
if let progressInfo = progressInfo {
notifyProgrss(item, progressInfo: progressInfo)
}
if let result = result {
notifyCompletion(item, result: result)
}
return token
}
private func notifyProgrss(item: ResultTrackingItem<T>, progressInfo: ProgressInfo) {
guard let progress = item.progress else { return }
dispatch_async(item.queue ?? trackerQueue){ progress(progressInfo) }
}
private func notifyCompletion(item: ResultTrackingItem<T>, result: Result<T>) {
guard let completion = item.completion else { return }
dispatch_async(item.queue ?? trackerQueue) { completion(result) }
}
}
|
308f52ad7e9f82d43c7b57a1a4787194
| 36.19469 | 220 | 0.648941 | false | false | false | false |
oskarpearson/rileylink_ios
|
refs/heads/master
|
NightscoutUploadKit/DeviceStatus/PumpStatus.swift
|
mit
|
1
|
//
// PumpStatus.swift
// RileyLink
//
// Created by Pete Schwamb on 7/26/16.
// Copyright © 2016 Pete Schwamb. All rights reserved.
//
import Foundation
public struct PumpStatus {
let clock: Date
let pumpID: String
let iob: IOBStatus?
let battery: BatteryStatus?
let suspended: Bool?
let bolusing: Bool?
let reservoir: Double?
public init(clock: Date, pumpID: String, iob: IOBStatus? = nil, battery: BatteryStatus? = nil, suspended: Bool? = nil, bolusing: Bool? = nil, reservoir: Double? = nil) {
self.clock = clock
self.pumpID = pumpID
self.iob = iob
self.battery = battery
self.suspended = suspended
self.bolusing = bolusing
self.reservoir = reservoir
}
public var dictionaryRepresentation: [String: Any] {
var rval = [String: Any]()
rval["clock"] = TimeFormat.timestampStrFromDate(clock)
rval["pumpID"] = pumpID
if let battery = battery {
rval["battery"] = battery.dictionaryRepresentation
}
if let reservoir = reservoir {
rval["reservoir"] = reservoir
}
if let iob = iob {
rval["iob"] = iob.dictionaryRepresentation
}
return rval
}
}
|
9b1e10bb5733d0cceae0c1ee6ec70f41
| 25.16 | 173 | 0.583333 | false | false | false | false |
googlearchive/science-journal-ios
|
refs/heads/master
|
ScienceJournal/UI/ExperimentItemsViewController.swift
|
apache-2.0
|
1
|
/*
* Copyright 2019 Google LLC. 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 UIKit
import third_party_objective_c_material_components_ios_components_Palettes_Palettes
import third_party_objective_c_material_components_ios_components_Typography_Typography
protocol ExperimentItemsViewControllerDelegate: class {
func experimentItemsViewControllerDidSelectItem(_ displayItem: DisplayItem)
func experimentItemsViewControllerCommentPressedForItem(_ displayItem: DisplayItem)
func experimentItemsViewControllerMenuPressedForItem(_ displayItem: DisplayItem,
button: MenuButton)
}
// swiftlint:disable type_body_length
/// A view controller that displays experiment items in a list.
class ExperimentItemsViewController: VisibilityTrackingViewController,
UICollectionViewDataSource,
UICollectionViewDelegate,
UICollectionViewDelegateFlowLayout,
ExperimentItemsDataSourceDelegate,
ExperimentCardCellDelegate {
// MARK: - Properties
let archivedFlagCellIdentifier = "ArchivedFlagCell"
let textNoteCardCellIdentifier = "TextNoteCardCell"
let pictureCardCellIdentifier = "PictureCardCell"
let snapshotCardCellIdentifier = "SnapshotCardCell"
let trialCardCellIdentifier = "TrialCardCell"
let triggerCardCellIdentifier = "TriggerCardCell"
let defaultCellIdentifier = "DefaultCell"
private(set) var collectionView: UICollectionView
private let experimentDataSource: ExperimentItemsDataSource!
weak var delegate: ExperimentItemsViewControllerDelegate?
/// The scroll delegate will recieve a subset of scroll delegate calls (didScroll,
/// didEndDecelerating, didEndDragging, willEndDragging).
weak var scrollDelegate: UIScrollViewDelegate?
/// The experiment's interaction options.
var experimentInteractionOptions: ExperimentInteractionOptions
/// Whether to show the archived flag.
var shouldShowArchivedFlag: Bool {
set {
experimentDataSource.shouldShowArchivedFlag = newValue
}
get {
return experimentDataSource.shouldShowArchivedFlag
}
}
var experimentDisplay: ExperimentDisplay = .normal {
didSet {
collectionView.backgroundColor = experimentDisplay.backgroundColor
}
}
/// The scroll position to use when adding items. This is changed when adding content to a trial
/// while recording but should be replaced by logic that can scroll to a view within a trial cell.
var collectionViewChangeScrollPosition = UICollectionView.ScrollPosition.top
/// Returns the insets for experiment cells.
var cellInsets: UIEdgeInsets {
if FeatureFlags.isActionAreaEnabled { return MaterialCardCell.cardInsets }
if experimentDisplay == .pdfExport {
return MaterialCardCell.cardInsets
}
var insets: UIEdgeInsets {
switch displayType {
case .compact, .compactWide:
return MaterialCardCell.cardInsets
case .regular:
return UIEdgeInsets(top: MaterialCardCell.cardInsets.top,
left: 150,
bottom: MaterialCardCell.cardInsets.bottom,
right: 150)
case .regularWide:
// The right side needs to compensate for the drawer sidebar when the experiment is not
// archived.
return UIEdgeInsets(top: MaterialCardCell.cardInsets.top,
left: 90,
bottom: MaterialCardCell.cardInsets.bottom,
right: 90)
}
}
return UIEdgeInsets(top: insets.top,
left: insets.left + view.safeAreaInsetsOrZero.left,
bottom: insets.bottom,
right: insets.right + view.safeAreaInsetsOrZero.right)
}
/// Returns true if there are no trials or notes in the experiment, otherwise false.
var isEmpty: Bool {
return experimentDataSource.experimentItems.count +
experimentDataSource.recordingTrialItemCount == 0
}
private let metadataManager: MetadataManager
private let trialCardNoteViewPool = TrialCardNoteViewPool()
// MARK: - Public
/// Designated initializer.
///
/// - Parameters:
/// - experimentInteractionOptions: The experiment's interaction options.
/// - metadataManager: The metadata manager.
/// - shouldShowArchivedFlag: Whether to show the archived flag.
init(experimentInteractionOptions: ExperimentInteractionOptions,
metadataManager: MetadataManager,
shouldShowArchivedFlag: Bool) {
self.experimentInteractionOptions = experimentInteractionOptions
experimentDataSource = ExperimentItemsDataSource(shouldShowArchivedFlag: shouldShowArchivedFlag)
self.metadataManager = metadataManager
let flowLayout = UICollectionViewFlowLayout()
collectionView = UICollectionView(frame: .zero, collectionViewLayout: flowLayout)
super.init(nibName: nil, bundle: nil)
experimentDataSource.delegate = self
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) is not supported")
}
override func viewDidLoad() {
super.viewDidLoad()
if FeatureFlags.isActionAreaEnabled == true {
view.preservesSuperviewLayoutMargins = true
}
// Always register collection view cells early to avoid a reload occurring first.
collectionView.register(ArchivedFlagCell.self,
forCellWithReuseIdentifier: archivedFlagCellIdentifier)
collectionView.register(TextNoteCardCell.self,
forCellWithReuseIdentifier: textNoteCardCellIdentifier)
collectionView.register(PictureCardCell.self,
forCellWithReuseIdentifier: pictureCardCellIdentifier)
collectionView.register(SnapshotCardCell.self,
forCellWithReuseIdentifier: snapshotCardCellIdentifier)
collectionView.register(TrialCardCell.self, forCellWithReuseIdentifier: trialCardCellIdentifier)
collectionView.register(TriggerCardCell.self,
forCellWithReuseIdentifier: triggerCardCellIdentifier)
collectionView.register(UICollectionViewCell.self,
forCellWithReuseIdentifier: defaultCellIdentifier)
// Collection view.
collectionView.alwaysBounceVertical = true
collectionView.dataSource = self
collectionView.delegate = self
collectionView.backgroundColor = experimentDisplay.backgroundColor
collectionView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(collectionView)
if FeatureFlags.isActionAreaEnabled == true {
collectionView.snp.makeConstraints { (make) in
make.top.bottom.equalToSuperview()
make.leading.equalTo(view.snp.leadingMargin)
make.trailing.equalTo(view.snp.trailingMargin)
}
} else {
collectionView.pinToEdgesOfView(view)
}
}
override func viewWillTransition(to size: CGSize,
with coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransition(to: size, with: coordinator)
coordinator.animate(alongsideTransition: { _ in
self.collectionView.collectionViewLayout.invalidateLayout()
})
}
/// Replaces the experiment items with new items.
///
/// - Parameter items: An array of display items.
func setExperimentItems(_ items: [DisplayItem]) {
experimentDataSource.experimentItems = items
collectionView.reloadData()
}
/// Sets the bottom and right collection view insets. Top insets are not set because they are
/// updated automatically by the MDC app bar.
///
/// - Parameters:
/// - bottom: The bottom inset.
/// - right: The right inset.
func setCollectionViewInsets(bottom: CGFloat, right: CGFloat) {
collectionView.contentInset.bottom = bottom
collectionView.contentInset.right = right
collectionView.scrollIndicatorInsets = collectionView.contentInset
if isViewVisible {
// Invalidating the collection view layout while the view is off screen causes the size for
// item at method to be called too early when navigating back to this view. Being called too
// early can result in a negative width to be calculated, which crashes the app.
collectionView.collectionViewLayout.invalidateLayout()
}
}
/// If a trial with a matching ID exists it will be updated with the given trial, otherwise the
/// trial will be added in the proper sort order.
///
/// - Parameters:
/// - displayTrial: A display trial.
/// - didFinishRecording: Whether or not this is a display trial that finished recording, and
/// should be moved from the recording trial section, to a recorded trial.
func addOrUpdateTrial(_ displayTrial: DisplayTrial, didFinishRecording: Bool) {
if didFinishRecording {
experimentDataSource.removeRecordingTrial()
}
experimentDataSource.addOrUpdateTrial(displayTrial)
}
/// Adds an experiment item to the end of the existing items.
///
/// - Parameters:
/// - displayItem: A display item.
/// - isSorted: Whether the item should be inserted in the correct sort order or added
/// to the end.
func addItem(_ displayItem: DisplayItem, sorted isSorted: Bool = false) {
experimentDataSource.addItem(displayItem, sorted: isSorted)
}
/// Adds a recording trial to the data source.
///
/// - Parameter recordingTrial: A recording trial.
func addOrUpdateRecordingTrial(_ recordingTrial: DisplayTrial) {
experimentDataSource.addOrUpdateRecordingTrial(recordingTrial)
}
/// Updates a matching trial with a new trial.
///
/// - Parameter displayTrial: A display trial.
func updateTrial(_ displayTrial: DisplayTrial) {
experimentDataSource.updateTrial(displayTrial)
}
/// Removes the trial with a given ID.
///
/// - Parameter trialID: A trial ID.
/// - Returns: The index of the removed trial if the removal succeeded.
@discardableResult func removeTrial(withID trialID: String) -> Int? {
return experimentDataSource.removeTrial(withID: trialID)
}
/// Removes the recording trial.
func removeRecordingTrial() {
return experimentDataSource.removeRecordingTrial()
}
/// Updates a matching note with a new note.
///
/// - Parameter displayNote: A display note.
func updateNote(_ displayNote: DisplayNote) {
experimentDataSource.updateNote(displayNote)
}
/// Removes the note with a given ID.
///
/// - Parameter noteID: A note ID.
func removeNote(withNoteID noteID: String) {
experimentDataSource.removeNote(withNoteID: noteID)
}
// MARK: - UICollectionViewDataSource
func numberOfSections(in collectionView: UICollectionView) -> Int {
return experimentDataSource.numberOfSections
}
func collectionView(_ collectionView: UICollectionView,
numberOfItemsInSection section: Int) -> Int {
return experimentDataSource.numberOfItemsInSection(section)
}
func collectionView(_ collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
sizeForItemAt indexPath: IndexPath) -> CGSize {
let width: CGFloat
if FeatureFlags.isActionAreaEnabled {
let collectionViewWidth = collectionView.bounds.width
let insets = [collectionView.adjustedContentInset, cellInsets]
.reduce(0) { return $0 + $1.left + $1.right }
width = collectionViewWidth - insets
} else {
width = collectionView.bounds.size.width - collectionView.contentInset.right -
cellInsets.left - cellInsets.right
}
var calculatedCellHeight: CGFloat
let section = experimentDataSource.section(atIndex: indexPath.section)
switch section {
case .archivedFlag:
calculatedCellHeight = ArchivedFlagCell.height
case .experimentData, .recordingTrial:
// The experiment's data.
let showHeader = experimentDataSource.isExperimentDataSection(indexPath.section)
let isRecordingTrial = experimentDataSource.isRecordingTrialSection(indexPath.section)
guard let experimentItem =
experimentDataSource.item(inSection: section,
atIndex: indexPath.item) else { return .zero }
switch experimentItem.itemType {
case .textNote(let displayTextNote):
calculatedCellHeight = TextNoteCardCell.height(inWidth: width,
textNote: displayTextNote,
showingHeader: showHeader,
showingInlineTimestamp: isRecordingTrial)
case .snapshotNote(let displaySnapshotNote):
calculatedCellHeight = SnapshotCardCell.height(inWidth: width,
snapshotNote: displaySnapshotNote,
showingHeader: showHeader)
case .trial(let displayTrial):
calculatedCellHeight = TrialCardCell.height(inWidth: width,
trial: displayTrial,
experimentDisplay: experimentDisplay)
case .pictureNote(let displayPictureNote):
let pictureStyle: PictureStyle = isRecordingTrial ? .small : .large
calculatedCellHeight = PictureCardCell.height(inWidth: width,
pictureNote: displayPictureNote,
pictureStyle: pictureStyle,
showingHeader: showHeader)
case .triggerNote(let displayTriggerNote):
calculatedCellHeight = TriggerCardCell.height(inWidth: width,
triggerNote: displayTriggerNote,
showingHeader: showHeader,
showingInlineTimestamp: isRecordingTrial)
}
calculatedCellHeight = ceil(calculatedCellHeight)
}
return CGSize(width: width, height: calculatedCellHeight)
}
func collectionView(_ collectionView: UICollectionView,
cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let section = experimentDataSource.section(atIndex: indexPath.section)
switch section {
case .archivedFlag:
return collectionView.dequeueReusableCell(withReuseIdentifier: archivedFlagCellIdentifier,
for: indexPath)
case .experimentData, .recordingTrial:
let showHeader = experimentDataSource.isExperimentDataSection(indexPath.section)
let isRecordingTrial = experimentDataSource.isRecordingTrialSection(indexPath.section)
let displayItem = experimentDataSource.item(inSection: section, atIndex: indexPath.item)
let showCaptionButton = experimentDisplay.showCaptionButton(for: experimentInteractionOptions)
let cell: UICollectionViewCell
switch displayItem?.itemType {
case .textNote(let textNote)?:
cell = collectionView.dequeueReusableCell(withReuseIdentifier: textNoteCardCellIdentifier,
for: indexPath)
if let cell = cell as? TextNoteCardCell {
cell.setTextNote(textNote,
showHeader: showHeader,
showInlineTimestamp: isRecordingTrial,
experimentDisplay: experimentDisplay)
cell.delegate = self
}
case .snapshotNote(let snapshotNote)?:
cell = collectionView.dequeueReusableCell(withReuseIdentifier: snapshotCardCellIdentifier,
for: indexPath)
if let cell = cell as? SnapshotCardCell {
cell.setSnapshotNote(snapshotNote,
showHeader: showHeader,
showInlineTimestamp: isRecordingTrial,
showCaptionButton: showCaptionButton,
experimentDisplay: experimentDisplay)
cell.delegate = self
}
case .trial(let trial)?:
cell = collectionView.dequeueReusableCell(withReuseIdentifier: trialCardCellIdentifier,
for: indexPath)
if let cell = cell as? TrialCardCell {
// The trial card note view pool must be set before configuring the cell.
cell.setTrialCardNoteViewPool(trialCardNoteViewPool)
if trial.status == .recording {
cell.configureRecordingCellWithTrial(trial, metadataManager: metadataManager)
} else {
cell.configureCellWithTrial(trial,
metadataManager: metadataManager,
experimentDisplay: experimentDisplay)
}
cell.delegate = self
}
case .pictureNote(let displayPictureNote)?:
cell = collectionView.dequeueReusableCell(withReuseIdentifier: pictureCardCellIdentifier,
for: indexPath)
if let cell = cell as? PictureCardCell {
let pictureStyle: PictureStyle = isRecordingTrial ? .small : .large
cell.setPictureNote(displayPictureNote,
withPictureStyle: pictureStyle,
metadataManager: metadataManager,
showHeader: showHeader,
showInlineTimestamp: isRecordingTrial,
showCaptionButton: showCaptionButton,
experimentDisplay: experimentDisplay)
cell.delegate = self
}
case .triggerNote(let displayTriggerNote)?:
cell = collectionView.dequeueReusableCell(withReuseIdentifier: triggerCardCellIdentifier,
for: indexPath)
if let cell = cell as? TriggerCardCell {
cell.setTriggerNote(displayTriggerNote,
showHeader: showHeader,
showInlineTimestamp: isRecordingTrial,
showCaptionButton: showCaptionButton,
experimentDisplay: experimentDisplay)
cell.delegate = self
}
case .none:
cell = collectionView.dequeueReusableCell(withReuseIdentifier: defaultCellIdentifier,
for: indexPath)
}
// Set the cell borders
if isRecordingTrial, let cell = cell as? MaterialCardCell {
let isFirstCellInRecordingSection = indexPath.item == 0
let isLastCellInRecordingSection =
indexPath.item == experimentDataSource.recordingTrialItemCount - 1
if isFirstCellInRecordingSection && isLastCellInRecordingSection {
cell.border = MaterialCardCell.Border(options: .all)
} else if isFirstCellInRecordingSection {
cell.border = MaterialCardCell.Border(options: .top)
} else if isLastCellInRecordingSection {
cell.border = MaterialCardCell.Border(options: .bottom)
} else {
cell.border = MaterialCardCell.Border(options: .none)
}
}
return cell
}
}
func collectionView(_ collectionView: UICollectionView,
willDisplay cell: UICollectionViewCell,
forItemAt indexPath: IndexPath) {
if experimentDataSource.section(atIndex: indexPath.section) == .experimentData ||
experimentDataSource.isRecordingTrialSection(indexPath.section) {
// Loading picture note images on demand instead of all at once prevents crashes and reduces
// the memory footprint.
if let pictureNoteCell = cell as? PictureCardCell {
pictureNoteCell.displayImage()
} else if let trialNoteCell = cell as? TrialCardCell {
trialNoteCell.displayImages()
}
}
}
func collectionView(_ collectionView: UICollectionView,
didEndDisplaying cell: UICollectionViewCell,
forItemAt indexPath: IndexPath) {
if experimentDataSource.section(atIndex: indexPath.section) == .experimentData {
if let pictureNoteCell = cell as? PictureCardCell {
pictureNoteCell.removeImage()
} else if let trialNoteCell = cell as? TrialCardCell {
trialNoteCell.removeImages()
}
}
}
// MARK: - UICollectionViewDelegate
func collectionView(_ collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
insetForSectionAt section: Int) -> UIEdgeInsets {
// Determine the last section with items.
var lastSectionWithItems: Int?
for i in 0..<experimentDataSource.numberOfSections {
if experimentDataSource.numberOfItemsInSection(i) > 0 {
lastSectionWithItems = i
}
}
if experimentDataSource.numberOfItemsInSection(section) == 0 {
// If the section is empty, no insets.
return .zero
} else if section == lastSectionWithItems {
// If this is the last section with items, include the bottom inset.
return cellInsets
} else {
// If this is not the last section with items section, but this section has items,
// use standard insets without bottom. This avoids an issue where two stacked
// sections can have double padding.
var modifiedInsets = cellInsets
modifiedInsets.bottom = 0
return modifiedInsets
}
}
func collectionView(_ collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
minimumLineSpacingForSectionAt section: Int) -> CGFloat {
if experimentDataSource.isRecordingTrialSection(section) {
return 0
}
return MaterialCardCell.cardInsets.bottom
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let section = experimentDataSource.section(atIndex: indexPath.section)
switch section {
case .experimentData, .recordingTrial:
guard let displayItem =
experimentDataSource.item(inSection: section, atIndex: indexPath.item) else { return }
delegate?.experimentItemsViewControllerDidSelectItem(displayItem)
default:
return
}
}
// MARK: - ExperimentCardCellDelegate
func experimentCardCellCommentButtonPressed(_ cell: MaterialCardCell) {
guard let indexPath = collectionView.indexPath(for: cell) else { return }
let section = experimentDataSource.section(atIndex: indexPath.section)
switch section {
case .experimentData:
guard let displayItem = experimentDataSource.item(inSection: section,
atIndex: indexPath.item) else { return }
delegate?.experimentItemsViewControllerCommentPressedForItem(displayItem)
case .recordingTrial:
return
default:
return
}
}
func experimentCardCellMenuButtonPressed(_ cell: MaterialCardCell, button: MenuButton) {
guard let indexPath = collectionView.indexPath(for: cell) else { return }
let section = experimentDataSource.section(atIndex: indexPath.section)
switch section {
case .experimentData, .recordingTrial:
guard let displayItem = experimentDataSource.item(inSection: section,
atIndex: indexPath.item) else { return }
delegate?.experimentItemsViewControllerMenuPressedForItem(displayItem, button: button)
default:
return
}
}
// Unsupported.
func experimentCardCellTimestampButtonPressed(_ cell: MaterialCardCell) {}
// MARK: - ExperimentItemsDataSourceDelegate
func experimentDataSource(_ experimentDataSource: ExperimentItemsDataSource,
didChange changes: [CollectionViewChange],
scrollToIndexPath indexPath: IndexPath?) {
guard isViewVisible else {
collectionView.reloadData()
return
}
// Perform changes.
collectionView.performChanges(changes)
// Scroll to index path if necessary.
guard let indexPath = indexPath else { return }
collectionView.scrollToItem(at: indexPath,
at: collectionViewChangeScrollPosition,
animated: true)
}
// MARK: - UIScrollViewDelegate
func scrollViewDidScroll(_ scrollView: UIScrollView) {
scrollDelegate?.scrollViewDidScroll!(scrollView)
}
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
scrollDelegate?.scrollViewDidEndDecelerating!(scrollView)
}
func scrollViewDidEndDragging(_ scrollView: UIScrollView,
willDecelerate decelerate: Bool) {
scrollDelegate?.scrollViewDidEndDragging!(scrollView, willDecelerate: decelerate)
}
func scrollViewWillEndDragging(_ scrollView: UIScrollView,
withVelocity velocity: CGPoint,
targetContentOffset: UnsafeMutablePointer<CGPoint>) {
scrollDelegate?.scrollViewWillEndDragging!(scrollView,
withVelocity: velocity,
targetContentOffset: targetContentOffset)
}
}
// swiftlint:enable type_body_length
|
0623a146bf758360ad4376a2e90bf1a6
| 41.339286 | 100 | 0.664967 | false | false | false | false |
cornerstonecollege/402
|
refs/heads/master
|
Younseo/CustomViews/CustomViews/ViewController.swift
|
gpl-3.0
|
1
|
//
// ViewController.swift
// CustomViews
//
// Created by hoconey on 2016/10/13.
// Copyright © 2016年 younseo. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let frame = CGRect(x: 0, y: 50, width: 100, height: 100)
let circle = FirstCustomView(frame: frame)
//circle.backgroundColor = UIColor.red
self.view.addSubview(circle)
let frame2 = CGRect(x: 200, y: 50, width: 100, height: 100)
let circle2 = FirstCustomView(frame: frame2)
//circle.backgroundColor = UIColor.red
self.view.addSubview(circle2)
let frame3 = CGRect(x: 100, y: 250, width: 100, height: 200)
let circle3 = FirstCustomView(frame: frame3)
//circle.backgroundColor = UIColor.red
self.view.addSubview(circle3)
let circleFrame = CGRect(x: 100, y: 100, width: 100, height: 100)
let circle4 = CircleView(frame: circleFrame)
//circle4.backgroundColor = UIColor.yellow
self.view.addSubview(circle4)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
|
c5a4d95a6228fbdb0bb19a8a691b8ae2
| 26.6 | 73 | 0.620773 | false | false | false | false |
dduan/swift
|
refs/heads/master
|
stdlib/public/core/LifetimeManager.swift
|
apache-2.0
|
2
|
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
/// Evaluate `f()` and return its result, ensuring that `x` is not
/// destroyed before f returns.
public func withExtendedLifetime<T, Result>(
x: T, @noescape _ f: () throws -> Result
) rethrows -> Result {
defer { _fixLifetime(x) }
return try f()
}
/// Evaluate `f(x)` and return its result, ensuring that `x` is not
/// destroyed before f returns.
public func withExtendedLifetime<T, Result>(
x: T, @noescape _ f: (T) throws -> Result
) rethrows -> Result {
defer { _fixLifetime(x) }
return try f(x)
}
extension String {
/// Invoke `f` on the contents of this string, represented as
/// a nul-terminated array of char, ensuring that the array's
/// lifetime extends through the execution of `f`.
public func withCString<Result>(
@noescape f: (UnsafePointer<Int8>) throws -> Result
) rethrows -> Result {
return try self.nulTerminatedUTF8.withUnsafeBufferPointer {
try f(UnsafePointer($0.baseAddress))
}
}
}
// Fix the lifetime of the given instruction so that the ARC optimizer does not
// shorten the lifetime of x to be before this point.
@_transparent
public func _fixLifetime<T>(x: T) {
Builtin.fixLifetime(x)
}
/// Invokes `body` with an `UnsafeMutablePointer` to `arg` and returns the
/// result. Useful for calling Objective-C APIs that take "in/out"
/// parameters (and default-constructible "out" parameters) by pointer.
public func withUnsafeMutablePointer<T, Result>(
arg: inout T,
@noescape _ body: (UnsafeMutablePointer<T>) throws -> Result
) rethrows -> Result
{
return try body(UnsafeMutablePointer<T>(Builtin.addressof(&arg)))
}
/// Like `withUnsafeMutablePointer`, but passes pointers to `arg0` and `arg1`.
public func withUnsafeMutablePointers<A0, A1, Result>(
arg0: inout A0,
_ arg1: inout A1,
@noescape _ body: (
UnsafeMutablePointer<A0>, UnsafeMutablePointer<A1>) throws -> Result
) rethrows -> Result {
return try body(
UnsafeMutablePointer<A0>(Builtin.addressof(&arg0)),
UnsafeMutablePointer<A1>(Builtin.addressof(&arg1)))
}
/// Like `withUnsafeMutablePointer`, but passes pointers to `arg0`, `arg1`,
/// and `arg2`.
public func withUnsafeMutablePointers<A0, A1, A2, Result>(
arg0: inout A0,
_ arg1: inout A1,
_ arg2: inout A2,
@noescape _ body: (
UnsafeMutablePointer<A0>,
UnsafeMutablePointer<A1>,
UnsafeMutablePointer<A2>
) throws -> Result
) rethrows -> Result {
return try body(
UnsafeMutablePointer<A0>(Builtin.addressof(&arg0)),
UnsafeMutablePointer<A1>(Builtin.addressof(&arg1)),
UnsafeMutablePointer<A2>(Builtin.addressof(&arg2)))
}
/// Invokes `body` with an `UnsafePointer` to `arg` and returns the
/// result. Useful for calling Objective-C APIs that take "in/out"
/// parameters (and default-constructible "out" parameters) by pointer.
public func withUnsafePointer<T, Result>(
arg: inout T,
@noescape _ body: (UnsafePointer<T>) throws -> Result
) rethrows -> Result
{
return try body(UnsafePointer<T>(Builtin.addressof(&arg)))
}
/// Like `withUnsafePointer`, but passes pointers to `arg0` and `arg1`.
public func withUnsafePointers<A0, A1, Result>(
arg0: inout A0,
_ arg1: inout A1,
@noescape _ body: (UnsafePointer<A0>, UnsafePointer<A1>) throws -> Result
) rethrows -> Result {
return try body(
UnsafePointer<A0>(Builtin.addressof(&arg0)),
UnsafePointer<A1>(Builtin.addressof(&arg1)))
}
/// Like `withUnsafePointer`, but passes pointers to `arg0`, `arg1`,
/// and `arg2`.
public func withUnsafePointers<A0, A1, A2, Result>(
arg0: inout A0,
_ arg1: inout A1,
_ arg2: inout A2,
@noescape _ body: (
UnsafePointer<A0>,
UnsafePointer<A1>,
UnsafePointer<A2>
) throws -> Result
) rethrows -> Result {
return try body(
UnsafePointer<A0>(Builtin.addressof(&arg0)),
UnsafePointer<A1>(Builtin.addressof(&arg1)),
UnsafePointer<A2>(Builtin.addressof(&arg2)))
}
|
4ba161b5828d3c327b6b544d121eae2b
| 32.450382 | 80 | 0.675491 | false | false | false | false |
guardianproject/poe
|
refs/heads/master
|
POE/Classes/Roboto.swift
|
bsd-3-clause
|
1
|
//
// Roboto.swift
// POE
//
// Created by Benjamin Erhart on 24.03.17.
// Copyright © 2017 Guardian Project. All rights reserved.
//
import UIKit
enum Roboto {
static let defaultSize: CGFloat = 17
static let regular = "Roboto-Regular"
static let italic = "Roboto-Italic"
static let bold = "Roboto-Bold"
static let boldItalic = "Roboto-BoldItalic"
static let black = "Roboto-Black"
static let blackItalic = "Roboto-BlackItalic"
static let medium = "Roboto-Medium"
static let mediumItalic = "Roboto-MediumItalic"
static let light = "Roboto-Light"
static let lightItalic = "Roboto-LightItalic"
static let thin = "Roboto-Thin"
static let thinItalic = "Roboto-ThinItalic"
static let condensed = "RobotoCondensed-Regular"
static let condensedItalic = "RobotoCondensed-Italic"
static let condensedBold = "RobotoCondensed-Bold"
static let condensedBoldItalic = "RobotoCondensed-BoldItalic"
static let condensedLight = "RobotoCondensed-Light"
static let condensedLightItalic = "RobotoCondensed-LightItalic"
}
/**
Evaluate a given font and replace it with the most adequate font of the Roboto family.
- Parameter oldFont
The original font.
Inspired by [Using custom font for entire iOS app swift](http://stackoverflow.com/questions/28180449/using-custom-font-for-entire-ios-app-swift).
*/
private func replaceFont(_ oldFont: UIFont?) -> UIFont? {
let oldName = oldFont?.fontName.lowercased() ?? ""
var name :String
if oldName.contains("condensed") {
if oldName.contains("bold") || oldName.contains("black") {
name = oldName.contains("italic") ? Roboto.condensedBoldItalic : Roboto.condensedBold
}
else if oldName.contains("light") || oldName.contains("ultralight") || oldName.contains("thin") {
name = oldName.contains("italic") ? Roboto.condensedLightItalic : Roboto.condensedLight
}
else if oldName.contains("italic") {
name = Roboto.condensedItalic
}
else {
name = Roboto.condensed
}
}
else if oldName.contains("bold") {
name = oldName.contains("italic") ? Roboto.boldItalic : Roboto.bold
}
else if oldName.contains("black") {
name = oldName.contains("italic") ? Roboto.blackItalic : Roboto.black
}
else if oldName.contains("medium") {
name = oldName.contains("italic") ? Roboto.mediumItalic : Roboto.medium
}
else if oldName.contains("light") {
name = oldName.contains("italic") ? Roboto.lightItalic : Roboto.light
}
else if oldName.contains("ultralight") || oldName.contains("thin") {
name = oldName.contains("italic") ? Roboto.thinItalic : Roboto.thin
}
else if oldName.contains("italic") {
name = Roboto.italic
}
else {
name = Roboto.regular
}
if let font = UIFont(name: name, size: oldFont?.pointSize ?? Roboto.defaultSize) {
return font
}
return oldFont
}
extension UILabel {
@objc var substituteFont: Bool {
get {
return false
}
set {
self.font = replaceFont(self.font)
}
}
}
extension UITextView {
@objc var substituteFont : Bool {
get {
return false
}
set {
self.font = replaceFont(self.font)
}
}
}
extension UITextField {
@objc var substituteFont : Bool {
get {
return false
}
set {
self.font = replaceFont(self.font)
}
}
}
/**
Taken from
[Can I embed a custom font in a bundle and access it from an ios framework?](http://stackoverflow.com/questions/14735522/can-i-embed-a-custom-font-in-a-bundle-and-access-it-from-an-ios-framework)
*/
private func registerFont(from url: URL) throws {
guard let fontDataProvider = CGDataProvider(url: url as CFURL) else {
throw NSError(domain: "Could not create font data provider for \(url).", code: -1, userInfo: nil)
}
let font = CGFont(fontDataProvider)
var error: Unmanaged<CFError>?
guard CTFontManagerRegisterGraphicsFont(font!, &error) else {
throw error!.takeUnretainedValue()
}
}
/**
Inspired by
[Can I embed a custom font in a bundle and access it from an ios framework?](http://stackoverflow.com/questions/14735522/can-i-embed-a-custom-font-in-a-bundle-and-access-it-from-an-ios-framework)
*/
private func fontURLs() -> [URL] {
var urls = [URL]()
// Fortunately, file and font names are identical with the Roboto font family.
let fileNames = [
Roboto.black, Roboto.blackItalic,
Roboto.bold, Roboto.boldItalic,
Roboto.italic,
Roboto.light, Roboto.lightItalic,
Roboto.medium, Roboto.mediumItalic,
Roboto.regular,
Roboto.thin, Roboto.thinItalic,
Roboto.condensedBold, Roboto.condensedBoldItalic,
Roboto.condensedItalic,
Roboto.condensedLight, Roboto.condensedLightItalic,
Roboto.condensed]
fileNames.forEach({
if let url = XibViewController.getBundle().url(forResource: $0, withExtension: "ttf") {
urls.append(url)
}
})
return urls
}
/**
#robotoIt() needs to be called only once.
This flag tracks that.
*/
private var robotoed = false
/**
Loads and injects the Roboto font family dynamically into the app.
Replaces the normal font of UILabels, UITextViews and UITextFields with proper styles of the
Roboto font family.
If the fonts are not properly replaced, ensure that the font files are added to the "POE" target
properly!
*/
func robotoIt() {
if (!robotoed) {
do {
try fontURLs().forEach({ try registerFont(from: $0) })
} catch {
print(error)
}
UILabel.appearance().substituteFont = true
UITextView.appearance().substituteFont = true
UITextField.appearance().substituteFont = true
robotoed = true
// // Debug: Print list of font families and their fonts.
// for family: String in UIFont.familyNames {
// print("\(family)")
// for names: String in UIFont.fontNames(forFamilyName: family) {
// print("== \(names)")
// }
// }
}
}
|
d27b514d7167020d762c4181ecf3c921
| 29.681159 | 199 | 0.635648 | false | false | false | false |
raymondshadow/SwiftDemo
|
refs/heads/master
|
SwiftApp/DesignMode/DesignMode/ProtoType(原型)/Resume.swift
|
apache-2.0
|
1
|
//
// Resume.swift
// DesignMode
//
// Created by wuyp on 2017/9/12.
// Copyright © 2017年 Raymond. All rights reserved.
//
import Foundation
class WorkExperience: NSObject, NSCopying {
var company: String = ""
var timespan: String = ""
init(company: String, timespan: String) {
self.company = company
self.timespan = timespan
}
func copy(with zone: NSZone? = nil) -> Any {
let new = WorkExperience(company: company, timespan: timespan)
return new
}
}
class Resume: NSObject, NSCopying {
var name: String
var workExperience: WorkExperience
init(name: String, experience: WorkExperience) {
self.name = name
self.workExperience = experience.copy() as! WorkExperience
}
func copy(with zone: NSZone? = nil) -> Any {
let new = Resume(name: name, experience: workExperience)
return new
}
}
|
3a73b87ac3cae87ef0bb8960aa055e43
| 22.641026 | 70 | 0.621475 | false | false | false | false |
mvader/advent-of-code
|
refs/heads/master
|
2021/03/01.swift
|
mit
|
1
|
import Foundation
let lines = try String(contentsOfFile: "./input.txt", encoding: .utf8).split(separator: "\n")
let diagnostic = lines.map { line in Int(line, radix: 2)! }
let rowSize = lines.first!.count
let gammaRate = (0 ..< rowSize).map { i in
let mask = 1 << (rowSize - i - 1)
let ones = diagnostic.reduce(0) { acc, n in acc + ((n & mask) > 0 ? 1 : 0) }
return (ones > diagnostic.count / 2) ? mask : 0
}.reduce(0, +)
let epsilonRate = ((1 << rowSize) - 1) ^ gammaRate
print(gammaRate * epsilonRate)
|
502bc348da8f972b368c805c1372dcf3
| 35.428571 | 93 | 0.639216 | false | false | false | false |
Bluthwort/Bluthwort
|
refs/heads/master
|
Sources/Classes/Style/UITableViewCellStyle.swift
|
mit
|
1
|
//
// UITableViewCellStyle.swift
//
// Copyright (c) 2018 Bluthwort
//
// 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.
//
extension Bluthwort where Base: UITableViewCell {
@discardableResult
public func backgroundView(_ view: UIView?) -> Bluthwort {
// The view used as the background of the cell.
base.backgroundView = view
return self
}
@discardableResult
public func selectedBackgroundView(_ view: UIView?) -> Bluthwort {
// The view used as the background of the cell when it is selected.
base.selectedBackgroundView = view
return self
}
@discardableResult
public func multipleSelectionBackgroundView(_ view: UIView?) -> Bluthwort {
// The background view to use for a selected cell when the table view allows multiple row
// selections.
base.multipleSelectionBackgroundView = view
return self
}
@discardableResult
public func accessoryType(_ type: UITableViewCellAccessoryType) -> Bluthwort {
// The type of standard accessory view the cell should use (normal state).
base.accessoryType = type
return self
}
@discardableResult
public func accessoryView(_ view: UIView?) -> Bluthwort {
// A view that is used, typically as a control, on the right side of the cell (normal state).
base.accessoryView = view
return self
}
@discardableResult
public func editingAccessoryType(_ type: UITableViewCellAccessoryType) -> Bluthwort {
// The type of standard accessory view the cell should use in the table view’s editing state.
base.editingAccessoryType = type
return self
}
@discardableResult
public func editingAccessoryView(_ view: UIView?) -> Bluthwort {
// A view that is used typically as a control on the right side of the cell when it is in
// editing mode.
base.editingAccessoryView = view
return self
}
@discardableResult
public func isSelected(_ flag: Bool, animated: Bool? = nil) -> Bluthwort {
if let animated = animated {
// Sets the selected state of the cell, optionally animating the transition between
// states.
base.setSelected(flag, animated: animated)
} else {
// A Boolean value that indicates whether the cell is selected.
base.isSelected = flag
}
return self
}
@discardableResult
public func selectionStyle(_ style: UITableViewCellSelectionStyle) -> Bluthwort {
// The style of selection for a cell.
base.selectionStyle = style
return self
}
@discardableResult
public func isHighlighted(_ flag: Bool, animated: Bool? = nil) -> Bluthwort {
if let animated = animated {
// Sets the highlighted state of the cell, optionally animating the transition between
// states.
base.setHighlighted(flag, animated: animated)
} else {
// A Boolean value that indicates whether the cell is highlighted.
base.isHighlighted = flag
}
return self
}
@discardableResult
public func isEditing(_ flag: Bool, animated: Bool? = nil) -> Bluthwort {
if let animated = animated {
// Toggles the receiver into and out of editing mode.
base.setEditing(flag, animated: animated)
} else {
// A Boolean value that indicates whether the cell is in an editable state.
base.isEditing = flag
}
return self
}
@discardableResult
public func showsReorderControl(_ flag: Bool) -> Bluthwort {
// A Boolean value that determines whether the cell shows the reordering control.
base.showsReorderControl = flag
return self
}
@available(iOS 11.0, *)
@discardableResult
public func userInteractionEnabledWhileDragging(_ flag: Bool) -> Bluthwort {
// A Boolean value indicating whether users can interact with a cell while it is being dragged.
base.userInteractionEnabledWhileDragging = flag
return self
}
@discardableResult
public func indentationLevel(_ level: Int) -> Bluthwort {
// The indentation level of the cell’s content.
base.indentationLevel = level
return self
}
@discardableResult
public func indentationWidth(_ width: CGFloat) -> Bluthwort {
// The width for each level of indentation of a cell's content.
base.indentationWidth = width
return self
}
@discardableResult
public func shouldIndentWhileEditing(_ flag: Bool) -> Bluthwort {
// A Boolean value that controls whether the cell background is indented when the table view
// is in editing mode.
base.shouldIndentWhileEditing = flag
return self
}
@discardableResult
public func separatorInset(_ inset: UIEdgeInsets) -> Bluthwort {
// The inset values for the cell’s content.
base.separatorInset = inset
return self
}
@discardableResult
public func focusStyle(_ style: UITableViewCellFocusStyle) -> Bluthwort {
// The appearance of the cell when focused.
base.focusStyle = style
return self
}
}
|
e6cdab7b09fc3e816734955e117aa8b6
| 35.58046 | 103 | 0.664415 | false | false | false | false |
omiz/In-Air
|
refs/heads/master
|
In Air/Source/Helper/Extension/UIView.swift
|
apache-2.0
|
1
|
//
// UIView.swift
// Clouds
//
// Created by Omar Allaham on 3/19/17.
// Copyright © 2017 Bemaxnet. All rights reserved.
//
import UIKit
extension UIView {
class func load(fromNib nib: String, bundle : Bundle? = nil) -> UIView? {
return UINib(
nibName: nib,
bundle: bundle
).instantiate(withOwner: nil, options: nil)[0] as? UIView
}
enum ShadowDirection: Int {
case horizontal
case vertical
}
func addShadow(_ direction: ShadowDirection = .vertical) {
layer.shadowColor = UIColor.darkGray.cgColor
layer.shadowOffset = CGSize(width: direction == .vertical ? 0 : -0.5, height: 0.5)
layer.shadowOpacity = 0.2
layer.shouldRasterize = false
clipsToBounds = false
layer.masksToBounds = false
}
}
|
4d8bb3c328c47e7a50128e05d8f09e79
| 23.606061 | 88 | 0.623153 | false | false | false | false |
MNTDeveloppement/MNTAppAnimations
|
refs/heads/master
|
MNTApp/Transitions/TransitionPresentationController.swift
|
mit
|
1
|
//
// TransitionController.swift
// MNTApp
//
// Created by Mehdi Sqalli on 30/12/14.
// Copyright (c) 2014 MNT Developpement. All rights reserved.
//
import UIKit
import QuartzCore
class TransitionPresentationController: NSObject, UIViewControllerAnimatedTransitioning {
let animationDuration = 1.0
var animating = false
var operation:UINavigationControllerOperation = .Push
weak var storedContext: UIViewControllerContextTransitioning? = nil
func transitionDuration(transitionContext: UIViewControllerContextTransitioning) -> NSTimeInterval {
return animationDuration
}
func animateTransition(transitionContext: UIViewControllerContextTransitioning) {
let fromViewController = transitionContext.viewControllerForKey(UITransitionContextFromViewControllerKey)!
let toViewController = transitionContext.viewControllerForKey(UITransitionContextToViewControllerKey)!
let containerView = transitionContext.containerView()
let animationDuration = self .transitionDuration(transitionContext)
// take a snapshot of the detail ViewController so we can do whatever with it (cause it's only a view), and don't have to care about breaking constraints
let snapshotView = toViewController.view.resizableSnapshotViewFromRect(toViewController.view.frame, afterScreenUpdates: true, withCapInsets: UIEdgeInsetsZero)
snapshotView.transform = CGAffineTransformMakeScale(0.1, 0.1)
snapshotView.center = fromViewController.view.center
containerView.addSubview(snapshotView)
// hide the detail view until the snapshot is being animated
toViewController.view.alpha = 0.0
containerView.addSubview(toViewController.view)
UIView.animateWithDuration(animationDuration, delay: 0.0, usingSpringWithDamping: 0.8, initialSpringVelocity: 20.0, options: nil,
animations: { () -> Void in
snapshotView.transform = CGAffineTransformIdentity
}, completion: { (finished) -> Void in
snapshotView.removeFromSuperview()
toViewController.view.alpha = 1.0
transitionContext.completeTransition(finished)
})
// storedContext = transitionContext
//
// let fromVC = transitionContext.viewControllerForKey(UITransitionContextFromViewControllerKey) as FirstViewController
// let toVC = transitionContext.viewControllerForKey(UITransitionContextToViewControllerKey) as HomeViewController
//
// transitionContext.containerView().addSubview(toVC.view)
//
// // grow logo
//
// let animation = CABasicAnimation(keyPath: "transform")
//
// animation.toValue = NSValue(CATransform3D: CATransform3DMakeScale(8.0, 10.0, 1.0)
//// CATransform3DConcat(
////// CATransform3DMakeTranslation(0.0, 0.0, 0.0),
//// CATransform3DMakeScale(15.0, 10.0, 10.0)
//// )
// )
//
// animation.duration = animationDuration
// animation.delegate = self
// animation.fillMode = kCAFillModeForwards
// animation.removedOnCompletion = false
// delay(seconds: animationDuration) { () -> () in
// fromVC.mntLogo.layer.removeAllAnimations()
// //transitionContext.containerView().addSubview(toVC.view)
// }
//
// fromVC.mntLogo.layer.addAnimation(animation, forKey: nil)
//
// toVC.logo.layer.opacity = 0.0
//
//// let fadeIn = CABasicAnimation(keyPath: "opacity")
//// fadeIn.duration = animationDuration
//// fadeIn.toValue = 3.0
//
//// toVC.logo.layer.addAnimation(fadeIn, forKey: "fadeIn")
//// toVC.logo.layer.addAnimation(animation, forKey: nil)
}
override func animationDidStop(anim: CAAnimation!, finished flag: Bool) {
if let context = storedContext {
// let toVC = context.viewControllerForKey(UITransitionContextToViewControllerKey) as HomeViewController
// toVC.logo.layer.opacity = 0
context.completeTransition(!context.transitionWasCancelled())
}
storedContext = nil
animating = false
}
}
|
9e245cce3c1a241aaf0e24a5a71b5bf5
| 40.913462 | 166 | 0.664373 | false | false | false | false |
ALHariPrasad/iOS-9-Sampler
|
refs/heads/master
|
iOS9Sampler/SampleViewControllers/SpringViewController.swift
|
mit
|
110
|
//
// SpringViewController.swift
// iOS9Sampler
//
// Created by Shuichi Tsutsumi on 9/13/15.
// Copyright © 2015 Shuichi Tsutsumi. All rights reserved.
//
// Thanks to
// http://qiita.com/kaway/items/b9e85403a4d78c11f8df
import UIKit
class SpringViewController: UIViewController {
@IBOutlet weak var massSlider: UISlider!
@IBOutlet weak var massLabel: UILabel!
@IBOutlet weak var stiffnessSlider: UISlider!
@IBOutlet weak var stiffnessLabel: UILabel!
@IBOutlet weak var dampingSlider: UISlider!
@IBOutlet weak var dampingLabel: UILabel!
@IBOutlet weak var durationLabel: UILabel!
@IBOutlet weak var animateBtn: UIButton!
@IBOutlet weak var imageView: UIImageView!
let animation = CASpringAnimation(keyPath: "position")
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
animation.initialVelocity = -5.0
animation.removedOnCompletion = false
animation.fillMode = kCAFillModeForwards
animation.delegate = self
// update labels
self.massChanged(massSlider)
self.stiffnessChanged(stiffnessSlider)
self.dampingChanged(dampingSlider)
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
let fromPos = CGPoint(x: CGRectGetMidX(view.bounds) + 100, y: imageView.center.y)
let toPos = CGPoint(x: fromPos.x - 200, y: fromPos.y)
animation.fromValue = NSValue(CGPoint: fromPos)
animation.toValue = NSValue(CGPoint: toPos)
imageView.center = fromPos
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
private func updateDurationLabel() {
durationLabel.text = String(format: "settlingDuration:%.1f", animation.settlingDuration)
}
// =========================================================================
// MARK: - CAAnimation Delegate
override func animationDidStop(anim: CAAnimation, finished flag: Bool) {
print(__FUNCTION__+"\n")
animateBtn.enabled = true
}
// =========================================================================
// MARK: - Actions
@IBAction func massChanged(sender: UISlider) {
massLabel.text = String(format: "%.1f", sender.value)
animation.mass = CGFloat(sender.value)
self.updateDurationLabel()
}
@IBAction func stiffnessChanged(sender: UISlider) {
stiffnessLabel.text = String(format: "%.1f", sender.value)
animation.stiffness = CGFloat(sender.value)
self.updateDurationLabel()
}
@IBAction func dampingChanged(sender: UISlider) {
dampingLabel.text = String(format: "%.1f", sender.value)
animation.damping = CGFloat(sender.value)
self.updateDurationLabel()
}
@IBAction func animateBtnTapped(sender: UIButton) {
animateBtn.enabled = false
animation.duration = animation.settlingDuration
imageView.layer.addAnimation(animation, forKey: nil)
}
}
|
af515f7b66dd4d95fa47e1a0cc9c7a34
| 28.733945 | 96 | 0.62851 | false | false | false | false |
rvanmelle/LeetSwift
|
refs/heads/master
|
Problems.playground/Pages/Reverse Integer.xcplaygroundpage/Contents.swift
|
mit
|
1
|
//: hello
/*
https://leetcode.com/problems/reverse-integer/#/description
Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
Note:
The input is assumed to be a 32-bit signed integer. Your function should return 0 when the reversed integer overflows.
*/
import Foundation
import XCTest
//: [Next](@next)
func reverse(_ x: Int) -> Int {
guard x >= 0 else {
return -reverse(abs(x))
}
let s = x.description
let charsReversed : [Character] = Array(s.characters).reversed()
let sreversed = charsReversed.map { $0.description }.joined(separator:"")
return Int(sreversed)!
}
XCTAssert( reverse(928374987234) == 432789473829 )
XCTAssert( reverse(-23412341423423123) == -32132432414321432 )
|
b209865863d84d28f1e4be579f69982a
| 23.03125 | 119 | 0.689207 | false | false | false | false |
GrandCentralBoard/GrandCentralBoard
|
refs/heads/develop
|
Pods/Operations/Sources/Features/Shared/Capability.swift
|
gpl-3.0
|
2
|
//
// Capability.swift
// Operations
//
// Created by Daniel Thorpe on 01/10/2015.
// Copyright © 2015 Dan Thorpe. All rights reserved.
//
import Foundation
/**
# CapabilityType
This is the high level definition for device/user/system
capabilities which typically would require the user's
permission to access. For example, location, calendars,
photos, health kit etc.
*/
public protocol CapabilityType {
/// A type which indicates the current status of the capability
associatedtype Status: AuthorizationStatusType
/// - returns: a String, the name of the capability
var name: String { get }
/**
A requirement of the capability. This is generic, and it
allows for granuality in the capabilities permissions.
For example, with Location, we either request a "when in use"
or "always" permission.
- returns: the necessary Status.Requirement
*/
var requirement: Status.Requirement { get }
/**
Initialize a new capability with the requirement and a registrar.
Implementations should provide a default registrar - it is here
to support injection & unit testing.
- parameter requirement: the needed Status.Requirement
*/
init(_ requirement: Status.Requirement)
/**
Query the capability to see if it's available on the device.
- returns: true Bool value if the capability is available.
*/
func isAvailable() -> Bool
/**
Get the current authorization status of the capability. This
can be performed asynchronously. The status is returns as the
argument to a completion block.
- parameter completion: a Status -> Void closure.
*/
func authorizationStatus(completion: Status -> Void)
/**
Request authorization with the requirement of the capability.
Again, this is designed to be performed asynchronously. More than
likely the registrar will present a dialog and wait for the user.
When control is returned, the completion block should be called.
- parameter completion: a dispatch_block_t closure.
*/
func requestAuthorizationWithCompletion(completion: dispatch_block_t)
}
/**
A protocol to define the authorization status of a device
capability. Typically this will be an enum, like
CLAuthorizationStatus. Note that it is itself generic over
the Requirement. This allows for another (or existing) enum
to be used to define granular levels of permissions. Use Void
if not needed.
*/
public protocol AuthorizationStatusType {
/// A generic type for the requirement
associatedtype Requirement
/**
Given the current authorization status (i.e. self)
this function should determine whether or not the
provided Requirement has been met or not. Therefore
this function should consider the overall authorization
state, and if *authorized* - whether the authorization
is enough for the Requirement.
- see: CLAuthorizationStatus extension for example.
- parameter requirement: the necessary Requirement
- returns: a Bool indicating whether or not the requirements are met.
*/
func isRequirementMet(requirement: Requirement) -> Bool
}
/**
Protocol for the underlying capabiltiy registrar.
*/
public protocol CapabilityRegistrarType {
/// The only requirement is that it can be initialized with
/// no parameters.
init()
}
/**
Capability is a namespace to nest as aliases the
various device capability types.
*/
public struct Capability { }
extension Capability {
/**
Some device capabilities might not have the need for
an authorization level, but still might not be available. For example
PassKit. In which case, use VoidStatus as the nested Status type.
*/
public struct VoidStatus: AuthorizationStatusType {
/// - returns: true, VoidStatus cannot fail to meet requirements.
public func isRequirementMet(requirement: Void) -> Bool {
return true
}
}
}
/**
# Get Authorization Status Operation
This is a generic operation which will get the current authorization
status for any CapabilityType.
*/
public class GetAuthorizationStatus<Capability: CapabilityType>: Operation {
/// the StatusResponse is a tuple for the capabilities availability and status
public typealias StatusResponse = (Bool, Capability.Status)
/// the Completion is a closure which receives a StatusResponse
public typealias Completion = StatusResponse -> Void
/**
After the operation has executed, this property will be set
either true or false.
- returns: a Bool indicating whether or not the capability is available.
*/
public var isAvailable: Bool? = .None
/**
After the operation has executed, this property will be set
to the current status of the capability.
- returns: a StatusResponse of the current status.
*/
public var status: Capability.Status? = .None
let capability: Capability
let completion: Completion
/**
Initialize the operation with a CapabilityType and completion. A default
completion is set which does nothing. The status is also available using
properties.
- parameter capability: the Capability.
- parameter completion: the Completion closure.
*/
public init(_ capability: Capability, completion: Completion = { _ in }) {
self.capability = capability
self.completion = completion
super.init()
name = "Get Authorization Status for \(capability.name)"
}
func determineState(completion: StatusResponse -> Void) {
isAvailable = capability.isAvailable()
capability.authorizationStatus { status in
self.status = status
completion((self.isAvailable!, self.status!))
}
}
/// The execute function required by Operation
public override func execute() {
determineState { response in
self.completion(response)
self.finish()
}
}
}
/**
# Authorize Operation
This is a generic operation which will request authorization
for any CapabilityType.
*/
public class Authorize<Capability: CapabilityType>: GetAuthorizationStatus<Capability> {
/**
Initialize the operation with a CapabilityType and completion. A default
completion is set which does nothing. The status is also available using
properties.
- parameter capability: the Capability.
- parameter completion: the Completion closure.
*/
public override init(_ capability: Capability, completion: Completion = { _ in }) {
super.init(capability, completion: completion)
name = "Authorize \(capability.name).\(capability.requirement)"
addCondition(MutuallyExclusive<Capability>())
}
/// The execute function required by Operation
public override func execute() {
capability.requestAuthorizationWithCompletion {
super.execute()
}
}
}
/**
An generic ErrorType used by the AuthorizedFor condition.
*/
public enum CapabilityError<Capability: CapabilityType>: ErrorType {
/// If the capability is not available
case NotAvailable
/// If authorization for the capability was not granted.
case AuthorizationNotGranted((Capability.Status, Capability.Status.Requirement?))
}
/**
This is a generic OperationCondition which can be used to allow or
deny operations to execute depending on the authorization status of a
capability.
By default, the condition will add an Authorize operation as a dependency
which means that potentially the user will be prompted to grant
authorization. Suppress this from happening with SilentCondition.
*/
public struct AuthorizedFor<Capability: CapabilityType>: OperationCondition {
/// - returns: a String, the name of the condition
public let name: String
/// - returns: false, is not mutually exclusive
public let isMutuallyExclusive = false
let capability: Capability
/**
Initialize the condition using a capability. For example
```swift
let myOperation = MyOperation() // etc etc
// Present the user with a permission dialog only if the authorization
// status has not yet been determined.
// If previously granted - operation will be executed with no dialog.
// If previously denied - operation will fail with
// CapabilityError<Capability.Location>.AuthorizationNotGranted
myOperation.addCondition(AuthorizedFor(Capability.Location(.WhenInUse)))
```
- parameter capability: the Capability.
*/
public init(_ capability: Capability) {
self.capability = capability
self.name = capability.name
}
/// Returns an Authorize operation as a dependency
public func dependencyForOperation(operation: Operation) -> NSOperation? {
return Authorize(capability)
}
/// Evaluated the condition
public func evaluateForOperation(operation: Operation, completion: OperationConditionResult -> Void) {
if !capability.isAvailable() {
completion(.Failed(CapabilityError<Capability>.NotAvailable))
}
else {
capability.authorizationStatus { [requirement = self.capability.requirement] status in
if status.isRequirementMet(requirement) {
completion(.Satisfied)
}
else {
completion(.Failed(CapabilityError<Capability>.AuthorizationNotGranted((status, requirement))))
}
}
}
}
}
extension Capability.VoidStatus: Equatable { }
/// Equality check for Capability.VoidStatus
public func == (_: Capability.VoidStatus, _: Capability.VoidStatus) -> Bool {
return true
}
|
030fb6d208594fb404e6aa92df95ed5c
| 29.779874 | 115 | 0.697998 | false | false | false | false |
mgingras/garagr
|
refs/heads/master
|
garagrIOS/ViewController.swift
|
mit
|
1
|
//
// ViewController.swift
// garagrIOS
//
// Created by Martin Gingras on 2014-12-01.
// Copyright (c) 2014 mgingras. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var formUsername: UITextField!
@IBOutlet weak var formPassword: UITextField!
@IBOutlet weak var feedback: UILabel!
var userId: NSNumber?
var username: NSString?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func validateUsernameAndPassword(){
if formUsername.hasText() && formPassword.hasText() {
getUserInfo(formUsername.text, formPassword: formPassword.text, handleFormInput)
}
}
func handleFormInput(isValid: Bool){
if(isValid){
self.performSegueWithIdentifier("moveToUserViewSegue", sender: self)
}
}
func getUserInfo(formUsername: String, formPassword: String, callback: (Bool)-> Void){
let url = NSURL(string: "http://localhost:3000/login?username=" + formUsername + "&password=" + formPassword)
var request = NSMutableURLRequest(URL: url!)
request.HTTPMethod = "POST"
let task = NSURLSession.sharedSession().dataTaskWithRequest(request){(data, response, error) in
println(NSString(data: data, encoding: NSUTF8StringEncoding))
var err: NSError?
var jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &err) as NSDictionary
if (err != nil) {
println("JSON Error \(err!.localizedDescription)")
}
let status: String! = jsonResult["status"] as NSString
if status != "ok" {
let message: String! = jsonResult["message"] as NSString
NSOperationQueue.mainQueue().addOperationWithBlock(){
self.feedback.text = message
callback(false)
}
} else{
NSOperationQueue.mainQueue().addOperationWithBlock(){
self.userId = jsonResult["userId"] as? NSNumber
self.username = formUsername
callback(true)
}
}
}
task.resume()
}
@IBAction func showSignUpAlert(){
showAlert("Enter details below")
}
func showAlert(message :NSString){
var alert = UIAlertController(title: "Create new account", message: message, preferredStyle: .Alert)
alert.addTextFieldWithConfigurationHandler({ (textField) -> Void in
textField.placeholder = "Username"
})
alert.addTextFieldWithConfigurationHandler({ (textField) -> Void in
textField.placeholder = "Password"
textField.secureTextEntry = true
})
alert.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel){
UIAlertAction in
})
alert.addAction(UIAlertAction(title: "OK", style: .Default, handler: { (action) -> Void in
let desiredUsername = alert.textFields![0] as UITextField
let desiredPassword = alert.textFields![1] as UITextField
if !desiredPassword.hasText() || !desiredUsername.hasText() {
self.showAlert("Please enter your desired Username and Password")
}else{
var url = NSURL(string: "http://localhost:3000/users?username=" + desiredUsername.text + "&password=" + desiredPassword.text)
var request = NSMutableURLRequest(URL: url!)
request.HTTPMethod = "POST"
let task = NSURLSession.sharedSession().dataTaskWithRequest(request){(data, response, error) in
println(NSString(data: data, encoding: NSUTF8StringEncoding))
var err: NSError?
var jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &err) as NSDictionary
if (err != nil) {
println("JSON Error \(err!.localizedDescription)")
}
let status: String! = jsonResult["status"] as NSString
if status != "ok" {
let message: String! = jsonResult["message"] as NSString
self.showAlert(message)
}else{
self.userId = jsonResult["userId"] as? NSNumber
NSOperationQueue.mainQueue().addOperationWithBlock(){
self.formUsername.text = desiredUsername.text
}
}
}
task.resume()
}
}))
self.presentViewController(alert, animated: true, completion: nil)
}
override func prepareForSegue(segue: (UIStoryboardSegue!), sender: AnyObject!) {
if segue.identifier == "moveToUserViewSegue" {
let appDelegate = UIApplication.sharedApplication().delegate as AppDelegate
appDelegate.userId = self.userId
appDelegate.username = self.username
}
}
}
|
5294819f54bfe1b8c2ec676b30d686e4
| 38.624113 | 159 | 0.578844 | false | false | false | false |
artsy/eigen
|
refs/heads/main
|
ios/Artsy/Views/Core/TextStack.swift
|
mit
|
1
|
import UIKit
class TextStack: ORStackView {
@discardableResult
func addArtistName(_ string: String) -> UILabel {
let artistNameLabel = UILabel()
artistNameLabel.text = string
artistNameLabel.font = UIFont.serifSemiBoldFont(withSize: 16)
addSubview(artistNameLabel, withTopMargin: "0", sideMargin: "0")
return artistNameLabel
}
@discardableResult
func addArtworkName(_ string: String, date: String?) -> ARArtworkTitleLabel {
let title = ARArtworkTitleLabel()
title.setTitle(string, date: date)
addSubview(title, withTopMargin: "4", sideMargin: "0")
return title
}
@discardableResult
func addSmallHeading(_ string: String, sideMargin: String = "0") -> UILabel {
let heading = ARSansSerifLabel()
heading.font = .sansSerifFont(withSize: 12)
heading.text = string
addSubview(heading, withTopMargin: "10", sideMargin: sideMargin)
return heading
}
@discardableResult
func addBigHeading(_ string: String, sideMargin: String = "0") -> UILabel {
let heading = ARSerifLabel()
heading.font = .serifFont(withSize: 26)
heading.text = string
addSubview(heading, withTopMargin: "20", sideMargin:sideMargin)
return heading
}
@discardableResult
func addSmallLineBreak(_ sideMargin: String = "0") -> UIView {
let line = UIView()
line.backgroundColor = .artsyGrayRegular()
addSubview(line, withTopMargin: "20", sideMargin: sideMargin)
line.constrainHeight("1")
return line
}
@discardableResult
func addThickLineBreak(_ sideMargin: String = "0") -> UIView {
let line = UIView()
line.backgroundColor = .black
addSubview(line, withTopMargin: "20", sideMargin: sideMargin)
line.constrainHeight("2")
return line
}
@discardableResult
func addBodyText(_ string: String, topMargin: String = "20", sideMargin: String = "0") -> UILabel {
let serif = ARSerifLabel()
serif.font = .serifFont(withSize: 16)
serif.numberOfLines = 0
serif.text = string
addSubview(serif, withTopMargin: topMargin, sideMargin: sideMargin)
return serif
}
@discardableResult
func addBodyMarkdown(_ string: MarkdownString, topMargin: String = "20", sideMargin: String = "0") -> ARTextView {
let text = ARTextView()
text.plainLinks = true
text.setMarkdownString(string)
addSubview(text, withTopMargin: topMargin, sideMargin: sideMargin)
return text
}
@discardableResult
func addLinkedBodyMarkdown(_ string: MarkdownString, topMargin: String = "20", sideMargin: String = "0") -> ARTextView {
let text = ARTextView()
text.setMarkdownString(string)
addSubview(text, withTopMargin: topMargin, sideMargin: sideMargin)
return text
}
}
|
5a5b291146eef5a0c8a109948289c634
| 34.421687 | 124 | 0.647959 | false | false | false | false |
breadwallet/breadwallet-ios
|
refs/heads/master
|
breadwallet/src/Constants/Constants.swift
|
mit
|
1
|
//
// Constants.swift
// breadwallet
//
// Created by Adrian Corscadden on 2016-10-24.
// Copyright © 2016-2019 Breadwinner AG. All rights reserved.
//
import UIKit
import WalletKit
let π: CGFloat = .pi
struct Padding {
var increment: CGFloat
subscript(multiplier: Int) -> CGFloat {
return CGFloat(multiplier) * increment
}
static var half: CGFloat {
return C.padding[1]/2.0
}
}
// swiftlint:disable type_name
/// Constants
struct C {
static let padding = Padding(increment: 8.0)
struct Sizes {
static let buttonHeight: CGFloat = 48.0
static let headerHeight: CGFloat = 48.0
static let largeHeaderHeight: CGFloat = 220.0
static let logoAspectRatio: CGFloat = 125.0/417.0
static let cutoutLogoAspectRatio: CGFloat = 342.0/553.0
static let roundedCornerRadius: CGFloat = 6.0
static let homeCellCornerRadius: CGFloat = 6.0
static let brdLogoHeight: CGFloat = 32.0
static let brdLogoTopMargin: CGFloat = E.isIPhoneX ? C.padding[9] + 35.0 : C.padding[9] + 20.0
}
static var defaultTintColor: UIColor = {
return UIView().tintColor
}()
static let animationDuration: TimeInterval = 0.3
static let secondsInDay: TimeInterval = 86400
static let secondsInMinute: TimeInterval = 60
static let maxMoney: UInt64 = 21000000*100000000
static let satoshis: UInt64 = 100000000
static let walletQueue = "com.breadwallet.walletqueue"
static let null = "(null)"
static let maxMemoLength = 250
static let feedbackEmail = "feedback@breadapp.com"
static let iosEmail = "ios@breadapp.com"
static let reviewLink = "https://itunes.apple.com/app/breadwallet-bitcoin-wallet/id885251393?action=write-review"
static var standardPort: Int {
return E.isTestnet ? 18333 : 8333
}
static let bip39CreationTime = TimeInterval(1388534400) - NSTimeIntervalSince1970
static let bCashForkBlockHeight: UInt32 = E.isTestnet ? 1155876 : 478559
static let bCashForkTimeStamp: TimeInterval = E.isTestnet ? (1501597117 - NSTimeIntervalSince1970) : (1501568580 - NSTimeIntervalSince1970)
static let txUnconfirmedHeight = Int32.max
/// Path where core library stores its persistent data
static var coreDataDirURL: URL {
let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
return documentsURL.appendingPathComponent("core-data", isDirectory: true)
}
static let consoleLogFileName = "log.txt"
static let previousConsoleLogFileName = "previouslog.txt"
// Returns the console log file path for the current instantiation of the app.
static var logFilePath: URL {
let cachesURL = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).first!
return cachesURL.appendingPathComponent(consoleLogFileName)
}
// Returns the console log file path for the previous instantiation of the app.
static var previousLogFilePath: URL {
let cachesURL = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).first!
return cachesURL.appendingPathComponent(previousConsoleLogFileName)
}
static let usdCurrencyCode = "USD"
static let euroCurrencyCode = "EUR"
static let britishPoundCurrencyCode = "GBP"
static let danishKroneCurrencyCode = "DKK"
static let erc20Prefix = "erc20:"
static var backendHost: String {
if let debugBackendHost = UserDefaults.debugBackendHost {
return debugBackendHost
} else {
return (E.isDebug || E.isTestFlight) ? "stage2.breadwallet.com" : "api.breadwallet.com"
}
}
static var webBundle: String {
if let debugWebBundle = UserDefaults.debugWebBundleName {
return debugWebBundle
} else {
// names should match AssetBundles.plist
return (E.isDebug || E.isTestFlight) ? "brd-web-3-staging" : "brd-web-3"
}
}
static var bdbHost: String {
return "api.blockset.com"
}
static let bdbClientTokenRecordId = "BlockchainDBClientID"
static let daiContractAddress = "0x89d24a6b4ccb1b6faa2625fe562bdd9a23260359"
static let daiContractCode = "DAI"
static let tusdContractAddress = "0x0000000000085d4780B73119b644AE5ecd22b376"
static let tusdContractCode = "TUSD"
static let fixerAPITokenRecordId = "FixerAPIToken"
}
enum Words {
//Returns the wordlist of the current localization
static var wordList: [NSString]? {
guard let path = Bundle.main.path(forResource: "BIP39Words", ofType: "plist") else { return nil }
return NSArray(contentsOfFile: path) as? [NSString]
}
//Returns the wordlist that matches to localization of the phrase
static func wordList(forPhrase phrase: String) -> [NSString]? {
var result = [NSString]()
Bundle.main.localizations.forEach { lang in
if let path = Bundle.main.path(forResource: "BIP39Words", ofType: "plist", inDirectory: nil, forLocalization: lang) {
if let words = NSArray(contentsOfFile: path) as? [NSString],
Account.validatePhrase(phrase, words: words.map { String($0) }) {
result = words
}
}
}
return result
}
}
|
12c4ce98bdc80639ed80e8afc47e3b2b
| 36.922535 | 143 | 0.676695 | false | false | false | false |
1d4Nf6/RazzleDazzle
|
refs/heads/develop
|
Carthage/Checkouts/Nimble/Nimble/Matchers/BeEmpty.swift
|
apache-2.0
|
45
|
import Foundation
/// A Nimble matcher that succeeds when a value is "empty". For collections, this
/// means the are no items in that collection. For strings, it is an empty string.
public func beEmpty<S: SequenceType>() -> NonNilMatcherFunc<S> {
return NonNilMatcherFunc { actualExpression, failureMessage in
failureMessage.postfixMessage = "be empty"
let actualSeq = actualExpression.evaluate()
if actualSeq == nil {
return true
}
var generator = actualSeq!.generate()
return generator.next() == nil
}
}
/// A Nimble matcher that succeeds when a value is "empty". For collections, this
/// means the are no items in that collection. For strings, it is an empty string.
public func beEmpty() -> NonNilMatcherFunc<String> {
return NonNilMatcherFunc { actualExpression, failureMessage in
failureMessage.postfixMessage = "be empty"
let actualString = actualExpression.evaluate()
return actualString == nil || (actualString! as NSString).length == 0
}
}
/// A Nimble matcher that succeeds when a value is "empty". For collections, this
/// means the are no items in that collection. For NSString instances, it is an empty string.
public func beEmpty() -> NonNilMatcherFunc<NSString> {
return NonNilMatcherFunc { actualExpression, failureMessage in
failureMessage.postfixMessage = "be empty"
let actualString = actualExpression.evaluate()
return actualString == nil || actualString!.length == 0
}
}
// Without specific overrides, beEmpty() is ambiguous for NSDictionary, NSArray,
// etc, since they conform to SequenceType as well as NMBCollection.
/// A Nimble matcher that succeeds when a value is "empty". For collections, this
/// means the are no items in that collection. For strings, it is an empty string.
public func beEmpty() -> NonNilMatcherFunc<NSDictionary> {
return NonNilMatcherFunc { actualExpression, failureMessage in
failureMessage.postfixMessage = "be empty"
let actualDictionary = actualExpression.evaluate()
return actualDictionary == nil || actualDictionary!.count == 0
}
}
/// A Nimble matcher that succeeds when a value is "empty". For collections, this
/// means the are no items in that collection. For strings, it is an empty string.
public func beEmpty() -> NonNilMatcherFunc<NSArray> {
return NonNilMatcherFunc { actualExpression, failureMessage in
failureMessage.postfixMessage = "be empty"
let actualArray = actualExpression.evaluate()
return actualArray == nil || actualArray!.count == 0
}
}
/// A Nimble matcher that succeeds when a value is "empty". For collections, this
/// means the are no items in that collection. For strings, it is an empty string.
public func beEmpty() -> NonNilMatcherFunc<NMBCollection> {
return NonNilMatcherFunc { actualExpression, failureMessage in
failureMessage.postfixMessage = "be empty"
let actual = actualExpression.evaluate()
return actual == nil || actual!.count == 0
}
}
extension NMBObjCMatcher {
public class func beEmptyMatcher() -> NMBObjCMatcher {
return NMBObjCMatcher(canMatchNil: false) { actualExpression, failureMessage in
let location = actualExpression.location
let actualValue = actualExpression.evaluate()
failureMessage.postfixMessage = "be empty"
if let value = actualValue as? NMBCollection {
let expr = Expression(expression: ({ value as NMBCollection }), location: location)
return beEmpty().matches(expr, failureMessage: failureMessage)
} else if let value = actualValue as? NSString {
let expr = Expression(expression: ({ value as String }), location: location)
return beEmpty().matches(expr, failureMessage: failureMessage)
} else if let actualValue = actualValue {
failureMessage.postfixMessage = "be empty (only works for NSArrays, NSSets, NSDictionaries, NSHashTables, and NSStrings)"
failureMessage.actualValue = "\(NSStringFromClass(actualValue.dynamicType)) type"
}
return false
}
}
}
|
e9ac752f0dd4cb26ced9cef2f93c12c5
| 45.544444 | 137 | 0.699212 | false | false | false | false |
xmkevinchen/CKMessagesKit
|
refs/heads/master
|
CKMessagesKit/Sources/Factories/CKMessagesAvatarImageFactory.swift
|
mit
|
1
|
//
// CKMessagesAvatarImageFactory.swift
// CKMessagesKit
//
// Created by Kevin Chen on 9/2/16.
// Copyright © 2016 Kevin Chen. All rights reserved.
//
import Foundation
public class CKMessagesAvatarImageFactory {
private let diameter: UInt
public init(diameter: UInt = 30) {
self.diameter = diameter
}
public func avatar(placeholder: UIImage) -> CKMessagesAvatarImage {
let image = placeholder.circular(diameter: diameter)
return CKMessagesAvatarImage.avater(placeholder: image)
}
public func avatar(image: UIImage) -> CKMessagesAvatarImage {
let normal = image.circular(diameter: diameter)
let highlighted = image.circular(diameter: diameter, highlighted: UIColor(white: 0.1, alpha: 0.3))
return CKMessagesAvatarImage(avatar: normal, highlighted: highlighted, placeholder: normal)
}
public func avatar(initials: String, backgroundColor: UIColor, textColor: UIColor, font: UIFont) -> CKMessagesAvatarImage {
let image = self.image(initials: initials, backgroundColor: backgroundColor, textColor: textColor, font: font)
let normal = image.circular(diameter: diameter)
let highlighted = image.circular(diameter: diameter, highlighted: UIColor(white: 0.1, alpha: 0.3))
return CKMessagesAvatarImage(avatar: normal, highlighted: highlighted, placeholder: normal)
}
private func image(initials: String, backgroundColor: UIColor, textColor: UIColor, font: UIFont) -> UIImage {
let frame = CGRect(x: 0, y: 0, width: Int(diameter), height: Int(diameter))
let attributes = [
NSFontAttributeName: font,
NSForegroundColorAttributeName: textColor
]
let textFrame = NSString(string: initials).boundingRect(with: frame.size,
options: [.usesLineFragmentOrigin, .usesFontLeading],
attributes: attributes,
context: nil)
let dx = frame.midX - textFrame.midX
let dy = frame.midY - textFrame.midY
let drawPoint = CGPoint(x: dx, y: dy)
UIGraphicsBeginImageContextWithOptions(frame.size, false, 0)
let context = UIGraphicsGetCurrentContext()!
context.setFillColor(backgroundColor.cgColor)
context.fill(frame)
NSString(string: initials).draw(at: drawPoint, withAttributes: attributes)
let image = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
return image
}
}
|
f53fcea6ed691599fddc0b415529affc
| 37.472222 | 127 | 0.618051 | false | false | false | false |
mrgerych/Cuckoo
|
refs/heads/master
|
Generator/Source/CuckooGeneratorFramework/Tokens/Key.swift
|
mit
|
1
|
//
// Key.swift
// CuckooGenerator
//
// Created by Filip Dolnik on 30.05.16.
// Copyright © 2016 Brightify. All rights reserved.
//
public enum Key: String {
case Substructure = "key.substructure"
case Kind = "key.kind"
case Accessibility = "key.accessibility"
case SetterAccessibility = "key.setter_accessibility"
case Name = "key.name"
case TypeName = "key.typename"
case InheritedTypes = "key.inheritedtypes"
case Length = "key.length"
case Offset = "key.offset"
case NameLength = "key.namelength"
case NameOffset = "key.nameoffset"
case BodyLength = "key.bodylength"
case BodyOffset = "key.bodyoffset"
}
|
8ab63ff26e26ec4bbda40acc88984bc5
| 25.038462 | 57 | 0.667651 | false | false | false | false |
wordpress-mobile/AztecEditor-iOS
|
refs/heads/develop
|
Example/Example/MediaInserter.swift
|
gpl-2.0
|
2
|
import Foundation
import UIKit
import Aztec
import AVFoundation
class MediaInserter
{
fileprivate var mediaErrorMode = false
struct MediaProgressKey {
static let mediaID = ProgressUserInfoKey("mediaID")
static let videoURL = ProgressUserInfoKey("videoURL")
}
let richTextView: TextView
var attachmentTextAttributes: [NSAttributedString.Key: Any]
init(textView: TextView, attachmentTextAttributes: [NSAttributedString.Key: Any]) {
self.richTextView = textView
self.attachmentTextAttributes = attachmentTextAttributes
}
func insertImage(_ image: UIImage) {
let fileURL = image.saveToTemporaryFile()
let attachment = richTextView.replaceWithImage(at: richTextView.selectedRange, sourceURL: fileURL, placeHolderImage: image)
attachment.size = .full
attachment.alignment = ImageAttachment.Alignment.none
if let attachmentRange = richTextView.textStorage.ranges(forAttachment: attachment).first {
richTextView.setLink(fileURL, inRange: attachmentRange)
}
let imageID = attachment.identifier
let progress = Progress(parent: nil, userInfo: [MediaProgressKey.mediaID: imageID])
progress.totalUnitCount = 100
Timer.scheduledTimer(timeInterval: 0.1, target: self, selector: #selector(MediaInserter.timerFireMethod(_:)), userInfo: progress, repeats: true)
}
func insertVideo(_ videoURL: URL) {
let asset = AVURLAsset(url: videoURL, options: nil)
let imgGenerator = AVAssetImageGenerator(asset: asset)
imgGenerator.appliesPreferredTrackTransform = true
guard let cgImage = try? imgGenerator.copyCGImage(at: CMTimeMake(value: 0, timescale: 1), actualTime: nil) else {
return
}
let posterImage = UIImage(cgImage: cgImage)
let posterURL = posterImage.saveToTemporaryFile()
let attachment = richTextView.replaceWithVideo(at: richTextView.selectedRange, sourceURL: URL(string:"placeholder://")!, posterURL: posterURL, placeHolderImage: posterImage)
let mediaID = attachment.identifier
let progress = Progress(parent: nil, userInfo: [MediaProgressKey.mediaID: mediaID, MediaProgressKey.videoURL:videoURL])
progress.totalUnitCount = 100
Timer.scheduledTimer(timeInterval: 0.1, target: self, selector: #selector(MediaInserter.timerFireMethod(_:)), userInfo: progress, repeats: true)
}
@objc func timerFireMethod(_ timer: Timer) {
guard let progress = timer.userInfo as? Progress,
let imageId = progress.userInfo[MediaProgressKey.mediaID] as? String,
let attachment = richTextView.attachment(withId: imageId)
else {
timer.invalidate()
return
}
progress.completedUnitCount += 1
attachment.progress = progress.fractionCompleted
if mediaErrorMode && progress.fractionCompleted >= 0.25 {
timer.invalidate()
let message = NSAttributedString(string: "Upload failed!", attributes: attachmentTextAttributes)
attachment.message = message
attachment.overlayImage = UIImage.systemImage("arrow.clockwise")
}
if progress.fractionCompleted >= 1 {
timer.invalidate()
attachment.progress = nil
if let videoAttachment = attachment as? VideoAttachment, let videoURL = progress.userInfo[MediaProgressKey.videoURL] as? URL {
videoAttachment.updateURL(videoURL, refreshAsset: false)
}
}
richTextView.refresh(attachment, overlayUpdateOnly: true)
}
}
|
c4feaceb973c0c0d0bc2cddc8611620c
| 41.964706 | 181 | 0.68839 | false | false | false | false |
See-Ku/SK4Toolkit
|
refs/heads/master
|
SK4ToolkitTests/StringExtensionTests.swift
|
mit
|
1
|
//
// StringExtensionTests.swift
// SK4Toolkit
//
// Created by See.Ku on 2016/03/30.
// Copyright (c) 2016 AxeRoad. All rights reserved.
//
import XCTest
import SK4Toolkit
class StringExtensionTests: XCTestCase {
func testString() {
let base = "12345678"
// /////////////////////////////////////////////////////////////
// sk4SubstringToIndex
// 先頭から4文字を取得
XCTAssert(base.sk4SubstringToIndex(4) == "1234")
// 先頭から0文字を取得 = ""
XCTAssert(base.sk4SubstringToIndex(0) == "")
// 文字列の長さを超えた場合、全体を返す
XCTAssert(base.sk4SubstringToIndex(12) == "12345678")
// 先頭より前を指定された場合、""を返す
XCTAssert(base.sk4SubstringToIndex(-4) == "")
// /////////////////////////////////////////////////////////////
// sk4SubstringFromIndex
// 4文字目以降を取得
XCTAssert(base.sk4SubstringFromIndex(4) == "5678")
// 0文字目以降をを取得
XCTAssert(base.sk4SubstringFromIndex(0) == "12345678")
// 文字列の長さを超えた場合""を返す
XCTAssert(base.sk4SubstringFromIndex(12) == "")
// 先頭より前を指定された場合、全体を返す
XCTAssert(base.sk4SubstringFromIndex(-4) == "12345678")
// /////////////////////////////////////////////////////////////
// sk4SubstringWithRange
// 2文字目から6文字目までを取得
XCTAssert(base.sk4SubstringWithRange(start: 2, end: 6) == "3456")
// 0文字目から4文字目までを取得
XCTAssert(base.sk4SubstringWithRange(start: 0, end: 4) == "1234")
// 4文字目から8文字目までを取得
XCTAssert(base.sk4SubstringWithRange(start: 4, end: 8) == "5678")
// 範囲外の指定は範囲内に丸める
XCTAssert(base.sk4SubstringWithRange(start: -2, end: 3) == "123")
XCTAssert(base.sk4SubstringWithRange(start: 5, end: 12) == "678")
XCTAssert(base.sk4SubstringWithRange(start: -3, end: 15) == "12345678")
// Rangeでの指定も可能
XCTAssert(base.sk4SubstringWithRange(1 ..< 4) == "234")
// /////////////////////////////////////////////////////////////
// sk4TrimSpace
// 文字列の前後から空白文字を取り除く
XCTAssert(" abc def\n ".sk4TrimSpace() == "abc def\n")
// 文字列の前後から空白文字と改行を取り除く
XCTAssert(" abc def\n ".sk4TrimSpaceNL() == "abc def")
// 全角空白も対応
XCTAssert(" どうかな? ".sk4TrimSpaceNL() == "どうかな?")
// 何も残らない場合は""になる
XCTAssert(" \n \n ".sk4TrimSpaceNL() == "")
XCTAssert("".sk4TrimSpaceNL() == "")
}
func testConvert() {
let str = "1234"
// utf8エンコードでNSDataに変換
if let data = str.sk4ToNSData() {
// println(data1)
XCTAssert(data.description == "<31323334>")
} else {
XCTFail("Fail")
}
// Base64をデコードしてNSDataに変換
if let data = str.sk4Base64Decode() {
// println(data2)
XCTAssert(data.description == "<d76df8>")
} else {
XCTFail("Fail")
}
let empty = ""
// utf8エンコードでNSDataに変換
if let data = empty.sk4ToNSData() {
XCTAssert(data.length == 0)
} else {
XCTFail("Fail")
}
// Base64をデコードしてNSDataに変換
if let data = empty.sk4Base64Decode() {
XCTAssert(data.length == 0)
} else {
XCTFail("Fail")
}
}
}
// eof
|
0324ce3ec2f26e8ca01175c33dd32072
| 22.04878 | 73 | 0.595767 | false | false | false | false |
vapor/vapor
|
refs/heads/main
|
Sources/Vapor/Concurrency/FileIO+Concurrency.swift
|
mit
|
1
|
#if compiler(>=5.5) && canImport(_Concurrency)
import NIOCore
@available(macOS 12, iOS 15, watchOS 8, tvOS 15, *)
extension FileIO {
/// Reads the contents of a file at the supplied path.
///
/// let data = try await req.fileio().read(file: "/path/to/file.txt")
/// print(data) // file data
///
/// - parameters:
/// - path: Path to file on the disk.
/// - returns: `ByteBuffer` containing the file data.
public func collectFile(at path: String) async throws -> ByteBuffer {
return try await self.collectFile(at: path).get()
}
/// Reads the contents of a file at the supplied path in chunks.
///
/// try await req.fileio().readChunked(file: "/path/to/file.txt") { chunk in
/// print("chunk: \(data)")
/// }
///
/// - parameters:
/// - path: Path to file on the disk.
/// - chunkSize: Maximum size for the file data chunks.
/// - onRead: Closure to be called sequentially for each file data chunk.
/// - returns: `Void` when the file read is finished.
// public func readFile(at path: String, chunkSize: Int = NonBlockingFileIO.defaultChunkSize, onRead: @escaping (ByteBuffer) async throws -> Void) async throws {
// // TODO
// // We should probably convert the internal private read function to async as well rather than wrapping it at this top level
// let promise = self.request.eventLoop.makePromise(of: Void.self)
// promise.completeWithTask {
// try await onRead
// }
// let closureFuture = promise.futureResult
// return try self.readFile(at: path, onRead: closureFuture).get()
// }
/// Write the contents of buffer to a file at the supplied path.
///
/// let data = ByteBuffer(string: "ByteBuffer")
/// try await req.fileio.writeFile(data, at: "/path/to/file.txt")
///
/// - parameters:
/// - path: Path to file on the disk.
/// - buffer: The `ByteBuffer` to write.
/// - returns: `Void` when the file write is finished.
public func writeFile(_ buffer: ByteBuffer, at path: String) async throws {
return try await self.writeFile(buffer, at: path).get()
}
}
#endif
|
b72e003d094c98679730577f9913418f
| 41.603774 | 165 | 0.60496 | false | false | false | false |
kesun421/firefox-ios
|
refs/heads/master
|
Client/Frontend/Browser/BrowserViewController.swift
|
mpl-2.0
|
1
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import Photos
import UIKit
import WebKit
import Shared
import Storage
import SnapKit
import XCGLogger
import Alamofire
import Account
import ReadingList
import MobileCoreServices
import SDWebImage
import SwiftyJSON
import Telemetry
import Sentry
private let KVOLoading = "loading"
private let KVOEstimatedProgress = "estimatedProgress"
private let KVOURL = "URL"
private let KVOTitle = "title"
private let KVOCanGoBack = "canGoBack"
private let KVOCanGoForward = "canGoForward"
private let KVOContentSize = "contentSize"
private let ActionSheetTitleMaxLength = 120
private struct BrowserViewControllerUX {
fileprivate static let BackgroundColor = UIConstants.AppBackgroundColor
fileprivate static let ShowHeaderTapAreaHeight: CGFloat = 32
fileprivate static let BookmarkStarAnimationDuration: Double = 0.5
fileprivate static let BookmarkStarAnimationOffset: CGFloat = 80
}
class BrowserViewController: UIViewController {
var homePanelController: HomePanelViewController?
var webViewContainer: UIView!
var urlBar: URLBarView!
var clipboardBarDisplayHandler: ClipboardBarDisplayHandler?
var readerModeBar: ReaderModeBarView?
var readerModeCache: ReaderModeCache
let webViewContainerToolbar = UIView()
var statusBarOverlay: UIView!
fileprivate(set) var toolbar: TabToolbar?
fileprivate var searchController: SearchViewController?
fileprivate var screenshotHelper: ScreenshotHelper!
fileprivate var homePanelIsInline = false
fileprivate var searchLoader: SearchLoader!
fileprivate let snackBars = UIView()
fileprivate var findInPageBar: FindInPageBar?
fileprivate let findInPageContainer = UIView()
lazy var mailtoLinkHandler: MailtoLinkHandler = MailtoLinkHandler()
lazy fileprivate var customSearchEngineButton: UIButton = {
let searchButton = UIButton()
searchButton.setImage(UIImage(named: "AddSearch")?.withRenderingMode(.alwaysTemplate), for: UIControlState())
searchButton.addTarget(self, action: #selector(BrowserViewController.addCustomSearchEngineForFocusedElement), for: .touchUpInside)
searchButton.accessibilityIdentifier = "BrowserViewController.customSearchEngineButton"
return searchButton
}()
fileprivate var customSearchBarButton: UIBarButtonItem?
// popover rotation handling
fileprivate var displayedPopoverController: UIViewController?
fileprivate var updateDisplayedPopoverProperties: (() -> Void)?
var openInHelper: OpenInHelper?
// location label actions
fileprivate var pasteGoAction: AccessibleAction!
fileprivate var pasteAction: AccessibleAction!
fileprivate var copyAddressAction: AccessibleAction!
fileprivate weak var tabTrayController: TabTrayController!
let profile: Profile
let tabManager: TabManager
// These views wrap the urlbar and toolbar to provide background effects on them
var header: UIView!
var footer: UIView!
fileprivate var topTouchArea: UIButton!
let urlBarTopTabsContainer = UIView(frame: CGRect.zero)
var topTabsVisible: Bool {
return topTabsViewController != nil
}
// Backdrop used for displaying greyed background for private tabs
var webViewContainerBackdrop: UIView!
var scrollController = TabScrollingController()
fileprivate var keyboardState: KeyboardState?
var didRemoveAllTabs: Bool = false
var pendingToast: ButtonToast? // A toast that might be waiting for BVC to appear before displaying
let WhiteListedUrls = ["\\/\\/itunes\\.apple\\.com\\/"]
// Tracking navigation items to record history types.
// TODO: weak references?
var ignoredNavigation = Set<WKNavigation>()
var typedNavigation = [WKNavigation: VisitType]()
var navigationToolbar: TabToolbarProtocol {
return toolbar ?? urlBar
}
var topTabsViewController: TopTabsViewController?
let topTabsContainer = UIView(frame: CGRect.zero)
init(profile: Profile, tabManager: TabManager) {
self.profile = profile
self.tabManager = tabManager
self.readerModeCache = DiskReaderModeCache.sharedInstance
super.init(nibName: nil, bundle: nil)
didInit()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
if UIDevice.current.userInterfaceIdiom == .phone {
return UIInterfaceOrientationMask.allButUpsideDown
} else {
return UIInterfaceOrientationMask.all
}
}
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransition(to: size, with: coordinator)
displayedPopoverController?.dismiss(animated: true) {
self.displayedPopoverController = nil
}
if let _ = self.presentedViewController as? PhotonActionSheet {
self.presentedViewController?.dismiss(animated: true, completion: nil)
}
coordinator.animate(alongsideTransition: { context in
self.scrollController.updateMinimumZoom()
self.topTabsViewController?.scrollToCurrentTab(false, centerCell: false)
if let popover = self.displayedPopoverController {
self.updateDisplayedPopoverProperties?()
self.present(popover, animated: true, completion: nil)
}
}, completion: { _ in
self.scrollController.setMinimumZoom()
})
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
fileprivate func didInit() {
screenshotHelper = ScreenshotHelper(controller: self)
tabManager.addDelegate(self)
tabManager.addNavigationDelegate(self)
}
override var preferredStatusBarStyle: UIStatusBarStyle {
let isPrivate = tabManager.selectedTab?.isPrivate ?? false
let isIpad = shouldShowTopTabsForTraitCollection(traitCollection)
return (isPrivate || isIpad) ? UIStatusBarStyle.lightContent : UIStatusBarStyle.default
}
func shouldShowFooterForTraitCollection(_ previousTraitCollection: UITraitCollection) -> Bool {
return previousTraitCollection.verticalSizeClass != .compact && previousTraitCollection.horizontalSizeClass != .regular
}
func shouldShowTopTabsForTraitCollection(_ newTraitCollection: UITraitCollection) -> Bool {
return newTraitCollection.verticalSizeClass == .regular && newTraitCollection.horizontalSizeClass == .regular
}
func toggleSnackBarVisibility(show: Bool) {
if show {
UIView.animate(withDuration: 0.1, animations: { self.snackBars.isHidden = false })
} else {
snackBars.isHidden = true
}
}
fileprivate func updateToolbarStateForTraitCollection(_ newCollection: UITraitCollection, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator? = nil) {
let showToolbar = shouldShowFooterForTraitCollection(newCollection)
let showTopTabs = shouldShowTopTabsForTraitCollection(newCollection)
urlBar.topTabsIsShowing = showTopTabs
urlBar.setShowToolbar(!showToolbar)
toolbar?.removeFromSuperview()
toolbar?.tabToolbarDelegate = nil
toolbar = nil
if showToolbar {
toolbar = TabToolbar()
footer.addSubview(toolbar!)
toolbar?.tabToolbarDelegate = self
let theme = (tabManager.selectedTab?.isPrivate ?? false) ? Theme.PrivateMode : Theme.NormalMode
toolbar?.applyTheme(theme)
updateTabCountUsingTabManager(self.tabManager)
}
if showTopTabs {
if topTabsViewController == nil {
let topTabsViewController = TopTabsViewController(tabManager: tabManager)
topTabsViewController.delegate = self
addChildViewController(topTabsViewController)
topTabsViewController.view.frame = topTabsContainer.frame
topTabsContainer.addSubview(topTabsViewController.view)
topTabsViewController.view.snp.makeConstraints { make in
make.edges.equalTo(topTabsContainer)
make.height.equalTo(TopTabsUX.TopTabsViewHeight)
}
self.topTabsViewController = topTabsViewController
}
topTabsContainer.snp.updateConstraints { make in
make.height.equalTo(TopTabsUX.TopTabsViewHeight)
}
} else {
topTabsContainer.snp.updateConstraints { make in
make.height.equalTo(0)
}
topTabsViewController?.view.removeFromSuperview()
topTabsViewController?.removeFromParentViewController()
topTabsViewController = nil
}
view.setNeedsUpdateConstraints()
if let home = homePanelController {
home.view.setNeedsUpdateConstraints()
}
if let tab = tabManager.selectedTab,
let webView = tab.webView {
updateURLBarDisplayURL(tab)
navigationToolbar.updateBackStatus(webView.canGoBack)
navigationToolbar.updateForwardStatus(webView.canGoForward)
navigationToolbar.updateReloadStatus(tab.loading)
}
}
override func willTransition(to newCollection: UITraitCollection, with coordinator: UIViewControllerTransitionCoordinator) {
super.willTransition(to: newCollection, with: coordinator)
// During split screen launching on iPad, this callback gets fired before viewDidLoad gets a chance to
// set things up. Make sure to only update the toolbar state if the view is ready for it.
if isViewLoaded {
updateToolbarStateForTraitCollection(newCollection, withTransitionCoordinator: coordinator)
}
displayedPopoverController?.dismiss(animated: true, completion: nil)
coordinator.animate(alongsideTransition: { context in
self.scrollController.showToolbars(animated: false)
if self.isViewLoaded {
self.statusBarOverlay.backgroundColor = self.shouldShowTopTabsForTraitCollection(self.traitCollection) ? UIColor(rgb: 0x272727) : self.urlBar.backgroundColor
self.setNeedsStatusBarAppearanceUpdate()
}
}, completion: nil)
}
func SELappDidEnterBackgroundNotification() {
displayedPopoverController?.dismiss(animated: false) {
self.displayedPopoverController = nil
}
}
func SELtappedTopArea() {
scrollController.showToolbars(animated: true)
}
func SELappWillResignActiveNotification() {
// Dismiss any popovers that might be visible
displayedPopoverController?.dismiss(animated: false) {
self.displayedPopoverController = nil
}
// If we are displying a private tab, hide any elements in the tab that we wouldn't want shown
// when the app is in the home switcher
guard let privateTab = tabManager.selectedTab, privateTab.isPrivate else {
return
}
webViewContainerBackdrop.alpha = 1
webViewContainer.alpha = 0
urlBar.locationContainer.alpha = 0
topTabsViewController?.switchForegroundStatus(isInForeground: false)
presentedViewController?.popoverPresentationController?.containerView?.alpha = 0
presentedViewController?.view.alpha = 0
}
func SELappDidBecomeActiveNotification() {
// Re-show any components that might have been hidden because they were being displayed
// as part of a private mode tab
UIView.animate(withDuration: 0.2, delay: 0, options: UIViewAnimationOptions(), animations: {
self.webViewContainer.alpha = 1
self.urlBar.locationContainer.alpha = 1
self.topTabsViewController?.switchForegroundStatus(isInForeground: true)
self.presentedViewController?.popoverPresentationController?.containerView?.alpha = 1
self.presentedViewController?.view.alpha = 1
self.view.backgroundColor = UIColor.clear
}, completion: { _ in
self.webViewContainerBackdrop.alpha = 0
})
// Re-show toolbar which might have been hidden during scrolling (prior to app moving into the background)
scrollController.showToolbars(animated: false)
}
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(self, selector: #selector(BrowserViewController.SELBookmarkStatusDidChange(_:)), name: NSNotification.Name(rawValue: BookmarkStatusChangedNotification), object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(BrowserViewController.SELappWillResignActiveNotification), name: NSNotification.Name.UIApplicationWillResignActive, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(BrowserViewController.SELappDidBecomeActiveNotification), name: NSNotification.Name.UIApplicationDidBecomeActive, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(BrowserViewController.SELappDidEnterBackgroundNotification), name: NSNotification.Name.UIApplicationDidEnterBackground, object: nil)
KeyboardHelper.defaultHelper.addDelegate(self)
webViewContainerBackdrop = UIView()
webViewContainerBackdrop.backgroundColor = UIColor.gray
webViewContainerBackdrop.alpha = 0
view.addSubview(webViewContainerBackdrop)
webViewContainer = UIView()
webViewContainer.addSubview(webViewContainerToolbar)
view.addSubview(webViewContainer)
// Temporary work around for covering the non-clipped web view content
statusBarOverlay = UIView()
view.addSubview(statusBarOverlay)
topTouchArea = UIButton()
topTouchArea.isAccessibilityElement = false
topTouchArea.addTarget(self, action: #selector(BrowserViewController.SELtappedTopArea), for: UIControlEvents.touchUpInside)
view.addSubview(topTouchArea)
// Setup the URL bar, wrapped in a view to get transparency effect
urlBar = URLBarView()
urlBar.translatesAutoresizingMaskIntoConstraints = false
urlBar.delegate = self
urlBar.tabToolbarDelegate = self
header = urlBarTopTabsContainer
urlBarTopTabsContainer.addSubview(urlBar)
urlBarTopTabsContainer.addSubview(topTabsContainer)
view.addSubview(header)
// UIAccessibilityCustomAction subclass holding an AccessibleAction instance does not work, thus unable to generate AccessibleActions and UIAccessibilityCustomActions "on-demand" and need to make them "persistent" e.g. by being stored in BVC
pasteGoAction = AccessibleAction(name: NSLocalizedString("Paste & Go", comment: "Paste the URL into the location bar and visit"), handler: { () -> Bool in
if let pasteboardContents = UIPasteboard.general.string {
self.urlBar(self.urlBar, didSubmitText: pasteboardContents)
return true
}
return false
})
pasteAction = AccessibleAction(name: NSLocalizedString("Paste", comment: "Paste the URL into the location bar"), handler: { () -> Bool in
if let pasteboardContents = UIPasteboard.general.string {
// Enter overlay mode and make the search controller appear.
self.urlBar.enterOverlayMode(pasteboardContents, pasted: true, search: true)
return true
}
return false
})
copyAddressAction = AccessibleAction(name: NSLocalizedString("Copy Address", comment: "Copy the URL from the location bar"), handler: { () -> Bool in
if let url = self.urlBar.currentURL {
UIPasteboard.general.url = url as URL
}
return true
})
searchLoader = SearchLoader(profile: profile, urlBar: urlBar)
footer = UIView()
self.view.addSubview(footer)
self.view.addSubview(snackBars)
snackBars.backgroundColor = UIColor.clear
self.view.addSubview(findInPageContainer)
if AppConstants.MOZ_CLIPBOARD_BAR {
clipboardBarDisplayHandler = ClipboardBarDisplayHandler(prefs: profile.prefs, tabManager: tabManager)
clipboardBarDisplayHandler?.delegate = self
}
scrollController.urlBar = urlBar
scrollController.header = header
scrollController.footer = footer
scrollController.snackBars = snackBars
scrollController.webViewContainerToolbar = webViewContainerToolbar
self.updateToolbarStateForTraitCollection(self.traitCollection)
setupConstraints()
}
fileprivate func setupConstraints() {
topTabsContainer.snp.makeConstraints { make in
make.leading.trailing.equalTo(self.header)
make.top.equalTo(urlBarTopTabsContainer)
}
urlBar.snp.makeConstraints { make in
make.leading.trailing.bottom.equalTo(urlBarTopTabsContainer)
make.height.equalTo(UIConstants.TopToolbarHeight)
make.top.equalTo(topTabsContainer.snp.bottom)
}
header.snp.makeConstraints { make in
scrollController.headerTopConstraint = make.top.equalTo(self.topLayoutGuide.snp.bottom).constraint
make.left.right.equalTo(self.view)
}
webViewContainerBackdrop.snp.makeConstraints { make in
make.edges.equalTo(webViewContainer)
}
webViewContainerToolbar.snp.makeConstraints { make in
make.left.right.top.equalTo(webViewContainer)
make.height.equalTo(0)
}
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
statusBarOverlay.snp.remakeConstraints { make in
make.top.left.right.equalTo(self.view)
make.height.equalTo(self.topLayoutGuide.length)
}
}
override var canBecomeFirstResponder: Bool {
return true
}
override func becomeFirstResponder() -> Bool {
// Make the web view the first responder so that it can show the selection menu.
return tabManager.selectedTab?.webView?.becomeFirstResponder() ?? false
}
func loadQueuedTabs(receivedURLs: [URL]? = nil) {
// Chain off of a trivial deferred in order to run on the background queue.
succeed().upon() { res in
self.dequeueQueuedTabs(receivedURLs: receivedURLs ?? [])
}
}
fileprivate func dequeueQueuedTabs(receivedURLs: [URL]) {
assert(!Thread.current.isMainThread, "This must be called in the background.")
self.profile.queue.getQueuedTabs() >>== { cursor in
// This assumes that the DB returns rows in some kind of sane order.
// It does in practice, so WFM.
if cursor.count > 0 {
// Filter out any tabs received by a push notification to prevent dupes.
let urls = cursor.flatMap { $0?.url.asURL }.filter { !receivedURLs.contains($0) }
if !urls.isEmpty {
DispatchQueue.main.async {
self.tabManager.addTabsForURLs(urls, zombie: false)
}
}
// Clear *after* making an attempt to open. We're making a bet that
// it's better to run the risk of perhaps opening twice on a crash,
// rather than losing data.
self.profile.queue.clearQueuedTabs()
}
// Then, open any received URLs from push notifications.
if !receivedURLs.isEmpty {
DispatchQueue.main.async {
let unopenedReceivedURLs = receivedURLs.filter { self.tabManager.getTabForURL($0) == nil }
self.tabManager.addTabsForURLs(unopenedReceivedURLs, zombie: false)
if let lastURL = receivedURLs.last, let tab = self.tabManager.getTabForURL(lastURL) {
self.tabManager.selectTab(tab)
}
}
}
}
}
// Because crashedLastLaunch is sticky, it does not get reset, we need to remember its
// value so that we do not keep asking the user to restore their tabs.
var displayedRestoreTabsAlert = false
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
// On iPhone, if we are about to show the On-Boarding, blank out the tab so that it does
// not flash before we present. This change of alpha also participates in the animation when
// the intro view is dismissed.
if UIDevice.current.userInterfaceIdiom == .phone {
self.view.alpha = (profile.prefs.intForKey(IntroViewControllerSeenProfileKey) != nil) ? 1.0 : 0.0
}
if !displayedRestoreTabsAlert && !cleanlyBackgrounded() && crashedLastLaunch() {
displayedRestoreTabsAlert = true
showRestoreTabsAlert()
} else {
tabManager.restoreTabs()
}
updateTabCountUsingTabManager(tabManager, animated: false)
clipboardBarDisplayHandler?.checkIfShouldDisplayBar()
}
fileprivate func crashedLastLaunch() -> Bool {
return Sentry.crashedLastLaunch
}
fileprivate func cleanlyBackgrounded() -> Bool {
guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else {
return false
}
return appDelegate.applicationCleanlyBackgrounded
}
fileprivate func showRestoreTabsAlert() {
if !canRestoreTabs() {
self.tabManager.addTabAndSelect()
return
}
let alert = UIAlertController.restoreTabsAlert(
okayCallback: { _ in
self.tabManager.restoreTabs()
self.updateTabCountUsingTabManager(self.tabManager, animated: false)
},
noCallback: { _ in
self.tabManager.addTabAndSelect()
self.updateTabCountUsingTabManager(self.tabManager, animated: false)
}
)
self.present(alert, animated: true, completion: nil)
}
fileprivate func canRestoreTabs() -> Bool {
guard let tabsToRestore = TabManager.tabsToRestore() else { return false }
return tabsToRestore.count > 0
}
override func viewDidAppear(_ animated: Bool) {
presentIntroViewController()
self.webViewContainerToolbar.isHidden = false
screenshotHelper.viewIsVisible = true
screenshotHelper.takePendingScreenshots(tabManager.tabs)
super.viewDidAppear(animated)
if shouldShowWhatsNewTab() {
// Only display if the SUMO topic has been configured in the Info.plist (present and not empty)
if let whatsNewTopic = AppInfo.whatsNewTopic, whatsNewTopic != "" {
if let whatsNewURL = SupportUtils.URLForTopic(whatsNewTopic) {
self.openURLInNewTab(whatsNewURL, isPrivileged: false)
profile.prefs.setString(AppInfo.appVersion, forKey: LatestAppVersionProfileKey)
}
}
}
if let toast = self.pendingToast {
self.pendingToast = nil
show(buttonToast: toast, afterWaiting: ButtonToastUX.ToastDelay)
}
showQueuedAlertIfAvailable()
}
fileprivate func shouldShowWhatsNewTab() -> Bool {
guard let latestMajorAppVersion = profile.prefs.stringForKey(LatestAppVersionProfileKey)?.components(separatedBy: ".").first else {
return DeviceInfo.hasConnectivity()
}
return latestMajorAppVersion != AppInfo.majorAppVersion && DeviceInfo.hasConnectivity()
}
fileprivate func showQueuedAlertIfAvailable() {
if let queuedAlertInfo = tabManager.selectedTab?.dequeueJavascriptAlertPrompt() {
let alertController = queuedAlertInfo.alertController()
alertController.delegate = self
present(alertController, animated: true, completion: nil)
}
}
override func viewWillDisappear(_ animated: Bool) {
screenshotHelper.viewIsVisible = false
super.viewWillDisappear(animated)
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
}
func resetBrowserChrome() {
// animate and reset transform for tab chrome
urlBar.updateAlphaForSubviews(1)
footer.alpha = 1
[header, footer, readerModeBar].forEach { view in
view?.transform = CGAffineTransform.identity
}
statusBarOverlay.isHidden = false
}
override func updateViewConstraints() {
super.updateViewConstraints()
topTouchArea.snp.remakeConstraints { make in
make.top.left.right.equalTo(self.view)
make.height.equalTo(BrowserViewControllerUX.ShowHeaderTapAreaHeight)
}
readerModeBar?.snp.remakeConstraints { make in
make.top.equalTo(self.header.snp.bottom)
make.height.equalTo(UIConstants.ToolbarHeight)
make.leading.trailing.equalTo(self.view)
}
webViewContainer.snp.remakeConstraints { make in
make.left.right.equalTo(self.view)
if let readerModeBarBottom = readerModeBar?.snp.bottom {
make.top.equalTo(readerModeBarBottom)
} else {
make.top.equalTo(self.header.snp.bottom)
}
let findInPageHeight = (findInPageBar == nil) ? 0 : UIConstants.ToolbarHeight
if let toolbar = self.toolbar {
make.bottom.equalTo(toolbar.snp.top).offset(-findInPageHeight)
} else {
make.bottom.equalTo(self.view).offset(-findInPageHeight)
}
}
// Setup the bottom toolbar
toolbar?.snp.remakeConstraints { make in
make.edges.equalTo(self.footer)
make.height.equalTo(UIConstants.BottomToolbarHeight)
}
footer.snp.remakeConstraints { make in
scrollController.footerBottomConstraint = make.bottom.equalTo(self.view.snp.bottom).constraint
make.leading.trailing.equalTo(self.view)
}
updateSnackBarConstraints()
urlBar.setNeedsUpdateConstraints()
// Remake constraints even if we're already showing the home controller.
// The home controller may change sizes if we tap the URL bar while on about:home.
homePanelController?.view.snp.remakeConstraints { make in
make.top.equalTo(self.urlBar.snp.bottom)
make.left.right.equalTo(self.view)
if self.homePanelIsInline {
make.bottom.equalTo(self.toolbar?.snp.top ?? self.view.snp.bottom)
} else {
make.bottom.equalTo(self.view.snp.bottom)
}
}
findInPageContainer.snp.remakeConstraints { make in
make.left.right.equalTo(self.view)
if let keyboardHeight = keyboardState?.intersectionHeightForView(self.view), keyboardHeight > 0 {
make.bottom.equalTo(self.view).offset(-keyboardHeight)
} else if let toolbar = self.toolbar {
make.bottom.equalTo(toolbar.snp.top)
} else {
make.bottom.equalTo(self.view)
}
}
}
fileprivate func showHomePanelController(inline: Bool) {
homePanelIsInline = inline
if homePanelController == nil {
let homePanelController = HomePanelViewController()
homePanelController.profile = profile
homePanelController.delegate = self
homePanelController.url = tabManager.selectedTab?.url?.displayURL
homePanelController.view.alpha = 0
self.homePanelController = homePanelController
addChildViewController(homePanelController)
view.addSubview(homePanelController.view)
homePanelController.didMove(toParentViewController: self)
}
guard let homePanelController = self.homePanelController else {
assertionFailure("homePanelController is still nil after assignment.")
return
}
let isPrivate = tabManager.selectedTab?.isPrivate ?? false
homePanelController.applyTheme(isPrivate ? Theme.PrivateMode : Theme.NormalMode)
let panelNumber = tabManager.selectedTab?.url?.fragment
// splitting this out to see if we can get better crash reports when this has a problem
var newSelectedButtonIndex = 0
if let numberArray = panelNumber?.components(separatedBy: "=") {
if let last = numberArray.last, let lastInt = Int(last) {
newSelectedButtonIndex = lastInt
}
}
homePanelController.selectedPanel = HomePanelType(rawValue: newSelectedButtonIndex)
// We have to run this animation, even if the view is already showing because there may be a hide animation running
// and we want to be sure to override its results.
UIView.animate(withDuration: 0.2, animations: { () -> Void in
homePanelController.view.alpha = 1
}, completion: { finished in
if finished {
self.webViewContainer.accessibilityElementsHidden = true
UIAccessibilityPostNotification(UIAccessibilityScreenChangedNotification, nil)
}
})
view.setNeedsUpdateConstraints()
}
fileprivate func hideHomePanelController() {
if let controller = homePanelController {
self.homePanelController = nil
UIView.animate(withDuration: 0.2, delay: 0, options: .beginFromCurrentState, animations: { () -> Void in
controller.view.alpha = 0
}, completion: { _ in
controller.willMove(toParentViewController: nil)
controller.view.removeFromSuperview()
controller.removeFromParentViewController()
self.webViewContainer.accessibilityElementsHidden = false
UIAccessibilityPostNotification(UIAccessibilityScreenChangedNotification, nil)
// Refresh the reading view toolbar since the article record may have changed
if let readerMode = self.tabManager.selectedTab?.getHelper(name: ReaderMode.name()) as? ReaderMode, readerMode.state == .active {
self.showReaderModeBar(animated: false)
}
})
}
}
fileprivate func updateInContentHomePanel(_ url: URL?) {
if !urlBar.inOverlayMode {
guard let url = url else {
hideHomePanelController()
return
}
if url.isAboutHomeURL {
showHomePanelController(inline: true)
} else if !url.isLocalUtility || url.isReaderModeURL {
hideHomePanelController()
}
}
}
fileprivate func showSearchController() {
if searchController != nil {
return
}
let isPrivate = tabManager.selectedTab?.isPrivate ?? false
searchController = SearchViewController(isPrivate: isPrivate)
searchController!.searchEngines = profile.searchEngines
searchController!.searchDelegate = self
searchController!.profile = self.profile
searchLoader.addListener(searchController!)
addChildViewController(searchController!)
view.addSubview(searchController!.view)
searchController!.view.snp.makeConstraints { make in
make.top.equalTo(self.urlBar.snp.bottom)
make.left.right.bottom.equalTo(self.view)
return
}
homePanelController?.view?.isHidden = true
searchController!.didMove(toParentViewController: self)
}
fileprivate func hideSearchController() {
if let searchController = searchController {
searchController.willMove(toParentViewController: nil)
searchController.view.removeFromSuperview()
searchController.removeFromParentViewController()
self.searchController = nil
homePanelController?.view?.isHidden = false
}
}
fileprivate func finishEditingAndSubmit(_ url: URL, visitType: VisitType) {
urlBar.currentURL = url
urlBar.leaveOverlayMode()
guard let tab = tabManager.selectedTab else {
return
}
if let webView = tab.webView {
resetSpoofedUserAgentIfRequired(webView, newURL: url)
}
if let nav = tab.loadRequest(PrivilegedRequest(url: url) as URLRequest) {
self.recordNavigationInTab(tab, navigation: nav, visitType: visitType)
}
}
func addBookmark(_ tabState: TabState) {
guard let url = tabState.url else { return }
let absoluteString = url.absoluteString
let shareItem = ShareItem(url: absoluteString, title: tabState.title, favicon: tabState.favicon)
profile.bookmarks.shareItem(shareItem)
var userData = [QuickActions.TabURLKey: shareItem.url]
if let title = shareItem.title {
userData[QuickActions.TabTitleKey] = title
}
QuickActions.sharedInstance.addDynamicApplicationShortcutItemOfType(.openLastBookmark,
withUserData: userData,
toApplication: UIApplication.shared)
if let tab = tabManager.getTabForURL(url) {
tab.isBookmarked = true
}
}
func SELBookmarkStatusDidChange(_ notification: Notification) {
if let bookmark = notification.object as? BookmarkItem {
if bookmark.url == urlBar.currentURL?.absoluteString {
if let userInfo = notification.userInfo as? Dictionary<String, Bool> {
if userInfo["added"] != nil {
if let tab = self.tabManager.getTabForURL(urlBar.currentURL!) {
tab.isBookmarked = false
}
}
}
}
}
}
override func accessibilityPerformEscape() -> Bool {
if urlBar.inOverlayMode {
urlBar.SELdidClickCancel()
return true
} else if let selectedTab = tabManager.selectedTab, selectedTab.canGoBack {
selectedTab.goBack()
return true
}
return false
}
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey: Any]?, context: UnsafeMutableRawPointer?) {
let webView = object as! WKWebView
guard let path = keyPath else { assertionFailure("Unhandled KVO key: \(keyPath ?? "nil")"); return }
switch path {
case KVOEstimatedProgress:
guard webView == tabManager.selectedTab?.webView,
let progress = change?[NSKeyValueChangeKey.newKey] as? Float else { break }
if !(webView.url?.isLocalUtility ?? false) {
urlBar.updateProgressBar(progress)
} else {
urlBar.hideProgressBar()
}
case KVOLoading:
guard let loading = change?[NSKeyValueChangeKey.newKey] as? Bool else { break }
if webView == tabManager.selectedTab?.webView {
navigationToolbar.updateReloadStatus(loading)
}
if !loading {
runScriptsOnWebView(webView)
}
case KVOURL:
guard let tab = tabManager[webView] else { break }
// To prevent spoofing, only change the URL immediately if the new URL is on
// the same origin as the current URL. Otherwise, do nothing and wait for
// didCommitNavigation to confirm the page load.
if tab.url?.origin == webView.url?.origin {
tab.url = webView.url
if tab === tabManager.selectedTab && !tab.restoring {
updateUIForReaderHomeStateForTab(tab)
}
}
case KVOTitle:
guard let tab = tabManager[webView] else { break }
// Ensure that the tab title *actually* changed to prevent repeated calls
// to navigateInTab(tab:).
guard let title = tab.title else { break }
if !title.isEmpty && title != tab.lastTitle {
navigateInTab(tab: tab)
}
case KVOCanGoBack:
guard webView == tabManager.selectedTab?.webView,
let canGoBack = change?[NSKeyValueChangeKey.newKey] as? Bool else { break }
navigationToolbar.updateBackStatus(canGoBack)
case KVOCanGoForward:
guard webView == tabManager.selectedTab?.webView,
let canGoForward = change?[NSKeyValueChangeKey.newKey] as? Bool else { break }
navigationToolbar.updateForwardStatus(canGoForward)
default:
assertionFailure("Unhandled KVO key: \(keyPath ?? "nil")")
}
}
fileprivate func runScriptsOnWebView(_ webView: WKWebView) {
webView.evaluateJavaScript("__firefox__.favicons.getFavicons()", completionHandler: nil)
webView.evaluateJavaScript("__firefox__.metadata.extractMetadata()", completionHandler: nil)
if #available(iOS 11, *) {
if NoImageModeHelper.isActivated(profile.prefs) {
webView.evaluateJavaScript("__firefox__.NoImageMode.setEnabled(true)", completionHandler: nil)
}
}
}
func updateUIForReaderHomeStateForTab(_ tab: Tab) {
updateURLBarDisplayURL(tab)
scrollController.showToolbars(animated: false)
if let url = tab.url {
if url.isReaderModeURL {
showReaderModeBar(animated: false)
NotificationCenter.default.addObserver(self, selector: #selector(BrowserViewController.SELDynamicFontChanged(_:)), name: NotificationDynamicFontChanged, object: nil)
} else {
hideReaderModeBar(animated: false)
NotificationCenter.default.removeObserver(self, name: NotificationDynamicFontChanged, object: nil)
}
updateInContentHomePanel(url as URL)
}
}
fileprivate func isWhitelistedUrl(_ url: URL) -> Bool {
for entry in WhiteListedUrls {
if let _ = url.absoluteString.range(of: entry, options: .regularExpression) {
return UIApplication.shared.canOpenURL(url)
}
}
return false
}
/// Updates the URL bar text and button states.
/// Call this whenever the page URL changes.
fileprivate func updateURLBarDisplayURL(_ tab: Tab) {
urlBar.currentURL = tab.url?.displayURL
let isPage = tab.url?.displayURL?.isWebPage() ?? false
navigationToolbar.updatePageStatus(isPage)
guard let url = tab.url?.displayURL?.absoluteString else {
return
}
profile.bookmarks.modelFactory >>== {
$0.isBookmarked(url).uponQueue(DispatchQueue.main) { [weak tab] result in
guard let bookmarked = result.successValue else {
print("Error getting bookmark status: \(result.failureValue ??? "nil").")
return
}
tab?.isBookmarked = bookmarked
}
}
}
// MARK: Opening New Tabs
func switchToPrivacyMode(isPrivate: Bool ) {
// applyTheme(isPrivate ? Theme.PrivateMode : Theme.NormalMode)
let tabTrayController = self.tabTrayController ?? TabTrayController(tabManager: tabManager, profile: profile, tabTrayDelegate: self)
if tabTrayController.privateMode != isPrivate {
tabTrayController.changePrivacyMode(isPrivate)
}
self.tabTrayController = tabTrayController
}
func switchToTabForURLOrOpen(_ url: URL, isPrivate: Bool = false, isPrivileged: Bool) {
popToBVC()
if let tab = tabManager.getTabForURL(url) {
tabManager.selectTab(tab)
} else {
openURLInNewTab(url, isPrivate: isPrivate, isPrivileged: isPrivileged)
}
}
func openURLInNewTab(_ url: URL?, isPrivate: Bool = false, isPrivileged: Bool) {
if let selectedTab = tabManager.selectedTab {
screenshotHelper.takeScreenshot(selectedTab)
}
let request: URLRequest?
if let url = url {
request = isPrivileged ? PrivilegedRequest(url: url) as URLRequest : URLRequest(url: url)
} else {
request = nil
}
switchToPrivacyMode(isPrivate: isPrivate)
_ = tabManager.addTabAndSelect(request, isPrivate: isPrivate)
if url == nil && NewTabAccessors.getNewTabPage(profile.prefs) == .blankPage {
urlBar.tabLocationViewDidTapLocation(urlBar.locationView)
}
}
func openBlankNewTab(focusLocationField: Bool, isPrivate: Bool = false) {
popToBVC()
openURLInNewTab(nil, isPrivate: isPrivate, isPrivileged: true)
if focusLocationField {
DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(300)) {
// Without a delay, the text field fails to become first responder
self.urlBar.tabLocationViewDidTapLocation(self.urlBar.locationView)
}
}
}
fileprivate func popToBVC() {
guard let currentViewController = navigationController?.topViewController else {
return
}
currentViewController.dismiss(animated: true, completion: nil)
if currentViewController != self {
_ = self.navigationController?.popViewController(animated: true)
} else if urlBar.inOverlayMode {
urlBar.SELdidClickCancel()
}
}
// MARK: User Agent Spoofing
func resetSpoofedUserAgentIfRequired(_ webView: WKWebView, newURL: URL) {
// Reset the UA when a different domain is being loaded
if webView.url?.host != newURL.host {
webView.customUserAgent = nil
}
}
func restoreSpoofedUserAgentIfRequired(_ webView: WKWebView, newRequest: URLRequest) {
// Restore any non-default UA from the request's header
let ua = newRequest.value(forHTTPHeaderField: "User-Agent")
webView.customUserAgent = ua != UserAgent.defaultUserAgent() ? ua : nil
}
fileprivate func presentActivityViewController(_ url: URL, tab: Tab? = nil, sourceView: UIView?, sourceRect: CGRect, arrowDirection: UIPopoverArrowDirection) {
let helper = ShareExtensionHelper(url: url, tab: tab)
let controller = helper.createActivityViewController({ [unowned self] completed, _ in
// After dismissing, check to see if there were any prompts we queued up
self.showQueuedAlertIfAvailable()
// Usually the popover delegate would handle nil'ing out the references we have to it
// on the BVC when displaying as a popover but the delegate method doesn't seem to be
// invoked on iOS 10. See Bug 1297768 for additional details.
self.displayedPopoverController = nil
self.updateDisplayedPopoverProperties = nil
})
if let popoverPresentationController = controller.popoverPresentationController {
popoverPresentationController.sourceView = sourceView
popoverPresentationController.sourceRect = sourceRect
popoverPresentationController.permittedArrowDirections = arrowDirection
popoverPresentationController.delegate = self
}
present(controller, animated: true, completion: nil)
LeanplumIntegration.sharedInstance.track(eventName: .userSharedWebpage)
}
func updateFindInPageVisibility(visible: Bool) {
if visible {
if findInPageBar == nil {
let findInPageBar = FindInPageBar()
self.findInPageBar = findInPageBar
findInPageBar.delegate = self
findInPageContainer.addSubview(findInPageBar)
findInPageBar.snp.makeConstraints { make in
make.edges.equalTo(findInPageContainer)
make.height.equalTo(UIConstants.ToolbarHeight)
}
updateViewConstraints()
// We make the find-in-page bar the first responder below, causing the keyboard delegates
// to fire. This, in turn, will animate the Find in Page container since we use the same
// delegate to slide the bar up and down with the keyboard. We don't want to animate the
// constraints added above, however, so force a layout now to prevent these constraints
// from being lumped in with the keyboard animation.
findInPageBar.layoutIfNeeded()
}
self.findInPageBar?.becomeFirstResponder()
} else if let findInPageBar = self.findInPageBar {
findInPageBar.endEditing(true)
guard let webView = tabManager.selectedTab?.webView else { return }
webView.evaluateJavaScript("__firefox__.findDone()", completionHandler: nil)
findInPageBar.removeFromSuperview()
self.findInPageBar = nil
updateViewConstraints()
}
}
@objc fileprivate func openSettings() {
assert(Thread.isMainThread, "Opening settings requires being invoked on the main thread")
let settingsTableViewController = AppSettingsTableViewController()
settingsTableViewController.profile = profile
settingsTableViewController.tabManager = tabManager
settingsTableViewController.settingsDelegate = self
let controller = SettingsNavigationController(rootViewController: settingsTableViewController)
controller.popoverDelegate = self
controller.modalPresentationStyle = UIModalPresentationStyle.formSheet
self.present(controller, animated: true, completion: nil)
}
fileprivate func postLocationChangeNotificationForTab(_ tab: Tab, navigation: WKNavigation?) {
let notificationCenter = NotificationCenter.default
var info = [AnyHashable: Any]()
info["url"] = tab.url?.displayURL
info["title"] = tab.title
if let visitType = self.getVisitTypeForTab(tab, navigation: navigation)?.rawValue {
info["visitType"] = visitType
}
info["isPrivate"] = tab.isPrivate
notificationCenter.post(name: NotificationOnLocationChange, object: self, userInfo: info)
}
func navigateInTab(tab: Tab, to navigation: WKNavigation? = nil) {
tabManager.expireSnackbars()
guard let webView = tab.webView else {
print("Cannot navigate in tab without a webView")
return
}
if let url = webView.url, !url.isErrorPageURL && !url.isAboutHomeURL {
tab.lastExecutedTime = Date.now()
postLocationChangeNotificationForTab(tab, navigation: navigation)
// Fire the readability check. This is here and not in the pageShow event handler in ReaderMode.js anymore
// because that event wil not always fire due to unreliable page caching. This will either let us know that
// the currently loaded page can be turned into reading mode or if the page already is in reading mode. We
// ignore the result because we are being called back asynchronous when the readermode status changes.
webView.evaluateJavaScript("\(ReaderModeNamespace).checkReadability()", completionHandler: nil)
// Re-run additional scripts in webView to extract updated favicons and metadata.
runScriptsOnWebView(webView)
}
if tab === tabManager.selectedTab {
UIAccessibilityPostNotification(UIAccessibilityScreenChangedNotification, nil)
// must be followed by LayoutChanged, as ScreenChanged will make VoiceOver
// cursor land on the correct initial element, but if not followed by LayoutChanged,
// VoiceOver will sometimes be stuck on the element, not allowing user to move
// forward/backward. Strange, but LayoutChanged fixes that.
UIAccessibilityPostNotification(UIAccessibilityLayoutChangedNotification, nil)
} else {
// To Screenshot a tab that is hidden we must add the webView,
// then wait enough time for the webview to render.
if let webView = tab.webView {
view.insertSubview(webView, at: 0)
DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(500)) {
self.screenshotHelper.takeScreenshot(tab)
if webView.superview == self.view {
webView.removeFromSuperview()
}
}
}
}
// Remember whether or not a desktop site was requested
tab.desktopSite = webView.customUserAgent?.isEmpty == false
}
// MARK: open in helper utils
func addViewForOpenInHelper(_ openInHelper: OpenInHelper) {
guard let view = openInHelper.openInView else { return }
webViewContainerToolbar.addSubview(view)
webViewContainerToolbar.snp.updateConstraints { make in
make.height.equalTo(OpenInViewUX.ViewHeight)
}
view.snp.makeConstraints { make in
make.edges.equalTo(webViewContainerToolbar)
}
self.openInHelper = openInHelper
}
func removeOpenInView() {
guard let _ = self.openInHelper else { return }
webViewContainerToolbar.subviews.forEach { $0.removeFromSuperview() }
webViewContainerToolbar.snp.updateConstraints { make in
make.height.equalTo(0)
}
self.openInHelper = nil
}
}
extension BrowserViewController: ClipboardBarDisplayHandlerDelegate {
func shouldDisplay(clipboardBar bar: ButtonToast) {
show(buttonToast: bar, duration: ClipboardBarToastUX.ToastDelay)
}
}
extension BrowserViewController: QRCodeViewControllerDelegate {
func scanSuccessOpenNewTabWithData(data: String) {
self.openBlankNewTab(focusLocationField: false)
self.urlBar(self.urlBar, didSubmitText: data)
}
}
extension BrowserViewController: SettingsDelegate {
func settingsOpenURLInNewTab(_ url: URL) {
self.openURLInNewTab(url, isPrivileged: false)
}
}
extension BrowserViewController: PresentingModalViewControllerDelegate {
func dismissPresentedModalViewController(_ modalViewController: UIViewController, animated: Bool) {
self.dismiss(animated: animated, completion: nil)
}
}
/**
* History visit management.
* TODO: this should be expanded to track various visit types; see Bug 1166084.
*/
extension BrowserViewController {
func ignoreNavigationInTab(_ tab: Tab, navigation: WKNavigation) {
self.ignoredNavigation.insert(navigation)
}
func recordNavigationInTab(_ tab: Tab, navigation: WKNavigation, visitType: VisitType) {
self.typedNavigation[navigation] = visitType
}
/**
* Untrack and do the right thing.
*/
func getVisitTypeForTab(_ tab: Tab, navigation: WKNavigation?) -> VisitType? {
guard let navigation = navigation else {
// See https://github.com/WebKit/webkit/blob/master/Source/WebKit2/UIProcess/Cocoa/NavigationState.mm#L390
return VisitType.link
}
if let _ = self.ignoredNavigation.remove(navigation) {
return nil
}
return self.typedNavigation.removeValue(forKey: navigation) ?? VisitType.link
}
}
extension BrowserViewController: URLBarDelegate {
func showTabTray() {
webViewContainerToolbar.isHidden = true
updateFindInPageVisibility(visible: false)
let tabTrayController = TabTrayController(tabManager: tabManager, profile: profile, tabTrayDelegate: self)
if let tab = tabManager.selectedTab {
screenshotHelper.takeScreenshot(tab)
}
navigationController?.pushViewController(tabTrayController, animated: true)
self.tabTrayController = tabTrayController
}
func urlBarDidPressReload(_ urlBar: URLBarView) {
tabManager.selectedTab?.reload()
}
func urlBarDidPressQRButton(_ urlBar: URLBarView) {
let qrCodeViewController = QRCodeViewController()
qrCodeViewController.qrCodeDelegate = self
let controller = QRCodeNavigationController(rootViewController: qrCodeViewController)
self.present(controller, animated: true, completion: nil)
}
func urlBarDidPressPageOptions(_ urlBar: URLBarView, from button: UIButton) {
let actionMenuPresenter: (URL, Tab, UIView, UIPopoverArrowDirection) -> Void = { (url, tab, view, _) in
self.presentActivityViewController(url, tab: tab, sourceView: view, sourceRect: view.bounds, arrowDirection: .up)
}
let findInPageAction = {
self.updateFindInPageVisibility(visible: true)
}
let successCallback: (String) -> Void = { (successMessage) in
SimpleToast().showAlertWithText(successMessage, bottomContainer: self.webViewContainer)
}
guard let tab = tabManager.selectedTab, tab.url != nil else { return }
// The logic of which actions appear when isnt final.
let pageActions = getTabActions(tab: tab, buttonView: button, presentShareMenu: actionMenuPresenter,
findInPage: findInPageAction, presentableVC: self, success: successCallback)
presentSheetWith(actions: pageActions, on: self, from: button)
}
func urlBarDidLongPressPageOptions(_ urlBar: URLBarView, from button: UIButton) {
guard let tab = tabManager.selectedTab else { return }
guard let url = tab.canonicalURL?.displayURL else { return }
presentActivityViewController(url, tab: tab, sourceView: button, sourceRect: button.bounds, arrowDirection: .up)
}
func urlBarDidPressStop(_ urlBar: URLBarView) {
tabManager.selectedTab?.stop()
}
func urlBarDidPressTabs(_ urlBar: URLBarView) {
showTabTray()
}
func urlBarDidPressReaderMode(_ urlBar: URLBarView) {
if let tab = tabManager.selectedTab {
if let readerMode = tab.getHelper(name: "ReaderMode") as? ReaderMode {
switch readerMode.state {
case .available:
enableReaderMode()
LeanplumIntegration.sharedInstance.track(eventName: .useReaderView)
case .active:
disableReaderMode()
case .unavailable:
break
}
}
}
}
func urlBarDidLongPressReaderMode(_ urlBar: URLBarView) -> Bool {
guard let tab = tabManager.selectedTab,
let url = tab.url?.displayURL,
let result = profile.readingList?.createRecordWithURL(url.absoluteString, title: tab.title ?? "", addedBy: UIDevice.current.name)
else {
UIAccessibilityPostNotification(UIAccessibilityAnnouncementNotification, NSLocalizedString("Could not add page to Reading list", comment: "Accessibility message e.g. spoken by VoiceOver after adding current webpage to the Reading List failed."))
return false
}
switch result {
case .success:
UIAccessibilityPostNotification(UIAccessibilityAnnouncementNotification, NSLocalizedString("Added page to Reading List", comment: "Accessibility message e.g. spoken by VoiceOver after the current page gets added to the Reading List using the Reader View button, e.g. by long-pressing it or by its accessibility custom action."))
// TODO: https://bugzilla.mozilla.org/show_bug.cgi?id=1158503 provide some form of 'this has been added' visual feedback?
case .failure(let error):
UIAccessibilityPostNotification(UIAccessibilityAnnouncementNotification, NSLocalizedString("Could not add page to Reading List. Maybe it’s already there?", comment: "Accessibility message e.g. spoken by VoiceOver after the user wanted to add current page to the Reading List and this was not done, likely because it already was in the Reading List, but perhaps also because of real failures."))
print("readingList.createRecordWithURL(url: \"\(url.absoluteString)\", ...) failed with error: \(error)")
}
return true
}
func locationActionsForURLBar(_ urlBar: URLBarView) -> [AccessibleAction] {
if UIPasteboard.general.string != nil {
return [pasteGoAction, pasteAction, copyAddressAction]
} else {
return [copyAddressAction]
}
}
func urlBarDisplayTextForURL(_ url: URL?) -> (String?, Bool) {
// use the initial value for the URL so we can do proper pattern matching with search URLs
var searchURL = self.tabManager.selectedTab?.currentInitialURL
if searchURL?.isErrorPageURL ?? true {
searchURL = url
}
if let query = profile.searchEngines.queryForSearchURL(searchURL as URL?) {
return (query, true)
} else {
return (url?.absoluteString, false)
}
}
func urlBarDidLongPressLocation(_ urlBar: URLBarView) {
let longPressAlertController = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
for action in locationActionsForURLBar(urlBar) {
longPressAlertController.addAction(action.alertAction(style: .default))
}
let cancelAction = UIAlertAction(title: NSLocalizedString("Cancel", comment: "Label for Cancel button"), style: .cancel, handler: { (alert: UIAlertAction) -> Void in
})
longPressAlertController.addAction(cancelAction)
let setupPopover = { [unowned self] in
if let popoverPresentationController = longPressAlertController.popoverPresentationController {
popoverPresentationController.sourceView = urlBar
popoverPresentationController.sourceRect = urlBar.frame
popoverPresentationController.permittedArrowDirections = .any
popoverPresentationController.delegate = self
}
}
setupPopover()
if longPressAlertController.popoverPresentationController != nil {
displayedPopoverController = longPressAlertController
updateDisplayedPopoverProperties = setupPopover
}
self.present(longPressAlertController, animated: true, completion: nil)
}
func urlBarDidPressScrollToTop(_ urlBar: URLBarView) {
if let selectedTab = tabManager.selectedTab {
// Only scroll to top if we are not showing the home view controller
if homePanelController == nil {
selectedTab.webView?.scrollView.setContentOffset(CGPoint.zero, animated: true)
}
}
}
func urlBarLocationAccessibilityActions(_ urlBar: URLBarView) -> [UIAccessibilityCustomAction]? {
return locationActionsForURLBar(urlBar).map { $0.accessibilityCustomAction }
}
func urlBar(_ urlBar: URLBarView, didEnterText text: String) {
searchLoader.query = text
if text.isEmpty {
hideSearchController()
} else {
showSearchController()
searchController!.searchQuery = text
}
}
func urlBar(_ urlBar: URLBarView, didSubmitText text: String) {
if let fixupURL = URIFixup.getURL(text) {
// The user entered a URL, so use it.
finishEditingAndSubmit(fixupURL, visitType: VisitType.typed)
return
}
// We couldn't build a URL, so check for a matching search keyword.
let trimmedText = text.trimmingCharacters(in: CharacterSet.whitespaces)
guard let possibleKeywordQuerySeparatorSpace = trimmedText.characters.index(of: " ") else {
submitSearchText(text)
return
}
let possibleKeyword = trimmedText.substring(to: possibleKeywordQuerySeparatorSpace)
let possibleQuery = trimmedText.substring(from: trimmedText.index(after: possibleKeywordQuerySeparatorSpace))
profile.bookmarks.getURLForKeywordSearch(possibleKeyword).uponQueue(DispatchQueue.main) { result in
if var urlString = result.successValue,
let escapedQuery = possibleQuery.addingPercentEncoding(withAllowedCharacters: NSCharacterSet.urlQueryAllowed),
let range = urlString.range(of: "%s") {
urlString.replaceSubrange(range, with: escapedQuery)
if let url = URL(string: urlString) {
self.finishEditingAndSubmit(url, visitType: VisitType.typed)
return
}
}
self.submitSearchText(text)
}
}
fileprivate func submitSearchText(_ text: String) {
let engine = profile.searchEngines.defaultEngine
if let searchURL = engine.searchURLForQuery(text) {
// We couldn't find a matching search keyword, so do a search query.
Telemetry.default.recordSearch(location: .actionBar, searchEngine: engine.engineID ?? "other")
finishEditingAndSubmit(searchURL, visitType: VisitType.typed)
} else {
// We still don't have a valid URL, so something is broken. Give up.
print("Error handling URL entry: \"\(text)\".")
assertionFailure("Couldn't generate search URL: \(text)")
}
}
func urlBarDidEnterOverlayMode(_ urlBar: URLBarView) {
if .blankPage == NewTabAccessors.getNewTabPage(profile.prefs) {
UIAccessibilityPostNotification(UIAccessibilityScreenChangedNotification, nil)
} else {
if let toast = clipboardBarDisplayHandler?.clipboardToast {
toast.removeFromSuperview()
}
showHomePanelController(inline: false)
}
LeanplumIntegration.sharedInstance.track(eventName: .interactWithURLBar)
}
func urlBarDidLeaveOverlayMode(_ urlBar: URLBarView) {
hideSearchController()
updateInContentHomePanel(tabManager.selectedTab?.url as URL?)
}
}
extension BrowserViewController: TabToolbarDelegate, PhotonActionSheetProtocol {
func tabToolbarDidPressBack(_ tabToolbar: TabToolbarProtocol, button: UIButton) {
tabManager.selectedTab?.goBack()
}
func tabToolbarDidLongPressBack(_ tabToolbar: TabToolbarProtocol, button: UIButton) {
showBackForwardList()
}
func tabToolbarDidPressReload(_ tabToolbar: TabToolbarProtocol, button: UIButton) {
tabManager.selectedTab?.reload()
}
func tabToolbarDidLongPressReload(_ tabToolbar: TabToolbarProtocol, button: UIButton) {
guard let tab = tabManager.selectedTab, tab.webView?.url != nil && (tab.getHelper(name: ReaderMode.name()) as? ReaderMode)?.state != .active else {
return
}
let toggleActionTitle: String
if tab.desktopSite {
toggleActionTitle = NSLocalizedString("Request Mobile Site", comment: "Action Sheet Button for Requesting the Mobile Site")
} else {
toggleActionTitle = NSLocalizedString("Request Desktop Site", comment: "Action Sheet Button for Requesting the Desktop Site")
}
let controller = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
controller.addAction(UIAlertAction(title: toggleActionTitle, style: .default, handler: { _ in tab.toggleDesktopSite() }))
controller.addAction(UIAlertAction(title: NSLocalizedString("Cancel", comment: "Label for Cancel button"), style: .cancel, handler: nil))
controller.popoverPresentationController?.sourceView = toolbar ?? urlBar
controller.popoverPresentationController?.sourceRect = button.frame
present(controller, animated: true, completion: nil)
}
func tabToolbarDidPressStop(_ tabToolbar: TabToolbarProtocol, button: UIButton) {
tabManager.selectedTab?.stop()
}
func tabToolbarDidPressForward(_ tabToolbar: TabToolbarProtocol, button: UIButton) {
tabManager.selectedTab?.goForward()
}
func tabToolbarDidLongPressForward(_ tabToolbar: TabToolbarProtocol, button: UIButton) {
showBackForwardList()
}
func tabToolbarDidPressMenu(_ tabToolbar: TabToolbarProtocol, button: UIButton) {
// ensure that any keyboards or spinners are dismissed before presenting the menu
UIApplication.shared.sendAction(#selector(UIResponder.resignFirstResponder), to: nil, from: nil, for: nil)
var actions: [[PhotonActionSheetItem]] = []
actions.append(getHomePanelActions())
actions.append(getOtherPanelActions(vcDelegate: self))
// force a modal if the menu is being displayed in compact split screen
let shouldSupress = !topTabsVisible && UIDevice.current.userInterfaceIdiom == .pad
presentSheetWith(actions: actions, on: self, from: button, supressPopover: shouldSupress)
}
func tabToolbarDidPressTabs(_ tabToolbar: TabToolbarProtocol, button: UIButton) {
showTabTray()
}
func tabToolbarDidLongPressTabs(_ tabToolbar: TabToolbarProtocol, button: UIButton) {
let controller = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
controller.addAction(UIAlertAction(title: Strings.NewTabTitle, style: .default, handler: { _ in
self.tabManager.addTabAndSelect(isPrivate: false)
}))
controller.addAction(UIAlertAction(title: Strings.NewPrivateTabTitle, style: .default, handler: { _ in
self.tabManager.addTabAndSelect(isPrivate: true)
}))
controller.addAction(UIAlertAction(title: NSLocalizedString("Cancel", comment: "Label for Cancel button"), style: .cancel, handler: nil))
controller.popoverPresentationController?.sourceView = toolbar ?? urlBar
controller.popoverPresentationController?.sourceRect = button.frame
present(controller, animated: true, completion: nil)
}
func showBackForwardList() {
if let backForwardList = tabManager.selectedTab?.webView?.backForwardList {
let backForwardViewController = BackForwardListViewController(profile: profile, backForwardList: backForwardList)
backForwardViewController.tabManager = tabManager
backForwardViewController.bvc = self
backForwardViewController.modalPresentationStyle = UIModalPresentationStyle.overCurrentContext
backForwardViewController.backForwardTransitionDelegate = BackForwardListAnimator()
self.present(backForwardViewController, animated: true, completion: nil)
}
}
}
extension BrowserViewController: TabDelegate {
func tab(_ tab: Tab, didCreateWebView webView: WKWebView) {
webView.frame = webViewContainer.frame
// Observers that live as long as the tab. Make sure these are all cleared
// in willDeleteWebView below!
webView.addObserver(self, forKeyPath: KVOEstimatedProgress, options: .new, context: nil)
webView.addObserver(self, forKeyPath: KVOLoading, options: .new, context: nil)
webView.addObserver(self, forKeyPath: KVOCanGoBack, options: .new, context: nil)
webView.addObserver(self, forKeyPath: KVOCanGoForward, options: .new, context: nil)
tab.webView?.addObserver(self, forKeyPath: KVOURL, options: .new, context: nil)
tab.webView?.addObserver(self, forKeyPath: KVOTitle, options: .new, context: nil)
webView.scrollView.addObserver(self.scrollController, forKeyPath: KVOContentSize, options: .new, context: nil)
webView.uiDelegate = self
let readerMode = ReaderMode(tab: tab)
readerMode.delegate = self
tab.addHelper(readerMode, name: ReaderMode.name())
let favicons = FaviconManager(tab: tab, profile: profile)
tab.addHelper(favicons, name: FaviconManager.name())
// only add the logins helper if the tab is not a private browsing tab
if !tab.isPrivate {
let logins = LoginsHelper(tab: tab, profile: profile)
tab.addHelper(logins, name: LoginsHelper.name())
}
let contextMenuHelper = ContextMenuHelper(tab: tab)
contextMenuHelper.delegate = self
tab.addHelper(contextMenuHelper, name: ContextMenuHelper.name())
let errorHelper = ErrorPageHelper()
tab.addHelper(errorHelper, name: ErrorPageHelper.name())
let sessionRestoreHelper = SessionRestoreHelper(tab: tab)
sessionRestoreHelper.delegate = self
tab.addHelper(sessionRestoreHelper, name: SessionRestoreHelper.name())
let findInPageHelper = FindInPageHelper(tab: tab)
findInPageHelper.delegate = self
tab.addHelper(findInPageHelper, name: FindInPageHelper.name())
let noImageModeHelper = NoImageModeHelper(tab: tab)
tab.addHelper(noImageModeHelper, name: NoImageModeHelper.name())
let printHelper = PrintHelper(tab: tab)
tab.addHelper(printHelper, name: PrintHelper.name())
let customSearchHelper = CustomSearchHelper(tab: tab)
tab.addHelper(customSearchHelper, name: CustomSearchHelper.name())
let nightModeHelper = NightModeHelper(tab: tab)
tab.addHelper(nightModeHelper, name: NightModeHelper.name())
// XXX: Bug 1390200 - Disable NSUserActivity/CoreSpotlight temporarily
// let spotlightHelper = SpotlightHelper(tab: tab)
// tab.addHelper(spotlightHelper, name: SpotlightHelper.name())
tab.addHelper(LocalRequestHelper(), name: LocalRequestHelper.name())
let historyStateHelper = HistoryStateHelper(tab: tab)
historyStateHelper.delegate = self
tab.addHelper(historyStateHelper, name: HistoryStateHelper.name())
if #available(iOS 11, *) {
(tab.contentBlocker as? ContentBlockerHelper)?.setupForWebView()
}
let metadataHelper = MetadataParserHelper(tab: tab, profile: profile)
tab.addHelper(metadataHelper, name: MetadataParserHelper.name())
}
func tab(_ tab: Tab, willDeleteWebView webView: WKWebView) {
tab.cancelQueuedAlerts()
webView.removeObserver(self, forKeyPath: KVOEstimatedProgress)
webView.removeObserver(self, forKeyPath: KVOLoading)
webView.removeObserver(self, forKeyPath: KVOCanGoBack)
webView.removeObserver(self, forKeyPath: KVOCanGoForward)
webView.scrollView.removeObserver(self.scrollController, forKeyPath: KVOContentSize)
webView.removeObserver(self, forKeyPath: KVOURL)
webView.removeObserver(self, forKeyPath: KVOTitle)
webView.uiDelegate = nil
webView.scrollView.delegate = nil
webView.removeFromSuperview()
}
fileprivate func findSnackbar(_ barToFind: SnackBar) -> Int? {
let bars = snackBars.subviews
for (index, bar) in bars.enumerated() where bar === barToFind {
return index
}
return nil
}
fileprivate func updateSnackBarConstraints() {
snackBars.snp.remakeConstraints { make in
make.bottom.equalTo(findInPageContainer.snp.top)
let bars = self.snackBars.subviews
if bars.count > 0 {
let view = bars[bars.count-1]
make.top.equalTo(view.snp.top)
} else {
make.height.equalTo(0)
}
if traitCollection.horizontalSizeClass != .regular {
make.leading.trailing.equalTo(self.view)
self.snackBars.layer.borderWidth = 0
} else {
make.centerX.equalTo(self.view)
make.width.equalTo(SnackBarUX.MaxWidth)
self.snackBars.layer.borderColor = UIConstants.BorderColor.cgColor
self.snackBars.layer.borderWidth = 1
}
}
}
// This removes the bar from its superview and updates constraints appropriately
fileprivate func finishRemovingBar(_ bar: SnackBar) {
// If there was a bar above this one, we need to remake its constraints.
if let index = findSnackbar(bar) {
// If the bar being removed isn't on the top of the list
let bars = snackBars.subviews
if index < bars.count-1 {
// Move the bar above this one
let nextbar = bars[index+1] as! SnackBar
nextbar.snp.makeConstraints { make in
// If this wasn't the bottom bar, attach to the bar below it
if index > 0 {
let bar = bars[index-1] as! SnackBar
nextbar.bottom = make.bottom.equalTo(bar.snp.top).constraint
} else {
// Otherwise, we attach it to the bottom of the snackbars
nextbar.bottom = make.bottom.equalTo(self.snackBars.snp.bottom).constraint
}
}
}
}
// Really remove the bar
bar.removeFromSuperview()
}
fileprivate func finishAddingBar(_ bar: SnackBar) {
snackBars.addSubview(bar)
bar.snp.makeConstraints { make in
// If there are already bars showing, add this on top of them
let bars = self.snackBars.subviews
// Add the bar on top of the stack
// We're the new top bar in the stack, so make sure we ignore ourself
if bars.count > 1 {
let view = bars[bars.count - 2]
bar.bottom = make.bottom.equalTo(view.snp.top).offset(0).constraint
} else {
bar.bottom = make.bottom.equalTo(self.snackBars.snp.bottom).offset(0).constraint
}
make.leading.trailing.equalTo(self.snackBars)
}
}
func showBar(_ bar: SnackBar, animated: Bool) {
finishAddingBar(bar)
updateSnackBarConstraints()
bar.hide()
view.layoutIfNeeded()
UIView.animate(withDuration: animated ? 0.25 : 0, animations: { () -> Void in
bar.show()
self.view.layoutIfNeeded()
})
}
func removeBar(_ bar: SnackBar, animated: Bool) {
if let _ = findSnackbar(bar) {
UIView.animate(withDuration: animated ? 0.25 : 0, animations: { () -> Void in
bar.hide()
self.view.layoutIfNeeded()
}, completion: { success in
// Really remove the bar
self.finishRemovingBar(bar)
self.updateSnackBarConstraints()
})
}
}
func removeAllBars() {
let bars = snackBars.subviews
for bar in bars {
if let bar = bar as? SnackBar {
bar.removeFromSuperview()
}
}
self.updateSnackBarConstraints()
}
func tab(_ tab: Tab, didAddSnackbar bar: SnackBar) {
showBar(bar, animated: true)
}
func tab(_ tab: Tab, didRemoveSnackbar bar: SnackBar) {
removeBar(bar, animated: true)
}
func tab(_ tab: Tab, didSelectFindInPageForSelection selection: String) {
updateFindInPageVisibility(visible: true)
findInPageBar?.text = selection
}
}
extension BrowserViewController: HomePanelViewControllerDelegate {
func homePanelViewController(_ homePanelViewController: HomePanelViewController, didSelectURL url: URL, visitType: VisitType) {
finishEditingAndSubmit(url, visitType: visitType)
}
func homePanelViewController(_ homePanelViewController: HomePanelViewController, didSelectPanel panel: Int) {
if let url = tabManager.selectedTab?.url, url.isAboutHomeURL {
tabManager.selectedTab?.webView?.evaluateJavaScript("history.replaceState({}, '', '#panel=\(panel)')", completionHandler: nil)
}
}
func homePanelViewControllerDidRequestToCreateAccount(_ homePanelViewController: HomePanelViewController) {
presentSignInViewController() // TODO UX Right now the flow for sign in and create account is the same
}
func homePanelViewControllerDidRequestToSignIn(_ homePanelViewController: HomePanelViewController) {
presentSignInViewController() // TODO UX Right now the flow for sign in and create account is the same
}
func homePanelViewControllerDidRequestToOpenInNewTab(_ url: URL, isPrivate: Bool) {
let tab = self.tabManager.addTab(PrivilegedRequest(url: url) as URLRequest, afterTab: self.tabManager.selectedTab, isPrivate: isPrivate)
// If we are showing toptabs a user can just use the top tab bar
// If in overlay mode switching doesnt correctly dismiss the homepanels
guard !topTabsVisible, !self.urlBar.inOverlayMode else {
return
}
// We're not showing the top tabs; show a toast to quick switch to the fresh new tab.
let toast = ButtonToast(labelText: Strings.ContextMenuButtonToastNewTabOpenedLabelText, buttonText: Strings.ContextMenuButtonToastNewTabOpenedButtonText, completion: { buttonPressed in
if buttonPressed {
self.tabManager.selectTab(tab)
}
})
self.show(buttonToast: toast)
}
}
extension BrowserViewController: SearchViewControllerDelegate {
func searchViewController(_ searchViewController: SearchViewController, didSelectURL url: URL) {
finishEditingAndSubmit(url, visitType: VisitType.typed)
}
func searchViewController(_ searchViewController: SearchViewController, didLongPressSuggestion suggestion: String) {
self.urlBar.setLocation(suggestion, search: true)
}
func presentSearchSettingsController() {
let settingsNavigationController = SearchSettingsTableViewController()
settingsNavigationController.model = self.profile.searchEngines
settingsNavigationController.profile = self.profile
let navController = ModalSettingsNavigationController(rootViewController: settingsNavigationController)
self.present(navController, animated: true, completion: nil)
}
}
extension BrowserViewController: TabManagerDelegate {
func tabManager(_ tabManager: TabManager, didSelectedTabChange selected: Tab?, previous: Tab?) {
// Remove the old accessibilityLabel. Since this webview shouldn't be visible, it doesn't need it
// and having multiple views with the same label confuses tests.
if let wv = previous?.webView {
removeOpenInView()
wv.endEditing(true)
wv.accessibilityLabel = nil
wv.accessibilityElementsHidden = true
wv.accessibilityIdentifier = nil
wv.removeFromSuperview()
}
if let tab = selected, let webView = tab.webView {
updateURLBarDisplayURL(tab)
if tab.isPrivate != previous?.isPrivate {
applyTheme(tab.isPrivate ? Theme.PrivateMode : Theme.NormalMode)
}
if tab.isPrivate {
readerModeCache = MemoryReaderModeCache.sharedInstance
} else {
readerModeCache = DiskReaderModeCache.sharedInstance
}
if let privateModeButton = topTabsViewController?.privateModeButton, previous != nil && previous?.isPrivate != tab.isPrivate {
privateModeButton.setSelected(tab.isPrivate, animated: true)
}
ReaderModeHandlers.readerModeCache = readerModeCache
scrollController.tab = selected
webViewContainer.addSubview(webView)
webView.snp.makeConstraints { make in
make.top.equalTo(webViewContainerToolbar.snp.bottom)
make.left.right.bottom.equalTo(self.webViewContainer)
}
webView.accessibilityLabel = NSLocalizedString("Web content", comment: "Accessibility label for the main web content view")
webView.accessibilityIdentifier = "contentView"
webView.accessibilityElementsHidden = false
if let url = webView.url {
let absoluteString = url.absoluteString
// Don't bother fetching bookmark state for about/sessionrestore and about/home.
if url.isAboutURL {
// Indeed, because we don't show the toolbar at all, don't even blank the star.
} else {
profile.bookmarks.modelFactory >>== { [weak tab] in
$0.isBookmarked(absoluteString)
.uponQueue(DispatchQueue.main) {
guard let isBookmarked = $0.successValue else {
print("Error getting bookmark status: \($0.failureValue ??? "nil").")
return
}
tab?.isBookmarked = isBookmarked
}
}
}
} else {
// The web view can go gray if it was zombified due to memory pressure.
// When this happens, the URL is nil, so try restoring the page upon selection.
tab.reload()
}
}
if let selected = selected, let previous = previous, selected.isPrivate != previous.isPrivate {
updateTabCountUsingTabManager(tabManager)
}
removeAllBars()
if let bars = selected?.bars {
for bar in bars {
showBar(bar, animated: true)
}
}
updateFindInPageVisibility(visible: false)
navigationToolbar.updateReloadStatus(selected?.loading ?? false)
navigationToolbar.updateBackStatus(selected?.canGoBack ?? false)
navigationToolbar.updateForwardStatus(selected?.canGoForward ?? false)
if !(selected?.webView?.url?.isLocalUtility ?? false) {
self.urlBar.updateProgressBar(Float(selected?.estimatedProgress ?? 0))
}
if let readerMode = selected?.getHelper(name: ReaderMode.name()) as? ReaderMode {
urlBar.updateReaderModeState(readerMode.state)
if readerMode.state == .active {
showReaderModeBar(animated: false)
} else {
hideReaderModeBar(animated: false)
}
} else {
urlBar.updateReaderModeState(ReaderModeState.unavailable)
}
updateInContentHomePanel(selected?.url as URL?)
}
func tabManager(_ tabManager: TabManager, willAddTab tab: Tab) {
}
func tabManager(_ tabManager: TabManager, didAddTab tab: Tab) {
// If we are restoring tabs then we update the count once at the end
if !tabManager.isRestoring {
updateTabCountUsingTabManager(tabManager)
}
tab.tabDelegate = self
}
func tabManager(_ tabManager: TabManager, willRemoveTab tab: Tab) {
}
func tabManager(_ tabManager: TabManager, didRemoveTab tab: Tab) {
updateTabCountUsingTabManager(tabManager)
// tabDelegate is a weak ref (and the tab's webView may not be destroyed yet)
// so we don't expcitly unset it.
if let url = tab.url, !url.isAboutURL && !tab.isPrivate {
profile.recentlyClosedTabs.addTab(url as URL, title: tab.title, faviconURL: tab.displayFavicon?.url)
}
}
func tabManagerDidAddTabs(_ tabManager: TabManager) {
updateTabCountUsingTabManager(tabManager)
}
func tabManagerDidRestoreTabs(_ tabManager: TabManager) {
updateTabCountUsingTabManager(tabManager)
}
func show(buttonToast: ButtonToast, afterWaiting delay: DispatchTimeInterval = SimpleToastUX.ToastDelayBefore, duration: DispatchTimeInterval = SimpleToastUX.ToastDismissAfter) {
// If BVC isnt visible hold on to this toast until viewDidAppear
if self.view.window == nil {
self.pendingToast = buttonToast
return
}
DispatchQueue.main.asyncAfter(deadline: .now() + delay) {
self.view.addSubview(buttonToast)
buttonToast.snp.makeConstraints { make in
make.left.right.equalTo(self.view)
make.bottom.equalTo(self.webViewContainer)
}
buttonToast.showToast(duration: duration)
}
}
func tabManagerDidRemoveAllTabs(_ tabManager: TabManager, toast: ButtonToast?) {
guard let toast = toast, !tabTrayController.privateMode else {
return
}
show(buttonToast: toast, afterWaiting: ButtonToastUX.ToastDelay)
}
fileprivate func updateTabCountUsingTabManager(_ tabManager: TabManager, animated: Bool = true) {
if let selectedTab = tabManager.selectedTab {
let count = selectedTab.isPrivate ? tabManager.privateTabs.count : tabManager.normalTabs.count
toolbar?.updateTabCount(count, animated: animated)
urlBar.updateTabCount(count, animated: !urlBar.inOverlayMode)
topTabsViewController?.updateTabCount(count, animated: animated)
}
}
}
/// List of schemes that are allowed to open a popup window
private let SchemesAllowedToOpenPopups = ["http", "https", "javascript", "data"]
extension BrowserViewController: WKUIDelegate {
func webView(_ webView: WKWebView, createWebViewWith configuration: WKWebViewConfiguration, for navigationAction: WKNavigationAction, windowFeatures: WKWindowFeatures) -> WKWebView? {
guard let parentTab = tabManager[webView] else { return nil }
if !navigationAction.isAllowed {
print("Denying unprivileged request: \(navigationAction.request)")
return nil
}
if let currentTab = tabManager.selectedTab {
screenshotHelper.takeScreenshot(currentTab)
}
// If the page uses window.open() or target="_blank", open the page in a new tab.
let newTab = tabManager.addTab(navigationAction.request, configuration: configuration, afterTab: parentTab, isPrivate: parentTab.isPrivate)
tabManager.selectTab(newTab)
// If the page we just opened has a bad scheme, we return nil here so that JavaScript does not
// get a reference to it which it can return from window.open() - this will end up as a
// CFErrorHTTPBadURL being presented.
guard let scheme = (navigationAction.request as NSURLRequest).url?.scheme?.lowercased(), SchemesAllowedToOpenPopups.contains(scheme) else {
return nil
}
return newTab.webView
}
fileprivate func canDisplayJSAlertForWebView(_ webView: WKWebView) -> Bool {
// Only display a JS Alert if we are selected and there isn't anything being shown
return ((tabManager.selectedTab == nil ? false : tabManager.selectedTab!.webView == webView)) && (self.presentedViewController == nil)
}
func webView(_ webView: WKWebView, runJavaScriptAlertPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping () -> Void) {
let messageAlert = MessageAlert(message: message, frame: frame, completionHandler: completionHandler)
if canDisplayJSAlertForWebView(webView) {
present(messageAlert.alertController(), animated: true, completion: nil)
} else if let promptingTab = tabManager[webView] {
promptingTab.queueJavascriptAlertPrompt(messageAlert)
} else {
// This should never happen since an alert needs to come from a web view but just in case call the handler
// since not calling it will result in a runtime exception.
completionHandler()
}
}
func webView(_ webView: WKWebView, runJavaScriptConfirmPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping (Bool) -> Void) {
let confirmAlert = ConfirmPanelAlert(message: message, frame: frame, completionHandler: completionHandler)
if canDisplayJSAlertForWebView(webView) {
present(confirmAlert.alertController(), animated: true, completion: nil)
} else if let promptingTab = tabManager[webView] {
promptingTab.queueJavascriptAlertPrompt(confirmAlert)
} else {
completionHandler(false)
}
}
func webView(_ webView: WKWebView, runJavaScriptTextInputPanelWithPrompt prompt: String, defaultText: String?, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping (String?) -> Void) {
let textInputAlert = TextInputAlert(message: prompt, frame: frame, completionHandler: completionHandler, defaultText: defaultText)
if canDisplayJSAlertForWebView(webView) {
present(textInputAlert.alertController(), animated: true, completion: nil)
} else if let promptingTab = tabManager[webView] {
promptingTab.queueJavascriptAlertPrompt(textInputAlert)
} else {
completionHandler(nil)
}
}
/// Invoked when an error occurs while starting to load data for the main frame.
func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) {
// Ignore the "Frame load interrupted" error that is triggered when we cancel a request
// to open an external application and hand it over to UIApplication.openURL(). The result
// will be that we switch to the external app, for example the app store, while keeping the
// original web page in the tab instead of replacing it with an error page.
let error = error as NSError
if error.domain == "WebKitErrorDomain" && error.code == 102 {
return
}
if checkIfWebContentProcessHasCrashed(webView, error: error as NSError) {
return
}
if error.code == Int(CFNetworkErrors.cfurlErrorCancelled.rawValue) {
if let tab = tabManager[webView], tab === tabManager.selectedTab {
urlBar.currentURL = tab.url?.displayURL
}
return
}
if let url = error.userInfo[NSURLErrorFailingURLErrorKey] as? URL {
ErrorPageHelper().showPage(error, forUrl: url, inWebView: webView)
// If the local web server isn't working for some reason (Firefox cellular data is
// disabled in settings, for example), we'll fail to load the session restore URL.
// We rely on loading that page to get the restore callback to reset the restoring
// flag, so if we fail to load that page, reset it here.
if url.aboutComponent == "sessionrestore" {
tabManager.tabs.filter { $0.webView == webView }.first?.restoring = false
}
}
}
fileprivate func checkIfWebContentProcessHasCrashed(_ webView: WKWebView, error: NSError) -> Bool {
if error.code == WKError.webContentProcessTerminated.rawValue && error.domain == "WebKitErrorDomain" {
print("WebContent process has crashed. Trying to reloadFromOrigin to restart it.")
webView.reloadFromOrigin()
return true
}
return false
}
func webView(_ webView: WKWebView, decidePolicyFor navigationResponse: WKNavigationResponse, decisionHandler: @escaping (WKNavigationResponsePolicy) -> Void) {
let helperForURL = OpenIn.helperForResponse(navigationResponse.response)
if navigationResponse.canShowMIMEType {
if let openInHelper = helperForURL {
addViewForOpenInHelper(openInHelper)
}
decisionHandler(WKNavigationResponsePolicy.allow)
return
}
guard var openInHelper = helperForURL else {
let error = NSError(domain: ErrorPageHelper.MozDomain, code: Int(ErrorPageHelper.MozErrorDownloadsNotEnabled), userInfo: [NSLocalizedDescriptionKey: Strings.UnableToDownloadError])
ErrorPageHelper().showPage(error, forUrl: navigationResponse.response.url!, inWebView: webView)
return decisionHandler(WKNavigationResponsePolicy.allow)
}
if openInHelper.openInView == nil {
openInHelper.openInView = navigationToolbar.menuButton
}
openInHelper.open()
decisionHandler(WKNavigationResponsePolicy.cancel)
}
func webViewDidClose(_ webView: WKWebView) {
if let tab = tabManager[webView] {
self.tabManager.removeTab(tab)
}
}
}
extension BrowserViewController: ReaderModeDelegate {
func readerMode(_ readerMode: ReaderMode, didChangeReaderModeState state: ReaderModeState, forTab tab: Tab) {
// If this reader mode availability state change is for the tab that we currently show, then update
// the button. Otherwise do nothing and the button will be updated when the tab is made active.
if tabManager.selectedTab === tab {
urlBar.updateReaderModeState(state)
}
}
func readerMode(_ readerMode: ReaderMode, didDisplayReaderizedContentForTab tab: Tab) {
self.showReaderModeBar(animated: true)
tab.showContent(true)
}
}
// MARK: - UIPopoverPresentationControllerDelegate
extension BrowserViewController: UIPopoverPresentationControllerDelegate {
func popoverPresentationControllerDidDismissPopover(_ popoverPresentationController: UIPopoverPresentationController) {
displayedPopoverController = nil
updateDisplayedPopoverProperties = nil
}
}
extension BrowserViewController: UIAdaptivePresentationControllerDelegate {
// Returning None here makes sure that the Popover is actually presented as a Popover and
// not as a full-screen modal, which is the default on compact device classes.
func adaptivePresentationStyle(for controller: UIPresentationController, traitCollection: UITraitCollection) -> UIModalPresentationStyle {
return UIModalPresentationStyle.none
}
}
// MARK: - ReaderModeStyleViewControllerDelegate
extension BrowserViewController: ReaderModeStyleViewControllerDelegate {
func readerModeStyleViewController(_ readerModeStyleViewController: ReaderModeStyleViewController, didConfigureStyle style: ReaderModeStyle) {
// Persist the new style to the profile
let encodedStyle: [String: Any] = style.encodeAsDictionary()
profile.prefs.setObject(encodedStyle, forKey: ReaderModeProfileKeyStyle)
// Change the reader mode style on all tabs that have reader mode active
for tabIndex in 0..<tabManager.count {
if let tab = tabManager[tabIndex] {
if let readerMode = tab.getHelper(name: "ReaderMode") as? ReaderMode {
if readerMode.state == ReaderModeState.active {
readerMode.style = style
}
}
}
}
}
}
extension BrowserViewController {
func updateReaderModeBar() {
if let readerModeBar = readerModeBar {
if let tab = self.tabManager.selectedTab, tab.isPrivate {
readerModeBar.applyTheme(Theme.PrivateMode)
} else {
readerModeBar.applyTheme(Theme.NormalMode)
}
if let url = self.tabManager.selectedTab?.url?.displayURL?.absoluteString, let result = profile.readingList?.getRecordWithURL(url) {
if let successValue = result.successValue, let record = successValue {
readerModeBar.unread = record.unread
readerModeBar.added = true
} else {
readerModeBar.unread = true
readerModeBar.added = false
}
} else {
readerModeBar.unread = true
readerModeBar.added = false
}
}
}
func showReaderModeBar(animated: Bool) {
if self.readerModeBar == nil {
let readerModeBar = ReaderModeBarView(frame: CGRect.zero)
readerModeBar.delegate = self
view.insertSubview(readerModeBar, belowSubview: header)
self.readerModeBar = readerModeBar
}
updateReaderModeBar()
self.updateViewConstraints()
}
func hideReaderModeBar(animated: Bool) {
if let readerModeBar = self.readerModeBar {
readerModeBar.removeFromSuperview()
self.readerModeBar = nil
self.updateViewConstraints()
}
}
/// There are two ways we can enable reader mode. In the simplest case we open a URL to our internal reader mode
/// and be done with it. In the more complicated case, reader mode was already open for this page and we simply
/// navigated away from it. So we look to the left and right in the BackForwardList to see if a readerized version
/// of the current page is there. And if so, we go there.
func enableReaderMode() {
guard let tab = tabManager.selectedTab, let webView = tab.webView else { return }
let backList = webView.backForwardList.backList
let forwardList = webView.backForwardList.forwardList
guard let currentURL = webView.backForwardList.currentItem?.url, let readerModeURL = currentURL.encodeReaderModeURL(WebServer.sharedInstance.baseReaderModeURL()) else { return }
if backList.count > 1 && backList.last?.url == readerModeURL {
webView.go(to: backList.last!)
} else if forwardList.count > 0 && forwardList.first?.url == readerModeURL {
webView.go(to: forwardList.first!)
} else {
// Store the readability result in the cache and load it. This will later move to the ReadabilityHelper.
webView.evaluateJavaScript("\(ReaderModeNamespace).readerize()", completionHandler: { (object, error) -> Void in
if let readabilityResult = ReadabilityResult(object: object as AnyObject?) {
do {
try self.readerModeCache.put(currentURL, readabilityResult)
} catch _ {
}
if let nav = webView.load(PrivilegedRequest(url: readerModeURL) as URLRequest) {
self.ignoreNavigationInTab(tab, navigation: nav)
}
}
})
}
}
/// Disabling reader mode can mean two things. In the simplest case we were opened from the reading list, which
/// means that there is nothing in the BackForwardList except the internal url for the reader mode page. In that
/// case we simply open a new page with the original url. In the more complicated page, the non-readerized version
/// of the page is either to the left or right in the BackForwardList. If that is the case, we navigate there.
func disableReaderMode() {
if let tab = tabManager.selectedTab,
let webView = tab.webView {
let backList = webView.backForwardList.backList
let forwardList = webView.backForwardList.forwardList
if let currentURL = webView.backForwardList.currentItem?.url {
if let originalURL = currentURL.decodeReaderModeURL {
if backList.count > 1 && backList.last?.url == originalURL {
webView.go(to: backList.last!)
} else if forwardList.count > 0 && forwardList.first?.url == originalURL {
webView.go(to: forwardList.first!)
} else {
if let nav = webView.load(URLRequest(url: originalURL)) {
self.ignoreNavigationInTab(tab, navigation: nav)
}
}
}
}
}
}
func SELDynamicFontChanged(_ notification: Notification) {
guard notification.name == NotificationDynamicFontChanged else { return }
var readerModeStyle = DefaultReaderModeStyle
if let dict = profile.prefs.dictionaryForKey(ReaderModeProfileKeyStyle) {
if let style = ReaderModeStyle(dict: dict as [String: AnyObject]) {
readerModeStyle = style
}
}
readerModeStyle.fontSize = ReaderModeFontSize.defaultSize
self.readerModeStyleViewController(ReaderModeStyleViewController(), didConfigureStyle: readerModeStyle)
}
}
extension BrowserViewController: ReaderModeBarViewDelegate {
func readerModeBar(_ readerModeBar: ReaderModeBarView, didSelectButton buttonType: ReaderModeBarButtonType) {
switch buttonType {
case .settings:
if let readerMode = tabManager.selectedTab?.getHelper(name: "ReaderMode") as? ReaderMode, readerMode.state == ReaderModeState.active {
var readerModeStyle = DefaultReaderModeStyle
if let dict = profile.prefs.dictionaryForKey(ReaderModeProfileKeyStyle) {
if let style = ReaderModeStyle(dict: dict as [String: AnyObject]) {
readerModeStyle = style
}
}
let readerModeStyleViewController = ReaderModeStyleViewController()
readerModeStyleViewController.delegate = self
readerModeStyleViewController.readerModeStyle = readerModeStyle
readerModeStyleViewController.modalPresentationStyle = UIModalPresentationStyle.popover
let setupPopover = { [unowned self] in
if let popoverPresentationController = readerModeStyleViewController.popoverPresentationController {
popoverPresentationController.backgroundColor = UIColor.white
popoverPresentationController.delegate = self
popoverPresentationController.sourceView = readerModeBar
popoverPresentationController.sourceRect = CGRect(x: readerModeBar.frame.width/2, y: UIConstants.ToolbarHeight, width: 1, height: 1)
popoverPresentationController.permittedArrowDirections = UIPopoverArrowDirection.up
}
}
setupPopover()
if readerModeStyleViewController.popoverPresentationController != nil {
displayedPopoverController = readerModeStyleViewController
updateDisplayedPopoverProperties = setupPopover
}
self.present(readerModeStyleViewController, animated: true, completion: nil)
}
case .markAsRead:
if let url = self.tabManager.selectedTab?.url?.displayURL?.absoluteString, let result = profile.readingList?.getRecordWithURL(url) {
if let successValue = result.successValue, let record = successValue {
profile.readingList?.updateRecord(record, unread: false) // TODO Check result, can this fail?
readerModeBar.unread = false
}
}
case .markAsUnread:
if let url = self.tabManager.selectedTab?.url?.displayURL?.absoluteString, let result = profile.readingList?.getRecordWithURL(url) {
if let successValue = result.successValue, let record = successValue {
profile.readingList?.updateRecord(record, unread: true) // TODO Check result, can this fail?
readerModeBar.unread = true
}
}
case .addToReadingList:
if let tab = tabManager.selectedTab,
let rawURL = tab.url, rawURL.isReaderModeURL,
let url = rawURL.decodeReaderModeURL {
profile.readingList?.createRecordWithURL(url.absoluteString, title: tab.title ?? "", addedBy: UIDevice.current.name) // TODO Check result, can this fail?
readerModeBar.added = true
readerModeBar.unread = true
}
case .removeFromReadingList:
if let url = self.tabManager.selectedTab?.url?.displayURL?.absoluteString,
let result = profile.readingList?.getRecordWithURL(url),
let successValue = result.successValue,
let record = successValue {
profile.readingList?.deleteRecord(record) // TODO Check result, can this fail?
readerModeBar.added = false
readerModeBar.unread = false
}
}
}
}
extension BrowserViewController: IntroViewControllerDelegate {
@discardableResult func presentIntroViewController(_ force: Bool = false, animated: Bool = true) -> Bool {
if let deeplink = self.profile.prefs.stringForKey("AdjustDeeplinkKey"), let url = URL(string: deeplink) {
self.launchFxAFromDeeplinkURL(url)
return true
}
if force || profile.prefs.intForKey(IntroViewControllerSeenProfileKey) == nil {
let introViewController = IntroViewController()
introViewController.delegate = self
// On iPad we present it modally in a controller
if topTabsVisible {
introViewController.preferredContentSize = CGSize(width: IntroViewControllerUX.Width, height: IntroViewControllerUX.Height)
introViewController.modalPresentationStyle = UIModalPresentationStyle.formSheet
}
present(introViewController, animated: animated) {
// On first run (and forced) open up the homepage in the background.
if let homePageURL = HomePageAccessors.getHomePage(self.profile.prefs), let tab = self.tabManager.selectedTab, DeviceInfo.hasConnectivity() {
tab.loadRequest(URLRequest(url: homePageURL))
}
}
return true
}
return false
}
func launchFxAFromDeeplinkURL(_ url: URL) {
self.profile.prefs.removeObjectForKey("AdjustDeeplinkKey")
var query = url.getQuery()
query["entrypoint"] = "adjust_deepklink_ios"
let fxaParams: FxALaunchParams
fxaParams = FxALaunchParams(query: query)
self.presentSignInViewController(fxaParams)
}
func introViewControllerDidFinish(_ introViewController: IntroViewController, requestToLogin: Bool) {
self.profile.prefs.setInt(1, forKey: IntroViewControllerSeenProfileKey)
introViewController.dismiss(animated: true) { finished in
if self.navigationController?.viewControllers.count ?? 0 > 1 {
_ = self.navigationController?.popToRootViewController(animated: true)
}
if requestToLogin {
self.presentSignInViewController()
}
}
}
func presentSignInViewController(_ fxaOptions: FxALaunchParams? = nil) {
// Show the settings page if we have already signed in. If we haven't then show the signin page
let vcToPresent: UIViewController
if profile.hasAccount() {
let settingsTableViewController = AppSettingsTableViewController()
settingsTableViewController.profile = profile
settingsTableViewController.tabManager = tabManager
vcToPresent = settingsTableViewController
} else {
let signInVC = FxAContentViewController(profile: profile, fxaOptions: fxaOptions)
signInVC.delegate = self
signInVC.navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.done, target: self, action: #selector(BrowserViewController.dismissSignInViewController))
vcToPresent = signInVC
}
let settingsNavigationController = SettingsNavigationController(rootViewController: vcToPresent)
settingsNavigationController.modalPresentationStyle = .formSheet
settingsNavigationController.navigationBar.isTranslucent = false
self.present(settingsNavigationController, animated: true, completion: nil)
}
func dismissSignInViewController() {
self.dismiss(animated: true, completion: nil)
}
}
extension BrowserViewController: FxAContentViewControllerDelegate {
func contentViewControllerDidSignIn(_ viewController: FxAContentViewController, withFlags flags: FxALoginFlags) {
if flags.verified {
self.dismiss(animated: true, completion: nil)
}
}
func contentViewControllerDidCancel(_ viewController: FxAContentViewController) {
self.dismiss(animated: true, completion: nil)
}
}
extension BrowserViewController: ContextMenuHelperDelegate {
func contextMenuHelper(_ contextMenuHelper: ContextMenuHelper, didLongPressElements elements: ContextMenuHelper.Elements, gestureRecognizer: UIGestureRecognizer) {
// locationInView can return (0, 0) when the long press is triggered in an invalid page
// state (e.g., long pressing a link before the document changes, then releasing after a
// different page loads).
let touchPoint = gestureRecognizer.location(in: view)
guard touchPoint != CGPoint.zero else { return }
let touchSize = CGSize(width: 0, height: 16)
let actionSheetController = UIAlertController(title: nil, message: nil, preferredStyle: UIAlertControllerStyle.actionSheet)
var dialogTitle: String?
if let url = elements.link, let currentTab = tabManager.selectedTab {
dialogTitle = url.absoluteString
let isPrivate = currentTab.isPrivate
let addTab = { (rURL: URL, isPrivate: Bool) in
let tab = self.tabManager.addTab(URLRequest(url: rURL as URL), afterTab: currentTab, isPrivate: isPrivate)
LeanplumIntegration.sharedInstance.track(eventName: .openedNewTab, withParameters: ["Source": "Long Press Context Menu" as AnyObject])
guard !self.topTabsVisible else {
return
}
// We're not showing the top tabs; show a toast to quick switch to the fresh new tab.
let toast = ButtonToast(labelText: Strings.ContextMenuButtonToastNewTabOpenedLabelText, buttonText: Strings.ContextMenuButtonToastNewTabOpenedButtonText, completion: { buttonPressed in
if buttonPressed {
self.tabManager.selectTab(tab)
}
})
self.show(buttonToast: toast)
}
if !isPrivate {
let newTabTitle = NSLocalizedString("Open in New Tab", comment: "Context menu item for opening a link in a new tab")
let openNewTabAction = UIAlertAction(title: newTabTitle, style: UIAlertActionStyle.default) { (action: UIAlertAction) in
addTab(url, false)
}
actionSheetController.addAction(openNewTabAction)
}
let openNewPrivateTabTitle = NSLocalizedString("Open in New Private Tab", tableName: "PrivateBrowsing", comment: "Context menu option for opening a link in a new private tab")
let openNewPrivateTabAction = UIAlertAction(title: openNewPrivateTabTitle, style: UIAlertActionStyle.default) { (action: UIAlertAction) in
addTab(url, true)
}
actionSheetController.addAction(openNewPrivateTabAction)
let copyTitle = NSLocalizedString("Copy Link", comment: "Context menu item for copying a link URL to the clipboard")
let copyAction = UIAlertAction(title: copyTitle, style: UIAlertActionStyle.default) { (action: UIAlertAction) -> Void in
UIPasteboard.general.url = url as URL
}
actionSheetController.addAction(copyAction)
let shareTitle = NSLocalizedString("Share Link", comment: "Context menu item for sharing a link URL")
let shareAction = UIAlertAction(title: shareTitle, style: UIAlertActionStyle.default) { _ in
self.presentActivityViewController(url as URL, sourceView: self.view, sourceRect: CGRect(origin: touchPoint, size: touchSize), arrowDirection: .any)
}
actionSheetController.addAction(shareAction)
}
if let url = elements.image {
if dialogTitle == nil {
dialogTitle = url.absoluteString
}
let photoAuthorizeStatus = PHPhotoLibrary.authorizationStatus()
let saveImageTitle = NSLocalizedString("Save Image", comment: "Context menu item for saving an image")
let saveImageAction = UIAlertAction(title: saveImageTitle, style: UIAlertActionStyle.default) { (action: UIAlertAction) -> Void in
if photoAuthorizeStatus == PHAuthorizationStatus.authorized || photoAuthorizeStatus == PHAuthorizationStatus.notDetermined {
self.getImage(url as URL) {
UIImageWriteToSavedPhotosAlbum($0, self, #selector(self.image(_:didFinishSavingWithError:contextInfo:)), nil)
}
} else {
let accessDenied = UIAlertController(title: NSLocalizedString("Firefox would like to access your Photos", comment: "See http://mzl.la/1G7uHo7"), message: NSLocalizedString("This allows you to save the image to your Camera Roll.", comment: "See http://mzl.la/1G7uHo7"), preferredStyle: UIAlertControllerStyle.alert)
let dismissAction = UIAlertAction(title: UIConstants.CancelString, style: UIAlertActionStyle.default, handler: nil)
accessDenied.addAction(dismissAction)
let settingsAction = UIAlertAction(title: NSLocalizedString("Open Settings", comment: "See http://mzl.la/1G7uHo7"), style: UIAlertActionStyle.default ) { (action: UIAlertAction!) -> Void in
UIApplication.shared.open(URL(string: UIApplicationOpenSettingsURLString)!, options: [:])
}
accessDenied.addAction(settingsAction)
self.present(accessDenied, animated: true, completion: nil)
}
}
actionSheetController.addAction(saveImageAction)
let copyImageTitle = NSLocalizedString("Copy Image", comment: "Context menu item for copying an image to the clipboard")
let copyAction = UIAlertAction(title: copyImageTitle, style: UIAlertActionStyle.default) { (action: UIAlertAction) -> Void in
// put the actual image on the clipboard
// do this asynchronously just in case we're in a low bandwidth situation
let pasteboard = UIPasteboard.general
pasteboard.url = url as URL
let changeCount = pasteboard.changeCount
let application = UIApplication.shared
var taskId: UIBackgroundTaskIdentifier = 0
taskId = application.beginBackgroundTask (expirationHandler: { _ in
application.endBackgroundTask(taskId)
})
Alamofire.request(url)
.validate(statusCode: 200..<300)
.response { response in
// Only set the image onto the pasteboard if the pasteboard hasn't changed since
// fetching the image; otherwise, in low-bandwidth situations,
// we might be overwriting something that the user has subsequently added.
if changeCount == pasteboard.changeCount, let imageData = response.data, response.error == nil {
pasteboard.addImageWithData(imageData, forURL: url)
}
application.endBackgroundTask(taskId)
}
}
actionSheetController.addAction(copyAction)
}
// If we're showing an arrow popup, set the anchor to the long press location.
if let popoverPresentationController = actionSheetController.popoverPresentationController {
popoverPresentationController.sourceView = view
popoverPresentationController.sourceRect = CGRect(origin: touchPoint, size: touchSize)
popoverPresentationController.permittedArrowDirections = .any
popoverPresentationController.delegate = self
}
if actionSheetController.popoverPresentationController != nil {
displayedPopoverController = actionSheetController
}
actionSheetController.title = dialogTitle?.ellipsize(maxLength: ActionSheetTitleMaxLength)
let cancelAction = UIAlertAction(title: UIConstants.CancelString, style: UIAlertActionStyle.cancel, handler: nil)
actionSheetController.addAction(cancelAction)
self.present(actionSheetController, animated: true, completion: nil)
}
fileprivate func getImage(_ url: URL, success: @escaping (UIImage) -> Void) {
Alamofire.request(url)
.validate(statusCode: 200..<300)
.response { response in
if let data = response.data,
let image = UIImage.dataIsGIF(data) ? UIImage.imageFromGIFDataThreadSafe(data) : UIImage.imageFromDataThreadSafe(data) {
success(image)
}
}
}
func contextMenuHelper(_ contextMenuHelper: ContextMenuHelper, didCancelGestureRecognizer: UIGestureRecognizer) {
displayedPopoverController?.dismiss(animated: true) {
self.displayedPopoverController = nil
}
}
}
extension BrowserViewController {
func image(_ image: UIImage, didFinishSavingWithError error: NSError?, contextInfo: UnsafeRawPointer) {
if error == nil {
LeanplumIntegration.sharedInstance.track(eventName: .saveImage)
}
}
}
extension BrowserViewController: HistoryStateHelperDelegate {
func historyStateHelper(_ historyStateHelper: HistoryStateHelper, didPushOrReplaceStateInTab tab: Tab) {
navigateInTab(tab: tab)
tabManager.storeChanges()
}
}
/**
A third party search engine Browser extension
**/
extension BrowserViewController {
func addCustomSearchButtonToWebView(_ webView: WKWebView) {
//check if the search engine has already been added.
let domain = webView.url?.domainURL.host
let matches = self.profile.searchEngines.orderedEngines.filter {$0.shortName == domain}
if !matches.isEmpty {
self.customSearchEngineButton.tintColor = UIColor.gray
self.customSearchEngineButton.isUserInteractionEnabled = false
} else {
self.customSearchEngineButton.tintColor = UIConstants.SystemBlueColor
self.customSearchEngineButton.isUserInteractionEnabled = true
}
/*
This is how we access hidden views in the WKContentView
Using the public headers we can find the keyboard accessoryView which is not usually available.
Specific values here are from the WKContentView headers.
https://github.com/JaviSoto/iOS9-Runtime-Headers/blob/master/Frameworks/WebKit.framework/WKContentView.h
*/
guard let webContentView = UIView.findSubViewWithFirstResponder(webView) else {
/*
In some cases the URL bar can trigger the keyboard notification. In that case the webview isnt the first responder
and a search button should not be added.
*/
return
}
guard let input = webContentView.perform(#selector(getter: UIResponder.inputAccessoryView)),
let inputView = input.takeUnretainedValue() as? UIInputView,
let nextButton = inputView.value(forKey: "_nextItem") as? UIBarButtonItem,
let nextButtonView = nextButton.value(forKey: "view") as? UIView else {
//failed to find the inputView instead lets use the inputAssistant
addCustomSearchButtonToInputAssistant(webContentView)
return
}
inputView.addSubview(self.customSearchEngineButton)
self.customSearchEngineButton.snp.remakeConstraints { make in
make.leading.equalTo(nextButtonView.snp.trailing).offset(20)
make.width.equalTo(inputView.snp.height)
make.top.equalTo(nextButtonView.snp.top)
make.height.equalTo(inputView.snp.height)
}
}
/**
This adds the customSearchButton to the inputAssistant
for cases where the inputAccessoryView could not be found for example
on the iPad where it does not exist. However this only works on iOS9
**/
func addCustomSearchButtonToInputAssistant(_ webContentView: UIView) {
guard customSearchBarButton == nil else {
return //The searchButton is already on the keyboard
}
let inputAssistant = webContentView.inputAssistantItem
let item = UIBarButtonItem(customView: customSearchEngineButton)
customSearchBarButton = item
inputAssistant.trailingBarButtonGroups.last?.barButtonItems.append(item)
}
func addCustomSearchEngineForFocusedElement() {
guard let webView = tabManager.selectedTab?.webView else {
return
}
webView.evaluateJavaScript("__firefox__.searchQueryForField()") { (result, _) in
guard let searchQuery = result as? String, let favicon = self.tabManager.selectedTab!.displayFavicon else {
//Javascript responded with an incorrectly formatted message. Show an error.
let alert = ThirdPartySearchAlerts.failedToAddThirdPartySearch()
self.present(alert, animated: true, completion: nil)
return
}
self.addSearchEngine(searchQuery, favicon: favicon)
self.customSearchEngineButton.tintColor = UIColor.gray
self.customSearchEngineButton.isUserInteractionEnabled = false
}
}
func addSearchEngine(_ searchQuery: String, favicon: Favicon) {
guard searchQuery != "",
let iconURL = URL(string: favicon.url),
let url = URL(string: searchQuery.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlFragmentAllowed)!),
let shortName = url.domainURL.host else {
let alert = ThirdPartySearchAlerts.failedToAddThirdPartySearch()
self.present(alert, animated: true, completion: nil)
return
}
let alert = ThirdPartySearchAlerts.addThirdPartySearchEngine { alert in
self.customSearchEngineButton.tintColor = UIColor.gray
self.customSearchEngineButton.isUserInteractionEnabled = false
SDWebImageManager.shared().loadImage(with: iconURL, options: .continueInBackground, progress: nil) { (image, _, _, _, _, _) in
guard let image = image else {
let alert = ThirdPartySearchAlerts.failedToAddThirdPartySearch()
self.present(alert, animated: true, completion: nil)
return
}
self.profile.searchEngines.addSearchEngine(OpenSearchEngine(engineID: nil, shortName: shortName, image: image, searchTemplate: searchQuery, suggestTemplate: nil, isCustomEngine: true))
let Toast = SimpleToast()
Toast.showAlertWithText(Strings.ThirdPartySearchEngineAdded, bottomContainer: self.webViewContainer)
}
}
self.present(alert, animated: true, completion: {})
}
}
extension BrowserViewController: KeyboardHelperDelegate {
func keyboardHelper(_ keyboardHelper: KeyboardHelper, keyboardWillShowWithState state: KeyboardState) {
keyboardState = state
updateViewConstraints()
UIView.animate(withDuration: state.animationDuration) {
UIView.setAnimationCurve(state.animationCurve)
self.findInPageContainer.layoutIfNeeded()
self.snackBars.layoutIfNeeded()
}
if let webView = tabManager.selectedTab?.webView {
webView.evaluateJavaScript("__firefox__.searchQueryForField()") { (result, _) in
guard let _ = result as? String else {
return
}
self.addCustomSearchButtonToWebView(webView)
}
}
}
func keyboardHelper(_ keyboardHelper: KeyboardHelper, keyboardDidShowWithState state: KeyboardState) {
}
func keyboardHelper(_ keyboardHelper: KeyboardHelper, keyboardWillHideWithState state: KeyboardState) {
keyboardState = nil
updateViewConstraints()
//If the searchEngineButton exists remove it form the keyboard
if let buttonGroup = customSearchBarButton?.buttonGroup {
buttonGroup.barButtonItems = buttonGroup.barButtonItems.filter { $0 != customSearchBarButton }
customSearchBarButton = nil
}
if self.customSearchEngineButton.superview != nil {
self.customSearchEngineButton.removeFromSuperview()
}
UIView.animate(withDuration: state.animationDuration) {
UIView.setAnimationCurve(state.animationCurve)
self.findInPageContainer.layoutIfNeeded()
self.snackBars.layoutIfNeeded()
}
}
}
extension BrowserViewController: SessionRestoreHelperDelegate {
func sessionRestoreHelper(_ helper: SessionRestoreHelper, didRestoreSessionForTab tab: Tab) {
tab.restoring = false
if let tab = tabManager.selectedTab, tab.webView === tab.webView {
updateUIForReaderHomeStateForTab(tab)
}
}
}
extension BrowserViewController: TabTrayDelegate {
// This function animates and resets the tab chrome transforms when
// the tab tray dismisses.
func tabTrayDidDismiss(_ tabTray: TabTrayController) {
resetBrowserChrome()
}
func tabTrayDidAddBookmark(_ tab: Tab) {
guard let url = tab.url?.absoluteString, url.characters.count > 0 else { return }
self.addBookmark(tab.tabState)
}
func tabTrayDidAddToReadingList(_ tab: Tab) -> ReadingListClientRecord? {
guard let url = tab.url?.absoluteString, url.characters.count > 0 else { return nil }
return profile.readingList?.createRecordWithURL(url, title: tab.title ?? url, addedBy: UIDevice.current.name).successValue
}
func tabTrayRequestsPresentationOf(_ viewController: UIViewController) {
self.present(viewController, animated: false, completion: nil)
}
}
// MARK: Browser Chrome Theming
extension BrowserViewController: Themeable {
func applyTheme(_ themeName: String) {
let ui: [Themeable?] = [urlBar, toolbar, readerModeBar, topTabsViewController]
ui.forEach { $0?.applyTheme(themeName) }
statusBarOverlay.backgroundColor = shouldShowTopTabsForTraitCollection(traitCollection) ? UIColor(rgb: 0x272727) : urlBar.backgroundColor
setNeedsStatusBarAppearanceUpdate()
}
}
protocol Themeable {
func applyTheme(_ themeName: String)
}
extension BrowserViewController: FindInPageBarDelegate, FindInPageHelperDelegate {
func findInPage(_ findInPage: FindInPageBar, didTextChange text: String) {
find(text, function: "find")
}
func findInPage(_ findInPage: FindInPageBar, didFindNextWithText text: String) {
findInPageBar?.endEditing(true)
find(text, function: "findNext")
}
func findInPage(_ findInPage: FindInPageBar, didFindPreviousWithText text: String) {
findInPageBar?.endEditing(true)
find(text, function: "findPrevious")
}
func findInPageDidPressClose(_ findInPage: FindInPageBar) {
updateFindInPageVisibility(visible: false)
}
fileprivate func find(_ text: String, function: String) {
guard let webView = tabManager.selectedTab?.webView else { return }
let escaped = text.replacingOccurrences(of: "\\", with: "\\\\")
.replacingOccurrences(of: "\"", with: "\\\"")
webView.evaluateJavaScript("__firefox__.\(function)(\"\(escaped)\")", completionHandler: nil)
}
func findInPageHelper(_ findInPageHelper: FindInPageHelper, didUpdateCurrentResult currentResult: Int) {
findInPageBar?.currentResult = currentResult
}
func findInPageHelper(_ findInPageHelper: FindInPageHelper, didUpdateTotalResults totalResults: Int) {
findInPageBar?.totalResults = totalResults
}
}
extension BrowserViewController: JSPromptAlertControllerDelegate {
func promptAlertControllerDidDismiss(_ alertController: JSPromptAlertController) {
showQueuedAlertIfAvailable()
}
}
extension BrowserViewController: TopTabsDelegate {
func topTabsDidPressTabs() {
urlBar.leaveOverlayMode(didCancel: true)
self.urlBarDidPressTabs(urlBar)
}
func topTabsDidPressNewTab(_ isPrivate: Bool) {
openBlankNewTab(focusLocationField: false, isPrivate: isPrivate)
}
func topTabsDidTogglePrivateMode() {
guard let selectedTab = tabManager.selectedTab else {
return
}
urlBar.leaveOverlayMode()
}
func topTabsDidChangeTab() {
urlBar.leaveOverlayMode(didCancel: true)
}
}
extension BrowserViewController: ClientPickerViewControllerDelegate, InstructionsViewControllerDelegate {
func instructionsViewControllerDidClose(_ instructionsViewController: InstructionsViewController) {
self.popToBVC()
}
func clientPickerViewControllerDidCancel(_ clientPickerViewController: ClientPickerViewController) {
self.popToBVC()
}
func clientPickerViewController(_ clientPickerViewController: ClientPickerViewController, didPickClients clients: [RemoteClient]) {
guard let tab = tabManager.selectedTab,
let url = tab.canonicalURL?.displayURL?.absoluteString else { return }
let shareItem = ShareItem(url: url, title: tab.title, favicon: tab.displayFavicon)
guard shareItem.isShareable else {
let alert = UIAlertController(title: Strings.SendToErrorTitle, message: Strings.SendToErrorMessage, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: Strings.SendToErrorOKButton, style: .default) { _ in self.popToBVC()})
present(alert, animated: true, completion: nil)
return
}
profile.sendItems([shareItem], toClients: clients).uponQueue(DispatchQueue.main) { _ in
self.popToBVC()
}
}
}
|
883e3118117e0330282c6ba68576aee4
| 43.348398 | 406 | 0.65786 | false | false | false | false |
CSSE497/pathfinder-ios
|
refs/heads/master
|
examples/Chimney Swap/Chimney Swap/EmployeeLoginViewController.swift
|
mit
|
1
|
//
// EmployeeLoginViewController.swift
// Chimney Swap
//
// Created by Adam Michael on 11/8/15.
// Copyright © 2015 Pathfinder. All rights reserved.
//
import Foundation
class EmployeeLoginViewController : UIViewController {
@IBAction func signInEmployee() {
let interfaceManager = GITInterfaceManager()
interfaceManager.delegate = self
GITClient.sharedInstance().delegate = self
interfaceManager.startSignIn()
}
}
extension EmployeeLoginViewController : GITInterfaceManagerDelegate, GITClientDelegate {
func client(client: GITClient!, didFinishSignInWithToken token: String!, account: GITAccount!, error: NSError!) {
print("GIT finished sign in and returned token \(token) for account \(account) with error \(error)")
let userDefaults = NSUserDefaults.standardUserDefaults()
userDefaults.setObject(token, forKey: "employeeToken")
userDefaults.synchronize()
self.performSegueWithIdentifier("signInEmployee", sender: token)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
let destination = (segue.destinationViewController) as! EmployeeViewController
destination.idToken = sender as! String
}
}
|
d5ed37dbd3dc5e60e10c2f60a0be6523
| 33.114286 | 115 | 0.760268 | false | false | false | false |
ifabijanovic/RxBattleNet
|
refs/heads/master
|
RxBattleNet/WoW/Model/GuildReward.swift
|
mit
|
1
|
//
// GuildReward.swift
// RxBattleNet
//
// Created by Ivan Fabijanović on 06/08/16.
// Copyright © 2016 Ivan Fabijanovic. All rights reserved.
//
import SwiftyJSON
public extension WoW {
public struct GuildReward: Model {
// MARK: - Properties
public let minGuildLevel: Int
public let minGuildRepLevel: Int
public let races: [Int]
public let achievement: WoW.Achievement
public let item: WoW.Item
// MARK: - Init
internal init(json: JSON) {
self.minGuildLevel = json["minGuildLevel"].intValue
self.minGuildRepLevel = json["minGuildRepLevel"].intValue
self.races = json["races"].map { $1.intValue }
self.achievement = WoW.Achievement(json: json["achievement"])
self.item = WoW.Item(json: json["item"])
}
}
}
|
77342a0c51a35d0ba9684d77839c5f02
| 25 | 73 | 0.579121 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.