repo_name
stringlengths 6
91
| path
stringlengths 8
968
| copies
stringclasses 210
values | size
stringlengths 2
7
| content
stringlengths 61
1.01M
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6
99.8
| line_max
int64 12
1k
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.89
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
DanielOYC/Tools | YCEmoticonKeyboard/YCEmoticonKeyboard/YCEmoticonView/Model/YCEmoticons.swift | 1 | 2367 | //
// YCEmoticons.swift
// YCEmoticonKeyboard
//
// Created by daniel on 2017/8/20.
// Copyright ยฉ 2017ๅนด daniel. All rights reserved.
// ๆไธ็ง่กจๆ
ๅ
ๆจกๅ
import UIKit
class YCEmoticons: NSObject {
var id: String? //่กจๆ
ๆๅจๆไปถๅคนๅ
var group_name_cn: String? //็ป่กจๆ
ๅ
ๅ
var emoticons: [YCEmoticon] = [YCEmoticon]() //่กจๆ
ๆฐ็ป
init(dic: [String : Any]) {
super.init()
setValuesForKeys(dic)
}
override func setValue(_ value: Any?, forKey key: String) {
if key == "emoticons" {
if let arr = value as? NSArray {
arr.enumerateObjects({ (obj, index, _) in
let tempIndex = index + index / 21
if (tempIndex + 1) % 21 == 0 {
let deleteEmoticon = YCEmoticon(dic: ["" : ""])
deleteEmoticon.isDelete = true
emoticons.append(deleteEmoticon)
}
let emoticon = YCEmoticon(dic: obj as! [String : Any])
if emoticon.png != nil {
emoticon.pngPath = "Emoticons.bundle/" + id! + "/"
}else {
if let code = emoticon.code {
emoticon.emoji = code.emoji
}
}
emoticons.append(emoticon)
})
}
let emptyCout = 21 - emoticons.count % 21 - 1
for _ in 0..<emptyCout {
let emptyEmoticon = YCEmoticon(dic: ["" : ""])
emptyEmoticon.isEmpty = true
emoticons.append(emptyEmoticon)
}
let deleteEmoticon = YCEmoticon(dic: ["" : ""])
deleteEmoticon.isDelete = true
emoticons.append(deleteEmoticon)
return
}
super.setValue(value, forKey: key)
}
override func setValue(_ value: Any?, forUndefinedKey key: String) {}
override var description: String {
let keys = ["id","group_name_cn"]
return dictionaryWithValues(forKeys: keys).description
}
}
| mit | f2be09b8d35b752a5599924398c2eca2 | 30.69863 | 74 | 0.450735 | 5.235294 | false | false | false | false |
Zewo/OpenSSL | Sources/OpenSSL/DWrap.swift | 4 | 3440 | import COpenSSL
public let BIO_TYPE_DWRAP: Int32 = (50 | 0x0400 | 0x0200)
private var methods_dwrap = BIO_METHOD(type: BIO_TYPE_DWRAP, name: "dtls_wrapper", bwrite: dwrap_write, bread: dwrap_read, bputs: dwrap_puts, bgets: dwrap_gets, ctrl: dwrap_ctrl, create: dwrap_new, destroy: dwrap_free, callback_ctrl: { bio, cmd, fp in
return BIO_callback_ctrl(bio!.pointee.next_bio, cmd, fp)
})
private func getPointer<T>(_ arg: UnsafeMutablePointer<T>) -> UnsafeMutablePointer<T> {
return arg
}
public func BIO_f_dwrap() -> UnsafeMutablePointer<BIO_METHOD> {
return getPointer(&methods_dwrap)
}
func OPENSSL_malloc(_ num: Int, file: String = #file, line: Int = #line) -> UnsafeMutableRawPointer {
return CRYPTO_malloc(Int32(num), file, Int32(line))
}
func OPENSSL_free(_ ptr: UnsafeMutableRawPointer) {
CRYPTO_free(ptr)
}
let BIO_FLAGS_RWS = (BIO_FLAGS_READ|BIO_FLAGS_WRITE|BIO_FLAGS_IO_SPECIAL)
func BIO_clear_retry_flags(_ b: UnsafeMutablePointer<BIO>) {
BIO_clear_flags(b, BIO_FLAGS_RWS|BIO_FLAGS_SHOULD_RETRY)
}
private struct BIO_F_DWRAP_CTX {
var dgram_timer_exp: Bool
}
private func dwrap_new(bio: UnsafeMutablePointer<BIO>?) -> Int32 {
let ctx = OPENSSL_malloc(MemoryLayout<BIO_F_DWRAP_CTX>.size)
memset(ctx, 0, MemoryLayout<BIO_F_DWRAP_CTX>.size)
let b = bio!.pointee
bio!.pointee = BIO(method: b.method, callback: b.callback, cb_arg: b.cb_arg, init: 1, shutdown: b.shutdown, flags: 0, retry_reason: b.retry_reason, num: b.num, ptr: ctx, next_bio: b.next_bio, prev_bio: b.prev_bio, references: b.references, num_read: b.num_read, num_write: b.num_write, ex_data: b.ex_data)
return 1
}
private func dwrap_free(bio: UnsafeMutablePointer<BIO>?) -> Int32 {
guard let bio = bio else { return 0 }
OPENSSL_free(bio.pointee.ptr)
let b = bio.pointee
bio.pointee = BIO(method: b.method, callback: b.callback, cb_arg: b.cb_arg, init: 0, shutdown: b.shutdown, flags: 0, retry_reason: b.retry_reason, num: b.num, ptr: nil, next_bio: b.next_bio, prev_bio: b.prev_bio, references: b.references, num_read: b.num_read, num_write: b.num_write, ex_data: b.ex_data)
return 1
}
private func dwrap_read(bio: UnsafeMutablePointer<BIO>?, data: UnsafeMutablePointer<Int8>?, length: Int32) -> Int32 {
guard let bio = bio, let data = data else { return 0 }
BIO_clear_retry_flags(bio)
let ret = BIO_read(bio.pointee.next_bio, data, length)
if ret <= 0 {
BIO_copy_next_retry(bio)
}
return ret
}
private func dwrap_write(bio: UnsafeMutablePointer<BIO>?, data: UnsafePointer<Int8>?, length: Int32) -> Int32 {
guard let bio = bio, let data = data, length > 0 else { return 0 }
return BIO_write(bio.pointee.next_bio, data, length)
}
private func dwrap_puts(bio: UnsafeMutablePointer<BIO>?, data: UnsafePointer<Int8>?) -> Int32 {
fatalError()
}
private func dwrap_gets(bio: UnsafeMutablePointer<BIO>?, data: UnsafeMutablePointer<Int8>?, length: Int32) -> Int32 {
fatalError()
}
private func dwrap_ctrl(bio: UnsafeMutablePointer<BIO>?, cmd: Int32, num: Int, ptr: UnsafeMutableRawPointer?) -> Int {
let ctx = bio!.pointee.ptr.assumingMemoryBound(to: BIO_F_DWRAP_CTX.self)
var ret: Int
switch cmd {
case BIO_CTRL_DGRAM_GET_RECV_TIMER_EXP:
if ctx.pointee.dgram_timer_exp {
ret = 1
ctx.pointee.dgram_timer_exp = false
} else {
ret = 0
}
case BIO_CTRL_DGRAM_SET_RECV_TIMEOUT:
ctx.pointee.dgram_timer_exp = true
ret = 1
default:
ret = BIO_ctrl(bio!.pointee.next_bio, cmd, num, ptr)
}
return ret
}
| mit | 3797900c76a648a3a931e9172621c739 | 33.059406 | 306 | 0.70843 | 2.885906 | false | false | false | false |
DJBCompany/DHNote | NoteBook/NoteBook/HZCategoryController.swift | 1 | 9187 | //
// HZCategoryController.swift
// NoteBook
//
// Created by chris on 16/4/27.
// Copyright ยฉ 2016ๅนด chris. All rights reserved.
//
import UIKit
class HZCategoryController: UITableViewController {
///้ป่ฎคๆฐๆฎ
var editingClick = true
var _allDataArr: [[String:NSObject]]?
// var allDataArr: [[String:NSObject]] = [["header":"้ป่ฎค","data":[AnyObject]()]]
var allDataArr:[[String:NSObject]]{
get{
if _allDataArr == nil {
_allDataArr = NSKeyedUnarchiver.unarchiveObjectWithFile(getDocumentPath()) as? [[String:NSObject]]
if _allDataArr == nil {
_allDataArr = [["header":"้ป่ฎค","data":[AnyObject]()]]
}
}
return _allDataArr!
}
set {
_allDataArr = newValue
}
}
var isHidden = false
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.title = "ๅ็ฑป"
let leftBarButtonItem = UIBarButtonItem(title: "ๆฐๅปบ", style: .Plain, target: self, action: "new")
navigationItem.leftBarButtonItem = leftBarButtonItem
let rightBtn = UIButton()
rightBtn.setTitle("็ผ่พ", forState: .Normal)
rightBtn.titleLabel?.font = UIFont.systemFontOfSize(14)
rightBtn.addTarget(self, action: Selector("edit"), forControlEvents: .TouchUpInside)
rightBtn.sizeToFit()
let righBarButtonItem = UIBarButtonItem(customView: rightBtn)
navigationItem.rightBarButtonItem = righBarButtonItem;
let textProperties = [NSFontAttributeName:UIFont.systemFontOfSize(14),NSForegroundColorAttributeName:UIColor.whiteColor()]
leftBarButtonItem.setTitleTextAttributes(textProperties, forState: .Normal)
righBarButtonItem.setTitleTextAttributes(textProperties, forState: .Normal)
tableView.registerClass(HZNoteCell.self, forCellReuseIdentifier: "cell")
}
///ๆ้ฎ็นๅปไบไปถ
func new(){
if(!isHidden){
self.navigationController?.view.addSubview(popView)
}else{
popView.removeFromSuperview()
}
isHidden = !isHidden
}
func edit(){
if(editingClick){
tableView.editing = true
}else{
tableView.editing = false
}
editingClick = !editingClick
}
override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
return true
}
override func tableView(tableView: UITableView, editingStyleForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCellEditingStyle {
return .Delete
}
override func tableView(tableView: UITableView, moveRowAtIndexPath sourceIndexPath: NSIndexPath, toIndexPath destinationIndexPath: NSIndexPath) {
var dic1 = allDataArr[sourceIndexPath.section]
var tempArr1 = dic1["data"] as! [AnyObject]
let note = tempArr1[sourceIndexPath.row]
tempArr1.removeAtIndex(sourceIndexPath.row)
allDataArr[sourceIndexPath.section]["data"] = tempArr1
var dic2 = allDataArr[destinationIndexPath.section]
var tempArr2 = dic2["data"] as! [AnyObject]
tempArr2.insert(note, atIndex: destinationIndexPath.row)
allDataArr[destinationIndexPath.section]["data"] = tempArr2
self.saveToLocation()
//self.tableView.reloadData()
}
override func tableView(tableView: UITableView, var commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
editingStyle = UITableViewCellEditingStyle.Delete
var dic = allDataArr[indexPath.section]
var tempArr = dic["data"] as! [AnyObject]
tempArr.removeAtIndex(indexPath.row)
allDataArr[indexPath.section]["data"] = tempArr
self.saveToLocation()
self.tableView.reloadData()
}
///ๆๅ ่ฝฝpopView
lazy var popView:UIView = {
let popView = UIView()
popView .removeFromSuperview()
popView.frame = CGRectMake(0, 64, 150, 80);
let btn1 = UIButton()
btn1.backgroundColor = UIColor.greenColor()
btn1.setTitle("item", forState: .Normal)
btn1.setTitleColor(UIColor.blackColor(), forState: .Normal)
btn1.frame = CGRectMake(0, 0,popView.bounds.width , popView.bounds.height*0.5)
popView.addSubview(btn1)
btn1.addTarget(self, action: Selector("addItem"), forControlEvents: .TouchUpInside)
let btn2 = UIButton()
btn2.backgroundColor = UIColor.greenColor()
btn2.setTitle("class", forState: .Normal)
btn2.setTitleColor(UIColor.blackColor(), forState: .Normal)
btn2.frame = CGRectMake(0, popView.bounds.height*0.5,popView.bounds.width , popView.bounds.height*0.5)
popView.addSubview(btn2)
btn2.addTarget(self, action: Selector("addClass"), forControlEvents: .TouchUpInside)
let seperatorView1 = UIView()
seperatorView1.frame = CGRectMake(0, popView.bounds.height*0.5, popView.bounds.width, 1)
seperatorView1.backgroundColor = UIColor.grayColor()
popView.addSubview(seperatorView1)
let seperatorView2 = UIView()
seperatorView2.frame = CGRectMake(0, popView.bounds.height, popView.bounds.width, 1)
seperatorView2.backgroundColor = UIColor.grayColor()
popView.addSubview(seperatorView2)
let seperatorView3 = UIView()
seperatorView3.frame = CGRectMake(popView.bounds.width-1, 0, 1 , popView.bounds.height)
seperatorView3.backgroundColor = UIColor.grayColor()
popView.addSubview(seperatorView3)
return popView
}()
func addClass(){
let classVc = HZClassViewController()
classVc.classclosure = {(dic:[String:NSObject])->() in
self.allDataArr.append(dic)
self.saveToLocation()
self.tableView.reloadData()
}
presentViewController(classVc, animated: true, completion: nil)
new()
}
func addItem(){
let noteVc = HZNoteController()
if(tableView.editing == true){
tableView.editing = false
}
noteVc.noteClosure = {(dict:[String:NSObject])->() in
var dic = self.allDataArr[0]
var dataArr = dic["data"] as! [[String:NSObject]]
dataArr.append(dict)
self.allDataArr[0]["data"] = dataArr
self.saveToLocation()
self.tableView.reloadData()
}
navigationController?.showViewController(noteVc, sender: nil)
new()
}
func getDocumentPath()-> String{
let documentPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).last
return (documentPath! as NSString).stringByAppendingPathComponent("note")
}
func saveToLocation(){
NSKeyedArchiver.archiveRootObject(allDataArr, toFile: getDocumentPath())
}
}
extension HZCategoryController{
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return allDataArr.count
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let dict = allDataArr[section]
let dataArr = dict["data"] as! [[String:NSObject]]
return dataArr.count
}
override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
let dict = allDataArr[section]
return dict["header"] as? String
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! HZNoteCell
let dic = allDataArr[indexPath.section]
let dataArr = dic["data"] as! [[String:NSObject]]
let rowDic = dataArr[indexPath.row]
cell.dic = rowDic
return cell
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let contentVc = HZContentController()
let dic = allDataArr[indexPath.section]
var dataArr = dic["data"] as! [[String:NSObject]]
let rowDic = dataArr[indexPath.row]
contentVc.dic = rowDic
contentVc.reloadClourse = {(dic:[String:NSObject])->() in
dataArr[indexPath.row] = dic
self.allDataArr[indexPath.section]["data"] = dataArr
self.saveToLocation()
self.tableView.reloadData()
}
navigationController?.showViewController(contentVc, sender: nil)
}
}
| mit | 4f6015541e569e5df48f52c556dbcdd3 | 27.645768 | 161 | 0.615343 | 5.288194 | false | false | false | false |
DDSSwiftTech/SwiftMine | Sources/SwiftMineCore/src/Player/Player.swift | 1 | 1234 | //
// Player.swift
// SwiftMine
//
// Created by David Schwartz on 8/3/16.
// Copyright ยฉ 2016 David Schwartz. All rights reserved.
//
import Foundation
//import simd
final public class Player: Entity, CommandSender {
let GUID: UInt64
let CID: String
let XUID: String
// let dataHandler: PlayerDataHandler
// let spawn: vector_double3
init(name: String, GUID: UInt64, CID: String, XUID: String) {
self.GUID = GUID
self.CID = CID
self.XUID = XUID
// self.dataHandler = PlayerDataHandler(playerName: self.name)
// let settingsDict = (dataHandler.NBTFileContents!.fileContentsObject! as! Dictionary<String, Any>)
// self.spawn = vector_double3(x: ((settingsDict["Pos"]! as! Array<Double>)[0]),
// y: ((settingsDict["Pos"]! as! Array<Double>)[1]),
// z: ((settingsDict["Pos"]! as! Array<Double>)[2])
// )
super.init(name: name, spawn: vector_float3(0, 100, 0))
}
deinit {
// self.dataHandler.writeNBTSync()
}
// class Recipient {
// init(<#parameters#>) {
// <#statements#>
// }
// }
}
| apache-2.0 | 75b884c500f17f9aa698a78a231467a4 | 26.4 | 107 | 0.549067 | 3.713855 | false | false | false | false |
googlemaps/google-maps-ios-utils | test/unit/Heatmap/HeatMapInterpolationTests.swift | 1 | 8120 | /* Copyright (c) 2020 Google 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
@testable import GoogleMapsUtils
class HeatMapInterpolationTests: XCTestCase {
private var gradientColor: [UIColor]!
private var startPoints: [NSNumber]!
private var colorMapSize: UInt!
private let interpolationController = HeatMapInterpolationPoints()
override func setUp() {
super.setUp()
gradientColor = [
UIColor(red: 102.0 / 255.0, green: 225.0 / 255.0, blue: 0, alpha: 1),
UIColor(red: 1.0, green: 0, blue: 0, alpha: 1)
]
startPoints = [0.005, 0.7] as [NSNumber]
colorMapSize = 3
}
func testInitWithColors() {
let gradient = GMUGradient(
colors: gradientColor,
startPoints: startPoints,
colorMapSize: colorMapSize
)
XCTAssertEqual(gradient.colors.count, gradient.startPoints.count)
}
func testWithTooSmallN() {
let newGMU = GMUWeightedLatLng(
coordinate: CLLocationCoordinate2D(latitude: -20.86 , longitude: 145.20),
intensity: 500
)
let newGMU2 = GMUWeightedLatLng(
coordinate: CLLocationCoordinate2D(latitude: -20.85, longitude: 145.20),
intensity: 20
)
let newGMU3 = GMUWeightedLatLng(
coordinate: CLLocationCoordinate2D(latitude: -32, longitude: 145.20),
intensity: 500
)
interpolationController.addWeightedLatLng(latlng: newGMU)
interpolationController.addWeightedLatLng(latlng: newGMU2)
interpolationController.addWeightedLatLng(latlng: newGMU3)
do {
_ = try interpolationController.generatePoints(influence: 1)
} catch {
print("\(error)")
XCTAssertTrue(true)
}
do {
_ = try interpolationController.generatePoints(influence: 0.5)
} catch {
print("\(error)")
XCTAssertTrue(true)
}
do {
_ = try interpolationController.generatePoints(influence: 1.9999999)
} catch {
print("\(error)")
XCTAssertTrue(true)
}
do {
_ = try interpolationController.generatePoints(influence: 1.5)
} catch {
print("\(error)")
XCTAssertTrue(true)
}
}
func testWithTooLargeN() {
let newGMU = GMUWeightedLatLng(
coordinate: CLLocationCoordinate2D(latitude: -20.86 , longitude: 145.20),
intensity: 500
)
let newGMU2 = GMUWeightedLatLng(
coordinate: CLLocationCoordinate2D(latitude: -20.85, longitude: 145.20),
intensity: 20
)
let newGMU3 = GMUWeightedLatLng(
coordinate: CLLocationCoordinate2D(latitude: -32, longitude: 145.20),
intensity: 500
)
interpolationController.addWeightedLatLng(latlng: newGMU)
interpolationController.addWeightedLatLng(latlng: newGMU2)
interpolationController.addWeightedLatLng(latlng: newGMU3)
do {
_ = try interpolationController.generatePoints(influence: 2.500001)
} catch {
print("\(error)")
XCTAssertTrue(true)
}
do {
_ = try interpolationController.generatePoints(influence: 3)
} catch {
print("\(error)")
XCTAssertTrue(true)
}
do {
_ = try interpolationController.generatePoints(influence: 100000)
} catch {
print("\(error)")
XCTAssertTrue(true)
}
}
func testWithAcceptableN() {
let newGMU = GMUWeightedLatLng(
coordinate: CLLocationCoordinate2D(latitude: -20.86 , longitude: 145.20),
intensity: 500
)
let newGMU2 = GMUWeightedLatLng(
coordinate: CLLocationCoordinate2D(latitude: -20.85, longitude: 145.20),
intensity: 20
)
let newGMU3 = GMUWeightedLatLng(
coordinate: CLLocationCoordinate2D(latitude: -32, longitude: 145.20),
intensity: 500
)
interpolationController.addWeightedLatLng(latlng: newGMU)
interpolationController.addWeightedLatLng(latlng: newGMU2)
interpolationController.addWeightedLatLng(latlng: newGMU3)
do {
let data = try interpolationController.generatePoints(influence: 2.4)
XCTAssertLessThan(0, data.count)
} catch {
print("\(error)")
XCTAssertTrue(false)
}
do {
let data = try interpolationController.generatePoints(influence: 2.3)
XCTAssertLessThan(0, data.count)
} catch {
print("\(error)")
XCTAssertTrue(false)
}
}
func testNoDataset() {
do {
let data = try interpolationController.generatePoints(influence: 2)
XCTAssertEqual(0, data.count)
} catch {
print("\(error)")
XCTAssertTrue(false)
}
}
func testMultipleCalls() {
let newGMU = GMUWeightedLatLng(
coordinate: CLLocationCoordinate2D(latitude: -20.86 , longitude: 145.20),
intensity: 500
)
let newGMU2 = GMUWeightedLatLng(
coordinate: CLLocationCoordinate2D(latitude: -20.85, longitude: 145.20),
intensity: 20
)
let newGMU3 = GMUWeightedLatLng(
coordinate: CLLocationCoordinate2D(latitude: -32, longitude: 145.20),
intensity: 500
)
interpolationController.addWeightedLatLng(latlng: newGMU)
interpolationController.addWeightedLatLng(latlng: newGMU2)
interpolationController.addWeightedLatLng(latlng: newGMU3)
do {
var data = try interpolationController.generatePoints(influence: 2)
let first = data.count
data = try interpolationController.generatePoints(influence: 2)
XCTAssertEqual(first, data.count)
} catch {
print("\(error)")
XCTAssertTrue(false)
}
}
func testListOfPoints() {
let newGMU = GMUWeightedLatLng(
coordinate: CLLocationCoordinate2D(latitude: -20.86 , longitude: 145.20),
intensity: 500
)
let newGMU2 = GMUWeightedLatLng(
coordinate: CLLocationCoordinate2D(latitude: -20.85, longitude: 145.20),
intensity: 20
)
let newGMU3 = GMUWeightedLatLng(
coordinate: CLLocationCoordinate2D(latitude: -32, longitude: 145.20),
intensity: 500
)
let points = [newGMU, newGMU2, newGMU3]
interpolationController.addWeightedLatLngs(latlngs: points)
do {
let data = try interpolationController.generatePoints(influence: 2.4)
XCTAssertLessThan(0, data.count)
} catch {
print("\(error)")
XCTAssertTrue(false)
}
}
func testDuplicatePoint() {
let newGMU = GMUWeightedLatLng(
coordinate: CLLocationCoordinate2D(latitude: -20.86 , longitude: 145.20),
intensity: 500
)
let points = [newGMU, newGMU, newGMU]
interpolationController.addWeightedLatLngs(latlngs: points)
do {
let data = try interpolationController.generatePoints(influence: 2.4)
XCTAssertLessThan(0, data.count)
} catch {
print("\(error)")
XCTAssertTrue(false)
}
}
}
| apache-2.0 | 37c1122f76532a818507effb1c8c7010 | 34 | 85 | 0.597044 | 5.145754 | false | true | false | false |
meetkei/KxUI | KxUI/TableView/Cell/KUTableViewCell.swift | 1 | 3116 | //
// Copyright (c) 2016 Keun young Kim <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
//public protocol KUTableViewCellCompatible: class {
// associatedtype DataType
// associatedtype CellType
//
// func compose(with data: DataType?)
// static func dequeueComposedCell(from tableView: UITableView, data: DataType?) -> CellType
//}
/**
ํ
์ด๋ธ๋ทฐ ์
๊ณตํต ํด๋์ค
*/
open class KUTableViewCell<T>: UITableViewCell {
/// ์
๊ณ ์ ๋์ด
open class var cellHeight: CGFloat {
#if swift(>=4.2)
return UITableView.automaticDimension
#else
return UITableViewAutomaticDimension
#endif
}
/**
์
์ฌ์ฌ์ฉ ์๋ณ์
์ฌ์ฌ์ฉ ์๋ณ์๋ ํด๋์ค ์ด๋ฆ์ผ๋ก ๊ณ ์ ํฉ๋๋ค.
*/
open class var cellIdentifier: String {
let fq = NSStringFromClass(self.classForCoder())
if let range = fq.range(of: ".", options: .backwards) {
#if swift(>=4.0)
return String(fq[fq.index(after: range.lowerBound)...])
#else
return fq.substring(from: fq.index(after: range.lowerBound))
#endif
}
return fq
}
/**
ํ
์ด๋ธ๋ทฐ์ ์ฌ์ฌ์ฉ ํ์์ ์๋ก์ด ์
์ ๋ฆฌํดํฉ๋๋ค.
- Parameter tableView: ๋์ ํ
์ด๋ธ๋ทฐ
- Parameter data: ์
๊ตฌ์ฑ์ ์ฌ์ฉํ ๋ฐ์ดํฐ
- Returns: ๋ฐ์ดํฐ ๊ตฌ์ฑ์ด ์๋ฃ๋ ํ
์ด๋ธ๋ทฐ ์
. ์ ์์ ์ผ๋ก ๊ตฌ์ฑํ ์ ์๋ ๊ฒฝ์ฐ nil์ ๋ฆฌํดํ์ฌ ์์ธ๊ฐ ๋ฐ์ํ๋๋ก ํฉ๋๋ค.
*/
open class func dequeueComposedCell<C: KUTableViewCell>(from tableView: UITableView, data: T?) -> C {
let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier) as! C
cell.compose(with: data)
return cell
}
/**
์ ๋ฌ๋ ๋ฐ์ดํฐ๋ฅผ ํตํด ์
์ ๊ตฌ์ฑํฉ๋๋ค.
- Parameter data: ์
๊ตฌ์ฑ์ ์ฌ์ฉ๋๋ ๋ฐ์ดํฐ
*/
open func compose(with data: T?) {
// do nothing
}
}
| mit | 6bb97245bacfd0661e458f6206ed9c76 | 31.413793 | 105 | 0.652128 | 3.790323 | false | false | false | false |
rjstelling/State | Documentation/State Tests Playground.playground/Contents.swift | 1 | 2531 | /*: **State Tests** - this is a quike overview of how to use State.
State is a very simple FSM. It vends a very simple delegate that can be used to observe the state cahnge.*/
import XCPlayground
import State
//Page set up
let page = XCPlaygroundPage.currentPage
//Frist, create an object that will implement the State delegate functions.
class ElectricCar : StateDelegate {
//: **Finite States Enum**
enum CarState {
case Parked
case Driving
case Charging
case BrokenDown
}
typealias StateType = CarState
//MARK: StateDelegate functions
//:Simple switch/case statements can be used to define the logic of the state machine.
func shouldTransitionFrom(from:StateType, to:StateType) -> Bool {
switch (from, to) {
case(.Parked, .Driving),
(.Parked, .Charging):
return true
case(.Driving, .Parked),
(.Driving, .BrokenDown):
return true
case(.Charging, .Parked):
return true
case(.BrokenDown, .Parked):
return true
// For anything not explicity listed above re return false and do not change the state
default:
return false
}
}
func didTransitionFrom(from:StateType, to:StateType) {
page.captureValue(to, withIdentifier: "Succssful State Change")
page.captureValue(to, withIdentifier: "State")
}
func failedTransitionFrom(from:StateType, to:StateType) {
page.captureValue(to, withIdentifier: "Failed State Change")
page.captureValue(from, withIdentifier: "State")
}
}
//: Next, we create a `State` object passing in the `ElecticCar` object as a type and delegate
let car = ElectricCar()
let stateMachine = State<ElectricCar>(initialState: .Parked, delegate: car)
//: Simple tests to show successful state changes and failed state changes
stateMachine.state = .Driving //This should work
stateMachine.state = .BrokenDown
stateMachine.state = .Parked
stateMachine.state = .Charging
stateMachine.state = .BrokenDown //This should not work
stateMachine.state = .Parked
stateMachine.state = .Driving
stateMachine.state = .BrokenDown
stateMachine.state = .Charging
//: Tests โ this is a simple test to make sure State meets all our assumptions, it si not a replacement for formal unit tests
assert(stateMachine.state == .BrokenDown, "State did not change as expected!")
| mit | 82d4c8ff2f83ac13cfd7b8b5a8672104 | 30.222222 | 125 | 0.659549 | 4.735955 | false | true | false | false |
kyle791121/Lookout | Lookout/Lookout/EventCoreDataManager.swift | 1 | 2803 | //
// EventCoreDataManager.swift
// Lookout
//
// Created by Chunkai Chan on 2016/10/16.
// Copyright ยฉ 2016ๅนด Chunkai Chan. All rights reserved.
//
import Foundation
import CoreData
protocol EventCoreDataManagerDelegate: class {
func manager(manager: EventCoreDataManager, didSaveEventData: AnyObject)
func manager(manager: EventCoreDataManager, getFetchEventError: ErrorType)
func manager(manager: EventCoreDataManager, didFetchEventData: AnyObject)
}
extension EventCoreDataManagerDelegate {
func manager(manager: EventCoreDataManager, didSaveEventData: AnyObject) {}
func manager(manager: EventCoreDataManager, getFetchEventError: ErrorType) {}
func manager(manager: EventCoreDataManager, didFetchEventData: AnyObject) {}
}
class EventCoreDataManager {
static let shared = EventCoreDataManager()
private init() {
}
private let entityName = "Events"
private var moc = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext
weak var delegate: EventCoreDataManagerDelegate?
func saveCoreData(eventToSave eventToSave: Event) {
let event = NSEntityDescription.insertNewObjectForEntityForName(entityName, inManagedObjectContext: moc) as! Events
event.time = eventToSave.time
event.data = eventToSave.data
event.latitude = eventToSave.latitude
event.longitude = eventToSave.longitude
event.isAccident = eventToSave.isAccident
do {
try self.moc.save()
print("Save new event to core data.")
} catch {
fatalError("Error occurs while saving an event.")
}
}
func fetchCoreData() {
let request = NSFetchRequest(entityName: entityName)
do {
guard let results = try moc.executeFetchRequest(request) as? [Events] else {fatalError()}
delegate?.manager(self, didFetchEventData: results)
} catch {
delegate?.manager(self, getFetchEventError: error)
}
}
func clearCoreData() {
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let managedContext = appDelegate.managedObjectContext
let fetchRequest = NSFetchRequest(entityName: entityName)
fetchRequest.returnsObjectsAsFaults = false
do
{
let results = try managedContext.executeFetchRequest(fetchRequest)
for managedObject in results
{
let managedObjectData:NSManagedObject = managedObject as! NSManagedObject
managedContext.deleteObject(managedObjectData)
}
print("Clear events core data")
} catch let error as NSError {
print(error)
}
}
} | mit | cd43bb66297cc5d87de2eb4d2f90a78f | 33.580247 | 123 | 0.675 | 5.522682 | false | false | false | false |
steelwheels/Coconut | CoconutData/Source/File/CNFile.swift | 1 | 5991 | /*
* @file CNFile.swift
* @brief Define CNFile, CNTextFile protocols
* @par Copyright
* Copyright (C) 2017-2021 Steel Wheels Project
*/
import Foundation
public class CNFile
{
public static let EOF: Int32 = -1
public enum Access {
case reader
case writer
}
public enum Char {
case char(Character)
case endOfFile
case null
}
public enum Line {
case line(String)
case endOfFile
case null
}
public enum Str {
case str(String)
case endOfFile
case null
}
private enum Stream {
case handle(FileHandle)
case pipe(Pipe)
}
private var mAccess: Access
private var mFile: Stream
private var mInputBuffer: String
private var mInputLock: NSLock
private var mReadDone: Bool
public init(access acc: Access, fileHandle handle: FileHandle){
mAccess = acc
mFile = .handle(handle)
mInputBuffer = ""
mInputLock = NSLock()
mReadDone = false
switch acc {
case .reader:
setupCallback(fileHandle: handle)
case .writer:
break
}
}
public init(access acc: Access, pipe pip: Pipe){
mAccess = acc
mFile = .pipe(pip)
mInputBuffer = ""
mInputLock = NSLock()
mReadDone = false
switch acc {
case .reader:
setupCallback(fileHandle: pip.fileHandleForReading)
case .writer:
break
}
}
private func setupCallback(fileHandle hdl: FileHandle) {
hdl.readabilityHandler = {
[weak self] (_ hdl: FileHandle) -> Void in
if let myself = self {
myself.mInputLock.lock()
let data = hdl.availableData
if data.count > 0 {
if let str = String(data: data, encoding: .utf8) {
myself.mInputBuffer += str
} else {
CNLog(logLevel: .error, message: "Failed to decode input", atFunction: #function, inFile: #file)
}
} else {
myself.mReadDone = true
myself.fileHandle.readabilityHandler = nil
}
myself.mInputLock.unlock()
}
}
}
deinit {
switch mAccess {
case .reader:
fileHandle.readabilityHandler = nil
case .writer:
break
}
}
public static func open(access acc: Access, for url: URL) -> CNFile? {
switch acc {
case .reader:
return open(forReading: url)
case .writer:
return open(forWriting: url)
}
}
public static func open(forReading url: URL) -> CNFile? {
do {
let handle = try FileHandle(forReadingFrom: url)
return CNFile(access: .reader, fileHandle: handle)
} catch {
return nil
}
}
public static func open(forWriting url: URL) -> CNFile? {
do {
let path = url.path
if FileManager.default.createFile(atPath: path, contents: nil, attributes: nil) {
let handle = try FileHandle(forWritingTo: url)
return CNFile(access: .reader, fileHandle: handle)
}
return nil
} catch {
return nil
}
}
public func close() {
switch mAccess {
case .reader:
mReadDone = true
switch mFile {
case .handle(let hdl):
hdl.closeFile()
case .pipe(let pipe):
pipe.fileHandleForReading.closeFile()
}
case .writer:
switch mFile {
case .handle(let hdl):
hdl.closeFile()
case .pipe(let pipe):
pipe.fileHandleForWriting.closeFile()
}
}
}
public func closeWritePipe(){
switch mFile {
case .handle(_):
break
case .pipe(let pipe):
switch mAccess {
case .reader:
break
case .writer:
pipe.fileHandleForWriting.closeFile()
}
}
}
public func activateReaderHandler(enable en: Bool) {
switch mAccess {
case .reader:
switch mFile {
case .handle(let hdl):
if en {
setupCallback(fileHandle: hdl)
} else {
hdl.readabilityHandler = nil
}
case .pipe(let pipe):
if en {
setupCallback(fileHandle: pipe.fileHandleForReading)
} else {
pipe.fileHandleForReading.readabilityHandler = nil
}
}
case .writer:
break
}
}
public var fileHandle: FileHandle { get {
let result: FileHandle
switch mFile {
case .handle(let hdl): result = hdl
case .pipe(let pipe):
switch mAccess {
case .reader:
result = pipe.fileHandleForReading
case .writer:
result = pipe.fileHandleForWriting
}
}
return result
}}
public var readDone: Bool { get { return mReadDone }}
public func getc() -> CNFile.Char {
var result: CNFile.Char = .null
mInputLock.lock()
if mInputBuffer.count == 0 && mReadDone {
result = .endOfFile
} else if let c = mInputBuffer.first {
mInputBuffer.removeFirst()
result = .char(c)
}
mInputLock.unlock()
return result
}
public func gets() -> CNFile.Str {
var result: CNFile.Str = .null
mInputLock.lock()
if mInputBuffer.count == 0 && mReadDone {
result = .endOfFile
} else if mInputBuffer.count > 0 {
result = .str(mInputBuffer)
mInputBuffer = ""
}
mInputLock.unlock()
return result
}
public func getl() -> CNFile.Line {
var result: CNFile.Line = .null
mInputLock.lock()
if mInputBuffer.count == 0 && mReadDone {
result = .endOfFile
} else if mInputBuffer.count > 0 {
let start = mInputBuffer.startIndex
let end = mInputBuffer.endIndex
var idx = start
while idx < end {
let c = mInputBuffer[idx]
if c.isNewline {
let next = mInputBuffer.index(after: idx)
let head = mInputBuffer.prefix(upTo: next)
let tail = mInputBuffer.suffix(from: next)
mInputBuffer = String(tail)
result = .line(String(head))
break
}
idx = mInputBuffer.index(after: idx)
}
/* newline is not found */
if mReadDone {
result = .line(String(mInputBuffer))
mInputBuffer = ""
}
}
mInputLock.unlock()
return result
}
/* Note this function requires unlimited execution time. Do not call by JavaScriptCore */
public func getall() -> String {
var result: String = ""
var docont: Bool = true
while docont {
switch self.gets() {
case .null:
break
case .str(let str):
result += str
case .endOfFile:
docont = false
}
}
return result
}
public func put(string str: String) {
if let data = str.data(using: .utf8) {
fileHandle.write(data)
}
}
}
| lgpl-2.1 | 8e272ba67b645cf0e62b7d881c2e2800 | 19.447099 | 102 | 0.649307 | 3.309945 | false | false | false | false |
cpuu/OTT | OTT/Central/PeripheralServiceCharacteristicEditDiscreteValuesViewController.swift | 1 | 6040 | //
// PeripheralServiceCharacteristicEditDiscreteValuesViewController.swift
// BlueCap
//
// Created by Troy Stribling on 7/20/14.
// Copyright (c) 2014 Troy Stribling. The MIT License (MIT).
//
import UIKit
import BlueCapKit
import CoreBluetooth
class PeripheralServiceCharacteristicEditDiscreteValuesViewController : UITableViewController {
private static var BCPeripheralStateKVOContext = UInt8()
weak var characteristic: BCCharacteristic!
var peripheralViewController: PeripheralViewController?
var progressView = ProgressView()
struct MainStoryboard {
static let peripheralServiceCharacteristicDiscreteValueCell = "PeripheraServiceCharacteristicEditDiscreteValueCell"
}
required init?(coder aDecoder:NSCoder) {
super.init(coder: aDecoder)
}
override func viewDidLoad() {
super.viewDidLoad()
self.navigationItem.title = self.characteristic.name
self.navigationItem.backBarButtonItem = UIBarButtonItem(title: "", style: .Plain, target: nil, action: nil)
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
let options = NSKeyValueObservingOptions([.New])
self.characteristic?.service?.peripheral?.addObserver(self, forKeyPath: "state", options: options, context: &PeripheralServiceCharacteristicEditDiscreteValuesViewController.BCPeripheralStateKVOContext)
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(PeripheralServiceCharacteristicEditDiscreteValuesViewController.didEnterBackground), name: UIApplicationDidEnterBackgroundNotification, object: nil)
}
override func viewDidDisappear(animated: Bool) {
super.viewDidDisappear(animated)
self.characteristic?.service?.peripheral?.removeObserver(self, forKeyPath: "state", context: &PeripheralServiceCharacteristicEditDiscreteValuesViewController.BCPeripheralStateKVOContext)
NSNotificationCenter.defaultCenter().removeObserver(self)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {
}
func peripheralDisconnected() {
BCLogger.debug()
if let peripheralViewController = self.peripheralViewController {
if peripheralViewController.peripheralConnected {
self.presentViewController(UIAlertController.alertWithMessage("Peripheral disconnected") {(action) in
peripheralViewController.peripheralConnected = false
self.navigationController?.popViewControllerAnimated(true)
}, animated: true, completion: nil)
}
}
}
func didEnterBackground() {
self.navigationController?.popToRootViewControllerAnimated(false)
BCLogger.debug()
}
override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String: AnyObject]?, context: UnsafeMutablePointer<Void>) {
guard keyPath != nil else {
super.observeValueForKeyPath(keyPath, ofObject: object, change: change, context: context)
return
}
switch (keyPath!, context) {
case("state", &PeripheralServiceCharacteristicEditDiscreteValuesViewController.BCPeripheralStateKVOContext):
if let change = change, newValue = change[NSKeyValueChangeNewKey], newRawState = newValue as? Int, newState = CBPeripheralState(rawValue: newRawState) {
if newState == .Disconnected {
dispatch_async(dispatch_get_main_queue()) { self.peripheralDisconnected() }
}
}
default:
super.observeValueForKeyPath(keyPath, ofObject: object, change: change, context: context)
}
}
// UITableViewDataSource
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(_: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.characteristic.stringValues.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(MainStoryboard.peripheralServiceCharacteristicDiscreteValueCell, forIndexPath: indexPath) as UITableViewCell
let stringValue = self.characteristic.stringValues[indexPath.row]
cell.textLabel?.text = stringValue
if let valueName = characteristic.stringValue?.keys.first {
if let value = self.characteristic.stringValue?[valueName] {
if value == stringValue {
cell.accessoryType = UITableViewCellAccessoryType.Checkmark
} else {
cell.accessoryType = UITableViewCellAccessoryType.None
}
}
}
return cell
}
// UITableViewDelegate
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
self.progressView.show()
if let characteristic = self.characteristic {
if let valueName = characteristic.stringValue?.keys.first {
let stringValue = [valueName:characteristic.stringValues[indexPath.row]]
let write = characteristic.writeString(stringValue, timeout:Double(ConfigStore.getCharacteristicReadWriteTimeout()))
write.onSuccess {characteristic in
self.progressView.remove()
self.navigationController?.popViewControllerAnimated(true)
return
}
write.onFailure {error in
self.presentViewController(UIAlertController.alertOnError("Charactertistic Write Error", error: error), animated: true, completion: nil)
self.progressView.remove()
self.navigationController?.popViewControllerAnimated(true)
return
}
}
}
}
}
| mit | 3c59a08b2f754ea7eb3228bc343419f0 | 44.413534 | 231 | 0.687086 | 6.213992 | false | false | false | false |
4np/UitzendingGemist | UitzendingGemist/String+substringWithNSRange.swift | 1 | 1433 | //
// String+substringWithNSRange.swift
// UitzendingGemist
//
// Created by Jeroen Wesbeek on 22/03/17.
// Copyright ยฉ 2017 Jeroen Wesbeek. All rights reserved.
//
import Foundation
extension String {
func nsRange(from range: Range<String.Index>) -> NSRange {
let from = range.lowerBound.samePosition(in: utf16)
let to = range.upperBound.samePosition(in: utf16)
return NSRange(location: utf16.distance(from: utf16.startIndex, to: from),
length: utf16.distance(from: from, to: to))
}
func range(from nsRange: NSRange) -> Range<String.Index>? {
guard
let from16 = utf16.index(utf16.startIndex, offsetBy: nsRange.location, limitedBy: utf16.endIndex),
let to16 = utf16.index(from16, offsetBy: nsRange.length, limitedBy: utf16.endIndex),
let from = String.Index(from16, within: self),
let to = String.Index(to16, within: self)
else { return nil }
return from ..< to
}
func substring(withNSRange nsRange: NSRange) -> String? {
guard let range = range(from: nsRange) else { return nil }
return substring(with: range)
}
func substring(withNSRange nsRange: NSRange, stripPattern pattern: String) -> String? {
return substring(withNSRange: nsRange)?.replacingOccurrences(of: pattern, with: "", options: [.regularExpression], range: nil)
}
}
| apache-2.0 | 5ac4096df4ba51a394441fa3fea51a86 | 37.702703 | 134 | 0.644553 | 4.103152 | false | false | false | false |
Foild/StatefulViewController | StatefulViewController/ViewStateMachine.swift | 1 | 6690 | //
// ViewStateMachine.swift
// StatefulViewController
//
// Created by Alexander Schuch on 30/07/14.
// Copyright (c) 2014 Alexander Schuch. All rights reserved.
//
import UIKit
/// Represents the state of the view state machine
public enum ViewStateMachineState : Equatable {
case None // No view shown
case View(String) // View with specific key is shown
}
public func == (lhs: ViewStateMachineState, rhs: ViewStateMachineState) -> Bool {
switch (lhs, rhs) {
case (.None, .None): return true
case (.View(let lName), .View(let rName)): return lName == rName
default: return false
}
}
///
/// A state machine that manages a set of views.
///
/// There are two possible states:
/// * Show a specific placeholder view, represented by a key
/// * Hide all managed views
///
public class ViewStateMachine {
private var viewStore: [String: UIView]
private let queue = dispatch_queue_create("com.aschuch.viewStateMachine.queue", DISPATCH_QUEUE_SERIAL)
var viewIndex = 0
/// The view that should act as the superview for any added views
public let view: UIView
/// The current display state of views
public private(set) var currentState: ViewStateMachineState = .None
/// The last state that was enqueued
public private(set) var lastState: ViewStateMachineState = .None
// MARK: Init
/// Designated initializer.
///
/// - parameter view: The view that should act as the superview for any added views
/// - parameter states: A dictionary of states
///
/// - returns: A view state machine with the given views for states
///
public init(view: UIView, states: [String: UIView]?) {
self.view = view
viewStore = states ?? [String: UIView]()
}
/// - parameter view: The view that should act as the superview for any added views
///
/// - returns: A view state machine
///
public convenience init(view: UIView) {
self.init(view: view, states: nil)
}
// MARK: Add and remove view states
/// - returns: the view for a given state
public func viewForState(state: String) -> UIView? {
return viewStore[state]
}
/// Associates a view for the given state
public func addView(view: UIView, forState state: String) {
viewStore[state] = view
}
/// Removes the view for the given state
public func removeViewForState(state: String) {
viewStore[state] = nil
}
// MARK: Subscripting
public subscript(state: String) -> UIView? {
get {
return viewForState(state)
}
set(newValue) {
if let value = newValue {
addView(value, forState: state)
} else {
removeViewForState(state)
}
}
}
// MARK: Switch view state
/// Adds and removes views to and from the `view` based on the given state.
/// Animations are synchronized in order to make sure that there aren't any animation gliches in the UI
///
/// - parameter state: The state to transition to
/// - parameter animated: true if the transition should fade views in and out
/// - parameter campletion: called when all animations are finished and the view has been updated
///
public func transitionToState(state: ViewStateMachineState, animated: Bool = true, completion: (() -> ())? = nil) {
lastState = state
dispatch_async(queue) {
if state == self.currentState {
return
}
// Suspend the queue, it will be resumed in the completion block
dispatch_suspend(self.queue)
self.currentState = state
let c: () -> () = {
dispatch_resume(self.queue)
completion?()
}
// Switch state and update the view
dispatch_sync(dispatch_get_main_queue()) {
switch state {
case .None:
self.hideAllViews(animated: animated, completion: c)
case .View(let viewKey):
self.showViewWithKey(viewKey, animated: animated, completion: c)
}
}
}
}
// MARK: Private view updates
private func showViewWithKey(state: String, animated: Bool, completion: (() -> ())? = nil) {
if let newView = self.viewStore[state] {
// Add new view using AutoLayout
newView.alpha = animated ? 0.0 : 1.0
newView.translatesAutoresizingMaskIntoConstraints = false
self.view.insertSubview(newView, atIndex: viewIndex)
let views = ["view": newView]
let hConstraints = NSLayoutConstraint.constraintsWithVisualFormat("|[view]|", options: [], metrics: nil, views: views)
let vConstraints = NSLayoutConstraint.constraintsWithVisualFormat("V:|[view]|", options: [], metrics: nil, views: views)
self.view.addConstraints(hConstraints)
self.view.addConstraints(vConstraints)
}
let animations: () -> () = {
if let newView = self.viewStore[state] {
newView.alpha = 1.0
}
}
let animationCompletion: (Bool) -> () = { (finished) in
for (key, view) in self.viewStore {
if !(key == state) {
view.removeFromSuperview()
}
}
completion?()
}
animateChanges(animated: animated, animations: animations, animationCompletion: animationCompletion)
}
private func hideAllViews(animated animated: Bool, completion: (() -> ())? = nil) {
let animations: () -> () = {
for (_, view) in self.viewStore {
view.alpha = 0.0
}
}
let animationCompletion: (Bool) -> () = { (finished) in
for (_, view) in self.viewStore {
view.removeFromSuperview()
}
completion?()
}
animateChanges(animated: animated, animations: animations, animationCompletion: animationCompletion)
}
private func animateChanges(animated animated: Bool, animations: () -> (), animationCompletion: (Bool) -> ()) {
if animated {
UIView.animateWithDuration(0.3, animations: animations, completion: animationCompletion)
} else {
animationCompletion(true)
}
}
}
| mit | 3340ba5daec127cc30f4befc63fc0978 | 31.794118 | 132 | 0.572795 | 4.933628 | false | false | false | false |
4np/UitzendingGemist | NPOKit/NPOKit/NPOVideo.swift | 1 | 2891 | //
// NPOVideo.swift
// NPOKit
//
// Created by Jeroen Wesbeek on 02/03/17.
// Copyright ยฉ 2017 Jeroen Wesbeek. All rights reserved.
//
import Foundation
import AlamofireObjectMapper
import AlamofireImage
import ObjectMapper
import CocoaLumberjack
// Example response for episodes:
//
//{
// "limited":false,
// "site":null,
// "items":[
// [
// {
// "label":"Hoog",
// "contentType":"odi",
// "url":"http://odi.omroep.nl/video/ida/h264_std/cd303cede19617dbc93a888f54b9c83b/58b7439d/AT_2077064/1?type=jsonp&callback=?",
// "format":"mp4"
// },
// {
// "label":"Normaal",
// "contentType":"odi",
// "url":"http://odi.omroep.nl/video/ida/h264_bb/c76b0c85c08dc6dbb3ed6e450ea22764/58b7439d/AT_2077064/1?type=jsonp&callback=?",
// "format":"mp4"
// },
// {
// "label":"Laag",
// "contentType":"odi",
// "url":"http://odi.omroep.nl/video/ida/h264_sb/f95897882c52fa7189903251a8756edf/58b7439d/AT_2077064/1?type=jsonp&callback=?",
// "format":"mp4"
// }
// ]
// ]
//}
//
// Example response for live / themed streams:
//{
// "limited": false,
// "site": null,
// "items": [
// [
// {
// "label": "Live",
// "contentType": "live",
// "url": "http://livestreams.omroep.nl/live/npo/tvlive/npo2/npo2.isml/npo2.m3u8?hash=f545b16018eac4752d498dea4e5a0c58&type=jsonp&protection=url",
// "format": "hls"
// }
// ]
// ]
//}
open class NPOVideo: Mappable, CustomDebugStringConvertible {
public internal(set) var channel: NPOLive? {
didSet {
// set channel on streams
let streams = self.streams ?? []
for stream in streams {
stream.channel = channel
}
}
}
public private(set) var limited: Bool?
public var site: String?
public var streams: [NPOStream]?
// MARK: Lifecycle
required public init?(map: Map) {
}
// MARK: Mapping
open func mapping(map: Map) {
limited <- map["limited"]
site <- map["site"]
streams <- map["items.0"]
}
// MARK: Convenience
public var preferredQualityStream: NPOStream? {
var preferredEpisodeQualityOrder = NPOManager.sharedInstance.preferredEpisodeQualityOrder
// not really a quality, but the same back end returns live streams as well
preferredEpisodeQualityOrder.append(.live)
for streamType in preferredEpisodeQualityOrder {
if let stream = self.streams?.filter({ $0.type == streamType }).first { return stream }
}
return nil
}
}
| apache-2.0 | 964296b566d82ba132e2eb0662374827 | 27.613861 | 161 | 0.538408 | 3.621554 | false | false | false | false |
justinmakaila/JSONMapping | JSONMappingTests/AttributeTypeSpec.swift | 1 | 2824 | import Quick
import Nimble
import CoreData
@testable
import JSONMapping
class AttributeTypeSpec: QuickSpec {
override func spec() {
let allAttributeTypes: [NSAttributeType] = [
.integer16AttributeType,
.integer32AttributeType,
.integer64AttributeType,
.decimalAttributeType,
.doubleAttributeType,
.floatAttributeType,
.stringAttributeType,
.binaryDataAttributeType,
.booleanAttributeType,
.dateAttributeType,
.objectIDAttributeType,
.transformableAttributeType,
.undefinedAttributeType,
]
it ("can tell if it's a number") {
allAttributeTypes.forEach { attributeType in
if [NSAttributeType.integer16AttributeType,
NSAttributeType.integer32AttributeType,
NSAttributeType.integer64AttributeType,
NSAttributeType.decimalAttributeType,
NSAttributeType.doubleAttributeType,
NSAttributeType.floatAttributeType].contains(attributeType) {
expect(attributeType.isNumber).to(beTrue())
} else {
expect(attributeType.isNumber).to(beFalse())
}
}
}
it ("can tell if it's a string") {
allAttributeTypes.forEach { attributeType in
if attributeType == .stringAttributeType {
expect(attributeType.isString).to(beTrue())
} else {
expect(attributeType.isString).to(beFalse())
}
}
}
it ("can tell if it's data") {
allAttributeTypes.forEach { attributeType in
if attributeType == .binaryDataAttributeType {
expect(attributeType.isData).to(beTrue())
} else {
expect(attributeType.isData).to(beFalse())
}
}
}
it ("can tell if it's a date") {
allAttributeTypes.forEach { attributeType in
if attributeType == .dateAttributeType {
expect(attributeType.isDate).to(beTrue())
} else {
expect(attributeType.isDate).to(beFalse())
}
}
}
it ("can tell if it's a decimal number") {
allAttributeTypes.forEach { attributeType in
if attributeType == .decimalAttributeType {
expect(attributeType.isDecimalNumber).to(beTrue())
} else {
expect(attributeType.isDecimalNumber).to(beFalse())
}
}
}
}
}
| mit | e122c6f78af6b84c76eab9117ac30852 | 33.864198 | 81 | 0.521601 | 6.275556 | false | false | false | false |
nthery/SwiftForth | SwiftForthKit/vm.swift | 1 | 6085 | //
// Forth virtual machine
//
import Foundation
// The instructions the virtual machine supports.
enum Instruction : Printable {
enum BranchCondition : Printable {
case Always, IfZero
var description : String {
switch self {
case Always:
return "always"
case IfZero:
return "ifZero"
}
}
}
case Nop
case Add
case Sub
case Mul
case Div
case Dot
case PushConstant(Int)
case PushControlStackTop
case Call(name: String, CompiledPhrase)
case Emit
case Branch(BranchCondition, CompiledPhrase.Address?)
case Do
case Loop(CompiledPhrase.Address)
var description : String {
switch self {
case Nop:
return "nop"
case Add:
return "add"
case Sub:
return "sub"
case Mul:
return "mul"
case Div:
return "div"
case Dot:
return "dot"
case let PushConstant(k):
return "pushConstant(\(k))"
case PushControlStackTop:
return "pushControlStackTop"
case let Call(name, _):
return "call(\(name))"
case Emit:
return "emit"
case let Branch(condition, address):
return "branch(\(condition), address)"
case Do:
return "do"
case let Loop(address):
return "loop(\(address))"
}
}
var expectedArgumentCount : Int {
switch self {
case Nop, .PushConstant, PushControlStackTop, Call, Loop:
return 0
case Dot, Emit:
return 1
case Add, Sub, Mul, Div, Do:
return 2
case PushConstant:
return 0
case let Branch(condition, _):
return condition == .Always ? 0 : 1
}
}
}
// Well-formed sequence of instructions. Typically corresponds to a word definition.
struct CompiledPhrase : Printable {
// Instruction offset.
typealias Address = Int
let instructions = [Instruction]()
subscript(i: Int) -> Instruction {
return instructions[i]
}
var count : Int {
return instructions.count
}
var description : String {
var acc = ""
for (i, insn) in enumerate(instructions) {
acc += "\(i):\(insn) "
}
return acc
}
}
// Forth virtual machine
class VM : ErrorRaiser {
var argStack = ForthStack<Int>()
var controlStack = ForthStack<Int>()
var output = ""
override func resetAfterError() {
argStack = ForthStack<Int>()
controlStack = ForthStack<Int>()
}
// Execute phrase and return true on success or false if a runtime error occurred.
func execPhrase(phrase: CompiledPhrase) -> Bool {
var pc = 0
while pc < phrase.count {
if let newPc = execInstruction(pc, insn: phrase[pc]) {
pc = newPc
} else {
return false
}
}
return true
}
// Execute single instruction and return new PC on success or nil if a runtime
// error occurred.
func execInstruction(pc: Int, insn: Instruction) -> Int? {
debug(.Vm, "Executing \(insn) @ \(pc) with argStack [ \(argStack) ] controlStack [ \(controlStack) ]")
if argStack.count < insn.expectedArgumentCount {
error("\(insn): expected \(insn.expectedArgumentCount) argument(s) but got \(argStack.count)")
return nil
}
switch insn {
case .Add:
let rhs = self.argStack.pop()
let lhs = self.argStack.pop()
self.argStack.push(lhs + rhs)
case .Sub:
let rhs = self.argStack.pop()
let lhs = self.argStack.pop()
self.argStack.push(lhs - rhs)
case .Mul:
let rhs = self.argStack.pop()
let lhs = self.argStack.pop()
self.argStack.push(lhs * rhs)
case .Div:
let rhs = self.argStack.pop()
let lhs = self.argStack.pop()
if rhs != 0 {
self.argStack.push(lhs / rhs)
} else {
error("division by zero")
return nil
}
case .Call(_, let phrase):
if !execPhrase(phrase) {
return nil
}
case .PushConstant(let k):
argStack.push(k)
case .PushControlStackTop:
if controlStack.count >= 1 {
argStack.push(controlStack.top())
} else {
error("I: not enough arguments on control stack")
return nil
}
case .Dot:
self.output += "\(self.argStack.pop()) "
case .Nop:
break
case let .Branch(condition, target):
if conditionIsTrue(condition) {
return target!
}
case .Emit:
self.output += String(fromAsciiCode: self.argStack.pop())
case .Do:
let limit = argStack.pop()
let base = argStack.pop()
controlStack.push(limit)
controlStack.push(base)
case let .Loop(address):
if controlStack.count >= 2 {
controlStack.push(controlStack.pop() + 1)
if controlStack.top() < controlStack.top(offsetFromTop: 1) {
// Loop back to beginning.
return address
} else {
// Cleanup index and limit.
controlStack.pop()
controlStack.pop()
}
} else {
error("LOOP: not enough arguments on control stack")
return nil
}
}
return pc + 1
}
func conditionIsTrue(condition: Instruction.BranchCondition) -> Bool {
switch condition {
case .Always:
return true
case .IfZero:
return argStack.pop() == 0
}
}
}
| mit | f1c5d1c204f1eb08662d67d659811bc7 | 26.659091 | 110 | 0.514873 | 4.772549 | false | false | false | false |
pksprojects/ElasticSwift | Sources/ElasticSwift/Requests/SearchRequest.swift | 1 | 46948 | //
// SearchRequest.swift
// ElasticSwift
//
// Created by Prafull Kumar Soni on 5/31/17.
//
//
import ElasticSwiftCodableUtils
import ElasticSwiftCore
import ElasticSwiftQueryDSL
import Foundation
import NIOHTTP1
// MARK: - Search Request Builder
public class SearchRequestBuilder: RequestBuilder {
public typealias RequestType = SearchRequest
private var _indices: [String]?
private var _types: [String]?
private var _searchSource = SearchSource()
private var _sourceFilter: SourceFilter?
private var _scroll: Scroll?
private var _searchType: SearchType?
private var _preference: String?
public init() {}
@discardableResult
public func set(indices: String...) -> Self {
_indices = indices
return self
}
@discardableResult
public func set(indices: [String]) -> Self {
_indices = indices
return self
}
@discardableResult
public func set(types: String...) -> Self {
_types = types
return self
}
@discardableResult
public func set(types: [String]) -> Self {
_types = types
return self
}
@discardableResult
public func set(searchSource: SearchSource) -> Self {
_searchSource = searchSource
return self
}
@discardableResult
public func set(from: Int16) -> Self {
_searchSource.from = from
return self
}
@discardableResult
public func set(size: Int16) -> Self {
_searchSource.size = size
return self
}
@discardableResult
public func set(query: Query) -> Self {
_searchSource.query = query
return self
}
@discardableResult
public func set(postFilter: Query) -> Self {
_searchSource.postFilter = postFilter
return self
}
@discardableResult
public func set(sorts: [Sort]) -> Self {
_searchSource.sorts = sorts
return self
}
@discardableResult
public func set(sourceFilter: SourceFilter) -> Self {
_searchSource.sourceFilter = sourceFilter
return self
}
@discardableResult
public func set(explain: Bool) -> Self {
_searchSource.explain = explain
return self
}
@discardableResult
public func set(minScore: Decimal) -> Self {
_searchSource.minScore = minScore
return self
}
@discardableResult
public func set(scroll: Scroll) -> Self {
_scroll = scroll
return self
}
@discardableResult
public func set(searchType: SearchType) -> Self {
_searchType = searchType
return self
}
@discardableResult
public func set(trackScores: Bool) -> Self {
_searchSource.trackScores = trackScores
return self
}
@discardableResult
public func set(indicesBoost: [IndexBoost]) -> Self {
_searchSource.indicesBoost = indicesBoost
return self
}
@discardableResult
public func set(preference: String) -> Self {
_preference = preference
return self
}
@discardableResult
public func set(version: Bool) -> Self {
_searchSource.version = version
return self
}
@discardableResult
public func set(seqNoPrimaryTerm: Bool) -> Self {
_searchSource.seqNoPrimaryTerm = seqNoPrimaryTerm
return self
}
@discardableResult
public func set(scriptFields: [ScriptField]) -> Self {
_searchSource.scriptFields = scriptFields
return self
}
@discardableResult
public func set(docvalueFields: [DocValueField]) -> Self {
_searchSource.docvalueFields = docvalueFields
return self
}
@discardableResult
public func set(rescore: [QueryRescorer]) -> Self {
_searchSource.rescore = rescore
return self
}
@discardableResult
public func set(searchAfter: CodableValue) -> Self {
_searchSource.searchAfter = searchAfter
return self
}
@discardableResult
public func add(sort: Sort) -> Self {
if _searchSource.sorts != nil {
_searchSource.sorts?.append(sort)
} else {
_searchSource.sorts = [sort]
}
return self
}
@discardableResult
public func add(indexBoost: IndexBoost) -> Self {
if _searchSource.indicesBoost != nil {
_searchSource.indicesBoost?.append(indexBoost)
} else {
_searchSource.indicesBoost = [indexBoost]
}
return self
}
@discardableResult
public func add(scriptField: ScriptField) -> Self {
if _searchSource.scriptFields != nil {
_searchSource.scriptFields?.append(scriptField)
} else {
_searchSource.scriptFields = [scriptField]
}
return self
}
@discardableResult
public func add(docvalueField: DocValueField) -> Self {
if _searchSource.docvalueFields != nil {
_searchSource.docvalueFields?.append(docvalueField)
} else {
_searchSource.docvalueFields = [docvalueField]
}
return self
}
@discardableResult
public func add(rescore: QueryRescorer) -> Self {
if _searchSource.rescore != nil {
_searchSource.rescore?.append(rescore)
} else {
_searchSource.rescore = [rescore]
}
return self
}
@discardableResult
public func set(storedFields: String...) -> Self {
_searchSource.storedFields = storedFields
return self
}
@discardableResult
public func set(storedFields: [String]) -> Self {
_searchSource.storedFields = storedFields
return self
}
@discardableResult
public func set(highlight: Highlight) -> Self {
_searchSource.highlight = highlight
return self
}
@discardableResult
public func add(index: String) -> Self {
if _indices != nil {
_indices?.append(index)
} else {
_indices = [index]
}
return self
}
@discardableResult
public func add(type: String) -> Self {
if _types != nil {
_types?.append(type)
} else {
_types = [type]
}
return self
}
public var indices: [String]? {
return _indices
}
public var types: [String]? {
return _types
}
public var searchSource: SearchSource {
return _searchSource
}
public var sourceFilter: SourceFilter? {
return _sourceFilter
}
public var scroll: Scroll? {
return _scroll
}
public var searchType: SearchType? {
return _searchType
}
public var preference: String? {
return _preference
}
public func build() throws -> SearchRequest {
return try SearchRequest(withBuilder: self)
}
}
// MARK: - Search Request
public struct SearchRequest: Request {
public var headers = HTTPHeaders()
public let indices: [String]?
public let types: [String]?
public let searchSource: SearchSource?
public var scroll: Scroll?
public var searchType: SearchType?
public var preference: String?
public init(indices: [String]?, types: [String]?, searchSource: SearchSource?, scroll: Scroll? = nil, searchType: SearchType? = nil, preference: String? = nil) {
self.indices = indices
self.types = types
self.searchSource = searchSource
self.scroll = scroll
self.searchType = searchType
self.preference = preference
}
public init(indices: [String]? = nil, types: [String]? = nil, query: Query? = nil, from: Int16? = nil, size: Int16? = nil, sorts: [Sort]? = nil, sourceFilter: SourceFilter? = nil, explain: Bool? = nil, minScore: Decimal? = nil, scroll: Scroll? = nil, trackScores: Bool? = nil, indicesBoost: [IndexBoost]? = nil, searchType: SearchType? = nil, seqNoPrimaryTerm: Bool? = nil, version: Bool? = nil, preference: String? = nil, scriptFields: [ScriptField]? = nil, storedFields: [String]? = nil, docvalueFields: [DocValueField]? = nil, postFilter: Query? = nil, highlight: Highlight? = nil, rescore: [QueryRescorer]? = nil, searchAfter: CodableValue? = nil) {
var searchSource = SearchSource()
searchSource.query = query
searchSource.postFilter = postFilter
searchSource.from = from
searchSource.size = size
searchSource.sorts = sorts
searchSource.sourceFilter = sourceFilter
searchSource.explain = explain
searchSource.minScore = minScore
searchSource.trackScores = trackScores
searchSource.indicesBoost = indicesBoost
searchSource.docvalueFields = docvalueFields
searchSource.highlight = highlight
searchSource.rescore = rescore
searchSource.searchAfter = searchAfter
searchSource.seqNoPrimaryTerm = seqNoPrimaryTerm
searchSource.scriptFields = scriptFields
searchSource.storedFields = storedFields
searchSource.version = version
self.init(indices: indices, types: types, searchSource: searchSource, scroll: scroll, searchType: searchType, preference: preference)
}
public init(indices: String..., types: [String]? = nil, query: Query? = nil, from: Int16? = nil, size: Int16? = nil, sorts: [Sort]? = nil, sourceFilter: SourceFilter? = nil, explain: Bool? = nil, minScore: Decimal? = nil, scroll: Scroll? = nil, trackScores: Bool? = nil, indicesBoost: [IndexBoost]? = nil, searchType: SearchType? = nil, seqNoPrimaryTerm: Bool? = nil, version: Bool? = nil, preference: String? = nil, scriptFields: [ScriptField]? = nil, storedFields: [String]? = nil, docvalueFields: [DocValueField]? = nil, postFilter: Query? = nil, highlight: Highlight? = nil, rescore: [QueryRescorer]? = nil, searchAfter: CodableValue? = nil) {
self.init(indices: indices, types: types, query: query, from: from, size: size, sorts: sorts, sourceFilter: sourceFilter, explain: explain, minScore: minScore, scroll: scroll, trackScores: trackScores, indicesBoost: indicesBoost, searchType: searchType, seqNoPrimaryTerm: seqNoPrimaryTerm, version: version, preference: preference, scriptFields: scriptFields, storedFields: storedFields, docvalueFields: docvalueFields, postFilter: postFilter, highlight: highlight, rescore: rescore, searchAfter: searchAfter)
}
internal init(withBuilder builder: SearchRequestBuilder) throws {
self.init(indices: builder.indices, types: builder.types, searchSource: builder.searchSource, scroll: builder.scroll, searchType: builder.searchType, preference: builder.preference)
}
public var method: HTTPMethod {
return .POST
}
public var endPoint: String {
var _endPoint = "_search"
if let types = self.types, !types.isEmpty {
_endPoint = types.joined(separator: ",") + "/" + _endPoint
}
if let indices = self.indices, !indices.isEmpty {
_endPoint = indices.joined(separator: ",") + "/" + _endPoint
}
return _endPoint
}
public var queryParams: [URLQueryItem] {
var queryItems = [URLQueryItem]()
if let scroll = self.scroll {
queryItems.append(URLQueryItem(name: QueryParams.scroll, value: scroll.keepAlive))
}
if let searchType = self.searchType {
queryItems.append(URLQueryItem(name: QueryParams.searchType, value: searchType.rawValue))
}
if let preference = self.preference {
queryItems.append(URLQueryItem(name: QueryParams.preference, value: preference))
}
return queryItems
}
public func makeBody(_ serializer: Serializer) -> Result<Data, MakeBodyError> {
if let body = searchSource {
return serializer.encode(body).mapError { error -> MakeBodyError in
MakeBodyError.wrapped(error)
}
}
return .failure(.noBodyForRequest)
}
}
extension SearchRequest: Equatable {}
/// Struct representing Index boost
public struct IndexBoost {
public let index: String
public let boost: Decimal
}
extension IndexBoost: Codable {
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: DynamicCodingKeys.self)
try container.encode(boost, forKey: .key(named: index))
}
public init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
let dic = try container.decode([String: Decimal].self)
if dic.isEmpty || dic.count > 1 {
throw Swift.DecodingError.dataCorruptedError(in: container, debugDescription: "Unexpected data found \(dic)")
}
index = dic.first!.key
boost = dic.first!.value
}
}
extension IndexBoost: Equatable {}
// MARK: - Scroll
public struct Scroll: Codable {
public let keepAlive: String
public init(keepAlive: String) {
self.keepAlive = keepAlive
}
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
try container.encode(keepAlive)
}
public init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
keepAlive = try container.decodeString()
}
public static var ONE_MINUTE: Scroll {
return Scroll(keepAlive: "1m")
}
}
extension Scroll: Equatable {}
// MARK: - Search Scroll Request Builder
public class SearchScrollRequestBuilder: RequestBuilder {
public typealias RequestType = SearchScrollRequest
private var _scrollId: String?
private var _scroll: Scroll?
private var _restTotalHitsAsInt: Bool?
public init() {}
@discardableResult
public func set(scrollId: String) -> Self {
_scrollId = scrollId
return self
}
@discardableResult
public func set(scroll: Scroll) -> Self {
_scroll = scroll
return self
}
@discardableResult
public func set(restTotalHitsAsInt: Bool) -> Self {
_restTotalHitsAsInt = restTotalHitsAsInt
return self
}
public var scrollId: String? {
return _scrollId
}
public var scroll: Scroll? {
return _scroll
}
public var restTotalHitsAsInt: Bool? {
return _restTotalHitsAsInt
}
public func build() throws -> SearchScrollRequest {
return try SearchScrollRequest(withBuilder: self)
}
}
// MARK: - Search Scroll Request
public struct SearchScrollRequest: Request {
public let scrollId: String
public let scroll: Scroll?
public var restTotalHitsAsInt: Bool?
public init(scrollId: String, scroll: Scroll?) {
self.scrollId = scrollId
self.scroll = scroll
}
internal init(withBuilder builder: SearchScrollRequestBuilder) throws {
guard builder.scrollId != nil else {
throw RequestBuilderError.missingRequiredField("scrollId")
}
scrollId = builder.scrollId!
scroll = builder.scroll
restTotalHitsAsInt = builder.restTotalHitsAsInt
}
public var headers: HTTPHeaders {
return HTTPHeaders()
}
public var queryParams: [URLQueryItem] {
var params = [URLQueryItem]()
if let totalHitsAsInt = restTotalHitsAsInt {
params.append(URLQueryItem(name: QueryParams.restTotalHitsAsInt, value: totalHitsAsInt))
}
return params
}
public var method: HTTPMethod {
return .POST
}
public var endPoint: String {
return "_search/scroll"
}
public func makeBody(_ serializer: Serializer) -> Result<Data, MakeBodyError> {
let body = Body(scroll: scroll, scrollId: scrollId)
return serializer.encode(body).mapError { error -> MakeBodyError in
.wrapped(error)
}
}
private struct Body: Encodable {
public let scroll: Scroll?
public let scrollId: String
enum CodingKeys: String, CodingKey {
case scroll
case scrollId = "scroll_id"
}
}
}
extension SearchScrollRequest: Equatable {}
// MARK: - Clear Scroll Request Builder
public class ClearScrollRequestBuilder: RequestBuilder {
public typealias RequestType = ClearScrollRequest
private var _scrollIds: [String] = []
public init() {}
@discardableResult
public func set(scrollIds: String...) -> Self {
_scrollIds = scrollIds
return self
}
public var scrollIds: [String] {
return _scrollIds
}
public func build() throws -> ClearScrollRequest {
return try ClearScrollRequest(withBuilder: self)
}
}
// MARK: - Clear Scroll Request
public struct ClearScrollRequest: Request {
public let scrollIds: [String]
public init(scrollId: String) {
self.init(scrollIds: [scrollId])
}
public init(scrollIds: [String]) {
self.scrollIds = scrollIds
}
internal init(withBuilder builder: ClearScrollRequestBuilder) throws {
guard !builder.scrollIds.isEmpty else {
throw RequestBuilderError.atlestOneElementRequired("scrollIds")
}
if builder.scrollIds.contains("_all") {
scrollIds = ["_all"]
} else {
scrollIds = builder.scrollIds
}
}
public var headers: HTTPHeaders {
return HTTPHeaders()
}
public var queryParams: [URLQueryItem] {
return []
}
public var method: HTTPMethod {
return .DELETE
}
public var endPoint: String {
if scrollIds.contains("_all") {
return "_search/scroll/_all"
} else {
return "_search/scroll"
}
}
public func makeBody(_ serializer: Serializer) -> Result<Data, MakeBodyError> {
if scrollIds.contains("_all") {
return .failure(.noBodyForRequest)
} else {
let body = Body(scrollId: scrollIds)
return serializer.encode(body).mapError { error -> MakeBodyError in
MakeBodyError.wrapped(error)
}
}
}
private struct Body: Codable, Equatable {
public let scrollId: [String]
public init(scrollId: [String]) {
self.scrollId = scrollId
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
do {
let id = try container.decodeString(forKey: .scrollId)
scrollId = [id]
} catch Swift.DecodingError.typeMismatch {
scrollId = try container.decodeArray(forKey: .scrollId)
}
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
if scrollId.count == 1 {
try container.encode(scrollId.first!, forKey: .scrollId)
} else {
try container.encode(scrollId, forKey: .scrollId)
}
}
enum CodingKeys: String, CodingKey {
case scrollId = "scroll_id"
}
}
}
extension ClearScrollRequest: Equatable {}
// MARK: - Search Type
/// Search type represent the manner at which the search operation is executed.
public enum SearchType: String, Codable {
/// Same as [queryThenFetch](x-source-tag://queryThenFetch), except for an initial scatter phase which goes and computes the distributed
/// term frequencies for more accurate scoring.
case dfsQueryThenFetch = "dfs_query_then_fetch"
/// The query is executed against all shards, but only enough information is returned (not the document content).
/// The results are then sorted and ranked, and based on it, only the relevant shards are asked for the actual
/// document content. The return number of hits is exactly as specified in size, since they are the only ones that
/// are fetched. This is very handy when the index has a lot of shards (not replicas, shard id groups).
/// - Tag: `queryThenFetch`
case queryThenFetch = "query_then_fetch"
/// Only used for pre 5.3 request where this type is still needed
@available(*, deprecated, message: "Only used for pre 5.3 request where this type is still needed")
case queryAndFetch = "query_and_fetch"
/// The default search type [queryThenFetch](x-source-tag://queryThenFetch)
public static let DEFAULT = SearchType.queryThenFetch
}
// MARK: - Source Filtering
public enum SourceFilter {
case fetchSource(Bool)
case filter(String)
case filters([String])
case source(includes: [String], excludes: [String])
}
extension SourceFilter: Codable {
enum CodingKeys: String, CodingKey {
case includes
case excludes
}
public func encode(to encoder: Encoder) throws {
switch self {
case let .fetchSource(value):
var contianer = encoder.singleValueContainer()
try contianer.encode(value)
case let .filter(value):
var contianer = encoder.singleValueContainer()
try contianer.encode(value)
case let .filters(values):
var contianer = encoder.unkeyedContainer()
try contianer.encode(contentsOf: values)
case let .source(includes, excludes):
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(includes, forKey: .includes)
try container.encode(excludes, forKey: .excludes)
}
}
public init(from decoder: Decoder) throws {
if let container = try? decoder.container(keyedBy: CodingKeys.self) {
let includes: [String] = try container.decodeArray(forKey: .includes)
let excludes: [String] = try container.decodeArray(forKey: .excludes)
self = .source(includes: includes, excludes: excludes)
} else if var contianer = try? decoder.unkeyedContainer() {
let values: [String] = try contianer.decodeArray()
self = .filters(values)
} else {
let container = try decoder.singleValueContainer()
if let value = try? container.decodeString() {
self = .filter(value)
} else {
let value = try container.decodeBool()
self = .fetchSource(value)
}
}
}
}
extension SourceFilter: Equatable {}
// MARK: - Rescoring
/// Protocol that all rescorer conform to.
public protocol Rescorer: Codable {
var rescorerType: RescorerType { get }
var windowSize: Int? { get }
func isEqualTo(_ other: Rescorer) -> Bool
}
public extension Rescorer where Self: Equatable {
func isEqualTo(_ other: Rescorer) -> Bool {
if let o = other as? Self {
return self == o
}
return false
}
}
/// Protocol to wrap rescorer type information
public protocol RescorerType: Codable {
var metaType: Rescorer.Type { get }
var name: String { get }
init?(_ name: String)
func isEqualTo(_ other: RescorerType) -> Bool
}
public extension RescorerType where Self: RawRepresentable, Self.RawValue == String {
var name: String {
return rawValue
}
init?(_ name: String) {
if let v = Self(rawValue: name) {
self = v
} else {
return nil
}
}
}
public extension RescorerType where Self: Equatable {
func isEqualTo(_ other: RescorerType) -> Bool {
if let o = other as? Self {
return self == o
}
return false
}
}
public enum RescorerTypes: String, RescorerType, Codable {
case query
}
public extension RescorerTypes {
var metaType: Rescorer.Type {
switch self {
case .query:
return QueryRescorer.self
}
}
}
/// `SearchRequest` rescorer based on a query.
public struct QueryRescorer: Rescorer {
public let rescorerType: RescorerType = RescorerTypes.query
public let windowSize: Int?
public let rescoreQuery: Query
public let queryWeight: Decimal?
public let rescoreQueryWeight: Decimal?
public let scoreMode: ScoreMode?
public init(_ rescoreQuery: Query, scoreMode: ScoreMode? = nil, queryWeight: Decimal? = nil, rescoreQueryWeight: Decimal? = nil, windowSize: Int? = nil) {
self.rescoreQuery = rescoreQuery
self.scoreMode = scoreMode
self.queryWeight = queryWeight
self.rescoreQueryWeight = rescoreQueryWeight
self.windowSize = windowSize
}
}
extension QueryRescorer: Codable {
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encodeIfPresent(windowSize, forKey: .windowSize)
var queryContainer = container.nestedContainer(keyedBy: CodingKeys.self, forKey: .query)
try queryContainer.encode(rescoreQuery, forKey: .rescoreQuery)
try queryContainer.encodeIfPresent(scoreMode, forKey: .scoreMode)
try queryContainer.encodeIfPresent(queryWeight, forKey: .queryWeight)
try queryContainer.encodeIfPresent(rescoreQueryWeight, forKey: .rescoreQueryWeight)
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
windowSize = try container.decodeIntIfPresent(forKey: .windowSize)
let queryContainer = try container.nestedContainer(keyedBy: CodingKeys.self, forKey: .query)
rescoreQuery = try queryContainer.decodeQuery(forKey: .rescoreQuery)
scoreMode = try queryContainer.decodeIfPresent(ScoreMode.self, forKey: .scoreMode)
queryWeight = try queryContainer.decodeDecimalIfPresent(forKey: .queryWeight)
rescoreQueryWeight = try queryContainer.decodeDecimalIfPresent(forKey: .rescoreQueryWeight)
}
enum CodingKeys: String, CodingKey {
case windowSize = "window_size"
case query
case rescoreQuery = "rescore_query"
case rescoreQueryWeight = "rescore_query_weight"
case queryWeight = "query_weight"
case scoreMode = "score_mode"
}
}
extension QueryRescorer: Equatable {
public static func == (lhs: QueryRescorer, rhs: QueryRescorer) -> Bool {
return lhs.rescorerType.isEqualTo(rhs.rescorerType)
&& lhs.windowSize == rhs.windowSize
&& lhs.queryWeight == rhs.queryWeight
&& lhs.rescoreQueryWeight == rhs.rescoreQueryWeight
&& lhs.scoreMode == rhs.scoreMode
&& isEqualQueries(lhs.rescoreQuery, rhs.rescoreQuery)
}
}
// MARK: - Search Source
public struct SearchSource {
public var query: Query?
public var sorts: [Sort]?
public var size: Int16?
public var from: Int16?
public var sourceFilter: SourceFilter?
public var explain: Bool?
public var minScore: Decimal?
public var trackScores: Bool?
public var indicesBoost: [IndexBoost]?
public var seqNoPrimaryTerm: Bool?
public var version: Bool?
public var scriptFields: [ScriptField]?
public var storedFields: [String]?
public var docvalueFields: [DocValueField]?
public var postFilter: Query?
public var highlight: Highlight?
public var rescore: [Rescorer]?
public var searchAfter: CodableValue?
public var suggest: SuggestSource?
}
extension SearchSource: Codable {
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
query = try container.decodeQueryIfPresent(forKey: .query)
sorts = try container.decodeArrayIfPresent(forKey: .sorts)
size = try container.decodeInt16IfPresent(forKey: .size)
from = try container.decodeInt16IfPresent(forKey: .from)
sourceFilter = try container.decodeIfPresent(SourceFilter.self, forKey: .sourceFilter)
explain = try container.decodeBoolIfPresent(forKey: .explain)
minScore = try container.decodeDecimalIfPresent(forKey: .minScore)
trackScores = try container.decodeBoolIfPresent(forKey: .trackScores)
indicesBoost = try container.decodeArrayIfPresent(forKey: .indicesBoost)
seqNoPrimaryTerm = try container.decodeBoolIfPresent(forKey: .seqNoPrimaryTerm)
version = try container.decodeBoolIfPresent(forKey: .version)
storedFields = try container.decodeArrayIfPresent(forKey: .storedFields)
docvalueFields = try container.decodeArrayIfPresent(forKey: .docvalueFields)
postFilter = try container.decodeQueryIfPresent(forKey: .postFilter)
highlight = try container.decodeIfPresent(Highlight.self, forKey: .highlight)
searchAfter = try container.decodeIfPresent(CodableValue.self, forKey: .searchAfter)
suggest = try container.decodeIfPresent(SuggestSource.self, forKey: .suggest)
do {
scriptFields = try container.decodeArrayIfPresent(forKey: .scriptFields)
} catch {
let scriptField = try container.decode(ScriptField.self, forKey: .scriptFields)
scriptFields = [scriptField]
}
do {
rescore = try container.decodeRescorersIfPresent(forKey: .rescore)
} catch {
let rescorer = try container.decode(QueryRescorer.self, forKey: .rescore)
rescore = [rescorer]
}
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encodeIfPresent(query, forKey: .query)
try container.encodeIfPresent(sorts, forKey: .sorts)
try container.encodeIfPresent(size, forKey: .size)
try container.encodeIfPresent(from, forKey: .from)
try container.encodeIfPresent(sourceFilter, forKey: .sourceFilter)
try container.encodeIfPresent(explain, forKey: .explain)
try container.encodeIfPresent(minScore, forKey: .minScore)
try container.encodeIfPresent(trackScores, forKey: .trackScores)
try container.encodeIfPresent(indicesBoost, forKey: .indicesBoost)
try container.encodeIfPresent(seqNoPrimaryTerm, forKey: .seqNoPrimaryTerm)
try container.encodeIfPresent(version, forKey: .version)
try container.encodeIfPresent(storedFields, forKey: .storedFields)
try container.encodeIfPresent(docvalueFields, forKey: .docvalueFields)
try container.encodeIfPresent(postFilter, forKey: .postFilter)
try container.encodeIfPresent(highlight, forKey: .highlight)
if let scriptFields = self.scriptFields, !scriptFields.isEmpty {
if scriptFields.count == 1 {
try container.encode(scriptFields[0], forKey: .scriptFields)
} else {
var nested = container.nestedContainer(keyedBy: DynamicCodingKeys.self, forKey: .scriptFields)
for scriptField in scriptFields {
var scriptContainer = nested.nestedContainer(keyedBy: DynamicCodingKeys.self, forKey: .key(named: scriptField.field))
try scriptContainer.encode(scriptField.script, forKey: .key(named: "script"))
}
}
}
if let rescore = self.rescore, !rescore.isEmpty {
if rescore.count == 1 {
try container.encode(rescore[0], forKey: .rescore)
} else {
try container.encode(rescore, forKey: .rescore)
}
}
try container.encodeIfPresent(searchAfter, forKey: .searchAfter)
try container.encodeIfPresent(suggest, forKey: .suggest)
}
enum CodingKeys: String, CodingKey {
case query
case sorts = "sort"
case size
case from
case sourceFilter = "_source"
case explain
case minScore = "min_score"
case trackScores = "track_scores"
case indicesBoost = "indices_boost"
case seqNoPrimaryTerm = "seq_no_primary_term"
case version
case scriptFields = "script_fields"
case storedFields = "stored_fields"
case docvalueFields = "docvalue_fields"
case postFilter = "post_filter"
case highlight
case rescore
case searchAfter = "search_after"
case suggest
}
}
extension SearchSource: Equatable {
public static func == (lhs: SearchSource, rhs: SearchSource) -> Bool {
return lhs.sorts == rhs.sorts
&& lhs.size == rhs.size
&& lhs.from == rhs.from
&& lhs.sourceFilter == rhs.sourceFilter
&& lhs.explain == rhs.explain
&& lhs.minScore == rhs.minScore
&& lhs.trackScores == rhs.trackScores
&& lhs.indicesBoost == rhs.indicesBoost
&& lhs.seqNoPrimaryTerm == rhs.seqNoPrimaryTerm
&& lhs.version == rhs.version
&& lhs.scriptFields == rhs.scriptFields
&& lhs.storedFields == rhs.storedFields
&& lhs.docvalueFields == rhs.docvalueFields
&& lhs.highlight == rhs.highlight
&& isEqualRescorers(lhs.rescore, rhs.rescore)
&& lhs.searchAfter == rhs.searchAfter
&& isEqualQueries(lhs.query, rhs.query)
&& isEqualQueries(lhs.postFilter, rhs.postFilter)
&& lhs.suggest == rhs.suggest
}
}
// MARK: - Search Template Request Builder
public class SearchTemplateRequestBuilder: RequestBuilder {
public typealias RequestType = SearchTemplateRequest
private var _scriptType: ScriptType?
private var _script: String?
private var _params: [String: CodableValue]?
private var _index: String?
private var _type: String?
private var _explain: Bool?
private var _profile: Bool?
private var _ignoreUnavailable: Bool?
private var _ignoreThrottled: Bool?
private var _allowNoIndices: Bool?
private var _expandWildcards: ExpandWildcards?
private var _preference: String?
private var _routing: String?
private var _scroll: String?
private var _searchType: SearchType?
private var _typedKeys: Bool?
private var _restTotalHitsAsInt: Bool?
public init() {}
@discardableResult
public func set(scriptType: ScriptType) -> Self {
_scriptType = scriptType
return self
}
@discardableResult
public func set(script: String) -> Self {
_script = script
return self
}
@discardableResult
public func set(params: [String: CodableValue]) -> Self {
_params = params
return self
}
@discardableResult
public func set(index: String) -> Self {
_index = index
return self
}
@discardableResult
public func set(type: String) -> Self {
_type = type
return self
}
@discardableResult
public func set(explain: Bool) -> Self {
_explain = explain
return self
}
@discardableResult
public func set(profile: Bool) -> Self {
_profile = profile
return self
}
@discardableResult
public func set(ignoreUnavailable: Bool) -> Self {
_ignoreUnavailable = ignoreUnavailable
return self
}
@discardableResult
public func set(ignoreThrottled: Bool) -> Self {
_ignoreThrottled = ignoreThrottled
return self
}
@discardableResult
public func set(allowNoIndices: Bool) -> Self {
_allowNoIndices = allowNoIndices
return self
}
@discardableResult
public func set(routing: String) -> Self {
_routing = routing
return self
}
@discardableResult
public func set(scroll: String) -> Self {
_scroll = scroll
return self
}
@discardableResult
public func set(searchType: SearchType) -> Self {
_searchType = searchType
return self
}
@discardableResult
public func set(typedKeys: Bool) -> Self {
_typedKeys = typedKeys
return self
}
@discardableResult
public func set(restTotalHitsAsInt: Bool) -> Self {
_restTotalHitsAsInt = restTotalHitsAsInt
return self
}
@discardableResult
public func set(expandWildcards: ExpandWildcards) -> Self {
_expandWildcards = expandWildcards
return self
}
@discardableResult
public func set(preference: String) -> Self {
_preference = preference
return self
}
public var scriptType: ScriptType? {
return _scriptType
}
public var script: String? {
return _script
}
public var params: [String: CodableValue]? {
return _params
}
public var index: String? {
return _index
}
public var type: String? {
return _type
}
public var explain: Bool? {
return _explain
}
public var profile: Bool? {
return _profile
}
public var ignoreUnavailable: Bool? {
return _ignoreUnavailable
}
public var ignoreThrottled: Bool? {
return _ignoreThrottled
}
public var allowNoIndices: Bool? {
return _allowNoIndices
}
public var expandWildcards: ExpandWildcards? {
return _expandWildcards
}
public var preference: String? {
return _preference
}
public var routing: String? {
return _routing
}
public var scroll: String? {
return _scroll
}
public var searchType: SearchType? {
return _searchType
}
public var typedKeys: Bool? {
return _typedKeys
}
public var restTotalHitsAsInt: Bool? {
return _restTotalHitsAsInt
}
public func build() throws -> SearchTemplateRequest {
return try SearchTemplateRequest(withBuilder: self)
}
}
// MARK: - Search Template Request
public struct SearchTemplateRequest: Request {
public var headers = HTTPHeaders()
public let scriptType: ScriptType
public let script: String
public let params: [String: CodableValue]
public let index: String?
public let type: String?
public let explain: Bool?
public let profile: Bool?
public var ignoreUnavailable: Bool?
public var ignoreThrottled: Bool?
public var allowNoIndices: Bool?
public var expandWildcards: ExpandWildcards?
public var preference: String?
public var routing: String?
public var scroll: String?
public var searchType: SearchType?
public var typedKeys: Bool?
public var restTotalHitsAsInt: Bool?
public init(scriptType: ScriptType, script: String, params: [String: CodableValue], index: String?, type: String?, explain: Bool?, profile: Bool?, ignoreUnavailable: Bool? = nil, ignoreThrottled: Bool? = nil, allowNoIndices: Bool? = nil, expandWildcards: ExpandWildcards? = nil, preference: String? = nil, routing: String? = nil, scroll: String? = nil, searchType: SearchType? = nil, typedKeys: Bool? = nil, restTotalHitsAsInt: Bool? = nil) {
self.scriptType = scriptType
self.script = script
self.params = params
self.index = index
self.type = type
self.explain = explain
self.profile = profile
self.ignoreUnavailable = ignoreUnavailable
self.ignoreThrottled = ignoreThrottled
self.allowNoIndices = allowNoIndices
self.expandWildcards = expandWildcards
self.preference = preference
self.routing = routing
self.scroll = scroll
self.searchType = searchType
self.typedKeys = typedKeys
self.restTotalHitsAsInt = restTotalHitsAsInt
}
internal init(withBuilder builder: SearchTemplateRequestBuilder) throws {
guard let script = builder.script else {
throw RequestBuilderError.missingRequiredField("script")
}
guard let scriptType = builder.scriptType else {
throw RequestBuilderError.missingRequiredField("scriptType")
}
guard let params = builder.params else {
throw RequestBuilderError.missingRequiredField("params")
}
self.init(scriptType: scriptType, script: script, params: params, index: builder.index, type: builder.type, explain: builder.explain, profile: builder.profile, ignoreUnavailable: builder.ignoreUnavailable, ignoreThrottled: builder.ignoreThrottled, allowNoIndices: builder.allowNoIndices, expandWildcards: builder.expandWildcards, preference: builder.preference, routing: builder.routing, scroll: builder.scroll, searchType: builder.searchType, typedKeys: builder.typedKeys, restTotalHitsAsInt: builder.restTotalHitsAsInt)
}
public var queryParams: [URLQueryItem] {
var queryItems = [URLQueryItem]()
if let ignoreUnavailable = self.ignoreUnavailable {
queryItems.append(URLQueryItem(name: QueryParams.ignoreUnavailable, value: ignoreUnavailable))
}
if let ignoreThrottled = self.ignoreThrottled {
queryItems.append(URLQueryItem(name: QueryParams.ignoreThrottled, value: ignoreThrottled))
}
if let allowNoIndices = self.allowNoIndices {
queryItems.append(URLQueryItem(name: QueryParams.allowNoIndices, value: allowNoIndices))
}
if let expandWildcards = self.expandWildcards {
queryItems.append(URLQueryItem(name: QueryParams.expandWildcards, value: expandWildcards.rawValue))
}
if let preference = self.preference {
queryItems.append(URLQueryItem(name: QueryParams.preference, value: preference))
}
if let routing = self.routing {
queryItems.append(URLQueryItem(name: QueryParams.routing, value: routing))
}
if let scroll = self.scroll {
queryItems.append(URLQueryItem(name: QueryParams.scroll, value: scroll))
}
if let searchType = self.searchType {
queryItems.append(URLQueryItem(name: QueryParams.searchType, value: searchType.rawValue))
}
if let typedKeys = self.typedKeys {
queryItems.append(URLQueryItem(name: QueryParams.typedKeys, value: typedKeys))
}
if let restTotalHitsAsInt = self.restTotalHitsAsInt {
queryItems.append(URLQueryItem(name: QueryParams.restTotalHitsAsInt, value: restTotalHitsAsInt))
}
return queryItems
}
public var method: HTTPMethod {
return .POST
}
public var endPoint: String {
var _endPoint = "_search/template"
if let type = self.type {
_endPoint = "\(type)/\(_endPoint)"
}
if let index = self.index {
_endPoint = "\(index)/\(_endPoint)"
}
return _endPoint
}
public func makeBody(_ serializer: Serializer) -> Result<Data, MakeBodyError> {
let body = (scriptType == .stored) ? Body(id: script, source: nil, params: params, explain: explain, profile: profile)
: Body(id: nil, source: script, params: params, explain: explain, profile: profile)
return serializer.encode(body).mapError { error -> MakeBodyError in
MakeBodyError.wrapped(error)
}
}
private struct Body: Encodable {
public let id: String?
public let source: String?
public let params: [String: CodableValue]
public let explain: Bool?
public let profile: Bool?
}
}
extension SearchTemplateRequest: Equatable {}
// MARK: - Extensions
public func isEqualRescorers(_ lhs: Rescorer?, _ rhs: Rescorer?) -> Bool {
if lhs == nil, rhs == nil {
return true
}
if let lhs = lhs, let rhs = rhs {
return lhs.isEqualTo(rhs)
}
return false
}
public func isEqualRescorers(_ lhs: [Rescorer]?, _ rhs: [Rescorer]?) -> Bool {
if lhs == nil, rhs == nil {
return true
}
if let lhs = lhs, let rhs = rhs {
if lhs.count == rhs.count {
return !zip(lhs, rhs).contains { !$0.isEqualTo($1) }
}
}
return false
}
public extension KeyedEncodingContainer {
mutating func encode(_ value: Rescorer, forKey key: KeyedEncodingContainer<K>.Key) throws {
try value.encode(to: superEncoder(forKey: key))
}
mutating func encode(_ value: [Rescorer], forKey key: KeyedEncodingContainer<K>.Key) throws {
let rescorersEncoder = superEncoder(forKey: key)
var rescorersContainer = rescorersEncoder.unkeyedContainer()
for rescorer in value {
let rescorerEncoder = rescorersContainer.superEncoder()
try rescorer.encode(to: rescorerEncoder)
}
}
}
public extension KeyedDecodingContainer {
func decodeRescorer(forKey key: KeyedDecodingContainer<K>.Key) throws -> Rescorer {
let qContainer = try nestedContainer(keyedBy: DynamicCodingKeys.self, forKey: key)
for rKey in qContainer.allKeys {
if let rType = RescorerTypes(rKey.stringValue) {
return try rType.metaType.init(from: superDecoder(forKey: key))
}
}
throw Swift.DecodingError.typeMismatch(RescorerTypes.self, .init(codingPath: codingPath, debugDescription: "Unable to identify rescorer type from key(s) \(qContainer.allKeys)"))
}
func decodeRescorerIfPresent(forKey key: KeyedDecodingContainer<K>.Key) throws -> Rescorer? {
guard contains(key) else {
return nil
}
return try decodeRescorer(forKey: key)
}
func decodeRescorers(forKey key: KeyedDecodingContainer<K>.Key) throws -> [Rescorer] {
var arrayContainer = try nestedUnkeyedContainer(forKey: key)
var result = [Rescorer]()
if let count = arrayContainer.count {
while !arrayContainer.isAtEnd {
let query = try arrayContainer.decodeRescorer()
result.append(query)
}
if result.count != count {
throw Swift.DecodingError.dataCorrupted(.init(codingPath: arrayContainer.codingPath, debugDescription: "Unable to decode all Rescorers expected: \(count) actual: \(result.count). Probable cause: Unable to determine RescorerType form key(s)"))
}
}
return result
}
func decodeRescorersIfPresent(forKey key: KeyedDecodingContainer<K>.Key) throws -> [Rescorer]? {
guard contains(key) else {
return nil
}
return try decodeRescorers(forKey: key)
}
}
extension UnkeyedDecodingContainer {
mutating func decodeRescorer() throws -> Rescorer {
var copy = self
let elementContainer = try copy.nestedContainer(keyedBy: DynamicCodingKeys.self)
for rKey in elementContainer.allKeys {
if let rType = RescorerTypes(rKey.stringValue) {
return try rType.metaType.init(from: superDecoder())
}
}
throw Swift.DecodingError.typeMismatch(RescorerTypes.self, .init(codingPath: codingPath, debugDescription: "Unable to identify rescorer type from key(s) \(elementContainer.allKeys)"))
}
}
| mit | e3f454fdc35c551d42b1761e7577988a | 31.762038 | 657 | 0.644671 | 4.983335 | false | false | false | false |
XGBCCC/JBImageBrowserViewController | Example/JBImagesBrowserViewController/ViewController.swift | 1 | 1053 | //
// ViewController.swift
// JBImagesBrowserViewController
//
// Created by JimBo on 16/2/17.
// Copyright ยฉ 2016ๅนด JimBo. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
@IBAction func buttonDidTouched(_ sender: UIButton) {
let image_1 = JBImage(url: URL.init(string: "http://images.apple.com/v/home/cj/images/promos/accessories_large_2x.jpg"))
let image_2 = JBImage(filePathURL: Bundle.main.url(forResource: "IMG_5445", withExtension: "JPG"))
let image_3 = JBImage(image: UIImage(named: "IMG_5429"))
let failedImage = UIImage(named: "error_place_image")
let imageBrowserVC = JBImageBrowserViewController(imageArray: [image_1,image_2,image_3],failedPlaceholderImage:failedImage)
self.present(imageBrowserVC, animated: true, completion: nil)
}
}
| mit | 295a4057dac5b4d1a95ed94c5e4f6c81 | 29 | 131 | 0.65619 | 3.932584 | false | false | false | false |
remzr7/Surge | Sources/Arithmetic.swift | 1 | 9710 | // Arithmetic.swift
//
// Copyright (c) 2014โ2015 Mattt Thompson (http://mattt.me)
//
// 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 Accelerate
// MARK: Sum
public func sum(_ x: [Float]) -> Float {
var result: Float = 0.0
vDSP_sve(x, 1, &result, vDSP_Length(x.count))
return result
}
public func sum(_ x: [Double]) -> Double {
var result: Double = 0.0
vDSP_sveD(x, 1, &result, vDSP_Length(x.count))
return result
}
// MARK: Sum of Absolute Values
public func asum(_ x: [Float]) -> Float {
return cblas_sasum(Int32(x.count), x, 1)
}
public func asum(_ x: [Double]) -> Double {
return cblas_dasum(Int32(x.count), x, 1)
}
// MARK: Maximum
public func max(_ x: [Float]) -> Float {
var result: Float = 0.0
vDSP_maxv(x, 1, &result, vDSP_Length(x.count))
return result
}
public func max(_ x: [Double]) -> Double {
var result: Double = 0.0
vDSP_maxvD(x, 1, &result, vDSP_Length(x.count))
return result
}
// MARK: Minimum
public func min(_ x: [Float]) -> Float {
var result: Float = 0.0
vDSP_minv(x, 1, &result, vDSP_Length(x.count))
return result
}
public func min(_ x: [Double]) -> Double {
var result: Double = 0.0
vDSP_minvD(x, 1, &result, vDSP_Length(x.count))
return result
}
// MARK: Mean
public func mean(_ x: [Float]) -> Float {
var result: Float = 0.0
vDSP_meanv(x, 1, &result, vDSP_Length(x.count))
return result
}
public func mean(_ x: [Double]) -> Double {
var result: Double = 0.0
vDSP_meanvD(x, 1, &result, vDSP_Length(x.count))
return result
}
// MARK: Mean Magnitude
public func meamg(_ x: [Float]) -> Float {
var result: Float = 0.0
vDSP_meamgv(x, 1, &result, vDSP_Length(x.count))
return result
}
public func meamg(_ x: [Double]) -> Double {
var result: Double = 0.0
vDSP_meamgvD(x, 1, &result, vDSP_Length(x.count))
return result
}
// MARK: Mean Square Value
public func measq(_ x: [Float]) -> Float {
var result: Float = 0.0
vDSP_measqv(x, 1, &result, vDSP_Length(x.count))
return result
}
public func measq(_ x: [Double]) -> Double {
var result: Double = 0.0
vDSP_measqvD(x, 1, &result, vDSP_Length(x.count))
return result
}
// MARK: Add
public func add(_ x: [Float], y: [Float]) -> [Float] {
var results = [Float](y)
cblas_saxpy(Int32(x.count), 1.0, x, 1, &results, 1)
return results
}
public func add(_ x: [Double], y: [Double]) -> [Double] {
var results = [Double](y)
cblas_daxpy(Int32(x.count), 1.0, x, 1, &results, 1)
return results
}
// MARK: Subtraction
public func sub(_ x: [Float], y: [Float]) -> [Float] {
var results = [Float](y)
catlas_saxpby(Int32(x.count), 1.0, x, 1, -1, &results, 1)
return results
}
public func sub(_ x: [Double], y: [Double]) -> [Double] {
var results = [Double](y)
catlas_daxpby(Int32(x.count), 1.0, x, 1, -1, &results, 1)
return results
}
// MARK: Multiply
public func mul(_ x: [Float], y: [Float]) -> [Float] {
var results = [Float](repeating: 0.0, count: x.count)
vDSP_vmul(x, 1, y, 1, &results, 1, vDSP_Length(x.count))
return results
}
public func mul(_ x: [Double], y: [Double]) -> [Double] {
var results = [Double](repeating: 0.0, count: x.count)
vDSP_vmulD(x, 1, y, 1, &results, 1, vDSP_Length(x.count))
return results
}
// MARK: Divide
public func div(_ x: [Float], y: [Float]) -> [Float] {
var results = [Float](repeating: 0.0, count: x.count)
vvdivf(&results, x, y, [Int32(x.count)])
return results
}
public func div(_ x: [Double], y: [Double]) -> [Double] {
var results = [Double](repeating: 0.0, count: x.count)
vvdiv(&results, x, y, [Int32(x.count)])
return results
}
// MARK: Modulo
public func mod(_ x: [Float], y: [Float]) -> [Float] {
var results = [Float](repeating: 0.0, count: x.count)
vvfmodf(&results, x, y, [Int32(x.count)])
return results
}
public func mod(_ x: [Double], y: [Double]) -> [Double] {
var results = [Double](repeating: 0.0, count: x.count)
vvfmod(&results, x, y, [Int32(x.count)])
return results
}
// MARK: Remainder
public func remainder(_ x: [Float], y: [Float]) -> [Float] {
var results = [Float](repeating: 0.0, count: x.count)
vvremainderf(&results, x, y, [Int32(x.count)])
return results
}
public func remainder(_ x: [Double], y: [Double]) -> [Double] {
var results = [Double](repeating: 0.0, count: x.count)
vvremainder(&results, x, y, [Int32(x.count)])
return results
}
// MARK: Square Root
public func sqrt(_ x: [Float]) -> [Float] {
var results = [Float](repeating: 0.0, count: x.count)
vvsqrtf(&results, x, [Int32(x.count)])
return results
}
public func sqrt(_ x: [Double]) -> [Double] {
var results = [Double](repeating: 0.0, count: x.count)
vvsqrt(&results, x, [Int32(x.count)])
return results
}
// MARK: Dot Product
public func dot(_ x: [Float], y: [Float]) -> Float {
precondition(x.count == y.count, "Vectors must have equal count")
var result: Float = 0.0
vDSP_dotpr(x, 1, y, 1, &result, vDSP_Length(x.count))
return result
}
public func dot(_ x: [Double], y: [Double]) -> Double {
precondition(x.count == y.count, "Vectors must have equal count")
var result: Double = 0.0
vDSP_dotprD(x, 1, y, 1, &result, vDSP_Length(x.count))
return result
}
// MARK: - Distance
public func dist(_ x: [Float], y: [Float]) -> Float {
precondition(x.count == y.count, "Vectors must have equal count")
let sub = x - y
var squared = [Float](repeating: 0.0, count: x.count)
vDSP_vsq(sub, 1, &squared, 1, vDSP_Length(x.count))
return sqrt(sum(squared))
}
public func dist(_ x: [Double], y: [Double]) -> Double {
precondition(x.count == y.count, "Vectors must have equal count")
let sub = x - y
var squared = [Double](repeating: 0.0, count: x.count)
vDSP_vsqD(sub, 1, &squared, 1, vDSP_Length(x.count))
return sqrt(sum(squared))
}
// MARK: - Sum of Square Values
public func sumsq(_ x: [Float]) -> Float {
var result: Float = 0
vDSP_svesq(x, 1, &result, vDSP_Length(x.count))
return result
}
public func sumsq(_ x: [Double]) -> Double {
var result: Double = 0
vDSP_svesqD(x, 1, &result, vDSP_Length(x.count))
return result
}
// MARK: - Operators
public func + (lhs: [Float], rhs: [Float]) -> [Float] {
return add(lhs, y: rhs)
}
public func + (lhs: [Double], rhs: [Double]) -> [Double] {
return add(lhs, y: rhs)
}
public func + (lhs: [Float], rhs: Float) -> [Float] {
return add(lhs, y: [Float](repeating: rhs, count: lhs.count))
}
public func + (lhs: [Double], rhs: Double) -> [Double] {
return add(lhs, y: [Double](repeating: rhs, count: lhs.count))
}
public func - (lhs: [Float], rhs: [Float]) -> [Float] {
return sub(lhs, y: rhs)
}
public func - (lhs: [Double], rhs: [Double]) -> [Double] {
return sub(lhs, y: rhs)
}
public func - (lhs: [Float], rhs: Float) -> [Float] {
return sub(lhs, y: [Float](repeating: rhs, count: lhs.count))
}
public func - (lhs: [Double], rhs: Double) -> [Double] {
return sub(lhs, y: [Double](repeating: rhs, count: lhs.count))
}
public func / (lhs: [Float], rhs: [Float]) -> [Float] {
return div(lhs, y: rhs)
}
public func / (lhs: [Double], rhs: [Double]) -> [Double] {
return div(lhs, y: rhs)
}
public func / (lhs: [Float], rhs: Float) -> [Float] {
return div(lhs, y: [Float](repeating: rhs, count: lhs.count))
}
public func / (lhs: [Double], rhs: Double) -> [Double] {
return div(lhs, y: [Double](repeating: rhs, count: lhs.count))
}
public func * (lhs: [Float], rhs: [Float]) -> [Float] {
return mul(lhs, y: rhs)
}
public func * (lhs: [Double], rhs: [Double]) -> [Double] {
return mul(lhs, y: rhs)
}
public func * (lhs: [Float], rhs: Float) -> [Float] {
return mul(lhs, y: [Float](repeating: rhs, count: lhs.count))
}
public func * (lhs: [Double], rhs: Double) -> [Double] {
return mul(lhs, y: [Double](repeating: rhs, count: lhs.count))
}
public func % (lhs: [Float], rhs: [Float]) -> [Float] {
return mod(lhs, y: rhs)
}
public func % (lhs: [Double], rhs: [Double]) -> [Double] {
return mod(lhs, y: rhs)
}
public func % (lhs: [Float], rhs: Float) -> [Float] {
return mod(lhs, y: [Float](repeating: rhs, count: lhs.count))
}
public func % (lhs: [Double], rhs: Double) -> [Double] {
return mod(lhs, y: [Double](repeating: rhs, count: lhs.count))
}
infix operator โข
public func โข (lhs: [Double], rhs: [Double]) -> Double {
return dot(lhs, y: rhs)
}
public func โข (lhs: [Float], rhs: [Float]) -> Float {
return dot(lhs, y: rhs)
}
| mit | 72fc28cce06075ee65d764b3c58342b7 | 24.134715 | 80 | 0.615852 | 3.042333 | false | false | false | false |
OneBusAway/onebusaway-iphone | Carthage/Checkouts/IGListKit/Examples/Examples-iOS/IGListKitExamples/Views/CenterLabelCell.swift | 2 | 1276 | /**
Copyright (c) Facebook, Inc. and its affiliates.
The examples provided by Facebook are for non-commercial testing and evaluation
purposes only. Facebook reserves all rights not expressly granted.
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
FACEBOOK 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
final class CenterLabelCell: UICollectionViewCell {
lazy private var label: UILabel = {
let view = UILabel()
view.backgroundColor = .clear
view.textAlignment = .center
view.textColor = .white
view.font = .boldSystemFont(ofSize: 18)
self.contentView.addSubview(view)
return view
}()
var text: String? {
get {
return label.text
}
set {
label.text = newValue
}
}
override func layoutSubviews() {
super.layoutSubviews()
label.frame = contentView.bounds
}
}
| apache-2.0 | eafdd6c46500551f8c9e20c9f094274a | 28.674419 | 80 | 0.678683 | 4.870229 | false | false | false | false |
sora0077/DribbbleKit | DribbbleKit/Sources/Users/User.swift | 1 | 4082 | //
// User.swift
// DribbbleKit
//
// Created by ๆ ้ไน on 2017/04/19.
// Copyright ยฉ 2017ๅนด jp.sora0077. All rights reserved.
//
import Foundation
import Alter
public struct User {
public struct Identifier: Decodable, Hashable, ExpressibleByIntegerLiteral {
let value: Int
public var hashValue: Int { return value.hashValue }
public init(integerLiteral value: Int) {
self.value = value
}
public init(_ value: Int) {
self.value = value
}
public static func decode(_ decoder: Decoder) throws -> User.Identifier {
return try self.init(integerLiteral: Int.decode(decoder))
}
public static func == (lhs: Identifier, rhs: Identifier) -> Bool {
return lhs.value == rhs.value
}
}
}
extension Int {
public init(_ userId: User.Identifier) {
self = userId.value
}
}
// MARK: - UserData
public protocol UserData: Decodable {
typealias Identifier = User.Identifier
init(
id: User.Identifier,
name: String,
username: String,
htmlURL: URL,
avatarURL: URL,
bio: String,
location: String,
links: [String: URL],
bucketsCount: Int,
commentsReceivedCount: Int,
followersCount: Int,
followingsCount: Int,
likesCount: Int,
likesReceivedCount: Int,
projectsCount: Int,
reboundsReceivedCount: Int,
shotsCount: Int,
teamsCount: Int,
canUploadShot: Bool,
type: String,
pro: Bool,
bucketsURL: URL,
followersURL: URL,
followingURL: URL,
likesURL: URL,
shotsURL: URL,
teamsURL: URL,
createdAt: Date,
updatedAt: Date
) throws
}
extension UserData {
public static func decode(_ decoder: Decoder) throws -> Self {
return try self.init(
id: decoder.decode(forKeyPath: "id"),
name: decoder.decode(forKeyPath: "name"),
username: decoder.decode(forKeyPath: "username"),
htmlURL: decoder.decode(forKeyPath: "html_url", Transformer.url),
avatarURL: decoder.decode(forKeyPath: "avatar_url", Transformer.url),
bio: decoder.decode(forKeyPath: "bio"),
location: decoder.decode(forKeyPath: "location", optional: true) ?? "",
links: decoder.decode(forKeyPath: "links", Transformer.url),
bucketsCount: decoder.decode(forKeyPath: "buckets_count"),
commentsReceivedCount: decoder.decode(forKeyPath: "comments_received_count"),
followersCount: decoder.decode(forKeyPath: "followers_count"),
followingsCount: decoder.decode(forKeyPath: "followings_count"),
likesCount: decoder.decode(forKeyPath: "likes_count"),
likesReceivedCount: decoder.decode(forKeyPath: "likes_received_count"),
projectsCount: decoder.decode(forKeyPath: "projects_count"),
reboundsReceivedCount: decoder.decode(forKeyPath: "rebounds_received_count"),
shotsCount: decoder.decode(forKeyPath: "shots_count"),
teamsCount: decoder.decode(forKeyPath: "teams_count"),
canUploadShot: decoder.decode(forKeyPath: "can_upload_shot"),
type: decoder.decode(forKeyPath: "type"),
pro: decoder.decode(forKeyPath: "pro"),
bucketsURL: decoder.decode(forKeyPath: "buckets_url", Transformer.url),
followersURL: decoder.decode(forKeyPath: "followers_url", Transformer.url),
followingURL: decoder.decode(forKeyPath: "following_url", Transformer.url),
likesURL: decoder.decode(forKeyPath: "likes_url", Transformer.url),
shotsURL: decoder.decode(forKeyPath: "shots_url", Transformer.url),
teamsURL: decoder.decode(forKeyPath: "teams_url", Transformer.url),
createdAt: decoder.decode(forKeyPath: "created_at", Transformer.date),
updatedAt: decoder.decode(forKeyPath: "updated_at", Transformer.date))
}
}
| mit | 424b974de6ddf3afaa17699e11b38a15 | 36.027273 | 89 | 0.621655 | 4.520533 | false | false | false | false |
haranicle/AlcatrazTour | Pods/OAuthSwift/OAuthSwift/SHA1.swift | 17 | 4513 | //
// SHA1.swift
// OAuthSwift
//
// Created by Dongri Jin on 1/28/15.
// Copyright (c) 2015 Dongri Jin. All rights reserved.
//
import Foundation
class SHA1 {
var message: NSData
init(_ message: NSData) {
self.message = message
}
/** Common part for hash calculation. Prepare header data. */
func prepare(len:Int = 64) -> NSMutableData {
let tmpMessage: NSMutableData = NSMutableData(data: self.message)
// Step 1. Append Padding Bits
tmpMessage.appendBytes([0x80]) // append one bit (Byte with one bit) to message
// append "0" bit until message length in bits โก 448 (mod 512)
while tmpMessage.length % len != (len - 8) {
tmpMessage.appendBytes([0x00])
}
return tmpMessage
}
func calculate() -> NSData {
//var tmpMessage = self.prepare()
let len = 64
let h:[UInt32] = [0x67452301, 0xEFCDAB89, 0x98BADCFE, 0x10325476, 0xC3D2E1F0]
let tmpMessage: NSMutableData = NSMutableData(data: self.message)
// Step 1. Append Padding Bits
tmpMessage.appendBytes([0x80]) // append one bit (Byte with one bit) to message
// append "0" bit until message length in bits โก 448 (mod 512)
while tmpMessage.length % len != (len - 8) {
tmpMessage.appendBytes([0x00])
}
// hash values
var hh = h
// append message length, in a 64-bit big-endian integer. So now the message length is a multiple of 512 bits.
tmpMessage.appendBytes((self.message.length * 8).bytes(64 / 8))
// Process the message in successive 512-bit chunks:
let chunkSizeBytes = 512 / 8 // 64
var leftMessageBytes = tmpMessage.length
for var i = 0; i < tmpMessage.length; i = i + chunkSizeBytes, leftMessageBytes -= chunkSizeBytes {
let chunk = tmpMessage.subdataWithRange(NSRange(location: i, length: min(chunkSizeBytes,leftMessageBytes)))
// break chunk into sixteen 32-bit words M[j], 0 โค j โค 15, big-endian
// Extend the sixteen 32-bit words into eighty 32-bit words:
var M:[UInt32] = [UInt32](count: 80, repeatedValue: 0)
for x in 0..<M.count {
switch (x) {
case 0...15:
var le:UInt32 = 0
chunk.getBytes(&le, range:NSRange(location:x * sizeofValue(M[x]), length: sizeofValue(M[x])))
M[x] = le.bigEndian
break
default:
M[x] = rotateLeft(M[x-3] ^ M[x-8] ^ M[x-14] ^ M[x-16], n: 1)
break
}
}
var A = hh[0]
var B = hh[1]
var C = hh[2]
var D = hh[3]
var E = hh[4]
// Main loop
for j in 0...79 {
var f: UInt32 = 0
var k: UInt32 = 0
switch (j) {
case 0...19:
f = (B & C) | ((~B) & D)
k = 0x5A827999
break
case 20...39:
f = B ^ C ^ D
k = 0x6ED9EBA1
break
case 40...59:
f = (B & C) | (B & D) | (C & D)
k = 0x8F1BBCDC
break
case 60...79:
f = B ^ C ^ D
k = 0xCA62C1D6
break
default:
break
}
let temp = (rotateLeft(A,n: 5) &+ f &+ E &+ M[j] &+ k) & 0xffffffff
E = D
D = C
C = rotateLeft(B, n: 30)
B = A
A = temp
}
hh[0] = (hh[0] &+ A) & 0xffffffff
hh[1] = (hh[1] &+ B) & 0xffffffff
hh[2] = (hh[2] &+ C) & 0xffffffff
hh[3] = (hh[3] &+ D) & 0xffffffff
hh[4] = (hh[4] &+ E) & 0xffffffff
}
// Produce the final hash value (big-endian) as a 160 bit number:
let buf: NSMutableData = NSMutableData()
hh.forEach({ (item) -> () in
var i:UInt32 = item.bigEndian
buf.appendBytes(&i, length: sizeofValue(i))
})
return buf.copy() as! NSData
}
} | mit | 85c5f43ebf5abf0ebd2c08258f47071b | 32.626866 | 119 | 0.455938 | 4.206349 | false | false | false | false |
SwiftGit2/SwiftGit2 | SwiftGit2/Diffs.swift | 1 | 3741 | //
// Diffs.swift
// SwiftGit2
//
// Created by Jake Van Alstyne on 8/20/17.
// Copyright ยฉ 2017 GitHub, Inc. All rights reserved.
//
import Clibgit2
public struct StatusEntry {
public var status: Diff.Status
public var headToIndex: Diff.Delta?
public var indexToWorkDir: Diff.Delta?
public init(from statusEntry: git_status_entry) {
self.status = Diff.Status(rawValue: statusEntry.status.rawValue)
if let htoi = statusEntry.head_to_index {
self.headToIndex = Diff.Delta(htoi.pointee)
}
if let itow = statusEntry.index_to_workdir {
self.indexToWorkDir = Diff.Delta(itow.pointee)
}
}
}
public struct Diff {
/// The set of deltas.
public var deltas = [Delta]()
public struct Delta {
public static let type = GIT_OBJECT_REF_DELTA
public var status: Status
public var flags: Flags
public var oldFile: File?
public var newFile: File?
public init(_ delta: git_diff_delta) {
self.status = Status(rawValue: UInt32(git_diff_status_char(delta.status)))
self.flags = Flags(rawValue: delta.flags)
self.oldFile = File(delta.old_file)
self.newFile = File(delta.new_file)
}
}
public struct File {
public var oid: OID
public var path: String
public var size: UInt64
public var flags: Flags
public init(_ diffFile: git_diff_file) {
self.oid = OID(diffFile.id)
let path = diffFile.path
self.path = path.map(String.init(cString:))!
self.size = diffFile.size
self.flags = Flags(rawValue: diffFile.flags)
}
}
public struct Status: OptionSet {
// This appears to be necessary due to bug in Swift
// https://bugs.swift.org/browse/SR-3003
public init(rawValue: UInt32) {
self.rawValue = rawValue
}
public let rawValue: UInt32
public static let current = Status(rawValue: GIT_STATUS_CURRENT.rawValue)
public static let indexNew = Status(rawValue: GIT_STATUS_INDEX_NEW.rawValue)
public static let indexModified = Status(rawValue: GIT_STATUS_INDEX_MODIFIED.rawValue)
public static let indexDeleted = Status(rawValue: GIT_STATUS_INDEX_DELETED.rawValue)
public static let indexRenamed = Status(rawValue: GIT_STATUS_INDEX_RENAMED.rawValue)
public static let indexTypeChange = Status(rawValue: GIT_STATUS_INDEX_TYPECHANGE.rawValue)
public static let workTreeNew = Status(rawValue: GIT_STATUS_WT_NEW.rawValue)
public static let workTreeModified = Status(rawValue: GIT_STATUS_WT_MODIFIED.rawValue)
public static let workTreeDeleted = Status(rawValue: GIT_STATUS_WT_DELETED.rawValue)
public static let workTreeTypeChange = Status(rawValue: GIT_STATUS_WT_TYPECHANGE.rawValue)
public static let workTreeRenamed = Status(rawValue: GIT_STATUS_WT_RENAMED.rawValue)
public static let workTreeUnreadable = Status(rawValue: GIT_STATUS_WT_UNREADABLE.rawValue)
public static let ignored = Status(rawValue: GIT_STATUS_IGNORED.rawValue)
public static let conflicted = Status(rawValue: GIT_STATUS_CONFLICTED.rawValue)
}
public struct Flags: OptionSet {
// This appears to be necessary due to bug in Swift
// https://bugs.swift.org/browse/SR-3003
public init(rawValue: UInt32) {
self.rawValue = rawValue
}
public let rawValue: UInt32
public static let binary = Flags([])
public static let notBinary = Flags(rawValue: 1 << 0)
public static let validId = Flags(rawValue: 1 << 1)
public static let exists = Flags(rawValue: 1 << 2)
}
/// Create an instance with a libgit2 `git_diff`.
public init(_ pointer: OpaquePointer) {
for i in 0..<git_diff_num_deltas(pointer) {
if let delta = git_diff_get_delta(pointer, i) {
deltas.append(Diff.Delta(delta.pointee))
}
}
}
}
| mit | ca93c60e33c8993f1802d50ac456a62b | 32.693694 | 99 | 0.70107 | 3.369369 | false | false | false | false |
SolarSwiftem/solarswiftem.github.io | solutions/lesson_3/for.swift | 1 | 300 | //Answers to Lesson 3: For Loops
// Question 1
for var i=1; i<11; i++ {
print(i)
}
// Question 2
for var i=0; i<51; i+=5 {
print(i)
}
// Question 3
for var i=10; i>0; i-- {
print(i)
}
// Question 4
for var i=40; i>=0; i-=4 {
print(i)
}
// Question 5
for var i=1; i^2<=81; i++ {
print(i)
}
| apache-2.0 | 6bca7c72d30c525e7c9f8e6df74ed88b | 10.538462 | 33 | 0.54 | 2.013423 | false | false | false | false |
richardpiazza/XCServerCoreData | Example/Pods/CodeQuickKit/Sources/PausableTimer.swift | 2 | 4389 | #if (os(macOS) || os(iOS) || os(tvOS) || os(watchOS))
import Foundation
public typealias PausableTimerExpiredCompletion = () -> Void
public protocol PausableTimerDelegate {
func pausableTimer(_ timer: PausableTimer, percentComplete: Double)
}
/// PausableTimer
/// Implements a timer that can be paused/resumed. Has options for
/// delegate callbacks of status or a expiry completion handler.
public class PausableTimer {
fileprivate let maxPercentComplete: Double = 1.0
fileprivate var completedIntervals: TimeInterval = 0.0
fileprivate var referenceDate: Date?
public var timeInterval: TimeInterval
public var delegate: PausableTimerDelegate?
public var delegateRefreshRate: Float = 0.1
public var expireCompletion: PausableTimerExpiredCompletion?
/// Instantiates a new PausabelTimer and automatically 'resumes' the execution.
public static func makeTimer(timeInterval: TimeInterval, delegate: PausableTimerDelegate? = nil, expireCompletion: PausableTimerExpiredCompletion? = nil) -> PausableTimer {
let timer = PausableTimer(timeInterval: timeInterval, delegate: delegate, expireCompletion: expireCompletion)
timer.resume()
return timer
}
public static func makeTimer(timeInterval: TimeInterval, delegate: PausableTimerDelegate) -> PausableTimer {
return makeTimer(timeInterval: timeInterval, delegate: delegate, expireCompletion: nil)
}
public static func makeTimer(timeInterval: TimeInterval, expireCompletion: @escaping PausableTimerExpiredCompletion) -> PausableTimer {
return makeTimer(timeInterval: timeInterval, delegate: nil, expireCompletion: expireCompletion)
}
public init(timeInterval: TimeInterval, delegate: PausableTimerDelegate? = nil, expireCompletion: PausableTimerExpiredCompletion? = nil) {
self.timeInterval = timeInterval
self.delegate = delegate
self.expireCompletion = expireCompletion
}
public convenience init(timeInterval: TimeInterval, delegate: PausableTimerDelegate) {
self.init(timeInterval: timeInterval, delegate: delegate, expireCompletion: nil)
}
public convenience init(timeInterval: TimeInterval, expireCompletion: @escaping PausableTimerExpiredCompletion) {
self.init(timeInterval: timeInterval, delegate: nil, expireCompletion: expireCompletion)
}
deinit {
expireCompletion = nil
delegate = nil
referenceDate = nil
}
public var isActive: Bool {
return referenceDate != nil
}
public var percentComplete: Double {
let percent = completedIntervals / timeInterval
return min(percent, maxPercentComplete)
}
fileprivate var dispatchTime: DispatchTime {
return DispatchTime.now() + Double(Int64(delegateRefreshRate * Float(NSEC_PER_SEC))) / Double(NSEC_PER_SEC)
}
/// Resets the timer to the inital state and begins counting.
public func reset() {
completedIntervals = 0
resume()
}
/// Pauses the timer
public func pause() {
referenceDate = nil
}
/// Resumes the timer
public func resume() {
referenceDate = Date(timeIntervalSinceNow: -completedIntervals)
update()
}
/// Calculates the number of completed intervals and notifies the delegate.
fileprivate func update() {
guard let referenceDate = self.referenceDate else {
return
}
completedIntervals = Date().timeIntervalSince(referenceDate)
let percent = percentComplete
guard percent < maxPercentComplete else {
expire()
return
}
if let delegate = self.delegate {
delegate.pausableTimer(self, percentComplete: percent)
}
DispatchQueue.global(qos: .utility).asyncAfter(deadline: dispatchTime) {
self.update()
}
}
/// Terminates the execution of the timer and notifies delegates.
fileprivate func expire() {
referenceDate = nil
if let delegate = self.delegate {
delegate.pausableTimer(self, percentComplete: maxPercentComplete)
}
if let expireCompletion = self.expireCompletion {
expireCompletion()
}
}
}
#endif
| mit | 7cbc9721ec96f9a580bf9bd01a5d813d | 34.395161 | 176 | 0.677147 | 5.744764 | false | false | false | false |
overtake/TelegramSwift | Telegram-Mac/MessageStatsController.swift | 1 | 10590 | //
// MessageStatsController.swift
// Telegram
//
// Created by Mikhail Filimonov on 28/10/2020.
// Copyright ยฉ 2020 Telegram. All rights reserved.
//
import Cocoa
import TGUIKit
import SwiftSignalKit
import TelegramCore
import Postbox
import GraphCore
private func _id_message(_ messageId: MessageId) -> InputDataIdentifier {
return InputDataIdentifier("_id_message_\(messageId)")
}
private func statsEntries(_ stats: MessageStats?, _ search: (SearchMessagesResult, SearchMessagesState)?, _ uiState: UIStatsState, openMessage: @escaping(MessageId) -> Void, updateIsLoading: @escaping(InputDataIdentifier, Bool)->Void, context: MessageStatsContext, accountContext: AccountContext) -> [InputDataEntry] {
var entries: [InputDataEntry] = []
var sectionId: Int32 = 0
var index: Int32 = 0
if let stats = stats {
entries.append(.sectionId(sectionId, type: .normal))
sectionId += 1
entries.append(.desc(sectionId: sectionId, index: index, text: .plain(strings().channelStatsOverview), data: .init(color: theme.colors.listGrayText, viewType: .textTopItem)))
index += 1
var overviewItems:[ChannelOverviewItem] = []
overviewItems.append(ChannelOverviewItem(title: "Views", value: .initialize(string: stats.views.formattedWithSeparator, color: theme.colors.text, font: .medium(.text))))
if let search = search, search.0.totalCount > 0 {
overviewItems.append(ChannelOverviewItem(title: strings().statsMessagePublicForwardsTitle, value: .initialize(string: Int(search.0.totalCount).formattedWithSeparator, color: theme.colors.text, font: .medium(.text))))
}
if stats.forwards > 0 {
overviewItems.append(ChannelOverviewItem(title: strings().statsMessagePrivateForwardsTitle, value: .initialize(string: "โ" + stats.forwards.formattedWithSeparator, color: theme.colors.text, font: .medium(.text))))
}
entries.append(.custom(sectionId: sectionId, index: index, value: .none, identifier: InputDataIdentifier("overview"), equatable: InputDataEquatable(overviewItems), comparable: nil, item: { initialSize, stableId in
return ChannelOverviewStatsRowItem(initialSize, stableId: stableId, items: overviewItems, viewType: .singleItem)
}))
index += 1
entries.append(.sectionId(sectionId, type: .normal))
sectionId += 1
struct Graph {
let graph: StatsGraph
let title: String
let identifier: InputDataIdentifier
let type: ChartItemType
let load:(InputDataIdentifier)->Void
}
var graphs: [Graph] = []
var chartType: ChartItemType
if stats.interactionsGraphDelta == 3600 {
chartType = .twoAxisHourlyStep
} else if stats.interactionsGraphDelta == 300 {
chartType = .twoAxis5MinStep
} else {
chartType = .twoAxisStep
}
if !stats.interactionsGraph.isEmpty {
graphs.append(Graph(graph: stats.interactionsGraph, title: strings().statsMessageInteractionsTitle, identifier: InputDataIdentifier("interactionsGraph"), type: chartType, load: { identifier in
updateIsLoading(identifier, true)
}))
}
for graph in graphs {
entries.append(.sectionId(sectionId, type: .normal))
sectionId += 1
entries.append(.desc(sectionId: sectionId, index: index, text: .plain(graph.title), data: .init(color: theme.colors.listGrayText, viewType: .textTopItem)))
index += 1
switch graph.graph {
case let .Loaded(_, string):
ChartsDataManager.readChart(data: string.data(using: .utf8)!, sync: true, success: { collection in
entries.append(.custom(sectionId: sectionId, index: index, value: .none, identifier: graph.identifier, equatable: InputDataEquatable(graph.graph), comparable: nil, item: { initialSize, stableId in
return StatisticRowItem(initialSize, stableId: stableId, context: accountContext, collection: collection, viewType: .singleItem, type: graph.type, getDetailsData: { date, completion in
})
}))
}, failure: { error in
entries.append(.custom(sectionId: sectionId, index: index, value: .none, identifier: graph.identifier, equatable: InputDataEquatable(graph.graph), comparable: nil, item: { initialSize, stableId in
return StatisticLoadingRowItem(initialSize, stableId: stableId, error: error.localizedDescription)
}))
})
updateIsLoading(graph.identifier, false)
index += 1
case .OnDemand:
entries.append(.custom(sectionId: sectionId, index: index, value: .none, identifier: graph.identifier, equatable: InputDataEquatable(graph.graph), comparable: nil, item: { initialSize, stableId in
return StatisticLoadingRowItem(initialSize, stableId: stableId, error: nil)
}))
index += 1
if !uiState.loading.contains(graph.identifier) {
graph.load(graph.identifier)
}
case let .Failed(error):
entries.append(.custom(sectionId: sectionId, index: index, value: .none, identifier: graph.identifier, equatable: InputDataEquatable(graph.graph), comparable: nil, item: { initialSize, stableId in
return StatisticLoadingRowItem(initialSize, stableId: stableId, error: error)
}))
index += 1
updateIsLoading(graph.identifier, false)
case .Empty:
break
}
}
entries.append(.sectionId(sectionId, type: .normal))
sectionId += 1
if let messages = search?.0, !messages.messages.isEmpty {
entries.append(.desc(sectionId: sectionId, index: index, text: .plain(strings().statsMessagePublicForwardsTitleHeader), data: .init(color: theme.colors.listGrayText, viewType: .textTopItem)))
index += 1
for (i, message) in messages.messages.enumerated() {
entries.append(.custom(sectionId: sectionId, index: index, value: .none, identifier: _id_message(message.id), equatable: InputDataEquatable(message), comparable: nil, item: { initialSize, stableId in
return MessageSharedRowItem(initialSize, stableId: stableId, context: accountContext, message: message, viewType: bestGeneralViewType(messages.messages, for: i), action: {
openMessage(message.id)
})
}))
index += 1
}
entries.append(.sectionId(sectionId, type: .normal))
sectionId += 1
}
} else {
entries.append(.custom(sectionId: sectionId, index: index, value: .none, identifier: InputDataIdentifier("loading"), equatable: nil, comparable: nil, item: { initialSize, stableId in
return StatisticsLoadingRowItem(initialSize, stableId: stableId, context: accountContext, text: strings().channelStatsLoading)
}))
}
return entries
}
func MessageStatsController(_ context: AccountContext, messageId: MessageId, datacenterId: Int32) -> ViewController {
let initialState = UIStatsState(loading: [])
let statePromise = ValuePromise(initialState, ignoreRepeated: true)
let stateValue = Atomic(value: initialState)
let updateState: ((UIStatsState) -> UIStatsState) -> Void = { f in
statePromise.set(stateValue.modify { f($0) })
}
let actionsDisposable = DisposableSet()
let dataPromise = Promise<MessageStats?>(nil)
let messagesPromise = Promise<(SearchMessagesResult, SearchMessagesState)?>(nil)
let statsContext = MessageStatsContext(postbox: context.account.postbox, network: context.account.network, datacenterId: datacenterId, messageId: messageId)
let dataSignal: Signal<MessageStats?, NoError> = statsContext.state
|> map { state in
return state.stats
}
dataPromise.set(.single(nil) |> then(dataSignal))
let openMessage: (MessageId)->Void = { messageId in
context.bindings.rootNavigation().push(ChatAdditionController(context: context, chatLocation: .peer(messageId.peerId), messageId: messageId))
}
let searchSignal = context.engine.messages.searchMessages(location: .publicForwards(messageId: messageId, datacenterId: Int(datacenterId)), query: "", state: nil)
|> map(Optional.init)
|> afterNext { result in
if let result = result {
for message in result.0.messages {
if let peer = message.peers[message.id.peerId], let peerReference = PeerReference(peer) {
let _ = context.engine.peers.updatedRemotePeer(peer: peerReference).start()
}
}
}
}
messagesPromise.set(.single(nil) |> then(searchSignal))
let signal = combineLatest(dataPromise.get(), messagesPromise.get(), statePromise.get())
|> deliverOnMainQueue
|> map { data, search, state -> [InputDataEntry] in
return statsEntries(data, search, state, openMessage: openMessage, updateIsLoading: { identifier, isLoading in
updateState { state in
if isLoading {
return state.withAddedLoading(identifier)
} else {
return state.withRemovedLoading(identifier)
}
}
}, context: statsContext, accountContext: context)
} |> map {
return InputDataSignalValue(entries: $0)
}
|> afterDisposed {
actionsDisposable.dispose()
}
let controller = InputDataController(dataSignal: signal, title: strings().statsMessageTitle, removeAfterDisappear: false, hasDone: false)
controller.contextObject = statsContext
controller.didLoaded = { controller, _ in
controller.tableView.alwaysOpenRowsOnMouseUp = true
controller.tableView.needUpdateVisibleAfterScroll = true
}
controller.onDeinit = {
}
return controller
}
| gpl-2.0 | efc8db3e7bf8dfd0af2b6f61c21f937c | 44.831169 | 318 | 0.627279 | 5.194799 | false | false | false | false |
betaY/columba | Columba/Columba/LoginViewController.swift | 1 | 4716 | //
// LoginViewController.swift
// Columba
//
// Created by Beta on 15/7/23.
// Copyright ยฉ 2015ๅนด Beta. All rights reserved.
//
import UIKit
class LoginViewController: UIViewController {
@IBOutlet weak var userEmailTextField: UITextField!
@IBOutlet weak var userPasswordTextField: UITextField!
// var userData: UserData?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func loginButtonTapped(sender: AnyObject) {
let userEmail = userEmailTextField.text
let userPassword = userPasswordTextField.text
let myUrl: NSURL! = NSURL(string: "http://beta.moe/userLogin.php")
let request: NSMutableURLRequest! = NSMutableURLRequest(URL: myUrl)
request.HTTPMethod = "POST"
let postString = "email=\(userEmail)&password=\(userPassword)"
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
print("url \(myUrl)")
print("post string \(postString)")
print("request \(request.HTTPBody)")
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
data, response, error in
// println("hello ")
if error != nil {
print("error=\(error)")
return
}
// println("response = \(response)")
let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)
print("responseString = \(responseString)")
let _: NSError?
let json = try! NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as? NSDictionary
let jsonArray = try! NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as? NSArray
// print("json = \(json) err = \(err)")
print("array = \(jsonArray)")
if let parseJSON = json {
let resultValue = parseJSON["status"] as! String
print("result: \(resultValue)")
if (resultValue == "Success"){
NSUserDefaults.standardUserDefaults().setBool(true, forKey: "isUserLoggedIn")
NSUserDefaults.standardUserDefaults().setValue("\(userEmail)", forKey: "userEmail")
NSUserDefaults.standardUserDefaults().setValue("\(userPassword)", forKey: "userPassword")
// var userData = UserData(userEmail: "\(userEmail)", userPassword: "\(userPassword)")
// self.userData?.setUserEmail("\(userEmail)")
// self.userData?.setUserPassword("\(userPassword)")
// userData.setUserEmail("\(userEmail)")
// userData.setUserPassword("\(userPassword)")
// NSUserDefaults.standardUserDefaults().setValue(userData, forKey: "userdata")
NSUserDefaults.standardUserDefaults().synchronize()
// println("==================\(userData.getUserEmail()!) \(userData.getUserPassword()!)")
self.dismissViewControllerAnimated(true, completion: nil)
} else {
let messageToDisplay:String = parseJSON["message"] as! String
dispatch_async(dispatch_get_main_queue(), {
let myAlert = UIAlertController(title: "Alert", message: messageToDisplay, preferredStyle: UIAlertControllerStyle.Alert)
let okAction = UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default, handler: nil)
myAlert.addAction(okAction)
self.presentViewController(myAlert, animated: true, completion: nil)
self.userPasswordTextField.text = nil
})
}
}
}
task.resume()
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| mit | 9ea44ca62e058599bf6d6def8304538e | 40.342105 | 144 | 0.571823 | 6.003822 | false | false | false | false |
mleiv/MEGameTracker | MEGameTracker/Models/CoreData/Data Rows/DataItems.swift | 1 | 1036 | //
// DataItems.swift
// MEGameTracker
//
// Created by Emily Ivie on 11/13/15.
// Copyright ยฉ 2015 Emily Ivie. All rights reserved.
//
import Foundation
import CoreData
extension DataItem: DataRowStorable, DataEventsable {
/// (CodableCoreDataStorable Protocol)
/// Type of the core data entity.
public typealias EntityType = DataItems
/// (CodableCoreDataStorable Protocol)
/// Sets core data values to match struct values (specific).
public func setAdditionalColumnsOnSave(
coreItem: EntityType
) {
// only save searchable columns
coreItem.id = id
coreItem.name = name
coreItem.inMapId = inMapId
coreItem.isShowInList = isShowInList ? 1: 0
coreItem.inMissionId = inMissionId
coreItem.gameVersion = gameVersion.stringValue
coreItem.relatedEvents = getRelatedDataEvents(context: coreItem.managedObjectContext)
// coreItem.setValue(itemType.stringValue, forKey: "itemType")
}
/// (DataRowStorable Protocol)
public mutating func migrateId(id newId: String) {
id = newId
}
}
| mit | c319975a9727983d5b87081d131d5064 | 26.236842 | 87 | 0.735266 | 4.074803 | false | false | false | false |
WaterReporter/WaterReporter-iOS | WaterReporter/WaterReporter/NewReportLocationSelector.swift | 1 | 2625 | //
// NewReportLocationSelector.swift
// Water-Reporter
//
// Created by Viable Industries on 10/28/16.
// Copyright ยฉ 2016 Viable Industries, L.L.C. All rights reserved.
//
import Foundation
import Mapbox
import UIKit
protocol NewReportLocationSelectorDelegate {
func sendCoordinates(coordinates : CLLocationCoordinate2D)
func onSetCoordinatesComplete(isFinished: Bool)
}
class NewReportLocationSelector: UIViewController, MGLMapViewDelegate, UINavigationControllerDelegate, CLLocationManagerDelegate {
var delegate: NewReportLocationSelectorDelegate?
@IBOutlet weak var mapReportLocation: MGLMapView!
@IBOutlet weak var mapCenterPoint: UIImageView!
var userSelectedCoordinates: CLLocationCoordinate2D!
@IBOutlet weak var navigationBarButtonCancel: UIBarButtonItem!
@IBOutlet weak var navigationBarButtonSet: UIBarButtonItem!
var mapView: MGLMapView!
override func viewDidLoad() {
super.viewDidLoad()
self.mapView = mapReportLocation
self.navigationBarButtonCancel.target = self
self.navigationBarButtonCancel.action = #selector(NewReportLocationSelector.dismissLocationSelector(_:))
self.navigationBarButtonCancel.enabled = true
self.navigationBarButtonSet.target = self
self.navigationBarButtonSet.action = #selector(NewReportLocationSelector.setLocationSelector(_:))
self.navigationBarButtonSet.enabled = false
}
func mapViewDidFinishLoadingMap(mapView: MGLMapView) {
self.mapView.showsUserLocation = true
self.mapView.setUserTrackingMode(MGLUserTrackingMode.Follow, animated: true)
}
func dismissLocationSelector(sender: UIBarButtonItem) {
self.dismissViewControllerAnimated(true, completion: nil)
}
func setLocationSelector(sender: UIBarButtonItem) {
self.dismissViewControllerAnimated(true, completion: {
if let del = self.delegate {
del.onSetCoordinatesComplete(true)
}
})
}
func mapView(mapView: MGLMapView, regionDidChangeAnimated animated: Bool) {
print("CHILD:sendCoordinates see \(self.mapView.centerCoordinate)")
self.userSelectedCoordinates = self.mapView.centerCoordinate
if (self.userSelectedCoordinates.longitude != 0.0 && self.userSelectedCoordinates.latitude != 0.0) {
self.navigationBarButtonSet.enabled = true
}
if let del = delegate {
del.sendCoordinates(self.userSelectedCoordinates)
}
}
}
| agpl-3.0 | 3a0267d9a2f62cf273ce8f6efd445c84 | 31.8 | 130 | 0.703887 | 5.691974 | false | false | false | false |
dc-uba/metrika_benchs_game | benchs/nbody/nbody.swift-2.swift | 1 | 3925 | /* The Computer Language Benchmarks Game
http://benchmarksgame.alioth.debian.org/
contributed by Isaac Gouy
*/
import CoreFoundation
struct Body {
var x, y, z, vx, vy, vz, mass : Double
mutating func advance(dt: Double) {
x += dt * vx
y += dt * vy
z += dt * vz
}
mutating func dec(vx: Double, _ vy: Double, _ vz: Double) {
self.vx -= vx
self.vy -= vy
self.vz -= vz
}
mutating func inc(vx: Double, _ vy: Double, _ vz: Double) {
self.vx += vx
self.vy += vy
self.vz += vz
}
}
let PI = 3.141592653589793
let SOLAR_MASS = 4 * PI * PI
let DAYS_PER_YEAR = 365.24
var bodies: [Body] = [
Body (
x: 0.0,
y: 0.0,
z: 0.0,
vx: 0.0,
vy: 0.0,
vz: 0.0,
mass: SOLAR_MASS
),
Body (
x: 4.84143144246472090e+00,
y: -1.16032004402742839e+00,
z: -1.03622044471123109e-01,
vx: 1.66007664274403694e-03 * DAYS_PER_YEAR,
vy: 7.69901118419740425e-03 * DAYS_PER_YEAR,
vz: -6.90460016972063023e-05 * DAYS_PER_YEAR,
mass: 9.54791938424326609e-04 * SOLAR_MASS
),
Body (
x: 8.34336671824457987e+00,
y: 4.12479856412430479e+00,
z: -4.03523417114321381e-01,
vx: -2.76742510726862411e-03 * DAYS_PER_YEAR,
vy: 4.99852801234917238e-03 * DAYS_PER_YEAR,
vz: 2.30417297573763929e-05 * DAYS_PER_YEAR,
mass: 2.85885980666130812e-04 * SOLAR_MASS
),
Body (
x: 1.28943695621391310e+01,
y: -1.51111514016986312e+01,
z: -2.23307578892655734e-01,
vx: 2.96460137564761618e-03 * DAYS_PER_YEAR,
vy: 2.37847173959480950e-03 * DAYS_PER_YEAR,
vz: -2.96589568540237556e-05 * DAYS_PER_YEAR,
mass: 4.36624404335156298e-05 * SOLAR_MASS
),
Body (
x: 1.53796971148509165e+01,
y: -2.59193146099879641e+01,
z: 1.79258772950371181e-01,
vx: 2.68067772490389322e-03 * DAYS_PER_YEAR,
vy: 1.62824170038242295e-03 * DAYS_PER_YEAR,
vz: -9.51592254519715870e-05 * DAYS_PER_YEAR,
mass: 5.15138902046611451e-05 * SOLAR_MASS
)
]
func offsetMomentum() {
var px = 0.0
var py = 0.0
var pz = 0.0
for body in bodies {
px += body.vx * body.mass
py += body.vy * body.mass
pz += body.vz * body.mass
}
bodies[0].inc(
-px / SOLAR_MASS,
-py / SOLAR_MASS,
-pz / SOLAR_MASS
)
}
func energy() -> Double {
var dx, dy, dz, distance: Double
var e = 0.0
for i in 0..<bodies.count {
e += 0.5 * bodies[i].mass *
( bodies[i].vx * bodies[i].vx
+ bodies[i].vy * bodies[i].vy
+ bodies[i].vz * bodies[i].vz )
for j in i+1..<bodies.count {
dx = bodies[i].x - bodies[j].x
dy = bodies[i].y - bodies[j].y
dz = bodies[i].z - bodies[j].z
distance = sqrt(dx*dx + dy*dy + dz*dz)
e -= (bodies[i].mass * bodies[j].mass) / distance
}
}
return e;
}
func advance(dt: Double) {
var dx, dy, dz, distance, mag: Double
for i in 0..<bodies.count {
for j in i+1..<bodies.count {
dx = bodies[i].x - bodies[j].x
dy = bodies[i].y - bodies[j].y
dz = bodies[i].z - bodies[j].z
distance = sqrt(dx*dx + dy*dy + dz*dz)
mag = dt / (distance * distance * distance)
bodies[i].dec(
dx * bodies[j].mass * mag,
dy * bodies[j].mass * mag,
dz * bodies[j].mass * mag
)
bodies[j].inc(
dx * bodies[i].mass * mag,
dy * bodies[i].mass * mag,
dz * bodies[i].mass * mag
)
}
}
for i in 0..<bodies.count {
bodies[i].advance(dt)
}
}
let n: Int = Int(Process.arguments[1])!
offsetMomentum()
print( energy() )
for _ in 1...n {
advance(0.01)
}
print( energy() )
| mit | c2c7dd3066b8d8cc358b023ca2261dd0 | 22.088235 | 62 | 0.527389 | 2.809592 | false | false | false | false |
AndyIbanez/fsduplicates | fsduplicates/main.swift | 1 | 16457 | //
// main.swift
// fsduplicates
//
// Created by Andy Ibanez on 6/22/16.
// Copyright ยฉ 2016 Andy Ibanez. All rights reserved.
//
import Foundation
// MARK: Tool info
/// Command line tool version
let VERSION = "0.0.2"
/// Path of the fpcalc tool.
let fpcalcPath: String
/// Command line arguments.
let arguments = Process.arguments
// Trigger help.
if arguments.contains("-h") {
usage()
exit(0)
}
// We are gonna check that fpalc does exist, or that it was passed as a valid path. If fpalc is not found, exit early.
// MARK: fpcalc validity checks
if let fpcalcIndex = arguments.index(of: "-fpcalc-path") {
// Ensuring that a path to fpcalc was passed.
let pathIndex = fpcalcIndex + 1
if pathIndex >= arguments.count {
print("Invalid fpcalc path")
usage()
exit(1)
}
fpcalcPath = arguments[pathIndex]
} else {
consoleOutput("-fpcalc-path has not been specified. Will try using the default path (/usr/local/bin/fpcalc)")
fpcalcPath = "/usr/local/bin/fpcalc"
}
// Ensuring that fpcalc does exist at the specified path and can be called.
let fpcalcExecutableExists = FileManager.default.isExecutableFile(atPath: fpcalcPath)
if !fpcalcExecutableExists {
print("\(fpcalcPath) does not exist. Exiting...")
exit(1)
}
// MARK: -f flag logic (if present).
if let fFlagIndex = arguments.index(of: "-f") {
// Acoustic id and file path touple.
typealias AcousticPair = (acoustID: String, filePath: String)
// This flag requires to extra arguments.
let minimumExpectedSize = fFlagIndex + 2
if minimumExpectedSize >= arguments.count {
print("Missing arguments for -f")
usage()
exit(1)
}
// Checking that the directories are valid.
let sourceDir = arguments[fFlagIndex + 1]
let outputDir = arguments[fFlagIndex + 2]
let (validSource, sourceMessage) = validDirectory(path: sourceDir, parameterName: "DIR_TO_SEARCH")
let (validOutput, outputMessage) = validDirectory(path: outputDir, parameterName: "DIR_TO_OUTPUT")
if !validSource {
if let msg = sourceMessage {
print("\(msg)")
} else {
print("Unknown error")
}
exit(1)
}
if !validOutput {
if let msg = outputMessage {
print("\(msg)")
} else {
print("Unknown error")
}
exit(1)
}
let outputSourceFile = outputDir + "/library"
let filesAndHashesFile = outputDir + "/fps_library"
let noFingerprintsFile = outputDir + "/no_fps_library"
let _ = shell(launchPath: "/usr/bin/touch", arguments: [outputSourceFile, filesAndHashesFile, noFingerprintsFile])
let loggedFiles = shell(launchPath: "/bin/cat", arguments: [outputSourceFile]).characters.split{$0 == "\n"}.map(String.init)
consoleOutput("Reading files in directory...")
var isDir: ObjCBool = false
let sourceFiles = shell(launchPath: "/usr/bin/find", arguments: [sourceDir, "-name", "*"]).characters.split{$0 == "\n"}.map(String.init).filter{ FileManager.default.fileExists(atPath: $0, isDirectory: &isDir) && !isDir }
consoleOutput("Validating songs against AcoustID and building the index. This can take a while...")
/// AcoustID's API requirements only allow us to make three calls every second. We will manually get three elements per iteration, and the stride will help us avoid repetition.
for var i in stride(from: 0, to: sourceFiles.count, by: 3) {
sleep(3)
for var j in i ... i + 2 {
if j >= sourceFiles.count {
break
}
if loggedFiles.index(of: sourceFiles[j]) != nil {
consoleOutput("\(sourceFiles[j]) is already logged")
} else {
AcoustID.shared.calculateFingerprint(atPath: sourceFiles[j], callback: { (fingerprint, error) in
if let error = error {
switch error {
case .InvalidFileFingerprint(let message): consoleOutput("Error on file \(sourceFiles[j]): \(message)")
case .ServerError(let message): consoleOutput("Server error for file \(sourceFiles[j]): \(message)")
case .NoFingerprintFound(let message):
let msg = "No AcoustID found for file: \(sourceFiles[j])"
consoleOutput(msg)
write(string: (sourceFiles[j] + "\n"), toFile: noFingerprintsFile)
}
} else {
if let fp = fingerprint {
consoleOutput("Obtained fingerprint for \(sourceFiles[j]): \(fp.acoustID)")
write(string: (sourceFiles[j] + "\n"), toFile: outputSourceFile)
write(string: "\(fp.acoustID):\(sourceFiles[j])\n", toFile: filesAndHashesFile)
} else {
consoleOutput("AcoustID returned successfully, but fingerprint is empty for file: \(sourceFiles[j])")
}
}
})
}
}
}
consoleOutput("The index has been created")
exit(0)
}
// MARK: -s flag (if present).
if let showFlagIndex = arguments.index(of: "-s") {
/// A touple for keeping track of AcoustID's and their repetitions.
typealias FingerprintRepetitions = (repeated: Int, acoustID: String)
// Ensuring the command is valid.
if showFlagIndex < arguments.count - 2 {
print("Missing parameter DIR_TO_OUTPUT")
usage()
exit(1)
}
var interactive = arguments.index(of: "-i") == nil ? false : true
let outputDir = arguments[showFlagIndex + 1]
let (validOutput, outputMessage) = validDirectory(path: outputDir, parameterName: "DIR_TO_OUTPUT")
if !validOutput {
if let msg = outputMessage {
print("\(msg)")
} else {
print("Unknown error")
}
exit(1)
}
let outputSourceFile = outputDir + "/library"
let filesAndHashesFile = outputDir + "/fps_library"
let noFingerprintsFile = outputDir + "/no_fps_library"
if !FileManager.default.fileExists(atPath: filesAndHashesFile) {
print("No duplicates found. Did you run the -f flag specifying \(outputDir) as the DIR_TO_OUTPUT?")
exit(1)
}
consoleOutput("Gathering duplicates...")
// Executing logic.
// cat fps_library | cut -d":" -f1 | sort | uniq -c | sort
let catTask = Task()
let cutTask = Task()
let sortTask = Task()
let uniqTask = Task()
let sortResultTask = Task()
catTask.launchPath = "/bin/cat"
catTask.arguments = [filesAndHashesFile]
cutTask.launchPath = "/usr/bin/cut"
cutTask.arguments = ["-d", ":", "-f1"]
sortTask.launchPath = "/usr/bin/sort"
uniqTask.launchPath = "/usr/bin/uniq"
uniqTask.arguments = ["-c"]
sortResultTask.launchPath = "/usr/bin/sort"
sortResultTask.arguments = ["-nr"]
let pipeBetweenCatAndCut = Pipe()
catTask.standardOutput = pipeBetweenCatAndCut
cutTask.standardInput = pipeBetweenCatAndCut
let pipeBetweenCutAndSort = Pipe()
cutTask.standardOutput = pipeBetweenCutAndSort
sortTask.standardInput = pipeBetweenCutAndSort
let pipeBetweenSortAndUniq = Pipe()
sortTask.standardOutput = pipeBetweenSortAndUniq
uniqTask.standardInput = pipeBetweenSortAndUniq
let pipeBetweenUniqAndFinalSort = Pipe()
uniqTask.standardOutput = pipeBetweenUniqAndFinalSort
sortResultTask.standardInput = pipeBetweenUniqAndFinalSort
let finalPipe = Pipe()
sortResultTask.standardOutput = finalPipe
let resultToRead = finalPipe.fileHandleForReading
catTask.launch()
cutTask.launch()
sortTask.launch()
uniqTask.launch()
sortResultTask.launch()
let resultData = resultToRead.readDataToEndOfFile()
let result = String(data: resultData, encoding: .utf8)
// The ultimate goal of this is to take all the raw output of the pipe and convert it into an array of FingerprintRepetitions.
let resultFps = result?.characters.split {$0 == "\n"}.map(String.init)
if let res = resultFps {
// string.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet())
let cleaned: [FingerprintRepetitions] = res.map { rawPair in
let noWs = rawPair.trimmingCharacters(in: NSCharacterSet.whitespaces)
let pair = noWs.characters.split{ $0 == " " }.map(String.init)
if let nInt = Int(pair[0]) {
let p: FingerprintRepetitions = (nInt, pair[1])
return p
}
return (0, "") // Not very likely to happen at all.
}
// We only care about the ones that are repeated. So those who appear only once are discarded.
let filtered = cleaned.filter{ $0.repeated > 1 }
// Read all the files from the library to do the the comparison.
var loggedFiles = shell(launchPath: "/bin/cat", arguments: [filesAndHashesFile]).characters.split{$0 == "\n"}.map(String.init)
/// Represents a single action.
enum SReadlineAction: String {
/// Move
case m
/// Symbolic link all
case s
/// Delete a file
case d
/// Skip to next duplicate sets.
case i
/// User option is invalid.
case invalid
/// Creates an action with a raw value.
init(rawOption: String) {
switch rawOption {
case "m": self = m
case "s": self = s
case "d": self = d
case "i": self = i
default: self = invalid
}
}
}
/// Represents a valid interactive action.
typealias SReadlineOption = (action: SReadlineAction, fileSelection: Int?, errorMessage: String?)
func parseOption(userInput: String) -> SReadlineOption {
let splat = userInput.characters.split{$0 == " "}.map(String.init)
var opt: SReadlineAction = .invalid
var file: Int? = nil
if splat.count > 0 {
opt = SReadlineAction(rawOption: splat[0])
if splat.count > 1 {
file = Int(splat[1])
}
if opt == .m || opt == .d {
if let f = file {
return (opt, f, nil)
} else {
return(.invalid, nil, "Format: OPT FILE#")
}
}
return(opt, nil, nil)
} else {
return (.invalid, 0, "Please insert an option")
}
}
func songName(_ fullPath: String) -> String {
let components = fullPath.characters.split{$0 == "/"}.map(String.init)
return components[components.count - 1]
}
func songPath(_ keyPair: String) -> String {
// keyPair = acoustid:file_path
let components = keyPair.characters.split{$0 == ":"}.map(String.init)
return components[components.count - 1]
}
for item in filtered {
let acoustid = item.acoustID
print("\n-----------------------------------")
print("Showing duplicates for \(acoustid):")
var counter = 0
let existing = loggedFiles.filter { line in
if line.contains(acoustid) {
let lineFileOnly = line.characters.split{$0 == ":"}.map(String.init)
counter += 1
print("\(counter). \(lineFileOnly[1])")
return true
}
return false
}
print("-----------------------------------")
if interactive {
var option: SReadlineOption = (.invalid, nil, nil)
repeat {
print("What do you want to do?:")
//print("(m)ove file to Library (d)elete a file")
print("(s)ymbolic link all to Library (i)gnore")
print("\nOPTION: ")
if let opt = readLine(strippingNewline: true) {
option = parseOption(userInput: opt)
if option.action == .invalid {
print("\n"+option.errorMessage!+"\n") // Everytime `action` is invalid, it will have an errorMessage. Safe to force-unwrap.
continue
}
let acoustidDirPath = outputDir + "/\(acoustid)"
if option.action == .s {
do {
consoleOutput("Attempting to create directory for symbolic links...")
try FileManager.default.createDirectory(atPath: acoustidDirPath, withIntermediateDirectories: false, attributes: nil)
consoleOutput("Directory created for symbolic links: \(acoustidDirPath)")
for file in existing {
let nameSong = songName(file)
let songLink = acoustidDirPath + "/\(nameSong)"
try FileManager.default.createSymbolicLink(atPath: songLink, withDestinationPath: songPath(file))
consoleOutput("Created symbolic link for \(songLink) \(file)")
}
} catch {
consoleOutput("Error creating symbolic links: \(error)")
}
}
if option.action == .m {
do {
if let file = option.fileSelection where (file - 1) < existing.count {
let songP = songPath(existing[file - 1])
let songN = songName(songP)
consoleOutput("Attempting to move file to directory...")
try FileManager.default.createDirectory(atPath: acoustidDirPath, withIntermediateDirectories: false , attributes: nil)
try FileManager.default.moveItem(atPath: songP, toPath: (acoustidDirPath + "/\(songN)"))
loggedFiles = loggedFiles.filter { return !$0.contains(songP) }
try FileManager.default.removeItem(atPath: filesAndHashesFile)
FileManager.default.createFile(atPath: filesAndHashesFile, contents: nil, attributes: nil)
for line in loggedFiles {
write(string: "\(line)\n", toFile: filesAndHashesFile)
}
consoleOutput("File moved successfully.")
continue
} else {
print("Invalid song number.")
continue
}
} catch {
consoleOutput("Error moving file: \(error)")
}
}
if option.action == .i {
break
}
} else {
continue
}
} while option.action == .invalid
}
}
//print("filtered \(filtered)")
} else {
consoleOutput("Error reading proceded results.")
exit(1)
}
}
| apache-2.0 | b01e33d8822d9ba83cb202287faa6a23 | 38.46283 | 224 | 0.522241 | 5.173216 | false | false | false | false |
accepton/accepton-apple | Pod/Classes/Shared/StringCases.swift | 1 | 1625 | import UIKit
extension String {
/**
Convert a string from snake case to pascal/capital camel case
This is useful for class names
```
"foo_bar".snakeToCamelCase => "FooBar"
```
- returns: A string in the ClassCase
*/
var snakeToClassCase: String {
var ss = NSMutableArray(array: (self as String).componentsSeparatedByString("_") as NSArray)
for (var i = 0; i < ss.count; ++i) {
ss[i] = ss[i].capitalizedString
}
return ss.componentsJoinedByString("") as String
}
/**
Convert a string from snake case to camel case
```
"foo_bar".snakeToCamelCase => "fooBar"
```
- returns: A string in the camelCase
*/
var snakeToCamelCase: String {
var ss = NSMutableArray(array: (self as String).componentsSeparatedByString("_") as NSArray)
for (var i = 1; i < ss.count; ++i) {
ss[i] = ss[i].capitalizedString
}
return ss.componentsJoinedByString("") as String
}
/**
Converts a string with spaces to a string to snake-case
```
"foo_bar".sentenceToSnakeCase => "FooBar"
```
- returns: A string in the ClassCase
*/
var sentenceToSnakeCase: String {
var ss = NSMutableArray(array: (self as String).componentsSeparatedByString(" ") as NSArray)
for (var i = 0; i < ss.count; ++i) {
ss[i] = ss[i].lowercaseString
}
return ss.componentsJoinedByString("_") as String
}
} | mit | 765901bc7d0ba732c14a54d90f10d846 | 24.809524 | 100 | 0.546462 | 4.723837 | false | false | false | false |
kenwilcox/WeeDate | WeeDate/SwipeView.swift | 1 | 3763 | //
// SwipeView.swift
// WeeDate
//
// Created by Kenneth Wilcox on 6/5/15.
// Copyright (c) 2015 Kenneth Wilcox. All rights reserved.
//
import Foundation
import UIKit
class SwipeView: UIView {
enum Direction {
case None
case Left
case Right
}
var innerView: UIView? {
didSet {
if let v = innerView {
insertSubview(v, belowSubview: overlay)
v.frame = CGRect(x: 0, y: 0, width: frame.width, height: frame.height)
}
}
}
private var originalPoint: CGPoint?
weak var delegate: SwipeViewDelegate?
let overlay: UIImageView = UIImageView()
var direction: Direction?
var yeahImage = UIImage(named: "yeah-stamp")
var nahImage = UIImage(named: "nah-stamp")
//MARK: - Initializers
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
initialize()
}
override init(frame: CGRect) {
super.init(frame: frame)
initialize()
}
init() {
super.init(frame: CGRectZero)
initialize()
}
//MARK: - Helper functions
private func initialize() {
self.backgroundColor = UIColor.clearColor()
self.addGestureRecognizer(UIPanGestureRecognizer(target: self, action: "dragged:"))
self.overlay.frame = CGRect(x: 0, y: 0, width: self.frame.width, height: self.frame.height)
self.addSubview(overlay)
}
// func rotateByDegrees(rotationAngle: CGFloat) {
// transform = CGAffineTransformMakeRotation(rotationAngle)
// }
func dragged(gestureRecognizer: UIPanGestureRecognizer) {
let distance = gestureRecognizer.translationInView(self)
println("Distance x:\(distance.x) y: \(distance.y)")
switch gestureRecognizer.state {
case UIGestureRecognizerState.Began:
originalPoint = center
case UIGestureRecognizerState.Changed:
// let rotationPercent = min(distance.x/(self.superview!.frame.width/2), 1)
let rotationPercent = distance.x/(self.superview!.frame.width/2)
let rotationAngle = (CGFloat(2*M_PI/16)*rotationPercent)
transform = CGAffineTransformMakeRotation(rotationAngle)
center = CGPointMake(originalPoint!.x + distance.x, originalPoint!.y + distance.y)
updateOverlay(distance.x)
case UIGestureRecognizerState.Ended:
if abs(distance.x) < frame.width/4 {
resetViewPositionAndTransformations()
} else {
swipe(distance.x > 0 ? .Right : .Left)
}
default:
println("Default trigged for GestureRecognizer: \(gestureRecognizer.state)")
break
}
}
func swipe(direction: Direction) {
if direction == .None {
return
}
var parentWidth = superview!.frame.size.width
if direction == .Left {
parentWidth *= -1
}
UIView.animateWithDuration(0.5, animations: {
self.center.x = self.frame.origin.x + parentWidth
self.updateOverlay(self.frame.origin.x + parentWidth)
}, completion: {
success in
if let delegate = self.delegate {
direction == .Right ? delegate.swipedRight(): delegate.swipedLeft()
}
})
}
private func updateOverlay(distance: CGFloat) {
var newDirection: Direction = distance < 0 ? .Left: .Right
if newDirection != direction {
direction = newDirection
overlay.image = direction == .Right ? yeahImage : nahImage
}
overlay.alpha = abs(distance) / (superview!.frame.width/2)
}
private func resetViewPositionAndTransformations() {
UIView.animateWithDuration(0.2, animations: { () -> Void in
self.center = self.originalPoint!
self.transform = CGAffineTransformMakeRotation(0)
self.overlay.alpha = 0
})
}
}
protocol SwipeViewDelegate: class {
func swipedLeft()
func swipedRight()
}
| mit | 68b41f3d46eebe8dfb64b1347e2c1808 | 26.268116 | 95 | 0.656923 | 4.247178 | false | false | false | false |
jpavley/Emoji-Tac-Toe2 | SimpleTagger.swift | 1 | 2767 | //
// SimpleTagger.swift
// Emoji Spy
//
// Created by John Pavley on 1/15/18.
// Copyright ยฉ 2018 Epic Loot. All rights reserved.
//
import Foundation
class SimpleTagger: SimpleSubstituter {
init(tagMap: [Int: String]) {
var subMap = [String: String]()
for (key, val) in tagMap {
subMap["\(key)"] = val
}
super.init(substituteMap: subMap)
}
override init?(sourceFileName: String = "CustomTags") {
super.init(sourceFileName: sourceFileName)
}
func getTags(for indexNumber: Int) -> [String]? {
let term = "\(indexNumber)"
return super.getSubstitutes(for: term)
}
/// Emoji groups and subgroups are not well named and/or are overbroad.
/// When creating tags from group and subgroup name hundreds of emoji
/// are inproperly tagged. Smileys are also tagged people and people are
/// are also tagged smileys. Plants are tagged animals. Foods are tagged
/// drinks and drinks are tagged food. Places and Travel are also
/// oddly tagged.
func tagAdjustment(emojiGlyphs: [EmojiGlyph]) -> [EmojiGlyph] {
var adjustedEmojiGlyphs = emojiGlyphs
// TODO: Integrate into CustomTags.txt (this is compact but will break with future emoji sets
adjustedEmojiGlyphs = remove(badTag: "person", start: 0, end: 106, emojiGlyphs: adjustedEmojiGlyphs)
adjustedEmojiGlyphs = remove(badTag: "smileys", start: 107, end: 1506, emojiGlyphs: adjustedEmojiGlyphs)
adjustedEmojiGlyphs = remove(badTag: "person", start: 1443, end: 1506, emojiGlyphs: adjustedEmojiGlyphs)
adjustedEmojiGlyphs = remove(badTag: "animal", start: 1598, end: 1629, emojiGlyphs: adjustedEmojiGlyphs)
adjustedEmojiGlyphs = remove(badTag: "drink", start: 1620, end: 1702, emojiGlyphs: adjustedEmojiGlyphs)
adjustedEmojiGlyphs = remove(badTag: "food", start: 1702, end: 1715, emojiGlyphs: adjustedEmojiGlyphs)
adjustedEmojiGlyphs = remove(badTag: "drink", start: 1716, end: 1720, emojiGlyphs: adjustedEmojiGlyphs)
adjustedEmojiGlyphs = remove(badTag: "food", start: 1721, end: 1722, emojiGlyphs: adjustedEmojiGlyphs)
adjustedEmojiGlyphs = remove(badTag: "place", start: 1786, end: 1928, emojiGlyphs: adjustedEmojiGlyphs)
return adjustedEmojiGlyphs
}
fileprivate func remove(badTag: String, start: Int, end: Int, emojiGlyphs: [EmojiGlyph]) -> [EmojiGlyph] {
var cleanedEmojiGlyphs = emojiGlyphs
let tagRange = Int(start)...Int(end)
for i in tagRange {
cleanedEmojiGlyphs[i].tags = cleanedEmojiGlyphs[i].tags.filter({$0 != badTag})
}
return cleanedEmojiGlyphs
}
}
| mit | 36ecfa637900e46e6007e4c543914c7c | 41.553846 | 112 | 0.661967 | 4.482982 | false | false | false | false |
toggl/superday | teferi/UI/Modules/Calendar/CalendarPresenter.swift | 1 | 1014 | import Foundation
class CalendarPresenter
{
private weak var viewController : CalendarViewController!
private let viewModelLocator : ViewModelLocator
private let dismissCallback : () -> ()
private init(viewModelLocator: ViewModelLocator, dismissCallBack: @escaping () -> ())
{
self.viewModelLocator = viewModelLocator
self.dismissCallback = dismissCallBack
}
static func create(with viewModelLocator: ViewModelLocator, dismissCallback: @escaping () -> ()) -> CalendarViewController
{
let presenter = CalendarPresenter(viewModelLocator: viewModelLocator, dismissCallBack: dismissCallback)
let viewController = StoryboardScene.Main.calendar.instantiate()
viewController.inject(presenter: presenter, viewModel: viewModelLocator.getCalendarViewModel())
presenter.viewController = viewController
return viewController
}
func dismiss()
{
dismissCallback()
}
}
| bsd-3-clause | 630671a6b70c67e200501618f608fbcf | 30.6875 | 126 | 0.690335 | 6.377358 | false | false | false | false |
moongift/NCMBiOSFaceook | NCMBiOS_Facebook/MasterViewController.swift | 1 | 8415 | //
// MasterViewController.swift
// NCMBiOS_Facebook
//
// Created by naokits on 7/4/15.
// Copyright (c) 2015 Naoki Tsutsui. All rights reserved.
//
import UIKit
class MasterViewController: UITableViewController {
/// TODOใๆ ผ็ดใใ้
ๅ
var objects = [Todo]()
override func awakeFromNib() {
super.awakeFromNib()
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
if let user = NCMBUser.currentUser() {
self.fetchAllTodos()
}
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
if let token = FBSDKAccessToken.currentAccessToken() {
println("ใใผใฏใณ๏ผ \(token)")
} else {
println("ใใผใฏใณใๅๅพใงใใพใใใงใใใ")
self.performSegueWithIdentifier("toLogin", sender: self)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// ------------------------------------------------------------------------
// MARK: - Segues
// ------------------------------------------------------------------------
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "goEditTodo" {
if let indexPath = self.tableView.indexPathForSelectedRow() {
let object = self.objects[indexPath.row]
if let dvc = segue.destinationViewController as? DetailViewController {
dvc.detailItem = object
dvc.updateButton.title = "ๆดๆฐ"
}
}
} else if segue.identifier == "goAddTodo" {
(segue.destinationViewController as! DetailViewController).updateButton.title = "่ฟฝๅ "
} else if segue.identifier == "toLogin" {
println("ใญใฐใขใฆใใใฆใญใฐใคใณ็ป้ขใซ้ท็งปใใพใ")
NCMBUser.logOut()
} else {
// ้ท็งปๅ
ใๅฎ็พฉใใใฆใใชใ
}
}
/// TODO็ป้ฒ๏ผ็ทจ้็ป้ขใใๆปใฃใฆใใๆใฎๅฆ็ใ่กใใพใใ
@IBAction func unwindFromTodoEdit(segue:UIStoryboardSegue) {
println("---- unwindFromTodoEdit: \(segue.identifier)")
let svc = segue.sourceViewController as! DetailViewController
if count(svc.todoTitle.text) < 3 {
return
}
if svc.detailItem == nil {
println("TODOใชใใธใงใฏใใๅญๅจใใชใใฎใงใๆฐ่ฆใจใฟใชใใพใใ")
println("\(svc.todoTitle.text)")
self.addTodoWithTitle(svc.todoTitle.text)
} else {
println("ๆดๆฐๅฆ็")
svc.detailItem?.title = svc.todoTitle.text
svc.detailItem?.saveInBackgroundWithBlock({ (error: NSError!) -> Void in
self.tableView.reloadData()
})
}
}
/// ใญใฐใคใณ็ป้ขใใๆปใฃใฆใใๆใฎๅฆ็ใ่กใใพใใ
@IBAction func unwindFromLogin(segue:UIStoryboardSegue) {
// ใญใฐใคใณใ็ตไบใใใๅผทๅถ็ใซTODOไธ่ฆงใๅๅพ
self.objects = [Todo]()
self.fetchAllTodos()
}
// ------------------------------------------------------------------------
// MARK: - Table View
// ------------------------------------------------------------------------
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return objects.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! UITableViewCell
let todo = objects[indexPath.row]
cell.textLabel!.text = todo.objectForKey("title") as? String
cell.textLabel!.text = todo.title
return cell
}
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
let todo = objects[indexPath.row]
let objectID = todo.objectId
let query = Todo.query()
query.getObjectInBackgroundWithId(objectID, block: { (object: NCMBObject!, fetchError: NSError?) -> Void in
if fetchError == nil {
// NCMBใใ้ๅๆใงๅฏพ่ฑกใชใใธใงใฏใใๅ้คใใพใ
// TODO: ๅ้คใฏๅๆๅฆ็ใซๅคๆดใใใๅ่ใใใ
object.deleteInBackgroundWithBlock({ (deleteError: NSError!) -> Void in
if (deleteError == nil) {
let deletedObject = self.objects.removeAtIndex(indexPath.row)
println("ๅ้คใใใชใใธใงใฏใใฎๆ
ๅ ฑ: \(deletedObject)")
// ใใผใฟใฝใผในใใๅ้ค
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else {
println("ๅ้คๅคฑๆ: \(deleteError)")
}
})
} else {
println("ใชใใธใงใฏใๅๅพๅคฑๆ: \(fetchError)")
}
})
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view.
}
}
// ------------------------------------------------------------------------
// MARK: Methods for Data Source
// ------------------------------------------------------------------------
/// ๅ
จใฆใฎTODOๆ
ๅ ฑใๅๅพใใใใญใใใฃใซๆ ผ็ดใใพใ
///
/// :param: None
/// :returns: None
func fetchAllTodos() {
// ใฏใจใชใ็ๆ
let query = Todo.query() as NCMBQuery
// ใฟใคใใซใซใใผใฟใๅซใพใใชใใใฎใฏ้คๅค
query.whereKeyExists("title")
// ็ป้ฒๆฅใฎ้้ ใงๅๅพ
query.orderByDescending("createDate")
// ๅๅพไปถๆฐใฎๆๅฎ
query.limit = 20
query.findObjectsInBackgroundWithBlock({(NSArray todos, NSError error) in
if (error == nil) {
println("็ป้ฒไปถๆฐ: \(todos.count)")
for todo in todos {
println("--- \(todo.objectId): \(todo.title)")
}
self.objects = todos as! [Todo] // NSArray -> Swift Array
self.tableView.reloadData()
} else {
println("Error: \(error)")
}
})
}
/// ๆฐ่ฆใซTODOใ่ฟฝๅ ใใพใ
///
/// :param: title TODOใฎใฟใคใใซ
/// :returns: None
func addTodoWithTitle(title: String) {
let todo = Todo.object() as! Todo
todo.title = title
todo.ACL = NCMBACL(user: NCMBUser.currentUser())
// ้ๅๆใงไฟๅญ
todo.saveInBackgroundWithBlock { (error: NSError!) -> Void in
if error == nil {
println("ๆฐ่ฆTODOใฎไฟๅญๆๅใ่กจ็คบใฎๆดๆฐใชใฉใ่กใใ")
self.insertNewTodoObject(todo)
} else {
println("ๆฐ่ฆTODOใฎไฟๅญใซๅคฑๆใใพใใ: \(error)")
}
}
}
/// TODOใDataSourceใซ่ฟฝๅ ใใฆใ่กจ็คบใๆดๆฐใใพใ
///
/// :param: todo TODOใชใใธใงใฏใ๏ผNCMBObject๏ผ
/// :returns: None
func insertNewTodoObject(todo: Todo!) {
self.objects.insert(todo, atIndex: 0)
let indexPath = NSIndexPath(forRow: 0, inSection: 0)
self.tableView.insertRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic)
self.tableView.reloadData()
}
}
| mit | 861033f1bcaf5be839134ca6b944f0b6 | 34.513889 | 157 | 0.531743 | 5.261317 | false | false | false | false |
jjochen/JJFloatingActionButton | Sources/JJCircleView.swift | 1 | 3733 | //
// JJCircleView.swift
//
// Copyright (c) 2017-Present Jochen Pfeiffer
//
// 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
/// A colored circle with an highlighted state
///
@objc @IBDesignable public class JJCircleView: UIView {
/// The color of the circle.
///
@objc @IBInspectable public dynamic var color: UIColor = Styles.defaultButtonColor {
didSet {
updateHighlightedColorFallback()
setNeedsDisplay()
}
}
/// The color of the circle when highlighted. Default is `nil`.
///
@objc @IBInspectable public dynamic var highlightedColor: UIColor? {
didSet {
setNeedsDisplay()
}
}
/// A Boolean value indicating whether the circle view draws a highlight.
/// Default is `false`.
///
@objc public var isHighlighted = false {
didSet {
setNeedsDisplay()
}
}
internal override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
/// Returns an object initialized from data in a given unarchiver.
///
/// - Parameter aDecoder: An unarchiver object.
///
/// - Returns: `self`, initialized using the data in decoder.
///
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
/// Draws the receiverโs image within the passed-in rectangle
/// Overrides `draw(rect: CGRect)` from `UIView`.
///
public override func draw(_: CGRect) {
drawCircle(inRect: bounds)
}
fileprivate var highlightedColorFallback = Styles.defaultHighlightedButtonColor
}
// MARK: - Private Methods
fileprivate extension JJCircleView {
func setup() {
backgroundColor = .clear
}
func drawCircle(inRect rect: CGRect) {
let context = UIGraphicsGetCurrentContext()!
context.saveGState()
let diameter = min(rect.width, rect.height)
var circleRect = CGRect()
circleRect.size.width = diameter
circleRect.size.height = diameter
circleRect.origin.x = (rect.width - diameter) / 2
circleRect.origin.y = (rect.height - diameter) / 2
let circlePath = UIBezierPath(ovalIn: circleRect)
currentColor.setFill()
circlePath.fill()
context.restoreGState()
}
var currentColor: UIColor {
if !isHighlighted {
return color
}
if let highlightedColor = highlightedColor {
return highlightedColor
}
return highlightedColorFallback
}
func updateHighlightedColorFallback() {
highlightedColorFallback = color.highlighted
}
}
| mit | b403ae341b9c5411d3eb4c7652ec34ad | 29.581967 | 88 | 0.658269 | 4.845455 | false | false | false | false |
volodg/iAsync.cache | Sources/Details/CacheDBInfoStorage.swift | 1 | 1032 | //
// CacheDBInfoStorage.swift
// iAsync_cache
//
// Created by Vladimir Gorbenko on 29.07.14.
// Copyright ยฉ 2014 EmbeddedSources. All rights reserved.
//
import Foundation
import iAsync_utils
final public class CacheDBInfoStorage {
internal let info: [String:CacheDBInfo]
public func infoBy(dbName: String) -> CacheDBInfo? {
return info[dbName]
}
init(plistInfo: NSDictionary) {
var info: [String:CacheDBInfo] = [:]
for (key, value) in plistInfo {
if let keyStr = key as? String {
if let plistInfo = value as? NSDictionary {
info[keyStr] = CacheDBInfo(plistInfo: plistInfo, dbPropertyName: keyStr)
} else {
iAsync_utils_logger.logError("plistInfo: \(plistInfo) not a NSDictionary", context: #function)
}
} else {
iAsync_utils_logger.logError("key: \(key) not a string", context: #function)
}
}
self.info = info
}
}
| mit | 0ba5fbdceb3b44bce335a301d8fbf9ed | 24.775 | 114 | 0.582929 | 4.22541 | false | false | false | false |
gaoleegin/SwiftLianxi | ReactiveSecondLianXi/Pods/ReactiveCocoa/ReactiveCocoa/Swift/Scheduler.swift | 33 | 10345 | //
// Scheduler.swift
// ReactiveCocoa
//
// Created by Justin Spahr-Summers on 2014-06-02.
// Copyright (c) 2014 GitHub. All rights reserved.
//
/// Represents a serial queue of work items.
public protocol SchedulerType {
/// Enqueues an action on the scheduler.
///
/// When the work is executed depends on the scheduler in use.
///
/// Optionally returns a disposable that can be used to cancel the work
/// before it begins.
func schedule(action: () -> ()) -> Disposable?
}
/// A particular kind of scheduler that supports enqueuing actions at future
/// dates.
public protocol DateSchedulerType: SchedulerType {
/// The current date, as determined by this scheduler.
///
/// This can be implemented to deterministic return a known date (e.g., for
/// testing purposes).
var currentDate: NSDate { get }
/// Schedules an action for execution at or after the given date.
///
/// Optionally returns a disposable that can be used to cancel the work
/// before it begins.
func scheduleAfter(date: NSDate, action: () -> ()) -> Disposable?
/// Schedules a recurring action at the given interval, beginning at the
/// given start time.
///
/// Optionally returns a disposable that can be used to cancel the work
/// before it begins.
func scheduleAfter(date: NSDate, repeatingEvery: NSTimeInterval, withLeeway: NSTimeInterval, action: () -> ()) -> Disposable?
}
/// A scheduler that performs all work synchronously.
public final class ImmediateScheduler: SchedulerType {
public init() {}
public func schedule(action: () -> ()) -> Disposable? {
action()
return nil
}
}
/// A scheduler that performs all work on the main thread, as soon as possible.
///
/// If the caller is already running on the main thread when an action is
/// scheduled, it may be run synchronously. However, ordering between actions
/// will always be preserved.
public final class UIScheduler: SchedulerType {
private var queueLength: Int32 = 0
public init() {}
public func schedule(action: () -> ()) -> Disposable? {
let disposable = SimpleDisposable()
let actionAndDecrement: () -> () = {
if !disposable.disposed {
action()
}
withUnsafeMutablePointer(&self.queueLength, OSAtomicDecrement32)
}
let queued = withUnsafeMutablePointer(&queueLength, OSAtomicIncrement32)
// If we're already running on the main thread, and there isn't work
// already enqueued, we can skip scheduling and just execute directly.
if NSThread.isMainThread() && queued == 1 {
actionAndDecrement()
} else {
dispatch_async(dispatch_get_main_queue(), actionAndDecrement)
}
return disposable
}
}
/// A scheduler backed by a serial GCD queue.
public final class QueueScheduler: DateSchedulerType {
internal let queue: dispatch_queue_t
/// A singleton QueueScheduler that always targets the main thread's GCD
/// queue.
///
/// Unlike UIScheduler, this scheduler supports scheduling for a future
/// date, and will always schedule asynchronously (even if already running
/// on the main thread).
public static let mainQueueScheduler = QueueScheduler(queue: dispatch_get_main_queue(), name: "org.reactivecocoa.ReactiveCocoa.QueueScheduler.mainQueueScheduler")
public var currentDate: NSDate {
return NSDate()
}
/// Initializes a scheduler that will target the given queue with its work.
///
/// Even if the queue is concurrent, all work items enqueued with the
/// QueueScheduler will be serial with respect to each other.
public init(queue: dispatch_queue_t, name: String = "org.reactivecocoa.ReactiveCocoa.QueueScheduler") {
self.queue = dispatch_queue_create(name, DISPATCH_QUEUE_SERIAL)
dispatch_set_target_queue(self.queue, queue)
}
/// Initializes a scheduler that will target the global queue with the given
/// priority.
public convenience init(priority: CLong = DISPATCH_QUEUE_PRIORITY_DEFAULT, name: String = "org.reactivecocoa.ReactiveCocoa.QueueScheduler") {
self.init(queue: dispatch_get_global_queue(priority, 0), name: name)
}
public func schedule(action: () -> ()) -> Disposable? {
let d = SimpleDisposable()
dispatch_async(queue) {
if !d.disposed {
action()
}
}
return d
}
private func wallTimeWithDate(date: NSDate) -> dispatch_time_t {
var seconds = 0.0
let frac = modf(date.timeIntervalSince1970, &seconds)
let nsec: Double = frac * Double(NSEC_PER_SEC)
var walltime = timespec(tv_sec: CLong(seconds), tv_nsec: CLong(nsec))
return dispatch_walltime(&walltime, 0)
}
public func scheduleAfter(date: NSDate, action: () -> ()) -> Disposable? {
let d = SimpleDisposable()
dispatch_after(wallTimeWithDate(date), queue) {
if !d.disposed {
action()
}
}
return d
}
/// Schedules a recurring action at the given interval, beginning at the
/// given start time, and with a reasonable default leeway.
///
/// Optionally returns a disposable that can be used to cancel the work
/// before it begins.
public func scheduleAfter(date: NSDate, repeatingEvery: NSTimeInterval, action: () -> ()) -> Disposable? {
// Apple's "Power Efficiency Guide for Mac Apps" recommends a leeway of
// at least 10% of the timer interval.
return scheduleAfter(date, repeatingEvery: repeatingEvery, withLeeway: repeatingEvery * 0.1, action: action)
}
public func scheduleAfter(date: NSDate, repeatingEvery: NSTimeInterval, withLeeway leeway: NSTimeInterval, action: () -> ()) -> Disposable? {
precondition(repeatingEvery >= 0)
precondition(leeway >= 0)
let nsecInterval = repeatingEvery * Double(NSEC_PER_SEC)
let nsecLeeway = leeway * Double(NSEC_PER_SEC)
let timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue)
dispatch_source_set_timer(timer, wallTimeWithDate(date), UInt64(nsecInterval), UInt64(nsecLeeway))
dispatch_source_set_event_handler(timer, action)
dispatch_resume(timer)
return ActionDisposable {
dispatch_source_cancel(timer)
}
}
}
/// A scheduler that implements virtualized time, for use in testing.
public final class TestScheduler: DateSchedulerType {
private final class ScheduledAction {
let date: NSDate
let action: () -> ()
init(date: NSDate, action: () -> ()) {
self.date = date
self.action = action
}
func less(rhs: ScheduledAction) -> Bool {
return date.compare(rhs.date) == .OrderedAscending
}
}
private let lock = NSRecursiveLock()
private var _currentDate: NSDate
/// The virtual date that the scheduler is currently at.
public var currentDate: NSDate {
let d: NSDate
lock.lock()
d = _currentDate
lock.unlock()
return d
}
private var scheduledActions: [ScheduledAction] = []
/// Initializes a TestScheduler with the given start date.
public init(startDate: NSDate = NSDate(timeIntervalSinceReferenceDate: 0)) {
lock.name = "org.reactivecocoa.ReactiveCocoa.TestScheduler"
_currentDate = startDate
}
private func schedule(action: ScheduledAction) -> Disposable {
lock.lock()
scheduledActions.append(action)
scheduledActions.sortInPlace { $0.less($1) }
lock.unlock()
return ActionDisposable {
self.lock.lock()
self.scheduledActions = self.scheduledActions.filter { $0 !== action }
self.lock.unlock()
}
}
public func schedule(action: () -> ()) -> Disposable? {
return schedule(ScheduledAction(date: currentDate, action: action))
}
/// Schedules an action for execution at or after the given interval
/// (counted from `currentDate`).
///
/// Optionally returns a disposable that can be used to cancel the work
/// before it begins.
public func scheduleAfter(interval: NSTimeInterval, action: () -> ()) -> Disposable? {
return scheduleAfter(currentDate.dateByAddingTimeInterval(interval), action: action)
}
public func scheduleAfter(date: NSDate, action: () -> ()) -> Disposable? {
return schedule(ScheduledAction(date: date, action: action))
}
private func scheduleAfter(date: NSDate, repeatingEvery: NSTimeInterval, disposable: SerialDisposable, action: () -> ()) {
precondition(repeatingEvery >= 0)
disposable.innerDisposable = scheduleAfter(date) { [unowned self] in
action()
self.scheduleAfter(date.dateByAddingTimeInterval(repeatingEvery), repeatingEvery: repeatingEvery, disposable: disposable, action: action)
}
}
/// Schedules a recurring action at the given interval, beginning at the
/// given interval (counted from `currentDate`).
///
/// Optionally returns a disposable that can be used to cancel the work
/// before it begins.
public func scheduleAfter(interval: NSTimeInterval, repeatingEvery: NSTimeInterval, withLeeway leeway: NSTimeInterval = 0, action: () -> ()) -> Disposable? {
return scheduleAfter(currentDate.dateByAddingTimeInterval(interval), repeatingEvery: repeatingEvery, withLeeway: leeway, action: action)
}
public func scheduleAfter(date: NSDate, repeatingEvery: NSTimeInterval, withLeeway: NSTimeInterval = 0, action: () -> ()) -> Disposable? {
let disposable = SerialDisposable()
scheduleAfter(date, repeatingEvery: repeatingEvery, disposable: disposable, action: action)
return disposable
}
/// Advances the virtualized clock by an extremely tiny interval, dequeuing
/// and executing any actions along the way.
///
/// This is intended to be used as a way to execute actions that have been
/// scheduled to run as soon as possible.
public func advance() {
advanceByInterval(DBL_EPSILON)
}
/// Advances the virtualized clock by the given interval, dequeuing and
/// executing any actions along the way.
public func advanceByInterval(interval: NSTimeInterval) {
lock.lock()
advanceToDate(currentDate.dateByAddingTimeInterval(interval))
lock.unlock()
}
/// Advances the virtualized clock to the given future date, dequeuing and
/// executing any actions up until that point.
public func advanceToDate(newDate: NSDate) {
lock.lock()
assert(currentDate.compare(newDate) != .OrderedDescending)
_currentDate = newDate
while scheduledActions.count > 0 {
if newDate.compare(scheduledActions[0].date) == .OrderedAscending {
break
}
let scheduledAction = scheduledActions[0]
scheduledActions.removeAtIndex(0)
scheduledAction.action()
}
lock.unlock()
}
/// Dequeues and executes all scheduled actions, leaving the scheduler's
/// date at `NSDate.distantFuture()`.
public func run() {
advanceToDate(NSDate.distantFuture())
}
}
| apache-2.0 | 7cc98d817aaf880fb089dfcae73faab8 | 31.737342 | 163 | 0.723441 | 4.064833 | false | false | false | false |
vlfm/swapi-swift | Source/Parsers/StarshipParser.swift | 1 | 1850 | import Foundation
final class StarshipParser {
static func make() -> Parser<Starship> {
return { json in
return try Extract.from(jsonDictionary: json) { input in
let identity = try input.identity()
let mglt = try input.string(at: "MGLT")
let cargoCapacity = try input.string(at: "cargo_capacity")
let consumables = try input.string(at: "consumables")
let costInCredits = try input.string(at: "cost_in_credits")
let crew = try input.string(at: "crew")
let hyperdriveRating = try input.string(at: "hyperdrive_rating")
let length = try input.string(at: "length")
let manufacturers = try input.string(at: "manufacturer", separator: ",")
let maxAtmospheringSpeed = try input.string(at: "max_atmosphering_speed")
let model = try input.string(at: "model")
let name = try input.string(at: "name")
let passengers = try input.string(at: "passengers")
let films = try input.urls(at: "films")
let pilots = try input.urls(at: "pilots")
let `class` = try input.string(at: "starship_class")
return Starship(identity: identity, name: name, model: model, class: `class`,
manufacturers: manufacturers, costInCredits: costInCredits,
length: length, crew: crew, passengers: passengers,
maxAtmospheringSpeed: maxAtmospheringSpeed, cargoCapacity: cargoCapacity,
consumables: consumables, films: films, pilots: pilots,
hyperdriveRating: hyperdriveRating, mglt: mglt)
}
}
}
}
| apache-2.0 | cf3235f6d117f51b8d4f1d25c48f4e8c | 55.060606 | 105 | 0.550811 | 4.567901 | false | false | false | false |
ddimitrov90/EverliveSDK | Tests/Pods/EverliveSDK/EverliveSDK/UploadFileHandler.swift | 2 | 1349 | //
// CreateSingleHandler.swift
// EverliveSwift
//
// Created by Dimitar Dimitrov on 2/17/16.
// Copyright ยฉ 2016 ddimitrov. All rights reserved.
//
import Foundation
import Alamofire
import EVReflection
import SwiftyJSON
public class UploadFileHandler : BaseHandler{
var item: File
public init(newFile: File, connection: EverliveConnection, typeName: String){
self.item = newFile
super.init(connection: connection, typeName: typeName)
}
required public init(connection: EverliveConnection, typeName: String) {
fatalError("init(connection:typeName:) has not been implemented")
}
public func execute(completionHandler: (Bool, EverliveError?) -> Void){
self.connection.uploadFile(self.item) { (response: Result<MultipleResult<UploadFileResult>, NSError>) -> Void in
if let result = response.value {
var success = false
let errorObject = result.getErrorObject()
if errorObject == nil {
self.item.Id = result.data[0].Id
self.item.CreatedAt = result.data[0].CreatedAt
self.item.Uri = result.data[0].Uri
success = true
}
completionHandler(success, result.getErrorObject())
}
}
}
} | mit | 57ebc45537777fcff6eef26cc5fabe19 | 31.902439 | 120 | 0.616469 | 4.729825 | false | false | false | false |
mkaply/firefox-ios | Extensions/Today/TodayUX.swift | 4 | 1134 | /* 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 UIKit
struct TodayUX {
static let backgroundHightlightColor = UIColor(white: 216.0/255.0, alpha: 44.0/255.0)
static let linkTextSize: CGFloat = 9.0
static let labelTextSize: CGFloat = 12.0
static let imageButtonTextSize: CGFloat = 13.0
static let copyLinkImageWidth: CGFloat = 20
static let margin: CGFloat = 8
static let buttonsHorizontalMarginPercentage: CGFloat = 0.1
static let buttonStackViewSpacing: CGFloat = 20.0
static var labelColor: UIColor {
if #available(iOS 13, *) {
return UIColor(named: "widgetLabelColors") ?? UIColor(rgb: 0x242327)
} else {
return UIColor(rgb: 0x242327)
}
}
static var subtitleLabelColor: UIColor {
if #available(iOS 13, *) {
return UIColor(named: "subtitleLableColor") ?? UIColor(rgb: 0x38383C)
} else {
return UIColor(rgb: 0x38383C)
}
}
}
| mpl-2.0 | d8b31bfd7cb9796a26d26ba83d5bee97 | 36.8 | 89 | 0.653439 | 3.910345 | false | false | false | false |
wftllc/hahastream | Haha Stream/Features/Loading/LoadingViewController.swift | 1 | 1511 | import UIKit
import AVKit
class LoadingViewController: HahaViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func playURL(_ url: URL) {
print("playURL");
let parentVC = self.presentingViewController;
self.dismiss(animated: false) {
// Create an AVPlayer, passing it the HTTP Live Streaming URL.
let player = AVPlayer(url: url)
// Create a new AVPlayerViewController and pass it a reference to the player.
let controller = PlayerViewController()
controller.player = player
// Modally present the player and call the player's play() method when complete.
parentVC?.present(controller, animated: true) {
player.play()
}
}
}
override func onStreamChoiceCanceled(){
self.dismiss(animated: true, completion: nil);
}
override func showLoading(animated: Bool) {
//do nothing!
}
override func hideLoading(animated: Bool, completion: (() -> Void)?) {
completion?()
//do nothing!
}
override func showAlert(title: String, message: String) {
let parentVC = self.presentingViewController;
self.dismiss(animated: true) {
parentVC?.showAlert(title: title, message: message)
}
}
override func showLoginAlert(message: String) {
let parentVC = self.presentingViewController;
self.dismiss(animated: true) {
parentVC?.showLoginAlert(message: message)
}
}
}
| mit | 42e975838d65083138d05132c468588f | 22.609375 | 83 | 0.708802 | 3.934896 | false | false | false | false |
parkera/swift | stdlib/public/Concurrency/MainActor.swift | 2 | 1856 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import Swift
/// A singleton actor whose executor is equivalent to the main
/// dispatch queue.
@available(SwiftStdlib 5.5, *)
@globalActor public final actor MainActor: GlobalActor {
public static let shared = MainActor()
@inlinable
public nonisolated var unownedExecutor: UnownedSerialExecutor {
#if compiler(>=5.5) && $BuiltinBuildMainExecutor
return UnownedSerialExecutor(Builtin.buildMainActorExecutorRef())
#else
fatalError("Swift compiler is incompatible with this SDK version")
#endif
}
@inlinable
public static var sharedUnownedExecutor: UnownedSerialExecutor {
#if compiler(>=5.5) && $BuiltinBuildMainExecutor
return UnownedSerialExecutor(Builtin.buildMainActorExecutorRef())
#else
fatalError("Swift compiler is incompatible with this SDK version")
#endif
}
@inlinable
public nonisolated func enqueue(_ job: UnownedJob) {
_enqueueOnMain(job)
}
}
@available(SwiftStdlib 5.5, *)
extension MainActor {
/// Execute the given body closure on the main actor.
public static func run<T>(
resultType: T.Type = T.self,
body: @MainActor @Sendable () throws -> T
) async rethrows -> T {
@MainActor func runOnMain(body: @MainActor @Sendable () throws -> T) async rethrows -> T {
return try body()
}
return try await runOnMain(body: body)
}
}
| apache-2.0 | 6a05e7674c547af73a2daec50b593d89 | 31 | 94 | 0.656789 | 4.734694 | false | false | false | false |
robertherdzik/RHPlaygroundFreestyle | InstaGradient/InstaGradient.playground/Contents.swift | 1 | 1641 | import UIKit
import PlaygroundSupport
let viewFrame = CGRect(x: 0, y: 0, width: 300, height: 300)
let view = UIView(frame: viewFrame)
view.backgroundColor = .white
let animation = CABasicAnimation(keyPath: "position.x")
animation.duration = 1
animation.fromValue = -view.bounds.width
animation.toValue = 2*view.bounds.width
animation.isRemovedOnCompletion = false
animation.repeatCount = Float.infinity
animation.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeIn)
func addGradient(view: UIView) -> CAGradientLayer {
let gradient = CAGradientLayer()
gradient.colors = [
UIColor.lightGray.cgColor,
UIColor.white.cgColor,
UIColor.white.cgColor,
UIColor.lightGray.cgColor
]
gradient.frame = CGRect(x: 0,
y: 0,
width: 2*view.bounds.width,
height: 2*view.bounds.height)
gradient.startPoint = CGPoint(x:0.2, y:0.3)
gradient.endPoint = CGPoint(x:1, y:0.9)
gradient.opacity = 0.4
gradient.locations = [0, 0.2, 0.22, 0.4]
gradient.add(animation, forKey: "gradient")
return gradient
}
var label = UIView(frame: CGRect(x: 0, y: 0, width: 270, height: 70))
label.backgroundColor = UIColor.lightGray
var image = UIView(frame: CGRect(x: 0, y: 80, width: 80, height: 70))
image.backgroundColor = UIColor.lightGray
[label, image].forEach {
view.addSubview($0)
}
[label, image].forEach {
let gradient = addGradient(view: label)
$0.layer.addSublayer(gradient)
$0.layer.masksToBounds = true
}
PlaygroundPage.current.liveView = view
| mit | b4886a0f70c4746b5bf8aea90210d470 | 27.789474 | 88 | 0.670932 | 3.843091 | false | false | false | false |
wssj/ShowMeThatStatus | ShowMeThatStatus/StatusIndicator.swift | 1 | 14597 | //
// StatusIndicator.swift
//
// Originally created by Abdul Karim
// Copyright ยฉ 2015 dhlabs. All rights reserved.
//
// Minor modifications to better suit ShowMeThatStatus
import UIKit
open class StatusIndicator: UIView, CAAnimationDelegate {
@IBInspectable open var lineWidth: CGFloat = SMTSConstants.smtsStyle.lineWidth {
didSet {
progressLayer.lineWidth = lineWidth
shapeLayer.lineWidth = lineWidth
setProgressLayerPath()
}
}
@IBInspectable open var strokeColor: UIColor = SMTSConstants.smtsStyle.progressColor {
didSet{
progressLayer.strokeColor = strokeColor.cgColor
shapeLayer.strokeColor = strokeColor.cgColor
progressLabel.textColor = strokeColor
}
}
@IBInspectable open var font: UIFont = SMTSConstants.smtsStyle.progressFont {
didSet{
progressLabel.font = font
}
}
open var hidesWhenCompleted: Bool = false
open var hideAfterTime: TimeInterval = SMTSConstants.hidesWhenCompletedDelay
var status: SMTSProgressStatus = .unknown
fileprivate var _progress: Float = 0.0
open var progress: Float {
get {
return _progress
}
set(newProgress) {
//Avoid calling excessively
if (newProgress - _progress >= 0.01 || newProgress >= 100.0) {
_progress = min(max(0, newProgress), 1)
progressLayer.strokeEnd = CGFloat(_progress)
if status == .loading {
progressLayer.removeAllAnimations()
} else if(status == .failure || status == .success) {
shapeLayer.strokeStart = 0
shapeLayer.strokeEnd = 0
shapeLayer.removeAllAnimations()
}
status = .progress
progressLabel.isHidden = false
let progressInt: Int = Int(_progress * 100)
progressLabel.text = "\(progressInt)"
}
}
}
fileprivate let progressLayer: CAShapeLayer! = CAShapeLayer()
fileprivate let shapeLayer: CAShapeLayer! = CAShapeLayer()
fileprivate let progressLabel: UILabel! = UILabel()
fileprivate var completionBlock: StatusIndicatorBlock?
public override init(frame: CGRect) {
super.init(frame: frame)
initialize()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
initialize()
}
deinit{
NotificationCenter.default.removeObserver(self)
}
override open func layoutSubviews() {
super.layoutSubviews()
let width = self.bounds.width
let height = self.bounds.height
let square = min(width, height)
let bounds = CGRect(x: 0, y: 0, width: square, height: square)
progressLayer.frame = CGRect(x: 0, y: 0, width: width, height: height)
setProgressLayerPath()
shapeLayer.bounds = bounds
shapeLayer.position = CGPoint(x: self.bounds.midX, y: self.bounds.midY)
let labelSquare = sqrt(2) / 2.0 * square
progressLabel.bounds = CGRect(x: 0, y: 0, width: labelSquare, height: labelSquare)
progressLabel.center = CGPoint(x: self.bounds.midX, y: self.bounds.midY)
}
//MARK: - Public
open func startLoading() {
if status == .loading {
return
}
status = .loading
progressLabel.isHidden = true
progressLabel.text = "0"
_progress = 0
shapeLayer.strokeStart = 0
shapeLayer.strokeEnd = 0
shapeLayer.removeAllAnimations()
self.isHidden = false
progressLayer.strokeEnd = 0.0
progressLayer.removeAllAnimations()
let animation = CABasicAnimation(keyPath: "transform.rotation")
animation.duration = 4.0
animation.fromValue = 0.0
animation.toValue = 2 * M_PI
animation.repeatCount = Float.infinity
progressLayer.add(animation, forKey: SMTSConstants.ringRotationAnimationKey)
let totalDuration = 1.0
let firstDuration = 2.0 * totalDuration / 3.0
let secondDuration = totalDuration / 3.0
let headAnimation = CABasicAnimation(keyPath: "strokeStart")
headAnimation.duration = firstDuration
headAnimation.fromValue = 0.0
headAnimation.toValue = 0.25
let tailAnimation = CABasicAnimation(keyPath: "strokeEnd")
tailAnimation.duration = firstDuration
tailAnimation.fromValue = 0.0
tailAnimation.toValue = 1.0
let endHeadAnimation = CABasicAnimation(keyPath: "strokeStart")
endHeadAnimation.beginTime = firstDuration
endHeadAnimation.duration = secondDuration
endHeadAnimation.fromValue = 0.25
endHeadAnimation.toValue = 1.0
let endTailAnimation = CABasicAnimation(keyPath: "strokeEnd")
endTailAnimation.beginTime = firstDuration
endTailAnimation.duration = secondDuration
endTailAnimation.fromValue = 1.0
endTailAnimation.toValue = 1.0
let animations = CAAnimationGroup()
animations.duration = firstDuration + secondDuration
animations.repeatCount = Float.infinity
animations.animations = [headAnimation, tailAnimation, endHeadAnimation, endTailAnimation]
progressLayer.add(animations, forKey: SMTSConstants.ringRotationAnimationKey)
}
open func completeLoading(_ success: Bool, completion: StatusIndicatorBlock? = nil) {
if status == .success || status == .failure {
return
}
completionBlock = completion
progressLabel.isHidden = true
progressLayer.strokeEnd = 1.0
progressLayer.removeAllAnimations()
if success {
setStrokeSuccessShapePath()
} else {
setStrokeFailureShapePath()
}
var strokeStart :CGFloat = 0.25
var strokeEnd :CGFloat = 0.8
var phase1Duration = 0.7 * SMTSConstants.completionAnimationDuration
var phase2Duration = 0.3 * SMTSConstants.completionAnimationDuration
var phase3Duration = 0.0
if !success {
let square = min(self.bounds.width, self.bounds.height)
let point = errorJoinPoint()
let increase = 1.0/3 * square - point.x
let sum = 2.0/3 * square
strokeStart = increase / (sum + increase)
strokeEnd = (increase + sum/2) / (sum + increase)
phase1Duration = 0.5 * SMTSConstants.completionAnimationDuration
phase2Duration = 0.2 * SMTSConstants.completionAnimationDuration
phase3Duration = 0.3 * SMTSConstants.completionAnimationDuration
}
shapeLayer.strokeEnd = 1.0
shapeLayer.strokeStart = strokeStart
let timeFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
let headStartAnimation = CABasicAnimation(keyPath: "strokeStart")
headStartAnimation.fromValue = 0.0
headStartAnimation.toValue = 0.0
headStartAnimation.duration = phase1Duration
headStartAnimation.timingFunction = timeFunction
let headEndAnimation = CABasicAnimation(keyPath: "strokeEnd")
headEndAnimation.fromValue = 0.0
headEndAnimation.toValue = strokeEnd
headEndAnimation.duration = phase1Duration
headEndAnimation.timingFunction = timeFunction
let tailStartAnimation = CABasicAnimation(keyPath: "strokeStart")
tailStartAnimation.fromValue = 0.0
tailStartAnimation.toValue = strokeStart
tailStartAnimation.beginTime = phase1Duration
tailStartAnimation.duration = phase2Duration
tailStartAnimation.timingFunction = timeFunction
let tailEndAnimation = CABasicAnimation(keyPath: "strokeEnd")
tailEndAnimation.fromValue = strokeEnd
tailEndAnimation.toValue = success ? 1.0 : strokeEnd
tailEndAnimation.beginTime = phase1Duration
tailEndAnimation.duration = phase2Duration
tailEndAnimation.timingFunction = timeFunction
let extraAnimation = CABasicAnimation(keyPath: "strokeEnd")
extraAnimation.fromValue = strokeEnd
extraAnimation.toValue = 1.0
extraAnimation.beginTime = phase1Duration + phase2Duration
extraAnimation.duration = phase3Duration
extraAnimation.timingFunction = timeFunction
let groupAnimation = CAAnimationGroup()
groupAnimation.animations = [headEndAnimation, headStartAnimation, tailStartAnimation, tailEndAnimation]
if !success {
groupAnimation.animations?.append(extraAnimation)
}
groupAnimation.duration = phase1Duration + phase2Duration + phase3Duration
groupAnimation.delegate = self
shapeLayer.add(groupAnimation, forKey: nil)
}
//MARK: CAAnimationDelegate
open func animationDidStop(_ anim: CAAnimation, finished flag: Bool) {
if hidesWhenCompleted {
Timer.scheduledTimer(timeInterval: SMTSConstants.hidesWhenCompletedDelay,
target: self,
selector: #selector(StatusIndicator.hiddenLoadingView),
userInfo: nil,
repeats: false)
} else {
status = .success
if completionBlock != nil {
completionBlock!()
}
}
}
//MARK: - Private
fileprivate func initialize() {
//progressLabel
progressLabel.font = font
progressLabel.textColor = strokeColor
progressLabel.textAlignment = .center
progressLabel.adjustsFontSizeToFitWidth = true
progressLabel.isHidden = true
self.addSubview(progressLabel)
//progressLayer
progressLayer.strokeColor = strokeColor.cgColor
progressLayer.fillColor = nil
progressLayer.lineWidth = lineWidth
self.layer.addSublayer(progressLayer)
//shapeLayer
shapeLayer.strokeColor = strokeColor.cgColor
shapeLayer.fillColor = nil
shapeLayer.lineWidth = lineWidth
shapeLayer.lineCap = kCALineCapRound
shapeLayer.lineJoin = kCALineJoinRound
shapeLayer.strokeStart = 0.0
shapeLayer.strokeEnd = 0.0
self.layer.addSublayer(shapeLayer)
NotificationCenter.default
.addObserver(self,
selector:#selector(StatusIndicator.resetAnimations),
name: NSNotification.Name.UIApplicationDidBecomeActive,
object: nil)
}
fileprivate func setProgressLayerPath() {
let center = CGPoint(x: self.bounds.midX, y: self.bounds.midY)
let radius = (min(self.bounds.width, self.bounds.height) - progressLayer.lineWidth) / 2
let path = UIBezierPath(arcCenter: center, radius: radius, startAngle: CGFloat(0.0), endAngle: CGFloat(2 * M_PI), clockwise: true)
progressLayer.path = path.cgPath
progressLayer.strokeStart = 0.0
progressLayer.strokeEnd = 0.0
}
fileprivate func setStrokeSuccessShapePath() {
let width = self.bounds.width
let height = self.bounds.height
let square = min(width, height)
let b = square/2
let oneTenth = square/10
let xOffset = oneTenth
let yOffset = 1.5 * oneTenth
let ySpace = 3.2 * oneTenth
let point = correctJoinPoint()
//y1 = x1 + xOffset + yOffset
//y2 = -x2 + 2b - xOffset + yOffset
let path = CGMutablePath()
path.move(to: point)
path.addLine(to: CGPoint(x: b - xOffset, y: b + yOffset))
path.addLine(to: CGPoint(x: 2 * b - xOffset + yOffset - ySpace, y: ySpace))
shapeLayer.path = path
shapeLayer.cornerRadius = square/2
shapeLayer.masksToBounds = true
shapeLayer.strokeStart = 0.0
shapeLayer.strokeEnd = 0.0
}
fileprivate func setStrokeFailureShapePath() {
let width = self.bounds.width
let height = self.bounds.height
let square = min(width, height)
let b = square/2
let space = square/3
let point = errorJoinPoint()
//y1 = x1
//y2 = -x2 + 2b
let path = CGMutablePath()
path.move(to: point)
path.addLine(to: CGPoint(x: 2 * b - space, y: 2 * b - space))
path.move(to: CGPoint(x: 2 * b - space, y: space))
path.addLine(to: CGPoint(x: space, y: 2 * b - space))
shapeLayer.path = path
shapeLayer.cornerRadius = square/2
shapeLayer.masksToBounds = true
shapeLayer.strokeStart = 0
shapeLayer.strokeEnd = 0.0
}
fileprivate func correctJoinPoint() -> CGPoint {
let r = min(self.bounds.width, self.bounds.height)/2
let m = r/2
let k = lineWidth/2
let a: CGFloat = 2.0
let b = -4 * r + 2 * m
let c = (r - m) * (r - m) + 2 * r * k - k * k
let x = (-b - sqrt(b * b - 4 * a * c))/(2 * a)
let y = x + m
return CGPoint(x: x, y: y)
}
fileprivate func errorJoinPoint() -> CGPoint {
let r = min(self.bounds.width, self.bounds.height)/2
let k = lineWidth/2
let a: CGFloat = 2.0
let b = -4 * r
let c = r * r + 2 * r * k - k * k
let x = (-b - sqrt(b * b - 4 * a * c))/(2 * a)
return CGPoint(x: x, y: x)
}
@objc fileprivate func resetAnimations() {
if status == .loading {
status = .unknown
progressLayer.removeAnimation(forKey: SMTSConstants.ringRotationAnimationKey)
progressLayer.removeAnimation(forKey: SMTSConstants.ringStrokeAnimationKey)
startLoading()
}
}
@objc fileprivate func hiddenLoadingView() {
status = .success
self.isHidden = true
if completionBlock != nil {
completionBlock!()
}
}
}
| mit | cb5cab9661a7f57d5884bbc319dedb7d | 35.039506 | 138 | 0.598657 | 5.315368 | false | false | false | false |
levieggert/Seek | Source/SeekTransform.swift | 1 | 4877 | //
// Created by Levi Eggert.
// Copyright ยฉ 2020 Levi Eggert. All rights reserved.
//
import UIKit
public struct SeekTransform: SeekType {
public let fromValue: CGAffineTransform
public let toValue: CGAffineTransform
public func valueForPosition(position: CGFloat) -> CGAffineTransform {
return SeekTransform.getTransformAtPosition(
position: position,
fromTransform: fromValue,
toTransform: toValue
)
}
}
// MARK: - Transformations
extension SeekTransform {
public static func addTransform(transformA: CGAffineTransform, toTransformB: CGAffineTransform) -> CGAffineTransform {
var transform: CGAffineTransform = CGAffineTransform.identity
transform.a = toTransformB.a + transformA.a
transform.b = toTransformB.b + transformA.b
transform.c = toTransformB.c + transformA.c
transform.d = toTransformB.d + transformA.d
transform.tx = toTransformB.tx + transformA.tx
transform.ty = toTransformB.ty + transformA.ty
return transform
}
public static func subtractTransform(transformA: CGAffineTransform, fromTransformB: CGAffineTransform) -> CGAffineTransform {
var transform: CGAffineTransform = CGAffineTransform.identity
transform.a = fromTransformB.a - transformA.a
transform.b = fromTransformB.b - transformA.b
transform.c = fromTransformB.c - transformA.c
transform.d = fromTransformB.d - transformA.d
transform.tx = fromTransformB.tx - transformA.tx
transform.ty = fromTransformB.ty - transformA.ty
return transform
}
public static func multiplyTransform(transformA: CGAffineTransform, byScalar: CGFloat) -> CGAffineTransform {
var transform: CGAffineTransform = CGAffineTransform.identity
transform.a = transformA.a * byScalar
transform.b = transformA.b * byScalar
transform.c = transformA.c * byScalar
transform.d = transformA.d * byScalar
transform.tx = transformA.tx * byScalar
transform.ty = transformA.ty * byScalar
return transform
}
public static func getTransform(x: CGFloat, y: CGFloat) -> CGAffineTransform {
return CGAffineTransform(translationX: x, y: y)
}
public static func getTransform(scaleX: CGFloat, scaleY: CGFloat) -> CGAffineTransform {
return CGAffineTransform(scaleX: scaleX, y: scaleY)
}
public static func getTransform(rotationDegrees: CGFloat) -> CGAffineTransform {
let rotation: CGFloat = CGFloat(Double.pi) * rotationDegrees / 180
return CGAffineTransform(rotationAngle: rotation)
}
public static func getTransform(x: CGFloat, y: CGFloat, scaleX: CGFloat, scaleY: CGFloat) -> CGAffineTransform {
let translation: CGAffineTransform = SeekTransform.getTransform(x: x, y: y)
let scale: CGAffineTransform = SeekTransform.getTransform(scaleX: scaleX, scaleY: scaleY)
return scale.concatenating(translation)
}
public static func getTransform(x: CGFloat, y: CGFloat, scaleX: CGFloat, scaleY: CGFloat, rotationDegrees: CGFloat) -> CGAffineTransform {
let translation: CGAffineTransform = SeekTransform.getTransform(x: x, y: y)
let scale: CGAffineTransform = SeekTransform.getTransform(scaleX: scaleX, scaleY: scaleY)
let rotation: CGAffineTransform = SeekTransform.getTransform(rotationDegrees: rotationDegrees)
let transform: CGAffineTransform = rotation.concatenating(scale)
return transform.concatenating(translation)
}
public static func getTransformAtPosition(position: CGFloat, fromTransform: CGAffineTransform, toTransform: CGAffineTransform) -> CGAffineTransform {
var transform: CGAffineTransform = CGAffineTransform.identity
let transformPosition: CGFloat = position
if transformPosition > 0 && transformPosition < 1 {
transform = SeekTransform.subtractTransform(transformA: fromTransform, fromTransformB: toTransform)
transform = SeekTransform.multiplyTransform(transformA: transform, byScalar: transformPosition)
transform = SeekTransform.addTransform(transformA: transform, toTransformB: fromTransform)
}
else if transformPosition == 0 {
transform = fromTransform
}
else if transformPosition == 1 {
transform = toTransform
}
return transform
}
public static func getTransformValue(transform: CGAffineTransform) -> NSValue? {
return NSValue(cgAffineTransform: transform)
}
}
| mit | 5514abf45ca7b0cf76e45bb7b320bd41 | 36.507692 | 153 | 0.66612 | 5.839521 | false | false | false | false |
Enziferum/iosBoss | iosBoss/JsonReader.swift | 1 | 1714 | //
// JsonReader.swift
// iosBoss
//
// Created by AlexRaag on 19/10/2017.
// Copyright ยฉ 2017 Alex Raag. All rights reserved.
//
import Foundation
/* TODO BLOCK
*/
/*
MARK:This classes uses for
*/
struct JsonAnswer{
var Answer:String
var isSmth:Bool
}
enum JsonReaderError:Error{
case noData
case noAnswer
}
//MARK
protocol JsonReaderDelegate{
func parse(JSON:Data?)throws->JsonAnswer
}
//TODO some util functions && vars//
class JsonReader{
func Send(url:URLable){
let request = Request()
request.accompishData(withUrl: url, handler: {
(data) in
guard let data = data else {
print("Error Parse")
return
}
self.JsonParse(data: data, args: ["",""])
})
}
// Remake JSONSerialization //
func JsonParse(data:Data,args:[String])->Bool{
let Flag:Bool = {
do {
let json = try JSONSerialization.jsonObject(with: data
, options: []) as? [String: Any]
guard let InfoData = json?[args[0]] as? Bool
else {
return false
}
if InfoData {
return InfoData
}
}
catch {
}
return false
}()
return Flag
}
}
extension JsonReader:JsonReaderDelegate{
func parse(JSON:Data?)throws->JsonAnswer{
let Answer = JsonAnswer(Answer: "", isSmth: true)
throw JsonReaderError.noData
throw JsonReaderError.noAnswer
return Answer
}
}
| mit | 394b6b24588ace49b1fe4d1334d1ac3a | 17.824176 | 70 | 0.509048 | 4.484293 | false | false | false | false |
iltercengiz/ICViewPager | ICViewPager/Scenes/Empty/EmptyViewController.swift | 1 | 861 | //
// EmptyViewController.swift
// ICViewPager
//
// Created by Ilter Cengiz on 18/5/18.
// Copyright ยฉ 2018 Ilter Cengiz. All rights reserved.
//
import UIKit
class EmptyViewController: UIViewController {
var backgroundColor: UIColor
var number: Int
@IBOutlet weak var numberLabel: UILabel!
// MARK: Init
init(backgroundColor: UIColor, number: Int) {
self.backgroundColor = backgroundColor
self.number = number
super.init(nibName: nil, bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
backgroundColor = .blue
number = 0
super.init(coder: aDecoder)
}
// MARK: View life cycle
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = backgroundColor
numberLabel.text = "\(number)"
}
}
| mit | 67026bed920ea66f1b919e0179440e41 | 21.631579 | 55 | 0.623256 | 4.479167 | false | false | false | false |
ivanbruel/MarkdownKit | MarkdownKit/Sources/Common/Elements/Code/MarkdownCode.swift | 1 | 1724 | //
// MarkdownCode.swift
// Pods
//
// Created by Ivan Bruel on 18/07/16.
//
//
import Foundation
open class MarkdownCode: MarkdownCommonElement {
fileprivate static let regex = "(.?|^)(\\`{1,3})(.+?)(\\2)"
open var font: MarkdownFont?
open var color: MarkdownColor?
open var textHighlightColor: MarkdownColor?
open var textBackgroundColor: MarkdownColor?
open var regex: String {
return MarkdownCode.regex
}
public init(font: MarkdownFont? = MarkdownCode.defaultFont,
color: MarkdownColor? = nil,
textHighlightColor: MarkdownColor? = MarkdownCode.defaultHighlightColor,
textBackgroundColor: MarkdownColor? = MarkdownCode.defaultBackgroundColor) {
self.font = font
self.color = color
self.textHighlightColor = textHighlightColor
self.textBackgroundColor = textBackgroundColor
}
open func addAttributes(_ attributedString: NSMutableAttributedString, range: NSRange) {
let matchString: String = attributedString.attributedSubstring(from: range).string
guard let unescapedString = matchString.unescapeUTF16() else { return }
attributedString.replaceCharacters(in: range, with: unescapedString)
var codeAttributes = attributes
textHighlightColor.flatMap { codeAttributes[NSAttributedString.Key.foregroundColor] = $0 }
textBackgroundColor.flatMap { codeAttributes[NSAttributedString.Key.backgroundColor] = $0 }
font.flatMap { codeAttributes[NSAttributedString.Key.font] = $0 }
let updatedRange = (attributedString.string as NSString).range(of: unescapedString)
attributedString.addAttributes(codeAttributes, range: NSRange(location: range.location, length: updatedRange.length))
}
}
| mit | 978ebd59e84930aa9ebdee2ff6c4f37b | 35.680851 | 121 | 0.734919 | 4.802228 | false | false | false | false |
radex/swift-compiler-crashes | crashes-fuzzing/21480-swift-constraints-constraintsystem-matchtypes.swift | 11 | 2304 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
if true {
case c,
func a<Int>
let start = [ [Void{
func b
case c,
let start = [ [Void{
((([Void{
var b = a
func a
struct d
{
func b
func e( ) {
class c : I
class
func a<T where g: a( ) {
protocol c {
class B {
var f = a( ) {
struct d
((i: C {
let a {
func a
var f = b<T {
case c,
func e( ) {
typealias B : d<b<T {
func a
if true {
enum S<l : a {
class
class B : C {
class c {
struct A {
func a( ([Void{
if true {
case c,
case c,
func a<T {
class
case c,
if true {
{
class
class
class
case c,
case c,
class c {
struct A {
func e( ) {
var f = a<b
struct A {
class
var f = b
case c,
let a {
protocol c {
func a<T where g: I
class
func b(((([Void{
if true {
typealias B {
}
func a<T {
{
enum S<T where g: B.E
""
struct d<b
protocol B : d<T {
class A {
(i: B.f
class
struct A {
protocol c {
case c,
{
"
enum S<T where g: d
protocol c {
([Void{
enum A {
var b = a
class
class
case c,
"
enum S<T where g: I
}
{
var b = a<T {
protocol c : T.f
enum A {
}
if true {
case c,
protocol B {
struct d
protocol c : a<T {
class
func e( ((n: T.E
([Void{
}
{
case c,
var b = b([Void{
protocol c : C {
}
{
enum S<T {
class c : a( ([Void{
typealias B : a {
if true {
enum S<l : I
case c,
enum A {
class A {
class B : T.E
func a
((i: T.E
{
func b((((((([Void{
enum A {
func b
}
case c,
if true {
if true {
class c {
var f = a<T where g: d<l : I
func b
func b([Void{
enum A {
if true {
protocol B : a {
func a<l : C {
protocol c {
{
struct d<Int>
typealias B {
class A {
class c : d
(n: d<Int>
class
enum A {
enum A {
protocol c : d<b(n: a {
let start = [ [Void{
class B {
protocol B {
{
class
([Void{
case c,
func a<b<T {
"
class c : a
func b
protocol c {
class
func a
}
(i: d<b(n: I
let a {
var f = a
class
}
class
case c,
class A {
enum A {
class
protocol c {
{
case c,
var b = b<T {
class
class c : a {
func e( ) {
{
class A {
protocol c {
var b = [ [Void{
protocol c : d
let a {
protocol B : d<T {
var f = a<T {
}
if true {
let start = [ [Void{
func e( ) {
struct A {
{
case c,
([Void{
var f = a<T {
if true {
let a {
func a<l : T.E
(i: T.f
func b
enum S<b
"
"
func b
{
protocol c : T.f
class
func a
case c,
protocol c {
struct A {
protocol c {
func a(
| mit | b2932ad3b4db718afa830f3dfde869ed | 9.520548 | 87 | 0.59158 | 2.274432 | false | false | false | false |
cbh2000/flickrtest | FlickrTest/PhotoSearchResult.swift | 1 | 1959 | //
// PhotoSearchResult.swift
// FlickrTest
//
// Created by Christopher Bryan Henderson on 9/20/16.
// Copyright ยฉ 2016 Christopher Bryan Henderson. All rights reserved.
//
import Foundation
// Represents an individual photo in a search response.
struct PhotoSearchResult: JSONInstantiatable {
let id: String
let owner: String
let title: String
let previewImageURL: URL
let fullSizeImageURL: URL
fileprivate static func parseError(_ reason: String) -> JSONInstantiationError {
return JSONInstantiationError.failedToParse(type: PhotoSearchResult.self, reason: reason)
}
init(json: [String : Any]) throws {
//
// For large apps, this approach to class serialization is tedious. But since this app is simple, it'll do.
//
guard let id = json["id"] as? String else {
throw PhotoSearchResult.parseError("Failed to parse id.")
}
guard let owner = json["owner"] as? String else {
throw PhotoSearchResult.parseError("Failed to parse owner.")
}
guard let title = json["title"] as? String else {
throw PhotoSearchResult.parseError("Failed to parse title.")
}
self.id = id
self.owner = owner
self.title = title
// Now, get the image URLs
guard let farmID = json["farm"] as? Int, let serverID = json["server"] as? String else {
throw PhotoSearchResult.parseError("Failed to parse farm or server.")
}
guard let secret = json["secret"] as? String else {
throw PhotoSearchResult.parseError("Failed to parse secret.")
}
self.previewImageURL = URL(string: "https://farm\(farmID).staticflickr.com/\(serverID)/\(id)_\(secret)_q.jpg")!
self.fullSizeImageURL = URL(string: "https://farm\(farmID).staticflickr.com/\(serverID)/\(id)_\(secret).jpg")!
}
}
| mit | 587677291660023d103fea529b163978 | 34.6 | 119 | 0.621042 | 4.661905 | false | false | false | false |
iOSDevLog/InkChat | InkChat/Pods/IBAnimatable/IBAnimatable/ActivityIndicatorAnimationLineSpinFadeLoader.swift | 1 | 2863 | //
// Created by Tom Baranes on 23/08/16.
// Copyright (c) 2016 IBAnimatable. All rights reserved.
//
import UIKit
public class ActivityIndicatorAnimationLineSpinFadeLoader: ActivityIndicatorAnimating {
// MARK: Properties
fileprivate let duration: CFTimeInterval = 1.2
fileprivate let timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
// MARK: ActivityIndicatorAnimating
public func configureAnimation(in layer: CALayer, size: CGSize, color: UIColor) {
let lineSpacing: CGFloat = 2
let lineSize = CGSize(width: (size.width - 4 * lineSpacing) / 5, height: (size.height - 2 * lineSpacing) / 3)
let x = (layer.bounds.size.width - size.width) / 2
let y = (layer.bounds.size.height - size.height) / 2
let beginTime = CACurrentMediaTime()
let beginTimes: [CFTimeInterval] = [0.12, 0.24, 0.36, 0.48, 0.6, 0.72, 0.84, 0.96]
let animation = defaultAnimation
for i in 0 ..< 8 {
let line = makeLineLayer(angle: CGFloat.pi / 4 * CGFloat(i),
size: lineSize,
origin: CGPoint(x: x, y: y),
containerSize: size,
color: color)
animation.beginTime = beginTime + beginTimes[i]
line.add(animation, forKey: "animation")
layer.addSublayer(line)
}
}
}
// MARK: - Setup
private extension ActivityIndicatorAnimationLineSpinFadeLoader {
var defaultAnimation: CAKeyframeAnimation {
let animation = CAKeyframeAnimation(keyPath: "opacity")
animation.keyTimes = [0, 0.5, 1]
animation.timingFunctions = [timingFunction, timingFunction]
animation.values = [1, 0.3, 1]
animation.duration = duration
animation.repeatCount = .infinity
animation.isRemovedOnCompletion = false
return animation
}
func makeLineLayer(angle: CGFloat, size: CGSize, origin: CGPoint, containerSize: CGSize, color: UIColor) -> CALayer {
let radius = containerSize.width / 2 - max(size.width, size.height) / 2
let lineContainerSize = CGSize(width: max(size.width, size.height), height: max(size.width, size.height))
let lineContainer = CALayer()
let lineContainerFrame = CGRect(
x: origin.x + radius * (cos(angle) + 1),
y: origin.y + radius * (sin(angle) + 1),
width: lineContainerSize.width,
height: lineContainerSize.height)
let line = ActivityIndicatorShape.line.makeLayer(size: size, color: color)
let lineFrame = CGRect(
x: (lineContainerSize.width - size.width) / 2,
y: (lineContainerSize.height - size.height) / 2,
width: size.width,
height: size.height)
lineContainer.frame = lineContainerFrame
line.frame = lineFrame
lineContainer.addSublayer(line)
lineContainer.sublayerTransform = CATransform3DMakeRotation(CGFloat.pi / 2 + angle, 0, 0, 1)
return lineContainer
}
}
| apache-2.0 | e1647fe6007a5f2589c08671140f759d | 35.705128 | 119 | 0.676214 | 4.228951 | false | false | false | false |
Bouke/HAP | Sources/HAP/Base/Predefined/Characteristics/Characteristic.CurrentAirQuality.swift | 1 | 2133 | import Foundation
public extension AnyCharacteristic {
static func currentAirQuality(
_ value: Enums.CurrentAirQuality = .good,
permissions: [CharacteristicPermission] = [.read, .events],
description: String? = "Current Air Quality",
format: CharacteristicFormat? = .uint8,
unit: CharacteristicUnit? = nil,
maxLength: Int? = nil,
maxValue: Double? = 5,
minValue: Double? = 0,
minStep: Double? = 1,
validValues: [Double] = [],
validValuesRange: Range<Double>? = nil
) -> AnyCharacteristic {
AnyCharacteristic(
PredefinedCharacteristic.currentAirQuality(
value,
permissions: permissions,
description: description,
format: format,
unit: unit,
maxLength: maxLength,
maxValue: maxValue,
minValue: minValue,
minStep: minStep,
validValues: validValues,
validValuesRange: validValuesRange) as Characteristic)
}
}
public extension PredefinedCharacteristic {
static func currentAirQuality(
_ value: Enums.CurrentAirQuality = .good,
permissions: [CharacteristicPermission] = [.read, .events],
description: String? = "Current Air Quality",
format: CharacteristicFormat? = .uint8,
unit: CharacteristicUnit? = nil,
maxLength: Int? = nil,
maxValue: Double? = 5,
minValue: Double? = 0,
minStep: Double? = 1,
validValues: [Double] = [],
validValuesRange: Range<Double>? = nil
) -> GenericCharacteristic<Enums.CurrentAirQuality> {
GenericCharacteristic<Enums.CurrentAirQuality>(
type: .currentAirQuality,
value: value,
permissions: permissions,
description: description,
format: format,
unit: unit,
maxLength: maxLength,
maxValue: maxValue,
minValue: minValue,
minStep: minStep,
validValues: validValues,
validValuesRange: validValuesRange)
}
}
| mit | 378824e3d189e7a67992a4443b1d8f24 | 33.967213 | 67 | 0.591655 | 5.441327 | false | false | false | false |
liufengting/FTZoomTransition | FTZoomTransition/FTZoomTransition.swift | 1 | 3666 | //
// FTTransitionDelegate.swift
// FTZoomTransition
//
// Created by liufengting on 30/11/2016.
// Copyright ยฉ 2016 LiuFengting <https://github.com/liufengting>. All rights reserved.
//
import UIKit
open class FTZoomTransitionConfig {
open weak var sourceView: UIView?
open var sourceFrame = CGRect.zero
open var targetFrame = CGRect.zero
open var enableZoom : Bool = false
open var presentAnimationDuriation : TimeInterval = 0.3
open var dismissAnimationDuriation : TimeInterval = 0.3
open lazy var transitionImageView: UIImageView = {
let iv = UIImageView()
iv.clipsToBounds = true
iv.contentMode = .scaleAspectFill
return iv
}()
static func maxAnimationDuriation() -> TimeInterval {
return 0.3
}
public convenience init(sourceView: UIView, image: UIImage?, targetFrame: CGRect) {
self.init()
self.sourceView = sourceView
self.targetFrame = targetFrame
self.transitionImageView.image = image
if self.sourceView != nil {
self.sourceFrame = (self.sourceView?.superview?.convert((self.sourceView?.frame)!, to: UIApplication.shared.delegate?.window!)) ?? .zero;
}
}
}
open class FTZoomTransition: NSObject, UIViewControllerTransitioningDelegate {
open var config : FTZoomTransitionConfig! {
willSet{
presentAnimator.config = newValue
dismissAnimator.config = newValue
}
}
final let presentAnimator = FTPresentAnimator()
final let dismissAnimator = FTDismissAnimator()
public let panDismissAnimator = FTPanDismissAnimator()
public func wirePanDismissToViewController(_ viewController: UIViewController, for view: UIView?) {
self.panDismissAnimator.wirePanDismissToViewController(viewController: viewController, for: view)
}
public func wireEdgePanDismissToViewController(viewController: UIViewController) {
self.panDismissAnimator.wireEdgePanDismissToViewController(viewController: viewController)
}
public func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
return presentAnimator
}
public func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
return dismissAnimator
}
public func interactionControllerForDismissal(using animator: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? {
if panDismissAnimator.interactionInProgress == true {
panDismissAnimator.dismissAnimator = dismissAnimator
return panDismissAnimator
} else {
return nil
}
}
}
public extension UIView {
// solution found at: http://stackoverflow.com/a/5666430/6310268
func setAnchorPoint(anchorPoint: CGPoint) {
var newPoint = CGPoint(x: self.bounds.size.width * anchorPoint.x, y: self.bounds.size.height * anchorPoint.y)
var oldPoint = CGPoint(x: self.bounds.size.width * self.layer.anchorPoint.x, y: self.bounds.size.height * self.layer.anchorPoint.y)
newPoint = newPoint.applying(self.transform)
oldPoint = oldPoint.applying(self.transform)
var position = self.layer.position
position.x -= oldPoint.x
position.x += newPoint.x
position.y -= oldPoint.y
position.y += newPoint.y
self.layer.position = position
self.layer.anchorPoint = anchorPoint
}
}
| mit | b6e90d5c7a381915dfa9e249518743b7 | 35.287129 | 177 | 0.689495 | 5.213371 | false | false | false | false |
designatednerd/iOS10NotificationSample | NotificationSample/ViewControllers/ViewController.swift | 1 | 4365 | //
// ViewController.swift
// NotificationSample
//
// Created by Ellen Shapiro (Work) on 8/14/16.
// Copyright ยฉ 2016 Designated Nerd Software. All rights reserved.
//
import ParrotKit
import UIKit
class ViewController: UIViewController {
private enum SegueTo: String {
case
prompt = "ToNotificationPrompt"
}
@IBOutlet private var parrotImageView: UIImageView!
@IBOutlet private var askedLabel: UILabel!
@IBOutlet private var askButton: UIButton!
@IBOutlet private var grantedLabel: UILabel!
@IBOutlet private var sendTestNotificationButton: UIButton!
@IBOutlet private var collectionView: UICollectionView!
var notificationHandler: VersionSpecificNotificationHandler!
private let parrots = PartyParrot.nonstandardParrots
//MARK: View Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
ParrotCollectionViewCell.register(with: self.collectionView)
// That other kind of notification
NotificationCenter
.default
.addObserver(forName: .PartyUpdated,
object: nil,
queue: .main,
using: {
[weak self]
_ in
self?.collectionView.reloadData()
})
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.parrotImageView.image = ParrotGif.partyparrot.animated
self.parrotImageView.isHidden = true
guard let notificationHandler = self.notificationHandler else {
assertionFailure("You're gonna want a notification handler to actually load this stuff")
return
}
notificationHandler.hasUserBeenAskedAboutPushNotifications() {
[weak self]
asked in
self?.userWasAskedForNotificationPermission(asked: asked)
if asked {
self?.notificationHandler.arePermissionsGranted {
granted in
self?.permissionsWereGranted(granted: granted)
}
}
}
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
guard
let identifier = segue.identifier,
let segueTo = SegueTo(rawValue: identifier) else {
assertionFailure("Could not find the appropriate segue identifier!")
return
}
switch segueTo {
case .prompt:
guard let destination = segue.destination as? NotificationPromptViewController else {
return
}
destination.notificationHandler = self.notificationHandler
}
}
//MARK: - UI setup
private func userWasAskedForNotificationPermission(asked: Bool) {
if asked {
self.askedLabel.text = "๐"
self.askButton.isEnabled = false
self.askButton.alpha = 0.5
self.parrotImageView.isHidden = false
} else {
self.askedLabel.text = "๐"
self.permissionsWereGranted(granted: false)
self.askButton.isEnabled = true
self.askButton.alpha = 1
self.parrotImageView.isHidden = true
}
}
private func permissionsWereGranted(granted: Bool) {
if granted {
self.grantedLabel.text = "๐"
self.sendTestNotificationButton.isEnabled = true
self.sendTestNotificationButton.alpha = 1
} else {
self.grantedLabel.text = "๐"
self.sendTestNotificationButton.isEnabled = false
self.sendTestNotificationButton.alpha = 0.5
self.parrotImageView.image = ParrotGif.sadparrot.animated
}
}
//MARK: - IBActions
@IBAction private func sendTestNotification() {
let randomIndex = Int(arc4random_uniform(UInt32(self.parrots.count)))
let parrot = self.parrots[randomIndex]
self.notificationHandler.scheduleNotification(for: parrot,
delay: 3)
}
}
| mit | 7fe883038562734cc8ac5d500ad2eeb1 | 31 | 100 | 0.574678 | 5.703801 | false | false | false | false |
kickstarter/ios-oss | Kickstarter-iOS/Features/ProjectActivities/Views/Cells/ProjectActivityBackingCell.swift | 1 | 7471 | import KsApi
import Library
import Prelude
import Prelude_UIKit
import UIKit
internal protocol ProjectActivityBackingCellDelegate: AnyObject {
func projectActivityBackingCellGoToBacking(project: Project, backing: Backing)
func projectActivityBackingCellGoToSendMessage(project: Project, backing: Backing)
}
internal final class ProjectActivityBackingCell: UITableViewCell, ValueCell {
fileprivate let viewModel: ProjectActivityBackingCellViewModelType = ProjectActivityBackingCellViewModel()
internal weak var delegate: ProjectActivityBackingCellDelegate?
@IBOutlet fileprivate var backerImageView: CircleAvatarImageView!
@IBOutlet fileprivate var backingButton: UIButton!
@IBOutlet fileprivate var bulletSeparatorView: UIView!
@IBOutlet fileprivate var cardView: UIView!
@IBOutlet fileprivate var footerDividerView: UIView!
@IBOutlet fileprivate var footerStackView: UIStackView!
@IBOutlet fileprivate var headerDividerView: UIView!
@IBOutlet fileprivate var headerStackView: UIStackView!
@IBOutlet fileprivate var pledgeAmountLabel: UILabel!
@IBOutlet fileprivate var pledgeAmountLabelsStackView: UIStackView!
@IBOutlet fileprivate var pledgeAmountsStackView: UIView!
@IBOutlet fileprivate var pledgeDetailsSeparatorView: UIView!
@IBOutlet fileprivate var pledgeDetailsStackView: UIStackView!
@IBOutlet fileprivate var previousPledgeAmountLabel: UILabel!
@IBOutlet fileprivate var previousPledgeStrikethroughView: UIView!
@IBOutlet fileprivate var rewardLabel: UILabel!
@IBOutlet fileprivate var sendMessageButton: UIButton!
@IBOutlet fileprivate var titleLabel: UILabel!
internal override func awakeFromNib() {
super.awakeFromNib()
_ = self.backingButton
|> UIButton.lens.targets .~ [(self, #selector(self.backingButtonPressed), .touchUpInside)]
_ = self.sendMessageButton
|> UIButton.lens.targets .~ [(self, #selector(self.sendMessageButtonPressed), .touchUpInside)]
}
internal func configureWith(value activityAndProject: (Activity, Project)) {
self.viewModel.inputs.configureWith(
activity: activityAndProject.0,
project: activityAndProject.1
)
}
internal override func bindViewModel() {
super.bindViewModel()
self.rac.accessibilityLabel = self.viewModel.outputs.cellAccessibilityLabel
self.rac.accessibilityValue = self.viewModel.outputs.cellAccessibilityValue
self.viewModel.outputs.backerImageURL
.observeForUI()
.on(event: { [weak self] _ in
self?.backerImageView.af.cancelImageRequest()
self?.backerImageView.image = nil
})
.skipNil()
.observeValues { [weak self] url in
self?.backerImageView.af.setImage(withURL: url)
}
self.viewModel.outputs.notifyDelegateGoToBacking
.observeForUI()
.observeValues { [weak self] project, backing in
self?.delegate?.projectActivityBackingCellGoToBacking(project: project, backing: backing)
}
self.viewModel.outputs.notifyDelegateGoToSendMessage
.observeForUI()
.observeValues { [weak self] project, backing in
self?.delegate?.projectActivityBackingCellGoToSendMessage(project: project, backing: backing)
}
self.pledgeAmountLabel.rac.hidden = self.viewModel.outputs.pledgeAmountLabelIsHidden
self.pledgeAmountLabel.rac.text = self.viewModel.outputs.pledgeAmount
self.pledgeAmountsStackView.rac.hidden = self.viewModel.outputs.pledgeAmountsStackViewIsHidden
self.pledgeDetailsSeparatorView.rac.hidden =
self.viewModel.outputs.pledgeDetailsSeparatorStackViewIsHidden
self.previousPledgeAmountLabel.rac.hidden = self.viewModel.outputs.previousPledgeAmountLabelIsHidden
self.previousPledgeAmountLabel.rac.text = self.viewModel.outputs.previousPledgeAmount
self.rewardLabel.rac.hidden = self.viewModel.outputs.rewardLabelIsHidden
self.sendMessageButton.rac.hidden = self.viewModel.outputs.sendMessageButtonAndBulletSeparatorHidden
self.bulletSeparatorView.rac.hidden = self.viewModel.outputs.sendMessageButtonAndBulletSeparatorHidden
self.viewModel.outputs.reward.observeForUI()
.observeValues { [weak rewardLabel] title in
guard let rewardLabel = rewardLabel else { return }
rewardLabel.attributedText = title.simpleHtmlAttributedString(
font: .ksr_body(size: 12),
bold: UIFont.ksr_body(size: 12).bolded,
italic: nil
)
_ = rewardLabel
|> UILabel.lens.numberOfLines .~ 0
|> UILabel.lens.textColor .~ .ksr_support_400
}
self.viewModel.outputs.title.observeForUI()
.observeValues { [weak titleLabel] title in
guard let titleLabel = titleLabel else { return }
titleLabel.attributedText = title.simpleHtmlAttributedString(
base: [
NSAttributedString.Key.font: UIFont.ksr_title3(size: 14),
NSAttributedString.Key.foregroundColor: UIColor.ksr_support_400
],
bold: [
NSAttributedString.Key.font: UIFont.ksr_title3(size: 14),
NSAttributedString.Key.foregroundColor: UIColor.ksr_support_700
],
italic: nil
)
?? .init()
}
}
internal override func bindStyles() {
super.bindStyles()
_ = self
|> baseTableViewCellStyle()
|> ProjectActivityBackingCell.lens.contentView.layoutMargins %~~ { layoutMargins, cell in
cell.traitCollection.isRegularRegular
? projectActivityRegularRegularLayoutMargins
: layoutMargins
}
|> UITableViewCell.lens.accessibilityHint %~ { _ in Strings.Opens_pledge_info() }
_ = self.backerImageView
|> ignoresInvertColorsImageViewStyle
_ = self.backingButton
|> projectActivityFooterButton
|> UIButton.lens.title(for: .normal) %~ { _ in Strings.dashboard_activity_pledge_info() }
_ = self.bulletSeparatorView
|> projectActivityBulletSeparatorViewStyle
_ = self.cardView
|> dropShadowStyleMedium()
_ = self.footerDividerView
|> projectActivityDividerViewStyle
_ = self.footerStackView
|> projectActivityFooterStackViewStyle
|> UIStackView.lens.layoutMargins .~ .init(all: Styles.grid(2))
_ = self.headerDividerView
|> projectActivityDividerViewStyle
_ = self.headerStackView
|> projectActivityHeaderStackViewStyle
_ = self.pledgeAmountLabel
|> UILabel.lens.textColor .~ .ksr_create_700
|> UILabel.lens.font .~ .ksr_callout(size: 24)
_ = self.pledgeAmountLabelsStackView
|> UIStackView.lens.spacing .~ Styles.grid(2)
_ = self.pledgeDetailsStackView
|> UIStackView.lens.layoutMargins .~ .init(topBottom: Styles.grid(3), leftRight: Styles.grid(2))
|> UIStackView.lens.isLayoutMarginsRelativeArrangement .~ true
_ = self.previousPledgeAmountLabel
|> UILabel.lens.font .~ .ksr_callout(size: 24)
|> UILabel.lens.textColor .~ .ksr_support_400
_ = self.previousPledgeStrikethroughView
|> UIView.lens.backgroundColor .~ .ksr_support_400
_ = self.sendMessageButton
|> projectActivityFooterButton
|> UIButton.lens.title(for: .normal) %~ { _ in Strings.dashboard_activity_send_message() }
}
@objc fileprivate func backingButtonPressed(_: UIButton) {
self.viewModel.inputs.backingButtonPressed()
}
@objc fileprivate func sendMessageButtonPressed(_: UIButton) {
self.viewModel.inputs.sendMessageButtonPressed()
}
}
| apache-2.0 | 613600d531510629e8855cb220454631 | 35.985149 | 108 | 0.729354 | 4.96742 | false | false | false | false |
apple/swift-experimental-string-processing | Sources/_StringProcessing/Algorithms/Algorithms/Replace.swift | 1 | 8415 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2021-2022 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
// MARK: `CollectionSearcher` algorithms
extension RangeReplaceableCollection {
func _replacing<Ranges: Collection, Replacement: Collection>(
_ ranges: Ranges,
with replacement: Replacement,
maxReplacements: Int = .max
) -> Self where Ranges.Element == Range<Index>,
Replacement.Element == Element
{
precondition(maxReplacements >= 0)
var result = Self()
var index = startIndex
// `maxRanges` is a workaround for https://github.com/apple/swift/issues/59522
let maxRanges = ranges.prefix(maxReplacements)
for range in maxRanges {
result.append(contentsOf: self[index..<range.lowerBound])
result.append(contentsOf: replacement)
index = range.upperBound
}
result.append(contentsOf: self[index...])
return result
}
mutating func _replace<
Ranges: Collection, Replacement: Collection
>(
_ ranges: Ranges,
with replacement: Replacement,
maxReplacements: Int = .max
) where Ranges.Element == Range<Index>, Replacement.Element == Element {
self = _replacing(
ranges,
with: replacement,
maxReplacements: maxReplacements)
}
}
// MARK: Fixed pattern algorithms
extension RangeReplaceableCollection where Element: Equatable {
/// Returns a new collection in which all occurrences of a target sequence
/// are replaced by another collection.
/// - Parameters:
/// - other: The sequence to replace.
/// - replacement: The new elements to add to the collection.
/// - subrange: The range in the collection in which to search for `other`.
/// - maxReplacements: A number specifying how many occurrences of `other`
/// to replace. Default is `Int.max`.
/// - Returns: A new collection in which all occurrences of `other` in
/// `subrange` of the collection are replaced by `replacement`.
@available(SwiftStdlib 5.7, *)
public func replacing<C: Collection, Replacement: Collection>(
_ other: C,
with replacement: Replacement,
subrange: Range<Index>,
maxReplacements: Int = .max
) -> Self where C.Element == Element, Replacement.Element == Element {
_replacing(
self[subrange]._ranges(of: other),
with: replacement,
maxReplacements: maxReplacements)
}
/// Returns a new collection in which all occurrences of a target sequence
/// are replaced by another collection.
/// - Parameters:
/// - other: The sequence to replace.
/// - replacement: The new elements to add to the collection.
/// - maxReplacements: A number specifying how many occurrences of `other`
/// to replace. Default is `Int.max`.
/// - Returns: A new collection in which all occurrences of `other` in
/// `subrange` of the collection are replaced by `replacement`.
@available(SwiftStdlib 5.7, *)
public func replacing<C: Collection, Replacement: Collection>(
_ other: C,
with replacement: Replacement,
maxReplacements: Int = .max
) -> Self where C.Element == Element, Replacement.Element == Element {
replacing(
other,
with: replacement,
subrange: startIndex..<endIndex,
maxReplacements: maxReplacements)
}
/// Replaces all occurrences of a target sequence with a given collection
/// - Parameters:
/// - other: The sequence to replace.
/// - replacement: The new elements to add to the collection.
/// - maxReplacements: A number specifying how many occurrences of `other`
/// to replace. Default is `Int.max`.
@available(SwiftStdlib 5.7, *)
public mutating func replace<C: Collection, Replacement: Collection>(
_ other: C,
with replacement: Replacement,
maxReplacements: Int = .max
) where C.Element == Element, Replacement.Element == Element {
self = replacing(
other,
with: replacement,
subrange: startIndex..<endIndex,
maxReplacements: maxReplacements)
}
}
extension RangeReplaceableCollection
where Self: BidirectionalCollection, Element: Comparable
{
func _replacing<C: Collection, Replacement: Collection>(
_ other: C,
with replacement: Replacement,
subrange: Range<Index>,
maxReplacements: Int = .max
) -> Self where C.Element == Element, Replacement.Element == Element {
_replacing(
self[subrange]._ranges(of: other),
with: replacement,
maxReplacements: maxReplacements)
}
func _replacing<C: Collection, Replacement: Collection>(
_ other: C,
with replacement: Replacement,
maxReplacements: Int = .max
) -> Self where C.Element == Element, Replacement.Element == Element {
_replacing(
other,
with: replacement,
subrange: startIndex..<endIndex,
maxReplacements: maxReplacements)
}
mutating func _replace<C: Collection, Replacement: Collection>(
_ other: C,
with replacement: Replacement,
maxReplacements: Int = .max
) where C.Element == Element, Replacement.Element == Element {
self = _replacing(
other,
with: replacement,
subrange: startIndex..<endIndex,
maxReplacements: maxReplacements)
}
}
// MARK: Regex algorithms
extension RangeReplaceableCollection where SubSequence == Substring {
/// Returns a new collection in which all occurrences of a sequence matching
/// the given regex are replaced by another collection.
/// - Parameters:
/// - regex: A regex describing the sequence to replace.
/// - replacement: The new elements to add to the collection.
/// - subrange: The range in the collection in which to search for `regex`.
/// - maxReplacements: A number specifying how many occurrences of the
/// sequence matching `regex` to replace. Default is `Int.max`.
/// - Returns: A new collection in which all occurrences of subsequence
/// matching `regex` in `subrange` are replaced by `replacement`.
@available(SwiftStdlib 5.7, *)
public func replacing<Replacement: Collection>(
_ regex: some RegexComponent,
with replacement: Replacement,
subrange: Range<Index>,
maxReplacements: Int = .max
) -> Self where Replacement.Element == Element {
_replacing(
self._ranges(
of: regex,
subjectBounds: startIndex..<endIndex,
searchBounds: subrange),
with: replacement,
maxReplacements: maxReplacements)
}
/// Returns a new collection in which all occurrences of a sequence matching
/// the given regex are replaced by another collection.
/// - Parameters:
/// - regex: A regex describing the sequence to replace.
/// - replacement: The new elements to add to the collection.
/// - maxReplacements: A number specifying how many occurrences of the
/// sequence matching `regex` to replace. Default is `Int.max`.
/// - Returns: A new collection in which all occurrences of subsequence
/// matching `regex` are replaced by `replacement`.
@_disfavoredOverload
@available(SwiftStdlib 5.7, *)
public func replacing<Replacement: Collection>(
_ regex: some RegexComponent,
with replacement: Replacement,
maxReplacements: Int = .max
) -> Self where Replacement.Element == Element {
replacing(
regex,
with: replacement,
subrange: startIndex..<endIndex,
maxReplacements: maxReplacements)
}
/// Replaces all occurrences of the sequence matching the given regex with
/// a given collection.
/// - Parameters:
/// - regex: A regex describing the sequence to replace.
/// - replacement: The new elements to add to the collection.
/// - maxReplacements: A number specifying how many occurrences of the
/// sequence matching `regex` to replace. Default is `Int.max`.
@available(SwiftStdlib 5.7, *)
public mutating func replace<Replacement: Collection>(
_ regex: some RegexComponent,
with replacement: Replacement,
maxReplacements: Int = .max
) where Replacement.Element == Element {
self = replacing(
regex,
with: replacement,
maxReplacements: maxReplacements)
}
}
| apache-2.0 | ef2c66d88e4953e3bde753f5ff4178c1 | 35.428571 | 82 | 0.670351 | 4.722222 | false | false | false | false |
moonrailgun/OpenCode | OpenCode/Classes/News/View/Notable/NotableList.swift | 1 | 3084 | //
// NotableList.swift
// OpenCode
//
// Created by ้ไบฎ on 16/6/14.
// Copyright ยฉ 2016ๅนด moonrailgun. All rights reserved.
//
import UIKit
import SwiftyJSON
import MJRefresh
class NotableList: UIView {
let NOTABLE_CELL_ID = "notable"
var controller:UIViewController?
var collectionView:UserListView?
var currentMaxPage = 1
init(frame: CGRect, controller:UIViewController?){
super.init(frame:frame)
self.controller = controller
initView()
initData()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func initView(){
collectionView = UserListView(frame: self.bounds, controller: controller)
collectionView?.mj_footer = MJRefreshAutoNormalFooter(refreshingBlock: {
self.currentMaxPage += 1
self.addonData(self.currentMaxPage)
})
self.addSubview(collectionView!)
}
func initData(){
if collectionView != nil{
Github.getNotableList(nil) { (data:AnyObject?) in
if let d = data{
let json = JSON(d)
print("ๅ
ฑ\(json["total_count"].int!)ไธชgithubๅไบบ")
let items = json["items"]
self.collectionView?.userListData = items.arrayValue
OperationQueueHelper.operateInMainQueue({
/*let header = UILabel(frame: CGRectMake(0,0,self.bounds.width,24))
header.text = "ๅ
ฑ\(json["total_count"].int!)ไธชๅไบบ"
header.textColor = UIColor.whiteColor()
header.backgroundColor = UIColor.peterRiverFlatColor()
header.textAlignment = .Center
header.font = UIFont.systemFontOfSize(14)
self.collectionView?.addSubview(header)*/
self.collectionView?.reloadData()
})
}
}
}
}
func addonData(page:Int){
if (self.collectionView != nil){
Github.getNotableList(page) { (data:AnyObject?) in
if let d = data{
let json = JSON(d)
print("ๅ ่ฝฝๆฐๆฐๆฎๅฎๆฏ,ๅ ่ฝฝ้กต็ \(page)")
let items = json["items"]
if(self.collectionView?.userListData != nil) {
for i in 0 ... items.count - 1{
self.collectionView!.userListData!.append(items[i])
}
}
OperationQueueHelper.operateInMainQueue({
self.collectionView?.reloadData()
self.collectionView?.mj_footer.endRefreshing()
})
}
}
}
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
}
| gpl-2.0 | 3c0382c1f065e10ea975a4a5243516cc | 31.329787 | 91 | 0.506088 | 5.266898 | false | false | false | false |
zjjzmw1/SwiftCodeFragments | SwiftCodeFragments/AnimationResource/ImageMaskAnimator.swift | 1 | 5900 | //
// ImageMaskAnimator.swift
// gwlTransformAnim
//
// Created by wangrui on 16/8/30.
// Copyright ยฉ 2016ๅนด tools. All rights reserved.
//
import UIKit
enum ImageMaskTransitionType {
case present
case dismiss
}
class ImageMaskAnimator: NSObject {
var transitionType : ImageMaskTransitionType = .present
var imageView : UIImageView!
var maskContentView : UIImageView!
// ็นๅป็ๅพ็
var fromImageView : UIImageView!
// ๅฐ่ฆๆไธบ็ๅพ็
var toImageView : UIImageView!
}
extension ImageMaskAnimator : UIViewControllerAnimatedTransitioning{
// ๅจ็ป็ๆถ้ด
func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return self.transitionType == .present ? 1.6 : 1.3
}
// ๅฎ้
็ๅจ็ป
func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
let fromView = transitionContext.view(forKey: UITransitionContextViewKey.from)!
let toView = transitionContext.view(forKey: UITransitionContextViewKey.to)!
// ๅฝไธคไธช่งๅพๆงๅถๅจไน้ด็่ฟๅบฆๅผๅงๆถ๏ผๅฝๅๅทฒ็ปๅญๅจ็่งๅพๅฐไผ่ขซๆทปๅ ๅฐcontainViewไธ๏ผ่ๆฐ็่งๅพๆงๅถๅจ็่งๅพไนๅจๆญคๆถ่ขซๅๅปบ๏ผๅชๆฏไธๅฏ่ง่ๅทฒ๏ผๆฅไธๆฅๅฐฑๆฏๆไปฌ็ไปปๅกไบ๏ผๅฐๆฐ็่งๅพๆทปๅ ๅฐcontrinerViewไธ๏ผ้ป่ฎคๆ
ๅตไธ๏ผ่ฟๅบฆๅจ็ปๆง่กๅฎไปฅๅ๏ผๆง่งๅพไผๅจcontainerViewไธ็งป้ค
let containView = transitionContext.containerView
print("\(fromView)" + "\(containView)" + "\(toView)" + "123213123123123")
let frame = UIScreen.main.bounds
// ๅจ็ป่ฟ็จไธญๆดไธช่ๆฏๅพ
maskContentView = UIImageView(frame: frame)
maskContentView.backgroundColor = UIColor.white
if self.transitionType == .present {
maskContentView.frame = containView.bounds
containView.addSubview(self.maskContentView)
let currentFromImageView = self.fromImageView
let adjustFromRect = currentFromImageView?.convert((currentFromImageView?.bounds)!, to: containView)
let currentToImageView = self.toImageView!
let adjustToRect = currentToImageView.convert(currentToImageView.bounds, to: containView)
imageView = UIImageView(frame: adjustFromRect!)
imageView.image = currentFromImageView?.image
containView.addSubview(imageView)
imageView.layer.shadowColor = UIColor.black.cgColor
imageView.layer.shadowOffset = CGSize(width: 2.0, height: 2.0)
imageView.layer.shadowRadius = 10.0
// ็ปshadowOpacityไธไธชๅคงไบ้ป่ฎคๅผ(0)็ๅผ๏ผ้ดๅฝฑๅฐฑๅฏไปฅๆพ็คบๅจไปปๆๅพๅฑไนไธ
imageView.layer.shadowOpacity = 0.8
UIView.animate(withDuration: 0.5 , animations: {
self.imageView.frame = adjustToRect
self.imageView.transform = CGAffineTransform(scaleX: 1.2, y: 1.2)
}, completion: { (finish) in
UIView .animate(withDuration: 0.3, animations: {
self.imageView.transform = CGAffineTransform.identity
self.imageView.layer.shadowOpacity = 0.0
}, completion: { (finished) in
containView.addSubview(toView)
containView.bringSubview(toFront: self.imageView)
let adjustFrame = self.imageView.convert(self.imageView.bounds, to: self.maskContentView)
toView.maskFrom(adjustFrame, duration: 0.8 / 1.6 ,complete: {
self.maskContentView.removeFromSuperview()
self.imageView.removeFromSuperview()
self.maskContentView = nil
self.imageView = nil
transitionContext.completeTransition(true)
})
})
})
}else{
maskContentView.frame = containView.bounds
containView.addSubview(self.maskContentView)
let fromImageView = self.fromImageView
let toImageView = self.toImageView!
let adjustFromRect = fromImageView?.convert((fromImageView?.bounds)!, to: containView)
let adjustToRect = toImageView.convert(toImageView.bounds, to: containView)
imageView = UIImageView(frame:adjustToRect)
imageView.image = fromImageView?.image
containView.addSubview(imageView)
containView.bringSubview(toFront: self.imageView)
containView.sendSubview(toBack: maskContentView)
let adjustFrame = self.imageView.convert(self.imageView.bounds, to: self.maskContentView)
fromView.maskTo(adjustFrame, duration: 0.8 / 1.3 ,complete: {
self.imageView.layer.shadowColor = UIColor.black.cgColor
self.imageView.layer.shadowOffset = CGSize(width: 2.0, height: 2.0)
self.imageView.layer.shadowRadius = 10.0
self.imageView.layer.shadowOpacity = 0.8
UIView.animate(withDuration: 0.5 / 1.3, animations: {
self.imageView.frame = adjustFromRect!
}, completion: { (finished) in
self.maskContentView.removeFromSuperview()
self.imageView.removeFromSuperview()
self.maskContentView = nil
self.imageView = nil
self.toImageView = nil
containView.addSubview(toView)
transitionContext.completeTransition(true)
})
})
}
}
}
| mit | d3e530a827c488466261584bca141c99 | 44.276423 | 155 | 0.605136 | 5.365125 | false | false | false | false |
Webtrekk/webtrekk-ios-sdk | Source/Public/Events/ActionEvent.swift | 1 | 2014 | /// ActionEvent that expects:
///
/// - parameter actionProperties: action Properties
/// - parameter advertisementProperties: advertisement Properties
/// - parameter ecommerceProperties: ecommerce Properties
/// - parameter pageProperties: page Properties
/// - parameter userProperties: user Properties
/// - parameter ipAddress: IP Address
/// - parameter sessionDetails: session Details
/// - parameter variables: variables
public class ActionEvent: TrackingEventWithActionProperties,
TrackingEventWithAdvertisementProperties,
TrackingEventWithEcommerceProperties,
TrackingEventWithPageProperties,
TrackingEventWithSessionDetails,
TrackingEventWithUserProperties {
public var actionProperties: ActionProperties
public var advertisementProperties: AdvertisementProperties
public var ecommerceProperties: EcommerceProperties
public var ipAddress: String?
public var pageProperties: PageProperties
public var sessionDetails: [Int: TrackingValue]
public var userProperties: UserProperties
public var variables: [String: String]
public init(
actionProperties: ActionProperties = ActionProperties(),
pageProperties: PageProperties = PageProperties(),
advertisementProperties: AdvertisementProperties = AdvertisementProperties(),
ecommerceProperties: EcommerceProperties = EcommerceProperties(),
ipAddress: String? = nil,
sessionDetails: [Int: TrackingValue] = [:],
userProperties: UserProperties = UserProperties(),
variables: [String: String] = [:]
) {
self.actionProperties = actionProperties
self.advertisementProperties = advertisementProperties
self.ecommerceProperties = ecommerceProperties
self.pageProperties = pageProperties
self.sessionDetails = sessionDetails
self.userProperties = userProperties
self.variables = variables
}
}
| mit | 0577a0da72e0551c1703a48fa3319ef9 | 43.755556 | 85 | 0.718471 | 6.159021 | false | false | false | false |
lokinfey/MyPerfectframework | PerfectLib/LogManager.swift | 2 | 725 | //
// LogManager.swift
// PerfectLib
//
// Created by Kyle Jessup on 7/21/15.
// Copyright (C) 2015 PerfectlySoft, Inc.
//
//===----------------------------------------------------------------------===//
//
// This source file is part of the Perfect.org open source project
//
// Copyright (c) 2015 - 2016 PerfectlySoft Inc. and the Perfect project authors
// Licensed under Apache License v2.0
//
// See http://perfect.org/licensing.html for license information
//
//===----------------------------------------------------------------------===//
//
public class LogManager {
static func logMessage(msg: String) {
print(msg)
}
static func logMessageCode(msg: String, code: Int) {
print("\(msg) \(code)")
}
} | apache-2.0 | 657ea0bbb4961b3679a7cc5769f56a30 | 23.2 | 80 | 0.529655 | 4.289941 | false | false | false | false |
kcome/SwiftIB | HistoryDataDump/HistoryDataWrapper.swift | 1 | 7181 |
//
// HistoryDataWrapper.swift
// SwiftIB
//
// Created by Harry Li on 16/01/2015.
// Copyright (c) 2014-2019 Hanfei Li. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
// of the Software, and to permit persons to whom the Software is furnished to
// do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
import Foundation
import SwiftIB
class HistoryDataWrapper: EWrapper {
var contents: [String] = [String](repeating: "", count: 2000)
var extraSleep : Double = 0
var closing = false
var broken = false
var reqComplete = false
var currentStart: Int64 = -1
var sinceTS: Int64 = 0
var currentTicker = ""
var timezone = ""
init() {
}
// currently unused callbacks
func accountDownloadEnd(_ accountName: String){}
func tickPrice(_ tickerId: Int, field: Int, price: Double, canAutoExecute: Int) {}
func tickSize(_ tickerId: Int, field: Int, size: Int) {}
func tickGeneric(_ tickerId: Int, tickType: Int, value: Double) {}
func tickString(_ tickerId: Int, tickType: Int, value: String) {}
func tickOptionComputation(_ tickerId: Int, field: Int, impliedVol: Double, delta: Double, optPrice: Double, pvDividend: Double, gamma: Double, vega: Double, theta: Double, undPrice: Double) {}
func tickEFP(_ tickerId: Int, tickType: Int, basisPoints: Double,
formattedBasisPoints: String, impliedFuture: Double, holdDays: Int,
futureExpiry: String, dividendImpact: Double, dividendsToExpiry: Double){}
func orderStatus(_ orderId: Int, status: String, filled: Int, remaining: Int,
avgFillPrice: Double, permId: Int, parentId: Int, lastFillPrice: Double,
clientId: Int, whyHeld: String){}
func openOrder(_ orderId: Int, contract: Contract, order: Order, orderState: OrderState){}
func openOrderEnd(){}
func updateAccountValue(_ key: String, value: String, currency: String, accountName: String){}
func updatePortfolio(_ contract: Contract, position: Int, marketPrice: Double, marketValue: Double,
averageCost: Double, unrealizedPNL: Double, realizedPNL: Double, accountName: String){}
func updateAccountTime(_ timeStamp: String){}
func nextValidId(_ orderId: Int){}
func contractDetails(_ reqId: Int, contractDetails: ContractDetails){}
func bondContractDetails(_ reqId: Int, contractDetails: ContractDetails){}
func contractDetailsEnd(_ reqId: Int){}
func execDetails(_ reqId: Int, contract: Contract, execution: Execution){}
func execDetailsEnd(_ reqId: Int){}
func updateMktDepth(_ tickerId: Int, position: Int, operation: Int, side: Int, price: Double, size: Int){}
func updateMktDepthL2(_ tickerId: Int, position: Int, marketMaker: String, operation: Int,
side: Int, price: Double, size: Int){}
func updateNewsBulletin(_ msgId: Int, msgType: Int, message: String, origExchange: String){}
func managedAccounts(_ accountsList: String){}
func receiveFA(_ faDataType: Int, xml: String){}
func scannerParameters(_ xml: String){}
func scannerData(_ reqId: Int, rank: Int, contractDetails: ContractDetails, distance: String,
benchmark: String, projection: String, legsStr: String){}
func scannerDataEnd(_ reqId: Int){}
func realtimeBar(_ reqId: Int, time: Int64, open: Double, high: Double, low: Double, close: Double, volume: Int64, wap: Double, count: Int) {}
func currentTime(_ time: Int64){}
func fundamentalData(_ reqId: Int, data: String){}
func deltaNeutralValidation(_ reqId: Int, underComp: UnderComp){}
func tickSnapshotEnd(_ reqId: Int){}
func marketDataType(_ reqId: Int, marketDataType: Int){}
func commissionReport(_ commissionReport: CommissionReport){}
func position(_ account: String, contract: Contract, pos: Int, avgCost: Double){}
func positionEnd(){}
func accountSummary(_ reqId: Int, account: String, tag: String, value: String, currency: String){}
func accountSummaryEnd(_ reqId: Int){}
func verifyMessageAPI(_ apiData: String){}
func verifyCompleted(_ isSuccessful: Bool, errorText: String){}
func displayGroupList(_ reqId: Int, groups: String){}
func displayGroupUpdated(_ reqId: Int, contractInfo: String){}
// end of unused functinos
// error handling
func error(_ e: NSException) {}
func error(_ str: String) {
print("error: \(str)")
}
func error(_ id: Int, errorCode: Int, errorMsg:String) {
switch errorCode {
case 2106:
print("2106 [A historical data farm is connected]\n\tmsg:\(errorMsg)")
default:
print("error: id(\(id)) code(\(errorCode)) msg:\(errorMsg)")
}
if (errorMsg as NSString).range(of: ":Historical data request pacing violation").length > 0 && errorCode == 162 { // Historical Market Data Service error message:Historical data request pacing violation
self.extraSleep = 15.0
}
else if errorCode == 162 && ((errorMsg as NSString).range(of: "HMDS query returned no data:").length >= 0) {
print("NO DATA for ticker")
self.currentStart = self.sinceTS
self.reqComplete = true
}
}
func connectionClosed() {
if !self.closing {
self.broken = true
print("!!CONNECTION CLOSE")
}
}
func historicalData(_ reqId: Int, date: String, open: Double, high: Double, low: Double,
close: Double, volume: Int, count: Int, WAP: Double, hasGaps: Bool) {
var s = ""
if date.hasPrefix("finished-") {
print("\(self.currentTicker): \(date)")
self.reqComplete = true
} else {
let ts : Int64 = (date as NSString).longLongValue
if self.currentStart < 0 {
self.currentStart = ts
}
if ts < self.sinceTS {
return
}
let iHasGaps = hasGaps ? 1 : 0
s = "\(HDDUtil.tsToStr(timestamp: ts, api: false, tz_name: timezone))\t\(open)\t\(high)\t\(low)\t\(close)\t\(volume)\t\(count)\t\(WAP)\t\(iHasGaps)"
}
if !s.isEmpty {
s = s + "\n"
self.contents.insert(s, at: 0)
}
}
}
| mit | d4130eb4de2e273e5ac991ec548f56f3 | 48.524138 | 210 | 0.654923 | 4.221634 | false | false | false | false |
sheepy1/SelectionOfZhihu | SelectionOfZhihu/ArticleViewController.swift | 1 | 1758 | //
// ArticleViewController.swift
// SelectionOfZhihu
//
// Created by ๆจๆด on 16/1/10.
// Copyright ยฉ 2016ๅนด Sheepy. All rights reserved.
//
import UIKit
//enum ScrollDirection {
// case Up
// case Down
// case None
//}
class ArticleViewController: UIViewController {
@IBOutlet weak var webView: UIWebView!
@IBOutlet weak var loadingView: UIActivityIndicatorView!
var urlString: String!
//var oldY: CGFloat = 0
//var newY: CGFloat = 0
//var scrollDirection: ScrollDirection = .None
func loadUrl() {
let url = NSURL(string: urlString)
let request = NSURLRequest(URL: url!)
webView.loadRequest(request)
}
override func viewDidLoad() {
super.viewDidLoad()
loadUrl()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
navigationController?.setNavigationBarHidden(false, animated: animated)
}
}
extension ArticleViewController: UIWebViewDelegate {
func webViewDidStartLoad(webView: UIWebView) {
loadingView.startAnimating()
}
func webView(webView: UIWebView, didFailLoadWithError error: NSError?) {
loadingView.stopAnimating()
}
func webViewDidFinishLoad(webView: UIWebView) {
loadingView.stopAnimating()
}
}
//extension ArticleViewController: UIScrollViewDelegate {
// //ๅคๆญๅฝๅๆฏๅไธ่ฟๆฏๅไธๆปๅจ
// func scrollViewDidScroll(scrollView: UIScrollView) {
// newY = scrollView.contentOffset.y
// if newY > oldY {
// scrollDirection = .Up
// } else if oldY > newY {
// scrollDirection = .Down
// }
// oldY = newY
// }
//}
| mit | 122f580f0327444e112b681b974743ce | 22.310811 | 79 | 0.627246 | 4.791667 | false | false | false | false |
soso1617/iCalendar | Calendar/ViewControllers/Agenda/AgendaViewController.swift | 1 | 4968 | //
// AgendaViewController.swift
// Calendar
//
// Created by Zhang, Eric X. on 5/5/17.
// Copyright ยฉ 2017 ShangHe. All rights reserved.
//
import UIKit
/*********************************************************************
*
* class AgendaViewController
*
*********************************************************************/
class AgendaViewController: BaseTableViewController {
private let cellId = "CellId"
var sortedEvents: Array<Event>?
var day: Day? {
didSet
{
self.sortedEvents = self.day?.sortedEvents()
}
}
lazy var noDataView: UIView = {
[unowned self] in
let retView = UIView.init()
retView.frame = CGRect(x: 0, y: 0, width: self.view.bounds.width, height: self.view.bounds.height)
retView.autoresizingMask = [.flexibleTopMargin, .flexibleBottomMargin, .flexibleRightMargin, .flexibleLeftMargin]
//
// add nodata label on view
//
let noDataLabel = UILabel.init()
noDataLabel.font = UIFont.icFont5
noDataLabel.text = "No_Event".localized
noDataLabel.textColor = UIColor.icPinkish
noDataLabel.backgroundColor = UIColor.clear
noDataLabel.textAlignment = .center
noDataLabel.frame = retView.bounds
noDataLabel.autoresizingMask = [.flexibleTopMargin, .flexibleBottomMargin, .flexibleRightMargin, .flexibleLeftMargin]
retView.addSubview(noDataLabel)
return retView
}()
convenience init() {
self.init(nibName: nil, bundle: nil)
}
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}
init(day: Day) {
self.day = day
self.sortedEvents = self.day?.sortedEvents()
super.init(style: .plain)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func initialFromLoad() {
self.tableView.backgroundColor = UIColor.icWhite
self.tableView.tableFooterView = UIView.init(frame: CGRect.zero) // set this for remove separator in empty cell
self.tableView.separatorStyle = .singleLine
self.tableView.separatorColor = UIColor.icSeparator
//
// register cell
//
self.tableView.register(AgendaTableViewCell.classForCoder(), forCellReuseIdentifier: self.cellId)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func setNewDayAndReload(_ day: Day) {
self.day = day
self.tableView.reloadData()
//
// show no data
//
if self.sortedEvents?.count ?? 0 > 0
{
self.noDataView.removeFromSuperview()
}
else
{
self.noDataView.frame = CGRect(x: 0, y: 0, width: self.view.bounds.width, height: self.view.bounds.height)
self.tableView.addSubview(self.noDataView)
}
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
//
// MARK: TableView Delegate
//
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.sortedEvents?.count ?? 0
}
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let retCell = tableView.dequeueReusableCell(withIdentifier: self.cellId) as! AgendaTableViewCell
if let event = self.sortedEvents?[indexPath.row]
{
retCell.setEvent(event, selectedDay: self.day!, isFirst: indexPath.row == 0, isLast: indexPath.row == self.sortedEvents!.count - 1)
}
return retCell
}
//
// auto height
//
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableViewAutomaticDimension
}
//
// auto height
//
override func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableViewAutomaticDimension
}
}
| mit | a78eed464e6ceef54e3632776b17c880 | 28.046784 | 143 | 0.591705 | 5.217437 | false | false | false | false |
VirgilSecurity/virgil-sdk-keys-x | Source/Keyknox/SyncKeyStorage/SyncKeyStorage.swift | 2 | 15848 | //
// Copyright (C) 2015-2021 Virgil Security Inc.
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// (1) Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// (2) Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in
// the documentation and/or other materials provided with the
// distribution.
//
// (3) Neither the name of the copyright holder nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE AUTHOR ''AS IS'' AND ANY EXPRESS OR
// IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT,
// INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
// IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//
// Lead Maintainer: Virgil Security Inc. <[email protected]>
//
import Foundation
import VirgilCrypto
/// Class responsible for synchronization between Keychain and Keyknox Cloud
@objc(VSSSyncKeyStorage) open class SyncKeyStorage: NSObject {
/// CloudKeyStorageProtocol implementation
public let cloudKeyStorage: CloudKeyStorageProtocol
internal let keychainStorage: KeychainStorageProtocol
internal let keychainUtils: KeychainUtils
private let queue = DispatchQueue(label: "SyncKeyStorageQueue")
/// Creates local key storage instance, to read keys withoud connecting to the Cloud
///
/// - Parameters:
/// - identity: User's identity to separate keys in Keychain
/// - keychainStorage: KeychainStorageProtocol implementation
/// - Returns: returns KeychainStorageProtocol
public static func makeLocalStorage(identity: String,
keychainStorage: KeychainStorageProtocol) -> KeychainStorageProtocol {
return SandboxedKeychainStorage(identity: identity, keychainStorage: keychainStorage)
}
/// Init
///
/// - Parameters:
/// - identity: User's identity to separate keys in Keychain
/// - keychainStorage: KeychainStorageProtocol implementation
/// - cloudKeyStorage: CloudKeyStorageProtocol implementation
public init(identity: String, keychainStorage: KeychainStorageProtocol,
cloudKeyStorage: CloudKeyStorageProtocol) {
self.keychainStorage = SandboxedKeychainStorage(identity: identity, keychainStorage: keychainStorage)
self.cloudKeyStorage = cloudKeyStorage
self.keychainUtils = KeychainUtils()
super.init()
}
/// Init
///
/// - Parameters:
/// - identity: User's identity to separate keys in Keychain
/// - cloudKeyStorage: CloudKeyStorageProtocol implementation
/// - Throws: Rethrows from `KeychainStorageParams`
@objc public convenience init(identity: String, cloudKeyStorage: CloudKeyStorage) throws {
let configuration = try KeychainStorageParams.makeKeychainStorageParams()
let keychainStorage = KeychainStorage(storageParams: configuration)
self.init(identity: identity, keychainStorage: keychainStorage, cloudKeyStorage: cloudKeyStorage)
}
/// Init
///
/// - Parameters:
/// - identity: User's identity to separate keys in Keychain
/// - crypto: Crypto
/// - accessTokenProvider: AccessTokenProvider implementation
/// - publicKeys: Public keys used for encryption and signature verification
/// - privateKey: Private key used for decryption and signature generation
/// - Throws: Rethrows from `CloudKeyStorage` and `KeychainStorageParams`
@objc public convenience init(identity: String, accessTokenProvider: AccessTokenProvider,
crypto: VirgilCrypto,
publicKeys: [VirgilPublicKey], privateKey: VirgilPrivateKey) throws {
let cloudKeyStorage = try CloudKeyStorage(accessTokenProvider: accessTokenProvider,
crypto: crypto,
publicKeys: publicKeys,
privateKey: privateKey)
try self.init(identity: identity, cloudKeyStorage: cloudKeyStorage)
}
}
// MARK: - Extension with Queries
extension SyncKeyStorage {
/// Updates entry in Keyknox Cloud and Keychain
///
/// - Parameters:
/// - name: Name
/// - data: New data
/// - meta: New meta
/// - Returns: GenericOperation<Void>
open func updateEntry(withName name: String, data: Data, meta: [String: String]?) -> GenericOperation<Void> {
return CallbackOperation { _, completion in
self.queue.async {
do {
guard try self.keychainStorage.existsEntry(withName: name) else {
throw SyncKeyStorageError.keychainEntryNotFoundWhileUpdating
}
do {
_ = try self.cloudKeyStorage.existsEntry(withName: name)
}
catch {
throw SyncKeyStorageError.cloudEntryNotFoundWhileUpdating
}
let cloudEntry = try self.cloudKeyStorage.updateEntry(withName: name,
data: data,
meta: meta)
.startSync()
.get()
let meta = try self.keychainUtils.createMetaForKeychain(from: cloudEntry)
try self.keychainStorage.updateEntry(withName: name, data: data, meta: meta)
completion((), nil)
}
catch {
completion(nil, error)
}
}
}
}
/// Retrieves entry from Keychain
///
/// - Parameter name: Name
/// - Returns: KeychainEntry
/// - Throws: Rethrows from `KeychainStorage`
@objc open func retrieveEntry(withName name: String) throws -> KeychainEntry {
return try self.keychainStorage.retrieveEntry(withName: name)
}
/// Deletes entries from both Keychain and Keyknox Cloud
///
/// - Parameter names: Names to delete
/// - Returns: GenericOperation<Void>
open func deleteEntries(withNames names: [String]) -> GenericOperation<Void> {
return CallbackOperation { _, completion in
self.queue.async {
do {
for name in names {
guard try self.cloudKeyStorage.existsEntry(withName: name) else {
throw SyncKeyStorageError.cloudEntryNotFoundWhileDeleting
}
}
_ = try self.cloudKeyStorage.deleteEntries(withNames: names).startSync().get()
for name in names {
_ = try self.keychainStorage.deleteEntry(withName: name)
}
completion((), nil)
}
catch {
completion(nil, error)
}
}
}
}
/// Deletes entry from both Keychain and Keyknox Cloud
///
/// - Parameter name: Name
/// - Returns: GenericOperation<Void>
open func deleteEntry(withName name: String) -> GenericOperation<Void> {
return self.deleteEntries(withNames: [name])
}
/// Stores entry in both Keychain and Keyknox Cloud
///
/// - Parameters:
/// - name: Name
/// - data: Data
/// - meta: Meta
/// - Returns: GenericOperation<KeychainEntry>
open func storeEntry(withName name: String, data: Data,
meta: [String: String]? = nil) -> GenericOperation<KeychainEntry> {
return CallbackOperation { _, completion in
self.queue.async {
do {
let entry = KeyknoxKeyEntry(name: name, data: data, meta: meta)
let keychainEntries = try self.storeEntriesSync([entry])
guard keychainEntries.count == 1, let keychainEntry = keychainEntries.first else {
throw SyncKeyStorageError.entrySavingError
}
completion(keychainEntry, nil)
}
catch {
completion(nil, error)
}
}
}
}
/// Stores entries in both Keychain and Keyknox Cloud
///
/// - Parameter keyEntries: Key entries to store
/// - Returns: GenericOperation<[KeychainEntry]>
open func storeEntries(_ keyEntries: [KeyknoxKeyEntry]) -> GenericOperation<[KeychainEntry]> {
return CallbackOperation { _, completion in
self.queue.async {
do {
completion(try self.storeEntriesSync(keyEntries), nil)
}
catch {
completion(nil, error)
}
}
}
}
private func storeEntriesSync(_ keyEntries: [KeyknoxKeyEntry]) throws -> [KeychainEntry] {
for keyEntry in keyEntries {
guard !(try self.keychainStorage.existsEntry(withName: keyEntry.name)) else {
throw SyncKeyStorageError.keychainEntryAlreadyExistsWhileStoring
}
guard !(try self.cloudKeyStorage.existsEntry(withName: keyEntry.name)) else {
throw SyncKeyStorageError.cloudEntryAlreadyExistsWhileStoring
}
}
let cloudEntries = try self.cloudKeyStorage.storeEntries(keyEntries).startSync().get()
var keychainEntries = [KeychainEntry]()
for entry in zip(keyEntries, cloudEntries) {
guard entry.0.name == entry.1.name else {
throw SyncKeyStorageError.inconsistentStateError
}
let meta = try self.keychainUtils.createMetaForKeychain(from: entry.1)
let keychainEntry = try self.keychainStorage.store(data: entry.0.data,
withName: entry.0.name,
meta: meta)
keychainEntries.append(keychainEntry)
}
return keychainEntries
}
/// Performs synchronization between Keychain and Keyknox Cloud
///
/// - Returns: GenericOperation<Void>
open func sync() -> GenericOperation<Void> {
return CallbackOperation { _, completion in
self.queue.async {
let retrieveCloudEntriesOperation = self.cloudKeyStorage.retrieveCloudEntries()
let retrieveKeychainEntriesOperation = CallbackOperation<[KeychainEntry]> { _, completion in
do {
let keychainEntries = try self.keychainStorage.retrieveAllEntries()
.compactMap(self.keychainUtils.filterKeyknoxKeychainEntry)
completion(keychainEntries, nil)
}
catch {
completion(nil, error)
}
}
let syncOperation = CallbackOperation<Void> { operation, completion in
do {
let keychainEntries: [KeychainEntry] = try operation.findDependencyResult()
let keychainSet = Set<String>(keychainEntries.map { $0.name })
let cloudSet = Set<String>(try self.cloudKeyStorage.retrieveAllEntries().map { $0.name })
let entriesToDelete = [String](keychainSet.subtracting(cloudSet))
let entriesToStore = [String](cloudSet.subtracting(keychainSet))
let entriesToCompare = [String](keychainSet.intersection(cloudSet))
try self.syncDeleteEntries(entriesToDelete)
try self.syncStoreEntries(entriesToStore)
try self.syncCompareEntries(entriesToCompare, keychainEntries: keychainEntries)
completion((), nil)
}
catch {
completion(nil, error)
}
}
syncOperation.addDependency(retrieveCloudEntriesOperation)
syncOperation.addDependency(retrieveKeychainEntriesOperation)
let operations = [
retrieveCloudEntriesOperation,
retrieveKeychainEntriesOperation,
syncOperation
]
let completionOperation = OperationUtils.makeCompletionOperation(completion: completion)
operations.forEach {
completionOperation.addDependency($0)
}
let queue = OperationQueue()
queue.addOperations(operations + [completionOperation], waitUntilFinished: true)
}
}
}
/// Updates recipients. See KeyknoxManager.updateRecipients
///
/// - Parameters:
/// - newPublicKeys: New public keys
/// - newPrivateKey: New private key
/// - Returns: GenericOperation<Void>
open func updateRecipients(newPublicKeys: [VirgilPublicKey]? = nil,
newPrivateKey: VirgilPrivateKey? = nil) -> GenericOperation<Void> {
return self.cloudKeyStorage.updateRecipients(newPublicKeys: newPublicKeys,
newPrivateKey: newPrivateKey)
}
/// Retrieves all entries from Keychain
///
/// - Returns: Keychain entries
/// - Throws: Rethrows from `KeychainStorage`
open func retrieveAllEntries() throws -> [KeychainEntry] {
return try self.keychainStorage.retrieveAllEntries().compactMap(self.keychainUtils.filterKeyknoxKeychainEntry)
}
/// Checks if entry exists in Keychain
///
/// - Parameter name: Entry name
/// - Returns: true if entry exists, false otherwise
/// - Throws: Rethrows from `KeychainStorage`
open func existsEntry(withName name: String) throws -> Bool {
return try self.keychainStorage.existsEntry(withName: name)
}
/// Deletes all entries in both Keychain and Keyknox Cloud
///
/// - Returns: GenericOperation<Void>
open func deleteAllEntries() -> GenericOperation<Void> {
return CallbackOperation { _, completion in
self.queue.async {
do {
_ = try self.cloudKeyStorage.deleteAllEntries().startSync().get()
let entriesToDelete = try self.keychainStorage.retrieveAllEntries()
.compactMap(self.keychainUtils.filterKeyknoxKeychainEntry)
.map { $0.name }
try self.syncDeleteEntries(entriesToDelete)
completion((), nil)
}
catch {
completion(nil, error)
}
}
}
}
}
| bsd-3-clause | f79c41901d96a4acffcbf2f51697d6ba | 40.056995 | 118 | 0.589854 | 5.832904 | false | false | false | false |
QuarkX/Quark | Sources/Quark/HTTP/Parser/Parser.swift | 1 | 1995 | import CHTTPParser
typealias Parser = UnsafeMutablePointer<http_parser>
extension http_errno : Error, CustomStringConvertible {
public var description: String {
return String(cString: http_errno_description(self))
}
}
extension Method {
init(code: Int) {
switch code {
case 00: self = .delete
case 01: self = .get
case 02: self = .head
case 03: self = .post
case 04: self = .put
case 05: self = .connect
case 06: self = .options
case 07: self = .trace
case 08: self = .other(method: "COPY")
case 09: self = .other(method: "LOCK")
case 10: self = .other(method: "MKCOL")
case 11: self = .other(method: "MOVE")
case 12: self = .other(method: "PROPFIND")
case 13: self = .other(method: "PROPPATCH")
case 14: self = .other(method: "SEARCH")
case 15: self = .other(method: "UNLOCK")
case 16: self = .other(method: "BIND")
case 17: self = .other(method: "REBIND")
case 18: self = .other(method: "UNBIND")
case 19: self = .other(method: "ACL")
case 20: self = .other(method: "REPORT")
case 21: self = .other(method: "MKACTIVITY")
case 22: self = .other(method: "CHECKOUT")
case 23: self = .other(method: "MERGE")
case 24: self = .other(method: "M-SEARCH")
case 25: self = .other(method: "NOTIFY")
case 26: self = .other(method: "SUBSCRIBE")
case 27: self = .other(method: "UNSUBSCRIBE")
case 28: self = .patch
case 29: self = .other(method: "PURGE")
case 30: self = .other(method: "MKCALENDAR")
case 31: self = .other(method: "LINK")
case 32: self = .other(method: "UNLINK")
default: self = .other(method: "UNKNOWN")
}
}
}
extension UnsafeMutablePointer {
func withPointee<R>(_ body: (_ pointer: inout Pointee) throws -> R) rethrows -> R {
return try body(&pointee)
}
}
| mit | d90ed46059a0c3f6c814533a0b492a52 | 34.625 | 87 | 0.569424 | 3.708178 | false | false | false | false |
onevcat/CotEditor | CotEditor/Sources/ShareMenuItem.swift | 2 | 2500 | //
// ShareMenuItem.swift
//
// CotEditor
// https://coteditor.com
//
// Created by 1024jp on 2021-07-10.
//
// ---------------------------------------------------------------------------
//
// ยฉ 2021 1024jp
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import AppKit
final class ShareMenuItem: NSMenuItem {
// MARK: Public Properties
var sharingItems: [Any]? { didSet { self.updateSubmenu() } }
// MARK: -
// MARK: Menu Item Methods
override func awakeFromNib() {
super.awakeFromNib()
self.title = "Share".localized
self.submenu = NSMenu(title: "Share".localized)
}
// MARK: Private Methods
private struct SharingServiceContainer {
var service: NSSharingService
var items: [Any]
}
private func updateSubmenu() {
defer {
// defer the operation to apply it _after_ the auto validation in the pop up button has done. (2021-07 on macOS 11)
DispatchQueue.main.async { [weak self] in
self?.isEnabled = self?.sharingItems != nil
}
}
guard let items = self.sharingItems else { return }
self.submenu?.items = NSSharingService.sharingServices(forItems: items).map { service in
let item = NSMenuItem(title: service.menuItemTitle, action: #selector(openSharingService), keyEquivalent: "")
item.image = service.image
item.representedObject = SharingServiceContainer(service: service, items: items)
item.target = self
return item
}
}
@objc private func openSharingService(sender: NSMenuItem) {
guard let container = sender.representedObject as? SharingServiceContainer else { return assertionFailure() }
container.service.perform(withItems: container.items)
}
}
| apache-2.0 | 4223dc16fc9553e0868fe0a44d6902f7 | 27.724138 | 127 | 0.597039 | 4.778203 | false | false | false | false |
xipengyang/SwiftApp1 | Cat Years/Cat Years/ViewController.swift | 1 | 996 | //
// ViewController.swift
// Cat Years
//
// Created by xipeng yang on 11/01/15.
// Copyright (c) 2015 xipeng yang. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var ageInput: UITextField!
@IBOutlet weak var ageOutput: UILabel!
@IBAction func findByAgePressed(sender: AnyObject) {
println(ageInput.text)
var enteredAge = ageInput.text.toInt()
if enteredAge != nil {
var catYears = enteredAge! * 7
ageOutput.text = "Your cat is \(catYears)"
} else {
ageOutput.text = "Please enter a whole number"
}
}
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.
}
}
| mit | 1e2ab7147b76826436451a06f17e2c6d | 21.636364 | 80 | 0.604418 | 4.486486 | false | false | false | false |
practicalswift/swift | test/refactoring/SyntacticRename/functions.swift | 40 | 11127 | import func SomeModule . /*import*/someFunc
func /*no-args:def*/aFunc() -> Int {
return 1
}
func /*param-label:def*/aFunc(a: Int) {}
func /*arg-label:def*/aFunc(b a:Int) {}
func /*no-label:def*/aFunc(_ b:Int) -> Int {
return /*no-args:call*/aFunc()
}
func /*whitespace-labels:def*/aFunc( a b: Int ,_ a: Int, c c : Int) {}
func /*referenced:def*/bar(a: Int) {}
func /*varargs:def*/aFunc(c: Int...) {}
/*varargs:call*/aFunc(c: 1, 2, 3, 4)
class AStruct {
func /*method:def*/foo(a: Int, b: Int, _ c: Int) -> Int {
return a + b + c
}
func /*bar:def*/bar(_ a: Int) -> (Int) -> Int {
return {a in a};
}
static func /*infix-operator:def*/+ (left: AStruct, right: AStruct) -> AStruct {
return AStruct()
}
static prefix func /*prefix-operator:def*/- (struct: AStruct) -> AStruct {
return AStruct()
}
}
let aStruct = /*prefix-operator:call*/-AStruct() /*infix-operator:call*/+ AStruct()
/*no-args:call*/aFunc()
/*param-label:call*/aFunc(a: 2)
/*arg-label:call*/aFunc(b: /*no-args:call*/aFunc() * /*no-args:call*/aFunc())
let _ = /*no-label:call*/aFunc(3)
/*whitespace-labels:call*/aFunc( a : 2 ,2, c: 4 )
let _ = aStruct . /*method:call*/foo(a: 2, b: 3, 1)
let _ = AStruct . /*method*/foo(aStruct)(a: 1, b: 8, 10)
let _ = aStruct . /*bar:call*/bar(/*no-args:call*/aFunc())(/*no-label:call*/aFunc(2))
var a = /*referenced*/bar
var b = /*referenced*/bar(a:)
let _ = "Some text \(/*param-label:call*/aFunc(a:1)) around"
class SomeClass {
init() {}
/*init:def*/init(a: Int, b:Int, c:Int) {}
/*sub:def*/subscript(x: Int, y j: Int) -> Int {
get { return 1 }
set {}
}
}
let someClass = SomeClass();
let _ = /*init:call*/SomeClass(a:1, b:1, c:1)
let _ = SomeClass . /*init*/init(a:b:c:)
_ = someClass/*sub:ref*/[1, y: 2]
someClass/*sub:ref*/[1, y: 2] = 2
class AnotherClass {
let bar = AnotherClass()
func /*nested:def*/foo(a: Int) -> AnotherClass {}
}
AnotherClass() . /*nested:call*/foo(a: 1) . /*nested2*/bar . /*nested2*/bar . /*nested:call*/foo(a: 2) . /*nested:call*/foo(a: 3) . /*nested:unknown*/foo . foo(a: 4)
struct Memberwise {
let /*memberwise-x:def*/x: Int
let y: Int = 0
var z: Int = 2
}
_ = Memberwise(/*memberwise-x:ref*/x: 1, z: 3)
let memberwise = Memberwise.init(/*memberwise-x:ref*/x:z:)
_ = memberwise . /*memberwise-x:ref*/x
// RUN: %empty-directory(%t.result)
// RUN: %refactor -syntactic-rename -source-filename %s -pos="bar" -is-function-like -old-name "bar(_:)" -new-name "barb(first:)" >> %t.result/functions_bar.swift
// RUN: diff -u %S/Outputs/functions/bar.swift.expected %t.result/functions_bar.swift
// RUN: %refactor -syntactic-rename -source-filename %s -pos="no-args" -is-function-like -old-name "aFunc" -new-name "anotherFunc" >> %t.result/functions_no-args.swift
// RUN: diff -u %S/Outputs/functions/no-args.swift.expected %t.result/functions_no-args.swift
// RUN: %refactor -syntactic-rename -source-filename %s -pos="param-label" -is-function-like -old-name "aFunc(a:)" -new-name "anotherFunc(param:)" >> %t.result/functions_param-label.swift
// RUN: diff -u %S/Outputs/functions/param-label.swift.expected %t.result/functions_param-label.swift
// RUN: %refactor -syntactic-rename -source-filename %s -pos="param-label" -is-function-like -old-name "aFunc(a:)" -new-name "aFunc(_:)" >> %t.result/functions_param-label_remove.swift
// RUN: diff -u %S/Outputs/functions/param-label_remove.swift.expected %t.result/functions_param-label_remove.swift
// RUN: %refactor -syntactic-rename -source-filename %s -pos="arg-label" -is-function-like -old-name "aFunc(b:)" -new-name "anotherFunc(c:)" >> %t.result/functions_arg-label.swift
// RUN: diff -u %S/Outputs/functions/arg-label.swift.expected %t.result/functions_arg-label.swift
// RUN: %refactor -syntactic-rename -source-filename %s -pos="arg-label" -is-function-like -old-name "aFunc(b:)" -new-name "aFunc(a:)" >> %t.result/functions_arg-label_same.swift
// RUN: diff -u %S/Outputs/functions/arg-label_same.swift.expected %t.result/functions_arg-label_same.swift
// RUN: %refactor -syntactic-rename -source-filename %s -pos="arg-label" -is-function-like -old-name "aFunc(b:)" -new-name "aFunc(_:)" >> %t.result/functions_arg-label_remove.swift
// RUN: diff -u %S/Outputs/functions/arg-label_remove.swift.expected %t.result/functions_arg-label_remove.swift
// RUN: %refactor -syntactic-rename -source-filename %s -pos="no-label" -is-function-like -old-name "aFunc(_:)" -new-name "aFunc2(aLabel:)" >> %t.result/functions_no-label.swift
// RUN: diff -u %S/Outputs/functions/no-label.swift.expected %t.result/functions_no-label.swift
// RUN: %refactor -syntactic-rename -source-filename %s -pos="no-label" -is-function-like -old-name "aFunc(_:)" -new-name "aFunc(b:)" >> %t.result/functions_no-label_same.swift
// RUN: diff -u %S/Outputs/functions/no-label_same.swift.expected %t.result/functions_no-label_same.swift
// RUN: %refactor -syntactic-rename -source-filename %s -pos="whitespace-labels" -is-function-like -old-name "aFunc(a:_:c:)" -new-name "aFunc(c:b:d:)" >> %t.result/functions_whitespace-labels.swift
// RUN: diff -u %S/Outputs/functions/whitespace-labels.swift.expected %t.result/functions_whitespace-labels.swift
// RUN: %refactor -syntactic-rename -source-filename %s -pos="referenced" -is-function-like -old-name "bar(a:)" -new-name "bah(b:)" >> %t.result/functions_referenced.swift
// RUN: diff -u %S/Outputs/functions/referenced.swift.expected %t.result/functions_referenced.swift
// RUN: %refactor -syntactic-rename -source-filename %s -pos="method" -is-function-like -old-name "foo(a:b:_:)" -new-name "myMethod(_:second:do:)" >> %t.result/functions_method.swift
// RUN: diff -u %S/Outputs/functions/method.swift.expected %t.result/functions_method.swift
// RUN: %refactor -syntactic-rename -source-filename %s -pos="infix-operator" -is-function-like -old-name "+(left:right:)" -new-name "-(left:right:)" >> %t.result/functions_infix-operator.swift
// RUN: diff -u %S/Outputs/functions/infix-operator.swift.expected %t.result/functions_infix-operator.swift
// RUN: %refactor -syntactic-rename -source-filename %s -pos="prefix-operator" -is-function-like -old-name "-(struct:)" -new-name "+(theStruct:)" >> %t.result/functions_prefix-operator.swift
// RUN: diff -u %S/Outputs/functions/prefix-operator.swift.expected %t.result/functions_prefix-operator.swift
// RUN: %refactor -syntactic-rename -source-filename %s -pos="init" -is-function-like -old-name "init(a:b:c:)" -new-name "init(_:d:e:)" >> %t.result/functions_init.swift
// RUN: diff -u %S/Outputs/functions/init.swift.expected %t.result/functions_init.swift
// RUN: %refactor -syntactic-rename -source-filename %s -pos="varargs" -is-function-like -old-name "aFunc(c:)" -new-name "aFunc(_:)" >> %t.result/functions_varargs.swift
// RUN: diff -u %S/Outputs/functions/varargs.swift.expected %t.result/functions_varargs.swift
// RUN: %refactor -syntactic-rename -source-filename %s -pos="import" -is-function-like -old-name "someFunc(a:)" -new-name "otherFunc(_:)" >> %t.result/functions_import.swift
// RUN: diff -u %S/Outputs/functions/import.swift.expected %t.result/functions_import.swift
// RUN: %refactor -syntactic-rename -source-filename %s -pos="nested" -is-function-like -old-name "foo(a:)" -new-name "bar(b:)" >> %t.result/functions_nested.swift
// RUN: diff -u %S/Outputs/functions/nested.swift.expected %t.result/functions_nested.swift
// RUN: %refactor -syntactic-rename -source-filename %s -pos="sub" -is-function-like -old-name "subscript(_:y:)" -new-name "subscript(x:j:)" >> %t.result/functions_sub.swift
// RUN: diff -u %S/Outputs/functions/sub.swift.expected %t.result/functions_sub.swift
// RUN: %refactor -syntactic-rename -source-filename %s -pos="memberwise-x" -old-name "x" -new-name "new_x" >> %t.result/functions_memberwise-x.swift
// RUN: diff -u %S/Outputs/functions/memberwise-x.swift.expected %t.result/functions_memberwise-x.swift
// RUN: %empty-directory(%t.ranges)
// RUN: %refactor -find-rename-ranges -source-filename %s -pos="bar" -is-function-like -old-name "bar(_:)" >> %t.ranges/functions_bar.swift
// RUN: diff -u %S/FindRangeOutputs/functions/bar.swift.expected %t.ranges/functions_bar.swift
// RUN: %refactor -find-rename-ranges -source-filename %s -pos="no-args" -is-function-like -old-name "aFunc" >> %t.ranges/functions_no-args.swift
// RUN: diff -u %S/FindRangeOutputs/functions/no-args.swift.expected %t.ranges/functions_no-args.swift
// RUN: %refactor -find-rename-ranges -source-filename %s -pos="param-label" -is-function-like -old-name "aFunc(a:)" >> %t.ranges/functions_param-label.swift
// RUN: diff -u %S/FindRangeOutputs/functions/param-label.swift.expected %t.ranges/functions_param-label.swift
// RUN: %refactor -find-rename-ranges -source-filename %s -pos="arg-label" -is-function-like -old-name "aFunc(b:)" >> %t.ranges/functions_arg-label.swift
// RUN: diff -u %S/FindRangeOutputs/functions/arg-label.swift.expected %t.ranges/functions_arg-label.swift
// RUN: %refactor -find-rename-ranges -source-filename %s -pos="whitespace-labels" -is-function-like -old-name "aFunc(a:_:c:)" >> %t.ranges/functions_whitespace-labels.swift
// RUN: diff -u %S/FindRangeOutputs/functions/whitespace-labels.swift.expected %t.ranges/functions_whitespace-labels.swift
// RUN: %refactor -find-rename-ranges -source-filename %s -pos="referenced" -is-function-like -old-name "bar(a:)" >> %t.ranges/functions_referenced.swift
// RUN: diff -u %S/FindRangeOutputs/functions/referenced.swift.expected %t.ranges/functions_referenced.swift
// RUN: %refactor -find-rename-ranges -source-filename %s -pos="method" -is-function-like -old-name "foo(a:b:_:)" >> %t.ranges/functions_method.swift
// RUN: diff -u %S/FindRangeOutputs/functions/method.swift.expected %t.ranges/functions_method.swift
// RUN: %refactor -find-rename-ranges -source-filename %s -pos="infix-operator" -is-function-like -old-name "+(left:right:)" >> %t.ranges/functions_infix-operator.swift
// RUN: diff -u %S/FindRangeOutputs/functions/infix-operator.swift.expected %t.ranges/functions_infix-operator.swift
// RUN: %refactor -find-rename-ranges -source-filename %s -pos="prefix-operator" -is-function-like -old-name "-(struct:)" >> %t.ranges/functions_prefix-operator.swift
// RUN: diff -u %S/FindRangeOutputs/functions/prefix-operator.swift.expected %t.ranges/functions_prefix-operator.swift
// RUN: %refactor -find-rename-ranges -source-filename %s -pos="init" -is-function-like -old-name "init(a:b:c:)" >> %t.ranges/functions_init.swift
// RUN: diff -u %S/FindRangeOutputs/functions/init.swift.expected %t.ranges/functions_init.swift
// RUN: %refactor -find-rename-ranges -source-filename %s -pos="sub" -is-function-like -old-name "subscript(_:y:)" >> %t.ranges/functions_sub.swift
// RUN: diff -u %S/FindRangeOutputs/functions/sub.swift.expected %t.ranges/functions_sub.swift
// RUN: %refactor -find-rename-ranges -source-filename %s -pos="memberwise-x" -old-name "x" >> %t.ranges/functions_memberwise-x.swift
// RUN: diff -u %S/FindRangeOutputs/functions/memberwise-x.swift.expected %t.ranges/functions_memberwise-x.swift
| apache-2.0 | 4839414b8a3a48c4f5294aa87fbc7158 | 72.688742 | 197 | 0.698301 | 3.011367 | false | false | false | false |
morganabel/cordova-plugin-audio-playlist | src/ios/Jukebox.swift | 1 | 20337 | //
// Jukebox.swift
//
// Copyright (c) 2015 Teodor Patraล
//
// 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 AVFoundation
import MediaPlayer
// MARK: - Custom types -
public protocol JukeboxDelegate: class {
func jukeboxStateDidChange(_ jukebox : Jukebox)
func jukeboxTrackChange(_ jukebox : Jukebox)
func jukeboxPlaybackProgressDidChange(_ jukebox : Jukebox)
func jukeboxDidLoadItem(_ jukebox : Jukebox, item : JukeboxItem)
func jukeboxDidUpdateMetadata(_ jukebox : Jukebox, forItem: JukeboxItem)
func jukeboxError(_ jukebox : Jukebox, item: JukeboxItem)
}
// MARK: - Public methods extension -
extension Jukebox {
/**
Starts item playback.
*/
public func play() {
play(atIndex: playIndex)
}
/**
Plays the item indicated by the passed index
- parameter index: index of the item to be played
*/
public func play(atIndex index: Int) {
guard index < queuedItems.count && index >= 0 else {
if queuedItems.count > 0 && autoLoop {
replay()
}
return
}
configureBackgroundAudioTask()
if queuedItems[index].playerItem != nil && playIndex == index {
resumePlayback()
} else {
if let item = currentItem?.playerItem {
unregisterForPlayToEndNotification(withItem: item)
}
playIndex = index
if let asset = queuedItems[index].playerItem?.asset {
playCurrentItem(withAsset: asset)
} else {
loadPlaybackItem()
}
delegate?.jukeboxTrackChange(self)
preloadNextAndPrevious(atIndex: playIndex)
}
updateInfoCenter()
}
/**
Pauses the playback.
*/
public func pause() {
stopProgressTimer()
player?.pause()
state = .paused
}
/**
Stops the playback.
*/
public func stop() {
invalidatePlayback()
state = .ready
UIApplication.shared.endBackgroundTask(backgroundIdentifier)
backgroundIdentifier = UIBackgroundTaskInvalid
endBackgroundTask()
}
/**
Starts playback from the beginning of the queue.
*/
public func replay() {
guard playerOperational else {return}
stopProgressTimer()
seek(toSecond: 0)
play(atIndex: 0)
}
public func setAutoLoop(shouldAutoLoop shouldLoop: Bool) {
autoLoop = shouldLoop
}
/**
Plays the next item in the queue.
*/
public func playNext() {
guard playerOperational else {return}
play(atIndex: playIndex + 1)
}
/**
Restarts the current item or plays the previous item in the queue
*/
public func playPrevious() {
guard playerOperational else {return}
play(atIndex: playIndex - 1)
}
/**
Restarts the playback for the current item
*/
public func replayCurrentItem() {
guard playerOperational else {return}
seek(toSecond: 0, shouldPlay: true)
}
/**
Checks if the current track is the last track.
*/
public func isLastTrack() -> Bool {
if playIndex >= queuedItems.count - 1 {
return true
} else {
return false
}
}
/**
Checks if playlist currently empty.
*/
public func isEmpty() -> Bool {
if (queuedItems != nil && queuedItems.count > 0) {
return false
} else {
return true
}
}
public func getPlayIndex() -> Int {
return playIndex
}
public func getTotalTrackCount() -> Int {
return queuedItems.count
}
/**
Seeks to a certain second within the current AVPlayerItem and starts playing
- parameter second: the second to seek to
- parameter shouldPlay: pass true if playback should be resumed after seeking
*/
public func seek(toSecond second: Int, shouldPlay: Bool = false) {
guard let player = player, let item = currentItem else {return}
player.seek(to: CMTimeMake(Int64(second), 1))
item.update()
if shouldPlay {
if #available(iOS 10.0, *) {
player.playImmediately(atRate: 1.0)
} else {
player.play()
}
if state != .playing {
state = .playing
}
}
delegate?.jukeboxPlaybackProgressDidChange(self)
}
/**
Appends and optionally loads an item
- parameter item: the item to be appended to the play queue
- parameter loadingAssets: pass true to load item's assets asynchronously
*/
public func append(item: JukeboxItem, loadingAssets: Bool) {
queuedItems.append(item)
item.delegate = self
if loadingAssets {
if queuedItems.count == 1 {
state = .loading
}
item.loadPlayerItem()
}
print("Item appended to jukebox playlist")
}
/**
Removes an item from the play queue
- parameter item: item to be removed
*/
public func remove(item: JukeboxItem) {
if let index = queuedItems.index(where: {$0.identifier == item.identifier}) {
queuedItems.remove(at: index)
}
}
/**
Removes all items from the play queue matching the URL
- parameter url: the item URL
*/
public func removeItems(withURL url : URL) {
let indexes = queuedItems.indexesOf({$0.URL as URL == url})
for index in indexes {
queuedItems.remove(at: index)
}
}
/**
Removes all items from the play queue.
*/
public func removeAllItems(){
queuedItems.removeAll(keepingCapacity: true)
playIndex = 0
}
}
// MARK: - Class implementation -
open class Jukebox: NSObject, JukeboxItemDelegate {
public enum State: Int, CustomStringConvertible {
case ready = 0
case playing
case paused
case loading
case failed
case ended
public var description: String {
get{
switch self
{
case .ready:
return "Ready"
case .playing:
return "Playing"
case .failed:
return "Failed"
case .paused:
return "Paused"
case .loading:
return "Loading"
case .ended:
return "Ended"
}
}
}
}
// MARK:- Properties -
fileprivate var player : AVPlayer?
fileprivate var progressObserver : AnyObject!
fileprivate var backgroundIdentifier = UIBackgroundTaskInvalid
fileprivate var backgroundTask : BackgroundTask?
fileprivate var cacheDirectory = ""
fileprivate(set) open weak var delegate : JukeboxDelegate?
fileprivate (set) open var playIndex = 0
fileprivate (set) open var queuedItems : [JukeboxItem]!
fileprivate (set) open var autoLoop = false
fileprivate (set) open var state = State.ready {
didSet {
delegate?.jukeboxStateDidChange(self)
}
}
// MARK: Computed
open var volume: Float{
get {
return player?.volume ?? 0
}
set {
player?.volume = newValue
}
}
open var currentItem: JukeboxItem? {
guard playIndex >= 0 && playIndex < queuedItems.count else {
return nil
}
return queuedItems[playIndex]
}
fileprivate var playerOperational: Bool {
return player != nil && currentItem != nil
}
// MARK:- Initializer -
/**
Create an instance with a delegate and a list of items without loading their assets.
- parameter delegate: jukebox delegate
- parameter items: array of items to be added to the play queue
- returns: Jukebox instance
*/
public required init?(delegate: JukeboxDelegate? = nil, items: [JukeboxItem] = [JukeboxItem]()) {
self.delegate = delegate
super.init()
do {
try configureAudioSession()
} catch {
print("[Jukebox - Error] \(error)")
return nil
}
assignQueuedItems(items)
configureObservers()
}
deinit{
NotificationCenter.default.removeObserver(self)
}
// MARK:- JukeboxItemDelegate -
func jukeboxItemDidFail(_ item: JukeboxItem) {
stop()
state = .failed
self.delegate?.jukeboxError(self, item: item)
}
func jukeboxItemDidUpdate(_ item: JukeboxItem) {
guard let item = currentItem else {return}
updateInfoCenter()
self.delegate?.jukeboxDidUpdateMetadata(self, forItem: item)
}
func jukeboxItemDidLoadPlayerItem(_ item: JukeboxItem) {
delegate?.jukeboxDidLoadItem(self, item: item)
let index = queuedItems.index(where: { (jukeboxItem) -> Bool in
jukeboxItem.identifier == item.identifier
})
guard let playItem = item.playerItem
, state == .loading && playIndex == index else {return}
registerForPlayToEndNotification(withItem: playItem)
startNewPlayer(forItem: playItem)
}
func jukeboxItemReadyToPlay(_ item: JukeboxItem) {
play()
}
// MARK:- Private methods -
// MARK: Playback
fileprivate func updateInfoCenter() {
guard let item = currentItem else {return}
let title = (item.meta.title ?? item.localTitle) ?? item.URL.lastPathComponent
let currentTime = item.currentTime ?? 0
let duration = item.meta.duration ?? 0
let trackNumber = playIndex
let trackCount = queuedItems.count
var nowPlayingInfo : [String : AnyObject] = [
MPMediaItemPropertyPlaybackDuration : duration as AnyObject,
MPMediaItemPropertyTitle : title as AnyObject,
MPNowPlayingInfoPropertyElapsedPlaybackTime : currentTime as AnyObject,
MPNowPlayingInfoPropertyPlaybackQueueCount :trackCount as AnyObject,
MPNowPlayingInfoPropertyPlaybackQueueIndex : trackNumber as AnyObject,
MPMediaItemPropertyMediaType : MPMediaType.anyAudio.rawValue as AnyObject
]
if let artist = item.meta.artist {
nowPlayingInfo[MPMediaItemPropertyArtist] = artist as AnyObject?
}
if let album = item.meta.album {
nowPlayingInfo[MPMediaItemPropertyAlbumTitle] = album as AnyObject?
}
if let img = currentItem?.meta.artwork {
nowPlayingInfo[MPMediaItemPropertyArtwork] = MPMediaItemArtwork(image: img)
}
MPNowPlayingInfoCenter.default().nowPlayingInfo = nowPlayingInfo
}
fileprivate func playCurrentItem(withAsset asset: AVAsset) {
queuedItems[playIndex].refreshPlayerItem(withAsset: asset)
startNewPlayer(forItem: queuedItems[playIndex].playerItem!)
guard let playItem = queuedItems[playIndex].playerItem else {return}
registerForPlayToEndNotification(withItem: playItem)
}
fileprivate func resumePlayback() {
if state != .playing {
startProgressTimer()
if let player = player {
if #available(iOS 10.0, *) {
player.playImmediately(atRate: 1.0)
} else {
player.play()
}
} else {
currentItem!.refreshPlayerItem(withAsset: currentItem!.playerItem!.asset)
startNewPlayer(forItem: currentItem!.playerItem!)
}
state = .playing
}
}
fileprivate func invalidatePlayback(shouldResetIndex resetIndex: Bool = true) {
stopProgressTimer()
player?.pause()
player = nil
if resetIndex {
playIndex = 0
}
}
fileprivate func startNewPlayer(forItem item : AVPlayerItem) {
invalidatePlayback(shouldResetIndex: false)
player = AVPlayer(playerItem: item)
player?.allowsExternalPlayback = false
startProgressTimer()
seek(toSecond: 0, shouldPlay: true)
updateInfoCenter()
}
// MARK: Items related
fileprivate func assignQueuedItems (_ items: [JukeboxItem]) {
queuedItems = items
for item in queuedItems {
item.delegate = self
}
}
fileprivate func loadPlaybackItem() {
guard playIndex >= 0 && playIndex < queuedItems.count else {
return
}
stopProgressTimer()
player?.pause()
queuedItems[playIndex].loadPlayerItem()
state = .loading
}
fileprivate func preloadNextAndPrevious(atIndex index: Int) {
guard !queuedItems.isEmpty else {return}
if index - 1 >= 0 {
queuedItems[index - 1].loadPlayerItem()
}
if index + 1 < queuedItems.count {
queuedItems[index + 1].loadPlayerItem()
}
}
// MARK: Progress tracking
fileprivate func startProgressTimer(){
guard let player = player , player.currentItem?.duration.isValid == true else {return}
progressObserver = player.addPeriodicTimeObserver(forInterval: CMTimeMakeWithSeconds(0.5, Int32(NSEC_PER_SEC)), queue: nil, using: { [unowned self] (time : CMTime) -> Void in
self.timerAction()
}) as AnyObject!
}
fileprivate func stopProgressTimer() {
guard let player = player, let observer = progressObserver else {
return
}
player.removeTimeObserver(observer)
progressObserver = nil
}
// MARK: Configurations
fileprivate func configureBackgroundAudioTask() {
backgroundIdentifier = UIApplication.shared.beginBackgroundTask (expirationHandler: { () -> Void in
UIApplication.shared.endBackgroundTask(self.backgroundIdentifier)
self.backgroundIdentifier = UIBackgroundTaskInvalid
})
// End backup background task.
endBackgroundTask()
}
fileprivate func configureAudioSession() throws {
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
try AVAudioSession.sharedInstance().setMode(AVAudioSessionModeDefault)
try AVAudioSession.sharedInstance().setActive(true)
}
fileprivate func configureObservers() {
NotificationCenter.default.addObserver(self, selector: #selector(Jukebox.handleStall), name: NSNotification.Name.AVPlayerItemPlaybackStalled, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(handleAudioSessionInterruption), name: NSNotification.Name.AVAudioSessionInterruption, object: AVAudioSession.sharedInstance())
NotificationCenter.default.addObserver(self, selector: #selector(Jukebox.handleEnterBackground), name: NSNotification.Name.UIApplicationDidEnterBackground, object: nil)
}
// MARK:- Notifications -
func handleAudioSessionInterruption(_ notification : Notification) {
guard self.currentItem != nil else { return } // ignore if we are not currently playing
guard let userInfo = notification.userInfo as? [String: AnyObject] else { return }
guard let rawInterruptionType = userInfo[AVAudioSessionInterruptionTypeKey] as? NSNumber else { return }
guard let interruptionType = AVAudioSessionInterruptionType(rawValue: rawInterruptionType.uintValue) else { return }
switch interruptionType {
case .began: //interruption started
self.pause()
case .ended: //interruption ended
if let rawInterruptionOption = userInfo[AVAudioSessionInterruptionOptionKey] as? NSNumber {
let interruptionOption = AVAudioSessionInterruptionOptions(rawValue: rawInterruptionOption.uintValue)
if interruptionOption == AVAudioSessionInterruptionOptions.shouldResume {
self.resumePlayback()
}
}
}
}
func handleStall() {
player?.pause()
if #available(iOS 10.0, *) {
player?.playImmediately(atRate: 1.0)
} else {
player?.play()
}
}
func handleEnterBackground() {
guard player?.currentItem != nil else {return}
if !isBackgroundTimeLongEnough() || state == .loading {
backgroundTask = BackgroundTask(application: UIApplication.shared)
backgroundTask!.begin()
} else {
if state != .playing {
endBackgroundTask()
}
}
}
func playerItemDidPlayToEnd(_ notification : Notification){
if playIndex >= queuedItems.count - 1 {
if (autoLoop) {
replay()
} else {
stop()
state = .ended
}
} else {
play(atIndex: playIndex + 1)
}
}
func timerAction() {
guard player?.currentItem != nil else {return}
currentItem?.update()
guard currentItem?.currentTime != nil else {return}
updateInfoCenter()
delegate?.jukeboxPlaybackProgressDidChange(self)
if !isBackgroundTimeLongEnough() {
handleEnterBackground()
}
}
func endBackgroundTask() {
backgroundTask?.end()
backgroundTask = nil
}
fileprivate func isBackgroundTimeLongEnough() -> Bool {
guard player?.currentItem != nil else {return true}
let timeLeft = (currentItem?.meta.duration ?? 0) - (currentItem?.currentTime ?? 0)
let bgTimeRemaining = UIApplication.shared.backgroundTimeRemaining
return bgTimeRemaining > timeLeft
}
fileprivate func registerForPlayToEndNotification(withItem item: AVPlayerItem) {
NotificationCenter.default.addObserver(self, selector: #selector(Jukebox.playerItemDidPlayToEnd(_:)), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: item)
}
fileprivate func unregisterForPlayToEndNotification(withItem item : AVPlayerItem) {
NotificationCenter.default.removeObserver(self, name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: item)
}
}
private extension Collection {
func indexesOf(_ predicate: (Iterator.Element) -> Bool) -> [Int] {
var indexes = [Int]()
for (index, item) in enumerated() {
if predicate(item){
indexes.append(index)
}
}
return indexes
}
}
private extension CMTime {
var isValid : Bool { return (flags.intersection(.valid)) != [] }
} | mit | 2335b1addc2f7c369cd81c6e3bc2a5ef | 30.826291 | 200 | 0.601003 | 5.450549 | false | false | false | false |
volodg/iAsync.network | Sources/URLConnectionCallbacks.swift | 1 | 661 | //
// URLConnectionCallbacks.swift
// iAsync_network
//
// Created by Vladimir Gorbenko on 25.09.14.
// Copyright ยฉ 2014 EmbeddedSources. All rights reserved.
//
import Foundation
import iAsync_utils
public typealias DidReceiveResponseHandler = (_ response: HTTPURLResponse) -> ()
public typealias DidFinishLoadingHandler = (_ error: ErrorWithContext?) -> ()
public typealias DidReceiveDataHandler = (_ data: Data) -> ()
public typealias DidUploadDataHandler = (_ progress: Double) -> ()
public typealias ShouldAcceptCertificateForHost = (_ callback: (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) -> Void
| mit | 57de69de80c9cae655958ce02fe87e10 | 37.823529 | 133 | 0.718182 | 4.680851 | false | false | false | false |
SeriousChoice/SCSwift | Example/Pods/Cache/Source/Shared/Storage/KeyObservationRegistry.swift | 2 | 1466 | import Foundation
/// A protocol used for adding and removing key observations
public protocol KeyObservationRegistry {
associatedtype S: StorageAware
/**
Registers observation closure which will be removed automatically
when the weakly captured observer has been deallocated.
- Parameter observer: Any object that helps determine if the observation is still valid
- Parameter key: Unique key to identify the object in the cache
- Parameter closure: Observation closure
- Returns: Token used to cancel the observation and remove the observation closure
*/
@discardableResult
func addObserver<O: AnyObject>(
_ observer: O,
forKey key: S.Key,
closure: @escaping (O, S, KeyChange<S.Value>) -> Void
) -> ObservationToken
/**
Removes observer by the given key.
- Parameter key: Unique key to identify the object in the cache
*/
func removeObserver(forKey key: S.Key)
/// Removes all registered key observers
func removeAllKeyObservers()
}
// MARK: - KeyChange
public enum KeyChange<T> {
case edit(before: T?, after: T)
case remove
}
extension KeyChange: Equatable where T: Equatable {
public static func == (lhs: KeyChange<T>, rhs: KeyChange<T>) -> Bool {
switch (lhs, rhs) {
case (.edit(let before1, let after1), .edit(let before2, let after2)):
return before1 == before2 && after1 == after2
case (.remove, .remove):
return true
default:
return false
}
}
}
| mit | 0cf88e18018c2569ca7c7e6e21abfd13 | 28.32 | 90 | 0.701228 | 4.376119 | false | false | false | false |
jovito-royeca/Decktracker | osx/DataSource/DataSource/CoreDataManager.swift | 1 | 10248 | //
// DataManager.swift
// WTHRM8
//
// Created by Jovit Royeca on 3/18/16.
// Copyright ยฉ 2016 Jovito Royeca. All rights reserved.
//
import Foundation
import CoreData
enum CoreDataError: ErrorType {
case NoSQLiteFile
case NoModelFile
}
class CoreDataManager: NSObject {
// MARK: Variables
private var sqliteFile:String?
private var modelFile:String?
// MARK: Setup
func setup(sqliteFile: String, modelFile: String) {
self.sqliteFile = sqliteFile
self.modelFile = modelFile
let plistPath = "\(NSBundle.mainBundle().bundlePath)/decktracker.plist"
let plistDict = NSDictionary(contentsOfFile: plistPath)
let documentPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).first
let cachePath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).first
let storePath = "\(documentPath!)/\(sqliteFile)"
// delete all cards from mtgimage.com
let mtgImageKey = "mtgimage.com images"
if !NSUserDefaults.standardUserDefaults().boolForKey(mtgImageKey) {
let path = "\(cachePath!)/images"
if NSFileManager.defaultManager().fileExistsAtPath(path) {
do {
try NSFileManager.defaultManager().removeItemAtPath(path)
} catch {}
}
}
NSUserDefaults.standardUserDefaults().setBool(true, forKey:mtgImageKey)
// copy Sqlite file to documents dir
if !NSFileManager.defaultManager().fileExistsAtPath(storePath) {
let path = "\(NSBundle.mainBundle().bundlePath)/\(sqliteFile)"
if NSFileManager.defaultManager().fileExistsAtPath(path) {
do {
try NSFileManager.defaultManager().copyItemAtPath(path, toPath: storePath)
if let jsonVersion = plistDict!["JSON Version"] as? String {
NSUserDefaults.standardUserDefaults().setValue(jsonVersion, forKey:"JSON Version")
NSUserDefaults.standardUserDefaults().synchronize()
}
} catch {
print("Error copying \(sqliteFile)")
}
}
} else {
if let plistDict = plistDict {
if let jsonVersion = plistDict["JSON Version"] as? String {
if let currentJSONVersion = NSUserDefaults.standardUserDefaults().valueForKey("JSON Version") as? String {
if jsonVersion != currentJSONVersion {
do {
for file in try NSFileManager.defaultManager().contentsOfDirectoryAtPath(documentPath!) {
if file.hasPrefix("decktracker.") || file.hasPrefix("Decktracker.") {
try NSFileManager.defaultManager().removeItemAtPath("\(documentPath!)/\(file)")
}
}
} catch {}
NSUserDefaults.standardUserDefaults().setValue(jsonVersion, forKey:"JSON Version")
NSUserDefaults.standardUserDefaults().synchronize()
setup(sqliteFile, modelFile: modelFile)
}
} else {
let path = "\(NSBundle.mainBundle().bundlePath)/\(sqliteFile)"
if NSFileManager.defaultManager().fileExistsAtPath(path) {
do {
for file in try NSFileManager.defaultManager().contentsOfDirectoryAtPath(documentPath!) {
if file.hasPrefix("decktracker.") || file.hasPrefix("Decktracker.") {
try NSFileManager.defaultManager().removeItemAtPath("\(documentPath!)/\(file)")
}
}
try NSFileManager.defaultManager().copyItemAtPath(path, toPath: storePath)
NSUserDefaults.standardUserDefaults().setValue(jsonVersion, forKey:"JSON Version")
NSUserDefaults.standardUserDefaults().synchronize()
} catch {
print("Error: \(sqliteFile)")
}
}
}
}
}
}
// ignore the database and other files from iCloud backup
let files = NSFileManager.defaultManager().enumeratorAtPath(documentPath!)
while let file = files?.nextObject() {
if file.hasPrefix(sqliteFile) {
let url = NSURL(fileURLWithPath: "\(documentPath!)/\(file)")
do {
try url.setResourceValue(NSNumber(bool: true), forKey: NSURLIsExcludedFromBackupKey)
} catch {
print("Error...")
}
}
}
}
// MARK: - The Core Data stack. The code has been moved, unaltered, from the AppDelegate.
lazy var applicationDocumentsDirectory: NSURL = {
// The directory the application uses to store the Core Data store file.
let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
return urls[urls.count-1]
}()
lazy var managedObjectModel: NSManagedObjectModel = {
// The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
let arr = self.modelFile!.componentsSeparatedByString(".")
let modelURL = NSBundle.mainBundle().URLForResource(arr.first, withExtension: arr.last)!
return NSManagedObjectModel(contentsOfURL: modelURL)!
}()
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = {
// The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail.
// Create the coordinator and store
let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent(self.sqliteFile!)
var failureReason = "There was an error creating or loading the application's saved data."
do {
let options = [NSMigratePersistentStoresAutomaticallyOption : true,
NSInferMappingModelAutomaticallyOption : true]
try coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: options)
} catch {
// Report any error we got.
var dict = [String: AnyObject]()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
dict[NSLocalizedFailureReasonErrorKey] = failureReason
dict[NSUnderlyingErrorKey] = error as! NSError
let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
// Replace this with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
print("Unresolved error \(wrappedError), \(wrappedError.userInfo)")
abort()
}
return coordinator
}()
lazy var mainObjectContext: NSManagedObjectContext = {
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
let coordinator = self.persistentStoreCoordinator
var mainObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType)
mainObjectContext.persistentStoreCoordinator = coordinator
return mainObjectContext
}()
lazy var privateContext: NSManagedObjectContext = {
var privateContext = NSManagedObjectContext(concurrencyType: .PrivateQueueConcurrencyType)
privateContext.parentContext = self.mainObjectContext
return privateContext
}()
// MARK: - Core Data Saving support
func saveMainContext () {
if mainObjectContext.hasChanges {
do {
try mainObjectContext.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
print("Unresolved error \(nserror), \(nserror.userInfo)")
abort()
}
}
}
func savePrivateContext() {
if privateContext.hasChanges {
do {
try privateContext.save()
} catch {
let nserror = error as NSError
print("Unresolved error \(nserror), \(nserror.userInfo)")
abort()
}
mainObjectContext.performBlockAndWait {
do {
try self.mainObjectContext.save()
} catch {
let nserror = error as NSError
print("Unresolved error \(nserror), \(nserror.userInfo)")
abort()
}
}
}
}
// MARK: - Shared Instance
static let sharedInstance = CoreDataManager()
}
| apache-2.0 | 80230f5a32f78194d818e84866fcad56 | 47.334906 | 291 | 0.586416 | 6.522597 | false | false | false | false |
michaello/Aloha | AlohaGIF/DynamicSubtitlesStyle.swift | 1 | 1434 | //
// DynamicSubtitlesStyle.swift
// AlohaGIF
//
// Created by Michal Pyrka on 24/04/2017.
// Copyright ยฉ 2017 Michal Pyrka. All rights reserved.
//
import UIKit
struct DynamicSubtitlesStyle {
private enum Constants {
static let fontMultiplierForOneAfterAnotherStyle: CGFloat = 24.0
static let fontMultiplierForOneWordOnlyStyle: CGFloat = 32.0
static let multiplierForRenderingVideo: CGFloat = 1.5
}
let effect: DynamicSubtitlesType
let font: UIFont
let color: UIColor
func font(forRenderingVideo logicValue: Bool) -> UIFont {
var fontSize = effect == .oneAfterAnother ? Constants.fontMultiplierForOneAfterAnotherStyle : Constants.fontMultiplierForOneWordOnlyStyle
fontSize = logicValue ? (fontSize * Constants.multiplierForRenderingVideo) : (fontSize / SharedVariables.videoScale)
return font.withSize(fontSize)
}
var textAttributes: [String : Any] {
return [
NSStrokeWidthAttributeName : -2.0,
NSStrokeColorAttributeName : UIColor.black,
NSFontAttributeName : font(forRenderingVideo: SharedVariables.isRenderingVideo),
NSForegroundColorAttributeName : color
]
}
}
extension DynamicSubtitlesStyle {
static let `default` = DynamicSubtitlesStyle(effect: DynamicSubtitlesType.oneAfterAnother, font: .boldSystemFont(ofSize: 16.0), color: .white)
}
| mit | d06d459912c230431c9ee345dcd0ca9e | 33.119048 | 146 | 0.703419 | 4.857627 | false | false | false | false |
cuappdev/eatery | Eatery Watch App Extension/UI/Eateries/CampusEateryRow.swift | 1 | 2260 | //
// CampusEateryRow.swift
// Eatery Watch App Extension
//
// Created by William Ma on 1/5/20.
// Copyright ยฉ 2020 CUAppDev. All rights reserved.
//
import Combine
import SwiftUI
private class PresentationState: ObservableObject {
private static let updateTimer = Timer.publish(every: 60, on: .current, in: .common).autoconnect()
@Published private(set) var presentation: EateryPresentation
private var updateSubscription: AnyCancellable?
init(eatery: CampusEatery) {
self.presentation = eatery.currentPresentation()
self.updateSubscription = PresentationState.updateTimer
.map { _ in eatery.currentPresentation() }
.assign(to: \.presentation, on: self)
}
}
/// A row in the campus eatery list
///
/// The view will display a distance label if `userLocation` is non-nil.
struct CampusEateryRow: View {
private let displayName: String
private let eateryLocation: CLLocation
private let userLocation: CLLocation?
@ObservedObject private var presentationState: PresentationState
var body: some View {
VStack(alignment: .leading, spacing: 0) {
HStack {
Spacer()
}
Text(self.displayName)
(Text(self.presentationState.presentation.statusText)
.foregroundColor(Color(self.presentationState.presentation.statusColor))
+ Text(" " + self.presentationState.presentation.nextEventText))
.font(.footnote)
self.detail
}
}
private var detail: AnyView {
if let userLocation = userLocation {
let distance = userLocation.distance(from: eateryLocation).converted(to: .miles).value
let text = "\(Double(round(10 * distance) / 10)) mi"
return AnyView(Text(text)
.font(.footnote)
.foregroundColor(.gray))
} else {
return AnyView(EmptyView())
}
}
init(eatery: CampusEatery, userLocation: CLLocation? = nil) {
self.displayName = eatery.displayName
self.eateryLocation = eatery.location
self.userLocation = userLocation
self.presentationState = PresentationState(eatery: eatery)
}
}
| mit | 42112939a8156ba074954c004688bfd4 | 27.961538 | 102 | 0.640992 | 4.796178 | false | false | false | false |
zjjzmw1/myGifSwift | Pods/IQKeyboardManagerSwift/IQKeyboardManagerSwift/IQKeyboardManager.swift | 3 | 113425 | //
// IQKeyboardManager.swift
// https://github.com/hackiftekhar/IQKeyboardManager
// Copyright (c) 2013-16 Iftekhar Qurashi.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
import CoreGraphics
import UIKit
import QuartzCore
///---------------------
/// MARK: IQToolbar tags
///---------------------
/**
Codeless drop-in universal library allows to prevent issues of keyboard sliding up and cover UITextField/UITextView. Neither need to write any code nor any setup required and much more. A generic version of KeyboardManagement. https://developer.apple.com/library/ios/documentation/StringsTextFonts/Conceptual/TextAndWebiPhoneOS/KeyboardManagement/KeyboardManagement.html
*/
open class IQKeyboardManager: NSObject, UIGestureRecognizerDelegate {
/**
Default tag for toolbar with Done button -1002.
*/
fileprivate static let kIQDoneButtonToolbarTag = -1002
/**
Default tag for toolbar with Previous/Next buttons -1005.
*/
fileprivate static let kIQPreviousNextButtonToolbarTag = -1005
///---------------------------
/// MARK: UIKeyboard handling
///---------------------------
/**
Registered classes list with library.
*/
fileprivate var registeredClasses = [UIView.Type]()
/**
Enable/disable managing distance between keyboard and textField. Default is YES(Enabled when class loads in `+(void)load` method).
*/
open var enable = false {
didSet {
//If not enable, enable it.
if enable == true &&
oldValue == false {
//If keyboard is currently showing. Sending a fake notification for keyboardWillShow to adjust view according to keyboard.
if _kbShowNotification != nil {
keyboardWillShow(_kbShowNotification)
}
showLog("enabled")
} else if enable == false &&
oldValue == true { //If not disable, desable it.
keyboardWillHide(nil)
showLog("disabled")
}
}
}
fileprivate func privateIsEnabled()-> Bool {
var isEnabled = enable
if let textFieldViewController = _textFieldView?.viewController() {
if isEnabled == false {
//If viewController is kind of enable viewController class, then assuming it's enabled.
for enabledClass in enabledDistanceHandlingClasses {
if textFieldViewController.isKind(of: enabledClass) {
isEnabled = true
break
}
}
}
if isEnabled == true {
//If viewController is kind of disabled viewController class, then assuming it's disabled.
for disabledClass in disabledDistanceHandlingClasses {
if textFieldViewController.isKind(of: disabledClass) {
isEnabled = false
break
}
}
//Special Controllers
if isEnabled == true {
let classNameString = NSStringFromClass(type(of:textFieldViewController.self))
//_UIAlertControllerTextFieldViewController
if (classNameString.contains("UIAlertController") && classNameString.hasSuffix("TextFieldViewController")) {
isEnabled = false
}
}
}
}
return isEnabled
}
/**
To set keyboard distance from textField. can't be less than zero. Default is 10.0.
*/
open var keyboardDistanceFromTextField: CGFloat {
set {
_privateKeyboardDistanceFromTextField = max(0, newValue)
showLog("keyboardDistanceFromTextField: \(_privateKeyboardDistanceFromTextField)")
}
get {
return _privateKeyboardDistanceFromTextField
}
}
/**
Boolean to know if keyboard is showing.
*/
open var keyboardShowing: Bool {
get {
return _privateIsKeyboardShowing
}
}
/**
moved distance to the top used to maintain distance between keyboard and textField. Most of the time this will be a positive value.
*/
open var movedDistance: CGFloat {
get {
return _privateMovedDistance
}
}
/**
Prevent keyboard manager to slide up the rootView to more than keyboard height. Default is YES.
*/
open var preventShowingBottomBlankSpace = true
/**
Returns the default singleton instance.
*/
open class func sharedManager() -> IQKeyboardManager {
struct Static {
//Singleton instance. Initializing keyboard manger.
static let kbManager = IQKeyboardManager()
}
/** @return Returns the default singleton instance. */
return Static.kbManager
}
///-------------------------
/// MARK: IQToolbar handling
///-------------------------
/**
Automatic add the IQToolbar functionality. Default is YES.
*/
open var enableAutoToolbar = true {
didSet {
privateIsEnableAutoToolbar() ?addToolbarIfRequired():removeToolbarIfRequired()
let enableToolbar = enableAutoToolbar ? "Yes" : "NO"
showLog("enableAutoToolbar: \(enableToolbar)")
}
}
fileprivate func privateIsEnableAutoToolbar() -> Bool {
var enableToolbar = enableAutoToolbar
if let textFieldViewController = _textFieldView?.viewController() {
if enableToolbar == false {
//If found any toolbar enabled classes then return.
for enabledClass in enabledToolbarClasses {
if textFieldViewController.isKind(of: enabledClass) {
enableToolbar = true
break
}
}
}
if enableToolbar == true {
//If found any toolbar disabled classes then return.
for disabledClass in disabledToolbarClasses {
if textFieldViewController.isKind(of: disabledClass) {
enableToolbar = false
break
}
}
//Special Controllers
if enableToolbar == true {
let classNameString = NSStringFromClass(type(of:textFieldViewController.self))
//_UIAlertControllerTextFieldViewController
if (classNameString.contains("UIAlertController") && classNameString.hasSuffix("TextFieldViewController")) {
enableToolbar = false
}
}
}
}
return enableToolbar
}
/**
/**
IQAutoToolbarBySubviews: Creates Toolbar according to subview's hirarchy of Textfield's in view.
IQAutoToolbarByTag: Creates Toolbar according to tag property of TextField's.
IQAutoToolbarByPosition: Creates Toolbar according to the y,x position of textField in it's superview coordinate.
Default is IQAutoToolbarBySubviews.
*/
AutoToolbar managing behaviour. Default is IQAutoToolbarBySubviews.
*/
open var toolbarManageBehaviour = IQAutoToolbarManageBehaviour.bySubviews
/**
If YES, then uses textField's tintColor property for IQToolbar, otherwise tint color is black. Default is NO.
*/
open var shouldToolbarUsesTextFieldTintColor = false
/**
This is used for toolbar.tintColor when textfield.keyboardAppearance is UIKeyboardAppearanceDefault. If shouldToolbarUsesTextFieldTintColor is YES then this property is ignored. Default is nil and uses black color.
*/
open var toolbarTintColor : UIColor?
/**
IQPreviousNextDisplayModeDefault: Show NextPrevious when there are more than 1 textField otherwise hide.
IQPreviousNextDisplayModeAlwaysHide: Do not show NextPrevious buttons in any case.
IQPreviousNextDisplayModeAlwaysShow: Always show nextPrevious buttons, if there are more than 1 textField then both buttons will be visible but will be shown as disabled.
*/
open var previousNextDisplayMode = IQPreviousNextDisplayMode.Default
/**
Toolbar done button icon, If nothing is provided then check toolbarDoneBarButtonItemText to draw done button.
*/
open var toolbarDoneBarButtonItemImage : UIImage?
/**
Toolbar done button text, If nothing is provided then system default 'UIBarButtonSystemItemDone' will be used.
*/
open var toolbarDoneBarButtonItemText : String?
/**
If YES, then it add the textField's placeholder text on IQToolbar. Default is YES.
*/
open var shouldShowTextFieldPlaceholder = true
/**
Placeholder Font. Default is nil.
*/
open var placeholderFont: UIFont?
///--------------------------
/// MARK: UITextView handling
///--------------------------
/** used to adjust contentInset of UITextView. */
fileprivate var startingTextViewContentInsets = UIEdgeInsets.zero
/** used to adjust scrollIndicatorInsets of UITextView. */
fileprivate var startingTextViewScrollIndicatorInsets = UIEdgeInsets.zero
/** used with textView to detect a textFieldView contentInset is changed or not. (Bug ID: #92)*/
fileprivate var isTextViewContentInsetChanged = false
///---------------------------------------
/// MARK: UIKeyboard appearance overriding
///---------------------------------------
/**
Override the keyboardAppearance for all textField/textView. Default is NO.
*/
open var overrideKeyboardAppearance = false
/**
If overrideKeyboardAppearance is YES, then all the textField keyboardAppearance is set using this property.
*/
open var keyboardAppearance = UIKeyboardAppearance.default
///-----------------------------------------------------------
/// MARK: UITextField/UITextView Next/Previous/Resign handling
///-----------------------------------------------------------
/**
Resigns Keyboard on touching outside of UITextField/View. Default is NO.
*/
open var shouldResignOnTouchOutside = false {
didSet {
_tapGesture.isEnabled = privateShouldResignOnTouchOutside()
let shouldResign = shouldResignOnTouchOutside ? "Yes" : "NO"
showLog("shouldResignOnTouchOutside: \(shouldResign)")
}
}
fileprivate func privateShouldResignOnTouchOutside() -> Bool {
var shouldResign = shouldResignOnTouchOutside
if let textFieldViewController = _textFieldView?.viewController() {
if shouldResign == false {
//If viewController is kind of enable viewController class, then assuming shouldResignOnTouchOutside is enabled.
for enabledClass in enabledTouchResignedClasses {
if textFieldViewController.isKind(of: enabledClass) {
shouldResign = true
break
}
}
}
if shouldResign == true {
//If viewController is kind of disable viewController class, then assuming shouldResignOnTouchOutside is disable.
for disabledClass in disabledTouchResignedClasses {
if textFieldViewController.isKind(of: disabledClass) {
shouldResign = false
break
}
}
//Special Controllers
if shouldResign == true {
let classNameString = NSStringFromClass(type(of:textFieldViewController.self))
//_UIAlertControllerTextFieldViewController
if (classNameString.contains("UIAlertController") && classNameString.hasSuffix("TextFieldViewController")) {
shouldResign = false
}
}
}
}
return shouldResign
}
/**
Resigns currently first responder field.
*/
@discardableResult open func resignFirstResponder()-> Bool {
if let textFieldRetain = _textFieldView {
//Resigning first responder
let isResignFirstResponder = textFieldRetain.resignFirstResponder()
// If it refuses then becoming it as first responder again. (Bug ID: #96)
if isResignFirstResponder == false {
//If it refuses to resign then becoming it first responder again for getting notifications callback.
textFieldRetain.becomeFirstResponder()
showLog("Refuses to resign first responder: \(String(describing: _textFieldView?._IQDescription()))")
}
return isResignFirstResponder
}
return false
}
/**
Returns YES if can navigate to previous responder textField/textView, otherwise NO.
*/
open var canGoPrevious: Bool {
//Getting all responder view's.
if let textFields = responderViews() {
if let textFieldRetain = _textFieldView {
//Getting index of current textField.
if let index = textFields.index(of: textFieldRetain) {
//If it is not first textField. then it's previous object canBecomeFirstResponder.
if index > 0 {
return true
}
}
}
}
return false
}
/**
Returns YES if can navigate to next responder textField/textView, otherwise NO.
*/
open var canGoNext: Bool {
//Getting all responder view's.
if let textFields = responderViews() {
if let textFieldRetain = _textFieldView {
//Getting index of current textField.
if let index = textFields.index(of: textFieldRetain) {
//If it is not first textField. then it's previous object canBecomeFirstResponder.
if index < textFields.count-1 {
return true
}
}
}
}
return false
}
/**
Navigate to previous responder textField/textView.
*/
@discardableResult open func goPrevious()-> Bool {
//Getting all responder view's.
if let textFieldRetain = _textFieldView {
if let textFields = responderViews() {
//Getting index of current textField.
if let index = textFields.index(of: textFieldRetain) {
//If it is not first textField. then it's previous object becomeFirstResponder.
if index > 0 {
let nextTextField = textFields[index-1]
let isAcceptAsFirstResponder = nextTextField.becomeFirstResponder()
// If it refuses then becoming previous textFieldView as first responder again. (Bug ID: #96)
if isAcceptAsFirstResponder == false {
//If next field refuses to become first responder then restoring old textField as first responder.
textFieldRetain.becomeFirstResponder()
showLog("Refuses to become first responder: \(nextTextField._IQDescription())")
}
return isAcceptAsFirstResponder
}
}
}
}
return false
}
/**
Navigate to next responder textField/textView.
*/
@discardableResult open func goNext()-> Bool {
//Getting all responder view's.
if let textFieldRetain = _textFieldView {
if let textFields = responderViews() {
//Getting index of current textField.
if let index = textFields.index(of: textFieldRetain) {
//If it is not last textField. then it's next object becomeFirstResponder.
if index < textFields.count-1 {
let nextTextField = textFields[index+1]
let isAcceptAsFirstResponder = nextTextField.becomeFirstResponder()
// If it refuses then becoming previous textFieldView as first responder again. (Bug ID: #96)
if isAcceptAsFirstResponder == false {
//If next field refuses to become first responder then restoring old textField as first responder.
textFieldRetain.becomeFirstResponder()
showLog("Refuses to become first responder: \(nextTextField._IQDescription())")
}
return isAcceptAsFirstResponder
}
}
}
}
return false
}
/** previousAction. */
internal func previousAction (_ barButton : UIBarButtonItem?) {
//If user wants to play input Click sound.
if shouldPlayInputClicks == true {
//Play Input Click Sound.
UIDevice.current.playInputClick()
}
if canGoPrevious == true {
if let textFieldRetain = _textFieldView {
let isAcceptAsFirstResponder = goPrevious()
if isAcceptAsFirstResponder &&
textFieldRetain.previousInvocation.target != nil &&
textFieldRetain.previousInvocation.action != nil {
UIApplication.shared.sendAction(textFieldRetain.previousInvocation.action!, to: textFieldRetain.previousInvocation.target, from: textFieldRetain, for: UIEvent())
}
}
}
}
/** nextAction. */
internal func nextAction (_ barButton : UIBarButtonItem?) {
//If user wants to play input Click sound.
if shouldPlayInputClicks == true {
//Play Input Click Sound.
UIDevice.current.playInputClick()
}
if canGoNext == true {
if let textFieldRetain = _textFieldView {
let isAcceptAsFirstResponder = goNext()
if isAcceptAsFirstResponder &&
textFieldRetain.nextInvocation.target != nil &&
textFieldRetain.nextInvocation.action != nil {
UIApplication.shared.sendAction(textFieldRetain.nextInvocation.action!, to: textFieldRetain.nextInvocation.target, from: textFieldRetain, for: UIEvent())
}
}
}
}
/** doneAction. Resigning current textField. */
internal func doneAction (_ barButton : IQBarButtonItem?) {
//If user wants to play input Click sound.
if shouldPlayInputClicks == true {
//Play Input Click Sound.
UIDevice.current.playInputClick()
}
if let textFieldRetain = _textFieldView {
//Resign textFieldView.
let isResignedFirstResponder = resignFirstResponder()
if isResignedFirstResponder &&
textFieldRetain.doneInvocation.target != nil &&
textFieldRetain.doneInvocation.action != nil{
UIApplication.shared.sendAction(textFieldRetain.doneInvocation.action!, to: textFieldRetain.doneInvocation.target, from: textFieldRetain, for: UIEvent())
}
}
}
/** Resigning on tap gesture. (Enhancement ID: #14)*/
internal func tapRecognized(_ gesture: UITapGestureRecognizer) {
if gesture.state == UIGestureRecognizerState.ended {
//Resigning currently responder textField.
_ = resignFirstResponder()
}
}
/** Note: returning YES is guaranteed to allow simultaneous recognition. returning NO is not guaranteed to prevent simultaneous recognition, as the other gesture's delegate may return YES. */
open func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
return false
}
/** To not detect touch events in a subclass of UIControl, these may have added their own selector for specific work */
open func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
// Should not recognize gesture if the clicked view is either UIControl or UINavigationBar(<Back button etc...) (Bug ID: #145)
for ignoreClass in touchResignedGestureIgnoreClasses {
if touch.view?.isKind(of: ignoreClass) == true {
return false
}
}
return true
}
///-----------------------
/// MARK: UISound handling
///-----------------------
/**
If YES, then it plays inputClick sound on next/previous/done click.
*/
open var shouldPlayInputClicks = true
///---------------------------
/// MARK: UIAnimation handling
///---------------------------
/**
If YES, then calls 'setNeedsLayout' and 'layoutIfNeeded' on any frame update of to viewController's view.
*/
open var layoutIfNeededOnUpdate = false
///-----------------------------------------------
/// @name InteractivePopGestureRecognizer handling
///-----------------------------------------------
/**
If YES, then always consider UINavigationController.view begin point as {0,0}, this is a workaround to fix a bug #464 because there are no notification mechanism exist when UINavigationController.view.frame gets changed internally.
*/
open var shouldFixInteractivePopGestureRecognizer = true
///------------------------------------
/// MARK: Class Level disabling methods
///------------------------------------
/**
Disable distance handling within the scope of disabled distance handling viewControllers classes. Within this scope, 'enabled' property is ignored. Class should be kind of UIViewController.
*/
open var disabledDistanceHandlingClasses = [UIViewController.Type]()
/**
Enable distance handling within the scope of enabled distance handling viewControllers classes. Within this scope, 'enabled' property is ignored. Class should be kind of UIViewController. If same Class is added in disabledDistanceHandlingClasses list, then enabledDistanceHandlingClasses will be ignored.
*/
open var enabledDistanceHandlingClasses = [UIViewController.Type]()
/**
Disable automatic toolbar creation within the scope of disabled toolbar viewControllers classes. Within this scope, 'enableAutoToolbar' property is ignored. Class should be kind of UIViewController.
*/
open var disabledToolbarClasses = [UIViewController.Type]()
/**
Enable automatic toolbar creation within the scope of enabled toolbar viewControllers classes. Within this scope, 'enableAutoToolbar' property is ignored. Class should be kind of UIViewController. If same Class is added in disabledToolbarClasses list, then enabledToolbarClasses will be ignore.
*/
open var enabledToolbarClasses = [UIViewController.Type]()
/**
Allowed subclasses of UIView to add all inner textField, this will allow to navigate between textField contains in different superview. Class should be kind of UIView.
*/
open var toolbarPreviousNextAllowedClasses = [UIView.Type]()
/**
Disabled classes to ignore 'shouldResignOnTouchOutside' property, Class should be kind of UIViewController.
*/
open var disabledTouchResignedClasses = [UIViewController.Type]()
/**
Enabled classes to forcefully enable 'shouldResignOnTouchOutsite' property. Class should be kind of UIViewController. If same Class is added in disabledTouchResignedClasses list, then enabledTouchResignedClasses will be ignored.
*/
open var enabledTouchResignedClasses = [UIViewController.Type]()
/**
if shouldResignOnTouchOutside is enabled then you can customise the behaviour to not recognise gesture touches on some specific view subclasses. Class should be kind of UIView. Default is [UIControl, UINavigationBar]
*/
open var touchResignedGestureIgnoreClasses = [UIView.Type]()
///-------------------------------------------
/// MARK: Third Party Library support
/// Add TextField/TextView Notifications customised NSNotifications. For example while using YYTextView https://github.com/ibireme/YYText
///-------------------------------------------
/**
Add/Remove customised Notification for third party customised TextField/TextView. Please be aware that the NSNotification object must be idential to UITextField/UITextView NSNotification objects and customised TextField/TextView support must be idential to UITextField/UITextView.
@param didBeginEditingNotificationName This should be identical to UITextViewTextDidBeginEditingNotification
@param didEndEditingNotificationName This should be identical to UITextViewTextDidEndEditingNotification
*/
open func registerTextFieldViewClass(_ aClass: UIView.Type, didBeginEditingNotificationName : String, didEndEditingNotificationName : String) {
registeredClasses.append(aClass)
NotificationCenter.default.addObserver(self, selector: #selector(self.textFieldViewDidBeginEditing(_:)), name: NSNotification.Name(rawValue: didBeginEditingNotificationName), object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(self.textFieldViewDidEndEditing(_:)), name: NSNotification.Name(rawValue: didEndEditingNotificationName), object: nil)
}
open func unregisterTextFieldViewClass(_ aClass: UIView.Type, didBeginEditingNotificationName : String, didEndEditingNotificationName : String) {
if let index = registeredClasses.index(where: { element in
return element == aClass.self
}) {
registeredClasses.remove(at: index)
}
NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: didBeginEditingNotificationName), object: nil)
NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: didEndEditingNotificationName), object: nil)
}
/**************************************************************************************/
///------------------------
/// MARK: Private variables
///------------------------
/*******************************************/
/** To save UITextField/UITextView object voa textField/textView notifications. */
fileprivate weak var _textFieldView: UIView?
/** To save rootViewController.view.frame. */
fileprivate var _topViewBeginRect = CGRect.zero
/** To save rootViewController */
fileprivate weak var _rootViewController: UIViewController?
/** To save topBottomLayoutConstraint original constant */
fileprivate var _layoutGuideConstraintInitialConstant: CGFloat = 0
/** To save topBottomLayoutConstraint original constraint reference */
fileprivate weak var _layoutGuideConstraint: NSLayoutConstraint?
/*******************************************/
/** Variable to save lastScrollView that was scrolled. */
fileprivate weak var _lastScrollView: UIScrollView?
/** LastScrollView's initial contentOffset. */
fileprivate var _startingContentOffset = CGPoint.zero
/** LastScrollView's initial scrollIndicatorInsets. */
fileprivate var _startingScrollIndicatorInsets = UIEdgeInsets.zero
/** LastScrollView's initial contentInsets. */
fileprivate var _startingContentInsets = UIEdgeInsets.zero
/*******************************************/
/** To save keyboardWillShowNotification. Needed for enable keyboard functionality. */
fileprivate var _kbShowNotification: Notification?
/** To save keyboard size. */
fileprivate var _kbSize = CGSize.zero
/** To save Status Bar size. */
fileprivate var _statusBarFrame = CGRect.zero
/** To save keyboard animation duration. */
fileprivate var _animationDuration = 0.25
/** To mimic the keyboard animation */
fileprivate var _animationCurve = UIViewAnimationOptions.curveEaseOut
/*******************************************/
/** TapGesture to resign keyboard on view's touch. */
fileprivate var _tapGesture: UITapGestureRecognizer!
/*******************************************/
/** Boolean to maintain keyboard is showing or it is hide. To solve rootViewController.view.frame calculations. */
fileprivate var _privateIsKeyboardShowing = false
fileprivate var _privateMovedDistance : CGFloat = 0.0
/** To use with keyboardDistanceFromTextField. */
fileprivate var _privateKeyboardDistanceFromTextField: CGFloat = 10.0
/**************************************************************************************/
///--------------------------------------
/// MARK: Initialization/Deinitialization
///--------------------------------------
/* Singleton Object Initialization. */
override init() {
super.init()
self.registerAllNotifications()
//Creating gesture for @shouldResignOnTouchOutside. (Enhancement ID: #14)
_tapGesture = UITapGestureRecognizer(target: self, action: #selector(self.tapRecognized(_:)))
_tapGesture.cancelsTouchesInView = false
_tapGesture.delegate = self
_tapGesture.isEnabled = shouldResignOnTouchOutside
//Loading IQToolbar, IQTitleBarButtonItem, IQBarButtonItem to fix first time keyboard appearance delay (Bug ID: #550)
let textField = UITextField()
textField.addDoneOnKeyboardWithTarget(nil, action: #selector(self.doneAction(_:)))
textField.addPreviousNextDoneOnKeyboardWithTarget(nil, previousAction: #selector(self.previousAction(_:)), nextAction: #selector(self.nextAction(_:)), doneAction: #selector(self.doneAction(_:)))
disabledDistanceHandlingClasses.append(UITableViewController.self)
disabledDistanceHandlingClasses.append(UIAlertController.self)
disabledToolbarClasses.append(UIAlertController.self)
disabledTouchResignedClasses.append(UIAlertController.self)
toolbarPreviousNextAllowedClasses.append(UITableView.self)
toolbarPreviousNextAllowedClasses.append(UICollectionView.self)
toolbarPreviousNextAllowedClasses.append(IQPreviousNextView.self)
touchResignedGestureIgnoreClasses.append(UIControl.self)
touchResignedGestureIgnoreClasses.append(UINavigationBar.self)
}
/** Override +load method to enable KeyboardManager when class loader load IQKeyboardManager. Enabling when app starts (No need to write any code) */
/** It doesn't work from Swift 1.2 */
// override public class func load() {
// super.load()
//
// //Enabling IQKeyboardManager.
// IQKeyboardManager.sharedManager().enable = true
// }
deinit {
// Disable the keyboard manager.
enable = false
//Removing notification observers on dealloc.
NotificationCenter.default.removeObserver(self)
}
/** Getting keyWindow. */
fileprivate func keyWindow() -> UIWindow? {
if let keyWindow = _textFieldView?.window {
return keyWindow
} else {
struct Static {
/** @abstract Save keyWindow object for reuse.
@discussion Sometimes [[UIApplication sharedApplication] keyWindow] is returning nil between the app. */
static var keyWindow : UIWindow?
}
/* (Bug ID: #23, #25, #73) */
let originalKeyWindow = UIApplication.shared.keyWindow
//If original key window is not nil and the cached keywindow is also not original keywindow then changing keywindow.
if originalKeyWindow != nil &&
(Static.keyWindow == nil || Static.keyWindow != originalKeyWindow) {
Static.keyWindow = originalKeyWindow
}
//Return KeyWindow
return Static.keyWindow
}
}
///-----------------------
/// MARK: Helper Functions
///-----------------------
/* Helper function to manipulate RootViewController's frame with animation. */
fileprivate func setRootViewFrame(_ frame: CGRect) {
// Getting topMost ViewController.
var controller = _textFieldView?.topMostController()
if controller == nil {
controller = keyWindow()?.topMostController()
}
if let unwrappedController = controller {
var newFrame = frame
//frame size needs to be adjusted on iOS8 due to orientation structure changes.
newFrame.size = unwrappedController.view.frame.size
//Used UIViewAnimationOptionBeginFromCurrentState to minimize strange animations.
UIView.animate(withDuration: _animationDuration, delay: 0, options: UIViewAnimationOptions.beginFromCurrentState.union(_animationCurve), animations: { () -> Void in
// Setting it's new frame
unwrappedController.view.frame = newFrame
self.showLog("Set \(String(describing: controller?._IQDescription())) frame to : \(newFrame)")
//Animating content if needed (Bug ID: #204)
if self.layoutIfNeededOnUpdate == true {
//Animating content (Bug ID: #160)
unwrappedController.view.setNeedsLayout()
unwrappedController.view.layoutIfNeeded()
}
}) { (animated:Bool) -> Void in}
} else { // If can't get rootViewController then printing warning to user.
showLog("You must set UIWindow.rootViewController in your AppDelegate to work with IQKeyboardManager")
}
}
/* Adjusting RootViewController's frame according to interface orientation. */
fileprivate func adjustFrame() {
// We are unable to get textField object while keyboard showing on UIWebView's textField. (Bug ID: #11)
if _textFieldView == nil {
return
}
let textFieldView = _textFieldView!
let startTime = CACurrentMediaTime()
showLog("****** \(#function) started ******")
// Getting KeyWindow object.
let optionalWindow = keyWindow()
// Getting RootViewController. (Bug ID: #1, #4)
var optionalRootController = _textFieldView?.topMostController()
if optionalRootController == nil {
optionalRootController = keyWindow()?.topMostController()
}
// Converting Rectangle according to window bounds.
let optionalTextFieldViewRect = textFieldView.superview?.convert(textFieldView.frame, to: optionalWindow)
if optionalRootController == nil ||
optionalWindow == nil ||
optionalTextFieldViewRect == nil {
return
}
let rootController = optionalRootController!
let window = optionalWindow!
let textFieldViewRect = optionalTextFieldViewRect!
// Getting RootViewRect.
var rootViewRect = rootController.view.frame
//Getting statusBarFrame
//Maintain keyboardDistanceFromTextField
var specialKeyboardDistanceFromTextField = textFieldView.keyboardDistanceFromTextField
if textFieldView.isSearchBarTextField() {
if let searchBar = textFieldView.superviewOfClassType(UISearchBar.self) {
specialKeyboardDistanceFromTextField = searchBar.keyboardDistanceFromTextField
}
}
let newKeyboardDistanceFromTextField = (specialKeyboardDistanceFromTextField == kIQUseDefaultKeyboardDistance) ? keyboardDistanceFromTextField : specialKeyboardDistanceFromTextField
var kbSize = _kbSize
kbSize.height += newKeyboardDistanceFromTextField
let statusBarFrame = UIApplication.shared.statusBarFrame
// (Bug ID: #250)
var layoutGuidePosition = IQLayoutGuidePosition.none
if let viewController = textFieldView.viewController() {
if let constraint = _layoutGuideConstraint {
var layoutGuide : UILayoutSupport?
if let itemLayoutGuide = constraint.firstItem as? UILayoutSupport {
layoutGuide = itemLayoutGuide
} else if let itemLayoutGuide = constraint.secondItem as? UILayoutSupport {
layoutGuide = itemLayoutGuide
}
if let itemLayoutGuide : UILayoutSupport = layoutGuide {
if (itemLayoutGuide === viewController.topLayoutGuide) //If topLayoutGuide constraint
{
layoutGuidePosition = .top
}
else if (itemLayoutGuide === viewController.bottomLayoutGuide) //If bottomLayoutGuice constraint
{
layoutGuidePosition = .bottom
}
}
}
}
let topLayoutGuide : CGFloat = statusBarFrame.height
var move : CGFloat = 0.0
// Move positive = textField is hidden.
// Move negative = textField is showing.
// Checking if there is bottomLayoutGuide attached (Bug ID: #250)
if layoutGuidePosition == .bottom {
// Calculating move position.
move = textFieldViewRect.maxY-(window.frame.height-kbSize.height)
} else {
// Calculating move position. Common for both normal and special cases.
move = min(textFieldViewRect.minY-(topLayoutGuide+5), textFieldViewRect.maxY-(window.frame.height-kbSize.height))
}
showLog("Need to move: \(move)")
var superScrollView : UIScrollView? = nil
var superView = textFieldView.superviewOfClassType(UIScrollView.self) as? UIScrollView
//Getting UIScrollView whose scrolling is enabled. // (Bug ID: #285)
while let view = superView {
if (view.isScrollEnabled) {
superScrollView = view
break
}
else {
// Getting it's superScrollView. // (Enhancement ID: #21, #24)
superView = view.superviewOfClassType(UIScrollView.self) as? UIScrollView
}
}
//If there was a lastScrollView. // (Bug ID: #34)
if let lastScrollView = _lastScrollView {
//If we can't find current superScrollView, then setting lastScrollView to it's original form.
if superScrollView == nil {
showLog("Restoring \(lastScrollView._IQDescription()) contentInset to : \(_startingContentInsets) and contentOffset to : \(_startingContentOffset)")
UIView.animate(withDuration: _animationDuration, delay: 0, options: UIViewAnimationOptions.beginFromCurrentState.union(_animationCurve), animations: { () -> Void in
lastScrollView.contentInset = self._startingContentInsets
lastScrollView.scrollIndicatorInsets = self._startingScrollIndicatorInsets
}) { (animated:Bool) -> Void in }
if lastScrollView.shouldRestoreScrollViewContentOffset == true {
lastScrollView.setContentOffset(_startingContentOffset, animated: true)
}
_startingContentInsets = UIEdgeInsets.zero
_startingScrollIndicatorInsets = UIEdgeInsets.zero
_startingContentOffset = CGPoint.zero
_lastScrollView = nil
} else if superScrollView != lastScrollView { //If both scrollView's are different, then reset lastScrollView to it's original frame and setting current scrollView as last scrollView.
showLog("Restoring \(lastScrollView._IQDescription()) contentInset to : \(_startingContentInsets) and contentOffset to : \(_startingContentOffset)")
UIView.animate(withDuration: _animationDuration, delay: 0, options: UIViewAnimationOptions.beginFromCurrentState.union(_animationCurve), animations: { () -> Void in
lastScrollView.contentInset = self._startingContentInsets
lastScrollView.scrollIndicatorInsets = self._startingScrollIndicatorInsets
}) { (animated:Bool) -> Void in }
if lastScrollView.shouldRestoreScrollViewContentOffset == true {
lastScrollView.setContentOffset(_startingContentOffset, animated: true)
}
_lastScrollView = superScrollView
_startingContentInsets = superScrollView!.contentInset
_startingScrollIndicatorInsets = superScrollView!.scrollIndicatorInsets
_startingContentOffset = superScrollView!.contentOffset
showLog("Saving New \(lastScrollView._IQDescription()) contentInset : \(_startingContentInsets) and contentOffset : \(_startingContentOffset)")
}
//Else the case where superScrollView == lastScrollView means we are on same scrollView after switching to different textField. So doing nothing, going ahead
} else if let unwrappedSuperScrollView = superScrollView { //If there was no lastScrollView and we found a current scrollView. then setting it as lastScrollView.
_lastScrollView = unwrappedSuperScrollView
_startingContentInsets = unwrappedSuperScrollView.contentInset
_startingScrollIndicatorInsets = unwrappedSuperScrollView.scrollIndicatorInsets
_startingContentOffset = unwrappedSuperScrollView.contentOffset
showLog("Saving \(unwrappedSuperScrollView._IQDescription()) contentInset : \(_startingContentInsets) and contentOffset : \(_startingContentOffset)")
}
// Special case for ScrollView.
// If we found lastScrollView then setting it's contentOffset to show textField.
if let lastScrollView = _lastScrollView {
//Saving
var lastView = textFieldView
var superScrollView = _lastScrollView
while let scrollView = superScrollView {
//Looping in upper hierarchy until we don't found any scrollView in it's upper hirarchy till UIWindow object.
if move > 0 ? (move > (-scrollView.contentOffset.y - scrollView.contentInset.top)) : scrollView.contentOffset.y>0 {
var tempScrollView = scrollView.superviewOfClassType(UIScrollView.self) as? UIScrollView
var nextScrollView : UIScrollView? = nil
while let view = tempScrollView {
if (view.isScrollEnabled) {
nextScrollView = view
break
} else {
tempScrollView = view.superviewOfClassType(UIScrollView.self) as? UIScrollView
}
}
//Getting lastViewRect.
if let lastViewRect = lastView.superview?.convert(lastView.frame, to: scrollView) {
//Calculating the expected Y offset from move and scrollView's contentOffset.
var shouldOffsetY = scrollView.contentOffset.y - min(scrollView.contentOffset.y,-move)
//Rearranging the expected Y offset according to the view.
shouldOffsetY = min(shouldOffsetY, lastViewRect.origin.y /*-5*/) //-5 is for good UI.//Commenting -5 (Bug ID: #69)
//[_textFieldView isKindOfClass:[UITextView class]] If is a UITextView type
//nextScrollView == nil If processing scrollView is last scrollView in upper hierarchy (there is no other scrollView upper hierrchy.)
//[_textFieldView isKindOfClass:[UITextView class]] If is a UITextView type
//shouldOffsetY >= 0 shouldOffsetY must be greater than in order to keep distance from navigationBar (Bug ID: #92)
if textFieldView is UITextView == true &&
nextScrollView == nil &&
shouldOffsetY >= 0 {
var maintainTopLayout : CGFloat = 0
if let navigationBarFrame = textFieldView.viewController()?.navigationController?.navigationBar.frame {
maintainTopLayout = navigationBarFrame.maxY
}
maintainTopLayout += 10.0 //For good UI
// Converting Rectangle according to window bounds.
if let currentTextFieldViewRect = textFieldView.superview?.convert(textFieldView.frame, to: window) {
//Calculating expected fix distance which needs to be managed from navigation bar
let expectedFixDistance = currentTextFieldViewRect.minY - maintainTopLayout
//Now if expectedOffsetY (superScrollView.contentOffset.y + expectedFixDistance) is lower than current shouldOffsetY, which means we're in a position where navigationBar up and hide, then reducing shouldOffsetY with expectedOffsetY (superScrollView.contentOffset.y + expectedFixDistance)
shouldOffsetY = min(shouldOffsetY, scrollView.contentOffset.y + expectedFixDistance)
//Setting move to 0 because now we don't want to move any view anymore (All will be managed by our contentInset logic.
move = 0
}
else {
//Subtracting the Y offset from the move variable, because we are going to change scrollView's contentOffset.y to shouldOffsetY.
move -= (shouldOffsetY-scrollView.contentOffset.y)
}
}
else
{
//Subtracting the Y offset from the move variable, because we are going to change scrollView's contentOffset.y to shouldOffsetY.
move -= (shouldOffsetY-scrollView.contentOffset.y)
}
//Getting problem while using `setContentOffset:animated:`, So I used animation API.
UIView.animate(withDuration: _animationDuration, delay: 0, options: UIViewAnimationOptions.beginFromCurrentState.union(_animationCurve), animations: { () -> Void in
self.showLog("Adjusting \(scrollView.contentOffset.y-shouldOffsetY) to \(scrollView._IQDescription()) ContentOffset")
self.showLog("Remaining Move: \(move)")
scrollView.contentOffset = CGPoint(x: scrollView.contentOffset.x, y: shouldOffsetY)
}) { (animated:Bool) -> Void in }
}
// Getting next lastView & superScrollView.
lastView = scrollView
superScrollView = nextScrollView
} else {
break
}
}
//Updating contentInset
if let lastScrollViewRect = lastScrollView.superview?.convert(lastScrollView.frame, to: window) {
let bottom : CGFloat = kbSize.height-newKeyboardDistanceFromTextField-(window.frame.height-lastScrollViewRect.maxY)
// Update the insets so that the scroll vew doesn't shift incorrectly when the offset is near the bottom of the scroll view.
var movedInsets = lastScrollView.contentInset
movedInsets.bottom = max(_startingContentInsets.bottom, bottom)
showLog("\(lastScrollView._IQDescription()) old ContentInset : \(lastScrollView.contentInset)")
//Getting problem while using `setContentOffset:animated:`, So I used animation API.
UIView.animate(withDuration: _animationDuration, delay: 0, options: UIViewAnimationOptions.beginFromCurrentState.union(_animationCurve), animations: { () -> Void in
lastScrollView.contentInset = movedInsets
var newInset = lastScrollView.scrollIndicatorInsets
newInset.bottom = movedInsets.bottom
lastScrollView.scrollIndicatorInsets = newInset
}) { (animated:Bool) -> Void in }
showLog("\(lastScrollView._IQDescription()) new ContentInset : \(lastScrollView.contentInset)")
}
}
//Going ahead. No else if.
if layoutGuidePosition == .top {
if let constraint = _layoutGuideConstraint {
let constant = min(_layoutGuideConstraintInitialConstant, constraint.constant-move)
UIView.animate(withDuration: _animationDuration, delay: 0, options: (_animationCurve.union(UIViewAnimationOptions.beginFromCurrentState)), animations: { () -> Void in
constraint.constant = constant
self._rootViewController?.view.setNeedsLayout()
self._rootViewController?.view.layoutIfNeeded()
}, completion: { (finished) -> Void in })
}
} else if layoutGuidePosition == .bottom {
if let constraint = _layoutGuideConstraint {
let constant = max(_layoutGuideConstraintInitialConstant, constraint.constant+move)
UIView.animate(withDuration: _animationDuration, delay: 0, options: (_animationCurve.union(UIViewAnimationOptions.beginFromCurrentState)), animations: { () -> Void in
constraint.constant = constant
self._rootViewController?.view.setNeedsLayout()
self._rootViewController?.view.layoutIfNeeded()
}, completion: { (finished) -> Void in })
}
} else {
//Special case for UITextView(Readjusting textView.contentInset when textView hight is too big to fit on screen)
//_lastScrollView If not having inside any scrollView, (now contentInset manages the full screen textView.
//[_textFieldView isKindOfClass:[UITextView class]] If is a UITextView type
if let textView = textFieldView as? UITextView {
let textViewHeight = min(textView.frame.height, (window.frame.height-kbSize.height-(topLayoutGuide)))
if (textView.frame.size.height-textView.contentInset.bottom>textViewHeight)
{
UIView.animate(withDuration: _animationDuration, delay: 0, options: (_animationCurve.union(UIViewAnimationOptions.beginFromCurrentState)), animations: { () -> Void in
self.showLog("\(textFieldView._IQDescription()) Old UITextView.contentInset : \(textView.contentInset)")
//_isTextViewContentInsetChanged, If frame is not change by library in past, then saving user textView properties (Bug ID: #92)
if (self.isTextViewContentInsetChanged == false)
{
self.startingTextViewContentInsets = textView.contentInset
self.startingTextViewScrollIndicatorInsets = textView.scrollIndicatorInsets
}
var newContentInset = textView.contentInset
newContentInset.bottom = textView.frame.size.height-textViewHeight
textView.contentInset = newContentInset
textView.scrollIndicatorInsets = newContentInset
self.isTextViewContentInsetChanged = true
self.showLog("\(textFieldView._IQDescription()) Old UITextView.contentInset : \(textView.contentInset)")
}, completion: { (finished) -> Void in })
}
}
// Special case for iPad modalPresentationStyle.
if rootController.modalPresentationStyle == UIModalPresentationStyle.formSheet ||
rootController.modalPresentationStyle == UIModalPresentationStyle.pageSheet {
showLog("Found Special case for Model Presentation Style: \(rootController.modalPresentationStyle)")
// +Positive or zero.
if move >= 0 {
// We should only manipulate y.
rootViewRect.origin.y -= move
// From now prevent keyboard manager to slide up the rootView to more than keyboard height. (Bug ID: #93)
if preventShowingBottomBlankSpace == true {
let minimumY: CGFloat = (window.frame.height-rootViewRect.size.height-topLayoutGuide)/2-(kbSize.height-newKeyboardDistanceFromTextField)
rootViewRect.origin.y = max(rootViewRect.minY, minimumY)
}
showLog("Moving Upward")
// Setting adjusted rootViewRect
setRootViewFrame(rootViewRect)
_privateMovedDistance = (_topViewBeginRect.origin.y-rootViewRect.origin.y)
} else { // -Negative
// Calculating disturbed distance. Pull Request #3
let disturbDistance = rootViewRect.minY-_topViewBeginRect.minY
// disturbDistance Negative = frame disturbed.
// disturbDistance positive = frame not disturbed.
if disturbDistance < 0 {
// We should only manipulate y.
rootViewRect.origin.y -= max(move, disturbDistance)
showLog("Moving Downward")
// Setting adjusted rootViewRect
setRootViewFrame(rootViewRect)
_privateMovedDistance = (_topViewBeginRect.origin.y-rootViewRect.origin.y)
}
}
} else { //If presentation style is neither UIModalPresentationFormSheet nor UIModalPresentationPageSheet then going ahead.(General case)
// +Positive or zero.
if move >= 0 {
rootViewRect.origin.y -= move
// From now prevent keyboard manager to slide up the rootView to more than keyboard height. (Bug ID: #93)
if preventShowingBottomBlankSpace == true {
rootViewRect.origin.y = max(rootViewRect.origin.y, min(0, -kbSize.height+newKeyboardDistanceFromTextField))
}
showLog("Moving Upward")
// Setting adjusted rootViewRect
setRootViewFrame(rootViewRect)
_privateMovedDistance = (_topViewBeginRect.origin.y-rootViewRect.origin.y)
} else { // -Negative
let disturbDistance : CGFloat = rootViewRect.minY-_topViewBeginRect.minY
// disturbDistance Negative = frame disturbed.
// disturbDistance positive = frame not disturbed.
if disturbDistance < 0 {
rootViewRect.origin.y -= max(move, disturbDistance)
showLog("Moving Downward")
// Setting adjusted rootViewRect
// Setting adjusted rootViewRect
setRootViewFrame(rootViewRect)
_privateMovedDistance = (_topViewBeginRect.origin.y-rootViewRect.origin.y)
}
}
}
}
let elapsedTime = CACurrentMediaTime() - startTime
showLog("****** \(#function) ended: \(elapsedTime) seconds ******")
}
///---------------------
/// MARK: Public Methods
///---------------------
/* Refreshes textField/textView position if any external changes is explicitly made by user. */
open func reloadLayoutIfNeeded() -> Void {
if privateIsEnabled() == true {
if _textFieldView != nil &&
_privateIsKeyboardShowing == true &&
_topViewBeginRect.equalTo(CGRect.zero) == false &&
_textFieldView?.isAlertViewTextField() == false {
adjustFrame()
}
}
}
///-------------------------------
/// MARK: UIKeyboard Notifications
///-------------------------------
/* UIKeyboardWillShowNotification. */
internal func keyboardWillShow(_ notification : Notification?) -> Void {
_kbShowNotification = notification
// Boolean to know keyboard is showing/hiding
_privateIsKeyboardShowing = true
let oldKBSize = _kbSize
if let info = (notification as NSNotification?)?.userInfo {
// Getting keyboard animation.
if let curve = (info[UIKeyboardAnimationCurveUserInfoKey] as? NSNumber)?.uintValue {
_animationCurve = UIViewAnimationOptions(rawValue: curve)
} else {
_animationCurve = UIViewAnimationOptions.curveEaseOut
}
// Getting keyboard animation duration
if let duration = (info[UIKeyboardAnimationDurationUserInfoKey] as? NSNumber)?.doubleValue {
//Saving animation duration
if duration != 0.0 {
_animationDuration = duration
}
} else {
_animationDuration = 0.25
}
// Getting UIKeyboardSize.
if let kbFrame = (info[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue {
let screenSize = UIScreen.main.bounds
//Calculating actual keyboard displayed size, keyboard frame may be different when hardware keyboard is attached (Bug ID: #469) (Bug ID: #381)
let intersectRect = kbFrame.intersection(screenSize)
if intersectRect.isNull {
_kbSize = CGSize(width: screenSize.size.width, height: 0)
} else {
_kbSize = intersectRect.size
}
showLog("UIKeyboard Size : \(_kbSize)")
}
}
if privateIsEnabled() == false {
return
}
let startTime = CACurrentMediaTime()
showLog("****** \(#function) started ******")
// (Bug ID: #5)
if _textFieldView != nil && _topViewBeginRect.equalTo(CGRect.zero) == true {
// keyboard is not showing(At the beginning only). We should save rootViewRect.
if let constraint = _textFieldView?.viewController()?.IQLayoutGuideConstraint {
_layoutGuideConstraint = constraint
_layoutGuideConstraintInitialConstant = constraint.constant
}
// keyboard is not showing(At the beginning only). We should save rootViewRect.
_rootViewController = _textFieldView?.topMostController()
if _rootViewController == nil {
_rootViewController = keyWindow()?.topMostController()
}
if let unwrappedRootController = _rootViewController {
_topViewBeginRect = unwrappedRootController.view.frame
if shouldFixInteractivePopGestureRecognizer == true &&
unwrappedRootController is UINavigationController &&
unwrappedRootController.modalPresentationStyle != UIModalPresentationStyle.formSheet &&
unwrappedRootController.modalPresentationStyle != UIModalPresentationStyle.pageSheet {
if let window = keyWindow() {
_topViewBeginRect.origin = CGPoint(x: 0,y: window.frame.size.height-unwrappedRootController.view.frame.size.height)
} else {
_topViewBeginRect.origin = CGPoint.zero
}
}
showLog("Saving \(unwrappedRootController._IQDescription()) beginning Frame: \(_topViewBeginRect)")
} else {
_topViewBeginRect = CGRect.zero
}
}
// Getting topMost ViewController.
var topMostController = _textFieldView?.topMostController()
if topMostController == nil {
topMostController = keyWindow()?.topMostController()
}
//If last restored keyboard size is different(any orientation accure), then refresh. otherwise not.
if _kbSize.equalTo(oldKBSize) == false {
//If _textFieldView is inside UITableViewController then let UITableViewController to handle it (Bug ID: #37) (Bug ID: #76) See note:- https://developer.apple.com/library/ios/documentation/StringsTextFonts/Conceptual/TextAndWebiPhoneOS/KeyboardManagement/KeyboardManagement.html If it is UIAlertView textField then do not affect anything (Bug ID: #70).
if _privateIsKeyboardShowing == true &&
_textFieldView != nil &&
_textFieldView?.isAlertViewTextField() == false {
// keyboard is already showing. adjust frame.
adjustFrame()
}
}
let elapsedTime = CACurrentMediaTime() - startTime
showLog("****** \(#function) ended: \(elapsedTime) seconds ******")
}
/* UIKeyboardDidShowNotification. */
internal func keyboardDidShow(_ notification : Notification?) -> Void {
if privateIsEnabled() == false {
return
}
let startTime = CACurrentMediaTime()
showLog("****** \(#function) started ******")
// Getting topMost ViewController.
var topMostController = _textFieldView?.topMostController()
if topMostController == nil {
topMostController = keyWindow()?.topMostController()
}
if _textFieldView != nil &&
(topMostController?.modalPresentationStyle == UIModalPresentationStyle.formSheet || topMostController?.modalPresentationStyle == UIModalPresentationStyle.pageSheet) &&
_textFieldView?.isAlertViewTextField() == false {
//In case of form sheet or page sheet, we'll add adjustFrame call in main queue to perform it when UI thread will do all framing updation so adjustFrame will be executed after all internal operations.
OperationQueue.main.addOperation {
self.adjustFrame()
}
}
let elapsedTime = CACurrentMediaTime() - startTime
showLog("****** \(#function) ended: \(elapsedTime) seconds ******")
}
/* UIKeyboardWillHideNotification. So setting rootViewController to it's default frame. */
internal func keyboardWillHide(_ notification : Notification?) -> Void {
//If it's not a fake notification generated by [self setEnable:NO].
if notification != nil {
_kbShowNotification = nil
}
// Boolean to know keyboard is showing/hiding
_privateIsKeyboardShowing = false
let info : [AnyHashable: Any]? = (notification as NSNotification?)?.userInfo
// Getting keyboard animation duration
if let duration = (info?[UIKeyboardAnimationDurationUserInfoKey] as? NSNumber)?.doubleValue {
if duration != 0 {
// Setitng keyboard animation duration
_animationDuration = duration
}
}
//If not enabled then do nothing.
if privateIsEnabled() == false {
return
}
let startTime = CACurrentMediaTime()
showLog("****** \(#function) started ******")
//Commented due to #56. Added all the conditions below to handle UIWebView's textFields. (Bug ID: #56)
// We are unable to get textField object while keyboard showing on UIWebView's textField. (Bug ID: #11)
// if (_textFieldView == nil) return
//Restoring the contentOffset of the lastScrollView
if let lastScrollView = _lastScrollView {
UIView.animate(withDuration: _animationDuration, delay: 0, options: UIViewAnimationOptions.beginFromCurrentState.union(_animationCurve), animations: { () -> Void in
lastScrollView.contentInset = self._startingContentInsets
lastScrollView.scrollIndicatorInsets = self._startingScrollIndicatorInsets
if lastScrollView.shouldRestoreScrollViewContentOffset == true {
lastScrollView.contentOffset = self._startingContentOffset
}
self.showLog("Restoring \(lastScrollView._IQDescription()) contentInset to : \(self._startingContentInsets) and contentOffset to : \(self._startingContentOffset)")
// TODO: restore scrollView state
// This is temporary solution. Have to implement the save and restore scrollView state
var superScrollView : UIScrollView? = lastScrollView
while let scrollView = superScrollView {
let contentSize = CGSize(width: max(scrollView.contentSize.width, scrollView.frame.width), height: max(scrollView.contentSize.height, scrollView.frame.height))
let minimumY = contentSize.height - scrollView.frame.height
if minimumY < scrollView.contentOffset.y {
scrollView.contentOffset = CGPoint(x: scrollView.contentOffset.x, y: minimumY)
self.showLog("Restoring \(scrollView._IQDescription()) contentOffset to : \(self._startingContentOffset)")
}
superScrollView = scrollView.superviewOfClassType(UIScrollView.self) as? UIScrollView
}
}) { (finished) -> Void in }
}
// Setting rootViewController frame to it's original position. // (Bug ID: #18)
if _topViewBeginRect.equalTo(CGRect.zero) == false {
if let rootViewController = _rootViewController {
//frame size needs to be adjusted on iOS8 due to orientation API changes.
_topViewBeginRect.size = rootViewController.view.frame.size
//Used UIViewAnimationOptionBeginFromCurrentState to minimize strange animations.
UIView.animate(withDuration: _animationDuration, delay: 0, options: UIViewAnimationOptions.beginFromCurrentState.union(_animationCurve), animations: { () -> Void in
if let constraint = self._layoutGuideConstraint {
constraint.constant = self._layoutGuideConstraintInitialConstant
rootViewController.view.setNeedsLayout()
rootViewController.view.layoutIfNeeded()
}
else {
self.showLog("Restoring \(rootViewController._IQDescription()) frame to : \(self._topViewBeginRect)")
// Setting it's new frame
rootViewController.view.frame = self._topViewBeginRect
self._privateMovedDistance = 0
//Animating content if needed (Bug ID: #204)
if self.layoutIfNeededOnUpdate == true {
//Animating content (Bug ID: #160)
rootViewController.view.setNeedsLayout()
rootViewController.view.layoutIfNeeded()
}
}
}) { (finished) -> Void in }
_rootViewController = nil
}
} else if let constraint = self._layoutGuideConstraint {
if let rootViewController = _rootViewController {
UIView.animate(withDuration: _animationDuration, delay: 0, options: UIViewAnimationOptions.beginFromCurrentState.union(_animationCurve), animations: { () -> Void in
constraint.constant = self._layoutGuideConstraintInitialConstant
rootViewController.view.setNeedsLayout()
rootViewController.view.layoutIfNeeded()
}) { (finished) -> Void in }
}
}
//Reset all values
_lastScrollView = nil
_kbSize = CGSize.zero
_layoutGuideConstraint = nil
_layoutGuideConstraintInitialConstant = 0
_startingContentInsets = UIEdgeInsets.zero
_startingScrollIndicatorInsets = UIEdgeInsets.zero
_startingContentOffset = CGPoint.zero
// topViewBeginRect = CGRectZero //Commented due to #82
let elapsedTime = CACurrentMediaTime() - startTime
showLog("****** \(#function) ended: \(elapsedTime) seconds ******")
}
internal func keyboardDidHide(_ notification:Notification) {
let startTime = CACurrentMediaTime()
showLog("****** \(#function) started ******")
_topViewBeginRect = CGRect.zero
_kbSize = CGSize.zero
let elapsedTime = CACurrentMediaTime() - startTime
showLog("****** \(#function) ended: \(elapsedTime) seconds ******")
}
///-------------------------------------------
/// MARK: UITextField/UITextView Notifications
///-------------------------------------------
/** UITextFieldTextDidBeginEditingNotification, UITextViewTextDidBeginEditingNotification. Fetching UITextFieldView object. */
internal func textFieldViewDidBeginEditing(_ notification:Notification) {
let startTime = CACurrentMediaTime()
showLog("****** \(#function) started ******")
// Getting object
_textFieldView = notification.object as? UIView
if overrideKeyboardAppearance == true {
if let textFieldView = _textFieldView as? UITextField {
//If keyboard appearance is not like the provided appearance
if textFieldView.keyboardAppearance != keyboardAppearance {
//Setting textField keyboard appearance and reloading inputViews.
textFieldView.keyboardAppearance = keyboardAppearance
textFieldView.reloadInputViews()
}
} else if let textFieldView = _textFieldView as? UITextView {
//If keyboard appearance is not like the provided appearance
if textFieldView.keyboardAppearance != keyboardAppearance {
//Setting textField keyboard appearance and reloading inputViews.
textFieldView.keyboardAppearance = keyboardAppearance
textFieldView.reloadInputViews()
}
}
}
//If autoToolbar enable, then add toolbar on all the UITextField/UITextView's if required.
if privateIsEnableAutoToolbar() == true {
//UITextView special case. Keyboard Notification is firing before textView notification so we need to resign it first and then again set it as first responder to add toolbar on it.
if _textFieldView is UITextView == true &&
_textFieldView?.inputAccessoryView == nil {
UIView.animate(withDuration: 0.00001, delay: 0, options: UIViewAnimationOptions.beginFromCurrentState.union(_animationCurve), animations: { () -> Void in
self.addToolbarIfRequired()
}, completion: { (finished) -> Void in
//On textView toolbar didn't appear on first time, so forcing textView to reload it's inputViews.
self._textFieldView?.reloadInputViews()
})
} else {
//Adding toolbar
addToolbarIfRequired()
}
} else {
removeToolbarIfRequired()
}
_tapGesture.isEnabled = privateShouldResignOnTouchOutside()
_textFieldView?.window?.addGestureRecognizer(_tapGesture) // (Enhancement ID: #14)
if privateIsEnabled() == true {
if _topViewBeginRect.equalTo(CGRect.zero) == true { // (Bug ID: #5)
// keyboard is not showing(At the beginning only). We should save rootViewRect.
if let constraint = _textFieldView?.viewController()?.IQLayoutGuideConstraint {
_layoutGuideConstraint = constraint
_layoutGuideConstraintInitialConstant = constraint.constant
}
_rootViewController = _textFieldView?.topMostController()
if _rootViewController == nil {
_rootViewController = keyWindow()?.topMostController()
}
if let rootViewController = _rootViewController {
_topViewBeginRect = rootViewController.view.frame
if shouldFixInteractivePopGestureRecognizer == true &&
rootViewController is UINavigationController &&
rootViewController.modalPresentationStyle != UIModalPresentationStyle.formSheet &&
rootViewController.modalPresentationStyle != UIModalPresentationStyle.pageSheet {
if let window = keyWindow() {
_topViewBeginRect.origin = CGPoint(x: 0,y: window.frame.size.height-rootViewController.view.frame.size.height)
} else {
_topViewBeginRect.origin = CGPoint.zero
}
}
showLog("Saving \(rootViewController._IQDescription()) beginning frame : \(_topViewBeginRect)")
}
}
//If _textFieldView is inside ignored responder then do nothing. (Bug ID: #37, #74, #76)
//See notes:- https://developer.apple.com/library/ios/documentation/StringsTextFonts/Conceptual/TextAndWebiPhoneOS/KeyboardManagement/KeyboardManagement.html If it is UIAlertView textField then do not affect anything (Bug ID: #70).
if _privateIsKeyboardShowing == true &&
_textFieldView != nil &&
_textFieldView?.isAlertViewTextField() == false {
// keyboard is already showing. adjust frame.
adjustFrame()
}
}
let elapsedTime = CACurrentMediaTime() - startTime
showLog("****** \(#function) ended: \(elapsedTime) seconds ******")
}
/** UITextFieldTextDidEndEditingNotification, UITextViewTextDidEndEditingNotification. Removing fetched object. */
internal func textFieldViewDidEndEditing(_ notification:Notification) {
let startTime = CACurrentMediaTime()
showLog("****** \(#function) started ******")
//Removing gesture recognizer (Enhancement ID: #14)
_textFieldView?.window?.removeGestureRecognizer(_tapGesture)
// We check if there's a change in original frame or not.
if let textView = _textFieldView as? UITextView {
if isTextViewContentInsetChanged == true {
UIView.animate(withDuration: _animationDuration, delay: 0, options: UIViewAnimationOptions.beginFromCurrentState.union(_animationCurve), animations: { () -> Void in
self.isTextViewContentInsetChanged = false
self.showLog("Restoring \(textView._IQDescription()) textView.contentInset to : \(self.startingTextViewContentInsets)")
//Setting textField to it's initial contentInset
textView.contentInset = self.startingTextViewContentInsets
textView.scrollIndicatorInsets = self.startingTextViewScrollIndicatorInsets
}, completion: { (finished) -> Void in })
}
}
//Setting object to nil
_textFieldView = nil
let elapsedTime = CACurrentMediaTime() - startTime
showLog("****** \(#function) ended: \(elapsedTime) seconds ******")
}
///------------------------------------------
/// MARK: UIStatusBar Notification methods
///------------------------------------------
/** UIApplicationWillChangeStatusBarOrientationNotification. Need to set the textView to it's original position. If any frame changes made. (Bug ID: #92)*/
internal func willChangeStatusBarOrientation(_ notification:Notification) {
let startTime = CACurrentMediaTime()
showLog("****** \(#function) started ******")
//If textViewContentInsetChanged is saved then restore it.
if let textView = _textFieldView as? UITextView {
if isTextViewContentInsetChanged == true {
UIView.animate(withDuration: _animationDuration, delay: 0, options: UIViewAnimationOptions.beginFromCurrentState.union(_animationCurve), animations: { () -> Void in
self.isTextViewContentInsetChanged = false
self.showLog("Restoring \(textView._IQDescription()) textView.contentInset to : \(self.startingTextViewContentInsets)")
//Setting textField to it's initial contentInset
textView.contentInset = self.startingTextViewContentInsets
textView.scrollIndicatorInsets = self.startingTextViewScrollIndicatorInsets
}, completion: { (finished) -> Void in })
}
}
let elapsedTime = CACurrentMediaTime() - startTime
showLog("****** \(#function) ended: \(elapsedTime) seconds ******")
}
/** UIApplicationDidChangeStatusBarFrameNotification. Need to refresh view position and update _topViewBeginRect. (Bug ID: #446)*/
internal func didChangeStatusBarFrame(_ notification : Notification?) -> Void {
let oldStatusBarFrame = _statusBarFrame;
// Getting keyboard animation duration
if let newFrame = ((notification as NSNotification?)?.userInfo?[UIApplicationStatusBarFrameUserInfoKey] as? NSNumber)?.cgRectValue {
_statusBarFrame = newFrame
}
if privateIsEnabled() == false {
return
}
let startTime = CACurrentMediaTime()
showLog("****** \(#function) started ******")
if _rootViewController != nil &&
!_topViewBeginRect.equalTo(_rootViewController!.view.frame) == true {
if let unwrappedRootController = _rootViewController {
_topViewBeginRect = unwrappedRootController.view.frame
if shouldFixInteractivePopGestureRecognizer == true &&
unwrappedRootController is UINavigationController &&
unwrappedRootController.modalPresentationStyle != UIModalPresentationStyle.formSheet &&
unwrappedRootController.modalPresentationStyle != UIModalPresentationStyle.pageSheet {
if let window = keyWindow() {
_topViewBeginRect.origin = CGPoint(x: 0,y: window.frame.size.height-unwrappedRootController.view.frame.size.height)
} else {
_topViewBeginRect.origin = CGPoint.zero
}
}
showLog("Saving \(unwrappedRootController._IQDescription()) beginning Frame: \(_topViewBeginRect)")
} else {
_topViewBeginRect = CGRect.zero
}
}
//If _textFieldView is inside UITableViewController then let UITableViewController to handle it (Bug ID: #37) (Bug ID: #76) See note:- https://developer.apple.com/library/ios/documentation/StringsTextFonts/Conceptual/TextAndWebiPhoneOS/KeyboardManagement/KeyboardManagement.html If it is UIAlertView textField then do not affect anything (Bug ID: #70).
if _privateIsKeyboardShowing == true &&
_textFieldView != nil &&
_statusBarFrame.size.equalTo(oldStatusBarFrame.size) == false &&
_textFieldView?.isAlertViewTextField() == false {
// keyboard is already showing. adjust frame.
adjustFrame()
}
let elapsedTime = CACurrentMediaTime() - startTime
showLog("****** \(#function) ended: \(elapsedTime) seconds ******")
}
///------------------
/// MARK: AutoToolbar
///------------------
/** Get all UITextField/UITextView siblings of textFieldView. */
fileprivate func responderViews()-> [UIView]? {
var superConsideredView : UIView?
//If find any consider responderView in it's upper hierarchy then will get deepResponderView.
for disabledClass in toolbarPreviousNextAllowedClasses {
superConsideredView = _textFieldView?.superviewOfClassType(disabledClass)
if superConsideredView != nil {
break
}
}
//If there is a superConsideredView in view's hierarchy, then fetching all it's subview that responds. No sorting for superConsideredView, it's by subView position. (Enhancement ID: #22)
if superConsideredView != nil {
return superConsideredView?.deepResponderViews()
} else { //Otherwise fetching all the siblings
if let textFields = _textFieldView?.responderSiblings() {
//Sorting textFields according to behaviour
switch toolbarManageBehaviour {
//If autoToolbar behaviour is bySubviews, then returning it.
case IQAutoToolbarManageBehaviour.bySubviews: return textFields
//If autoToolbar behaviour is by tag, then sorting it according to tag property.
case IQAutoToolbarManageBehaviour.byTag: return textFields.sortedArrayByTag()
//If autoToolbar behaviour is by tag, then sorting it according to tag property.
case IQAutoToolbarManageBehaviour.byPosition: return textFields.sortedArrayByPosition()
}
} else {
return nil
}
}
}
/** Add toolbar if it is required to add on textFields and it's siblings. */
fileprivate func addToolbarIfRequired() {
let startTime = CACurrentMediaTime()
showLog("****** \(#function) started ******")
// Getting all the sibling textFields.
if let siblings = responderViews() {
showLog("Found \(siblings.count) responder sibling(s)")
// If only one object is found, then adding only Done button.
if (siblings.count == 1 && previousNextDisplayMode == .Default) || previousNextDisplayMode == .alwaysHide {
if let textField = _textFieldView {
var needReload = false;
//Either there is no inputAccessoryView or if accessoryView is not appropriate for current situation(There is Previous/Next/Done toolbar).
//setInputAccessoryView: check (Bug ID: #307)
if textField.responds(to: #selector(setter: UITextField.inputAccessoryView)) {
if textField.inputAccessoryView == nil ||
textField.inputAccessoryView?.tag == IQKeyboardManager.kIQPreviousNextButtonToolbarTag {
//Supporting Custom Done button image (Enhancement ID: #366)
if textField.inputAccessoryView?.tag == IQKeyboardManager.kIQPreviousNextButtonToolbarTag {
needReload = true
}
if let doneBarButtonItemImage = toolbarDoneBarButtonItemImage {
textField.addRightButtonOnKeyboardWithImage(doneBarButtonItemImage, target: self, action: #selector(self.doneAction(_:)), shouldShowPlaceholder: shouldShowTextFieldPlaceholder)
}
//Supporting Custom Done button text (Enhancement ID: #209, #411, Bug ID: #376)
else if let doneBarButtonItemText = toolbarDoneBarButtonItemText {
textField.addRightButtonOnKeyboardWithText(doneBarButtonItemText, target: self, action: #selector(self.doneAction(_:)), shouldShowPlaceholder: shouldShowTextFieldPlaceholder)
} else {
//Now adding textField placeholder text as title of IQToolbar (Enhancement ID: #27)
textField.addDoneOnKeyboardWithTarget(self, action: #selector(self.doneAction(_:)), shouldShowPlaceholder: shouldShowTextFieldPlaceholder)
}
textField.inputAccessoryView?.tag = IQKeyboardManager.kIQDoneButtonToolbarTag // (Bug ID: #78)
}
else if let toolbar = textField.inputAccessoryView as? IQToolbar {
if toolbar.tag == IQKeyboardManager.kIQDoneButtonToolbarTag {
if textField.inputAccessoryView?.tag == IQKeyboardManager.kIQDoneButtonToolbarTag {
if let doneBarButtonItemImage = toolbarDoneBarButtonItemImage {
if toolbar.doneImage?.isEqual(doneBarButtonItemImage) == false {
textField.addRightButtonOnKeyboardWithImage(doneBarButtonItemImage, target: self, action: #selector(self.doneAction(_:)), shouldShowPlaceholder: shouldShowTextFieldPlaceholder)
needReload = true
}
}
//Supporting Custom Done button text (Enhancement ID: #209, #411, Bug ID: #376)
else if let doneBarButtonItemText = toolbarDoneBarButtonItemText {
if toolbar.doneTitle != doneBarButtonItemText {
textField.addRightButtonOnKeyboardWithText(doneBarButtonItemText, target: self, action: #selector(self.doneAction(_:)), shouldShowPlaceholder: shouldShowTextFieldPlaceholder)
needReload = true
}
} else if (toolbarDoneBarButtonItemText == nil && toolbar.doneTitle != nil) ||
(toolbarDoneBarButtonItemImage == nil && toolbar.doneImage != nil) {
//Now adding textField placeholder text as title of IQToolbar (Enhancement ID: #27)
textField.addDoneOnKeyboardWithTarget(self, action: #selector(self.doneAction(_:)), shouldShowPlaceholder: shouldShowTextFieldPlaceholder)
needReload = true
}
textField.inputAccessoryView?.tag = IQKeyboardManager.kIQDoneButtonToolbarTag // (Bug ID: #78)
}
}
}
}
if textField.inputAccessoryView is IQToolbar &&
textField.inputAccessoryView?.tag == IQKeyboardManager.kIQDoneButtonToolbarTag {
let toolbar = textField.inputAccessoryView as! IQToolbar
// Setting toolbar to keyboard.
if let _textField = textField as? UITextField {
//Bar style according to keyboard appearance
switch _textField.keyboardAppearance {
case UIKeyboardAppearance.dark:
toolbar.barStyle = UIBarStyle.black
toolbar.tintColor = UIColor.white
default:
toolbar.barStyle = UIBarStyle.default
//Setting toolbar tintColor // (Enhancement ID: #30)
if shouldToolbarUsesTextFieldTintColor {
toolbar.tintColor = _textField.tintColor
} else if let tintColor = toolbarTintColor {
toolbar.tintColor = tintColor
} else {
toolbar.tintColor = UIColor.black
}
}
} else if let _textView = textField as? UITextView {
//Bar style according to keyboard appearance
switch _textView.keyboardAppearance {
case UIKeyboardAppearance.dark:
toolbar.barStyle = UIBarStyle.black
toolbar.tintColor = UIColor.white
default:
toolbar.barStyle = UIBarStyle.default
if shouldToolbarUsesTextFieldTintColor {
toolbar.tintColor = _textView.tintColor
} else if let tintColor = toolbarTintColor {
toolbar.tintColor = tintColor
} else {
toolbar.tintColor = UIColor.black
}
}
}
//Setting toolbar title font. // (Enhancement ID: #30)
if shouldShowTextFieldPlaceholder == true &&
textField.shouldHidePlaceholderText == false {
//Updating placeholder font to toolbar. //(Bug ID: #148, #272)
if toolbar.title == nil ||
toolbar.title != textField.drawingPlaceholderText {
toolbar.title = textField.drawingPlaceholderText
}
//Setting toolbar title font. // (Enhancement ID: #30)
if placeholderFont != nil {
toolbar.titleFont = placeholderFont
}
} else {
toolbar.title = nil
}
}
if needReload {
textField.reloadInputViews()
}
}
} else if (siblings.count > 1 && previousNextDisplayMode == .Default) || previousNextDisplayMode == .alwaysShow {
// If more than 1 textField is found. then adding previous/next/done buttons on it.
for textField in siblings {
var needReload = false;
//Either there is no inputAccessoryView or if accessoryView is not appropriate for current situation(There is Done toolbar).
//setInputAccessoryView: check (Bug ID: #307)
if textField.responds(to: #selector(setter: UITextField.inputAccessoryView)) &&
(textField.inputAccessoryView == nil || textField.inputAccessoryView?.tag == IQKeyboardManager.kIQDoneButtonToolbarTag) {
if textField.inputAccessoryView == nil ||
textField.inputAccessoryView?.tag == IQKeyboardManager.kIQDoneButtonToolbarTag {
if textField.inputAccessoryView?.tag == IQKeyboardManager.kIQDoneButtonToolbarTag {
needReload = true
}
//Supporting Custom Done button image (Enhancement ID: #366)
if let doneBarButtonItemImage = toolbarDoneBarButtonItemImage {
textField.addPreviousNextRightOnKeyboardWithTarget(self, rightButtonImage: doneBarButtonItemImage, previousAction: #selector(self.previousAction(_:)), nextAction: #selector(self.nextAction(_:)), rightButtonAction: #selector(self.doneAction(_:)), shouldShowPlaceholder: shouldShowTextFieldPlaceholder)
}
//Supporting Custom Done button text (Enhancement ID: #209, #411, Bug ID: #376)
else if let doneBarButtonItemText = toolbarDoneBarButtonItemText {
textField.addPreviousNextRightOnKeyboardWithTarget(self, rightButtonTitle: doneBarButtonItemText, previousAction: #selector(self.previousAction(_:)), nextAction: #selector(self.nextAction(_:)), rightButtonAction: #selector(self.doneAction(_:)), shouldShowPlaceholder: shouldShowTextFieldPlaceholder)
} else {
//Now adding textField placeholder text as title of IQToolbar (Enhancement ID: #27)
textField.addPreviousNextDoneOnKeyboardWithTarget(self, previousAction: #selector(self.previousAction(_:)), nextAction: #selector(self.nextAction(_:)), doneAction: #selector(self.doneAction(_:)), shouldShowPlaceholder: shouldShowTextFieldPlaceholder)
}
}
else if let toolbar = textField.inputAccessoryView as? IQToolbar {
if textField.inputAccessoryView?.tag == IQKeyboardManager.kIQPreviousNextButtonToolbarTag {
if let doneBarButtonItemImage = toolbarDoneBarButtonItemImage {
if toolbar.doneImage?.isEqual(doneBarButtonItemImage) == false {
textField.addPreviousNextRightOnKeyboardWithTarget(self, rightButtonImage: toolbarDoneBarButtonItemImage!, previousAction: #selector(self.previousAction(_:)), nextAction: #selector(self.nextAction(_:)), rightButtonAction: #selector(self.doneAction(_:)), shouldShowPlaceholder: shouldShowTextFieldPlaceholder)
needReload = true
}
}
//Supporting Custom Done button text (Enhancement ID: #209, #411, Bug ID: #376)
else if let doneBarButtonItemText = toolbarDoneBarButtonItemText {
if toolbar.doneTitle != doneBarButtonItemText {
textField.addPreviousNextRightOnKeyboardWithTarget(self, rightButtonTitle: toolbarDoneBarButtonItemText!, previousAction: #selector(self.previousAction(_:)), nextAction: #selector(self.nextAction(_:)), rightButtonAction: #selector(self.doneAction(_:)), shouldShowPlaceholder: shouldShowTextFieldPlaceholder)
needReload = true
}
} else if (toolbarDoneBarButtonItemText == nil && toolbar.doneTitle != nil) ||
(toolbarDoneBarButtonItemImage == nil && toolbar.doneImage != nil) {
//Now adding textField placeholder text as title of IQToolbar (Enhancement ID: #27)
textField.addPreviousNextDoneOnKeyboardWithTarget(self, previousAction: #selector(self.previousAction(_:)), nextAction: #selector(self.nextAction(_:)), doneAction: #selector(self.doneAction(_:)), shouldShowPlaceholder: shouldShowTextFieldPlaceholder)
needReload = true
}
}
}
textField.inputAccessoryView?.tag = IQKeyboardManager.kIQPreviousNextButtonToolbarTag // (Bug ID: #78)
}
if textField.inputAccessoryView is IQToolbar &&
textField.inputAccessoryView?.tag == IQKeyboardManager.kIQPreviousNextButtonToolbarTag {
let toolbar = textField.inputAccessoryView as! IQToolbar
// Setting toolbar to keyboard.
if let _textField = textField as? UITextField {
//Bar style according to keyboard appearance
switch _textField.keyboardAppearance {
case UIKeyboardAppearance.dark:
toolbar.barStyle = UIBarStyle.black
toolbar.tintColor = UIColor.white
default:
toolbar.barStyle = UIBarStyle.default
if shouldToolbarUsesTextFieldTintColor {
toolbar.tintColor = _textField.tintColor
} else if let tintColor = toolbarTintColor {
toolbar.tintColor = tintColor
} else {
toolbar.tintColor = UIColor.black
}
}
} else if let _textView = textField as? UITextView {
//Bar style according to keyboard appearance
switch _textView.keyboardAppearance {
case UIKeyboardAppearance.dark:
toolbar.barStyle = UIBarStyle.black
toolbar.tintColor = UIColor.white
default:
toolbar.barStyle = UIBarStyle.default
if shouldToolbarUsesTextFieldTintColor {
toolbar.tintColor = _textView.tintColor
} else if let tintColor = toolbarTintColor {
toolbar.tintColor = tintColor
} else {
toolbar.tintColor = UIColor.black
}
}
}
//Setting toolbar title font. // (Enhancement ID: #30)
if shouldShowTextFieldPlaceholder == true &&
textField.shouldHidePlaceholderText == false {
//Updating placeholder font to toolbar. //(Bug ID: #148, #272)
if toolbar.title == nil ||
toolbar.title != textField.drawingPlaceholderText {
toolbar.title = textField.drawingPlaceholderText
}
//Setting toolbar title font. // (Enhancement ID: #30)
if placeholderFont != nil {
toolbar.titleFont = placeholderFont
}
}
else {
toolbar.title = nil
}
//In case of UITableView (Special), the next/previous buttons has to be refreshed everytime. (Bug ID: #56)
// If firstTextField, then previous should not be enabled.
if siblings[0] == textField {
if (siblings.count == 1) {
textField.setEnablePrevious(false, isNextEnabled: false)
} else {
textField.setEnablePrevious(false, isNextEnabled: true)
}
} else if siblings.last == textField { // If lastTextField then next should not be enaled.
textField.setEnablePrevious(true, isNextEnabled: false)
} else {
textField.setEnablePrevious(true, isNextEnabled: true)
}
}
if needReload {
textField.reloadInputViews()
}
}
}
}
let elapsedTime = CACurrentMediaTime() - startTime
showLog("****** \(#function) ended: \(elapsedTime) seconds ******")
}
/** Remove any toolbar if it is IQToolbar. */
fileprivate func removeToolbarIfRequired() { // (Bug ID: #18)
let startTime = CACurrentMediaTime()
showLog("****** \(#function) started ******")
// Getting all the sibling textFields.
if let siblings = responderViews() {
showLog("Found \(siblings.count) responder sibling(s)")
for view in siblings {
if let toolbar = view.inputAccessoryView as? IQToolbar {
//setInputAccessoryView: check (Bug ID: #307)
if view.responds(to: #selector(setter: UITextField.inputAccessoryView)) &&
(toolbar.tag == IQKeyboardManager.kIQDoneButtonToolbarTag || toolbar.tag == IQKeyboardManager.kIQPreviousNextButtonToolbarTag) {
if let textField = view as? UITextField {
textField.inputAccessoryView = nil
} else if let textView = view as? UITextView {
textView.inputAccessoryView = nil
}
}
}
}
}
let elapsedTime = CACurrentMediaTime() - startTime
showLog("****** \(#function) ended: \(elapsedTime) seconds ******")
}
/** reloadInputViews to reload toolbar buttons enable/disable state on the fly Enhancement ID #434. */
open func reloadInputViews() {
//If enabled then adding toolbar.
if privateIsEnableAutoToolbar() == true {
self.addToolbarIfRequired()
} else {
self.removeToolbarIfRequired()
}
}
///------------------
/// MARK: Debugging & Developer options
///------------------
open var enableDebugging = false
/**
@warning Use below methods to completely enable/disable notifications registered by library internally. Please keep in mind that library is totally dependent on NSNotification of UITextField, UITextField, Keyboard etc. If you do unregisterAllNotifications then library will not work at all. You should only use below methods if you want to completedly disable all library functions. You should use below methods at your own risk.
*/
open func registerAllNotifications() {
// Registering for keyboard notification.
NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillShow(_:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardDidShow(_:)), name: NSNotification.Name.UIKeyboardDidShow, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillHide(_:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardDidHide(_:)), name: NSNotification.Name.UIKeyboardDidHide, object: nil)
// Registering for UITextField notification.
registerTextFieldViewClass(UITextField.self, didBeginEditingNotificationName: NSNotification.Name.UITextFieldTextDidBeginEditing.rawValue, didEndEditingNotificationName: NSNotification.Name.UITextFieldTextDidEndEditing.rawValue)
// Registering for UITextView notification.
registerTextFieldViewClass(UITextView.self, didBeginEditingNotificationName: NSNotification.Name.UITextViewTextDidBeginEditing.rawValue, didEndEditingNotificationName: NSNotification.Name.UITextViewTextDidEndEditing.rawValue)
// Registering for orientation changes notification
NotificationCenter.default.addObserver(self, selector: #selector(self.willChangeStatusBarOrientation(_:)), name: NSNotification.Name.UIApplicationWillChangeStatusBarOrientation, object: UIApplication.shared)
// Registering for status bar frame change notification
NotificationCenter.default.addObserver(self, selector: #selector(self.didChangeStatusBarFrame(_:)), name: NSNotification.Name.UIApplicationDidChangeStatusBarFrame, object: UIApplication.shared)
}
open func unregisterAllNotifications() {
// Unregistering for keyboard notification.
NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillShow, object: nil)
NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardDidShow, object: nil)
NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillHide, object: nil)
NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardDidHide, object: nil)
// Unregistering for UITextField notification.
unregisterTextFieldViewClass(UITextField.self, didBeginEditingNotificationName: NSNotification.Name.UITextFieldTextDidBeginEditing.rawValue, didEndEditingNotificationName: NSNotification.Name.UITextFieldTextDidEndEditing.rawValue)
// Unregistering for UITextView notification.
unregisterTextFieldViewClass(UITextView.self, didBeginEditingNotificationName: NSNotification.Name.UITextViewTextDidBeginEditing.rawValue, didEndEditingNotificationName: NSNotification.Name.UITextViewTextDidEndEditing.rawValue)
// Unregistering for orientation changes notification
NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIApplicationWillChangeStatusBarOrientation, object: UIApplication.shared)
// Unregistering for status bar frame change notification
NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIApplicationDidChangeStatusBarFrame, object: UIApplication.shared)
}
fileprivate func showLog(_ logString: String) {
if enableDebugging {
print("IQKeyboardManager: " + logString)
}
}
}
| mit | a364bf2c1ceb1ee59ab5fb1cadd595da | 47.953388 | 434 | 0.565052 | 7.182434 | false | false | false | false |
sora0077/iTunesMusic | Sources/Model/Album.swift | 1 | 5473 | //
// Album.swift
// iTunesMusic
//
// Created by ๆ้ไน on 2016/07/02.
// Copyright ยฉ 2016ๅนด jp.sora0077. All rights reserved.
//
import Foundation
import RealmSwift
import RxSwift
import Timepiece
import APIKit
import ErrorEventHandler
private func getOrCreateCache(collectionId: Int, realm: Realm) -> _AlbumCache {
if let cache = realm.object(ofType: _AlbumCache.self, forPrimaryKey: collectionId) {
return cache
}
let cache = _AlbumCache()
cache.collectionId = collectionId
cache.collection = realm.object(ofType: _Collection.self, forPrimaryKey: collectionId)!
// swiftlint:disable:next force_try
try! realm.write {
realm.add(cache)
}
return cache
}
extension Model {
public final class Album: Fetchable, ObservableList, _ObservableList {
private var objectsToken: NotificationToken?
private var token: NotificationToken?
fileprivate let collectionId: Int
fileprivate let caches: Results<_AlbumCache>
fileprivate var tracks: Results<_Track>
public convenience init(collection: Collection) {
self.init(collectionId: collection.id)
}
public init(collectionId: Int) {
self.collectionId = collectionId
let realm = iTunesRealm()
let cache = getOrCreateCache(collectionId: collectionId, realm: realm)
caches = realm.objects(_AlbumCache.self).filter("collectionId = \(collectionId)")
tracks = caches[0].collection.sortedTracks
token = caches.observe { [weak self] changes in
guard let `self` = self else { return }
func updateObserver(with results: Results<_AlbumCache>) {
let tracks = results[0].collection.sortedTracks
self.objectsToken = tracks.observe { [weak self] changes in
self?._changes.onNext(CollectionChange(changes))
}
self.tracks = tracks
}
switch changes {
case .initial(let results):
updateObserver(with: results)
case .update(let results, deletions: _, insertions: let insertions, modifications: _):
if !insertions.isEmpty {
updateObserver(with: results)
}
case .error(let error):
fatalError("\(error)")
}
}
}
}
}
extension Model.Album: Playlist {
public var name: String { return collection.name }
public var allTrackCount: Int { return collection.trackCount }
public var trackCount: Int { return tracks.count }
public var isTrackEmpty: Bool { return tracks.isEmpty }
public func track(at index: Int) -> Track { return tracks[index] }
}
extension Model.Album {
public var collection: Collection {
return caches[0].collection
}
}
extension Model.Album: _Fetchable {
var _refreshAt: Date { return caches[0].refreshAt }
var _refreshDuration: Duration { return 60.minutes }
}
extension Model.Album: _FetchableSimple {
typealias Request = LookupWithIds<LookupResponse>
private var _collection: _Collection { return caches[0].collection }
func makeRequest(refreshing: Bool) -> Request? {
if !refreshing && _collection._trackCount == _collection.sortedTracks.count {
return nil
}
return LookupWithIds(id: collectionId)
}
func doResponse(_ response: Request.Response, request: Request, refreshing: Bool) -> RequestState {
let realm = iTunesRealm()
// swiftlint:disable:next force_try
try! realm.write {
var collectionNames: [Int: String] = [:]
var collectionCensoredNames: [Int: String] = [:]
response.objects.reversed().forEach {
switch $0 {
case .track(let obj):
if let c = obj._collection {
collectionNames[c._collectionId] = c._collectionName
collectionCensoredNames[c._collectionId] = c._collectionCensoredName
}
realm.add(obj, update: true)
case .collection(let obj):
if let name = collectionNames[obj._collectionId] {
obj._collectionName = name
}
if let name = collectionCensoredNames[obj._collectionId] {
obj._collectionCensoredName = name
}
realm.add(obj, update: true)
case .artist(let obj):
realm.add(obj, update: true)
case .unknown:()
}
}
let cache = getOrCreateCache(collectionId: collectionId, realm: realm)
cache.updateAt = Date()
if refreshing {
cache.refreshAt = Date()
}
}
return .done
}
}
extension Model.Album: Swift.Collection {
public var count: Int { return trackCount }
public var isEmpty: Bool { return isTrackEmpty }
public var startIndex: Int { return tracks.startIndex }
public var endIndex: Int { return tracks.endIndex }
public subscript (index: Int) -> Track { return track(at: index) }
public func index(after i: Int) -> Int {
return tracks.index(after: i)
}
}
| mit | 631a7613da0708a1e5ceb4c2d1c40b6b | 31.141176 | 103 | 0.585652 | 4.940325 | false | false | false | false |
tranhieutt/Swiftz | Swiftz/DictionaryExt.swift | 1 | 9069 | //
// DictionaryExt.swift
// Swiftz
//
// Created by Maxwell Swadling on 5/06/2014.
// Copyright (c) 2014 Maxwell Swadling. All rights reserved.
//
extension Dictionary {
/// Creates a Dictionary from a list of Key-Value pairs.
static func fromList(l : [(Key, Value)]) -> Dictionary<Key, Value> {
var d = Dictionary<Key, Value>(minimumCapacity: l.count)
l.forEach { (k, v) in
d[k] = v
}
return d
}
/// MARK: Query
/// Returns whether the given key exists in the receiver.
public func isMember(k : Key) -> Bool {
return self[k] != nil
}
/// Returns whether the given key does not exist in the receiver.
public func notMember(k : Key) -> Bool {
return !self.isMember(k)
}
/// Looks up a value in the receiver. If one is not found the default is used.
public func lookup(k : Key, def : Value) -> Value {
return self[k] ?? def
}
/// Returns a copy of the receiver with the given key associated with the given value.
public func insert(k : Key, v : Value) -> Dictionary<Key, Value> {
var d = self
d[k] = v
return d
}
/// Returns a copy of the receiver with the given key associated with the value returned from
/// a combining function. If the receiver does not contain a value for the given key this
/// function is equivalent to an `insert`.
public func insertWith(k : Key, v : Value, combiner : Value -> Value -> Value) -> Dictionary<Key, Value> {
return self.insertWithKey(k, v: v, combiner: { (_, newValue, oldValue) -> Value in
return combiner(newValue)(oldValue)
})
}
/// Returns a copy of the receiver with the given key associated with the value returned from
/// a combining function. If the receiver does not contain a value for the given key this
/// function is equivalent to an `insert`.
public func insertWith(k : Key, v : Value, combiner : (new : Value, old : Value) -> Value) -> Dictionary<Key, Value> {
return self.insertWith(k, v: v, combiner: curry(combiner))
}
/// Returns a copy of the receiver with the given key associated with the value returned from
/// a combining function. If the receiver does not contain a value for the given key this
/// function is equivalent to an `insert`.
public func insertWithKey(k : Key, v : Value, combiner : Key -> Value -> Value -> Value) -> Dictionary<Key, Value> {
if let oldV = self[k] {
return self.insert(k, v: combiner(k)(v)(oldV))
}
return self.insert(k, v: v)
}
/// Returns a copy of the receiver with the given key associated with the value returned from
/// a combining function. If the receiver does not contain a value for the given key this
/// function is equivalent to an `insert`.
public func insertWithKey(k : Key, v : Value, combiner : (key : Key, newValue : Value, oldValue : Value) -> Value) -> Dictionary<Key, Value> {
if let oldV = self[k] {
return self.insert(k, v: combiner(key: k, newValue: v, oldValue: oldV))
}
return self.insert(k, v: v)
}
/// Combines insert and retrieval of the old value if it exists.
public func insertLookupWithKey(k : Key, v : Value, combiner : (key : Key, newValue : Value, oldValue : Value) -> Value) -> (Optional<Value>, Dictionary<Key, Value>) {
return (self[k], self.insertWithKey(k, v: v, combiner: combiner))
}
/// MARK: Update
/// Returns a copy of the receiver with the value for the given key removed.
public func delete(k : Key) -> Dictionary<Key, Value> {
var d = self
d[k] = nil
return d
}
/// Updates a value at the given key with the result of the function provided. If the key is
/// not in the receiver this function is equivalent to `identity`.
public func adjust(k : Key, adjustment : Value -> Value) -> Dictionary<Key, Value> {
return self.adjustWithKey(k, adjustment: { (_, x) -> Value in
return adjustment(x)
})
}
/// Updates a value at the given key with the result of the function provided. If the key is
/// not in the receiver this function is equivalent to `identity`.
public func adjustWithKey(k : Key, adjustment : Key -> Value -> Value) -> Dictionary<Key, Value> {
return self.updateWithKey(k, update: { (k, x) -> Optional<Value> in
return .Some(adjustment(k)(x))
})
}
/// Updates a value at the given key with the result of the function provided. If the key is
/// not in the receiver this function is equivalent to `identity`.
public func adjustWithKey(k : Key, adjustment : (Key, Value) -> Value) -> Dictionary<Key, Value> {
return self.adjustWithKey(k, adjustment: curry(adjustment))
}
/// Updates a value at the given key with the result of the function provided. If the result of
/// the function is `.None`, the value associated with the given key is removed. If the key is
/// not in the receiver this function is equivalent to `identity`.
public func update(k : Key, update : Value -> Optional<Value>) -> Dictionary<Key, Value> {
return self.updateWithKey(k, update: { (_, x) -> Optional<Value> in
return update(x)
})
}
/// Updates a value at the given key with the result of the function provided. If the result of
/// the function is `.None`, the value associated with the given key is removed. If the key is
/// not in the receiver this function is equivalent to `identity`.
public func updateWithKey(k : Key, update : Key -> Value -> Optional<Value>) -> Dictionary<Key, Value> {
if let oldV = self[k], newV = update(k)(oldV) {
return self.insert(k, v: newV)
}
return self.delete(k)
}
/// Updates a value at the given key with the result of the function provided. If the result of
/// the function is `.None`, the value associated with the given key is removed. If the key is
/// not in the receiver this function is equivalent to `identity`.
public func updateWithKey(k : Key, update : (Key, Value) -> Optional<Value>) -> Dictionary<Key, Value> {
return self.updateWithKey(k, update: curry(update))
}
/// Alters the value (if any) for a given key with the result of the function provided. If the
/// result of the function is `.None`, the value associated with the given key is removed.
public func alter(k : Key, alteration : Optional<Value> -> Optional<Value>) -> Dictionary<Key, Value> {
if let newV = alteration(self[k]) {
return self.insert(k, v: newV)
}
return self.delete(k)
}
/// MARK: Map
/// Maps a function over all values in the receiver.
public func map<Value2>(f : Value -> Value2) -> Dictionary<Key, Value2> {
return self.mapWithKey({ (_, x) -> Value2 in
return f(x)
})
}
/// Maps a function over all keys and values in the receiver.
public func mapWithKey<Value2>(f : Key -> Value -> Value2) -> Dictionary<Key, Value2> {
var d = Dictionary<Key, Value2>()
self.forEach { (k, v) in
d[k] = f(k)(v)
}
return d
}
/// Maps a function over all keys and values in the receiver.
public func mapWithKey<Value2>(f : (Key, Value) -> Value2) -> Dictionary<Key, Value2> {
return self.mapWithKey(curry(f))
}
/// Maps a function over all keys in the receiver.
public func mapKeys<Key2 : Hashable>(f : Key -> Key2) -> Dictionary<Key2, Value> {
var d = Dictionary<Key2, Value>()
self.forEach { (k, v) in
d[f(k)] = v
}
return d
}
/// MARK: Partition
/// Filters all values that do not satisfy a given predicate from the receiver.
public func filter(pred : Value -> Bool) -> Dictionary<Key, Value> {
return self.filterWithKey({ (_, x) -> Bool in
return pred(x)
})
}
/// Filters all keys and values that do not satisfy a given predicate from the receiver.
public func filterWithKey(pred : Key -> Value -> Bool) -> Dictionary<Key, Value> {
var d = Dictionary<Key, Value>()
self.forEach { (k, v) in
if pred(k)(v) {
d[k] = v
}
}
return d
}
/// Filters all keys and values that do not satisfy a given predicate from the receiver.
public func filterWithKey(pred : (Key, Value) -> Bool) -> Dictionary<Key, Value> {
return self.filterWithKey(curry(pred))
}
/// Partitions the receiver into a Dictionary of values that passed the given predicate and a
/// Dictionary of values that failed the given predicate.
public func partition(pred : Value -> Bool) -> (passed : Dictionary<Key, Value>, failed : Dictionary<Key, Value>) {
return self.partitionWithKey({ (_, x) -> Bool in
return pred(x)
})
}
/// Partitions the receiver into a Dictionary of values that passed the given predicate and a
/// Dictionary of values that failed the given predicate.
public func partitionWithKey(pred : Key -> Value -> Bool) -> (passed : Dictionary<Key, Value>, failed : Dictionary<Key, Value>) {
var pass = Dictionary<Key, Value>()
var fail = Dictionary<Key, Value>()
self.forEach { (k, v) in
if pred(k)(v) {
pass[k] = v
} else {
fail[k] = v
}
}
return (pass, fail)
}
/// Partitions the receiver into a Dictionary of values that passed the given predicate and a
/// Dictionary of values that failed the given predicate.
public func partitionWithKey(pred : (Key, Value) -> Bool) -> (passed : Dictionary<Key, Value>, failed : Dictionary<Key, Value>) {
return self.partitionWithKey(curry(pred))
}
}
| bsd-3-clause | 88b6584d91da9e74f2ba26a385002f45 | 37.265823 | 168 | 0.677804 | 3.450913 | false | false | false | false |
stripe/stripe-ios | StripeIdentity/StripeIdentity/Source/NativeComponents/Detectors/BarcodeDetector.swift | 1 | 3098 | //
// BarcodeDetector.swift
// StripeIdentity
//
// Created by Mel Ludowise on 2/25/22.
// Copyright ยฉ 2022 Stripe, Inc. All rights reserved.
//
import Foundation
import Vision
struct BarcodeDetectorOutput: Equatable {
let hasBarcode: Bool
let isTimedOut: Bool
let symbology: VNBarcodeSymbology
let timeTryingToFindBarcode: TimeInterval
}
extension BarcodeDetectorOutput: VisionBasedDetectorOutput {
init(
detector: BarcodeDetector,
observations: [VNObservation],
originalImageSize: CGSize
) throws {
let barcodeObservations: [VNBarcodeObservation] = observations.compactMap {
guard let observation = $0 as? VNBarcodeObservation,
detector.configuration.symbology == observation.symbology
else {
return nil
}
return observation
}
var timeTryingToFindBarcode: TimeInterval = -1
if let firstScanTimestamp = detector.firstScanTimestamp {
timeTryingToFindBarcode = Date().timeIntervalSince(firstScanTimestamp)
}
self.init(
hasBarcode: !barcodeObservations.isEmpty,
isTimedOut: false,
symbology: detector.configuration.symbology,
timeTryingToFindBarcode: timeTryingToFindBarcode
)
}
}
final class BarcodeDetector: VisionBasedDetector {
struct Configuration {
/// Which type of barcode symbology to scan for
let symbology: VNBarcodeSymbology
/// The amount of time to look for a barcode before accepting images without
let timeout: TimeInterval
}
/// Wrap all instance property modifications in a serial queue
private let serialQueue = DispatchQueue(label: "com.stripe.identity.barcode-detector")
fileprivate var firstScanTimestamp: Date?
let configuration: Configuration
let metricsTracker: MLDetectorMetricsTracker? = nil
init(
configuration: Configuration
) {
self.configuration = configuration
}
func visionBasedDetectorMakeRequest() -> VNImageBasedRequest {
let request = VNDetectBarcodesRequest()
request.symbologies = [configuration.symbology]
return request
}
func visionBasedDetectorOutputIfSkipping() -> BarcodeDetectorOutput? {
let timeOfScanRequest = Date()
var timeSinceScan: TimeInterval = 0
serialQueue.sync { [weak self] in
let firstScanTimestamp = self?.firstScanTimestamp ?? timeOfScanRequest
self?.firstScanTimestamp = firstScanTimestamp
timeSinceScan = timeOfScanRequest.timeIntervalSince(firstScanTimestamp)
}
guard timeSinceScan >= configuration.timeout else {
return nil
}
return .init(
hasBarcode: false,
isTimedOut: true,
symbology: configuration.symbology,
timeTryingToFindBarcode: timeSinceScan
)
}
func reset() {
serialQueue.async { [weak self] in
self?.firstScanTimestamp = nil
}
}
}
| mit | 70ad0525f8c6ea109e54d7c3833f28ca | 29.362745 | 90 | 0.659348 | 5.520499 | false | true | false | false |
eurofurence/ef-app_ios | Packages/EurofurenceModel/Sources/EurofurenceModel/Private/Services/ConcreteSessionStateService.swift | 1 | 1898 | import Foundation
class ConcreteSessionStateService: SessionStateService {
private let forceRefreshRequired: ForceRefreshRequired
private let userPreferences: UserPreferences
private let dataStore: DataStore
private var dataStoreChangedRegistration: Any?
private var observers = [any SessionStateObserver]()
private var lastNotifiedState: EurofurenceSessionState?
init(
eventBus: EventBus,
forceRefreshRequired: ForceRefreshRequired,
userPreferences: UserPreferences,
dataStore: DataStore
) {
self.forceRefreshRequired = forceRefreshRequired
self.userPreferences = userPreferences
self.dataStore = dataStore
self.lastNotifiedState = currentState
let updateSessionState = DataStoreChangedConsumer("ConcreteSessionStateService") { [weak self] in
self?.notifyObserversOfCurrentState()
}
dataStoreChangedRegistration = eventBus.subscribe(consumer: updateSessionState, priority: .last)
}
private var currentState: EurofurenceSessionState {
let shouldPerformForceRefresh: Bool = forceRefreshRequired.isForceRefreshRequired
guard dataStore.fetchLastRefreshDate() != nil else { return .uninitialized }
let dataStoreStale = shouldPerformForceRefresh || userPreferences.refreshStoreOnLaunch
return dataStoreStale ? .stale : .initialized
}
private func notifyObserversOfCurrentState() {
let state = currentState
guard state != lastNotifiedState else { return }
for observer in observers {
observer.sessionStateDidChange(state)
}
lastNotifiedState = state
}
func add(observer: any SessionStateObserver) {
observers.append(observer)
observer.sessionStateDidChange(currentState)
}
}
| mit | 5fa8d6b41795ef8083fab120e6928749 | 33.509091 | 105 | 0.69863 | 6.142395 | false | false | false | false |
open-telemetry/opentelemetry-swift | Tests/ExportersTests/PersistenceExporter/Helpers/CoreMocks.swift | 1 | 7142 | /*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
@testable import PersistenceExporter
import Foundation
// MARK: - PerformancePreset Mocks
struct StoragePerformanceMock: StoragePerformancePreset {
let maxFileSize: UInt64
let maxDirectorySize: UInt64
let maxFileAgeForWrite: TimeInterval
let minFileAgeForRead: TimeInterval
let maxFileAgeForRead: TimeInterval
let maxObjectsInFile: Int
let maxObjectSize: UInt64
static let readAllFiles = StoragePerformanceMock(
maxFileSize: .max,
maxDirectorySize: .max,
maxFileAgeForWrite: 0,
minFileAgeForRead: -1, // make all files eligible for read
maxFileAgeForRead: .distantFuture, // make all files eligible for read
maxObjectsInFile: .max,
maxObjectSize: .max
)
static let writeEachObjectToNewFileAndReadAllFiles = StoragePerformanceMock(
maxFileSize: .max,
maxDirectorySize: .max,
maxFileAgeForWrite: 0, // always return new file for writting
minFileAgeForRead: readAllFiles.minFileAgeForRead,
maxFileAgeForRead: readAllFiles.maxFileAgeForRead,
maxObjectsInFile: 1, // write each data to new file
maxObjectSize: .max
)
static let writeAllObjectsToTheSameFile = StoragePerformanceMock(
maxFileSize: .max,
maxDirectorySize: .max,
maxFileAgeForWrite: .distantFuture,
minFileAgeForRead: -1, // make all files eligible for read
maxFileAgeForRead: .distantFuture, // make all files eligible for read
maxObjectsInFile: .max,
maxObjectSize: .max
)
}
struct ExportPerformanceMock: ExportPerformancePreset {
let initialExportDelay: TimeInterval
let defaultExportDelay: TimeInterval
let minExportDelay: TimeInterval
let maxExportDelay: TimeInterval
let exportDelayChangeRate: Double
static let veryQuick = ExportPerformanceMock(
initialExportDelay: 0.05,
defaultExportDelay: 0.05,
minExportDelay: 0.05,
maxExportDelay: 0.05,
exportDelayChangeRate: 0
)
}
extension PersistencePerformancePreset {
static func mockWith(storagePerformance: StoragePerformancePreset,
synchronousWrite: Bool,
exportPerformance: ExportPerformancePreset) -> PersistencePerformancePreset {
return PersistencePerformancePreset(maxFileSize: storagePerformance.maxFileSize,
maxDirectorySize: storagePerformance.maxDirectorySize,
maxFileAgeForWrite: storagePerformance.maxFileAgeForWrite,
minFileAgeForRead: storagePerformance.minFileAgeForRead,
maxFileAgeForRead: storagePerformance.maxFileAgeForRead,
maxObjectsInFile: storagePerformance.maxObjectsInFile,
maxObjectSize: storagePerformance.maxObjectSize,
synchronousWrite: synchronousWrite,
initialExportDelay: exportPerformance.initialExportDelay,
defaultExportDelay: exportPerformance.defaultExportDelay,
minExportDelay: exportPerformance.minExportDelay,
maxExportDelay: exportPerformance.maxExportDelay,
exportDelayChangeRate: exportPerformance.exportDelayChangeRate)
}
}
/// `DateProvider` mock returning consecutive dates in custom intervals, starting from given reference date.
class RelativeDateProvider: DateProvider {
private(set) var date: Date
internal let timeInterval: TimeInterval
private let queue = DispatchQueue(label: "queue-RelativeDateProvider-\(UUID().uuidString)")
private init(date: Date, timeInterval: TimeInterval) {
self.date = date
self.timeInterval = timeInterval
}
convenience init(using date: Date = Date()) {
self.init(date: date, timeInterval: 0)
}
convenience init(startingFrom referenceDate: Date = Date(), advancingBySeconds timeInterval: TimeInterval = 0) {
self.init(date: referenceDate, timeInterval: timeInterval)
}
/// Returns current date and advances next date by `timeInterval`.
func currentDate() -> Date {
defer {
queue.async {
self.date.addTimeInterval(self.timeInterval)
}
}
return queue.sync {
return date
}
}
/// Pushes time forward by given number of seconds.
func advance(bySeconds seconds: TimeInterval) {
queue.async {
self.date = self.date.addingTimeInterval(seconds)
}
}
}
struct DataExporterMock: DataExporter {
let exportStatus: DataExportStatus
var onExport: ((Data) -> Void)? = nil
func export(data: Data) -> DataExportStatus {
onExport?(data)
return exportStatus
}
}
extension DataExportStatus {
static func mockWith(needsRetry: Bool) -> DataExportStatus {
return DataExportStatus(needsRetry: needsRetry)
}
}
class FileWriterMock: FileWriter {
var onWrite: ((Bool, Data) -> Void)? = nil
func write(data: Data) {
onWrite?(false, data)
}
func writeSync(data: Data) {
onWrite?(true, data)
}
var onFlush: (() -> Void)? = nil
func flush() {
onFlush?()
}
}
class FileReaderMock: FileReader {
private class ReadableFileMock: ReadableFile {
private var deleted = false
private let data: Data
private(set) var name: String
init(name: String, data: Data) {
self.name = name
self.data = data
}
func read() throws -> Data {
guard deleted == false else {
throw ErrorMock("read failed because delete was called")
}
return data
}
func delete() throws {
deleted = true
}
}
var files: [ReadableFile] = []
func addFile(name: String, data: Data) {
files.append(ReadableFileMock(name: name, data: data))
}
func readNextBatch() -> Batch? {
if let file = files.first,
let fileData = try? file.read() {
return Batch(data: fileData, file: file)
}
return nil
}
func onRemainingBatches(process: (Batch) -> ()) -> Bool {
do {
try files.forEach {
let fileData = try $0.read()
process(Batch(data: fileData, file: $0))
}
return true
} catch {
return false
}
}
func markBatchAsRead(_ batch: Batch) {
try? batch.file.delete()
files.removeAll { file -> Bool in
return file.name == batch.file.name
}
}
}
| apache-2.0 | 9ed6280528a098aa19d1ec3beb17151a | 31.316742 | 116 | 0.603892 | 5.51932 | false | false | false | false |
bengottlieb/HelpKit | HelpKit/Framework Code/Walkthrough.swift | 1 | 4375 | //
// Walkthrough.swift
// HelpKit
//
// Created by Ben Gottlieb on 2/18/17.
// Copyright ยฉ 2017 Stand Alone, Inc. All rights reserved.
//
import UIKit
public typealias Scene = WalkthroughScene
open class Walkthrough: UIViewController {
public var contentInset: UIEdgeInsets = .zero
var scenes: [Scene] = []
var visible: [Scene] = []
weak var nextSceneTimer: Timer?
var contentFrame: CGRect {
let bounds = self.view.bounds
return CGRect(x: bounds.origin.x + self.contentInset.left,
y: bounds.origin.y + self.contentInset.top,
width: bounds.width - (self.contentInset.left + self.contentInset.right),
height: bounds.height - (self.contentInset.top + self.contentInset.bottom))
}
required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder); self.didInit() }
public init() { super.init(nibName: nil, bundle: nil); self.didInit() }
open func didInit() { }
open func reset() {
self.visible.forEach { $0.remove() }
self.visible = []
}
open func clearScenes() {
self.reset()
self.scenes = []
}
open func present(in parent: UIViewController) {
self.willMove(toParentViewController: parent)
parent.addChildViewController(self)
self.view.frame = parent.view.bounds
parent.view.addSubview(self.view)
self.didMove(toParentViewController: parent)
self.start()
}
open func dismiss(animated: Bool = true) {
self.willMove(toParentViewController: nil)
self.removeFromParentViewController()
self.view.removeFromSuperview()
self.didMove(toParentViewController: nil)
}
public func add(scene: Scene) {
if self.scenes.count == 0 { scene.replacesExisting = true }
scene.walkthrough = self
self.scenes.append(scene)
}
public func add(ids: [String], from storyboard: UIStoryboard) {
for id in ids {
if let scene = storyboard.instantiateViewController(withIdentifier: id) as? Scene { self.add(scene: scene) }
}
}
@discardableResult public func apply(_ transition: Transition, direction: Walkthrough.Direction = .out, batchID: String, over duration: TimeInterval) -> TimeInterval {
let views = self.viewsWith(batchID: batchID)
if views.count == 0 {
print("Unable to find any views with a batch ID: \(batchID)")
return 0
}
return self.apply(transition, direction: direction, to: views, over: duration)
}
@discardableResult public func apply(_ transition: Transition, direction: Walkthrough.Direction = .out, sceneID: String, over duration: TimeInterval) -> TimeInterval {
guard let view = self.existingView(with: sceneID) else {
print("Unable to find any views with a sceneID: \(sceneID)")
return 0
}
return self.apply(transition, direction: direction, to: [view], over: duration)
}
@discardableResult public func apply(_ transition: Transition, direction: Walkthrough.Direction = .out, to views: [UIView], over duration: TimeInterval) -> TimeInterval {
guard let current = self.visible.last else { return 0 }
var maxDuration: TimeInterval = 0
views.forEach { view in
maxDuration = max(maxDuration, view.apply(transition, for: direction, duration: duration, in: current))
}
return maxDuration
}
}
extension Walkthrough {
open override func viewDidLoad() {
super.viewDidLoad()
}
}
extension Walkthrough {
public func start() {
self.show(next: self.scenes.first!)
}
public func show(next scene: Scene) {
if scene.replacesExisting {
self.visible.forEach { $0.remove() }
self.visible = []
}
self.visible.append(scene)
scene.show(in: self)
}
func advanceToNext() { self.advance() }
public func advance() {
guard let current = self.visible.last, let index = self.scenes.index(of: current) else { return }
if index >= self.scenes.count - 1 {
} else {
let scene = self.scenes[index + 1]
self.show(next: scene)
}
}
}
extension Walkthrough {
func existingView(with id: String) -> UIView? {
for view in self.viewsWithSceneIDs { if view.helpKitSceneID == id {
return view
}}
return nil
}
var viewsWithSceneIDs: [UIView] {
var views: [UIView] = []
for scene in self.visible { views += scene.view.viewsWithSceneIDs }
return views
}
func viewsWith(batchID: String) -> [UIView] {
var views: [UIView] = []
for scene in self.visible { views += scene.view.viewsMatching(batchID: batchID) }
return views
}
}
| mit | 501318cb217fd06b247b89a228b36087 | 27.038462 | 171 | 0.695016 | 3.516077 | false | false | false | false |
blackbear/OpenHumansUpload | OpenHumansUpload/OpenHumansUpload/OH_OAuth2.swift | 1 | 16600 | //
// OH-Oauth2.swift
// OpenHumansUpload
//
// Created by James Turner on 6/7/16.
//
/**
The MIT License (MIT)
Copyright (c) 2016 James M. Turner
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
**/
import Foundation
import UIKit
import SafariServices
typealias JSON = AnyObject
typealias JSONDictionary = Dictionary<String, JSON>
typealias JSONArray = Array<JSON>
class PopupWebViewController : ViewController {
var previousViewController : ViewController?
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder);
}
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
super.init(nibName:nibNameOrNil, bundle:nibBundleOrNil )
}
}
enum AuthorizationStatus {
case AUTHORIZED
case CANCELED
case FAILED
case REQUIRES_LOGIN
}
let oauthsharedInstance = OH_OAuth2()
class OH_OAuth2 : NSObject, SFSafariViewControllerDelegate {
static func sharedInstance() -> OH_OAuth2 {
return oauthsharedInstance;
}
var wv_vc : SFSafariViewController?
var memberId : String?
/// The username used to authenticate OAuth2 requests with the OpenHumans server. Found on the project page for your activity / study
var ohClientId=""
/// The password used to authenticate OAuth2 requests with the OpenHumans server. Found on the project page for your activity / study
var ohSecretKey=""
/// The URL scheme that has been registered for Open Humans with this activity / study
var applicationURLScheme=""
override init() {
super.init()
if let path = NSBundle.mainBundle().pathForResource("OhSettings", ofType: "plist"), dict = NSDictionary(contentsOfFile: path) as? [String: AnyObject] {
ohSecretKey = dict["oh_client_secret"] as! String
ohClientId = dict["oh_client_id"] as! String
applicationURLScheme = dict["oh_url_prefix"] as! String
}
}
enum GrantType {
case Authorize, Refresh
}
/// Get member info from token
///
func getMemberInfo(onSuccess: (memberId : String, messagePermission : Bool, usernameShared : Bool, username : String?, files: JSONArray) -> Void, onFailure:() ->Void) -> Void {
let prefs = NSUserDefaults.standardUserDefaults()
let accessToken = prefs.stringForKey("oauth2_access_token")
let request = NSMutableURLRequest(URL: NSURL (string: "https://www.openhumans.org/api/direct-sharing/project/exchange-member/?access_token=" + accessToken!)!)
let loginString = NSString(format: "%@:%@", ohClientId, ohSecretKey)
let loginData: NSData = loginString.dataUsingEncoding(NSUTF8StringEncoding)!
let base64LoginString = loginData.base64EncodedStringWithOptions([])
request.setValue("Basic \(base64LoginString)", forHTTPHeaderField: "Authorization")
let session = NSURLSession.sharedSession()
request.HTTPMethod = "GET"
request.addValue("application/json", forHTTPHeaderField: "Accept")
let task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
do {
let htresponse = response as! NSHTTPURLResponse
if (htresponse.statusCode != 200) {
onFailure()
}
var json = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions()) as? JSONDictionary
if let json = json {
if (json["project_member_id"] != nil) {
self.memberId = (json["project_member_id"] as! String)
let messagePermission = json["message_permission"] as! Bool
var usernameShared = false
var fileList = [] as! JSONArray
var username = ""
if let x = json["username_shared"] {
usernameShared = x as! Bool
}
if let x = json["data"] {
fileList = x as! JSONArray
}
// let sources_shared = json!["sources_shared"] as! Dictionary
if let x = json["username"] {
username = json["username"] as! String
}
onSuccess(memberId: self.memberId!, messagePermission: messagePermission, usernameShared: usernameShared, username: username, files:fileList)
return
}
}
onFailure()
} catch {
print(error)
}
});
task.resume()
}
/// This function should be called from the `openURL` handler of your application to intercept and handle
/// Open Humans OAuth2 callbacks. If it returns true, the URL was handled and no further processing of the
/// URL should be attempted.
func parseLaunchURL(url : NSURL) -> Bool {
let components = NSURLComponents.init(URL: url, resolvingAgainstBaseURL: false)
if components?.scheme != applicationURLScheme {
return false;
}
if let queryItems = components?.queryItems {
for queryItem in queryItems {
if queryItem.name == "code" {
self.sendTokenRequestWithToken(queryItem.value!, grantType: GrantType.Authorize);
}
}
}
return true;
}
func processResponse(data : NSData?, error: NSError?, grantType : GrantType) -> Void {
if (error != nil) {
for client in self.subscribers {
self.clearCachedToken()
if grantType == .Refresh {
client(status: AuthorizationStatus.REQUIRES_LOGIN)
} else {
client(status: AuthorizationStatus.FAILED)
}
}
self.subscribers.removeAll()
return;
}
do {
var json = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions()) as? JSONDictionary
let accessToken = json!["access_token"] as! String
let refreshToken = json!["refresh_token"] as! String
let prefs = NSUserDefaults.standardUserDefaults()
prefs.setValue(refreshToken, forKeyPath:"oauth2_refresh_token")
prefs.setValue(accessToken, forKeyPath:"oauth2_access_token")
for client in self.subscribers {
client(status: AuthorizationStatus.AUTHORIZED)
}
self.subscribers.removeAll()
} catch {
print(error)
}
}
func sendTokenRequestWithToken(token : String, grantType : GrantType) -> Void {
var reqString = "";
switch (grantType) {
case GrantType.Authorize:
reqString = "grant_type=authorization_code&code=" + token + "&redirect_uri=" + self.applicationURLScheme + "://";
case GrantType.Refresh:
reqString = "grant_type=refresh_token&refresh_token=" + token + "&redirect_uri=" + self.applicationURLScheme + "://";
}
let request = NSMutableURLRequest(URL: NSURL(string: "https://www.openhumans.org/oauth2/token/")!)
let session = NSURLSession.sharedSession()
request.HTTPMethod = "POST"
let loginString = NSString(format: "%@:%@", ohClientId, ohSecretKey)
let loginData: NSData = loginString.dataUsingEncoding(NSUTF8StringEncoding)!
let base64LoginString = loginData.base64EncodedStringWithOptions([])
request.setValue("Basic \(base64LoginString)", forHTTPHeaderField: "Authorization")
request.HTTPBody = reqString.dataUsingEncoding(NSUTF8StringEncoding)
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
// request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
let task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
if self.wv_vc != nil {
dispatch_async(dispatch_get_main_queue(), {
self.wv_vc?.dismissViewControllerAnimated(true, completion: {
self.processResponse(data, error:error, grantType:grantType)
})
})
} else {
let httpResponse = response as! NSHTTPURLResponse
if httpResponse.statusCode == 401 {
self.clearCachedToken()
for client in self.subscribers {
if grantType == .Refresh {
client(status: AuthorizationStatus.REQUIRES_LOGIN)
} else {
client(status: AuthorizationStatus.FAILED)
}
}
self.subscribers.removeAll()
}
self.processResponse(data, error:error, grantType:grantType);
}
});
task.resume()
}
var subscribers: [(status: AuthorizationStatus) -> Void] = Array();
func subscribeToEvents(listener: (status: AuthorizationStatus) -> Void) {
subscribers.append(listener)
}
func hasCachedToken() -> Bool {
let prefs = NSUserDefaults.standardUserDefaults()
return prefs.stringForKey("oauth2_refresh_token") != nil
}
func clearCachedToken() -> Void {
let prefs = NSUserDefaults.standardUserDefaults()
prefs.removeObjectForKey("oauth2_refresh_token")
prefs.removeObjectForKey("oauth2_access_token")
}
func closeWeb () -> Void {
if self.wv_vc != nil {
self.wv_vc?.dismissViewControllerAnimated(true, completion: {
for client in self.subscribers {
client(status: AuthorizationStatus.CANCELED)
}
})
} else {
for client in self.subscribers {
client(status: AuthorizationStatus.CANCELED)
}
}
self.subscribers.removeAll()
self.wv_vc = nil;
}
func safariViewControllerDidFinish(controller: SFSafariViewController)
{
controller.dismissViewControllerAnimated(true, completion: nil)
}
func authenticateOAuth2(vc:ViewController, allowLogin:Bool, handler:(status: AuthorizationStatus)->Void) -> Void {
subscribers.append(handler)
let prefs = NSUserDefaults.standardUserDefaults()
if let token = prefs.stringForKey("oauth2_refresh_token") {
sendTokenRequestWithToken(token, grantType: GrantType.Refresh)
return
}
if allowLogin {
let url = NSURL (string: "https://www.openhumans.org/direct-sharing/projects/oauth2/authorize/?client_id=" + ohClientId + "&response_type=code");
self.wv_vc = SFSafariViewController(URL: url!);
vc.presentViewController(self.wv_vc!, animated: true, completion: nil)
} else {
handler(status: AuthorizationStatus.REQUIRES_LOGIN)
}
}
func deleteFile(id : NSNumber, handler:(success: Bool) -> Void) {
let prefs = NSUserDefaults.standardUserDefaults()
let accessToken = prefs.stringForKey("oauth2_access_token")
let reqString = "https://www.openhumans.org/api/direct-sharing/project/files/delete/?access_token=" + accessToken!;
let request = NSMutableURLRequest(URL: NSURL(string: reqString)!)
let session = NSURLSession.sharedSession()
request.HTTPMethod = "POST"
let loginString = NSString(format: "%@:%@", ohClientId, ohSecretKey)
let loginData: NSData = loginString.dataUsingEncoding(NSUTF8StringEncoding)!
let base64LoginString = loginData.base64EncodedStringWithOptions([])
request.setValue("Basic \(base64LoginString)", forHTTPHeaderField: "Authorization")
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
let httpBody = "{\"project_member_id\": \"" + self.memberId! + "\", \"file_id\": " + id.stringValue + "}"
request.HTTPBody = httpBody.dataUsingEncoding(NSUTF8StringEncoding)
request.addValue("application/json", forHTTPHeaderField: "Accept")
let task = session.dataTaskWithRequest(request, completionHandler: {data1, response, error -> Void in
let httpResponse = response as! NSHTTPURLResponse
if httpResponse.statusCode != 200 {
handler(success: false)
return
}
handler(success:true)
});
task.resume()
}
func uploadFile(fileName : String, data : String, memberId : String, handler:(success: Bool, filename: String?) -> Void) -> Void {
let dic = NSProcessInfo.processInfo().environment
if dic["dont_send"] != nil {
NSLog("Sending file %@ with data %@", fileName, data)
handler(success: true, filename: nil)
return
}
let prefs = NSUserDefaults.standardUserDefaults()
let accessToken = prefs.stringForKey("oauth2_access_token")
let reqString = "https://www.openhumans.org/api/direct-sharing/project/files/upload/?access_token=" + accessToken!;
let request = NSMutableURLRequest(URL: NSURL(string: reqString)!)
let session = NSURLSession.sharedSession()
request.HTTPMethod = "POST"
let loginString = NSString(format: "%@:%@", ohClientId, ohSecretKey)
let loginData: NSData = loginString.dataUsingEncoding(NSUTF8StringEncoding)!
let base64LoginString = loginData.base64EncodedStringWithOptions([])
request.setValue("Basic \(base64LoginString)", forHTTPHeaderField: "Authorization")
request.setValue("multipart/form-data; boundary=60b1416fed664815a28bf8be840458ae", forHTTPHeaderField: "Content-Type")
let httpBody = "--60b1416fed664815a28bf8be840458ae\r\n" +
"Content-Disposition: form-data; name=\"project_member_id\"\r\n\r\n" +
memberId +
"\r\n--60b1416fed664815a28bf8be840458ae\r\n" +
"Content-Disposition: form-data; name=\"metadata\"\r\n\r\n" +
"{\"tags\": [\"healthkit\",\"json\"], \"description\": \"JSON dump of Healthkit Data\"}\r\n" +
"--60b1416fed664815a28bf8be840458ae\r\n" +
"Content-Disposition: form-data; name=\"data_file\"; filename=\"" + fileName + "\"\r\n\r\n" + data +
"\r\n\r\n--60b1416fed664815a28bf8be840458ae--\r\n"
request.HTTPBody = httpBody.dataUsingEncoding(NSUTF8StringEncoding)
request.addValue("application/json", forHTTPHeaderField: "Accept")
let task = session.dataTaskWithRequest(request, completionHandler: {data1, response, error -> Void in
let httpResponse = response as! NSHTTPURLResponse
if httpResponse.statusCode != 201 {
handler(success: false, filename: nil)
return
}
handler(success:true, filename: String(data: data1!, encoding: NSUTF8StringEncoding)!)
});
task.resume()
}
}
| mit | ee53170320417ae1c260a76142b9cbec | 42.915344 | 180 | 0.611446 | 5.15528 | false | false | false | false |
mbernson/HomeControl.iOS | HomeControl/Clients/MqttHomeClient.swift | 1 | 3986 | //
// MqttHomeClient.swift
// HomeControl
//
// Created by Mathijs Bernson on 05/02/16.
// Copyright ยฉ 2016 Duckson. All rights reserved.
//
import Foundation
import Promissum
import RxSwift
import MQTTClient
class MqttHomeClient: HomeClient {
class MqttHomeDelegate: NSObject, MQTTSessionDelegate {
var observer: AnyObserver<Message>!
init(observer: AnyObserver<Message>) {
print("MqttHomeDelegate init")
self.observer = observer
}
deinit {
print("MqttHomeDelegate deinit")
}
func newMessage(_ session: MQTTSession!, data: Data!, onTopic topic: String!, qos: MQTTQosLevel, retained: Bool, mid: UInt32) {
let message = Message(topic: topic, payload: data, qos: Message.QoS.fromMqttQoS(qos), retain: retained)
print("received a message on topic \(topic) with content \(message.payloadString)")
observer.on(.next(message))
}
func subAckReceived(_ session: MQTTSession!, msgID: UInt16, grantedQoss qoss: [NSNumber]!) {
print("subscribe acknowledged")
}
func unsubAckReceived(_ session: MQTTSession!, msgID: UInt16) {
print("unsubscribe acknowledged")
}
}
let mqttSession: MQTTSession
let messages: Observable<Message>
var currentObserver: AnyObserver<Message>?
var topics = [Topic]()
convenience init(userDefaults: Foundation.UserDefaults = Foundation.UserDefaults.standard) {
let host = userDefaults.string(forKey: "mqtt_host")!
let port = UInt16(userDefaults.integer(forKey: "mqtt_port"))
self.init(host: host, port: port)
}
init(host: String, port: UInt16) {
let mqttTransport: MQTTCFSocketTransport
let mqttSession: MQTTSession
var delegate: MqttHomeDelegate? = nil
var currentObserver: AnyObserver<Message>? = nil
mqttTransport = MQTTCFSocketTransport()
mqttTransport.host = host
mqttTransport.port = port
mqttSession = MQTTSession()
mqttSession.transport = mqttTransport
self.mqttSession = mqttSession
self.messages = Observable.create { observer in
delegate = MqttHomeDelegate(observer: observer)
mqttSession.delegate = delegate
currentObserver = observer
return Disposables.create {
print("disposing mqttsession!")
mqttSession.disconnect()
}
}.shareReplay(1) // This line is important!
self.currentObserver = currentObserver
}
func connect() -> Promise<Void, HomeClientError> {
let source = PromiseSource<Void, HomeClientError>()
mqttSession.connectHandler = { error in
if let error = error {
source.reject(HomeClientError(message: error.description))
} else {
for topic in self.topics {
self.mqttSession.subscribe(toTopic: topic, at: .atLeastOnce)
}
source.resolve()
}
}
mqttSession.connect()
return source.promise
}
func disconnect() {
mqttSession.disconnect()
}
func publish(_ message: Message) -> Promise<Message, HomeClientError> {
let publish = PromiseSource<Message, HomeClientError>()
mqttSession.publishData(message.payload, onTopic: message.topic, retain: message.retain, qos: message.mqttQos) { [weak self] error in
if let error = error {
publish.reject(HomeClientError(message: error.description))
} else {
print("published message '\(message.payloadString)' on topic '\(message.topic)'")
self?.currentObserver?.on(.next(message))
publish.resolve(message)
}
}
return publish.promise
}
func subscribe(_ topic: Topic) -> Observable<Message> {
// Tell the broker that we're interested in a new topic
mqttSession.subscribe(toTopic: topic, at: .atLeastOnce) { (error, qos) in
if error != nil {
print("subscribing failed!")
} else {
print("subscribed to topic \(topic), granted QoS of \(qos)")
}
}
topics.append(topic)
return messages.filter { message in
return message.topic == topic
}
}
}
| mit | c2b4a45cb75bbacbcf83a58f336ca1ed | 28.738806 | 137 | 0.675784 | 4.374314 | false | false | false | false |
wbaumann/SmartReceiptsiOS | SmartReceipts/Modules/Generate Report/GenerateReportShareService.swift | 2 | 4646 | //
// GenerateReportShareService.swift
// SmartReceipts
//
// Created by Bogdan Evsenev on 08/06/2017.
// Copyright ยฉ 2017 Will Baumann. All rights reserved.
//
import Foundation
import MessageUI
class GenerateReportShareService: NSObject, MFMailComposeViewControllerDelegate {
private weak var presenter: GenerateReportPresenter!
private var trip: WBTrip!
init(presenter: GenerateReportPresenter, trip: WBTrip) {
super.init()
self.presenter = presenter
self.trip = trip
}
func emailFiles(_ files: [String]) {
guard MFMailComposeViewController.canSendMail() else {
self.presenter.presentAlert(title: LocalizedString("generic_error_alert_title"),
message: LocalizedString("error_email_not_configured_message"))
remove(files: files)
return
}
// TODO: Switch to using plurals once we integrate this with Twine
let messageBody = files.count > 1 ? String(format: LocalizedString("reports_attached", comment: ""), "\(files.count)") : LocalizedString("report_attached", comment: "")
let composer = MFMailComposeViewController()
let subjectFormatter = SmartReceiptsFormattableString(fromOriginalText: WBPreferences.defaultEmailSubject())
composer.mailComposeDelegate = self
composer.setSubject(subjectFormatter.format(trip))
composer.setMessageBody(messageBody, isHTML: false)
composer.setToRecipients(split(WBPreferences.defaultEmailRecipient()))
composer.setCcRecipients(split(WBPreferences.defaultEmailCC()))
composer.setBccRecipients(split(WBPreferences.defaultEmailBCC()))
if #available(iOS 13.0, *) {
composer.navigationBar.tintColor = AppTheme.primaryColor
composer.view.tintColor = AppTheme.primaryColor
} else {
composer.navigationBar.tintColor = .white
}
for file in files {
Logger.debug("func emailFiles: Attach \(file)")
guard let data = try? Data(contentsOf: URL(fileURLWithPath: file)) else {
Logger.warning("func emailFiles: No data?")
continue
}
let mimeType: String
if file.hasSuffix("pdf") {
mimeType = "application/pdf"
} else if file.hasSuffix("csv") {
mimeType = "text/csv"
} else {
mimeType = "application/octet-stream"
}
composer.addAttachmentData(data, mimeType: mimeType, fileName: NSString(string: file).lastPathComponent)
}
remove(files: files)
presenter.present(vc: composer, animated: true)
}
func shareFiles(_ files: [String]) {
var attached = [URL]()
for file in files {
attached.append(URL(fileURLWithPath: file))
}
let shareViewController = UIActivityViewController(activityItems: attached, applicationActivities: nil)
shareViewController.completionWithItemsHandler = { [weak self]
type, success, returned, error in
Logger.debug("Type \(type.debugDescription) - \(success.description)")
Logger.debug("Returned \(returned?.count ?? 0)")
if let error = error {
Logger.error(error.localizedDescription)
}
if success {
self?.presenter.close()
}
self?.remove(files: files)
self?.presenter.presentInterstitialAd()
}
presenter.present(vc: shareViewController, animated: true, isPopover: true, completion: nil)
}
public func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) {
if let error = error {
Logger.error("Send email error: \(error)")
}
controller.dismiss(animated: true) { [weak self] in
self?.presenter.close()
self?.presenter.presentInterstitialAd()
}
}
fileprivate func split(_ string: String) -> [String] {
if string.contains(",") {
// For legacy reasons, we allow these to also be separated by a comma (,)
return string.components(separatedBy: ",")
} else {
return string.components(separatedBy: ";")
}
}
private func remove(files: [String]) {
for file in files { FileManager.deleteIfExists(filepath: file) }
}
}
| agpl-3.0 | 0cf9e6e88e472935eb2c799739596f1f | 37.38843 | 176 | 0.605382 | 5.26644 | false | false | false | false |
johnnywjy/JYRadarChart | JYRadarChartSwiftDemo/JYRadarChartSwiftDemo/JYLegendView.swift | 1 | 4225 | //
// JYLegendView.swift
// JYRadarChartSwiftDemo
//
// Created by Erick Santos on 30/04/17.
//
//
import UIKit
class JYLegendView: UIView {
private let colorPadding: CGFloat = 15.0
private let padding: CGFloat = 3.0
private let fontSize: CGFloat = 10.0
private let roundRadius: CGFloat = 7.0
private let circleDiameter: CGFloat = 6.0
var legendFont: UIFont = UIFont.systemFont(ofSize: 12.0)
var titles: [String] = []
var colors: [UIColor] = []
func CGContextAddRoundedRect(c: CGContext, rect: CGRect, radius: CGFloat) {
var radiusAux = radius
if (2 * radiusAux > rect.size.height) {
radiusAux = rect.size.height / 2.0
}
if (2 * radiusAux > rect.size.width) {
radiusAux = rect.size.width / 2.0
}
c.addArc(center: CGPoint(x: rect.origin.x + radiusAux,
y: rect.origin.y + radiusAux),
radius: radiusAux,
startAngle: CGFloat(Double.pi),
endAngle: CGFloat(Double.pi) * 1.5,
clockwise: false)
c.addArc(center: CGPoint(x: rect.origin.x + rect.size.width - radiusAux,
y: rect.origin.y + radiusAux),
radius: radiusAux,
startAngle: CGFloat(Double.pi) * 1.5,
endAngle: CGFloat(Double.pi) * 2.0,
clockwise: false)
c.addArc(center: CGPoint(x: rect.origin.x + rect.size.width - radiusAux,
y: rect.origin.y + rect.size.height - radiusAux),
radius: radiusAux,
startAngle: CGFloat(Double.pi) * 2.0,
endAngle: CGFloat(Double.pi) * 0.5,
clockwise: false)
c.addArc(center: CGPoint(x: rect.origin.x + radiusAux,
y: rect.origin.y + rect.size.height - radiusAux),
radius: radiusAux,
startAngle: CGFloat(Double.pi) * 0.5,
endAngle: CGFloat(Double.pi),
clockwise: false)
c.addLine(to: CGPoint(x: rect.origin.x, y: rect.origin.y + radiusAux))
}
func GContextFillRoundedRect(c: CGContext, rect: CGRect, radius: CGFloat) {
c.beginPath()
let clipPath: CGPath = UIBezierPath(roundedRect: rect, cornerRadius: radius).cgPath
c.addPath(clipPath)
c.fillPath()
}
override func draw(_ rect: CGRect) {
let context: CGContext? = UIGraphicsGetCurrentContext()
context?.setFillColor(UIColor.init(white: 0.0, alpha: 0.1).cgColor)
let clipPath: CGPath = UIBezierPath(roundedRect: self.bounds, cornerRadius: CGFloat(roundRadius)).cgPath
context?.addPath(clipPath)
var y: CGFloat = 0
for (index, title) in titles.enumerated() {
var color = UIColor.black
if colors.count == titles.count {
color = colors[index]
}
color.setFill()
context?.fillEllipse(in: CGRect(x: padding + 2.0,
y: padding + round(y) + legendFont.xHeight / 2 + 1,
width: circleDiameter,
height: circleDiameter))
UIColor.black.set()
title.draw(at: CGPoint(x: colorPadding + padding, y: y + padding), withAttributes: [NSFontAttributeName: legendFont])
y = y + legendFont.lineHeight
}
}
override func sizeThatFits(_ size: CGSize) -> CGSize {
let height: CGFloat = legendFont.lineHeight * CGFloat(titles.count)
var width: CGFloat = 0
titles.forEach {
let size: CGSize = $0.size(attributes: [NSFontAttributeName: legendFont])
width = max(width, size.width)
}
return CGSize(width: colorPadding + width + 2 * padding, height: height + 2 * padding)
}
}
| mit | 4712f7a2090a331fbe2ac6e5bdcf26ab | 33.349593 | 129 | 0.51645 | 4.684035 | false | false | false | false |
maximveksler/Developing-iOS-8-Apps-with-Swift | lesson-013/Trax Segue/Trax/GPXViewController.swift | 2 | 8152 | //
// GPXViewController.swift
// Trax
//
// Created by CS193p Instructor.
// Copyright (c) 2015 Stanford University. All rights reserved.
//
import UIKit
import MapKit
class GPXViewController: UIViewController, MKMapViewDelegate, UIPopoverPresentationControllerDelegate
{
// MARK: - Outlets
@IBOutlet weak var mapView: MKMapView! {
didSet {
mapView.mapType = .Satellite
mapView.delegate = self
}
}
// MARK: - Public API
var gpxURL: NSURL? {
didSet {
clearWaypoints()
if let url = gpxURL {
GPX.parse(url) {
if let gpx = $0 {
self.handleWaypoints(gpx.waypoints)
}
}
}
}
}
// MARK: - Waypoints
private func clearWaypoints() {
if mapView?.annotations != nil { mapView.removeAnnotations(mapView.annotations as [MKAnnotation]) }
}
private func handleWaypoints(waypoints: [GPX.Waypoint]) {
mapView.addAnnotations(waypoints)
mapView.showAnnotations(waypoints, animated: true)
}
@IBAction func addWaypoint(sender: UILongPressGestureRecognizer)
{
if sender.state == UIGestureRecognizerState.Began {
let coordinate = mapView.convertPoint(sender.locationInView(mapView), toCoordinateFromView: mapView)
let waypoint = EditableWaypoint(latitude: coordinate.latitude, longitude: coordinate.longitude)
waypoint.name = "Dropped"
mapView.addAnnotation(waypoint)
}
}
// MARK: - MKMapViewDelegate
func mapView(mapView: MKMapView, viewForAnnotation annotation: MKAnnotation) -> MKAnnotationView? {
var view = mapView.dequeueReusableAnnotationViewWithIdentifier(Constants.AnnotationViewReuseIdentifier)
if view == nil {
view = MKPinAnnotationView(annotation: annotation, reuseIdentifier: Constants.AnnotationViewReuseIdentifier)
view!.canShowCallout = true
} else {
view!.annotation = annotation
}
view!.draggable = annotation is EditableWaypoint
view!.leftCalloutAccessoryView = nil
view!.rightCalloutAccessoryView = nil
if let waypoint = annotation as? GPX.Waypoint {
if waypoint.thumbnailURL != nil {
view!.leftCalloutAccessoryView = UIButton(frame: Constants.LeftCalloutFrame)
}
if annotation is EditableWaypoint {
view!.rightCalloutAccessoryView = UIButton.buttonWithType(UIButtonType.DetailDisclosure) as UIButton
}
}
return view
}
func mapView(mapView: MKMapView, didSelectAnnotationView view: MKAnnotationView) {
if let waypoint = view.annotation as? GPX.Waypoint {
if let thumbnailImageButton = view.leftCalloutAccessoryView as? UIButton {
if let imageData = NSData(contentsOfURL: waypoint.thumbnailURL!) { // blocks main thread!
if let image = UIImage(data: imageData) {
thumbnailImageButton.setImage(image, forState: .Normal)
}
}
}
}
}
func mapView(mapView: MKMapView, annotationView view: MKAnnotationView, calloutAccessoryControlTapped control: UIControl) {
if (control as? UIButton)?.buttonType == UIButtonType.DetailDisclosure {
mapView.deselectAnnotation(view.annotation, animated: false)
performSegueWithIdentifier(Constants.EditWaypointSegue, sender: view)
} else if let waypoint = view.annotation as? GPX.Waypoint {
if waypoint.imageURL != nil {
performSegueWithIdentifier(Constants.ShowImageSegue, sender: view)
}
}
}
// MARK: - Navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == Constants.ShowImageSegue {
if let waypoint = (sender as? MKAnnotationView)?.annotation as? GPX.Waypoint {
if let ivc = segue.destinationViewController.contentViewController as? ImageViewController {
ivc.imageURL = waypoint.imageURL
ivc.title = waypoint.name
}
}
} else if segue.identifier == Constants.EditWaypointSegue {
if let waypoint = (sender as? MKAnnotationView)?.annotation as? EditableWaypoint {
if let ewvc = segue.destinationViewController.contentViewController as? EditWaypointViewController {
if let ppc = ewvc.popoverPresentationController {
let coordinatePoint = mapView.convertCoordinate(waypoint.coordinate, toPointToView: mapView)
ppc.sourceRect = (sender as! MKAnnotationView).popoverSourceRectForCoordinatePoint(coordinatePoint)
let minimumSize = ewvc.view.systemLayoutSizeFittingSize(UILayoutFittingCompressedSize)
ewvc.preferredContentSize = CGSize(width: Constants.EditWaypointPopoverWidth, height: minimumSize.height)
ppc.delegate = self
}
ewvc.waypointToEdit = waypoint
}
}
}
}
// MARK: - UIAdaptivePresentationControllerDelegate
func adaptivePresentationStyleForPresentationController(controller: UIPresentationController) -> UIModalPresentationStyle {
return UIModalPresentationStyle.OverFullScreen // full screen, but we can see what's underneath
}
func presentationController(controller: UIPresentationController, viewControllerForAdaptivePresentationStyle style: UIModalPresentationStyle) -> UIViewController?
{
let navcon = UINavigationController(rootViewController: controller.presentedViewController)
let visualEffectView = UIVisualEffectView(effect: UIBlurEffect(style: .ExtraLight))
visualEffectView.frame = navcon.view.bounds
navcon.view.insertSubview(visualEffectView, atIndex: 0) // "back-most" subview
return navcon
}
// MARK: - View Controller Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
// sign up to hear about GPX files arriving
// we never remove this observer, so we will never leave the heap
// might make some sense to think about when to remove this observer
let center = NSNotificationCenter.defaultCenter()
let queue = NSOperationQueue.mainQueue()
let appDelegate = UIApplication.sharedApplication().delegate
center.addObserverForName(GPXURL.Notification, object: appDelegate, queue: queue) { notification in
if let url = notification.userInfo?[GPXURL.Key] as? NSURL {
self.gpxURL = url
}
}
gpxURL = NSURL(string: "http://cs193p.stanford.edu/Vacation.gpx") // for demo/debug/testing
}
// MARK: - Constants
private struct Constants {
static let LeftCalloutFrame = CGRect(x: 0, y: 0, width: 59, height: 59)
static let AnnotationViewReuseIdentifier = "waypoint"
static let ShowImageSegue = "Show Image"
static let EditWaypointSegue = "Edit Waypoint"
static let EditWaypointPopoverWidth: CGFloat = 320
}
}
// MARK: - Convenience Extensions
extension UIViewController {
var contentViewController: UIViewController {
if let navcon = self as? UINavigationController {
return navcon.visibleViewController!
} else {
return self
}
}
}
extension MKAnnotationView {
func popoverSourceRectForCoordinatePoint(coordinatePoint: CGPoint) -> CGRect {
var popoverSourceRectCenter = coordinatePoint
popoverSourceRectCenter.x -= frame.width / 2 - centerOffset.x - calloutOffset.x
popoverSourceRectCenter.y -= frame.height / 2 - centerOffset.y - calloutOffset.y
return CGRect(origin: popoverSourceRectCenter, size: frame.size)
}
}
| apache-2.0 | bff28c29abc60dbc97f9d9a6008c2e47 | 39.157635 | 166 | 0.642787 | 5.761131 | false | false | false | false |
bascar2020/ios-truelinc | Truelinc/Buscador.swift | 1 | 7943 | //
// Buscador.swift
// Truelinc
//
// Created by Juan Diaz on 26/01/16.
// Copyright ยฉ 2016 Indibyte. All rights reserved.
//
import Foundation
import Parse
class Buscador : UIViewController, UITableViewDataSource, UISearchBarDelegate, SWRevealViewControllerDelegate {
@IBOutlet weak var abrir: UIBarButtonItem!
@IBOutlet weak var tableTarjetas: UITableView!
@IBOutlet weak var mySearchBar: UISearchBar!
var resultFilter = [PFObject]()
var misTarjetas = [String]()
override func viewDidLoad() {
self.tableTarjetas.tableFooterView = UIView(frame: CGRect.zero)
let logo = UIImage(named: "logoT")
let imageView = UIImageView(image:logo)
self.navigationItem.titleView = imageView
if (nil != (PFUser.current()?.value(forKey: "tarjetas"))) {
self.misTarjetas = (PFUser.current()?.value(forKey: "tarjetas")) as! [String]
}
if self.revealViewController() != nil {
abrir.target = self.revealViewController()
abrir.action = #selector(SWRevealViewController.revealToggle(_:))
self.revealViewController().delegate = self
self.view.addGestureRecognizer(self.revealViewController().panGestureRecognizer())
}
}
func revealController(_ revealController: SWRevealViewController!, willMoveTo position: FrontViewPosition)
{
if revealController.frontViewPosition == FrontViewPosition.left
{
self.view.isUserInteractionEnabled = false
}
else
{
self.view.isUserInteractionEnabled = true
}
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return resultFilter.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let singleCell: SingleTowCellTableViewCell = tableView.dequeueReusableCell(withIdentifier: "myCell") as! SingleTowCellTableViewCell
if(resultFilter[indexPath.row].object(forKey: "Empresa") != nil){
singleCell.lb_empresa.text = (resultFilter[indexPath.row].object(forKey: "Empresa") as AnyObject).capitalized}
if(resultFilter[indexPath.row].object(forKey: "Nombre") != nil){
singleCell.lb_nombre.text = (resultFilter[indexPath.row].object(forKey: "Nombre") as AnyObject).capitalized}
if(resultFilter[indexPath.row].object(forKey: "Cargo") != nil){
singleCell.lb_cargo.text = (resultFilter[indexPath.row].object(forKey: "Cargo") as AnyObject).capitalized}
if(resultFilter[indexPath.row].object(forKey: "LogoEmpresa") != nil){
(resultFilter[indexPath.row].object(forKey: "LogoEmpresa") as AnyObject).getDataInBackground(block: { (imageData: Data?, error) in
if error == nil {
let image = UIImage(data: imageData!)
singleCell.img_logo.image = image
}else{
print("error",error)
}
})
}else{
let image = UIImage(named: "nologo.png")
singleCell.img_logo.image = image
}
if(resultFilter[indexPath.row].object(forKey: "Foto") != nil){
(resultFilter[indexPath.row].object(forKey: "Foto") as AnyObject).getDataInBackground(block: { (imageData: Data?, error) in
if error == nil {
let image = UIImage(data: imageData!)
singleCell.img_foto.image = image
}else{
print("error",error)
}
})
}else{
let image = UIImage(named: "no_perfil.png")
singleCell.img_foto.image = image
}
return singleCell
}
func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
if Reachability.isConnectedToNetwork() == true {
mySearchBar.resignFirstResponder()
let nombreQuery = PFQuery(className: "Tarjetas")
nombreQuery.whereKey("Privada", equalTo: false)
nombreQuery.whereKey("Nombre", contains: (searchBar.text!.lowercased()))
let empresaQuery = PFQuery(className: "Tarjetas")
empresaQuery.whereKey("Privada", equalTo: false)
empresaQuery.whereKey("Empresa", contains: (searchBar.text!.lowercased()))
let tagsQuery = PFQuery(className: "Tarjetas")
tagsQuery.whereKey("Privada", equalTo: false)
tagsQuery.whereKey("tags", containedIn: [searchBar.text!.lowercased()])
if !self.misTarjetas.isEmpty {
nombreQuery.whereKey("objectId", notContainedIn: self.misTarjetas)
empresaQuery.whereKey("objectId", notContainedIn: self.misTarjetas)
tagsQuery.whereKey("objectId", notContainedIn: self.misTarjetas)
}
let query = PFQuery.orQuery(withSubqueries: [nombreQuery,empresaQuery,tagsQuery])
query.findObjectsInBackground { (results:[PFObject]?, error) in
if error != nil {
let myAlert = UIAlertController(title: "Alert", message: error?.localizedDescription, preferredStyle: UIAlertControllerStyle.alert)
let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil)
myAlert.addAction(okAction)
self.present(myAlert, animated: true, completion: nil)
return
}else{
self.resultFilter.removeAll(keepingCapacity: false)
for tarjeta in results! {
self.resultFilter.append(tarjeta)
}
DispatchQueue.main.async{
self.tableTarjetas.reloadData()
self.mySearchBar.resignFirstResponder()
}
}
}
}else
{
let myAlert = UIAlertController(title: "Tenemos un Problema!", message: "Comprueba tu conexion y vuelve a intentarlo", preferredStyle: UIAlertControllerStyle.alert)
let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil)
myAlert.addAction(okAction)
self.present(myAlert, animated: true, completion: nil)
}
}
func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
mySearchBar.resignFirstResponder()
mySearchBar.text = ""
}
func tableView(_ tableView: UITableView, didSelectRowAtIndexPath indexPath: IndexPath) {
self.performSegue(withIdentifier: "showCardOnline", sender: indexPath)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if(segue.identifier == "showCardOnline"){
if let destination = segue.destination as? TarjetaViewController{
let path = tableTarjetas.indexPathForSelectedRow
let cell = tableTarjetas.cellForRow(at: path!) as! SingleTowCellTableViewCell
destination.tarjetaesmia = false // esta variable representa que el usuario sigue esta tarjeta
destination.viaSegueTarjeta = resultFilter[path!.row]
destination.viaSegueLogo = cell.img_logo.image!
destination.viaSegueFoto = cell.img_foto.image!
}
}
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
if tableTarjetas.indexPathForSelectedRow != nil {
tableTarjetas.deselectRow(at: tableTarjetas.indexPathForSelectedRow! , animated: false)
}
}
}
| gpl-3.0 | 328f8aaf94b9a79c0742138edb13b14b | 36.462264 | 176 | 0.599597 | 5.238786 | false | false | false | false |
coderwjq/swiftweibo | SwiftWeibo/SwiftWeibo/Classes/Home/View/HomeTableViewCell.swift | 1 | 6668 | //
// HomeTableViewCell.swift
// SwiftWeibo
//
// Created by mzzdxt on 2016/11/4.
// Copyright ยฉ 2016ๅนด wjq. All rights reserved.
//
import UIKit
import SDWebImage
private let edgeMargin: CGFloat = 15
private let itemMargin: CGFloat = 10
class HomeTableViewCell: UITableViewCell {
// MARK:- ๆงไปถๅฑๆง
@IBOutlet weak var iconView: UIImageView!
@IBOutlet weak var verfiedView: UIImageView!
@IBOutlet weak var screenNameLabel: UILabel!
@IBOutlet weak var vipView: UIImageView!
@IBOutlet weak var timeLabel: UILabel!
@IBOutlet weak var sourceLabel: UILabel!
@IBOutlet weak var contentLabel: UILabel!
@IBOutlet weak var retweetedBgView: UIView!
@IBOutlet weak var picView: PicCollectionView!
@IBOutlet weak var retweetedContentLabel: UILabel!
@IBOutlet weak var bottomToolView: UIView!
// MARK:- ็บฆๆ็ๅฑๆง
@IBOutlet weak var contentLabelWCons: NSLayoutConstraint!
@IBOutlet weak var retweetedContentLabelTopCons: NSLayoutConstraint!
@IBOutlet weak var picViewBottomCons: NSLayoutConstraint!
@IBOutlet weak var picViewWCons: NSLayoutConstraint!
@IBOutlet weak var picViewHCons: NSLayoutConstraint!
// MARK:- ่ชๅฎไนๅฑๆง
var viewModel: StatusViewModel? {
didSet {
// ็ฉบๅผๆ ก้ช
guard let viewModel = viewModel else {
return
}
// ่ฎพ็ฝฎๅคดๅ
iconView.sd_setImage(with: viewModel.profileURL, placeholderImage: UIImage(named: "avatar_default_small"))
// ่ฎพ็ฝฎ่ฎค่ฏ็ๅพๆ
verfiedView.image = viewModel.verifiedImage
// ่ฎพ็ฝฎๆต็งฐ
screenNameLabel.text = viewModel.status?.user?.screen_name
// ่ฎพ็ฝฎไผๅๅพๆ
vipView.image = viewModel.vipImage
// ่ฎพ็ฝฎๆถ้ด็label
timeLabel.text = viewModel.createdAtText
// ่ฎพ็ฝฎๆฅๆบ
if let sourceText = viewModel.sourceText {
sourceLabel.text = "ๆฅ่ช " + sourceText
} else {
sourceLabel.text = nil
}
// ่ฎพ็ฝฎๅพฎๅๆญฃๆ
contentLabel.attributedText = FindEmoticon.sharedInstance.findAttrString(statusText: viewModel.status?.text, font: contentLabel.font)
// ่ฎพ็ฝฎๆต็งฐ็ๆๅญ้ข่ฒ
screenNameLabel.textColor = viewModel.vipImage == nil ? UIColor.black : UIColor.orange
// ๆ นๆฎๅพ็ไธชๆฐ่ฎก็ฎpicView็ๅฎฝๅบฆๅ้ซๅบฆ็บฆๆ
let picViewSize = calculatePicViewSize(count: viewModel.picURLs.count)
picViewWCons.constant = picViewSize.width
picViewHCons.constant = picViewSize.height
// ๅฐpicURLๆฐๆฎไผ ้็ปpicView
picView.picURLs = viewModel.picURLs
// ่ฎพ็ฝฎ่ฝฌๅๅพฎๅ็ๆญฃๆ
if viewModel.status?.retweeted_status != nil {
// ๆ่ฝฌๅๅพฎๅ
// ่ฎพ็ฝฎ่ฝฌๅๅพฎๅ็ๆญฃๆ
if let screenName = viewModel.status?.retweeted_status?.user?.screen_name, let retweetedText = viewModel.status?.retweeted_status?.text {
let retweetedText = "@" + "\(screenName): " + retweetedText
retweetedContentLabel.attributedText = FindEmoticon.sharedInstance.findAttrString(statusText: retweetedText, font: retweetedContentLabel.font)
// ่ฎพ็ฝฎ่ฝฌๅๆญฃๆ่ท็ฆป้กถ้จ็็บฆๆ
retweetedContentLabelTopCons.constant = 15
}
// ่ฎพ็ฝฎ่ๆฏๆพ็คบ
retweetedBgView.isHidden = false
} else {
// ๆฒกๆ่ฝฌๅๅพฎๅ
// ่ฎพ็ฝฎ่ฝฌๅๅพฎๅ็ๆญฃๆ
retweetedContentLabel.text = nil
// ่ฎพ็ฝฎ่ๆฏๆพ็คบ
retweetedBgView.isHidden = true
// ่ฎพ็ฝฎ่ฝฌๅๆญฃๆ่ท็ฆป้กถ้จ็็บฆๆ
retweetedContentLabelTopCons.constant = 0
}
// ่ฎก็ฎcell็้ซๅบฆๅนถไฟๅญ
if viewModel.cellHight == 0 {
// ๅผบๅถๅธๅฑ
layoutIfNeeded()
// ่ทๅๅบ้จๅทฅๅ
ทๆ ็ๆๅคงYๅผ
viewModel.cellHight = bottomToolView.frame.maxY
}
}
}
// MARK:- ็ณป็ปๅ่ฐๅฝๆฐ
override func awakeFromNib() {
super.awakeFromNib()
// ่ฎพ็ฝฎๅพฎๅๆญฃๆ็ๅฎฝๅบฆ็บฆๆ
contentLabelWCons.constant = UIScreen.main.bounds.size.width - 2 * edgeMargin
}
}
// MARK:- ่ฎก็ฎๆนๆณ
extension HomeTableViewCell {
fileprivate func calculatePicViewSize(count: Int) -> CGSize {
// ๆฒกๆ้
ๅพ
if count == 0 {
picViewBottomCons.constant = 0
return CGSize.zero
}
// ๆ้
ๅพ้่ฆๆน็บฆๆๆๅผ
picViewBottomCons.constant = 10
// ๅๅบpicViewๅฏนๅบ็Layout
let layout = picView.collectionViewLayout as! UICollectionViewFlowLayout
// ๅๅผ ้
ๅพ
if count == 1 {
// ๅๅบๅพ็
let urlString = viewModel?.picURLs.last?.absoluteString
let image = SDWebImageManager.shared().imageCache.imageFromDiskCache(forKey: urlString)!
// ่ฎพ็ฝฎไธๅผ ๅพ็ๆฏlayout็itemSize
layout.itemSize = CGSize(width: image.size.width * 2, height: image.size.height * 2)
return CGSize(width: image.size.width * 2, height: image.size.height * 2)
}
// ่ฎก็ฎๅบๆฅimageViewWH
let imageViewWH = (UIScreen.main.bounds.width - 2 * edgeMargin - 2 * itemMargin) / 3
// ่ฎพ็ฝฎๅ
ถไปๅผ ๅพ็ๆถlayout็itemSize
layout.itemSize = CGSize(width: imageViewWH, height: imageViewWH)
// ๅๅผ ้
ๅพ
if count == 4 {
let picViewWH = imageViewWH * 2 + itemMargin
return CGSize(width: picViewWH, height: picViewWH)
}
// ๅ
ถไปๅผ ้
ๅพ
// ่ฎก็ฎ่กๆฐ
let rows = CGFloat((count - 1) / 3 + 1)
// ่ฎก็ฎpicView็้ซๅบฆ
let picViewH = rows * imageViewWH + (rows - 1) * itemMargin
// ่ฎก็ฎpicView็ๅฎฝๅบฆ
let picViewW = UIScreen.main.bounds.width - 2 * edgeMargin
// ่ฟๅCGSize
return CGSize(width: picViewW, height: picViewH)
}
}
| apache-2.0 | e2ac4416c52c2ed8a578be6e56571411 | 32.916667 | 162 | 0.564455 | 5.294883 | false | false | false | false |
smogun/KVLAnimatedLoader | Pods/KVLHelpers/KVLHelpers/KVLHelpers/Classes/KVLLogger.swift | 1 | 3114 | //
// KVLLogger.swift
// KVLArounder
//
// Created by Misha Koval on 9/14/15.
// Copyright (c) 2015 Misha Koval. All rights reserved.
//
import Foundation
public typealias WHERE = String
/****************************************************************************************/
public func GetCodeLocation(file: String = __FILE__, function: String = __FUNCTION__, line: Int = __LINE__, col: Int = __COLUMN__) -> WHERE!
{
return String(format: "%@:%@:(%d,%d)", file.lastPathComponent!.stringByDeletingPathExtension!, function, line, col)
}
/*
IMPORTANT! in order for this class to print, there is a need to add DEBUG flag in build settings for debug scheme.
If installed from pods, this has to be done in POD target:
(POD project -> Buld settings -> Swift compiler - Custom Flags -> other Swift Flags -> Debug -> add "-DDEBUG")
Since POD target is being assembled by pod install, pod file has to include "post_install" script (see example projects).
*/
@objc
public class KVLLogger: NSObject
{
public class func printLogMessage(format: String, _ args: CVarArgType...)
{
#if DEBUG
withVaList(args) { NSLogv(format, $0) }
#endif
}
public class func printErrorMessage(message: String?, location: WHERE?)
{
printLogMessage("โ๏ธ %@ >>> %@", location == nil ? "" : location!, message == nil ? "" : message!)
}
public class func printSuccessMessage(message: String?, location: WHERE?)
{
printLogMessage("โ
%@ >>> %@", location == nil ? "" : location!, message == nil ? "" : message!)
}
public class func printNormalMessage(message: String?, location: WHERE?)
{
printLogMessage("โ %@ >>> %@", location == nil ? "" : location!, message == nil ? "" : message!)
}
public class func printError(error: NSError?, location: WHERE?)
{
if (error == nil)
{
return;
}
let localizedRecoveryOptions:AnyObject? = error!.localizedRecoveryOptions
let userInfo:AnyObject? = error!.userInfo
printErrorMessage(String(format:"Description: %@\nFailureReason: %@\nRecoverySuggestion: %@\nRecoveryOptions: %@\nCode: %zd\nDomain: %@\nUserInfo: %@",
error!.localizedDescription,
error!.localizedFailureReason == nil ? "" : error!.localizedDescription,
(error!.localizedRecoverySuggestion == nil ? "" : error!.localizedRecoverySuggestion)!,
localizedRecoveryOptions == nil ? "" : localizedRecoveryOptions as! String,
error!.code,
error!.domain,
userInfo == nil ? "" : userInfo as! NSDictionary), location: location == nil ? "" : location!);
}
public class func printException(exception: NSException?, location: WHERE?)
{
if (exception == nil)
{
return;
}
printErrorMessage(String(format:"Name: %@\nReason: %@, stackTrace:%@",
exception!.name,
exception!.reason!,
exception!.callStackSymbols), location: location == nil ? "" : location!);
}
} | mit | b683fe00191b87e3d3a8f6f390245e8f | 36.890244 | 159 | 0.594334 | 4.670677 | false | false | false | false |
finder39/Swimgur | Swimgur/Controllers/GalleryItemView/Cells/CommentCell.swift | 1 | 3777 | //
// CommentCell.swift
// Swimgur
//
// Created by Joseph Neuman on 11/2/14.
// Copyright (c) 2014 Joseph Neuman. All rights reserved.
//
import Foundation
import UIKit
import SWNetworking
class CommentCell: UITableViewCell {
@IBOutlet var authorButton:UIButton!
@IBOutlet var pointsLabel:UILabel!
@IBOutlet var imgurText:UITextView!
@IBOutlet var expandButton:UIButton!
@IBOutlet var authorWidth:NSLayoutConstraint!
@IBOutlet var pointsWidth:NSLayoutConstraint!
@IBOutlet var expandWidth:NSLayoutConstraint!
@IBOutlet var authorLeadingConstraint:NSLayoutConstraint!
@IBOutlet var commentLeadingConstraint:NSLayoutConstraint!
weak var associatedGalleryItem:GalleryItem?
weak var associatedComment:Comment?
weak var parentTableView:UITableView?
override func awakeFromNib() {
super.awakeFromNib()
setup()
self.indentationWidth = 15
}
func setup() {
authorButton.setTitleColor(UIColor.RGBColor(red: 51, green: 102, blue: 187), forState: .Normal)
imgurText.textColor = UIColorEXT.TextColor()
pointsLabel.textColor = UIColorEXT.TextColor()
imgurText.linkTextAttributes = [NSForegroundColorAttributeName:UIColor.RGBColor(red: 51, green: 102, blue: 187)]
}
override func prepareForReuse() {
super.prepareForReuse()
authorButton.setTitle(nil, forState: .Normal)
pointsLabel.text = nil
imgurText.text = nil
expandButton.hidden = true
associatedComment = nil
associatedGalleryItem = nil
parentTableView = nil
expandButton.setTitle("Expand", forState: .Normal)
// bug fix for text maintaining old links
var newImgurTextView = UITextView()
newImgurTextView.font = imgurText.font
newImgurTextView.backgroundColor = imgurText.backgroundColor
newImgurTextView.dataDetectorTypes = imgurText.dataDetectorTypes
newImgurTextView.selectable = imgurText.selectable
newImgurTextView.editable = imgurText.editable
newImgurTextView.scrollEnabled = imgurText.scrollEnabled
newImgurTextView.textColor = imgurText.textColor
newImgurTextView.linkTextAttributes = imgurText.linkTextAttributes
newImgurTextView.setTranslatesAutoresizingMaskIntoConstraints(false)
imgurText.removeFromSuperview()
self.addSubview(newImgurTextView)
imgurText = newImgurTextView
let top = NSLayoutConstraint(item: newImgurTextView, attribute: .Top, relatedBy: .Equal, toItem: self, attribute: .Top, multiplier: 1.0, constant: 24)
let bottom = NSLayoutConstraint(item: newImgurTextView, attribute: .Bottom, relatedBy: .Equal, toItem: self, attribute: .Bottom, multiplier: 1.0, constant: 0)
commentLeadingConstraint = NSLayoutConstraint(item: newImgurTextView, attribute: .Leading, relatedBy: .Equal, toItem: self, attribute: .Leading, multiplier: 1.0, constant: 4)
let trailing = NSLayoutConstraint(item: newImgurTextView, attribute: .Trailing, relatedBy: .Equal, toItem: self, attribute: .Trailing, multiplier: 1.0, constant: 4)
self.addConstraints([top, bottom, commentLeadingConstraint, trailing])
}
override func layoutSubviews() {
super.layoutSubviews()
let indentPoints:CGFloat = CGFloat(self.indentationLevel) * self.indentationWidth
authorLeadingConstraint.constant = 8 + indentPoints
commentLeadingConstraint.constant = 4 + indentPoints
}
// MARK: Actions
@IBAction func expand() {
if expandButton.titleForState(.Normal) == "Expand" {
associatedComment?.expanded = true
expandButton.setTitle("Collapse", forState: .Normal)
} else {
associatedComment?.expanded = false
expandButton.setTitle("Expand", forState: .Normal)
}
associatedGalleryItem?.updateTableViewDataSourceCommentsArray()
parentTableView?.reloadData()
}
} | mit | a936786177abb27889f62bd9d2129e3e | 37.161616 | 178 | 0.751655 | 5.056225 | false | false | false | false |
lorentey/swift | test/Interpreter/generic_casts.swift | 3 | 8118 | // RUN: %empty-directory(%t)
// RUN: %target-build-swift -Onone %s -o %t/a.out
// RUN: %target-run %t/a.out | %FileCheck --check-prefix CHECK --check-prefix CHECK-ONONE %s
// RUN: %target-build-swift -O %s -o %t/a.out.optimized
// RUN: %target-codesign %t/a.out.optimized
// RUN: %target-run %t/a.out.optimized | %FileCheck %s
// REQUIRES: executable_test
// FIXME: rdar://problem/19648117 Needs splitting objc parts out
#if canImport(Foundation)
import Foundation
#endif
func allToInt<T>(_ x: T) -> Int {
return x as! Int
}
func allToIntOrZero<T>(_ x: T) -> Int {
if x is Int {
return x as! Int
}
return 0
}
func anyToInt(_ x: Any) -> Int {
return x as! Int
}
func anyToIntOrZero(_ x: Any) -> Int {
if x is Int {
return x as! Int
}
return 0
}
protocol Class : class {}
class C : Class {
func print() { Swift.print("C!") }
}
class D : C {
override func print() { Swift.print("D!") }
}
class E : C {
override func print() { Swift.print("E!") }
}
class X : Class {
}
func allToC<T>(_ x: T) -> C {
return x as! C
}
func allToCOrE<T>(_ x: T) -> C {
if x is C {
return x as! C
}
return E()
}
func anyToC(_ x: Any) -> C {
return x as! C
}
func anyToCOrE(_ x: Any) -> C {
if x is C {
return x as! C
}
return E()
}
func allClassesToC<T : Class>(_ x: T) -> C {
return x as! C
}
func allClassesToCOrE<T : Class>(_ x: T) -> C {
if x is C {
return x as! C
}
return E()
}
func anyClassToC(_ x: Class) -> C {
return x as! C
}
func anyClassToCOrE(_ x: Class) -> C {
if x is C {
return x as! C
}
return E()
}
func allToAll<T, U>(_ t: T, _: U.Type) -> Bool {
return t is U
}
func allMetasToAllMetas<T, U>(_: T.Type, _: U.Type) -> Bool {
return T.self is U.Type
}
print(allToInt(22)) // CHECK: 22
print(anyToInt(44)) // CHECK: 44
allToC(C()).print() // CHECK: C!
allToC(D()).print() // CHECK: D!
anyToC(C()).print() // CHECK: C!
anyToC(D()).print() // CHECK: D!
allClassesToC(C()).print() // CHECK: C!
allClassesToC(D()).print() // CHECK: D!
anyClassToC(C()).print() // CHECK: C!
anyClassToC(D()).print() // CHECK: D!
print(allToIntOrZero(55)) // CHECK: 55
print(allToIntOrZero("fifty-five")) // CHECK: 0
print(anyToIntOrZero(88)) // CHECK: 88
print(anyToIntOrZero("eighty-eight")) // CHECK: 0
allToCOrE(C()).print() // CHECK: C!
allToCOrE(D()).print() // CHECK: D!
allToCOrE(143).print() // CHECK: E!
allToCOrE(X()).print() // CHECK: E!
anyToCOrE(C()).print() // CHECK: C!
anyToCOrE(D()).print() // CHECK: D!
anyToCOrE(143).print() // CHECK: E!
anyToCOrE(X()).print() // CHECK: E!
allClassesToCOrE(C()).print() // CHECK: C!
allClassesToCOrE(D()).print() // CHECK: D!
allClassesToCOrE(X()).print() // CHECK: E!
anyClassToCOrE(C()).print() // CHECK: C!
anyClassToCOrE(D()).print() // CHECK: D!
anyClassToCOrE(X()).print() // CHECK: E!
protocol P {}
struct PS: P {}
enum PE: P {}
class PC: P {}
class PCSub: PC {}
func nongenericAnyIsP(type: Any.Type) -> Bool {
return type is P.Type
}
func nongenericAnyIsPAndAnyObject(type: Any.Type) -> Bool {
return type is (P & AnyObject).Type
}
func nongenericAnyIsPAndPCSub(type: Any.Type) -> Bool {
return type is (P & PCSub).Type
}
func genericAnyIs<T>(type: Any.Type, to: T.Type, expected: Bool) -> Bool {
// If we're testing against a runtime that doesn't have the fix this tests,
// just pretend we got it right.
if #available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *) {
return type is T.Type
} else {
return expected
}
}
// CHECK-LABEL: casting types to protocols with generics:
print("casting types to protocols with generics:")
print(nongenericAnyIsP(type: PS.self)) // CHECK: true
print(genericAnyIs(type: PS.self, to: P.self, expected: true)) // CHECK-ONONE: true
print(nongenericAnyIsP(type: PE.self)) // CHECK: true
print(genericAnyIs(type: PE.self, to: P.self, expected: true)) // CHECK-ONONE: true
print(nongenericAnyIsP(type: PC.self)) // CHECK: true
print(genericAnyIs(type: PC.self, to: P.self, expected: true)) // CHECK-ONONE: true
print(nongenericAnyIsP(type: PCSub.self)) // CHECK: true
print(genericAnyIs(type: PCSub.self, to: P.self, expected: true)) // CHECK-ONONE: true
// CHECK-LABEL: casting types to protocol & AnyObject existentials:
print("casting types to protocol & AnyObject existentials:")
print(nongenericAnyIsPAndAnyObject(type: PS.self)) // CHECK: false
print(genericAnyIs(type: PS.self, to: (P & AnyObject).self, expected: false)) // CHECK: false
print(nongenericAnyIsPAndAnyObject(type: PE.self)) // CHECK: false
print(genericAnyIs(type: PE.self, to: (P & AnyObject).self, expected: false)) // CHECK: false
print(nongenericAnyIsPAndAnyObject(type: PC.self)) // CHECK: true
print(genericAnyIs(type: PC.self, to: (P & AnyObject).self, expected: true)) // CHECK-ONONE: true
print(nongenericAnyIsPAndAnyObject(type: PCSub.self)) // CHECK: true
print(genericAnyIs(type: PCSub.self, to: (P & AnyObject).self, expected: true)) // CHECK-ONONE: true
// CHECK-LABEL: casting types to protocol & class existentials:
print("casting types to protocol & class existentials:")
print(nongenericAnyIsPAndPCSub(type: PS.self)) // CHECK: false
print(genericAnyIs(type: PS.self, to: (P & PCSub).self, expected: false)) // CHECK: false
print(nongenericAnyIsPAndPCSub(type: PE.self)) // CHECK: false
print(genericAnyIs(type: PE.self, to: (P & PCSub).self, expected: false)) // CHECK: false
//print(nongenericAnyIsPAndPCSub(type: PC.self)) // CHECK-SR-11565: false -- FIXME: reenable this when SR-11565 is fixed
print(genericAnyIs(type: PC.self, to: (P & PCSub).self, expected: false)) // CHECK: false
print(nongenericAnyIsPAndPCSub(type: PCSub.self)) // CHECK: true
print(genericAnyIs(type: PCSub.self, to: (P & PCSub).self, expected: true)) // CHECK-ONONE: true
// CHECK-LABEL: type comparisons:
print("type comparisons:\n")
print(allMetasToAllMetas(Int.self, Int.self)) // CHECK: true
print(allMetasToAllMetas(Int.self, Float.self)) // CHECK: false
print(allMetasToAllMetas(C.self, C.self)) // CHECK: true
print(allMetasToAllMetas(D.self, C.self)) // CHECK: true
print(allMetasToAllMetas(C.self, D.self)) // CHECK: false
print(C.self is D.Type) // CHECK: false
print((D.self as C.Type) is D.Type) // CHECK: true
let t: Any.Type = type(of: 1 as Any)
print(t is Int.Type) // CHECK: true
print(t is Float.Type) // CHECK: false
print(t is C.Type) // CHECK: false
let u: Any.Type = type(of: (D() as Any))
print(u is C.Type) // CHECK: true
print(u is D.Type) // CHECK: true
print(u is E.Type) // CHECK: false
print(u is Int.Type) // CHECK: false
// FIXME: Can't spell AnyObject.Protocol
// CHECK-LABEL: AnyObject casts:
print("AnyObject casts:")
print(allToAll(C(), AnyObject.self)) // CHECK: true
// On Darwin, the object will be the ObjC-runtime-class object;
// out of Darwin, this should not succeed.
print(allToAll(type(of: C()), AnyObject.self))
// CHECK-objc: true
// CHECK-native: false
// Bridging
// NSNumber on Darwin, __SwiftValue on Linux.
print(allToAll(0, AnyObject.self)) // CHECK: true
// This will get bridged using __SwiftValue.
struct NotBridged { var x: Int }
print(allToAll(NotBridged(x: 0), AnyObject.self)) // CHECK: true
#if canImport(Foundation)
// This requires Foundation (for NSCopying):
print(allToAll(NotBridged(x: 0), NSCopying.self)) // CHECK-objc: true
#endif
// On Darwin, these casts fail (intentionally) even though __SwiftValue does
// technically conform to these protocols through NSObject.
// Off Darwin, it should not conform at all.
print(allToAll(NotBridged(x: 0), CustomStringConvertible.self)) // CHECK: false
print(allToAll(NotBridged(x: 0), (AnyObject & CustomStringConvertible).self)) // CHECK: false
#if canImport(Foundation)
// This requires Foundation (for NSArray):
//
// rdar://problem/19482567
//
func swiftOptimizesThisFunctionIncorrectly() -> Bool {
let anArray = [] as NSArray
if let whyThisIsNeverExecutedIfCalledFromFunctionAndNotFromMethod = anArray as? [NSObject] {
return true
}
return false
}
let result = swiftOptimizesThisFunctionIncorrectly()
print("Bridge cast result: \(result)") // CHECK-NEXT-objc: Bridge cast result: true
#endif
| apache-2.0 | c52abe68b51c7b0c6c7b1d6862e76ee2 | 29.86692 | 120 | 0.677507 | 3.234263 | false | false | false | false |
ru-kio/Hydra | FXHydra/FXLocalized.swift | 3 | 711 | //
// FXLocalized.swift
// FXHydra
//
// Created by kioshimafx on 3/12/16.
// Copyright ยฉ 2016 FXSolutions. All rights reserved.
//
import UIKit
//func FXLocalized(text: String!) -> String! {
// if text == nil {
// return nil
// }
//
// let appRes = NSLocalizedString(text, comment: "")
//
// if (appRes != text) {
// return appRes
// }
//
// for t in tables {
// let res = NSLocalizedString(text, tableName: t.table, bundle: t.bundle, value: text, comment: "")
// if (res != text) {
// return res
// }
// }
//
// return NSLocalizedString(text, tableName: nil, bundle: NSBundle.framework, value: text, comment: "")
//} | mit | 04735be42cccc77a4117cf591e37c32c | 22.7 | 107 | 0.549296 | 3.256881 | false | false | false | false |
nwjs/chromium.src | ios/chrome/browser/ui/omnibox/popup/shared/popup_view.swift | 7 | 18760 | // Copyright 2022 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import SwiftUI
/// A view modifier which embeds the content in a `ScrollViewReader` and calls `action`
/// when the provided `value` changes. It is similar to the `onChange` view modifier, but provides
/// a `ScrollViewProxy` object in addition to the new state of `value` when calling `action`.
struct ScrollOnChangeModifier<V: Equatable>: ViewModifier {
@Binding var value: V
let action: (V, ScrollViewProxy) -> Void
func body(content: Content) -> some View {
ScrollViewReader { scrollProxy in
content.onChange(of: value) { newState in action(newState, scrollProxy) }
}
}
}
#if __IPHONE_16_0
@available(iOS 16, *)
struct ScrollDismissesKeyboardModifier: ViewModifier {
let mode: ScrollDismissesKeyboardMode
func body(content: Content) -> some View {
content.scrollDismissesKeyboard(mode)
}
}
#endif // __IPHONE_16_0
/// Utility which provides a way to treat the `accessibilityIdentifier` view modifier as a value.
struct AccessibilityIdentifierModifier: ViewModifier {
let identifier: String
func body(content: Content) -> some View {
content.accessibilityIdentifier(identifier)
}
}
/// Returns the closest pixel-aligned value higher than `value`, taking the scale
/// factor into account. At a scale of 1, equivalent to ceil().
func alignValueToUpperPixel(_ value: CGFloat) -> CGFloat {
let scale = UIScreen.main.scale
return ceil(value * scale) / scale
}
struct PopupView: View {
enum Dimensions {
static let matchListRowInsets = EdgeInsets(.zero)
enum VariationOne {
static let pedalSectionSeparatorPadding = EdgeInsets(
top: 8.5, leading: 0, bottom: 4, trailing: 0)
static let visibleTopContentInset: CGFloat = 4
// This allows hiding floating section headers at the top of the list in variation one.
static let hiddenTopContentInset: CGFloat = -50
static let selfSizingListBottomMargin: CGFloat = 8
}
enum VariationTwo {
// Default height if no other header or footer. This spaces the sections
// out properly in variation two.
static let headerFooterHeight: CGFloat = 16
// Default list row insets. These are removed to inset the popup to the
// width of the omnibox.
static let defaultInset: CGFloat = 16
static let selfSizingListBottomMargin: CGFloat = 16
}
}
/// Applies custom list style according to UI variation.
struct ListStyleModifier: ViewModifier {
@Environment(\.popupUIVariation) var popupUIVariation: PopupUIVariation
func body(content: Content) -> some View {
switch popupUIVariation {
case .one:
content.listStyle(.plain)
case .two:
content.listStyle(.insetGrouped)
}
}
}
/// Calls `onScroll` when the user performs a drag gesture over the content of the list.
struct ListScrollDetectionModifier: ViewModifier {
let onScroll: () -> Void
func body(content: Content) -> some View {
content
// For some reason, without this, user interaction is not forwarded to the list.
// Setting the count to more than one ensures a buggy SwiftUI will not
// ignore actual tap gestures in subviews.
.onTapGesture(count: 2) {}
// Long press gestures are dismissed and `onPressingChanged` called with
// `pressing` equal to `false` when the user performs a drag gesture
// over the content, hence why this works. `DragGesture` cannot be used
// here, even with a `simultaneousGesture` modifier, because it prevents
// swipe-to-delete from correctly triggering within the list.
.onLongPressGesture(
perform: {},
onPressingChanged: { pressing in
if !pressing {
onScroll()
}
})
}
}
/// Custom modifier emulating `.environment(key, value)`.
struct EnvironmentValueModifier<Value>: ViewModifier {
let key: WritableKeyPath<SwiftUI.EnvironmentValues, Value>
let value: Value
init(_ key: WritableKeyPath<SwiftUI.EnvironmentValues, Value>, _ value: Value) {
self.key = key
self.value = value
}
func body(content: Content) -> some View {
content.environment(key, value)
}
}
/// Custom modifier emulating `.padding(edges, length)`.
struct PaddingModifier: ViewModifier {
let edges: Edge.Set
let length: CGFloat?
init(_ edges: Edge.Set = .all, _ length: CGFloat? = nil) {
self.edges = edges
self.length = length
}
func body(content: Content) -> some View {
content.padding(edges, length)
}
}
@ObservedObject var model: PopupModel
@ObservedObject var uiConfiguration: PopupUIConfiguration
private let shouldSelfSize: Bool
private let appearanceContainerType: UIAppearanceContainer.Type?
@Environment(\.colorScheme) var colorScheme: ColorScheme
@Environment(\.popupUIVariation) var popupUIVariation: PopupUIVariation
@Environment(\.horizontalSizeClass) var sizeClass
/// The current height of the self-sizing list.
@State private var selfSizingListHeight: CGFloat? = nil
/// This is an ugly workaround that is not necessary in iOS 16.
/// This flag is set on trailing button tap, and is reset a fraction of a second later. This
/// prevents the onScroll event from being dispatched to the delegate.
@State private var shouldIgnoreScrollEvents: Bool = false
init(
model: PopupModel, uiConfiguration: PopupUIConfiguration, shouldSelfSize: Bool = false,
appearanceContainerType: UIAppearanceContainer.Type? = nil
) {
self.model = model
self.uiConfiguration = uiConfiguration
self.shouldSelfSize = shouldSelfSize
self.appearanceContainerType = appearanceContainerType
}
/// Determines if a custom separator should be shown for a given row.
func shouldDisplayCustomSeparators(
section: PopupMatchSection, indexPath: IndexPath, isHighlighted: Bool
) -> Bool {
// No separator on the last row in a section.
// No separators when there is one or 0 rows in a section.
// No separator on highlighted row.
return
!isHighlighted && (section.matches.count > 1)
&& (indexPath.row < section.matches.count - 1)
}
/// View for a single PopupMatchSection of the suggestion list.
@ViewBuilder func sectionContents(
_ sectionIndex: Int, _ section: PopupMatchSection, _ geometry: GeometryProxy
) -> some View {
let layoutDirection =
(model.rtlContentAttribute == .unspecified)
? (UIApplication.shared.userInterfaceLayoutDirection
== UIUserInterfaceLayoutDirection.leftToRight
? LayoutDirection.leftToRight : LayoutDirection.rightToLeft)
: ((model.rtlContentAttribute == .forceLeftToRight)
? LayoutDirection.leftToRight : LayoutDirection.rightToLeft)
ForEach(Array(zip(section.matches.indices, section.matches)), id: \.0) {
matchIndex, match in
let indexPath = IndexPath(row: matchIndex, section: sectionIndex)
let highlighted = indexPath == model.highlightedMatchIndexPath
PopupMatchRowView(
match: match,
isHighlighted: highlighted,
toolbarConfiguration: uiConfiguration.toolbarConfiguration,
selectionHandler: {
model.delegate?.autocompleteResultConsumer(
model, didSelect: match.suggestion, inRow: UInt(matchIndex))
},
trailingButtonHandler: {
model.delegate?.autocompleteResultConsumer(
model, didTapTrailingButtonOn: match.suggestion,
inRow: UInt(matchIndex))
shouldIgnoreScrollEvents = true
DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
shouldIgnoreScrollEvents = false
}
},
uiConfiguration: uiConfiguration,
shouldDisplayCustomSeparator: shouldDisplayCustomSeparators(
section: section, indexPath: indexPath, isHighlighted: highlighted)
)
.id(indexPath)
.deleteDisabled(!match.supportsDeletion)
.listRowInsets(Dimensions.matchListRowInsets)
.listRowBackground(Color.clear)
.accessibilityElement(children: .combine)
.accessibilityIdentifier(
OmniboxPopupAccessibilityIdentifierHelper.accessibilityIdentifierForRow(at: indexPath)
)
.environment(\.layoutDirection, layoutDirection)
}
.onDelete { indexSet in
for matchIndex in indexSet {
model.delegate?.autocompleteResultConsumer(
model, didSelectSuggestionForDeletion: section.matches[matchIndex].suggestion,
inRow: UInt(matchIndex))
}
}
}
/// Section footer, to be used in variation two.
@ViewBuilder func footerForVariationTwo() -> some View {
Spacer()
// Use `leastNonzeroMagnitude` to remove the footer. Otherwise,
// it uses a default height.
.frame(height: CGFloat.leastNonzeroMagnitude)
.listRowInsets(EdgeInsets())
}
func listContent(geometry: GeometryProxy) -> some View {
ForEach(Array(zip(model.sections.indices, model.sections)), id: \.0) {
sectionIndex, section in
Section(
header: header(for: section, at: sectionIndex, geometry: geometry),
footer: popupUIVariation == .one ? nil : footerForVariationTwo()
) {
sectionContents(sectionIndex, section, geometry)
}
}
}
@ViewBuilder
var bottomSeparator: some View {
Color.toolbarShadow.frame(height: alignValueToUpperPixel(kToolbarSeparatorHeight))
}
var selfSizingListBottomMargin: CGFloat {
switch popupUIVariation {
case .one:
return Dimensions.VariationOne.selfSizingListBottomMargin
case .two:
return Dimensions.VariationTwo.selfSizingListBottomMargin
}
}
func scrollModifier() -> some ViewModifier {
#if __IPHONE_16_0
if #available(iOS 16.0, *) {
return ScrollDismissesKeyboardModifier(
mode: uiConfiguration.shouldDismissKeyboardOnScroll ? .immediately : .never)
} else {
return ListScrollDetectionModifier(onScroll: onScroll)
}
#else // __IPHONE_16_0
return ListScrollDetectionModifier(onScroll: onScroll)
#endif // __IPHONE_16_0
}
@ViewBuilder
var listView: some View {
let commonListModifier = AccessibilityIdentifierModifier(
identifier: kOmniboxPopupTableViewAccessibilityIdentifier
)
.concat(ScrollOnChangeModifier(value: $model.sections, action: onNewSections))
.concat(ListStyleModifier())
.concat(EnvironmentValueModifier(\.defaultMinListHeaderHeight, 0))
.concat(omniboxPaddingModifier)
.concat(scrollModifier())
GeometryReader { geometry in
ZStack(alignment: .top) {
listBackground.frame(height: selfSizingListHeight)
if shouldSelfSize {
ZStack(alignment: .top) {
SelfSizingList(
bottomMargin: selfSizingListBottomMargin,
listModifier: commonListModifier,
content: {
listContent(geometry: geometry)
},
emptySpace: {
PopupEmptySpaceView.View()
}
)
.frame(width: geometry.size.width, height: geometry.size.height)
.onPreferenceChange(SelfSizingListHeightPreferenceKey.self) { height in
selfSizingListHeight = height
}
bottomSeparator.offset(x: 0, y: selfSizingListHeight ?? 0)
}
} else {
List {
listContent(geometry: geometry)
}
// This fixes list section header internal representation from overlapping safe areas.
.padding([.leading, .trailing], 0.2)
.modifier(commonListModifier)
.ignoresSafeArea(.keyboard)
.ignoresSafeArea(.container, edges: [.leading, .trailing])
.frame(width: geometry.size.width, height: geometry.size.height)
}
}
}
}
var body: some View {
listView
.onAppear(perform: onAppear)
.measureVisibleSuggestionCount(with: self.uiConfiguration, updating: self.model)
}
@ViewBuilder
func header(for section: PopupMatchSection, at index: Int, geometry: GeometryProxy) -> some View {
if section.header.isEmpty {
if popupUIVariation == .one {
if index == 0 {
// Additional space between omnibox and top section.
let firstSectionHeader = Color(uiConfiguration.toolbarConfiguration.backgroundColor)
.frame(
width: geometry.size.width, height: -Dimensions.VariationOne.hiddenTopContentInset)
if #available(iOS 15.0, *) {
// Additional padding is added on iOS 15, which needs to be cancelled here.
firstSectionHeader.padding([.top, .bottom], -6)
} else {
firstSectionHeader
}
} else if index == 1 {
// Spacing and separator below the top (pedal) section is inserted as
// a header in the second section.
let separatorColor = Color.separator
let pedalSectionSeparator =
separatorColor
.frame(width: geometry.size.width, height: 0.5)
.padding(Dimensions.VariationOne.pedalSectionSeparatorPadding)
.background(Color(uiConfiguration.toolbarConfiguration.backgroundColor))
if #available(iOS 15.0, *) {
pedalSectionSeparator.padding([.top, .bottom], -6)
} else {
pedalSectionSeparator
}
} else {
EmptyView()
}
} else {
Spacer()
.frame(height: Dimensions.VariationTwo.headerFooterHeight)
.listRowInsets(EdgeInsets())
}
} else {
Text(section.header)
}
}
@Environment(\.layoutDirection) var layoutDirection: LayoutDirection
/// Returns a `ViewModifier` to correctly space the sides of the list based
/// on the current omnibox spacing
var omniboxPaddingModifier: some ViewModifier {
let leadingSpace: CGFloat
let trailingSpace: CGFloat
let leadingHorizontalMargin: CGFloat
let trailingHorizontalMargin: CGFloat
switch popupUIVariation {
case .one:
leadingSpace = 0
trailingSpace = 0
leadingHorizontalMargin = 0
trailingHorizontalMargin = 0
case .two:
leadingSpace = uiConfiguration.omniboxLeadingSpace - Dimensions.VariationTwo.defaultInset
trailingSpace =
(shouldSelfSize && sizeClass != .compact
? uiConfiguration.omniboxTrailingSpace : uiConfiguration.safeAreaTrailingSpace)
- Dimensions.VariationTwo.defaultInset
leadingHorizontalMargin = 0
trailingHorizontalMargin = sizeClass == .compact ? kContractedLocationBarHorizontalMargin : 0
}
return PaddingModifier([.leading], leadingSpace + leadingHorizontalMargin).concat(
PaddingModifier([.trailing], trailingSpace + trailingHorizontalMargin))
}
var listBackground: some View {
let backgroundColor: Color
// iOS 14 + SwiftUI has a bug with dark mode colors in high contrast mode.
// If no dark mode + high contrast color is provided, they are supposed to
// default to the dark mode color. Instead, SwiftUI defaults to the light
// mode color. This bug is fixed in iOS 15, but until then, a workaround
// color with the dark mode + high contrast color specified is used.
if #available(iOS 15, *) {
switch popupUIVariation {
case .one:
backgroundColor = Color(uiConfiguration.toolbarConfiguration.backgroundColor)
case .two:
backgroundColor = .groupedPrimaryBackground
}
} else {
switch popupUIVariation {
case .one:
backgroundColor = Color("background_color_swiftui_ios14")
case .two:
backgroundColor = Color("grouped_primary_background_color_swiftui_ios14")
}
}
return backgroundColor.edgesIgnoringSafeArea(.all)
}
func onAppear() {
if let appearanceContainerType = self.appearanceContainerType {
let listAppearance = UITableView.appearance(whenContainedInInstancesOf: [
appearanceContainerType
])
listAppearance.backgroundColor = .clear
// Custom separators are provided, so the system ones are made invisible.
listAppearance.separatorColor = .clear
listAppearance.separatorStyle = .none
listAppearance.separatorInset = .zero
if #available(iOS 15.0, *) {
listAppearance.sectionHeaderTopPadding = 0
} else {
listAppearance.sectionFooterHeight = 0
}
if popupUIVariation == .one {
listAppearance.contentInset.top = Dimensions.VariationOne.hiddenTopContentInset
listAppearance.contentInset.top += Dimensions.VariationOne.visibleTopContentInset
}
if shouldSelfSize {
listAppearance.bounces = false
}
}
}
func onScroll() {
guard !shouldIgnoreScrollEvents else {
return
}
model.highlightedMatchIndexPath = nil
model.delegate?.autocompleteResultConsumerDidScroll(model)
}
func onNewSections(sections: [PopupMatchSection], scrollProxy: ScrollViewProxy) {
// Scroll to the very top of the list.
if sections.first?.matches.first != nil {
scrollProxy.scrollTo(IndexPath(row: 0, section: 0), anchor: UnitPoint(x: 0, y: -.infinity))
}
}
}
struct PopupView_Previews: PreviewProvider {
static func model() -> PopupModel {
PopupModel(
matches: [PopupMatch.previews], headers: ["Suggestions"], dataSource: nil, delegate: nil)
}
static var previews: some View {
let sample = PopupView(
model: model(), uiConfiguration: PopupUIConfiguration.previewsConfiguration()
).previewDevice(PreviewDevice(rawValue: "iPhone 13 mini"))
sample.environment(\.popupUIVariation, .one)
.environment(\.locale, .init(identifier: "ar"))
sample.environment(\.popupUIVariation, .two)
.environment(\.locale, .init(identifier: "ar"))
sample.environment(\.popupUIVariation, .one)
sample.environment(\.popupUIVariation, .two)
sample.environment(\.locale, .init(identifier: "ar"))
PopupView(model: model(), uiConfiguration: PopupUIConfiguration.previewsConfigurationIPad())
.previewDevice(PreviewDevice(rawValue: "iPad Pro (11-inch) (3rd generation)"))
let darkSample = sample.environment(\.colorScheme, .dark)
darkSample.environment(\.popupUIVariation, .one)
darkSample.environment(\.popupUIVariation, .two)
let sampleWithExtraLargeFont =
sample.environment(\.sizeCategory, .accessibilityExtraLarge)
sampleWithExtraLargeFont.environment(\.popupUIVariation, .one)
sampleWithExtraLargeFont.environment(\.popupUIVariation, .two)
}
}
| bsd-3-clause | 81f72ccdbe061dd31040a8bd3923efbd | 35.569201 | 100 | 0.682303 | 4.960338 | false | true | false | false |
gregomni/swift | test/expr/closure/trailing.swift | 2 | 27976 | // RUN: %target-typecheck-verify-swift -swift-version 4
@discardableResult
func takeFunc(_ f: (Int) -> Int) -> Int {}
func takeValueAndFunc(_ value: Int, _ f: (Int) -> Int) {}
func takeTwoFuncs(_ f: (Int) -> Int, _ g: (Int) -> Int) {}
func takeFuncWithDefault(f : ((Int) -> Int)? = nil) {}
func takeTwoFuncsWithDefaults(f1 : ((Int) -> Int)? = nil, f2 : ((String) -> String)? = nil) {}
// expected-note@-1{{'takeTwoFuncsWithDefaults(f1:f2:)' declared here}}
struct X {
func takeFunc(_ f: (Int) -> Int) {}
func takeValueAndFunc(_ value: Int, f: (Int) -> Int) {}
func takeTwoFuncs(_ f: (Int) -> Int, g: (Int) -> Int) {}
}
func addToMemberCalls(_ x: X) {
x.takeFunc() { x in x }
x.takeFunc() { $0 }
x.takeValueAndFunc(1) { x in x }
x.takeTwoFuncs({ x in x }) { y in y }
}
func addToCalls() {
takeFunc() { x in x }
takeFunc() { $0 }
takeValueAndFunc(1) { x in x }
takeTwoFuncs({ x in x }) { y in y }
}
func makeCalls() {
takeFunc { x in x }
takeFunc { $0 }
takeTwoFuncs ({ x in x }) { y in y }
}
func notPostfix() {
_ = 1 + takeFunc { $0 }
}
func notLiterals() {
struct SR3671 { // <https://bugs.swift.org/browse/SR-3671>
var v: Int = 1 { // expected-error {{variable with getter/setter cannot have an initial value}}
get {
return self.v
}
}
}
var x: Int? = nil { get { } } // expected-error {{variable with getter/setter cannot have an initial value}}
_ = 1 {}
// expected-error@-1 {{consecutive statements on a line must be separated by ';'}}
// expected-error@-2 {{closure expression is unused}} expected-note@-2 {{did you mean to use a 'do' statement?}} {{9-9=do }}
_ = "hello" {}
// expected-error@-1 {{consecutive statements on a line must be separated by ';'}}
// expected-error@-2 {{closure expression is unused}} expected-note@-2 {{did you mean to use a 'do' statement?}} {{15-15=do }}
_ = [42] {}
// expected-error@-1 {{consecutive statements on a line must be separated by ';'}}
// expected-error@-2 {{closure expression is unused}} expected-note@-2 {{did you mean to use a 'do' statement?}} {{12-12=do }}
_ = (6765, 10946, 17711) {}
// expected-error@-1 {{consecutive statements on a line must be separated by ';'}}
// expected-error@-2 {{closure expression is unused}} expected-note@-2 {{did you mean to use a 'do' statement?}} {{28-28=do }}
}
class C {
func map(_ x: (Int) -> Int) -> C { return self }
func filter(_ x: (Int) -> Bool) -> C { return self }
}
var a = C().map {$0 + 1}.filter {$0 % 3 == 0}
var b = C().map {$0 + 1}
.filter {$0 % 3 == 0}
var c = C().map
{
$0 + 1
}
var c2 = C().map // expected-note{{callee is here}}
{ // expected-warning{{braces here form a trailing closure separated from its callee by multiple newlines}}
$0 + 1
}
var c3 = C().map // expected-note{{callee is here}}
// blah blah blah
{ // expected-warning{{braces here form a trailing closure separated from its callee by multiple newlines}}
$0 + 1
}
// Calls with multiple trailing closures should be rejected until we have time
// to design it right.
// <rdar://problem/16835718> Ban multiple trailing closures
func multiTrailingClosure(_ a : () -> (), b : () -> ()) { // expected-note {{'multiTrailingClosure(_:b:)' declared here}}
multiTrailingClosure({}) {} // ok
multiTrailingClosure {} {} // expected-error {{missing argument for parameter 'b' in call}} expected-error {{consecutive statements on a line must be separated by ';'}} {{26-26=;}} expected-error {{closure expression is unused}} expected-note{{did you mean to use a 'do' statement?}} {{27-27=do }}
}
func labeledArgumentAndTrailingClosure() {
// Trailing closures can bind to labeled parameters.
takeFuncWithDefault { $0 + 1 }
takeFuncWithDefault() { $0 + 1 }
// ... but not non-trailing closures.
takeFuncWithDefault({ $0 + 1 }) // expected-error {{missing argument label 'f:' in call}} {{23-23=f: }}
takeFuncWithDefault(f: { $0 + 1 })
// Trailing closure binds to first parameter... unless only the second matches.
takeTwoFuncsWithDefaults { "Hello, " + $0 } // expected-warning{{backward matching of the unlabeled trailing closure is deprecated; label the argument with 'f2' to suppress this warning}}
takeTwoFuncsWithDefaults { $0 + 1 }
takeTwoFuncsWithDefaults(f1: {$0 + 1 })
}
// rdar://problem/17965209
func rdar17965209_f<T>(_ t: T) {}
func rdar17965209(x: Int = 0, _ handler: (_ y: Int) -> ()) {}
func rdar17965209_test() {
rdar17965209() {
(y) -> () in
rdar17965209_f(1)
}
rdar17965209(x: 5) {
(y) -> () in
rdar17965209_f(1)
}
}
// <rdar://problem/22298549> QoI: Unwanted trailing closure produces weird error
func limitXY(_ xy:Int, toGamut gamut: [Int]) {}
let someInt = 0
let intArray = [someInt]
limitXY(someInt, toGamut: intArray) {} // expected-error{{extra trailing closure passed in call}}
// <rdar://problem/23036383> QoI: Invalid trailing closures in stmt-conditions produce lowsy diagnostics
func retBool(x: () -> Int) -> Bool {}
func maybeInt(_: () -> Int) -> Int? {}
func twoClosureArgs(_:()->Void, _:()->Void) -> Bool {}
class Foo23036383 {
init() {}
func map(_: (Int) -> Int) -> Int? {}
func meth1(x: Int, _: () -> Int) -> Bool {}
func meth2(_: Int, y: () -> Int) -> Bool {}
func filter(by: (Int) -> Bool) -> [Int] {}
}
enum MyErr : Error {
case A
}
func r23036383(foo: Foo23036383?, obj: Foo23036383) {
if retBool(x: { 1 }) { } // OK
if (retBool { 1 }) { } // OK
if retBool{ 1 } { // expected-warning {{trailing closure in this context is confusable with the body of the statement; pass as a parenthesized argument to silence this warning}} {{13-13=(x: }} {{18-18=)}}
}
if retBool { 1 } { // expected-warning {{trailing closure in this context is confusable with the body of the statement; pass as a parenthesized argument to silence this warning}} {{13-14=(x: }} {{19-19=)}}
}
if retBool() { 1 } { // expected-warning {{trailing closure in this context is confusable with the body of the statement; pass as a parenthesized argument to silence this warning}} {{14-16=x: }} {{21-21=)}}
} else if retBool( ) { 0 } { // expected-warning {{trailing closure in this context is confusable with the body of the statement; pass as a parenthesized argument to silence this warning}} {{21-24=x: }} {{29-29=)}}
}
if let _ = maybeInt { 1 } { // expected-warning {{trailing closure in this context is confusable with the body of the statement; pass as a parenthesized argument to silence this warning}} {{22-23=(}} {{28-28=)}}
}
if let _ = maybeInt { 1 } , true { // expected-warning {{trailing closure in this context is confusable with the body of the statement; pass as a parenthesized argument to silence this warning}} {{22-23=(}} {{28-28=)}}
}
if let _ = foo?.map {$0+1} { // expected-warning {{trailing closure in this context is confusable with the body of the statement; pass as a parenthesized argument to silence this warning}} {{22-23=(}} {{29-29=)}}
}
if let _ = foo?.map() {$0+1} { // expected-warning {{trailing closure in this context is confusable with the body of the statement; pass as a parenthesized argument to silence this warning}} {{23-25=}} {{31-31=)}}
}
if let _ = foo, retBool { 1 } { // expected-warning {{trailing closure in this context is confusable with the body of the statement; pass as a parenthesized argument to silence this warning}} {{26-27=(x: }} {{32-32=)}}
}
if obj.meth1(x: 1) { 0 } { // expected-warning {{trailing closure in this context is confusable with the body of the statement; pass as a parenthesized argument to silence this warning}} {{20-22=, }} {{27-27=)}}
}
if obj.meth2(1) { 0 } { // expected-warning {{trailing closure in this context is confusable with the body of the statement; pass as a parenthesized argument to silence this warning}} {{17-19=, y: }} {{24-24=)}}
}
for _ in obj.filter {$0 > 4} { // expected-warning {{trailing closure in this context is confusable with the body of the statement; pass as a parenthesized argument to silence this warning}} {{22-23=(by: }} {{31-31=)}}
}
for _ in obj.filter {$0 > 4} where true { // expected-warning {{trailing closure in this context is confusable with the body of the statement; pass as a parenthesized argument to silence this warning}} {{22-23=(by: }} {{31-31=)}}
}
for _ in [1,2] where retBool { 1 } { // expected-warning {{trailing closure in this context is confusable with the body of the statement; pass as a parenthesized argument to silence this warning}} {{31-32=(x: }} {{37-37=)}}
}
while retBool { 1 } { // expected-warning {{trailing closure in this context is confusable with the body of the statement; pass as a parenthesized argument to silence this warning}} {{16-17=(x: }} {{22-22=)}}
}
while let _ = foo, retBool { 1 } { // expected-warning {{trailing closure in this context is confusable with the body of the statement; pass as a parenthesized argument to silence this warning}} {{29-30=(x: }} {{35-35=)}}
}
switch retBool { return 1 } { // expected-warning {{trailing closure in this context is confusable with the body of the statement; pass as a parenthesized argument to silence this warning}} {{17-18=(x: }} {{30-30=)}}
default: break
}
do {
throw MyErr.A;
} catch MyErr.A where retBool { 1 } { // expected-warning {{trailing closure in this context is confusable with the body of the statement; pass as a parenthesized argument to silence this warning}} {{32-33=(x: }} {{38-38=)}}
} catch { }
if let _ = maybeInt { 1 }, retBool { 1 } { }
// expected-warning@-1 {{trailing closure in this context is confusable with the body of the statement; pass as a parenthesized argument to silence this warning}} {{22-23=(}} {{28-28=)}}
// expected-warning@-2 {{trailing closure in this context is confusable with the body of the statement; pass as a parenthesized argument to silence this warning}} {{37-38=(x: }} {{43-43=)}}
if let _ = foo?.map {$0+1}.map {$0+1} {} // expected-warning {{trailing closure in this context is confusable with the body of the statement; pass as a parenthesized argument to silence this warning}} {{33-34=(}} {{40-40=)}}
// expected-warning@-1 {{trailing closure in this context is confusable with the body of the statement; pass as a parenthesized argument to silence this warning}} {{22-23=(}} {{29-29=)}}
if let _ = foo?.map {$0+1}.map({$0+1}) {} // expected-warning {{trailing closure in this context is confusable with the body of the statement; pass as a parenthesized argument to silence this warning}} {{22-23=(}} {{29-29=)}}
if let _ = foo?.map {$0+1}.map({$0+1}).map{$0+1} {} // expected-warning {{trailing closure in this context is confusable with the body of the statement; pass as a parenthesized argument to silence this warning}} {{45-45=(}} {{51-51=)}}
// expected-warning@-1 {{trailing closure in this context is confusable with the body of the statement; pass as a parenthesized argument to silence this warning}} {{22-23=(}} {{29-29=)}}
if twoClosureArgs({}) {} {} // expected-warning {{trailing closure in this context is confusable with the body of the statement; pass as a parenthesized argument to silence this warning}} {{23-25=, }} {{27-27=)}}
if let _ = (foo?.map {$0+1}.map({$0+1}).map{$0+1}) {} // OK
if let _ = (foo?.map {$0+1}.map({$0+1})).map({$0+1}) {} // OK
}
func id<T>(fn: () -> T) -> T { return fn() }
func any<T>(fn: () -> T) -> Any { return fn() }
func testSR8736() {
if !id { true } { return } // expected-warning {{trailing closure in this context is confusable with the body of the statement; pass as a parenthesized argument to silence this warning}}
if id { true } == true { return } // expected-warning {{trailing closure in this context is confusable with the body of the statement; pass as a parenthesized argument to silence this warning}}
if true == id { true } { return } // expected-warning {{trailing closure in this context is confusable with the body of the statement; pass as a parenthesized argument to silence this warning}}
if id { true } ? true : false { return } // expected-warning {{trailing closure in this context is confusable with the body of the statement; pass as a parenthesized argument to silence this warning}}
if true ? id { true } : false { return } // expected-warning {{trailing closure in this context is confusable with the body of the statement; pass as a parenthesized argument to silence this warning}}
if true ? true : id { false } { return } // expected-warning {{trailing closure in this context is confusable with the body of the statement; pass as a parenthesized argument to silence this warning}}
if id { [false,true] }[0] { return } // expected-warning {{trailing closure in this context is confusable with the body of the statement; pass as a parenthesized argument to silence this warning}}
if id { { true } } () { return } // expected-warning {{trailing closure in this context is confusable with the body of the statement; pass as a parenthesized argument to silence this warning}}
if any { true } as! Bool { return } // expected-warning {{trailing closure in this context is confusable with the body of the statement; pass as a parenthesized argument to silence this warning}}
if let _ = any { "test" } as? Int { return } // expected-warning {{trailing closure in this context is confusable with the body of the statement; pass as a parenthesized argument to silence this warning}}
if any { "test" } is Int { return } // expected-warning {{trailing closure in this context is confusable with the body of the statement; pass as a parenthesized argument to silence this warning}}
if let _ = id { [] as [Int]? }?.first { return } // expected-warning {{trailing closure in this context is confusable with the body of the statement; pass as a parenthesized argument to silence this warning}}
if id { true as Bool? }! { return } // expected-warning {{trailing closure in this context is confusable with the body of the statement; pass as a parenthesized argument to silence this warning}}
if case id { 1 } = 1 { return } // expected-warning {{trailing closure in this context is confusable with the body of the statement; pass as a parenthesized argument to silence this warning}}
if case 1 = id { 1 } { return } // expected-warning {{trailing closure in this context is confusable with the body of the statement; pass as a parenthesized argument to silence this warning}}
if case 1 = id { 1 } /*comment*/ { return } // expected-warning {{trailing closure in this context is confusable with the body of the statement; pass as a parenthesized argument to silence this warning}}
if case (id { 1 }) = 1 { return } // OK
if case 1 = (id { 1 }) { return } // OK
if [id { true }].count == 0 { return } // OK
if [id { true } : "test"].keys.count == 0 { return } // OK
if "\(id { true })" == "foo" { return } // OK
if (id { true }) { return } // OK
if (id { true }) { }
[1, 2, 3].count // expected-warning {{expression of type 'Int' is unused}}
if true { }
() // OK
if true
{
}
() // OK
}
func overloadOnLabel(a: () -> Void) {}
func overloadOnLabel(b: () -> Void) {}
func overloadOnLabel(c: () -> Void) {}
func overloadOnLabel2(a: () -> Void) {}
func overloadOnLabel2(_: () -> Void) {}
func overloadOnLabelArgs(_: Int, a: () -> Void) {}
func overloadOnLabelArgs(_: Int, b: () -> Void) {}
func overloadOnLabelArgs2(_: Int, a: () -> Void) {}
func overloadOnLabelArgs2(_: Int, _: () -> Void) {}
func overloadOnLabelDefaultArgs(x: Int = 0, a: () -> Void) {}
func overloadOnLabelDefaultArgs(x: Int = 1, b: () -> Void) {}
func overloadOnLabelSomeDefaultArgs(_: Int, x: Int = 0, a: () -> Void) {}
func overloadOnLabelSomeDefaultArgs(_: Int, x: Int = 1, b: () -> Void) {}
func overloadOnDefaultArgsOnly(x: Int = 0, a: () -> Void) {} // expected-note 2 {{found this candidate}}
func overloadOnDefaultArgsOnly(y: Int = 1, a: () -> Void) {} // expected-note 2 {{found this candidate}}
func overloadOnDefaultArgsOnly2(x: Int = 0, a: () -> Void) {} // expected-note 2 {{found this candidate}}
func overloadOnDefaultArgsOnly2(y: Bool = true, a: () -> Void) {} // expected-note 2 {{found this candidate}}
func overloadOnDefaultArgsOnly3(x: Int = 0, a: () -> Void) {} // expected-note 2 {{found this candidate}}
func overloadOnDefaultArgsOnly3(x: Bool = true, a: () -> Void) {} // expected-note 2 {{found this candidate}}
func overloadOnSomeDefaultArgsOnly(_: Int, x: Int = 0, a: () -> Void) {} // expected-note {{found this candidate}}
func overloadOnSomeDefaultArgsOnly(_: Int, y: Int = 1, a: () -> Void) {} // expected-note {{found this candidate}}
func overloadOnSomeDefaultArgsOnly2(_: Int, x: Int = 0, a: () -> Void) {} // expected-note {{found this candidate}}
func overloadOnSomeDefaultArgsOnly2(_: Int, y: Bool = true, a: () -> Void) {} // expected-note {{found this candidate}}
func overloadOnSomeDefaultArgsOnly3(_: Int, x: Int = 0, a: () -> Void) {} // expected-note {{found this candidate}}
func overloadOnSomeDefaultArgsOnly3(_: Int, x: Bool = true, a: () -> Void) {} // expected-note {{found this candidate}}
func testOverloadAmbiguity() {
overloadOnLabel {} // expected-error {{ambiguous use of 'overloadOnLabel'}} expected-note {{use an explicit argument label instead of a trailing closure to call 'overloadOnLabel(a:)'}} {{18-19=(a: }} {{21-21=)}} expected-note {{use an explicit argument label instead of a trailing closure to call 'overloadOnLabel(b:)'}} {{18-19=(b: }} {{21-21=)}} expected-note {{use an explicit argument label instead of a trailing closure to call 'overloadOnLabel(c:)'}} {{18-19=(c: }} {{21-21=)}}
overloadOnLabel() {} // expected-error {{ambiguous use of 'overloadOnLabel'}} expected-note {{use an explicit argument label instead of a trailing closure to call 'overloadOnLabel(a:)'}} {{19-21=a: }} {{23-23=)}} expected-note {{use an explicit argument label instead of a trailing closure to call 'overloadOnLabel(b:)'}} {{19-21=b: }} {{23-23=)}} expected-note {{use an explicit argument label instead of a trailing closure to call 'overloadOnLabel(c:)'}} {{19-21=c: }} {{23-23=)}}
overloadOnLabel2 {} // expected-error {{ambiguous use of 'overloadOnLabel2'}} expected-note {{use an explicit argument label instead of a trailing closure to call 'overloadOnLabel2(a:)'}} {{19-20=(a: }} {{22-22=)}} expected-note {{avoid using a trailing closure to call 'overloadOnLabel2'}} {{19-20=(}} {{22-22=)}}
overloadOnLabel2() {} // expected-error {{ambiguous use of 'overloadOnLabel2'}} expected-note {{use an explicit argument label instead of a trailing closure to call 'overloadOnLabel2(a:)'}} {{20-22=a: }} {{24-24=)}} expected-note {{avoid using a trailing closure to call 'overloadOnLabel2'}} {{20-22=}} {{24-24=)}}
overloadOnLabelArgs(1) {} // expected-error {{ambiguous use of 'overloadOnLabelArgs'}} expected-note {{use an explicit argument label instead of a trailing closure to call 'overloadOnLabelArgs(_:a:)'}} {{24-26=, a: }} {{28-28=)}} expected-note {{use an explicit argument label instead of a trailing closure to call 'overloadOnLabelArgs(_:b:)'}} {{24-26=, b: }} {{28-28=)}}
overloadOnLabelArgs2(1) {} // expected-error {{ambiguous use of 'overloadOnLabelArgs2'}} expected-note {{use an explicit argument label instead of a trailing closure to call 'overloadOnLabelArgs2(_:a:)'}} {{25-27=, a: }} {{29-29=)}} expected-note {{avoid using a trailing closure to call 'overloadOnLabelArgs2'}} {{25-27=, }} {{29-29=)}}
overloadOnLabelDefaultArgs {} // expected-error {{ambiguous use of 'overloadOnLabelDefaultArgs'}} expected-note {{use an explicit argument label instead of a trailing closure to call 'overloadOnLabelDefaultArgs(x:a:)'}} {{29-30=(a: }} {{32-32=)}} expected-note {{use an explicit argument label instead of a trailing closure to call 'overloadOnLabelDefaultArgs(x:b:)'}} {{29-30=(b: }} {{32-32=)}}
overloadOnLabelDefaultArgs() {} // expected-error {{ambiguous use of 'overloadOnLabelDefaultArgs'}} expected-note {{use an explicit argument label instead of a trailing closure to call 'overloadOnLabelDefaultArgs(x:a:)'}} {{30-32=a: }} {{34-34=)}} expected-note {{use an explicit argument label instead of a trailing closure to call 'overloadOnLabelDefaultArgs(x:b:)'}} {{30-32=b: }} {{34-34=)}}
overloadOnLabelDefaultArgs(x: 2) {} // expected-error {{ambiguous use of 'overloadOnLabelDefaultArgs'}} expected-note {{use an explicit argument label instead of a trailing closure to call 'overloadOnLabelDefaultArgs(x:a:)'}} {{34-36=, a: }} {{38-38=)}} expected-note {{use an explicit argument label instead of a trailing closure to call 'overloadOnLabelDefaultArgs(x:b:)'}} {{34-36=, b: }} {{38-38=)}}
overloadOnLabelSomeDefaultArgs(1) {} // expected-error {{ambiguous use of 'overloadOnLabelSomeDefaultArgs'}} expected-note {{use an explicit argument label instead of a trailing closure to call 'overloadOnLabelSomeDefaultArgs(_:x:a:)'}} {{35-37=, a: }} {{39-39=)}} expected-note {{use an explicit argument label instead of a trailing closure to call 'overloadOnLabelSomeDefaultArgs(_:x:b:)'}} {{35-37=, b: }} {{39-39=)}}
overloadOnLabelSomeDefaultArgs(1, x: 2) {} // expected-error {{ambiguous use of 'overloadOnLabelSomeDefaultArgs'}} expected-note {{use an explicit argument label instead of a trailing closure to call 'overloadOnLabelSomeDefaultArgs(_:x:a:)'}} {{41-43=, a: }} {{45-45=)}} expected-note {{use an explicit argument label instead of a trailing closure to call 'overloadOnLabelSomeDefaultArgs(_:x:b:)'}} {{41-43=, b: }} {{45-45=)}}
overloadOnLabelSomeDefaultArgs( // expected-error {{ambiguous use of 'overloadOnLabelSomeDefaultArgs'}} expected-note {{use an explicit argument label instead of a trailing closure to call 'overloadOnLabelSomeDefaultArgs(_:x:a:)'}} {{12-5=, a: }} {{4-4=)}} expected-note {{use an explicit argument label instead of a trailing closure to call 'overloadOnLabelSomeDefaultArgs(_:x:b:)'}} {{12-5=, b: }} {{4-4=)}}
1, x: 2
) {
// some
}
overloadOnDefaultArgsOnly {} // expected-error {{ambiguous use of 'overloadOnDefaultArgsOnly'}}
overloadOnDefaultArgsOnly() {} // expected-error {{ambiguous use of 'overloadOnDefaultArgsOnly'}}
overloadOnDefaultArgsOnly2 {} // expected-error {{ambiguous use of 'overloadOnDefaultArgsOnly2'}}
overloadOnDefaultArgsOnly2() {} // expected-error {{ambiguous use of 'overloadOnDefaultArgsOnly2'}}
overloadOnDefaultArgsOnly3 {} // expected-error {{ambiguous use of 'overloadOnDefaultArgsOnly3(x:a:)'}}
overloadOnDefaultArgsOnly3() {} // expected-error {{ambiguous use of 'overloadOnDefaultArgsOnly3(x:a:)'}}
overloadOnSomeDefaultArgsOnly(1) {} // expected-error {{ambiguous use of 'overloadOnSomeDefaultArgsOnly'}}
overloadOnSomeDefaultArgsOnly2(1) {} // expected-error {{ambiguous use of 'overloadOnSomeDefaultArgsOnly2'}}
overloadOnSomeDefaultArgsOnly3(1) {} // expected-error {{ambiguous use of 'overloadOnSomeDefaultArgsOnly3(_:x:a:)'}}
}
func overloadMismatch(a: () -> Void) -> Bool { return true}
func overloadMismatch(x: Int = 0, a: () -> Void) -> Int { return 0 }
func overloadMismatchLabel(a: () -> Void) -> Bool { return true}
func overloadMismatchLabel(x: Int = 0, b: () -> Void) -> Int { return 0 }
func overloadMismatchArgs(_: Int, a: () -> Void) -> Bool { return true}
func overloadMismatchArgs(_: Int, x: Int = 0, a: () -> Void) -> Int { return 0 }
func overloadMismatchArgsLabel(_: Int, a: () -> Void) -> Bool { return true}
func overloadMismatchArgsLabel(_: Int, x: Int = 0, b: () -> Void) -> Int { return 0 }
func overloadMismatchMultiArgs(_: Int, a: () -> Void) -> Bool { return true}
func overloadMismatchMultiArgs(_: Int, x: Int = 0, y: Int = 1, a: () -> Void) -> Int { return 0 }
func overloadMismatchMultiArgsLabel(_: Int, a: () -> Void) -> Bool { return true}
func overloadMismatchMultiArgsLabel(_: Int, x: Int = 0, y: Int = 1, b: () -> Void) -> Int { return 0 }
func overloadMismatchMultiArgs2(_: Int, z: Int = 0, a: () -> Void) -> Bool { return true}
func overloadMismatchMultiArgs2(_: Int, x: Int = 0, y: Int = 1, a: () -> Void) -> Int { return 0 }
func overloadMismatchMultiArgs2Label(_: Int, z: Int = 0, a: () -> Void) -> Bool { return true}
func overloadMismatchMultiArgs2Label(_: Int, x: Int = 0, y: Int = 1, b: () -> Void) -> Int { return 0 }
func testOverloadDefaultArgs() {
let a = overloadMismatch {}
_ = a as String // expected-error {{cannot convert value of type 'Bool' to type 'String'}}
let b = overloadMismatch() {}
_ = b as String // expected-error {{cannot convert value of type 'Bool' to type 'String'}}
let c = overloadMismatchLabel {}
_ = c as String // expected-error {{cannot convert value of type 'Bool' to type 'String'}}
let d = overloadMismatchLabel() {}
_ = d as String // expected-error {{cannot convert value of type 'Bool' to type 'String'}}
let e = overloadMismatchArgs(0) {}
_ = e as String // expected-error {{cannot convert value of type 'Bool' to type 'String'}}
let f = overloadMismatchArgsLabel(0) {}
_ = f as String // expected-error {{cannot convert value of type 'Bool' to type 'String'}}
let g = overloadMismatchMultiArgs(0) {}
_ = g as String // expected-error {{cannot convert value of type 'Bool' to type 'String'}}
let h = overloadMismatchMultiArgsLabel(0) {}
_ = h as String // expected-error {{cannot convert value of type 'Bool' to type 'String'}}
let i = overloadMismatchMultiArgs2(0) {}
_ = i as String // expected-error {{cannot convert value of type 'Bool' to type 'String'}}
let j = overloadMismatchMultiArgs2Label(0) {}
_ = j as String // expected-error {{cannot convert value of type 'Bool' to type 'String'}}
}
func variadic(_: (() -> Void)...) {}
func variadicLabel(closures: (() -> Void)...) {}
func variadicOverloadMismatch(_: (() -> Void)...) -> Bool { return true }
func variadicOverloadMismatch(x: Int = 0, _: (() -> Void)...) -> Int { return 0 }
func variadicOverloadMismatchLabel(a: (() -> Void)...) -> Bool { return true }
func variadicOverloadMismatchLabel(x: Int = 0, b: (() -> Void)...) -> Int { return 0 }
func variadicAndNonOverload(_: (() -> Void)) -> Bool { return false }
func variadicAndNonOverload(_: (() -> Void)...) -> Int { return 0 }
func variadicAndNonOverloadLabel(a: (() -> Void)) -> Bool { return false }
func variadicAndNonOverloadLabel(b: (() -> Void)...) -> Int { return 0 }
func testVariadic() {
variadic {}
variadic() {}
variadic({}) {}
variadicLabel {}
variadicLabel() {}
variadicLabel(closures: {}) {}
let a1 = variadicOverloadMismatch {}
_ = a1 as String // expected-error {{cannot convert value of type 'Bool' to type 'String'}}
let a2 = variadicOverloadMismatch() {}
_ = a2 as String // expected-error {{cannot convert value of type 'Bool' to type 'String'}}
let b1 = variadicOverloadMismatchLabel {}
_ = b1 as String // expected-error {{cannot convert value of type 'Bool' to type 'String'}}
let b2 = variadicOverloadMismatchLabel() {}
_ = b2 as String // expected-error {{cannot convert value of type 'Bool' to type 'String'}}
let c1 = variadicAndNonOverloadLabel {}
_ = c1 as String // expected-error {{cannot convert value of type 'Bool' to type 'String'}}
let c2 = variadicAndNonOverload {}
_ = c2 as String // expected-error {{cannot convert value of type 'Bool' to type 'String'}}
}
// rdar://18426302
class TrailingBase {
init(fn: () -> ()) {}
init(x: Int, fn: () -> ()) {}
convenience init() {
self.init {}
}
convenience init(x: Int) {
self.init(x: x) {}
}
}
class TrailingDerived : TrailingBase {
init(foo: ()) {
super.init {}
}
init(x: Int, foo: ()) {
super.init(x: x) {}
}
}
// rdar://85343171 - Spurious warning on trailing closure in argument list.
func rdar85343171() {
func foo(_ i: Int) -> Bool { true }
func bar(_ fn: () -> Void) -> Int { 0 }
// Okay, as trailing closure is nested in argument list.
if foo(bar {}) {}
}
| apache-2.0 | d89a00eecea762c2b8b8e5aa330e93dc | 57.649895 | 485 | 0.668037 | 3.976688 | false | false | false | false |
dreamsxin/swift | test/SILGen/objc_nonnull_lie_hack.swift | 3 | 4148 | // RUN: rm -rf %t/APINotes
// RUN: mkdir -p %t/APINotes
// RUN: %clang_apinotes -yaml-to-binary %S/Inputs/gizmo.apinotes -o %t/APINotes/gizmo.apinotesc
// RUN: %target-swift-frontend -emit-silgen -sdk %S/Inputs -I %S/Inputs -I %t/APINotes -enable-source-import -primary-file %s | FileCheck -check-prefix=SILGEN %s
// RUN: %target-swift-frontend -emit-sil -O -sdk %S/Inputs -I %S/Inputs -I %t/APINotes -enable-source-import -primary-file %s | FileCheck -check-prefix=OPT %s
// REQUIRES: objc_interop
import Foundation
import gizmo
// SILGEN-LABEL: sil hidden @_TF21objc_nonnull_lie_hack10makeObjectFT_GSqCSo8NSObject_
// SILGEN: [[INIT:%.*]] = function_ref @_TFCSo8NSObjectC
// SILGEN: [[NONOPTIONAL:%.*]] = apply [[INIT]]
// SILGEN: [[OPTIONAL:%.*]] = unchecked_ref_cast [[NONOPTIONAL]]
// OPT-LABEL: sil hidden @_TF21objc_nonnull_lie_hack10makeObjectFT_GSqCSo8NSObject_
// OPT: [[OPT:%.*]] = unchecked_ref_cast
// OPT: switch_enum [[OPT]] : $Optional<NSObject>, case #Optional.none!enumelt: [[NIL:bb[0-9]+]]
func makeObject() -> NSObject? {
let foo: NSObject? = NSObject()
if foo == nil {
print("nil")
}
return foo
}
// OPT-LABEL: sil hidden @_TF21objc_nonnull_lie_hack15callClassMethod
// OPT: [[METATYPE:%[0-9]+]] = metatype $@thick Gizmo.Type
// OPT: [[METHOD:%[0-9]+]] = class_method [volatile] [[METATYPE]] : $@thick Gizmo.Type, #Gizmo.nonNilGizmo!1.foreign : Gizmo.Type -> () -> Gizmo , $@convention(objc_method) (@objc_metatype Gizmo.Type) -> @autoreleased Gizmo
// OPT: [[OBJC_METATYPE:%[0-9]+]] = metatype $@objc_metatype Gizmo.Type
// OPT: [[NONOPTIONAL:%[0-9]+]] = apply [[METHOD]]([[OBJC_METATYPE]]) : $@convention(objc_method) (@objc_metatype Gizmo.Type) -> @autoreleased Gizmo
// OPT: [[OPTIONAL:%[0-9]+]] = unchecked_ref_cast [[NONOPTIONAL]] : $Gizmo to $Optional<Gizmo>
// OPT: switch_enum [[OPTIONAL]] : $Optional<Gizmo>
func callClassMethod() -> Gizmo? {
let foo: Gizmo? = Gizmo.nonNilGizmo()
if foo == nil {
print("nil")
}
return foo
}
// OPT-LABEL: sil hidden @_TTSf4g___TF21objc_nonnull_lie_hack18callInstanceMetho
// OPT: [[METHOD:%[0-9]+]] = class_method [volatile] [[OBJ:%[0-9]+]] : $Gizmo, #Gizmo.nonNilGizmo!1.foreign : Gizmo -> () -> Gizmo , $@convention(objc_method) (Gizmo) -> @autoreleased Gizmo
// OPT: [[NONOPTIONAL:%[0-9]+]] = apply [[METHOD]]([[OBJ]]) : $@convention(objc_method) (Gizmo) -> @autoreleased Gizmo
// OPT: [[OPTIONAL:%[0-9]+]] = unchecked_ref_cast [[NONOPTIONAL]]
// OPT: switch_enum [[OPTIONAL]] : $Optional<Gizmo>
func callInstanceMethod(gizmo: Gizmo) -> Gizmo? {
let foo: Gizmo? = gizmo.nonNilGizmo()
if foo == nil {
print("nil")
}
return foo
}
// OPT-LABEL: sil hidden @_TTSf4g___TF21objc_nonnull_lie_hack12loadPropertyFT5gizmoCSo5Gizmo_GSqS0__
// OPT: [[GETTER:%[0-9]+]] = class_method [volatile] [[OBJ:%[0-9]+]] : $Gizmo, #Gizmo.nonNilGizmoProperty!getter.1.foreign : Gizmo -> () -> Gizmo , $@convention(objc_method) (Gizmo) -> @autoreleased Gizmo
// OPT: [[NONOPTIONAL:%[0-9]+]] = apply [[GETTER]]([[OBJ]]) : $@convention(objc_method) (Gizmo) -> @autoreleased Gizmo
// OPT: [[OPTIONAL:%[0-9]+]] = unchecked_ref_cast [[NONOPTIONAL]] : $Gizmo to $Optional<Gizmo>
// OPT: switch_enum [[OPTIONAL]] : $Optional<Gizmo>,
func loadProperty(gizmo: Gizmo) -> Gizmo? {
let foo: Gizmo? = gizmo.nonNilGizmoProperty
if foo == nil {
print("nil")
}
return foo
}
// OPT-LABEL: sil hidden @_TTSf4g___TF21objc_nonnull_lie_hack19loadUnownedPropertyFT5gizmoCSo5Gizmo_GSqS0__
// OPT: [[GETTER:%[0-9]+]] = class_method [volatile] [[OBJ:%[0-9]+]] : $Gizmo, #Gizmo.unownedNonNilGizmoProperty!getter.1.foreign : Gizmo -> () -> Gizmo , $@convention(objc_method) (Gizmo) -> @autoreleased Gizmo
// OPT: [[NONOPTIONAL:%[0-9]+]] = apply [[GETTER]]([[OBJ]]) : $@convention(objc_method) (Gizmo) -> @autoreleased Gizmo
// OPT: [[OPTIONAL:%[0-9]+]] = unchecked_ref_cast [[NONOPTIONAL]] : $Gizmo to $Optional<Gizmo>
// OPT: switch_enum [[OPTIONAL]] : $Optional<Gizmo>
func loadUnownedProperty(gizmo: Gizmo) -> Gizmo? {
let foo: Gizmo? = gizmo.unownedNonNilGizmoProperty
if foo == nil {
print("nil")
}
return foo
}
| apache-2.0 | 80af480e794b3fff34ab44a57390eb8f | 50.209877 | 223 | 0.652604 | 3.297297 | false | false | false | false |
borglab/SwiftFusion | Sources/SwiftFusion/Inference/BetweenFactorAlternative.swift | 1 | 1381 | // Copyright 2020 The SwiftFusion 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 _Differentiation
import PenguinStructures
/// A BetweenFactor alternative that uses the Chordal (Frobenious) norm on rotation for Pose3
public struct BetweenFactorAlternative: LinearizableFactor2 {
public let edges: Variables.Indices
public let difference: Pose3
public init(_ startId: TypedID<Pose3>, _ endId: TypedID<Pose3>, _ difference: Pose3) {
self.edges = Tuple2(startId, endId)
self.difference = difference
}
@differentiable
public func errorVector(_ start: Pose3, _ end: Pose3) -> Vector12 {
let actualMotion = between(start, end)
let R = actualMotion.coordinate.rot.coordinate.R + (-1) * difference.rot.coordinate.R
let t = actualMotion.t - difference.t
return Vector12(concatenating: R, t)
}
}
| apache-2.0 | 208171c4ccfd5c508cce57d42e390acd | 37.361111 | 93 | 0.738595 | 4.110119 | false | false | false | false |
elpassion/el-space-ios | ELSpace/Screens/Hub/Activity/Type/Activity/ActivityTypeView.swift | 1 | 1479 | import UIKit
import Anchorage
import RxSwift
class ActivityTypeView: UIView {
init() {
super.init(frame: .zero)
addSubviews()
setupLayout()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
let imageView = Factory.imageView()
let titleLabel = Factory.titleLabel()
let button = UIButton()
// MARK: - Privates
private func addSubviews() {
addSubview(imageView)
addSubview(titleLabel)
addSubview(button)
}
private func setupLayout() {
imageView.topAnchor == topAnchor
imageView.leadingAnchor == leadingAnchor
imageView.trailingAnchor == trailingAnchor
titleLabel.topAnchor == imageView.bottomAnchor + 6
titleLabel.leadingAnchor == leadingAnchor
titleLabel.trailingAnchor == trailingAnchor
titleLabel.bottomAnchor == bottomAnchor
button.edgeAnchors == edgeAnchors
}
}
private extension ActivityTypeView {
struct Factory {
static func imageView() -> UIImageView {
let imageView = UIImageView(frame: .zero)
imageView.contentMode = .center
return imageView
}
static func titleLabel() -> UILabel {
let label = UILabel(frame: .zero)
label.textAlignment = .center
label.font = UIFont(name: "Gotham-Medium", size: 8)
return label
}
}
}
| gpl-3.0 | aaae9d1343ecd37a37fbd3e23eac3364 | 23.245902 | 63 | 0.617985 | 5.417582 | false | false | false | false |
jeremy-w/ImageSlicer | ImageSlicing/Cut.swift | 1 | 1659 | // Copyright ยฉ 2016 Jeremy W. Sherman. Released with NO WARRANTY.
//
// 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 Quartz
struct Cut {
let at: CGPoint
let oriented: Orientation
func slice(subimage: Subimage) -> [Subimage] {
let edge: CGRectEdge
let amount: CGFloat
switch oriented {
case .Horizontally:
edge = .minYEdge
amount = at.y - subimage.rect.minY
case .Vertically:
edge = .minXEdge
amount = at.x - subimage.rect.minX
}
let (subrect, otherSubrect) = subimage.rect.divided(atDistance: amount, from: edge)
return [subrect, otherSubrect].map(Subimage.init)
}
}
extension Cut {
var asDictionary: [String: AnyObject] {
var dictionary: [String: AnyObject] = [:]
dictionary["at"] = NSValue(point: at)
dictionary["oriented"] = oriented.rawValue as AnyObject
return dictionary
}
init?(dictionary: [String: AnyObject]) {
guard let value = dictionary["at"] as? NSValue else {
return nil
}
at = value.pointValue
guard
let rawValue = dictionary["oriented"] as? String,
let orientation = Orientation(rawValue: rawValue) else {
return nil
}
oriented = orientation
}
}
extension Cut: Equatable {}
func ==(left: Cut, right: Cut) -> Bool {
return left.oriented == right.oriented && left.at.equalTo(right.at)
}
| mpl-2.0 | c2a8dec5047d79543b80b6d77d0be894 | 27.101695 | 91 | 0.60193 | 4.295337 | false | false | false | false |
yrchen/edx-app-ios | Source/MenuOptionsViewController.swift | 1 | 5100 | //
// MenuOptionsViewController.swift
// edX
//
// Created by Tang, Jeff on 5/15/15.
// Copyright (c) 2015 edX. All rights reserved.
//
import UIKit
protocol MenuOptionsViewControllerDelegate : class {
func menuOptionsController(controller : MenuOptionsViewController, selectedOptionAtIndex index: Int)
func menuOptionsController(controller : MenuOptionsViewController, canSelectOptionAtIndex index: Int) -> Bool
}
//TODO: Remove this (duplicate) when swift compiler recognizes this extension from DiscussionTopicCell.swift
extension UITableViewCell {
private func indentationOffsetForDepth(itemDepth depth : UInt) -> CGFloat {
return CGFloat(depth + 1) * StandardHorizontalMargin
}
}
public class MenuOptionsViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
class MenuOptionTableViewCell : UITableViewCell {
static let identifier = "MenuOptionTableViewCellIdentifier"
private let optionLabel = UILabel()
var depth : UInt = 0 {
didSet {
optionLabel.snp_updateConstraints { (make) -> Void in
make.leading.equalTo(contentView).offset(self.indentationOffsetForDepth(itemDepth: depth))
}
}
}
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
contentView.addSubview(optionLabel)
optionLabel.snp_makeConstraints { (make) -> Void in
make.centerY.equalTo(contentView)
make.leading.equalTo(contentView)
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
public struct MenuOption {
let depth : UInt
let label : String
}
var menuWidth: CGFloat = 120.0
var menuHeight: CGFloat = 90.0
static let menuItemHeight: CGFloat = 30.0
private var tableView: UITableView?
var options: [MenuOption] = []
var selectedOptionIndex: Int?
weak var delegate : MenuOptionsViewControllerDelegate?
private var titleTextStyle : OEXTextStyle {
let style = OEXTextStyle(weight: .Normal, size: .XSmall, color: OEXStyles.sharedStyles().neutralDark())
return style
}
public override func viewDidLoad() {
super.viewDidLoad()
let tableView = UITableView(frame: CGRect(x: 0, y: 0, width: menuWidth, height: menuHeight), style: .Plain)
tableView.registerClass(MenuOptionTableViewCell.classForCoder(), forCellReuseIdentifier: MenuOptionTableViewCell.identifier)
tableView.separatorStyle = .SingleLine
tableView.dataSource = self
tableView.delegate = self
tableView.layer.borderColor = OEXStyles.sharedStyles().neutralLight().CGColor
tableView.layer.borderWidth = 1.0
view.addSubview(tableView)
self.tableView = tableView
}
// MARK: - Table view data source
public func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
public func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return options.count
}
public func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(MenuOptionTableViewCell.identifier, forIndexPath: indexPath) as! MenuOptionTableViewCell
// Configure the cell...
let style : OEXTextStyle
let option = options[indexPath.row]
cell.selectionStyle = option.depth == 0 ? .None : .Default
if let optionIndex = selectedOptionIndex where indexPath.row == optionIndex {
cell.backgroundColor = OEXStyles.sharedStyles().neutralLight()
style = titleTextStyle.withColor(OEXStyles.sharedStyles().neutralBlack())
}
else {
cell.backgroundColor = OEXStyles.sharedStyles().neutralWhite()
style = titleTextStyle
}
cell.depth = option.depth
cell.optionLabel.attributedText = style.attributedStringWithText(option.label)
cell.applyStandardSeparatorInsets()
return cell
}
public func tableView(tableView: UITableView, willSelectRowAtIndexPath indexPath: NSIndexPath) -> NSIndexPath? {
if delegate?.menuOptionsController(self, canSelectOptionAtIndex:indexPath.row) ?? false {
return indexPath
}
else {
return nil
}
}
public func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
delegate?.menuOptionsController(self, selectedOptionAtIndex: indexPath.row)
}
// MARK: - Table view delegate
public func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 30
}
}
| apache-2.0 | e5ad91c8cb60b2fc9a0a559f73020519 | 34.664336 | 151 | 0.664706 | 5.58598 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.