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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
lee0741/Glider | Glider Widget/Story.swift | 1 | 2313 | //
// Story.swift
// Glider
//
// Created by Yancen Li on 3/5/17.
// Copyright © 2017 Yancen Li. All rights reserved.
//
import Foundation
enum StoryType: String {
case news = "Hacker News"
case best = "Best"
case newest = "Newest"
case ask = "Ask HN"
case show = "Show HN"
case jobs = "Jobs"
case noobstories = "Noob Stories"
case search
}
struct Story {
let id: Int
let title: String
let time_ago: String
let comments_count: Int
let url: String
let domain: String
var points: Int?
var user: String?
init(from json: [String: Any]) {
// for noob and best type
if let id = json["id"] as? Int {
self.id = id
} else {
self.id = Int(json["id"] as! String)!
}
self.title = json["title"] as! String
self.time_ago = json["time_ago"] as! String
self.comments_count = json["comments_count"] as! Int
// for jobs type
self.points = json["points"] as? Int
self.user = json["user"] as? String
let url = json["url"] as! String
if url.hasPrefix("item?id=") {
self.url = "https://news.ycombinator.com/\(url)"
self.domain = "news.ycombinator.com"
} else {
self.url = url
self.domain = url.components(separatedBy: "/")[2]
}
}
}
extension Story {
static func getStories(completion: @escaping ([Story]) -> Void) {
let url = URL(string: "https://glider.herokuapp.com/news")!
URLSession.shared.dataTask(with: url) { (data, response, error) in
var stories = [Story]()
if let error = error {
print("Failed to fetch data: \(error)")
return
}
guard let data = data else { return }
if let rawStories = try? JSONSerialization.jsonObject(with: data, options: []) as! [[String: Any]] {
rawStories.forEach { rawStroy in
stories.append(Story.init(from: rawStroy))
}
}
DispatchQueue.main.async {
completion(stories)
}
}.resume()
}
}
| mit | f873d379c3a4d7ae3c81d64f49c75f61 | 25.574713 | 112 | 0.505623 | 4.05614 | false | false | false | false |
Pluto-tv/RxSwift | RxExample/RxExample/Services/ImageService.swift | 1 | 2671 | //
// ImageService.swift
// Example
//
// Created by Krunoslav Zaher on 3/28/15.
// Copyright (c) 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
#if !RX_NO_MODULE
import RxSwift
import RxCocoa
#endif
#if os(iOS)
import UIKit
#elseif os(OSX)
import Cocoa
#endif
protocol ImageService {
func imageFromURL(URL: NSURL) -> Observable<Image>
}
class DefaultImageService: ImageService {
static let sharedImageService = DefaultImageService() // Singleton
let $: Dependencies = Dependencies.sharedDependencies
// 1st level cache
let imageCache = NSCache()
// 2nd level cache
let imageDataCache = NSCache()
let loadingImage = ActivityIndicator()
private init() {
// cost is approx memory usage
self.imageDataCache.totalCostLimit = 10 * MB
self.imageCache.countLimit = 20
}
func decodeImage(imageData: NSData) -> Observable<Image> {
return just(imageData)
.observeOn($.backgroundWorkScheduler)
.map { data in
guard let image = Image(data: data) else {
// some error
throw apiError("Decoding image error")
}
return image
}
.observeOn($.mainScheduler)
}
func imageFromURL(URL: NSURL) -> Observable<Image> {
return deferred {
let maybeImage = self.imageCache.objectForKey(URL) as? Image
let decodedImage: Observable<Image>
// best case scenario, it's already decoded an in memory
if let image = maybeImage {
decodedImage = just(image)
}
else {
let cachedData = self.imageDataCache.objectForKey(URL) as? NSData
// does image data cache contain anything
if let cachedData = cachedData {
decodedImage = self.decodeImage(cachedData)
}
else {
// fetch from network
decodedImage = self.$.URLSession.rx_data(NSURLRequest(URL: URL))
.doOn(onNext: { data in
self.imageDataCache.setObject(data, forKey: URL)
})
.flatMap(self.decodeImage)
.trackActivity(self.loadingImage)
}
}
return decodedImage.doOn(onNext: { image in
self.imageCache.setObject(image, forKey: URL)
})
}
.observeOn($.mainScheduler)
}
}
| mit | d1351ac11b18bb6a598442728127c3ee | 27.72043 | 84 | 0.540621 | 5.310139 | false | false | false | false |
Cookiezby/YiIndex | YiIndex/View/YiHudView.swift | 1 | 2978 | //
// YiHudView.swift
// YiIndex
//
// Created by cookie on 22/07/2017.
// Copyright © 2017 cookie. All rights reserved.
//
import Foundation
import UIKit
class YiHudView: UIImageView {
let dot: CALayer = {
let layer = CALayer()
layer.cornerRadius = 3
layer.backgroundColor = UIColor.white.cgColor
return layer
}()
var labelList:[UILabel]!
var labelSize:CGSize!
var max: Int = 3
var index = 0
var currLabel: String {
get{
var str = ""
for label in labelList {
if (label.text == "-"){
break
}else{
str.append(label.text!)
}
}
return str
}
}
init(frame: CGRect, level: Int) {
super.init(frame: frame)
max = level
labelSize = frame.size
clipsToBounds = true
backgroundColor = UIColor(white: 0.0, alpha: 0.5)
layer.cornerRadius = 5
labelList = [UILabel]()
for i in 0 ..< max {
let label = createLabel()
addSubview(label)
label.frame = CGRect(x: CGFloat(i) * labelSize.width, y: 0, width: labelSize.width, height: labelSize.height)
labelList.append(label)
}
layer.addSublayer(dot)
dot.frame = CGRect(x: labelSize.width / 2 - 3, y: labelSize.height - 10, width: 6, height: 6)
}
func createLabel() -> UILabel {
let label = UILabel()
label.frame = CGRect(x: 0, y: 0, width: labelSize.width, height: labelSize.height)
label.textAlignment = .center
label.textColor = UIColor.white
label.text = "-"
label.font = UIFont.systemFont(ofSize: 40)
return label
}
func insertLabel() {
guard (index + 1) < max else {
return
}
index += 1
labelList[index].text = labelList[index-1].text
UIView.animate(withDuration: 0.3, animations: {
self.frame = CGRect(x: 0, y: 0, width: self.labelSize.width * CGFloat(self.index + 1), height: self.frame.height)
self.center = self.superview!.center
}) { (finished) in
UIView.animate(withDuration: 0.5, animations: {
self.dot.frame = self.dot.frame.offsetBy(dx: self.labelSize.width, dy: 0)
})
}
}
func updateLabel(text: String){
labelList[index].text = text
}
func resetHud() {
for label in labelList {
label.text = "-"
}
frame = CGRect(x: 0, y:0, width: labelSize.width, height: labelSize.height)
center = superview!.center
dot.frame = CGRect(x: labelSize.width / 2 - 3, y: labelSize.height - 10, width: 6, height: 6)
index = 0
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| mit | 3315f9adf7df905d087fb4a4aeed166c | 27.902913 | 125 | 0.535102 | 4.18118 | false | false | false | false |
jwfriese/FrequentFlyer | FrequentFlyerTests/Pipelines/PipelineDataDeserializerSpec.swift | 1 | 13951 | import XCTest
import Quick
import Nimble
import RxSwift
import ObjectMapper
@testable import FrequentFlyer
class PipelineDataDeserializerSpec: QuickSpec {
override func spec() {
describe("PipelineDataDeserializer") {
var subject: PipelineDataDeserializer!
beforeEach {
subject = PipelineDataDeserializer()
}
describe("Deserializing pipeline data that is all valid") {
var deserialization$: Observable<[Pipeline]>!
var result: StreamResult<[Pipeline]>!
beforeEach {
let validDataJSONArray = [
[
"name" : "turtle pipeline one",
"public" : true,
"team_name" : "turtle team name"
],
[
"name" : "turtle pipeline two",
"public" : true,
"team_name" : "turtle team name"
]
]
let validData = try! JSONSerialization.data(withJSONObject: validDataJSONArray, options: .prettyPrinted)
deserialization$ = subject.deserialize(validData)
result = StreamResult(deserialization$)
}
it("emits a pipeline for each JSON pipeline entry") {
expect(result.elements.first?.count).to(equal(2))
expect(result.elements.first?[0]).to(equal(Pipeline(name: "turtle pipeline one", isPublic: true, teamName: "turtle team name")))
expect(result.elements.first?[1]).to(equal(Pipeline(name: "turtle pipeline two", isPublic: true, teamName: "turtle team name")))
}
it("emits no error") {
expect(result.error).to(beNil())
}
}
describe("Deserializing pipeline data where some of the data is invalid") {
var deserialization$: Observable<[Pipeline]>!
var result: StreamResult<[Pipeline]>!
context("Missing required 'name' field") {
beforeEach {
let partiallyValidDataJSONArray = [
[
"name" : "turtle pipeline one",
"public" : true,
"team_name" : "turtle team name"
],
[
"public" : true,
"team_name" : "turtle team name"
],
[
"name": "turtle pipeline three",
"public" : false,
"team_name" : "turtle team name"
]
]
let partiallyValidData = try! JSONSerialization.data(withJSONObject: partiallyValidDataJSONArray, options: .prettyPrinted)
deserialization$ = subject.deserialize(partiallyValidData)
result = StreamResult(deserialization$)
}
it("emits a pipeline for each valid JSON pipeline entry") {
expect(result.elements.first?.count).to(equal(2))
expect(result.elements.first?[0]).to(equal(Pipeline(name: "turtle pipeline one", isPublic: true, teamName: "turtle team name")))
expect(result.elements.first?[1]).to(equal(Pipeline(name: "turtle pipeline three", isPublic: false, teamName: "turtle team name")))
}
it("emits no error") {
expect(result.error).to(beNil())
}
}
context("'name' field is not a string") {
beforeEach {
let partiallyValidDataJSONArray = [
[
"name" : "turtle pipeline one",
"public" : true,
"team_name" : "turtle team name"
],
[
"name" : 1,
"public" : false,
"team_name" : "turtle team name"
],
[
"name": "turtle pipeline three",
"public" : false,
"team_name" : "turtle team name"
]
]
let partiallyValidData = try! JSONSerialization.data(withJSONObject: partiallyValidDataJSONArray, options: .prettyPrinted)
deserialization$ = subject.deserialize(partiallyValidData)
result = StreamResult(deserialization$)
}
it("emits a pipeline for each valid JSON pipeline entry") {
expect(result.elements.first?.count).to(equal(2))
expect(result.elements.first?[0]).to(equal(Pipeline(name: "turtle pipeline one", isPublic: true, teamName: "turtle team name")))
expect(result.elements.first?[1]).to(equal(Pipeline(name: "turtle pipeline three", isPublic: false, teamName: "turtle team name")))
}
it("emits no error") {
expect(result.error).to(beNil())
}
}
context("Missing required 'public' field") {
beforeEach {
let partiallyValidDataJSONArray = [
[
"name" : "turtle pipeline one",
"public" : false,
"team_name" : "turtle team name"
],
[
"name" : "turtle pipeline two",
"team_name" : "turtle team name"
],
[
"name": "turtle pipeline three",
"public" : true,
"team_name" : "turtle team name"
]
]
let partiallyValidData = try! JSONSerialization.data(withJSONObject: partiallyValidDataJSONArray, options: .prettyPrinted)
deserialization$ = subject.deserialize(partiallyValidData)
result = StreamResult(deserialization$)
}
it("emits a pipeline for each valid JSON pipeline entry") {
expect(result.elements.first?.count).to(equal(2))
expect(result.elements.first?[0]).to(equal(Pipeline(name: "turtle pipeline one", isPublic: false, teamName: "turtle team name")))
expect(result.elements.first?[1]).to(equal(Pipeline(name: "turtle pipeline three", isPublic: true, teamName: "turtle team name")))
}
it("emits no error") {
expect(result.error).to(beNil())
}
}
context("'public' field is not a bool") {
beforeEach {
let partiallyValidDataJSONArray = [
[
"name" : "turtle pipeline one",
"public" : true,
"team_name" : "turtle team name"
],
[
"name" : "turtle pipeline two",
"public" : 1,
"team_name" : "turtle team name"
],
[
"name": "turtle pipeline three",
"public" : false,
"team_name" : "turtle team name"
]
]
let partiallyValidData = try! JSONSerialization.data(withJSONObject: partiallyValidDataJSONArray, options: .prettyPrinted)
deserialization$ = subject.deserialize(partiallyValidData)
result = StreamResult(deserialization$)
}
it("emits a pipeline for each valid JSON pipeline entry") {
expect(result.elements.first?.count).to(equal(2))
expect(result.elements.first?[0]).to(equal(Pipeline(name: "turtle pipeline one", isPublic: true, teamName: "turtle team name")))
expect(result.elements.first?[1]).to(equal(Pipeline(name: "turtle pipeline three", isPublic: false, teamName: "turtle team name")))
}
it("emits no error") {
expect(result.error).to(beNil())
}
}
context("Missing required 'team_name' field") {
beforeEach {
let partiallyValidDataJSONArray = [
[
"name" : "turtle pipeline one",
"public" : true,
"team_name" : "turtle team name"
],
[
"name" : "turtle pipeline two",
"public" : true
],
[
"name": "turtle pipeline three",
"public" : false,
"team_name" : "turtle team name"
]
]
let partiallyValidData = try! JSONSerialization.data(withJSONObject: partiallyValidDataJSONArray, options: .prettyPrinted)
deserialization$ = subject.deserialize(partiallyValidData)
result = StreamResult(deserialization$)
}
it("emits a pipeline for each valid JSON pipeline entry") {
expect(result.elements.first?.count).to(equal(2))
expect(result.elements.first?[0]).to(equal(Pipeline(name: "turtle pipeline one", isPublic: true, teamName: "turtle team name")))
expect(result.elements.first?[1]).to(equal(Pipeline(name: "turtle pipeline three", isPublic: false, teamName: "turtle team name")))
}
it("emits no error") {
expect(result.error).to(beNil())
}
}
context("'team_name' field is not a string") {
beforeEach {
let partiallyValidDataJSONArray = [
[
"name" : "turtle pipeline one",
"public" : true,
"team_name" : "turtle team name"
],
[
"name" : "turtle pipeline two",
"public" : true,
"team_name" : 1
],
[
"name": "turtle pipeline three",
"public" : true,
"team_name" : "turtle team name"
]
]
let partiallyValidData = try! JSONSerialization.data(withJSONObject: partiallyValidDataJSONArray, options: .prettyPrinted)
deserialization$ = subject.deserialize(partiallyValidData)
result = StreamResult(deserialization$)
}
it("emits a pipeline for each valid JSON pipeline entry") {
expect(result.elements.first?.count).to(equal(2))
expect(result.elements.first?[0]).to(equal(Pipeline(name: "turtle pipeline one", isPublic: true, teamName: "turtle team name")))
expect(result.elements.first?[1]).to(equal(Pipeline(name: "turtle pipeline three", isPublic: true, teamName: "turtle team name")))
}
it("emits no error") {
expect(result.error).to(beNil())
}
}
}
describe("Given data cannot be interpreted as JSON") {
var deserialization$: Observable<[Pipeline]>!
var result: StreamResult<[Pipeline]>!
beforeEach {
let pipelinesDataString = "some string"
let invalidPipelinesData = pipelinesDataString.data(using: String.Encoding.utf8)
deserialization$ = subject.deserialize(invalidPipelinesData!)
result = StreamResult(deserialization$)
}
it("emits no pipelines") {
expect(result.elements).to(beEmpty())
}
it("emits an error") {
let error = result.error as? MapError
expect(error).toNot(beNil())
expect(error?.reason).to(equal("Could not interpret data as JSON"))
}
}
}
}
}
| apache-2.0 | eaf2ceda69d2c870ab2cbc5dbe844082 | 46.452381 | 155 | 0.424199 | 6.376143 | false | false | false | false |
Egibide-DAM/swift | 02_ejemplos/03_estructuras_control/03_alternativa_multiple/05_switch_where.playground/Contents.swift | 1 | 288 | let yetAnotherPoint = (1, -1)
switch yetAnotherPoint {
case let (x, y) where x == y:
print("(\(x), \(y)) is on the line x == y")
case let (x, y) where x == -y:
print("(\(x), \(y)) is on the line x == -y")
case let (x, y):
print("(\(x), \(y)) is just some arbitrary point")
}
| apache-2.0 | e077b72565b95096c4f08370ec27a272 | 27.8 | 54 | 0.53125 | 2.851485 | false | false | false | false |
mtgto/GPM | GPM/github/GitHubScope.swift | 1 | 1139 | //
// GitHubScope.swift
// GPM
//
// Created by mtgto on 2016/09/22.
// Copyright © 2016 mtgto. All rights reserved.
//
import Cocoa
// All definition is found in https://developer.github.com/v3/oauth/#scopes
public enum GitHubScope: String {
case User = "user" // also contains "user:email", "user:follow"
case UserEmail = "user:email"
case UserFollow = "user:follow"
case PublicRepo = "public_repo"
case Repo = "repo"
case RepoDeployment = "repo_deployment"
case RepoStatus = "repo:status"
case DeleteRepo = "delete_repo"
case Notifications = "notifications"
case Gist = "gist"
case ReadRepoHook = "read:repo_hook"
case WriteRepoHook = "write:repo_hook"
case AdminRepoHook = "admin:repo_hook"
case AdminOrgHook = "admin:org_hook"
case ReadOrg = "read:org"
case WriteOrg = "write:org"
case AdminOrg = "admin:org"
case ReadPublicKey = "read:public_key"
case WritePublicKey = "write:public_key"
case AdminPublicKey = "admin:public_key"
case ReadGpgKey = "read:gpg_key"
case WriteGpgKey = "write:gpg_key"
case AdminGpgKey = "admin:gpg_key"
}
| mit | b0650a5135a4ad61c95c4d71879f1f82 | 30.611111 | 75 | 0.672232 | 3.327485 | false | false | false | false |
nixzhu/AudioBot | VoiceMemo/VoiceMemo.swift | 2 | 434 | //
// VoiceMemo.swift
// VoiceMemo
//
// Created by NIX on 15/11/28.
// Copyright © 2015年 nixWork. All rights reserved.
//
import UIKit
class VoiceMemo {
let fileURL: URL
var duration: TimeInterval
var progress: CGFloat = 0
var playing: Bool = false
let createdAt: Date = Date()
init(fileURL: URL, duration: TimeInterval) {
self.fileURL = fileURL
self.duration = duration
}
}
| mit | 2f689367ea232690e6fc63542f2c3075 | 15.576923 | 51 | 0.63109 | 3.780702 | false | false | false | false |
bingoogolapple/SwiftNote-PartOne | UISearchBar/UISearchBar/ViewController.swift | 1 | 3063 | //
// ViewController.swift
// UISearchBar
//
// Created by bingoogol on 14/9/1.
// Copyright (c) 2014年 bingoogol. All rights reserved.
//
import UIKit
// 表格行的可重用标示符
let TableID = "myCell"
class ViewController: UITableViewController,UISearchDisplayDelegate {
// 表格本身显示的数据
var dataList:NSMutableArray!
// 搜索结果数据
var resultList:NSMutableArray!
override func viewDidLoad() {
super.viewDidLoad()
dataList = NSMutableArray(capacity: 30)
//初始化数据
for index in 0 ..< 30 {
dataList.addObject("bingoogol\(arc4random_uniform(10000))")
}
// 为搜索栏中的TableView注册可重用单元格
self.searchDisplayController.searchResultsTableView.registerClass(MyCell.classForCoder(), forCellReuseIdentifier: TableID)
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// 如果使用搜索栏搜索数据,在处理数据源方法时,需要对传入的表格进行对比
if self.searchDisplayController.searchResultsTableView == tableView {
return resultList == nil ? 0 : resultList.count
} else {
return dataList.count
}
}
override func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! {
var cell:UITableViewCell? = tableView.dequeueReusableCellWithIdentifier(TableID) as? UITableViewCell
// 注意:在storyboard中的设定,只能将原型单元格注册到tableView,而不会注册到SearchBar的TableView
// 因此,在此需要对cell是否初始化做进一步处理
//上面已经注册过了,所以次错不用再实例化
// if cell == nil {
// cell = UITableViewCell(style: UITableViewCellStyle.Value2, reuseIdentifier: ID)
// }
// 如果使用搜索栏搜索数据,在处理数据源方法时,需要对传入的表格进行对比
if self.searchDisplayController.searchResultsTableView == tableView {
cell?.textLabel.text = resultList.objectAtIndex(indexPath.row) as NSString
} else {
cell?.textLabel.text = dataList.objectAtIndex(indexPath.row) as NSString
}
return cell
}
//搜索栏代理方法
func searchDisplayController(controller: UISearchDisplayController!, shouldReloadTableForSearchString searchString: String!) -> Bool {
// 根据用户输入的内容,对现有表格内容进行匹配
var predicate:NSPredicate = NSPredicate(format: "self CONTAINS[C] '\(searchString)'")
// 在查询之前需要清理或者初始化数组:懒加载
if resultList != nil {
resultList.removeAllObjects()
}
resultList = NSMutableArray(array: dataList.filteredArrayUsingPredicate(predicate))
// 返回true,刷新表格
return true
}
} | apache-2.0 | 0746a1e8e08ff487583fa1500ddd5a57 | 32.714286 | 138 | 0.658574 | 4.709619 | false | false | false | false |
2794129697/-----mx | CoolXuePlayer/LoginTool.swift | 1 | 1880 | //
// LoginTool.swift
// CoolXuePlayer
//
// Created by lion-mac on 15/7/7.
// Copyright (c) 2015年 lion-mac. All rights reserved.
//
import UIKit
enum LoginType{
case None,QQ,Sina
}
class LoginTool: NSObject {
static var isLogin:Bool = false
static var isAutoLogin:Bool = false
static var isNeedUserLogin:Bool = false
static var loginType:LoginType = .None
static func autoLogin(){
var userAccount:NSUserDefaults = NSUserDefaults.standardUserDefaults()
var is_login:Bool? = userAccount.objectForKey("is_login") as? Bool
var uid:String? = userAccount.objectForKey("uid") as? String
var upwd:String? = userAccount.objectForKey("upwd") as? String
if uid != nil && upwd != nil {
self.Login(uid,upwd: upwd)
self.isAutoLogin = true
}else{
self.isNeedUserLogin = true
}
}
static func Login(uid:String?,upwd:String?){
if uid != nil && upwd != nil {
var url = "http://www.icoolxue.com/account/login"
var bodyParam:Dictionary = ["username":uid!,"password":upwd!]
HttpManagement.requestttt(url, method: "POST",bodyParam: bodyParam,headParam:nil) { (repsone:NSHTTPURLResponse,data:NSData) -> Void in
var bdict:NSDictionary = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments, error: nil) as!NSDictionary
println(bdict)
var code:Int = bdict["code"] as! Int
if HttpManagement.HttpResponseCodeCheck(code, viewController: nil){
var userAccount:NSUserDefaults = NSUserDefaults.standardUserDefaults()
self.isLogin = true
self.isAutoLogin = true
}else{
self.isLogin = false
}
}
}
}
}
| lgpl-3.0 | 0a230d97c222bac44c846d3ada35c5e3 | 38.125 | 159 | 0.608626 | 4.347222 | false | false | false | false |
EckoEdc/simpleDeadlines-iOS | SimpleDeadlinesWatchOS Extension/TaskDetailsInterfaceController.swift | 1 | 1445 | //
// TaskDetailsInterfaceController.swift
// Simple Deadlines
//
// Created by Edric MILARET on 17-01-26.
// Copyright © 2017 Edric MILARET. All rights reserved.
//
import WatchKit
import Foundation
import WatchConnectivity
class TaskDetailsInterfaceController: WKInterfaceController {
@IBOutlet var titleLabel: WKInterfaceLabel!
@IBOutlet var categoryLabel: WKInterfaceLabel!
@IBOutlet var daysLeftLabel: WKInterfaceLabel!
var task: [String: Any] = [:]
var session: WCSession? = nil
override func awake(withContext context: Any?) {
super.awake(withContext: context)
guard context != nil else {return}
let array = context as! [Any]
task = array[0] as! [String: Any]
session = array[1] as? WCSession
titleLabel.setText(task["title"] as? String)
daysLeftLabel.setText(NSLocalizedString("\(task["daysLeft"] as! String) Days left", comment: ""))
categoryLabel.setText(task["category"] as? String)
}
override func willActivate() {
super.willActivate()
}
override func didDeactivate() {
super.didDeactivate()
}
@IBAction func onDoneTapped() {
session?.sendMessage(["TaskDone" : task["id"]!], replyHandler: { response in
self.pop()
}, errorHandler: { (error) in
self.pop()
print(error)
})
}
}
| gpl-3.0 | cd3a0a10bacfb8be374e347d9f918ed0 | 25.740741 | 105 | 0.617729 | 4.643087 | false | false | false | false |
e78l/swift-corelibs-foundation | Foundation/CGFloat.swift | 1 | 25929 | // This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016, 2018 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
@_fixed_layout
public struct CGFloat {
#if arch(i386) || arch(arm)
/// The native type used to store the CGFloat, which is Float on
/// 32-bit architectures and Double on 64-bit architectures.
public typealias NativeType = Float
#elseif arch(x86_64) || arch(arm64) || arch(s390x) || arch(powerpc64) || arch(powerpc64le)
/// The native type used to store the CGFloat, which is Float on
/// 32-bit architectures and Double on 64-bit architectures.
public typealias NativeType = Double
#endif
@_transparent public init() {
self.native = 0.0
}
@_transparent public init(_ value: Float) {
self.native = NativeType(value)
}
@_transparent public init(_ value: Double) {
self.native = NativeType(value)
}
#if !os(Windows) && (arch(i386) || arch(x86_64))
@_transparent public init(_ value: Float80) {
self.native = NativeType(value)
}
#endif
@_transparent public init(_ value: CGFloat) {
self.native = value.native
}
/// Creates a new value, rounded to the closest possible representation.
///
/// If two representable values are equally close, the result is the value
/// with more trailing zeros in its significand bit pattern.
///
/// - Parameter value: The integer to convert to a floating-point value.
public init(_ value: UInt8) {
self.native = NativeType(value)
}
/// Creates a new value, rounded to the closest possible representation.
///
/// If two representable values are equally close, the result is the value
/// with more trailing zeros in its significand bit pattern.
///
/// - Parameter value: The integer to convert to a floating-point value.
public init(_ value: Int8) {
self.native = NativeType(value)
}
/// Creates a new value, rounded to the closest possible representation.
///
/// If two representable values are equally close, the result is the value
/// with more trailing zeros in its significand bit pattern.
///
/// - Parameter value: The integer to convert to a floating-point value.
public init(_ value: UInt16) {
self.native = NativeType(value)
}
/// Creates a new value, rounded to the closest possible representation.
///
/// If two representable values are equally close, the result is the value
/// with more trailing zeros in its significand bit pattern.
///
/// - Parameter value: The integer to convert to a floating-point value.
public init(_ value: Int16) {
self.native = NativeType(value)
}
/// Creates a new value, rounded to the closest possible representation.
///
/// If two representable values are equally close, the result is the value
/// with more trailing zeros in its significand bit pattern.
///
/// - Parameter value: The integer to convert to a floating-point value.
public init(_ value: UInt32) {
self.native = NativeType(value)
}
/// Creates a new value, rounded to the closest possible representation.
///
/// If two representable values are equally close, the result is the value
/// with more trailing zeros in its significand bit pattern.
///
/// - Parameter value: The integer to convert to a floating-point value.
public init(_ value: Int32) {
self.native = NativeType(value)
}
/// Creates a new value, rounded to the closest possible representation.
///
/// If two representable values are equally close, the result is the value
/// with more trailing zeros in its significand bit pattern.
///
/// - Parameter value: The integer to convert to a floating-point value.
public init(_ value: UInt64) {
self.native = NativeType(value)
}
/// Creates a new value, rounded to the closest possible representation.
///
/// If two representable values are equally close, the result is the value
/// with more trailing zeros in its significand bit pattern.
///
/// - Parameter value: The integer to convert to a floating-point value.
public init(_ value: Int64) {
self.native = NativeType(value)
}
/// Creates a new value, rounded to the closest possible representation.
///
/// If two representable values are equally close, the result is the value
/// with more trailing zeros in its significand bit pattern.
///
/// - Parameter value: The integer to convert to a floating-point value.
public init(_ value: UInt) {
self.native = NativeType(value)
}
/// Creates a new value, rounded to the closest possible representation.
///
/// If two representable values are equally close, the result is the value
/// with more trailing zeros in its significand bit pattern.
///
/// - Parameter value: The integer to convert to a floating-point value.
public init(_ value: Int) {
self.native = NativeType(value)
}
/// The native value.
public var native: NativeType
}
extension CGFloat : SignedNumeric {
// FIXME(integers): implement
public init?<T : BinaryInteger>(exactly source: T) {
fatalError()
}
@_transparent
public var magnitude: CGFloat {
return CGFloat(Swift.abs(native))
}
}
extension CGFloat : BinaryFloatingPoint {
public typealias RawSignificand = UInt
public typealias Exponent = Int
@_transparent
public static var exponentBitCount: Int {
return NativeType.exponentBitCount
}
@_transparent
public static var significandBitCount: Int {
return NativeType.significandBitCount
}
// Conversions to/from integer encoding. These are not part of the
// BinaryFloatingPoint prototype because there's no guarantee that an
// integer type of the same size actually exists (e.g. Float80).
@_transparent
public var bitPattern: UInt {
return UInt(native.bitPattern)
}
@_transparent
public init(bitPattern: UInt) {
#if arch(i386) || arch(arm)
native = NativeType(bitPattern: UInt32(bitPattern))
#elseif arch(x86_64) || arch(arm64) || arch(s390x) || arch(powerpc64) || arch(powerpc64le)
native = NativeType(bitPattern: UInt64(bitPattern))
#endif
}
@_transparent
public var sign: FloatingPointSign {
return native.sign
}
@_transparent
public var exponentBitPattern: UInt {
return native.exponentBitPattern
}
@_transparent
public var significandBitPattern: UInt {
return UInt(native.significandBitPattern)
}
@_transparent
public init(sign: FloatingPointSign,
exponentBitPattern: UInt,
significandBitPattern: UInt) {
native = NativeType(sign: sign,
exponentBitPattern: exponentBitPattern,
significandBitPattern: NativeType.RawSignificand(significandBitPattern))
}
@_transparent
public init(nan payload: RawSignificand, signaling: Bool) {
native = NativeType(nan: NativeType.RawSignificand(payload),
signaling: signaling)
}
@_transparent
public static var infinity: CGFloat {
return CGFloat(NativeType.infinity)
}
@_transparent
public static var nan: CGFloat {
return CGFloat(NativeType.nan)
}
@_transparent
public static var signalingNaN: CGFloat {
return CGFloat(NativeType.signalingNaN)
}
@available(*, unavailable, renamed: "nan")
public static var quietNaN: CGFloat {
fatalError("unavailable")
}
@_transparent
public static var greatestFiniteMagnitude: CGFloat {
return CGFloat(NativeType.greatestFiniteMagnitude)
}
@_transparent
public static var pi: CGFloat {
return CGFloat(NativeType.pi)
}
@_transparent
public var ulp: CGFloat {
return CGFloat(native.ulp)
}
@_transparent
public static var leastNormalMagnitude: CGFloat {
return CGFloat(NativeType.leastNormalMagnitude)
}
@_transparent
public static var leastNonzeroMagnitude: CGFloat {
return CGFloat(NativeType.leastNonzeroMagnitude)
}
@_transparent
public var exponent: Int {
return native.exponent
}
@_transparent
public var significand: CGFloat {
return CGFloat(native.significand)
}
@_transparent
public init(sign: FloatingPointSign, exponent: Int, significand: CGFloat) {
native = NativeType(sign: sign,
exponent: exponent, significand: significand.native)
}
@_transparent
public mutating func round(_ rule: FloatingPointRoundingRule) {
native.round(rule)
}
@_transparent
public var nextUp: CGFloat {
return CGFloat(native.nextUp)
}
@_transparent
public mutating func negate() {
native.negate()
}
@_transparent
public static func +=(_ lhs: inout CGFloat, _ rhs: CGFloat) {
lhs.native += rhs.native
}
@_transparent
public static func -=(_ lhs: inout CGFloat, _ rhs: CGFloat) {
lhs.native -= rhs.native
}
@_transparent
public static func *=(_ lhs: inout CGFloat, _ rhs: CGFloat) {
lhs.native *= rhs.native
}
@_transparent
public static func /=(_ lhs: inout CGFloat, _ rhs: CGFloat) {
lhs.native /= rhs.native
}
@_transparent
public mutating func formTruncatingRemainder(dividingBy other: CGFloat) {
native.formTruncatingRemainder(dividingBy: other.native)
}
@_transparent
public mutating func formRemainder(dividingBy other: CGFloat) {
native.formRemainder(dividingBy: other.native)
}
@_transparent
public mutating func formSquareRoot( ) {
native.formSquareRoot( )
}
@_transparent
public mutating func addProduct(_ lhs: CGFloat, _ rhs: CGFloat) {
native.addProduct(lhs.native, rhs.native)
}
@_transparent
public func isEqual(to other: CGFloat) -> Bool {
return self.native.isEqual(to: other.native)
}
@_transparent
public func isLess(than other: CGFloat) -> Bool {
return self.native.isLess(than: other.native)
}
@_transparent
public func isLessThanOrEqualTo(_ other: CGFloat) -> Bool {
return self.native.isLessThanOrEqualTo(other.native)
}
@_transparent
public var isNormal: Bool {
return native.isNormal
}
@_transparent
public var isFinite: Bool {
return native.isFinite
}
@_transparent
public var isZero: Bool {
return native.isZero
}
@_transparent
public var isSubnormal: Bool {
return native.isSubnormal
}
@_transparent
public var isInfinite: Bool {
return native.isInfinite
}
@_transparent
public var isNaN: Bool {
return native.isNaN
}
@_transparent
public var isSignalingNaN: Bool {
return native.isSignalingNaN
}
@available(*, unavailable, renamed: "isSignalingNaN")
public var isSignaling: Bool {
fatalError("unavailable")
}
@_transparent
public var isCanonical: Bool {
return true
}
@_transparent
public var floatingPointClass: FloatingPointClassification {
return native.floatingPointClass
}
@_transparent
public var binade: CGFloat {
return CGFloat(native.binade)
}
@_transparent
public var significandWidth: Int {
return native.significandWidth
}
/// Create an instance initialized to `value`.
@_transparent
public init(floatLiteral value: NativeType) {
native = value
}
/// Create an instance initialized to `value`.
@_transparent
public init(integerLiteral value: Int) {
native = NativeType(value)
}
}
extension CGFloat {
@available(*, unavailable, renamed: "leastNormalMagnitude")
public static var min: CGFloat {
fatalError("unavailable")
}
@available(*, unavailable, renamed: "greatestFiniteMagnitude")
public static var max: CGFloat {
fatalError("unavailable")
}
@available(*, unavailable, message: "Please use the `abs(_:)` free function")
public static func abs(_ x: CGFloat) -> CGFloat {
fatalError("unavailable")
}
}
@available(*, unavailable, renamed: "CGFloat.leastNormalMagnitude")
public var CGFLOAT_MIN: CGFloat {
fatalError("unavailable")
}
@available(*, unavailable, renamed: "CGFloat.greatestFiniteMagnitude")
public var CGFLOAT_MAX: CGFloat {
fatalError("unavailable")
}
extension CGFloat : CustomReflectable {
/// Returns a mirror that reflects `self`.
public var customMirror: Mirror {
return Mirror(reflecting: native)
}
}
extension CGFloat : CustomStringConvertible {
/// A textual representation of `self`.
public var description: String {
return native.description
}
}
extension CGFloat : Hashable {
/// The hash value.
///
/// **Axiom:** `x == y` implies `x.hashValue == y.hashValue`
///
/// - Note: the hash value is not guaranteed to be stable across
/// different invocations of the same program. Do not persist the
/// hash value across program runs.
@_transparent
public var hashValue: Int {
return native.hashValue
}
@_transparent
public func hash(into hasher: inout Hasher) {
hasher.combine(native)
}
@_transparent
public func _rawHashValue(seed: Int) -> Int {
return native._rawHashValue(seed: seed)
}
}
extension UInt8 {
@_transparent
public init(_ value: CGFloat) {
self = UInt8(value.native)
}
}
extension Int8 {
@_transparent
public init(_ value: CGFloat) {
self = Int8(value.native)
}
}
extension UInt16 {
@_transparent
public init(_ value: CGFloat) {
self = UInt16(value.native)
}
}
extension Int16 {
@_transparent
public init(_ value: CGFloat) {
self = Int16(value.native)
}
}
extension UInt32 {
@_transparent
public init(_ value: CGFloat) {
self = UInt32(value.native)
}
}
extension Int32 {
@_transparent
public init(_ value: CGFloat) {
self = Int32(value.native)
}
}
extension UInt64 {
@_transparent
public init(_ value: CGFloat) {
self = UInt64(value.native)
}
}
extension Int64 {
@_transparent
public init(_ value: CGFloat) {
self = Int64(value.native)
}
}
extension UInt {
@_transparent
public init(_ value: CGFloat) {
self = UInt(value.native)
}
}
extension Int {
@_transparent
public init(_ value: CGFloat) {
self = Int(value.native)
}
}
extension Double {
@_transparent
public init(_ value: CGFloat) {
self = Double(value.native)
}
}
extension Float {
@_transparent
public init(_ value: CGFloat) {
self = Float(value.native)
}
}
//===----------------------------------------------------------------------===//
// Standard Operator Table
//===----------------------------------------------------------------------===//
// TODO: These should not be necessary, since they're already provided by
// <T: FloatingPoint>, but in practice they are currently needed to
// disambiguate overloads. We should find a way to remove them, either by
// tweaking the overload resolution rules, or by removing the other
// definitions in the standard lib, or both.
extension CGFloat {
@_transparent
public static func +(lhs: CGFloat, rhs: CGFloat) -> CGFloat {
var lhs = lhs
lhs += rhs
return lhs
}
@_transparent
public static func -(lhs: CGFloat, rhs: CGFloat) -> CGFloat {
var lhs = lhs
lhs -= rhs
return lhs
}
@_transparent
public static func *(lhs: CGFloat, rhs: CGFloat) -> CGFloat {
var lhs = lhs
lhs *= rhs
return lhs
}
@_transparent
public static func /(lhs: CGFloat, rhs: CGFloat) -> CGFloat {
var lhs = lhs
lhs /= rhs
return lhs
}
}
//===----------------------------------------------------------------------===//
// Strideable Conformance
//===----------------------------------------------------------------------===//
extension CGFloat : Strideable {
/// Returns a stride `x` such that `self.advanced(by: x)` approximates
/// `other`.
///
/// - Complexity: O(1).
@_transparent
public func distance(to other: CGFloat) -> CGFloat {
return CGFloat(other.native - self.native)
}
/// Returns a `Self` `x` such that `self.distance(to: x)` approximates
/// `n`.
///
/// - Complexity: O(1).
@_transparent
public func advanced(by amount: CGFloat) -> CGFloat {
return CGFloat(self.native + amount.native)
}
}
//===----------------------------------------------------------------------===//
// Deprecated operators
//===----------------------------------------------------------------------===//
@available(*, unavailable, message: "Use truncatingRemainder instead")
public func %(lhs: CGFloat, rhs: CGFloat) -> CGFloat {
fatalError("% is not available.")
}
@available(*, unavailable, message: "Use formTruncatingRemainder instead")
public func %=(lhs: inout CGFloat, rhs: CGFloat) {
fatalError("%= is not available.")
}
//===----------------------------------------------------------------------===//
// tgmath
//===----------------------------------------------------------------------===//
@_transparent
public func acos(_ x: CGFloat) -> CGFloat {
return CGFloat(acos(x.native))
}
@_transparent
public func cos(_ x: CGFloat) -> CGFloat {
return CGFloat(cos(x.native))
}
@_transparent
public func sin(_ x: CGFloat) -> CGFloat {
return CGFloat(sin(x.native))
}
@_transparent
public func asin(_ x: CGFloat) -> CGFloat {
return CGFloat(asin(x.native))
}
@_transparent
public func atan(_ x: CGFloat) -> CGFloat {
return CGFloat(atan(x.native))
}
@_transparent
public func tan(_ x: CGFloat) -> CGFloat {
return CGFloat(tan(x.native))
}
@_transparent
public func acosh(_ x: CGFloat) -> CGFloat {
return CGFloat(acosh(x.native))
}
@_transparent
public func asinh(_ x: CGFloat) -> CGFloat {
return CGFloat(asinh(x.native))
}
@_transparent
public func atanh(_ x: CGFloat) -> CGFloat {
return CGFloat(atanh(x.native))
}
@_transparent
public func cosh(_ x: CGFloat) -> CGFloat {
return CGFloat(cosh(x.native))
}
@_transparent
public func sinh(_ x: CGFloat) -> CGFloat {
return CGFloat(sinh(x.native))
}
@_transparent
public func tanh(_ x: CGFloat) -> CGFloat {
return CGFloat(tanh(x.native))
}
@_transparent
public func exp(_ x: CGFloat) -> CGFloat {
return CGFloat(exp(x.native))
}
@_transparent
public func exp2(_ x: CGFloat) -> CGFloat {
return CGFloat(exp2(x.native))
}
@_transparent
public func expm1(_ x: CGFloat) -> CGFloat {
return CGFloat(expm1(x.native))
}
@_transparent
public func log(_ x: CGFloat) -> CGFloat {
return CGFloat(log(x.native))
}
@_transparent
public func log10(_ x: CGFloat) -> CGFloat {
return CGFloat(log10(x.native))
}
@_transparent
public func log2(_ x: CGFloat) -> CGFloat {
return CGFloat(log2(x.native))
}
@_transparent
public func log1p(_ x: CGFloat) -> CGFloat {
return CGFloat(log1p(x.native))
}
@_transparent
public func logb(_ x: CGFloat) -> CGFloat {
return CGFloat(logb(x.native))
}
@_transparent
public func cbrt(_ x: CGFloat) -> CGFloat {
return CGFloat(cbrt(x.native))
}
@_transparent
public func erf(_ x: CGFloat) -> CGFloat {
return CGFloat(erf(x.native))
}
@_transparent
public func erfc(_ x: CGFloat) -> CGFloat {
return CGFloat(erfc(x.native))
}
@_transparent
public func tgamma(_ x: CGFloat) -> CGFloat {
return CGFloat(tgamma(x.native))
}
@_transparent
public func nearbyint(_ x: CGFloat) -> CGFloat {
return CGFloat(nearbyint(x.native))
}
@_transparent
public func rint(_ x: CGFloat) -> CGFloat {
return CGFloat(rint(x.native))
}
@_transparent
public func atan2(_ lhs: CGFloat, _ rhs: CGFloat) -> CGFloat {
return CGFloat(atan2(lhs.native, rhs.native))
}
@_transparent
public func hypot(_ lhs: CGFloat, _ rhs: CGFloat) -> CGFloat {
return CGFloat(hypot(lhs.native, rhs.native))
}
@_transparent
public func pow(_ lhs: CGFloat, _ rhs: CGFloat) -> CGFloat {
return CGFloat(pow(lhs.native, rhs.native))
}
@_transparent
public func copysign(_ lhs: CGFloat, _ rhs: CGFloat) -> CGFloat {
return CGFloat(copysign(lhs.native, rhs.native))
}
@_transparent
public func nextafter(_ lhs: CGFloat, _ rhs: CGFloat) -> CGFloat {
return CGFloat(nextafter(lhs.native, rhs.native))
}
@_transparent
public func fdim(_ lhs: CGFloat, _ rhs: CGFloat) -> CGFloat {
return CGFloat(fdim(lhs.native, rhs.native))
}
@_transparent
public func fmax(_ lhs: CGFloat, _ rhs: CGFloat) -> CGFloat {
return CGFloat(fmax(lhs.native, rhs.native))
}
@_transparent
public func fmin(_ lhs: CGFloat, _ rhs: CGFloat) -> CGFloat {
return CGFloat(fmin(lhs.native, rhs.native))
}
@_transparent
@available(*, unavailable, message: "use the floatingPointClass property.")
public func fpclassify(_ x: CGFloat) -> Int {
fatalError("unavailable")
}
@available(*, unavailable, message: "use the isNormal property.")
public func isnormal(_ value: CGFloat) -> Bool { return value.isNormal }
@available(*, unavailable, message: "use the isFinite property.")
public func isfinite(_ value: CGFloat) -> Bool { return value.isFinite }
@available(*, unavailable, message: "use the isInfinite property.")
public func isinf(_ value: CGFloat) -> Bool { return value.isInfinite }
@available(*, unavailable, message: "use the isNaN property.")
public func isnan(_ value: CGFloat) -> Bool { return value.isNaN }
@available(*, unavailable, message: "use the sign property.")
public func signbit(_ value: CGFloat) -> Int { return value.sign.rawValue }
@_transparent
public func modf(_ x: CGFloat) -> (CGFloat, CGFloat) {
let (ipart, fpart) = modf(x.native)
return (CGFloat(ipart), CGFloat(fpart))
}
@_transparent
public func ldexp(_ x: CGFloat, _ n: Int) -> CGFloat {
return CGFloat(scalbn(x.native, n))
}
@_transparent
public func frexp(_ x: CGFloat) -> (CGFloat, Int) {
let (frac, exp) = frexp(x.native)
return (CGFloat(frac), exp)
}
@_transparent
public func ilogb(_ x: CGFloat) -> Int {
return x.native.exponent
}
@_transparent
public func scalbn(_ x: CGFloat, _ n: Int) -> CGFloat {
return CGFloat(scalbn(x.native, n))
}
#if !os(Windows)
@_transparent
public func lgamma(_ x: CGFloat) -> (CGFloat, Int) {
let (value, sign) = lgamma(x.native)
return (CGFloat(value), sign)
}
#endif
@_transparent
public func remquo(_ x: CGFloat, _ y: CGFloat) -> (CGFloat, Int) {
let (rem, quo) = remquo(x.native, y.native)
return (CGFloat(rem), quo)
}
@_transparent
public func nan(_ tag: String) -> CGFloat {
return CGFloat(nan(tag) as CGFloat.NativeType)
}
@_transparent
public func j0(_ x: CGFloat) -> CGFloat {
return CGFloat(j0(Double(x.native)))
}
@_transparent
public func j1(_ x: CGFloat) -> CGFloat {
return CGFloat(j1(Double(x.native)))
}
@_transparent
public func jn(_ n: Int, _ x: CGFloat) -> CGFloat {
return CGFloat(jn(n, Double(x.native)))
}
@_transparent
public func y0(_ x: CGFloat) -> CGFloat {
return CGFloat(y0(Double(x.native)))
}
@_transparent
public func y1(_ x: CGFloat) -> CGFloat {
return CGFloat(y1(Double(x.native)))
}
@_transparent
public func yn(_ n: Int, _ x: CGFloat) -> CGFloat {
return CGFloat(yn(n, Double(x.native)))
}
extension CGFloat : _CVarArgPassedAsDouble, _CVarArgAligned {
/// Transform `self` into a series of machine words that can be
/// appropriately interpreted by C varargs
@_transparent
public var _cVarArgEncoding: [Int] {
return native._cVarArgEncoding
}
/// Return the required alignment in bytes of
/// the value returned by `_cVarArgEncoding`.
@_transparent
public var _cVarArgAlignment: Int {
return native._cVarArgAlignment
}
}
extension CGFloat : Codable {
@_transparent
public init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
do {
self.native = try container.decode(NativeType.self)
} catch DecodingError.typeMismatch(let type, let context) {
// We may have encoded as a different type on a different platform. A
// strict fixed-format decoder may disallow a conversion, so let's try the
// other type.
do {
if NativeType.self == Float.self {
self.native = NativeType(try container.decode(Double.self))
} else {
self.native = NativeType(try container.decode(Float.self))
}
} catch {
// Failed to decode as the other type, too. This is neither a Float nor
// a Double. Throw the old error; we don't want to clobber the original
// info.
throw DecodingError.typeMismatch(type, context)
}
}
}
@_transparent
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
try container.encode(self.native)
}
}
| apache-2.0 | 810df435112bd06ca1a6de28040b4098 | 25.703399 | 100 | 0.626827 | 4.40445 | false | false | false | false |
lioonline/Swift | NSURLSessionDownloadDelegate/NSURLSessionDownloadDelegate/ViewController.swift | 1 | 2529 | //
// ViewController.swift
// NSURLSessionDownloadDelegate
//
// Created by Carlos Butron on 02/12/14.
// Copyright (c) 2014 Carlos Butron.
//
// This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public
// License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later
// version.
// This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied
// warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
// You should have received a copy of the GNU General Public License along with this program. If not, see
// http:/www.gnu.org/licenses/.
//
import UIKit
class ViewController: UIViewController, NSURLSessionDownloadDelegate {
var session = NSURLSession()
@IBOutlet weak var imagen: UIImageView!
@IBOutlet weak var progreso: UIProgressView!
@IBAction func cargar(sender: UIButton) {
var imageUrl: NSString = "http://carlosbutron.es/wp-content/uploads/2014/11/logo-carlosbutrondev.jpg"
var getImageTask: NSURLSessionDownloadTask =
session.downloadTaskWithURL(NSURL(string: imageUrl)!)
getImageTask.resume()
}
override func viewDidLoad() {
super.viewDidLoad()
var sessionConfig =
NSURLSessionConfiguration.defaultSessionConfiguration()
session = NSURLSession(configuration: sessionConfig, delegate: self, delegateQueue: nil)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didFinishDownloadingToURL location: NSURL){
println("Download finished")
var downloadedImage = UIImage(data: NSData(contentsOfURL: location)!)
dispatch_async(dispatch_get_main_queue(), {() in
self.imagen.image = downloadedImage
})
}
func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didWriteData bytesWritten: Int64,totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64){
dispatch_async(dispatch_get_main_queue(), {() in
var variable = Float(totalBytesWritten)/Float(totalBytesExpectedToWrite)
self.progreso.progress = variable
}) }
}
| gpl-3.0 | 82536da8d5f2119d586e043fc314a35f | 37.318182 | 176 | 0.702649 | 5.088531 | false | true | false | false |
philipbannon/iOS | ProductWishlist/ProductWishlist/AppDelegate.swift | 1 | 6128 | //
// AppDelegate.swift
// ProductWishlist
//
// Created by Philip Bannon on 07/01/2016.
// Copyright © 2016 Philip Bannon. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Core Data stack
lazy var applicationDocumentsDirectory: NSURL = {
// The directory the application uses to store the Core Data store file. This code uses a directory named "com.DogHouseSoftware.ProductWishlist" in the application's documents Application Support directory.
let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
return urls[urls.count-1]
}()
lazy var managedObjectModel: NSManagedObjectModel = {
// The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
let modelURL = NSBundle.mainBundle().URLForResource("ProductWishlist", withExtension: "momd")!
return NSManagedObjectModel(contentsOfURL: modelURL)!
}()
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = {
// The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail.
// Create the coordinator and store
let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("SingleViewCoreData.sqlite")
var failureReason = "There was an error creating or loading the application's saved data."
do {
try coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil)
} catch {
// Report any error we got.
var dict = [String: AnyObject]()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
dict[NSLocalizedFailureReasonErrorKey] = failureReason
dict[NSUnderlyingErrorKey] = error as NSError
let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
// Replace this with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)")
abort()
}
return coordinator
}()
lazy var managedObjectContext: NSManagedObjectContext = {
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
let coordinator = self.persistentStoreCoordinator
var managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType)
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
// MARK: - Core Data Saving support
func saveContext () {
if managedObjectContext.hasChanges {
do {
try managedObjectContext.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
NSLog("Unresolved error \(nserror), \(nserror.userInfo)")
abort()
}
}
}
}
| gpl-2.0 | cfff81c368272ffd6a80da9d7ba8e111 | 54.198198 | 291 | 0.721071 | 5.914093 | false | false | false | false |
inban/WeatherControl | WeatherControl/WeatherManager.swift | 1 | 3228 | //
// WeatherManager.swift
// Weather
//
// Created by Jeevanantham Kalyanasundram on 3/10/17.
// Copyright © 2017 Jeevanantham Kalyanasundram. All rights reserved.
//
import Foundation
// The delegate method didGetWeather is called if the weather data was received.
// The delegate method didNotGetWeather method is called if weather data was not received.
// The delegate method didReceivedImageData is called when weather icon image data received.
public protocol WeatherManagerDelegate: class {
func didGetWeather(weather: WeatherDetails)
func didNotGetWeather(error: NSError)
func didReceivedImageData(data: Data)
}
// MARK: WeatherManager
public class WeatherManager {
public weak var delegate: WeatherManagerDelegate?
// MARK: -
public init(delegate: WeatherManagerDelegate) {
self.delegate = delegate
}
public func getWeatherInfo(weatherInfoRequestURL: String) {
// This is the shared session will do.
let session = URLSession.shared
//Converting string to URL
let url = URL(string: weatherInfoRequestURL)!
let task = session.dataTask(with: url, completionHandler: { (data, response, error) in
if let networkError = error {
// An error occurred while trying to get data from the server.
self.delegate?.didNotGetWeather(error: networkError as NSError)
}
else {
print("Success")
// We got data from the server!
do {
let weatherData = try JSONSerialization.jsonObject(
with: data!,
options: .mutableContainers) as! [String: AnyObject]
// Initializing dictionary to Weather struct.
let weather = WeatherDetails(weatherData: weatherData)
// Pass Weather struct to view controller to display the weather info.
self.delegate?.didGetWeather(weather: weather)
}
catch let jsonError as NSError {
self.delegate?.didNotGetWeather(error: jsonError)
}
}
})
task.resume()
}
public func getWeatherImage(iconImageRequestUrl: String) {
// This is the shared session will do.
let session = URLSession.shared
//Converting string to URL
let requestURLForIconImage = URL(string: iconImageRequestUrl)
let task = session.dataTask(with: requestURLForIconImage!, completionHandler: { (data, response, error) in
if let networkError = error {
// An error occurred while trying to get data from the server.
self.delegate?.didNotGetWeather(error: networkError as NSError)
}
else {
print("Success")
// We got image data from the server!
self.delegate?.didReceivedImageData(data:data!)
}
})
task.resume()
}
}
| mit | fb30c55a09fbc280ad8a445107749ab7 | 31.928571 | 114 | 0.578866 | 5.478778 | false | false | false | false |
breadwallet/breadwallet-core | Swift/BRCryptoDemo/TransferCreateRecvController.swift | 1 | 3160 | //
// TransferCreateRecvController.swift
// BRCryptoDemo
//
// Created by Ed Gamble on 8/6/19.
// Copyright © 2019 Breadwinner AG. All rights reserved.
//
// See the LICENSE file at the project root for license information.
// See the CONTRIBUTORS file at the project root for a list of contributors.
//
import UIKit
class TransferCreateRecvController: TransferCreateController {
let qrCodeSize = CGSize(width: 186.0, height: 186.0)
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
updateView()
}
func updateView () {
let target = wallet.target
walletAddrButton.setTitle (target.description, for: .normal)
// Generate a QR Code
if let scheme = wallet.manager.network.scheme {
let uri = "\(scheme):\(target.description)"
qrCodeImage.isHidden = false
qrCodeImage.image = UIImage
.qrCode(data: uri.data(using: .utf8)!)!
.resize(qrCodeSize)
}
else {
qrCodeImage.isHidden = true
}
}
@IBAction func done(_ sender: UIBarButtonItem) {
self.dismiss(animated: true) {}
}
@IBAction func toPasteBoard(_ sender: UIButton) {
UIPasteboard.general.string = sender.titleLabel?.text
}
@IBOutlet var walletAddrButton: UIButton!
@IBOutlet var qrCodeImage: UIImageView!
}
// https://github.com/breadwallet/breadwallet-ios
extension UIImage {
static func qrCode(data: Data,
color: CIColor = .black,
backgroundColor: CIColor = .white) -> UIImage? {
guard let qrFilter = CIFilter(name: "CIQRCodeGenerator"),
let colorFilter = CIFilter(name: "CIFalseColor") else { return nil }
qrFilter.setDefaults()
qrFilter.setValue(data, forKey: "inputMessage")
qrFilter.setValue("L", forKey: "inputCorrectionLevel")
colorFilter.setDefaults()
colorFilter.setValue(qrFilter.outputImage, forKey: "inputImage")
colorFilter.setValue(color, forKey: "inputColor0")
colorFilter.setValue(backgroundColor, forKey: "inputColor1")
guard let outputImage = colorFilter.outputImage else { return nil }
guard let cgImage = CIContext().createCGImage(outputImage, from: outputImage.extent) else { return nil }
return UIImage(cgImage: cgImage)
}
func resize(_ size: CGSize, inset: CGFloat = 6.0) -> UIImage? {
UIGraphicsBeginImageContext(size)
defer { UIGraphicsEndImageContext() }
guard let context = UIGraphicsGetCurrentContext() else { assert(false, "Could not create image context"); return nil }
guard let cgImage = self.cgImage else { assert(false, "No cgImage property"); return nil }
context.interpolationQuality = .none
context.rotate(by: .pi) // flip
context.scaleBy(x: -1.0, y: 1.0) // mirror
context.draw(cgImage, in: context.boundingBoxOfClipPath.insetBy(dx: inset, dy: inset))
return UIGraphicsGetImageFromCurrentImageContext()
}
}
| mit | 44fb02660100c1300f8e4de22cc6598b | 33.336957 | 126 | 0.64894 | 4.693908 | false | false | false | false |
rgravina/tddtris | TddTetris/Components/Game/DefaultTimeKeeper.swift | 1 | 443 | import Foundation
class DefaultTimeKeeper: TimeKeeper {
fileprivate let tickLength = CFTimeInterval(0.6)
fileprivate var lastTickAt: CFTimeInterval!
func update(_ now: CFTimeInterval) -> Bool {
if (lastTickAt == nil) {
lastTickAt = now
return false
}
if (lastTickAt + tickLength <= now) {
lastTickAt = now
return true
}
return false
}
}
| mit | c0ec5033dd2ef8f04696e26041475272 | 23.611111 | 52 | 0.575621 | 4.815217 | false | false | false | false |
LoveZYForever/HXWeiboPhotoPicker | Pods/HXPHPicker/Sources/HXPHPicker/Core/Extension/Core+UIImage.swift | 1 | 11240 | //
// Core+UIImage.swift
// HXPHPickerExample
//
// Created by Silence on 2020/11/15.
// Copyright © 2020 Silence. All rights reserved.
//
import UIKit
import ImageIO
import CoreGraphics
import MobileCoreServices
#if canImport(Kingfisher)
import Kingfisher
#endif
extension UIImage {
var width: CGFloat {
size.width
}
var height: CGFloat {
size.height
}
class func image(for named: String?) -> UIImage? {
if named == nil {
return nil
}
let bundle = PhotoManager.shared.bundle
var image: UIImage?
if bundle != nil {
var path = bundle?.path(forResource: "images", ofType: nil)
if path != nil {
path! += "/" + named!
image = self.init(named: path!)
}
}
if image == nil {
image = self.init(named: named!)
}
return image
}
func scaleSuitableSize() -> UIImage? {
var imageSize = self.size
while imageSize.width * imageSize.height > 3 * 1000 * 1000 {
imageSize.width *= 0.5
imageSize.height *= 0.5
}
return self.scaleToFillSize(size: imageSize)
}
func scaleToFillSize(size: CGSize, equalRatio: Bool = false, scale: CGFloat = 0) -> UIImage? {
if __CGSizeEqualToSize(self.size, size) {
return self
}
let scale = scale == 0 ? self.scale : scale
let rect: CGRect
if size.width / size.height != width / height && equalRatio {
let scale = size.width / width
var scaleHeight = scale * height
var scaleWidth = size.width
if scaleHeight < size.height {
scaleWidth = size.height / scaleHeight * size.width
scaleHeight = size.height
}
rect = CGRect(
x: -(scaleWidth - size.height) * 0.5,
y: -(scaleHeight - size.height) * 0.5,
width: scaleWidth,
height: scaleHeight
)
}else {
rect = CGRect(origin: .zero, size: size)
}
UIGraphicsBeginImageContextWithOptions(size, false, scale)
self.draw(in: rect)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
func scaleImage(toScale: CGFloat) -> UIImage? {
if toScale == 1 {
return self
}
UIGraphicsBeginImageContextWithOptions(
CGSize(width: width * toScale, height: height * toScale),
false,
self.scale
)
self.draw(in: CGRect(x: 0, y: 0, width: width * toScale, height: height * toScale))
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
class func image(for color: UIColor?, havingSize: CGSize, radius: CGFloat = 0) -> UIImage? {
if let color = color {
let rect: CGRect
if havingSize.equalTo(CGSize.zero) {
rect = CGRect(x: 0, y: 0, width: 1, height: 1)
}else {
rect = CGRect(x: 0, y: 0, width: havingSize.width, height: havingSize.height)
}
UIGraphicsBeginImageContextWithOptions(rect.size, false, UIScreen.main.scale)
let context = UIGraphicsGetCurrentContext()
context?.setFillColor(color.cgColor)
let path = UIBezierPath(roundedRect: rect, cornerRadius: radius).cgPath
context?.addPath(path)
context?.fillPath()
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
return nil
}
func normalizedImage() -> UIImage? {
if imageOrientation == .up {
return self
}
return repaintImage()
}
func repaintImage() -> UIImage? {
UIGraphicsBeginImageContextWithOptions(size, false, scale)
draw(in: CGRect(x: 0, y: 0, width: size.width, height: size.height))
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
func roundCropping() -> UIImage? {
UIGraphicsBeginImageContext(size)
let path = UIBezierPath(ovalIn: CGRect(x: 0, y: 0, width: size.width, height: size.height))
path.addClip()
draw(at: .zero)
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage
}
func cropImage(toRect cropRect: CGRect, viewWidth: CGFloat, viewHeight: CGFloat) -> UIImage? {
if cropRect.isEmpty {
return self
}
let imageViewScale = max(size.width / viewWidth,
size.height / viewHeight)
// Scale cropRect to handle images larger than shown-on-screen size
let cropZone = CGRect(
x: cropRect.origin.x * imageViewScale,
y: cropRect.origin.y * imageViewScale,
width: cropRect.size.width * imageViewScale,
height: cropRect.size.height * imageViewScale
)
// Perform cropping in Core Graphics
guard let cutImageRef: CGImage = cgImage?.cropping(to: cropZone)
else {
return nil
}
// Return image to UIImage
let croppedImage: UIImage = UIImage(cgImage: cutImageRef)
return croppedImage
}
func rotation(to orientation: UIImage.Orientation) -> UIImage? {
if let cgImage = cgImage {
func swapWidthAndHeight(_ toRect: CGRect) -> CGRect {
var rect = toRect
let swap = rect.width
rect.size.width = rect.height
rect.size.height = swap
return rect
}
var rect = CGRect(x: 0, y: 0, width: cgImage.width, height: cgImage.height)
while rect.width * rect.height > 3 * 1000 * 1000 {
rect.size.width = rect.width * 0.5
rect.size.height = rect.height * 0.5
}
var trans: CGAffineTransform
var bnds = rect
switch orientation {
case .up:
return self
case .upMirrored:
trans = .init(translationX: rect.width, y: 0)
trans = trans.scaledBy(x: -1, y: 1)
case .down:
trans = .init(translationX: rect.width, y: rect.height)
trans = trans.rotated(by: CGFloat.pi)
case .downMirrored:
trans = .init(translationX: 0, y: rect.height)
trans = trans.scaledBy(x: 1, y: -1)
case .left:
bnds = swapWidthAndHeight(bnds)
trans = .init(translationX: 0, y: rect.width)
trans = trans.rotated(by: 3 * CGFloat.pi * 0.5)
case .leftMirrored:
bnds = swapWidthAndHeight(bnds)
trans = .init(translationX: rect.height, y: rect.width)
trans = trans.scaledBy(x: -1, y: 1)
trans = trans.rotated(by: 3 * CGFloat.pi * 0.5)
case .right:
bnds = swapWidthAndHeight(bnds)
trans = .init(translationX: rect.height, y: 0)
trans = trans.rotated(by: CGFloat.pi * 0.5)
case .rightMirrored:
bnds = swapWidthAndHeight(bnds)
trans = .init(scaleX: -1, y: 1)
trans = trans.rotated(by: CGFloat.pi * 0.5)
default:
return self
}
UIGraphicsBeginImageContext(bnds.size)
let context = UIGraphicsGetCurrentContext()
switch orientation {
case .left, .leftMirrored, .right, .rightMirrored:
context?.scaleBy(x: -1, y: 1)
context?.translateBy(x: -rect.height, y: 0)
default:
context?.scaleBy(x: 1, y: -1)
context?.translateBy(x: 0, y: -rect.height)
}
context?.concatenate(trans)
context?.draw(cgImage, in: rect)
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage
}
return nil
}
func rotation(angle: Int, isHorizontal: Bool) -> UIImage? {
switch angle {
case 0, 360, -360:
if isHorizontal {
return rotation(to: .upMirrored)
}
case 90, -270:
if !isHorizontal {
return rotation(to: .right)
}else {
return rotation(to: .rightMirrored)
}
case 180, -180:
if !isHorizontal {
return rotation(to: .down)
}else {
return rotation(to: .downMirrored)
}
case 270, -90:
if !isHorizontal {
return rotation(to: .left)
}else {
return rotation(to: .leftMirrored)
}
default:
break
}
return self
}
func merge(_ image: UIImage, origin: CGPoint, scale: CGFloat = UIScreen.main.scale) -> UIImage? {
UIGraphicsBeginImageContextWithOptions(size, false, scale)
draw(in: CGRect(origin: .zero, size: size))
image.draw(in: CGRect(origin: origin, size: size))
let mergeImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return mergeImage
}
func merge(images: [UIImage], scale: CGFloat = UIScreen.main.scale) -> UIImage? {
if images.isEmpty {
return self
}
UIGraphicsBeginImageContextWithOptions(size, false, scale)
draw(in: CGRect(origin: .zero, size: size))
for image in images {
image.draw(in: CGRect(origin: .zero, size: size))
}
let mergeImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return mergeImage
}
class func merge(images: [UIImage], scale: CGFloat = UIScreen.main.scale) -> UIImage? {
if images.isEmpty {
return nil
}
if images.count == 1 {
return images.first
}
UIGraphicsBeginImageContextWithOptions(images.first!.size, false, scale)
for image in images {
image.draw(in: CGRect(origin: .zero, size: image.size))
}
let mergeImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return mergeImage
}
class func gradualShadowImage(_ havingSize: CGSize) -> UIImage? {
let layer = PhotoTools.getGradientShadowLayer(true)
layer.frame = CGRect(origin: .zero, size: havingSize)
UIGraphicsBeginImageContextWithOptions(havingSize, false, UIScreen.main.scale)
guard let context = UIGraphicsGetCurrentContext() else {
return nil
}
layer.render(in: context)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
}
| mit | 8a1f30de8d0a75fbd273b886c10f937b | 35.372168 | 101 | 0.554943 | 4.914298 | false | false | false | false |
SwiftFMI/iOS_2017_2018 | Upr/28.10.17/SecondTaskComplexSolution/SecondTaskComplexSolution/Model/SongManager.swift | 1 | 772 | //
// SongManager.swift
// SecondTaskComplexSolution
//
// Created by Petko Haydushki on 3.11.17.
// Copyright © 2017 Petko Haydushki. All rights reserved.
//
import UIKit
class SongManager: NSObject {
let data : NSMutableArray = []
override init()
{
super.init()
let first = Song.init(name: "Shape of you", artist: "Ed Sheran", artwork: "shape")
let second = Song.init(name: "Panda", artist: "Desiigner", artwork: "panda")
let third = Song.init(name: "Mask off", artist: "Future", artwork: "mask")
let fourth = Song.init(name: "Mind", artist: "Skrillex", artwork: "mind")
data.add(first);
data.add(second);
data.add(third);
data.add(fourth);
}
}
| apache-2.0 | 7d679e4f3eb792dc28dd9282edf54b83 | 23.870968 | 90 | 0.584955 | 3.552995 | false | false | false | false |
MyHZ/DouYuZB | DYZB/DYZB/Classes/Tools/Common.swift | 1 | 335 | //
// Common.swift
// DYZB
//
// Created by DM on 2016/11/16.
// Copyright © 2016年 DM. All rights reserved.
//
import Foundation
import UIKit
let kStatusBarh : CGFloat = 20
let kNavgationBarH : CGFloat = 44
let kTabBarH : CGFloat = 44
let KScreenW = UIScreen .main.bounds.width
let kScreenH = UIScreen .main.bounds.height
| mit | c0d30c178cf1bad2d503d32318749a6c | 15.6 | 46 | 0.704819 | 3.387755 | false | false | false | false |
AthanasiusOfAlex/PiEstimator | PiEstimator/ViewController.swift | 1 | 4549 | //
// ViewController.swift
// PiEstimator
//
// Created by Louis Melahn on 4/19/17.
// Copyright © 2017 Louis Melahn
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//
import Cocoa
extension ViewController: PiEstimatorDelegate {
func simulationHasBegun() {
piEstimatorLock = .locked
}
func progressBarWasUpticked(percentDone: Double) {
self.progressBar.doubleValue = percentDone * 100
}
func numberOfPairsWasUpdated(coprimes: Int, composites: Int) {
self.coprimePairs.integerValue = coprimes
self.compositePairs.integerValue = composites
}
func ratioWasUpdated(ratio: Double) {
self.ratioCoprimesToTotal.doubleValue = ratio
}
func estimateOfPiWasMade(π: Double) {
self.estimateOfPi.doubleValue = π
}
func killSwitchWasTurnedOn() {
killSwitch = .dontKill
}
func simulationHasTerminated() {
piEstimatorLock = .unlocked
}
}
class ViewController: NSViewController {
@IBOutlet weak var dieCastUpperBound: NSTextField!
@IBOutlet weak var numberOfInterations: NSTextField!
@IBOutlet weak var progressBar: NSProgressIndicator!
@IBOutlet weak var estimateOfPi: NSTextField!
@IBOutlet weak var ratioCoprimesToTotal: NSTextField!
@IBOutlet weak var compositePairs: NSTextField!
@IBOutlet weak var coprimePairs: NSTextField!
@IBOutlet weak var calculating: NSTextField!
@IBAction func upperBoundDidUpdate(_ sender: Any) {
}
@IBAction func iterationsDidUpdate(_ sender: Any) {
}
@IBAction func runSimulation(_ sender: NSButton) {
//self.progressBar.doubleValue = 0.0
updatePiEstimator()
killSwitch = .dontKill
piEstimator.run()
}
@IBAction func stopSimulation(_ sender: NSButton) {
killSwitch = .kill
}
@IBAction func quit(_ sender: NSButton) {
NSApplication.shared().terminate(self)
}
private var piEstimator = PiEstimator()
public var killSwitch = PiEstimator.KillSwitch.dontKill
public var piEstimatorLock = PiEstimator.Lock.unlocked
func updatePiEstimator() {
let upperBoundString = self.dieCastUpperBound.stringValue
let iterationsString = self.numberOfInterations.stringValue
let formatter = NumberFormatter()
formatter.numberStyle = .decimal
let upperBound = Int(formatter.number(from: upperBoundString) ?? 1)
let iterations = Int(formatter.number(from: iterationsString) ?? 1)
piEstimator.dieCastUpperBound = upperBound
piEstimator.iterations = iterations
readValuesFromPiEstimator()
}
func readValuesFromPiEstimator() {
self.dieCastUpperBound.integerValue = piEstimator.dieCastUpperBound
self.numberOfInterations.integerValue = piEstimator.iterations
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
piEstimator.delegate = self
readValuesFromPiEstimator()
self.progressBar.doubleValue = 0.0
}
override var representedObject: Any? {
didSet {
// Update the view, if already loaded.
}
}
}
| mit | 1fca29a3a36c4797921d505be8995569 | 27.061728 | 80 | 0.655961 | 5.012128 | false | false | false | false |
xin-wo/kankan | kankan/kankan/Class/Hot/Controller/HotViewController.swift | 1 | 2857 | //
// HotViewController.swift
// kankan
//
// Created by Xin on 16/10/19.
// Copyright © 2016年 王鑫. All rights reserved.
//
import UIKit
class HotViewController: UIViewController, WXNavigationProtocol,PageTitleViewDelegate, PageContentViewDelegate {
//索引栏视图
lazy var titleView: PageTitleView = {
let titleView = PageTitleView(frame: CGRect(x: 0, y: 64, width: screenWidth, height: 40), titiles: ["奇葩", "萌物", "美女", "精品"])
return titleView
}()
lazy var contentPageView: PageContentView = {
// 确定所有子视图控制器
var childVcs: [UIViewController] = []
let vc1 = SelectedViewController()
vc1.statusBarHidenClosure = { (bool) in
UIApplication.sharedApplication().setStatusBarHidden(bool, withAnimation: .None)
}
let vc2 = BeautyViewController()
vc2.statusBarHidenClosure = { (bool) in
UIApplication.sharedApplication().setStatusBarHidden(bool, withAnimation: .None)
}
let vc3 = JokeViewController()
vc3.statusBarHidenClosure = { (bool) in
UIApplication.sharedApplication().setStatusBarHidden(bool, withAnimation: .None)
}
let vc4 = VideoViewController()
vc4.statusBarHidenClosure = { (bool) in
UIApplication.sharedApplication().setStatusBarHidden(bool, withAnimation: .None)
}
childVcs.append(vc1)
childVcs.append(vc2)
childVcs.append(vc3)
childVcs.append(vc4)
let contentView = PageContentView(frame: CGRect(x: 0, y: 104, width: UIScreen.mainScreen().bounds.width, height: screenHeight-148), childVcS: childVcs, parentVc: self)
return contentView
}()
var currentBtn: UIButton!
var childVcs: [UIViewController] = []
var isStatusBarHiden = true
override func viewDidLoad() {
super.viewDidLoad()
configNavigationBar()
}
func configNavigationBar() {
self.automaticallyAdjustsScrollViewInsets = false
view.backgroundColor = UIColor.whiteColor()
addTitle("热点")
addBottomImage()
titleView.delegate = self
self.view.addSubview(titleView)
contentPageView.delegate = self
self.view.addSubview(contentPageView)
}
}
//MARK: 实现索引栏协议方法
extension HotViewController {
func pageContentView(contentView: PageContentView, progress: CGFloat, sourceIndex: Int, targetIndex: Int) {
titleView.setContentWith(progress, sourceIndex: sourceIndex, targetIndex: targetIndex)
}
func pageTitleView(titleView: PageTitleView, selectedIndex: Int) {
contentPageView.setCurrentIndex(selectedIndex)
}
}
| mit | 2a839ef0aace84373f258cdee61dae2e | 27.659794 | 175 | 0.638489 | 4.894366 | false | false | false | false |
lkzhao/MCollectionView | Carthage/Checkouts/YetAnotherAnimationLibrary/Sources/Solvers/SpringSolver.swift | 1 | 2595 | // The MIT License (MIT)
//
// Copyright (c) 2016 Luke Zhao <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
public struct SpringSolver<Value: VectorConvertible>: RK4Solver {
public typealias Vector = Value.Vector
public let stiffness: Double
public let damping: Double
public let threshold: Double
public let current: AnimationProperty<Value>
public let velocity: AnimationProperty<Value>
public let target: AnimationProperty<Value>
public init(stiffness: Double,
damping: Double,
threshold: Double,
current: AnimationProperty<Value>,
velocity: AnimationProperty<Value>,
target: AnimationProperty<Value>) {
self.stiffness = stiffness
self.damping = damping
self.threshold = threshold
self.current = current
self.velocity = velocity
self.target = target
}
public func acceleration(current: Vector, velocity: Vector) -> Vector {
return stiffness * (target.vector - current) - damping * velocity
}
public func updateWith(newCurrent: Vector, newVelocity: Vector) -> Bool {
if newCurrent.distance(between: target.vector) < threshold,
newVelocity.distance(between: .zero) < threshold {
current.vector = target.vector
velocity.vector = .zero
return true
} else {
current.vector = newCurrent
velocity.vector = newVelocity
return false
}
}
}
| mit | ba6d30a2268cf88e446f7a5926845bb5 | 39.546875 | 80 | 0.686705 | 4.87782 | false | false | false | false |
cp3hnu/SwiftExtension | Extension/UIKit/UILabel.swift | 1 | 1563 | //
// UILabel.swift
// hnup
//
// Created by CP3 on 16/5/10.
// Copyright © 2016年 DataYP. All rights reserved.
//
import UIKit
// MARK: - 级联
public extension UILabel {
/// 设置字体,参数是字体(UIFont)
public func font(font: UIFont) -> Self {
self.font = font
return self
}
/// 设置字体,参数是字体大小
public func fontSize(size: CGFloat) -> Self {
self.font = UIFont.systemFontOfSize(size)
return self
}
/// 设置文字颜色
public func textColor(color: UIColor) -> Self {
self.textColor = color
return self
}
/// 设置行数
public func numberOfLines(number: Int) -> Self {
self.numberOfLines = number
return self
}
/// 设置text
public func text(text: String?) -> Self {
self.text = text
return self
}
/// 设置attributedText
public func attributedText(attributedText: NSAttributedString?) -> Self {
self.attributedText = attributedText
return self
}
/// 文字左对齐
public func alignLeft() -> Self {
return self.align()
}
/// 文字居中
public func alignMiddle() -> Self {
return self.align(.Center)
}
/// 文字右对齐
public func alignRight() -> Self {
return self.align(.Right)
}
}
private extension UILabel {
func align(alignment: NSTextAlignment = .Left) -> Self {
self.textAlignment = alignment
return self
}
}
| mit | 0024a7d2a81d4f6bd982672e1d19c8da | 19.222222 | 77 | 0.56456 | 4.232558 | false | false | false | false |
thomaskamps/SlideFeedback | SlideFeedback/Pods/Socket.IO-Client-Swift/Source/SocketParsable.swift | 5 | 6188 | //
// SocketParsable.swift
// Socket.IO-Client-Swift
//
// 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
protocol SocketParsable {
func parseBinaryData(_ data: Data)
func parseSocketMessage(_ message: String)
}
extension SocketParsable where Self: SocketIOClientSpec {
private func isCorrectNamespace(_ nsp: String) -> Bool {
return nsp == self.nsp
}
private func handleConnect(_ packetNamespace: String) {
if packetNamespace == "/" && nsp != "/" {
joinNamespace(nsp)
} else {
didConnect()
}
}
private func handlePacket(_ pack: SocketPacket) {
switch pack.type {
case .event where isCorrectNamespace(pack.nsp):
handleEvent(pack.event, data: pack.args, isInternalMessage: false, withAck: pack.id)
case .ack where isCorrectNamespace(pack.nsp):
handleAck(pack.id, data: pack.data)
case .binaryEvent where isCorrectNamespace(pack.nsp):
waitingPackets.append(pack)
case .binaryAck where isCorrectNamespace(pack.nsp):
waitingPackets.append(pack)
case .connect:
handleConnect(pack.nsp)
case .disconnect:
didDisconnect(reason: "Got Disconnect")
case .error:
handleEvent("error", data: pack.data, isInternalMessage: true, withAck: pack.id)
default:
DefaultSocketLogger.Logger.log("Got invalid packet: %@", type: "SocketParser", args: pack.description)
}
}
/// Parses a messsage from the engine. Returning either a string error or a complete SocketPacket
func parseString(_ message: String) -> Either<String, SocketPacket> {
var reader = SocketStringReader(message: message)
guard let type = Int(reader.read(count: 1)).flatMap({ SocketPacket.PacketType(rawValue: $0) }) else {
return .left("Invalid packet type")
}
if !reader.hasNext {
return .right(SocketPacket(type: type, nsp: "/"))
}
var namespace = "/"
var placeholders = -1
if type == .binaryEvent || type == .binaryAck {
if let holders = Int(reader.readUntilOccurence(of: "-")) {
placeholders = holders
} else {
return .left("Invalid packet")
}
}
if reader.currentCharacter == "/" {
namespace = reader.readUntilOccurence(of: ",")
}
if !reader.hasNext {
return .right(SocketPacket(type: type, nsp: namespace, placeholders: placeholders))
}
var idString = ""
if type == .error {
reader.advance(by: -1)
} else {
while reader.hasNext {
if let int = Int(reader.read(count: 1)) {
idString += String(int)
} else {
reader.advance(by: -2)
break
}
}
}
var dataArray = String(message.utf16[message.utf16.index(reader.currentIndex, offsetBy: 1)..<message.utf16.endIndex])!
if type == .error && !dataArray.hasPrefix("[") && !dataArray.hasSuffix("]") {
dataArray = "[" + dataArray + "]"
}
switch parseData(dataArray) {
case let .left(err):
return .left(err)
case let .right(data):
return .right(SocketPacket(type: type, data: data, id: Int(idString) ?? -1,
nsp: namespace, placeholders: placeholders))
}
}
// Parses data for events
private func parseData(_ data: String) -> Either<String, [Any]> {
do {
return .right(try data.toArray())
} catch {
return .left("Error parsing data for packet")
}
}
// Parses messages recieved
func parseSocketMessage(_ message: String) {
guard !message.isEmpty else { return }
DefaultSocketLogger.Logger.log("Parsing %@", type: "SocketParser", args: message)
switch parseString(message) {
case let .left(err):
DefaultSocketLogger.Logger.error("\(err): %@", type: "SocketParser", args: message)
case let .right(pack):
DefaultSocketLogger.Logger.log("Decoded packet as: %@", type: "SocketParser", args: pack.description)
handlePacket(pack)
}
}
func parseBinaryData(_ data: Data) {
guard !waitingPackets.isEmpty else {
DefaultSocketLogger.Logger.error("Got data when not remaking packet", type: "SocketParser")
return
}
// Should execute event?
guard waitingPackets[waitingPackets.count - 1].addData(data) else { return }
let packet = waitingPackets.removeLast()
if packet.type != .binaryAck {
handleEvent(packet.event, data: packet.args, isInternalMessage: false, withAck: packet.id)
} else {
handleAck(packet.id, data: packet.args)
}
}
}
| unlicense | d2393600beeba99b69b0694b1266777b | 36.277108 | 126 | 0.59373 | 4.78577 | false | false | false | false |
EyreFree/EFQRCode | Source/NSColor+.swift | 2 | 1757 | //
// NSColor+.swift
// EFQRCode
//
// Created by EyreFree on 2019/11/21.
//
// Copyright © 2019 EyreFree. 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.
#if !canImport(UIKit)
import AppKit
extension NSColor {
func ciColor() -> CIColor {
return cgColor.ciColor()
}
func cgColor() -> CGColor {
return self.cgColor
}
static func white(white: CGFloat = 1.0, alpha: CGFloat = 1.0) -> NSColor {
return self.init(white: white, alpha: alpha)
}
static func black(black: CGFloat = 1.0, alpha: CGFloat = 1.0) -> NSColor {
let white: CGFloat = 1.0 - black
return Self.white(white: white, alpha: alpha)
}
}
#endif
| mit | 0ece68ea2a3130ad00f23e985bb42d96 | 34.836735 | 81 | 0.697039 | 4.083721 | false | false | false | false |
wujianguo/esmerization | esmerization/RoomListViewController.swift | 1 | 6263 | //
// RoomListViewController.swift
// esmerization
//
// Created by 吴建国 on 16/2/18.
// Copyright © 2016年 wujianguo. All rights reserved.
//
import UIKit
import SnapKit
import Kingfisher
extension UIColor {
class func themeColor() -> UIColor { return UIColor.whiteColor().colorWithAlphaComponent(0.5) }
/**
* Initializes and returns a color object for the given RGB hex integer.
*/
public convenience init(rgb: Int) {
self.init(
red: CGFloat((rgb & 0xFF0000) >> 16) / 255.0,
green: CGFloat((rgb & 0x00FF00) >> 8) / 255.0,
blue: CGFloat((rgb & 0x0000FF) >> 0) / 255.0,
alpha: 1)
}
public convenience init(colorString: String) {
var colorInt: UInt32 = 0
NSScanner(string: colorString).scanHexInt(&colorInt)
self.init(rgb: (Int) (colorInt ?? 0xaaaaaa))
}
}
class RoomCollectionCell: UICollectionViewCell {
override func awakeFromNib() {
super.awakeFromNib()
smallImage.layer.cornerRadius = smallImage.frame.width / 2
smallImage.layer.masksToBounds = true
smallImage.layer.borderWidth = 2
smallImage.layer.borderColor = UIColor.redColor().CGColor
}
@IBOutlet weak var smallImage: UIImageView!
@IBOutlet weak var bigImage: UIImageView!
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var cityLabel: UILabel!
@IBOutlet weak var onlineUsersLabel: UILabel!
var room: Room! {
didSet {
updateUI()
}
}
var task: RetrieveImageTask?
func updateUI() {
nameLabel.text = room.anchor?.nick
cityLabel.text = room.city
onlineUsersLabel.text = "\(room.onlineUsers)在看"
let url = NSURL(string:room.anchor!.portrait!)
guard url != nil else { return }
if task?.downloadTask?.URL != url {
smallImage.kf_cancelDownloadTask()
}
smallImage.image = nil
task = bigImage.kf_setImageWithURL(url!, placeholderImage: nil, optionsInfo: nil) { (image, error, cacheType, imageURL) -> () in
self.smallImage.image = image
}
}
}
class RoomListViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {
override func viewDidLoad() {
super.viewDidLoad()
collectionView.delegate = self
collectionView.dataSource = self
refreshControl.addTarget(self, action: "refresh", forControlEvents: .ValueChanged)
collectionView.addSubview(refreshControl)
collectionView?.backgroundColor = UIColor.clearColor()
refresh()
}
var refreshControl = UIRefreshControl()
var rooms = [Room]()
func refresh() {
requestRoomList { (rms) -> Void in
self.refreshControl.endRefreshing()
self.rooms = rms
// self.rooms.appendContentsOf(rms)
self.collectionView.reloadData()
}
}
@IBOutlet weak var collectionView: UICollectionView!
override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransitionToSize(size, withTransitionCoordinator: coordinator)
let flowLayout = collectionView?.collectionViewLayout
flowLayout?.invalidateLayout()
}
func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return rooms.count
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("RoomListCellIdentifier", forIndexPath: indexPath) as! RoomCollectionCell
cell.room = rooms[indexPath.row]
return cell
}
struct CellRatio {
static let x = CGFloat(320)
static let y = CGFloat(390)
}
let mininumInteritemSpacing = CGFloat(8)
var collectionViewEdgeInset = UIEdgeInsetsMake(8, 0, 8, 0)
func calculateCellNum(size: CGSize) -> Int {
let width = size.width - collectionViewEdgeInset.left - collectionViewEdgeInset.right + mininumInteritemSpacing
let num = width / (CellRatio.x + mininumInteritemSpacing)
let actXNum = num - CGFloat(Int(num)) >= 0.7 ? Int(num) + 1 : Int(num)
return actXNum > 0 ? actXNum : 1
}
var collectionCellWidth: CGFloat {
let bounds = collectionView!.bounds
let width = bounds.width - collectionViewEdgeInset.left - collectionViewEdgeInset.right + mininumInteritemSpacing
let n = calculateCellNum(bounds.size)
return width/CGFloat(n) - mininumInteritemSpacing
}
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
let width = collectionCellWidth
return CGSizeMake(width, width*CellRatio.y/CellRatio.x)
}
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAtIndex section: Int) -> CGFloat {
return mininumInteritemSpacing
}
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAtIndex section: Int) -> UIEdgeInsets {
return collectionViewEdgeInset
}
// 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?) {
if let dvc = segue.destinationViewController as? RoomViewController {
if let cell = sender as? RoomCollectionCell {
if let indexPath = collectionView.indexPathForCell(cell) {
dvc.room = rooms[indexPath.row]
}
}
}
}
}
| mit | f9b11b1ef780213fbb07399be8252f1e | 34.310734 | 178 | 0.66176 | 5.32368 | false | false | false | false |
ResearchSuite/ResearchSuiteExtensions-iOS | Example/Pods/ResearchSuiteTaskBuilder/ResearchSuiteTaskBuilder/Classes/Element Providers/Generators/RSTBElementSelectorGenerator.swift | 1 | 2935 | //
// RTSBElementSelectorGenerator.swift
// Pods
//
// Created by James Kizer on 1/9/17.
//
//
import Gloss
open class RSTBElementSelectorGenerator: RSTBBaseElementGenerator {
public init(){}
let _supportedTypes = [
"elementSelector"
]
public var supportedTypes: [String]! {
return self._supportedTypes
}
open func generateElements(type: String, jsonObject: JSON, helper: RSTBTaskBuilderHelper) -> [JSON]? {
guard let descriptor = RSTBElementSelectorDescriptor(json: jsonObject),
descriptor.elementList.count > 0 else {
return nil
}
let elements: [JSON] = descriptor.elementList
switch (descriptor.selectorType) {
case "random":
return [elements.random()!]
case "selectOneByDate":
//note that this algo was checked via playground and seems to provide
//"good enough" distribution
//note that nested selectors should use different UUIDStorageKeys
//same UUIDStorageKeys should provide the same hash value on same day
//thus allowing us to vary based on date alone
let userPortionString: String = {
guard let uuidStorageKey: String = "UUIDStorageKey" <~~ jsonObject,
let stateHelper = helper.stateHelper else {
return ""
}
if let uuid = stateHelper.valueInState(forKey: uuidStorageKey) as? String {
return uuid
}
else {
let uuid: String = UUID().uuidString
stateHelper.setValueInState(value: uuid as NSSecureCoding!, forKey: uuidStorageKey)
return uuid
}
} ()
let date: Date = {
guard let dayOffset: Int = "dayOffset" <~~ jsonObject else {
return Date()
}
return Date(timeIntervalSinceNow: TimeInterval(dayOffset) + 24.0 * 60.6 * 60.0)
} ()
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale.current
dateFormatter.dateStyle = DateFormatter.Style.medium
let datePortionString = dateFormatter.string(from: date)
print(datePortionString)
let hash: Int = userPortionString.hashValue ^ datePortionString.hashValue
let index: Int = abs(hash) % elements.count
if elements.indices.contains(index) {
return [elements[index]]
}
else {
return nil
}
default:
return elements
}
}
}
| apache-2.0 | 19c0e7efbdc3e7d1ad37c6a26bd931b4 | 31.252747 | 106 | 0.519932 | 5.811881 | false | false | false | false |
wordpress-mobile/WordPress-iOS | WordPress/Classes/ViewRelated/Site Creation/Shared/ErrorStates/InlineErrorRetryTableViewCell.swift | 2 | 4285 |
import UIKit
import Gridicons
import WordPressShared
// MARK: - InlineErrorRetryTableViewCellAccessoryView
/// The accessory view comprises a retry Gridicon & advisory text
///
private class InlineErrorRetryTableViewCellAccessoryView: UIStackView {
// MARK: Properties
/// A collection of parameters uses for view layout
private struct Metrics {
static let minimumHeight = CGFloat(28)
static let retryDimension = CGFloat(16)
static let padding = CGFloat(4)
}
/// One of the arranged subviews : a "refresh" Gridicon
private let retryImageView: UIImageView
/// One of the arranged subviews : user-facing text
private let retryLabel: UILabel
// MARK: InlineErrorRetryTableViewCellAccessoryView
init() {
self.retryImageView = {
let dismissImage = UIImage.gridicon(.refresh).imageWithTintColor(.primary)
let imageView = UIImageView(image: dismissImage)
imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.contentMode = .scaleAspectFit
return imageView
}()
self.retryLabel = {
let label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
label.font = WPStyleGuide.fontForTextStyle(.body, fontWeight: .bold)
label.textColor = .primary
label.textAlignment = .center
label.text = NSLocalizedString("Retry", comment: "Title for accessory view in the empty state table view cell in the Verticals step of Enhanced Site Creation")
label.sizeToFit()
return label
}()
super.init(frame: .zero)
initialize()
}
// MARK: UIView
required init(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: Private behavior
private func initialize() {
translatesAutoresizingMaskIntoConstraints = false
axis = .horizontal
alignment = .center
spacing = Metrics.padding
addArrangedSubviews([retryImageView, retryLabel])
NSLayoutConstraint.activate([
heightAnchor.constraint(greaterThanOrEqualToConstant: Metrics.minimumHeight),
retryImageView.widthAnchor.constraint(equalToConstant: Metrics.retryDimension),
retryImageView.heightAnchor.constraint(equalToConstant: Metrics.retryDimension),
])
}
}
// MARK: - InlineErrorRetryTableViewCell
/// Responsible for apprising the user of an error that occurred, accompanied by a visual affordance to retry the preceding action.
///
final class InlineErrorRetryTableViewCell: UITableViewCell, ReusableCell {
// MARK: Properties
/// A collection of parameters uses for view layout
private struct Metrics {
static let height = CGFloat(44)
static let trailingInset = CGFloat(16)
}
/// A subview akin to an accessory view
private let retryAccessoryView = InlineErrorRetryTableViewCellAccessoryView()
// MARK: UITableViewCell
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: .default, reuseIdentifier: InlineErrorRetryTableViewCell.cellReuseIdentifier())
initialize()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: Internal behavior
func setMessage(_ message: String) {
textLabel?.text = message
}
// MARK: Private behavior
private func initialize() {
if let label = textLabel {
WPStyleGuide.configureLabel(label, textStyle: .body)
label.textColor = .neutral(.shade40)
}
let borderColor = UIColor.divider
addTopBorder(withColor: borderColor)
addBottomBorder(withColor: borderColor)
accessoryType = .none
addSubview(retryAccessoryView)
NSLayoutConstraint.activate([
heightAnchor.constraint(equalToConstant: Metrics.height),
retryAccessoryView.centerYAnchor.constraint(equalTo: centerYAnchor),
retryAccessoryView.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -Metrics.trailingInset)
])
}
}
| gpl-2.0 | df79fcdde1a36a031e4b5c2d5cb1cb2b | 29.176056 | 171 | 0.672579 | 5.690571 | false | false | false | false |
Roommate-App/roomy | roomy/Pods/IBAnimatable/Sources/Enums/GradientStartPoint.swift | 3 | 1250 | //
// Created by Jake Lin on 12/2/15.
// Copyright © 2015 IBAnimatable. All rights reserved.
//
import UIKit
public enum GradientStartPoint: IBEnum {
case top
case topRight
case right
case bottomRight
case bottom
case bottomLeft
case left
case topLeft
case custom(start: CGPoint, end: CGPoint)
case none
}
extension GradientStartPoint {
public init(string: String?) {
guard let string = string else {
self = .none
return
}
let (name, params) = AnimationType.extractNameAndParams(from: string)
switch name {
case "top":
self = .top
case "topright":
self = .topRight
case "right":
self = .right
case "bottomright":
self = .bottomRight
case "bottom":
self = .bottom
case "bottomleft":
self = .bottomLeft
case "left":
self = .left
case "topleft":
self = .topLeft
case "custom":
self = .custom(start: CGPoint(x: params[safe: 0]?.toDouble() ?? 0,
y: params[safe: 1]?.toDouble() ?? 0),
end: CGPoint(x: params[safe: 2]?.toDouble() ?? 0,
y: params[safe: 3]?.toDouble() ?? 0))
default:
self = .none
}
}
}
| mit | 54b9ebcf32d9e9db753b6d89f2195779 | 21.303571 | 73 | 0.56205 | 4.042071 | false | false | false | false |
whiteshadow-gr/HatForIOS | HAT/Objects/Facebook/Posts/HATFacebookApplication.swift | 1 | 5607 | /**
* Copyright (C) 2018 HAT Data Exchange Ltd
*
* SPDX-License-Identifier: MPL2
*
* This file is part of the Hub of All Things project (HAT).
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/
*/
import SwiftyJSON
// MARK: Struct
/// A struct representing the application that this post came from
public struct HATFacebookApplication: HatApiType, Comparable, HATObject {
// MARK: - Coding Keys
/**
The JSON fields used by the hat
The Fields are the following:
* `applicationID` in JSON is `id`
* `namespace` in JSON is `namespace`
* `name` in JSON is `name`
* `category` in JSON is `category`
* `link` in JSON is `link`
*/
private enum CodingKeys: String, CodingKey {
case applicationID = "id"
case namespace = "namespace"
case name = "name"
case category = "category"
case link = "link"
}
// MARK: - Comparable protocol
/// Returns a Boolean value indicating whether two values are equal.
///
/// Equality is the inverse of inequality. For any values `a` and `b`,
/// `a == b` implies that `a != b` is `false`.
///
/// - Parameters:
/// - lhs: A value to compare.
/// - rhs: Another value to compare.
public static func == (lhs: HATFacebookApplication, rhs: HATFacebookApplication) -> Bool {
return (lhs.applicationID == rhs.applicationID && lhs.namespace == rhs.namespace && lhs.name == rhs.name && lhs.category == rhs.category && lhs.link == rhs.link)
}
/// Returns a Boolean value indicating whether the value of the first
/// argument is less than that of the second argument.
///
/// This function is the only requirement of the `Comparable` protocol. The
/// remainder of the relational operator functions are implemented by the
/// standard library for any type that conforms to `Comparable`.
///
/// - Parameters:
/// - lhs: A value to compare.
/// - rhs: Another value to compare.
public static func < (lhs: HATFacebookApplication, rhs: HATFacebookApplication) -> Bool {
return lhs.name < rhs.name
}
// MARK: - Variables
/// The id of the application
public var applicationID: String = ""
/// The namespace of the application
public var namespace: String = ""
/// The name of the application
public var name: String = ""
/// The category of the application
public var category: String = ""
/// The url of the application
public var link: String = ""
// MARK: - Initialisers
/**
The default initialiser. Initialises everything to default values.
*/
public init() {
applicationID = ""
namespace = ""
name = ""
category = ""
link = ""
}
/**
It initialises everything from the received JSON file from HAT
- dictionary: The JSON file received
*/
public init(from dictionary: Dictionary<String, JSON>) {
self.init()
if let tempID: String = dictionary[CodingKeys.applicationID.rawValue]?.stringValue {
applicationID = tempID
}
if let tempNameSpace: String = dictionary[CodingKeys.namespace.rawValue]?.stringValue {
namespace = tempNameSpace
}
if let tempName: String = dictionary[CodingKeys.name.rawValue]?.string {
name = tempName
}
if let tempCategory: String = dictionary[CodingKeys.category.rawValue]?.stringValue {
category = tempCategory
}
if let tempLink: String = dictionary[CodingKeys.link.rawValue]?.stringValue {
link = tempLink
}
}
/**
It initialises everything from the received JSON file from HAT
- dict: The JSON file received
*/
public mutating func inititialize(dict: Dictionary<String, JSON>) {
if let tempID: String = dict[CodingKeys.applicationID.rawValue]?.stringValue {
applicationID = tempID
}
if let tempNameSpace: String = dict[CodingKeys.namespace.rawValue]?.stringValue {
namespace = tempNameSpace
}
if let tempName: String = dict[CodingKeys.name.rawValue]?.string {
name = tempName
}
if let tempCategory: String = dict[CodingKeys.category.rawValue]?.stringValue {
category = tempCategory
}
if let tempLink: String = dict[CodingKeys.link.rawValue]?.stringValue {
link = tempLink
}
}
/**
It initialises everything from the received JSON file from the cache
- fromCache: The Dictionary file returned from cache
*/
public mutating func initialize(fromCache: Dictionary<String, Any>) {
let dictionary: JSON = JSON(fromCache)
self.inititialize(dict: dictionary.dictionaryValue)
}
// MARK: - JSON Mapper
/**
Returns the object as Dictionary, JSON
- returns: Dictionary<String, String>
*/
public func toJSON() -> Dictionary<String, Any> {
return [
CodingKeys.name.rawValue: self.name,
CodingKeys.applicationID.rawValue: self.applicationID,
CodingKeys.category.rawValue: self.category,
CodingKeys.link.rawValue: self.link
]
}
}
| mpl-2.0 | c277b335a5f4554398741f56b50f2982 | 29.145161 | 169 | 0.604245 | 4.796407 | false | false | false | false |
narner/AudioKit | AudioKit/macOS/AudioKit/User Interface/AKSlider.swift | 1 | 13907 | //
// AKSlider.swift
// AudioKit for macOS
//
// Created by Aurelius Prochazka on 7/26/16.
// Copyright © 2017 Aurelius Prochazka. All rights reserved.
//
public enum AKSliderStyle {
case roundIndicator
case tabIndicator
// Factor for calculating the corner radius of the slider based on the width of the slider indicator
var cornerRadiusFactor: CGFloat {
switch self {
case .roundIndicator: return 2.0
case .tabIndicator: return 4.0
}
}
}
@IBDesignable public class AKSlider: AKPropertyControl {
// Width for the tab indicator
static var tabIndicatorWidth: CGFloat = 20.0
// Padding surrounding the text inside the value bubble
static var bubblePadding: CGSize = CGSize(width: 10.0, height: 2.0)
// Margin between the top of the tap and the value bubble
static var bubbleMargin: CGFloat = 10.0
// Corner radius for the value bubble
static var bubbleCornerRadius: CGFloat = 2.0
/// Background color
@IBInspectable public var bgColor: NSColor?
/// Slider border color
@IBInspectable public var sliderBorderColor: NSColor?
/// Indicator border color
@IBInspectable public var indicatorBorderColor: NSColor?
/// Slider overlay color
@IBInspectable public var color: NSColor = AKStylist.sharedInstance.nextColor
/// Text color
@IBInspectable public var textColor: NSColor?
/// Bubble font size
@IBInspectable public var bubbleFontSize: CGFloat = 12
// Slider style
open var sliderStyle: AKSliderStyle = .tabIndicator
// Border width
@IBInspectable public var sliderBorderWidth: CGFloat = 3.0
// Show value bubble
@IBInspectable public var showsValueBubble: Bool = false
// Value bubble border width
@IBInspectable public var valueBubbleBorderWidth: CGFloat = 1.0
// Calculated height of the slider based on text size and view bounds
private var sliderHeight: CGFloat = 0.0
public init(property: String,
value: Double = 0.0,
range: ClosedRange<Double> = 0 ... 1,
taper: Double = 1,
format: String = "%0.3f",
color: AKColor = AKStylist.sharedInstance.nextColor,
frame: CGRect = CGRect(x: 0, y: 0, width: 440, height: 60),
callback: @escaping (_ x: Double) -> Void = { _ in }) {
self.color = color
super.init(property: property,
value: value,
range: range,
taper: taper,
format: format,
frame: frame,
callback: callback)
}
/// Initialization within Interface Builder
required public init?(coder: NSCoder) {
super.init(coder: coder)
self.wantsLayer = true
}
override public func mouseDragged(with theEvent: NSEvent) {
let loc = convert(theEvent.locationInWindow, from: nil)
let sliderMargin = (indicatorWidth + sliderBorderWidth) / 2.0
val = (0 ... 1).clamp(Double( (loc.x - sliderMargin) / (bounds.width - sliderMargin * 2.0) ))
value = val.denormalized(to: range, taper: taper)
callback(value)
}
private var indicatorWidth: CGFloat {
switch sliderStyle {
case .roundIndicator: return sliderHeight
case .tabIndicator: return AKSlider.tabIndicatorWidth
}
}
var bgColorForTheme: AKColor {
if let bgColor = bgColor { return bgColor }
switch AKStylist.sharedInstance.theme {
case .basic: return AKColor(white: 0.3, alpha: 1.0)
case .midnight: return AKColor(white: 0.7, alpha: 1.0)
}
}
var indicatorBorderColorForTheme: AKColor {
if let indicatorBorderColor = indicatorBorderColor { return indicatorBorderColor }
switch AKStylist.sharedInstance.theme {
case .basic: return AKColor(white: 0.3, alpha: 1.0)
case .midnight: return AKColor.white
}
}
var sliderBorderColorForTheme: AKColor {
if let sliderBorderColor = sliderBorderColor { return sliderBorderColor }
switch AKStylist.sharedInstance.theme {
case .basic: return AKColor(white: 0.2, alpha: 1.0)
case .midnight: return AKColor(white: 0.9, alpha: 1.0)
}
}
var textColorForTheme: AKColor {
if let textColor = textColor { return textColor }
switch AKStylist.sharedInstance.theme {
case .basic: return AKColor(white: 0.3, alpha: 1.0)
case .midnight: return AKColor.white
}
}
/// Draw the slider
override public func draw(_ rect: NSRect) {
drawFlatSlider(currentValue: CGFloat(val),
propertyName: property,
currentValueText: String(format: format, value)
)
}
func drawFlatSlider(currentValue: CGFloat = 0,
initialValue: CGFloat = 0,
propertyName: String = "Property Name",
currentValueText: String = "0.0") {
//// General Declarations
let context = unsafeBitCast(NSGraphicsContext.current?.graphicsPort, to: CGContext.self)
let width = self.frame.width
let height = self.frame.height
// Calculate name label height
let themeTextColor = textColorForTheme
let nameLabelRect = CGRect(x: 0, y: 0, width: width, height: height)
let nameLabelStyle = NSMutableParagraphStyle()
nameLabelStyle.alignment = .left
let nameLabelFontAttributes = [NSAttributedStringKey.font: NSFont.boldSystemFont(ofSize: fontSize),
NSAttributedStringKey.foregroundColor: themeTextColor,
NSAttributedStringKey.paragraphStyle: nameLabelStyle]
let nameLabelTextHeight: CGFloat = NSString(string: propertyName).boundingRect(
with: CGSize(width: width, height: CGFloat.infinity),
options: NSString.DrawingOptions.usesLineFragmentOrigin,
attributes: nameLabelFontAttributes).size.height
context.saveGState()
// Calculate slider height and other values based on expected label height
let sliderTextMargin: CGFloat = 5.0
let labelOrigin = nameLabelTextHeight + sliderTextMargin
let sliderOrigin = sliderBorderWidth
sliderHeight = height - labelOrigin - sliderTextMargin
let indicatorSize = CGSize(width: indicatorWidth, height: sliderHeight)
let sliderCornerRadius = indicatorSize.width / sliderStyle.cornerRadiusFactor
// Draw name label
let nameLabelInset: CGRect = nameLabelRect.insetBy(dx: sliderCornerRadius, dy: sliderOrigin * 2.0)
context.clip(to: nameLabelInset)
NSString(string: propertyName).draw(
in: CGRect(x: nameLabelInset.minX,
y: nameLabelInset.minY + sliderHeight,
width: nameLabelInset.width,
height: nameLabelTextHeight),
withAttributes: nameLabelFontAttributes)
context.restoreGState()
//// Variable Declarations
let sliderMargin = (indicatorWidth + sliderBorderWidth) / 2.0
let currentWidth: CGFloat = currentValue < 0 ? sliderMargin :
(currentValue < 1 ?
currentValue * (width - (sliderMargin * 2.0)) + sliderMargin :
width - sliderMargin)
//// sliderArea Drawing
let sliderAreaRect = NSRect(x: sliderBorderWidth / 2.0,
y: sliderOrigin,
width: width - sliderBorderWidth,
height: sliderHeight)
let sliderAreaPath = NSBezierPath(roundedRect: sliderAreaRect,
xRadius: sliderCornerRadius,
yRadius: sliderCornerRadius)
bgColorForTheme.setFill()
sliderAreaPath.fill()
sliderAreaPath.lineWidth = sliderBorderWidth
//// valueRectangle Drawing
let valueWidth = currentWidth // < indicatorSize.width ? indicatorSize.width : currentWidth
let valueAreaRect = NSRect(x: sliderBorderWidth / 2.0,
y: sliderOrigin + sliderBorderWidth / 2.0,
width: valueWidth + indicatorSize.width / 2.0,
height: sliderHeight - sliderBorderWidth)
let valueAreaPath = NSBezierPath(roundedRect: valueAreaRect,
xRadius: sliderCornerRadius,
yRadius: sliderCornerRadius)
color.withAlphaComponent(0.6).setFill()
valueAreaPath.fill()
// sliderArea Border
sliderBorderColorForTheme.setStroke()
sliderAreaPath.stroke()
// Indicator view drawing
let indicatorRect = NSRect(x: currentWidth - indicatorSize.width / 2.0,
y: sliderOrigin,
width: indicatorSize.width,
height: indicatorSize.height)
let indicatorPath = NSBezierPath(roundedRect: indicatorRect,
xRadius: sliderCornerRadius,
yRadius: sliderCornerRadius)
color.setFill()
indicatorPath.fill()
indicatorPath.lineWidth = sliderBorderWidth
indicatorBorderColorForTheme.setStroke()
indicatorPath.stroke()
//// valueLabel Drawing
if showsValueBubble && isDragging {
let valueLabelRect = NSRect(x: 0, y: 0, width: width, height: height)
let valueLabelStyle = NSMutableParagraphStyle()
valueLabelStyle.alignment = .center
let valueLabelFontAttributes = [NSAttributedStringKey.font: NSFont.boldSystemFont(ofSize: bubbleFontSize),
NSAttributedStringKey.foregroundColor: themeTextColor,
NSAttributedStringKey.paragraphStyle: valueLabelStyle]
let valueLabelInset: NSRect = valueLabelRect.insetBy(dx: 0, dy: 0)
let valueLabelTextSize = NSString(string: currentValueText).boundingRect(
with: CGSize(width: valueLabelInset.width, height: CGFloat.infinity),
options: NSString.DrawingOptions.usesLineFragmentOrigin,
attributes: valueLabelFontAttributes).size
let bubbleSize = CGSize(width: valueLabelTextSize.width + AKSlider.bubblePadding.width,
height: valueLabelTextSize.height + AKSlider.bubblePadding.height)
var bubbleOriginX = (currentWidth - bubbleSize.width / 2.0 - valueBubbleBorderWidth)
if bubbleOriginX < 0.0 {
bubbleOriginX = valueBubbleBorderWidth
} else if (bubbleOriginX + bubbleSize.width) > bounds.width {
bubbleOriginX = bounds.width - bubbleSize.width - valueBubbleBorderWidth
}
let bubbleRect = NSRect(x: bubbleOriginX,
y: sliderHeight + valueLabelTextSize.height - AKSlider.bubbleMargin + sliderOrigin,
width: bubbleSize.width,
height: bubbleSize.height)
let bubblePath = NSBezierPath(roundedRect: bubbleRect, xRadius: AKSlider.bubbleCornerRadius,
yRadius: AKSlider.bubbleCornerRadius)
color.setFill()
bubblePath.fill()
bubblePath.lineWidth = valueBubbleBorderWidth
indicatorBorderColorForTheme.setStroke()
bubblePath.stroke()
context.saveGState()
context.clip(to: valueLabelInset)
NSString(string: currentValueText).draw(
in: CGRect(x: bubbleOriginX + ((bubbleSize.width - valueLabelTextSize.width) / 2.0),
y: sliderHeight + valueLabelTextSize.height - AKSlider.bubbleMargin +
AKSlider.bubblePadding.height / 2.0 + sliderOrigin,
width: valueLabelTextSize.width,
height: valueLabelTextSize.height),
withAttributes: valueLabelFontAttributes)
context.restoreGState()
} else if showsValueBubble == false {
let valueLabelRect = CGRect(x: 0, y: 0, width: width, height: height)
let valueLabelStyle = NSMutableParagraphStyle()
valueLabelStyle.alignment = .right
let valueLabelFontAttributes = [NSAttributedStringKey.font: NSFont.boldSystemFont(ofSize: fontSize),
NSAttributedStringKey.foregroundColor: themeTextColor,
NSAttributedStringKey.paragraphStyle: valueLabelStyle]
let valueLabelInset: CGRect = valueLabelRect.insetBy(dx: sliderCornerRadius, dy: sliderOrigin * 2.0)
let valueLabelTextHeight: CGFloat = NSString(string: currentValueText).boundingRect(
with: CGSize(width: valueLabelInset.width, height: CGFloat.infinity),
options: NSString.DrawingOptions.usesLineFragmentOrigin,
attributes: valueLabelFontAttributes).size.height
context.saveGState()
context.clip(to: valueLabelInset)
NSString(string: currentValueText).draw(
in: CGRect(x: valueLabelInset.minX,
y: valueLabelInset.minY + sliderHeight,
width: valueLabelInset.width,
height: valueLabelTextHeight),
withAttributes: valueLabelFontAttributes)
context.restoreGState()
}
}
}
| mit | 5552fd2b602712c9669fb4f683eb0931 | 41.656442 | 119 | 0.606788 | 5.784526 | false | false | false | false |
czechboy0/swift-package-crawler | Sources/AnalyzerLib/DependencyUtils.swift | 1 | 2569 | //
// DependencyUtils.swift
// swift-package-crawler
//
// Created by Honza Dvorsky on 5/19/16.
//
//
private func _prettyDependencyNames(package: Package) -> [String] {
let deps = package
.allDependencies
.filter { $0.url.lowercased().isRemoteGitURL() }
.map { $0.url.githubName() }
.map { $0.authorAliasResolved() }
return deps
}
func _directDependencies(packageIterator: PackageIterator) throws -> [String: [String]] {
var directDeps: [String: [String]] = [:]
var it = packageIterator
while let package = try it.next() {
directDeps[package.remoteName] = _prettyDependencyNames(package: package)
}
return directDeps
}
func _transitiveDependees(_ directDeps: [String: [String]]) -> [String: Set<String>] {
var transitiveDependees: [String: Set<String>] = [:]
let directDependees = _directDependees(directDependencies: directDeps)
var stack: Set<String> = [] //for cycle detection
func _calculateTransitiveDependees(name: String) -> Set<String> {
//check the cache first
if let deps = transitiveDependees[name] {
return deps
}
// print("+ \(name)?")
if stack.contains(name) {
//cycle detected
print("Cycle detected when re-adding \(name). Cycle between \(stack)")
return []
}
stack.insert(name)
//by definition, transitive dependees are
//all direct dependees + their transitive dependees
let direct = directDependees[name] ?? []
let transDepsOfDeps = direct
.map { _calculateTransitiveDependees(name: $0) }
.reduce(Set<String>(), combine: { $0.union($1) })
let allDependees = direct.union(transDepsOfDeps)
transitiveDependees[name] = allDependees
stack.remove(name)
// print("- \(name) -> \(allDependees.count)")
return allDependees
}
//run
directDependees.keys.forEach { _calculateTransitiveDependees(name: $0) }
return transitiveDependees
}
func _directDependees(directDependencies: [String: [String]]) -> [String: Set<String>] {
var dependees: [String: Set<String>] = [:]
directDependencies.forEach { (name: String, dependencies: [String]) in
dependencies.forEach({ (dependency) in
var d = dependees[dependency.lowercased()] ?? []
d.insert(name.lowercased())
dependees[dependency.lowercased()] = d
})
}
return dependees
}
| mit | 301f8ca3cabc25bb33f7427fd04a4589 | 32.802632 | 89 | 0.605683 | 4.383959 | false | false | false | false |
feliperuzg/CleanExample | CleanExample/Core/Network/NetworkConfiguration/NetworkConstants.swift | 1 | 388 | //
// NetworkConstants.swift
// CleanExample
//
// Created by Felipe Ruz on 12-12-17.
// Copyright © 2017 Felipe Ruz. All rights reserved.
//
enum NetworkConstants {
static let networkConfigurationList = "NetworkConfiguration"
static let fileExtension = "plist"
static let baseURL = "BaseURL"
static let version = "Version"
static let endpointKey = "Endpoint"
}
| mit | e5739fa4e23dae45bdab4f8f99614876 | 24.8 | 64 | 0.702842 | 4.117021 | false | true | false | false |
feliperuzg/CleanExample | CleanExampleTests/Authentication/Data/Repository/AuthenticationRepositorySpec.swift | 1 | 1948 | //
// AuthenticationRepositorySpec.swift
// CleanExampleTests
//
// Created by Felipe Ruz on 19-07-17.
// Copyright © 2017 Felipe Ruz. All rights reserved.
//
import XCTest
@testable import CleanExample
class CodableMock: CodableHelper {
override func decodeNetworkObject<D>(object: Data) -> D? where D : Decodable {
return nil
}
override func decodeObjectFrom<E, D>(object: E) -> D? where E : Encodable, D : Decodable {
return nil
}
}
class AuthenticationRepositorySpec: XCTestCase {
let locator = AuthenticationServiceLocator()
func testAuthenticationRepositoryCanSuccsessfullyLoginUser() {
let sut = locator.repository
let exp = expectation(description: "testLoginRepositoryCanSuccsessfullyLoginUser")
let model = LoginModel(userName: "Juan", password: "1234")
sut.executeLogin(with: model) { (token, error) in
XCTAssertNotNil(token)
XCTAssertNil(error)
exp.fulfill()
}
waitForExpectations(timeout: 3, handler: nil)
}
func testAuthenticationRepositoryCanShowFailureLoginUser() {
let sut = locator.repository
let exp = expectation(description: "testLoginRepositoryCanShowFailureLoginUser")
let model = LoginModel(userName: "", password: "")
sut.executeLogin(with: model) { (token, error) in
XCTAssertNotNil(error)
XCTAssertNil(token)
exp.fulfill()
}
waitForExpectations(timeout: 3, handler: nil)
}
func testCanHandlerCorruptedModel() {
var sut = locator.repository
let model = LoginModel(userName: "", password: "")
sut.codableHelper = CodableMock()
sut.executeLogin(with: model) { (token, error) in
XCTAssertNil(token)
XCTAssertNotNil(error)
XCTAssertEqual(error?.localizedDescription, CustomError().localizedDescription)
}
}
}
| mit | 81d964fb04884c8416db92fb2535d13f | 31.45 | 94 | 0.655881 | 4.783784 | false | true | false | false |
kostiakoval/SpeedLog | Example/Example-iOS/AppDelegate.swift | 1 | 1363 | //
// AppDelegate.swift
// SpeedLogExample
//
// Created by Kostiantyn Koval on 12/07/15.
// Copyright (c) 2015 Kostiantyn Koval. All rights reserved.
//
import UIKit
import SpeedLog
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
myFunc()
colorLog()
return true
}
func myFunc() {
SpeedLog.print("Hello")
SpeedLog.mode = .AllOptions
SpeedLog.print("Enable All Features")
SpeedLog.mode = .FuncName
SpeedLog.print("Show only FunctionName")
SpeedLog.mode = [.FuncName, .FileName]
SpeedLog.print("Show FunctionName and File name")
SpeedLog.mode = [.FuncName, .FileName, .Line]
SpeedLog.print("Show 3 options :)")
SpeedLog.mode = .FullCodeLocation
SpeedLog.print("Show fullCode, same as above")
SpeedLog.mode = [.Date, .FuncName, .FileName, .Line]
SpeedLog.print("Show all 3 options :)")
}
func colorLog() {
SpeedLog.mode = .None
SpeedLog.print("\nNice UIColor :) \n")
let c = UIColor.red
print("Original:", c)
SpeedLog.enableVisualColorLog()
SpeedLog.print("Visual:", c)
SpeedLog.disableVisualColorLog()
SpeedLog.print("Original Restored:", c)
}
}
| mit | c643d17e900d90c9c8710ee60dfd9581 | 22.5 | 142 | 0.683786 | 4.193846 | false | false | false | false |
kzaher/RegX | RegX/Functional.swift | 1 | 2270 | //
// Functional.swift
// RegX
//
// Created by Krunoslav Zaher on 10/19/14.
// Copyright (c) 2014 Krunoslav Zaher. All rights reserved.
//
// this is because of accessing privately defined members
enum OptionalReflection {
case Failure(AnyObject?, String)
case Success(AnyObject!)
var hasValue : Bool {
get {
switch (self) {
case .Success(let object) : return object != nil;
default: return false;
}
}
}
var value : AnyObject {
get {
switch (self) {
case .Success(let result) : return result
default: fatalError("Doesn't have value")
}
}
}
var description : String {
get {
switch self {
case .Success(let object) : return "\(object)"
case .Failure(let object, let selectors) : return "\(object):\(selectors)"
}
}
}
}
precedencegroup VeryLowPrecedence {
associativity: left
lowerThan: AssignmentPrecedence
}
infix operator .. : VeryLowPrecedence
postfix operator !!
func .. (object: OptionalReflection, selector: String) -> OptionalReflection {
switch(object) {
case .Failure(_, _): return object;
case .Success(let object):
let result : AnyObject! = RegX_performSelector(object, selector) as AnyObject;
return result != nil
? OptionalReflection.Success(result)
: OptionalReflection.Failure(object, selector)
}
}
func .. (object: AnyObject!, selector: String) -> OptionalReflection {
if object == nil {
return .Failure(nil, selector)
}
let result : AnyObject! = RegX_performSelector(object, selector) as AnyObject;
if result == nil {
return .Failure(object!, selector)
}
return .Success(result)
}
func .. (object: OptionalReflection, selectors: [String]) -> OptionalReflection {
switch object {
case .Failure(_, _): return object
default: break
}
for selector in selectors {
let result = object .. selector
switch result {
case .Success(_):return result
default:break
}
}
return .Failure(object.value, "\(selectors)")
}
| mit | 295b63f957ae482bbcaeac5b465cb9fd | 24.222222 | 86 | 0.584141 | 4.690083 | false | false | false | false |
MikotoZero/MMCache | Source/Cache.swift | 1 | 4520 | //
// Cache.swift
// Cache
//
// Created by 丁帅 on 2017/5/18.
// Copyright © 2017年 丁帅. All rights reserved.
//
import Foundation
public class Cache {
// MARK: public properties
public static let `default` = Cache(withIdentifer: "MMDefaultCache", directoryName: "MMCache")
public init(withIdentifer identifer: String, directoryName name: String? = nil, memoryCapacity capacity: Int = 1000, memoryTrimLevel level: UInt32 = 2) {
documentDC = DiskCache(path: FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!.appendingPathComponent(name ?? identifer), identifer: identifer)
cacheDC = DiskCache(path: FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).first!.appendingPathComponent(name ?? identifer), identifer: identifer)
tempDC = DiskCache(path: FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!.appendingPathComponent(name ?? identifer), identifer: identifer)
memoryCache = MemoryCache(capacity: capacity, trimLevel: level)
}
// MARK: private properties
fileprivate let documentDC: DiskCache
fileprivate let cacheDC: DiskCache
fileprivate let tempDC: DiskCache
fileprivate let memoryCache: MemoryCache<Any>
}
// MARK: memory cache
extension Cache {
fileprivate func setToMemory<K>(_ value: K.Result, key: K) where K: KeyType {
memoryCache[key.key] = value
}
fileprivate func getFromMemory<K>(with key: K) -> K.Result? where K: KeyType {
if let memory = memoryCache[key.key] as? K.Result {
return memory
}
return nil
}
fileprivate func removeFromMemory<K>(with key: K) where K: KeyType {
memoryCache[key.key] = nil
}
}
// MARK: disk cache
extension Cache {
private func diskCache<K>(for key: K) -> DiskCache? where K: KeyType {
switch key.level {
case .document:
return documentDC
case .cache:
return cacheDC
case .temp:
return tempDC
case .none:
return nil
}
}
fileprivate func setToDisk<K>(_ value: K.Result, for key: K) where K: KeyType {
guard let dc = diskCache(for: key) else { return }
dc.set(value, for: key.key, expriedInterval: key.expriedInterval)
}
fileprivate func getFromDisk<K>(with key: K) -> K.Result? where K: KeyType, K.Result: Encodable {
guard let dc = diskCache(for: key) else { return nil }
return dc.getSwift(with: key.key)
}
fileprivate func getFromDisk<K>(with key: K) -> K.Result? where K: KeyType {
guard let dc = diskCache(for: key) else { return nil }
return dc.get(with: key.key)
}
fileprivate func removeFromDisk<K>(with key: K) where K: KeyType {
guard let dc = diskCache(for: key) else { return }
dc.remove(with: key.key)
}
}
// MARK: - Public
// MARK: set & get
extension Cache {
public func set<K>(_ value: K.Result?, for key: K) where K: KeyType {
if let value = value {
setToMemory(value, key: key)
setToDisk(value, for: key)
} else {
removeFromMemory(with: key)
removeFromDisk(with: key)
}
}
public func get<K>(with key: K) -> K.Result? where K: KeyType, K.Result: Encodable {
if let memory = getFromMemory(with: key) {
return memory
} else if let disk = getFromDisk(with: key) {
setToMemory(disk, key: key)
return disk
}
return nil
}
public func get<K>(with key: K) -> K.Result? where K: KeyType {
if let memory = getFromMemory(with: key) {
return memory
} else if let disk = getFromDisk(with: key) {
setToMemory(disk, key: key)
return disk
}
return nil
}
}
// MARK: subscript
extension Cache {
// TODO: Can not use generic type in subscript. This is coming in Swift 4
/*
subscript<K>(_ key: K) -> K.Result? where K: KeyType {
}
*/
}
// MARK: clean
extension Cache {
public func cleanMemory() {
memoryCache.clean()
}
public func cleanDiskDocument() {
documentDC.clean()
}
public func cleanDiskCache() {
cacheDC.clean()
}
public func cleanDiskTemplate() {
tempDC.clean()
}
public func cleanAll() {
memoryCache.clean()
documentDC.clean()
cacheDC.clean()
tempDC.clean()
}
}
| mit | 1cbf6dbcc364a76fed98b49aef110a5a | 29.06 | 179 | 0.614992 | 4.099091 | false | false | false | false |
Zglove/DouYu | DYTV/DYTV/Classes/Tools/Common.swift | 1 | 345 | //
// Common.swift
// DYTV
//
// Created by people on 2016/10/28.
// Copyright © 2016年 people2000. All rights reserved.
//
import UIKit
let kStatusBarH : CGFloat = 20
let kNavigationBarH : CGFloat = 44
let kTabBarH : CGFloat = 44
let kScreenW : CGFloat = UIScreen.main.bounds.width
let kScreenH : CGFloat = UIScreen.main.bounds.height
| mit | 20e8bd176ff7ce5c690c0772c0bde14b | 20.375 | 54 | 0.716374 | 3.5625 | false | false | false | false |
TheInfiniteKind/duckduckgo-iOS | DuckDuckGo/AppDelegate.swift | 1 | 3542 | //
// AppDelegate.swift
// DuckDuckGo
//
// Created by Mia Alexiou on 18/01/2017.
// Copyright © 2017 DuckDuckGo. All rights reserved.
//
import UIKit
import Core
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
private struct ShortcutKey {
static let search = "com.duckduckgo.mobile.ios.newsearch"
static let clipboard = "com.duckduckgo.mobile.ios.clipboard"
}
var window: UIWindow?
private lazy var groupData = GroupDataStore()
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
if let shortcutItem = launchOptions?[.shortcutItem] {
handleShortCutItem(shortcutItem as! UIApplicationShortcutItem)
}
return true
}
func applicationDidBecomeActive(_ application: UIApplication) {
startOnboardingFlowIfNotSeenBefore()
}
private func startOnboardingFlowIfNotSeenBefore() {
var settings = OnboardingSettings()
if !settings.hasSeenOnboarding {
startOnboardingFlow()
settings.hasSeenOnboarding = true
}
}
private func startOnboardingFlow() {
guard let root = mainViewController() else { return }
let onboardingController = OnboardingViewController.loadFromStoryboard()
onboardingController.modalTransitionStyle = .flipHorizontal
root.present(onboardingController, animated: false, completion: nil)
}
func application(_ application: UIApplication, performActionFor shortcutItem: UIApplicationShortcutItem, completionHandler: @escaping (Bool) -> Void) {
handleShortCutItem(shortcutItem)
}
private func handleShortCutItem(_ shortcutItem: UIApplicationShortcutItem) {
Logger.log(text: "Handling shortcut item: \(shortcutItem.type)")
if shortcutItem.type == ShortcutKey.search {
clearNavigationStack()
}
if shortcutItem.type == ShortcutKey.clipboard, let query = UIPasteboard.general.string {
mainViewController()?.loadQueryInNewWebTab(query: query)
}
}
func application(_ application: UIApplication, open url: URL, sourceApplication: String?, annotation: Any) -> Bool {
Logger.log(text: "App launched with url \(url.absoluteString)")
clearNavigationStack()
if AppDeepLinks.isLaunch(url: url) {
return true
}
if AppDeepLinks.isQuickLink(url: url), let link = quickLink(from: url) {
loadQuickLink(link: link)
}
return true
}
private func quickLink(from url: URL) -> Link? {
guard let links = groupData.bookmarks else { return nil }
guard let host = url.host else { return nil }
guard let index = Int(host) else { return nil }
guard index < links.count else { return nil }
return links[index]
}
private func loadQuickLink(link: Link) {
mainViewController()?.loadUrlInNewWebTab(url: link.url)
}
private func mainViewController() -> MainViewController? {
return UIApplication.shared.keyWindow?.rootViewController?.childViewControllers.first as? MainViewController
}
private func clearNavigationStack() {
if let navigationController = UIApplication.shared.keyWindow?.rootViewController as? UINavigationController {
navigationController.popToRootViewController(animated: false)
}
}
}
| apache-2.0 | eb8957c27abc79baa773608e47004902 | 35.132653 | 155 | 0.672974 | 5.324812 | false | false | false | false |
JensRavens/Interstellar | Interstellar.playground/Pages/2 Error Handling.xcplaygroundpage/Sources/Observable.swift | 3 | 6442 | //
// Observable.swift
// Interstellar
//
// Created by Jens Ravens on 10/12/15.
// Copyright © 2015 nerdgeschoss GmbH. All rights reserved.
//
import Foundation
public struct ObservingOptions: OptionSet {
public let rawValue: Int
public init(rawValue: Int) { self.rawValue = rawValue }
/// The last value of this Observable will not retained, therefore `observable.value` will always be nil.
/// - Note: Observables without retained values can not be merged.
public static let NoInitialValue = ObservingOptions(rawValue: 1)
/// Observables will only fire once for an update and nil out their completion blocks afterwards.
/// Use this to automatically resolve retain cycles for one-off operations.
public static let Once = ObservingOptions(rawValue: 2)
}
/**
An Observable<T> is value that will change over time.
```
let text = Observable("World")
text.subscribe { string in
print("Hello \(string)") // prints Hello World
}
text.update("Developer") // will invoke the block and print Hello Developer
```
Observables are thread safe.
*/
public final class Observable<T> {
fileprivate typealias Observer = (T)->Void
fileprivate var observers = [ObserverToken: Observer]()
public private(set) var value: T?
public let options: ObservingOptions
fileprivate let mutex = Mutex()
/// Create a new observable without a value and the desired options. You can supply a value later via `update`.
public init(options: ObservingOptions = []) {
self.options = options
}
/**
Create a new observable from a value, the type will be automatically inferred:
let magicNumber = Observable(42)
- Note: See observing options for various upgrades and awesome additions.
*/
public init(_ value: T, options: ObservingOptions = []) {
self.options = options
if !options.contains(.NoInitialValue){
self.value = value
}
}
/**
Subscribe to the future values of this observable with a block. You can use the obtained
`ObserverToken` to manually unsubscribe from future updates via `unsubscribe`.
- Note: This block will be retained by the observable until it is deallocated or the corresponding `unsubscribe`
function is called.
*/
@discardableResult public func subscribe(_ observer: @escaping (T) -> Void) -> ObserverToken {
var token: ObserverToken!
mutex.lock {
let newHashValue = (observers.keys.map({$0.hashValue}).max() ?? -1) + 1
token = ObserverToken(hashValue: newHashValue)
if !(options.contains(.Once) && value != nil) {
observers[token] = observer
}
if let value = value , !options.contains(.NoInitialValue) {
observer(value)
}
}
return token
}
/// Update the inner state of an observable and notify all observers about the new value.
public func update(_ value: T) {
mutex.lock {
if !options.contains(.NoInitialValue) {
self.value = value
}
for observe in observers.values {
observe(value)
}
if options.contains(.Once) {
observers.removeAll()
}
}
}
/// Unsubscribe from future updates with the token obtained from `subscribe`. This will also release the observer block.
public func unsubscribe(_ token: ObserverToken) {
mutex.lock {
observers[token] = nil
}
}
/**
Merge multiple observables of the same type:
```
let greeting: Observable<[String]> = Observable<[String]>.merge([Observable("Hello"), Observable("World")]) // contains ["Hello", "World"]
```
- Precondition: Observables with the option .NoInitialValue do not retain their value and therefore cannot be merged.
*/
public static func merge<U>(_ observables: [Observable<U>], options: ObservingOptions = []) -> Observable<[U]> {
let merged = Observable<[U]>(options: options)
let copies = observables.map { $0.map { return $0 } } // copy all observables via subscription to not retain the originals
for observable in copies {
precondition(!observable.options.contains(.NoInitialValue), "Event style observables do not support merging")
observable.subscribe { value in
let values = copies.flatMap { $0.value }
if values.count == copies.count {
merged.update(values)
}
}
}
return merged
}
}
extension Observable {
/**
Create a new observable with a transform applied:
let text = Observable("Hello World")
let uppercaseText = text.map { $0.uppercased() }
text.update("yeah!") // uppercaseText will contain "YEAH!"
*/
public func map<U>(_ transform: @escaping (T) -> U) -> Observable<U> {
let observable = Observable<U>(options: options)
subscribe { observable.update(transform($0)) }
return observable
}
/**
Creates a new observable with a transform applied. The value of the observable will be wrapped in a Result<T> in case the transform throws.
*/
public func map<U>(_ transform: @escaping (T) throws -> U) -> Observable<Result<U>> {
let observable = Observable<Result<U>>(options: options)
subscribe { value in
observable.update(Result(block: { return try transform(value) }))
}
return observable
}
/**
Creates a new observable with a transform applied. The transform can return asynchronously by updating its returned observable.
*/
public func flatMap<U>(_ transform: @escaping (T)->Observable<U>) -> Observable<U> {
let observable = Observable<U>(options: options)
subscribe { transform($0).subscribe(observable.update) }
return observable
}
public func merge<U>(_ merge: Observable<U>) -> Observable<(T,U)> {
let signal = Observable<(T,U)>()
self.subscribe { a in
if let b = merge.value {
signal.update((a,b))
}
}
merge.subscribe { b in
if let a = self.value {
signal.update((a,b))
}
}
return signal
}
}
| mit | 5f14fb7222283e9f2eabb5188cc1dc02 | 34.39011 | 143 | 0.615277 | 4.795979 | false | false | false | false |
MYLILUYANG/xinlangweibo | xinlangweibo/xinlangweibo/Class/NewFeature/WlecomeController.swift | 1 | 1509 | //
// WlecomeController.swift
// xinlangweibo
//
// Created by liluyang on 2017/3/21.
// Copyright © 2017年 liluyang. All rights reserved.
//
import UIKit
import SDWebImage
class WlecomeController: UIViewController {
//头像底部约束
@IBOutlet weak var icoBbuttonCons: NSLayoutConstraint!
//标题
@IBOutlet weak var titleLabel: UILabel!
//头像容器
@IBOutlet weak var iconImageView: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
iconImageView.layer.cornerRadius = 45.0
iconImageView.layer.masksToBounds = true;
assert(UserAccount.loadUserAccount() != nil, "必须授权之后才能显示欢迎界面")
guard let urlStr = UserAccount.loadUserAccount()?.avatar_large else {
return
}
iconImageView.sd_setImage(with: NSURL(fileURLWithPath: urlStr) as URL);
}
override func viewDidAppear(_ animated: Bool) {
viewDidAppear(animated)
UIView.animate(withDuration: 3) {
self.icoBbuttonCons.constant = UIScreen.main.bounds.height - self.icoBbuttonCons.constant;
}
UIView.animate(withDuration: 2, animations: {
self.view.layoutIfNeeded()
}) { (_) in
UIView.animate(withDuration: 2.5, animations: {
self.titleLabel.alpha = 1;
}, completion: { (_ ) in
LYLog(logName: "s");
})
}
}
}
| gpl-3.0 | 3b9025867948b85204b4ae69645da207 | 28.08 | 102 | 0.599037 | 4.487654 | false | false | false | false |
RoRoche/iOSSwiftStarter | iOSSwiftStarter/Pods/StatefulViewController/StatefulViewController/StatefulViewControllerImplementation.swift | 1 | 4251 | import UIKit
// MARK: Default Implementation BackingViewProvider
extension BackingViewProvider where Self: UIViewController {
public var backingView: UIView {
return view
}
}
extension BackingViewProvider where Self: UIView {
public var backingView: UIView {
return self
}
}
// MARK: Default Implementation StatefulViewController
/// Default implementation of StatefulViewController for UIViewController
extension StatefulViewController {
public var stateMachine: ViewStateMachine {
return associatedObject(self, key: &stateMachineKey) { [unowned self] in
return ViewStateMachine(view: self.backingView)
}
}
public var currentState: StatefulViewControllerState {
switch stateMachine.currentState {
case .None: return .Content
case .View(let viewKey): return StatefulViewControllerState(rawValue: viewKey)!
}
}
public var lastState: StatefulViewControllerState {
switch stateMachine.lastState {
case .None: return .Content
case .View(let viewKey): return StatefulViewControllerState(rawValue: viewKey)!
}
}
// MARK: Views
public var loadingView: UIView? {
get { return placeholderView(.Loading) }
set { setPlaceholderView(newValue, forState: .Loading) }
}
public var errorView: UIView? {
get { return placeholderView(.Error) }
set { setPlaceholderView(newValue, forState: .Error) }
}
public var emptyView: UIView? {
get { return placeholderView(.Empty) }
set { setPlaceholderView(newValue, forState: .Empty) }
}
// MARK: Transitions
public func setupInitialViewState() {
let isLoading = (lastState == .Loading)
let error: NSError? = (lastState == .Error) ? NSError(domain: "com.aschuch.StatefulViewController.ErrorDomain", code: -1, userInfo: nil) : nil
transitionViewStates(isLoading, error: error, animated: false)
}
public func startLoading(animated: Bool = false, completion: (() -> Void)? = nil) {
transitionViewStates(true, animated: animated, completion: completion)
}
public func endLoading(animated: Bool = true, error: ErrorType? = nil, completion: (() -> Void)? = nil) {
transitionViewStates(false, animated: animated, error: error, completion: completion)
}
public func transitionViewStates(loading: Bool = false, error: ErrorType? = nil, animated: Bool = true, completion: (() -> Void)? = nil) {
// Update view for content (i.e. hide all placeholder views)
if hasContent() {
if let e = error {
// show unobstrusive error
handleErrorWhenContentAvailable(e)
}
self.stateMachine.transitionToState(.None, animated: animated, completion: completion)
return
}
// Update view for placeholder
var newState: StatefulViewControllerState = .Empty
if loading {
newState = .Loading
} else if let _ = error {
newState = .Error
}
self.stateMachine.transitionToState(.View(newState.rawValue), animated: animated, completion: completion)
}
// MARK: Content and error handling
public func hasContent() -> Bool {
return true
}
public func handleErrorWhenContentAvailable(error: ErrorType) {
// Default implementation does nothing.
}
// MARK: Helper
private func placeholderView(state: StatefulViewControllerState) -> UIView? {
return stateMachine[state.rawValue]
}
private func setPlaceholderView(view: UIView?, forState state: StatefulViewControllerState) {
stateMachine[state.rawValue] = view
}
}
// MARK: Association
private var stateMachineKey: UInt8 = 0
private func associatedObject<T: AnyObject>(host: AnyObject, key: UnsafePointer<Void>, initial: () -> T) -> T {
var value = objc_getAssociatedObject(host, key) as? T
if value == nil {
value = initial()
objc_setAssociatedObject(host, key, value, .OBJC_ASSOCIATION_RETAIN)
}
return value!
}
| apache-2.0 | 01577f888813cc0eae2dd5ce1dd6fe4a | 30.488889 | 150 | 0.642202 | 5.066746 | false | false | false | false |
Piwigo/Piwigo-Mobile | piwigo/Image/ImageDescriptionView.swift | 1 | 6029 | //
// ImageDescriptionView.swift
// piwigo
//
// Created by Eddy Lelièvre-Berna on 22/12/2021.
// Copyright © 2021 Piwigo.org. All rights reserved.
//
import UIKit
class ImageDescriptionView: UIVisualEffectView {
@IBOutlet weak var descWidth: NSLayoutConstraint!
@IBOutlet weak var descHeight: NSLayoutConstraint!
@IBOutlet weak var descOffset: NSLayoutConstraint!
@IBOutlet weak var descTextView: UITextView!
override func awakeFromNib() {
// Initialization code
super.awakeFromNib()
}
func setDescriptionColor() {
if #available(iOS 13.0, *) {
descTextView.textColor = .piwigoColorText()
} else {
backgroundColor = .piwigoColorBackground()
descTextView.textColor = .piwigoColorText()
}
}
func configDescription(with imageComment:String?,
completion: @escaping () -> Void) {
// Should we present a description?
guard let comment = imageComment, comment.isEmpty == false else {
// Hide the description view
descTextView.text = ""
self.isHidden = true
completion()
return
}
// Configure the description view
descTextView.attributedText = comment.htmlToAttributedString
let navController = topMostController()?.navigationController
self.isHidden = navController?.isNavigationBarHidden ?? false
// Calculate the available width
var safeAreaWidth: CGFloat = UIScreen.main.bounds.size.width
if let root = navController?.topViewController {
safeAreaWidth = root.view.frame.size.width
if #available(iOS 11.0, *) {
safeAreaWidth -= root.view.safeAreaInsets.left + root.view.safeAreaInsets.right
}
}
// Calculate the required number of lines, corners'width deducted
let context = NSStringDrawingContext()
context.minimumScaleFactor = 1.0
let lineHeight = (descTextView.font ?? UIFont.piwigoFontSmall()).lineHeight
let cornerRadius = descTextView.textContainerInset.top + lineHeight/2
let rect = descTextView.attributedText.boundingRect(with: CGSize(width: safeAreaWidth - 2*cornerRadius,
height: CGFloat.greatestFiniteMagnitude),
options: .usesLineFragmentOrigin, context: context)
let textHeight = rect.height
let nberOfLines = textHeight / lineHeight
// Can the description be presented on 3 lines maximum?
if nberOfLines < 4 {
// Calculate the height (the width should be < safeAreaWidth)
let requiredHeight = ceil(descTextView.textContainerInset.top + textHeight + descTextView.textContainerInset.bottom)
// Calculate the optimum size
let size = descTextView.sizeThatFits(CGSize(width: safeAreaWidth - cornerRadius,
height: requiredHeight))
descWidth.constant = size.width + cornerRadius // Add space taken by corners
descHeight.constant = size.height
descOffset.constant = 10 - 2 * nberOfLines
self.layer.cornerRadius = cornerRadius
self.layer.masksToBounds = true
}
else if rect.width < safeAreaWidth - 4*cornerRadius {
// Several short lines but width much smaller than screen width
descWidth.constant = rect.width + cornerRadius // Add space taken by corners
self.layer.cornerRadius = cornerRadius
self.layer.masksToBounds = true
// The maximum height is limited on iPhone
if UIDevice.current.userInterfaceIdiom == .phone {
let orientation: UIInterfaceOrientation
if #available(iOS 14, *) {
orientation = UIApplication.shared.windows.first?.windowScene?.interfaceOrientation ?? .portrait
} else {
orientation = UIApplication.shared.statusBarOrientation
}
let maxHeight:CGFloat = orientation.isPortrait ? 88 : 52
descHeight.constant = min(maxHeight, rect.height)
descOffset.constant = 2
}
else {
descHeight.constant = rect.height
descOffset.constant = 0
}
// Scroll text to the top
descTextView.scrollRangeToVisible(NSRange(location: 0, length: 1))
}
else {
// Several long lines spread over full width for minimising height
self.layer.cornerRadius = 0 // Disable rounded corner in case user added text
self.layer.masksToBounds = false
descWidth.constant = safeAreaWidth
descOffset.constant = 0
let height = descTextView.sizeThatFits(CGSize(width: safeAreaWidth,
height: CGFloat.greatestFiniteMagnitude)).height
// The maximum height is limited on iPhone
if UIDevice.current.userInterfaceIdiom == .phone {
let orientation: UIInterfaceOrientation
if #available(iOS 14, *) {
orientation = UIApplication.shared.windows.first?.windowScene?.interfaceOrientation ?? .portrait
} else {
orientation = UIApplication.shared.statusBarOrientation
}
let maxHeight:CGFloat = orientation.isPortrait ? 88 : 52
descHeight.constant = min(maxHeight, height)
}
else {
descHeight.constant = height
}
// Scroll text to the top
descTextView.scrollRangeToVisible(NSRange(location: 0, length: 1))
}
completion()
}
}
| mit | 363b18cbf050e78779428d8779bbfa35 | 43.316176 | 128 | 0.590012 | 6.039078 | false | false | false | false |
Yokong/douyu | douyu/douyu/Classes/Home/View/RecommendTopView.swift | 1 | 3864 | //
// RecommendTopView.swift
// douyu
//
// Created by Yoko on 2017/4/27.
// Copyright © 2017年 Yokooll. All rights reserved.
//
import UIKit
class RecommendTopView: UIView {
@IBOutlet weak var collectionView: UICollectionView!
@IBOutlet weak var pageControl: UIPageControl!
var circles: [CircleModel] = [CircleModel]()
var timer: Timer?
override func awakeFromNib() {
super.awakeFromNib()
setUp()
}
/// 返回topView
static func topView() -> RecommendTopView {
return Bundle.main.loadNibNamed("RecommendTopView", owner: self, options: nil)?.first as! RecommendTopView
}
}
//MARK:- ------基础配置------
extension RecommendTopView {
func setUp() {
autoresizingMask = .init(rawValue: 0)
collectionView.dataSource = self
collectionView.delegate = self
// 注册cell
collectionView.register(UINib(nibName: "CircleCell", bundle: nil), forCellWithReuseIdentifier: "cell")
// 请求数据
loadData()
pageControl.numberOfPages = circles.count
stopTimer()
startTimer()
}
override func layoutSubviews() {
super.layoutSubviews()
collectionView.frame = CGRect(x: 0, y: 0, width: bounds.width, height: bounds.height - 80)
let layout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout
layout.itemSize = collectionView.bounds.size
// 设置collectionView默认偏移到中间位置
let offSetX = 600 * collectionView.bounds.width
collectionView.setContentOffset(CGPoint(x: offSetX, y: 0), animated: false)
}
}
//MARK:- ------网络请求------
extension RecommendTopView {
func loadData() {
RecommentViewModel.shared.loadTopViewData {
self.circles = RecommentViewModel.shared.circles
}
}
}
//MARK:- ------collectionView 数据源 代理------
extension RecommendTopView: UICollectionViewDelegate, UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return circles.count * 10000
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! CircleCell
let index = indexPath.item % circles.count
cell.circle = circles[index]
return cell
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
let offSetX = scrollView.contentOffset.x + Screen_W
let page = Int(offSetX / Screen_W) % (circles.count)
pageControl.currentPage = page
}
func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
stopTimer()
}
func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
startTimer()
}
}
//MARK:- ------设置定时器------
extension RecommendTopView {
func startTimer() {
timer = Timer(timeInterval: 3.0, target: self, selector: #selector(RecommendTopView.nextPage), userInfo: nil, repeats: true)
RunLoop.main.add(timer!, forMode: .commonModes)
}
func stopTimer() {
timer?.invalidate()
timer = nil
}
func nextPage() {
// 获取当前偏移量
let currentOffset = collectionView.contentOffset.x
// 累加偏移
let offsetX = currentOffset + collectionView.bounds.width
collectionView.setContentOffset(CGPoint(x: offsetX, y: 0), animated: true)
}
}
| mit | 2e05a3e0901cf7074b639fde71392f5a | 23.448052 | 132 | 0.616202 | 5.25838 | false | false | false | false |
Acidburn0zzz/firefox-ios | Storage/SuggestedSites.swift | 9 | 1589 | /* 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
import Shared
open class SuggestedSite: Site {
override open var tileURL: URL {
return URL(string: url as String) ?? URL(string: "about:blank")!
}
let trackingId: Int
init(data: SuggestedSiteData) {
self.trackingId = data.trackingId
super.init(url: data.url, title: data.title, bookmarked: nil)
self.guid = "default" + data.title // A guid is required in the case the site might become a pinned site
}
}
public let SuggestedSites = SuggestedSitesCursor()
open class SuggestedSitesCursor: ArrayCursor<SuggestedSite> {
fileprivate init() {
let locale = Locale.current
let sites = DefaultSuggestedSites.sites[locale.identifier] ??
DefaultSuggestedSites.sites["default"]! as Array<SuggestedSiteData>
let tiles = sites.map({ data -> SuggestedSite in
var site = data
if let domainMap = DefaultSuggestedSites.urlMap[data.url], let localizedURL = domainMap[locale.identifier] {
site.url = localizedURL
}
return SuggestedSite(data: site)
})
super.init(data: tiles, status: .success, statusMessage: "Loaded")
}
}
public struct SuggestedSiteData {
var url: String
var bgColor: String
var imageUrl: String
var faviconUrl: String
var trackingId: Int
var title: String
}
| mpl-2.0 | 2af863796c8316965b6a9df8c9a3c9e0 | 33.543478 | 120 | 0.660164 | 4.260054 | false | false | false | false |
geojow/beeryMe | beeryMe/ConnectionCheck.swift | 1 | 993 | //
// ConnectionCheck.swift
// beeryMe
//
// Created by George Jowitt on 26/11/2017.
// Copyright © 2017 George Jowitt. All rights reserved.
//
import Foundation
import SystemConfiguration
public class ConnectionCheck {
class func isConnectedToNetwork() -> Bool {
var zeroAddress = sockaddr_in()
zeroAddress.sin_len = UInt8(MemoryLayout<sockaddr_in>.size)
zeroAddress.sin_family = sa_family_t(AF_INET)
guard let defaultRouteReachability = withUnsafePointer(to: &zeroAddress, {
$0.withMemoryRebound(to: sockaddr.self, capacity: 1) {
SCNetworkReachabilityCreateWithAddress(nil, $0)
}
}) else {
return false
}
var flags: SCNetworkReachabilityFlags = []
if !SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags) {
return false
}
let isReachable = flags.contains(.reachable)
let needsConnection = flags.contains(.connectionRequired)
return (isReachable && !needsConnection)
}
}
| mit | 349f20eda40c3d1d7e8fee04de8fe1ae | 27.342857 | 78 | 0.694556 | 4.52968 | false | false | false | false |
ciamic/Smashtag | Smashtag/TweetCollectionViewCell.swift | 1 | 2919 | //
// TweetCollectionViewCell.swift
//
// Copyright (c) 2017 michelangelo
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
class TweetCollectionViewCell: UICollectionViewCell {
// MARK: - Model
var imageUrl: URL? {
didSet { updateUI() }
}
//an optional cache in which try to get the image before starting the download
var cache: NSCache<AnyObject, AnyObject>?
// MARK: - Outlets
@IBOutlet weak var tweetImageView: UIImageView!
@IBOutlet weak var spinner: UIActivityIndicatorView!
// MARK: - Utils
//fetches an image at the specified url and set the image of the imageView when done.
//if a cache is available, checks for the image in the cache first.
fileprivate func updateUI() {
tweetImageView?.image = nil
if let url = imageUrl {
spinner?.startAnimating()
if let imageData = cache?.object(forKey: url as AnyObject) as? Data,
let image = UIImage(data: imageData) {
tweetImageView.image = image
spinner?.stopAnimating()
return
}
DispatchQueue.global(qos: DispatchQoS.QoSClass.userInitiated).async {
let imageData = try? Data(contentsOf: url)
DispatchQueue.main.async { [weak self] in
if url == self?.imageUrl {
if imageData != nil {
self?.tweetImageView.image = UIImage(data: imageData!)
self?.cache?.setObject(imageData! as AnyObject, forKey: url as AnyObject)
} else {
self?.tweetImageView.image = nil
}
self?.spinner.stopAnimating()
}
}
}
}
}
}
| mit | 012b19bec321bc354aaf3b47692e9421 | 38.986301 | 101 | 0.621788 | 4.998288 | false | false | false | false |
DrabWeb/Azusa | Source/Yui/Yui/Objects/Plugins.swift | 1 | 7565 | //
// Plugins.swift
// Yui
//
// Created by Ushio on 2/14/17.
//
import Foundation
// MARK: - PluginManager
public class PluginManager {
// MARK: - Properties
// MARK: Public Properties
public class var global : PluginManager {
return _global;
}
public var plugins : [PluginInfo] {
return _plugins;
}
public var enabledPlugins : [PluginInfo] {
var ep : [PluginInfo] = [];
plugins.forEach {
if $0.isEnabled {
ep.append($0);
}
}
return ep;
}
public var defaultPlugin : PluginInfo? {
for (_, p) in plugins.enumerated() {
if p.bundleIdentifier == Preferences.global.defaultPlugin && p.isEnabled {
return p;
}
}
return nil;
}
// MARK: Private Properties
private let basePath : String = "\(NSHomeDirectory())/Library/Application Support/Azusa/Plugins"
private static let _global : PluginManager = PluginManager();
private var _plugins : [PluginInfo] = [];
// MARK: - Methods
// MARK: Public Methods
// MARK: Private Methods
// TODO: Maybe add some sort of safety here?
// Not sure because it should be on the user to only install trusted plugins
// Probably go with what most do where it's disabled when installed and the user has to enable it
/// Loads all the `Plugin`s in the plugins folder and puts them in `_plugins`
private func loadPlugins() {
var plugins : [PluginInfo] = [];
// Load the `Plugin` class from every `.bundle` in the `Plugins` directory, and if it's valid add it to `plugins`
do {
for (_, file) in try FileManager.default.contentsOfDirectory(atPath: basePath).enumerated() {
if let filename = file as String? {
if let bundle = Bundle(path: "\(basePath)/\(filename)") {
if let plugin = PluginInfo(bundle: bundle) {
plugins.append(plugin);
}
}
}
}
}
catch let error {
Logger.logError("PluginManager: Error getting plugins, \(error)");
}
_plugins = plugins;
}
// MARK: - Init / Deinit
init() {
do {
try FileManager.default.createDirectory(atPath: basePath, withIntermediateDirectories: true, attributes: nil);
}
catch let error {
Logger.logError("PluginManager: Error creating plugins folder, \(error)");
}
loadPlugins();
}
}
// MARK: - Plugin
/// The protocol for a Azusa plugin to implement in the base class, provides info about the plugin and access to it's classes
public protocol Plugin {
// MARK: - Methods
// MARK: Public Methods
/// Provides a new instance of the plugin's `MusicSource` with the provided settings
func getMusicSource(settings : [String : Any]) -> MusicSource;
/// Provides a new `PluginPreferencesController` for this plugin
func getPreferencesController() -> PluginPreferencesController;
// MARK: - Init / Deinit
init();
}
// MARK: - PluginInfo
public class PluginInfo: CustomStringConvertible {
// MARK: - Properties
// MARK: Public Properties
public let name : String;
public var version : String;
public var info : String;
public var bundleIdentifier : String;
public var bundlePath : String;
public var pluginClass : Plugin.Type!
public var description : String {
return "PluginInfo(\(pluginClass)): \(name) v\(version), \(info)";
}
public var isEnabled : Bool {
return Preferences.global.enabledPlugins.contains(bundleIdentifier);
}
public var isDefault : Bool {
return Preferences.global.defaultPlugin == bundleIdentifier;
}
private var _plugin : Plugin? = nil;
public var getPlugin : Plugin? {
if isEnabled {
if _plugin == nil {
_plugin = pluginClass.init();
}
return _plugin;
}
return nil;
}
public var settings : [String : Any] {
get {
if let p = Preferences.global.pluginSettings[bundleIdentifier] {
return p;
}
else {
return [:];
}
}
}
// MARK: - Methods
// MARK: Public Methods
public func enable() {
Preferences.global.enablePlugin(self);
}
public func disable() {
Preferences.global.disablePlugin(self);
}
public func toggleEnabled() {
if isEnabled {
Preferences.global.disablePlugin(self);
}
else {
Preferences.global.enablePlugin(self);
}
}
public func makeDefault() {
Preferences.global.defaultPlugin = bundleIdentifier;
}
// MARK: - Init / Deinit
init?(bundle : Bundle) {
if let pluginClass = bundle.principalClass.self?.class() as? Plugin.Type {
self.name = bundle.object(forInfoDictionaryKey: "CFBundleName") as! String;
self.version = bundle.object(forInfoDictionaryKey: "CFBundleShortVersionString") as! String;
self.info = bundle.object(forInfoDictionaryKey: "PluginDescription") as! String;
self.bundleIdentifier = bundle.bundleIdentifier ?? "";
self.bundlePath = bundle.bundlePath;
self.pluginClass = pluginClass;
}
else {
return nil;
}
}
init(name : String, version : String, info : String, bundleIdentifier : String, bundlePath : String, pluginClass : Plugin.Type) {
self.name = name;
self.version = version;
self.info = info;
self.bundleIdentifier = bundleIdentifier;
self.bundlePath = bundlePath;
self.pluginClass = pluginClass;
}
}
// NSViewController-based protocol that returns a settings dictionary for when the user presses apply
// Probably also some way to check if applying is allowed for something like Plex where the user has to enter the pin first
// Not sure how to go about that yet
// Preferences controllers should only be loaded when the plugin is enabled, if it was loaded when disabled then it could potentionally run code without user confirmation
// This is the best way I could see to force a base class and protocol on a subclass
// MARK: - PluginPreferencesProtocol
protocol PluginPreferencesProtocol {
/// Gets the settings for the current state of this preferences controller
///
/// - Returns: A dictionary of settings suitable for `MusicSource`
func getSettings() -> [String : Any];
/// Display the given settings dictionary
///
/// - Parameter settings: The settings to display
func display(settings : [String : Any]);
}
// MARK: - PluginPreferencesController
/// The base class for preferences views of plugins
open class PluginPreferencesController: NSViewController, PluginPreferencesProtocol {
open func getSettings() -> [String : Any] {
fatalError("PluginPreferencesController subclasses must override getSettings()");
}
open func display(settings: [String : Any]) {
fatalError("PluginPreferencesController subclasses must override display(settings:)");
}
}
| gpl-3.0 | 4ae170e2b23ebe5ba8b092afb13320c1 | 29.504032 | 170 | 0.596563 | 5.066979 | false | false | false | false |
Ethenyl/JAMFKit | JamfKit/Sources/Models/Category.swift | 1 | 960 | //
// Copyright © 2017-present JamfKit. All rights reserved.
// Licensed under the MIT License. See LICENSE file in the project root for full license information.
//
@objc(JMFKCategory)
public final class Category: BaseObject {
// MARK: - Constants
static let PriorityKey = "priority"
// MARK: - Properties
@objc
public var priority: UInt = 0
// MARK: - Initialization
public required init?(json: [String: Any], node: String = "") {
guard let priority = json[Category.PriorityKey] as? UInt else {
return nil
}
self.priority = priority
super.init(json: json)
}
public override init?(identifier: UInt, name: String) {
super.init(identifier: identifier, name: name)
}
// MARK: - Functions
public override func toJSON() -> [String: Any] {
var json = super.toJSON()
json[Category.PriorityKey] = priority
return json
}
}
| mit | 46c488704acf5b2e4a87b55d56c21e4f | 21.302326 | 102 | 0.619395 | 4.300448 | false | false | false | false |
Automattic/Automattic-Tracks-iOS | Tests/Tests/Event Logging/EventLoggingTests.swift | 1 | 3999 | import XCTest
import OHHTTPStubs
#if SWIFT_PACKAGE
@testable import AutomatticRemoteLogging
@testable import AutomatticEncryptedLogs
#else
@testable import AutomatticTracks
#endif
class EventLoggingTests: XCTestCase {
private let domain = "event-logging-tests.example"
lazy var url = URL(string: "http://\(domain)")!
func testThatOnlyOneFileIsUploadedSimultaneously() {
stubResponse(domain: domain, status: "ok")
let uploadCount = Int.random(in: 3...10)
var isUploading = false
waitForExpectation() { (exp) in
exp.expectedFulfillmentCount = uploadCount
let eventLogging = self.eventLogging(delegate: MockEventLoggingDelegate()
.withDidStartUploadingCallback { log in
XCTAssertFalse(isUploading, "Only one upload should be running at the same time")
isUploading = true
}
.withDidFinishUploadingCallback { log in
XCTAssertTrue(isUploading, "Only one upload should be running at the same time")
isUploading = false
exp.fulfill()
}
)
DispatchQueue.concurrentPerform(iterations: uploadCount) { _ in
try! eventLogging.enqueueLogForUpload(log: LogFile.containingRandomString())
}
}
}
func testThatAllFilesAreEventuallyUploaded() throws {
stubResponse(domain: domain, status: "ok")
let uploadCount = Int.random(in: 3...10)
let logs = (0...uploadCount).map { _ in LogFile.containingRandomString() }
try waitForExpectation() { (exp) in
exp.expectedFulfillmentCount = logs.count
let delegate = MockEventLoggingDelegate()
.withDidFinishUploadingCallback { _ in
exp.fulfill()
}
let eventLogging = self.eventLogging(delegate: delegate)
/// Adding logs one at at time means the queue will probably drain as fast (if not faster) than we can add them.
/// This tests the do-the-next-one logic
try logs.forEach {
try eventLogging.enqueueLogForUpload(log: $0)
}
}
}
func testThatDelegateCancellationPausesLogUpload() {
stubResponse(domain: domain, status: "ok")
let uploadCount = Int.random(in: 3...10)
waitForExpectation() { (exp) in
exp.expectedFulfillmentCount = 1
exp.assertForOverFulfill = true
let delegate = MockEventLoggingDelegate()
.withShouldUploadLogFilesValue(false)
.withUploadCancelledCallback { _ in
exp.fulfill() // we should only ever get one of these, because afterward
}
.withDidStartUploadingCallback({ _ in
XCTFail("Files should not start uploading")
})
let eventLogging = self.eventLogging(delegate: delegate)
DispatchQueue.concurrentPerform(iterations: uploadCount) { _ in
try! eventLogging.enqueueLogForUpload(log: LogFile.containingRandomString())
}
}
}
func testThatRunningOutOfLogFilesDoesNotPauseLogUpload() {
let delegate = MockEventLoggingDelegate()
let eventLogging = self.eventLogging(delegate: delegate)
XCTAssertNil(eventLogging.uploadsPausedUntil)
eventLogging.uploadNextLogFileIfNeeded()
Thread.sleep(forTimeInterval: 1.0)
XCTAssertNil(eventLogging.uploadsPausedUntil)
}
}
extension EventLoggingTests {
func eventLogging(delegate: EventLoggingDelegate) -> EventLogging {
return EventLogging(dataSource: dataSource(), delegate: delegate)
}
func dataSource() -> MockEventLoggingDataSource {
MockEventLoggingDataSource()
.withEncryptionKey()
.withLogUploadUrl(url)
}
}
| gpl-2.0 | 0c0c339daf2bee3d3988ab5e9f470bbe | 34.389381 | 124 | 0.617654 | 5.508264 | false | true | false | false |
jmohr7/civil-war | civil-war/GameOverScene.swift | 1 | 1332 | //
// GameOverScene.swift
// civil-war
//
// Created by Joseph Mohr on 2/1/16.
// Copyright © 2016 Mohr. All rights reserved.
//
import Foundation
import SpriteKit
class GameOverScene: SKScene {
init(size: CGSize, score:Int) {
super.init(size: size)
// Set background
backgroundColor = SKColor(colorLiteralRed: 0.07, green: 0.277, blue: 0.203, alpha: 0)
// Set Message
let message = "Score: \(score) \(score > 20 ? "😃" : "😵")"
let label = SKLabelNode(fontNamed: "Chalkduster")
label.text = message
label.fontSize = 40
label.fontColor = SKColor(colorLiteralRed: 0.992, green: 0.879, blue: 0.137, alpha: 1)
label.position = CGPoint(x: size.width/2, y: size.height/2)
addChild(label)
// Set transition animation
runAction(SKAction.sequence([
SKAction.waitForDuration(3.0),
SKAction.runBlock() {
let reveal = SKTransition.flipHorizontalWithDuration(0.5)
let scene = GameScene(size: size)
self.view?.presentScene(scene, transition:reveal)
}
]))
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
} | mit | 71f5661a9e6db37752d0b4e7c1c7c37e | 28.466667 | 94 | 0.571321 | 4.246795 | false | false | false | false |
apparata/ProjectKit | Sources/ProjectKit/Project File Objects/File Element/Base File Element/FileElement.swift | 1 | 932 |
import Foundation
/// Abstract base class of the concrete file element objects.
public class FileElement {
public class ID: ObjectID { }
/// A 96 bit unique identifier.
public private(set) var id: ID
/// A 96 bit unique identifier.
public var objectID: ObjectID {
return id
}
/// The raw dictionary representation of the object.
public private(set) var object: NSDictionary
public private(set) var path: String?
public private(set) var sourceTree: SourceTree?
public private(set) var name: String?
public init(id: ID, object: NSDictionary) {
self.id = id
self.object = object
path = object["path"] as? String
name = object["name"] as? String
sourceTree = nil
if let sourceTree = object["sourceTree"] as? String {
self.sourceTree = SourceTree(rawValue: sourceTree)
}
}
}
| mit | 42fe504f1677a546ce3b0274fd083b68 | 24.888889 | 62 | 0.618026 | 4.591133 | false | false | false | false |
justinhester/hacking-with-swift | src/Project23/Project23/GameScene.swift | 1 | 3687 | //
// GameScene.swift
// Project23
//
// Created by Justin Lawrence Hester on 2/14/16.
// Copyright (c) 2016 Justin Lawrence Hester. All rights reserved.
//
import GameplayKit
import SpriteKit
class GameScene: SKScene, SKPhysicsContactDelegate {
var starfield: SKEmitterNode!
var player: SKSpriteNode!
var scoreLabel: SKLabelNode!
var score: Int = 0 {
didSet {
scoreLabel.text = "Score: \(score)"
}
}
var possibleEnemies = ["ball", "hammer", "tv"]
var gameTimer: NSTimer!
var gameOver = false
override func didMoveToView(view: SKView) {
/* Setup your scene here */
backgroundColor = UIColor.blackColor()
starfield = SKEmitterNode(fileNamed: "Starfield")!
starfield.position = CGPoint(x: size.width, y: size.height / 2)
starfield.advanceSimulationTime(10)
addChild(starfield)
starfield.zPosition = -1
player = SKSpriteNode(imageNamed: "player")
player.position = CGPoint(x: 100, y: size.height / 2)
player.physicsBody = SKPhysicsBody(
texture: player.texture!,
size: player.size
)
player.physicsBody!.contactTestBitMask = 1
addChild(player)
scoreLabel = SKLabelNode(fontNamed: "Chalkduster")
scoreLabel.position = CGPoint(x: 16, y: 16)
scoreLabel.horizontalAlignmentMode = .Left
addChild(scoreLabel)
score = 0
physicsWorld.gravity = CGVector(dx: 0, dy: 0)
physicsWorld.contactDelegate = self
gameTimer = NSTimer.scheduledTimerWithTimeInterval(
0.35,
target: self,
selector: "createEnemy",
userInfo: nil,
repeats: true
)
}
override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {
guard let touch = touches.first else { return }
var location = touch.locationInNode(self)
if location.y < 100 {
location.y = 100
} else if location.y > 668 {
location.y = 668
}
player.position = location
}
func didBeginContact(contact: SKPhysicsContact) {
/* Blow up player's spaceship. */
let explosion = SKEmitterNode(fileNamed: "explosion")!
explosion.position = player.position
addChild(explosion)
player.removeFromParent()
gameOver = true
}
func createEnemy() {
possibleEnemies = GKRandomSource
.sharedRandom()
.arrayByShufflingObjectsInArray(possibleEnemies) as! [String]
let randomDistribution = GKRandomDistribution(
lowestValue: 50,
highestValue: 736
)
let sprite = SKSpriteNode(imageNamed: possibleEnemies[0])
sprite.position = CGPoint(x: 1200, y: randomDistribution.nextInt())
addChild(sprite)
sprite.physicsBody = SKPhysicsBody(texture: sprite.texture!, size: sprite.size)
sprite.physicsBody?.categoryBitMask = 1
sprite.physicsBody?.velocity = CGVector(dx: -500, dy: 0)
sprite.physicsBody?.angularVelocity = 5
sprite.physicsBody?.linearDamping = 0
sprite.physicsBody?.angularDamping = 0
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
/* Called when a touch begins */
}
override func update(currentTime: CFTimeInterval) {
/* Called before each frame is rendered */
for node in children {
if node.position.x < -300 {
node.removeFromParent()
}
}
if !gameOver {
score += 1
}
}
}
| gpl-3.0 | 3e8692a720e86e886233e5c725491998 | 28.031496 | 87 | 0.606726 | 4.909454 | false | false | false | false |
richardpiazza/LCARSDisplayKit | Workspace/LCARSDisplayKitExample/ViewController.swift | 1 | 1838 | //
// ViewController.swift
// LCARSDisplayKit
//
// Created by Richard Piazza on 10/2/15.
// Copyright © 2015 Richard Piazza. All rights reserved.
//
import UIKit
import LCARSDisplayKitUI
class ViewController: UIViewController {
@IBOutlet weak var dgroup: DGroupView02?
var isConditionRed = false
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
guard let dgroup = self.dgroup else {
return
}
dgroup.outerRing14.isHidden = true
dgroup.innerRing10.isHidden = true
dgroup.innerRing16.isHidden = true
let blinkSequence = CommandSequence([dgroup.modeSelect, dgroup.outerRing16]) {
dgroup.innerRing11.behavior = .pulsate(timeInterval: 2.5)
dgroup.outerRing16.behavior = .pulsate(timeInterval: 3.0)
dgroup.outerRing01.behavior = .pulsate(timeInterval: 4.0)
}
CommandSequencer.default.register(commandSequence: blinkSequence)
let inverseBlink = CommandSequence([dgroup.modeSelect, dgroup.outerRing17]) {
dgroup.innerRing11.behavior = nil
dgroup.outerRing16.behavior = nil
dgroup.outerRing01.behavior = nil
}
CommandSequencer.default.register(commandSequence: inverseBlink)
let redAlert = CommandSequence([dgroup.outerRing20, dgroup.outerRing20, dgroup.outerRing20]) {
self.isConditionRed = !self.isConditionRed
print("Is Condition Red: \(self.isConditionRed)")
}
CommandSequencer.default.register(commandSequence: redAlert)
}
}
| mit | b4e6667704952614585125d15163abcd | 31.22807 | 102 | 0.641807 | 4.524631 | false | false | false | false |
bitboylabs/selluv-ios | selluv-ios/Pods/ObjectMapper/Sources/Operators.swift | 113 | 10440 | //
// Operators.swift
// ObjectMapper
//
// Created by Tristan Himmelman on 2014-10-09.
//
// The MIT License (MIT)
//
// Copyright (c) 2014-2016 Hearst
//
// 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.
/**
* This file defines a new operator which is used to create a mapping between an object and a JSON key value.
* There is an overloaded operator definition for each type of object that is supported in ObjectMapper.
* This provides a way to add custom logic to handle specific types of objects
*/
/// Operator used for defining mappings to and from JSON
infix operator <-
/// Operator used to define mappings to JSON
infix operator >>>
// MARK:- Objects with Basic types
/// Object of Basic type
public func <- <T>(left: inout T, right: Map) {
switch right.mappingType {
case .fromJSON where right.isKeyPresent:
FromJSON.basicType(&left, object: right.value())
case .toJSON:
left >>> right
default: ()
}
}
public func >>> <T>(left: T, right: Map) {
if right.mappingType == .toJSON {
ToJSON.basicType(left, map: right)
}
}
/// Optional object of basic type
public func <- <T>(left: inout T?, right: Map) {
switch right.mappingType {
case .fromJSON where right.isKeyPresent:
FromJSON.optionalBasicType(&left, object: right.value())
case .toJSON:
left >>> right
default: ()
}
}
public func >>> <T>(left: T?, right: Map) {
if right.mappingType == .toJSON {
ToJSON.optionalBasicType(left, map: right)
}
}
/// Implicitly unwrapped optional object of basic type
public func <- <T>(left: inout T!, right: Map) {
switch right.mappingType {
case .fromJSON where right.isKeyPresent:
FromJSON.optionalBasicType(&left, object: right.value())
case .toJSON:
left >>> right
default: ()
}
}
// MARK:- Mappable Objects - <T: BaseMappable>
/// Object conforming to Mappable
public func <- <T: BaseMappable>(left: inout T, right: Map) {
switch right.mappingType {
case .fromJSON:
FromJSON.object(&left, map: right)
case .toJSON:
left >>> right
}
}
public func >>> <T: BaseMappable>(left: T, right: Map) {
if right.mappingType == .toJSON {
ToJSON.object(left, map: right)
}
}
/// Optional Mappable objects
public func <- <T: BaseMappable>(left: inout T?, right: Map) {
switch right.mappingType {
case .fromJSON where right.isKeyPresent:
FromJSON.optionalObject(&left, map: right)
case .toJSON:
left >>> right
default: ()
}
}
public func >>> <T: BaseMappable>(left: T?, right: Map) {
if right.mappingType == .toJSON {
ToJSON.optionalObject(left, map: right)
}
}
/// Implicitly unwrapped optional Mappable objects
public func <- <T: BaseMappable>(left: inout T!, right: Map) {
switch right.mappingType {
case .fromJSON where right.isKeyPresent:
FromJSON.optionalObject(&left, map: right)
case .toJSON:
left >>> right
default: ()
}
}
// MARK:- Dictionary of Mappable objects - Dictionary<String, T: BaseMappable>
/// Dictionary of Mappable objects <String, T: Mappable>
public func <- <T: BaseMappable>(left: inout Dictionary<String, T>, right: Map) {
switch right.mappingType {
case .fromJSON where right.isKeyPresent:
FromJSON.objectDictionary(&left, map: right)
case .toJSON:
left >>> right
default: ()
}
}
public func >>> <T: BaseMappable>(left: Dictionary<String, T>, right: Map) {
if right.mappingType == .toJSON {
ToJSON.objectDictionary(left, map: right)
}
}
/// Optional Dictionary of Mappable object <String, T: Mappable>
public func <- <T: BaseMappable>(left: inout Dictionary<String, T>?, right: Map) {
switch right.mappingType {
case .fromJSON where right.isKeyPresent:
FromJSON.optionalObjectDictionary(&left, map: right)
case .toJSON:
left >>> right
default: ()
}
}
public func >>> <T: BaseMappable>(left: Dictionary<String, T>?, right: Map) {
if right.mappingType == .toJSON {
ToJSON.optionalObjectDictionary(left, map: right)
}
}
/// Implicitly unwrapped Optional Dictionary of Mappable object <String, T: Mappable>
public func <- <T: BaseMappable>(left: inout Dictionary<String, T>!, right: Map) {
switch right.mappingType {
case .fromJSON where right.isKeyPresent:
FromJSON.optionalObjectDictionary(&left, map: right)
case .toJSON:
left >>> right
default: ()
}
}
/// Dictionary of Mappable objects <String, T: Mappable>
public func <- <T: BaseMappable>(left: inout Dictionary<String, [T]>, right: Map) {
switch right.mappingType {
case .fromJSON where right.isKeyPresent:
FromJSON.objectDictionaryOfArrays(&left, map: right)
case .toJSON:
left >>> right
default: ()
}
}
public func >>> <T: BaseMappable>(left: Dictionary<String, [T]>, right: Map) {
if right.mappingType == .toJSON {
ToJSON.objectDictionaryOfArrays(left, map: right)
}
}
/// Optional Dictionary of Mappable object <String, T: Mappable>
public func <- <T: BaseMappable>(left: inout Dictionary<String, [T]>?, right: Map) {
switch right.mappingType {
case .fromJSON where right.isKeyPresent:
FromJSON.optionalObjectDictionaryOfArrays(&left, map: right)
case .toJSON:
left >>> right
default: ()
}
}
public func >>> <T: BaseMappable>(left: Dictionary<String, [T]>?, right: Map) {
if right.mappingType == .toJSON {
ToJSON.optionalObjectDictionaryOfArrays(left, map: right)
}
}
/// Implicitly unwrapped Optional Dictionary of Mappable object <String, T: Mappable>
public func <- <T: BaseMappable>(left: inout Dictionary<String, [T]>!, right: Map) {
switch right.mappingType {
case .fromJSON where right.isKeyPresent:
FromJSON.optionalObjectDictionaryOfArrays(&left, map: right)
case .toJSON:
left >>> right
default: ()
}
}
// MARK:- Array of Mappable objects - Array<T: BaseMappable>
/// Array of Mappable objects
public func <- <T: BaseMappable>(left: inout Array<T>, right: Map) {
switch right.mappingType {
case .fromJSON where right.isKeyPresent:
FromJSON.objectArray(&left, map: right)
case .toJSON:
left >>> right
default: ()
}
}
public func >>> <T: BaseMappable>(left: Array<T>, right: Map) {
if right.mappingType == .toJSON {
ToJSON.objectArray(left, map: right)
}
}
/// Optional array of Mappable objects
public func <- <T: BaseMappable>(left: inout Array<T>?, right: Map) {
switch right.mappingType {
case .fromJSON where right.isKeyPresent:
FromJSON.optionalObjectArray(&left, map: right)
case .toJSON:
left >>> right
default: ()
}
}
public func >>> <T: BaseMappable>(left: Array<T>?, right: Map) {
if right.mappingType == .toJSON {
ToJSON.optionalObjectArray(left, map: right)
}
}
/// Implicitly unwrapped Optional array of Mappable objects
public func <- <T: BaseMappable>(left: inout Array<T>!, right: Map) {
switch right.mappingType {
case .fromJSON where right.isKeyPresent:
FromJSON.optionalObjectArray(&left, map: right)
case .toJSON:
left >>> right
default: ()
}
}
// MARK:- Array of Array of Mappable objects - Array<Array<T: BaseMappable>>
/// Array of Array Mappable objects
public func <- <T: BaseMappable>(left: inout Array<Array<T>>, right: Map) {
switch right.mappingType {
case .fromJSON where right.isKeyPresent:
FromJSON.twoDimensionalObjectArray(&left, map: right)
case .toJSON:
left >>> right
default: ()
}
}
public func >>> <T: BaseMappable>(left: Array<Array<T>>, right: Map) {
if right.mappingType == .toJSON {
ToJSON.twoDimensionalObjectArray(left, map: right)
}
}
/// Optional array of Mappable objects
public func <- <T: BaseMappable>(left:inout Array<Array<T>>?, right: Map) {
switch right.mappingType {
case .fromJSON where right.isKeyPresent:
FromJSON.optionalTwoDimensionalObjectArray(&left, map: right)
case .toJSON:
left >>> right
default: ()
}
}
public func >>> <T: BaseMappable>(left: Array<Array<T>>?, right: Map) {
if right.mappingType == .toJSON {
ToJSON.optionalTwoDimensionalObjectArray(left, map: right)
}
}
/// Implicitly unwrapped Optional array of Mappable objects
public func <- <T: BaseMappable>(left: inout Array<Array<T>>!, right: Map) {
switch right.mappingType {
case .fromJSON where right.isKeyPresent:
FromJSON.optionalTwoDimensionalObjectArray(&left, map: right)
case .toJSON:
left >>> right
default: ()
}
}
// MARK:- Set of Mappable objects - Set<T: BaseMappable where T: Hashable>
/// Set of Mappable objects
public func <- <T: BaseMappable>(left: inout Set<T>, right: Map) where T: Hashable {
switch right.mappingType {
case .fromJSON where right.isKeyPresent:
FromJSON.objectSet(&left, map: right)
case .toJSON:
left >>> right
default: ()
}
}
public func >>> <T: BaseMappable>(left: Set<T>, right: Map) where T: Hashable {
if right.mappingType == .toJSON {
ToJSON.objectSet(left, map: right)
}
}
/// Optional Set of Mappable objects
public func <- <T: BaseMappable>(left: inout Set<T>?, right: Map) where T: Hashable, T: Hashable {
switch right.mappingType {
case .fromJSON where right.isKeyPresent:
FromJSON.optionalObjectSet(&left, map: right)
case .toJSON:
left >>> right
default: ()
}
}
public func >>> <T: BaseMappable>(left: Set<T>?, right: Map) where T: Hashable, T: Hashable {
if right.mappingType == .toJSON {
ToJSON.optionalObjectSet(left, map: right)
}
}
/// Implicitly unwrapped Optional Set of Mappable objects
public func <- <T: BaseMappable>(left: inout Set<T>!, right: Map) where T: Hashable {
switch right.mappingType {
case .fromJSON where right.isKeyPresent:
FromJSON.optionalObjectSet(&left, map: right)
case .toJSON:
left >>> right
default: ()
}
}
| mit | b2a27ee3d9fa45eb2baf474facf3c0a8 | 26.692308 | 108 | 0.705651 | 3.606218 | false | false | false | false |
uias/Tabman | Sources/Tabman/TabmanViewController.swift | 1 | 13870 | //
// TabmanViewController.swift
// Tabman
//
// Created by Merrick Sapsford on 17/02/2017.
// Copyright © 2022 UI At Six. All rights reserved.
//
import UIKit
import Pageboy
/// A view controller which embeds a `PageboyViewController` and provides the ability to add bars which
/// can directly manipulate, control and display the status of the page view controller. It also handles
/// automatic insetting of child view controller contents.
open class TabmanViewController: PageboyViewController, PageboyViewControllerDelegate, TMBarDelegate {
// MARK: Types
/// Location of the bar in the view controller.
///
/// - top: Pin to the top of the safe area.
/// - bottom: Pin to the bottom of the safe area.
/// - navigationItem: Set as a `UINavigationItem.titleView`.
/// - custom: Add the view to a custom view and provide custom layout.
/// If no layout is provided, all edge anchors will be constrained
/// to the superview.
public enum BarLocation {
case top
case bottom
case navigationItem(item: UINavigationItem)
case custom(view: UIView, layout: ((UIView) -> Void)?)
}
// MARK: Views
internal let topBarContainer = UIStackView()
internal let bottomBarContainer = UIStackView()
/// All bars that have been added to the view controller.
public private(set) var bars = [TMBar]()
// MARK: Layout
private var requiredInsets: Insets?
private let insetter = AutoInsetter()
/// Whether to automatically adjust child view controller content insets with bar geometry.
///
/// This must be set before `viewDidLoad`, setting it after this point will result in no change.
/// Default is `true`.
public var automaticallyAdjustsChildInsets: Bool = true
@available(*, unavailable)
open override var automaticallyAdjustsScrollViewInsets: Bool {
didSet {}
}
/// The insets that are required to safely layout content between the bars
/// that have been added.
///
/// This will only take account of bars that are added to the `.top` or `.bottom`
/// locations - bars that are added to custom locations are responsible for handling
/// their own insets.
public var barInsets: UIEdgeInsets {
return requiredInsets?.barInsets ?? .zero
}
/// The layout guide representing the portion of the view controller's view that is not
/// obstructed by bars.
public let barLayoutGuide: UILayoutGuide = {
let guide = UILayoutGuide()
guide.identifier = "barLayoutGuide"
return guide
}()
private var barLayoutGuideTop: NSLayoutConstraint?
private var barLayoutGuideBottom: NSLayoutConstraint?
@available(*, unavailable)
open override var delegate: PageboyViewControllerDelegate? {
didSet {}
}
// MARK: Init
public override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
commonInit()
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
private func commonInit() {
super.delegate = self
}
// MARK: Lifecycle
open override func viewDidLoad() {
super.viewDidLoad()
if automaticallyAdjustsChildInsets {
insetter.enable(for: self)
}
configureBarLayoutGuide(barLayoutGuide)
layoutContainers(in: view)
}
open override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
setNeedsInsetsUpdate()
}
/// A method for calculating insets that are required to layout content between the bars
/// that have been added.
///
/// One can override this method with their own implementation for custom bar inset calculation, to
/// take advantage of automatic insets updates for all Tabman's pages during its lifecycle.
///
/// - Returns: information about required insets for current state.
open func calculateRequiredInsets() -> Insets {
return Insets.for(self)
}
// MARK: Pageboy
/// :nodoc:
open override func insertPage(at index: PageboyViewController.PageIndex,
then updateBehavior: PageboyViewController.PageUpdateBehavior) {
bars.forEach({ $0.reloadData(at: index...index, context: .insertion) })
super.insertPage(at: index, then: updateBehavior)
}
/// :nodoc:
open override func deletePage(at index: PageboyViewController.PageIndex,
then updateBehavior: PageboyViewController.PageUpdateBehavior) {
bars.forEach({ $0.reloadData(at: index...index, context: .deletion) })
super.deletePage(at: index, then: updateBehavior)
}
/// :nodoc:
open func pageboyViewController(_ pageboyViewController: PageboyViewController,
willScrollToPageAt index: PageIndex,
direction: NavigationDirection,
animated: Bool) {
let viewController = dataSource?.viewController(for: self, at: index)
setNeedsInsetsUpdate(to: viewController)
if animated {
updateActiveBars(to: CGFloat(index),
direction: direction,
animated: true)
}
}
/// :nodoc:
open func pageboyViewController(_ pageboyViewController: PageboyViewController,
didScrollTo position: CGPoint,
direction: NavigationDirection,
animated: Bool) {
if !animated {
updateActiveBars(to: relativeCurrentPosition,
direction: direction,
animated: false)
}
}
/// :nodoc:
open func pageboyViewController(_ pageboyViewController: PageboyViewController,
didScrollToPageAt index: PageIndex,
direction: NavigationDirection,
animated: Bool) {
updateActiveBars(to: CGFloat(index),
direction: direction,
animated: false)
}
/// :nodoc:
open func pageboyViewController(_ pageboyViewController: PageboyViewController,
didCancelScrollToPageAt index: PageboyViewController.PageIndex,
returnToPageAt previousIndex: PageboyViewController.PageIndex) {
}
/// :nodoc:
open func pageboyViewController(_ pageboyViewController: PageboyViewController,
didReloadWith currentViewController: UIViewController,
currentPageIndex: PageIndex) {
setNeedsInsetsUpdate(to: currentViewController)
guard let pageCount = pageboyViewController.pageCount else {
return
}
bars.forEach({ $0.reloadData(at: 0...pageCount - 1, context: .full) })
}
// MARK: TMBarDelegate
/// :nodoc:
open func bar(_ bar: TMBar,
didRequestScrollTo index: PageboyViewController.PageIndex) {
scrollToPage(.at(index: index), animated: true, completion: nil)
}
}
// MARK: - Bar Layout
extension TabmanViewController {
/// Add a new `TMBar` to the view controller.
///
/// - Parameters:
/// - bar: Bar to add.
/// - dataSource: Data source for the bar.
/// - location: Location of the bar.
public func addBar(_ bar: TMBar,
dataSource: TMBarDataSource,
at location: BarLocation) {
bar.dataSource = dataSource
bar.delegate = self
if bars.contains(where: { $0 === bar }) == false {
bars.append(bar)
}
layoutView(bar, at: location)
updateBar(bar, to: relativeCurrentPosition, animated: false)
if let pageCount = self.pageCount, pageCount > 0 {
bar.reloadData(at: 0...pageCount - 1, context: .full)
}
}
/// Remove a `TMBar` from the view controller.
///
/// - Parameter bar: Bar to remove.
public func removeBar(_ bar: TMBar) {
guard let index = bars.firstIndex(where: { $0 === bar }) else {
return
}
bars.remove(at: index)
bar.removeFromSuperview()
}
private func layoutContainers(in view: UIView) {
topBarContainer.axis = .vertical
view.addSubview(topBarContainer)
topBarContainer.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
topBarContainer.leadingAnchor.constraint(equalTo: view.leadingAnchor),
topBarContainer.trailingAnchor.constraint(equalTo: view.trailingAnchor),
topBarContainer.topAnchor.constraint(equalTo: view.safeAreaTopAnchor)
])
bottomBarContainer.axis = .vertical
view.addSubview(bottomBarContainer)
bottomBarContainer.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
bottomBarContainer.leadingAnchor.constraint(equalTo: view.leadingAnchor),
bottomBarContainer.trailingAnchor.constraint(equalTo: view.trailingAnchor),
bottomBarContainer.bottomAnchor.constraint(equalTo: view.safeAreaBottomAnchor)
])
}
private func layoutView(_ view: UIView,
at location: BarLocation) {
view.removeFromSuperview()
switch location {
case .top:
topBarContainer.addArrangedSubview(view)
case .bottom:
bottomBarContainer.insertArrangedSubview(view, at: 0)
case .custom(let superview, let layout):
superview.addSubview(view)
if layout != nil {
layout?(view)
} else {
view.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
view.leadingAnchor.constraint(equalTo: superview.leadingAnchor),
view.topAnchor.constraint(equalTo: superview.topAnchor),
view.trailingAnchor.constraint(equalTo: superview.trailingAnchor),
view.bottomAnchor.constraint(equalTo: superview.bottomAnchor)
])
}
case .navigationItem(let item):
let container = ViewTitleViewContainer(for: view)
container.frame = CGRect(x: 0.0, y: 0.0, width: 300, height: 50)
container.layoutIfNeeded()
item.titleView = container
}
}
private func configureBarLayoutGuide(_ guide: UILayoutGuide) {
guard barLayoutGuide.owningView == nil else {
return
}
view.addLayoutGuide(barLayoutGuide)
let barLayoutGuideTop = barLayoutGuide.topAnchor.constraint(equalTo: view.topAnchor)
let barLayoutGuideBottom = view.bottomAnchor.constraint(equalTo: barLayoutGuide.bottomAnchor)
NSLayoutConstraint.activate([
barLayoutGuide.leadingAnchor.constraint(equalTo: view.leadingAnchor),
barLayoutGuideTop,
barLayoutGuide.trailingAnchor.constraint(equalTo: view.trailingAnchor),
barLayoutGuideBottom
])
self.barLayoutGuideTop = barLayoutGuideTop
self.barLayoutGuideBottom = barLayoutGuideBottom
}
}
// MARK: - Bar Management
private extension TabmanViewController {
func updateActiveBars(to position: CGFloat?,
direction: NavigationDirection = .neutral,
animated: Bool) {
bars.forEach({ self.updateBar($0, to: position,
direction: direction,
animated: animated) })
}
func updateBar(_ bar: TMBar,
to position: CGFloat?,
direction: NavigationDirection = .neutral,
animated: Bool) {
let position = position ?? 0.0
let capacity = self.pageCount ?? 0
let animation = TMAnimation(isEnabled: animated,
duration: transition?.duration ?? 0.25)
bar.update(for: position,
capacity: capacity,
direction: direction.barUpdateDirection,
animation: animation)
}
}
// MARK: - Insetting
internal extension TabmanViewController {
func setNeedsInsetsUpdate() {
setNeedsInsetsUpdate(to: currentViewController)
}
func setNeedsInsetsUpdate(to viewController: UIViewController?) {
guard viewIfLoaded?.window != nil else {
return
}
let insets = calculateRequiredInsets()
self.requiredInsets = insets
barLayoutGuideTop?.constant = insets.spec.allRequiredInsets.top
barLayoutGuideBottom?.constant = insets.spec.allRequiredInsets.bottom
// Don't inset TabmanViewController using AutoInsetter
if viewController is TabmanViewController {
if viewController?.additionalSafeAreaInsets != insets.spec.additionalRequiredInsets {
viewController?.additionalSafeAreaInsets = insets.spec.additionalRequiredInsets
}
} else {
insetter.inset(viewController, requiredInsetSpec: insets.spec)
}
}
}
| mit | 04b5ed6c4e2267ac6fc3712c083f81ae | 36.282258 | 104 | 0.603865 | 5.805358 | false | false | false | false |
akane/Akane | Akane/Akane/Component/Controller/ComponentController.swift | 1 | 1969 | //
// This file is part of Akane
//
// Created by JC on 15/12/15.
// For the full copyright and license information, please view the LICENSE
// file that was distributed with this source code
//
import Foundation
import HasAssociatedObjects
/**
ComponentController is a Controller making the link between a `ComponentView`
and its `ComponentViewModel`.
*/
public protocol ComponentController : ComponentDisplayable, ComponentContainer {
associatedtype ViewType: ComponentDisplayable where ViewType.Parameters == Parameters
// MARK: Associated component elements
/// The Controller's ComponentView.
var componentView: ViewType? { get }
/// The Controller's CompnentViewModel.
var viewModel: ViewType.Parameters! { get }
/**
Called every time `viewModel` is setted on Controller.
You can use it to (re)initialize anything related to ViewModel.
You can also use it to bind components which are "outside" workflow/hierarchy, like navigation bar.
*/
func didLoadComponent()
}
extension ComponentController {
public func didLoadComponent() {
}
}
extension ComponentController {
/// The Controller's CompnentViewModel.
public fileprivate(set) var viewModel: ViewType.Parameters! {
get {
return self.associatedObjects["viewModel"] as? ViewType.Parameters
}
set {
self.associatedObjects["viewModel"] = newValue
}
}
public func bindings(_ observer: ViewObserver, params viewModel: ViewType.Parameters) {
self.viewModel = viewModel
self.didLoadComponent()
viewModel.mountIfNeeded()
if let componentView = componentView {
componentView.bind(observer, params: viewModel)
}
}
}
extension ComponentController where Self : UIViewController {
/// The Controller's ComponentView.
public var componentView: ViewType? {
get { return self.view as? ViewType }
}
}
| mit | 93e5f0687df94e21f878cd52fac294a0 | 27.955882 | 104 | 0.694769 | 4.9225 | false | false | false | false |
wikimedia/wikipedia-ios | Wikipedia/Code/PageHistoryComparisonSelectionViewController.swift | 1 | 4908 | import UIKit
protocol PageHistoryComparisonSelectionViewControllerDelegate: AnyObject {
func pageHistoryComparisonSelectionViewController(_ pageHistoryComparisonSelectionViewController: PageHistoryComparisonSelectionViewController, selectionOrder: SelectionOrder)
func pageHistoryComparisonSelectionViewControllerDidTapCompare(_ pageHistoryComparisonSelectionViewController: PageHistoryComparisonSelectionViewController)
}
class PageHistoryComparisonSelectionViewController: UIViewController {
@IBOutlet private weak var firstSelectionButton: AlignedImageButton!
@IBOutlet private weak var secondSelectionButton: AlignedImageButton!
@IBOutlet private weak var compareButton: UIButton!
private var theme = Theme.standard
public weak var delegate: PageHistoryComparisonSelectionViewControllerDelegate?
override func viewDidLoad() {
super.viewDidLoad()
setup(button: firstSelectionButton)
setup(button: secondSelectionButton)
compareButton.setTitle(CommonStrings.compareTitle, for: .normal)
compareButton.addTarget(self, action: #selector(performCompareButtonAction(_:)), for: .touchUpInside)
resetSelectionButtons()
updateFonts()
}
private func setup(button: AlignedImageButton) {
button.cornerRadius = 8
button.clipsToBounds = true
button.backgroundColor = theme.colors.paperBackground
button.imageView?.tintColor = theme.colors.link
button.setTitleColor(theme.colors.link, for: .normal)
button.titleLabel?.font = UIFont.wmf_font(.semiboldSubheadline, compatibleWithTraitCollection: traitCollection)
button.horizontalSpacing = 10
button.contentHorizontalAlignment = .leading
button.leftPadding = 10
button.rightPadding = 10
button.addTarget(self, action: #selector(performSelectionButtonAction(_:)), for: .touchUpInside)
}
@objc private func performSelectionButtonAction(_ sender: AlignedImageButton) {
guard let selectionOrder = SelectionOrder(rawValue: sender.tag) else {
return
}
delegate?.pageHistoryComparisonSelectionViewController(self, selectionOrder: selectionOrder)
}
@objc private func performCompareButtonAction(_ sender: UIButton) {
delegate?.pageHistoryComparisonSelectionViewControllerDidTapCompare(self)
}
private func reset(button: AlignedImageButton?) {
button?.setTitle(nil, for: .normal)
button?.setImage(nil, for: .normal)
button?.backgroundColor = theme.colors.paperBackground
button?.borderWidth = 1
// themeTODO: define a semantic color for this instead of checking isDark
button?.borderColor = theme.isDark ? .base70 : theme.colors.border
}
public func resetSelectionButton(_ selectionOrder: SelectionOrder) {
reset(button: button(selectionOrder))
}
public func resetSelectionButtons() {
reset(button: firstSelectionButton)
reset(button: secondSelectionButton)
}
public func setCompareButtonEnabled(_ enabled: Bool) {
compareButton.isEnabled = enabled
}
private func button(_ selectionOrder: SelectionOrder) -> AlignedImageButton? {
switch selectionOrder {
case .first:
return firstSelectionButton
case .second:
return secondSelectionButton
}
}
public func updateSelectionButton(_ selectionOrder: SelectionOrder, with themeModel: PageHistoryViewController.SelectionThemeModel, cell: PageHistoryCollectionViewCell) {
let button = self.button(selectionOrder)
UIView.performWithoutAnimation {
button?.setTitle(cell.time, for: .normal)
button?.setImage(cell.authorImage, for: .normal)
button?.backgroundColor = themeModel.backgroundColor
button?.imageView?.tintColor = themeModel.authorColor
button?.setTitleColor(themeModel.authorColor, for: .normal)
button?.tintColor = themeModel.authorColor
button?.borderWidth = 1
button?.borderColor = themeModel.borderColor
}
}
private func updateFonts() {
compareButton.titleLabel?.font = UIFont.wmf_font(.semiboldSubheadline, compatibleWithTraitCollection: traitCollection)
firstSelectionButton.titleLabel?.font = UIFont.wmf_font(.semiboldSubheadline, compatibleWithTraitCollection: traitCollection)
secondSelectionButton.titleLabel?.font = UIFont.wmf_font(.semiboldSubheadline, compatibleWithTraitCollection: traitCollection)
}
}
extension PageHistoryComparisonSelectionViewController: Themeable {
func apply(theme: Theme) {
self.theme = theme
guard viewIfLoaded != nil else {
return
}
view.backgroundColor = theme.colors.midBackground
compareButton.tintColor = theme.colors.link
}
}
| mit | 576e7483e73e7761e03dff2d88a7d953 | 42.052632 | 179 | 0.72555 | 5.913253 | false | false | false | false |
alloyapple/Goose | Sources/Goose/FileDescriptor.swift | 1 | 2627 | //
// Created by color on 5/2/18.
//
import Foundation
import CGoose
public class FileDescriptor: Hashable {
public let fd: Int32
public static let `in` = FileDescriptor(fd: 0)
public static let out = FileDescriptor(fd: 1)
public static let err = FileDescriptor(fd: 2)
public init(fd: Int32) {
self.fd = fd
}
public func write(_ data: [Int8]) -> Int {
return Glibc.write(self.fd, data, data.count)
}
public func read(_ data: inout [Int8]) -> Int {
return Glibc.read(self.fd, &data, data.count)
}
deinit {
close(fd)
}
public var hashValue: Int {
return fd.hashValue
}
public static func == (lhs: FileDescriptor, rhs: FileDescriptor) -> Bool {
return lhs.fd == rhs.fd
}
}
extension FileDescriptor {
public func write(text: String) -> Int? {
let bytes = text.bytes
let ret = Glibc.write(fd, bytes, bytes.count)
guard ret != -1 else {
return nil
}
return ret
}
public func write(bytes: [Int8]) -> Int? {
let ret = Glibc.write(fd, bytes, bytes.count)
guard ret != -1 else {
return nil
}
return ret
}
}
extension FileDescriptor {
public func fchdir() -> Int32? {
let ret = Glibc.fchdir(fd)
guard ret != -1 else {
return nil
}
return ret
}
public func fchmod(mode: UInt32) -> Int32? {
let ret = Glibc.fchmod(fd, mode)
guard ret != -1 else {
return nil
}
return ret
}
public func fchown(owner: UInt32, group: UInt32) -> Int32? {
let ret = Glibc.fchown(fd, owner, group)
guard ret != -1 else {
return nil
}
return ret
}
public func fdopen(mode: String = "r") -> FileDescriptor? {
let ret = Glibc.fdopen(fd, mode)
guard ret != nil else {
return nil
}
return FileDescriptor(fd: fileno(ret))
}
}
extension FileDescriptor {
public func fcntl(cmd: Int32) -> Int32? {
let ret = fcntl_int(fd, cmd)
guard ret > -1 else {
return nil
}
return ret
}
public func fcntl(cmd: Int32, arg: Int32) -> Int32? {
let ret = fcntl_int_int(fd, cmd, arg)
guard ret > -1 else {
return nil
}
return ret
}
public func fcntl(cmd: Int32, arg: String) -> Int32? {
let ret = fcntl_int_string(fd, cmd, arg)
guard ret > -1 else {
return nil
}
return ret
}
} | bsd-3-clause | 6dbd1ecfe6063661fd1bb2f33fea59eb | 20.365854 | 78 | 0.527217 | 3.823872 | false | false | false | false |
tomalbrc/PoGoMobile | PoGoMobile/Global.swift | 1 | 1226 | //
// Global.swift
// PoGoMobile
//
// Created by Tom Albrecht on 10.08.16.
// Copyright © 2016 Tom Albrecht. All rights reserved.
//
import Foundation
import CoreLocation
import PGoApi
// Some stuff that doesnt really belong anywhere and I want a clean ViewController.swift
func degToRad(deg : Double) -> Double {
return deg / 180 * M_PI
}
func locationWithBearing(bearing:Double, distanceMeters:Double, origin:CLLocationCoordinate2D) -> CLLocationCoordinate2D {
let distRadians = distanceMeters / (6372797.6) // earth radius in meters
let lat1 = origin.latitude * M_PI / 180
let lon1 = origin.longitude * M_PI / 180
let lat2 = asin(sin(lat1) * cos(distRadians) + cos(lat1) * sin(distRadians) * cos(bearing))
let lon2 = lon1 + atan2(sin(bearing) * sin(distRadians) * cos(lat1), cos(distRadians) - sin(lat1) * sin(lat2))
return CLLocationCoordinate2D(latitude: lat2 * 180 / M_PI, longitude: lon2 * 180 / M_PI)
}
// TODO: um
class ClientInformation {
var playerData: Pogoprotos.Data.PlayerData?
var playerStats: Pogoprotos.Data.Player.PlayerStats?
var inventoryItems: Array<Pogoprotos.Inventory.InventoryItem>?
}
var clientInformation = ClientInformation()
| mit | 32c9c04ca76dd069904c885a8807fea3 | 28.166667 | 122 | 0.710204 | 3.613569 | false | false | false | false |
collegboi/DIT-Timetable-iOS | DIT Timtable watch Extension/ComplicationController.swift | 1 | 3012 | //
// ComplicationController.swift
// DIT Timtable watch Extension
//
// Created by Timothy Barnard on 17/09/2017.
// Copyright © 2017 Timothy Barnard. All rights reserved.
//
import ClockKit
class ComplicationController: NSObject, CLKComplicationDataSource {
let userCalendar = NSCalendar.current
let dateFormatter = DateFormatter()
var complicationHandler = ComplicationHandler()
// MARK: - Timeline Configuration
func getSupportedTimeTravelDirections(for complication: CLKComplication, withHandler handler: @escaping (CLKComplicationTimeTravelDirections) -> Void) {
handler([.forward, .backward])
}
func getTimelineStartDate(for complication: CLKComplication, withHandler handler: @escaping (Date?) -> Void) {
handler(nil)
}
func getTimelineEndDate(for complication: CLKComplication, withHandler handler: @escaping (Date?) -> Void) {
handler(nil)
}
func getPrivacyBehavior(for complication: CLKComplication, withHandler handler: @escaping (CLKComplicationPrivacyBehavior) -> Void) {
handler(.showOnLockScreen)
}
// MARK: - Update Scheduling
func getNextRequestedUpdateDate(handler: @escaping (Date?) -> Void) {
handler(Date(timeIntervalSinceNow: TimeInterval(10*60)))
}
// MARK: - Timeline Population
func getCurrentTimelineEntry(for complication: CLKComplication, withHandler handler: @escaping (CLKComplicationTimelineEntry?) -> Void) {
handler(self.complicationHandler.getCurrentTimelineEntry(complication: complication))
}
func getTimelineEntries(for complication: CLKComplication, before date: Date, limit: Int, withHandler handler: @escaping ([CLKComplicationTimelineEntry]?) -> Void) {
// Call the handler with the timeline entries prior to the given date
handler(nil)
}
func getTimelineEntries(for complication: CLKComplication, after date: Date, limit: Int, withHandler handler: @escaping ([CLKComplicationTimelineEntry]?) -> Void) {
handler(self.complicationHandler.getTimelineEntriesAfter(complication: complication))
}
// MARK: - Placeholder Templates
func getLocalizableSampleTemplate(for complication: CLKComplication, withHandler handler: @escaping (CLKComplicationTemplate?) -> Void) {
handler(self.complicationHandler.getTimelineSampleData(complication: complication))
}
/*var dayFraction : Float {
let now = Date()
let calendar = Calendar.current
let componentFlags = Set<Calendar.Component>([.year, .month, .day, .weekOfYear, .hour, .minute, .second, .weekday, .weekdayOrdinal])
var components = calendar.dateComponents(componentFlags, from: now)
components.hour = 0
components.minute = 0
components.second = 0
let startOfDay = calendar.date(from: components)!
return Float(now.timeIntervalSince(startOfDay)) / Float(24*60*60)
}*/
}
| mit | ed1271fdec56d7cfb0a949c42b5d041a | 38.618421 | 169 | 0.701428 | 5.367201 | false | false | false | false |
kaojohnny/CoreStore | Sources/Internal/NSManagedObjectModel+Setup.swift | 1 | 9949 | //
// NSManagedObjectModel+Setup.swift
// CoreStore
//
// Copyright © 2015 John Rommel Estropia
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
import Foundation
import CoreData
// MARK: - NSManagedObjectModel
internal extension NSManagedObjectModel {
// MARK: Internal
@nonobjc
internal static func fromBundle(bundle: NSBundle, modelName: String, modelVersionHints: Set<String> = []) -> NSManagedObjectModel {
guard let modelFilePath = bundle.pathForResource(modelName, ofType: "momd") else {
CoreStore.abort("Could not find \"\(modelName).momd\" from the bundle. \(bundle)")
}
let modelFileURL = NSURL(fileURLWithPath: modelFilePath)
let versionInfoPlistURL = modelFileURL.URLByAppendingPathComponent("VersionInfo.plist", isDirectory: false)
guard let versionInfo = NSDictionary(contentsOfURL: versionInfoPlistURL),
let versionHashes = versionInfo["NSManagedObjectModel_VersionHashes"] as? [String: AnyObject] else {
CoreStore.abort("Could not load \(cs_typeName(NSManagedObjectModel)) metadata from path \"\(versionInfoPlistURL)\".")
}
let modelVersions = Set(versionHashes.keys)
let currentModelVersion: String
if let plistModelVersion = versionInfo["NSManagedObjectModel_CurrentVersionName"] as? String where modelVersionHints.isEmpty || modelVersionHints.contains(plistModelVersion) {
currentModelVersion = plistModelVersion
}
else if let resolvedVersion = modelVersions.intersect(modelVersionHints).first {
CoreStore.log(
.Warning,
message: "The MigrationChain leaf versions do not include the model file's current version. Resolving to version \"\(resolvedVersion)\"."
)
currentModelVersion = resolvedVersion
}
else if let resolvedVersion = modelVersions.first ?? modelVersionHints.first {
if !modelVersionHints.isEmpty {
CoreStore.log(
.Warning,
message: "The MigrationChain leaf versions do not include any of the model file's embedded versions. Resolving to version \"\(resolvedVersion)\"."
)
}
currentModelVersion = resolvedVersion
}
else {
CoreStore.abort("No model files were found in URL \"\(modelFileURL)\".")
}
var modelVersionFileURL: NSURL?
for modelVersion in modelVersions {
let fileURL = modelFileURL.URLByAppendingPathComponent("\(modelVersion).mom", isDirectory: false)
if modelVersion == currentModelVersion {
modelVersionFileURL = fileURL
continue
}
precondition(
NSManagedObjectModel(contentsOfURL: fileURL) != nil,
"Could not find the \"\(modelVersion).mom\" version file for the model at URL \"\(modelFileURL)\"."
)
}
if let modelVersionFileURL = modelVersionFileURL,
let rootModel = NSManagedObjectModel(contentsOfURL: modelVersionFileURL) {
rootModel.modelVersionFileURL = modelVersionFileURL
rootModel.modelVersions = modelVersions
rootModel.currentModelVersion = currentModelVersion
return rootModel
}
CoreStore.abort("Could not create an \(cs_typeName(NSManagedObjectModel)) from the model at URL \"\(modelFileURL)\".")
}
@nonobjc
internal private(set) var currentModelVersion: String? {
get {
let value: NSString? = cs_getAssociatedObjectForKey(
&PropertyKeys.currentModelVersion,
inObject: self
)
return value as? String
}
set {
cs_setAssociatedCopiedObject(
newValue == nil ? nil : (newValue! as NSString),
forKey: &PropertyKeys.currentModelVersion,
inObject: self
)
}
}
@nonobjc
internal private(set) var modelVersions: Set<String>? {
get {
let value: NSSet? = cs_getAssociatedObjectForKey(
&PropertyKeys.modelVersions,
inObject: self
)
return value as? Set<String>
}
set {
cs_setAssociatedCopiedObject(
newValue == nil ? nil : (newValue! as NSSet),
forKey: &PropertyKeys.modelVersions,
inObject: self
)
}
}
@nonobjc
internal func entityNameForClass(entityClass: AnyClass) -> String {
return self.entityNameMapping[NSStringFromClass(entityClass)]!
}
@nonobjc
internal func entityTypesMapping() -> [String: NSManagedObject.Type] {
var mapping = [String: NSManagedObject.Type]()
self.entityNameMapping.forEach { (className, entityName) in
mapping[entityName] = (NSClassFromString(className)! as! NSManagedObject.Type)
}
return mapping
}
@nonobjc
internal func mergedModels() -> [NSManagedObjectModel] {
return self.modelVersions?.map { self[$0] }.flatMap { $0 == nil ? [] : [$0!] } ?? [self]
}
@nonobjc
internal subscript(modelVersion: String) -> NSManagedObjectModel? {
if modelVersion == self.currentModelVersion {
return self
}
guard let modelFileURL = self.modelFileURL,
let modelVersions = self.modelVersions
where modelVersions.contains(modelVersion) else {
return nil
}
let versionModelFileURL = modelFileURL.URLByAppendingPathComponent("\(modelVersion).mom", isDirectory: false)
guard let model = NSManagedObjectModel(contentsOfURL: versionModelFileURL) else {
return nil
}
model.currentModelVersion = modelVersion
model.modelVersionFileURL = versionModelFileURL
model.modelVersions = modelVersions
return model
}
@nonobjc
internal subscript(metadata: [String: AnyObject]) -> NSManagedObjectModel? {
guard let modelHashes = metadata[NSStoreModelVersionHashesKey] as? [String : NSData] else {
return nil
}
for modelVersion in self.modelVersions ?? [] {
if let versionModel = self[modelVersion] where modelHashes == versionModel.entityVersionHashesByName {
return versionModel
}
}
return nil
}
// MARK: Private
@nonobjc
private var modelFileURL: NSURL? {
get {
return self.modelVersionFileURL?.URLByDeletingLastPathComponent
}
}
@nonobjc
private var modelVersionFileURL: NSURL? {
get {
let value: NSURL? = cs_getAssociatedObjectForKey(
&PropertyKeys.modelVersionFileURL,
inObject: self
)
return value
}
set {
cs_setAssociatedCopiedObject(
newValue,
forKey: &PropertyKeys.modelVersionFileURL,
inObject: self
)
}
}
@nonobjc
private var entityNameMapping: [String: String] {
get {
if let mapping: NSDictionary = cs_getAssociatedObjectForKey(&PropertyKeys.entityNameMapping, inObject: self) {
return mapping as! [String: String]
}
var mapping = [String: String]()
self.entities.forEach {
guard let entityName = $0.name else {
return
}
let className = $0.managedObjectClassName
mapping[className] = entityName
}
cs_setAssociatedCopiedObject(
mapping as NSDictionary,
forKey: &PropertyKeys.entityNameMapping,
inObject: self
)
return mapping
}
}
private struct PropertyKeys {
static var entityNameMapping: Void?
static var modelVersionFileURL: Void?
static var modelVersions: Void?
static var currentModelVersion: Void?
}
}
| mit | 3a8e839ca4a5a9f76df4eeebf324bfbb | 33.068493 | 183 | 0.576699 | 6.12939 | false | false | false | false |
rodrigoruiz/SwiftUtilities | SwiftUtilities/Cocoa/UIViewController+Keyboard.swift | 1 | 1633 | //
// UIViewController+Keyboard.swift
// SwiftUtilities
//
// Created by Rodrigo Ruiz on 8/24/17.
// Copyright © 2017 Rodrigo Ruiz. All rights reserved.
//
import RxCocoa
import RxSwift
extension UIViewController {
public func setupKeyboardNotifications(show: @escaping (_ keyboardFrame: CGRect) -> Void, hide: @escaping () -> Void) -> Disposable {
var isKeyboardShowing = false
let showDisposable = NotificationCenter.default.rx.notification(.UIKeyboardWillShow).subscribe(onNext: { [weak self] notification in
if isKeyboardShowing { return }
isKeyboardShowing = true
let keyboardFrame = notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? CGRect ?? CGRect()
show(keyboardFrame)
let duration = notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? Double ?? 0
UIView.animate(withDuration: duration, animations: {
self?.view.layoutIfNeeded()
})
})
let hideDisposable = NotificationCenter.default.rx.notification(.UIKeyboardWillHide).subscribe(onNext: { [weak self] notification in
if !isKeyboardShowing { return }
isKeyboardShowing = false
hide()
let duration = notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? Double ?? 0
UIView.animate(withDuration: duration, animations: {
self?.view.layoutIfNeeded()
})
})
return CompositeDisposable(showDisposable, hideDisposable)
}
}
| mit | d5e87073119601cc4479fa4ea1c9173e | 34.478261 | 140 | 0.625 | 5.849462 | false | false | false | false |
SuPair/firefox-ios | ClientTests/MockProfile.swift | 1 | 7212 | /* 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/. */
@testable import Client
import Foundation
import Account
import Shared
import Storage
import Sync
import XCTest
import Deferred
open class MockSyncManager: SyncManager {
open var isSyncing = false
open var lastSyncFinishTime: Timestamp?
open var syncDisplayState: SyncDisplayState?
open func hasSyncedHistory() -> Deferred<Maybe<Bool>> {
return deferMaybe(true)
}
private func completedWithStats(collection: String) -> Deferred<Maybe<SyncStatus>> {
return deferMaybe(SyncStatus.completed(SyncEngineStatsSession(collection: collection)))
}
open func syncClients() -> SyncResult { return completedWithStats(collection: "mock_clients") }
open func syncClientsThenTabs() -> SyncResult { return completedWithStats(collection: "mock_clientsandtabs") }
open func syncHistory() -> SyncResult { return completedWithStats(collection: "mock_history") }
open func syncLogins() -> SyncResult { return completedWithStats(collection: "mock_logins") }
open func mirrorBookmarks() -> SyncResult { return completedWithStats(collection: "mock_bookmarks") }
open func syncEverything(why: SyncReason) -> Success {
return succeed()
}
open func syncNamedCollections(why: SyncReason, names: [String]) -> Success {
return succeed()
}
open func beginTimedSyncs() {}
open func endTimedSyncs() {}
open func applicationDidBecomeActive() {
self.beginTimedSyncs()
}
open func applicationDidEnterBackground() {
self.endTimedSyncs()
}
open func onNewProfile() {
}
open func onAddedAccount() -> Success {
return succeed()
}
open func onRemovedAccount(_ account: FirefoxAccount?) -> Success {
return succeed()
}
open func hasSyncedLogins() -> Deferred<Maybe<Bool>> {
return deferMaybe(true)
}
}
open class MockTabQueue: TabQueue {
open func addToQueue(_ tab: ShareItem) -> Success {
return succeed()
}
open func getQueuedTabs() -> Deferred<Maybe<Cursor<ShareItem>>> {
return deferMaybe(ArrayCursor<ShareItem>(data: []))
}
open func clearQueuedTabs() -> Success {
return succeed()
}
}
open class MockPanelDataObservers: PanelDataObservers {
override init(profile: Profile) {
super.init(profile: profile)
self.activityStream = MockActivityStreamDataObserver(profile: profile)
}
}
open class MockActivityStreamDataObserver: DataObserver {
public var profile: Profile
public weak var delegate: DataObserverDelegate?
init(profile: Profile) {
self.profile = profile
}
public func refreshIfNeeded(forceHighlights highlights: Bool, forceTopSites topsites: Bool) {
}
}
open class MockProfile: Profile {
// Read/Writeable properties for mocking
public var recommendations: HistoryRecommendations
public var places: BrowserHistory & Favicons & SyncableHistory & ResettableSyncStorage & HistoryRecommendations
public var files: FileAccessor
public var history: BrowserHistory & SyncableHistory & ResettableSyncStorage
public var logins: BrowserLogins & SyncableLogins & ResettableSyncStorage
public var syncManager: SyncManager!
public lazy var panelDataObservers: PanelDataObservers = {
return MockPanelDataObservers(profile: self)
}()
var db: BrowserDB
var readingListDB: BrowserDB
fileprivate let name: String = "mockaccount"
init() {
files = MockFiles()
syncManager = MockSyncManager()
logins = MockLogins(files: files)
db = BrowserDB(filename: "mock.db", schema: BrowserSchema(), files: files)
readingListDB = BrowserDB(filename: "mock_ReadingList.db", schema: ReadingListSchema(), files: files)
places = SQLiteHistory(db: self.db, prefs: MockProfilePrefs())
recommendations = places
history = places
}
public func localName() -> String {
return name
}
public func reopen() {
}
public func shutdown() {
}
public var isShutdown: Bool = false
public var favicons: Favicons {
return self.places
}
lazy public var queue: TabQueue = {
return MockTabQueue()
}()
lazy public var metadata: Metadata = {
return SQLiteMetadata(db: self.db)
}()
lazy public var isChinaEdition: Bool = {
return Locale.current.identifier == "zh_CN"
}()
lazy public var certStore: CertStore = {
return CertStore()
}()
lazy public var bookmarks: BookmarksModelFactorySource & KeywordSearchSource & SyncableBookmarks & LocalItemSource & MirrorItemSource & ShareToDestination = {
// Make sure the rest of our tables are initialized before we try to read them!
// This expression is for side-effects only.
let p = self.places
return MergedSQLiteBookmarks(db: self.db)
}()
lazy public var searchEngines: SearchEngines = {
return SearchEngines(prefs: self.prefs, files: self.files)
}()
lazy public var prefs: Prefs = {
return MockProfilePrefs()
}()
lazy public var readingList: ReadingList = {
return SQLiteReadingList(db: self.readingListDB)
}()
lazy public var recentlyClosedTabs: ClosedTabsStore = {
return ClosedTabsStore(prefs: self.prefs)
}()
internal lazy var remoteClientsAndTabs: RemoteClientsAndTabs = {
return SQLiteRemoteClientsAndTabs(db: self.db)
}()
fileprivate lazy var syncCommands: SyncCommands = {
return SQLiteRemoteClientsAndTabs(db: self.db)
}()
public let accountConfiguration: FirefoxAccountConfiguration = ProductionFirefoxAccountConfiguration()
var account: FirefoxAccount?
public func hasAccount() -> Bool {
return account != nil
}
public func hasSyncableAccount() -> Bool {
return account?.actionNeeded == FxAActionNeeded.none
}
public func getAccount() -> FirefoxAccount? {
return account
}
public func setAccount(_ account: FirefoxAccount) {
self.account = account
self.syncManager.onAddedAccount()
}
public func flushAccount() {}
public func removeAccount() {
let old = self.account
self.account = nil
self.syncManager.onRemovedAccount(old)
}
public func getClients() -> Deferred<Maybe<[RemoteClient]>> {
return deferMaybe([])
}
public func getCachedClients() -> Deferred<Maybe<[RemoteClient]>> {
return deferMaybe([])
}
public func getClientsAndTabs() -> Deferred<Maybe<[ClientAndTabs]>> {
return deferMaybe([])
}
public func getCachedClientsAndTabs() -> Deferred<Maybe<[ClientAndTabs]>> {
return deferMaybe([])
}
public func storeTabs(_ tabs: [RemoteTab]) -> Deferred<Maybe<Int>> {
return deferMaybe(0)
}
public func sendItem(_ item: ShareItem, toClients clients: [RemoteClient]) -> Success {
return succeed()
}
}
| mpl-2.0 | bae068cf8c18e8ec631d65adbc9e03fb | 29.05 | 162 | 0.674847 | 5.09682 | false | false | false | false |
CUNY-Hunter-CSCI-Capstone-Summer2014/XMPP-Chat | DampKeg/OS X/Source Code/AppDelegate.swift | 1 | 13810 | /**********************************************************************************************************************
* @file AppDelegate.swift
* @date 2014-06-09
* @brief <# Brief Description#>
* @details <#Detailed Description#>
***********************************************************************************************************************/
import Cocoa
import Rambler
class AppDelegate: NSObject, NSApplicationDelegate {
var addContactWindowController: AddContacttWindowController?
var chatBoxWindowController: NSWindowController?
var editProfileWindowController: NSWindowController?
var groupAddWindowController: NSWindowController?
var loginWindowController: LoginWindowController?
var rosterListWindowController: RosterListWindowController?
var viewProfileController: NSWindowController?
var conversationWindowControllers: NSMutableDictionary?
var subscriptionRequestWindowControllers: NSMutableDictionary?
var client: Client?;
/* *********************************** */
func applicationDidFinishLaunching(aNotification: NSNotification?) {
// Insert code here to initialize your application
addContactWindowController = AddContacttWindowController(windowNibName: "AddContact")
chatBoxWindowController = ConversationWindowController(windowNibName: "ConversationWindow")
editProfileWindowController = NSWindowController(windowNibName: "ProfileUpdate")
groupAddWindowController = NSWindowController(windowNibName: "GroupChatBox")
loginWindowController = LoginWindowController(windowNibName: "LoginWindow")
rosterListWindowController = RosterListWindowController(windowNibName: "RosterListWindow")
viewProfileController = NSWindowController(windowNibName: "ContactProfile")
conversationWindowControllers = NSMutableDictionary()
/* *********************************** */
/* ****** loginWindowController ****** */
/* *********************************** */
/* The login button has a tag of 1 in the .xib file */
let loginButton: NSButton = loginWindowController!.window.contentView.viewWithTag(1) as NSButton
loginButton.target = self;
loginButton.action = "closeLoginWindowAndOpenRosterListWindow:"
loginWindowController!.showWindow(self)
/* ************************************ */
/* **** rosterListWindowController **** */
/* ************************************ */
/* Add Contact Button */
let addContactButton: NSButton = rosterListWindowController!.window.contentView.viewWithTag(1) as NSButton
addContactButton.target = self;
addContactButton.action = "openAddContactWindow:";
/* Start Conversation Button */
let startConversationButton: NSButton = rosterListWindowController!.window.contentView.viewWithTag(2) as NSButton
startConversationButton.target = self;
startConversationButton.action = "startConversationWithSelectedContact:";
/* Change Status PopUp Button */
let statusChangePopUpButton: NSPopUpButton? = rosterListWindowController!.window.contentView.viewWithTag(99) as? NSPopUpButton
for item in statusChangePopUpButton!.itemArray {
if let menuItem = item as? NSMenuItem {
menuItem.target = self
menuItem.action = "editStatus:"
}
}
/* Remove Contact Button */
let deleteContactButton: NSButton = rosterListWindowController!.window.contentView.viewWithTag(3) as NSButton
deleteContactButton.target = self
deleteContactButton.action = "removeContact:"
/* ************************************ */
/* **** addContactWindowController **** */
/* ************************************ */
let DoneAddingContact: NSButton = addContactWindowController!.window.contentView.viewWithTag(1) as NSButton
DoneAddingContact.target = self;
DoneAddingContact.action = "userDidCompleteAddContact:";
/* ************************************ */
let CancelAddingContact: NSButton = addContactWindowController!.window.contentView.viewWithTag(2) as NSButton
CancelAddingContact.target = self;
CancelAddingContact.action = "userDidCancelAddContact:";
/* ************************************ */
/* ***** groupAddWindowController ***** */
/* ************************************ */
let CreateChatButton: NSButton = groupAddWindowController!.window.contentView.viewWithTag(2) as NSButton
CreateChatButton.target = self;
CreateChatButton.action = "createChatBox:";
/* ************************************ */
let CancelGroupAddButton: NSButton = groupAddWindowController!.window.contentView.viewWithTag(3) as NSButton
CancelGroupAddButton.target = self;
CancelGroupAddButton.action = "cancelGroupAdd:";
/* ************************************ */
let ConfirmEditProfileButton: NSButton = editProfileWindowController!.window.contentView.viewWithTag(1) as NSButton
ConfirmEditProfileButton.target = self;
ConfirmEditProfileButton.action = "saveProfileChanges:";
/* ************************************ */
let DiscardEditProfileButton: NSButton = editProfileWindowController!.window.contentView.viewWithTag(2) as NSButton
DiscardEditProfileButton.target = self;
DiscardEditProfileButton.action = "discardProfileChanges:";
}
/* ************************************ */
func applicationWillTerminate(aNotification: NSNotification?) {
}
func applicationShouldTerminateAfterLastWindowClosed(sender: NSApplication!) -> Bool {
return true;
}
/* ************************************ */
/* *********** Login Window *********** */
/* ************************************ */
@IBAction func closeLoginWindowAndOpenRosterListWindow(sender: AnyObject) {
client = Client(JIDString: self.loginWindowController!.plainAuthenticationCredentials.username);
client!.passwordRequiredEventHandler = { (String username) in
return self.loginWindowController!.plainAuthenticationCredentials.password
}
client!.messageReceivedEventHandler = {
(message: Message?) in
if !message {
return
}
var jid = message!.sender.bareJID.description
var conversationWindowController: ConversationWindowController
if self.conversationWindowControllers![jid] {
conversationWindowController =
self.conversationWindowControllers![jid] as ConversationWindowController
} else {
conversationWindowController = ConversationWindowController(windowNibName: "ConversationWindow")
conversationWindowController.partner = JID(string: jid)
conversationWindowController.client = self.client
conversationWindowController.windowTitle = "Conversation with \(jid)"
self.conversationWindowControllers![jid] = conversationWindowController
}
conversationWindowController.displayMessage(message)
conversationWindowController.showWindow(self)
}
client!.presenceReceivedEventHandler = {
(presence: Presence?, jid: JID?) in
if presence? && jid? {
self.rosterListWindowController?.updatePresence(presence!, jid: jid!)
}
}
client!.rosterItemReceivedEventHandler = {
(item: RosterItem?) in
if item? {
self.rosterListWindowController?.addRosterItem(item!)
}
}
client!.rosterItemRemovedEventHandler = {
(jid: JID?) in
if jid? {
self.rosterListWindowController?.removeRosterItemWithJID(jid!)
}
}
self.client!.subscriptionRequestedByJIDEventHandler = {
(maybeJID: JID?, maybeMessage: String?) in
if !self.subscriptionRequestWindowControllers? {
self.subscriptionRequestWindowControllers = NSMutableDictionary()
}
if let jid = maybeJID {
let controller = SubscriptionRequestWindowController(windowNibName: "SubscriptionRequestWindow")
self.subscriptionRequestWindowControllers![jid] = controller
controller.appDelegate = self
controller.client = self.client
controller.jid = jid
controller.message = maybeMessage
NSOperationQueue.mainQueue().addOperationWithBlock() {
controller.showWindow(self)
}
}
}
self.client!.start();
NSOperationQueue.mainQueue().addOperationWithBlock() {
self.loginWindowController!.window.orderOut(self)
self.rosterListWindowController!.showWindow(self)
}
}
/* ************************************ */
@IBAction func createChatBox(sender: AnyObject) {
NSOperationQueue.mainQueue().addOperationWithBlock() {
self.chatBoxWindowController!.showWindow(self)
self.groupAddWindowController!.window.orderOut(self)
}
}
@IBAction func startConversationWithSelectedContact(sender: AnyObject) {
let possibleSelectedObjects = rosterListWindowController?.rosterListController?.selectedObjects
if let theSelectedObjects = possibleSelectedObjects {
for selectedObject in theSelectedObjects {
if let item = selectedObject as? RosterListViewItem {
var conversationWindowController: ConversationWindowController
if conversationWindowControllers![item.jid] {
conversationWindowController =
conversationWindowControllers![item.jid] as ConversationWindowController
} else {
conversationWindowController = ConversationWindowController(windowNibName: "ConversationWindow")
conversationWindowController.partner = JID(string: item.jid)
conversationWindowController.client = client
conversationWindowController.windowTitle = "Conversation with \(item.name)"
conversationWindowControllers![item.jid] = conversationWindowController
}
conversationWindowController.showWindow(self)
}
}
}
}
/* ************************************ */
/* ******** Add Contact Window ******** */
/* ************************************ */
@IBAction func openAddContactWindow(sender: AnyObject) {
NSOperationQueue.mainQueue().addOperationWithBlock() {
self.addContactWindowController!.showWindow(self)
}
}
@IBAction func closeAddContactWindow(sender: AnyObject) {
NSOperationQueue.mainQueue().addOperationWithBlock() {
self.addContactWindowController!.window.close();
self.addContactWindowController!.clearFields();
}
}
@IBAction func userDidCompleteAddContact(sender: AnyObject) {
let jid = JID(string: addContactWindowController?.contactJID)
let name = addContactWindowController?.contactName
closeAddContactWindow(sender);
let item = RosterItem(JID: jid, subscriptionState: .None, name: name)
client?.updateRosterWithItem(item);
client?.requestSubscriptionFromJID(jid, message: nil);
}
@IBAction func userDidCancelAddContact(sender: AnyObject) {
closeAddContactWindow(sender);
}
@IBAction func editStatus(sender: AnyObject){
NSOperationQueue.mainQueue().addOperationWithBlock(){
if let menuItem = sender as? NSMenuItem {
NSLog("%@", menuItem.title);
switch menuItem.tag {
case 0:
self.client?.sendPresence(Presence(state: .Available))
case 1:
self.client?.sendPresence(Presence(state: .WantsToChat))
case 2:
self.client?.sendPresence(Presence(state: .Away))
case 3:
self.client?.sendPresence(Presence(state: .DoNotDisturb))
case 4:
self.client?.sendPresence(Presence(state: .ExtendedAway))
case 5:
self.client?.sendPresence(Presence(state: .Unavailable))
default:
break;
}
}
}
}
@IBAction func removeContact(sender: AnyObject){
let possibleSelectedObjects = self.rosterListWindowController?.rosterListController?.selectedObjects
if let theSelectedObjects = possibleSelectedObjects {
for selectedObject in theSelectedObjects {
if let item = selectedObject as? RosterListViewItem {
self.client?.removeItemFromRoster(item.rosterItem)
self.client?.unsubscribeFromJID(item.rosterItem?.jid)
self.client?.cancelSubscriptionFromJID(item.rosterItem?.jid)
}
}
}
}
}
| apache-2.0 | 77a2860b6f474cd124d159b650e7c43e | 39.498534 | 134 | 0.58559 | 6.684414 | false | false | false | false |
kunsy/DYZB | DYZB/DYZB/Classes/Tools/Common.swift | 1 | 324 | //
// Common.swift
// DYZB
//
// Created by Anyuting on 2017/8/5.
// Copyright © 2017年 Anyuting. All rights reserved.
//
import UIKit
let kStatusBarH : CGFloat = 20
let kNavigationBarH : CGFloat = 44
let kTabbarH :CGFloat = 44
let kScreenW = UIScreen.main.bounds.width
let kScreenH = UIScreen.main.bounds.height
| mit | 8163c137f3430b7625da4ba3e0cafc2b | 16.833333 | 52 | 0.713396 | 3.527473 | false | false | false | false |
kar1m/firefox-ios | Client/Frontend/Widgets/AutocompleteTextField.swift | 2 | 7005 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
// This code is loosely based on https://github.com/Antol/APAutocompleteTextField
import UIKit
import Shared
/// Delegate for the text field events. Since AutocompleteTextField owns the UITextFieldDelegate,
/// callers must use this instead.
protocol AutocompleteTextFieldDelegate: class {
func autocompleteTextField(autocompleteTextField: AutocompleteTextField, didEnterText text: String)
func autocompleteTextFieldShouldReturn(autocompleteTextField: AutocompleteTextField) -> Bool
func autocompleteTextFieldShouldClear(autocompleteTextField: AutocompleteTextField) -> Bool
func autocompleteTextFieldDidBeginEditing(autocompleteTextField: AutocompleteTextField)
}
private struct AutocompleteTextFieldUX {
static let HighlightColor = UIColor(rgb: 0xccdded)
}
class AutocompleteTextField: UITextField, UITextFieldDelegate {
var autocompleteDelegate: AutocompleteTextFieldDelegate?
private var completionActive = false
private var canAutocomplete = true
private var enteredTextLength = 0
private var notifyTextChanged: (() -> ())? = nil
override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
private func commonInit() {
super.delegate = self
notifyTextChanged = debounce(0.1, {
if self.editing {
self.autocompleteDelegate?.autocompleteTextField(self, didEnterText: self.text)
}
})
}
func highlightAll() {
if !text.isEmpty {
let attributedString = NSMutableAttributedString(string: text)
attributedString.addAttribute(NSBackgroundColorAttributeName, value: AutocompleteTextFieldUX.HighlightColor, range: NSMakeRange(0, count(text)))
attributedText = attributedString
enteredTextLength = 0
completionActive = true
}
selectedTextRange = textRangeFromPosition(beginningOfDocument, toPosition: beginningOfDocument)
}
/// Commits the completion by setting the text and removing the highlight.
private func applyCompletion() {
if completionActive {
self.attributedText = NSAttributedString(string: text)
completionActive = false
// This is required to notify the SearchLoader that some text has changed and previous
// cached query will get updated.
notifyTextChanged?()
}
}
/// Removes the autocomplete-highlighted text from the field.
private func removeCompletion() {
if completionActive {
let enteredText = text.substringToIndex(advance(text.startIndex, enteredTextLength, text.endIndex))
// Workaround for stuck highlight bug.
if enteredTextLength == 0 {
attributedText = NSAttributedString(string: " ")
}
attributedText = NSAttributedString(string: enteredText)
completionActive = false
}
}
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
if completionActive && string.isEmpty {
// Characters are being deleted, so clear the autocompletion, but don't change the text.
removeCompletion()
return false
}
return true
}
func setAutocompleteSuggestion(suggestion: String?) {
if let suggestion = suggestion where editing && canAutocomplete {
// Check that the length of the entered text is shorter than the length of the suggestion.
// This ensures that completionActive is true only if there are remaining characters to
// suggest (which will suppress the caret).
if suggestion.startsWith(text) && count(text) < count(suggestion) {
let endingString = suggestion.substringFromIndex(advance(suggestion.startIndex, count(self.text)))
let completedAndMarkedString = NSMutableAttributedString(string: suggestion)
completedAndMarkedString.addAttribute(NSBackgroundColorAttributeName, value: AutocompleteTextFieldUX.HighlightColor, range: NSMakeRange(enteredTextLength, count(endingString)))
attributedText = completedAndMarkedString
completionActive = true
}
}
}
func textFieldDidBeginEditing(textField: UITextField) {
autocompleteDelegate?.autocompleteTextFieldDidBeginEditing(self)
}
func textFieldShouldEndEditing(textField: UITextField) -> Bool {
applyCompletion()
return true
}
func textFieldShouldReturn(textField: UITextField) -> Bool {
return autocompleteDelegate?.autocompleteTextFieldShouldReturn(self) ?? true
}
func textFieldShouldClear(textField: UITextField) -> Bool {
removeCompletion()
return autocompleteDelegate?.autocompleteTextFieldShouldClear(self) ?? true
}
override func setMarkedText(markedText: String!, selectedRange: NSRange) {
// Clear the autocompletion if any provisionally inserted text has been
// entered (e.g., a partial composition from a Japanese keyboard).
removeCompletion()
super.setMarkedText(markedText, selectedRange: selectedRange)
}
override func insertText(text: String) {
canAutocomplete = true
removeCompletion()
super.insertText(text)
enteredTextLength = count(self.text)
notifyTextChanged?()
}
override func deleteBackward() {
canAutocomplete = false
removeCompletion()
super.deleteBackward()
enteredTextLength = count(self.text)
autocompleteDelegate?.autocompleteTextField(self, didEnterText: self.text)
}
override func caretRectForPosition(position: UITextPosition!) -> CGRect {
return completionActive ? CGRectZero : super.caretRectForPosition(position)
}
override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
if !completionActive {
super.touchesBegan(touches, withEvent: event)
}
}
override func touchesMoved(touches: Set<NSObject>, withEvent event: UIEvent) {
if !completionActive {
super.touchesMoved(touches, withEvent: event)
}
}
override func touchesEnded(touches: Set<NSObject>, withEvent event: UIEvent) {
if !completionActive {
super.touchesEnded(touches, withEvent: event)
} else {
applyCompletion()
// Set the current position to the end of the text.
selectedTextRange = textRangeFromPosition(endOfDocument, toPosition: endOfDocument)
}
}
}
| mpl-2.0 | d56683539b02329ab31ef96e094add2c | 37.489011 | 192 | 0.68394 | 5.822943 | false | false | false | false |
edx/edx-app-ios | Source/UserProfileManager.swift | 1 | 2913 | //
// UserProfileManager.swift
// edX
//
// Created by Akiva Leffert on 10/28/15.
// Copyright © 2015 edX. All rights reserved.
//
import Foundation
open class UserProfileManager : NSObject {
private let networkManager : NetworkManager
private let session: OEXSession
private let currentUserFeed = BackedFeed<UserProfile>()
private let currentUserUpdateStream = Sink<UserProfile>()
private let cache = LiveObjectCache<Feed<UserProfile>>()
@objc public init(networkManager : NetworkManager, session : OEXSession) {
self.networkManager = networkManager
self.session = session
super.init()
self.currentUserFeed.backingStream.addBackingStream(currentUserUpdateStream)
NotificationCenter.default.oex_addObserver(observer: self, name: NSNotification.Name.OEXSessionEnded.rawValue) { (_, owner, _) -> Void in
owner.sessionChanged()
}
NotificationCenter.default.oex_addObserver(observer: self, name: NSNotification.Name.OEXSessionStarted.rawValue) { (_, owner, _) -> Void in
owner.sessionChanged()
}
self.sessionChanged()
}
open func feedForUser(username : String) -> Feed<UserProfile> {
return self.cache.objectForKey(key: username) {
let request = ProfileAPI.profileRequest(username: username)
return Feed(request: request, manager: self.networkManager)
}
}
private func sessionChanged() {
if let username = self.session.currentUser?.username {
self.currentUserFeed.backWithFeed(feed: self.feedForUser(username: username))
}
else {
self.currentUserFeed.removeBacking()
// clear the stream
self.currentUserUpdateStream.send(NSError.oex_unknownError())
}
if self.session.currentUser == nil {
self.cache.empty()
}
}
// Feed that updates if the current user changes
public func feedForCurrentUser() -> Feed<UserProfile> {
return currentUserFeed
}
public func updateCurrentUserProfile(profile : UserProfile, handler : @escaping (Result<UserProfile>) -> Void) {
guard let request = ProfileAPI.profileUpdateRequest(profile: profile) else {
handler(Result.failure(NSError.oex_unknownNetworkError()))
return
}
networkManager.taskForRequest(request) { [weak self] result -> Void in
if !(result.response?.httpStatusCode.is2xx ?? true) {
handler(Result.failure(NSError.oex_unknownNetworkError()))
return
}
if let data = result.data {
self?.currentUserUpdateStream.send(Success(v: data))
}
handler(result.data.toResult(result.error!))
}
}
}
| apache-2.0 | aa109ae2eecb6b4980fe255d1c0618be | 34.950617 | 147 | 0.625687 | 5.003436 | false | false | false | false |
saiwu-bigkoo/iOS-AlbumView | AlbumView/AlbumView.swift | 1 | 5183 | //
// Albuum.swift
// AlbumView
//
// Created by Sai on 15/3/16.
// Copyright (c) 2015年 OurSound. All rights reserved.
//
import UIKit
@IBDesignable
class AlbumView: UIView,UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout,AlbumViewDelegate{
var indexPath: NSIndexPath!
var collectionView:UICollectionView!
let identifier = "Cell"
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override init(frame: CGRect) {
super.init(frame: frame)
}
override func awakeFromNib() {
super.awakeFromNib()
}
override func layoutSubviews() {
initLayout()
}
func initLayout() {
if(collectionView != nil){ return }
let flowLayout = UICollectionViewFlowLayout()
flowLayout.scrollDirection = UICollectionViewScrollDirection.Horizontal
flowLayout.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0)
flowLayout.minimumInteritemSpacing = 0
flowLayout.minimumLineSpacing = 0
collectionView = UICollectionView(frame: self.frame, collectionViewLayout: flowLayout)
collectionView.backgroundColor = UIColor.clearColor()//背景色为透明
collectionView.pagingEnabled = true//每次滚一页
collectionView.delegate = self
collectionView.dataSource = self
collectionView.showsHorizontalScrollIndicator = false
collectionView.showsVerticalScrollIndicator = false
collectionView.registerClass(AlbumViewCell.self, forCellWithReuseIdentifier: identifier)
self.addSubview(collectionView)
if(indexPath != nil){
collectionView.scrollToItemAtIndexPath(indexPath, atScrollPosition: UICollectionViewScrollPosition.CenteredHorizontally, animated: false)
}
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int{
return 20
}
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize{
return CGSizeMake(self.frame.size.width, self.frame.size.height)
}
// The cell that is returned must be retrieved from a call to -dequeueReusableCellWithReuseIdentifier:forIndexPath:
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell{
let row = indexPath.row
var cell: AlbumViewCell = collectionView.dequeueReusableCellWithReuseIdentifier(identifier, forIndexPath: indexPath) as AlbumViewCell
cell.setData()
cell.delegate = self
return cell
}
func onAlbumItemClick(){
//点击cell回调
}
}
class AlbumViewCell: UICollectionViewCell ,UIScrollViewDelegate{
var vScrollView: UIScrollView!
var startContentOffsetX :CGFloat!
var startContentOffsetY :CGFloat!
var vImage: UIImageView!
var delegate: AlbumViewDelegate!
override init(frame: CGRect) {
super.init(frame: frame)
vImage = UIImageView()
vImage.frame.size = frame.size
vImage.contentMode = UIViewContentMode.ScaleAspectFit
vScrollView = UIScrollView()
vScrollView.frame.size = frame.size
vScrollView.addSubview(vImage)
vScrollView.delegate = self
vScrollView.minimumZoomScale = 0.5
vScrollView.maximumZoomScale = 2
vScrollView.showsVerticalScrollIndicator = false
vScrollView.showsHorizontalScrollIndicator = false
//添加单击
var tapRecognizer = UITapGestureRecognizer(target: self, action: "scrollViewTapped:")
vScrollView.addGestureRecognizer(tapRecognizer)
self.addSubview(vScrollView)
}
func setData() {
vScrollView.zoomScale = 1
vImage.image = UIImage(named:"IMG_1798")
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func viewForZoomingInScrollView(scrollView: UIScrollView) -> UIView? {
return vImage
}
//缩放触发
func scrollViewDidZoom(scrollView: UIScrollView) {
centerScrollViewContents()//缩小图片的时候把图片设置到scrollview中间
}
func centerScrollViewContents() {
let boundsSize = vScrollView.bounds.size
var contentsFrame = vImage.frame
if contentsFrame.size.width < boundsSize.width {
contentsFrame.origin.x = (boundsSize.width - contentsFrame.size.width) / 2.0
} else {
contentsFrame.origin.x = 0.0
}
if contentsFrame.size.height < boundsSize.height {
contentsFrame.origin.y = (boundsSize.height - contentsFrame.size.height) / 2.0
} else {
contentsFrame.origin.y = 0.0
}
vImage.frame = contentsFrame
}
func scrollViewTapped(recognizer: UITapGestureRecognizer) {
//单击回调
if(delegate != nil){
delegate.onAlbumItemClick()
}
}
}
protocol AlbumViewDelegate{
func onAlbumItemClick()
}
| gpl-2.0 | 6e266c434371cd3fff27cc267cbfd583 | 35.669065 | 168 | 0.68452 | 5.498382 | false | false | false | false |
bizz84/SwiftyStoreKit | Sources/SwiftyStoreKit/ProductsInfoController.swift | 1 | 3654 | //
// ProductsInfoController.swift
// SwiftyStoreKit
//
// Copyright (c) 2015 Andrea Bizzotto ([email protected])
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
import StoreKit
protocol InAppProductRequestBuilder: AnyObject {
func request(productIds: Set<String>, callback: @escaping InAppProductRequestCallback) -> InAppProductRequest
}
class InAppProductQueryRequestBuilder: InAppProductRequestBuilder {
func request(productIds: Set<String>, callback: @escaping InAppProductRequestCallback) -> InAppProductRequest {
return InAppProductQueryRequest(productIds: productIds, callback: callback)
}
}
class ProductsInfoController: NSObject {
struct InAppProductQuery {
let request: InAppProductRequest
var completionHandlers: [InAppProductRequestCallback]
}
let inAppProductRequestBuilder: InAppProductRequestBuilder
init(inAppProductRequestBuilder: InAppProductRequestBuilder = InAppProductQueryRequestBuilder()) {
self.inAppProductRequestBuilder = inAppProductRequestBuilder
}
// As we can have multiple inflight requests, we store them in a dictionary by product ids
private var inflightRequests: [Set<String>: InAppProductQuery] = [:]
@discardableResult
func retrieveProductsInfo(_ productIds: Set<String>, completion: @escaping (RetrieveResults) -> Void) -> InAppProductRequest {
if inflightRequests[productIds] == nil {
let request = inAppProductRequestBuilder.request(productIds: productIds) { results in
if let query = self.inflightRequests[productIds] {
for completion in query.completionHandlers {
completion(results)
}
self.inflightRequests[productIds] = nil
} else {
// should not get here, but if it does it seems reasonable to call the outer completion block
completion(results)
}
}
inflightRequests[productIds] = InAppProductQuery(request: request, completionHandlers: [completion])
request.start()
return request
} else {
inflightRequests[productIds]!.completionHandlers.append(completion)
let query = inflightRequests[productIds]!
if query.request.hasCompleted {
query.completionHandlers.forEach {
$0(query.request.cachedResults!)
}
}
return inflightRequests[productIds]!.request
}
}
}
| mit | 15b1afe66464bbea7c0edb4c028f2f6f | 39.6 | 130 | 0.689655 | 5.691589 | false | false | false | false |
jobandtalent/AnimatedTextInput | AnimatedTextInput/Classes/AnimatedTextView.swift | 1 | 3981 | import UIKit
final public class AnimatedTextView: UITextView {
public var textAttributes: [NSAttributedString.Key: Any]? {
didSet {
guard let attributes = textAttributes else { return }
typingAttributes = Dictionary(uniqueKeysWithValues: attributes.lazy.map { ($0.key, $0.value) })
}
}
public override var font: UIFont? {
didSet {
var attributes = typingAttributes
attributes[NSAttributedString.Key.font] = font
textAttributes = Dictionary(uniqueKeysWithValues: attributes.lazy.map { ($0.key, $0.value)})
}
}
public weak var textInputDelegate: TextInputDelegate?
override init(frame: CGRect, textContainer: NSTextContainer?) {
super.init(frame: frame, textContainer: textContainer)
setup()
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
fileprivate func setup() {
contentInset = UIEdgeInsets(top: 0, left: -4, bottom: 0, right: 0)
delegate = self
}
public override func resignFirstResponder() -> Bool {
return super.resignFirstResponder()
}
}
extension AnimatedTextView: TextInput {
public func configureInputView(newInputView: UIView) {
inputView = newInputView
}
public var currentText: String? {
get { return text }
set { self.text = newValue }
}
public var currentSelectedTextRange: UITextRange? {
get { return self.selectedTextRange }
set { self.selectedTextRange = newValue }
}
public var currentBeginningOfDocument: UITextPosition? {
return self.beginningOfDocument
}
public var currentKeyboardAppearance: UIKeyboardAppearance {
get { return self.keyboardAppearance }
set { self.keyboardAppearance = newValue}
}
public var autocorrection: UITextAutocorrectionType {
get { return self.autocorrectionType }
set { self.autocorrectionType = newValue }
}
@available(iOS 10.0, *)
public var currentTextContentType: UITextContentType {
get { return self.textContentType }
set { self.textContentType = newValue }
}
public func changeReturnKeyType(with newReturnKeyType: UIReturnKeyType) {
returnKeyType = newReturnKeyType
}
public func currentPosition(from: UITextPosition, offset: Int) -> UITextPosition? {
return position(from: from, offset: offset)
}
public func changeClearButtonMode(with newClearButtonMode: UITextField.ViewMode) {}
}
extension AnimatedTextView: UITextViewDelegate {
public func textViewDidBeginEditing(_ textView: UITextView) {
textInputDelegate?.textInputDidBeginEditing(textInput: self)
}
public func textViewDidEndEditing(_ textView: UITextView) {
textInputDelegate?.textInputDidEndEditing(textInput: self)
}
public func textViewDidChange(_ textView: UITextView) {
let range = textView.selectedRange
textView.attributedText = NSAttributedString(string: textView.text, attributes: textAttributes)
textView.selectedRange = range
textInputDelegate?.textInputDidChange(textInput: self)
}
public func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
if text == "\n" {
return textInputDelegate?.textInputShouldReturn(textInput: self) ?? true
}
return textInputDelegate?.textInput(textInput: self, shouldChangeCharactersInRange: range, replacementString: text) ?? true
}
public func textViewShouldBeginEditing(_ textView: UITextView) -> Bool {
return textInputDelegate?.textInputShouldBeginEditing(textInput: self) ?? true
}
public func textViewShouldEndEditing(_ textView: UITextView) -> Bool {
return textInputDelegate?.textInputShouldEndEditing(textInput: self) ?? true
}
}
| mit | 004e288b62d55edc022a39ba26884123 | 31.365854 | 131 | 0.67998 | 5.529167 | false | false | false | false |
Crebs/Discrete-Mathematics | DiscreteMathProblems/DiscreteMathProblems/EuclideanAlgorithms.swift | 1 | 3740 | //
// EuclideanAlgorithms.swift
// DiscreteMathProblems
//
// Created by Riley Crebs on 3/4/16.
// Copyright © 2016 Incravo. All rights reserved.
//
import Foundation
extension Int {
/**
Division Algorithm from page 225 of Rosen. The division states that if a
(self in this case) is an interger and d is a postive integer, then there
are unique integers q and r with 0 <= r < d and a = dq + r.
@param a Integer value representing the dividend of the equation.
@param b Integer value representing the divisor of the equation.
@return 2-tuple q as the quotient and r as the remainder.
*/
func divmod(b :Int) -> (q :Int, r :Int) {
var q = 0
var r = abs(self)
while r >= b {
r = r - b
q = q + 1
}
if self < 0 && r > 0 {
r = b - r
q = -(q + 1)
}
return (q, r)
}
/**
Euclidean algorithm (name after Euclid, Greek Mathematician from his book
the Elements) for finding the greatest common divisor of two integers.
Argude to be one of the most useful algorithms and possibly one of the
oldest. (For more information see Rosen Section 3.6 start @ pg 226.)
https://en.wikipedia.org/wiki/Euclid
@param b Integer value to find gcd
@return the gcd of the two integers
*/
func gcd(b :Int) -> Int {
var result = self
if b != 0 {
result = b.gcd(self%b)
}
return result
}
}
struct Euclidean {
/**
origianl source from https://gist.github.com/gpfeiffer/4013925
given non-negative integers a and b, compute
coefficients s and t such that gcd(a, b) == s*a + t*b [aka Bézout's Identity]
reference: https://en.wikipedia.org/wiki/Bézout%27s_identity
Finding gcd(a, b) as a linear combination of a and b with coefficients s
and t. (For more informaitn see Rosen Section 3.6 start @ pg 232.)
Example table for gcd(252, 198) = 18 as a linear combination of 252 and 198
Stack a , b , q, r , s , t , returned tuple (t, s - q * t)
0 252 198 1 54 - - -
1 198 54 3 36 - - -
2 54 36 1 18 - - -
3 36 18 2 0 - - -
4 18 0 - - - - (1 , 0) 18 = 18
3 36 18 2 0 1 0 (0 , 1 - 2*0 = 1) => ( 0, 1 ) 18 = 36*0 + 18*1
2 54 36 1 18 0 1 (1 , 0 - 1 * 1 = -1) => ( 1, -1) 18 = 54*1 + 36*-1
1 198 54 3 36 1 -1 (-1, 1 - 3*-1 = 4) => (-1, 4 ) 18 = 198*-1 + 54*4
0 252 198 1 54 -1 4 (4 , -1 - 1 * 4 = -5) => ( 4, -5) 18 = 252*4 + 198*-5
{ this completes the solution in the form gcd(252, 198) = 18 = 4*252 + -5*198,
where s is 4 and t is -5 }
@param a Integer value to find linear combination of
@param b Integer value to find linear combination of
@return tuple of coefficients s, t for the Bézout's Identity s*a + tb
*/
func linearCombination(a :Int, b :Int) -> (s: Int, t: Int) {
if b == 0 {
return (1, 0)
}
let divmod = a.divmod(b)
let combination = linearCombination(b, b:divmod.r)
return (combination.t, combination.s - divmod.q * combination.t);
}
/**
Uses Extended Euclidean Algorithm (linear combination of a and b) to find an inverse of a mod m.
@param e Int deviden from the form e == 1 mod n.
@param n Int divisor from the form e == 1 mod n.
@return The invers of e mod n.
*/
func inversOf(e:Int, mod n:Int) -> Int {
let tuple = self.linearCombination(e, b: n)
return tuple.s
}
} | mit | 72c5f83936854a4ec0389c68553dd42d | 36.747475 | 101 | 0.539882 | 3.362736 | false | false | false | false |
ricardopereira/PremierKit | Source/Premier+UserDefaults.swift | 1 | 2184 | //
// Premier+UserDefaults.swift
// PremierKit
//
// Created by Ricardo Pereira on 01/10/2019.
// Copyright © 2019 Ricardo Pereira. All rights reserved.
//
import Foundation
@propertyWrapper
public struct UserDefault<T> {
let key: String
let defaultValue: T
let suiteName: String?
public init(_ key: String, defaultValue: T, suiteName: String? = nil) {
self.key = key
self.defaultValue = defaultValue
self.suiteName = suiteName
}
private func userDefaults() -> UserDefaults {
var userDefaults = UserDefaults.standard
if let suiteName = suiteName, let suiteUserDefaults = UserDefaults(suiteName: suiteName) {
userDefaults = suiteUserDefaults
}
return userDefaults
}
public var wrappedValue: T {
get {
return userDefaults().object(forKey: key) as? T ?? defaultValue
}
set {
userDefaults().set(newValue, forKey: key)
}
}
}
@propertyWrapper
public struct OptionalUserDefault<T> {
let key: String
let defaultValue: T?
let suiteName: String?
public init(_ key: String, defaultValue: T? = nil, suiteName: String? = nil) {
self.key = key
self.defaultValue = defaultValue
self.suiteName = suiteName
}
private func userDefaults() -> UserDefaults {
var userDefaults = UserDefaults.standard
if let suiteName = suiteName, let suiteUserDefaults = UserDefaults(suiteName: suiteName) {
userDefaults = suiteUserDefaults
}
return userDefaults
}
public var wrappedValue: T? {
get {
return userDefaults().object(forKey: key) as? T ?? defaultValue
}
set {
userDefaults().set(newValue, forKey: key)
}
}
}
private struct TestUserDefault {
@UserDefault(#function, defaultValue: "")
static var a: String
@UserDefault(#function, defaultValue: "", suiteName: "PremierKitGroup")
static var b: String
@OptionalUserDefault(#function)
static var c: String?
@OptionalUserDefault(#function, suiteName: "PremierKitGroup")
static var d: String?
}
| mit | 7f752f46af3533b77a4342896872a376 | 24.682353 | 98 | 0.632158 | 4.725108 | false | false | false | false |
alblue/swift | stdlib/public/core/Character.swift | 1 | 8024 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
/// A single extended grapheme cluster that approximates a user-perceived
/// character.
///
/// The `Character` type represents a character made up of one or more Unicode
/// scalar values, grouped by a Unicode boundary algorithm. Generally, a
/// `Character` instance matches what the reader of a string will perceive as
/// a single character. Strings are collections of `Character` instances, so
/// the number of visible characters is generally the most natural way to
/// count the length of a string.
///
/// let greeting = "Hello! 🐥"
/// print("Length: \(greeting.count)")
/// // Prints "Length: 8"
///
/// Because each character in a string can be made up of one or more Unicode
/// scalar values, the number of characters in a string may not match the
/// length of the Unicode scalar value representation or the length of the
/// string in a particular binary representation.
///
/// print("Unicode scalar value count: \(greeting.unicodeScalars.count)")
/// // Prints "Unicode scalar value count: 15"
///
/// print("UTF-8 representation count: \(greeting.utf8.count)")
/// // Prints "UTF-8 representation count: 18"
///
/// Every `Character` instance is composed of one or more Unicode scalar values
/// that are grouped together as an *extended grapheme cluster*. The way these
/// scalar values are grouped is defined by a canonical, localized, or
/// otherwise tailored Unicode segmentation algorithm.
///
/// For example, a country's Unicode flag character is made up of two regional
/// indicator scalar values that correspond to that country's ISO 3166-1
/// alpha-2 code. The alpha-2 code for The United States is "US", so its flag
/// character is made up of the Unicode scalar values `"\u{1F1FA}"` (REGIONAL
/// INDICATOR SYMBOL LETTER U) and `"\u{1F1F8}"` (REGIONAL INDICATOR SYMBOL
/// LETTER S). When placed next to each other in a string literal, these two
/// scalar values are combined into a single grapheme cluster, represented by
/// a `Character` instance in Swift.
///
/// let usFlag: Character = "\u{1F1FA}\u{1F1F8}"
/// print(usFlag)
/// // Prints "🇺🇸"
///
/// For more information about the Unicode terms used in this discussion, see
/// the [Unicode.org glossary][glossary]. In particular, this discussion
/// mentions [extended grapheme clusters][clusters] and [Unicode scalar
/// values][scalars].
///
/// [glossary]: http://www.unicode.org/glossary/
/// [clusters]: http://www.unicode.org/glossary/#extended_grapheme_cluster
/// [scalars]: http://www.unicode.org/glossary/#unicode_scalar_value
@_fixed_layout
public struct Character {
@usableFromInline
internal var _str: String
@inlinable @inline(__always)
internal init(unchecked str: String) {
self._str = str
_invariantCheck()
}
}
extension Character {
#if !INTERNAL_CHECKS_ENABLED
@inlinable @inline(__always) internal func _invariantCheck() {}
#else
@usableFromInline @inline(never) @_effects(releasenone)
internal func _invariantCheck() {
_sanityCheck(_str.count == 1)
_sanityCheck(_str._guts.isFastUTF8)
}
#endif // INTERNAL_CHECKS_ENABLED
}
extension Character {
@usableFromInline
typealias UTF8View = String.UTF8View
@inlinable
internal var utf8: UTF8View {
return _str.utf8
}
@usableFromInline
typealias UTF16View = String.UTF16View
@inlinable
internal var utf16: UTF16View {
return _str.utf16
}
public typealias UnicodeScalarView = String.UnicodeScalarView
@inlinable
public var unicodeScalars: UnicodeScalarView {
return _str.unicodeScalars
}
}
extension Character :
_ExpressibleByBuiltinExtendedGraphemeClusterLiteral,
ExpressibleByExtendedGraphemeClusterLiteral
{
/// Creates a character containing the given Unicode scalar value.
///
/// - Parameter content: The Unicode scalar value to convert into a character.
@inlinable @inline(__always)
public init(_ content: Unicode.Scalar) {
self.init(unchecked: String(content))
}
@inlinable @inline(__always)
@_effects(readonly)
public init(_builtinUnicodeScalarLiteral value: Builtin.Int32) {
self.init(Unicode.Scalar(_builtinUnicodeScalarLiteral: value))
}
// Inlining ensures that the whole constructor can be folded away to a single
// integer constant in case of small character literals.
@inlinable @inline(__always)
@_effects(readonly)
public init(
_builtinExtendedGraphemeClusterLiteral start: Builtin.RawPointer,
utf8CodeUnitCount: Builtin.Word,
isASCII: Builtin.Int1
) {
self.init(unchecked: String(
_builtinExtendedGraphemeClusterLiteral: start,
utf8CodeUnitCount: utf8CodeUnitCount,
isASCII: isASCII))
}
/// Creates a character with the specified value.
///
/// Do not call this initalizer directly. It is used by the compiler when
/// you use a string literal to initialize a `Character` instance. For
/// example:
///
/// let oBreve: Character = "o\u{306}"
/// print(oBreve)
/// // Prints "ŏ"
///
/// The assignment to the `oBreve` constant calls this initializer behind the
/// scenes.
@inlinable @inline(__always)
public init(extendedGraphemeClusterLiteral value: Character) {
self.init(unchecked: value._str)
}
/// Creates a character from a single-character string.
///
/// The following example creates a new character from the uppercase version
/// of a string that only holds one character.
///
/// let a = "a"
/// let capitalA = Character(a.uppercased())
///
/// - Parameter s: The single-character string to convert to a `Character`
/// instance. `s` must contain exactly one extended grapheme cluster.
@inlinable @inline(__always)
public init(_ s: String) {
_precondition(!s.isEmpty,
"Can't form a Character from an empty String")
_debugPrecondition(s.index(after: s.startIndex) == s.endIndex,
"Can't form a Character from a String containing more than one extended grapheme cluster")
self.init(unchecked: s)
}
}
extension Character : CustomStringConvertible {
@inlinable
public var description: String {
return _str
}
}
extension Character : LosslessStringConvertible { }
extension Character : CustomDebugStringConvertible {
/// A textual representation of the character, suitable for debugging.
public var debugDescription: String {
return _str.debugDescription
}
}
extension String {
/// Creates a string containing the given character.
///
/// - Parameter c: The character to convert to a string.
@inlinable @inline(__always)
public init(_ c: Character) {
self.init(c._str._guts)
}
}
extension Character : Equatable {
@inlinable @inline(__always)
@_effects(readonly)
public static func == (lhs: Character, rhs: Character) -> Bool {
return lhs._str == rhs._str
}
}
extension Character : Comparable {
@inlinable @inline(__always)
@_effects(readonly)
public static func < (lhs: Character, rhs: Character) -> Bool {
return lhs._str < rhs._str
}
}
extension Character: Hashable {
// not @inlinable (performance)
/// Hashes the essential components of this value by feeding them into the
/// given hasher.
///
/// - Parameter hasher: The hasher to use when combining the components
/// of this instance.
@_effects(releasenone)
public func hash(into hasher: inout Hasher) {
_str.hash(into: &hasher)
}
}
extension Character {
@usableFromInline // @testable
internal var _isSmall: Bool {
return _str._guts.isSmall
}
}
| apache-2.0 | c89501f4a896049a3d34128ed523fb3a | 32.391667 | 96 | 0.690666 | 4.306287 | false | false | false | false |
semiroot/SwiftyConstraints | Tests/SC206HeightTests.swift | 1 | 5264 | //
// SC201Top.swift
// SwiftyConstraints
//
// Created by Hansmartin Geiser on 15/04/17.
// Copyright © 2017 Hansmartin Geiser. All rights reserved.
//
import XCTest
import Foundation
@testable import SwiftyConstraints
class SC206HeightTests: SCTest {
var subview1 = SCView()
var subview2 = SCView()
var superview: SCView?
var swiftyConstraints: SwiftyConstraints?
override func setUp() {
super.setUp()
superview = SCView()
swiftyConstraints = SwiftyConstraints(superview!)
}
override func tearDown() {
super.tearDown()
swiftyConstraints = nil
superview = nil
}
func test00Height() {
guard let swiftyConstraints = swiftyConstraints else { XCTFail("Test setup failure"); return }
swiftyConstraints.attach(subview1)
swiftyConstraints.height(100.5)
guard let constraint1 = SCTAssertConstraintCreated(swiftyConstraints, .height) else { return }
SCTAssertConstraintMatching(constraint1, produceConstraint(subview1, nil, .height, .height, .equal, 1, 100.5))
swiftyConstraints.removeHeight()
SCTAssertConstraintRemoved(swiftyConstraints, constraint1, .height)
}
func test01HeightOf() {
guard let swiftyConstraints = swiftyConstraints, let superview = superview else { XCTFail("Test setup failure"); return }
swiftyConstraints
.attach(subview1)
.attach(subview2)
swiftyConstraints.heightOf(subview1)
guard let constraint1 = SCTAssertConstraintCreated(swiftyConstraints, .height) else { return }
SCTAssertConstraintMatching(constraint1, produceConstraint(subview2, subview1, .height, .height, .equal, 1, 0))
swiftyConstraints.removeHeight()
SCTAssertConstraintRemoved(swiftyConstraints, constraint1, .height)
swiftyConstraints.heightOf(subview1, 0.5)
guard let constraint2 = SCTAssertConstraintCreated(swiftyConstraints, .height) else { return }
SCTAssertConstraintMatching(constraint2, produceConstraint(subview2, subview1, .height, .height, .equal, 0.5, 0))
swiftyConstraints.removeHeight()
SCTAssertConstraintRemoved(swiftyConstraints, constraint2, .height)
swiftyConstraints.heightOf(subview1, 0.75, -10)
guard let constraint3 = SCTAssertConstraintCreated(swiftyConstraints, .height) else { return }
SCTAssertConstraintMatching(constraint3, produceConstraint(subview2, subview1, .height, .height, .equal, 0.75, -10))
swiftyConstraints.removeHeight()
SCTAssertConstraintRemoved(swiftyConstraints, constraint3, .height)
swiftyConstraints.heightOfSuperview()
guard let constraint4 = SCTAssertConstraintCreated(swiftyConstraints, .height) else { return }
SCTAssertConstraintMatching(constraint4, produceConstraint(subview2, superview, .height, .height, .equal, 1, 0))
swiftyConstraints.removeHeight()
SCTAssertConstraintRemoved(swiftyConstraints, constraint4, .height)
swiftyConstraints.heightOfSuperview(0.75, -10)
guard let constraint5 = SCTAssertConstraintCreated(swiftyConstraints, .height) else { return }
SCTAssertConstraintMatching(constraint5, produceConstraint(subview2, superview, .height, .height, .equal, 0.75, -10))
swiftyConstraints.removeHeight()
SCTAssertConstraintRemoved(swiftyConstraints, constraint5, .height)
// invalid reference
let view = SCView()
swiftyConstraints.heightOf(view)
XCTAssertTrue(
superview.constraints.count == 0,
"Constraint should not have been created for inexistent reference"
)
XCTAssertEqual(
swiftyConstraints.previousErrors.last,
SCError.emptyReferenceView,
"Empty reference view did not cause error"
)
}
func test02HeightFrom() {
guard let swiftyConstraints = swiftyConstraints else { XCTFail("Test setup failure"); return }
swiftyConstraints.attach(subview1)
swiftyConstraints.heightFromWidth()
guard let constraint1 = SCTAssertConstraintCreated(swiftyConstraints, .height) else { return }
SCTAssertConstraintMatching(constraint1, produceConstraint(subview1, subview1, .height, .width, .equal, 1, 0))
swiftyConstraints.removeHeight()
SCTAssertConstraintRemoved(swiftyConstraints, constraint1, .height)
swiftyConstraints.heightFromWidth(0.5)
guard let constraint2 = SCTAssertConstraintCreated(swiftyConstraints, .height) else { return }
SCTAssertConstraintMatching(constraint2, produceConstraint(subview1, subview1, .height, .width, .equal, 0.5, 0))
swiftyConstraints.removeHeight()
SCTAssertConstraintRemoved(swiftyConstraints, constraint2, .height)
swiftyConstraints.heightFromWidth(0.5, 10)
guard let constraint3 = SCTAssertConstraintCreated(swiftyConstraints, .height) else { return }
SCTAssertConstraintMatching(constraint3, produceConstraint(subview1, subview1, .height, .width, .equal, 0.5, 10))
swiftyConstraints.removeHeight()
SCTAssertConstraintRemoved(swiftyConstraints, constraint3, .height)
swiftyConstraints.removeHeight()
XCTAssertEqual(
swiftyConstraints.previousErrors.last,
SCError.emptyRemoveConstraint,
"Removing empty constraint did not cause error"
)
}
}
| mit | 2cbfb7fa2b24e1100d1e3659b32d5575 | 35.296552 | 125 | 0.736272 | 5.257742 | false | true | false | false |
jihun-kang/ios_a2big_sdk | A2bigSDK/ArroundData.swift | 1 | 982 | //
// ArroundData.swift
// nextpage
//
// Created by a2big on 2016. 11. 2..
// Copyright © 2016년 a2big. All rights reserved.
//
//import SwiftyJSON
public class ArroundData {
public var no: String!
public var name: String!
public var image_no: String!
public var ment: String!
public var category: String!
public var lat: String!
public var lon: String!
public var address: String!
required public init(json: JSON, baseUrl:String) {
let image = baseUrl+json["image_no"].stringValue.replacingOccurrences(of: "./", with: "")
no = json["surroundings_no"].stringValue
name = json["surroundings_name"].stringValue
image_no = image
ment = json["surroundings_ment"].stringValue
category = json["surroundings_category"].stringValue
lat = json["lat"].stringValue
lon = json["lon"].stringValue
address = json["surroundings_address"].stringValue
}
}
| apache-2.0 | eb0c4e2557a6f55e5320d94a424066ae | 26.194444 | 97 | 0.633299 | 4.130802 | false | false | false | false |
ankitthakur/SHSwiftKit | Sources/iOS/SHFileManager.swift | 1 | 1869 | //
// SHFileManager.swift
// SHSwiftKit
//
// Created by Ankit Thakur on 06/03/16.
// Copyright © 2016 AnkitThakur. All rights reserved.
//
import Foundation
let kSystemDirectory_System = "/System";
let kSystemDirectory_Applications = "/Applications";
let kSystemDirectory_tmp = "/tmp";
let kSystemDirectory_var = "/var";
let kSystemDirectory_Developer_Tools = "/Developer/Tools";
let kSystemDirectory_Developer_Applications = "/Developer/Applications";
let kSystemDirectory_App_Containers = "/private/var/mobile/Containers/Data/Application/";
let kSystemDirectory_Private = "/private";
let kSystemDirectory_Cores = "/cores";
let kSystemDirectory_etc = "/etc";
let kSystemDirectory_home = "/home";
let kSystemDirectory_net = "/net";
let kSystemDirectory_opt = "/opt";
let kSystemDirectory_private = "/private";
let kSystemDirectory_Library = "/Library";
let kSystemDirectory_Network = "/Network";
let kSystemDirectory_usr = "/usr";
let kSystemDirectory_Users = "/Users";
public class SHFileManager {
public class var sharedInstance: SHFileManager {
struct Singleton {
static let instance = SHFileManager()
}
return Singleton.instance
}
public var systemDirectories = [kSystemDirectory_System, kSystemDirectory_Applications,
kSystemDirectory_tmp, kSystemDirectory_var, kSystemDirectory_Developer_Tools, kSystemDirectory_Developer_Applications];
public class func file(filePath:String!) -> (session: SHFile?, error: NSError?){
return SHFile.file(filePath: filePath);
}
public class func numberOfApps() -> ((Int, [String]), NSError?){
return SHFile.installedApps()
}
}
| mit | ed08100b08e188cae53bf2e13a185ef6 | 36.36 | 121 | 0.646146 | 4.600985 | false | false | false | false |
Ehrippura/firefox-ios | Client/Frontend/Browser/OpenInHelper.swift | 9 | 9336 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import PassKit
import WebKit
import SnapKit
import Shared
import XCGLogger
private let log = Logger.browserLogger
struct OpenInViewUX {
static let ViewHeight: CGFloat = 40.0
static let TextFont = UIFont.systemFont(ofSize: 16)
static let TextColor = UIColor(red: 74.0/255.0, green: 144.0/255.0, blue: 226.0/255.0, alpha: 1.0)
static let TextOffset = -15
static let OpenInString = NSLocalizedString("Open in…", comment: "String indicating that the file can be opened in another application on the device")
}
enum MimeType: String {
case PDF = "application/pdf"
case PASS = "application/vnd.apple.pkpass"
}
protocol OpenInHelper {
init?(response: URLResponse)
var openInView: UIView? { get set }
func open()
}
struct OpenIn {
static let helpers: [OpenInHelper.Type] = [OpenPdfInHelper.self, OpenPassBookHelper.self, ShareFileHelper.self]
static func helperForResponse(_ response: URLResponse) -> OpenInHelper? {
return helpers.flatMap { $0.init(response: response) }.first
}
}
class ShareFileHelper: NSObject, OpenInHelper {
var openInView: UIView?
fileprivate var url: URL
var pathExtension: String?
required init?(response: URLResponse) {
guard let MIMEType = response.mimeType, !(MIMEType == MimeType.PASS.rawValue || MIMEType == MimeType.PDF.rawValue),
let responseURL = response.url else { return nil }
url = (responseURL as NSURL) as URL
super.init()
}
func open() {
let alertController = UIAlertController(
title: Strings.OpenInDownloadHelperAlertTitle,
message: Strings.OpenInDownloadHelperAlertMessage,
preferredStyle: UIAlertControllerStyle.alert)
alertController.addAction( UIAlertAction(title: Strings.OpenInDownloadHelperAlertCancel, style: .cancel, handler: nil))
alertController.addAction(UIAlertAction(title: Strings.OpenInDownloadHelperAlertConfirm, style: .default) { (action) in
let objectsToShare = [self.url]
let activityVC = UIActivityViewController(activityItems: objectsToShare, applicationActivities: nil)
if let sourceView = self.openInView, let popoverController = activityVC.popoverPresentationController {
popoverController.sourceView = sourceView
popoverController.sourceRect = CGRect(origin: CGPoint(x: sourceView.bounds.midX, y: sourceView.bounds.maxY), size: .zero)
popoverController.permittedArrowDirections = .up
}
UIApplication.shared.keyWindow?.rootViewController?.present(activityVC, animated: true, completion: nil)
})
UIApplication.shared.keyWindow?.rootViewController?.present(alertController, animated: true, completion: nil)
}
}
class OpenPassBookHelper: NSObject, OpenInHelper {
var openInView: UIView?
fileprivate var url: URL
required init?(response: URLResponse) {
guard let MIMEType = response.mimeType, MIMEType == MimeType.PASS.rawValue && PKAddPassesViewController.canAddPasses(),
let responseURL = response.url else { return nil }
url = responseURL
super.init()
}
func open() {
guard let passData = try? Data(contentsOf: url) else { return }
var error: NSError? = nil
let pass = PKPass(data: passData, error: &error)
if let _ = error {
// display an error
let alertController = UIAlertController(
title: Strings.UnableToAddPassErrorTitle,
message: Strings.UnableToAddPassErrorMessage,
preferredStyle: UIAlertControllerStyle.alert)
alertController.addAction(
UIAlertAction(title: Strings.UnableToAddPassErrorDismiss, style: .cancel) { (action) in
// Do nothing.
})
UIApplication.shared.keyWindow?.rootViewController?.present(alertController, animated: true, completion: nil)
return
}
let passLibrary = PKPassLibrary()
if passLibrary.containsPass(pass) {
UIApplication.shared.openURL(pass.passURL!)
} else {
let addController = PKAddPassesViewController(pass: pass)
UIApplication.shared.keyWindow?.rootViewController?.present(addController, animated: true, completion: nil)
}
}
}
class OpenPdfInHelper: NSObject, OpenInHelper, UIDocumentInteractionControllerDelegate {
fileprivate var url: URL
fileprivate var docController: UIDocumentInteractionController?
fileprivate var openInURL: URL?
lazy var openInView: UIView? = getOpenInView(self)()
lazy var documentDirectory: URL = {
return URL(string: NSTemporaryDirectory())!.appendingPathComponent("pdfs")
}()
fileprivate var filepath: URL?
required init?(response: URLResponse) {
guard let MIMEType = response.mimeType, MIMEType == MimeType.PDF.rawValue && UIApplication.shared.canOpenURL(URL(string: "itms-books:")!),
let responseURL = response.url else { return nil }
url = responseURL
super.init()
setFilePath(response.suggestedFilename ?? url.lastPathComponent )
}
fileprivate func setFilePath(_ suggestedFilename: String) {
var filename = suggestedFilename
let pathExtension = filename.asURL?.pathExtension
if pathExtension == nil {
filename.append(".pdf")
}
filepath = documentDirectory.appendingPathComponent(filename)
}
deinit {
guard let url = openInURL else { return }
let fileManager = FileManager.default
do {
try fileManager.removeItem(at: url)
} catch {
log.error("failed to delete file at \(url): \(error)")
}
}
func getOpenInView() -> OpenInView {
let overlayView = OpenInView()
overlayView.openInButton.addTarget(self, action: #selector(OpenPdfInHelper.open), for: .touchUpInside)
return overlayView
}
func createDocumentControllerForURL(url: URL) {
docController = UIDocumentInteractionController(url: url)
docController?.delegate = self
self.openInURL = url
}
func createLocalCopyOfPDF() {
guard let filePath = filepath else {
log.error("failed to create proper URL")
return
}
if docController == nil {
// if we already have a URL but no document controller, just create the document controller
if let url = openInURL {
createDocumentControllerForURL(url: url)
return
}
let contentsOfFile = try? Data(contentsOf: url)
let fileManager = FileManager.default
do {
try fileManager.createDirectory(atPath: documentDirectory.absoluteString, withIntermediateDirectories: true, attributes: nil)
if fileManager.createFile(atPath: filePath.absoluteString, contents: contentsOfFile, attributes: nil) {
let openInURL = URL(fileURLWithPath: filePath.absoluteString)
createDocumentControllerForURL(url: openInURL)
} else {
log.error("Unable to create local version of PDF file at \(filePath)")
}
} catch {
log.error("Error on creating directory at \(self.documentDirectory)")
}
}
}
func open() {
createLocalCopyOfPDF()
guard let _parentView = self.openInView!.superview, let docController = self.docController else { log.error("view doesn't have a superview so can't open anything"); return }
// iBooks should be installed by default on all devices we care about, so regardless of whether or not there are other pdf-capable
// apps on this device, if we can open in iBooks we can open this PDF
// simulators do not have iBooks so the open in view will not work on the simulator
if UIApplication.shared.canOpenURL(URL(string: "itms-books:")!) {
log.info("iBooks installed: attempting to open pdf")
docController.presentOpenInMenu(from: .zero, in: _parentView, animated: true)
} else {
log.info("iBooks is not installed")
}
}
}
class OpenInView: UIView {
let openInButton = UIButton()
init() {
super.init(frame: .zero)
openInButton.setTitleColor(OpenInViewUX.TextColor, for: UIControlState.normal)
openInButton.setTitle(OpenInViewUX.OpenInString, for: UIControlState.normal)
openInButton.titleLabel?.font = OpenInViewUX.TextFont
openInButton.sizeToFit()
self.addSubview(openInButton)
openInButton.snp.makeConstraints { make in
make.centerY.equalTo(self)
make.height.equalTo(self)
make.trailing.equalTo(self).offset(OpenInViewUX.TextOffset)
}
self.backgroundColor = UIColor.white
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| mpl-2.0 | b265d0bb413f9f46a16f4e4469c27597 | 39.232759 | 181 | 0.660167 | 4.978133 | false | false | false | false |
robzimpulse/mynurzSDK | mynurzSDK/Classes/Realm Model/Degree.swift | 1 | 5108 | //
// Degree.swift
// Pods
//
// Created by Robyarta on 6/5/17.
//
//
import UIKit
import RealmSwift
public class Degree: Object{
public dynamic var id = 0
public dynamic var name = ""
}
public class DegreeController {
public static let sharedInstance = DegreeController()
var realm: Realm?
public func put(id:Int, name:String) {
self.realm = try! Realm()
try! self.realm!.write {
let object = Degree()
object.id = id
object.name = name
self.realm!.add(object)
}
}
public func get() -> Results<Degree> {
self.realm = try! Realm()
return self.realm!.objects(Degree.self)
}
public func get(byId id: Int) -> Degree? {
self.realm = try! Realm()
return self.realm!.objects(Degree.self).filter("id = '\(id)'").first
}
public func get(byName name: String) -> Degree? {
self.realm = try! Realm()
return self.realm!.objects(Degree.self).filter("name = '\(name)'").first
}
public func drop() {
self.realm = try! Realm()
try! self.realm!.write {
self.realm!.delete(self.realm!.objects(Degree.self))
}
}
}
public class DegreeTablePicker: UITableViewController, UISearchResultsUpdating {
var searchController: UISearchController?
open var customFont: UIFont?
open var didSelectClosure: ((Int, String) -> ())?
var filteredData = [Degree]()
var data = [Degree]()
let controller = DegreeController.sharedInstance
override public func viewDidLoad() {
super.viewDidLoad()
self.automaticallyAdjustsScrollViewInsets = false
self.tableView.tableFooterView = UIView()
self.tableView.separatorInset = UIEdgeInsets.zero
self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: "UITableViewCell")
if self.tableView.tableHeaderView == nil {
let mySearchController = UISearchController(searchResultsController: nil)
mySearchController.searchResultsUpdater = self
mySearchController.dimsBackgroundDuringPresentation = false
self.tableView.tableHeaderView = mySearchController.searchBar
searchController = mySearchController
}
self.tableView.reloadData()
self.definesPresentationContext = true
for appenData in controller.get() {
data.append(appenData)
}
}
override public func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func filter(_ searchText: String){
filteredData = [Degree]()
self.data.forEach({ degree in
if degree.name.characters.count > searchText.characters.count {
let result = degree.name.compare(searchText, options: [.caseInsensitive, .diacriticInsensitive], range: searchText.characters.startIndex ..< searchText.characters.endIndex)
if result == .orderedSame {
filteredData.append(degree)
}
}
})
}
public func updateSearchResults(for searchController: UISearchController) {
guard let validText = searchController.searchBar.text else {return}
filter(validText)
self.tableView.reloadData()
}
// MARK: - Table view data source
override public func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
guard let validSearchController = searchController else {return self.data.count}
guard let validText = validSearchController.searchBar.text else {return self.data.count}
if validText.characters.count > 0 {
return self.filteredData.count
}
return self.data.count
}
override public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell(style: .default, reuseIdentifier: "reuseIdentifier")
if let validLabel = cell.textLabel {
if let validSearchController = searchController {
if validSearchController.searchBar.text!.characters.count > 0 {
validLabel.text = filteredData[indexPath.row].name
}else{
validLabel.text = data[indexPath.row].name
}
}
if let validFont = customFont {
validLabel.font = validFont
}
}
return cell
}
override public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
guard let validClosure = self.didSelectClosure else {return}
let selectedData = self.data[indexPath.row]
validClosure(selectedData.id, selectedData.name)
}
}
| mit | a1dbdc154dfaa4f56377a361aac23f88 | 31.535032 | 188 | 0.615309 | 5.304258 | false | false | false | false |
bealex/AwesomeTableAnimationCalculator | Code/Example/ViewControllerCollection.swift | 1 | 14004 | //
// Created by Alexander Babaev on 17.04.16.
// Copyright (c) 2016 Alexander Babaev, LonelyBytes. All rights reserved.
// Sources: https://github.com/bealex/AwesomeTableAnimationCalculator
// License: MIT https://github.com/bealex/AwesomeTableAnimationCalculator/blob/master/LICENSE
//
import UIKit
import AwesomeTableAnimationCalculator
class ViewControllerCollection: UIViewController, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
private let collectionView: UICollectionView = UICollectionView(frame: .zero, collectionViewLayout: UICollectionViewFlowLayout())
private let calculator = ATableAnimationCalculator(cellSectionModel: ACellSectionModelExample())
private var iterationIndex = 1
override var prefersStatusBarHidden: Bool {
return false
}
override func viewDidLoad() {
super.viewDidLoad()
calculator.cellModelComparator = { lhs, rhs in
if lhs.header < rhs.header {
return true
} else {
if lhs.header > rhs.header {
return false
} else {
return lhs.text < rhs.text
// return Int(lhs.text) < Int(rhs.text)
}
}
}
self.view.backgroundColor = .white
collectionView.backgroundColor = .clear
collectionView.frame = self.view.bounds
collectionView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
collectionView.alwaysBounceVertical = true
collectionView.dataSource = self
collectionView.delegate = self
collectionView.register(CellViewCollection.self, forCellWithReuseIdentifier: "generalCell")
collectionView.register(CellHeaderViewCollection.self, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader,
withReuseIdentifier: "generalHeader")
if let flowLayout = collectionView.collectionViewLayout as? UICollectionViewFlowLayout {
flowLayout.scrollDirection = .vertical
flowLayout.itemSize = CGSize(width: self.view.bounds.size.width, height: 25)
flowLayout.estimatedItemSize = flowLayout.itemSize
flowLayout.headerReferenceSize = CGSize(width: self.view.bounds.size.width, height: 20)
}
self.view.addSubview(collectionView)
// runTestFromBundledFile("1.Test_DBZ_small.txt")
// runTestFromBundledFile("2.Test_Assertion (not working).txt")
initBigData()
// initData()
// startTest()
}
func numberOfSections(in collectionView: UICollectionView) -> Int {
return calculator.sectionsCount()
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return calculator.itemsCount(inSection: section)
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "generalCell", for: indexPath)
cell.selectedBackgroundView?.backgroundColor = .lightGray
if let cellView = cell as? CellViewCollection {
cellView.label.text = calculator.item(forIndexPath: indexPath).text
}
return cell
}
func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String,
at indexPath: IndexPath) -> UICollectionReusableView {
let header = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionElementKindSectionHeader,
withReuseIdentifier: "generalHeader", for: indexPath)
if let headerView = header as? CellHeaderViewCollection {
let sectionData = calculator.section(withIndex: indexPath.section)
headerView.label.text = "Header: \(sectionData.title)"
}
return header
}
// MARK: - Helpers
func parseLineToACellExample(_ line: String) -> ACellModelExample {
let result = ACellModelExample(text: "", header: "")
let parts = line
.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
.components(separatedBy: ";")
for part in parts {
if part.contains("Header: ") {
result.header = part
.replacingOccurrences(of: "Header: ", with: "")
.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
.trimmingCharacters(in: CharacterSet(charactersIn: "\""))
} else if part.contains("Text: ") {
result.text = part
.replacingOccurrences(of: "Text: ", with: "")
.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
.trimmingCharacters(in: CharacterSet(charactersIn: "\""))
} else if part.contains("id: ") {
let resultId = part
.replacingOccurrences(of: "id: ", with: "")
.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
.trimmingCharacters(in: CharacterSet(charactersIn: "\""))
result.id = NSUUID(uuidString: resultId)!
}
}
return result
}
func runTestFromBundledFile(fileName: String) {
let filePath = Bundle.main.path(forResource: fileName, ofType: nil)
let blocks = try! String(contentsOfFile: filePath!).components(separatedBy: "\n----------------")
var initialItems = [ACellModelExample]()
var addedItems = [ACellModelExample]()
var updatedItems = [ACellModelExample]()
var deletedItems = [ACellModelExample]()
for block in blocks {
let lines = block.components(separatedBy: "\n")
if block.contains("--- Old items") {
for line in lines {
if !line.contains("---") {
if !line.isEmpty {
initialItems.append(parseLineToACellExample(line))
}
}
}
} else if block.contains("--- Added") {
for line in lines {
if !line.contains("---") {
if !line.isEmpty {
addedItems.append(parseLineToACellExample(line))
}
}
}
} else if block.contains("--- Updated") {
for line in lines {
if !line.contains("---") {
if !line.isEmpty {
updatedItems.append(parseLineToACellExample(line))
}
}
}
} else if block.contains("--- Deleted") {
for line in lines {
if !line.contains("---") {
if !line.isEmpty {
deletedItems.append(parseLineToACellExample(line))
}
}
}
}
}
let _ = try! calculator.setItems(initialItems)
updatedItems.append(contentsOf: addedItems)
dispatch_after_main(1) {
let itemsToAnimate = try! self.calculator.updateItems(addOrUpdate: updatedItems, delete: deletedItems)
itemsToAnimate.applyTo(collectionView: self.collectionView) {}
}
}
// MARK: - Random tests
func initData() {
let _ = try! calculator.setItems([
ACellModelExample(text: "1", header: "A"),
ACellModelExample(text: "2", header: "B"),
ACellModelExample(text: "3", header: "C"),
ACellModelExample(text: "4", header: "D"),
ACellModelExample(text: "5", header: "E")
])
print("--------------------------------------------- NewItems: ")
print(" " + calculator.items.map({ $0.debugDescription }).joined(separator: ",\n "))
print("---------------------------------------------\n\n")
collectionView.reloadData()
}
func initBigData() {
var headers = [
"A",
// "B", "C", "D", "E", "F", "G", "H"
]
var headerIndex = 0
var bigDataSet: [ACellModelExample] = []
for i in 1...100000 {
// bigDataSet.append(ACellModelExample(text: "1", header: headers[headerIndex]))
bigDataSet.append(ACellModelExample(text: "\(i)", header: headers[headerIndex]))
headerIndex += 1
if headerIndex >= headers.count {
headerIndex = 0
}
}
// calculator.cellModelComparator = nil
dispatch_async_main {
Thread.sleep(forTimeInterval: 5)
let _ = try! self.calculator.setItems(bigDataSet)
self.collectionView.reloadData()
}
}
func randomText() -> String {
return "\(arc4random_uniform(20))"
}
func randomHeader() -> String {
let code = UInt32("A".utf8.first!) + arc4random_uniform(UInt32("G".utf8.first!) - UInt32("A".utf8.first!))
return "\(Character(UnicodeScalar(code)!))"
}
func runRandomTest() {
let items = calculator.items
var addedItems = [ACellModelExample]()
var updatedItems = [ACellModelExample]()
var deletedItems = [ACellModelExample]()
let maxItemsInEveryPart = UInt32(5)
// let maxItemsInEveryPart = UInt32(items.count)
let addedCount = arc4random_uniform(maxItemsInEveryPart)
let updatedCount = arc4random_uniform(maxItemsInEveryPart)
let deletedCount = arc4random_uniform(maxItemsInEveryPart)
for _ in 0 ..< addedCount {
addedItems.append(ACellModelExample(text: randomText(), header: randomHeader()))
}
var updatedIndexes = [Int]()
var deletedIndexes = [Int]()
if items.count != 0 {
for _ in 0 ..< updatedCount {
let index = Int(arc4random_uniform(UInt32(items.count)))
if !updatedIndexes.contains(index) {
let updatedItem = ACellModelExample(copy: items[index])
updatedItem.text = randomText()
if (arc4random_uniform(500) > 250) {
updatedItem.header = randomHeader()
}
// updatedItems.append(updatedItem)
updatedIndexes.append(index)
}
}
for _ in 0 ..< deletedCount {
let index = Int(arc4random_uniform(UInt32(items.count)))
if !deletedIndexes.contains(index) {
let item = items[index]
deletedItems.append(ACellModelExample(copy: item))
deletedIndexes.append(index)
}
}
}
print("\n\n\n")
print("--------------------------------------------- Old items (iteration \(iterationIndex)): ")
print(" " + calculator.items.map({ $0.debugDescription }).joined(separator: ",\n "))
print("--------------------------------------------- Added: ")
print(" " + addedItems.map({ $0.debugDescription }).joined(separator: ", \n "))
print("--------------------------------------------- Updated: ")
print(" " + updatedItems.map({ $0.debugDescription }).joined(separator: ",\n "))
print("--------------------------------------------- Deleted: ")
print(" " + deletedItems.map({ $0.debugDescription }).joined(separator: ",\n "))
print("------------------------------------------------------")
updatedItems.append(contentsOf: addedItems)
let itemsToAnimate = try! calculator.updateItems(addOrUpdate: updatedItems, delete: deletedItems)
print("--------------------------------------------- New items: ")
print(" " + calculator.items.map({ $0.debugDescription }).joined(separator: ",\n "))
print("---------------------------------------------\n\n")
itemsToAnimate.applyTo(collectionView: collectionView) {
self.iterationIndex += 1
dispatch_after_main(0.6) {
self.runRandomTest()
}
}
}
func update(addItems addedItems: [ACellModelExample], updateItemsWithIndexes: [Int], deleteItemsWithIndexes: [Int]) {
var updatedItems: [ACellModelExample] = updateItemsWithIndexes.map { index in
let updatedValue = ACellModelExample(copy: self.calculator.item(withIndex: index))
updatedValue.text = "\(Int(updatedValue.text)! - 2)"
// updatedValue.text = updatedValue.text + " •"
return updatedValue
}
let deletedItems = deleteItemsWithIndexes.map { index in
return self.calculator.item(withIndex: index)
}
updatedItems.append(contentsOf: addedItems)
print("\n\n\n--------------------------------------------- Updated: ")
print(" " + updatedItems.map({ $0.debugDescription }).joined(separator: "\n "))
print("--------------------------------------------- Deleted: ")
print(" " + deletedItems.map({ $0.debugDescription }).joined(separator: ",\n "))
print("--------------------------------------------- Changes: ")
let itemsToAnimate = try! calculator.updateItems(addOrUpdate: updatedItems, delete: deletedItems)
print("--------------------------------------------- NewItems: ")
print(" " + calculator.items.map({ $0.debugDescription }).joined(separator: ",\n "))
print("---------------------------------------------\n\n")
itemsToAnimate.applyTo(collectionView: collectionView, completionHandler: nil)
}
func startTest() {
dispatch_after_main(1) {
self.runRandomTest()
}
}
}
| mit | ca211ba99701ffac1ab4d0fbede638db | 38.331461 | 133 | 0.550778 | 5.45037 | false | false | false | false |
farhanpatel/firefox-ios | Providers/PocketFeed.swift | 2 | 5790 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import Alamofire
import Shared
import Deferred
import Storage
private let PocketEnvAPIKey = "PocketEnvironmentAPIKey"
private let PocketGlobalFeed = "https://getpocket.cdn.mozilla.net/v3/firefox/global-recs"
private let MaxCacheAge: Timestamp = OneMinuteInMilliseconds * 60 // 1 hour in milliseconds
private let SupportedLocales = ["en_US", "en_GB", "en_CA", "de_DE", "de_AT", "de_CH"]
/*s
The Pocket class is used to fetch stories from the Pocked API.
Right now this only supports the global feed
For a sample feed item check ClientTests/pocketglobalfeed.json
*/
struct PocketStory {
let url: URL
let title: String
let storyDescription: String
let imageURL: URL
let domain: String
let dedupeURL: URL
static func parseJSON(list: Array<[String: Any]>) -> [PocketStory] {
return list.flatMap({ (storyDict) -> PocketStory? in
guard let urlS = storyDict["url"] as? String, let domain = storyDict["domain"] as? String,
let dedupe_URL = storyDict["dedupe_url"] as? String,
let imageURLS = storyDict["image_src"] as? String,
let title = storyDict["title"] as? String,
let description = storyDict["excerpt"] as? String else {
return nil
}
guard let url = URL(string: urlS), let imageURL = URL(string: imageURLS), let dedupeURL = URL(string: dedupe_URL) else {
return nil
}
return PocketStory(url: url, title: title, storyDescription: description, imageURL: imageURL, domain: domain, dedupeURL: dedupeURL)
})
}
}
private class PocketError: MaybeErrorType {
var description = "Failed to load from API"
}
class Pocket {
private let pocketGlobalFeed: String
static let MoreStoriesURL = URL(string: "https://getpocket.cdn.mozilla.net/explore/trending?src=ff_ios")!
// Allow endPoint to be overriden for testing
init(endPoint: String = PocketGlobalFeed) {
self.pocketGlobalFeed = endPoint
}
lazy fileprivate var alamofire: SessionManager = {
let ua = UserAgent.defaultClientUserAgent
let configuration = URLSessionConfiguration.default
return SessionManager.managerWithUserAgent(ua, configuration: configuration)
}()
private func findCachedResponse(for request: URLRequest) -> [String: Any]? {
let cachedResponse = URLCache.shared.cachedResponse(for: request)
guard let cachedAtTime = cachedResponse?.userInfo?["cache-time"] as? Timestamp, (Date.now() - cachedAtTime) < MaxCacheAge else {
return nil
}
guard let data = cachedResponse?.data, let json = try? JSONSerialization.jsonObject(with: data, options: []) else {
return nil
}
return json as? [String: Any]
}
private func cache(response: HTTPURLResponse?, for request: URLRequest, with data: Data?) {
guard let resp = response, let data = data else {
return
}
let metadata = ["cache-time": Date.now()]
let cachedResp = CachedURLResponse(response: resp, data: data, userInfo: metadata, storagePolicy: .allowed)
URLCache.shared.removeCachedResponse(for: request)
URLCache.shared.storeCachedResponse(cachedResp, for: request)
}
// Fetch items from the global pocket feed
func globalFeed(items: Int = 2) -> Deferred<Array<PocketStory>> {
let deferred = Deferred<Array<PocketStory>>()
guard let request = createGlobalFeedRequest(items: items) else {
deferred.fill([])
return deferred
}
if let cachedResponse = findCachedResponse(for: request), let items = cachedResponse["list"] as? Array<[String: Any]> {
deferred.fill(PocketStory.parseJSON(list: items))
return deferred
}
alamofire.request(request).validate(contentType: ["application/json"]).responseJSON { response in
guard response.error == nil, let result = response.result.value as? [String: Any] else {
return deferred.fill([])
}
self.cache(response: response.response, for: request, with: response.data)
guard let items = result["list"] as? Array<[String: Any]> else {
return deferred.fill([])
}
return deferred.fill(PocketStory.parseJSON(list: items))
}
return deferred
}
// Returns nil if the locale is not supported
static func IslocaleSupported(_ locale: String) -> Bool {
return SupportedLocales.contains(locale)
}
// Create the URL request to query the Pocket API. The max items that the query can return is 20
private func createGlobalFeedRequest(items: Int = 2) -> URLRequest? {
guard items > 0 && items <= 20 else {
return nil
}
let locale = Locale.current.identifier
let pocketLocale = locale.replacingOccurrences(of: "_", with: "-")
var params = [URLQueryItem(name: "count", value: String(items)), URLQueryItem(name: "locale_lang", value: pocketLocale)]
if let consumerKey = Bundle.main.object(forInfoDictionaryKey: PocketEnvAPIKey) as? String {
params.append(URLQueryItem(name: "consumer_key", value: consumerKey))
}
guard let feedURL = URL(string: pocketGlobalFeed)?.withQueryParams(params) else {
return nil
}
return URLRequest(url: feedURL, cachePolicy: URLRequest.CachePolicy.reloadIgnoringCacheData, timeoutInterval: 5)
}
}
| mpl-2.0 | 6cc0c909e67a0a6ecf8cdf03affbe40c | 40.06383 | 143 | 0.652677 | 4.562648 | false | false | false | false |
xingerdayu/dayu | dayu/StringUtil.swift | 1 | 3011 | //
// StringUtil.swift
// Community
//
// Created by Xinger on 15/3/19.
// Copyright (c) 2015年 Xinger. All rights reserved.
//
import Foundation
class StringUtil {
class func getValue(value:NSNumber?) -> NSNumber {
if value != nil {
return value!
}
return NSNumber(int: 0)
}
class func getFloatValue(value:Float?) -> String {
if value != nil {
return StringUtil.formatFloat(value! * 100)
}
return "0"
}
class func getStringValue(value:String?) -> String {
if value != nil {
return value!
}
return ""
}
//格式化时间
class func formatTime(time:Int64) -> String {
let date = NSDate(timeIntervalSince1970: Double(time))
let format = NSDateFormatter()
format.dateFormat = "yyyy-MM-dd HH:mm:ss"
let stringDate = format.stringFromDate(date)
return stringDate
}
class func formatFloat(f:Float) -> String {
var str = NSString(format: "%.02lf", f)
if str.length > 5 {
str = str.substringToIndex(5)
}
return str as String
}
//格式化时间
class func fitFormatTime(time:Int64) -> String {
let current = Int64(NSDate().timeIntervalSince1970)
let pTime = (current - time) / 60
if pTime < 0 {
return "刚刚"
} else if pTime < 60 {
return "\(pTime)分钟前"
} else if pTime / 60 < 24 {
return "\(pTime / 60)小时前"
} else {
return formatTime(time)
}
}
class func colorWithHexString (hex:String)-> UIColor {
var cString:String = hex.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()).uppercaseString
if (cString.hasPrefix("#")) {
cString = cString.substringFromIndex(cString.startIndex.advancedBy(1))
}
if (cString.lengthOfBytesUsingEncoding(NSUTF8StringEncoding) != 6) {
return UIColor.grayColor()
}
let rString = cString.substringToIndex(cString.startIndex.advancedBy(2))
let gString = cString.substringFromIndex(cString.startIndex.advancedBy(2)).substringToIndex(cString.startIndex.advancedBy(2))
let bString = cString.substringFromIndex(cString.startIndex.advancedBy(4)).substringToIndex(cString.startIndex.advancedBy(2))
var r:CUnsignedInt = 0, g:CUnsignedInt = 0, b:CUnsignedInt = 0;
NSScanner(string: rString).scanHexInt(&r)
NSScanner(string: gString).scanHexInt(&g)
NSScanner(string: bString).scanHexInt(&b)
//NSScanner.scannerWithString(rString).scanHexInt(&r)
//NSScanner.scannerWithString(gString).scanHexInt(&g)
//NSScanner.scannerWithString(bString).scanHexInt(&b)
return UIColor(red: CGFloat(r) / 255.0, green:CGFloat(g) / 255.0, blue:CGFloat(b) / 255.0, alpha:CGFloat(1))
}
} | bsd-3-clause | 25eae5f230d108ce6f783dc708ed6e3c | 31.326087 | 133 | 0.60074 | 4.457271 | false | false | false | false |
Estimote/iOS-SDK | Examples/swift/LoyaltyStore/LoyaltyStore/Models/Customer/Customer.swift | 1 | 1940 | //
// Please report any problems with this app template to [email protected]
//
import UIKit.UIImage
enum Update: String {
case Points = "UpdatePoints"
case Default = "ReloadTableView"
}
/// Store customer conforming to customer protocol which implements all the necessairy functionality
class Customer: Displayable, Identifiable, Gamifiable {
/// Store customer has an identifier
var identifier : String?
/// Store customer has an avatar
var avatar : UIImage? {
didSet { self.updateCustomerInView(updates: [.Default]) }
}
/// Store customer has a display name
var name : String? {
didSet { self.updateCustomerInView(updates: [.Default]) }
}
/// Store customer has points
var points : Int? {
didSet { self.updateCustomerInView(updates: [.Default, .Points]) }
}
/**
Initialise a new customer
- parameter identifier: unique identifier for the customer
- returns: Customer object with identifier, avatar, display name and points
*/
required init(identifier: String) {
self.identifier = identifier
/**
* async retrieve avatar from cache or Firebase
* -> reload view
*/
self.retrieveAvatar { _avatar in
self.avatar = _avatar
}
/**
* async retrive display name from cache or Firebase
* -> reload view
*/
self.retrieveDisplayName { _name in
self.name = _name
}
/**
* aync syncronise points from Firebase
* -> reload view
*/
self.syncPoints { _points in
self.points = _points
}
}
func updateCustomerInView(updates: [Update]) {
let notificationCenter = NotificationCenter.default
for update in updates {
// post notification to reload collection view
notificationCenter.post(name: Notification.Name(rawValue: update.rawValue), object: (update == .Points) ? self.points : nil)
}
}
}
| mit | ac953f1c7a72ac0e232b323da735c8d6 | 24.194805 | 130 | 0.647423 | 4.522145 | false | false | false | false |
overtake/TelegramSwift | Telegram-Mac/ChatInputSendAsView.swift | 1 | 3945 | //
// ChatInputSendAsView.swift
// Telegram
//
// Created by Mikhail Filimonov on 12.11.2021.
// Copyright © 2021 Telegram. All rights reserved.
//
import Foundation
import TGUIKit
import SwiftSignalKit
import TelegramCore
import Postbox
final class ChatInputSendAsView : Control {
private weak var chatInteraction: ChatInteraction?
private var peers: [SendAsPeer]?
private var currentPeerId: PeerId?
private var avatar: AvatarControl?
required init(frame frameRect: NSRect) {
super.init(frame: frameRect)
self.scaleOnClick = true
self.contextMenu = { [weak self] in
let menu = ContextMenu(betterInside: true)
guard let list = self?.peers else {
return nil
}
guard let chatInteraction = self?.chatInteraction else {
return nil
}
let currentPeerId = self?.currentPeerId
let context = chatInteraction.context
var items:[ContextMenuItem] = []
var peers = list
if let index = peers.firstIndex(where: { $0.peer.id == currentPeerId }) {
peers.move(at: index, to: 0)
}
let header = ContextMenuItem(strings().chatSendAsHeader)
header.isEnabled = false
items.append(header)
for (i, peer) in peers.enumerated() {
items.append(ContextSendAsMenuItem(peer: peer, context: context, isSelected: i == 0, handler: { [weak self] in
self?.toggleSendAs(peer, context: context)
}))
}
for item in items {
menu.addItem(item)
}
return menu
}
}
private func toggleSendAs(_ peer: SendAsPeer, context: AccountContext) {
if peer.isPremiumRequired && !context.isPremium {
showModal(with: PremiumBoardingController(context: context, source: .send_as), for: context.window)
} else {
self.chatInteraction?.toggleSendAs(peer.peer.id)
}
}
override func layout() {
super.layout()
guard let avatar = self.avatar else {
return
}
avatar.centerY(x: frame.width - avatar.frame.width)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
var first: Bool = true
func update(_ peers: [SendAsPeer], currentPeerId: PeerId, chatInteraction: ChatInteraction, animated: Bool) {
let currentIsUpdated = self.currentPeerId != currentPeerId
self.currentPeerId = currentPeerId
self.peers = peers
self.chatInteraction = chatInteraction
let currentPeer = peers.first(where: { $0.peer.id == currentPeerId })
if currentIsUpdated {
if let view = self.avatar {
if animated {
view.layer?.animateScaleSpring(from: 1, to: 0.1, duration: 0.3, removeOnCompletion: false, completion: { [weak view] _ in
view?.removeFromSuperview()
})
} else {
view.removeFromSuperview()
}
}
let avatar = AvatarControl(font: .avatar(18))
avatar.frame = NSMakeRect(0, 0, 30, 30)
avatar.userInteractionEnabled = false
avatar.setPeer(account: chatInteraction.context.account, peer: currentPeer?.peer)
self.addSubview(avatar)
avatar.centerY(x: frame.width - avatar.frame.width)
self.avatar = avatar
if animated, !first {
avatar.layer?.animateScaleSpring(from: 0.1, to: 1.0, duration: 0.3)
}
first = false
}
}
}
| gpl-2.0 | 7f8d53499ba3cb30fb97f736e190bbc1 | 31.595041 | 141 | 0.550203 | 5.043478 | false | false | false | false |
AcroMace/DreamBig | DreamBig/Drawing/DrawingViewController.swift | 1 | 4021 | //
// DrawingViewController.swift
// DreamBig
//
// Created by Andy Cho on 2017-06-13.
// Copyright © 2017 AcroMace. All rights reserved.
//
import UIKit
class DrawingViewController: UIViewController, DrawingImageViewDelegate {
let emojiBaseSize: CGFloat = 12 // Base font size for the emoji
var drawingModel: DrawingModel? // Model passed to the AR view controller after drawing
let emojiPalettePopover = EmojiPalettePopover()
@IBOutlet weak var drawingImageView: DrawingImageView!
@IBOutlet weak var emojiButton: UIBarButtonItem!
override func viewDidLoad() {
super.viewDidLoad()
emojiButton.title = emojiPalettePopover.selectedEmoji
emojiPalettePopover.delegate = self
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
// We need to ensure that the drawingImageView has been expanded
// before we can get its size
guard drawingModel == nil else { return }
drawingImageView.delegate = self
drawingModel = DrawingModel(canvasSize: drawingImageView.frame.size)
}
func drewEmoji(at point: CGPoint, with size: CGFloat) {
DispatchQueue.main.async { // Don't block on the touch update calls
guard let point = self.createDrawingPoint(at: point, with: size) else {
return
}
self.drawingModel?.addPoint(point: point)
self.view.addSubview(self.convertDrawingPointToLabel(drawingPoint: point))
}
}
@IBAction func didPressEmojisButton(_ sender: Any) {
guard let emojiPaletteContainer = emojiPalettePopover.viewController else {
return
}
present(emojiPaletteContainer, animated: true, completion: nil)
emojiPaletteContainer.popoverPresentationController?.barButtonItem = emojiButton
}
@IBAction func didPressDoneButton(_ sender: Any) {
let cameraStoryboard = UIStoryboard(name: CameraViewController.storyboard, bundle: Bundle(for: CameraViewController.self))
guard let cameraViewController = cameraStoryboard.instantiateInitialViewController() as? CameraViewController else {
print("ERROR: Could not create the CameraViewController")
return
}
cameraViewController.drawingModel = drawingModel
navigationController?.pushViewController(cameraViewController, animated: true)
}
@IBAction func didPressClearButton(_ sender: Any) {
drawingModel?.clearPoints()
for subview in view.subviews {
if let label = subview as? UILabel {
label.removeFromSuperview()
}
}
}
// MARK: - Private methods
private func createDrawingPoint(at point: CGPoint, with size: CGFloat) -> DrawingPoint? {
guard let emoji = emojiPalettePopover.selectedEmoji else {
return nil
}
return DrawingPoint(x: point.x, y: point.y, size: size, emoji: emoji)
}
private func convertDrawingPointToLabel(drawingPoint: DrawingPoint) -> UILabel {
let emoji = UILabel(frame: CGRect.zero)
emoji.text = drawingPoint.emoji
emoji.font = UIFont.systemFont(ofSize: emojiBaseSize * drawingPoint.size)
emoji.sizeToFit()
// Calculate the coordinates of the emoji so that it's centred underneath the finger or pencil
let x = drawingPoint.x - emoji.frame.size.width / 2
let navigationBarHeight = navigationController?.navigationBar.frame.size.height ?? 0
let statusBarHeight = UIApplication.shared.statusBarFrame.size.height
let y = drawingPoint.y - emoji.frame.size.height / 2 + navigationBarHeight + statusBarHeight
emoji.frame.origin = CGPoint(x: x, y: y)
return emoji
}
}
// MARK: - EmojiPalettePopoverDelegate
extension DrawingViewController: EmojiPalettePopoverDelegate {
func didSelectEmoji(emoji: String) {
emojiButton.title = emoji
dismiss(animated: true, completion: nil)
}
}
| mit | e6c5c8173820009c53200b474bc6183a | 35.880734 | 130 | 0.684328 | 5.075758 | false | false | false | false |
easyui/EZPlayer | EZPlayer/EZPlayerUtils.swift | 1 | 6290 | //
// EZPlayerUtils.swift
// EZPlayer
//
// Created by yangjun zhu on 2016/12/28.
// Copyright © 2016年 yangjun zhu. All rights reserved.
//
import UIKit
import MediaPlayer
// MARK: - 全局变量
/// 动画时间
public var EZPlayerAnimatedDuration = 0.3
public let EZPlayerErrorDomain = "EZPlayerErrorDomain"
// MARK: - 全局方法
/// 全局log
///
/// - Parameters:
/// - message: log信息
/// - file: 打印log所属的文件
/// - method: 打印log所属的方法
/// - line: 打印log所在的行
public func printLog<T>(_ message: T...,
file: String = #file,
method: String = #function,
line: Int = #line)
{
if EZPlayer.showLog {
print("EZPlayer Log-->\((file as NSString).lastPathComponent)[\(line)], \(method): \(message)")
}
}
public func toNSError(code: Int, userInfo dict: [String : Any]? = nil) -> NSError
{
return NSError(domain: EZPlayerErrorDomain, code: code, userInfo: dict)
}
// MARK: -
/// EZPlayerState的相等判断
///
/// - Parameters:
/// - lhs: 左值
/// - rhs: 右值
/// - Returns: 比较结果
public func ==(lhs: EZPlayerState, rhs: EZPlayerState) -> Bool {
switch (lhs, rhs) {
case (.unknown, .unknown): return true
case (.readyToPlay, .readyToPlay): return true
case (.buffering, .buffering): return true
case (.bufferFinished, .bufferFinished): return true
case (.playing, .playing): return true
case (.seekingForward, .seekingForward): return true
case (.seekingBackward, .seekingBackward): return true
case (.pause, .pause): return true
case (.stopped, .stopped): return true
case (.error(let a), .error(let b)) where a == b: return true
default: return false
}
}
/// EZPlayerState的不相等判断
///
/// - Parameters:
/// - lhs: 左值
/// - rhs: 右值
/// - Returns: 比较结果
public func !=(lhs: EZPlayerState, rhs: EZPlayerState) -> Bool {
return !(lhs == rhs)
}
// MARK: - 辅助方法
public class EZPlayerUtils{
/// system volume ui
public static let systemVolumeSlider : UISlider = {
let volumeView = MPVolumeView()
volumeView.showsVolumeSlider = true//显示系统音量条
volumeView.showsRouteButton = false//去掉提示框
var returnSlider : UISlider!
for view in volumeView.subviews {
if let slider = view as? UISlider {
returnSlider = slider
break
}
}
return returnSlider
}()
/// fotmat time
///
/// - Parameters:
/// - position: video current position
/// - duration: video duration
/// - Returns: formated time string
public static func formatTime( position: TimeInterval,duration:TimeInterval) -> String{
guard !position.isNaN && !duration.isNaN else{
return ""
}
let positionHours = (Int(position) / 3600) % 60
let positionMinutes = (Int(position) / 60) % 60
let positionSeconds = Int(position) % 60;
let durationHours = (Int(duration) / 3600) % 60
let durationMinutes = (Int(duration) / 60) % 60
let durationSeconds = Int(duration) % 60
if(durationHours == 0){
return String(format: "%02d:%02d/%02d:%02d",positionMinutes,positionSeconds,durationMinutes,durationSeconds)
}
return String(format: "%02d:%02d:%02d/%02d:%02d:%02d",positionHours,positionMinutes,positionSeconds,durationHours,durationMinutes,durationSeconds)
}
/// get current top viewController
///
/// - Returns: current top viewController
public static func activityViewController() -> UIViewController?{
var result: UIViewController? = nil
guard var window = UIApplication.shared.keyWindow else {
return nil
}
if window.windowLevel != UIWindow.Level.normal {
let windows = UIApplication.shared.windows
for tmpWin in windows {
if tmpWin.windowLevel == UIWindow.Level.normal {
window = tmpWin
break
}
}
}
result = window.rootViewController
while let presentedVC = result?.presentedViewController {
result = presentedVC
}
if result is UITabBarController {
result = (result as? UITabBarController)?.selectedViewController
}
while result is UINavigationController && (result as? UINavigationController)?.topViewController != nil{
result = (result as? UINavigationController)?.topViewController
}
return result
}
/// get viewController from view
///
/// - Parameter view: view
/// - Returns: viewController
public static func viewController(from view: UIView) -> UIViewController? {
var responder = view as UIResponder
while let nextResponder = responder.next {
if (responder is UIViewController) {
return (responder as! UIViewController)
}
responder = nextResponder
}
return nil
}
/// is iPhone X
public static var hasSafeArea: Bool{
if #available(iOS 13.0, *){
return UIApplication.shared.windows.filter {$0.isKeyWindow}.first?.safeAreaInsets.bottom ?? 0 > 0
}else if #available(iOS 11.0, *) {
return UIApplication.shared.delegate?.window??.safeAreaInsets.bottom ?? 0 > 0
}
return false
}
/// is iPhone X
public static var statusBarHeight: CGFloat{
return EZPlayerUtils.hasSafeArea ? 44 : 20
}
public static func floatModelSupported(_ player :EZPlayer) -> EZPlayerFloatMode{
if player.floatMode == .auto {
if UIDevice.current.userInterfaceIdiom == .pad {
if #available(iOS 9.0, *) {
return .system
}
return .window
}else if UIDevice.current.userInterfaceIdiom == .phone {
if #available(iOS 14.0, *) {
return .system
}
return .window
}
return .none
}
return player.floatMode
}
}
| mit | b095fd4f4e8188719673127621d68db5 | 29.341584 | 154 | 0.589003 | 4.503306 | false | false | false | false |
p-rothen/PRViews | PRViews/DotsMenu.swift | 1 | 4776 | //
// DotsMenu.swift
// Doctor Cloud
//
// Created by Pedro on 03-01-17.
// Copyright © 2017 Pedro Rothen. All rights reserved.
//
import UIKit
//private let sharedInstance = DotsMenu(frame: CGRect.zero)
public protocol DotsMenuDelegate {
func didSelectItem(index: Int)
}
public class DotsMenu: UIView, UITableViewDelegate, UITableViewDataSource {
let cellIdentifier = "cell"
var tableView: UITableView!
var backgroundView: UIView!
var menuView: UIView!
var initialFrame: CGRect!
var delegate: DotsMenuDelegate?
var menuRows:[String]
var x:CGFloat?
var y:CGFloat?
var tapHanlder: (Int -> Void)?
var width:CGFloat = 150
public init(x: CGFloat?, y: CGFloat?, width: CGFloat? = nil, menuRows: [String], tapHanlder:(Int -> Void)? = nil) {
self.x = x
self.y = y
self.menuRows = menuRows
self.tapHanlder = tapHanlder
if let width = width {
self.width = width
}
super.init(frame: CGRect.zero)
self.setup()
}
public required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func setup() {
let window = UIApplication.sharedApplication().keyWindow!
self.frame = window.frame
let x = self.x ?? window.frame.maxX - (self.width + 20)
var y = self.y ?? CGFloat(20)
let width = self.width ?? CGFloat(self.width)
//let height = window.bounds.height * 0.7
let height = 44 * CGFloat(self.menuRows.count)
let maxY = y + height
if maxY > window.frame.maxY {
y = window.frame.maxY - height
}
self.initialFrame = CGRectMake(x, y, width, 0)
let targetFrame = CGRectMake(x, y, width, height)
self.menuView = UIView(frame: initialFrame)
self.menuView.backgroundColor = UIColor(red:0.96, green:0.96, blue:0.98, alpha:1.0)
self.menuView.clipsToBounds = true
self.tableView = UITableView(frame: CGRectMake(0, 0, width, 0), style: .Plain)
//let nib = UINib(nibName: "EntryViewCell", bundle: nil)
//self.tableView.registerNib(nib, forCellReuseIdentifier: self.cellIdentifier)
self.tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: self.cellIdentifier)
self.tableView.delegate = self
self.tableView.dataSource = self
self.tableView.separatorStyle = .None
//self.tableView.allowsSelection = false
self.tableView.bounces = false
self.menuView.addSubview(self.tableView)
ViewUtils.addLightShadow(self.menuView)
self.backgroundView = UIView(frame: window.bounds)
self.backgroundView.backgroundColor = .blackColor()
self.backgroundView.alpha = 0.0
self.addSubview(self.backgroundView)
self.addSubview(self.menuView)
window.addSubview(self)
UIView.animateWithDuration(0.3, animations: {
self.menuView.frame = targetFrame
self.tableView.frame = CGRectMake(0, 0, width, height)
self.backgroundView.alpha = 0.2
})
backgroundView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(self.closeMenu)))
}
func closeMenu() {
UIView.animateWithDuration(0.3, animations: {
self.menuView.frame = self.initialFrame
self.tableView.frame = CGRectMake(0, 0, self.initialFrame.width, 0)
self.backgroundView.alpha = 0
}, completion: { _ in
self.removeFromSuperview()
})
}
public func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(self.cellIdentifier, forIndexPath: indexPath)
cell.textLabel?.font = UIFont.boldSystemFontOfSize(14)
cell.textLabel?.textColor = UIColor(red:0.37, green:0.37, blue:0.36, alpha:1.0)
cell.textLabel?.text = self.menuRows[indexPath.row]
//cell.selectionStyle = .None
return cell
}
public func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.menuRows.count
}
public func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
//tableView.deselectRowAtIndexPath(indexPath, animated: false)
if let handler = self.tapHanlder {
self.closeMenu()
handler(indexPath.row)
} else {
self.delegate?.didSelectItem(indexPath.row)
self.closeMenu()
}
}
} | mit | 03d048d9a401a7b55df6b639ee2cd994 | 34.377778 | 119 | 0.626597 | 4.547619 | false | false | false | false |
2345Team/Design-Pattern-For-Swift | 15.IteratorPattern/15.IteratorPattern/ViewController.swift | 1 | 1104 | //
// ViewController.swift
// 15.IteratorPattern
//
// Created by Merlin on 16/5/18.
// Copyright © 2016年 2345. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let titleArray:NSArray = ["apple","banana","orange"]
for titleStr in titleArray {
print(titleStr)
}
let enumerator:NSEnumerator = titleArray.objectEnumerator()
while let string=enumerator.nextObject() {
print(string)
}
let concreteSet = ConcreteSet()
concreteSet.insertItem("apple")
concreteSet.insertItem("banana")
concreteSet.insertItem("orange")
print("Count is :\(concreteSet.getCount())")
let iterator:ConcreteIterator = ConcreteIterator.init(mySet: concreteSet)
while !iterator.isFinish() {
print(iterator.currentItem())
iterator.nextItem()
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
| mit | 24071cf96612024530fc17b5e8616c97 | 23.466667 | 81 | 0.608538 | 5.027397 | false | false | false | false |
yanagiba/swift-transform | Sources/Transform/Tokenizer.swift | 1 | 100325 | /*
Copyright 2017-2019 Ryuichi Laboratories and the Yanagiba project contributors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import AST
// NOTE: This class contains all the tokenizations of node elements in one unique file insetad of
// separating them into extensions to allow subclasses (implemented by other libraries using this
// one) to subclass and override its behavior.
// In Swift4, methods declared in extensions can not be overriden yet. Move this back into
// extensions when the compiler allows it in future versions
open class Tokenizer {
public let options: [String: Any]?
open var indentation: String {
return " "
}
public init(options: [String: Any]? = nil) {
self.options = options
}
// MARK: - Utils
open func indent(_ tokens: [Token]) -> [Token] {
guard let node = tokens.first?.node else { return tokens }
return tokens.reduce([node.newToken(.indentation, indentation)]) { (result, token) -> [Token] in
return result + token + (token.kind == .linebreak ? token.node?.newToken(.indentation, indentation) : nil)
}
}
// MARK: - Attributes
open func tokenize(_ attributes: Attributes, node: ASTNode) -> [Token] {
return attributes.map { tokenize($0, node: node) }.joined(token: node.newToken(.space, " ", node))
}
open func tokenize(_ attribute: Attribute, node: ASTNode) -> [Token] {
return
attribute.newToken(.symbol, "@", node) +
attribute.newToken(.identifier, attribute.name, node) +
attribute.argumentClause.map { tokenize($0, node: node) }
}
open func tokenize(_ argument: Attribute.ArgumentClause, node: ASTNode) -> [Token] {
return
argument.newToken(.startOfScope, "(", node) +
tokenize(argument.balancedTokens, node: node) +
argument.newToken(.endOfScope, ")", node)
}
open func tokenize(_ tokens: [Attribute.ArgumentClause.BalancedToken], node: ASTNode) -> [Token] {
return tokens.map { tokenize($0, node: node) }.joined()
}
open func tokenize(_ token: Attribute.ArgumentClause.BalancedToken, node: ASTNode) -> [Token] {
switch token {
case .token(let tokenString):
return [token.newToken(.identifier, tokenString, node)]
case .parenthesis(let tokens):
return token.newToken(.startOfScope, "(", node) +
tokenize(tokens, node: node) + token.newToken(.endOfScope, ")", node)
case .square(let tokens):
return token.newToken(.startOfScope, "[", node) +
tokenize(tokens, node: node) + token.newToken(.endOfScope, "]", node)
case .brace(let tokens):
return token.newToken(.startOfScope, "{", node) +
tokenize(tokens, node: node) + token.newToken(.endOfScope, "}", node)
}
}
// MARK: - Declarations
open func tokenize(_ declaration: Declaration) -> [Token] { // swift-lint:suppress(high_cyclomatic_complexity)
switch declaration {
case let decl as ClassDeclaration:
return tokenize(decl)
case let decl as ConstantDeclaration:
return tokenize(decl)
case let decl as DeinitializerDeclaration:
return tokenize(decl)
case let decl as EnumDeclaration:
return tokenize(decl)
case let decl as ExtensionDeclaration:
return tokenize(decl)
case let decl as FunctionDeclaration:
return tokenize(decl)
case let decl as ImportDeclaration:
return tokenize(decl)
case let decl as InitializerDeclaration:
return tokenize(decl)
case let decl as OperatorDeclaration:
return tokenize(decl)
case let decl as PrecedenceGroupDeclaration:
return tokenize(decl)
case let decl as ProtocolDeclaration:
return tokenize(decl)
case let decl as StructDeclaration:
return tokenize(decl)
case let decl as SubscriptDeclaration:
return tokenize(decl)
case let decl as TypealiasDeclaration:
return tokenize(decl)
case let decl as VariableDeclaration:
return tokenize(decl)
default:
return [Token(origin: declaration as? ASTTokenizable,
node: declaration as? ASTNode,
kind: .identifier,
value: declaration.textDescription)]
}
}
open func tokenize(_ topLevelDeclaration: TopLevelDeclaration) -> [Token] {
return topLevelDeclaration.statements.map(tokenize)
.joined(token: topLevelDeclaration.newToken(.linebreak, "\n")) +
topLevelDeclaration.newToken(.linebreak, "\n")
}
open func tokenize(_ codeBlock: CodeBlock) -> [Token] {
if codeBlock.statements.isEmpty {
return [codeBlock.newToken(.startOfScope, "{"), codeBlock.newToken(.endOfScope, "}")]
}
let lineBreakToken = codeBlock.newToken(.linebreak, "\n")
return [
[codeBlock.newToken(.startOfScope, "{")],
indent(codeBlock.statements.map(tokenize).joined(token: lineBreakToken)),
[codeBlock.newToken(.endOfScope, "}")]
].joined(token: lineBreakToken)
}
open func tokenize(_ block: GetterSetterBlock.GetterClause, node: ASTNode) -> [Token] {
return [
tokenize(block.attributes, node: node),
block.mutationModifier.map { tokenize($0, node: node) } ?? [],
[block.newToken(.keyword, "get", node)],
tokenize(block.codeBlock)
].joined(token: block.newToken(.space, " ", node))
}
open func tokenize(_ block: GetterSetterBlock.SetterClause, node: ASTNode) -> [Token] {
let mutationTokens = block.mutationModifier.map { tokenize($0, node: node) } ?? []
let setTokens = block.newToken(.keyword, "set", node) +
block.name.map { name in
block.newToken(.startOfScope, "(", node) +
block.newToken(.identifier, name, node) +
block.newToken(.endOfScope, ")", node)
}
return [
tokenize(block.attributes, node: node),
mutationTokens,
setTokens,
tokenize(block.codeBlock)
].joined(token: block.newToken(.space, " ", node))
}
open func tokenize(_ block: GetterSetterBlock, node: ASTNode) -> [Token] {
let getterTokens = tokenize(block.getter, node: node)
let setterTokens = block.setter.map { tokenize($0, node: node) } ?? []
return [
[block.newToken(.startOfScope, "{", node)],
indent(getterTokens),
indent(setterTokens),
[block.newToken(.endOfScope, "}", node)]
].joined(token: block.newToken(.linebreak, "\n", node))
}
open func tokenize(_ block: GetterSetterKeywordBlock, node: ASTNode) -> [Token] {
let getterTokens = tokenize(block.getter, node: node)
let setterTokens = block.setter.map { tokenize($0, node: node) } ?? []
return [
[block.newToken(.startOfScope, "{", node)],
indent(getterTokens),
indent(setterTokens),
[block.newToken(.endOfScope, "}", node)]
].joined(token: block.newToken(.linebreak, "\n", node))
}
open func tokenize(_ block: WillSetDidSetBlock.WillSetClause, node: ASTNode) -> [Token] {
let nameTokens = block.name.map { name in
return block.newToken(.startOfScope, "(", node) +
block.newToken(.identifier, name, node) +
block.newToken(.endOfScope, ")", node)
} ?? []
return [
tokenize(block.attributes, node: node),
block.newToken(.keyword, "willSet", node) + nameTokens,
tokenize(block.codeBlock)
].joined(token: block.newToken(.space, " ", node))
}
open func tokenize(_ block: WillSetDidSetBlock.DidSetClause, node: ASTNode) -> [Token] {
let nameTokens = block.name.map { name in
return block.newToken(.startOfScope, "(", node) +
block.newToken(.identifier, name, node) +
block.newToken(.endOfScope, ")", node)
} ?? []
return [
tokenize(block.attributes, node: node),
block.newToken(.keyword, "didSet", node) + nameTokens,
tokenize(block.codeBlock)
].joined(token: block.newToken(.space, " ", node))
}
open func tokenize(_ block: WillSetDidSetBlock, node: ASTNode) -> [Token] {
let willSetClause = block.willSetClause.map { tokenize($0, node: node) } ?? []
let didSetClause = block.didSetClause.map { tokenize($0, node: node) } ?? []
return [
[block.newToken(.startOfScope, "{", node)],
indent(willSetClause),
indent(didSetClause),
[block.newToken(.endOfScope, "}", node)]
].joined(token: block.newToken(.linebreak, "\n", node))
}
open func tokenize(_ clause: GetterSetterKeywordBlock.GetterKeywordClause, node: ASTNode) -> [Token] {
return [
tokenize(clause.attributes, node: node),
clause.mutationModifier.map { tokenize($0, node: node) } ?? [],
[clause.newToken(.keyword, "get", node)],
].joined(token: clause.newToken(.space, " ", node))
}
open func tokenize(_ clause: GetterSetterKeywordBlock.SetterKeywordClause, node: ASTNode) -> [Token] {
return [
tokenize(clause.attributes, node: node),
clause.mutationModifier.map { tokenize($0, node: node) } ?? [],
[clause.newToken(.keyword, "set", node)],
].joined(token: clause.newToken(.space, " ", node))
}
open func tokenize(_ patternInitializer: PatternInitializer, node: ASTNode) -> [Token] {
let pttrnTokens = tokenize(patternInitializer.pattern, node: node)
guard let initExpr = patternInitializer.initializerExpression else {
return pttrnTokens
}
return pttrnTokens +
[patternInitializer.newToken(.symbol, " = ", node)] +
tokenize(expression: initExpr)
}
open func tokenize(_ initializers: [PatternInitializer], node: ASTNode) -> [Token] {
return initializers.map { tokenize($0, node: node) }.joined(token: node.newToken(.delimiter, ", "))
}
open func tokenize(_ member: ClassDeclaration.Member) -> [Token] {
switch member {
case .declaration(let decl):
return tokenize(decl)
case .compilerControl(let stmt):
return tokenize(stmt)
}
}
open func tokenize(_ declaration: ClassDeclaration) -> [Token] {
let attrsTokens = tokenize(declaration.attributes, node: declaration)
let modifierTokens = declaration.accessLevelModifier.map { tokenize($0, node: declaration) } ?? []
let finalTokens = declaration.isFinal ? [declaration.newToken(.keyword, "final")] : []
let headTokens = [
attrsTokens,
modifierTokens,
finalTokens,
[declaration.newToken(.keyword, "class")],
[declaration.newToken(.identifier, declaration.name)],
].joined(token: declaration.newToken(.space, " "))
let genericParameterClauseTokens = declaration.genericParameterClause.map {
tokenize($0, node: declaration)
} ?? []
let typeTokens = declaration.typeInheritanceClause.map { tokenize($0, node: declaration) } ?? []
let whereTokens = declaration.genericWhereClause.map {
declaration.newToken(.space, " ") + tokenize($0, node: declaration)
} ?? []
let neckTokens = genericParameterClauseTokens + typeTokens + whereTokens
let membersTokens = indent(declaration.members.map(tokenize)
.joined(token: declaration.newToken(.linebreak, "\n")))
.prefix(with: declaration.newToken(.linebreak, "\n"))
.suffix(with: declaration.newToken(.linebreak, "\n"))
let declTokens = headTokens +
neckTokens +
[declaration.newToken(.space, " "), declaration.newToken(.startOfScope, "{")] +
membersTokens +
[declaration.newToken(.endOfScope, "}")]
return declTokens.prefix(with: declaration.newToken(.linebreak, "\n"))
}
open func tokenize(_ constant: ConstantDeclaration) -> [Token] {
return [
tokenize(constant.attributes, node: constant),
tokenize(constant.modifiers, node: constant),
[constant.newToken(.keyword, "let")],
tokenize(constant.initializerList, node: constant)
].joined(token: constant.newToken(.space, " "))
}
open func tokenize(_ declaration: DeinitializerDeclaration) -> [Token] {
let declTokens = [
tokenize(declaration.attributes, node: declaration),
[declaration.newToken(.keyword, "deinit")],
tokenize(declaration.body),
]
return declTokens
.joined(token: declaration.newToken(.space, " "))
.prefix(with: declaration.newToken(.linebreak, "\n"))
}
open func tokenize(_ member: EnumDeclaration.Member, node: ASTNode) -> [Token] {
switch member {
case .declaration(let decl):
return tokenize(decl)
case .union(let enumCase):
return tokenize(enumCase, node: node)
case .rawValue(let enumCase):
return tokenize(enumCase, node: node)
case .compilerControl(let stmt):
return tokenize(stmt)
}
}
open func tokenize(_ union: EnumDeclaration.UnionStyleEnumCase, node: ASTNode) -> [Token] {
let casesTokens = union.cases.map { c in
return c.newToken(.identifier, c.name, node) + c.tuple.map { tokenize($0, node: node) }
}.joined(token: union.newToken(.delimiter, ", ", node))
return [
tokenize(union.attributes, node: node),
union.isIndirect ? [union.newToken(.keyword, "indirect", node)] : [],
[union.newToken(.keyword, "case", node)],
casesTokens
].joined(token: union.newToken(.space, " ", node))
}
open func tokenize(_ raw: EnumDeclaration.RawValueStyleEnumCase, node: ASTNode) -> [Token] {
let casesTokens = raw.cases.map { c -> [Token] in
var assignmentTokens = [Token]()
if let assignment = c.assignment {
assignmentTokens += [c.newToken(.symbol, " = ", node)]
switch assignment {
case .integer(let i):
assignmentTokens += [c.newToken(.number, "\(i)", node)]
case .floatingPoint(let d):
assignmentTokens += [c.newToken(.number, "\(d)", node)]
case .string(let s):
assignmentTokens += [c.newToken(.string, "\"\(s)\"", node)]
case .boolean(let b):
assignmentTokens += [c.newToken(.keyword, b ? "true" : "false", node)]
}
}
return c.newToken(.identifier, c.name, node) + assignmentTokens
}.joined(token: raw.newToken(.delimiter, ", ", node))
return [
tokenize(raw.attributes, node: node),
[raw.newToken(.keyword, "case", node)],
casesTokens
].joined(token: raw.newToken(.space, " ", node))
}
open func tokenize(_ declaration: EnumDeclaration) -> [Token] {
let attrsTokens = tokenize(declaration.attributes, node: declaration)
let modifierTokens = declaration.accessLevelModifier.map { tokenize($0, node: declaration) } ?? []
let indirectTokens = declaration.isIndirect ? [declaration.newToken(.keyword, "indirect")] : []
let headTokens = [
attrsTokens,
modifierTokens,
indirectTokens,
[declaration.newToken(.keyword, "enum")],
[declaration.newToken(.identifier, declaration.name)],
].joined(token: declaration.newToken(.space, " "))
let genericParameterClauseTokens = declaration.genericParameterClause.map {
tokenize($0, node: declaration)
} ?? []
let typeTokens = declaration.typeInheritanceClause.map { tokenize($0, node: declaration) } ?? []
let whereTokens = declaration.genericWhereClause.map {
declaration.newToken(.space, " ") + tokenize($0, node: declaration)
} ?? []
let neckTokens = genericParameterClauseTokens +
typeTokens +
whereTokens
let membersTokens = indent(declaration.members.map { tokenize($0, node: declaration) }
.joined(token: declaration.newToken(.linebreak, "\n")))
.prefix(with: declaration.newToken(.linebreak, "\n"))
.suffix(with: declaration.newToken(.linebreak, "\n"))
let declTokens = headTokens +
neckTokens +
[declaration.newToken(.space, " "), declaration.newToken(.startOfScope, "{")] +
membersTokens +
[declaration.newToken(.endOfScope, "}")]
return declTokens.prefix(with: declaration.newToken(.linebreak, "\n"))
}
open func tokenize(_ member: ExtensionDeclaration.Member) -> [Token] {
switch member {
case .declaration(let decl):
return tokenize(decl)
case .compilerControl(let stmt):
return tokenize(stmt)
}
}
open func tokenize(_ declaration: ExtensionDeclaration) -> [Token] {
let attrsTokens = tokenize(declaration.attributes, node: declaration)
let modifierTokens = declaration.accessLevelModifier.map { tokenize($0, node: declaration) } ?? []
let headTokens = [
attrsTokens,
modifierTokens,
[declaration.newToken(.keyword, "extension")],
tokenize(declaration.type, node: declaration)
].joined(token: declaration.newToken(.space, " "))
let typeTokens = declaration.typeInheritanceClause.map { tokenize($0, node: declaration) } ?? []
let whereTokens = declaration.genericWhereClause.map {
declaration.newToken(.space, " ") + tokenize($0, node: declaration)
} ?? []
let neckTokens = typeTokens + whereTokens
let membersTokens = indent(declaration.members.map(tokenize)
.joined(token: declaration.newToken(.linebreak, "\n")))
.prefix(with: declaration.newToken(.linebreak, "\n"))
.suffix(with: declaration.newToken(.linebreak, "\n"))
let declTokens = headTokens +
neckTokens +
[declaration.newToken(.space, " "), declaration.newToken(.startOfScope, "{")] +
membersTokens +
[declaration.newToken(.endOfScope, "}")]
return declTokens.prefix(with: declaration.newToken(.linebreak, "\n"))
}
open func tokenize(_ declaration: FunctionDeclaration) -> [Token] {
let attrsTokens = tokenize(declaration.attributes, node: declaration)
let modifierTokens = declaration.modifiers.map { tokenize($0, node: declaration) }
.joined(token: declaration.newToken(.space, " "))
let headTokens = [
attrsTokens,
modifierTokens,
[declaration.newToken(.keyword, "func")],
].joined(token: declaration.newToken(.space, " "))
let genericParameterClauseTokens = declaration.genericParameterClause.map {
tokenize($0, node: declaration)
} ?? []
let signatureTokens = tokenize(declaration.signature, node: declaration)
let whereTokens = declaration.genericWhereClause.map { tokenize($0, node: declaration) } ?? []
let bodyTokens = declaration.body.map(tokenize) ?? []
return [
headTokens,
[declaration.newToken(.identifier, declaration.name)] + genericParameterClauseTokens + signatureTokens,
whereTokens,
bodyTokens
].joined(token: declaration.newToken(.space, " "))
.prefix(with: declaration.newToken(.linebreak, "\n"))
}
open func tokenize(_ parameter: FunctionSignature.Parameter, node: ASTNode) -> [Token] {
let externalNameTokens = parameter.externalName.map { [parameter.newToken(.identifier, $0, node)] } ?? []
let localNameTokens = parameter.localName.textDescription.isEmpty ? [] : [
parameter.newToken(.identifier, parameter.localName.textDescription, node)
]
let nameTokens = [externalNameTokens, localNameTokens].joined(token: parameter.newToken(.space, " ", node))
let typeAnnoTokens = tokenize(parameter.typeAnnotation, node: node)
let defaultTokens = parameter.defaultArgumentClause.map {
return parameter.newToken(.symbol, " = ", node) + tokenize($0)
}
let varargsTokens = parameter.isVarargs ? [parameter.newToken(.symbol, "...", node)] : []
return
nameTokens +
typeAnnoTokens +
defaultTokens +
varargsTokens
}
open func tokenize(_ signature: FunctionSignature, node: ASTNode) -> [Token] {
let parameterTokens = signature.newToken(.startOfScope, "(", node) +
signature.parameterList.map { tokenize($0, node: node) }
.joined(token: signature.newToken(.delimiter, ", ", node)) +
signature.newToken(.endOfScope, ")", node)
let throwsKindTokens = tokenize(signature.throwsKind, node: node)
let resultTokens = signature.result.map { tokenize($0, node: node) } ?? []
return [parameterTokens, throwsKindTokens, resultTokens]
.joined(token: signature.newToken(.space, " ", node))
}
open func tokenize(_ result: FunctionResult, node: ASTNode) -> [Token] {
let typeTokens = tokenize(result.type, node: node)
let attributeTokens = tokenize(result.attributes, node: node)
return [
[result.newToken(.symbol, "->", node)],
attributeTokens,
typeTokens
].joined(token: result.newToken(.space, " ", node))
}
open func tokenize(_ declaration: ImportDeclaration) -> [Token] {
let attrsTokens = tokenize(declaration.attributes, node: declaration)
let kindTokens = declaration.kind.map { [declaration.newToken(.identifier, $0.rawValue)] } ?? []
let pathTokens = declaration.path.isEmpty ? [] : [
declaration.newToken(.identifier, declaration.path.map({ $0.textDescription }).joined(separator: "."))
]
return [
attrsTokens,
[declaration.newToken(.keyword, "import")],
kindTokens,
pathTokens
].joined(token: declaration.newToken(.space, " "))
}
open func tokenize(_ declaration: InitializerDeclaration) -> [Token] {
let attrsTokens = tokenize(declaration.attributes, node: declaration)
let modifierTokens = tokenize(declaration.modifiers, node: declaration)
let headTokens = [
attrsTokens,
modifierTokens,
[declaration.newToken(.keyword, "init")] + tokenize(declaration.kind, node: declaration)
].joined(token: declaration.newToken(.space, " "))
let genericParamTokens = declaration.genericParameterClause.map { tokenize($0, node: declaration) } ?? []
let parameterTokens = declaration.newToken(.startOfScope, "(") +
declaration.parameterList.map { tokenize($0, node: declaration) }
.joined(token: declaration.newToken(.delimiter, ", ")) +
declaration.newToken(.endOfScope, ")")
let throwsKindTokens = tokenize(declaration.throwsKind, node: declaration)
let genericWhereTokens = declaration.genericWhereClause.map { tokenize($0, node: declaration) } ?? []
let bodyTokens = tokenize(declaration.body)
return [
headTokens + genericParamTokens + parameterTokens,
throwsKindTokens,
genericWhereTokens,
bodyTokens
].joined(token: declaration.newToken(.space, " "))
.prefix(with: declaration.newToken(.linebreak, "\n"))
}
open func tokenize(_ declaration: InitializerDeclaration.InitKind, node: ASTNode) -> [Token] {
switch declaration {
case .nonfailable:
return []
case .optionalFailable:
return [declaration.newToken(.symbol, "?", node)]
case .implicitlyUnwrappedFailable:
return [declaration.newToken(.symbol, "!", node)]
}
}
open func tokenize(_ declaration: OperatorDeclaration) -> [Token] {
switch declaration.kind {
case .prefix(let op):
return [
[declaration.newToken(.keyword, "prefix")],
[declaration.newToken(.keyword, "operator")],
[declaration.newToken(.identifier, op)],
].joined(token: declaration.newToken(.space, " "))
case .postfix(let op):
return [
[declaration.newToken(.keyword, "postfix")],
[declaration.newToken(.keyword, "operator")],
[declaration.newToken(.identifier, op)],
].joined(token: declaration.newToken(.space, " "))
case .infix(let op, nil):
return [
[declaration.newToken(.keyword, "infix")],
[declaration.newToken(.keyword, "operator")],
[declaration.newToken(.identifier, op)],
].joined(token: declaration.newToken(.space, " "))
case .infix(let op, let id?):
return [
[declaration.newToken(.keyword, "infix")],
[declaration.newToken(.keyword, "operator")],
[declaration.newToken(.identifier, op)],
[declaration.newToken(.symbol, ":")],
[declaration.newToken(.identifier, id)]
].joined(token: declaration.newToken(.space, " "))
}
}
open func tokenize(_ declaration: PrecedenceGroupDeclaration) -> [Token] {
let attrsTokens = declaration.attributes.map { tokenize($0, node: declaration) }
.joined(token: declaration.newToken(.linebreak, "\n"))
let attrsBlockTokens: [Token]
if declaration.attributes.isEmpty {
attrsBlockTokens = [declaration.newToken(.startOfScope, "{"), declaration.newToken(.endOfScope, "}")]
} else {
attrsBlockTokens = [
[declaration.newToken(.startOfScope, "{")],
indent(attrsTokens),
[declaration.newToken(.endOfScope, "}")]
].joined(token: declaration.newToken(.linebreak, "\n"))
}
return [
[declaration.newToken(.keyword, "precedencegroup")],
[declaration.newToken(.identifier, declaration.name)],
attrsBlockTokens
].joined(token: declaration.newToken(.space, " "))
}
open func tokenize(_ attribute: PrecedenceGroupDeclaration.Attribute, node: ASTNode) -> [Token] {
switch attribute {
case .higherThan(let ids):
return [
attribute.newToken(.keyword, "higherThan", node),
attribute.newToken(.symbol, ":", node),
attribute.newToken(.space, " ", node),
attribute.newToken(.identifier, ids.textDescription, node)
]
case .lowerThan(let ids):
return [
attribute.newToken(.keyword, "lowerThan", node),
attribute.newToken(.symbol, ":", node),
attribute.newToken(.space, " ", node),
attribute.newToken(.identifier, ids.textDescription, node)
]
case .assignment(let b):
return [
attribute.newToken(.keyword, "assignment", node),
attribute.newToken(.symbol, ":", node),
attribute.newToken(.space, " ", node),
attribute.newToken(.keyword, b ? "true" : "false", node)
]
case .associativityLeft:
return [
attribute.newToken(.keyword, "associativity", node),
attribute.newToken(.symbol, ":", node),
attribute.newToken(.space, " ", node),
attribute.newToken(.keyword, "left", node)
]
case .associativityRight:
return [
attribute.newToken(.keyword, "associativity", node),
attribute.newToken(.symbol, ":", node),
attribute.newToken(.space, " ", node),
attribute.newToken(.keyword, "right", node)
]
case .associativityNone:
return [
attribute.newToken(.keyword, "associativity", node),
attribute.newToken(.symbol, ":", node),
attribute.newToken(.space, " ", node),
attribute.newToken(.keyword, "none", node)
]
}
}
open func tokenize(_ declaration: ProtocolDeclaration) -> [Token] {
let attrsTokens = tokenize(declaration.attributes, node: declaration)
let modifierTokens = declaration.accessLevelModifier.map { tokenize($0, node: declaration) } ?? []
let headTokens = [
attrsTokens,
modifierTokens,
[declaration.newToken(.keyword, "protocol")],
[declaration.newToken(.identifier, declaration.name)],
].joined(token: declaration.newToken(.space, " "))
let typeTokens = declaration.typeInheritanceClause.map { tokenize($0, node: declaration) } ?? []
let membersTokens = indent(declaration.members.map { tokenize($0, node: declaration) }
.joined(token: declaration.newToken(.linebreak, "\n")))
.prefix(with: declaration.newToken(.linebreak, "\n"))
.suffix(with: declaration.newToken(.linebreak, "\n"))
let declTokens = headTokens +
typeTokens +
[declaration.newToken(.space, " "), declaration.newToken(.startOfScope, "{")] +
membersTokens +
[declaration.newToken(.endOfScope, "}")]
return declTokens.prefix(with: declaration.newToken(.linebreak, "\n"))
}
open func tokenize(_ member: ProtocolDeclaration.Member, node: ASTNode) -> [Token] {
switch member {
case .property(let member):
return tokenize(member, node: node)
case .method(let member):
return tokenize(member, node: node)
case .initializer(let member):
return tokenize(member, node: node)
case .subscript(let member):
return tokenize(member, node: node)
case .associatedType(let member):
return tokenize(member, node: node)
case .compilerControl(let stmt):
return tokenize(stmt)
}
}
open func tokenize(_ member: ProtocolDeclaration.PropertyMember, node: ASTNode) -> [Token] {
let attrsTokens = tokenize(member.attributes, node: node)
let modifiersTokens = tokenize(member.modifiers, node: node)
let blockTokens = tokenize(member.getterSetterKeywordBlock, node: node)
return [
attrsTokens,
modifiersTokens,
[member.newToken(.keyword, "var", node)],
member.newToken(.identifier, member.name, node) + tokenize(member.typeAnnotation, node: node),
blockTokens
].joined(token: member.newToken(.space, " ", node))
}
open func tokenize(_ member: ProtocolDeclaration.MethodMember, node: ASTNode) -> [Token] {
let attrsTokens = tokenize(member.attributes, node: node)
let modifierTokens = member.modifiers.map { tokenize($0, node: node) }
.joined(token: member.newToken(.space, " ", node))
let headTokens = [
attrsTokens,
modifierTokens,
[member.newToken(.keyword, "func", node)],
].joined(token: member.newToken(.space, " ", node))
let genericParameterClauseTokens = member.genericParameter.map { tokenize($0, node: node) } ?? []
let signatureTokens = tokenize(member.signature, node: node)
let genericWhereClauseTokens = member.genericWhere.map { (tokenize($0, node: node)) } ?? []
return [
headTokens,
[member.newToken(.identifier, member.name, node)] + genericParameterClauseTokens + signatureTokens,
genericWhereClauseTokens
].joined(token: member.newToken(.space, " ", node))
}
open func tokenize(_ member: ProtocolDeclaration.InitializerMember, node: ASTNode) -> [Token] {
let attrsTokens = tokenize(member.attributes, node: node)
let modifierTokens = tokenize(member.modifiers, node: node)
let headTokens = [
attrsTokens,
modifierTokens,
member.newToken(.keyword, "init", node) + tokenize(member.kind, node: node),
].joined(token: member.newToken(.space, " ", node))
let genericParameterClauseTokens = member.genericParameter.map { tokenize($0, node: node) } ?? []
let parameterTokens = member.newToken(.startOfScope, "(", node) +
member.parameterList.map { tokenize($0, node: node) }
.joined(token: member.newToken(.delimiter, ", ", node)) +
member.newToken(.endOfScope, ")", node)
let throwsKindTokens = tokenize(member.throwsKind, node: node)
let genericWhereClauseTokens = member.genericWhere.map { tokenize($0, node: node) } ?? []
return [
headTokens + genericParameterClauseTokens + parameterTokens,
throwsKindTokens,
genericWhereClauseTokens
].joined(token: member.newToken(.space, " ", node))
}
open func tokenize(_ member: ProtocolDeclaration.SubscriptMember, node: ASTNode) -> [Token] {
let attrsTokens = tokenize(member.attributes, node: node)
let modifierTokens = tokenize(member.modifiers, node: node)
let genericParameterClauseTokens = member.genericParameter.map { tokenize($0, node: node) } ?? []
let parameterTokens = member.newToken(.startOfScope, "(", node) +
member.parameterList.map { tokenize($0, node: node) }
.joined(token: member.newToken(.delimiter, ", ", node)) +
member.newToken(.endOfScope, ")", node)
let headTokens = [
attrsTokens,
modifierTokens,
[member.newToken(.keyword, "subscript", node)] + genericParameterClauseTokens + parameterTokens
].joined(token: member.newToken(.space, " ", node))
let resultAttrsTokens = tokenize(member.resultAttributes, node: node)
let resultTokens = [
[member.newToken(.symbol, "->", node)],
resultAttrsTokens,
tokenize(member.resultType, node: node)
].joined(token: member.newToken(.space, " ", node))
let genericWhereClauseTokens = member.genericWhere.map { tokenize($0, node: node) } ?? []
return [
headTokens,
resultTokens,
genericWhereClauseTokens,
tokenize(member.getterSetterKeywordBlock, node: node)
].joined(token: member.newToken(.space, " ", node))
}
open func tokenize(_ member: ProtocolDeclaration.AssociativityTypeMember, node: ASTNode) -> [Token] {
let attrsTokens = tokenize(member.attributes, node: node)
let modifierTokens = member.accessLevelModifier.map { tokenize($0, node: node) } ?? []
let typeTokens = member.typeInheritance.map { tokenize($0, node: node) } ?? []
let assignmentTokens: [Token] = member.assignmentType.map {
member.newToken(.symbol, "=", node) + member.newToken(.space, " ", node) + tokenize($0, node: node)
} ?? []
let genericWhereTokens = member.genericWhere.map { tokenize($0, node: node) } ?? []
return [
attrsTokens,
modifierTokens,
[member.newToken(.keyword, "associatedtype", node)],
[member.newToken(.identifier, member.name, node)] + typeTokens,
assignmentTokens,
genericWhereTokens
].joined(token: member.newToken(.space, " ", node))
}
open func tokenize(_ declaration: StructDeclaration) -> [Token] {
let attrsTokens = tokenize(declaration.attributes, node: declaration)
let modifierTokens = declaration.accessLevelModifier.map { tokenize($0, node: declaration) } ?? []
let headTokens = [
attrsTokens,
modifierTokens,
[declaration.newToken(.keyword, "struct")],
[declaration.newToken(.identifier, declaration.name)],
].joined(token: declaration.newToken(.space, " "))
let genericParameterClauseTokens = declaration.genericParameterClause.map {
tokenize($0, node: declaration)
} ?? []
let typeTokens = declaration.typeInheritanceClause.map { tokenize($0, node: declaration) } ?? []
let whereTokens = declaration.genericWhereClause.map {
declaration.newToken(.space, " ") + tokenize($0, node: declaration)
} ?? []
let neckTokens = genericParameterClauseTokens +
typeTokens +
whereTokens
let membersTokens = indent(declaration.members.map(tokenize)
.joined(token: declaration.newToken(.linebreak, "\n")))
.prefix(with: declaration.newToken(.linebreak, "\n"))
.suffix(with: declaration.newToken(.linebreak, "\n"))
let declTokens = headTokens +
neckTokens +
[declaration.newToken(.space, " "), declaration.newToken(.startOfScope, "{")] +
membersTokens +
[declaration.newToken(.endOfScope, "}")]
return declTokens.prefix(with: declaration.newToken(.linebreak, "\n"))
}
open func tokenize(_ member: StructDeclaration.Member) -> [Token] {
switch member {
case .declaration(let decl):
return tokenize(decl)
case .compilerControl(let stmt):
return tokenize(stmt)
}
}
open func tokenize(_ declaration: SubscriptDeclaration) -> [Token] {
let attrsTokens = tokenize(declaration.attributes, node: declaration)
let modifierTokens = tokenize(declaration.modifiers, node: declaration)
let genericParameterClauseTokens = declaration.genericParameterClause.map {
tokenize($0, node: declaration)
} ?? []
let parameterTokens = declaration.newToken(.startOfScope, "(") +
declaration.parameterList.map { tokenize($0, node: declaration) }
.joined(token: declaration.newToken(.delimiter, ", ")) +
declaration.newToken(.endOfScope, ")")
let headTokens = [
attrsTokens,
modifierTokens,
[declaration.newToken(.keyword, "subscript")] + genericParameterClauseTokens + parameterTokens
].joined(token: declaration.newToken(.space, " "))
let resultAttrsTokens = tokenize(declaration.resultAttributes, node: declaration)
let resultTokens = [
[declaration.newToken(.symbol, "->")],
resultAttrsTokens,
tokenize(declaration.resultType, node: declaration)
].joined(token: declaration.newToken(.space, " "))
let genericWhereClauseTokens = declaration.genericWhereClause.map { tokenize($0, node: declaration) } ?? []
return [
headTokens,
resultTokens,
genericWhereClauseTokens,
tokenize(declaration.body, node: declaration)
].joined(token: declaration.newToken(.space, " "))
}
open func tokenize(_ body: SubscriptDeclaration.Body, node: ASTNode) -> [Token] {
switch body {
case .codeBlock(let block):
return tokenize(block)
case .getterSetterBlock(let block):
return tokenize(block, node: node)
case .getterSetterKeywordBlock(let block):
return tokenize(block, node: node)
}
}
open func tokenize(_ declaration: TypealiasDeclaration) -> [Token] {
let attrsTokens = tokenize(declaration.attributes, node: declaration)
let modifierTokens = declaration.accessLevelModifier.map { tokenize($0, node: declaration) } ?? []
let genericTokens = declaration.generic.map { tokenize($0, node: declaration) } ?? []
let assignmentTokens = tokenize(declaration.assignment, node: declaration)
return [
attrsTokens,
modifierTokens,
[declaration.newToken(.keyword, "typealias")],
[declaration.newToken(.identifier, declaration.name)] + genericTokens,
[declaration.newToken(.symbol, "=")],
assignmentTokens
].joined(token: declaration.newToken(.space, " "))
}
open func tokenize(_ declaration: VariableDeclaration) -> [Token] {
let attrsTokens = tokenize(declaration.attributes, node: declaration)
let modifierTokens = tokenize(declaration.modifiers, node: declaration)
return [
attrsTokens,
modifierTokens,
[declaration.newToken(.keyword, "var")],
tokenize(declaration.body, node: declaration)
].joined(token: declaration.newToken(.space, " "))
}
open func tokenize(_ body: VariableDeclaration.Body, node: ASTNode) -> [Token] {
switch body {
case .initializerList(let inits):
return inits.map { tokenize($0, node: node) }.joined(token: body.newToken(.delimiter, ", ", node))
case let .codeBlock(name, typeAnnotation, codeBlock):
return body.newToken(.identifier, name, node) +
tokenize(typeAnnotation, node: node) +
body.newToken(.space, " ", node) +
tokenize(codeBlock)
case let .getterSetterBlock(name, typeAnnotation, block):
return body.newToken(.identifier, name, node) +
tokenize(typeAnnotation, node: node) +
body.newToken(.space, " ", node) +
tokenize(block, node: node)
case let .getterSetterKeywordBlock(name, typeAnnotation, block):
return body.newToken(.identifier, name, node) +
tokenize(typeAnnotation, node: node) +
body.newToken(.space, " ", node) +
tokenize(block, node: node)
case let .willSetDidSetBlock(name, typeAnnotation, initExpr, block):
let typeAnnoTokens = typeAnnotation.map { tokenize($0, node: node) } ?? []
let initTokens = initExpr.map { body.newToken(.symbol, " = ", node) + tokenize($0) } ?? []
return [body.newToken(.identifier, name, node)] +
typeAnnoTokens +
initTokens +
[body.newToken(.space, " ", node)] +
tokenize(block, node: node)
}
}
open func tokenize(_ modifiers: [DeclarationModifier], node: ASTNode) -> [Token] {
return modifiers.map { tokenize($0, node: node) }
.joined(token: node.newToken(.space, " "))
}
open func tokenize(_ modifier: DeclarationModifier, node: ASTNode) -> [Token] { /*
swift-lint:suppress(high_cyclomatic_complexity) */
switch modifier {
case .class:
return [modifier.newToken(.keyword, "class", node)]
case .convenience:
return [modifier.newToken(.keyword, "convenience", node)]
case .dynamic:
return [modifier.newToken(.keyword, "dynamic", node)]
case .final:
return [modifier.newToken(.keyword, "final", node)]
case .infix:
return [modifier.newToken(.keyword, "infix", node)]
case .lazy:
return [modifier.newToken(.keyword, "lazy", node)]
case .optional:
return [modifier.newToken(.keyword, "optional", node)]
case .override:
return [modifier.newToken(.keyword, "override", node)]
case .postfix:
return [modifier.newToken(.keyword, "postfix", node)]
case .prefix:
return [modifier.newToken(.keyword, "prefix", node)]
case .required:
return [modifier.newToken(.keyword, "required", node)]
case .static:
return [modifier.newToken(.keyword, "static", node)]
case .unowned:
return [modifier.newToken(.keyword, "unowned", node)]
case .unownedSafe:
return [modifier.newToken(.keyword, "unowned(safe)", node)]
case .unownedUnsafe:
return [modifier.newToken(.keyword, "unowned(unsafe)", node)]
case .weak:
return [modifier.newToken(.keyword, "weak", node)]
case .accessLevel(let modifier):
return tokenize(modifier, node: node)
case .mutation(let modifier):
return tokenize(modifier, node: node)
}
}
open func tokenize(_ modifier: AccessLevelModifier, node: ASTNode) -> [Token] {
return [modifier.newToken(.keyword, modifier.rawValue, node)]
}
open func tokenize(_ modifier: MutationModifier, node: ASTNode) -> [Token] {
return [modifier.newToken(.keyword, modifier.rawValue, node)]
}
// MARK: - Expressions
open func tokenize(expression: Expression) -> [Token] {
return tokenize(expression)
}
open func tokenize(_ expression: Expression) -> [Token] { /*
swift-lint:suppress(high_cyclomatic_complexity, high_ncss) */
switch expression {
case let expr as AssignmentOperatorExpression:
return tokenize(expr)
case let expr as BinaryOperatorExpression:
return tokenize(expr)
case let expr as ClosureExpression:
return tokenize(expr)
case let expr as ExplicitMemberExpression:
return tokenize(expr)
case let expr as ForcedValueExpression:
return tokenize(expr)
case let expr as FunctionCallExpression:
return tokenize(expr)
case let expr as IdentifierExpression:
return tokenize(expr)
case let expr as ImplicitMemberExpression:
return tokenize(expr)
case let expr as InOutExpression:
return tokenize(expr)
case let expr as InitializerExpression:
return tokenize(expr)
case let expr as KeyPathStringExpression:
return tokenize(expr)
case let expr as LiteralExpression:
return tokenize(expr)
case let expr as OptionalChainingExpression:
return tokenize(expr)
case let expr as ParenthesizedExpression:
return tokenize(expr)
case let expr as PostfixOperatorExpression:
return tokenize(expr)
case let expr as PostfixSelfExpression:
return tokenize(expr)
case let expr as PrefixOperatorExpression:
return tokenize(expr)
case let expr as SelectorExpression:
return tokenize(expr)
case let expr as SelfExpression:
return tokenize(expr)
case let expr as SequenceExpression:
return tokenize(expr)
case let expr as SubscriptExpression:
return tokenize(expr)
case let expr as SuperclassExpression:
return tokenize(expr)
case let expr as TernaryConditionalOperatorExpression:
return tokenize(expr)
case let expr as TryOperatorExpression:
return tokenize(expr)
case let expr as TupleExpression:
return tokenize(expr)
case let expr as TypeCastingOperatorExpression:
return tokenize(expr)
case let expr as WildcardExpression:
return tokenize(expr)
default:
return [Token(origin: expression as? ASTTokenizable,
node: expression as? ASTNode,
kind: .identifier,
value: expression.textDescription)]
}
}
open func tokenize(_ expression: AssignmentOperatorExpression) -> [Token] {
return tokenize(expression.leftExpression) +
expression.newToken(.symbol, " = ") +
tokenize(expression.rightExpression)
}
open func tokenize(_ expression: BinaryOperatorExpression) -> [Token] {
return [
tokenize(expression.leftExpression),
[expression.newToken(.symbol, expression.binaryOperator)],
tokenize(expression.rightExpression),
].joined(token: expression.newToken(.space, " "))
}
open func tokenize(_ expression: ClosureExpression) -> [Token] {
let spaceToken = expression.newToken(.space, " ")
var signatureTokens = [Token]()
var stmtsTokens = [Token]()
if let signature = expression.signature {
signatureTokens = spaceToken +
tokenize(signature, node: expression) +
spaceToken +
expression.newToken(.keyword, "in")
if expression.statements == nil {
stmtsTokens = [spaceToken]
}
}
if let stmts = expression.statements {
if expression.signature == nil && stmts.count == 1 {
stmtsTokens = spaceToken + tokenize(stmts, node: expression) + spaceToken
} else {
stmtsTokens += [expression.newToken(.linebreak, "\n")]
stmtsTokens += indent(tokenize(stmts, node: expression))
stmtsTokens += [expression.newToken(.linebreak, "\n")]
}
}
return [expression.newToken(.startOfScope, "{")] +
signatureTokens +
stmtsTokens +
[expression.newToken(.endOfScope, "}")]
}
open func tokenize(_ expression: ClosureExpression.Signature.CaptureItem, node: ASTNode) -> [Token] {
return [
expression.specifier.map { tokenize($0, node: node) } ?? [],
tokenize(expression.expression),
].joined(token: expression.newToken(.space, " ", node))
}
open func tokenize(_ expression: ClosureExpression.Signature.CaptureItem.Specifier, node: ASTNode) -> [Token] {
return [expression.newToken(.identifier, expression.rawValue, node)]
}
open func tokenize(_ expression: ClosureExpression.Signature.ParameterClause, node: ASTNode) -> [Token] {
switch expression {
case .parameterList(let params):
return expression.newToken(.startOfScope, "(", node) +
params.map { tokenize($0, node: node) }.joined(token: expression.newToken(.delimiter, ", ", node)) +
expression.newToken(.endOfScope, ")", node)
case .identifierList(let idList):
return [expression.newToken(.identifier, idList.textDescription, node)]
}
}
open func tokenize(_ expression: ClosureExpression.Signature.ParameterClause.Parameter, node: ASTNode) -> [Token] {
return expression.newToken(.identifier, expression.name, node) +
expression.typeAnnotation.map { typeAnnotation in
return tokenize(typeAnnotation, node: node) +
(expression.isVarargs ? typeAnnotation.newToken(.symbol, "...", node) : nil)
}
}
open func tokenize(_ expression: ClosureExpression.Signature, node: ASTNode) -> [Token] {
let captureTokens = expression.captureList.map { captureList in
return expression.newToken(.startOfScope, "[", node) +
captureList.map { tokenize($0, node: node) }
.joined(token: expression.newToken(.delimiter, ", ", node)) +
expression.newToken(.endOfScope, "]", node)
} ?? []
let parameterTokens = expression.parameterClause.map { tokenize($0, node: node) } ?? []
let throwTokens = expression.canThrow ? [expression.newToken(.keyword, "throws", node)] : []
let resultTokens = expression.functionResult.map { tokenize($0, node: node) } ?? []
return [
captureTokens,
parameterTokens,
throwTokens,
resultTokens,
].joined(token: expression.newToken(.space, " ", node))
}
open func tokenize(_ expression: ExplicitMemberExpression) -> [Token] {
switch expression.kind {
case let .tuple(postfixExpr, index):
return tokenize(postfixExpr) + expression.newToken(.delimiter, ".") +
expression.newToken(.number, "\(index)")
case let .namedType(postfixExpr, identifier):
return tokenize(postfixExpr) + expression.newToken(.delimiter, ".") +
expression.newToken(.identifier, identifier)
case let .generic(postfixExpr, identifier, genericArgumentClause):
return tokenize(postfixExpr) + expression.newToken(.delimiter, ".") +
expression.newToken(.identifier, identifier) +
tokenize(genericArgumentClause, node: expression)
case let .argument(postfixExpr, identifier, argumentNames):
let argumentTokens = argumentNames.isEmpty ? nil : argumentNames.flatMap {
expression.newToken(.identifier, $0) + expression.newToken(.delimiter, ":")
}.prefix(with: expression.newToken(.startOfScope, "("))
.suffix(with: expression.newToken(.endOfScope, ")"))
return tokenize(postfixExpr) + expression.newToken(.delimiter, ".") +
expression.newToken(.identifier, identifier) +
argumentTokens
}
}
open func tokenize(_ expression: ForcedValueExpression) -> [Token] {
return tokenize(expression.postfixExpression) + expression.newToken(.symbol, "!")
}
open func tokenize(_ expression: FunctionCallExpression) -> [Token] {
var parameterTokens = [Token]()
if let argumentClause = expression.argumentClause {
let argumentsTokens = argumentClause.map{ tokenize($0, node: expression) }
.joined(token: expression.newToken(.delimiter, ", "))
parameterTokens = expression.newToken(.startOfScope, "(") +
argumentsTokens +
expression.newToken(.endOfScope, ")")
}
var trailingTokens = [Token]()
if let trailingClosure = expression.trailingClosure {
trailingTokens = trailingClosure.newToken(.space, " ", expression) +
tokenize(trailingClosure)
}
return tokenize(expression.postfixExpression) + parameterTokens + trailingTokens
}
open func tokenize(_ expression: FunctionCallExpression.Argument, node: ASTNode) -> [Token] {
switch expression {
case .expression(let expr):
return tokenize(expr)
case let .namedExpression(identifier, expr):
return expression.newToken(.identifier, identifier, node) +
expression.newToken(.delimiter, ": ", node) +
tokenize(expr)
case .memoryReference(let expr):
return expression.newToken(.symbol, "&", node) + tokenize(expr)
case let .namedMemoryReference(name, expr):
return expression.newToken(.identifier, name, node) +
expression.newToken(.delimiter, ": ", node) +
expression.newToken(.symbol, "&", node) +
tokenize(expr)
case .operator(let op):
return [expression.newToken(.symbol, op, node)]
case let .namedOperator(identifier, op):
return expression.newToken(.identifier, identifier, node) +
expression.newToken(.delimiter, ": ", node) +
expression.newToken(.symbol, op, node)
}
}
open func tokenize(_ expression: IdentifierExpression) -> [Token] {
switch expression.kind {
case let .identifier(id, generic):
return expression.newToken(.identifier, id) + generic.map { tokenize($0, node: expression) }
case let .implicitParameterName(i, generic):
return expression.newToken(.symbol, "$") +
expression.newToken(.number, "\(i)") +
generic.map { tokenize($0, node: expression) }
case .bindingReference(let refVar):
return expression.newToken(.symbol, "$") + expression.newToken(.identifier, refVar)
}
}
open func tokenize(_ expression: ImplicitMemberExpression) -> [Token] {
return expression.newToken(.symbol, ".") + expression.newToken(.identifier, expression.identifier)
}
open func tokenize(_ expression: InOutExpression) -> [Token] {
return expression.newToken(.symbol, "&") + expression.newToken(.identifier, expression.identifier)
}
open func tokenize(_ expression: InitializerExpression) -> [Token] {
var tokens = tokenize(expression.postfixExpression) +
expression.newToken(.identifier, ".init")
if !expression.argumentNames.isEmpty {
let argumentNames = expression.argumentNames.flatMap {
return expression.newToken(.identifier, $0) +
expression.newToken(.delimiter, ":")
}
tokens = tokens +
expression.newToken(.startOfScope, "(") +
argumentNames +
expression.newToken(.endOfScope, ")")
}
return tokens
}
open func tokenize(_ expression: KeyPathStringExpression) -> [Token] {
return expression.newToken(.keyword, "#keyPath") +
expression.newToken(.startOfScope, "(") +
tokenize(expression.expression) +
expression.newToken(.endOfScope, ")")
}
open func tokenize(_ expression: LiteralExpression) -> [Token] {
switch expression.kind {
case .nil:
return [expression.newToken(.keyword, "nil")]
case .boolean(let bool):
return [expression.newToken(.keyword, bool ? "true" : "false")]
case let .integer(_, rawText):
return [expression.newToken(.number, rawText)]
case let .floatingPoint(_, rawText):
return [expression.newToken(.number, rawText)]
case let .staticString(_, rawText):
return [expression.newToken(.string, rawText)]
case let .interpolatedString(_, rawText):
return [expression.newToken(.string, rawText)]
case .array(let exprs):
return
expression.newToken(.startOfScope, "[") +
exprs.map { tokenize($0) }.joined(token: expression.newToken(.delimiter, ", ")) +
expression.newToken(.endOfScope, "]")
case .dictionary(let entries):
if entries.isEmpty {
return expression.newToken(.startOfScope, "[") +
expression.newToken(.delimiter, ":") +
expression.newToken(.endOfScope, "]")
}
return entries.map { tokenize($0, node: expression) }.joined(token: expression.newToken(.delimiter, ", "))
.prefix(with: expression.newToken(.startOfScope, "["))
.suffix(with: expression.newToken(.endOfScope, "]"))
case .playground(let playgroundLiteral):
return tokenize(playgroundLiteral, expression)
}
}
open func tokenize(_ playgroundLiteral: PlaygroundLiteral, _ expression: LiteralExpression) -> [Token] {
switch playgroundLiteral {
case let .color(red, green, blue, alpha):
var colorTokens = [
expression.newToken(.keyword, "#colorLiteral"),
expression.newToken(.startOfScope, "("),
]
colorTokens.append(contentsOf:
[("red", red), ("green", green), ("blue", blue), ("alpha", alpha)]
.map { expression.newToken(.keyword, $0.0) +
expression.newToken(.delimiter, ": ") + tokenize($0.1) }
.joined(token: expression.newToken(.delimiter, ", ")))
colorTokens.append(expression.newToken(.endOfScope, ")"))
return colorTokens
case .file(let resourceName):
return [
expression.newToken(.keyword, "#fileLiteral"),
expression.newToken(.startOfScope, "("),
expression.newToken(.keyword, "resourceName"),
expression.newToken(.delimiter, ": "),
] +
tokenize(resourceName) +
expression.newToken(.endOfScope, ")")
case .image(let resourceName):
return [
expression.newToken(.keyword, "#imageLiteral"),
expression.newToken(.startOfScope, "("),
expression.newToken(.keyword, "resourceName"),
expression.newToken(.delimiter, ": "),
] +
tokenize(resourceName) +
expression.newToken(.endOfScope, ")")
}
}
open func tokenize(_ expression: OptionalChainingExpression) -> [Token] {
return tokenize(expression.postfixExpression) + expression.newToken(.symbol, "?")
}
open func tokenize(_ expression: ParenthesizedExpression) -> [Token] {
return tokenize(expression.expression)
.prefix(with: expression.newToken(.startOfScope, "("))
.suffix(with: expression.newToken(.endOfScope, ")"))
}
open func tokenize(_ expression: PostfixOperatorExpression) -> [Token] {
return tokenize(expression.postfixExpression) +
expression.newToken(.symbol, expression.postfixOperator)
}
open func tokenize(_ expression: PostfixSelfExpression) -> [Token] {
return tokenize(expression.postfixExpression) +
expression.newToken(.symbol, ".") +
expression.newToken(.keyword, "self")
}
open func tokenize(_ expression: PrefixOperatorExpression) -> [Token] {
return expression.newToken(.symbol, expression.prefixOperator) +
tokenize(expression.postfixExpression)
}
open func tokenize(_ expression: SelectorExpression) -> [Token] {
switch expression.kind {
case .selector(let expr):
return expression.newToken(.keyword, "#selector") +
expression.newToken(.startOfScope, "(") +
tokenize(expr) +
expression.newToken(.endOfScope, ")")
case .getter(let expr):
return [expression.newToken(.keyword, "#selector"),
expression.newToken(.startOfScope, "("),
expression.newToken(.keyword, "getter"),
expression.newToken(.delimiter, ": ")] +
tokenize(expr) +
expression.newToken(.endOfScope, ")")
case .setter(let expr):
return [expression.newToken(.keyword, "#selector"),
expression.newToken(.startOfScope, "("),
expression.newToken(.keyword, "setter"),
expression.newToken(.delimiter, ": ")] +
tokenize(expr) +
expression.newToken(.endOfScope, ")")
case let .selfMember(identifier, argumentNames):
var tokens = [expression.newToken(.identifier, identifier)]
if !argumentNames.isEmpty {
let argumentNames = argumentNames.flatMap {
expression.newToken(.identifier, $0) +
expression.newToken(.delimiter, ":")
}
tokens += (argumentNames
.prefix(with: expression.newToken(.startOfScope, "("))
.suffix(with: expression.newToken(.endOfScope, ")")))
}
return [expression.newToken(.keyword, "#selector")] +
[expression.newToken(.startOfScope, "(")] +
tokens +
[expression.newToken(.endOfScope, ")")]
}
}
open func tokenize(_ expression: SelfExpression) -> [Token] {
switch expression.kind {
case .self:
return [expression.newToken(.keyword, "self")]
case .method(let name):
return expression.newToken(.keyword, "self") +
expression.newToken(.delimiter, ".") +
expression.newToken(.identifier, name)
case .subscript(let args):
return expression.newToken(.keyword, "self") +
expression.newToken(.startOfScope, "[") +
args.map { tokenize($0, node: expression) }.joined(token: expression.newToken(.delimiter, ", ")) +
expression.newToken(.endOfScope, "]")
case .initializer:
return expression.newToken(.keyword, "self") +
expression.newToken(.delimiter, ".") +
expression.newToken(.keyword, "init")
}
}
open func tokenize(_ element: SequenceExpression.Element, node: ASTNode) -> [Token] {
switch element {
case .expression(let expr):
return tokenize(expr)
case .assignmentOperator:
return [node.newToken(.symbol, "=")]
case .binaryOperator(let op):
return [node.newToken(.symbol, op)]
case .ternaryConditionalOperator(let expr):
return [
[node.newToken(.symbol, "?")],
tokenize(expr),
[node.newToken(.symbol, ":")],
].joined(token: node.newToken(.space, " "))
case .typeCheck(let type):
return [
[node.newToken(.keyword, "is")],
tokenize(type, node: node),
].joined(token: node.newToken(.space, " "))
case .typeCast(let type):
return [
[node.newToken(.keyword, "as")],
tokenize(type, node: node),
].joined(token: node.newToken(.space, " "))
case .typeConditionalCast(let type):
return [
[
node.newToken(.keyword, "as"),
node.newToken(.symbol, "?"),
],
tokenize(type, node: node),
].joined(token: node.newToken(.space, " "))
case .typeForcedCast(let type):
return [
[
node.newToken(.keyword, "as"),
node.newToken(.symbol, "!"),
],
tokenize(type, node: node),
].joined(token: node.newToken(.space, " "))
}
}
open func tokenize(_ expression: SequenceExpression) -> [Token] {
return expression.elements
.map({ tokenize($0, node: expression) })
.joined(token: expression.newToken(.space, " "))
}
open func tokenize(_ expression: SubscriptExpression) -> [Token] {
return tokenize(expression.postfixExpression) +
expression.newToken(.startOfScope, "[") +
expression.arguments.map { tokenize($0, node: expression) }
.joined(token: expression.newToken(.delimiter, ", ")) +
expression.newToken(.endOfScope, "]")
}
open func tokenize(_ expression: SuperclassExpression) -> [Token] {
switch expression.kind {
case .method(let name):
return expression.newToken(.keyword, "super") +
expression.newToken(.delimiter, ".") +
expression.newToken(.identifier, name)
case .subscript(let args):
return expression.newToken(.keyword, "super") +
expression.newToken(.startOfScope, "[") +
args.map { tokenize($0, node: expression) }.joined(token: expression.newToken(.delimiter, ", ")) +
expression.newToken(.endOfScope, "]")
case .initializer:
return expression.newToken(.keyword, "super") +
expression.newToken(.delimiter, ".") +
expression.newToken(.keyword, "init")
}
}
open func tokenize(_ expression: TernaryConditionalOperatorExpression) -> [Token] {
return [
tokenize(expression.conditionExpression),
[expression.newToken(.symbol, "?")],
tokenize(expression.trueExpression),
[expression.newToken(.symbol, ":")],
tokenize(expression.falseExpression),
].joined(token: expression.newToken(.space, " "))
}
open func tokenize(_ expression: TryOperatorExpression) -> [Token] {
switch expression.kind {
case .try(let expr):
return expression.newToken(.keyword, "try") +
expression.newToken(.space, " ") +
tokenize(expr)
case .forced(let expr):
return expression.newToken(.keyword, "try") +
expression.newToken(.symbol, "!") +
expression.newToken(.space, " ") +
tokenize(expr)
case .optional(let expr):
return expression.newToken(.keyword, "try") +
expression.newToken(.symbol, "?") +
expression.newToken(.space, " ") +
tokenize(expr)
}
}
open func tokenize(_ expression: TupleExpression) -> [Token] {
if expression.elementList.isEmpty {
return expression.newToken(.startOfScope, "(") +
expression.newToken(.endOfScope, ")")
}
return expression.elementList.map { element in
var idTokens = [Token]()
if let id = element.identifier {
idTokens = element.newToken(.identifier, id, expression) +
element.newToken(.delimiter, ": ", expression)
}
return idTokens + tokenize(element.expression)
}.joined(token: expression.newToken(.delimiter, ", "))
.prefix(with: expression.newToken(.startOfScope, "("))
.suffix(with: expression.newToken(.endOfScope, ")"))
}
open func tokenize(_ expression: TypeCastingOperatorExpression) -> [Token] {
let exprTokens: [Token]
let operatorTokens: [Token]
let typeTokens: [Token]
switch expression.kind {
case let .check(expr, type):
exprTokens = tokenize(expr)
operatorTokens = [expression.newToken(.keyword, "is")]
typeTokens = tokenize(type, node: expression)
case let .cast(expr, type):
exprTokens = tokenize(expr)
operatorTokens = [expression.newToken(.keyword, "as")]
typeTokens = tokenize(type, node: expression)
case let .conditionalCast(expr, type):
exprTokens = tokenize(expr)
operatorTokens = [expression.newToken(.keyword, "as"), expression.newToken(.symbol, "?")]
typeTokens = tokenize(type, node: expression)
case let .forcedCast(expr, type):
exprTokens = tokenize(expr)
operatorTokens = [expression.newToken(.keyword, "as"), expression.newToken(.symbol, "!")]
typeTokens = tokenize(type, node: expression)
}
return [
exprTokens,
operatorTokens,
typeTokens,
].joined(token: expression.newToken(.space, " "))
}
open func tokenize(_ expression: WildcardExpression) -> [Token] {
return [expression.newToken(.symbol, "_")]
}
open func tokenize(_ entry: DictionaryEntry, node: ASTNode) -> [Token] {
return tokenize(entry.key) +
entry.newToken(.delimiter, ": ", node) +
tokenize(entry.value)
}
open func tokenize(_ arg: SubscriptArgument, node: ASTNode) -> [Token] {
return arg.identifier.map { id in
return arg.newToken(.identifier, id, node) + arg.newToken(.delimiter, ": ", node)
} + tokenize(arg.expression)
}
// MARK: - Generics
open func tokenize(_ parameter: GenericParameterClause.GenericParameter, node: ASTNode) -> [Token] {
switch parameter {
case let .identifier(t):
return [parameter.newToken(.identifier, t, node)]
case let .typeConformance(t, typeIdentifier):
return parameter.newToken(.identifier, t, node) +
parameter.newToken(.delimiter, ": ", node) +
tokenize(typeIdentifier, node: node)
case let .protocolConformance(t, protocolCompositionType):
return parameter.newToken(.identifier, t, node) +
parameter.newToken(.delimiter, ": ", node) +
tokenize(protocolCompositionType, node: node)
}
}
open func tokenize(_ clause: GenericParameterClause, node: ASTNode) -> [Token] {
return
clause.newToken(.startOfScope, "<", node) +
clause.parameterList.map { tokenize($0, node: node) }
.joined(token: clause.newToken(.delimiter, ", ", node)) +
clause.newToken(.endOfScope, ">", node)
}
open func tokenize(_ clause: GenericWhereClause.Requirement, node: ASTNode) -> [Token] {
switch clause {
case let .sameType(t, type):
return tokenize(t, node: node) +
clause.newToken(.symbol, " == ", node) +
tokenize(type, node: node)
case let .typeConformance(t, typeIdentifier):
return tokenize(t, node: node) +
clause.newToken(.symbol, ": ", node) +
tokenize(typeIdentifier, node: node)
case let .protocolConformance(t, protocolCompositionType):
return tokenize(t, node: node) +
clause.newToken(.symbol, ": ", node) +
tokenize(protocolCompositionType, node: node)
}
}
open func tokenize(_ clause: GenericWhereClause, node: ASTNode) -> [Token] {
return clause.newToken(.keyword, "where", node) +
clause.newToken(.space, " ", node) +
clause.requirementList.map { tokenize($0, node: node) }
.joined(token: clause.newToken(.delimiter, ", ", node))
}
open func tokenize(_ clause: GenericArgumentClause, node: ASTNode) -> [Token] {
return clause.newToken(.startOfScope, "<", node) +
clause.argumentList.map { tokenize($0, node: node) }
.joined(token: clause.newToken(.delimiter, ", ", node)) +
clause.newToken(.endOfScope, ">", node)
}
// MARK: - Patterns
open func tokenize(_ pattern: Pattern, node: ASTNode) -> [Token] {
switch pattern {
case let pattern as EnumCasePattern:
return tokenize(pattern, node: node)
case let pattern as ExpressionPattern:
return tokenize(pattern)
case let pattern as IdentifierPattern:
return tokenize(pattern, node: node)
case let pattern as OptionalPattern:
return tokenize(pattern, node: node)
case let pattern as TuplePattern:
return tokenize(pattern, node: node)
case let pattern as TypeCastingPattern:
return tokenize(pattern, node: node)
case let pattern as ValueBindingPattern:
return tokenize(pattern, node: node)
case let pattern as WildcardPattern:
return tokenize(pattern, node: node)
default:
return [node.newToken(.identifier, pattern.textDescription)]
}
}
open func tokenize(_ pattern: EnumCasePattern, node: ASTNode) -> [Token] {
return
pattern.typeIdentifier.map { tokenize($0, node: node) } +
pattern.newToken(.delimiter, ".", node) +
pattern.newToken(.identifier, pattern.name, node) +
pattern.tuplePattern.map { tokenize($0, node: node) }
}
open func tokenize(_ pattern: ExpressionPattern) -> [Token] {
return tokenize(pattern.expression)
}
open func tokenize(_ pattern: IdentifierPattern, node: ASTNode) -> [Token] {
return
pattern.newToken(.identifier, pattern.identifier, node) +
pattern.typeAnnotation.map { tokenize($0, node: node) }
}
open func tokenize(_ pattern: OptionalPattern, node: ASTNode) -> [Token] {
switch pattern.kind {
case .identifier(let idPttrn):
return tokenize(idPttrn, node: node) + pattern.newToken(.symbol, "?", node)
case .wildcard:
return pattern.newToken(.symbol, "_", node) + pattern.newToken(.symbol, "?", node)
case .enumCase(let enumCasePttrn):
return tokenize(enumCasePttrn, node: node) + pattern.newToken(.symbol, "?", node)
case .tuple(let tuplePttrn):
return tokenize(tuplePttrn, node: node) + pattern.newToken(.symbol, "?", node)
}
}
open func tokenize(_ pattern: TuplePattern, node: ASTNode) -> [Token] {
return
pattern.newToken(.startOfScope, "(", node) +
pattern.elementList.map { tokenize($0, node: node) }
.joined(token: pattern.newToken(.delimiter, ", ", node)) +
pattern.newToken(.endOfScope, ")", node) +
pattern.typeAnnotation.map { tokenize($0, node: node) }
}
open func tokenize(_ element: TuplePattern.Element, node: ASTNode) -> [Token] {
switch element {
case .pattern(let pattern):
return tokenize(pattern, node: node)
case let .namedPattern(name, pattern):
return element.newToken(.identifier, name, node) +
element.newToken(.delimiter, ": ", node) +
tokenize(pattern, node: node)
}
}
open func tokenize(_ pattern: TypeCastingPattern, node: ASTNode) -> [Token] {
switch pattern.kind {
case .is(let type):
return pattern.newToken(.keyword, "is", node) +
pattern.newToken(.space, " ", node) +
tokenize(type, node: node)
case let .as(p, type):
return tokenize(p, node: node) +
pattern.newToken(.space, " ", node) +
pattern.newToken(.keyword, "as", node) +
pattern.newToken(.space, " ", node) +
tokenize(type, node: node)
}
}
open func tokenize(_ pattern: ValueBindingPattern, node: ASTNode) -> [Token] {
switch pattern.kind {
case .var(let p):
return pattern.newToken(.keyword, "var", node) +
pattern.newToken(.space, " ", node) +
tokenize(p, node: node)
case .let(let p):
return pattern.newToken(.keyword, "let", node) +
pattern.newToken(.space, " ", node) +
tokenize(p, node: node)
}
}
open func tokenize(_ pattern: WildcardPattern, node: ASTNode) -> [Token] {
return pattern.newToken(.keyword, "_", node) +
pattern.typeAnnotation.map { tokenize($0, node: node) }
}
// MARK: - Statements
open func tokenize(_ statement: Statement) -> [Token] { /*
swift-lint:suppress(high_cyclomatic_complexity) */
switch statement {
case let decl as Declaration:
return tokenize(decl)
case let expr as Expression:
return tokenize(expr)
case let stmt as BreakStatement:
return tokenize(stmt)
case let stmt as CompilerControlStatement:
return tokenize(stmt)
case let stmt as ContinueStatement:
return tokenize(stmt)
case let stmt as DeferStatement:
return tokenize(stmt)
case let stmt as DoStatement:
return tokenize(stmt)
case let stmt as FallthroughStatement:
return tokenize(stmt)
case let stmt as ForInStatement:
return tokenize(stmt)
case let stmt as GuardStatement:
return tokenize(stmt)
case let stmt as IfStatement:
return tokenize(stmt)
case let stmt as LabeledStatement:
return tokenize(stmt)
case let stmt as RepeatWhileStatement:
return tokenize(stmt)
case let stmt as ReturnStatement:
return tokenize(stmt)
case let stmt as SwitchStatement:
return tokenize(stmt)
case let stmt as ThrowStatement:
return tokenize(stmt)
case let stmt as WhileStatement:
return tokenize(stmt)
default:
return [
Token(
origin: statement as? ASTTokenizable,
node: statement as? ASTNode,
kind: .identifier,
value: statement.textDescription
),
]
}
}
open func tokenize(_ statement: BreakStatement) -> [Token] {
return [
[statement.newToken(.keyword, "break")],
statement.labelName.map { [statement.newToken(.identifier, $0)] } ?? []
].joined(token: statement.newToken(.space, " "))
}
open func tokenize(_ statement: CompilerControlStatement) -> [Token] {
switch statement.kind {
case .if(let condition):
return statement.newToken(.keyword, "#if") + statement.newToken(.identifier, condition)
case .elseif(let condition):
return statement.newToken(.keyword, "#elseif") + statement.newToken(.identifier, condition)
case .else:
return [statement.newToken(.keyword, "#else")]
case .endif:
return [statement.newToken(.keyword, "#endif")]
case let .sourceLocation(fileName, lineNumber):
var lineTokens = [Token]()
if let fileName = fileName, let lineNumber = lineNumber {
lineTokens = [statement.newToken(.identifier, "file: \"\(fileName)\", line: \(lineNumber)")]
}
return [
statement.newToken(.keyword, "#sourceLocation"),
statement.newToken(.startOfScope, "(")
] +
lineTokens +
[statement.newToken(.endOfScope, ")")]
}
}
open func tokenize(_ statement: ContinueStatement) -> [Token] {
return [
[statement.newToken(.keyword, "continue")],
statement.labelName.map { [statement.newToken(.identifier, $0)] } ?? []
].joined(token: statement.newToken(.space, " "))
}
open func tokenize(_ statement: DeferStatement) -> [Token] {
return [
[statement.newToken(.keyword, "defer")],
tokenize(statement.codeBlock)
].joined(token: statement.newToken(.space, " "))
}
open func tokenize(_ statement: DoStatement) -> [Token] {
return [
[statement.newToken(.keyword, "do")],
tokenize(statement.codeBlock),
tokenize(statement.catchClauses, node: statement)
].joined(token: statement.newToken(.space, " "))
}
open func tokenize(_ statements: [DoStatement.CatchClause], node: ASTNode) -> [Token] {
return statements.map { tokenize($0, node: node) }.joined(token: node.newToken(.space, " "))
}
open func tokenize(_ statement: DoStatement.CatchClause, node: ASTNode) -> [Token] {
let catchTokens = [statement.newToken(.keyword, "catch", node)]
let patternTokens = statement.pattern.map { tokenize($0, node: node) } ?? []
let whereKeyword = statement.whereExpression.map { _ in [statement.newToken(.keyword, "where", node)] } ?? []
let whereTokens = statement.whereExpression.map { tokenize($0) } ?? []
let codeTokens = tokenize(statement.codeBlock)
return [
catchTokens,
patternTokens,
whereKeyword,
whereTokens,
codeTokens
].joined(token: statement.newToken(.space, " ", node))
}
open func tokenize(_ statement: FallthroughStatement) -> [Token] {
return [statement.newToken(.keyword, "fallthrough")]
}
open func tokenize(_ statement: ForInStatement) -> [Token] {
let tokens: [[Token]] = [
[statement.newToken(.keyword, "for")],
statement.item.isCaseMatching ? [statement.newToken(.keyword, "case")] : [],
tokenize(statement.item.matchingPattern, node: statement),
[statement.newToken(.keyword, "in")],
tokenize(statement.collection),
statement.item.whereClause.map { _ in [statement.newToken(.keyword, "where")] } ?? [],
statement.item.whereClause.map { tokenize($0) } ?? [],
tokenize(statement.codeBlock)
]
return tokens.joined(token: statement.newToken(.space, " "))
}
open func tokenize(_ statement: GuardStatement) -> [Token] {
return [
[statement.newToken(.keyword, "guard")],
tokenize(statement.conditionList, node: statement),
[statement.newToken(.keyword, "else")],
tokenize(statement.codeBlock)
].joined(token: statement.newToken(.space, " "))
}
open func tokenize(_ statement: IfStatement) -> [Token] {
return [
[statement.newToken(.keyword, "if")],
tokenize(statement.conditionList, node: statement),
tokenize(statement.codeBlock),
statement.elseClause.map { tokenize($0, node: statement) } ?? []
].joined(token: statement.newToken(.space, " "))
}
open func tokenize(_ statement: IfStatement.ElseClause, node: ASTNode) -> [Token] {
var blockTokens = [Token]()
switch statement {
case .else(let codeBlock):
blockTokens = tokenize(codeBlock)
case .elseif(let ifStmt):
blockTokens = tokenize(ifStmt)
}
return [
[statement.newToken(.keyword, "else", node)],
blockTokens
].joined(token: statement.newToken(.space, " ", node))
}
open func tokenize(_ statement: LabeledStatement) -> [Token] {
return
statement.newToken(.identifier, statement.labelName, statement) +
statement.newToken(.delimiter, ": ") +
tokenize(statement.statement)
}
open func tokenize(_ statement: RepeatWhileStatement) -> [Token] {
return [
[statement.newToken(.keyword, "repeat")],
tokenize(statement.codeBlock),
[statement.newToken(.keyword, "while")],
tokenize(statement.conditionExpression),
].joined(token: statement.newToken(.space, " "))
}
open func tokenize(_ statement: ReturnStatement) -> [Token] {
return [
[statement.newToken(.keyword, "return")],
statement.expression.map { tokenize($0) } ?? []
].joined(token: statement.newToken(.space, " "))
}
open func tokenize(_ statement: SwitchStatement) -> [Token] {
var casesTokens = statement.newToken(.startOfScope, "{") + statement.newToken(.endOfScope, "}")
if !statement.cases.isEmpty {
casesTokens = [
[statement.newToken(.startOfScope, "{")],
statement.cases.map { tokenize($0, node: statement) }
.joined(token: statement.newToken(.linebreak, "\n")),
[statement.newToken(.endOfScope, "}")]
].joined(token: statement.newToken(.linebreak, "\n"))
}
return [
[statement.newToken(.keyword, "switch")],
tokenize(statement.expression),
casesTokens
].joined(token: statement.newToken(.space, " "))
}
open func tokenize(_ statement: SwitchStatement.Case, node: ASTNode) -> [Token] {
switch statement {
case let .case(itemList, stmts):
var tokens = [
statement.newToken(.keyword, "case", node),
statement.newToken(.space, " ", node),
]
tokens.append(contentsOf: itemList
.map { tokenize($0, node: node) }
.joined(token: statement.newToken(.delimiter, ", ", node)))
tokens.append(statement.newToken(.delimiter, ":", node))
tokens.append(statement.newToken(.linebreak, "\n", node))
tokens.append(contentsOf: indent(tokenize(stmts, node: node)))
return tokens
case .default(let stmts):
return
statement.newToken(.keyword, "default", node) +
statement.newToken(.delimiter, ":", node) +
statement.newToken(.linebreak, "\n", node) +
indent(tokenize(stmts, node: node))
}
}
open func tokenize(_ statement: SwitchStatement.Case.Item, node: ASTNode) -> [Token] {
return [
tokenize(statement.pattern, node: node),
statement.whereExpression.map { _ in [statement.newToken(.keyword, "where", node)] } ?? [],
statement.whereExpression.map { tokenize($0) } ?? []
].joined(token: statement.newToken(.space, " ", node))
}
open func tokenize(_ statement: ThrowStatement) -> [Token] {
return
statement.newToken(.keyword, "throw") +
statement.newToken(.space, " ") +
tokenize(statement.expression)
}
open func tokenize(_ statement: WhileStatement) -> [Token] {
return [
[statement.newToken(.keyword, "while")],
tokenize(statement.conditionList, node: statement),
tokenize(statement.codeBlock)
].joined(token: statement.newToken(.space, " "))
}
// MARK: Utils
open func tokenize(_ statements: [Statement], node: ASTNode) -> [Token] {
return statements.map(tokenize).joined(token: node.newToken(.linebreak, "\n"))
}
open func tokenize(_ conditions: ConditionList, node: ASTNode) -> [Token] {
return conditions.map { tokenize($0, node: node) }.joined(token: node.newToken(.delimiter, ", "))
}
open func tokenize(_ condition: Condition, node: ASTNode) -> [Token] {
switch condition {
case .expression(let expr):
return tokenize(expr)
case .availability(let availabilityCondition):
return tokenize(availabilityCondition, node: node)
case let .case(pattern, expr):
return [
[condition.newToken(.keyword, "case", node)],
tokenize(pattern, node: node),
[condition.newToken(.symbol, "=", node)],
tokenize(expr)
].joined(token: condition.newToken(.space, " ", node))
case let .let(pattern, expr):
return [
[condition.newToken(.keyword, "let", node)],
tokenize(pattern, node: node),
[condition.newToken(.symbol, "=", node)],
tokenize(expr)
].joined(token: condition.newToken(.space, " ", node))
case let .var(pattern, expr):
return [
[condition.newToken(.keyword, "var", node)],
tokenize(pattern, node: node),
[condition.newToken(.symbol, "=", node)],
tokenize(expr)
].joined(token: condition.newToken(.space, " ", node))
}
}
open func tokenize(_ condition: AvailabilityCondition, node: ASTNode) -> [Token] {
return
condition.newToken(.keyword, "#available", node) +
condition.newToken(.startOfScope, "(", node) +
condition.arguments.map { tokenize($0, node: node) }
.joined(token: condition.newToken(.delimiter, ", ", node)) +
condition.newToken(.endOfScope, ")", node)
}
open func tokenize(_ argument: AvailabilityCondition.Argument, node: ASTNode) -> [Token] {
return [argument.newToken(.identifier, argument.textDescription, node)]
}
// MARK: - Types
open func tokenize(_ type: Type, node: ASTNode) -> [Token] {
switch type {
case let type as AnyType:
return tokenize(type, node: node)
case let type as ArrayType:
return tokenize(type, node: node)
case let type as DictionaryType:
return tokenize(type, node: node)
case let type as FunctionType:
return tokenize(type, node: node)
case let type as ImplicitlyUnwrappedOptionalType:
return tokenize(type, node: node)
case let type as MetatypeType:
return tokenize(type, node: node)
case let type as OptionalType:
return tokenize(type, node: node)
case let type as ProtocolCompositionType:
return tokenize(type, node: node)
case let type as SelfType:
return tokenize(type, node: node)
case let type as TupleType:
return tokenize(type, node: node)
case let type as TypeIdentifier:
return tokenize(type, node: node)
default:
return [node.newToken(.identifier, type.textDescription)]
}
}
open func tokenize(_ type: AnyType, node: ASTNode) -> [Token] {
return [type.newToken(.keyword, "Any", node)]
}
open func tokenize(_ type: ArrayType, node: ASTNode) -> [Token] {
return type.newToken(.startOfScope, "[", node) +
tokenize(type.elementType, node: node) +
type.newToken(.endOfScope, "]", node)
}
open func tokenize(_ type: DictionaryType, node: ASTNode) -> [Token] {
return (
tokenize(type.keyType, node: node) +
type.newToken(.delimiter, ":", node) +
type.newToken(.space, " ", node) +
tokenize(type.valueType, node: node)
).prefix(with: type.newToken(.startOfScope, "[", node))
.suffix(with: type.newToken(.endOfScope, "]", node))
}
open func tokenize(_ type: FunctionType, node: ASTNode) -> [Token] {
let attrs = tokenize(type.attributes, node: node)
let args = type.newToken(.startOfScope, "(", node) +
type.arguments.map { tokenize($0, node: node) }
.joined(token: type.newToken(.delimiter, ", ", node)) +
type.newToken(.endOfScope, ")", node)
let throwTokens = tokenize(type.throwsKind, node: node)
let returnTokens = tokenize(type.returnType, node: node)
return [
attrs,
args,
throwTokens,
[type.newToken(.symbol, "->", node)],
returnTokens
].joined(token: type.newToken(.space, " ", node))
}
open func tokenize(_ type: FunctionType.Argument, node: ASTNode) -> [Token] {
let tokens = [
type.externalName.map { [type.newToken(.identifier, $0, node)]} ?? [],
type.localName.map { [
type.newToken(.identifier, $0, node),
type.newToken(.delimiter, ":", node)
]} ?? [],
tokenize(type.attributes, node: node),
type.isInOutParameter ? [type.newToken(.keyword, "inout", node)] : [],
tokenize(type.type, node: node),
]
let variadicDots = type.isVariadic ? [type.newToken(.keyword, "...", node)] : []
return tokens.joined(token: type.newToken(.space, " ", node)) +
variadicDots
}
open func tokenize(_ type: ImplicitlyUnwrappedOptionalType, node: ASTNode) -> [Token] {
return tokenize(type.wrappedType, node: node) +
type.newToken(.symbol, "!", node)
}
open func tokenize(_ type: MetatypeType, node: ASTNode) -> [Token] {
let kind: Token
switch type.kind {
case .type:
kind = type.newToken(.keyword, "Type", node)
case .protocol:
kind = type.newToken(.keyword, "Protocol", node)
}
return [tokenize(type.referenceType, node: node),
[type.newToken(.delimiter, ".", node)],
[kind]
].joined()
}
open func tokenize(_ type: OptionalType, node: ASTNode) -> [Token] {
return tokenize(type.wrappedType, node: node) +
type.newToken(.symbol, "?", node)
}
open func tokenize(_ type: ProtocolCompositionType, node: ASTNode) -> [Token] {
if node is ClassDeclaration || node is StructDeclaration || node is EnumDeclaration {
return
type.newToken(.keyword, "protocol", node) +
type.newToken(.startOfScope, "<", node) +
type.protocolTypes.map { tokenize($0, node: node) }
.joined(token: type.newToken(.delimiter, ", ", node)) +
type.newToken(.endOfScope, ">", node)
} else {
return type.protocolTypes.map { tokenize($0, node: node) }
.joined(token: type.newToken(.delimiter, " & ", node))
}
}
open func tokenize(_ type: SelfType, node: ASTNode) -> [Token] {
return [type.newToken(.keyword, "Self", node)]
}
open func tokenize(_ type: TupleType, node: ASTNode) -> [Token] {
return type.newToken(.startOfScope, "(", node) +
type.elements.map { tokenize($0, node: node) }.joined(token: type.newToken(.delimiter, ", ", node)) +
type.newToken(.endOfScope, ")", node)
}
open func tokenize(_ type: TupleType.Element, node: ASTNode) -> [Token] {
let inoutTokens = type.isInOutParameter ? [type.newToken(.keyword, "inout", node)] : []
var nameTokens = [Token]()
if let name = type.name {
nameTokens = type.newToken(.identifier, name, node) +
type.newToken(.delimiter, ":", node)
}
return [
nameTokens,
tokenize(type.attributes, node: node),
inoutTokens,
tokenize(type.type, node: node)
].joined(token: type.newToken(.space, " ", node))
}
open func tokenize(_ type: TypeAnnotation, node: ASTNode) -> [Token] {
let inoutTokens = type.isInOutParameter ? [type.newToken(.keyword, "inout", node)] : []
return [
[type.newToken(.delimiter, ":", node)],
tokenize(type.attributes, node: node),
inoutTokens,
tokenize(type.type, node: node)
].joined(token: type.newToken(.space, " ", node))
}
open func tokenize(_ type: TypeIdentifier, node: ASTNode) -> [Token] {
return type.names.map { tokenize($0, node: node) }
.joined(token: type.newToken(.delimiter, ".", node))
}
open func tokenize(_ type: TypeIdentifier.TypeName, node: ASTNode) -> [Token] {
return type.newToken(.identifier, type.name, node) +
type.genericArgumentClause.map { tokenize($0, node: node) }
}
open func tokenize(_ type: TypeInheritanceClause, node: ASTNode) -> [Token] {
var inheritanceTokens = type.classRequirement ? [[type.newToken(.keyword, "class", node)]] : [[]]
inheritanceTokens += type.typeInheritanceList.map { tokenize($0, node: node) }
return type.newToken(.symbol, ": ", node) +
inheritanceTokens.joined(token: type.newToken(.delimiter, ", ", node))
}
// MARK: - Utils
open func tokenize(_ origin: ThrowsKind, node: ASTNode) -> [Token] {
switch origin {
case .nothrowing: return []
case .throwing: return [origin.newToken(.keyword, "throws", node)]
case .rethrowing: return [origin.newToken(.keyword, "rethrows", node)]
}
}
}
| apache-2.0 | e83f58841bcd1d7ade52dc494428cfcb | 42.944371 | 119 | 0.583972 | 4.961426 | false | false | false | false |
u10int/Kinetic | Pod/Classes/Spring.swift | 1 | 1926 | //
// Spring.swift
// Kinetic
//
// Created by Nicholas Shipes on 12/30/15.
// Copyright © 2015 Urban10 Interactive, LLC. All rights reserved.
//
// Spring.swift used and adapted from Cheetah library under the MIT license, https://github.com/suguru/Cheetah
// Created by Suguru Namura on 2015/08/19.
// Copyright © 2015年 Suguru Namura.
import UIKit
public class Spring {
let tension: Double
let friction: Double
var velocity: Double = 0
var current: Double = 0
var elapsed: Double = 0
var ended: Bool = false
fileprivate let tolerence: Double = 1 / 100000
fileprivate let maxDT: Double = 16 / 1000
init(tension: Double = 500, friction: Double = 20) {
self.tension = tension
self.friction = friction
}
fileprivate func acceleration(forX x: Double, v: Double) -> Double {
return (-tension * x) - (friction * v)
}
fileprivate func proceedStep(_ stepSize: Double) {
elapsed += stepSize
if ended {
return
}
let x = current - 1
let v = velocity
let ax = v
let av = acceleration(forX: x, v: v)
let bx = v + av * stepSize * 0.5
let bv = acceleration(forX: x + ax * stepSize * 0.5, v: bx)
let cx = v + bv * stepSize * 0.5
let cv = acceleration(forX: x + bx * stepSize * 0.5, v: cx)
let dx = v + cv * stepSize
let dv = acceleration(forX: x + cx * stepSize, v: dx)
let dxdt = 1.0 / 6.0 * (ax + 2.0 * (bx + cx) + dx)
let dvdt = 1.0 / 6.0 * (av + 2.0 * (bv + cv) + dv)
let afterx = x + dxdt * stepSize
let afterv = v + dvdt * stepSize
ended = abs(afterx) < tolerence && abs(afterv) < tolerence
if ended {
current = 1
velocity = 0
} else {
current = 1 + afterx
velocity = afterv
}
}
func proceed(_ dt: Double) {
var dt = dt
while dt > maxDT {
proceedStep(maxDT)
dt -= maxDT
}
if dt > 0 {
proceedStep(dt)
}
}
func reset() {
current = 0
velocity = 0
elapsed = 0
ended = false
}
}
| mit | c27b9a7b43ca4275e30de6c3142bca9c | 20.355556 | 111 | 0.613424 | 2.952381 | false | false | false | false |
dpereira411/GCTabView | GCTabView-swift/TabBarViewController.swift | 1 | 6791 | //
// TabBarViewController.swift
// GCTabView-swift
//
// Created by Daniel Pereira on 14/11/14.
// Copyright (c) 2014 Daniel Pereira. All rights reserved.
//
import Cocoa
enum TabBarMouseState {
case Possible
case Began
case Finished
case Canceled
}
protocol TabBarViewControllerDelegate {
func didSelectIndex(index: Int)
}
class TabBarViewController: NSViewController {
private let tab = TabBarView()
private let buttons = NSView()
private var items = Array<TabBarItem>()
private var state = TabBarMouseState.Possible
private var selected: TabBarItem?
var delegate: TabBarViewControllerDelegate?
override func loadView() {
self.view = self.tab
}
override func viewDidLoad() {
super.viewDidLoad()
let gr = UpDownMouseGestureRecognizer(target: self, action: Selector("mouse:"));
self.view.addGestureRecognizer(gr)
self.buttons.translatesAutoresizingMaskIntoConstraints = false
self.view.addSubview(self.buttons)
self.buttons.needsLayout = true
self.view.addConstraint(NSLayoutConstraint(item: self.tab, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: self.buttons, attribute: NSLayoutAttribute.CenterX, multiplier: 1, constant: 0))
self.view.addConstraint(NSLayoutConstraint(item: self.view, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: self.buttons, attribute: NSLayoutAttribute.Top, multiplier: 1, constant: 0))
self.buttons.addConstraint(NSLayoutConstraint(item: self.buttons, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: 28))
self.view.addConstraint(NSLayoutConstraint(item: self.buttons, attribute: NSLayoutAttribute.Leading, relatedBy: NSLayoutRelation.GreaterThanOrEqual, toItem: self.view, attribute: NSLayoutAttribute.Leading, multiplier: 1, constant: 10))
}
func addItem(item: TabBarItem) {
self.items.append(item)
}
private func removeSubviews() {
for view in self.items {
view.removeFromSuperview()
}
}
func updateButtons() {
self.removeSubviews()
let buttonsWidth = CGFloat(self.items.count) * TabBarItem.width()
self.buttons.addConstraint(NSLayoutConstraint(item: self.buttons, attribute: NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.GreaterThanOrEqual, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: buttonsWidth))
for (index, view) in enumerate(self.items) {
let leading = CGFloat(index) * TabBarItem.width()
let trailing = CGFloat((self.items.count - 1 - index)) * TabBarItem.width()
view.index = index
view.translatesAutoresizingMaskIntoConstraints = false
view.needsLayout = true
self.buttons.addSubview(view)
self.buttons.addConstraint(NSLayoutConstraint(item: view, attribute: NSLayoutAttribute.Leading, relatedBy: NSLayoutRelation.Equal, toItem: self.buttons, attribute: NSLayoutAttribute.Leading, multiplier: 1, constant: leading))
self.buttons.addConstraint(NSLayoutConstraint(item: self.buttons, attribute: NSLayoutAttribute.Trailing, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.Trailing, multiplier: 1, constant: trailing))
self.buttons.addConstraint(NSLayoutConstraint(item: self.buttons, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.Top, multiplier: 1, constant: 0))
}
if let first = self.items.first {
first.updateState(TabBarItemState.Tinted)
if let index = first.index {
self.delegate?.didSelectIndex(index)
}
}
if self.items.count > 1 {
let range = Range(start: 1, end: self.items.count)
for (index, view) in enumerate(self.items[range]) {
view.updateState(TabBarItemState.Regular)
}
}
}
func mouse(gr: UpDownMouseGestureRecognizer) {
switch gr.state {
case .Began:
self.down(gr.locationInView(self.buttons))
case .Changed:
self.drag(gr.locationInView(self.buttons))
case .Ended:
self.up()
default:
break;
}
}
private func testHit(x: CGFloat) -> TabBarItem? {
var hit: TabBarItem?
for (index, view) in enumerate(self.items) {
//println("\(x) - \(NSMinX(view.frame)) and \(NSMaxX(view.frame))")
if x > NSMinX(view.frame) && x < NSMaxX(view.frame) {
hit = view
}
}
return hit;
}
private func up() {
if self.state == TabBarMouseState.Began {
if let index = self.selected?.index {
self.delegate?.didSelectIndex(index)
}
self.setSelectedState(TabBarItemState.Tinted)
self.state = TabBarMouseState.Possible
}
}
private func down(location: NSPoint) {
if let hit = self.testHit(location.x) {
self.state = TabBarMouseState.Began
self.selected = hit
self.setSelectedState(TabBarItemState.Bold)
}
}
private func drag(location: NSPoint) {
if self.state != .Began {
return
}
if let hit = self.testHit(location.x) {
self.selected = hit;
} else {
if location.x <= NSMinX(self.buttons.frame) {
self.selected = self.items.first
} else if location.x >= NSMaxX(self.buttons.frame) {
self.selected = self.items.last
}
}
self.setSelectedState(TabBarItemState.Bold)
}
private func setSelectedState(state: TabBarItemState) {
for view in self.items {
if self.selected == view {
view.updateState(state)
} else {
view.updateState(TabBarItemState.Regular)
}
}
}
}
| mit | 1bacf2843037b7e2c18144dd18ab6ca2 | 28.271552 | 255 | 0.588426 | 5.183969 | false | false | false | false |
yichizhang/JCTiledScrollView_Swift | JCTiledScrollView_Swift_Source/JCPDFDocument.swift | 1 | 2079 | //
// Copyright (c) 2015-present Yichi Zhang
// https://github.com/yichizhang
// [email protected]
//
// This source code is licensed under MIT license found in the LICENSE file
// in the root directory of this source tree.
// Attribution can be found in the ATTRIBUTION file in the root directory
// of this source tree.
//
import UIKit
import Foundation
class JCPDFDocument
{
class func createX(_ documentURL: URL!, password: String!) -> CGPDFDocument?
{
// Check for non-NULL CFURLRef
guard let document = CGPDFDocument(documentURL as CFURL) else {
return nil
}
// Encrypted
// Try a blank password first, per Apple's Quartz PDF example
if document.isEncrypted == true &&
document.unlockWithPassword("") == false {
// Nope, now let's try the provided password to unlock the PDF
if let cPasswordString = password.cString(using: String.Encoding.utf8) {
if document.unlockWithPassword(cPasswordString) == false {
// Unlock failed
#if DEBUG
print("CGPDFDocumentCreateX: Unable to unlock \(documentURL)")
#endif
}
}
}
return document
}
class func needsPassword(_ documentURL: URL!, password: String!) -> Bool
{
var needsPassword = false
// Check for non-NULL CFURLRef
guard let document = CGPDFDocument(documentURL as CFURL) else {
return needsPassword
}
// Encrypted
// Try a blank password first, per Apple's Quartz PDF example
if document.isEncrypted == true &&
document.unlockWithPassword("") == false {
// Nope, now let's try the provided password to unlock the PDF
if let cPasswordString = password.cString(using: String.Encoding.utf8) {
if document.unlockWithPassword(cPasswordString) == false {
needsPassword = true
}
}
}
return needsPassword
}
}
| mit | 6aa8ca01a441ea9f13f8380a7b1e0bdb | 30.5 | 84 | 0.601732 | 4.735763 | false | false | false | false |
AndreMuis/TISensorTag | TISensorTag/Views/TSTMainViewController.swift | 1 | 12124 | //
// TSTViewController.swift
// TISensorTag
//
// Created by Andre Muis on 5/9/16.
// Copyright © 2016 Andre Muis. All rights reserved.
//
import CoreBluetooth
import SceneKit
import UIKit
import STGTISensorTag
class TSTMainViewController : UIViewController, STGCentralManagerDelegate, STGSensorTagDelegate
{
@IBOutlet weak var centralManagerStateLabel: UILabel!
@IBOutlet weak var connectionStatusLabel: UILabel!
@IBOutlet weak var rssiBarGaugeView: TSTBarGaugeView!
@IBOutlet weak var magneticFieldStrengthBarGaugeView: TSTBarGaugeView!
@IBOutlet weak var leftKeyView: TSTSimpleKeyView!
@IBOutlet weak var rightKeyView: TSTSimpleKeyView!
@IBOutlet weak var temperatureLabel: UILabel!
@IBOutlet weak var humidityLabel: UILabel!
@IBOutlet weak var barometricPressureLabel: UILabel!
@IBOutlet weak var messagesTextView: UITextView!
var centralManager : STGCentralManager!
var sensorTag : STGSensorTag?
var angularVelocityViewController : TSTAngularVelocityViewController?
var accelerationViewController : TSTAccelerationViewController?
required init?(coder aDecoder: NSCoder)
{
super.init(coder: aDecoder)
self.centralManager = STGCentralManager(delegate: self)
self.sensorTag = nil
self.angularVelocityViewController = nil
self.accelerationViewController = nil
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?)
{
if let viewController = segue.destinationViewController as? TSTAngularVelocityViewController
{
self.angularVelocityViewController = viewController
}
else if let viewController = segue.destinationViewController as? TSTAccelerationViewController
{
self.accelerationViewController = viewController
}
}
override func viewDidLoad()
{
super.viewDidLoad()
self.view.backgroundColor = TSTConstants.mainViewBackgroundColor
self.messagesTextView.backgroundColor = TSTConstants.messagesTextViewBackgroundColor
self.centralManagerStateLabel.text = self.centralManager.state.desscription
self.connectionStatusLabel.text = self.centralManager.connectionStatus.rawValue
self.rssiBarGaugeView.setup(backgroundColor: TSTConstants.RSSIBarGaugeView.backgroundColor,
indicatorColor: TSTConstants.RSSIBarGaugeView.indicatorColor)
self.magneticFieldStrengthBarGaugeView.setup(backgroundColor: TSTConstants.MagneticFieldStrengthBarGaugeView.backgroundColor,
indicatorColor: TSTConstants.MagneticFieldStrengthBarGaugeView.indicatorColor)
self.leftKeyView.setup()
self.rightKeyView.setup()
self.resetUI()
}
func scheduleRSSITimer()
{
NSTimer.scheduledTimerWithTimeInterval(TSTConstants.rssiUpdateIntervalInSeconds,
target: self,
selector: #selector(TSTMainViewController.readRSSI),
userInfo: nil,
repeats: false)
}
func readRSSI()
{
if let sensorTag : STGSensorTag = self.sensorTag
{
sensorTag.readRSSI()
}
}
// MARK: STGCentralManagerDelegate
func centralManagerDidUpdateState(state: STGCentralManagerState)
{
self.centralManagerStateLabel.text = state.desscription
if (state == STGCentralManagerState.PoweredOn)
{
self.centralManagerStateLabel.textColor = TSTConstants.centralManagerPoweredOnTextColor
self.centralManager.startScanningForSensorTags()
}
else
{
self.centralManagerStateLabel.textColor = UIColor.blackColor()
}
}
func centralManagerDidUpdateConnectionStatus(status: STGCentralManagerConnectionStatus)
{
self.connectionStatusLabel.text = status.rawValue
}
func centralManager(central: STGCentralManager, didConnectSensorTagPeripheral peripheral: CBPeripheral)
{
let sensorTag : STGSensorTag = STGSensorTag(delegate: self, peripheral: peripheral)
self.sensorTag = sensorTag
self.scheduleRSSITimer()
sensorTag.discoverServices()
}
func centralManager(central: STGCentralManager, didDisconnectSensorTagPeripheral peripheral: CBPeripheral)
{
self.sensorTag = nil
self.resetUI()
}
func centralManager(central: STGCentralManager, didEncounterError error: NSError)
{
if error.domain == CBErrorDomain && error.code == CBError.PeripheralDisconnected.rawValue
{
self.sensorTag = nil
self.resetUI()
}
self.addMessage(error.description)
}
// MARK: STGSensorTagDelegate
func sensorTag(sensorTag: STGSensorTag, didUpdateRSSI rssi: NSNumber)
{
let rssiValue : Float = rssi.floatValue
self.rssiBarGaugeView.normalizedReading = (rssiValue - STGConstants.rssiMinimum) / (STGConstants.rssiMaximum - STGConstants.rssiMinimum)
self.scheduleRSSITimer()
}
func sensorTag(sensorTag: STGSensorTag, didDiscoverCharacteristicsForAccelerometer accelerometer: STGAccelerometer)
{
sensorTag.accelerometer.enable(measurementPeriodInMilliseconds: TSTConstants.Accelerometer.measurementPeriodInMilliseconds,
lowPassFilteringFactor: TSTConstants.Accelerometer.lowPassFilteringFactor)
}
func sensorTag(sensorTag: STGSensorTag, didDiscoverCharacteristicsForBarometricPressureSensor sensor: STGBarometricPressureSensor)
{
sensorTag.barometricPressureSensor.enable(measurementPeriodInMilliseconds: TSTConstants.BarometricPressureSensor.measurementPeriodInMilliseconds)
}
func sensorTag(sensorTag: STGSensorTag, didDiscoverCharacteristicsForGyroscope gyroscope: STGGyroscope)
{
sensorTag.gyroscope.enable(measurementPeriodInMilliseconds: TSTConstants.Gyroscope.measurementPeriodInMilliseconds)
}
func sensorTag(sensorTag: STGSensorTag, didDiscoverCharacteristicsForHumiditySensor humiditySensor: STGHumiditySensor)
{
sensorTag.humiditySensor.enable(measurementPeriodInMilliseconds: TSTConstants.HumiditySensor.measurementPeriodInMilliseconds)
}
func sensorTag(sensorTag: STGSensorTag, didDiscoverCharacteristicsForMagnetometer magnetometer: STGMagnetometer)
{
sensorTag.magnetometer.enable(measurementPeriodInMilliseconds: TSTConstants.Magnetometer.measurementPeriodInMilliseconds)
}
func sensorTag(sensorTag: STGSensorTag, didDiscoverCharacteristicsForSimpleKeysService simpleKeysService: STGSimpleKeysService)
{
sensorTag.simpleKeysService.enable()
}
func sensorTag(sensorTag: STGSensorTag, didDiscoverCharacteristicsForTemperatureSensor temperatureSensor: STGTemperatureSensor)
{
sensorTag.temperatureSensor.enable(measurementPeriodInMilliseconds: TSTConstants.TemperatureSensor.measurementPeriodInMilliseconds)
}
func sensorTag(sensorTag: STGSensorTag, didUpdateAcceleration acceleration: STGVector)
{
}
func sensorTag(sensorTag: STGSensorTag, didUpdateSmoothedAcceleration acceleration: STGVector)
{
if let viewController : TSTAccelerationViewController = self.accelerationViewController
{
viewController.didUpdateSmoothedAcceleration(acceleration: acceleration)
}
}
func sensorTag(sensorTag: STGSensorTag, didUpdateBarometricPressure pressure: Int)
{
self.displayBarometricPressure(pressure)
}
func sensorTag(sensorTag: STGSensorTag, didUpdateAngularVelocity angularVelocity: STGVector)
{
if let viewController : TSTAngularVelocityViewController = self.angularVelocityViewController
{
viewController.didUpdateAngularVelocity(angularVelocity: angularVelocity)
}
}
func sensorTag(sensorTag: STGSensorTag, didUpdateRelativeHumidity relativeHumidity: Float)
{
self.displayRelativeHumidity(relativeHumidity)
}
func sensorTag(sensorTag : STGSensorTag, didUpdateMagneticField magneticField : STGVector)
{
let minimum : Float = STGConstants.Magnetometer.magneticFieldStrengthMinimum
let maximum : Float = STGConstants.Magnetometer.magneticFieldStrengthMaximum
self.magneticFieldStrengthBarGaugeView.normalizedReading = (magneticField.magnitude - minimum) / (maximum - minimum)
}
func sensorTag(sensorTag: STGSensorTag, didUpdateSimpleKeysState state: STGSimpleKeysState?)
{
if let someState = state
{
switch someState
{
case STGSimpleKeysState.NonePressed:
self.leftKeyView.depress()
self.rightKeyView.depress()
case STGSimpleKeysState.LeftPressed:
self.leftKeyView.press()
self.rightKeyView.depress()
case STGSimpleKeysState.RightPressed:
self.leftKeyView.depress()
self.rightKeyView.press()
case STGSimpleKeysState.BothPressed:
self.leftKeyView.press()
self.rightKeyView.press()
}
}
}
func sensorTag(sensorTag: STGSensorTag, didUpdateAmbientTemperature temperature: STGTemperature)
{
self.displayAmbientTemperature(temperature)
}
func sensorTag(sensorTag: STGSensorTag, didEncounterError error: NSError)
{
addMessage(error.description)
}
// MARK:
func resetUI()
{
self.rssiBarGaugeView.normalizedReading = 0.0
if let viewController : TSTAngularVelocityViewController = self.angularVelocityViewController
{
viewController.resetUI()
}
if let viewController : TSTAccelerationViewController = self.accelerationViewController
{
viewController.resetUI()
}
self.magneticFieldStrengthBarGaugeView.normalizedReading = 0.0
self.leftKeyView.depress()
self.rightKeyView.depress()
self.displayAmbientTemperature(nil)
self.displayRelativeHumidity(nil)
self.displayBarometricPressure(nil)
}
func displayAmbientTemperature(ambientTemperature : STGTemperature?)
{
if let temperature = ambientTemperature
{
self.temperatureLabel.text = "\(temperature.fahrenheit.format(".1")) \u{00B0}F"
}
else
{
self.temperatureLabel.text = "? \u{00B0}F"
}
}
func displayRelativeHumidity(relativeHumidity: Float?)
{
if let humidity = relativeHumidity
{
self.humidityLabel.text = "\(humidity.format(".0"))%"
}
else
{
self.humidityLabel.text = "? %"
}
}
func displayBarometricPressure(barometricPressure: Int?)
{
if let pressure = barometricPressure
{
self.barometricPressureLabel.text = String(pressure)
}
else
{
self.barometricPressureLabel.text = "?"
}
}
func addMessage(message : String)
{
if self.messagesTextView.text.isEmpty == true
{
self.messagesTextView.text = self.messagesTextView.text + message
}
else
{
self.messagesTextView.text = self.messagesTextView.text + "\n\n" + message
}
let bottom : NSRange = NSMakeRange(self.messagesTextView.text.characters.count - 1, 1)
self.messagesTextView.scrollRangeToVisible(bottom)
}
}
| mit | a329185c24e10aa9fa8edd4e3b4215b7 | 32.304945 | 153 | 0.669966 | 6.113464 | false | false | false | false |
catloafsoft/AudioKit | AudioKit/Common/Internals/AKTable.swift | 1 | 2947 | //
// AKTable.swift
// AudioKit
//
// Created by Aurelius Prochazka, revision history on Github.
// Copyright (c) 2015 Aurelius Prochazka. All rights reserved.
//
import Foundation
/// Supported default table types
public enum AKTableType: String {
/// Standard sine waveform
case Sine
/// Standard triangle waveform
case Triangle
/// Standard square waveform
case Square
/// Standard sawtooth waveform
case Sawtooth
/// Reversed sawtooth waveform
case ReverseSawtooth
}
/// A table of values accessible as a waveform or lookup mechanism
public struct AKTable {
// MARK: - Properties
/// Values stored in the table
public var values = [Float]()
/// Number of values stored in the table
var size = 4096
/// Type of table
var type: AKTableType
// MARK: - Initialization
/// Initialize and set up the default table
///
/// - parameter tableType: AKTableType of teh new table
/// - parameter size: Size of the table (multiple of 2)
///
public init(_ tableType: AKTableType = .Sine, size tableSize: Int = 4096) {
type = tableType
size = tableSize
switch type {
case .Sine:
self.standardSineWave()
case .Sawtooth:
self.standardSawtoothWave()
case .Triangle:
self.standardTriangleWave()
case .ReverseSawtooth:
self.standardReverseSawtoothWave()
case .Square:
self.standardSquareWave()
}
}
/// Instantiate the table as a triangle wave
mutating func standardTriangleWave() {
values = [Float]()
let slope = Float(4.0) / Float(size)
for i in 0..<size {
if i < size / 2 {
values.append(slope * Float(i) - 1.0)
} else {
values.append(slope * Float(-i) + 3.0)
}
}
}
/// Instantiate the table as a square wave
mutating func standardSquareWave() {
values = [Float]()
for i in 0..<size {
if i < size / 2 {
values.append(-1.0)
} else {
values.append(1.0)
}
}
}
/// Instantiate the table as a sawtooth wave
mutating func standardSawtoothWave() {
values = [Float]()
for i in 0..<size {
values.append(-1.0 + 2.0*Float(i)/Float(size))
}
}
/// Instantiate the table as a reverse sawtooth wave
mutating func standardReverseSawtoothWave() {
values = [Float]()
for i in 0..<size {
values.append(1.0 - 2.0*Float(i)/Float(size))
}
}
/// Instantiate the table as a sine wave
mutating func standardSineWave() {
values = [Float]()
for i in 0..<size {
values.append(sin(2 * 3.14159265 * Float(i)/Float(size)))
}
}
} | mit | cd4dfc45b2075ef92d7db71877fef198 | 24.634783 | 79 | 0.553444 | 4.533846 | false | false | false | false |
giggle-engineer/DOFavoriteButton | DOFavoriteButton-DEMO/DOFavoriteButton-OSX/ViewController.swift | 2 | 2547 | //
// ViewController.swift
// DOFavoriteButton-OSX
//
// Created by Chloe Stars on 7/17/15.
// Copyright © 2015 Daiki Okumura. All rights reserved.
//
import Cocoa
import DOFavoriteButton
class ViewController: NSViewController {
override func viewDidLoad() {
super.viewDidLoad()
let width = (self.view.frame.width - 44) / 4
var x = width / 2
let y = self.view.frame.height / 2
// star button
let starButton = DOFavoriteButton(frame: CGRectMake(x, y, 44, 44))
self.view.addSubview(starButton)
x += width
// heart button
let heartButton = DOFavoriteButton(frame: CGRectMake(x, y, 44, 44), image: NSImage(named: "heart"), imageFrame: CGRectMake(12, 12, 20, 20))
heartButton.imageColorOn = NSColor(red: 254/255, green: 110/255, blue: 111/255, alpha: 1.0)
heartButton.circleColor = NSColor(red: 254/255, green: 110/255, blue: 111/255, alpha: 1.0)
heartButton.lineColor = NSColor(red: 226/255, green: 96/255, blue: 96/255, alpha: 1.0)
heartButton.bordered = false
self.view.addSubview(heartButton)
x += width
// like button
let likeButton = DOFavoriteButton(frame: CGRectMake(x, y, 44, 44), image: NSImage(named: "like"), imageFrame: CGRectMake(12, 12, 20, 20))
likeButton.imageColorOn = NSColor(red: 52/255, green: 152/255, blue: 219/255, alpha: 1.0)
likeButton.circleColor = NSColor(red: 52/255, green: 152/255, blue: 219/255, alpha: 1.0)
likeButton.lineColor = NSColor(red: 41/255, green: 128/255, blue: 185/255, alpha: 1.0)
self.view.addSubview(likeButton)
x += width
// smile button
let smileButton = DOFavoriteButton(frame: CGRectMake(x, y, 44, 44), image: NSImage(named: "smile"), imageFrame: CGRectMake(12, 12, 20, 20))
smileButton.imageColorOn = NSColor(red: 45/255, green: 204/255, blue: 112/255, alpha: 1.0)
smileButton.circleColor = NSColor(red: 45/255, green: 204/255, blue: 112/255, alpha: 1.0)
smileButton.lineColor = NSColor(red: 45/255, green: 195/255, blue: 106/255, alpha: 1.0)
self.view.addSubview(smileButton)
// Do any additional setup after loading the view.
}
@IBAction func liked(sender: DOFavoriteButton) {
NSLog("button was pressed, state is: %@", !sender.selected)
}
override var representedObject: AnyObject? {
didSet {
// Update the view, if already loaded.
}
}
}
| mit | e8c639c86e43a4bb3044fef6be54cc4d | 38.169231 | 147 | 0.626866 | 3.727672 | false | false | false | false |
merlos/iOS-Open-GPX-Tracker | Pods/MapCache/MapCache/Classes/DiskCache/DiskCache.swift | 1 | 12084 | //
// DiskCache.swift
// MapCache
//
// Created by merlos on 02/06/2019.
//
// Based on Haneke Disk Cache
// https://github.com/Haneke/HanekeSwift
//
import Foundation
///
/// A specialized cache for storing data in disk.
/// Based on [Haneke Disk Cache](https://github.com/Haneke/HanekeSwift) and customized for the MapCache project.
///
open class DiskCache {
/// Gets the root base folder to be used.
open class func baseURL() -> URL {
// where should you put your files
// https://developer.apple.com/library/archive/documentation/FileManagement/Conceptual/FileSystemProgrammingGuide/FileSystemOverview/FileSystemOverview.html#//apple_ref/doc/uid/TP40010672-CH2-SW28
let cachePath = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.cachesDirectory, FileManager.SearchPathDomainMask.userDomainMask, true)[0]
let baseURL = URL(fileURLWithPath: cachePath, isDirectory: true).appendingPathComponent("DiskCache", isDirectory: true)
return baseURL
}
/// URL of the physical folder of the Cache in the file system.
public let folderURL: URL
/// A shortcut for `folderURL.path`.
open var path: String {
get {
return self.folderURL.path
}
}
/// Sum of the allocated size in disk for the cache expressed in bytes.
///
/// Note that, this size is the actual disk allocation. It is equivalent with the amount of bytes
/// that would become available on the volume if the directory is deleted.
///
/// For example, a file may just contain 156 bytes of data (size listed in `ls` command), however its
/// disk size is 4096, 1 volume block (as listed using `du -h`)
///
/// This size is calculated each time
open var diskSize : UInt64 = 0
/// This is the sum of the data sizes of the files within the `DiskCache`
///
/// This size is calculated each time it is used
/// - Seealso: `diskSize`
open var fileSize: UInt64? {
return try? FileManager.default.fileSizeForDirectory(at: folderURL)
}
/// Maximum allowed cache disk allocated size for this `DiskCache``
/// Defaults to unlimited capacity (`UINT64_MAX`)
open var capacity : UInt64 = UINT64_MAX {
didSet {
self.cacheQueue.async(execute: {
self.controlCapacity()
})
}
}
/// Queue for making async operations.
open lazy var cacheQueue : DispatchQueue = {
let queueName = "DiskCache.\(folderURL.lastPathComponent)"
let cacheQueue = DispatchQueue(label: queueName, attributes: [])
return cacheQueue
}()
/// Constructor
/// - Parameter withName: Name of the cache, will be the subfolder name too.
/// - Parameter capacity: capacity of the cache in bytes. Defaults to virutally unlimited capacity (`UINT64_MAX`)
public init(withName cacheName: String, capacity: UInt64 = UINT64_MAX) {
folderURL = DiskCache.baseURL().appendingPathComponent(cacheName, isDirectory: true)
do {
try FileManager.default.createDirectory(at: self.folderURL, withIntermediateDirectories: true, attributes: nil)
} catch {
Log.error(message: "DiskCache::init --- Failed to create directory \(folderURL.absoluteString)", error: error)
}
self.capacity = capacity
cacheQueue.async(execute: {
self.diskSize = self.calculateDiskSize()
self.controlCapacity()
})
//Log.debug(message: "DiskCache folderURL=\(folderURL.absoluteString)")
}
/// Get the path for key.
open func path(forKey key: String) -> String {
return self.folderURL.appendingPathComponent(key.toMD5()).path
}
/// Sets the data for the key asyncronously.
/// Use this function for writing into the cache.
open func setData( _ data: Data, forKey key: String) {
cacheQueue.async(execute: {
self.setDataSync(data, forKey: key)
})
}
/// Sets the data for the key synchronously.
open func setDataSync(_ data: Data, forKey key: String) {
let filePath = path(forKey: key)
Log.debug(message: "DiskCache::setDataSync --- filePath: \(filePath) data count: \(data.count) key: \(key) diskBlocks:\(Double(data.count) / 4096.0)")
//If the file exists get the current file diskSize.
let fileURL = URL(fileURLWithPath: filePath)
do {
substract(diskSize: try fileURL.regularFileAllocatedDiskSize())
} catch {} //if file is not found do nothing
do {
try data.write(to: URL(fileURLWithPath: filePath), options: Data.WritingOptions.atomicWrite)
} catch {
Log.error(message: "DiskCache::setDataSync --- Failed to write key: \(key) filepath: \(filePath)", error: error)
}
//Now add to the diskSize the file size
var diskBlocks = Double(data.count) / 4096.0
diskBlocks.round(.up)
diskSize += UInt64(diskBlocks * 4096.0)
self.controlCapacity()
}
/// Fetches the image data from storage synchronously.
///
/// - Parameter forKey: Key within the cache
/// - Parameter failure: closure to be run in case of error
/// - Parameter success: closure to be run once the data is ready
///
open func fetchDataSync(forKey key: String, failure fail: ((Error?) -> ())? = nil, success succeed: @escaping (Data) -> ()) {
let path = self.path(forKey: key)
do {
let data = try Data(contentsOf: URL(fileURLWithPath: path), options: Data.ReadingOptions())
succeed(data)
self.updateDiskAccessDate(atPath: path)
} catch {
if let block = fail {
block(error)
}
}
}
/// Removes asynchronously the data from the diskcache for the key passed as argument.
/// - Parameter withKey: key to be removed
open func removeData(withKey key: String) {
cacheQueue.async(execute: {
let path = self.path(forKey: key)
self.removeFile(atPath: path)
})
}
/// Removes asynchronously all data from the cache.
/// Calls completition closure once the task is done.
/// - Parameter completition: closure run once all the files are deleted from the cache
open func removeAllData(_ completion: (() -> ())? = nil) {
let fileManager = FileManager.default
cacheQueue.async(execute: {
do {
let contents = try fileManager.contentsOfDirectory(atPath: self.path)
for filename in contents {
let filePath = self.folderURL.appendingPathComponent(filename).path
do {
try fileManager.removeItem(atPath: filePath)
Log.debug(message: "DiskCache::removeAllData --- Removed path \(filename)")
} catch {
Log.error(message: "DiskCache::removeAllData --- Failed to remove path \(filePath)", error: error)
}
}
self.diskSize = self.calculateDiskSize()
Log.debug(message: "DiskCache::removeAllData --- Size at the end \(self.diskSize)")
} catch {
Log.error(message: "DiskCache::removeAllData --- Failed to list directory", error: error)
}
if let completion = completion {
DispatchQueue.main.async {
completion()
}
}
})
}
/// Removes the cache from the system.
/// This method not only removes the data, it also removes the cache folder.
///
/// Do not call any method after removing the cache, create a new instance instead.
///
open func removeCache() {
do {
try FileManager.default.removeItem(at: self.folderURL)
} catch {
Log.error(message: "Diskcache::removeCache --- Error removing DiskCache folder", error: error)
}
}
/// Asynchronously updates the access date of a file.
open func updateAccessDate( _ getData: @autoclosure @escaping () -> Data?, key: String) {
cacheQueue.async(execute: {
let path = self.path(forKey: key)
let fileManager = FileManager.default
if (!(fileManager.fileExists(atPath: path) && self.updateDiskAccessDate(atPath: path))){
if let data = getData() {
self.setDataSync(data, forKey: key)
} else {
Log.error(message: "DiskCache::updateAccessDate --- Failed to get data for key \(key)")
}
}
})
}
/// Calculates the size used by all the files in the cache.
public func calculateDiskSize() -> UInt64 {
let fileManager = FileManager.default
var currentSize : UInt64 = 0
do {
currentSize = try fileManager.allocatedDiskSizeForDirectory(at: folderURL)
}
catch {
Log.error(message: "DiskCache::calculateDiskSize --- Failed to get diskSize of directory", error: error)
}
return currentSize
}
// MARK: Private
/// It checks if the capacity of the cache has been reached. If so, it removes the least recently used file (LRU).
fileprivate func controlCapacity() {
if self.diskSize <= self.capacity { return }
let fileManager = FileManager.default
let cachePath = self.path
fileManager.enumerateContentsOfDirectory(
atPath: cachePath,
orderedByProperty: URLResourceKey.contentModificationDateKey.rawValue, ascending: true) {
(URL : URL, _, stop : inout Bool) -> Void in
self.removeFile(atPath: URL.path)
stop = self.diskSize <= self.capacity
}
}
/// Updates the time a file was accessed for the last time.
@discardableResult fileprivate func updateDiskAccessDate(atPath path: String) -> Bool {
let fileManager = FileManager.default
let now = Date()
do {
try fileManager.setAttributes([FileAttributeKey.modificationDate : now], ofItemAtPath: path)
return true
} catch {
Log.error(message: "DiskCache::updateDiskAccessDate --- Failed to update access date", error: error)
return false
}
}
/// Removes a file syncrhonously.
fileprivate func removeFile(atPath path: String) {
let fileManager = FileManager.default
do {
let fileURL = URL(fileURLWithPath: path)
let fileSize = try fileURL.regularFileAllocatedDiskSize()
try fileManager.removeItem(atPath: path)
substract(diskSize: fileSize)
} catch {
if isNoSuchFileError(error) {
Log.error(message: "DiskCache::removeFile --- Failed to remove file. File not found", error: error)
} else {
Log.error(message: "DiskCache::removeFile --- Failed to remove file. Size or other error", error: error)
}
}
}
/// Substracts from the cachesize the disk size passed as parameter.
/// Logs an error message if the amount to be substracted is larger than the current used disk space.
///
/// - Parameter diskSize: disksize to be deducted
fileprivate func substract(diskSize : UInt64) {
if (self.diskSize >= diskSize) {
self.diskSize -= diskSize
} else {
Log.error(message: "DiskCache::diskSize --- (\(self.diskSize)) is smaller than diskSize to substract (\(diskSize))")
self.diskSize = 0
}
}
}
/// Error when there is not a file.
private func isNoSuchFileError(_ error : Error?) -> Bool {
if let error = error {
return NSCocoaErrorDomain == (error as NSError).domain && (error as NSError).code == NSFileReadNoSuchFileError
}
return false
}
| gpl-3.0 | a8ffb359fe99817d8a275172db41de17 | 40.102041 | 204 | 0.61089 | 4.872581 | false | false | false | false |
MattesGroeger/BrightFutures | BrightFuturesTests/ResultTests.swift | 1 | 5859 | // The MIT License (MIT)
//
// Copyright (c) 2014 Thomas Visser
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import XCTest
import Result
import BrightFutures
extension Result {
var isSuccess: Bool {
return self.analysis(ifSuccess: { _ in return true }, ifFailure: { _ in return false })
}
var isFailure: Bool {
return !isSuccess
}
}
class ResultTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testSuccess() {
let result = Result<Int,NSError>(value: 3)
XCTAssert(result.isSuccess)
XCTAssertFalse(result.isFailure)
XCTAssertEqual(result.value!, 3)
XCTAssertNil(result.error)
let result1 = Result<Int,NSError>(value: 4)
XCTAssert(result1.isSuccess)
XCTAssertFalse(result1.isFailure)
XCTAssertEqual(result1.value!, 4)
XCTAssertNil(result1.error)
}
func testFailure() {
let error = NSError(domain: "TestDomain", code: 2, userInfo: nil)
let result = Result<Int, NSError>(error: error)
XCTAssert(result.isFailure)
XCTAssertFalse(result.isSuccess)
XCTAssertEqual(result.error!, error)
XCTAssertNil(result.value)
}
func testMapSuccess() {
let r = Result<Int,NSError>(value: 2).map { i -> Bool in
XCTAssertEqual(i, 2)
return i % 2 == 0
}
XCTAssertTrue(r.isSuccess)
XCTAssertEqual(r.value!, true)
}
func testMapFailure() {
let r = Result<Int, NSError>(error: NSError(domain: "error", code: 1, userInfo: nil)).map { i -> Int in
XCTAssert(false, "map should not get called if the result failed")
return i * 2
}
XCTAssert(r.isFailure)
XCTAssertEqual(r.error!.domain, "error")
}
func testFlatMapResultSuccess() {
let r = divide(20, 5).flatMap {
divide($0, 2)
}
XCTAssertEqual(r.value!, 2)
}
func testFlatMapResultFailure() {
let r = divide(20, 0).flatMap { i -> Result<Int, MathError> in
XCTAssert(false, "flatMap should not get called if the result failed")
return divide(i, 2)
}
XCTAssert(r.isFailure)
XCTAssertEqual(r.error!, MathError.DivisionByZero)
}
func testFlatMapFutureSuccess() {
let f = divide(100, 10).flatMap { i -> Future<Int, MathError> in
return future {
fibonacci(i)
}.promoteError()
}
let e = self.expectation()
f.onSuccess { i in
XCTAssertEqual(i, 55)
e.fulfill()
}
self.waitForExpectationsWithTimeout(2, handler: nil)
}
func testFlatMapFutureFailure() {
let f = divide(100, 0).flatMap { i -> Future<Int, MathError> in
XCTAssert(false, "flatMap should not get called if the result failed")
return future {
fibonacci(i)
}.promoteError()
}
let e = self.expectation()
f.onFailure { err in
XCTAssertEqual(err, MathError.DivisionByZero)
e.fulfill()
}
self.waitForExpectationsWithTimeout(2, handler: nil)
}
func testSequenceSuccess() {
let results: [Result<Int, MathError>] = (1...10).map { i in
return divide(123, i)
}
let result: Result<[Int], MathError> = results.sequence()
let outcome = [123, 61, 41, 30, 24, 20, 17, 15, 13, 12]
XCTAssertEqual(result.value!, outcome)
}
func testSequenceFailure() {
let results: [Result<Int, MathError>] = (-10...10).map { i in
return divide(123, i)
}
let r = results.sequence()
XCTAssert(r.isFailure)
XCTAssertEqual(r.error!, MathError.DivisionByZero)
}
func testRecoverNeeded() {
let r = divide(10, 0).recover(2)
XCTAssertEqual(r, 2)
XCTAssertEqual(divide(10, 0) ?? 2, 2)
}
func testRecoverUnneeded() {
let r = divide(10, 3).recover(10)
XCTAssertEqual(r, 3)
XCTAssertEqual(divide(10, 3) ?? 10, 3)
}
}
enum MathError: ErrorType {
case DivisionByZero
}
func divide(a: Int, _ b: Int) -> Result<Int, MathError> {
if (b == 0) {
return Result(error: .DivisionByZero)
}
return Result(value: a / b)
}
| mit | 6522e09ec2aebbc3329da9e01b1f3632 | 29.836842 | 111 | 0.597713 | 4.475936 | false | true | false | false |
tadyjp/ShareCalc | ShareCalc/ExpenseListViewController.swift | 1 | 3573 | //
// ExpenseListViewController.swift
// ShareCalc
//
// Created by tady on 9/23/14.
// Copyright (c) 2014 tady. All rights reserved.
//
import UIKit
class ExpenseListViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet weak var expenseTableView: UITableView!
@IBOutlet weak var totalValueLabelViewWrapper: UIView!
@IBOutlet weak var totalItemsLabelViewWrapper: UIView!
@IBOutlet weak var totalPayersLabelViewWrapper: UIView!
var totalValueLabelView: ValueLabelView!
var totalItemsLabelView: ValueLabelView!
var totalPayersLabelView: ValueLabelView!
override func viewDidLoad() {
super.viewDidLoad()
self.totalValueLabelView = ValueLabelView.render("total", value: "0")
self.totalValueLabelViewWrapper.addSubview(self.totalValueLabelView)
self.totalItemsLabelView = ValueLabelView.render("items", value: "0")
self.totalItemsLabelViewWrapper.addSubview(self.totalItemsLabelView)
self.totalPayersLabelView = ValueLabelView.render("payers", value: "0")
self.totalPayersLabelViewWrapper.addSubview(self.totalPayersLabelView)
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
self.expenseTableView.reloadData()
let app: AppDelegate = (UIApplication.sharedApplication().delegate as AppDelegate)
self.totalValueLabelView.valueField.text = Helpers.formatValue(app.expenseList.reduce(0, combine: {$0 + $1.value}))
self.totalItemsLabelView.valueField.text = String(app.expenseList.count)
self.totalPayersLabelView.valueField.text = String($.uniq(app.expenseList.map({ (item) in item.payer })).count)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let app: AppDelegate = (UIApplication.sharedApplication().delegate as AppDelegate)
return app.expenseList.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let app: AppDelegate = (UIApplication.sharedApplication().delegate as AppDelegate)
let cell: ExpenseTableViewCell = self.expenseTableView.dequeueReusableCellWithIdentifier("ExpenseTableViewCell") as ExpenseTableViewCell
cell.dateField.text = app.expenseList[indexPath.row].dateWithFormat
cell.valueField.text = app.expenseList[indexPath.row].valueWithFormat
cell.typeField.text = app.expenseList[indexPath.row].type
cell.payerField.text = app.expenseList[indexPath.row].payer
return cell;
}
// 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!) {
let expenseEditViewController: ExpenseDetailViewController = segue.destinationViewController as ExpenseDetailViewController
switch segue.identifier {
case "toExpenseEdit":
let indexPath: NSIndexPath = self.expenseTableView.indexPathForSelectedRow()!
expenseEditViewController.expenseIndexPathRow = indexPath.row
expenseEditViewController.actionType = "edit"
case "toExpenseAdd":
expenseEditViewController.actionType = "add"
default:
break
}
}
}
| mit | 5af49b7a6b5de6d5a715f33777af585e | 42.048193 | 144 | 0.722362 | 5.285503 | false | false | false | false |
julien-c/swifter | Sources/Swifter/HttpRequest.swift | 1 | 992 | //
// HttpRequest.swift
// Swifter
// Copyright (c) 2015 Damian Kołakowski. All rights reserved.
//
import Foundation
public struct HttpRequest {
public let url: String
public let urlParams: [(String, String)]
public let method: String
public let headers: [String: String]
public let body: [UInt8]?
public var address: String?
public var params: [String: String]
public func parseForm() -> [(String, String)] {
if let body = body {
return UInt8ArrayToUTF8String(body).split("&").map { (param: String) -> (String, String) in
let tokens = param.split("=")
if tokens.count >= 2 {
let key = tokens[0].replace("+", new: " ").removePercentEncoding()
let value = tokens[1].replace("+", new: " ").removePercentEncoding()
return (key, value)
}
return ("","")
}
}
return []
}
}
| bsd-3-clause | 7d30538a8acec5f83ad6421423f14e3c | 29.030303 | 103 | 0.535822 | 4.525114 | false | false | false | false |
whong7/swift-knowledge | 思维导图/4-3:网易新闻/Pods/Kingfisher/Sources/AnimatedImageView.swift | 66 | 12494 | //
// AnimatableImageView.swift
// Kingfisher
//
// Created by bl4ckra1sond3tre on 4/22/16.
//
// The AnimatableImageView, AnimatedFrame and Animator is a modified version of
// some classes from kaishin's Gifu project (https://github.com/kaishin/Gifu)
//
// The MIT License (MIT)
//
// Copyright (c) 2017 Reda Lemeden.
//
// 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.
//
// The name and characters used in the demo of this software are property of their
// respective owners.
import UIKit
import ImageIO
/// `AnimatedImageView` is a subclass of `UIImageView` for displaying animated image.
open class AnimatedImageView: UIImageView {
/// Proxy object for prevending a reference cycle between the CADDisplayLink and AnimatedImageView.
class TargetProxy {
private weak var target: AnimatedImageView?
init(target: AnimatedImageView) {
self.target = target
}
@objc func onScreenUpdate() {
target?.updateFrame()
}
}
// MARK: - Public property
/// Whether automatically play the animation when the view become visible. Default is true.
public var autoPlayAnimatedImage = true
/// The size of the frame cache.
public var framePreloadCount = 10
/// Specifies whether the GIF frames should be pre-scaled to save memory. Default is true.
public var needsPrescaling = true
/// The animation timer's run loop mode. Default is `NSRunLoopCommonModes`. Set this property to `NSDefaultRunLoopMode` will make the animation pause during UIScrollView scrolling.
public var runLoopMode = RunLoopMode.commonModes {
willSet {
if runLoopMode == newValue {
return
} else {
stopAnimating()
displayLink.remove(from: .main, forMode: runLoopMode)
displayLink.add(to: .main, forMode: newValue)
startAnimating()
}
}
}
// MARK: - Private property
/// `Animator` instance that holds the frames of a specific image in memory.
private var animator: Animator?
/// A flag to avoid invalidating the displayLink on deinit if it was never created, because displayLink is so lazy. :D
private var isDisplayLinkInitialized: Bool = false
/// A display link that keeps calling the `updateFrame` method on every screen refresh.
private lazy var displayLink: CADisplayLink = {
self.isDisplayLinkInitialized = true
let displayLink = CADisplayLink(target: TargetProxy(target: self), selector: #selector(TargetProxy.onScreenUpdate))
displayLink.add(to: .main, forMode: self.runLoopMode)
displayLink.isPaused = true
return displayLink
}()
// MARK: - Override
override open var image: Image? {
didSet {
if image != oldValue {
reset()
}
setNeedsDisplay()
layer.setNeedsDisplay()
}
}
deinit {
if isDisplayLinkInitialized {
displayLink.invalidate()
}
}
override open var isAnimating: Bool {
if isDisplayLinkInitialized {
return !displayLink.isPaused
} else {
return super.isAnimating
}
}
/// Starts the animation.
override open func startAnimating() {
if self.isAnimating {
return
} else {
displayLink.isPaused = false
}
}
/// Stops the animation.
override open func stopAnimating() {
super.stopAnimating()
if isDisplayLinkInitialized {
displayLink.isPaused = true
}
}
override open func display(_ layer: CALayer) {
if let currentFrame = animator?.currentFrame {
layer.contents = currentFrame.cgImage
} else {
layer.contents = image?.cgImage
}
}
override open func didMoveToWindow() {
super.didMoveToWindow()
didMove()
}
override open func didMoveToSuperview() {
super.didMoveToSuperview()
didMove()
}
// This is for back compatibility that using regular UIImageView to show GIF.
override func shouldPreloadAllGIF() -> Bool {
return false
}
// MARK: - Private method
/// Reset the animator.
private func reset() {
animator = nil
if let imageSource = image?.kf.imageSource?.imageRef {
animator = Animator(imageSource: imageSource, contentMode: contentMode, size: bounds.size, framePreloadCount: framePreloadCount)
animator?.needsPrescaling = needsPrescaling
animator?.prepareFramesAsynchronously()
}
didMove()
}
private func didMove() {
if autoPlayAnimatedImage && animator != nil {
if let _ = superview, let _ = window {
startAnimating()
} else {
stopAnimating()
}
}
}
/// Update the current frame with the displayLink duration.
private func updateFrame() {
if animator?.updateCurrentFrame(duration: displayLink.duration) ?? false {
layer.setNeedsDisplay()
}
}
}
/// Keeps a reference to an `Image` instance and its duration as a GIF frame.
struct AnimatedFrame {
var image: Image?
let duration: TimeInterval
static let null: AnimatedFrame = AnimatedFrame(image: .none, duration: 0.0)
}
// MARK: - Animator
class Animator {
// MARK: Private property
fileprivate let size: CGSize
fileprivate let maxFrameCount: Int
fileprivate let imageSource: CGImageSource
fileprivate var animatedFrames = [AnimatedFrame]()
fileprivate let maxTimeStep: TimeInterval = 1.0
fileprivate var frameCount = 0
fileprivate var currentFrameIndex = 0
fileprivate var currentPreloadIndex = 0
fileprivate var timeSinceLastFrameChange: TimeInterval = 0.0
fileprivate var needsPrescaling = true
/// Loop count of animatd image.
private var loopCount = 0
var currentFrame: UIImage? {
return frame(at: currentFrameIndex)
}
var contentMode = UIViewContentMode.scaleToFill
private lazy var preloadQueue: DispatchQueue = {
return DispatchQueue(label: "com.onevcat.Kingfisher.Animator.preloadQueue")
}()
/**
Init an animator with image source reference.
- parameter imageSource: The reference of animated image.
- parameter contentMode: Content mode of AnimatedImageView.
- parameter size: Size of AnimatedImageView.
- parameter framePreloadCount: Frame cache size.
- returns: The animator object.
*/
init(imageSource source: CGImageSource, contentMode mode: UIViewContentMode, size: CGSize, framePreloadCount count: Int) {
self.imageSource = source
self.contentMode = mode
self.size = size
self.maxFrameCount = count
}
func frame(at index: Int) -> Image? {
return animatedFrames[safe: index]?.image
}
func prepareFramesAsynchronously() {
preloadQueue.async { [weak self] in
self?.prepareFrames()
}
}
private func prepareFrames() {
frameCount = CGImageSourceGetCount(imageSource)
if let properties = CGImageSourceCopyProperties(imageSource, nil),
let gifInfo = (properties as NSDictionary)[kCGImagePropertyGIFDictionary as String] as? NSDictionary,
let loopCount = gifInfo[kCGImagePropertyGIFLoopCount as String] as? Int
{
self.loopCount = loopCount
}
let frameToProcess = min(frameCount, maxFrameCount)
animatedFrames.reserveCapacity(frameToProcess)
animatedFrames = (0..<frameToProcess).reduce([]) { $0 + pure(prepareFrame(at: $1))}
currentPreloadIndex = (frameToProcess + 1) % frameCount
}
private func prepareFrame(at index: Int) -> AnimatedFrame {
guard let imageRef = CGImageSourceCreateImageAtIndex(imageSource, index, nil) else {
return AnimatedFrame.null
}
let defaultGIFFrameDuration = 0.100
let frameDuration = imageSource.kf.gifProperties(at: index).map {
gifInfo -> Double in
let unclampedDelayTime = gifInfo[kCGImagePropertyGIFUnclampedDelayTime as String] as Double?
let delayTime = gifInfo[kCGImagePropertyGIFDelayTime as String] as Double?
let duration = unclampedDelayTime ?? delayTime ?? 0.0
/**
http://opensource.apple.com/source/WebCore/WebCore-7600.1.25/platform/graphics/cg/ImageSourceCG.cpp
Many annoying ads specify a 0 duration to make an image flash as quickly as
possible. We follow Safari and Firefox's behavior and use a duration of 100 ms
for any frames that specify a duration of <= 10 ms.
See <rdar://problem/7689300> and <http://webkit.org/b/36082> for more information.
See also: http://nullsleep.tumblr.com/post/16524517190/animated-gif-minimum-frame-delay-browser.
*/
return duration > 0.011 ? duration : defaultGIFFrameDuration
} ?? defaultGIFFrameDuration
let image = Image(cgImage: imageRef)
let scaledImage: Image?
if needsPrescaling {
scaledImage = image.kf.resize(to: size, for: contentMode)
} else {
scaledImage = image
}
return AnimatedFrame(image: scaledImage, duration: frameDuration)
}
/**
Updates the current frame if necessary using the frame timer and the duration of each frame in `animatedFrames`.
*/
func updateCurrentFrame(duration: CFTimeInterval) -> Bool {
timeSinceLastFrameChange += min(maxTimeStep, duration)
guard let frameDuration = animatedFrames[safe: currentFrameIndex]?.duration, frameDuration <= timeSinceLastFrameChange else {
return false
}
timeSinceLastFrameChange -= frameDuration
let lastFrameIndex = currentFrameIndex
currentFrameIndex += 1
currentFrameIndex = currentFrameIndex % animatedFrames.count
if animatedFrames.count < frameCount {
preloadFrameAsynchronously(at: lastFrameIndex)
}
return true
}
private func preloadFrameAsynchronously(at index: Int) {
preloadQueue.async { [weak self] in
self?.preloadFrame(at: index)
}
}
private func preloadFrame(at index: Int) {
animatedFrames[index] = prepareFrame(at: currentPreloadIndex)
currentPreloadIndex += 1
currentPreloadIndex = currentPreloadIndex % frameCount
}
}
extension CGImageSource: KingfisherCompatible { }
extension Kingfisher where Base: CGImageSource {
func gifProperties(at index: Int) -> [String: Double]? {
let properties = CGImageSourceCopyPropertiesAtIndex(base, index, nil) as Dictionary?
return properties?[kCGImagePropertyGIFDictionary] as? [String: Double]
}
}
extension Array {
subscript(safe index: Int) -> Element? {
return indices ~= index ? self[index] : nil
}
}
private func pure<T>(_ value: T) -> [T] {
return [value]
}
| mit | 878628cba1de8debb4eff73a7bdcbbb0 | 34.194366 | 184 | 0.643189 | 5.369145 | false | false | false | false |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.