repo_name
stringlengths
7
91
path
stringlengths
8
658
copies
stringclasses
125 values
size
stringlengths
3
6
content
stringlengths
118
674k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6.09
99.2
line_max
int64
17
995
alpha_frac
float64
0.3
0.9
ratio
float64
2
9.18
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
pjcau/LocalNotifications_Over_iOS10
Pods/SwiftDate/Sources/SwiftDate/ISO8601DateTimeFormatter.swift
2
9978
// SwiftDate // Manage Date/Time & Timezone in Swift // // Created by: Daniele Margutti // Email: <[email protected]> // Web: <http://www.danielemargutti.com> // // Licensed under MIT License. import Foundation /// MARK: - ISO8601DateTimeFormatter /// This is a re-implementation of the ISO8601DateFormatter which is compatible with iOS lower than version 10. public class ISO8601DateTimeFormatter { public struct Options: OptionSet { public let rawValue: Int public init(rawValue: Int) { self.rawValue = rawValue } /// The date representation includes the year. The format for year is inferred based on the other specified options. /// - If withWeekOfYear is specified, YYYY is used. /// - Otherwise, yyyy is used. public static let withYear = ISO8601DateTimeFormatter.Options(rawValue: 1 << 0) /// The date representation includes the month. The format for month is MM. public static let withMonth = ISO8601DateTimeFormatter.Options(rawValue: 1 << 1) /// The date representation includes the week of the year. /// The format for week of year is ww, including the W prefix. public static let withWeekOfYear = ISO8601DateTimeFormatter.Options(rawValue: 1 << 2) /// The date representation includes the day. The format for day is inferred based on provided options: /// - If withMonth is specified, dd is used. /// - If withWeekOfYear is specified, ee is used. /// - Otherwise, DDD is used. public static let withDay = ISO8601DateTimeFormatter.Options(rawValue: 1 << 3) /// The date representation includes the time. The format for time is HH:mm:ss. public static let withTime = ISO8601DateTimeFormatter.Options(rawValue: 1 << 4) /// The date representation includes the timezone. The format for timezone is ZZZZZ. public static let withTimeZone = ISO8601DateTimeFormatter.Options(rawValue: 1 << 5) /// The date representation uses a space ( ) instead of T between the date and time. public static let withSpaceBetweenDateAndTime = ISO8601DateTimeFormatter.Options(rawValue: 1 << 6) /// The date representation uses the dash separator (-) in the date. public static let withDashSeparatorInDate = ISO8601DateTimeFormatter.Options(rawValue: 1 << 7) /// The date representation uses the colon separator (:) in the time. public static let withFullDate = ISO8601DateTimeFormatter.Options(rawValue: 1 << 8) /// The date representation includes the hour, minute, and second. public static let withFullTime = ISO8601DateTimeFormatter.Options(rawValue: 1 << 9) /// The format used for internet date times, according to the RFC 3339 standard. /// Equivalent to specifying withFullDate, withFullTime, withDashSeparatorInDate, /// withColonSeparatorInTime, and withColonSeparatorInTimeZone. public static let withInternetDateTime = ISO8601DateTimeFormatter.Options(rawValue: 1 << 10) // The format used for internet date times; it's similar to .withInternetDateTime // but include milliseconds ('yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ'). public static let withInternetDateTimeExtended = ISO8601DateTimeFormatter.Options(rawValue: 1 << 11) /// Evaluate formatting string public var formatterString: String { if self.contains(.withInternetDateTimeExtended) { return "yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ" } if self.contains(.withInternetDateTime) { return "yyyy-MM-dd'T'HH:mm:ssZZZZZ" } var format: String = "" if self.contains(.withFullDate) { format += "yyyy-MM-dd" } else { if self.contains(.withYear) { if self.contains(.withWeekOfYear) { format += "YYYY" } else if self.contains(.withMonth) || self.contains(.withDay) { format += "yyyy" } else { // not valid } } if self.contains(.withMonth) { if self.contains(.withYear) || self.contains(.withDay) || self.contains(.withWeekOfYear) { format += "MM" } else { // not valid } } if self.contains(.withWeekOfYear) { if self.contains(.withDay) { format += "'W'ww" } else { if self.contains(.withYear) || self.contains(.withMonth) { if self.contains(.withDashSeparatorInDate) { format += "-'W'ww" } else { format += "'W'ww" } } else { // not valid } } } if self.contains(.withDay) { if self.contains(.withWeekOfYear) { format += "FF" } else if self.contains(.withMonth) { format += "dd" } else if self.contains(.withYear) { if self.contains(.withDashSeparatorInDate) { format += "-DDD" } else { format += "DDD" } } else { // not valid } } } let hasDate = (self.contains(.withFullDate) || self.contains(.withMonth) || self.contains(.withDay) || self.contains(.withWeekOfYear) || self.contains(.withYear)) if hasDate && (self.contains(.withFullTime) || self.contains(.withTimeZone)) { if self.contains(.withSpaceBetweenDateAndTime) { format += " " } else { format += "'T'" } } if self.contains(.withFullTime) { format += "HH:mm:ssZZZZZ" } else { if self.contains(.withTime) { format += "HH:mm:ss" } if self.contains(.withTimeZone) { format += "ZZZZZ" } } return format } } /// Options for generating and parsing ISO 8601 date representations. @available(*, deprecated: 4.1.0, message: "This property is not used anymore. Use string(from:options:) to format a date to string or class func date(from:config:) to transform a string to date") public var formatOptions: ISO8601DateTimeFormatter.Options = ISO8601DateTimeFormatter.Options(rawValue: 0) /// The time zone used to create and parse date representations. When unspecified, GMT is used. @available(*, deprecated: 4.1.0, message: "This property is not used anymore. Parsing is done automatically by reading specified timezone. If not specified UTC is used.") public var timeZone: TimeZone? { set { self.formatter.timeZone = newValue ?? TimeZone(secondsFromGMT: 0) } get { return self.formatter.timeZone } } public var locale: Locale? { get { return self.formatter.locale } set { self.formatter.locale = newValue } } /// formatter instance used for date private var formatter: DateFormatter = DateFormatter() public init() { } /// Creates and returns an ISO 8601 formatted string representation of the specified date. /// /// - parameter date: The date to be represented. /// /// - returns: A user-readable string representing the date. @available(*, deprecated: 4.1.0, message: "Use string(from:options:) function instead") public func string(from date: Date) -> String { self.formatter.dateFormat = self.formatOptions.formatterString return self.formatter.string(from: date) } /// Creates and returns a date object from the specified ISO 8601 formatted string representation. /// /// - parameter string: The ISO 8601 formatted string representation of a date. /// /// - returns: A date object, or nil if no valid date was found. @available(*, deprecated: 4.1.0, message: "Use ISO8601DateTimeFormatter class func date(from:config) instead") public func date(from string: String) -> Date? { //self.formatter.dateFormat = self.formatOptions.formatterString //return self.formatter.date(from: string) return ISO8601DateTimeFormatter.date(from: string) } /// Creates and return a date object from the specified ISO8601 formatted string representation /// /// - Parameters: /// - string: valid ISO8601 string to parse /// - config: configuration to use. `nil` uses default configuration /// - Returns: a valid `Date` object or `nil` if parse fails public class func date(from string: String, config: ISO8601Configuration = ISO8601Configuration()) -> Date? { return ISO8601Parser(string, config: config)?.parsedDate } /// Creates and returns an ISO 8601 formatted string representation of the specified date. /// /// - Parameters: /// - date: The date to be represented. /// - options: Formastting style /// - Returns: a string description of the date public func string(from date: Date, tz: TimeZone, options: ISO8601DateTimeFormatter.Options = [.withInternetDateTime]) -> String { self.formatter.dateFormat = options.formatterString formatter.locale = LocaleName.englishUnitedStatesComputer.locale // fix for 12/24h formatter.timeZone = tz let string = self.formatter.string(from: date) return string } /// Creates a representation of the specified date with a given time zone and format options. /// /// - parameter date: The date to be represented. /// - parameter timeZone: The time zone used. /// - parameter formatOptions: The options used. For possible values, see ISO8601DateTimeFormatter.Options. /// /// - returns: A user-readable string representing the date. @available(*, deprecated: 4.1.0, message: "Use ISO8601DateTimeFormatter class func string(from:options:) instead") public class func string(from date: Date, timeZone: TimeZone, formatOptions: ISO8601DateTimeFormatter.Options = []) -> String { return ISO8601DateTimeFormatter.string(from: date, tz: timeZone, options: formatOptions) } /// Creates a representation of the specified date with a given time zone and format options. /// /// - Parameters: /// - date: The date to be represented. /// - tz: Destination timezone /// - options: The options used. For possible values, see ISO8601DateTimeFormatter.Options. /// - returns: A user-readable string representing the date. public class func string(from date: Date, tz: TimeZone, options: ISO8601DateTimeFormatter.Options = []) -> String { let formatter = ISO8601DateTimeFormatter() formatter.locale = LocaleName.englishUnitedStatesComputer.locale // fix for 12/24h return formatter.string(from: date, tz: tz, options: options) } }
mit
b101c066ff7ab5e30f70326439c4ad2b
37.376923
196
0.694328
3.86295
false
false
false
false
suifengqjn/swiftDemo
基本语法/3字符串和字符/1字符串和字符.playground/Contents.swift
1
3521
//: Playground - noun: a place where people can play import UIKit ///空字符串的初始化 let emptyStr = "" let emptyStr2 = String() ///通过检查布尔量 isEmpty属性来确认一个 String值是否为空: if emptyStr.isEmpty { print("emptyStr is nil") } ///遍历字符 let stringvalue1 = "afhfha!@#我是一个、" for character in stringvalue1.characters { print(character) } ///连接字符串和字符 //用 + 号连接2个字符串 let string1 = "hello" let string2 = " there" var welcome = string1 + string2 // += 实现字符串追加 welcome += "123" // appending()实现字符串追加 welcome = welcome.appending("iamkkkk") ///字符串插值 //每一个你插入到字符串字面量的元素都要被一对圆括号包裹,然后使用反斜杠前缀 \() let multiplier = 3 let message = "\(multiplier) times 2.5 is \(Double(multiplier) * 2.5)" print(message) ///字符统计 (.characters.count) let unusualMenagerie = "Koala 🐨, Snail 🐌, Penguin 🐧, Dromedary 🐪" print("unusualMenagerie has \(unusualMenagerie.characters.count) characters") ///字符串索引 //String.Index,它相当于每个 Character在字符串中的位置 let greeting = "Guten Tag! hello" greeting[greeting.startIndex] // G greeting[greeting.index(before: greeting.endIndex)] // ! greeting[greeting.index(after: greeting.startIndex)] // u let index = greeting.index(greeting.startIndex, offsetBy: 7) greeting[index] // a //尝试访问的 Character如果索引位置在字符串范围之外,就会触发运行时错误 //greeting[greeting.endIndex] // error ///使用 characters属性的 indices属性来创建所有能够用来访问字符串中独立字符的索引范围 Range。 for index2 in greeting.characters.indices { print("\(greeting[index2]) ", terminator: "") } ///插入和删除 ///使用 insert(_:at:)方法,另外要冲入另一个字符串的内容到特定的索引,使用 insert(contentsOf:at:) 方法。 var weclome2 = "welcome" weclome2.insert("!",at: weclome2.endIndex) print(weclome2) weclome2.insert(contentsOf:" there".characters, at: weclome2.index(before: weclome2.endIndex)) print(weclome2) ///要从字符串的特定索引位置移除字符,使用 remove(at:)方法,另外要移除一小段特定范围的字符串,使用 removeSubrange(_:) 方法: weclome2.remove(at: weclome2.index(before: weclome2.endIndex)) print(weclome2) let range = weclome2.index(weclome2.endIndex, offsetBy: -6)..<weclome2.endIndex weclome2.removeSubrange(range) print(weclome2) ///字符串和字符相等性 let quotation = "We're a lot alike, you and I." let sameQuotation = "We're a lot alike, you and I." if quotation == sameQuotation { print("These two strings are considered equal") } ///前缀和后缀 let ispewquo = quotation.hasPrefix("We") let ishewquo = quotation.hasSuffix("We") ///字符串字面量中的特殊字符 //转义特殊字符 \0 (空字符), \\ (反斜杠), \t (水平制表符), \n (换行符), \r(回车符), \" (双引号) 以及 \' (单引号); //任意的 Unicode 标量,写作 \u{n},里边的 n是一个 1-8 个与合法 Unicode 码位相等的16进制数字。 let wiseWords = "\"Imagination is more important than knowledge\" - Einstein" // "Imagination is more important than knowledge" - Einstein let dollarSign = "\u{24}" // $, Unicode scalar U+0024 let blackHeart = "\u{2665}" // ♥, Unicode scalar U+2665 let sparklingHeart = "\u{1F496}" // 💖, Unicode scalar U+1F496
apache-2.0
231b42930b0d3bebdd6c365efb194595
21.192
94
0.717015
2.824847
false
false
false
false
Hodglim/hacking-with-swift
Project-04/EasyBrowser/ViewController.swift
1
3423
// // ViewController.swift // EasyBrowser // // Created by Darren Hodges on 11/10/2015. // Copyright © 2015 Darren Hodges. All rights reserved. // import UIKit import WebKit class ViewController: UIViewController, WKNavigationDelegate { var webView: WKWebView! var progressView: UIProgressView! var websites = ["apple.com", "hackingwithswift.com"] override func loadView() { // Create web view webView = WKWebView() webView.navigationDelegate = self view = webView } override func viewDidLoad() { super.viewDidLoad() // Load initial site let url = NSURL(string: "https://\(websites[0])")! webView.loadRequest(NSURLRequest(URL:url)) webView.allowsBackForwardNavigationGestures = true // Watch the estimatedProgress value webView.addObserver(self, forKeyPath: "estimatedProgress", options: .New, context: nil) // Right navigation bar button navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Open", style: .Plain, target: self, action: "openTapped") progressView = UIProgressView(progressViewStyle: .Default) progressView.sizeToFit() let progressButton = UIBarButtonItem(customView: progressView) let spacer = UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: nil, action: nil) let refresh = UIBarButtonItem(barButtonSystemItem: .Refresh, target: webView, action: "reload") toolbarItems = [progressButton, spacer, refresh] navigationController?.toolbarHidden = false } func openTapped() { // Present list of sites to open let ac = UIAlertController(title: "Open page…", message: nil, preferredStyle: .ActionSheet) for website in websites { ac.addAction(UIAlertAction(title: website, style: .Default, handler: openPage)) } ac.addAction(UIAlertAction(title: "Cancel", style: .Cancel, handler: nil)) presentViewController(ac, animated: true, completion: nil) } func openPage(action: UIAlertAction!) { let url = NSURL(string: "https://" + action.title!)! webView.loadRequest(NSURLRequest(URL: url)) } func webView(webView: WKWebView, didFinishNavigation navigation: WKNavigation!) { // Set title title = webView.title } func webView(webView: WKWebView, decidePolicyForNavigationAction navigationAction: WKNavigationAction, decisionHandler: (WKNavigationActionPolicy) -> Void) { // Only allow urls in our safe list let url = navigationAction.request.URL if let host = url!.host { for website in websites { if host.rangeOfString(website) != nil { decisionHandler(.Allow) return } } } decisionHandler(.Cancel) } override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) { if keyPath == "estimatedProgress" { let floatValue = webView.estimatedProgress == 1.0 ? Float(0.0) : Float(webView.estimatedProgress) progressView.progress = floatValue } } }
mit
03ce314894c96c7c338cbd6d10d418f9
32.203883
159
0.624561
5.269646
false
false
false
false
Rag0n/QuNotes
Core/Library/LibrarySpec.swift
1
12392
// // LibrarySpec.swift // QuNotesTests // // Created by Alexander Guschin on 03.11.2017. // Copyright © 2017 Alexander Guschin. All rights reserved. // import Quick import Nimble import Result class LibrarySpec: QuickSpec { override func spec() { let notebook = Dummy.notebook(uuid: "notebookUUID") let model = Library.Model(notebooks: [notebook]) let error = Dummy.error(withMessage: "message") var e: Library.Evaluator! beforeEach { e = Library.Evaluator(model: model) } context("when initialized") { it("has zero effects") { expect(e.effects).to(beEmpty()) } it("has passed model") { expect(e.model).to(equal(model)) } } describe("-evaluating:") { var event: Library.Event! context("when receiving addNotebook event") { context("when notebook with that uuid is not added yet") { let newNotebook = Dummy.notebook(uuid: "newNotebookUUID") beforeEach { event = .addNotebook(newNotebook) e = e.evaluating(event: event) } it("has createNotebook effect with notebook & meta url") { expect(e.effects).to(equalDiff([ .createNotebook(newNotebook, url: Dummy.url("newNotebookUUID.qvnotebook/meta.json")) ])) } it("updates model by adding passed notebook") { expect(e.model).to(equalDiff( Library.Model(notebooks: [notebook, newNotebook]) )) } } context("when notebook with that uuid is already added") { beforeEach { event = .addNotebook(notebook) e = e.evaluating(event: event) } it("doesnt have effects") { expect(e.effects).to(beEmpty()) } it("doesnt update model") { expect(e.model).to(equalDiff(model)) } } } context("when receiving removeNotebook event") { context("when notebook with that uuid was added") { beforeEach { event = .removeNotebook(notebook) e = e.evaluating(event: event) } it("removes notebook from model") { expect(e.model).to(equalDiff( Library.Model(notebooks: []) )) } it("has deleteNotebook effect with notebook url") { expect(e.effects).to(equalDiff([ .deleteNotebook(notebook, url: Dummy.url("notebookUUID.qvnotebook")) ])) } } context("when notebook with that uuid was not added") { beforeEach { let notAddedNotebook = Dummy.notebook() event = .removeNotebook(notAddedNotebook) e = e.evaluating(event: event) } it("doesnt update model") { expect(e.model).to(equalDiff(model)) } it("doesnt have effects") { expect(e.effects).to(beEmpty()) } } } context("when receiving loadNotebooks event") { beforeEach { event = .loadNotebooks e = e.evaluating(event: event) } it("doesnt update model") { expect(e.model).to(equalDiff(model)) } it("has readBaseDirectory effect") { expect(e.effects).to(equalDiff([ .readBaseDirectory ])) } } context("when receiving didAddNotebook event") { context("when successfully adds notebook") { beforeEach { let notebook = Dummy.notebook() event = .didAddNotebook(notebook, error: nil) e = e.evaluating(event: event) } it("doesnt update model") { expect(e.model).to(equalDiff(model)) } it("doesnt have effects") { expect(e.effects).to(beEmpty()) } } context("when fails to add notebook") { context("when notebook is in model") { beforeEach { event = .didAddNotebook(notebook, error: error) e = e.evaluating(event: event) } it("removes notebook from model") { expect(e.model).to(equalDiff( Library.Model(notebooks: []) )) } } context("when notebook is not in model") { beforeEach { let anotherNotebook = Dummy.notebook() event = .didAddNotebook(anotherNotebook, error: error) e = e.evaluating(event: event) } it("does nothing") { expect(e.model).to(equal(model)) expect(e.effects).to(equal([])) } } } } context("when receiving didRemoveNotebook event") { let removedNotebook = Dummy.notebook() context("when successfully removes notebook") { beforeEach { event = .didRemoveNotebook(removedNotebook, error: nil) e = e.evaluating(event: event) } it("doesnt update model") { expect(e.model).to(equalDiff(model)) } it("doesnt have effects") { expect(e.effects).to(beEmpty()) } } context("when fails to remove notebook") { beforeEach { event = .didRemoveNotebook(removedNotebook, error: error) e = e.evaluating(event: event) } it("adds notebook back to model") { expect(e.model).to(equalDiff( Library.Model(notebooks: [notebook, removedNotebook]) )) } } } context("when receiving didReadBaseDirecotry event") { context("when successfuly reads directories") { beforeEach { let urls = [ URL(string: "/firstNotebookURL.qvnotebook")!, URL(string: "/notANotebookURL")!, URL(string: "/secondNotebookURL.qvnotebook")!, ] event = .didReadBaseDirectory(urls: Result(value: urls)) e = e.evaluating(event: event) } it("has readNotebooks effect with notebook urls & notebook meta type") { expect(e.effects).to(equalDiff([ .readNotebooks(urls: [URL(string: "/firstNotebookURL.qvnotebook/meta.json")!, URL(string: "/secondNotebookURL.qvnotebook/meta.json")!]) ])) } } context("when fails to read directories") { beforeEach { event = .didReadBaseDirectory(urls: Result(error: error)) e = e.evaluating(event: event) } it("has handleError effect") { expect(e.effects).to(equalDiff([ .handleError(title: "Failed to load notebooks", message: "message") ])) } } } context("when receiving didReadNotebooks event") { context("when notebooks list is empty") { beforeEach { event = .didReadNotebooks([]) e = e.evaluating(event: event) } it("has didLoadNotebooks effect with empty list") { expect(e.effects).to(equalDiff([ .didLoadNotebooks([]) ])) } it("updates model with empty notebook list") { expect(e.model).to(equalDiff( Library.Model(notebooks: []) )) } } context("when notebooks list has result with notebook") { let notebook = Dummy.notebook() beforeEach { event = .didReadNotebooks([Result(value: notebook)]) e = e.evaluating(event: event) } it("has didLoadNotebooks effect with 1 notebook") { expect(e.effects).to(equalDiff([ .didLoadNotebooks([notebook]) ])) } it("updates model with notebook") { expect(e.model).to(equalDiff( Library.Model(notebooks: [notebook]) )) } } context("when notebook list has result with error") { beforeEach { event = .didReadNotebooks([Result(error: error)]) e = e.evaluating(event: event) } it("has handleError effect with message from error") { expect(e.effects).to(equalDiff([ .handleError(title: "Failed to load notebooks", message: "message") ])) } } context("when notebook list has result with notebook and several errors") { beforeEach { let notebook = Dummy.notebook() let secondError = Dummy.error(withMessage: "secondMessage") event = .didReadNotebooks([Result(error: error), Result(value: notebook), Result(error: secondError)]) e = e.evaluating(event: event) } it("has handleError effect with combined message from errors") { expect(e.effects).to(equalDiff([ .handleError(title: "Failed to load notebooks", message: "message\nsecondMessage") ])) } } } } } } private enum Dummy { static func notebook(uuid: String = UUID().uuidString) -> Notebook.Meta { return Notebook.Meta(uuid: uuid, name: uuid + "name") } static func error(withMessage message: String) -> AnyError { let underlyingError = NSError(domain: "error domain", code: 1, userInfo: [NSLocalizedDescriptionKey: message]) return AnyError(underlyingError) } static func url(_ string: String) -> DynamicBaseURL { return DynamicBaseURL(url: URL(string: string)!) } }
gpl-3.0
66584a865c0eca2074b6ac4613f867e9
36.662614
118
0.419659
5.892059
false
false
false
false
tomlokhorst/CoreDataKit
CoreDataKit/Importing/NSManagedObjectContext+Importing.swift
1
4199
// // NSManagedObjectContext+Importing.swift // CoreDataKit // // Created by Mathijs Kadijk on 17-10-14. // Copyright (c) 2014 Mathijs Kadijk. All rights reserved. // import CoreData extension NSManagedObjectContext { /** Import dictionary into the given type of entity, will do lookups in the context to find the object to import :see: Importing documentation at [TODO] - parameter entity: Type of entity to import - parameter dictionary: Data to import - returns: Result with managed object of the given entity type with the data imported on it */ public func importEntity<T: NSManagedObject where T:NamedManagedObject>(entity: T.Type, dictionary: [String : AnyObject]) throws -> T { let desc = try entityDescription(entity) return try self.importEntity(desc, dictionary: dictionary) } /** Import dictionary into an entity based on entity description, will do lookups in the context to find the object to import :see: Importing documentation at [TODO] - parameter entityDescription: Description of entity to import - parameter dictionary: Data to import - returns: Result with managed object of the given entity type with the data imported on it */ func importEntity<T:NSManagedObject>(entityDescription: NSEntityDescription, dictionary: [String : AnyObject]) throws -> T { let identifyingAttribute = try entityDescription.identifyingAttribute() switch identifyingAttribute.preferredValueFromDictionary(dictionary) { case let .Some(value): let object: T = try self.objectForImport(entityDescription, identifyingValue: value) try object.importDictionary(dictionary) return object case .Null: let error = NSError(domain: CoreDataKitErrorDomain, code: CoreDataKitErrorCode.InvalidValue.rawValue, userInfo: [NSLocalizedDescriptionKey: "Value 'null' in import dictionary for identifying atribute '\(entityDescription.name).\(identifyingAttribute.name)', dictionary: \(dictionary)"]) throw error case .None: let error = NSError(domain: CoreDataKitErrorDomain, code: CoreDataKitErrorCode.InvalidValue.rawValue, userInfo: [NSLocalizedDescriptionKey: "No value in import dictionary for identifying atribute '\(entityDescription.name).\(identifyingAttribute.name)', dictionary: \(dictionary)"]) throw error } } /** Find or create an instance of this managed object to use for import - parameter entityDescription: Description of entity to import - parameter identifyingValue: The identifying value of the object :return: Result with the object to perform the import on */ private func objectForImport<T:NSManagedObject>(entityDescription: NSEntityDescription, identifyingValue: AnyObject) throws -> T { do { if let object: T = try findEntityByIdentifyingAttribute(entityDescription, identifyingValue: identifyingValue) { return object } } catch { } return try create(entityDescription) } /** Find entity based on the identifying attribute - parameter entityDescription: Description of entity to find - parameter identifyingValue: The identifying value of the object - returns: Result with the optional object that is found, nil on not found */ func findEntityByIdentifyingAttribute<T:NSManagedObject>(entityDescription: NSEntityDescription, identifyingValue: AnyObject) throws -> T? { let identifyingAttribute = try entityDescription.identifyingAttribute() let predicate = NSPredicate(format: "%K = %@", argumentArray: [identifyingAttribute.name, identifyingValue]) let objects = try self.find(entityDescription, predicate: predicate) if objects.count > 1 { let error = NSError(domain: CoreDataKitErrorDomain, code: CoreDataKitErrorCode.UnexpectedNumberOfResults.rawValue, userInfo: [NSLocalizedDescriptionKey: "Expected 0...1 result, got \(objects.count) results"]) throw error } return objects.first as? T } }
mit
17271feec64752e81142c003c996f5b8
41.846939
298
0.707073
5.275126
false
false
false
false
yinnieryou/DesignPattern
Principle/SingleResponsibilityPrinciple.playground/contents.swift
1
2758
// Playground - noun: a place where people can play // import UIKit /* 单一职责原则 Single responsibility principle (SRP) 定义:不要存在多于一个导致类变更的原因。通俗的说,即一个类只负责一项职责。 问题由来:类T负责两个不同的职责:职责P1,职责P2。当由于职责P1需求发生改变而需要修改类T时,有可能会导致原本运行正常的职责P2功能发生故障。 解决方案:遵循单一职责原则。分别建立两个类T1、T2,使T1完成职责P1功能,T2完成职责P2功能。这样,当修改类T1时,不会使职责P2发生故障风险;同理,当修改T2时,也不会使职责P1发生故障风险。 优点: 1.可以降低类的复杂度,一个类只负责一项职责,其逻辑肯定要比负责多项职责简单的多; 2.提高类的可读性,提高系统的可维护性; 3.变更引起的风险降低,变更是必然的,如果单一职责原则遵守的好,当修改一个功能时,可以显著降低对其他功能的影响。 */ class Animal0 { func breathe(animal:String){ println("\(animal)呼吸空气") } } class Client0 { init(){ var animal = Animal0() animal.breathe("🐂") animal.breathe("🐑") animal.breathe("🐷") } } var client0 = Client0() //问题:添加一种鱼,呼吸水 //解决方案1 class Terrestrial { func breathe(animal:String){ println("\(animal)呼吸空气") } } class Aquatic { func breathe(animal:String){ println("\(animal)呼吸水") } } class Client1 { init(){ var terrestrial = Terrestrial() terrestrial.breathe("🐂") terrestrial.breathe("🐑") terrestrial.breathe("🐷") var aquatic = Aquatic() aquatic.breathe("🐟") } } var client1 = Client1() //解决方案2 class Animal2 { func breathe(animal:String){ if animal == "🐟" { println("\(animal)呼吸水") }else{ println("\(animal)呼吸空气") } } } class Client2 { init(){ var animal = Animal2() animal.breathe("🐂") animal.breathe("🐑") animal.breathe("🐷") animal.breathe("🐟") } } var client2 = Client2() //解决方案3 class Animal3 { func breathe(animal:String){ println("\(animal)呼吸空气") } func breathe2(animal:String){ println("\(animal)呼吸水") } } class Client3 { init(){ var animal = Animal3() animal.breathe("🐂") animal.breathe("🐑") animal.breathe("🐷") animal.breathe2("🐟") } } var client3 = Client3()
mit
a80f05993f57ddeee27c92fc7a61e649
18.2
104
0.580853
2.423077
false
false
false
false
wordpress-mobile/WordPress-iOS
WordPress/Classes/Models/LastPostStatsRecordValue+CoreDataClass.swift
1
2185
import Foundation import CoreData public class LastPostStatsRecordValue: StatsRecordValue { public var url: URL? { guard let url = urlString as String? else { return nil } return URL(string: url) } public var featuredImageURL: URL? { guard let url = featuredImageUrlString as String? else { return nil } return URL(string: url) } public override func validateForInsert() throws { try super.validateForInsert() try recordValueSingleValueValidation() } } extension StatsLastPostInsight: StatsRecordValueConvertible { func statsRecordValues(in context: NSManagedObjectContext) -> [StatsRecordValue] { let value = LastPostStatsRecordValue(context: context) value.commentsCount = Int64(self.commentsCount) value.likesCount = Int64(self.likesCount) value.publishedDate = self.publishedDate as NSDate value.title = self.title value.urlString = self.url.absoluteString value.viewsCount = Int64(self.viewsCount) value.postID = Int64(self.postID) value.featuredImageUrlString = self.featuredImageURL?.absoluteString return [value] } init?(statsRecordValues: [StatsRecordValue]) { guard let insight = statsRecordValues.first as? LastPostStatsRecordValue, let title = insight.title, let url = insight.url, let publishedDate = insight.publishedDate else { return nil } self = StatsLastPostInsight(title: title, url: url, publishedDate: publishedDate as Date, likesCount: Int(insight.likesCount), commentsCount: Int(insight.commentsCount), viewsCount: Int(insight.viewsCount), postID: Int(insight.postID), featuredImageURL: insight.featuredImageURL) } static var recordType: StatsRecordType { return .lastPostInsight } }
gpl-2.0
7d4c023c727b5b7781572d11b07d2985
32.615385
86
0.59405
5.408416
false
false
false
false
ReSwift/ReSwift-Router
ReSwiftRouter/Router.swift
2
9255
// // Router.swift // Meet // // Created by Benjamin Encz on 11/11/15. // Copyright © 2015 ReSwift Community. All rights reserved. // import Foundation import ReSwift open class Router<State>: StoreSubscriber { public typealias NavigationStateTransform = (Subscription<State>) -> Subscription<NavigationState> var store: Store<State> var lastNavigationState = NavigationState() var routables: [Routable] = [] let waitForRoutingCompletionQueue = DispatchQueue(label: "WaitForRoutingCompletionQueue", attributes: []) public init(store: Store<State>, rootRoutable: Routable, stateTransform: @escaping NavigationStateTransform) { self.store = store self.routables.append(rootRoutable) self.store.subscribe(self, transform: stateTransform) } open func newState(state: NavigationState) { let routingActions = Router.routingActionsForTransition(from: lastNavigationState.route, to: state.route) routingActions.forEach { routingAction in let semaphore = DispatchSemaphore(value: 0) // Dispatch all routing actions onto this dedicated queue. This will ensure that // only one routing action can run at any given time. This is important for using this // Router with UI frameworks. Whenever a navigation action is triggered, this queue will // block (using semaphore_wait) until it receives a callback from the Routable // indicating that the navigation action has completed waitForRoutingCompletionQueue.async { switch routingAction { case let .pop(responsibleRoutableIndex, elementToBePopped): DispatchQueue.main.async { self.routables[responsibleRoutableIndex] .pop( elementToBePopped, animated: state.changeRouteAnimated) { semaphore.signal() } self.routables.remove(at: responsibleRoutableIndex + 1) } case let .change(responsibleRoutableIndex, elementToBeReplaced, newElement): DispatchQueue.main.async { self.routables[responsibleRoutableIndex + 1] = self.routables[responsibleRoutableIndex] .change( elementToBeReplaced, to: newElement, animated: state.changeRouteAnimated) { semaphore.signal() } } case let .push(responsibleRoutableIndex, elementToBePushed): DispatchQueue.main.async { self.routables.append( self.routables[responsibleRoutableIndex] .push( elementToBePushed, animated: state.changeRouteAnimated) { semaphore.signal() } ) } } let waitUntil = DispatchTime.now() + Double(Int64(3 * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC) let result = semaphore.wait(timeout: waitUntil) if case .timedOut = result { print("[ReSwiftRouter]: Router is stuck waiting for a" + " completion handler to be called. Ensure that you have called the" + " completion handler in each Routable element.") print("Set a symbolic breakpoint for the `ReSwiftRouterStuck` symbol in order" + " to halt the program when this happens") ReSwiftRouterStuck() } } } lastNavigationState = state } // MARK: Route Transformation Logic static func largestCommonSubroute(_ oldRoute: Route, newRoute: Route) -> Int { var largestCommonSubroute = -1 while largestCommonSubroute + 1 < newRoute.count && largestCommonSubroute + 1 < oldRoute.count && newRoute[largestCommonSubroute + 1] == oldRoute[largestCommonSubroute + 1] { largestCommonSubroute += 1 } return largestCommonSubroute } // Maps Route index to Routable index. Routable index is offset by 1 because the root Routable // is not represented in the route, e.g. // route = ["tabBar"] // routables = [RootRoutable, TabBarRoutable] static func routableIndex(for element: Int) -> Int { return element + 1 } static func routingActionsForTransition( from oldRoute: Route, to newRoute: Route) -> [RoutingActions] { var routingActions: [RoutingActions] = [] // Find the last common subroute between two routes let commonSubroute = largestCommonSubroute(oldRoute, newRoute: newRoute) if commonSubroute == oldRoute.count - 1 && commonSubroute == newRoute.count - 1 { return [] } // Keeps track which element of the routes we are working on // We start at the end of the old route var routeBuildingIndex = oldRoute.count - 1 // Pop all route elements of the old route that are no longer in the new route // Stop one element ahead of the commonSubroute. When we are one element ahead of the // commmon subroute we have three options: // // 1. The old route had an element after the commonSubroute and the new route does not // we need to pop the route element after the commonSubroute // 2. The old route had no element after the commonSubroute and the new route does, we // we need to push the route element(s) after the commonSubroute // 3. The new route has a different element after the commonSubroute, we need to replace // the old route element with the new one while routeBuildingIndex > commonSubroute + 1 { let routeElementToPop = oldRoute[routeBuildingIndex] let popAction = RoutingActions.pop( responsibleRoutableIndex: routableIndex(for: routeBuildingIndex - 1), elementToBePopped: routeElementToPop ) routingActions.append(popAction) routeBuildingIndex -= 1 } // This is the 3. case: // "The new route has a different element after the commonSubroute, we need to replace // the old route element with the new one" if oldRoute.count > (commonSubroute + 1) && newRoute.count > (commonSubroute + 1) { let changeAction = RoutingActions.change( responsibleRoutableIndex: routableIndex(for: commonSubroute), elementToBeReplaced: oldRoute[commonSubroute + 1], newElement: newRoute[commonSubroute + 1]) routingActions.append(changeAction) } // This is the 1. case: // "The old route had an element after the commonSubroute and the new route does not // we need to pop the route element after the commonSubroute" else if oldRoute.count > newRoute.count { let popAction = RoutingActions.pop( responsibleRoutableIndex: routableIndex(for: routeBuildingIndex - 1), elementToBePopped: oldRoute[routeBuildingIndex] ) routingActions.append(popAction) routeBuildingIndex -= 1 } // Push remainder of elements in new Route that weren't in old Route, this covers // the 2. case: // "The old route had no element after the commonSubroute and the new route does, // we need to push the route element(s) after the commonSubroute" let newRouteIndex = newRoute.count - 1 while routeBuildingIndex < newRouteIndex { let routeElementToPush = newRoute[routeBuildingIndex + 1] let pushAction = RoutingActions.push( responsibleRoutableIndex: routableIndex(for: routeBuildingIndex), elementToBePushed: routeElementToPush ) routingActions.append(pushAction) routeBuildingIndex += 1 } return routingActions } } func ReSwiftRouterStuck() {} enum RoutingActions { case push(responsibleRoutableIndex: Int, elementToBePushed: RouteElement) case pop(responsibleRoutableIndex: Int, elementToBePopped: RouteElement) case change(responsibleRoutableIndex: Int, elementToBeReplaced: RouteElement, newElement: RouteElement) }
mit
58a7ca4794c28833cd973f1e9470b386
42.242991
115
0.572509
5.370865
false
false
false
false
SusanDoggie/Doggie
Sources/DoggieGraphics/ColorSpace/ColorSpaceBase/ICC/iccProfile/iccTagData/iccMultiLocalizedUnicode.swift
1
5649
// // iccMultiLocalizedUnicode.swift // // The MIT License // Copyright (c) 2015 - 2022 Susan Cheng. 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. // struct iccMultiLocalizedUnicode: RandomAccessCollection, ByteCodable { public typealias Indices = Range<Int> public typealias Index = Int var messages: [(LanguageCode, CountryCode, String)] init<S : Sequence>(_ messages: S) where S.Element == (LanguageCode, CountryCode, String) { self.messages = Array(messages) } init(from data: inout Data) throws { let _data = data guard data.count > 8 else { throw AnyColorSpace.ICCError.endOfData } guard try data.decode(iccProfile.TagType.self) == .multiLocalizedUnicode else { throw AnyColorSpace.ICCError.invalidFormat(message: "Invalid multiLocalizedUnicode.") } data.removeFirst(4) let header = try data.decode(Header.self) let entries = try (0..<Int(header.count)).map { _ in try data.decode(Entry.self) } self.messages = [] for entry in entries { let offset = Int(entry.offset) let length = Int(entry.length) guard _data.count >= offset + length else { throw AnyColorSpace.ICCError.endOfData } let strData = _data.dropFirst(offset).prefix(length) messages.append((entry.language, entry.country, String(bytes: strData, encoding: .utf16BigEndian) ?? "")) } } func write<Target: ByteOutputStream>(to stream: inout Target) { stream.encode(iccProfile.TagType.multiLocalizedUnicode) stream.encode(0 as BEUInt32) stream.encode(Header(count: BEUInt32(messages.count), size: BEUInt32(MemoryLayout<Entry>.stride))) let entry_size = messages.count * MemoryLayout<Entry>.stride var strData = Data() var offset = entry_size + 16 for (language, country, string) in messages { let str = string.data(using: .utf16BigEndian)! strData.append(str) stream.encode(Entry(language: language, country: country, length: BEUInt32(str.count), offset: BEUInt32(offset))) offset += str.count } stream.write(strData) } var startIndex: Int { return 0 } var endIndex: Int { return messages.count } subscript(position: Int) -> (language: LanguageCode, country: CountryCode, String) { return messages[position] } } extension iccMultiLocalizedUnicode { struct LanguageCode: SignatureProtocol { var rawValue: BEUInt16 init(rawValue: BEUInt16) { self.rawValue = rawValue } } struct CountryCode: SignatureProtocol { var rawValue: BEUInt16 init(rawValue: BEUInt16) { self.rawValue = rawValue } } struct Header: ByteCodable { var count: BEUInt32 var size: BEUInt32 init(count: BEUInt32, size: BEUInt32) { self.count = count self.size = size } init(from data: inout Data) throws { self.count = try data.decode(BEUInt32.self) self.size = try data.decode(BEUInt32.self) } func write<Target: ByteOutputStream>(to stream: inout Target) { stream.encode(count) stream.encode(size) } } struct Entry: ByteCodable { var language: LanguageCode var country: CountryCode var length: BEUInt32 var offset: BEUInt32 init(language: LanguageCode, country: CountryCode, length: BEUInt32, offset: BEUInt32) { self.language = language self.country = country self.length = length self.offset = offset } init(from data: inout Data) throws { self.language = try data.decode(LanguageCode.self) self.country = try data.decode(CountryCode.self) self.length = try data.decode(BEUInt32.self) self.offset = try data.decode(BEUInt32.self) } func write<Target: ByteOutputStream>(to stream: inout Target) { stream.encode(language) stream.encode(country) stream.encode(length) stream.encode(offset) } } }
mit
772dc1d6d390f1e75ee9d996594c7d35
31.843023
175
0.607364
4.570388
false
false
false
false
yanqingsmile/Stanford_Swift_iOS
SmashTag/SmashTag/TweetTableViewCell.swift
1
3230
// // TweetTableViewCell.swift // SmashTag // // Created by Vivian Liu on 12/14/16. // Copyright © 2016 Vivian Liu. All rights reserved. // import UIKit import Twitter class TweetTableViewCell: UITableViewCell { @IBOutlet weak var tweetScreenNameLabel: UILabel! @IBOutlet weak var tweetTextLabel: UILabel! @IBOutlet weak var tweetCreatedLabel: UILabel! @IBOutlet weak var tweetProfileImageView: UIImageView! var tweet: Twitter.Tweet? { didSet { updateUI() } } private func updateUI() { // reset any existing tweet information tweetTextLabel?.attributedText = nil tweetScreenNameLabel?.text = nil tweetProfileImageView?.image = nil tweetCreatedLabel?.text = nil // load new information from our tweet (if any) if let tweet = self.tweet { var labelText = tweet.text for _ in tweet.media { labelText += " 📷" } // convert to attributed string let attributedString = NSMutableAttributedString(string: labelText) let hashTagAttributes = [NSForegroundColorAttributeName: UIColor.red] let urlAttributes = [NSForegroundColorAttributeName: UIColor.blue] let userMentionAttributes = [NSForegroundColorAttributeName: UIColor.brown] for hashtag in tweet.hashtags { attributedString.addAttributes(hashTagAttributes, range: hashtag.nsrange) } for url in tweet.urls { attributedString.addAttributes(urlAttributes, range: url.nsrange) } for userMention in tweet.userMentions { attributedString.addAttributes(userMentionAttributes, range: userMention.nsrange) } tweetTextLabel?.attributedText = attributedString tweetScreenNameLabel?.text = "\(tweet.user)" // tweet.user.description if let profileImageURL = tweet.user.profileImageURL { /* // Use GCD to download image and set image view DispatchQueue.global(qos: .default).async {[weak weakSelf = self] in if let imageData = NSData(contentsOf: profileImageURL) { DispatchQueue.main.async { weakSelf?.tweetProfileImageView?.image = UIImage(data: imageData as Data) } } } */ // Use SDWebImage to download image and set image view tweetProfileImageView?.sd_setImage(with: profileImageURL, placeholderImage: UIImage(named: "placeholder.png")) } let formatter = DateFormatter() if NSDate().timeIntervalSince(tweet.created) > 24*60*60 { formatter.dateStyle = DateFormatter.Style.short } else { formatter.timeStyle = DateFormatter.Style.short } tweetCreatedLabel?.text = formatter.string(from: tweet.created) } } }
mit
18264372b8f7aeb97644a87ceccdb67c
34.450549
126
0.573776
5.844203
false
false
false
false
PauuloG/app-native-ios
film-quizz/Classes/ViewControllers/CreditViewController.swift
1
808
// // CreditViewController.swift // film-quizz // // Created by Paul Gabriel on 16/06/16. // Copyright © 2016 Paul Gabriel. All rights reserved. // import UIKit class CreditViewcontroller: UIViewController { override func viewDidLoad() { self.navigationController?.setNavigationBarHidden(false, animated: true) let nav = self.navigationController?.navigationBar // Customizing the navBar text color nav?.tintColor = UIColor.whiteColor() // Customizing the navBar background color nav?.barTintColor = UIColor(red:0.13, green:0.13, blue:0.16, alpha:1.0) nav?.translucent = false //Getting Light theme for statusBar UIApplication.sharedApplication().statusBarStyle = UIStatusBarStyle.LightContent } }
mit
7f5127544337585328932a0dcc469a82
30.038462
88
0.677819
4.747059
false
false
false
false
HabitRPG/habitrpg-ios
Habitica Models/Habitica Models/Content/ItemProtocol.swift
1
1377
// // ItemProtocol.swift // Habitica Models // // Created by Phillip Thelen on 12.03.18. // Copyright © 2018 HabitRPG Inc. All rights reserved. // import Foundation public enum ItemType: String, EquatableStringEnumProtocol { case eggs case food case hatchingPotions case quests case special } @objc public protocol ItemProtocol { var key: String? { get set } var text: String? { get set } var notes: String? { get set } var value: Float { get set } var itemType: String? { get set } var isSubscriberItem: Bool { get set } } public extension ItemProtocol { var imageName: String { if itemType == ItemType.eggs { return "Pet_Egg_\(key ?? "")" } else if itemType == ItemType.food { return "Pet_Food_\(key ?? "")" } else if itemType == ItemType.hatchingPotions { return "Pet_HatchingPotion_\(key ?? "")" } else if itemType == ItemType.quests { return "inventory_quest_scroll_\(key ?? "")" } else if itemType == ItemType.special { if key == "inventory_present" { let month = Calendar.current.component(.month, from: Date()) return String(format: "inventory_present_%02d", month) } else { return "shop_\(key ?? "")" } } return "" } }
gpl-3.0
e869ed7d135ae94d39d162f02ee6ac2c
27.081633
76
0.571948
4.169697
false
false
false
false
LinDing/Positano
Positano/ViewControllers/Register/RegisterPickMobileViewController.swift
1
5314
// // RegisterPickMobileViewController.swift // Yep // // Created by NIX on 15/3/17. // Copyright (c) 2015年 Catch Inc. All rights reserved. // import UIKit import PositanoKit import Ruler import RxSwift import RxCocoa final class RegisterPickMobileViewController: BaseInputMobileViewController { fileprivate lazy var disposeBag = DisposeBag() @IBOutlet weak var pickMobileNumberPromptLabel: UILabel! @IBOutlet weak var pickMobileNumberPromptLabelTopConstraint: NSLayoutConstraint! fileprivate lazy var nextButton: UIBarButtonItem = { let button = UIBarButtonItem() button.title = String.trans_buttonNextStep button.rx.tap .subscribe(onNext: { [weak self] in self?.tryShowRegisterVerifyMobile() }) .addDisposableTo(self.disposeBag) return button }() deinit { println("deinit RegisterPickMobile") } override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = UIColor.yepViewBackgroundColor() navigationItem.titleView = NavigationTitleLabel(title: NSLocalizedString("Sign Up", comment: "")) navigationItem.rightBarButtonItem = nextButton pickMobileNumberPromptLabel.text = NSLocalizedString("What's your number?", comment: "") let mobilePhone = sharedStore().state.mobilePhone areaCodeTextField.text = mobilePhone?.areaCode ?? TimeZone.areaCode areaCodeTextField.backgroundColor = UIColor.white areaCodeTextField.delegate = self areaCodeTextField.rx.textInput.text .subscribe(onNext: { [weak self] _ in self?.adjustAreaCodeTextFieldWidth() }) .addDisposableTo(disposeBag) //mobileNumberTextField.placeholder = "" mobileNumberTextField.text = mobilePhone?.number mobileNumberTextField.backgroundColor = UIColor.white mobileNumberTextField.textColor = UIColor.yepInputTextColor() mobileNumberTextField.delegate = self Observable.combineLatest(areaCodeTextField.rx.textInput.text, mobileNumberTextField.rx.textInput.text) { (a, b) -> Bool in guard let a = a, let b = b else { return false } return !a.isEmpty && !b.isEmpty } .bindTo(nextButton.rx.isEnabled) .addDisposableTo(disposeBag) pickMobileNumberPromptLabelTopConstraint.constant = Ruler.iPhoneVertical(30, 50, 60, 60).value if mobilePhone?.number == nil { nextButton.isEnabled = false } } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) mobileNumberTextField.becomeFirstResponder() } // MARK: Actions override func tappedKeyboardReturn() { tryShowRegisterVerifyMobile() } func tryShowRegisterVerifyMobile() { view.endEditing(true) guard let number = mobileNumberTextField.text, let areaCode = areaCodeTextField.text else { return } let mobilePhone = MobilePhone(areaCode: areaCode, number: number) sharedStore().dispatch(MobilePhoneUpdateAction(mobilePhone: mobilePhone)) YepHUD.showActivityIndicator() validateMobilePhone(mobilePhone, failureHandler: { (reason, errorMessage) in YepHUD.hideActivityIndicator() }, completion: { (available, message) in if available, let nickname = PositanoUserDefaults.nickname.value { println("ValidateMobile: available") registerMobilePhone(mobilePhone, nickname: nickname, failureHandler: { (reason, errorMessage) in YepHUD.hideActivityIndicator() if let errorMessage = errorMessage { YepAlert.alertSorry(message: errorMessage, inViewController: self, withDismissAction: { [weak self] in self?.mobileNumberTextField.becomeFirstResponder() }) } }, completion: { created in YepHUD.hideActivityIndicator() if created { SafeDispatch.async { [weak self] in self?.performSegue(withIdentifier: "showRegisterVerifyMobile", sender: nil) } } else { SafeDispatch.async { [weak self] in self?.nextButton.isEnabled = false YepAlert.alertSorry(message: "registerMobile failed", inViewController: self, withDismissAction: { [weak self] in self?.mobileNumberTextField.becomeFirstResponder() }) } } }) } else { println("ValidateMobile: \(message)") YepHUD.hideActivityIndicator() SafeDispatch.async { [weak self] in self?.nextButton.isEnabled = false YepAlert.alertSorry(message: message, inViewController: self, withDismissAction: { [weak self] in self?.mobileNumberTextField.becomeFirstResponder() }) } } }) } }
mit
8a4a3665c0d28c6b6d2f3c876a16e108
33.051282
141
0.609563
5.663113
false
false
false
false
jpedrosa/sua_nc
Sources/locale.swift
2
3587
public class Locale { public let months = [ "January", "February", "March", "April", "May", "June", "July", "August", "Septemper", "October", "November", "December"] public let abbreviatedMonths = [ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"] public let weekdays = [ "Monday", "Thuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"] public let abbreviatedWeekdays = ["Mon", "Thu", "Wed", "Thu", "Fri", "Sat", "Sun"] // Formats time like the strftime function in C. // We're still missing some of the features though. // E.g. // p(Time().strftime("%Y-%m-%d %H:%M:%S")) //> "2015-12-29 04:06:12" public func strftime(time: Time, mask: String) -> String { var sb = "" var tokenIndex = -1 var i = 0 func process(z: String, padding: Int = 0) { if tokenIndex >= 0 { sb += mask.utf16.substring(tokenIndex, endIndex: i - 1) ?? "" tokenIndex = -1 } var j = z.utf16.count - padding while j < 0 { sb += "0" j += 1 } sb += z } let len = mask.utf16.count let lasti = len - 1 while i < len { if mask.utf16.codeUnitAt(i) == 37 && i < lasti { // % i += 1 switch mask.utf16.codeUnitAt(i) { case 37: // % sb += "%" case 45: // - if i < lasti { if mask.utf16.codeUnitAt(i + 1) == 100 { // d process("\(time.day)") i += 1 } else { i -= 1 } } else { i -= 1 } case 65: // A process(weekdays[time.weekday - 1]) case 66: // B process(months[time.month - 1]) case 72: // H process("\(time.hour)", padding: 2) case 76: // L process("\(time.nanoseconds / 1000000)", padding: 3) case 77: // M process("\(time.minute)", padding: 2) case 80: // P process(time.hour >= 12 ? "PM" : "AM") case 83: // S process("\(time.second)", padding: 2) case 89: // Y process("\(time.year)", padding: 4) case 97: // a process(abbreviatedWeekdays[time.weekday - 1]) case 98: // b process(abbreviatedMonths[time.month - 1]) case 100: // d process("\(time.day)", padding: 2) case 109: // m process("\(time.month)", padding: 2) case 112: // p process(time.hour >= 12 ? "pm" : "am") default: i -= 1 } } else { if tokenIndex < 0 { tokenIndex = i } } i += 1 } if tokenIndex >= 0 { sb += mask.utf16.substring(tokenIndex, endIndex: i) ?? "" } return sb } public func formatDouble(f: Double, precision: Int = 2) -> String { var p = 1 for _ in 0..<precision { p *= 10 } let neutral = Math.abs(Math.round((f * Double(p)))) var s = "" let a = "\(neutral)".characters let len = a.count var dot = len - precision if f < 0 { s += "-" } if dot <= 0 { dot = 1 } let pad = precision - len var i = 0 while i <= pad { s += i == dot ? ".0" : "0" i += 1 } for c in a { if i == dot { s += "." } s.append(c) i += 1 } return s } // Default, constant locale that can be used when the format requires // American, English or standard system compatibility. public static let one = Locale() }
apache-2.0
c65a408c5a2b6af3fb0716c99c49d86c
25.182482
77
0.466685
3.615927
false
false
false
false
dobaduc/SwiftStarterKit
SwiftStarterKitTests/OtherSwiftSyntaxTests.swift
1
1982
// // OtherSwiftSyntaxTests.swift // SwiftStarterKit // // Created by Doba Duc on 7/7/15. // Copyright (c) 2015 Doba Duc. All rights reserved. // import XCTest class OtherSwiftSyntaxTests: XCTestCase { func testSomeMoreSwiftSyntax() { // NOTE: # has been removed from Swift 2.0 func containsCharacter(#string: String, #characterToFind: Character) -> Bool { for character in string { if character == characterToFind { return true } } return false } // Variadic Parameters func min(numbers: Int...) -> Int { var min: Int = Int.max for number in numbers { if min > number { min = number } } return min } XCTAssert(min(10, 4, 332, 232, 2, 11, 1) == 1, "Min should be 1") } // MARK:- Literal func testNumberLiteralWithUnderscore() { let creditCardNumber = 1234_5678_9012 let phoneNumber = 0120_1234_5678 // phoneNumber == 12012345678 let phoneNumberString: String = "" + 0120_1234_5678.description // phoneNumberString == "12012345678" let numberFromString = "1234_4567_4343".toInt() // ---> numberFromString == nil XCTAssert(creditCardNumber == 123456789012 , "Failed") XCTAssert(phoneNumber == 12012345678 , "Failed") XCTAssert(phoneNumberString == "12012345678" , "Failed") XCTAssertNil(numberFromString , "Failed") } func testAutoClosure() { func isEmpty(tester: () -> Bool) -> String { return tester() ? "TRUE" : "FALSE" } func isEmptyWithAutoClosure(@autoclosure tester: () -> Bool) -> String { return tester() ? "TRUE" : "FALSE" } XCTAssert(isEmpty({ 2 > 1}) == "TRUE", "Wrong result") XCTAssert(isEmptyWithAutoClosure( 3 > 5) == "FALSE", "Wrong result") } }
mit
3282bf4dc163fe7fd50359d63fcb1869
30.47619
109
0.559031
4.463964
false
true
false
false
bowdoincollege/iOS-OSC-Sender
OSC-Sender/ViewController.swift
1
2597
// // ViewController.swift // OSC-Sender // // Created by Stephen Houser on 4/13/17. // Copyright © 2017 stephenhouser. All rights reserved. // import UIKit import OSCKit // https://github.com/256dpi/OSCKit import AVFoundation class ViewController: UIViewController { let ipAddressKey = "ip_address" let ipPortKey = "ip_port" let client = OSCClient() var clientIPAddress = "127.0.0.1" var clientIPPort = "2222" var clientAddress = "127.0.0.1:2222" //inet 139.140.214.218 var audioPlayer: AVAudioPlayer! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. updateClientAddress() // Define identifier let notificationName = UserDefaults.didChangeNotification // Register to receive notification NotificationCenter.default.addObserver(self, selector: #selector(self.updateClientAddress), name: notificationName, object: nil) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func updateClientAddress() { print("Updated settings") let settings = UserDefaults.standard if settings.value(forKey: ipAddressKey) == nil { settings.set(clientIPAddress, forKey: ipAddressKey) } if settings.value(forKey: ipPortKey) == nil { settings.set(clientIPPort, forKey: ipPortKey) } if let ipAddressValue = settings.string(forKey: ipAddressKey), let ipPortValue = settings.string(forKey: ipPortKey) { clientAddress = "\(ipAddressValue):\(ipPortValue)" } } @IBAction func clickSoundButton(_ sender: UIButton) { if (audioPlayer != nil && audioPlayer.isPlaying) { audioPlayer.stop() audioPlayer = nil; } else { if let path = Bundle.main.path(forResource: "Narration", ofType: "mp3") { let url = URL(fileURLWithPath: path) do { audioPlayer = try AVAudioPlayer(contentsOf: url) audioPlayer.prepareToPlay() audioPlayer.play() } catch { } } } } @IBAction func clickButton(_ sender: UIButton) { let tag = "/button-\(sender.tag)" let message = OSCMessage(address: tag, arguments: nil) client.send(message, to: "udp://\(clientAddress)") } }
mit
e8381a61af498a322ce9e76ae5c73eeb
28.168539
85
0.602465
4.59469
false
false
false
false
mpangburn/RayTracer
RayTracer/Models/Sphere.swift
1
2858
// // Sphere.swift // RayTracer // // Created by Michael Pangburn on 6/26/17. // Copyright © 2017 Michael Pangburn. All rights reserved. // import Foundation import CoreData /// Represents a sphere. extension Sphere { /** Creates a sphere with the given center, radius, and color. - Parameters: - center: The center of the sphere. - radius: The radius of the sphere. - color: The color of sphere; defaults to black. */ convenience init(center: Point, radius: Double, color: Color, finish: Finish, context: NSManagedObjectContext) { self.init(context: context) self.center = center self.radius = radius self.color = color self.finish = finish } } // MARK: - Sphere math extension Sphere { /** Returns the normal vector from the center to the point. - Parameter point: The point for which to compute the normal vector at. - Returns: The normal vector from the center to the point. */ func normal(at point: Point) -> Vector { return Vector(from: self.center, to: point).normalized() } } // MARK: - Sphere string parsing extension Sphere { /** Parses a string of format `x y z radius r g b ambient diffuse specular roughness` and creates the corresponding sphere. Fails if the string is malformed. - Parameter string: The string containing the sphere's data. */ convenience init?(string: String, context: NSManagedObjectContext) { let components = string.components(separatedBy: " ") .map { Double($0) } .flatMap { $0 } guard components.count == 11 else { return nil } let center = Point(x: components[0], y: components[1], z: components[2]) let radius = components[3] let color = Color(red: components[4], green: components[5], blue: components[6]) let finish = Finish(ambient: components[7], diffuse: components[8], specular: components[9], roughness: components[10]) self.init(center: center, radius: radius, color: color, finish: finish, context: context) } /// The equation form of the sphere. func equation(usingIntegers: Bool) -> String { let base: String if usingIntegers { base = "(x - \(Int(self.center.x)))² + (y - \(Int(self.center.y)))² + (z - \(Int(self.center.z)))² = \(Int(self.radius))" } else { base = "(x - \(self.center.x))² + (y - \(self.center.y))² + (z - \(self.center.z))² = \(self.radius)" } return base.replacingOccurrences(of: "- -", with: "+ ") } } extension Sphere { static func == (lhs: Sphere, rhs: Sphere) -> Bool { return lhs.center == rhs.center && lhs.radius == rhs.radius && lhs.color == rhs.color && lhs.finish == rhs.finish } }
mit
022db4069eba361a3d565ae64cf5fa9a
31.397727
133
0.608909
3.998597
false
false
false
false
blockchain/My-Wallet-V3-iOS
Modules/FeatureOnboarding/Tests/FeatureOnboardingUITests/Mocks/MockBuyCryptoRouter.swift
1
1156
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import Combine import FeatureOnboardingUI import ToolKit import UIKit final class MockBuyCryptoRouter: TransactionsRouterAPI { struct RecordedInvocations { var presentBuyFlow: [UIViewController] = [] var navigateToBuyCryptoFlow: [UIViewController] = [] var navigateToReceiveCryptoFlow: [UIViewController] = [] } struct StubbedResults { var presentBuyFlow: AnyPublisher<OnboardingResult, Never> = .just(.abandoned) } private(set) var recordedInvocations = RecordedInvocations() var stubbedResults = StubbedResults() func presentBuyFlow(from presenter: UIViewController) -> AnyPublisher<OnboardingResult, Never> { recordedInvocations.presentBuyFlow.append(presenter) return stubbedResults.presentBuyFlow } func navigateToBuyCryptoFlow(from presenter: UIViewController) { recordedInvocations.navigateToBuyCryptoFlow.append(presenter) } func navigateToReceiveCryptoFlow(from presenter: UIViewController) { recordedInvocations.navigateToReceiveCryptoFlow.append(presenter) } }
lgpl-3.0
a3ccaa65c8f91ceb68bfd6d6d4534fa6
32
100
0.750649
5.088106
false
false
false
false
blockchain/My-Wallet-V3-iOS
Modules/CryptoAssets/Sources/BitcoinCashKit/Network/Client/APIClient.swift
1
1635
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import BitcoinChainKit import Combine import DIKit import Errors import NetworkKit import PlatformKit enum APIClientError: Error { case unknown } protocol APIClientAPI { func multiAddress(for wallets: [XPub]) -> AnyPublisher<BitcoinCashMultiAddressResponse, NetworkError> func balances(for wallets: [XPub]) -> AnyPublisher<BitcoinCashBalanceResponse, NetworkError> func dust() -> AnyPublisher<BchDustResponse, NetworkError> } final class APIClient: APIClientAPI { private let client: BitcoinChainKit.APIClientAPI private let requestBuilder: RequestBuilder private let networkAdapter: NetworkAdapterAPI // MARK: - Init init( client: BitcoinChainKit.APIClientAPI = resolve(tag: BitcoinChainCoin.bitcoinCash), requestBuilder: RequestBuilder = resolve(), networkAdapter: NetworkAdapterAPI = resolve() ) { self.client = client self.requestBuilder = requestBuilder self.networkAdapter = networkAdapter } // MARK: - APIClientAPI func multiAddress( for wallets: [XPub] ) -> AnyPublisher<BitcoinCashMultiAddressResponse, NetworkError> { client.multiAddress(for: wallets) } func balances( for wallets: [XPub] ) -> AnyPublisher<BitcoinCashBalanceResponse, NetworkError> { client.balances(for: wallets) } func dust() -> AnyPublisher<BchDustResponse, NetworkError> { let request = requestBuilder.get( path: "/bch/dust" )! return networkAdapter.perform(request: request) } }
lgpl-3.0
0b9b88e247014314e95bad226259a4dd
25.786885
105
0.69951
4.75
false
false
false
false
TwistFate6/RxPersonalPhoneNum
RxContracts/RxContracts/RxContractsViewController.swift
1
4224
// // RxContractsViewController.swift // PocketContracts // // Created by RXL on 16/4/6. // Copyright © 2016年 RXL. All rights reserved. // import UIKit var test = NSMutableArray() class RxContractsViewController: UITableViewController { lazy var Contracts : NSMutableArray = { var Contracts = NSKeyedUnarchiver.unarchiveObjectWithFile(DataPath) as? NSMutableArray if Contracts == nil { Contracts = NSMutableArray() } return Contracts! }() override func viewDidLoad() { super.viewDidLoad() let bgView = UIImageView(frame: view.bounds) bgView.image = UIImage(named: "bg1") tableView.backgroundView = bgView tableView.separatorStyle = .None } /** 注销按钮 */ @IBAction func LoginOut(sender: AnyObject) { // Mark : 弹窗 let alert = UIAlertController(title: "提示", message: "确定注销吗", preferredStyle: UIAlertControllerStyle.ActionSheet) let confirm = UIAlertAction(title: "确定", style: UIAlertActionStyle.Destructive) { (UIAlertAction) in self.navigationController!.popViewControllerAnimated(true) } let cancel = UIAlertAction(title: "取消", style: UIAlertActionStyle.Cancel, handler: nil) alert.addAction(confirm) alert.addAction(cancel) self .presentViewController(alert, animated: true, completion: nil) } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows return Contracts.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("cell") as! RxContractCell let contract = Contracts[indexPath.row] cell.contracts = contract as? RxContracts cell.backgroundColor = UIColor.clearColor() cell.selectionStyle = .Blue return cell } // MARK : - 实现cell的删除 override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { // 将对应的模型从数组中删除 Contracts.removeObjectAtIndex(indexPath.row) // 删除指定行 tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) // 将数组重新写入本地 NSKeyedArchiver.archiveRootObject(Contracts, toFile: DataPath) } // MARK : - 修改删除按钮的名称 override func tableView(tableView: UITableView, titleForDeleteConfirmationButtonForRowAtIndexPath indexPath: NSIndexPath) -> String? { return "删除" } // cell的点击 override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { self.performSegueWithIdentifier("callPhone", sender: nil) } @IBAction func addContract(sender: AnyObject) { self.performSegueWithIdentifier("addContract", sender: nil) } // 准备跳转的时候进行调用 override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // 目标控制器 let destVC = segue.destinationViewController // 进行判断跳转的是哪一个控制器 if destVC.isKindOfClass(RxAddContract) { let addVC = destVC as! RxAddContract addVC.addContractModel = { (contract: RxContracts) in self.Contracts.addObject(contract) // 将数组保存到本地 NSKeyedArchiver.archiveRootObject(self.Contracts, toFile: DataPath) self.tableView.reloadData() } } } }
mit
7af60fdeb5340f6a07b74955b696f81d
25.986577
157
0.602835
5.448509
false
false
false
false
SeriousChoice/SCSwift
Example/Pods/Cache/Source/Shared/Library/MD5.swift
2
9000
/* * A JavaScript implementation of the RSA Data Security, Inc. MD5 Message * Digest Algorithm, as defined in RFC 1321. * Version 2.2 Copyright (C) Paul Johnston 1999 - 2009 * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet * Distributed under the BSD License * See http://pajhome.org.uk/crypt/md5 for more info. */ /** * SwiftHash * Copyright (c) Khoa Pham 2017 * Licensed under the MIT license. See LICENSE file. */ import Foundation // MARK: - Public public func MD5(_ input: String) -> String { return hex_md5(input) } // MARK: - Functions func hex_md5(_ input: String) -> String { return rstr2hex(rstr_md5(str2rstr_utf8(input))) } func str2rstr_utf8(_ input: String) -> [CUnsignedChar] { return Array(input.utf8) } func rstr2tr(_ input: [CUnsignedChar]) -> String { var output: String = "" input.forEach { output.append(String(UnicodeScalar($0))) } return output } /* * Convert a raw string to a hex string */ func rstr2hex(_ input: [CUnsignedChar]) -> String { let hexTab: [Character] = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F"] var output: [Character] = [] for i in 0..<input.count { let x = input[i] let value1 = hexTab[Int((x >> 4) & 0x0F)] let value2 = hexTab[Int(Int32(x) & 0x0F)] output.append(value1) output.append(value2) } return String(output) } /* * Convert a raw string to an array of little-endian words * Characters >255 have their high-byte silently ignored. */ func rstr2binl(_ input: [CUnsignedChar]) -> [Int32] { var output: [Int: Int32] = [:] for i in stride(from: 0, to: input.count * 8, by: 8) { let value: Int32 = (Int32(input[i/8]) & 0xFF) << (Int32(i) % 32) output[i >> 5] = unwrap(output[i >> 5]) | value } return dictionary2array(output) } /* * Convert an array of little-endian words to a string */ func binl2rstr(_ input: [Int32]) -> [CUnsignedChar] { var output: [CUnsignedChar] = [] for i in stride(from: 0, to: input.count * 32, by: 8) { // [i>>5] >>> let value: Int32 = zeroFillRightShift(input[i>>5], Int32(i % 32)) & 0xFF output.append(CUnsignedChar(value)) } return output } /* * Calculate the MD5 of a raw string */ func rstr_md5(_ input: [CUnsignedChar]) -> [CUnsignedChar] { return binl2rstr(binl_md5(rstr2binl(input), input.count * 8)) } /* * Add integers, wrapping at 2^32. */ func safe_add(_ x: Int32, _ y: Int32) -> Int32 { return x &+ y } /* * Bitwise rotate a 32-bit number to the left. */ func bit_rol(_ num: Int32, _ cnt: Int32) -> Int32 { // num >>> return (num << cnt) | zeroFillRightShift(num, (32 - cnt)) } /* * These funcs implement the four basic operations the algorithm uses. */ func md5_cmn(_ q: Int32, _ a: Int32, _ b: Int32, _ x: Int32, _ s: Int32, _ t: Int32) -> Int32 { return safe_add(bit_rol(safe_add(safe_add(a, q), safe_add(x, t)), s), b) } func md5_ff(_ a: Int32, _ b: Int32, _ c: Int32, _ d: Int32, _ x: Int32, _ s: Int32, _ t: Int32) -> Int32 { return md5_cmn((b & c) | ((~b) & d), a, b, x, s, t) } func md5_gg(_ a: Int32, _ b: Int32, _ c: Int32, _ d: Int32, _ x: Int32, _ s: Int32, _ t: Int32) -> Int32 { return md5_cmn((b & d) | (c & (~d)), a, b, x, s, t) } func md5_hh(_ a: Int32, _ b: Int32, _ c: Int32, _ d: Int32, _ x: Int32, _ s: Int32, _ t: Int32) -> Int32 { return md5_cmn(b ^ c ^ d, a, b, x, s, t) } func md5_ii(_ a: Int32, _ b: Int32, _ c: Int32, _ d: Int32, _ x: Int32, _ s: Int32, _ t: Int32) -> Int32 { return md5_cmn(c ^ (b | (~d)), a, b, x, s, t) } /* * Calculate the MD5 of an array of little-endian words, and a bit length. */ func binl_md5(_ input: [Int32], _ len: Int) -> [Int32] { /* append padding */ var x: [Int: Int32] = [:] for (index, value) in input.enumerated() { x[index] = value } let value: Int32 = 0x80 << Int32((len) % 32) x[len >> 5] = unwrap(x[len >> 5]) | value // >>> 9 let index = (((len + 64) >> 9) << 4) + 14 x[index] = unwrap(x[index]) | Int32(len) var a: Int32 = 1732584193 var b: Int32 = -271733879 var c: Int32 = -1732584194 var d: Int32 = 271733878 for i in stride(from: 0, to: length(x), by: 16) { let olda: Int32 = a let oldb: Int32 = b let oldc: Int32 = c let oldd: Int32 = d a = md5_ff(a, b, c, d, unwrap(x[i + 0]), 7 , -680876936) d = md5_ff(d, a, b, c, unwrap(x[i + 1]), 12, -389564586) c = md5_ff(c, d, a, b, unwrap(x[i + 2]), 17, 606105819) b = md5_ff(b, c, d, a, unwrap(x[i + 3]), 22, -1044525330) a = md5_ff(a, b, c, d, unwrap(x[i + 4]), 7 , -176418897) d = md5_ff(d, a, b, c, unwrap(x[i + 5]), 12, 1200080426) c = md5_ff(c, d, a, b, unwrap(x[i + 6]), 17, -1473231341) b = md5_ff(b, c, d, a, unwrap(x[i + 7]), 22, -45705983) a = md5_ff(a, b, c, d, unwrap(x[i + 8]), 7 , 1770035416) d = md5_ff(d, a, b, c, unwrap(x[i + 9]), 12, -1958414417) c = md5_ff(c, d, a, b, unwrap(x[i + 10]), 17, -42063) b = md5_ff(b, c, d, a, unwrap(x[i + 11]), 22, -1990404162) a = md5_ff(a, b, c, d, unwrap(x[i + 12]), 7 , 1804603682) d = md5_ff(d, a, b, c, unwrap(x[i + 13]), 12, -40341101) c = md5_ff(c, d, a, b, unwrap(x[i + 14]), 17, -1502002290) b = md5_ff(b, c, d, a, unwrap(x[i + 15]), 22, 1236535329) a = md5_gg(a, b, c, d, unwrap(x[i + 1]), 5 , -165796510) d = md5_gg(d, a, b, c, unwrap(x[i + 6]), 9 , -1069501632) c = md5_gg(c, d, a, b, unwrap(x[i + 11]), 14, 643717713) b = md5_gg(b, c, d, a, unwrap(x[i + 0]), 20, -373897302) a = md5_gg(a, b, c, d, unwrap(x[i + 5]), 5 , -701558691) d = md5_gg(d, a, b, c, unwrap(x[i + 10]), 9 , 38016083) c = md5_gg(c, d, a, b, unwrap(x[i + 15]), 14, -660478335) b = md5_gg(b, c, d, a, unwrap(x[i + 4]), 20, -405537848) a = md5_gg(a, b, c, d, unwrap(x[i + 9]), 5 , 568446438) d = md5_gg(d, a, b, c, unwrap(x[i + 14]), 9 , -1019803690) c = md5_gg(c, d, a, b, unwrap(x[i + 3]), 14, -187363961) b = md5_gg(b, c, d, a, unwrap(x[i + 8]), 20, 1163531501) a = md5_gg(a, b, c, d, unwrap(x[i + 13]), 5 , -1444681467) d = md5_gg(d, a, b, c, unwrap(x[i + 2]), 9 , -51403784) c = md5_gg(c, d, a, b, unwrap(x[i + 7]), 14, 1735328473) b = md5_gg(b, c, d, a, unwrap(x[i + 12]), 20, -1926607734) a = md5_hh(a, b, c, d, unwrap(x[i + 5]), 4 , -378558) d = md5_hh(d, a, b, c, unwrap(x[i + 8]), 11, -2022574463) c = md5_hh(c, d, a, b, unwrap(x[i + 11]), 16, 1839030562) b = md5_hh(b, c, d, a, unwrap(x[i + 14]), 23, -35309556) a = md5_hh(a, b, c, d, unwrap(x[i + 1]), 4 , -1530992060) d = md5_hh(d, a, b, c, unwrap(x[i + 4]), 11, 1272893353) c = md5_hh(c, d, a, b, unwrap(x[i + 7]), 16, -155497632) b = md5_hh(b, c, d, a, unwrap(x[i + 10]), 23, -1094730640) a = md5_hh(a, b, c, d, unwrap(x[i + 13]), 4 , 681279174) d = md5_hh(d, a, b, c, unwrap(x[i + 0]), 11, -358537222) c = md5_hh(c, d, a, b, unwrap(x[i + 3]), 16, -722521979) b = md5_hh(b, c, d, a, unwrap(x[i + 6]), 23, 76029189) a = md5_hh(a, b, c, d, unwrap(x[i + 9]), 4 , -640364487) d = md5_hh(d, a, b, c, unwrap(x[i + 12]), 11, -421815835) c = md5_hh(c, d, a, b, unwrap(x[i + 15]), 16, 530742520) b = md5_hh(b, c, d, a, unwrap(x[i + 2]), 23, -995338651) a = md5_ii(a, b, c, d, unwrap(x[i + 0]), 6 , -198630844) d = md5_ii(d, a, b, c, unwrap(x[i + 7]), 10, 1126891415) c = md5_ii(c, d, a, b, unwrap(x[i + 14]), 15, -1416354905) b = md5_ii(b, c, d, a, unwrap(x[i + 5]), 21, -57434055) a = md5_ii(a, b, c, d, unwrap(x[i + 12]), 6 , 1700485571) d = md5_ii(d, a, b, c, unwrap(x[i + 3]), 10, -1894986606) c = md5_ii(c, d, a, b, unwrap(x[i + 10]), 15, -1051523) b = md5_ii(b, c, d, a, unwrap(x[i + 1]), 21, -2054922799) a = md5_ii(a, b, c, d, unwrap(x[i + 8]), 6 , 1873313359) d = md5_ii(d, a, b, c, unwrap(x[i + 15]), 10, -30611744) c = md5_ii(c, d, a, b, unwrap(x[i + 6]), 15, -1560198380) b = md5_ii(b, c, d, a, unwrap(x[i + 13]), 21, 1309151649) a = md5_ii(a, b, c, d, unwrap(x[i + 4]), 6 , -145523070) d = md5_ii(d, a, b, c, unwrap(x[i + 11]), 10, -1120210379) c = md5_ii(c, d, a, b, unwrap(x[i + 2]), 15, 718787259) b = md5_ii(b, c, d, a, unwrap(x[i + 9]), 21, -343485551) a = safe_add(a, olda) b = safe_add(b, oldb) c = safe_add(c, oldc) d = safe_add(d, oldd) } return [a, b, c, d] } // MARK: - Helper func length(_ dictionary: [Int: Int32]) -> Int { return (dictionary.keys.max() ?? 0) + 1 } func dictionary2array(_ dictionary: [Int: Int32]) -> [Int32] { var array = Array<Int32>(repeating: 0, count: dictionary.keys.count) for i in Array(dictionary.keys).sorted() { array[i] = unwrap(dictionary[i]) } return array } func unwrap(_ value: Int32?, _ fallback: Int32 = 0) -> Int32 { if let value = value { return value } return fallback } func zeroFillRightShift(_ num: Int32, _ count: Int32) -> Int32 { let value = UInt32(bitPattern: num) >> UInt32(bitPattern: count) return Int32(bitPattern: value) }
mit
95733bb9d1e11b83c0743812bc625929
31.846715
108
0.549667
2.335236
false
false
false
false
keith/ModMove
ModMove/AccessibilityElement.swift
1
3688
import AppKit import Foundation final class AccessibilityElement { static let systemWideElement = AccessibilityElement.createSystemWideElement() var position: CGPoint? { get { return self.getPosition() } set { if let position = newValue { self.set(position: position) } } } var size: CGSize? { get { return self.getSize() } set { if let size = newValue { self.set(size: size) } } } private let elementRef: AXUIElement init(elementRef: AXUIElement) { self.elementRef = elementRef } func element(at point: CGPoint) -> Self? { var ref: AXUIElement? AXUIElementCopyElementAtPosition(self.elementRef, Float(point.x), Float(point.y), &ref) return ref.map(type(of: self).init) } func window() -> Self? { var element = self while element.role() != kAXWindowRole { if let nextElement = element.parent() { element = nextElement } else { return nil } } return element } func parent() -> Self? { return self.value(for: .parent) } func role() -> String? { return self.value(for: .role) } func pid() -> pid_t? { let pointer = UnsafeMutablePointer<pid_t>.allocate(capacity: 1) let error = AXUIElementGetPid(self.elementRef, pointer) return error == .success ? pointer.pointee : nil } func bringToFront() { if let isMainWindow = self.rawValue(for: .main) as? Bool, isMainWindow { return } AXUIElementSetAttributeValue(self.elementRef, NSAccessibility.Attribute.main.rawValue as CFString, true as CFTypeRef) } // MARK: - Private functions private static func createSystemWideElement() -> Self { return self.init(elementRef: AXUIElementCreateSystemWide()) } private func getPosition() -> CGPoint? { return self.value(for: .position) } private func set(position: CGPoint) { if let value = AXValue.from(value: position, type: .cgPoint) { AXUIElementSetAttributeValue(self.elementRef, kAXPositionAttribute as CFString, value) } } private func getSize() -> CGSize? { return self.value(for: .size) } private func set(size: CGSize) { if let value = AXValue.from(value: size, type: .cgSize) { AXUIElementSetAttributeValue(self.elementRef, kAXSizeAttribute as CFString, value) } } private func rawValue(for attribute: NSAccessibility.Attribute) -> AnyObject? { var rawValue: AnyObject? let error = AXUIElementCopyAttributeValue(self.elementRef, attribute.rawValue as CFString, &rawValue) return error == .success ? rawValue : nil } private func value(for attribute: NSAccessibility.Attribute) -> Self? { if let rawValue = self.rawValue(for: attribute), CFGetTypeID(rawValue) == AXUIElementGetTypeID() { return type(of: self).init(elementRef: rawValue as! AXUIElement) } return nil } private func value(for attribute: NSAccessibility.Attribute) -> String? { return self.rawValue(for: attribute) as? String } private func value<T>(for attribute: NSAccessibility.Attribute) -> T? { if let rawValue = self.rawValue(for: attribute), CFGetTypeID(rawValue) == AXValueGetTypeID() { return (rawValue as! AXValue).toValue() } return nil } }
mit
009fa60119c267110ecfe52e9207140c
28.269841
109
0.593547
4.598504
false
false
false
false
C453/Force-Touch-Command-Center
Force Touch Command Center/Options.swift
1
1932
// // Options.swift // Force Touch Command Center // // Created by Case Wright on 9/24/15. // Copyright © 2015 C453. All rights reserved. // import Foundation import AudioToolbox enum ActionType: Int { case Volume = 0 case Brightness = 1 } enum ShapeType: CGFloat { case Square = 30.0 case Circle = 150.0 } struct Options { static let kPreferenceGlobalShortcut = "GlobalShortcut"; static let center: CGPoint = CGPoint(x: CGDisplayPixelsWide(0) / 2, y: CGDisplayPixelsHigh(0) / 2) static var optionsWindowController: NSWindowController? static var popupWindowController: NSWindowController? static var defaultOutputDeviceID = AudioDeviceID(0) static var action: ActionType = .Brightness static var lowerLimit: Float = 0.1 static var upperLimit: Float = 1 static var Shape: ShapeType = .Square static var showSlider:Bool = true static var showLevel:Bool = true static func getVolumeDevice() { var defaultOutputDeviceIDSize = UInt32(sizeofValue(defaultOutputDeviceID)) var getDefaultOutputDevicePropertyAddress = AudioObjectPropertyAddress( mSelector: AudioObjectPropertySelector(kAudioHardwarePropertyDefaultOutputDevice), mScope: AudioObjectPropertyScope(kAudioObjectPropertyScopeGlobal), mElement: AudioObjectPropertyElement(kAudioObjectPropertyElementMaster)) AudioObjectGetPropertyData( AudioObjectID(kAudioObjectSystemObject), &getDefaultOutputDevicePropertyAddress, 0, nil, &defaultOutputDeviceIDSize, &defaultOutputDeviceID) } static func delay(delay: Double, block:()->()) { let nSecDispatchTime = dispatch_time(DISPATCH_TIME_NOW, Int64(delay * Double(NSEC_PER_SEC))); let queue = dispatch_get_main_queue() dispatch_after(nSecDispatchTime, queue, block) } }
gpl-2.0
56f294fbed183c4a70259b482c25d630
31.2
94
0.69653
4.511682
false
false
false
false
vanshg/MacAssistant
Pods/SwiftyUserDefaults/Sources/DefaultsSerializable+BuiltIns.swift
1
10645
// // SwiftyUserDefaults // // Copyright (c) 2015-2018 Radosław Pietruszewski, Łukasz Mróz // // 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 extension String: DefaultsSerializable, DefaultsDefaultArrayValueType, DefaultsDefaultValueType { public static var defaultValue: String = "" public static var defaultArrayValue: [String] = [] public static func get(key: String, userDefaults: UserDefaults) -> String? { return userDefaults.string(forKey: key) } public static func getArray(key: String, userDefaults: UserDefaults) -> [String]? { return userDefaults.array(forKey: key) as? [String] } public static func save(key: String, value: String?, userDefaults: UserDefaults) { userDefaults.set(value, forKey: key) } public static func saveArray(key: String, value: [String], userDefaults: UserDefaults) { userDefaults.set(value, forKey: key) } } extension Int: DefaultsSerializable, DefaultsDefaultArrayValueType, DefaultsDefaultValueType { public static var defaultValue: Int = 0 public static var defaultArrayValue: [Int] = [] public static func get(key: String, userDefaults: UserDefaults) -> Int? { return userDefaults.number(forKey: key)?.intValue } public static func getArray(key: String, userDefaults: UserDefaults) -> [Int]? { return userDefaults.array(forKey: key) as? [Int] } public static func save(key: String, value: Int?, userDefaults: UserDefaults) { userDefaults.set(value, forKey: key) } public static func saveArray(key: String, value: [Int], userDefaults: UserDefaults) { userDefaults.set(value, forKey: key) } } extension Double: DefaultsSerializable, DefaultsDefaultArrayValueType, DefaultsDefaultValueType { public static var defaultValue: Double = 0.0 public static var defaultArrayValue: [Double] = [] public static func get(key: String, userDefaults: UserDefaults) -> Double? { return userDefaults.number(forKey: key)?.doubleValue } public static func getArray(key: String, userDefaults: UserDefaults) -> [Double]? { return userDefaults.array(forKey: key) as? [Double] } public static func save(key: String, value: Double?, userDefaults: UserDefaults) { userDefaults.set(value, forKey: key) } public static func saveArray(key: String, value: [Double], userDefaults: UserDefaults) { userDefaults.set(value, forKey: key) } } extension Bool: DefaultsSerializable, DefaultsDefaultArrayValueType, DefaultsDefaultValueType { public static var defaultValue: Bool = false public static var defaultArrayValue: [Bool] = [] public static func get(key: String, userDefaults: UserDefaults) -> Bool? { // @warning we use number(forKey:) instead of bool(forKey:), because // bool(forKey:) will always return value, even if it's not set // and it does a little bit of magic under the hood as well // e.g. transforming strings like "YES" or "true" to true return userDefaults.number(forKey: key)?.boolValue } public static func getArray(key: String, userDefaults: UserDefaults) -> [Bool]? { return userDefaults.array(forKey: key) as? [Bool] } public static func save(key: String, value: Bool?, userDefaults: UserDefaults) { userDefaults.set(value, forKey: key) } public static func saveArray(key: String, value: [Bool], userDefaults: UserDefaults) { userDefaults.set(value, forKey: key) } } extension Data: DefaultsSerializable, DefaultsDefaultArrayValueType, DefaultsDefaultValueType { public static var defaultValue: Data = Data() public static var defaultArrayValue: [Data] = [] public static func get(key: String, userDefaults: UserDefaults) -> Data? { return userDefaults.data(forKey: key) } public static func getArray(key: String, userDefaults: UserDefaults) -> [Data]? { return userDefaults.array(forKey: key) as? [Data] } public static func save(key: String, value: Data?, userDefaults: UserDefaults) { userDefaults.set(value, forKey: key) } public static func saveArray(key: String, value: [Data], userDefaults: UserDefaults) { userDefaults.set(value, forKey: key) } } extension Date: DefaultsSerializable { public static func get(key: String, userDefaults: UserDefaults) -> Date? { return userDefaults.object(forKey: key) as? Date } public static func getArray(key: String, userDefaults: UserDefaults) -> [Date]? { return userDefaults.array(forKey: key) as? [Date] } public static func save(key: String, value: Date?, userDefaults: UserDefaults) { userDefaults.set(value, forKey: key) } public static func saveArray(key: String, value: [Date], userDefaults: UserDefaults) { userDefaults.set(value, forKey: key) } } extension URL: DefaultsSerializable { public static func get(key: String, userDefaults: UserDefaults) -> URL? { return userDefaults.url(forKey: key) } public static func getArray(key: String, userDefaults: UserDefaults) -> [URL]? { return userDefaults.data(forKey: key).flatMap(NSKeyedUnarchiver.unarchiveObject) as? [URL] } public static func save(key: String, value: URL?, userDefaults: UserDefaults) { userDefaults.set(value, forKey: key) } public static func saveArray(key: String, value: [URL], userDefaults: UserDefaults) { if #available(OSX 10.11, *) { userDefaults.set(NSKeyedArchiver.archivedData(withRootObject: value), forKey: key) } else { // Fallback on earlier versions } } } extension Array: DefaultsSerializable where Element: DefaultsSerializable { public static func get(key: String, userDefaults: UserDefaults) -> [Element]? { return Element.getArray(key: key, userDefaults: userDefaults) } public static func getArray(key: String, userDefaults: UserDefaults) -> [[Element]]? { return [Element].getArray(key: key, userDefaults: userDefaults) } public static func save(key: String, value: [Element]?, userDefaults: UserDefaults) { guard let value = value else { userDefaults.removeObject(forKey: key) return } Element.saveArray(key: key, value: value, userDefaults: userDefaults) } public static func saveArray(key: String, value: [[Element]], userDefaults: UserDefaults) { [Element].saveArray(key: key, value: value, userDefaults: userDefaults) } } extension DefaultsStoreable where Self: Encodable { public static func saveArray(key: String, value: [Self], userDefaults: UserDefaults) { userDefaults.set(encodable: value, forKey: key) } public static func save(key: String, value: Self?, userDefaults: UserDefaults) { guard let value = value else { userDefaults.removeObject(forKey: key) return } userDefaults.set(encodable: value, forKey: key) } } extension DefaultsGettable where Self: Decodable { public static func getArray(key: String, userDefaults: UserDefaults) -> [Self]? { return userDefaults.decodable(forKey: key) as [Self]? } public static func get(key: String, userDefaults: UserDefaults) -> Self? { return userDefaults.decodable(forKey: key) as Self? } } extension DefaultsGettable where Self: NSCoding { public static func get(key: String, userDefaults: UserDefaults) -> Self? { return userDefaults.data(forKey: key).flatMap(NSKeyedUnarchiver.unarchiveObject) as? Self } public static func getArray(key: String, userDefaults: UserDefaults) -> [Self]? { return userDefaults.data(forKey: key).flatMap(NSKeyedUnarchiver.unarchiveObject) as? [Self] } } extension DefaultsStoreable where Self: NSCoding { public static func save(key: String, value: Self?, userDefaults: UserDefaults) { guard let value = value else { userDefaults.removeObject(forKey: key) return } if #available(OSX 10.11, *) { userDefaults.set(NSKeyedArchiver.archivedData(withRootObject: value), forKey: key) } else { // Fallback on earlier versions } } public static func saveArray(key: String, value: [Self], userDefaults: UserDefaults) { if #available(OSX 10.11, *) { userDefaults.set(NSKeyedArchiver.archivedData(withRootObject: value), forKey: key) } else { // Fallback on earlier versions } } } extension DefaultsGettable where Self: RawRepresentable { public static func get(key: String, userDefaults: UserDefaults) -> Self? { return userDefaults.object(forKey: key).flatMap { Self(rawValue: $0 as! Self.RawValue) } } public static func getArray(key: String, userDefaults: UserDefaults) -> [Self]? { return userDefaults.array(forKey: key)?.compactMap { Self(rawValue: $0 as! Self.RawValue) } } } extension DefaultsStoreable where Self: RawRepresentable { public static func save(key: String, value: Self?, userDefaults: UserDefaults) { guard let value = value?.rawValue else { userDefaults.removeObject(forKey: key) return } userDefaults.set(value, forKey: key) } public static func saveArray(key: String, value: [Self], userDefaults: UserDefaults) { let raw = value.map { $0.rawValue } userDefaults.set(raw, forKey: key) } }
mit
13ac30d4e382df8de8b1599d77880f42
35.074576
99
0.68521
4.505504
false
false
false
false
PureSwift/Bluetooth
Sources/BluetoothHCI/HCILEReadChannelMap.swift
1
3554
// // HCILEReadChannelMapReturnParameter.swift // Bluetooth // // Created by Alsey Coleman Miller on 6/13/18. // Copyright © 2018 PureSwift. All rights reserved. // import Foundation // MARK: - Method public extension BluetoothHostControllerInterface { /// LE Read Channel Map Command /// /// Returns the current Channel_Map for the specified Connection_Handle. The returned value indicates the state /// of the Channel_Map specified by the last transmitted or received Channel_Map (in a CONNECT_IND or LL_CHANNEL_MAP_IND message) /// for the specified Connection_Handle, regardless of whether the Master has received an acknowledgment. func lowEnergyReadChannelMap(handle: UInt16, timeout: HCICommandTimeout = .default) async throws -> LowEnergyChannelMap { let parameters = HCILEReadChannelMap(connectionHandle: handle) let returnParameters = try await deviceRequest(parameters, HCILEReadChannelMap.ReturnParameter.self, timeout: timeout) return returnParameters.channelMap } } // MARK: - Command /// LE Read Channel Map Command /// /// The command returns the current Channel_Map for the specified Connection_Handle. The returned value indicates the state /// of the Channel_Map specified by the last transmitted or received Channel_Map (in a CONNECT_IND or LL_CHANNEL_MAP_IND message) /// for the specified Connection_Handle, regardless of whether the Master has received an acknowledgment. @frozen public struct HCILEReadChannelMap: HCICommandParameter { // HCI_LE_Read_Channel_Map public static let command = HCILowEnergyCommand.readChannelMap //0x0015 public var connectionHandle: UInt16 //Connection_Handle public init(connectionHandle: UInt16) { self.connectionHandle = connectionHandle } public var data: Data { let connectionHandleBytes = connectionHandle.littleEndian.bytes return Data([ connectionHandleBytes.0, connectionHandleBytes.1 ]) } } // MARK: - Return Parameter public extension HCILEReadChannelMap { typealias ReturnParameter = HCILEReadChannelMapReturnParameter } /// LE Read Channel Map Command /// /// The command returns the current Channel_Map for the specified Connection_Handle. The returned value indicates the state /// of the Channel_Map specified by the last transmitted or received Channel_Map (in a CONNECT_IND or LL_CHANNEL_MAP_IND message) /// for the specified Connection_Handle, regardless of whether the Master has received an acknowledgment. @frozen public struct HCILEReadChannelMapReturnParameter: HCICommandReturnParameter { public static let command = HCILowEnergyCommand.readChannelMap //0x0015 public static let length: Int = 7 public let connectionHandle: UInt16 // Connection_Handle /// This parameter contains 37 1-bit fields. /// The Nth such field (in the range 0 to 36) contains the value for the link layer channel index n. /// Channel n is unused = 0. /// Channel n is used = 1. /// The most significant bits are reserved for future use. public let channelMap: LowEnergyChannelMap // Channel_Map public init?(data: Data) { guard data.count == type(of: self).length else { return nil } self.connectionHandle = UInt16(littleEndian: UInt16(bytes: (data[0], data[1]))) self.channelMap = (data[2], data[3], data[4], data[5], data[6]) } }
mit
1a5186bca07ce24418ca796d6d1ce355
35.628866
133
0.705601
4.578608
false
false
false
false
bitboylabs/selluv-ios
selluv-ios/selluv-ios/Classes/Controller/UI/Tabs/Tab4Brand/SLV_411_BrandEditContoller.swift
1
10607
// // SLV_411_BrandEditContoller.swift // selluv-ios // // Created by 조백근 on 2016. 11. 8.. // Copyright © 2016년 BitBoy Labs. All rights reserved. // /* 선호브랜드 편집 컨트롤러 */ import Foundation import UIKit class SLV_411_BrandEditContoller: SLVBaseStatusShowController { var isEditMode: Bool = false // var followBrandList: [Brand] = [] var followList: [String] = [] @IBOutlet weak var tableView: UITableView! override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) tabController.animationTabBarHidden(true) tabController.hideFab() self.loadMyFollowBrand() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) self.navigationController?.isNavigationBarHidden = false self.navigationItem.hidesBackButton = true } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) UIView.cancelPreviousPerformRequests(withTarget: self) self.tableView.isEditing = false } override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) } override func viewDidLoad() { super.viewDidLoad() self.setupNavigationButtons() self.title = "브랜드 편집" self.setupTableView() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } func setupTableView() { tableView.delegate = self tableView.dataSource = self tableView.contentInset = UIEdgeInsetsMake(0, 0, 0, 0) } func setupNavigationButtons() { let back = UIButton() back.setImage(UIImage(named:"ic-back-arrow.png"), for: .normal) back.frame = CGRect(x: 17, y: 23, width: 12+32, height: 20) back.imageEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 26) back.addTarget(self, action: #selector(SLV_411_BrandEditContoller.back(sender:)), for: .touchUpInside) let item = UIBarButtonItem(customView: back) self.navigationItem.leftBarButtonItem = item let edit = UIButton() edit.setTitle("편집", for: .normal) edit.setTitle("완료", for: .selected) edit.titleLabel?.font = UIFont.systemFont(ofSize: 13, weight: UIFontWeightRegular) edit.contentHorizontalAlignment = .right edit.setTitleColor(text_color_blue, for: .normal) edit.frame = CGRect(x: self.view.bounds.width - 44/* - 17*/, y: 32, width: 12+32, height: 20) edit.titleEdgeInsets = UIEdgeInsets(top: 4, left: -10, bottom: 4, right: 4) edit.addTarget(self, action: #selector(SLV_411_BrandEditContoller.edit(sender:)), for: .touchUpInside) let item2 = UIBarButtonItem(customView: edit) self.navigationItem.rightBarButtonItem = item2 } //MARK: EVENT // func dismiss(callBack: AnyObject? = nil) { // modalDelegate?.modalViewControllerDismiss(callbackData: callBack) // } func back(sender: UIBarButtonItem?) { _ = self.navigationController?.tr_popViewController() } func edit(sender: Any) { let button = sender as! UIButton if self.isEditMode == false { self.isEditMode = true self.tableView.isEditing = true button.isSelected = true } else { self.isEditMode = false self.tableView.isEditing = false button.isSelected = false self.resetMyFollowBrand() } } // func moveFollowBrandAdd() { let board = UIStoryboard(name:"Brand", bundle: nil) let controller = board.instantiateViewController(withIdentifier: "SLV_412_BrandAddController") as! SLV_412_BrandAddController self.navigationController?.tr_pushViewController(controller, method: TRPushTransitionMethod.fade, statusBarStyle: .default) { } } // func loadMyFollowBrand() { BrandTabModel.shared.followBrands { (success, list) in if success == true { if list != nil { // self.followBrandList = list! var brandIdList: [String] = [] _ = list!.map() { let item = $0 brandIdList.append(item.id) } self.followList = brandIdList self.tableView.reloadData() } } } } func resetMyFollowBrand() { BrandTabModel.shared.sortingFollowBrands(brands: self.followList) { (success) in } } } extension SLV_411_BrandEditContoller: UITableViewDelegate { func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath as IndexPath, animated: false) } func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? { let deleteAction = UITableViewRowAction(style: .default, title: "Delete", handler: { (action , indexPath) -> Void in let index = indexPath.row self.followList.remove(at: index) self.delay(time: 0.2) { self.tableView.reloadData() } }) deleteAction.backgroundColor = UIColor.red return [deleteAction] } func tableView(_ tableView: UITableView, accessoryButtonTappedForRowWith indexPath: IndexPath) { } // // Allows customization of the editingStyle for a particular cell located at 'indexPath'. If not implemented, all editable cells will have UITableViewCellEditingStyleDelete set for them when the table has editing property set to YES. // @available(iOS 2.0, *) // optional public func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCellEditingStyle // // @available(iOS 3.0, *) // optional public func tableView(_ tableView: UITableView, titleForDeleteConfirmationButtonForRowAt indexPath: IndexPath) -> String? // // @available(iOS 8.0, *) // optional public func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? // supercedes -tableView:titleForDeleteConfirmationButtonForRowAtIndexPath: if return value is non-nil // } extension SLV_411_BrandEditContoller: UITableViewDataSource { func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let w = UIScreen.main.bounds.width let view = UIView() view.frame = CGRect(x:0, y:0, width: w, height: 51) view.backgroundColor = bg_color_g245 let button = UIButton(type: .custom) button.frame = CGRect(x: 17, y: 10, width: w - 34, height: 32 ) button.setTitle("브랜드 추가", for: .normal) button.setTitleColor(text_color_bl51, for: .normal) button.titleLabel?.font = UIFont.systemFont(ofSize: 12, weight: UIFontWeightRegular) button.setImage(UIImage(named:"brand-add.png"), for: .normal) button.backgroundColor = UIColor.white button.borderColor = bg_color_gline button.borderWidth = 1 button.cornerRadius = 5 button.imageEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 15) button.addTarget(self, action: #selector(SLV_411_BrandEditContoller.moveFollowBrandAdd), for: .touchUpInside) view.addSubview(button) return view } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.followList.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "SLVBrandListCell", for: indexPath) as! SLVBrandListCell cell.brandLabel.textColor = UIColor.gray var cellBrand: Brand? let brandId = self.followList[indexPath.row] cellBrand = BrandModel.shared.detect(brandId) if let brand = cellBrand { let en = brand.english let ko = brand.korean let enLen = en.distance(from: en.startIndex, to: en.endIndex) let koLen = ko.distance(from: ko.startIndex, to: ko.endIndex) let enFirst = "\(en) \(ko)" let koFirst = "\(ko) \(en)" if BrandModel.shared.isEnName == true { let myMutableString = NSMutableAttributedString(string: enFirst, attributes: [ NSFontAttributeName:UIFont.systemFont(ofSize: 13), NSForegroundColorAttributeName: text_color_g153] ) myMutableString.addAttribute(NSFontAttributeName, value: UIFont.systemFont(ofSize: 15), range: NSRange(location:0,length:enLen)) myMutableString.addAttribute(NSForegroundColorAttributeName, value: text_color_bl51, range: NSRange(location:0,length:enLen)) cell.brandLabel.attributedText = myMutableString } else { let myMutableString = NSMutableAttributedString(string: koFirst, attributes: [ NSFontAttributeName:UIFont.systemFont(ofSize: 13), NSForegroundColorAttributeName: text_color_g153] ) myMutableString.addAttribute(NSFontAttributeName, value: UIFont.systemFont(ofSize: 15), range: NSRange(location:0,length:koLen)) myMutableString.addAttribute(NSForegroundColorAttributeName, value: text_color_bl51, range: NSRange(location:0,length:koLen)) cell.brandLabel.attributedText = myMutableString } } cell.layoutMargins = UIEdgeInsets.zero return cell } public func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) { let from = sourceIndexPath.row let to = destinationIndexPath.row if from > to { let value = self.followList[from] self.followList.remove(at: from) self.followList.insert(value, at: to) } else { let value = self.followList[from] self.followList.insert(value, at: to + 1) self.followList.remove(at: from) } self.delay(time: 0.2) { self.tableView.reloadData() } } }
mit
fba8d93944ca9588274377a9976fad48
39.569231
243
0.630356
4.692171
false
false
false
false
chronotruck/CTKFlagPhoneNumber
Sources/FPNCountryPicker/FPNCountryPicker.swift
1
1843
import UIKit open class FPNCountryPicker: UIPickerView, UIPickerViewDelegate, UIPickerViewDataSource { open var repository: FPNCountryRepository? open var showPhoneNumbers: Bool open var didSelect: ((FPNCountry) -> Void)? public init(showPhoneNumbers: Bool = true) { self.showPhoneNumbers = showPhoneNumbers super.init(frame: .zero) dataSource = self delegate = self } required public init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } open func setup(repository: FPNCountryRepository) { self.repository = repository reloadAllComponents() } // MARK: - FPNCountry Methods open func setCountry(_ code: FPNCountryCode) { guard let countries = repository?.countries else { return } for (index, country) in countries.enumerated() { if country.code == code { selectRow(index, inComponent: 0, animated: true) didSelect?(country) } } } // MARK: - Picker Methods open func numberOfComponents(in pickerView: UIPickerView) -> Int { return 1 } open func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { return repository?.countries.count ?? 0 } open func pickerView(_ pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusing view: UIView?) -> UIView { var resultView: FPNCountryView let country = repository!.countries[row] if view == nil { resultView = FPNCountryView() } else { resultView = view as! FPNCountryView } resultView.setup(country) if !showPhoneNumbers { resultView.countryCodeLabel.isHidden = true } return resultView } open func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { guard let countries = repository?.countries else { return } let country = countries[row] didSelect?(country) } }
apache-2.0
3a80b10b1c9dc7b3f2bab9a6c34de8be
23.25
134
0.72599
3.871849
false
false
false
false
dangnguyenhuu/JSQMessagesSwift
Sources/Views/JSQActionSelectView.swift
1
4426
// // JSQActionSelectView.swift // JSQMessagesSwift // // Created by NGUYEN HUU DANG on 2017/03/20. // // import UIKit public protocol JSQActionSelectViewDelegate { func didSelectView( atIndex index: Int) } open class JSQActionSelectView: UIView { @IBOutlet var collectionView: UICollectionView! var delegate: JSQActionSelectViewDelegate? internal var sourse : [(image: UIImage, title: String)]! internal var columns: CGFloat = 3.0 internal var insert: CGFloat = 0 internal var spacing: CGFloat = 0 internal var lineSpacing: CGFloat = 0 public override init(frame: CGRect) { super.init(frame: frame) self.setup() self.setupCollectionView() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.setup() self.setupCollectionView() } // MARK: - Private private func setup() { let bundle = Bundle(for: type(of: self)) let nib = UINib(nibName: "JSQActionSelectView", bundle: bundle) if let view = nib.instantiate(withOwner: self, options: nil).first as? UIView { addSubview(view) view.translatesAutoresizingMaskIntoConstraints = false let bindings = ["view": view] addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|[view]|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: bindings)) addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[view]|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: bindings)) } } private func setupCollectionView() { self.collectionView.register( UINib(nibName: "JSQActionViewCell", bundle: Bundle.jsq_messagesBundle()), forCellWithReuseIdentifier: "JSQActionViewCell") self.collectionView.delegate = self self.collectionView.dataSource = self } } extension JSQActionSelectView: UICollectionViewDataSource { public func numberOfSections(in collectionView: UICollectionView) -> Int { return 1 } public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return self.sourse.count } public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "JSQActionViewCell", for: indexPath) as! JSQActionViewCell cell.image.image = self.sourse[indexPath.row].image cell.title.text = self.sourse[indexPath.row].title return cell } } extension JSQActionSelectView: UICollectionViewDelegateFlowLayout { public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { let with = (collectionView.frame.width / columns) - (insert + spacing) return CGSize(width: with, height: with - 20) } public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets { return UIEdgeInsets(top: insert, left: insert, bottom: insert, right: insert) } public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat { return lineSpacing } public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat { return spacing } } extension JSQActionSelectView: UICollectionViewDelegate { public func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { self.delegate?.didSelectView(atIndex: indexPath.row) } }
apache-2.0
4c6d59836a05b7e6180461a227d1977e
36.508475
182
0.641437
5.763021
false
false
false
false
InLefter/Wea
Wea/SearchCityViewController.swift
1
6891
// // SearchCityViewController.swift // Wea // // Created by Howie on 16/3/17. // Copyright © 2016年 Howie. All rights reserved. // import UIKit @objc protocol SearchCityViewControllerDelegate{ func cityDidSearched(cityKey: String) } class SearchCityViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UISearchResultsUpdating, UISearchBarDelegate, CustomSearchControllerDelegate,UIScrollViewDelegate { @IBOutlet weak var background: UIImageView! @IBOutlet weak var tableView: UITableView! @IBOutlet weak var delegate:SearchCityViewControllerDelegate? var selectedIndex: Int? var searchData = [String]() //搜索结果 var filteredArray = [String]() var shouldShowSearchResults = true var searchController:UISearchController! var customSearchController: CustomSearchController! //var shouldShowSearchResults = false override func preferredStatusBarStyle() -> UIStatusBarStyle { return UIStatusBarStyle.LightContent; } override func viewDidLoad() { super.viewDidLoad() loadListOfCountries() // Do any additional setup after loading the view. configureCustomSearchController() self.tableView.backgroundView?.backgroundColor = UIColor.clearColor() self.tableView.backgroundColor = UIColor.clearColor() self.tableView.separatorColor = UIColor.clearColor() customSearchController.searchBarTextDidBeginEditing(customSearchController.customSearchBar) } func scrollViewDidScroll(scrollView: UIScrollView) { customSearchController.customSearchBar.resignFirstResponder() } func loadListOfCountries() { // Specify the path to the countries list file. let pathToFile = NSBundle.mainBundle().pathForResource("cities", ofType: "txt") if let path = pathToFile { // Load the file contents as a string. let countriesString = try? String(contentsOfFile: path, encoding: NSUTF8StringEncoding) // Append the countries from the string to the dataArray array by breaking them using the line change character. searchData = countriesString!.componentsSeparatedByString("\n") } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func configureCustomSearchController() { customSearchController = CustomSearchController(searchResultsController: self, searchBarFrame: CGRectMake(0.0, 20.0, tableView.frame.size.width, 50.0), searchBarFont: UIFont(name: "Futura", size: 16.0)!, searchBarTextColor: UIColor.lightGrayColor(), searchBarTintColor: UIColor.blackColor()) customSearchController.customSearchBar.placeholder = "搜索城市..." self.view.addSubview(customSearchController.customSearchBar) customSearchController.customDelegate = self } func filterContentForSearchText(searchText: String) { } func updateSearchResultsForSearchController(searchController: UISearchController) { guard let searchText = searchController.searchBar.text else { return } filteredArray = searchData.filter({ ( cities: String) -> Bool in /*let nameMatch = cities.rangeOfString(searchText, options: NSStringCompareOptions.CaseInsensitiveSearch) let locationMatch = cities.rangeOfString(searchText, options: NSStringCompareOptions.CaseInsensitiveSearch)*/ return cities.hasPrefix("\(searchText)") }) tableView.reloadData() } /*func didStartSearching() { shouldShowSearchResults = true tableView.reloadData() }*/ func didTapOnSearchButton() { shouldShowSearchResults = true tableView.reloadData() } func didTapOnCancelButton() { //print("Cancled") self.dismissViewControllerAnimated(true, completion: nil) } func didChangeSearchText(searchText: String) { // Filter the data array and get only those countries that match the search text. filteredArray = searchData.filter({ (city) -> Bool in let cityText: NSString = city return (cityText.rangeOfString(searchText, options: NSStringCompareOptions.CaseInsensitiveSearch).location) != NSNotFound }) // Reload the tableview. tableView.reloadData() } //指定UITableView中有多少个section的,section分区,一个section里会包含多个Cell func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } //每一个section里面有多少个Cell func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { //print(cityMessage.count) if shouldShowSearchResults { return filteredArray.count } else { return searchData.count } } //初始化每一个Cell func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("city" , forIndexPath: indexPath) as! SearchCityTableViewCell cell.backgroundColor = UIColor.clearColor() cell.selectionStyle = UITableViewCellSelectionStyle.None if searchData.count != 0 { if shouldShowSearchResults { cell.cityName.text = filteredArray[indexPath.row] } else { //cell.cityName.text = searchResults[indexPath.row] } } return cell } //选中一个Cell后执行的方法 func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { //print("did select row \(indexPath.row)") // set current selected index of city list self.selectedIndex = indexPath.row if self.selectedIndex != nil && self.delegate != nil { let cityKey = Array(self.filteredArray)[self.selectedIndex!] self.delegate?.cityDidSearched(cityKey) } tableView.deselectRowAtIndexPath(indexPath, animated: true) self.dismissViewControllerAnimated(true, completion: nil) } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
mit
54cfbb60733fb0677507f08e2d7dffbf
34.322917
299
0.66647
5.728041
false
false
false
false
kamawshuang/iOS---Animation
3D(七)/3DSlideMenu/3DSlideMenu/MenuItem.swift
4
1935
// // MenuItem.swift // 3DSlideMenu // // Created by 51Testing on 15/12/9. // Copyright © 2015年 HHW. All rights reserved. // import UIKit let menuColors = [ UIColor(red: 249/255, green: 84/255, blue: 7/255, alpha: 1.0), UIColor(red: 69/255, green: 59/255, blue: 55/255, alpha: 1.0), UIColor(red: 249/255, green: 194/255, blue: 7/255, alpha: 1.0), UIColor(red: 32/255, green: 188/255, blue: 32/255, alpha: 1.0), UIColor(red: 207/255, green: 34/255, blue: 156/255, alpha: 1.0), UIColor(red: 14/255, green: 88/255, blue: 149/255, alpha: 1.0), UIColor(red: 15/255, green: 193/255, blue: 231/255, alpha: 1.0) ] class MenuItem { let title: String let symbol: String let color: UIColor //初始化model init(symbol: String, color: UIColor, title: String) { self.title = title self.symbol = symbol self.color = color } //单例 class var sharedItems: [MenuItem] { struct Static { static let items = MenuItem.sharedMenuItems() } return Static.items } class func sharedMenuItems() -> [MenuItem] { var items = [MenuItem]() items.append(MenuItem(symbol: "☎︎", color: menuColors[0], title: "Phone book")) items.append(MenuItem(symbol: "✉︎", color: menuColors[1], title: "Email directory")) items.append(MenuItem(symbol: "♻︎", color: menuColors[2], title: "Company recycle policy")) items.append(MenuItem(symbol: "♞", color: menuColors[3], title: "Games and fun")) items.append(MenuItem(symbol: "✾", color: menuColors[4], title: "Training programs")) items.append(MenuItem(symbol: "✈︎", color: menuColors[5], title: "Travel")) items.append(MenuItem(symbol: "🃖", color: menuColors[6], title: "Etc.")) return items } }
apache-2.0
12a8664bdecc94b7cacd22e5f8908d96
27.772727
99
0.581359
3.379004
false
false
false
false
wenluma/swift
test/SILGen/accessors.swift
5
10815
// RUN: %target-swift-frontend -Xllvm -sil-full-demangle -emit-silgen %s | %FileCheck %s // Hold a reference to do to magically become non-POD. class Reference {} // A struct with a non-mutating getter and a mutating setter. struct OrdinarySub { var ptr = Reference() subscript(value: Int) -> Int { get { return value } set {} } } class A { var array = OrdinarySub() } func index0() -> Int { return 0 } func index1() -> Int { return 1 } func someValidPointer<T>() -> UnsafePointer<T> { fatalError() } func someValidPointer<T>() -> UnsafeMutablePointer<T> { fatalError() } // Verify that there is no unnecessary extra copy_value of ref.array. // rdar://19002913 func test0(_ ref: A) { ref.array[index0()] = ref.array[index1()] } // CHECK: sil hidden @_T09accessors5test0yAA1ACF : $@convention(thin) (@owned A) -> () { // CHECK: bb0([[ARG:%.*]] : $A): // CHECK-NEXT: debug_value // Formal evaluation of LHS. // CHECK-NEXT: [[BORROWED_ARG_LHS:%.*]] = begin_borrow [[ARG]] // CHECK-NEXT: // function_ref accessors.index0() -> Swift.Int // CHECK-NEXT: [[T0:%.*]] = function_ref @_T09accessors6index0SiyF // CHECK-NEXT: [[INDEX0:%.*]] = apply [[T0]]() // Formal evaluation of RHS. // CHECK-NEXT: [[BORROWED_ARG_RHS:%.*]] = begin_borrow [[ARG]] // CHECK-NEXT: // function_ref accessors.index1() -> Swift.Int // CHECK-NEXT: [[T0:%.*]] = function_ref @_T09accessors6index1SiyF // CHECK-NEXT: [[INDEX1:%.*]] = apply [[T0]]() // Formal access to RHS. // CHECK-NEXT: [[TEMP:%.*]] = alloc_stack $OrdinarySub // CHECK-NEXT: [[T0:%.*]] = class_method [[BORROWED_ARG_RHS]] : $A, #A.array!getter.1 // CHECK-NEXT: [[T1:%.*]] = apply [[T0]]([[BORROWED_ARG_RHS]]) // CHECK-NEXT: store [[T1]] to [init] [[TEMP]] // CHECK-NEXT: [[T0:%.*]] = load_borrow [[TEMP]] // CHECK-NEXT: // function_ref accessors.OrdinarySub.subscript.getter : (Swift.Int) -> Swift.Int // CHECK-NEXT: [[T1:%.*]] = function_ref @_T09accessors11OrdinarySubV9subscriptS2icfg // CHECK-NEXT: [[VALUE:%.*]] = apply [[T1]]([[INDEX1]], [[T0]]) // CHECK-NEXT: end_borrow [[T0]] from [[TEMP]] // CHECK-NEXT: destroy_addr [[TEMP]] // Formal access to LHS. // CHECK-NEXT: // function_ref accessors.OrdinarySub.subscript.setter : (Swift.Int) -> Swift.Int // CHECK-NEXT: [[SETTER:%.*]] = function_ref @_T09accessors11OrdinarySubV9subscriptS2icfs // CHECK-NEXT: [[STORAGE:%.*]] = alloc_stack $Builtin.UnsafeValueBuffer // CHECK-NEXT: [[BUFFER:%.*]] = alloc_stack $OrdinarySub // CHECK-NEXT: [[T0:%.*]] = address_to_pointer [[BUFFER]] // CHECK-NEXT: [[T1:%.*]] = class_method [[BORROWED_ARG_LHS]] : $A, #A.array!materializeForSet.1 // CHECK-NEXT: [[T2:%.*]] = apply [[T1]]([[T0]], [[STORAGE]], [[BORROWED_ARG_LHS]]) // CHECK-NEXT: [[T3:%.*]] = tuple_extract [[T2]] {{.*}}, 0 // CHECK-NEXT: [[OPT_CALLBACK:%.*]] = tuple_extract [[T2]] {{.*}}, 1 // CHECK-NEXT: [[T4:%.*]] = pointer_to_address [[T3]] // CHECK-NEXT: [[ADDR:%.*]] = mark_dependence [[T4]] : $*OrdinarySub on [[BORROWED_ARG_LHS]] : $A // CHECK-NEXT: apply [[SETTER]]([[VALUE]], [[INDEX0]], [[ADDR]]) // CHECK-NEXT: switch_enum [[OPT_CALLBACK]] : $Optional<Builtin.RawPointer>, case #Optional.some!enumelt.1: [[WRITEBACK:bb[0-9]+]], case #Optional.none!enumelt: [[CONT:bb[0-9]+]] // CHECK: [[WRITEBACK]]([[CALLBACK_ADDR:%.*]] : $Builtin.RawPointer): // CHECK-NEXT: [[CALLBACK:%.*]] = pointer_to_thin_function [[CALLBACK_ADDR]] : $Builtin.RawPointer to $@convention(method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout A, @thick A.Type) -> () // CHECK-NEXT: [[TEMP2:%.*]] = alloc_stack $A // SEMANTIC SIL TODO: This is an issue caused by the callback for materializeForSet in the class case taking the value as @inout when it should really take it as @guaranteed. // CHECK-NEXT: store_borrow [[BORROWED_ARG_LHS]] to [[TEMP2]] : $*A // CHECK-NEXT: [[T0:%.*]] = metatype $@thick A.Type // CHECK-NEXT: [[T1:%.*]] = address_to_pointer [[ADDR]] : $*OrdinarySub to $Builtin.RawPointer // CHECK-NEXT: apply [[CALLBACK]]([[T1]], [[STORAGE]], [[TEMP2]], [[T0]]) // CHECK-NEXT: dealloc_stack [[TEMP2]] // CHECK-NEXT: br [[CONT]] // CHECK: [[CONT]]: // CHECK-NEXT: dealloc_stack [[BUFFER]] // CHECK-NEXT: dealloc_stack [[STORAGE]] // CHECK-NEXT: dealloc_stack [[TEMP]] // CHECK-NEXT: end_borrow [[BORROWED_ARG_RHS]] from [[ARG]] // CHECK-NEXT: end_borrow [[BORROWED_ARG_LHS]] from [[ARG]] // Balance out the +1 from the function parameter. // CHECK-NEXT: destroy_value [[ARG]] // CHECK-NEXT: tuple () // CHECK-NEXT: return // A struct with a mutating getter and a mutating setter. struct MutatingSub { var ptr = Reference() subscript(value: Int) -> Int { mutating get { return value } set {} } } class B { var array = MutatingSub() } func test1(_ ref: B) { ref.array[index0()] = ref.array[index1()] } // CHECK-LABEL: sil hidden @_T09accessors5test1yAA1BCF : $@convention(thin) (@owned B) -> () { // CHECK: bb0([[ARG:%.*]] : $B): // CHECK-NEXT: debug_value // Formal evaluation of LHS. // CHECK-NEXT: [[BORROWED_ARG_LHS:%.*]] = begin_borrow [[ARG]] // CHECK-NEXT: // function_ref accessors.index0() -> Swift.Int // CHECK-NEXT: [[T0:%.*]] = function_ref @_T09accessors6index0SiyF // CHECK-NEXT: [[INDEX0:%.*]] = apply [[T0]]() // Formal evaluation of RHS. // CHECK-NEXT: [[BORROWED_ARG_RHS:%.*]] = begin_borrow [[ARG]] // CHECK-NEXT: // function_ref accessors.index1() -> Swift.Int // CHECK-NEXT: [[T0:%.*]] = function_ref @_T09accessors6index1SiyF // CHECK-NEXT: [[INDEX1:%.*]] = apply [[T0]]() // Formal access to RHS. // CHECK-NEXT: [[STORAGE:%.*]] = alloc_stack $Builtin.UnsafeValueBuffer // CHECK-NEXT: [[BUFFER:%.*]] = alloc_stack $MutatingSub // CHECK-NEXT: [[T0:%.*]] = address_to_pointer [[BUFFER]] // CHECK-NEXT: [[T1:%.*]] = class_method [[BORROWED_ARG_RHS]] : $B, #B.array!materializeForSet.1 // CHECK-NEXT: [[T2:%.*]] = apply [[T1]]([[T0]], [[STORAGE]], [[BORROWED_ARG_RHS]]) // CHECK-NEXT: [[T3:%.*]] = tuple_extract [[T2]] {{.*}}, 0 // CHECK-NEXT: [[OPT_CALLBACK:%.*]] = tuple_extract [[T2]] {{.*}}, 1 // CHECK-NEXT: [[T4:%.*]] = pointer_to_address [[T3]] // CHECK-NEXT: [[ADDR:%.*]] = mark_dependence [[T4]] : $*MutatingSub on [[BORROWED_ARG_RHS]] : $B // CHECK-NEXT: // function_ref accessors.MutatingSub.subscript.getter : (Swift.Int) -> Swift.Int // CHECK-NEXT: [[T0:%.*]] = function_ref @_T09accessors11MutatingSubV9subscriptS2icfg : $@convention(method) (Int, @inout MutatingSub) -> Int // CHECK-NEXT: [[VALUE:%.*]] = apply [[T0]]([[INDEX1]], [[ADDR]]) // CHECK-NEXT: switch_enum [[OPT_CALLBACK]] : $Optional<Builtin.RawPointer>, case #Optional.some!enumelt.1: [[WRITEBACK:bb[0-9]+]], case #Optional.none!enumelt: [[CONT:bb[0-9]+]] // // CHECK: [[WRITEBACK]]([[CALLBACK_ADDR:%.*]] : $Builtin.RawPointer): // CHECK-NEXT: [[CALLBACK:%.*]] = pointer_to_thin_function [[CALLBACK_ADDR]] : $Builtin.RawPointer to $@convention(method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout B, @thick B.Type) -> () // CHECK-NEXT: [[TEMP2:%.*]] = alloc_stack $B // CHECK-NEXT: store_borrow [[BORROWED_ARG_RHS]] to [[TEMP2]] : $*B // CHECK-NEXT: [[T0:%.*]] = metatype $@thick B.Type // CHECK-NEXT: [[T1:%.*]] = address_to_pointer [[ADDR]] : $*MutatingSub to $Builtin.RawPointer // CHECK-NEXT: apply [[CALLBACK]]([[T1]], [[STORAGE]], [[TEMP2]], [[T0]]) // CHECK-NEXT: dealloc_stack [[TEMP2]] // CHECK-NEXT: br [[CONT]] // // CHECK: [[CONT]]: // Formal access to LHS. // CHECK-NEXT: // function_ref accessors.MutatingSub.subscript.setter : (Swift.Int) -> Swift.Int // CHECK-NEXT: [[SETTER:%.*]] = function_ref @_T09accessors11MutatingSubV9subscriptS2icfs : $@convention(method) (Int, Int, @inout MutatingSub) -> () // CHECK-NEXT: [[STORAGE2:%.*]] = alloc_stack $Builtin.UnsafeValueBuffer // CHECK-NEXT: [[BUFFER2:%.*]] = alloc_stack $MutatingSub // CHECK-NEXT: [[T0:%.*]] = address_to_pointer [[BUFFER2]] // CHECK-NEXT: [[T1:%.*]] = class_method [[BORROWED_ARG_LHS]] : $B, #B.array!materializeForSet.1 // CHECK-NEXT: [[T2:%.*]] = apply [[T1]]([[T0]], [[STORAGE2]], [[BORROWED_ARG_LHS]]) // CHECK-NEXT: [[T3:%.*]] = tuple_extract [[T2]] {{.*}}, 0 // CHECK-NEXT: [[OPT_CALLBACK:%.*]] = tuple_extract [[T2]] {{.*}}, 1 // CHECK-NEXT: [[T4:%.*]] = pointer_to_address [[T3]] // CHECK-NEXT: [[ADDR:%.*]] = mark_dependence [[T4]] : $*MutatingSub on [[BORROWED_ARG_LHS]] : $B // CHECK-NEXT: apply [[SETTER]]([[VALUE]], [[INDEX0]], [[ADDR]]) // CHECK-NEXT: switch_enum [[OPT_CALLBACK]] : $Optional<Builtin.RawPointer>, case #Optional.some!enumelt.1: [[WRITEBACK:bb[0-9]+]], case #Optional.none!enumelt: [[CONT:bb[0-9]+]] // // CHECK: [[WRITEBACK]]([[CALLBACK_ADDR:%.*]] : $Builtin.RawPointer): // CHECK-NEXT: [[CALLBACK:%.*]] = pointer_to_thin_function [[CALLBACK_ADDR]] : $Builtin.RawPointer to $@convention(method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout B, @thick B.Type) -> () // CHECK-NEXT: [[TEMP2:%.*]] = alloc_stack $B // CHECK-NEXT: store_borrow [[BORROWED_ARG_LHS]] to [[TEMP2]] : $*B // CHECK-NEXT: [[T0:%.*]] = metatype $@thick B.Type // CHECK-NEXT: [[T1:%.*]] = address_to_pointer [[ADDR]] : $*MutatingSub to $Builtin.RawPointer // CHECK-NEXT: apply [[CALLBACK]]([[T1]], [[STORAGE2]], [[TEMP2]], [[T0]]) // CHECK-NEXT: dealloc_stack [[TEMP2]] // CHECK-NEXT: br [[CONT]] // // CHECK: [[CONT]]: // CHECK-NEXT: dealloc_stack [[BUFFER2]] // CHECK-NEXT: dealloc_stack [[STORAGE2]] // CHECK-NEXT: dealloc_stack [[BUFFER]] // CHECK-NEXT: dealloc_stack [[STORAGE]] // CHECK: end_borrow [[BORROWED_ARG_RHS]] from [[ARG]] // CHECK: end_borrow [[BORROWED_ARG_LHS]] from [[ARG]] // Balance out the +1 from the function parameter. // CHECK-NEXT: destroy_value [[ARG]] // CHECK-NEXT: tuple () // CHECK-NEXT: return struct RecInner { subscript(i: Int) -> Int { get { return i } } } struct RecOuter { var inner : RecInner { unsafeAddress { return someValidPointer() } unsafeMutableAddress { return someValidPointer() } } } func test_rec(_ outer: inout RecOuter) -> Int { return outer.inner[0] } // This uses the immutable addressor. // CHECK: sil hidden @_T09accessors8test_recSiAA8RecOuterVzF : $@convention(thin) (@inout RecOuter) -> Int { // CHECK: function_ref @_T09accessors8RecOuterV5innerAA0B5InnerVflu : $@convention(method) (RecOuter) -> UnsafePointer<RecInner> struct Rec2Inner { subscript(i: Int) -> Int { mutating get { return i } } } struct Rec2Outer { var inner : Rec2Inner { unsafeAddress { return someValidPointer() } unsafeMutableAddress { return someValidPointer() } } } func test_rec2(_ outer: inout Rec2Outer) -> Int { return outer.inner[0] } // This uses the mutable addressor. // CHECK: sil hidden @_T09accessors9test_rec2SiAA9Rec2OuterVzF : $@convention(thin) (@inout Rec2Outer) -> Int { // CHECK: function_ref @_T09accessors9Rec2OuterV5innerAA0B5InnerVfau : $@convention(method) (@inout Rec2Outer) -> UnsafeMutablePointer<Rec2Inner>
mit
6ca6c191480506a5292513fa212a1739
50.014151
208
0.635784
3.243851
false
false
false
false
iCrany/iOSExample
iOSExample/Module/UIBenchMarkExample/UIBenchMarkExampleTableViewController.swift
1
3984
// // UIBenchMarkExampleTableViewController.swift // iOSExample // // Created by iCrany on 2017/10/25. // Copyright © 2017 iCrany. All rights reserved. // import Foundation import UIKit class UIBenchMarkExampleTableViewController: UIViewController { struct Constant { static let kFrameBenchMarkExample = "UIView param bench mark"//UIView param 性能测试 static let kDemo2: String = "Normal corner radius bench mark" //通常的圆角的性能测试 static let kDemo3: String = "CAShaper corner radius bench mark" //优化的圆角性能测试 static let kDemo4: String = "Graphics corner radius bench mark" //Graphics优化圆角的性能 } private lazy var tableView: UITableView = { let tableView = UITableView.init(frame: .zero, style: .plain) tableView.tableFooterView = UIView.init() tableView.delegate = self tableView.dataSource = self return tableView }() fileprivate var dataSource: [String] = [] init() { super.init(nibName: nil, bundle: nil) self.prepareDataSource() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() self.title = "UIView Bench Mark Example" self.setupUI() } private func setupUI() { self.view.addSubview(self.tableView) self.tableView.snp.makeConstraints { maker in maker.edges.equalTo(self.view) } self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: NSStringFromClass(UITableViewCell.self)) } private func prepareDataSource() { self.dataSource.append(Constant.kFrameBenchMarkExample) self.dataSource.append(Constant.kDemo2) self.dataSource.append(Constant.kDemo3) self.dataSource.append(Constant.kDemo4) } } extension UIBenchMarkExampleTableViewController: UITableViewDelegate { public func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 60 } public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let selectedDataSourceStr = self.dataSource[indexPath.row] switch selectedDataSourceStr { case Constant.kFrameBenchMarkExample: let vc: UIBenchMarkViewController = UIBenchMarkViewController.init() self.navigationController?.pushViewController(vc, animated: true) case Constant.kDemo2: let vc: UICornerRadiusBenchMarkVC = UICornerRadiusBenchMarkVC() self.navigationController?.pushViewController(vc, animated: true) case Constant.kDemo3: let vc: UICornerRadiusBenchMarkVC = UICornerRadiusBenchMarkVC(cornerRadiusType: .shapeLayer) self.navigationController?.pushViewController(vc, animated: true) case Constant.kDemo4: let vc: UICornerRadiusBenchMarkVC = UICornerRadiusBenchMarkVC(cornerRadiusType: .cg) self.navigationController?.pushViewController(vc, animated: true) default: break } } } extension UIBenchMarkExampleTableViewController: UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.dataSource.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let dataSourceStr: String = self.dataSource[indexPath.row] let tableViewCell: UITableViewCell? = tableView.dequeueReusableCell(withIdentifier: NSStringFromClass(UITableViewCell.self)) if let cell = tableViewCell { cell.textLabel?.text = dataSourceStr cell.textLabel?.textColor = UIColor.black return cell } else { return UITableViewCell.init(style: .default, reuseIdentifier: "error") } } }
mit
07d43187830b9c36426aab0c8ebdfaab
33.716814
132
0.688504
4.855198
false
false
false
false
Darktt/ScrollBanner
SrcollViewDemo/UIScrollViewExtension.swift
1
1179
// // UIScrollViewExtension.swift // SrcollViewDemo // // Created by EdenLi on 2016/2/4. // Copyright © 2016年 Darktt. All rights reserved. // import UIKit public enum UIScrollOrientation { case Vertical case Horizontal } public extension UIScrollView { public class func scrollViewPaging(frame: CGRect) -> UIScrollView { let scrollView: UIScrollView = UIScrollView(frame: frame) scrollView.pagingEnabled = true return scrollView } public func addSubviews(views: Array<UIView>, scrollOrientation orientation: Set<UIScrollOrientation>) { for view in views { self.addSubview(view) } let vertical: Bool = orientation.contains(.Vertical) let horizonal: Bool = orientation.contains(.Horizontal) if let lastView = views.last { let width: CGFloat = horizonal ? CGRectGetMaxX(lastView.frame) : 0.0 let height: CGFloat = vertical ? CGRectGetMaxY(lastView.frame) : 0.0 let _contentSize: CGSize = CGSize(width: width, height: height) self.contentSize = _contentSize } } }
apache-2.0
21e7896fc9016fecd73abbbb455a4819
25.727273
106
0.631803
4.629921
false
false
false
false
zisko/swift
test/SILGen/call_chain_reabstraction.swift
1
1009
// RUN: %target-swift-frontend -emit-silgen -enable-sil-ownership %s | %FileCheck %s struct A { func g<U>(_ recur: (A, U) -> U) -> (A, U) -> U { return { _, x in return x } } // CHECK-LABEL: sil hidden @$S24call_chain_reabstraction1AV1f{{[_0-9a-zA-Z]*}}F // CHECK: [[G:%.*]] = function_ref @$S24call_chain_reabstraction1AV1g{{[_0-9a-zA-Z]*}}F // CHECK: [[G2:%.*]] = apply [[G]]<A> // CHECK: [[REABSTRACT_THUNK:%.*]] = function_ref @$S24call_chain_reabstraction1AVA2CIegyir_A3CIegyyd_TR // CHECK: [[REABSTRACT:%.*]] = partial_apply [callee_guaranteed] [[REABSTRACT_THUNK]]([[G2]]) // CHECK: [[BORROW:%.*]] = begin_borrow [[REABSTRACT]] // CHECK: apply [[BORROW]]([[SELF:%.*]], [[SELF]]) // CHECK: destroy_value [[REABSTRACT]] func f() { let recur: (A, A) -> A = { c, x in x } let b = g(recur)(self, self) } }
apache-2.0
b11be481b162aa488c052e94dc2e2bff
52.105263
120
0.481665
3.467354
false
false
false
false
53ningen/todo
TODO/UI/Issue/IssueInfoCellView.swift
1
1399
import UIKit import Foundation final class IssueInfoCellView: UITableViewCell { @IBOutlet weak var idLabel: UILabel! @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var statusView: UIView! @IBOutlet weak var statusText: UILabel! @IBOutlet weak var descriptionTextView: UITextView! @IBOutlet weak var dateLabel: UILabel! override func willMove(toSuperview newSuperview: UIView?) { super.willMove(toSuperview: newSuperview) descriptionTextView.roundedCorners(5) descriptionTextView.border(1, color: UIColor.borderColor.cgColor) statusView.roundedCorners(5) } func bind(_ issue: Issue) { idLabel.text = "#\(issue.id.value)" titleLabel.text = issue.info.title descriptionTextView.text = issue.info.desc.isEmpty ? "No description provided." : issue.info.desc descriptionTextView.textColor = issue.info.desc.isEmpty ? UIColor.lightGray : UIColor.black statusView.backgroundColor = issue.info.state == .open ? UIColor.issueOpenColor : UIColor.issueClosedColor statusText.text = issue.info.state.rawValue.capitalized let status = issue.info.state == .open ? "opened" : "closed" let dateText = issue.info.state.closedAt?.formattedString ?? issue.info.createdAt.formattedString dateLabel.text = "\(status) this issue on \(dateText)" } }
mit
97e07d8b83565dd16950c26fbeff8a4b
42.71875
114
0.70193
4.694631
false
false
false
false
relayrides/objective-c-sdk
Pods/Mixpanel-swift/Mixpanel/WebSocket.swift
1
34330
////////////////////////////////////////////////////////////////////////////////////////////////// // // Websocket.swift // // Created by Dalton Cherry on 7/16/14. // Copyright (c) 2014-2015 Dalton Cherry. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ////////////////////////////////////////////////////////////////////////////////////////////////// import Foundation import CoreFoundation import Security let WebsocketDidConnectNotification = "WebsocketDidConnectNotification" let WebsocketDidDisconnectNotification = "WebsocketDidDisconnectNotification" let WebsocketDisconnectionErrorKeyName = "WebsocketDisconnectionErrorKeyName" protocol WebSocketDelegate: class { func websocketDidConnect(_ socket: WebSocket) func websocketDidDisconnect(_ socket: WebSocket, error: NSError?) func websocketDidReceiveMessage(_ socket: WebSocket, text: String) func websocketDidReceiveData(_ socket: WebSocket, data: Data) } protocol WebSocketPongDelegate: class { func websocketDidReceivePong(_ socket: WebSocket) } class WebSocket: NSObject, StreamDelegate { enum OpCode: UInt8 { case continueFrame = 0x0 case textFrame = 0x1 case binaryFrame = 0x2 // 3-7 are reserved. case connectionClose = 0x8 case ping = 0x9 case pong = 0xA // B-F reserved. } enum CloseCode: UInt16 { case normal = 1000 case goingAway = 1001 case protocolError = 1002 case protocolUnhandledType = 1003 // 1004 reserved. case noStatusReceived = 1005 //1006 reserved. case encoding = 1007 case policyViolated = 1008 case messageTooBig = 1009 } static let ErrorDomain = "WebSocket" enum InternalErrorCode: UInt16 { // 0-999 WebSocket status codes not used case outputStreamWriteError = 1 } // Where the callback is executed. It defaults to the main UI thread queue. var callbackQueue = DispatchQueue.main var optionalProtocols: [String]? // MARK: - Constants let headerWSUpgradeName = "Upgrade" let headerWSUpgradeValue = "websocket" let headerWSHostName = "Host" let headerWSConnectionName = "Connection" let headerWSConnectionValue = "Upgrade" let headerWSProtocolName = "Sec-WebSocket-Protocol" let headerWSVersionName = "Sec-WebSocket-Version" let headerWSVersionValue = "13" let headerWSKeyName = "Sec-WebSocket-Key" let headerOriginName = "Origin" let headerWSAcceptName = "Sec-WebSocket-Accept" let BUFFER_MAX = 4096 let FinMask: UInt8 = 0x80 let OpCodeMask: UInt8 = 0x0F let RSVMask: UInt8 = 0x70 let MaskMask: UInt8 = 0x80 let PayloadLenMask: UInt8 = 0x7F let MaxFrameSize: Int = 32 let httpSwitchProtocolCode = 101 let supportedSSLSchemes = ["wss", "https"] class WSResponse { var isFin = false var code: OpCode = .continueFrame var bytesLeft = 0 var frameCount = 0 var buffer: NSMutableData? } // MARK: - Delegates /// Responds to callback about new messages coming in over the WebSocket /// and also connection/disconnect messages. weak var delegate: WebSocketDelegate? /// Recives a callback for each pong message recived. weak var pongDelegate: WebSocketPongDelegate? // MARK: - Block based API. var onConnect: ((Void) -> Void)? var onDisconnect: ((NSError?) -> Void)? var onText: ((String) -> Void)? var onData: ((Data) -> Void)? var onPong: ((Void) -> Void)? var headers = [String: String]() var voipEnabled = false var selfSignedSSL = false var security: SSLSecurity? var enabledSSLCipherSuites: [SSLCipherSuite]? var origin: String? var timeout = 5 var isConnected: Bool { return connected } var currentURL: URL { return url } // MARK: - Private private var url: URL private var inputStream: InputStream? private var outputStream: OutputStream? private var connected = false private var isConnecting = false private var writeQueue = OperationQueue() private var readStack = [WSResponse]() private var inputQueue = [Data]() private var fragBuffer: Data? private var certValidated = false private var didDisconnect = false private var readyToWrite = false private let mutex = NSLock() private let notificationCenter = NotificationCenter.default private var canDispatch: Bool { mutex.lock() let canWork = readyToWrite mutex.unlock() return canWork } /// The shared processing queue used for all WebSocket. private static let sharedWorkQueue = DispatchQueue(label: "com.vluxe.starscream.websocket", attributes: []) init(url: URL, protocols: [String]? = nil) { self.url = url self.origin = url.absoluteString writeQueue.maxConcurrentOperationCount = 1 optionalProtocols = protocols } /// Connect to the WebSocket server on a background thread. func connect() { guard !isConnecting else { return } didDisconnect = false isConnecting = true createHTTPRequest() isConnecting = false } /** Disconnect from the server. I send a Close control frame to the server, then expect the server to respond with a Close control frame and close the socket from its end. I notify my delegate once the socket has been closed. If you supply a non-nil `forceTimeout`, I wait at most that long (in seconds) for the server to close the socket. After the timeout expires, I close the socket and notify my delegate. If you supply a zero (or negative) `forceTimeout`, I immediately close the socket (without sending a Close control frame) and notify my delegate. - Parameter forceTimeout: Maximum time to wait for the server to close the socket. */ func disconnect(forceTimeout: TimeInterval? = nil) { switch forceTimeout { case .some(let seconds) where seconds > 0: callbackQueue.asyncAfter(deadline: .now() + Double(Int64(seconds * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC)) { [weak self] in self?.disconnectStream(nil) } fallthrough case .none: writeError(CloseCode.normal.rawValue) default: disconnectStream(nil) break } } func write(string: String, completion: (() -> ())? = nil) { guard isConnected else { return } dequeueWrite(string.data(using: String.Encoding.utf8)!, code: .textFrame, writeCompletion: completion) } func write(data: Data, completion: (() -> ())? = nil) { guard isConnected else { return } dequeueWrite(data, code: .binaryFrame, writeCompletion: completion) } func write(_ ping: Data, completion: (() -> ())? = nil) { guard isConnected else { return } dequeueWrite(ping, code: .ping, writeCompletion: completion) } private func createHTTPRequest() { let urlRequest = CFHTTPMessageCreateRequest(kCFAllocatorDefault, "GET" as CFString, url as CFURL, kCFHTTPVersion1_1).takeRetainedValue() var port = url.port if port == nil { if supportedSSLSchemes.contains(url.scheme!) { port = 443 } else { port = 80 } } addHeader(urlRequest, key: headerWSUpgradeName, val: headerWSUpgradeValue) addHeader(urlRequest, key: headerWSConnectionName, val: headerWSConnectionValue) if let protocols = optionalProtocols { addHeader(urlRequest, key: headerWSProtocolName, val: protocols.joined(separator: ",")) } addHeader(urlRequest, key: headerWSVersionName, val: headerWSVersionValue) addHeader(urlRequest, key: headerWSKeyName, val: generateWebSocketKey()) if let origin = origin { addHeader(urlRequest, key: headerOriginName, val: origin) } addHeader(urlRequest, key: headerWSHostName, val: "\(url.host!):\(port!)") for (key, value) in headers { addHeader(urlRequest, key: key, val: value) } if let cfHTTPMessage = CFHTTPMessageCopySerializedMessage(urlRequest) { let serializedRequest = cfHTTPMessage.takeRetainedValue() initStreamsWithData(serializedRequest as Data, Int(port!)) } } private func addHeader(_ urlRequest: CFHTTPMessage, key: String, val: String) { CFHTTPMessageSetHeaderFieldValue(urlRequest, key as CFString, val as CFString) } private func generateWebSocketKey() -> String { var key = "" let seed = 16 for _ in 0..<seed { let uni = UnicodeScalar(UInt32(97 + arc4random_uniform(25))) key += "\(Character(uni!))" } let data = key.data(using: String.Encoding.utf8) let baseKey = data?.base64EncodedString(options: NSData.Base64EncodingOptions(rawValue: 0)) return baseKey! } private func initStreamsWithData(_ data: Data, _ port: Int) { //higher level API we will cut over to at some point //NSStream.getStreamsToHostWithName(url.host, port: url.port.integerValue, inputStream: &inputStream, outputStream: &outputStream) var readStream: Unmanaged<CFReadStream>? var writeStream: Unmanaged<CFWriteStream>? let h = url.host! as NSString CFStreamCreatePairWithSocketToHost(nil, h, UInt32(port), &readStream, &writeStream) inputStream = readStream!.takeRetainedValue() outputStream = writeStream!.takeRetainedValue() guard let inStream = inputStream, let outStream = outputStream else { return } inStream.delegate = self outStream.delegate = self if supportedSSLSchemes.contains(url.scheme!) { inStream.setProperty(StreamSocketSecurityLevel.negotiatedSSL as AnyObject, forKey: Stream.PropertyKey.socketSecurityLevelKey) outStream.setProperty(StreamSocketSecurityLevel.negotiatedSSL as AnyObject, forKey: Stream.PropertyKey.socketSecurityLevelKey) } else { certValidated = true //not a https session, so no need to check SSL pinning } if voipEnabled { inStream.setProperty(StreamNetworkServiceTypeValue.voIP as AnyObject, forKey: Stream.PropertyKey.networkServiceType) outStream.setProperty(StreamNetworkServiceTypeValue.voIP as AnyObject, forKey: Stream.PropertyKey.networkServiceType) } if selfSignedSSL { let settings: [NSObject: NSObject] = [kCFStreamSSLValidatesCertificateChain: NSNumber(value: false), kCFStreamSSLPeerName: kCFNull] inStream.setProperty(settings, forKey: kCFStreamPropertySSLSettings as Stream.PropertyKey) outStream.setProperty(settings, forKey: kCFStreamPropertySSLSettings as Stream.PropertyKey) } if let cipherSuites = self.enabledSSLCipherSuites { if let sslContextIn = CFReadStreamCopyProperty(inputStream, CFStreamPropertyKey(rawValue: kCFStreamPropertySSLContext)) as! SSLContext?, let sslContextOut = CFWriteStreamCopyProperty(outputStream, CFStreamPropertyKey(rawValue: kCFStreamPropertySSLContext)) as! SSLContext? { let resIn = SSLSetEnabledCiphers(sslContextIn, cipherSuites, cipherSuites.count) let resOut = SSLSetEnabledCiphers(sslContextOut, cipherSuites, cipherSuites.count) if resIn != errSecSuccess { let error = self.errorWithDetail("Error setting ingoing cypher suites", code: UInt16(resIn)) disconnectStream(error) return } if resOut != errSecSuccess { let error = self.errorWithDetail("Error setting outgoing cypher suites", code: UInt16(resOut)) disconnectStream(error) return } } } CFReadStreamSetDispatchQueue(inStream, WebSocket.sharedWorkQueue) CFWriteStreamSetDispatchQueue(outStream, WebSocket.sharedWorkQueue) inStream.open() outStream.open() self.mutex.lock() self.readyToWrite = true self.mutex.unlock() let bytes = UnsafeRawPointer((data as NSData).bytes).assumingMemoryBound(to: UInt8.self) var out = timeout * 1000000 // wait 5 seconds before giving up writeQueue.addOperation { [weak self] in while !outStream.hasSpaceAvailable { usleep(100) // wait until the socket is ready out -= 100 if out < 0 { self?.cleanupStream() self?.doDisconnect(self?.errorWithDetail("write wait timed out", code: 2)) return } else if outStream.streamError != nil { return // disconnectStream will be called. } } outStream.write(bytes, maxLength: data.count) } } func stream(_ aStream: Stream, handle eventCode: Stream.Event) { if let sec = security, !certValidated && [.hasBytesAvailable, .hasSpaceAvailable].contains(eventCode) { let trust = aStream.property(forKey: kCFStreamPropertySSLPeerTrust as Stream.PropertyKey) as AnyObject let domain = aStream.property(forKey: kCFStreamSSLPeerName as Stream.PropertyKey) as? String if sec.isValid(trust as! SecTrust, domain: domain) { certValidated = true } else { let error = errorWithDetail("Invalid SSL certificate", code: 1) disconnectStream(error) return } } if eventCode == .hasBytesAvailable { if aStream == inputStream { processInputStream() } } else if eventCode == .errorOccurred { disconnectStream(aStream.streamError as NSError?) } else if eventCode == .endEncountered { disconnectStream(nil) } } private func disconnectStream(_ error: NSError?) { if error == nil { writeQueue.waitUntilAllOperationsAreFinished() } else { writeQueue.cancelAllOperations() } cleanupStream() doDisconnect(error) } private func cleanupStream() { outputStream?.delegate = nil inputStream?.delegate = nil if let stream = inputStream { CFReadStreamSetDispatchQueue(stream, nil) stream.close() } if let stream = outputStream { CFWriteStreamSetDispatchQueue(stream, nil) stream.close() } outputStream = nil inputStream = nil } private func processInputStream() { let buf = NSMutableData(capacity: BUFFER_MAX) let buffer = UnsafeMutableRawPointer(mutating: buf!.bytes).assumingMemoryBound(to: UInt8.self) let length = inputStream!.read(buffer, maxLength: BUFFER_MAX) guard length > 0 else { return } var process = false if inputQueue.isEmpty { process = true } inputQueue.append(Data(bytes: buffer, count: length)) if process { dequeueInput() } } private func dequeueInput() { while !inputQueue.isEmpty { let data = inputQueue[0] var work = data if let fragBuffer = fragBuffer { var combine = NSData(data: fragBuffer) as Data combine.append(data) work = combine self.fragBuffer = nil } let buffer = UnsafeRawPointer((work as NSData).bytes).assumingMemoryBound(to: UInt8.self) let length = work.count if !connected { processTCPHandshake(buffer, bufferLen: length) } else { processRawMessagesInBuffer(buffer, bufferLen: length) } inputQueue = inputQueue.filter { $0 != data } } } private func processTCPHandshake(_ buffer: UnsafePointer<UInt8>, bufferLen: Int) { let code = processHTTP(buffer, bufferLen: bufferLen) switch code { case 0: connected = true guard canDispatch else {return} callbackQueue.async { [weak self] in guard let s = self else { return } s.onConnect?() s.delegate?.websocketDidConnect(s) s.notificationCenter.post(name: NSNotification.Name(WebsocketDidConnectNotification), object: self) } case -1: fragBuffer = Data(bytes: buffer, count: bufferLen) break // do nothing, we are going to collect more data default: doDisconnect(errorWithDetail("Invalid HTTP upgrade", code: UInt16(code))) } } private func processHTTP(_ buffer: UnsafePointer<UInt8>, bufferLen: Int) -> Int { let CRLFBytes = [UInt8(ascii: "\r"), UInt8(ascii: "\n"), UInt8(ascii: "\r"), UInt8(ascii: "\n")] var k = 0 var totalSize = 0 for i in 0..<bufferLen { if buffer[i] == CRLFBytes[k] { k += 1 if k == 3 { totalSize = i + 1 break } } else { k = 0 } } if totalSize > 0 { let code = validateResponse(buffer, bufferLen: totalSize) if code != 0 { return code } totalSize += 1 //skip the last \n let restSize = bufferLen - totalSize if restSize > 0 { processRawMessagesInBuffer(buffer + totalSize, bufferLen: restSize) } return 0 //success } return -1 // Was unable to find the full TCP header. } private func validateResponse(_ buffer: UnsafePointer<UInt8>, bufferLen: Int) -> Int { let response = CFHTTPMessageCreateEmpty(kCFAllocatorDefault, false).takeRetainedValue() CFHTTPMessageAppendBytes(response, buffer, bufferLen) let code = CFHTTPMessageGetResponseStatusCode(response) if code != httpSwitchProtocolCode { return code } if let cfHeaders = CFHTTPMessageCopyAllHeaderFields(response) { let headers = cfHeaders.takeRetainedValue() as NSDictionary if let acceptKey = headers[headerWSAcceptName as NSString] as? NSString { if acceptKey.length > 0 { return 0 } } } return -1 } private static func readUint16(_ buffer: UnsafePointer<UInt8>, offset: Int) -> UInt16 { return (UInt16(buffer[offset + 0]) << 8) | UInt16(buffer[offset + 1]) } private static func readUint64(_ buffer: UnsafePointer<UInt8>, offset: Int) -> UInt64 { var value = UInt64(0) for i in 0...7 { value = (value << 8) | UInt64(buffer[offset + i]) } return value } private static func writeUint16(_ buffer: UnsafeMutablePointer<UInt8>, offset: Int, value: UInt16) { buffer[offset + 0] = UInt8(value >> 8) buffer[offset + 1] = UInt8(value & 0xff) } private static func writeUint64(_ buffer: UnsafeMutablePointer<UInt8>, offset: Int, value: UInt64) { for i in 0...7 { buffer[offset + i] = UInt8((value >> (8*UInt64(7 - i))) & 0xff) } } private func processOneRawMessage(inBuffer buffer: UnsafeBufferPointer<UInt8>) -> UnsafeBufferPointer<UInt8> { let response = readStack.last guard let baseAddress = buffer.baseAddress else {return emptyBuffer} let bufferLen = buffer.count if response != nil && bufferLen < 2 { fragBuffer = Data(buffer: buffer) return emptyBuffer } if let response = response, response.bytesLeft > 0 { var len = response.bytesLeft var extra = bufferLen - response.bytesLeft if response.bytesLeft > bufferLen { len = bufferLen extra = 0 } response.bytesLeft -= len response.buffer?.append(Data(bytes: baseAddress, count: len)) _ = processResponse(response) return buffer.fromOffset(bufferLen - extra) } else { let isFin = (FinMask & baseAddress[0]) let receivedOpcode = OpCode(rawValue: (OpCodeMask & baseAddress[0])) let isMasked = (MaskMask & baseAddress[1]) let payloadLen = (PayloadLenMask & baseAddress[1]) var offset = 2 if (isMasked > 0 || (RSVMask & baseAddress[0]) > 0) && receivedOpcode != .pong { let errCode = CloseCode.protocolError.rawValue doDisconnect(errorWithDetail("masked and rsv data is not currently supported", code: errCode)) writeError(errCode) return emptyBuffer } let isControlFrame = (receivedOpcode == .connectionClose || receivedOpcode == .ping) if !isControlFrame && (receivedOpcode != .binaryFrame && receivedOpcode != .continueFrame && receivedOpcode != .textFrame && receivedOpcode != .pong) { let errCode = CloseCode.protocolError.rawValue doDisconnect(errorWithDetail("unknown opcode: \(receivedOpcode)", code: errCode)) writeError(errCode) return emptyBuffer } if isControlFrame && isFin == 0 { let errCode = CloseCode.protocolError.rawValue doDisconnect(errorWithDetail("control frames can't be fragmented", code: errCode)) writeError(errCode) return emptyBuffer } if receivedOpcode == .connectionClose { var code = CloseCode.normal.rawValue if payloadLen == 1 { code = CloseCode.protocolError.rawValue } else if payloadLen > 1 { code = WebSocket.readUint16(baseAddress, offset: offset) if code < 1000 || (code > 1003 && code < 1007) || (code > 1011 && code < 3000) { code = CloseCode.protocolError.rawValue } offset += 2 } var closeReason = "connection closed by server" if payloadLen > 2 { let len = Int(payloadLen - 2) if len > 0 { let bytes = baseAddress + offset if let customCloseReason = String(data: Data(bytes: bytes, count: len), encoding: .utf8) { closeReason = customCloseReason } else { code = CloseCode.protocolError.rawValue } } } doDisconnect(errorWithDetail(closeReason, code: code)) writeError(code) return emptyBuffer } if isControlFrame && payloadLen > 125 { writeError(CloseCode.protocolError.rawValue) return emptyBuffer } var dataLength = UInt64(payloadLen) if dataLength == 127 { dataLength = WebSocket.readUint64(baseAddress, offset: offset) offset += MemoryLayout<UInt64>.size } else if dataLength == 126 { dataLength = UInt64(WebSocket.readUint16(baseAddress, offset: offset)) offset += MemoryLayout<UInt16>.size } if bufferLen < offset || UInt64(bufferLen - offset) < dataLength { fragBuffer = Data(bytes: baseAddress, count: bufferLen) return emptyBuffer } var len = dataLength if dataLength > UInt64(bufferLen) { len = UInt64(bufferLen-offset) } let data: Data if len < 0 { len = 0 data = Data() } else { data = Data(bytes: baseAddress+offset, count: Int(len)) } if receivedOpcode == .pong { if canDispatch { callbackQueue.async { [weak self] in guard let s = self else { return } s.onPong?() s.pongDelegate?.websocketDidReceivePong(s) } } return buffer.fromOffset(offset + Int(len)) } var response = readStack.last if isControlFrame { response = nil // Don't append pings. } if isFin == 0 && receivedOpcode == .continueFrame && response == nil { let errCode = CloseCode.protocolError.rawValue doDisconnect(errorWithDetail("continue frame before a binary or text frame", code: errCode)) writeError(errCode) return emptyBuffer } var isNew = false if response == nil { if receivedOpcode == .continueFrame { let errCode = CloseCode.protocolError.rawValue doDisconnect(errorWithDetail("first frame can't be a continue frame", code: errCode)) writeError(errCode) return emptyBuffer } isNew = true response = WSResponse() response!.code = receivedOpcode! response!.bytesLeft = Int(dataLength) response!.buffer = NSMutableData(data: data) } else { if receivedOpcode == .continueFrame { response!.bytesLeft = Int(dataLength) } else { let errCode = CloseCode.protocolError.rawValue doDisconnect(errorWithDetail("second and beyond of fragment message must be a continue frame", code: errCode)) writeError(errCode) return emptyBuffer } response!.buffer!.append(data) } if let response = response { response.bytesLeft -= Int(len) response.frameCount += 1 response.isFin = isFin > 0 ? true : false if isNew { readStack.append(response) } _ = processResponse(response) } let step = Int(offset + numericCast(len)) return buffer.fromOffset(step) } } private func processRawMessagesInBuffer(_ pointer: UnsafePointer<UInt8>, bufferLen: Int) { var buffer = UnsafeBufferPointer(start: pointer, count: bufferLen) repeat { buffer = processOneRawMessage(inBuffer: buffer) } while buffer.count >= 2 if !buffer.isEmpty { fragBuffer = Data(buffer: buffer) } } private func processResponse(_ response: WSResponse) -> Bool { if response.isFin && response.bytesLeft <= 0 { if response.code == .ping { let data = response.buffer! // local copy so it is perverse for writing dequeueWrite(data as Data, code: .pong) } else if response.code == .textFrame { let str: NSString? = NSString(data: response.buffer! as Data, encoding: String.Encoding.utf8.rawValue) if str == nil { writeError(CloseCode.encoding.rawValue) return false } if canDispatch { callbackQueue.async { [weak self] in guard let s = self else { return } s.onText?(str! as String) s.delegate?.websocketDidReceiveMessage(s, text: str! as String) } } } else if response.code == .binaryFrame { if canDispatch { let data = response.buffer! // local copy so it is perverse for writing callbackQueue.async { [weak self] in guard let s = self else { return } s.onData?(data as Data) s.delegate?.websocketDidReceiveData(s, data: data as Data) } } } readStack.removeLast() return true } return false } private func errorWithDetail(_ detail: String, code: UInt16) -> NSError { var details = [String: String]() details[NSLocalizedDescriptionKey] = detail return NSError(domain: WebSocket.ErrorDomain, code: Int(code), userInfo: details) } private func writeError(_ code: UInt16) { let buf = NSMutableData(capacity: MemoryLayout<UInt16>.size) let buffer = UnsafeMutableRawPointer(mutating: buf!.bytes).assumingMemoryBound(to: UInt8.self) WebSocket.writeUint16(buffer, offset: 0, value: code) dequeueWrite(Data(bytes: buffer, count: MemoryLayout<UInt16>.size), code: .connectionClose) } private func dequeueWrite(_ data: Data, code: OpCode, writeCompletion: (() -> ())? = nil) { writeQueue.addOperation { [weak self] in //stream isn't ready, let's wait guard let s = self else { return } var offset = 2 let dataLength = data.count let frame = NSMutableData(capacity: dataLength + s.MaxFrameSize) let buffer = UnsafeMutableRawPointer(frame!.mutableBytes).assumingMemoryBound(to: UInt8.self) buffer[0] = s.FinMask | code.rawValue if dataLength < 126 { buffer[1] = CUnsignedChar(dataLength) } else if dataLength <= Int(UInt16.max) { buffer[1] = 126 WebSocket.writeUint16(buffer, offset: offset, value: UInt16(dataLength)) offset += MemoryLayout<UInt16>.size } else { buffer[1] = 127 WebSocket.writeUint64(buffer, offset: offset, value: UInt64(dataLength)) offset += MemoryLayout<UInt64>.size } buffer[1] |= s.MaskMask let maskKey = UnsafeMutablePointer<UInt8>(buffer + offset) _ = SecRandomCopyBytes(kSecRandomDefault, Int(MemoryLayout<UInt32>.size), maskKey) offset += MemoryLayout<UInt32>.size for i in 0..<dataLength { buffer[offset] = data[i] ^ maskKey[i % MemoryLayout<UInt32>.size] offset += 1 } var total = 0 while true { guard let outStream = s.outputStream else { break } let writeBuffer = UnsafeRawPointer(frame!.bytes+total).assumingMemoryBound(to: UInt8.self) let len = outStream.write(writeBuffer, maxLength: offset-total) if len < 0 { var error: Error? if let streamError = outStream.streamError { error = streamError } else { let errCode = InternalErrorCode.outputStreamWriteError.rawValue error = s.errorWithDetail("output stream error during write", code: errCode) } s.doDisconnect(error as NSError?) break } else { total += len } if total >= offset { if let queue = self?.callbackQueue, let callback = writeCompletion { queue.async { callback() } } break } } } } private func doDisconnect(_ error: NSError?) { guard !didDisconnect else { return } didDisconnect = true connected = false guard canDispatch else {return} callbackQueue.async { [weak self] in guard let s = self else { return } s.onDisconnect?(error) s.delegate?.websocketDidDisconnect(s, error: error) let userInfo = error.map { [WebsocketDisconnectionErrorKeyName: $0] } s.notificationCenter.post(name: NSNotification.Name(WebsocketDidDisconnectNotification), object: self, userInfo: userInfo) } } // MARK: - Deinit deinit { mutex.lock() readyToWrite = false mutex.unlock() cleanupStream() } } private extension Data { init(buffer: UnsafeBufferPointer<UInt8>) { self.init(bytes: buffer.baseAddress!, count: buffer.count) } } private extension UnsafeBufferPointer { func fromOffset(_ offset: Int) -> UnsafeBufferPointer<Element> { return UnsafeBufferPointer<Element>(start: baseAddress?.advanced(by: offset), count: count - offset) } } private let emptyBuffer = UnsafeBufferPointer<UInt8>(start: nil, count: 0)
apache-2.0
0310e2e9f2e95c8f67c95879664142cf
39.771971
139
0.573755
5.475279
false
false
false
false
CoderXpert/EPGGrid
EPG/EPG/EpgGridLayout.swift
1
5334
// // EpgGridLayout.swift // EPG // // Created by Adnan Aftab on 2/14/15. // Copyright (c) 2015 CX. All rights reserved. // import UIKit class EpgGridLayout: UICollectionViewLayout { let cellIdentifier = "EPGCollectionViewCell" let RELATIVE_HOUR : TimeInterval = (240.0) let ACTUAL_HOUR : TimeInterval = 3600.0 var epgStartTime : Date! var epgEndTime : Date! var xPos:CGFloat = 0 var yPos:CGFloat = 0 var layoutInfo : NSMutableDictionary? var framesInfo : NSMutableDictionary? let weekTimeInterval : TimeInterval = (60 * 60 * 24 * 7) let TILE_WIDTH : CGFloat = 200 let TILE_HEIGHT : CGFloat = 70 var channels : [Channel]? override init() { super.init() setup() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setup() } func setup() { let cal = Calendar.current var date = Date() date = cal.startOfDay(for: date) date = (cal as NSCalendar).date(byAdding: .day, value: -1, to: date, options: [])! epgStartTime = date epgEndTime = epgStartTime.addingTimeInterval(weekTimeInterval) layoutInfo = NSMutableDictionary() framesInfo = NSMutableDictionary() channels = Channel.channels() } override func prepare() { calculateFramesForAllPrograms() let newLayoutInfo = NSMutableDictionary() let cellLayoutInfo = NSMutableDictionary() guard let channels = channels else { return } for section in 0..<channels.count { let channel = channels[section] guard let programs = channel.programs else { continue } for index in 0..<programs.count { let indexPath = IndexPath(item: index, section: section) let itemAttributes = UICollectionViewLayoutAttributes(forCellWith: indexPath) itemAttributes.frame = frameForItemAtIndexPath(indexPath) cellLayoutInfo[indexPath] = itemAttributes } } newLayoutInfo[cellIdentifier] = cellLayoutInfo layoutInfo = newLayoutInfo } override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? { var layoutAttributes = [UICollectionViewLayoutAttributes]() let enumerateClosure = { (object: Any, attributes: Any, stop: UnsafeMutablePointer<ObjCBool>) in guard let attributes = attributes as? UICollectionViewLayoutAttributes, rect.intersects(attributes.frame) else { return } layoutAttributes.append(attributes) } layoutInfo?.enumerateKeysAndObjects({ (object: Any, elementInfo: Any, stop: UnsafeMutablePointer<ObjCBool>) in guard let infoDic = elementInfo as? NSDictionary else { return } infoDic.enumerateKeysAndObjects(enumerateClosure) }) return layoutAttributes } override func layoutAttributesForItem(at indexPath: IndexPath) -> (UICollectionViewLayoutAttributes!) { let attributes = UICollectionViewLayoutAttributes(forCellWith: indexPath) attributes.frame = self.frameForItemAtIndexPath(indexPath) return attributes } func tileSize(for program : Program) -> CGSize { let duartionFactor = program.duration / ACTUAL_HOUR let width :CGFloat = CGFloat(duartionFactor * RELATIVE_HOUR) return CGSize(width: width, height: TILE_HEIGHT) } func calculateFramesForAllPrograms() { guard let channels = channels else { return } for i in 0..<channels.count { xPos = 0 let channel = channels[i] guard let programs = channel.programs else { yPos += TILE_HEIGHT continue } for index in 0..<programs.count { let program = programs[index] let tileSize = self.tileSize(for: program) let frame = CGRect(x: xPos, y: yPos, width: tileSize.width, height: tileSize.height) let rectString = NSStringFromCGRect(frame) let indexPath = IndexPath(item: index, section: i) framesInfo?[indexPath] = rectString xPos = xPos+tileSize.width } yPos += TILE_HEIGHT } } func frameForItemAtIndexPath(_ indexPath : IndexPath) -> CGRect { guard let infoDic = framesInfo, let rectString = infoDic[indexPath] as? String else { return CGRect.zero } return CGRectFromString(rectString) } override var collectionViewContentSize : CGSize { guard let channels = channels else { return CGSize.zero } let intervals = epgEndTime.timeIntervalSince(epgStartTime) let numberOfHours = CGFloat(intervals / 3600) let width = numberOfHours * TILE_WIDTH let height = CGFloat(channels.count) * TILE_HEIGHT return CGSize(width: width, height: height) } override func shouldInvalidateLayout(forBoundsChange newBounds: CGRect) -> Bool { return !collectionView!.bounds.size.equalTo(newBounds.size) } override func invalidateLayout() { xPos = 0 yPos = 0 super.invalidateLayout() } }
mit
340f7a33ab89307c3c5151842b30133c
35.786207
133
0.628046
5.051136
false
false
false
false
chaoyang805/DoubanMovie
DoubanMovie/MovieDialogView.swift
1
6118
/* * Copyright 2016 chaoyang805 [email protected] * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import UIKit class MovieDialogView: UIView, LoadingEffect { var titleLabel: UILabel! var collectCountLabel: UILabel! var ratingInfoView: RatingStar! var posterImageButton: UIButton! var titleBarView: UIVisualEffectView! var loadingImageView: UIImageView! var movie: DoubanMovie? { didSet { guard let m = movie else { return } configureWithMovie(m) } } override init(frame: CGRect) { super.init(frame: frame) setupAppearence() initSubviews() } private func initSubviews() { // addBackgroundImageButton addBackgroundButton() // initTitlebar addTitlebar() } func configureWithMovie(_ movie: DoubanMovie) { titleLabel.text = movie.title collectCountLabel.text = String(format: "%d人看过", movie.collectCount) ratingInfoView.ratingScore = CGFloat(movie.rating?.average ?? 0) ratingInfoView.isHidden = false posterImageButton.imageView?.contentMode = .scaleAspectFill posterImageButton.contentHorizontalAlignment = .fill posterImageButton.sd_setImage(with: URL(string: movie.images!.largeImageURL), for: .normal) } func addTarget(target: AnyObject?, action: Selector, for controlEvents: UIControlEvents) { if posterImageButton != nil { posterImageButton.addTarget(target, action: action, for: controlEvents) } } private func addBackgroundButton() { posterImageButton = UIButton(type: .custom) posterImageButton.frame = self.bounds addSubview(posterImageButton) } private func addTitlebar() { titleBarView = UIVisualEffectView(effect: UIBlurEffect(style: .light)) titleBarView.frame = CGRect(x: 0, y: 0, width: self.bounds.width, height: 80) // add title label titleLabel = UILabel(frame: CGRect(x: 20, y: 18, width: 190, height: 26)) titleLabel.textColor = UIColor.white titleLabel.font = UIFont(name: "PingFang SC", size: 18) titleBarView.contentView.addSubview(titleLabel) // add collect count label collectCountLabel = UILabel(frame: CGRect(x: 20, y: 49, width: 150, height: 14)) collectCountLabel.textColor = UIColor.white collectCountLabel.font = UIFont(name: "PingFang SC", size: 10) titleBarView.contentView.addSubview(collectCountLabel) // add ratingbar ratingInfoView = RatingStar(ratingScore: 0, style: .small) let ratingBarX = self.bounds.width - ratingInfoView.bounds.width - 20 let ratingBarY: CGFloat = 18 ratingInfoView.frame.origin = CGPoint(x: ratingBarX, y: ratingBarY) titleBarView.contentView.addSubview(ratingInfoView) // add loading imageView default hidden loadingImageView = UIImageView(image: UIImage(named: "loading")!) loadingImageView.frame = CGRect(x: 0, y: 0, width: 120, height: 120) loadingImageView.center = CGPoint(x: self.bounds.midX, y: self.bounds.midY) loadingImageView.isHidden = true self.addSubview(loadingImageView) self.addSubview(titleBarView) } private func setupAppearence() { self.layer.cornerRadius = 10 self.layer.shadowOpacity = 0.5 self.layer.shadowRadius = 4 self.layer.shadowOffset = CGSize(width: 1, height: 1) self.layer.shadowColor = UIColor.darkGray.cgColor self.backgroundColor = UIColor.lightGray self.clipsToBounds = true } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // LoadingEffect private(set) var isLoading: Bool = false func rotateAnimation() -> CABasicAnimation { let animation = CABasicAnimation(keyPath: "transform") animation.duration = 0.5 animation.repeatCount = HUGE animation.isCumulative = true let angle = -CGFloat(2 * M_PI / 5) let transform = CATransform3DMakeRotation(angle, 0, 0, -1) animation.byValue = NSValue(caTransform3D: transform) return animation } func beginLoading() { if isLoading { return } self.isLoading = true self.loadingImageView.alpha = 0 self.loadingImageView.isHidden = false UIView.animate(withDuration: 0.2) { [weak self] in guard let `self` = self else { return } self.loadingImageView.alpha = 1 self.titleBarView.alpha = 0 self.posterImageButton.alpha = 0 self.loadingImageView.layer.add(self.rotateAnimation(), forKey: "rotateAnimation") } } func endLoading() { if !isLoading { return } self.loadingImageView.layer.removeAllAnimations() UIView.animate(withDuration: 0.2, animations: { [weak self] in guard let `self` = self else { return } self.loadingImageView.alpha = 0 self.titleBarView.alpha = 1 self.posterImageButton.alpha = 1 }) { [weak self](done) in guard let `self` = self else { return } self.loadingImageView.isHidden = true self.isLoading = false } } }
apache-2.0
e2d1c5f7c55be7cbd80eb151114966bd
33.531073
99
0.627127
4.712413
false
false
false
false
cdmx/MiniMancera
miniMancera/Controller/Abstract/ControllerParentTransitions.swift
1
8593
import UIKit extension ControllerParent { enum Vertical:CGFloat { case top = -1 case bottom = 1 case none = 0 } enum Horizontal:CGFloat { case left = -1 case right = 1 case none = 0 } //MARK: private private func slide(controller:UIViewController, left:CGFloat) { guard let view:ViewParent = self.view as? ViewParent, let currentController:UIViewController = childViewControllers.last, let newView:ViewProtocol = controller.view as? ViewProtocol, let currentView:ViewProtocol = currentController.view as? ViewProtocol else { return } addChildViewController(controller) controller.beginAppearanceTransition(true, animated:true) currentController.beginAppearanceTransition(false, animated:true) view.slide( currentView:currentView, newView:newView, left:left) { controller.endAppearanceTransition() currentController.endAppearanceTransition() currentController.removeFromParentViewController() } } //MARK: public func slideTo(horizontal:Horizontal, controller:UIViewController) { let viewWidth:CGFloat = -view.bounds.maxX let left:CGFloat = viewWidth * horizontal.rawValue slide(controller:controller, left:left) } func mainController(controller:UIViewController) { addChildViewController(controller) guard let view:ViewParent = self.view as? ViewParent, let newView:ViewProtocol = controller.view as? ViewProtocol else { return } view.mainView(view:newView) } func push( controller:UIViewController, horizontal:Horizontal = Horizontal.none, vertical:Vertical = Vertical.none, background:Bool = true, completion:(() -> ())? = nil) { guard let view:ViewParent = self.view as? ViewParent, let currentController:UIViewController = childViewControllers.last, let newView:ViewProtocol = controller.view as? ViewProtocol else { return } let width:CGFloat = view.bounds.maxX let height:CGFloat = view.bounds.maxY let left:CGFloat = width * horizontal.rawValue let top:CGFloat = height * vertical.rawValue addChildViewController(controller) controller.beginAppearanceTransition(true, animated:true) currentController.beginAppearanceTransition(false, animated:true) view.panRecognizer.isEnabled = true view.push( newView:newView, left:left, top:top, background:background) { controller.endAppearanceTransition() currentController.endAppearanceTransition() completion?() } } func animateOver(controller:UIViewController) { guard let view:ViewParent = self.view as? ViewParent, let currentController:UIViewController = childViewControllers.last, let newView:ViewProtocol = controller.view as? ViewProtocol else { return } addChildViewController(controller) controller.beginAppearanceTransition(true, animated:true) currentController.beginAppearanceTransition(false, animated:true) view.animateOver( newView:newView) { controller.endAppearanceTransition() currentController.endAppearanceTransition() } } func removeBetweenFirstAndLast() { var controllers:Int = childViewControllers.count - 1 while controllers > 1 { controllers -= 1 let controller:UIViewController = childViewControllers[controllers] controller.beginAppearanceTransition(false, animated:false) controller.view.removeFromSuperview() controller.endAppearanceTransition() controller.removeFromParentViewController() } } func removeAllButLast() { var controllers:Int = childViewControllers.count - 1 while controllers > 0 { controllers -= 1 let controller:UIViewController = childViewControllers[controllers] controller.beginAppearanceTransition(false, animated:false) controller.view.removeFromSuperview() controller.endAppearanceTransition() controller.removeFromParentViewController() } } func pop( horizontal:Horizontal = Horizontal.none, vertical:Vertical = Vertical.none, completion:(() -> ())? = nil) { let width:CGFloat = view.bounds.maxX let height:CGFloat = view.bounds.maxY let left:CGFloat = width * horizontal.rawValue let top:CGFloat = height * vertical.rawValue let controllers:Int = childViewControllers.count if controllers > 1 { let currentController:UIViewController = childViewControllers[controllers - 1] let previousController:UIViewController = childViewControllers[controllers - 2] guard let view:ViewParent = self.view as? ViewParent, let currentView:ViewProtocol = currentController.view as? ViewProtocol else { return } currentController.beginAppearanceTransition(false, animated:true) previousController.beginAppearanceTransition(true, animated:true) view.pop( currentView:currentView, left:left, top:top) { previousController.endAppearanceTransition() currentController.endAppearanceTransition() currentController.removeFromParentViewController() completion?() if self.childViewControllers.count > 1 { view.panRecognizer.isEnabled = true } else { view.panRecognizer.isEnabled = false } } } } func popSilent(removeIndex:Int) { let controllers:Int = childViewControllers.count if controllers > removeIndex { let removeController:UIViewController = childViewControllers[removeIndex] guard let view:ViewParent = self.view as? ViewParent, let removeView:ViewProtocol = removeController.view as? ViewProtocol else { return } removeView.pushBackground?.removeFromSuperview() removeController.view.removeFromSuperview() removeController.removeFromParentViewController() if childViewControllers.count < 2 { view.panRecognizer.isEnabled = false } } } func dismissAnimateOver(completion:(() -> ())?) { guard let view:ViewParent = self.view as? ViewParent, let currentController:UIViewController = childViewControllers.last else { return } currentController.removeFromParentViewController() guard let previousController:UIViewController = childViewControllers.last else { return } currentController.beginAppearanceTransition(false, animated:true) previousController.beginAppearanceTransition(true, animated:true) view.dismissAnimateOver( currentView:currentController.view) { currentController.endAppearanceTransition() previousController.endAppearanceTransition() completion?() } } }
mit
00ee8e0800e1897a1de7f1329121ddc4
28.733564
91
0.560922
6.559542
false
false
false
false
hooman/swift
test/IRGen/autolink-runtime-compatibility.swift
2
5118
// REQUIRES: OS=macosx,CPU=x86_64 // Doesn't autolink compatibility library because autolinking is disabled // RUN: %target-swift-frontend -disable-autolinking-runtime-compatibility-dynamic-replacements -target %target-cpu-apple-macosx10.9 -disable-autolinking-runtime-compatibility -disable-autolinking-runtime-compatibility-concurrency -emit-ir -parse-stdlib %s | %FileCheck -check-prefix=NO-FORCE-LOAD %s // RUN: %target-swift-frontend -disable-autolinking-runtime-compatibility-dynamic-replacements -runtime-compatibility-version 5.0 -disable-autolinking-runtime-compatibility -disable-autolinking-runtime-compatibility-concurrency -emit-ir -parse-stdlib %s | %FileCheck -check-prefix=NO-FORCE-LOAD %s // Doesn't autolink compatibility library because runtime compatibility library is disabled // RUN: %target-swift-frontend -runtime-compatibility-version none -emit-ir -parse-stdlib %s | %FileCheck -check-prefix=NO-FORCE-LOAD %s // Doesn't autolink compatibility library because target OS doesn't need it // RUN: %target-swift-frontend -target %target-cpu-apple-macosx10.24 -emit-ir -parse-stdlib %s | %FileCheck -check-prefix=NO-FORCE-LOAD %s // Only autolinks 5.1 compatibility library because target OS has 5.1 // RUN: %target-swift-frontend -target %target-cpu-apple-macosx10.15 -emit-ir -parse-stdlib %s | %FileCheck -check-prefix=FORCE-LOAD-51 %s // Autolinks because compatibility library was explicitly asked for // RUN: %target-swift-frontend -runtime-compatibility-version 5.0 -emit-ir -parse-stdlib %s | %FileCheck -check-prefix=FORCE-LOAD %s // RUN: %target-swift-frontend -runtime-compatibility-version 5.1 -emit-ir -parse-stdlib %s | %FileCheck -check-prefix=FORCE-LOAD-51 %s // RUN: %target-swift-frontend -runtime-compatibility-version 5.5 -emit-ir -parse-stdlib %s | %FileCheck -check-prefix=FORCE-LOAD-55 %s // RUN: %target-swift-frontend -target %target-cpu-apple-macosx10.24 -runtime-compatibility-version 5.0 -emit-ir -parse-stdlib %s | %FileCheck -check-prefix=FORCE-LOAD %s // RUN: %target-swift-frontend -target %target-cpu-apple-macosx10.24 -runtime-compatibility-version 5.1 -emit-ir -parse-stdlib %s | %FileCheck -check-prefix=FORCE-LOAD-51 %s // RUN: %target-swift-frontend -target %target-cpu-apple-macosx10.24 -runtime-compatibility-version 5.5 -emit-ir -parse-stdlib %s | %FileCheck -check-prefix=FORCE-LOAD-55 %s public func foo() {} // NO-FORCE-LOAD-NOT: FORCE_LOAD // NO-FORCE-LOAD-NOT: !{!"-lswiftCompatibility50"} // NO-FORCE-LOAD-NOT: !{!"-lswiftCompatibility51"} // NO-FORCE-LOAD-NOT: !{!"-lswiftCompatibilityDynamicReplacements"} // NO-FORCE-LOAD-NOT: !{!"-lswiftCompatibilityConcurrency"} // FORCE-LOAD: declare {{.*}} @"_swift_FORCE_LOAD_$_swiftCompatibility50" // FORCE-LOAD: declare {{.*}} @"_swift_FORCE_LOAD_$_swiftCompatibilityDynamicReplacements" // FORCE-LOAD: declare {{.*}} @"_swift_FORCE_LOAD_$_swiftCompatibilityConcurrency" // FORCE-LOAD-DAG: [[AUTOLINK_SWIFT_COMPAT:![0-9]+]] = !{!"-lswiftCompatibility50"} // FORCE-LOAD-DAG: !{!"-lswiftCompatibility51"} // FORCE-LOAD-DAG: !{!"-lswiftCompatibilityDynamicReplacements"} // FORCE-LOAD-DAG: !{!"-lswiftCompatibilityConcurrency"} // FORCE-LOAD-DAG: !llvm.linker.options = !{{{.*}}[[AUTOLINK_SWIFT_COMPAT]]{{[,}]}} // FORCE-LOAD-51-NOT: @"_swift_FORCE_LOAD_$_swiftCompatibility50" // FORCE-LOAD-51-NOT: @"_swift_FORCE_LOAD_$_swiftCompatibilityDynamicReplacements" // FORCE-LOAD-51-DAG: declare {{.*}} @"_swift_FORCE_LOAD_$_swiftCompatibility51" // FORCE-LOAD-51-DAG: declare {{.*}} @"_swift_FORCE_LOAD_$_swiftCompatibilityConcurrency" // FORCE-LOAD-51-NOT: @"_swift_FORCE_LOAD_$_swiftCompatibility50" // FORCE-LOAD-51-NOT: @"_swift_FORCE_LOAD_$_swiftCompatibilityDynamicReplacements" // FORCE-LOAD-51-DAG: [[AUTOLINK_SWIFT_COMPAT:![0-9]+]] = !{!"-lswiftCompatibility51"} // FORCE-LOAD-51-DAG: [[AUTOLINK_SWIFT_COMPAT_CONCURRENCY:![0-9]+]] = !{!"-lswiftCompatibilityConcurrency"} // FORCE-LOAD-51-DAG: !llvm.linker.options = !{{{.*}}[[AUTOLINK_SWIFT_COMPAT]], {{.*}}[[AUTOLINK_SWIFT_COMPAT_CONCURRENCY]]{{[,}]}} // FORCE-LOAD-51-NOT: @"_swift_FORCE_LOAD_$_swiftCompatibility50" // FORCE-LOAD-51-NOT: @"_swift_FORCE_LOAD_$_swiftCompatibilityDynamicReplacements" // FORCE-LOAD-55-NOT: @"_swift_FORCE_LOAD_$_swiftCompatibility50" // FORCE-LOAD-55-NOT: @"_swift_FORCE_LOAD_$_swiftCompatibilityDynamicReplacements" // FORCE-LOAD-55-NOT: @"_swift_FORCE_LOAD_$_swiftCompatibility51" // FORCE-LOAD-55-DAG: declare {{.*}} @"_swift_FORCE_LOAD_$_swiftCompatibilityConcurrency" // FORCE-LOAD-55-NOT: @"_swift_FORCE_LOAD_$_swiftCompatibility50" // FORCE-LOAD-55-NOT: @"_swift_FORCE_LOAD_$_swiftCompatibilityDynamicReplacements" // FORCE-LOAD-55-NOT: @"_swift_FORCE_LOAD_$_swiftCompatibility51" // FORCE-LOAD-55-DAG: [[AUTOLINK_SWIFT_COMPAT_CONCURRENCY:![0-9]+]] = !{!"-lswiftCompatibilityConcurrency"} // FORCE-LOAD-55-DAG: !llvm.linker.options = !{{{.*}}[[AUTOLINK_SWIFT_COMPAT_CONCURRENCY]]{{[,}]}} // FORCE-LOAD-55-NOT: @"_swift_FORCE_LOAD_$_swiftCompatibility50" // FORCE-LOAD-55-NOT: @"_swift_FORCE_LOAD_$_swiftCompatibilityDynamicReplacements" // FORCE-LOAD-55-NOT: @"_swift_FORCE_LOAD_$_swiftCompatibility51"
apache-2.0
c6129711e3e892687ae7b6ad38c8f0b4
78.96875
299
0.739547
3.627215
false
false
false
false
kokuyoku82/NumSwift
NumSwift/Source/Arithmetics/MatrixUtils.swift
2
3198
// // Dear maintainer: // // When I wrote this code, only I and God // know what it was. // Now, only God knows! // // So if you are done trying to 'optimize' // this routine (and failed), // please increment the following counter // as warning to the next guy: // // var TotalHoursWastedHere = 0 // // Reference: http://stackoverflow.com/questions/184618/what-is-the-best-comment-in-source-code-you-have-ever-encountered // import Accelerate public func mean<Element:Field>(of matrices:[Matrix<Element>]) -> Matrix<Element> { var meanMatrix = Matrix<Element>.Zeros(like: matrices[0]) for index in 0..<matrices.count { meanMatrix = meanMatrix + matrices[index] } meanMatrix = meanMatrix * Element(1.0/Double(matrices.count)) return meanMatrix } public func mean<Element:Field>(of matrix:Matrix<Element>) -> Element { var result = [Element(0)] switch matrix.dtype { case is Double.Type: let ptrResult = UnsafeMutablePointer<Double>(result) let ptrData = UnsafePointer<Double>(matrix.data) vDSP_meanvD(ptrData, 1, ptrResult, UInt(matrix.count)) case is Float.Type: let ptrResult = UnsafeMutablePointer<Float>(result) let ptrData = UnsafePointer<Float>(matrix.data) vDSP_meanv(ptrData, 1, ptrResult, UInt(matrix.count)) default: break } return result[0] } public func transpose<Element:Field>(matrix:Matrix<Element>) -> Matrix<Element> { let newData = [Element](count:matrix.count, repeatedValue:Element(0)) switch matrix.dtype { case is Double.Type: let ptrData = UnsafePointer<Double>(matrix.data) let ptrNewData = UnsafeMutablePointer<Double>(newData) vDSP_mtransD(ptrData, 1, ptrNewData, 1, UInt(matrix.cols), UInt(matrix.rows)) case is Float.Type: let ptrData = UnsafePointer<Float>(matrix.data) let ptrNewData = UnsafeMutablePointer<Float>(newData) vDSP_mtrans(ptrData, 1, ptrNewData, 1, UInt(matrix.cols), UInt(matrix.rows)) default: break } return Matrix<Element>(data:newData, rows:matrix.cols, cols:matrix.rows)! } // TODO: implement other norm type. public func norm<Element:Field>(matrix: Matrix<Element>, normType:MatrixNormType = .NormL2) -> Element { let matrixNorm:Element switch (matrix.dtype, normType) { case (is Double.Type, .NormL2): let ptrData = UnsafePointer<Double>(matrix.data) var dataSquare = [Double](count:matrix.count, repeatedValue:0) vDSP_vsqD(ptrData, 1, &dataSquare, 1, UInt(matrix.count)) matrixNorm = Element(sqrt(dataSquare.reduce(0){ $0 + $1 })) case (is Float.Type, .NormL2): let ptrData = UnsafePointer<Float>(matrix.data) var dataSquare = [Float](count:matrix.count, repeatedValue:0) vDSP_vsq(ptrData, 1, &dataSquare, 1, UInt(matrix.count)) matrixNorm = Element(sqrt(dataSquare.reduce(0){ $0 + $1 })) default: matrixNorm = Element(0) } return matrixNorm } // TODO: matrix inverse. public func inv<Element:Field>(matrix:Matrix<Element>) -> Matrix<Element> { return Matrix<Element>.Zeros(2, 2) }
mit
5fdcb4427af411621d59827d81552305
31.642857
121
0.66354
3.688581
false
false
false
false
tavultesoft/keymanweb
ios/engine/KMEI/KeymanEngine/Classes/Resource Management/KeyboardSearchViewController.swift
1
11044
// // KeyboardSearchViewController.swift // KeymanEngine // // Created by Joshua Horton on 7/21/20. // Copyright © 2020 SIL International. All rights reserved. // import UIKit import WebKit /* * Minor design notes: * * This class is designed for use as a 'library component' of KeymanEngine that apps may choose * whether or not to utilize. It simply returns the specifications of any packages/resources * to download, leaving control of their actual installation up to KeymanEngine's host app. */ /** * Loads a WebView to Keyman's online keyboard search. This WebView will intercept any package download links * and return the specifications of such interceptions - the search results - to the instance's owner via a closure specified * during initialization. */ public class KeyboardSearchViewController: UIViewController, WKNavigationDelegate { public enum SearchDownloadResult { case success(KeymanPackage, AnyLanguageResourceFullID) case cancelled case error(Error?) } public enum SearchResult<FullID: LanguageResourceFullID> { /** * Indicates that the user cancelled the search. */ case cancelled /** * Indicates that a package has been selected for download, but we don't know what language * they wish to use it for. This case will never be specified for the lexical-model selection closure. * * Once a target language has been identified, call the third parameter's closure to start a search * for associated lexical models (or to indicate that none should occur). Otherwise, the lexical model * search closure provided to the keyboard search will never evaluate. */ case untagged(KeymanPackage.Key, URL) /** * Indicates that a package has been selected for download and is already associated with a * language tag. */ case tagged(KeymanPackage.Key, URL, FullID) } // Useful documentation regarding certain implementation details: // https://docs.google.com/document/d/1rhgMeJlCdXCi6ohPb_CuyZd0PZMoSzMqGpv1A8cMFHY/edit /** * Parameters: * 1. The unique package identifier for the selected package. If nil, the user 'cancelled' and intends for nothing to be installed. * 2. The Keyman cloud URL from which that package may be downloaded. Will be nil if and only if the first parameter is nil. * 3. The unique identifier for the resource WITHIN that package to install. Useful when a package's resource(s) support multiple languages. */ public typealias SelectionCompletedHandler<FullID: LanguageResourceFullID> = (SearchResult<FullID>) -> Void public typealias SearchDownloadHandler<FullID: LanguageResourceFullID> = (SearchDownloadResult) -> Void private var hasFinalized = false private let keyboardSelectionClosure: SelectionCompletedHandler<FullKeyboardID>! private let languageCode: String? private let session: URLSession private var progressView: UIProgressView? private var observation: NSKeyValueObservation? = nil private static var ENDPOINT_ROOT: URL { var baseURL = KeymanHosts.KEYMAN_COM baseURL.appendPathComponent("go") baseURL.appendPathComponent("ios") // platform // API endpoint only supports major.minor, will break if `.build` is also present baseURL.appendPathComponent(Version.current.majorMinor.description) baseURL.appendPathComponent("download-keyboards") return baseURL } public init(languageCode: String? = nil, withSession session: URLSession = URLSession.shared, keyboardSelectionBlock: @escaping SelectionCompletedHandler<FullKeyboardID>) { self.languageCode = languageCode self.session = session self.keyboardSelectionClosure = keyboardSelectionBlock super.init(nibName: nil, bundle: nil) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } deinit { observation = nil } public override func loadView() { let webView = WKWebView() webView.navigationDelegate = self if let languageCode = languageCode { let baseURL = KeyboardSearchViewController.ENDPOINT_ROOT let specificURL = URL.init(string: "\(baseURL)?q=l:id:\(languageCode)")! webView.load(URLRequest(url: specificURL)) } else { webView.load(URLRequest(url: KeyboardSearchViewController.ENDPOINT_ROOT)) } progressView = UIProgressView(progressViewStyle: .bar) progressView!.translatesAutoresizingMaskIntoConstraints = false observation = webView.observe(\.estimatedProgress) { _, _ in if let progressView = self.progressView { progressView.setProgress(Float(webView.estimatedProgress), animated: true) progressView.isHidden = progressView.progress > 0.99 } } progressView!.setProgress(1, animated: false) progressView!.isHidden = true webView.addSubview(progressView!) view = webView } // Used to intercept download links. public func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) { if navigationAction.navigationType == .linkActivated { let link = navigationAction.request.url! if let parsedLink = UniversalLinks.tryParseKeyboardInstallLink(link) { decisionHandler(.cancel) // Notify our caller of the search results. self.hasFinalized = true // Prevent popViewController from triggering cancellation events. self.navigationController?.popViewController(animated: true) // Rewind UI finalize(with: parsedLink) return } else if UniversalLinks.isExternalLink(link) { decisionHandler(.cancel) // Kick this link out to an external Safari process. UniversalLinks.externalLinkLauncher?(link) return } } decisionHandler(.allow) // Makes it clear that there IS a progress bar, in case of super-slow response. progressView?.setProgress(0, animated: false) // This way, if the load is instant, the 0.01 doesn't really stand out. progressView?.setProgress(0.01, animated: true) progressView?.isHidden = false } private func failWithAlert(for error: Error) { let errorTitle = NSLocalizedString("alert-no-connection-title", bundle: engineBundle, comment: "") let alert = ResourceFileManager.shared.buildSimpleAlert(title: errorTitle, message: error.localizedDescription) { // If we are in a UINavigationViewController and are not its root view... if let navVC = self.navigationController, navVC.viewControllers.first != self { navVC.popViewController(animated: true) } else { self.dismiss(animated: true) } } self.present(alert, animated: true) } public func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) { failWithAlert(for: error) } public func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) { failWithAlert(for: error) } override public func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) if let navVC = self.navigationController { progressView?.topAnchor.constraint(equalTo: navVC.navigationBar.bottomAnchor).isActive = true } else { progressView?.topAnchor.constraint(equalTo: self.view.topAnchor).isActive = true } progressView?.widthAnchor.constraint(equalTo: self.view.widthAnchor).isActive = true progressView?.leftAnchor.constraint(equalTo: self.view.leftAnchor).isActive = true } override public func viewWillDisappear(_ animated: Bool) { // If the view is being dismissed but no matching link has been intercepted... if self.isMovingFromParent, !hasFinalized { self.keyboardSelectionClosure(.cancelled) } } internal func finalize(with parsedLink: UniversalLinks.ParsedKeyboardInstallLink) { let packageKey = KeymanPackage.Key(id: parsedLink.keyboard_id, type: .keyboard) // If we have a language ID AND do not yet have a model for it. if let lang_id = parsedLink.lang_id { let resourceKey = FullKeyboardID(keyboardID: parsedLink.keyboard_id, languageID: lang_id) let kbdURL = ResourceDownloadManager.shared.defaultDownloadURL(forPackage: packageKey, andResource: resourceKey, asUpdate: false) self.keyboardSelectionClosure(.tagged(packageKey, kbdURL, resourceKey)) } else { let kbdURL = ResourceDownloadManager.shared.defaultDownloadURL(forPackage: packageKey, asUpdate: false) self.keyboardSelectionClosure(.untagged(packageKey, kbdURL)) } } public static func defaultDownloadClosure(downloadCompletionBlock: @escaping SearchDownloadHandler<FullKeyboardID>) -> SelectionCompletedHandler<FullKeyboardID> { return defaultDownloadClosure(withDownloadManager: ResourceDownloadManager.shared, downloadCompletionBlock: downloadCompletionBlock) } // For unit testing. internal static func defaultDownloadClosure(withDownloadManager downloadManager: ResourceDownloadManager, downloadCompletionBlock: @escaping SearchDownloadHandler<FullKeyboardID>) -> SelectionCompletedHandler<FullKeyboardID> { return { searchResult in var packageKey: KeymanPackage.Key var packageURL: URL switch searchResult { case .cancelled: downloadCompletionBlock(.cancelled) return case .untagged(let key, let url): packageKey = key packageURL = url case .tagged(let key, let url, _): packageKey = key packageURL = url } let downloadClosure: ResourceDownloadManager.CompletionHandler<KeyboardKeymanPackage> = { package, error in guard let package = package, error == nil else { downloadCompletionBlock(.error(error)) return } switch searchResult { case .untagged(_, _): let resourceKey = package.installables.first!.first!.fullID downloadCompletionBlock(.success(package, resourceKey)) case .tagged(_, _, let resourceKey): downloadCompletionBlock(.success(package, resourceKey)) default: // Illegal state - we already checked this. fatalError() } // We've likely installed the package, and we already know // the package's current publishing state - we literally just // downloaded it from the cloud as part of the keyboard search. // // Why query later when we know the query's answer NOW? let publishState = KeymanPackage.DistributionStateMetadata(downloadURL: packageURL, version: package.version) Storage.active.userDefaults.cachedPackageQueryMetadata[package.key] = publishState } downloadManager.downloadPackage(withKey: packageKey, from: packageURL, withNotifications: true, completionBlock: downloadClosure) } } }
apache-2.0
980794ba8b15459c9da4ec3fdf8bb20e
39.749077
166
0.715838
4.881963
false
false
false
false
ludagoo/Perfect
Examples/Tap Tracker/Tap Tracker Server/TTHandlers.swift
2
5470
// // TTHandlers.swift // Tap Tracker // // Created by Kyle Jessup on 2015-10-23. // Copyright (C) 2015 PerfectlySoft, Inc. // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as // published by the Free Software Foundation, either version 3 of the // License, or (at your option) any later version, as supplemented by the // Perfect Additional Terms. // // 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 Affero General Public License, as supplemented by the // Perfect Additional Terms, for more details. // // You should have received a copy of the GNU Affero General Public License // and the Perfect Additional Terms that immediately follow the terms and // conditions of the GNU Affero General Public License along with this // program. If not, see <http://www.perfect.org/AGPL_3_0_With_Perfect_Additional_Terms.txt>. // import PerfectLib // This is the function which all Perfect Server modules must expose. // The system will load the module and call this function. // In here, register any handlers or perform any one-time tasks. public func PerfectServerModuleInit() { // Register our handler class with the PageHandlerRegistry. // The name "TTHandler", which we supply here, is used within a mustache template to associate the template with the handler. PageHandlerRegistry.addPageHandler("TTHandler") { // This closure is called in order to create the handler object. // It is called once for each relevant request. // The supplied WebResponse object can be used to tailor the return value. // However, all request processing should take place in the `valuesForResponse` function. (r:WebResponse) -> PageHandler in return TTHandler() } // Create our SQLite tracking database. do { let sqlite = try SQLite(TTHandler.trackerDbPath) try sqlite.execute("CREATE TABLE IF NOT EXISTS taps (id INTEGER PRIMARY KEY, time REAL, lat REAL, long REAL)") } catch { print("Failure creating tracker database at " + TTHandler.trackerDbPath) } } // Handler class // When referenced in a mustache template, this class will be instantiated to handle the request // and provide a set of values which will be used to complete the template. class TTHandler: PageHandler { // all template handlers must inherit from PageHandler static var trackerDbPath: String { // Full path to the SQLite database in which we store our tracking data. let dbPath = PerfectServer.staticPerfectServer.homeDir() + serverSQLiteDBs + "TapTrackerDb" return dbPath } // This is the function which all handlers must impliment. // It is called by the system to allow the handler to return the set of values which will be used when populating the template. // - parameter context: The MustacheEvaluationContext which provides access to the WebRequest containing all the information pertaining to the request // - parameter collector: The MustacheEvaluationOutputCollector which can be used to adjust the template output. For example a `defaultEncodingFunc` could be installed to change how outgoing values are encoded. func valuesForResponse(context: MustacheEvaluationContext, collector: MustacheEvaluationOutputCollector) throws -> MustacheEvaluationContext.MapType { // The dictionary which we will return var values = MustacheEvaluationContext.MapType() print("TTHandler got request") // Grab the WebRequest if let request = context.webRequest { // Try to get the last tap instance from the database let sqlite = try SQLite(TTHandler.trackerDbPath) defer { sqlite.close() } // Select most recent // If there are no existing taps, we'll just return the current one var gotTap = false try sqlite.forEachRow("SELECT time, lat, long FROM taps ORDER BY time DESC LIMIT 1") { (stmt:SQLiteStmt, i:Int) -> () in // We got a result row // Pull out the values and place them in the resulting values dictionary let time = stmt.columnDouble(0) let lat = stmt.columnDouble(1) let long = stmt.columnDouble(2) do { let timeStr = try ICU.formatDate(time, format: "yyyy-MM-d hh:mm aaa") let resultSets: [[String:Any]] = [["time": timeStr, "lat":lat, "long":long, "last":true]] values["resultSets"] = resultSets } catch { } gotTap = true } // If the user is posting a new tap for tracking purposes... if request.requestMethod() == "POST" { // Adding a new ta[ instance if let lat = request.param("lat"), let long = request.param("long") { let time = ICU.getNow() try sqlite.doWithTransaction { // Insert the new row try sqlite.execute("INSERT INTO taps (time,lat,long) VALUES (?,?,?)", doBindings: { (stmt:SQLiteStmt) -> () in try stmt.bind(1, time) try stmt.bind(2, lat) try stmt.bind(3, long) }) } // As a fallback, for demo purposes, if there were no rows then just return the current values if !gotTap { let timeStr = try ICU.formatDate(time, format: "yyyy-MM-d hh:mm aaa") let resultSets: [[String:Any]] = [["time": timeStr, "lat":lat, "long":long, "last":true]] values["resultSets"] = resultSets } } } } // Return the values // These will be used to populate the template return values } }
agpl-3.0
e40b9a5943c58139811c6c3cfdc8ffab
37.251748
211
0.717185
3.907143
false
false
false
false
GuiBayma/PasswordVault
PasswordVault/Scenes/Add Item/AddItemViewController.swift
1
3375
// // AddItemViewController.swift // PasswordVault // // Created by Guilherme Bayma on 7/31/17. // Copyright © 2017 Bayma. All rights reserved. // import UIKit class AddItemViewController: UIViewController, UITextFieldDelegate { // MARK: - Variables fileprivate let addItemView = AddItemView() fileprivate var textFields: [UITextField] = [] weak var delegate: NewDataDelegate? var group: Group? // MARK: - Initializing required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) } override func loadView() { self.view = addItemView } // MARK: - View lifecycle override func viewDidLoad() { super.viewDidLoad() self.navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .cancel, target: self, action: #selector(self.cancelPressed(_:))) addItemView.buttonAction = donePressed setUpTextFields() startInput() } // MARK: - Bar button items func cancelPressed(_ sender: UIBarButtonItem) { dismiss(animated: true) {} } // MARK: - Text Fields func setUpTextFields() { textFields.append(addItemView.nameLabeledTextField.textField) textFields.append(addItemView.userLabeledTextField.textField) textFields.append(addItemView.passwordLabeledTextField.textField) for field in textFields { field.delegate = self } } // MARK: - Input func startInput() { textFields.first?.becomeFirstResponder() } // MARK: - Text Field Delegate func textFieldShouldReturn(_ textField: UITextField) -> Bool { textField.resignFirstResponder() if let index = textFields.index(of: textField) { if index < textFields.count - 1 { let nextTextField = textFields[index + 1] nextTextField.becomeFirstResponder() } else { saveNewItemAndDismiss() } } return true } // MARK: - Button action func donePressed() { for field in textFields { field.resignFirstResponder() } saveNewItemAndDismiss() } // MARK: - Save new Item func saveNewItemAndDismiss() { guard let name = textFields[0].text, let user = textFields[1].text, let pwd = textFields[2].text else { fatalError("\(String(describing: type(of: self))): Error retrieving text from textfield") } if name == "" { dismiss(animated: true) {} } else { let newItem = ItemManager.sharedInstance.newItem() newItem?.name = name newItem?.userName = user newItem?.password = pwd if let item = newItem { group?.addItem(item) _ = ItemManager.sharedInstance.save() delegate?.addNewDataAndDismiss(self, data: item) } else { dismiss(animated: true) {} } } } }
mit
feed9b7aecb7787653fc84f30e7ca6fe
26.430894
106
0.572318
5.305031
false
false
false
false
blackspotbear/MMDViewer
MMDViewer/RigidBody.swift
1
1254
import Foundation import GLKit class RigidBody: NSObject { var name: String var nameE: String @objc var boneIndex: Int @objc var groupID: UInt8 @objc var groupFlag: UInt16 @objc var shapeType: UInt8 @objc var size: GLKVector3 @objc var pos: GLKVector3 @objc var rot: GLKVector3 @objc var mass: Float @objc var linearDamping: Float @objc var angularDamping: Float @objc var restitution: Float @objc var friction: Float @objc var type: UInt8 init(name: String, nameE: String, boneIndex: Int, groupID: UInt8, groupFlag: UInt16, shapeType: UInt8, size: GLKVector3, pos: GLKVector3, rot: GLKVector3, mass: Float, linearDamping: Float, angularDamping: Float, restitution: Float, friction: Float, type: UInt8) { self.name = name self.nameE = nameE self.boneIndex = boneIndex self.groupID = groupID self.groupFlag = groupFlag self.shapeType = shapeType self.size = size self.pos = pos self.rot = rot self.mass = mass self.linearDamping = linearDamping self.angularDamping = angularDamping self.restitution = restitution self.friction = friction self.type = type } }
mit
7d007926a1dee3a494f7f4d50984e8b9
27.5
268
0.653907
4.058252
false
false
false
false
waterskier2007/NVActivityIndicatorView
NVActivityIndicatorView/Animations/NVActivityIndicatorAnimationBallClipRotate.swift
1
3138
// // NVActivityIndicatorBallClipRotate.swift // NVActivityIndicatorViewDemo // // The MIT License (MIT) // Copyright (c) 2016 Vinh Nguyen // 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 NVActivityIndicatorAnimationBallClipRotate: NVActivityIndicatorAnimationDelegate { func setUpAnimation(in layer: CALayer, size: CGSize, color: UIColor) { let duration: CFTimeInterval = 0.75 // Scale animation let scaleAnimation = CAKeyframeAnimation(keyPath: "transform.scale") scaleAnimation.keyTimes = [0, 0.5, 1] scaleAnimation.values = [1, 0.6, 1] // Rotate animation let rotateAnimation = CAKeyframeAnimation(keyPath: "transform.rotation.z") rotateAnimation.keyTimes = scaleAnimation.keyTimes rotateAnimation.values = [0, CGFloat.pi, 2 * CGFloat.pi] // Animation let animation = CAAnimationGroup() animation.animations = [scaleAnimation, rotateAnimation] animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear) animation.duration = duration animation.repeatCount = HUGE animation.isRemovedOnCompletion = false // Draw circle <<<<<<< HEAD let circle = NVActivityIndicatorShape.RingThirdFour.createLayerWith(size: CGSize(width: size.width, height: size.height), color: color) let frame = CGRect(x: (layer.bounds.width - size.width) / 2, y: (layer.bounds.height - size.height) / 2, width: size.width, height: size.height) ======= let circle = NVActivityIndicatorShape.ringThirdFour.layerWith(size: CGSize(width: size.width, height: size.height), color: color) let frame = CGRect(x: (layer.bounds.size.width - size.width) / 2, y: (layer.bounds.size.height - size.height) / 2, width: size.width, height: size.height) >>>>>>> ninjaprox/master circle.frame = frame circle.add(animation, forKey: "animation") layer.addSublayer(circle) } }
mit
4c5299a2d02c8ea9682409b69a71bc18
40.289474
143
0.688337
4.733032
false
false
false
false
frankcjw/CJWUtilsS
CJWUtilsS/QPLib/Lib/DVR/SessionUploadTask.swift
1
774
class SessionUploadTask: NSURLSessionUploadTask { // MARK: - Types typealias Completion = (NSData?, NSURLResponse?, NSError?) -> Void // MARK: - Properties weak var session: Session! let request: NSURLRequest let completion: Completion? let dataTask: SessionDataTask // MARK: - Initializers init(session: Session, request: NSURLRequest, completion: Completion? = nil) { self.session = session self.request = request self.completion = completion dataTask = SessionDataTask(session: session, request: request, completion: completion) } // MARK: - NSURLSessionTask override func cancel() { // Don't do anything } override func resume() { dataTask.resume() } }
mit
9b48edf57138497383446751b8090dfb
23.1875
94
0.644703
5.025974
false
false
false
false
cuappdev/podcast-ios
Recast/Cells/HomePodcastGridCollectionViewCell.swift
1
1424
// // SeriesGridTableViewCell.swift // Recast // // Created by Jaewon Sim on 9/22/18. // Copyright © 2018 Cornell AppDev. All rights reserved. // import UIKit // swiftlint:disable:next type_name class HomePodcastGridCollectionViewCell: UICollectionViewCell { // MARK: View vars var collectionView: UICollectionView! // MARK: CV reuse identifier private let seriesGridReuse = "gridCvReuse" // MARK: Lifecycle override init(frame: CGRect) { super.init(frame: frame) //collection view layout constants let collectionViewMinimumInteritemSpacing = CGFloat(12) //setup flow layout using layout constants above let layout = UICollectionViewFlowLayout() layout.minimumInteritemSpacing = collectionViewMinimumInteritemSpacing layout.scrollDirection = .horizontal collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout) collectionView.register(PodcastGridCollectionViewCell.self, forCellWithReuseIdentifier: seriesGridReuse) contentView.addSubview(collectionView) setUpConstraints() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: Constraint setup private func setUpConstraints() { collectionView.snp.makeConstraints { make in make.edges.equalTo(contentView) } } }
mit
e88aec323e536553eef1b0af4c3105c5
28.040816
112
0.703443
5.155797
false
false
false
false
natecook1000/swift
test/Inputs/clang-importer-sdk/swift-modules/Foundation.swift
2
9111
@_exported import ObjectiveC @_exported import CoreGraphics @_exported import Foundation public let NSUTF8StringEncoding: UInt = 8 extension AnyHashable : _ObjectiveCBridgeable { public func _bridgeToObjectiveC() -> NSObject { return NSObject() } public static func _forceBridgeFromObjectiveC(_ x: NSObject, result: inout AnyHashable?) { } public static func _conditionallyBridgeFromObjectiveC( _ x: NSObject, result: inout AnyHashable? ) -> Bool { return true } public static func _unconditionallyBridgeFromObjectiveC(_ x: NSObject?) -> AnyHashable { return AnyHashable("") } } extension String : _ObjectiveCBridgeable { public func _bridgeToObjectiveC() -> NSString { return NSString() } public static func _forceBridgeFromObjectiveC(_ x: NSString, result: inout String?) { } public static func _conditionallyBridgeFromObjectiveC( _ x: NSString, result: inout String? ) -> Bool { return true } public static func _unconditionallyBridgeFromObjectiveC(_ x: NSString?) -> String { return String() } } extension Int : _ObjectiveCBridgeable { public func _bridgeToObjectiveC() -> NSNumber { return NSNumber() } public static func _forceBridgeFromObjectiveC( _ x: NSNumber, result: inout Int? ) { } public static func _conditionallyBridgeFromObjectiveC( _ x: NSNumber, result: inout Int? ) -> Bool { return true } public static func _unconditionallyBridgeFromObjectiveC( _ x: NSNumber? ) -> Int { return 0 } } extension Bool: _ObjectiveCBridgeable { public func _bridgeToObjectiveC() -> NSNumber { return NSNumber() } public static func _forceBridgeFromObjectiveC( _ x: NSNumber, result: inout Bool? ) { } public static func _conditionallyBridgeFromObjectiveC( _ x: NSNumber, result: inout Bool? ) -> Bool { return true } public static func _unconditionallyBridgeFromObjectiveC( _ x: NSNumber? ) -> Bool { return false } } extension Array : _ObjectiveCBridgeable { public func _bridgeToObjectiveC() -> NSArray { return NSArray() } public static func _forceBridgeFromObjectiveC( _ x: NSArray, result: inout Array? ) { } public static func _conditionallyBridgeFromObjectiveC( _ x: NSArray, result: inout Array? ) -> Bool { return true } public static func _unconditionallyBridgeFromObjectiveC( _ x: NSArray? ) -> Array { return Array() } } extension Dictionary : _ObjectiveCBridgeable { public func _bridgeToObjectiveC() -> NSDictionary { return NSDictionary() } public static func _forceBridgeFromObjectiveC( _ x: NSDictionary, result: inout Dictionary? ) { } public static func _conditionallyBridgeFromObjectiveC( _ x: NSDictionary, result: inout Dictionary? ) -> Bool { return true } public static func _unconditionallyBridgeFromObjectiveC( _ x: NSDictionary? ) -> Dictionary { return Dictionary() } } extension Set : _ObjectiveCBridgeable { public func _bridgeToObjectiveC() -> NSSet { return NSSet() } public static func _forceBridgeFromObjectiveC( _ x: NSSet, result: inout Set? ) { } public static func _conditionallyBridgeFromObjectiveC( _ x: NSSet, result: inout Set? ) -> Bool { return true } public static func _unconditionallyBridgeFromObjectiveC( _ x: NSSet? ) -> Set { return Set() } } extension CGFloat : _ObjectiveCBridgeable { public func _bridgeToObjectiveC() -> NSNumber { return NSNumber() } public static func _forceBridgeFromObjectiveC( _ x: NSNumber, result: inout CGFloat? ) { } public static func _conditionallyBridgeFromObjectiveC( _ x: NSNumber, result: inout CGFloat? ) -> Bool { return true } public static func _unconditionallyBridgeFromObjectiveC( _ x: NSNumber? ) -> CGFloat { return CGFloat() } } extension NSRange : _ObjectiveCBridgeable { public func _bridgeToObjectiveC() -> NSValue { return NSValue() } public static func _forceBridgeFromObjectiveC( _ x: NSValue, result: inout NSRange? ) { result = x.rangeValue } public static func _conditionallyBridgeFromObjectiveC( _ x: NSValue, result: inout NSRange? ) -> Bool { self._forceBridgeFromObjectiveC(x, result: &result) return true } public static func _unconditionallyBridgeFromObjectiveC( _ x: NSValue? ) -> NSRange { return NSRange() } } public struct URL : _ObjectiveCBridgeable { public init() { } public init?(string: String) { return nil } public func _bridgeToObjectiveC() -> NSURL { return NSURL() } public static func _forceBridgeFromObjectiveC(_ x: NSURL, result: inout URL?) { } public static func _conditionallyBridgeFromObjectiveC( _ x: NSURL, result: inout URL? ) -> Bool { return true } public static func _unconditionallyBridgeFromObjectiveC(_ x: NSURL?) -> URL { return URL() } } extension NSError : Error { public var _domain: String { return domain } public var _code: Int { return code } } internal enum _GenericObjCError : Error { case nilError } public func _convertNSErrorToError(_ error: NSError?) -> Error { if let error = error { return error } return _GenericObjCError.nilError } public func _convertErrorToNSError(_ x: Error) -> NSError { return x as NSError } extension _SwiftNewtypeWrapper where Self.RawValue == Error { @inlinable // FIXME(sil-serialize-all) public func _bridgeToObjectiveC() -> NSError { return rawValue as NSError } @inlinable // FIXME(sil-serialize-all) public static func _forceBridgeFromObjectiveC( _ source: NSError, result: inout Self? ) { result = Self(rawValue: source) } @inlinable // FIXME(sil-serialize-all) public static func _conditionallyBridgeFromObjectiveC( _ source: NSError, result: inout Self? ) -> Bool { result = Self(rawValue: source) return result != nil } @inlinable // FIXME(sil-serialize-all) public static func _unconditionallyBridgeFromObjectiveC( _ source: NSError? ) -> Self { return Self(rawValue: _convertNSErrorToError(source))! } } extension NSArray { @objc(methodIntroducedInOverlay) public func introducedInOverlay() { } } /// An internal protocol to represent Swift error enums that map to standard /// Cocoa NSError domains. public protocol _ObjectiveCBridgeableError : Error { /// Produce a value of the error type corresponding to the given NSError, /// or return nil if it cannot be bridged. init?(_bridgedNSError: NSError) } /// Describes a bridged error that stores the underlying NSError, so /// it can be queried. public protocol _BridgedStoredNSError : _ObjectiveCBridgeableError { /// The type of an error code. associatedtype Code: _ErrorCodeProtocol /// The error code for the given error. var code: Code { get } //// Retrieves the embedded NSError. var _nsError: NSError { get } /// Create a new instance of the error type with the given embedded /// NSError. /// /// The \c error must have the appropriate domain for this error /// type. init(_nsError error: NSError) } public protocol _ErrorCodeProtocol { /// The corresponding error code. associatedtype _ErrorType } public extension _BridgedStoredNSError { public init?(_bridgedNSError error: NSError) { self.init(_nsError: error) } } /// Various helper implementations for _BridgedStoredNSError public extension _BridgedStoredNSError where Code: RawRepresentable, Code.RawValue: SignedInteger { // FIXME: Generalize to Integer. public var code: Code { return Code(rawValue: numericCast(_nsError.code))! } /// Initialize an error within this domain with the given ``code`` /// and ``userInfo``. public init(_ code: Code, userInfo: [String : Any] = [:]) { self.init(_nsError: NSError(domain: "", code: 0, userInfo: [:])) } /// The user-info dictionary for an error that was bridged from /// NSError. var userInfo: [String : Any] { return [:] } } /// Various helper implementations for _BridgedStoredNSError public extension _BridgedStoredNSError where Code: RawRepresentable, Code.RawValue: UnsignedInteger { // FIXME: Generalize to Integer. public var code: Code { return Code(rawValue: numericCast(_nsError.code))! } /// Initialize an error within this domain with the given ``code`` /// and ``userInfo``. public init(_ code: Code, userInfo: [String : Any] = [:]) { self.init(_nsError: NSError(domain: "", code: 0, userInfo: [:])) } } extension NSDictionary { @objc public subscript(_: Any) -> Any? { @objc(_swift_objectForKeyedSubscript:) get { fatalError() } } public func nonObjCExtensionMethod<T>(_: T) {} } extension NSMutableDictionary { public override subscript(_: Any) -> Any? { get { fatalError() } @objc(_swift_setObject:forKeyedSubscript:) set { } } }
apache-2.0
020f6049605cd36d4ecf0536782385f4
23.758152
90
0.672045
4.641365
false
false
false
false
qoncept/TensorSwift
Tests/TensorSwiftTests/CalculationPerformanceTests.swift
1
2122
import XCTest @testable import TensorSwift private func getTensor1000x1000() -> Tensor { let elements = [Float](repeating: 0.1 ,count: 1000*1000) return Tensor(shape: [1000, 1000], elements: elements) } private func getTensor1x1000() -> Tensor { let elements = [Float](repeating: 0, count: 1000) return Tensor(shape: [1, 1000], elements: elements) } class CalculationPerformanceTests : XCTestCase { func testElementAccess(){ let W = getTensor1000x1000() measure{ for _ in 0..<100000{ let _ = W[500,500] } } } func testElementAccessRaw(){ let W = getTensor1000x1000() measure{ for _ in 0..<100000{ let _ = W.elements[500*W.shape.dimensions[1].value + 500] } } } func testMultiplication(){ let W = getTensor1000x1000() let x = getTensor1x1000() measure{ let _ = x.matmul(W) } } func testMultiplicationRaw() { let W = getTensor1000x1000() let x = getTensor1x1000() measure{ let xRow = x.shape.dimensions[0].value let WRow = W.shape.dimensions[0].value let WColumn = W.shape.dimensions[1].value var elements = [Float](repeating: 0, count: 1000) for r in 0..<xRow { for i in 0..<WRow { let tmp = x.elements[r * WRow + i] for c in 0..<WColumn { elements[r * WRow + c] = tmp * W.elements[i * WRow + c] } } } let _ = Tensor(shape: [1,1000], elements: elements) } } static var allTests : [(String, (CalculationPerformanceTests) -> () throws -> Void)] { return [ ("testElementAccess", testElementAccess), ("testElementAccessRaw", testElementAccessRaw), ("testElementMultiplication", testMultiplication), ("testElementMultiplicationRaw", testMultiplicationRaw), ] } }
mit
83e2820400532019aaf5b8cc4de96874
28.887324
90
0.524034
4.218688
false
true
false
false
brentsimmons/Evergreen
Mac/MainWindow/Detail/DetailContainerView.swift
1
972
// // DetailContainerView.swift // NetNewsWire // // Created by Brent Simmons on 2/12/19. // Copyright © 2019 Ranchero Software. All rights reserved. // import AppKit final class DetailContainerView: NSView { @IBOutlet var detailStatusBarView: DetailStatusBarView! var contentViewConstraints: [NSLayoutConstraint]? var contentView: NSView? { didSet { if contentView == oldValue { return } if let currentConstraints = contentViewConstraints { NSLayoutConstraint.deactivate(currentConstraints) } contentViewConstraints = nil oldValue?.removeFromSuperviewWithoutNeedingDisplay() if let contentView = contentView { contentView.translatesAutoresizingMaskIntoConstraints = false addSubview(contentView, positioned: .below, relativeTo: detailStatusBarView) let constraints = constraintsToMakeSubViewFullSize(contentView) NSLayoutConstraint.activate(constraints) contentViewConstraints = constraints } } } }
mit
22407bbb64eddaa0eecf937299220364
24.552632
80
0.763131
4.601896
false
false
false
false
Czajnikowski/TrainTrippin
Pods/RxSwift/RxSwift/Observables/Implementations/ShareReplay1WhileConnected.swift
3
2568
// // ShareReplay1WhileConnected.swift // RxSwift // // Created by Krunoslav Zaher on 12/6/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // import Foundation // optimized version of share replay for most common case final class ShareReplay1WhileConnected<Element> : Observable<Element> , ObserverType , SynchronizedUnsubscribeType { typealias DisposeKey = Bag<AnyObserver<Element>>.KeyType private let _source: Observable<Element> private var _lock = NSRecursiveLock() private var _connection: SingleAssignmentDisposable? private var _element: Element? private var _observers = Bag<AnyObserver<Element>>() init(source: Observable<Element>) { self._source = source } override func subscribe<O : ObserverType>(_ observer: O) -> Disposable where O.E == E { _lock.lock(); defer { _lock.unlock() } return _synchronized_subscribe(observer) } func _synchronized_subscribe<O : ObserverType>(_ observer: O) -> Disposable where O.E == E { if let element = self._element { observer.on(.next(element)) } let initialCount = self._observers.count let disposeKey = self._observers.insert(AnyObserver(observer)) if initialCount == 0 { let connection = SingleAssignmentDisposable() _connection = connection connection.setDisposable(self._source.subscribe(self)) } return SubscriptionDisposable(owner: self, key: disposeKey) } func synchronizedUnsubscribe(_ disposeKey: DisposeKey) { _lock.lock(); defer { _lock.unlock() } _synchronized_unsubscribe(disposeKey) } func _synchronized_unsubscribe(_ disposeKey: DisposeKey) { // if already unsubscribed, just return if self._observers.removeKey(disposeKey) == nil { return } if _observers.count == 0 { _connection?.dispose() _connection = nil _element = nil } } func on(_ event: Event<E>) { _lock.lock(); defer { _lock.unlock() } _synchronized_on(event) } func _synchronized_on(_ event: Event<E>) { switch event { case .next(let element): _element = element _observers.on(event) case .error, .completed: _element = nil _connection?.dispose() _connection = nil let observers = _observers _observers = Bag() observers.on(event) } } }
mit
dab88fbd86aa9fcbafe1877134902934
26.902174
96
0.604597
4.701465
false
false
false
false
proxyco/RxBluetoothKit
Example/Example/ScansTableViewController.swift
1
5350
// // ScansTableViewController.swift // RxBluetoothKit // // Created by Kacper Harasim on 29.03.2016. // Copyright © 2016 CocoaPods. All rights reserved. // import UIKit import RxBluetoothKit import RxSwift import CoreBluetooth class ScansTableViewController: UIViewController { @IBOutlet weak var scansTableView: UITableView! private var isScanInProgress = false private var peripheralsArray: [ScannedPeripheral] = [] private var scheduler: ConcurrentDispatchQueueScheduler! private let manager = BluetoothManager(queue: dispatch_get_main_queue()) private var scanningDisposable: Disposable? private let scannedPeripheralCellIdentifier = "peripheralCellId" override func viewDidLoad() { super.viewDidLoad() splitViewController?.delegate = self let timerQueue = dispatch_queue_create("com.polidea.rxbluetoothkit.timer", nil) scheduler = ConcurrentDispatchQueueScheduler(queue: timerQueue) scansTableView.delegate = self scansTableView.dataSource = self scansTableView.estimatedRowHeight = 80.0 scansTableView.rowHeight = UITableViewAutomaticDimension } private func stopScanning() { scanningDisposable?.dispose() isScanInProgress = false self.title = "" } private func startScanning() { isScanInProgress = true self.title = "Scanning..." scanningDisposable = manager.rx_state .timeout(4.0, scheduler: scheduler) .take(1) .flatMap { _ in self.manager.scanForPeripherals(nil, options:nil) } .subscribeOn(MainScheduler.instance) .subscribe(onNext: { self.addNewScannedPeripheral($0) }, onError: { error in }) } private func addNewScannedPeripheral(peripheral: ScannedPeripheral) { let mapped = peripheralsArray.map { $0.peripheral } if let indx = mapped.indexOf(peripheral.peripheral) { peripheralsArray[indx] = peripheral } else { self.peripheralsArray.append(peripheral) } dispatch_async(dispatch_get_main_queue()) { self.scansTableView.reloadData() } } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { guard let identifier = segue.identifier, let cell = sender as? UITableViewCell where identifier == "PresentPeripheralDetails" else { return } guard let navigationVC = segue.destinationViewController as? UINavigationController, let peripheralDetails = navigationVC.topViewController as? PeripheralServicesViewController else { return } if let indexPath = scansTableView.indexPathForCell(cell) { peripheralDetails.scannedPeripheral = peripheralsArray[indexPath.row] peripheralDetails.manager = manager } } @IBAction func scanButtonClicked(sender: UIButton) { if isScanInProgress { stopScanning() sender.setTitle("Start scanning", forState: .Normal) } else { startScanning() sender.setTitle("Stop scanning", forState: .Normal) } } } extension ScansTableViewController: UITableViewDelegate, UITableViewDataSource { func tableView(tableView: UITableView, viewForFooterInSection section: Int) -> UIView? { return UIView(frame: .zero) } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return peripheralsArray.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier(scannedPeripheralCellIdentifier, forIndexPath: indexPath) let peripheral = peripheralsArray[indexPath.row] if let peripheralCell = cell as? ScannedPeripheralCell { peripheralCell.configureWithScannedPeripheral(peripheral) } return cell } } extension ScansTableViewController: UISplitViewControllerDelegate { func splitViewController(splitViewController: UISplitViewController, collapseSecondaryViewController secondaryViewController:UIViewController, ontoPrimaryViewController primaryViewController:UIViewController) -> Bool { //TODO: Check how this works on both devices. guard let secondaryAsNavController = secondaryViewController as? UINavigationController else { return false } guard let topAsDetailController = secondaryAsNavController.topViewController as? PeripheralServicesViewController else { return false } if topAsDetailController.scannedPeripheral == nil { // Return true to indicate that we have handled the collapse by doing nothing; the secondary controller will be discarded. return true } return false } } extension ScannedPeripheralCell { func configureWithScannedPeripheral(peripheral: ScannedPeripheral) { RSSILabel.text = peripheral.RSSI.stringValue peripheralNameLabel.text = peripheral.advertisementData.localName ?? peripheral.peripheral.identifier.UUIDString //TODO: Pretty print it ;) nsattributed string maybe. advertismentDataLabel.text = "\(peripheral.advertisementData.advertisementData)" } }
mit
b7403e67a28bc67b415c8a4aa357e1a4
38.330882
143
0.701066
5.560291
false
false
false
false
satoshimuraki/PWebActivity
Sources/PWebActivityDemo/ViewController.swift
1
1976
// // ViewController.swift // // Copyright © 2017 Satoshi Muraki. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() } } // MARK: - Actions extension ViewController { @IBAction func shareURL(_ sender: Any?) { guard let url = URL(string: "https://www.apple.com/") else { return } let applicationActivities: [UIActivity] = [ PSafariActivity(), PChromeActivity() ] let controller = UIActivityViewController(activityItems: [url], applicationActivities: applicationActivities) if UIDevice.current.userInterfaceIdiom == .pad { if let button = sender as? UIView { controller.popoverPresentationController?.sourceRect = button.frame controller.popoverPresentationController?.sourceView = self.view self.present(controller, animated: true, completion: nil) } } else { self.present(controller, animated: true, completion: nil) } } @IBAction func shareString(_ sender: Any?) { let strings: [String] = ["Apple", "https://www.apple.com/"] let string = strings.joined(separator: "\n") let applicationActivities: [UIActivity] = [ PSafariActivity(), PChromeActivity() ] let controller = UIActivityViewController(activityItems: [string], applicationActivities: applicationActivities) if UIDevice.current.userInterfaceIdiom == .pad { if let button = sender as? UIView { controller.popoverPresentationController?.sourceRect = button.frame controller.popoverPresentationController?.sourceView = self.view self.present(controller, animated: true, completion: nil) } } else { self.present(controller, animated: true, completion: nil) } } }
mit
ebba16b07a6eaa3ba6ca475b61c3237d
32.474576
120
0.622785
5.197368
false
false
false
false
kaich/CKPhotoGallery
CKPhotoGallery/Classes/CKPhotoViewController.swift
1
3501
// // CKPhotoViewController.swift // Pods // // Created by mac on 16/10/17. // // import UIKit import Kingfisher class CKPhotoViewController: UIViewController, UIScrollViewDelegate { var url :URL? lazy var scalingImageView :CKScalingImageView = { let imageView = CKScalingImageView(frame: self.view.bounds) imageView.delegate = self self.view.addSubview(imageView) return imageView }() lazy var emptyImageView :UIImageView = { let imageView = UIImageView(image: UIImage.make(name:"nullData_icon_Img_40x40")) imageView.translatesAutoresizingMaskIntoConstraints = false self.view.addSubview(imageView) self.view.addConstraint( NSLayoutConstraint(item: self.view, attribute: .centerX, relatedBy: .equal, toItem: imageView, attribute: .centerX, multiplier: 1, constant: 0) ) self.view.addConstraint( NSLayoutConstraint(item: self.view, attribute: .centerY, relatedBy: .equal, toItem: imageView, attribute: .centerY, multiplier: 1, constant: 0) ) return imageView }() init(url :URL) { self.url = url super.init(nibName: nil, bundle: nil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. view.backgroundColor = UIColor.clear scalingImageView.backgroundColor = UIColor.clear scalingImageView.translatesAutoresizingMaskIntoConstraints = false let resource = ImageResource(downloadURL: url!) scalingImageView.imageView.kf.setImage(with: resource, placeholder: nil, options: nil, progressBlock: nil, completionHandler: { (image, error, type, url) in if image == nil { self.emptyImageView.isHidden = false } else { self.emptyImageView.isHidden = true } }); } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() scalingImageView.frame = view.bounds } // MARK:- UIScrollViewDelegate open func viewForZooming(in scrollView: UIScrollView) -> UIView? { return scalingImageView.imageView } open func scrollViewWillBeginZooming(_ scrollView: UIScrollView, with view: UIView?) { scrollView.panGestureRecognizer.isEnabled = true } open func scrollViewDidEndZooming(_ scrollView: UIScrollView, with view: UIView?, atScale scale: CGFloat) { // There is a bug, especially prevalent on iPhone 6 Plus, that causes zooming to render all other gesture recognizers ineffective. // This bug is fixed by disabling the pan gesture recognizer of the scroll view when it is not needed. if (scrollView.zoomScale == scrollView.minimumZoomScale) { scrollView.panGestureRecognizer.isEnabled = false; } } }
mit
f4c27a8bcf988579a2b8ca11d99c26ed
33.663366
164
0.600114
5.574841
false
false
false
false
LetItPlay/iOSClient
blockchainapp/PlaylistView.swift
1
3747
// // PlaylistView.swift // blockchainapp // // Created by Aleksey Tyurnin on 06/12/2017. // Copyright © 2017 Ivan Gorbulin. All rights reserved. // import UIKit class PlaylistView: UIView { let tableView: UITableView = UITableView.init(frame: .zero, style: .grouped) var tracks: [[AudioTrack]] = [[]] var currentIndex: IndexPath = IndexPath.invalid convenience init() { self.init(frame: CGRect.zero) self.addSubview(tableView) tableView.snp.makeConstraints { (make) in make.edges.equalToSuperview() } tableView.delegate = self tableView.dataSource = self self.tableView.separatorColor = self.tableView.backgroundColor tableView.register(PlayerTableViewCell.self, forCellReuseIdentifier: PlayerTableViewCell.cellID) } } extension PlaylistView: UITableViewDelegate, UITableViewDataSource { func numberOfSections(in tableView: UITableView) -> Int { return self.tracks.count } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.tracks[section].count } func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { if self.tracks[section].count == 0 { return nil } let view = UIView() view.backgroundColor = .white let label = UILabel() label.font = AppFont.Title.big label.textColor = AppColor.Title.dark label.text = "Current playlist".localized let tracks = IconedLabel.init(type: .tracks) tracks.setData(data: Int64(self.tracks[section].count)) let time = IconedLabel.init(type: .time) time.setData(data: Int64(self.tracks[section].map({$0.length}).reduce(0, {$0 + $1}))) view.addSubview(label) label.snp.makeConstraints { (make) in make.top.equalToSuperview().inset(3) make.left.equalToSuperview().inset(16) } view.addSubview(tracks) tracks.snp.makeConstraints { (make) in make.left.equalToSuperview().inset(16) make.top.equalTo(label.snp.bottom).inset(-7) } view.addSubview(time) time.snp.makeConstraints { (make) in make.left.equalTo(tracks.snp.right).inset(-8) make.centerY.equalTo(tracks) } let line = UIView() line.backgroundColor = AppColor.Element.redBlur line.layer.cornerRadius = 1 line.layer.masksToBounds = true view.addSubview(line) line.snp.makeConstraints { (make) in make.left.equalToSuperview().inset(16) make.right.equalToSuperview().inset(16) make.bottom.equalToSuperview() make.height.equalTo(2) } return view } func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { return 0.01 } func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? { return nil } func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { if self.tracks[section].count == 0 { return 0.1 } return 73 } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let contr = AudioController.main contr.make(command: .play(id: self.tracks[indexPath].id)) } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: PlayerTableViewCell.cellID, for: indexPath) as! PlayerTableViewCell let track = self.tracks[indexPath] cell.track = track let hideListens = indexPath == currentIndex cell.dataLabels[.listens]?.isHidden = hideListens cell.dataLabels[.playingIndicator]?.isHidden = !hideListens return cell } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { let track = self.tracks[indexPath] return SmallTrackTableViewCell.height(text: track.name, width: tableView.frame.width) } }
mit
975a1729c6f925a6521cc8ae4f4472ff
27.59542
126
0.728777
3.727363
false
false
false
false
ndleon09/TopApps
TopAppsTests/AppsTestRepository.swift
1
847
// // AppsTestRepository.swift // TopApps // // Created by Nelson Dominguez on 24/04/16. // Copyright © 2016 Nelson Dominguez. All rights reserved. // import Foundation @testable import TopApps class AppsTestRepository: AppsRepositoryImp { override init(persistence: PersistenceLayerProtocol) { super.init(persistence: persistence) if apps.count == 0 { var apps = [App]() for i in 1 ... 15 { let app = App(value: ["id": i, "name": "App \(i)", "category": "Category", "summary": "Summary for App \(i)"]) apps.append(app) } persistenceLayer.save(apps: apps) } } override func getAll(completion: @escaping ([App]) -> ()) { let result = Array(apps) completion(result) } }
mit
a7d95970188e9fa4ac5dedc6044302ea
24.636364
126
0.554374
4.167488
false
true
false
false
caodong1991/SwiftStudyNote
Swift.playground/Pages/08 - Enumerations.xcplaygroundpage/Contents.swift
1
8321
import Foundation // 枚举 /* 枚举作为一组相关的值定义了一个共同的类型,可以在代码中以类型安全的方式来使用这些值。 不必给每一个枚举成员提供一个值。如果给枚举成员提供一个值(称为原始值),则该值的类型可以使字符串、字符、或是一个整型值或浮点数。 枚举成员可以指定任意类型的关联值存储到枚举成员中。可以在枚举中定义一组相关的枚举成员,每一个枚举成员都可以有适当类型的关联值。 */ // 枚举语法 /* 使用enum关键词来创建枚举并且把它们的整个定义放在一对大括号内。 */ enum SomeEnumeration { // 枚举定义放在这里 } /* 枚举中定义的值是这个枚举的成员值(或成员)。 使用case关键字来定义一个新的枚举成员值。 与OC不同,枚举成员在被创建的时候不会被赋予一个默认的整型值。相反,这些枚举成员本身就是完备的值,这些值的类型是已经明确定义好的CompassPoint类型。 */ enum CompassPoint { case north case south case east case west } /* 多个成员值可以出现在同一行上,用逗号隔开。 */ enum Plant { case mercury, venus, earth, mars, jupiter, saturn, uranus, neptune } /* 每个枚举定义了一个全新的类型。枚举名以一个大写字母开头。给枚举类型起一个单数名字而不是复数名字。 directionToHead的类型可以在它被CompassPoint的某个值初始化时推断出来。 */ var directionToHead = CompassPoint.west /* 一旦被声明为具体的类型,可以使用更简短的点语法。 类型已知时,再次为其赋值可以省略枚举类型名。 使用具有显式类型的枚举值,让代码具有更好的可读性。 */ directionToHead = .east // 使用Switch语句匹配枚举值 /* 使用switch语句匹配单个枚举值 */ directionToHead = .south switch directionToHead { case .north: print("Lots of planets have a north") case .south: print("Watch out for penguins") case .east: print("Where the sun rises") case .west: print("Where the skies are blue") } /* 当不需要匹配每个枚举成员的时候,可以用default分支来涵盖所有未明确处理的枚举成员。 */ let somePlanet = Plant.earth switch somePlanet { case .earth: print("Mostly harmless") default: print("Not a safe place for humans") } // 枚举成员的遍历 /* 需要一个包含枚举所有成员的集合: 令枚举遵循CaseIterable协议。Swift会生成一个allCases属性,用于表示一个包含枚举所有成员的集合。 */ enum Beverage: CaseIterable { case coffee, tea, juice } /* allCases---集合中的元素是枚举类型的实例,这些元素都是枚举值。 */ let numberOfChoices = Beverage.allCases.count print("\(numberOfChoices) beverages available") for beverage in Beverage.allCases { print(beverage) } // 关联值 /* 为枚举成员设置一个常量或变量,并且在赋值之后查看这个值。 把其他类型的值和成员值一起存储起来会很有用,这额外的信息被称为关联值。 使用该枚举成员时,可以修改这个关联值。 可以定义枚举存储任意类型的关联值,还可以每个枚举成员的关联值类型可以各不相同。 */ enum BarCode { case upc(Int, Int, Int, Int) case qrCode(String) } /* 上面代码只是定义了一个枚举类型,当使用枚举的成员值时,可以存储关联值 */ var productBarcode = BarCode.upc(8, 85909, 51226, 3) /* 原始的Barcode.upc和其整数关联值被新的Barcode.qrCode和其字符串关联值所替代。同一时间只能存储一个成员值。 */ productBarcode = .qrCode("ABCDEFGHIJKLMNOP") /* 关联值可以被提取出来作为switch语句的一部分。 */ switch productBarcode { case .upc(let numberSystem, let manuFacturer, let product, let check): print("UPC:\(numberSystem), \(manuFacturer), \(product), \(check)") case .qrCode(let productCode): print("QR code: \(productCode)") } /* 如果一个枚举成员的所有关联值都被提取为常量或者变量,可以在成员名称前标注一个let或者var。 */ switch productBarcode { case let .upc(numberSystem, manuFacturer, product, check): print("UPC:\(numberSystem), \(manuFacturer), \(product), \(check)") case let .qrCode(productCode): print("QR code: \(productCode)") } // 原始值 /* 关联值的替代选择。 枚举成员可以被默认值(原始值)预填充,这些原始值的类型必须相同。 原始值可以使字符串,字符或者任意整型值或浮点型值。每个原始值在枚举声明中必须是唯一的。 原始值和关联值是不同的: 1. 原始值是在定义枚举时被预先填充的值。对于一个特定的枚举成员,它的原始值始终不变。 2. 关联值是创建一个基于枚举成员的常量或变量时才设置的值,枚举成员的关联值可以变化。 */ enum ASCIIControCharacter: Character { case tab = "\t" case lineFeed = "\n" case carriageReturn = "\r" } // 原始值的隐式赋值 /* 使用原始值为整数或者字符串类型的枚举时,不需要显示地为每一个枚举成员设置原始值,会自动为你赋值。 当使用整数作为原始值事,隐式赋值的值依次递增1,如果第一个枚举成员没有设置原始值,其原始值将为0。 */ enum OtherPlanet: Int { case mercury = 1, venus, earth, mars, jupiter, saturn, uranus, neptune } /* 当使用字符串作为枚举类型的原始值时,每个枚举成员的隐式原始值为该枚举成员的名称。 */ enum OtherCompassPoint: String { case north, south, east, west } /* 使用枚举成员的rawValue属性可以访问该枚举成员的原始值。 */ let earthOrder = OtherPlanet.earth.rawValue let sunsetDirection = OtherCompassPoint.west.rawValue // 使用原始值初始化枚举实例 /* 如果在定义枚举类型的时候使用了原始值,那么将会自动获得一个初始化方法,这个方法接收一个叫做rawValue的参数,参数类型即为原始值类型,返回值是枚举成员或nil。 */ /* 使用初始化方法来创建一个新的枚举实例 原始值构造器总是返回一个可选的枚举成员。 原始构造器是一个可失败构造器,因为并不是每一个原始值都有与之对应的枚举成员。 */ let possiblePlant = OtherPlanet(rawValue: 7) // possiblePlant类型为 OtherPlant? let positionToFind = 11 if let somePlanet = OtherPlanet(rawValue: positionToFind) { switch somePlanet { case .earth: print("Mostly harmless") default: print("Not a safe place for humans") } } else { print("There isn't a planet at position \(positionToFind)") } // 递归枚举 /* 递归枚举是一种枚举类型,它有一个或多个枚举成员使用该枚举类型的实例作为关联值。 使用递归枚举时,编译器会插入一个间接层。 可以在枚举成员前加上indirect来表示该成员可递归 */ enum ArithmeticExpression { case number(Int) indirect case addition(ArithmeticExpression, ArithmeticExpression) indirect case multiplicaion(ArithmeticExpression, ArithmeticExpression) } /* 也可以在枚举类型开头加上indirect关键字来表明它的所有成员都是可递归的。 */ indirect enum OtherArithmeticExpression { case number(Int) case addition(ArithmeticExpression, ArithmeticExpression) case multiplicaion(ArithmeticExpression, ArithmeticExpression) } let five = ArithmeticExpression.number(5) let four = ArithmeticExpression.number(4) let sum = ArithmeticExpression.addition(five, four) let product = ArithmeticExpression.multiplicaion(sum, ArithmeticExpression.number(2)) /* 要操作具有递归性质的数据结构,使用递归函数是一种直截了当的方式。 */ func evaluate(_ expression: ArithmeticExpression) -> Int { switch expression { case let .number(value): return value case let .addition(left, right): return evaluate(left) + evaluate(right) case let .multiplicaion(left, right): return evaluate(left) * evaluate(right) } } print(evaluate(product))
mit
73dd1b3751dd262138686faebb21ae9c
20.9375
85
0.747958
2.814003
false
false
false
false
evan0322/WorkoutCompanion
WorkoutCompanion/WorkoutCompanion/ExerciseDetailTableViewController.swift
1
7363
// // ExerciseDataTableViewController.swift // WorkoutCompanion // // Created by Wei Xie on 2016-06-13. // Copyright © 2016 WEI.XIE. All rights reserved. // import UIKit import CoreData import SCLAlertView class ExerciseDetailTableViewController: UITableViewController { var exercise:Exercise! var exerciseDetails:[ExerciseData]? lazy var context: NSManagedObjectContext = { let appDelegate = UIApplication.shared.delegate as! AppDelegate return appDelegate.managedObjectContext }() override func viewDidLoad() { super.viewDidLoad() exerciseDetails = exercise.exerciseData.allObjects as? [ExerciseData] exerciseDetails = exerciseDetails!.sorted(by:{ data1,data2 in return data1.date.compare(data2.date as Date) == ComparisonResult.orderedDescending }) self.tableView.separatorStyle = .none self.tableView.backgroundColor = Constants.themeColorAlabuster self.title = exercise.name } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { guard let details = exerciseDetails else { return 0 } if details.count < 1 { UIManager.sharedInstance().handleNoDataLabel(add: true, forTableView: self.tableView) } else { UIManager.sharedInstance().handleNoDataLabel(add: false, forTableView: self.tableView) } return details.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell : CardTableViewCell = tableView.dequeueReusableCell(withIdentifier: "cardTableViewCell", for: indexPath as IndexPath) as! CardTableViewCell guard let details = exerciseDetails else { return cell } //Caculate One-Rep Max with Epley Formula let detail = details[indexPath.row] as ExerciseData let oneRepMax = detail.reps==1 ? Int(detail.weight) : Int((Double(detail.reps)/30+1)*Double(detail.weight)) cell.cardFirstSectionLabel!.text = "\(String(detail.sets))" cell.cardSecondSectionLabel!.text = "\(String(detail.reps))" cell.cardThirdSectionLabel!.text = "\(String(detail.weight))" cell.cardDateLabel!.text = detail.date.toString() cell.cardDetailLabel!.text = "\(oneRepMax)" cell.backgroundColor = UIColor.clear cell.tintColor = Constants.themeColorWhite cell.selectionStyle = UITableViewCellSelectionStyle.none return cell } override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 140 } override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { switch editingStyle { case .delete: let exerciseDetail = exerciseDetails![indexPath.row] context.delete(exerciseDetail) exerciseDetails?.remove(at: indexPath.row) do { try context.save() tableView.deleteRows(at: [indexPath as IndexPath], with: .fade) } catch let error as NSError { print("Error saving context after delete: \(error.localizedDescription)") } default:break } } @IBAction func addButtonPressed(sender: AnyObject) { let appearance = SCLAlertView.SCLAppearance( kTitleFont: UIFont(name: "HelveticaNeue", size: 20)!, kTextFont: UIFont(name: "HelveticaNeue", size: 14)!, kButtonFont: UIFont(name: "HelveticaNeue-Bold", size: 14)!, showCloseButton: false, showCircularIcon: false, shouldAutoDismiss: false, contentViewColor:Constants.themeColorAlabuster ) let alert = SCLAlertView(appearance: appearance) let repsInput = alert.addTextField(Constants.stringPlaceHolderReps) let setsInput = alert.addTextField(Constants.stringPlaceHolderSets) let weightInput = alert.addTextField(Constants.stringPlaceHolderWeight) repsInput.keyboardType = UIKeyboardType.numberPad setsInput.keyboardType = UIKeyboardType.numberPad weightInput.keyboardType = UIKeyboardType.numberPad var alertViewResponder = SCLAlertViewResponder(alertview: alert) alert.addButton(Constants.stringButtonAdd, backgroundColor: Constants.themeColorBlack, textColor: UIColor.white, showTimeout: nil) { //Validate data guard (repsInput.text != "" && setsInput.text != "" && weightInput.text != "") else{ alertViewResponder.setSubTitle(Constants.stringWarningDataEmpty) return } guard let entity = NSEntityDescription.entity(forEntityName: Constants.CoreDataEntityType.ExerciseData.rawValue, in:self.context) else { return } let exerciseData = ExerciseData(entity: entity, insertInto:self.context) exerciseData.setValue(Int(repsInput.text!), forKey: "Reps") exerciseData.setValue(Int(setsInput.text!), forKey: "Sets") exerciseData.setValue(Int(weightInput.text!), forKey: "Weight") exerciseData.setValue(Date(), forKey: "Date") exerciseData.exercise = self.exercise let exerciseDatas = self.exercise.mutableOrderedSetValue(forKey: "exerciseData") exerciseDatas.insert(exerciseData, at: 0) do { try self.context.save() } catch let error as NSError { print("Error saving movie \(error.localizedDescription)") } alert.hideView() self.exerciseDetails?.insert(exerciseData, at: 0) self.tableView.beginUpdates() self.tableView.insertRows(at: [NSIndexPath(row: 0, section: 0) as IndexPath], with: .fade) self.tableView.endUpdates() } alert.addButton("Cancel", backgroundColor: Constants.themeColorMadderLake, textColor: UIColor.white, showTimeout: nil) { alert.hideView() } alertViewResponder = alert.showTitle(Constants.stringAlertTitleAddWorkout, subTitle: Constants.stringAlertSubtitleEnterData, timeout: nil, completeText: Constants.stringButtonDone, style: .success, colorStyle: 0xFFFFFF, colorTextButton: 0xFFFFFF, circleIconImage: nil, animationStyle: .topToBottom) } }
mit
d74d6eaf33dff7dcc735b77e5750e436
43.890244
156
0.607851
5.43321
false
false
false
false
Erickson0806/AdaptivePhotos
AdaptivePhotosUsingUIKitTraitsandSizeClasses/AdaptiveCode/AdaptiveCode/ProfileViewController.swift
1
7114
/* Copyright (C) 2015 Apple Inc. All Rights Reserved. See LICENSE.txt for this sample’s licensing information Abstract: A view controller that shows a user's profile. */ import UIKit class ProfileViewController: UIViewController { // MARK: Properties private var imageView: UIImageView? private var nameLabel: UILabel? private var conversationsLabel: UILabel? private var photosLabel: UILabel? // Holds the current constraints used to position the subviews. private var constraints = [NSLayoutConstraint]() let user: User var nameText: String { return user.name } var conversationsText: String { let conversationCount = user.conversations.count let localizedStringFormat = NSLocalizedString("%d conversations", comment: "X conversations") return String.localizedStringWithFormat(localizedStringFormat, conversationCount) } var photosText: String { let photoCount = user.conversations.reduce(0) { count, conversation in return count + conversation.photos.count } let localizedStringFormat = NSLocalizedString("%d photos", comment: "X photos") return String.localizedStringWithFormat(localizedStringFormat, photoCount) } // MARK: Initialization init(user: User) { self.user = user super.init(nibName: nil, bundle: nil) title = NSLocalizedString("Profile", comment: "Profile") } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: View Controller override func loadView() { let view = UIView() view.backgroundColor = UIColor.whiteColor() // Create an image view let imageView = UIImageView() imageView.contentMode = .ScaleAspectFit imageView.translatesAutoresizingMaskIntoConstraints = false self.imageView = imageView view.addSubview(imageView) // Create a label for the profile name let nameLabel = UILabel() nameLabel.font = UIFont.preferredFontForTextStyle(UIFontTextStyleHeadline) nameLabel.translatesAutoresizingMaskIntoConstraints = false self.nameLabel = nameLabel view.addSubview(nameLabel) // Create a label for the number of conversations let conversationsLabel = UILabel() conversationsLabel.font = UIFont.preferredFontForTextStyle(UIFontTextStyleBody) conversationsLabel.translatesAutoresizingMaskIntoConstraints = false self.conversationsLabel = conversationsLabel view.addSubview(conversationsLabel) // Create a label for the number of photos let photosLabel = UILabel() photosLabel.font = UIFont.preferredFontForTextStyle(UIFontTextStyleBody) photosLabel.translatesAutoresizingMaskIntoConstraints = false self.photosLabel = photosLabel view.addSubview(photosLabel) self.view = view // Update all of the visible information updateUser() updateConstraintsForTraitCollection(traitCollection) } override func willTransitionToTraitCollection(newCollection: UITraitCollection, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) { super.willTransitionToTraitCollection(newCollection, withTransitionCoordinator: coordinator) // When the trait collection changes, change our views' constraints and animate the change coordinator.animateAlongsideTransition({ _ in self.updateConstraintsForTraitCollection(newCollection) self.view.setNeedsLayout() }, completion: nil) } // Applies the proper constraints to the subviews for the size class of the given trait collection. func updateConstraintsForTraitCollection(collection: UITraitCollection) { let views: [String: AnyObject] = [ "topLayoutGuide": topLayoutGuide, "imageView": imageView!, "nameLabel": nameLabel!, "conversationsLabel": conversationsLabel!, "photosLabel": photosLabel! ] // Make our new set of constraints for the current traits var newConstraints = [NSLayoutConstraint]() if collection.verticalSizeClass == .Compact { // When we're vertically compact, show the image and labels side-by-side newConstraints += NSLayoutConstraint.constraintsWithVisualFormat("|[imageView]-[nameLabel]-|", options: [], metrics: nil, views: views) newConstraints += NSLayoutConstraint.constraintsWithVisualFormat("[imageView]-[conversationsLabel]-|", options: [], metrics: nil, views: views) newConstraints += NSLayoutConstraint.constraintsWithVisualFormat("[imageView]-[photosLabel]-|", options: [], metrics: nil, views: views) newConstraints += NSLayoutConstraint.constraintsWithVisualFormat("V:|[topLayoutGuide]-[nameLabel]-[conversationsLabel]-[photosLabel]", options: [], metrics: nil, views: views) newConstraints += NSLayoutConstraint.constraintsWithVisualFormat("V:|[topLayoutGuide][imageView]|", options: [], metrics: nil, views: views) newConstraints += [ NSLayoutConstraint(item: imageView!, attribute: .Width, relatedBy: .Equal, toItem: view, attribute: .Width, multiplier: 0.5, constant: 0) ] } else { // When we're vertically compact, show the image and labels top-and-bottom newConstraints += NSLayoutConstraint.constraintsWithVisualFormat("|[imageView]|", options: [], metrics: nil, views: views) newConstraints += NSLayoutConstraint.constraintsWithVisualFormat("|-[nameLabel]-|", options: [], metrics: nil, views: views) newConstraints += NSLayoutConstraint.constraintsWithVisualFormat("|-[conversationsLabel]-|", options: [], metrics: nil, views: views) newConstraints += NSLayoutConstraint.constraintsWithVisualFormat("|-[photosLabel]-|", options: [], metrics: nil, views: views) newConstraints += NSLayoutConstraint.constraintsWithVisualFormat("V:[topLayoutGuide]-[nameLabel]-[conversationsLabel]-[photosLabel]-20-[imageView]|", options: [], metrics: nil, views: views) } // Change to our new constraints NSLayoutConstraint.deactivateConstraints(constraints) constraints = newConstraints NSLayoutConstraint.activateConstraints(newConstraints) } // MARK: Convenience // Updates the user interface with the data from the current user object. func updateUser() { nameLabel?.text = nameText conversationsLabel?.text = conversationsText photosLabel?.text = photosText imageView?.image = user.lastPhoto?.image } }
apache-2.0
19980cdb0a7910a7465a83bba7986dab
41.333333
202
0.662823
6.205934
false
false
false
false
steryokhin/AsciiArtPlayer
src/AsciiArtPlayer/Pods/PromiseKit/Sources/when.swift
5
8557
import Foundation import Dispatch private func _when<T>(_ promises: [Promise<T>]) -> Promise<Void> { let root = Promise<Void>.pending() var countdown = promises.count guard countdown > 0 else { root.fulfill() return root.promise } #if PMKDisableProgress || os(Linux) var progress: (completedUnitCount: Int, totalUnitCount: Int) = (0, 0) #else let progress = Progress(totalUnitCount: Int64(promises.count)) progress.isCancellable = false progress.isPausable = false #endif let barrier = DispatchQueue(label: "org.promisekit.barrier.when", attributes: .concurrent) for promise in promises { promise.state.pipe { resolution in barrier.sync(flags: .barrier) { switch resolution { case .rejected(let error, let token): token.consumed = true if root.promise.isPending { progress.completedUnitCount = progress.totalUnitCount root.reject(error) } case .fulfilled: guard root.promise.isPending else { return } progress.completedUnitCount += 1 countdown -= 1 if countdown == 0 { root.fulfill() } } } } } return root.promise } /** Wait for all promises in a set to fulfill. For example: when(fulfilled: promise1, promise2).then { results in //… }.catch { error in switch error { case URLError.notConnectedToInternet: //… case CLError.denied: //… } } - Note: If *any* of the provided promises reject, the returned promise is immediately rejected with that error. - Warning: In the event of rejection the other promises will continue to resolve and, as per any other promise, will either fulfill or reject. This is the right pattern for `getter` style asynchronous tasks, but often for `setter` tasks (eg. storing data on a server), you most likely will need to wait on all tasks and then act based on which have succeeded and which have failed, in such situations use `when(resolved:)`. - Parameter promises: The promises upon which to wait before the returned promise resolves. - Returns: A new promise that resolves when all the provided promises fulfill or one of the provided promises rejects. - Note: `when` provides `NSProgress`. - SeeAlso: `when(resolved:)` */ public func when<T>(fulfilled promises: [Promise<T>]) -> Promise<[T]> { return _when(promises).then(on: zalgo) { promises.map{ $0.value! } } } /// Wait for all promises in a set to fulfill. public func when(fulfilled promises: Promise<Void>...) -> Promise<Void> { return _when(promises) } /// Wait for all promises in a set to fulfill. public func when(fulfilled promises: [Promise<Void>]) -> Promise<Void> { return _when(promises) } /// Wait for all promises in a set to fulfill. public func when<U, V>(fulfilled pu: Promise<U>, _ pv: Promise<V>) -> Promise<(U, V)> { return _when([pu.asVoid(), pv.asVoid()]).then(on: zalgo) { (pu.value!, pv.value!) } } /// Wait for all promises in a set to fulfill. public func when<U, V, W>(fulfilled pu: Promise<U>, _ pv: Promise<V>, _ pw: Promise<W>) -> Promise<(U, V, W)> { return _when([pu.asVoid(), pv.asVoid(), pw.asVoid()]).then(on: zalgo) { (pu.value!, pv.value!, pw.value!) } } /// Wait for all promises in a set to fulfill. public func when<U, V, W, X>(fulfilled pu: Promise<U>, _ pv: Promise<V>, _ pw: Promise<W>, _ px: Promise<X>) -> Promise<(U, V, W, X)> { return _when([pu.asVoid(), pv.asVoid(), pw.asVoid(), px.asVoid()]).then(on: zalgo) { (pu.value!, pv.value!, pw.value!, px.value!) } } /// Wait for all promises in a set to fulfill. public func when<U, V, W, X, Y>(fulfilled pu: Promise<U>, _ pv: Promise<V>, _ pw: Promise<W>, _ px: Promise<X>, _ py: Promise<Y>) -> Promise<(U, V, W, X, Y)> { return _when([pu.asVoid(), pv.asVoid(), pw.asVoid(), px.asVoid(), py.asVoid()]).then(on: zalgo) { (pu.value!, pv.value!, pw.value!, px.value!, py.value!) } } /** Generate promises at a limited rate and wait for all to fulfill. For example: func downloadFile(url: URL) -> Promise<Data> { // ... } let urls: [URL] = /*…*/ let urlGenerator = urls.makeIterator() let generator = AnyIterator<Promise<Data>> { guard url = urlGenerator.next() else { return nil } return downloadFile(url) } when(generator, concurrently: 3).then { datum: [Data] -> Void in // ... } - Warning: Refer to the warnings on `when(fulfilled:)` - Parameter promiseGenerator: Generator of promises. - Returns: A new promise that resolves when all the provided promises fulfill or one of the provided promises rejects. - SeeAlso: `when(resolved:)` */ public func when<T, PromiseIterator: IteratorProtocol>(fulfilled promiseIterator: PromiseIterator, concurrently: Int) -> Promise<[T]> where PromiseIterator.Element == Promise<T> { guard concurrently > 0 else { return Promise(error: PMKError.whenConcurrentlyZero) } var generator = promiseIterator var root = Promise<[T]>.pending() var pendingPromises = 0 var promises: [Promise<T>] = [] let barrier = DispatchQueue(label: "org.promisekit.barrier.when", attributes: [.concurrent]) func dequeue() { guard root.promise.isPending else { return } // don’t continue dequeueing if root has been rejected var shouldDequeue = false barrier.sync { shouldDequeue = pendingPromises < concurrently } guard shouldDequeue else { return } var index: Int! var promise: Promise<T>! barrier.sync(flags: .barrier) { guard let next = generator.next() else { return } promise = next index = promises.count pendingPromises += 1 promises.append(next) } func testDone() { barrier.sync { if pendingPromises == 0 { root.fulfill(promises.flatMap{ $0.value }) } } } guard promise != nil else { return testDone() } promise.state.pipe { resolution in barrier.sync(flags: .barrier) { pendingPromises -= 1 } switch resolution { case .fulfilled: dequeue() testDone() case .rejected(let error, let token): token.consumed = true root.reject(error) } } dequeue() } dequeue() return root.promise } /** Waits on all provided promises. `when(fulfilled:)` rejects as soon as one of the provided promises rejects. `when(resolved:)` waits on all provided promises and **never** rejects. when(resolved: promise1, promise2, promise3).then { results in for result in results where case .fulfilled(let value) { //… } }.catch { error in // invalid! Never rejects } - Returns: A new promise that resolves once all the provided promises resolve. - Warning: The returned promise can *not* be rejected. - Note: Any promises that error are implicitly consumed, your UnhandledErrorHandler will not be called. */ public func when<T>(resolved promises: Promise<T>...) -> Promise<[Result<T>]> { return when(resolved: promises) } /// Waits on all provided promises. public func when<T>(resolved promises: [Promise<T>]) -> Promise<[Result<T>]> { guard !promises.isEmpty else { return Promise(value: []) } var countdown = promises.count let barrier = DispatchQueue(label: "org.promisekit.barrier.join", attributes: .concurrent) return Promise { fulfill, reject in for promise in promises { promise.state.pipe { resolution in if case .rejected(_, let token) = resolution { token.consumed = true // all errors are implicitly consumed } var done = false barrier.sync(flags: .barrier) { countdown -= 1 done = countdown == 0 } if done { fulfill(promises.map { Result($0.state.get()!) }) } } } } }
mit
a0c6ee8f6e2bf39f2ee0da3f9ad3dd65
33.317269
424
0.593329
4.289659
false
false
false
false
troystribling/BlueCap
Examples/BlueCap/BlueCap/Central/PeripheralsViewController.swift
1
27405
// // PeripheralsViewController.swift // BlueCapUI // // Created by Troy Stribling on 6/5/14. // Copyright (c) 2014 Troy Stribling. The MIT License (MIT). // import UIKit import CoreBluetooth import BlueCapKit class SerialUUIDQueue { let queue = Queue("serial-uuid-queue") var uuids = [UUID]() var isEmpty: Bool { return self.uuids.count == 0 } var count: Int { return uuids.count } func push(_ uuid: UUID) { guard !self.uuids.contains(uuid) else { return } Logger.debug("queueing \(uuid)") self.uuids.append(uuid) } func shift() -> UUID? { guard self.uuids.count > 0 else { return nil } let uuid = self.uuids.remove(at: 0) Logger.debug("dequeueing \(uuid)") return uuid } func removeAll() { self.uuids.removeAll() } func set(_ peripherals: [Peripheral]) { peripherals.forEach { peripheral in guard !self.uuids.contains(peripheral.identifier) else { return } self.uuids.append(peripheral.identifier) } } } class PeripheralsViewController : UITableViewController { var stopScanBarButtonItem: UIBarButtonItem! var startScanBarButtonItem: UIBarButtonItem! var peripheralsToConnect = SerialUUIDQueue() var peripheralsToDisconnect = SerialUUIDQueue() var connectingPeripherals = Set<UUID>() var connectedPeripherals = Set<UUID>() var discoveredPeripherals = Set<UUID>() var removedPeripherals = Set<UUID>() var peripheralAdvertisments = [UUID : PeripheralAdvertisements]() var scanEnabled = false var canScanAndConnect = false var didReset = false var atDiscoveryLimit: Bool { return Singletons.discoveryManager.peripherals.count >= ConfigStore.getMaximumPeripheralsDiscovered() } var allPeripheralsConnected: Bool { return connectedPeripherals.count == Singletons.discoveryManager.peripherals.count } var peripheralsSortedByRSSI: [Peripheral] { return Singletons.discoveryManager.peripherals.sorted() { (p1, p2) -> Bool in guard let p1RSSI = Singletons.scanningManager.discoveredPeripherals[p1.identifier], let p2RSSI = Singletons.scanningManager.discoveredPeripherals[p2.identifier] else { return false } if (p1RSSI.RSSI == 127 || p1RSSI.RSSI == 0) && (p2RSSI.RSSI != 127 || p2RSSI.RSSI != 0) { return false } else if (p1RSSI.RSSI != 127 || p1RSSI.RSSI != 0) && (p2RSSI.RSSI == 127 || p2RSSI.RSSI == 0) { return true } else if (p1RSSI.RSSI == 127 || p1RSSI.RSSI == 0) && (p2RSSI.RSSI == 127 || p2RSSI.RSSI == 0) { return true } else { return p1RSSI.RSSI >= p2RSSI.RSSI } } } var peripherals: [Peripheral] { if ConfigStore.getPeripheralSortOrder() == .discoveryDate { return Singletons.discoveryManager.peripherals } else { return self.peripheralsSortedByRSSI } } struct MainStoryboard { static let peripheralCell = "PeripheralCell" static let peripheralSegue = "Peripheral" } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) navigationItem.backBarButtonItem = UIBarButtonItem(title: "", style: .plain, target: nil, action: nil) stopScanBarButtonItem = UIBarButtonItem(barButtonSystemItem: .stop, target: self, action: #selector(PeripheralsViewController.toggleScan(_:))) startScanBarButtonItem = UIBarButtonItem(title: "Scan", style: UIBarButtonItem.Style.plain, target: self, action: #selector(PeripheralsViewController.toggleScan(_:))) styleUIBarButton(self.startScanBarButtonItem) Singletons.discoveryManager.whenStateChanges().onSuccess { state in Logger.debug("discoveryManager state changed: \(state)") } Singletons.scanningManager.whenStateChanges().onSuccess { [weak self] state in self.forEach { strongSelf in Logger.debug("scanningManager state changed: \(state)") switch state { case .poweredOn: if strongSelf.didReset { strongSelf.didReset = false strongSelf.startScanIfNotScanning() strongSelf.updatePeripheralConnectionsIfNecessary() } case .unknown: break case .poweredOff: strongSelf.alertAndStopScan(message: "Bluetooth powered off") case .unauthorized: strongSelf.alertAndStopScan(message: "Bluetooth unauthorized") case .resetting: strongSelf.stopScan() strongSelf.setScanButton() strongSelf.didReset = true sleep(1) Singletons.scanningManager.reset() case .unsupported: strongSelf.alertAndStopScan(message: "Bluetooth unsupported") } } } Singletons.discoveryManager.whenStateChanges().onSuccess { [weak self] state in self.forEach { strongSelf in Logger.debug("scanningManager state changed: \(state)") switch state { case .resetting, .unsupported: Singletons.discoveryManager.reset() default: break } } } } func alertAndStopScan(message: String) { present(UIAlertController.alert(message: message), animated:true) { [weak self] () -> Void in self.forEach { strongSelf in strongSelf.stopScanAndToggleOff() strongSelf.setScanButton() } } } override func viewDidLoad() { super.viewDidLoad() styleNavigationBar() setScanButton() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) NotificationCenter.default.addObserver(self, selector:#selector(PeripheralsViewController.didBecomeActive), name: UIApplication.didBecomeActiveNotification, object:nil) NotificationCenter.default.addObserver(self, selector:#selector(PeripheralsViewController.didEnterBackground), name: UIApplication.didEnterBackgroundNotification, object:nil) resumeScanAndConnecting() restartConnectionUpdatesIfNecessary() updatePeripheralConnectionsIfNecessary() setScanButton() updateWhenActive() } override func viewDidDisappear(_ animated: Bool) { super.viewWillDisappear(animated) NotificationCenter.default.removeObserver(self) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } override func prepare(for segue: UIStoryboardSegue, sender: Any!) { if segue.identifier == MainStoryboard.peripheralSegue { if let selectedIndex = self.tableView.indexPath(for: sender as! UITableViewCell) { let viewController = segue.destination as! PeripheralViewController let peripheral = self.peripherals[selectedIndex.row] viewController.peripheral = peripheral viewController.peripheralAdvertisements = peripheralAdvertisments[peripheral.identifier] } } } override func shouldPerformSegue(withIdentifier identifier: String, sender: Any?) -> Bool { guard let selectedIndex = self.tableView.indexPath(for: sender as! UITableViewCell), identifier == MainStoryboard.peripheralSegue else { return true } let peripheral = self.peripherals[selectedIndex.row] return !connectingPeripherals.contains(peripheral.identifier) } @objc func didBecomeActive() { Logger.debug() tableView.reloadData() setScanButton() } @objc func didEnterBackground() { Logger.debug() stopScanAndToggleOff() } func setScanButton() { if scanEnabled { navigationItem.setLeftBarButton(self.stopScanBarButtonItem, animated:false) } else { navigationItem.setLeftBarButton(self.startScanBarButtonItem, animated:false) } } // MARK: Peripheral Connection func disconnectConnectingPeripherals() { for peripheral in peripherals where connectingPeripherals.contains(peripheral.identifier) { Logger.debug("Disconnecting peripheral '\(peripheral.name)', \(peripheral.identifier.uuidString)") peripheral.disconnect() } } func connectPeripheralsToConnect() { guard canScanAndConnect else { Logger.debug("connection updates disabled") disconnectConnectingPeripherals() return } guard Singletons.discoveryManager.discoveredPeripherals.count > 1 else { return } let maxConnections = ConfigStore.getMaximumPeripheralsConnected() var connectingCount = connectingPeripherals.count guard connectingCount < maxConnections else { Logger.debug("max connections reached") return } Logger.debug("peripheralsToConnect count=\(peripheralsToConnect.count), connectingCount=\(connectingCount)") while let peripheralIdentifier = peripheralsToConnect.shift() { guard let peripheral = Singletons.discoveryManager.discoveredPeripherals[peripheralIdentifier] else { Logger.debug("peripheral with identifier '\(peripheralIdentifier.uuidString)' not found in discovery manager") restartConnectionUpdatesIfNecessary() continue } Logger.debug("Connecting peripheral '\(peripheral.name)', \(peripheral.identifier.uuidString), timeout count=\(peripheral.timeoutCount), disconnect count=\(peripheral.disconnectionCount)") connectingPeripherals.insert(peripheral.identifier) connect(peripheral) connectingCount += 1 guard connectingCount < maxConnections else { Logger.debug("max connections reached") return } } } func disconnectPeripheralsToDisconnect() { Logger.debug("peripheralsToDisconnect count=\(peripheralsToDisconnect.count), connectingCount=\(connectingPeripherals.count)") while let peripheralIdentifier = peripheralsToDisconnect.shift() { guard let peripheral = Singletons.discoveryManager.discoveredPeripherals[peripheralIdentifier] else { Logger.debug("peripheral with identifier '\(peripheralIdentifier.uuidString)' not found") continue } Logger.debug("Disconnecting peripheral: '\(peripheral.name)', \(peripheral.identifier.uuidString)") peripheral.disconnect() } } func updatePeripheralConnectionsIfNecessary() { guard canScanAndConnect else { Logger.debug("connection updates paused") return } Logger.debug("update peripheral connections") Queue.main.delay(Params.updateConnectionsInterval) { [weak self] in self.forEach { strongSelf in strongSelf.disconnectPeripheralsToDisconnect() strongSelf.connectPeripheralsToConnect() strongSelf.updateWhenActive() strongSelf.updatePeripheralConnectionsIfNecessary() } } } func connect(_ peripheral: Peripheral) { Logger.debug("Connect peripheral '\(peripheral.name)'', \(peripheral.identifier.uuidString), timeout count=\(peripheral.timeoutCount), disconnect count=\(peripheral.disconnectionCount)") let connectionTimeout = ConfigStore.getPeripheralConnectionTimeoutEnabled() ? Double(ConfigStore.getPeripheralConnectionTimeout()) : Double.infinity let connectionFuture = peripheral.connect(connectionTimeout: connectionTimeout, capacity: 10) connectionFuture.onSuccess { [weak self, weak peripheral] _ in guard let peripheral = peripheral else { return } self.forEach { strongSelf in Logger.debug("Connected peripheral '\(peripheral.name)', \(peripheral.identifier.uuidString), timeout count=\(peripheral.timeoutCount), disconnect count=\(peripheral.disconnectionCount)") strongSelf.connectedPeripherals.insert(peripheral.identifier) strongSelf.discoverServices(peripheral) strongSelf.updateWhenActive() } } connectionFuture.onFailure { [weak self, weak peripheral] error in guard let peripheral = peripheral else { return } self.forEach { strongSelf in let maxTimeouts = ConfigStore.getPeripheralMaximumTimeoutsEnabled() ? ConfigStore.getPeripheralMaximumTimeouts() : UInt.max let maxDisconnections = ConfigStore.getPeripheralMaximumDisconnectionsEnabled() ? ConfigStore.getPeripheralMaximumDisconnections() : UInt.max Logger.debug("Connection failed: '\(peripheral.name)', \(peripheral.identifier.uuidString), timeout count=\(peripheral.timeoutCount), max timeouts=\(maxTimeouts), disconnect count=\(peripheral.disconnectionCount), max disconnections=\(maxDisconnections)") switch error { case PeripheralError.forcedDisconnect: Logger.debug("Forced Disconnection '\(peripheral.name)', \(peripheral.identifier.uuidString)") strongSelf.connectingPeripherals.remove(peripheral.identifier) strongSelf.startScanAndConnectingIfNotPaused() strongSelf.restartConnectionUpdatesIfNecessary() if !strongSelf.discoveredPeripherals.contains(peripheral.identifier) { strongSelf.removedPeripherals.insert(peripheral.identifier) peripheral.terminate() strongSelf.connectedPeripherals.remove(peripheral.identifier) strongSelf.updateWhenActive() } return case PeripheralError.connectionTimeout: if peripheral.timeoutCount < maxTimeouts { Logger.debug("Connection timeout retrying '\(peripheral.name)', \(peripheral.identifier.uuidString), timeout count=\(peripheral.timeoutCount), max timeouts=\(maxTimeouts)") peripheral.reconnect(withDelay: 1.0) return } default: if peripheral.disconnectionCount < maxDisconnections { peripheral.reconnect(withDelay: 1.0) Logger.debug("Disconnected retrying '\(peripheral.name)', \(peripheral.identifier.uuidString), disconnect count=\(peripheral.disconnectionCount), max disconnections=\(maxDisconnections)") return } } Logger.debug("Connection failed giving up '\(error), \(peripheral.name)', \(peripheral.identifier.uuidString)") strongSelf.connectingPeripherals.remove(peripheral.identifier) strongSelf.startScanAndConnectingIfNotPaused() strongSelf.restartConnectionUpdatesIfNecessary() strongSelf.removedPeripherals.insert(peripheral.identifier) peripheral.terminate() strongSelf.connectedPeripherals.remove(peripheral.identifier) strongSelf.updateWhenActive() } } } func restartConnectionUpdatesIfNecessary() { guard peripheralsToConnect.isEmpty else { return } Logger.debug("restart connection updates") connectedPeripherals.removeAll() connectingPeripherals.removeAll() peripheralsToConnect.set(peripherals) } // MARK: Service Scanning func pauseScanAndConnecting() { guard canScanAndConnect else { return } canScanAndConnect = false Singletons.scanningManager.stopScanning() } func resumeScanAndConnecting() { guard !canScanAndConnect else { return } canScanAndConnect = true startScanIfNotScanning() } func startScanAndConnectingIfNotPaused() { guard canScanAndConnect else { return } startScanIfNotScanning() } func stopScanIfDiscoverLimitReached() { guard atDiscoveryLimit else { return } Singletons.scanningManager.stopScanning() } @objc func toggleScan(_ sender: AnyObject) { guard !Singletons.beaconManager.isMonitoring else { present(UIAlertController.alert(message: "iBeacon monitoring is active. Cannot scan and monitor iBeacons simutaneously. Stop iBeacon monitoring to start scan"), animated:true, completion:nil) return } guard Singletons.discoveryManager.poweredOn else { present(UIAlertController.alert(message: "Bluetooth is not enabled. Enable Bluetooth in settings."), animated:true, completion:nil) return } guard Singletons.scanningManager.poweredOn else { present(UIAlertController.alert(message: "Bluetooth is not enabled. Enable Bluetooth in settings."), animated:true, completion:nil) return } if scanEnabled { Logger.debug("Scan toggled off") scanEnabled = false disconnectConnectingPeripherals() stopScan() } else { Logger.debug("Scan toggled on") scanEnabled = true startScanIfNotScanning() updatePeripheralConnectionsIfNecessary() } setScanButton() } func startScanIfNotScanning() { guard scanEnabled else { return } guard !atDiscoveryLimit else { return } guard !Singletons.scanningManager.isScanning else { return } let scanOptions = [CBCentralManagerScanOptionAllowDuplicatesKey : true] let future: FutureStream<Peripheral> let scanMode = ConfigStore.getScanMode() let scanDuration = ConfigStore.getScanDurationEnabled() ? Double(ConfigStore.getScanDuration()) : Double.infinity switch scanMode { case .promiscuous: future = Singletons.scanningManager.startScanning(capacity:10, timeout: scanDuration, options: scanOptions) case .service: let scannedServices = ConfigStore.getScannedServiceUUIDs() guard scannedServices.isEmpty == false else { present(UIAlertController.alert(message: "No scan services configured"), animated: true) return } future = Singletons.scanningManager.startScanning(forServiceUUIDs: scannedServices, capacity: 10, timeout: scanDuration, options: scanOptions) } future.onSuccess(completion: afterPeripheralDiscovered) future.onFailure(completion: afterTimeout) } func afterTimeout(error: Swift.Error) -> Void { guard let error = error as? CentralManagerError, error == .serviceScanTimeout else { return } Logger.debug("timeoutScan: timing out") stopScanAndToggleOff() setScanButton() present(UIAlertController.alert(message: "Bluetooth scan timeout."), animated:true) } func afterPeripheralDiscovered(_ peripheral: Peripheral?) -> Void { updateWhenActive() guard let peripheral = peripheral else { return } guard Singletons.discoveryManager.discoveredPeripherals[peripheral.identifier] == nil else { Logger.debug("Peripheral already discovered \(peripheral.name), \(peripheral.identifier.uuidString)") return } guard !removedPeripherals.contains(peripheral.identifier) else { Logger.debug("Peripheral has been removed \(peripheral.name), \(peripheral.identifier.uuidString)") return } guard Singletons.discoveryManager.retrievePeripherals(withIdentifiers: [peripheral.identifier]).first != nil else { Logger.debug("Discovered peripheral not found") return } Logger.debug("Discovered peripheral: '\(peripheral.name)', \(peripheral.identifier.uuidString)") peripheralsToConnect.push(peripheral.identifier) peripheralAdvertisments[peripheral.identifier] = peripheral.advertisements stopScanIfDiscoverLimitReached() } func stopScanAndToggleOff() { scanEnabled = false stopScan() } func stopScan() { Singletons.scanningManager.stopScanning() Singletons.discoveryManager.removeAllPeripherals() Singletons.scanningManager.removeAllPeripherals() connectingPeripherals.removeAll() connectedPeripherals.removeAll() discoveredPeripherals.removeAll() removedPeripherals.removeAll() peripheralsToConnect.removeAll() peripheralsToDisconnect.removeAll() updateWhenActive() } // MARK: Service Discovery func discoverServices(_ peripheral: Peripheral) { guard peripheral.state == .connected else { return } guard !discoveredPeripherals.contains(peripheral.identifier) else { peripheralsToDisconnect.push(peripheral.identifier) return } Logger.debug("Discovering service for peripheral: '\(peripheral.name)', \(peripheral.identifier.uuidString)") let scanTimeout = TimeInterval(ConfigStore.getCharacteristicReadWriteTimeout()) let peripheralDiscoveryFuture = peripheral.discoverAllServices(timeout: scanTimeout).flatMap { [weak peripheral] () -> Future<[Void]> in guard let peripheral = peripheral else { throw AppError.unlikelyFailure } return peripheral.services.map { $0.discoverAllCharacteristics(timeout: scanTimeout) }.sequence() } peripheralDiscoveryFuture.onSuccess { [weak self, weak peripheral] (_) -> Void in guard let peripheral = peripheral else { return } self.forEach { strongSelf in Logger.debug("Service discovery successful peripheral: '\(peripheral.name)', \(peripheral.identifier.uuidString)") strongSelf.discoveredPeripherals.insert(peripheral.identifier) strongSelf.peripheralsToDisconnect.push(peripheral.identifier) strongSelf.updateWhenActive() } } peripheralDiscoveryFuture.onFailure { [weak self, weak peripheral] (error) -> Void in guard let peripheral = peripheral else { return } self.forEach { strongSelf in Logger.debug("Service discovery failed peripheral: \(error), \(peripheral.name), \(peripheral.identifier.uuidString)") strongSelf.peripheralsToDisconnect.push(peripheral.identifier) strongSelf.updateWhenActive() } } } // MARK: UITableViewDataSource override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_: UITableView, numberOfRowsInSection section: Int) -> Int { return atDiscoveryLimit ? ConfigStore.getMaximumPeripheralsDiscovered() : Singletons.discoveryManager.peripherals.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: MainStoryboard.peripheralCell, for: indexPath) as! PeripheralCell let peripheral = peripherals[indexPath.row] cell.nameLabel.text = peripheral.name if peripheral.state == .connected || discoveredPeripherals.contains(peripheral.identifier) { cell.nameLabel.textColor = UIColor.black } else { cell.nameLabel.textColor = UIColor.lightGray } if peripheral.state == .connected { cell.nameLabel.textColor = UIColor.black cell.stateLabel.text = "Connected" cell.stateLabel.textColor = UIColor(red:0.1, green:0.7, blue:0.1, alpha:0.5) } else if connectedPeripherals.contains(peripheral.identifier) && discoveredPeripherals.contains(peripheral.identifier) && connectingPeripherals.contains(peripheral.identifier) { cell.stateLabel.text = "Discovered" cell.stateLabel.textColor = UIColor(red:0.4, green:0.75, blue:1.0, alpha:0.5) } else if discoveredPeripherals.contains(peripheral.identifier) && connectingPeripherals.contains(peripheral.identifier) { cell.stateLabel.text = "Connecting" cell.stateLabel.textColor = UIColor(red:0.7, green:0.1, blue:0.1, alpha:0.5) } else if discoveredPeripherals.contains(peripheral.identifier) { cell.stateLabel.text = "Discovered" cell.stateLabel.textColor = UIColor(red:0.4, green:0.75, blue:1.0, alpha:0.5) } else if connectingPeripherals.contains(peripheral.identifier) { cell.stateLabel.text = "Connecting" cell.stateLabel.textColor = UIColor(red:0.7, green:0.1, blue:0.1, alpha:0.5) } else { cell.stateLabel.text = "Disconnected" cell.stateLabel.textColor = UIColor.lightGray } updateRSSI(peripheral: peripheral, cell: cell) cell.servicesLabel.text = "\(peripheral.services.count)" return cell } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let peripheral = peripherals[indexPath.row] if !connectingPeripherals.contains(peripheral.identifier) { pauseScanAndConnecting() disconnectConnectingPeripherals() } } func updateRSSI(peripheral: Peripheral, cell: PeripheralCell) { guard let discoveredPeripheral = Singletons.scanningManager.discoveredPeripherals[peripheral.identifier] else { cell.rssiImage.image = #imageLiteral(resourceName: "RSSI-0") cell.rssiLabel.text = "NA" return } cell.rssiLabel.text = "\(discoveredPeripheral.RSSI)" let rssiImage: UIImage switch discoveredPeripheral.RSSI { case (-40)...(-1): rssiImage = #imageLiteral(resourceName: "RSSI-5") case (-55)...(-41): rssiImage = #imageLiteral(resourceName: "RSSI-4") case (-70)...(-56): rssiImage = #imageLiteral(resourceName: "RSSI-3") case (-85)...(-71): rssiImage = #imageLiteral(resourceName: "RSSI-2") case (-99)...(-86): rssiImage = #imageLiteral(resourceName: "RSSI-1") default: rssiImage = #imageLiteral(resourceName: "RSSI-0") } cell.rssiImage.image = rssiImage } }
mit
15e6799c546b757437984adf4f4adc00
42.293839
271
0.638278
5.453731
false
false
false
false
hulinSun/MyRx
MyRx/MyRx/Classes/Main/Helper/MusicPlayer.swift
1
10502
// // MusicPlayer.swift // MyRx // // Created by Hony on 2017/1/12. // Copyright © 2017年 Hony. All rights reserved. // import UIKit import AVFoundation import RxSwift import RxCocoa import MediaPlayer class MusicPlayer: NSObject { let bag = DisposeBag() var musics: [Music] // 所有的歌曲 var index: Int = 0 // 当前播放的歌曲索引 var player: AVPlayer! var currentPlayItem: AVPlayerItem! var first: Bool = true /// 标记第一次添加的通知。第一次没播放的不添加通知 var timerReturn: Any! var currentTime: Float64! = 0 var allTime: Float64! = 0 /// 初始化方法 init(musics: [Music]) { self.musics = musics super.init() remoteControl() configPlayback() setupPlayer() addPlayEndObserve() // 播放结束的通知 } /// 默认播放的是第一首歌 private func setupPlayer(){ // MARK: 这里默认去第一个的目的是先让aplayer 有值 index = 0 let initMusic = musics[index] guard let mp3 = initMusic.infos?.mp3 else { return } if let item = mp3.playItem(){ player = AVPlayer(playerItem: item) } } /// 播放第几个歌曲 ---> 这里才是真正的播放.所以在这里做KVO操作 private func play(at idx: Int){ currentTime = 0 allTime = 0 let initMusic = musics[idx] index = idx guard let mp3 = initMusic.infos?.mp3 else { return } if let item = mp3.playItem(){ if !first{ removeAllObser()} player.replaceCurrentItem(with: item) player.play() print("播放歌曲名\(initMusic.infos?.title)") first = false // 第一次没有了 = = addAllObser() configNowPlayingCenterInfo(with: initMusic) }else{ print("初始化item 失败") } } /// 播放制定歌曲 func play(music: Music) { // 获取index let idx = musics.index { (m) -> Bool in return m.infos?.mp3 == music.infos?.mp3 } if let d = idx{ play(at: d) } } /// kvo监听item改变 private func addobserToItem(playItem: AVPlayerItem){ // 播放状态 playItem.addObserver(self, forKeyPath: #keyPath(AVPlayerItem.status), options: NSKeyValueObservingOptions.new, context: nil) /// 缓冲 playItem.addObserver(self, forKeyPath: #keyPath(AVPlayerItem.loadedTimeRanges), options: NSKeyValueObservingOptions.new, context: nil) // 缓冲区空了,需要等待数据 playItem.addObserver(self, forKeyPath: #keyPath(AVPlayerItem.isPlaybackBufferEmpty), options: NSKeyValueObservingOptions.new, context: nil) // 缓冲区有足够数据可以播放了 playItem.addObserver(self, forKeyPath: #keyPath(AVPlayerItem.isPlaybackLikelyToKeepUp), options: NSKeyValueObservingOptions.new, context: nil) } private func removeObserToitem(playItem: AVPlayerItem){ playItem.removeObserver(self, forKeyPath: #keyPath(AVPlayerItem.status)) playItem.removeObserver(self, forKeyPath: #keyPath(AVPlayerItem.loadedTimeRanges)) playItem.removeObserver(self, forKeyPath: #keyPath(AVPlayerItem.isPlaybackBufferEmpty)) playItem.removeObserver(self, forKeyPath: #keyPath(AVPlayerItem.isPlaybackLikelyToKeepUp)) } override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { let item = player.currentItem! guard let key = keyPath , let changeValue = change else { return } let new = changeValue[.newKey] switch key { case "status": if let status = new as? AVPlayerStatus, status == AVPlayerStatus.readyToPlay{ print("正在播放\(CMTimeGetSeconds(item.duration))") } case "loadedTimeRanges": // 计算缓冲进度 if let timeInterVarl = self.availableDuration() { print("缓冲\(timeInterVarl)") } case "playbackBufferEmpty": print("playbackBufferEmpty \(new!)") case "playbackLikelyToKeepUp": print("playbackLikelyToKeepUp \(new!)") default: print("--") } } /// 添加播放结束通知 private func addPlayEndObserve() { NotificationCenter.default.addObserver(self, selector: #selector(playend), name: Notification.Name.AVPlayerItemDidPlayToEndTime, object: nil) } func playend() { self.next() } /// 移除通知 private func removePlayEndObser(){ NotificationCenter.default.removeObserver(self) } /// 添加播放进度通知 private func progressObser(){ if let playItem = player.currentItem{ let time = CMTime(value: CMTimeValue(1.0), timescale: CMTimeScale(1.0)) // FIXME: 这里返回的是AVPeriodicTimebaseObserver 私有类,需要移除这个监听 timerReturn = player.addPeriodicTimeObserver(forInterval: time, queue: DispatchQueue.main, using: { (t) in let current = CMTimeGetSeconds(t) let total = CMTimeGetSeconds(playItem.duration) print("当前 \(current) 总时长 \(total)") self.currentTime = current self.allTime = total }) } } /// 移除播放进度通知 private func removeprogressObser(){ //MARK: 注意这里的释放方法,一定要释放。不然那个方法会走很多次 player.removeTimeObserver(timerReturn) } /// 计算缓冲时长 fileprivate func availableDuration() -> TimeInterval? { if let loadedTimeRanges = player.currentItem?.loadedTimeRanges, let first = loadedTimeRanges.first { let timeRange = first.timeRangeValue // 本次缓冲时长 let startSeconds = CMTimeGetSeconds(timeRange.start) let durationSecound = CMTimeGetSeconds(timeRange.duration) let result = startSeconds + durationSecound return result } return nil } /// 下一首 func next() { if index == musics.count - 1{ // 最后一首 // 播放第一首 play(at: 0) }else{ let i = index + 1 play(at: i ) } } /// 上一首 func previous() { if index == 0{ play(at: musics.count - 1) }else{ let i = index - 1 play(at: i) } } /// 暂停 func pause() { player.pause() } /// 继续播放 func resumu(){ // 继续播放 self.player.play() } deinit { removeAllObser() NotificationCenter.default.removeObserver(self, name: Notification.Name.AVPlayerItemDidPlayToEndTime, object: nil) } /// 添加所有通知 private func addAllObser(){ progressObser() // 进度 if let item = player.currentItem{ addobserToItem(playItem: item) // kvo } } /// 移除所有通知 private func removeAllObser(){ removeprogressObser() if let item = player.currentItem{ removeObserToitem(playItem: item) } } /// 设置后台播放 private func configPlayback(){ let session = AVAudioSession.sharedInstance() do{ try session.setActive(true) try session.setCategory(AVAudioSessionCategoryPlayback) }catch{ print(error) } } /// 配置锁屏状态下的数据 private func configNowPlayingCenterInfo(with music: Music){ guard let mp3 = music.infos?.mp3 else { return } var dict = [String: Any]() if let urlStr = mp3.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed), let url = URL(string: urlStr){ let audioAsset = AVURLAsset(url: url, options: nil) let audioDurationSeconds = CMTimeGetSeconds(audioAsset.duration) dict[MPMediaItemPropertyTitle] = music.infos?.title ?? "标题" dict[MPMediaItemPropertyArtist] = music.infos?.author ?? "作者" // dict[MPMediaItemPropertyAlbumTitle] = "相册的名字" dict[MPMediaItemPropertyPlaybackDuration] = "\(audioDurationSeconds)" let work = MPMediaItemArtwork(image: randomImage()) dict[MPMediaItemPropertyArtwork] = work MPNowPlayingInfoCenter.default().nowPlayingInfo = dict } } private func randomImage()-> UIImage{ let i = arc4random_uniform(6) + 1 let imgName = "d\(i)" return UIImage(named: imgName)! } /// 远程事件 private func remoteControl(){ /// MARK: 这句话一定要写,不然锁屏状态下不会显示图片 UIApplication.shared.beginReceivingRemoteControlEvents() /// 播放事件 MPRemoteCommandCenter.shared().playCommand.addTarget { (event) -> MPRemoteCommandHandlerStatus in print("点击了播放") self.resumu() return .success } /// 暂停事件 MPRemoteCommandCenter.shared().pauseCommand.addTarget { (event) -> MPRemoteCommandHandlerStatus in print("点击了暂停") self.pause() return .success } /// 下一首 MPRemoteCommandCenter.shared().nextTrackCommand.addTarget { (event) -> MPRemoteCommandHandlerStatus in self.next() print("点击了下一首") return .success } /// 上一首 MPRemoteCommandCenter.shared().previousTrackCommand.addTarget { (event) -> MPRemoteCommandHandlerStatus in print("点击了上一首") self.previous() return .success } } } private extension String{ func playItem() -> AVPlayerItem? { if self.isEmpty { return nil } if let urlString = self.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) , let url = URL.init(string: urlString){ return AVPlayerItem(url: url) }else{ return nil } } }
mit
7483946f899e04094648c2efa4bf6565
30.697068
151
0.587093
4.611848
false
false
false
false
swordfishyou/fieldstool
FieldTool/Sources/Annotations/FieldAnnotation.swift
1
557
// // FieldAnnotation.swift // FieldTool // // Created by Anatoly Tukhtarov on 2/18/17. // Copyright © 2017 Anatoly Tukhtarov. All rights reserved. // import MapKit class FieldAnnotation: MKPointAnnotation, GeometryAnnotation { typealias Object = Field var object: Field required init(object: Field) { self.object = object super.init() self.title = object.title self.subtitle = object.subtitle } func set(coordinate: CLLocationCoordinate2D) { self.coordinate = coordinate } }
mit
ebbb31f8df2b06be38be35e0a9960ef1
21.24
62
0.656475
4
false
false
false
false
apple/swift
test/Generics/invalid.swift
4
5733
// RUN: %target-typecheck-verify-swift protocol he where A : B { // expected-error {{cannot find type 'A' in scope}} // expected-error@-1 {{cannot find type 'B' in scope}} associatedtype vav where A : B // expected-error{{cannot find type 'A' in scope}} // expected-error@-1 {{cannot find type 'B' in scope}} } struct Lunch<T> { struct Dinner<U> { var leftovers: T var transformation: (T) -> U } } class Deli<Spices> { // expected-note {{'Spices' declared as parameter to type 'Deli'}} // expected-note@-1 {{arguments to generic parameter 'Spices' ('Pepper' and 'ChiliFlakes') are expected to be equal}} class Pepperoni {} struct Sausage {} } struct Pizzas<Spices> { // expected-note {{arguments to generic parameter 'Spices' ('ChiliFlakes' and 'Pepper') are expected to be equal}} class NewYork { } class DeepDish { } } class HotDog { } struct Pepper {} struct ChiliFlakes {} func eatDinnerConcrete(d: Pizzas<ChiliFlakes>.NewYork, t: Deli<ChiliFlakes>.Pepperoni) { } func eatDinnerConcrete(d: Pizzas<Pepper>.DeepDish, t: Deli<Pepper>.Pepperoni) { } func badDiagnostic1() { _ = Lunch<Pizzas<Pepper>.NewYork>.Dinner<HotDog>( leftovers: Pizzas<ChiliFlakes>.NewYork(), // expected-error {{cannot convert parent type 'Pizzas<ChiliFlakes>' to expected type 'Pizzas<Pepper>'}} transformation: { _ in HotDog() }) } func badDiagnostic2() { let firstCourse = Pizzas<ChiliFlakes>.NewYork() var dinner = Lunch<Pizzas<ChiliFlakes>.NewYork>.Dinner<HotDog>( leftovers: firstCourse, transformation: { _ in HotDog() }) let topping = Deli<Pepper>.Pepperoni() eatDinnerConcrete(d: firstCourse, t: topping) // expected-error@-1 {{cannot convert parent type 'Deli<Pepper>' to expected type 'Deli<ChiliFlakes>'}} } // Real error is that we cannot infer the generic parameter from context func takesAny(_ a: Any) {} func badDiagnostic3() { takesAny(Deli.self) // expected-error {{generic parameter 'Spices' could not be inferred}} // expected-note@-1 {{explicitly specify the generic arguments to fix this issue}} {{16-16=<Any>}} } // Crash with missing nested type inside concrete type class OuterGeneric<T> { class InnerGeneric<U> where U:OuterGeneric<T.NoSuchType> { // expected-error@-1 {{'NoSuchType' is not a member type of type 'T'}} func method() { _ = method } } } // Crash with missing types in requirements. protocol P1 { associatedtype A where A == ThisTypeDoesNotExist // expected-error@-1{{cannot find type 'ThisTypeDoesNotExist' in scope}} associatedtype B where ThisTypeDoesNotExist == B // expected-error@-1{{cannot find type 'ThisTypeDoesNotExist' in scope}} associatedtype C where ThisTypeDoesNotExist == ThisTypeDoesNotExist // expected-error@-1 2{{cannot find type 'ThisTypeDoesNotExist' in scope}} } // Diagnostic referred to the wrong type - <rdar://problem/33604221> protocol E { associatedtype XYZ } class P<N> { func q<A>(b:A) where A:E, N : A.XYZ { return } // expected-error@-1 {{type 'N' constrained to non-protocol, non-class type 'A.XYZ'}} } // https://github.com/apple/swift/issues/48151 protocol Foo { associatedtype Bar where Bar.Nonsense == Int // expected-error{{'Nonsense' is not a member type of type 'Self.Bar'}} } protocol Wibble : Foo where Bar.EvenMoreNonsense == Int { } // expected-error{{'EvenMoreNonsense' is not a member type of type 'Self.Bar'}} // rdar://45271500 - failure to emit a diagnostic enum Cat<A> {} protocol Tail { associatedtype T } struct Dog<B, C : Tail> where C.T == B {} func foo<B, A>() -> Dog<B, Cat<A>> {} // expected-error@-1 {{type 'Cat<A>' does not conform to protocol 'Tail'}} // Tests for generic argument mismatch diagnosis struct X<A> : Hashable { class Foo {} class Bar {} } // expected-note@-4 3 {{arguments to generic parameter 'A' ('Int' and 'Bool') are expected to be equal}} // expected-note@-5 2 {{arguments to generic parameter 'A' ('Bool' and 'Int') are expected to be equal}} // expected-note@-6 4 {{arguments to generic parameter 'A' ('Int' and 'Bool') are expected to be equal}} struct Y<A, B, C>{} // expected-note {{arguments to generic parameter 'A' ('Int' and 'Bool') are expected to be equal}} // expected-note@-1 {{arguments to generic parameter 'C' ('Int' and 'Float') are expected to be equal}} struct YieldValue { var property: X<Bool> { _read { yield X<Int>() // expected-error {{cannot convert value of type 'X<Int>' to expected yield type 'X<Bool>'}} } } } func multipleArguments(y: Y<Int, Int, Int>) { let _: Y<Bool, Int, Float> = y // expected-error {{cannot assign value of type 'Y<Int, Int, Int>' to type 'Y<Bool, Int, Float>'}} } func errorMessageVariants(x: X<Int>, x2: X<Bool> = X<Int>()) -> X<Bool> { // expected-error@-1 {{default argument value of type 'X<Int>' cannot be converted to type 'X<Bool>'}} let _: X<Bool> = x // expected-error {{cannot assign value of type 'X<Int>' to type 'X<Bool>'}} errorMessageVariants(x: x2, x2: x2) // expected-error {{cannot convert value of type 'X<Bool>' to expected argument type 'X<Int>'}} let _: X<Bool> = { return x }() // expected-error {{cannot convert value of type 'X<Int>' to closure result type 'X<Bool>'}} let _: [X<Bool>] = [x] // expected-error {{cannot convert value of type 'X<Int>' to expected element type 'X<Bool>'}} let _ = x as X<Bool> // expected-error {{cannot convert value of type 'X<Int>' to type 'X<Bool>' in coercion}} let _: X<Int>.Foo = X<Bool>.Foo() // expected-error {{cannot convert parent type 'X<Bool>' to expected type 'X<Int>'}} return x // expected-error {{cannot convert return expression of type 'X<Int>' to return type 'X<Bool>'}} }
apache-2.0
4123b27ec2b296d0dd75ad13820dacbd
35.75
153
0.673469
3.589856
false
false
false
false
apple/swift
stdlib/public/core/Bitset.swift
3
9826
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2018 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 simple bitmap of a fixed number of bits, implementing a sorted set of /// small nonnegative Int values. /// /// Because `_UnsafeBitset` implements a flat bit vector, it isn't suitable for /// holding arbitrarily large integers. The maximal element a bitset can store /// is fixed at its initialization. @frozen @usableFromInline // @testable internal struct _UnsafeBitset { @usableFromInline internal let words: UnsafeMutablePointer<Word> @usableFromInline internal let wordCount: Int @inlinable @inline(__always) internal init(words: UnsafeMutablePointer<Word>, wordCount: Int) { self.words = words self.wordCount = wordCount } } extension _UnsafeBitset { @inlinable @inline(__always) internal static func word(for element: Int) -> Int { _internalInvariant(element >= 0) // Note: We perform on UInts to get faster unsigned math (shifts). let element = UInt(bitPattern: element) let capacity = UInt(bitPattern: Word.capacity) return Int(bitPattern: element / capacity) } @inlinable @inline(__always) internal static func bit(for element: Int) -> Int { _internalInvariant(element >= 0) // Note: We perform on UInts to get faster unsigned math (masking). let element = UInt(bitPattern: element) let capacity = UInt(bitPattern: Word.capacity) return Int(bitPattern: element % capacity) } @inlinable @inline(__always) internal static func split(_ element: Int) -> (word: Int, bit: Int) { return (word(for: element), bit(for: element)) } @inlinable @inline(__always) internal static func join(word: Int, bit: Int) -> Int { _internalInvariant(bit >= 0 && bit < Word.capacity) return word &* Word.capacity &+ bit } } extension _UnsafeBitset { @inlinable @inline(__always) internal static func wordCount(forCapacity capacity: Int) -> Int { return word(for: capacity &+ Word.capacity &- 1) } @inlinable internal var capacity: Int { @inline(__always) get { return wordCount &* Word.capacity } } @inlinable @inline(__always) internal func isValid(_ element: Int) -> Bool { return element >= 0 && element <= capacity } @inlinable @inline(__always) internal func uncheckedContains(_ element: Int) -> Bool { _internalInvariant(isValid(element)) let (word, bit) = _UnsafeBitset.split(element) return words[word].uncheckedContains(bit) } @inlinable @inline(__always) @discardableResult internal func uncheckedInsert(_ element: Int) -> Bool { _internalInvariant(isValid(element)) let (word, bit) = _UnsafeBitset.split(element) return words[word].uncheckedInsert(bit) } @inlinable @inline(__always) @discardableResult internal func uncheckedRemove(_ element: Int) -> Bool { _internalInvariant(isValid(element)) let (word, bit) = _UnsafeBitset.split(element) return words[word].uncheckedRemove(bit) } @inlinable @inline(__always) internal func clear() { words.update(repeating: .empty, count: wordCount) } } extension _UnsafeBitset: Sequence { @usableFromInline internal typealias Element = Int @inlinable internal var count: Int { var count = 0 for w in 0 ..< wordCount { count += words[w].count } return count } @inlinable internal var underestimatedCount: Int { return count } @inlinable func makeIterator() -> Iterator { return Iterator(self) } @usableFromInline @frozen internal struct Iterator: IteratorProtocol { @usableFromInline internal let bitset: _UnsafeBitset @usableFromInline internal var index: Int @usableFromInline internal var word: Word @inlinable internal init(_ bitset: _UnsafeBitset) { self.bitset = bitset self.index = 0 self.word = bitset.wordCount > 0 ? bitset.words[0] : .empty } @inlinable internal mutating func next() -> Int? { if let bit = word.next() { return _UnsafeBitset.join(word: index, bit: bit) } while (index + 1) < bitset.wordCount { index += 1 word = bitset.words[index] if let bit = word.next() { return _UnsafeBitset.join(word: index, bit: bit) } } return nil } } } //////////////////////////////////////////////////////////////////////////////// extension _UnsafeBitset { @frozen @usableFromInline internal struct Word { @usableFromInline internal var value: UInt @inlinable internal init(_ value: UInt) { self.value = value } } } extension _UnsafeBitset.Word { @inlinable internal static var capacity: Int { @inline(__always) get { return UInt.bitWidth } } @inlinable @inline(__always) internal func uncheckedContains(_ bit: Int) -> Bool { _internalInvariant(bit >= 0 && bit < UInt.bitWidth) return value & (1 &<< bit) != 0 } @inlinable @inline(__always) @discardableResult internal mutating func uncheckedInsert(_ bit: Int) -> Bool { _internalInvariant(bit >= 0 && bit < UInt.bitWidth) let mask: UInt = 1 &<< bit let inserted = value & mask == 0 value |= mask return inserted } @inlinable @inline(__always) @discardableResult internal mutating func uncheckedRemove(_ bit: Int) -> Bool { _internalInvariant(bit >= 0 && bit < UInt.bitWidth) let mask: UInt = 1 &<< bit let removed = value & mask != 0 value &= ~mask return removed } } extension _UnsafeBitset.Word { @inlinable var minimum: Int? { @inline(__always) get { guard value != 0 else { return nil } return value.trailingZeroBitCount } } @inlinable var maximum: Int? { @inline(__always) get { guard value != 0 else { return nil } return _UnsafeBitset.Word.capacity &- 1 &- value.leadingZeroBitCount } } @inlinable var complement: _UnsafeBitset.Word { @inline(__always) get { return _UnsafeBitset.Word(~value) } } @inlinable @inline(__always) internal func subtracting(elementsBelow bit: Int) -> _UnsafeBitset.Word { _internalInvariant(bit >= 0 && bit < _UnsafeBitset.Word.capacity) let mask = UInt.max &<< bit return _UnsafeBitset.Word(value & mask) } @inlinable @inline(__always) internal func intersecting(elementsBelow bit: Int) -> _UnsafeBitset.Word { _internalInvariant(bit >= 0 && bit < _UnsafeBitset.Word.capacity) let mask: UInt = (1 as UInt &<< bit) &- 1 return _UnsafeBitset.Word(value & mask) } @inlinable @inline(__always) internal func intersecting(elementsAbove bit: Int) -> _UnsafeBitset.Word { _internalInvariant(bit >= 0 && bit < _UnsafeBitset.Word.capacity) let mask = (UInt.max &<< bit) &<< 1 return _UnsafeBitset.Word(value & mask) } } extension _UnsafeBitset.Word { @inlinable internal static var empty: _UnsafeBitset.Word { @inline(__always) get { return _UnsafeBitset.Word(0) } } @inlinable internal static var allBits: _UnsafeBitset.Word { @inline(__always) get { return _UnsafeBitset.Word(UInt.max) } } } // Word implements Sequence by using a copy of itself as its Iterator. // Iteration with `next()` destroys the word's value; however, this won't cause // problems in normal use, because `next()` is usually called on a separate // iterator, not the original word. extension _UnsafeBitset.Word: Sequence, IteratorProtocol { @inlinable internal var count: Int { return value.nonzeroBitCount } @inlinable internal var underestimatedCount: Int { return count } @inlinable internal var isEmpty: Bool { @inline(__always) get { return value == 0 } } /// Return the index of the lowest set bit in this word, /// and also destructively clear it. @inlinable internal mutating func next() -> Int? { guard value != 0 else { return nil } let bit = value.trailingZeroBitCount value &= value &- 1 // Clear lowest nonzero bit. return bit } } extension _UnsafeBitset { @_alwaysEmitIntoClient @inline(__always) internal static func _withTemporaryUninitializedBitset<R>( wordCount: Int, body: (_UnsafeBitset) throws -> R ) rethrows -> R { try withUnsafeTemporaryAllocation( of: _UnsafeBitset.Word.self, capacity: wordCount ) { buffer in let bitset = _UnsafeBitset( words: buffer.baseAddress!, wordCount: buffer.count) return try body(bitset) } } @_alwaysEmitIntoClient @inline(__always) internal static func withTemporaryBitset<R>( capacity: Int, body: (_UnsafeBitset) throws -> R ) rethrows -> R { let wordCount = Swift.max(1, Self.wordCount(forCapacity: capacity)) return try _withTemporaryUninitializedBitset( wordCount: wordCount ) { bitset in bitset.clear() return try body(bitset) } } } extension _UnsafeBitset { @_alwaysEmitIntoClient @inline(__always) internal static func withTemporaryCopy<R>( of original: _UnsafeBitset, body: (_UnsafeBitset) throws -> R ) rethrows -> R { try _withTemporaryUninitializedBitset( wordCount: original.wordCount ) { bitset in bitset.words.initialize(from: original.words, count: original.wordCount) return try body(bitset) } } }
apache-2.0
c121d5625d138ae532a7b32e09f97b5e
24.390181
80
0.642276
4.183057
false
false
false
false
nRewik/SimplePDF
ExampleCode.swift
1
3137
import UIKit import SimplePDF let a4PaperSize = CGSize(width: 595, height: 842) let pdf = SimplePDF(pageSize: a4PaperSize) pdf.setContentAlignment(.Center) // add logo image let logoImage = UIImage(named:"simple_pdf_logo")! pdf.addImage(logoImage) pdf.addLineSpace(30) pdf.setContentAlignment(.Left) pdf.addText("Normal text follows by line separator") pdf.addLineSeparator() pdf.addLineSpace(20.0) pdf.setContentAlignment(.Right) pdf.addText("Text after set content alignment to .Right") pdf.addLineSpace(20.0) pdf.addText("Cras quis eros orci.\nLorem ipsum dolor sit amet, consectetur adipiscing elit.\nDonec mollis vitae mi ut lobortis.\nUt ultrices mi vel neque venenatis, ut efficitur metus eleifend. Sed pellentesque lobortis est quis maximus. Maecenas ultricies risus et enim consectetur, id lobortis ante porta. Quisque at euismod enim. Vestibulum faucibus purus non justo fringilla, sit amet iaculis ex pellentesque. Vestibulum eget vulputate diam, sit amet ornare sem. Duis at eros non tortor malesuada accumsan.\nNunc vel libero ut sapien dictum iaculis a vel odio. Quisque purus turpis, tristique auctor ex non, consectetur scelerisque lorem. Mauris est justo, sollicitudin sit amet nisi a, mattis posuere orci. Sed elementum est at est tristique gravida. Aliquam iaculis, metus facilisis varius viverra, nunc libero ultricies arcu, in accumsan sem nibh vel purus.") pdf.addLineSpace(30) pdf.setContentAlignment(.Center) pdf.addText("Center Text") pdf.addLineSpace(20.0) pdf.addText("Cras varius leo ac lectus malesuada, ut rhoncus nunc blandit.\n In venenatis diam et vehicula suscipit.\n Aliquam in ante at dolor sodales consectetur ut semper quam.\n Vivamus massa purus, congue sed leo sed, lobortis consectetur lacus. Nunc sed tortor nec augue mattis faucibus. Sed malesuada metus in sapien efficitur, ut aliquet nisl lobortis. Vestibulum faucibus purus non justo fringilla, sit amet iaculis ex pellentesque. Vestibulum eget vulputate diam, sit amet ornare sem. Aliquam erat volutpat. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Proin scelerisque posuere mi, non consequat mauris auctor a. Fusce lacinia auctor lectus a elementum.") pdf.addLineSpace(30.0) pdf.setContentAlignment(.Left) let textString = "This is an example of long text. If the text doesn't fit in the current page. Simple pdf will draw a part of text, and automatically begin a new page to draw the remaining text. This process will be repeated until there's no text left to draw. " pdf.addText(textString) pdf.beginNewPage() pdf.addText("Begin new page") // Generate PDF data and save to a local file. if let documentDirectories = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).first { let fileName = "example.pdf" let documentsFileName = documentDirectories + "/" + fileName let pdfData = pdf.generatePDFdata() do{ try pdfData.writeToFile(documentsFileName, options: .DataWritingAtomic) print("\nThe generated pdf can be found at:") print("\n\t\(documentsFileName)\n") }catch{ print(error) } }
mit
c4ccf2308db4ee9e6d8a0b08bf5ba129
51.283333
866
0.779088
4.205094
false
false
false
false
zhouhao27/WOWRibbonView
WOWRibbonView/Classes/WOWRibbonView.swift
1
8063
// // WOWRibbonView.swift // WOWRibbonView // // Created by Zhou Hao on 27/10/16. // Copyright © 2016年 Zhou Hao. All rights reserved. // import UIKit @IBDesignable open class WOWRibbonView: UIView { // MARK: properties // rift or arrow, default to arrow @IBInspectable open var isRift : Bool = false { didSet { refreshConstraints() refreshDisplay() } } @IBInspectable open var length : CGFloat = 5.0 { didSet { refreshConstraints() refreshDisplay() } } // left or right, default to right @IBInspectable open var isLeft : Bool = false { didSet { refreshConstraints() refreshDisplay() } } // TODO: this is not supported by IB so I don't use them at the timebeing // private var _padding : UIEdgeInsets = UIEdgeInsetsMake(5, 10, 5, 10) // @IBInspectable // var padding: UIEdgeInsets { // get { // return _padding // } // set(newPadding) { // _padding = newPadding // refreshDisplay() // } // } @IBInspectable open var top : CGFloat = 5.0 { didSet { refreshConstraints() } } @IBInspectable open var left : CGFloat = 10.0 { didSet { refreshConstraints() } } @IBInspectable open var right : CGFloat = 10.0 { didSet { refreshConstraints() } } @IBInspectable open var bottom : CGFloat = 5.0 { didSet { refreshConstraints() } } @IBInspectable open var text: String? { get { return _textLabel.text } set(newText) { _textLabel.text = newText refreshDisplay() } } @IBInspectable open var textColor : UIColor { get { return _textLabel.textColor } set(newColor) { _textLabel.textColor = newColor refreshDisplay() } } // TODO: this is not supported to modify through IB @IBInspectable open var textFont : UIFont { get { return _textLabel.font } set(newFont) { _textLabel.font = newFont refreshDisplay() } } @IBInspectable open var textSize : CGFloat = 14.0 { didSet { let origFont = _textLabel.font _textLabel.font = UIFont(name: (origFont?.fontName)!, size: textSize) refreshDisplay() } } @IBInspectable open var borderWidth : CGFloat = 0.0 { didSet { self._shape.lineWidth = borderWidth refreshDisplay() } } @IBInspectable open var borderColor : UIColor = UIColor.clear { didSet { self._shape.strokeColor = borderColor.cgColor refreshDisplay() } } @IBInspectable open var fillColor : UIColor = UIColor.white { didSet { self._shape.fillColor = fillColor.cgColor } } // MARK: private properties private var _textLabel : UILabel = UILabel() private var _shape = CAShapeLayer() private var _verticalConstraints : [NSLayoutConstraint]? private var _horizontalConstraints : [NSLayoutConstraint]? private var _setup : Bool = false // MARK: init override public init(frame: CGRect) { super.init(frame: frame) setup() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override open func awakeFromNib() { setup() } // MARK: private methods // one time setup func setup() { if !_setup { _setup = true self._shape.lineCap = kCALineCapRound self._shape.lineJoin = kCALineJoinRound self.layer.addSublayer(_shape) // label on top of layer addSubview(_textLabel) _textLabel.backgroundColor = UIColor.clear _textLabel.translatesAutoresizingMaskIntoConstraints = false self.translatesAutoresizingMaskIntoConstraints = false refreshConstraints() } } func refreshConstraints() { if self._setup { let views : [String : UIView] = ["label" : _textLabel] let formatsH : String = self.isLeft ? "H:|-\(self.left + self.length)-[label]-\(self.right )-|" : "H:|-\(self.left)-[label]-\(self.right + self.length )-|" let formatsV : String = "V:|-\(self.top)-[label]-\(self.bottom)-|" if let vConstraints = self._verticalConstraints { NSLayoutConstraint.deactivate(vConstraints) } self._verticalConstraints = NSLayoutConstraint.constraints(withVisualFormat: formatsV, options: [], metrics: nil, views: views) if let hConstraints = self._horizontalConstraints { NSLayoutConstraint.deactivate(hConstraints) } self._horizontalConstraints = NSLayoutConstraint.constraints(withVisualFormat: formatsH, options: [], metrics: nil, views: views) NSLayoutConstraint.activate(self._verticalConstraints!) NSLayoutConstraint.activate(self._horizontalConstraints!) } // self.setNeedsUpdateConstraints() } func refreshDisplay() { if _setup { self.setNeedsDisplay() } } // MARK: draw override open func draw(_ rect: CGRect) { // TODO: to consider the bounds orgin is not (0,0) let path = UIBezierPath() var p = CGPoint.zero if self.isRift { p.x = 0 p.y = 0 path.move(to: p) p.x = self.bounds.width path.addLine(to: p) if self.isLeft { p.y += self.bounds.height path.addLine(to: p) p.x = 0 path.addLine(to: p) p.x += self.length p.y -= self.bounds.height / 2.0 path.addLine(to: p) } else { p.x -= self.length p.y += self.bounds.height / 2.0 path.addLine(to: p) p.x += self.length p.y += self.bounds.height / 2.0 path.addLine(to: p) p.x = 0 p.y = self.bounds.height path.addLine(to: p) } } else { if self.isLeft { p.x = 0 p.y += self.bounds.height / 2.0 path.move(to: p) p.x += self.length p.y = 0 path.addLine(to: p) p.x = self.bounds.width path.addLine(to: p) p.y += self.bounds.height path.addLine(to: p) p.x = self.length path.addLine(to: p) } else { p.x = 0 p.y = 0 path.move(to: p) p.x = self.bounds.width - self.length path.addLine(to: p) p.x = self.bounds.width p.y += self.bounds.height / 2.0 path.addLine(to: p) p.x = self.bounds.width - self.length p.y += self.bounds.height / 2.0 path.addLine(to: p) p.x = 0 path.addLine(to: p) } } path.close() self._shape.path = path.cgPath } }
mit
a780fdaf18b3aebb346bb0b2e6ee614e
25.084142
167
0.478784
4.911639
false
false
false
false
publickanai/PLMScrollMenu
Pod/Classes/PLScrollMenuAnimator.swift
1
10039
// // PLMScrollMenuAnimator.swift // PLMScrollMenu // // Created by Tatsuhiro Kanai on 2016/03/16. // Copyright © 2016年 Adways Inc. All rights reserved. // import UIKit // MARK: - // MARK: - PLMScrollMenuAnimator internal class PLMScrollMenuAnimator: NSObject , UIViewControllerAnimatedTransitioning { private var _transitionContext : PLMScrollMenuTransitionContext! // This is used for percent driven interactive transitions, as well as for container controllers that have companion animations that might need to // synchronize with the main animation. internal func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval { return 0.2 } // This method can only be a nop if the transition is interactive and not a percentDriven interactive transition. internal func animateTransition(transitionContext: UIViewControllerContextTransitioning) { //print("start animateTransition") let tc:PLMScrollMenuTransitionContext = transitionContext as! PLMScrollMenuTransitionContext let toViewController :UIViewController = tc.viewControllerForKey(UITransitionContextToViewControllerKey)! let fromViewController :UIViewController = tc.viewControllerForKey(UITransitionContextFromViewControllerKey)! transitionContext.containerView()?.addSubview(toViewController.view) transitionContext.containerView()?.insertSubview( toViewController.view, belowSubview: fromViewController.view) _transitionContext = tc; let fromInitialFrame = tc.initialFrameForViewController(fromViewController) let fromFinalFrame = tc.finalFrameForViewController(fromViewController) let toInitialFrame = tc.initialFrameForViewController(toViewController) let toFinalFrame = tc.finalFrameForViewController(toViewController) fromViewController.view.frame = fromInitialFrame; toViewController.view.frame = toInitialFrame; //fromViewController.view.alpha = 1.0; //toViewController.view.alpha = 1.0; CATransaction.begin() var point : CGPoint // Animation of fromView let fromViewAnimation : CABasicAnimation = CABasicAnimation(keyPath: "position") // fromValue point = fromInitialFrame.origin; point.x += fromInitialFrame.size.width*0.5; point.y += fromInitialFrame.size.height*0.5; fromViewAnimation.fromValue = NSValue(CGPoint: point) // toValue point = fromFinalFrame.origin; point.x += fromFinalFrame.size.width*0.5; point.y += fromFinalFrame.size.height*0.5; fromViewAnimation.toValue = NSValue(CGPoint: point) fromViewAnimation.duration = self.transitionDuration(transitionContext) fromViewAnimation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseOut) // Maintain final animation state. fromViewAnimation.removedOnCompletion = false fromViewAnimation.fillMode = kCAFillModeForwards fromViewController.view.layer.addAnimation(fromViewAnimation,forKey:"from_transition") // Animation of toView let toViewAnimation : CABasicAnimation = CABasicAnimation(keyPath: "position") // point = toInitialFrame.origin point.x += toInitialFrame.size.width*0.5 point.y += toInitialFrame.size.height*0.5 toViewAnimation.fromValue = NSValue(CGPoint: point) point = toFinalFrame.origin point.x += toFinalFrame.size.width*0.5 point.y += toFinalFrame.size.height*0.5 toViewAnimation.toValue = NSValue(CGPoint: point) toViewAnimation.duration = self.transitionDuration(transitionContext) toViewAnimation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseOut) // Maintain final animation state. toViewAnimation.removedOnCompletion = false toViewAnimation.fillMode = kCAFillModeForwards toViewAnimation.delegate = self toViewController.view.layer.addAnimation(toViewAnimation, forKey: "to_transition") CATransaction.commit() } internal override func animationDidStart(animation:CAAnimation) { } internal override func animationDidStop( animation : CAAnimation , finished : Bool ) { let toViewController = _transitionContext.viewControllerForKey(UITransitionContextToViewControllerKey) let fromViewController = _transitionContext.viewControllerForKey(UITransitionContextFromViewControllerKey) if _transitionContext.transitionWasCancelled() { fromViewController!.view.frame = _transitionContext.initialFrameForViewController(fromViewController!) toViewController!.view.frame = _transitionContext.initialFrameForViewController(toViewController!) }else{ fromViewController!.view.frame = _transitionContext.finalFrameForViewController(fromViewController!) toViewController!.view.frame = _transitionContext.finalFrameForViewController(toViewController!) } _transitionContext.completeTransition(!_transitionContext.transitionWasCancelled()) // Remove animations fromViewController!.view.layer.removeAllAnimations() toViewController!.view.layer.removeAllAnimations() } } // MARK: - // MARK: - PLMScrollMenuInteractiveTransition public class PLMScrollMenuInteractiveTransition : NSObject , UIViewControllerInteractiveTransitioning { public var percentComplete: CGFloat! = 0.0 private var _animator : UIViewControllerAnimatedTransitioning! private var _context : UIViewControllerContextTransitioning! private var _displayLink : CADisplayLink! private var _completion : (()->())? /** Init */ override init() { super.init() } convenience init (animator: UIViewControllerAnimatedTransitioning ) { self.init() _animator = animator } /** Values for Transitioning */ @objc public func completionCurve() -> UIViewAnimationCurve { return UIViewAnimationCurve.Linear } @objc public func completionSpeed() -> CGFloat { return 1.0 } /** Start Transition */ public func startInteractiveTransition(transitionContext: UIViewControllerContextTransitioning) { _context = transitionContext _context.containerView()!.layer.speed = 0 _animator.animateTransition(_context) } /** Update */ internal func updateInteractiveTransition( percentComplete:CGFloat ) { //print("InteractiveTransition updateInteractiveTransition percentComplete:\(percentComplete) context:\(_context) ") // Set PercentComplete self.percentComplete = percentComplete // Get Duration let duration : NSTimeInterval = _animator.transitionDuration(_context) if let context = _context , containerView = context.containerView() { // Set TimeOffset containerView.layer.timeOffset = CFTimeInterval( percentComplete * CGFloat(duration) ) // Update context.updateInteractiveTransition( self.percentComplete ) } } /** Cancel */ internal func cancelInteractiveTransitionWithCompletion(completion: (()->()) ) { _completion = completion _displayLink = CADisplayLink(target: self, selector: "updateCancelAnimation") _displayLink.addToRunLoop(NSRunLoop.mainRunLoop(), forMode: NSRunLoopCommonModes) } /** Finish */ internal func finishInteractiveTransition() { // Animation _context.containerView()?.layer.speed = Float ( self.completionSpeed() ) let pausedTimeOffset : CFTimeInterval = _context.containerView()!.layer.timeOffset _context.containerView()!.layer.timeOffset = 0.0 _context.containerView()!.layer.beginTime = 0.0 let newBeginTime : CFTimeInterval = _context.containerView()!.layer.convertTime( CACurrentMediaTime() , fromLayer: nil) - pausedTimeOffset _context.containerView()!.layer.beginTime = newBeginTime; // context transition _context.finishInteractiveTransition() } /** Update Cancel Animation */ internal func updateCancelAnimation() { let timeOffset : NSTimeInterval = _context.containerView()!.layer.timeOffset - _displayLink.duration * 0.3 if timeOffset < 0 { _displayLink.invalidate() _displayLink = nil _context.containerView()!.layer.speed = Float(self.completionSpeed()) _context.containerView()!.layer.timeOffset = 0.0 _context.updateInteractiveTransition( CGFloat( timeOffset / _animator.transitionDuration(_context) ) ) let toViewController : UIViewController = _context.viewControllerForKey(UITransitionContextToViewControllerKey)! toViewController.view.layer.removeAllAnimations() let fromViewController : UIViewController = _context.viewControllerForKey(UITransitionContextFromViewControllerKey)! fromViewController.view.layer.removeAllAnimations() _context.cancelInteractiveTransition() if let completion = _completion { completion(); } } else { _context.containerView()?.layer.timeOffset = timeOffset _context.updateInteractiveTransition( CGFloat( timeOffset/_animator.transitionDuration(_context) ) ) } } }
mit
dddb9bb27475c7dcbe4142bb9fe01cbf
37.015152
156
0.670387
6.14951
false
false
false
false
Hendrik44/pi-weather-app
Carthage/Checkouts/Charts/ChartsDemo-iOS/Swift/Demos/PiePolylineChartViewController.swift
1
4969
// // PiePolylineChartViewController.swift // ChartsDemo-iOS // // Created by Jacob Christie on 2017-07-09. // Copyright © 2017 jc. All rights reserved. // #if canImport(UIKit) import UIKit #endif import Charts class PiePolylineChartViewController: DemoBaseViewController { @IBOutlet var chartView: PieChartView! @IBOutlet var sliderX: UISlider! @IBOutlet var sliderY: UISlider! @IBOutlet var sliderTextX: UITextField! @IBOutlet var sliderTextY: UITextField! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. self.title = "Pie Poly Line Chart" self.options = [.toggleValues, .toggleXValues, .togglePercent, .toggleHole, .animateX, .animateY, .animateXY, .spin, .drawCenter, .saveToGallery, .toggleData] self.setup(pieChartView: chartView) chartView.delegate = self chartView.legend.enabled = false chartView.setExtraOffsets(left: 20, top: 0, right: 20, bottom: 0) sliderX.value = 40 sliderY.value = 100 self.slidersValueChanged(nil) chartView.animate(xAxisDuration: 1.4, easingOption: .easeOutBack) } override func updateChartData() { if self.shouldHideData { chartView.data = nil return } self.setDataCount(Int(sliderX.value), range: UInt32(sliderY.value)) } func setDataCount(_ count: Int, range: UInt32) { let entries = (0..<count).map { (i) -> PieChartDataEntry in // IMPORTANT: In a PieChart, no values (Entry) should have the same xIndex (even if from different DataSets), since no values can be drawn above each other. return PieChartDataEntry(value: Double(arc4random_uniform(range) + range / 5), label: parties[i % parties.count]) } let set = PieChartDataSet(entries: entries, label: "Election Results") set.sliceSpace = 2 set.colors = ChartColorTemplates.vordiplom() + ChartColorTemplates.joyful() + ChartColorTemplates.colorful() + ChartColorTemplates.liberty() + ChartColorTemplates.pastel() + [UIColor(red: 51/255, green: 181/255, blue: 229/255, alpha: 1)] set.valueLinePart1OffsetPercentage = 0.8 set.valueLinePart1Length = 0.2 set.valueLinePart2Length = 0.4 //set.xValuePosition = .outsideSlice set.yValuePosition = .outsideSlice let data = PieChartData(dataSet: set) let pFormatter = NumberFormatter() pFormatter.numberStyle = .percent pFormatter.maximumFractionDigits = 1 pFormatter.multiplier = 1 pFormatter.percentSymbol = " %" data.setValueFormatter(DefaultValueFormatter(formatter: pFormatter)) data.setValueFont(.systemFont(ofSize: 11, weight: .light)) data.setValueTextColor(.black) chartView.data = data chartView.highlightValues(nil) } override func optionTapped(_ option: Option) { switch option { case .toggleXValues: chartView.drawEntryLabelsEnabled = !chartView.drawEntryLabelsEnabled chartView.setNeedsDisplay() case .togglePercent: chartView.usePercentValuesEnabled = !chartView.usePercentValuesEnabled chartView.setNeedsDisplay() case .toggleHole: chartView.drawHoleEnabled = !chartView.drawHoleEnabled chartView.setNeedsDisplay() case .drawCenter: chartView.drawCenterTextEnabled = !chartView.drawCenterTextEnabled chartView.setNeedsDisplay() case .animateX: chartView.animate(xAxisDuration: 1.4) case .animateY: chartView.animate(yAxisDuration: 1.4) case .animateXY: chartView.animate(xAxisDuration: 1.4, yAxisDuration: 1.4) case .spin: chartView.spin(duration: 2, fromAngle: chartView.rotationAngle, toAngle: chartView.rotationAngle + 360, easingOption: .easeInCubic) default: handleOption(option, forChartView: chartView) } } // MARK: - Actions @IBAction func slidersValueChanged(_ sender: Any?) { sliderTextX.text = "\(Int(sliderX.value))" sliderTextY.text = "\(Int(sliderY.value))" self.updateChartData() } }
mit
30cb4633c985d6592d7f0ca29c66e1dd
32.795918
168
0.570451
5.330472
false
false
false
false
muyang00/YEDouYuTV
YEDouYuZB/YEDouYuZB/Home/Views/RecommendGameView.swift
1
2120
// // RecommendGameView.swift // YEDouYuZB // // Created by yongen on 17/3/31. // Copyright © 2017年 yongen. All rights reserved. // import UIKit protocol RecommendGameViewDelegate : class { func recommendGameView(_ recommendView : RecommendGameView, index: Int) } private let kGameCellID = "kGameCellID" private let kEdgeInsetMargin : CGFloat = 10 class RecommendGameView: UIView { var groups : [BaseGameModel]? { didSet{ self.collectionView.reloadData() } } @IBOutlet weak var collectionView: UICollectionView! override func awakeFromNib() { super.awakeFromNib() //设置该控件不随着父控件的拉伸而拉伸 autoresizingMask = UIViewAutoresizing() collectionView.backgroundColor = UIColor.white collectionView.register( UINib(nibName: "CollectionGameCell", bundle: nil), forCellWithReuseIdentifier: kGameCellID) collectionView.contentInset = UIEdgeInsets(top: 0, left: kEdgeInsetMargin, bottom: 0, right: kEdgeInsetMargin) } } //MARK: - 快速从xib创建类方法 extension RecommendGameView{ class func recommedGameView () -> RecommendGameView{ return Bundle.main.loadNibNamed("RecommendGameView", owner: nil, options: nil)?.first as! RecommendGameView } } extension RecommendGameView : UICollectionViewDataSource { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return groups?.count ?? 0 } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: kGameCellID, for: indexPath) as! CollectionGameCell cell.baseGame = self.groups![(indexPath as IndexPath).item] return cell } } extension RecommendGameView : UICollectionViewDelegate { func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { print("RecommendGameView ----", indexPath) } }
apache-2.0
8b5693e31331cad13e231ef5e0632286
28.956522
126
0.704886
5.286445
false
false
false
false
Brightify/ReactantUI
Sources/Live/Utils/WeakUIBox.swift
1
504
// // WeakUIBox.swift // ReactantUI // // Created by Matouš Hýbl on 23/03/2018. // import Foundation import Reactant private struct WeakUIBox { weak var ui: ReactantUI? /// Workaround for non-existent class existentials weak var view: UIView? init<UI: UIView>(ui: UI) where UI: ReactantUI { self.ui = ui self.view = ui } } extension WeakUIBox: Equatable { static func ==(lhs: WeakUIBox, rhs: WeakUIBox) -> Bool { return lhs.ui === rhs.ui } }
mit
daadb7659bf62de715c919d537d5348a
17.592593
60
0.625498
3.51049
false
false
false
false
goin18/test-ios
CostDetailVC.swift
1
5935
// // CostDetailVC.swift // Toshl iOS // // Created by Marko Budal on 26/03/15. // Copyright (c) 2015 Marko Budal. All rights reserved. // import UIKit import CoreData class CostDetailVC: UIViewController, UITableViewDataSource, UITableViewDelegate { @IBOutlet weak var tableView: UITableView! let tableImage:[String] = ["home", "internet", "bank", "numberTwo"] var costDetail:Cost! var tableCostDetail:[String] = [] let appDelegete = (UIApplication.sharedApplication().delegate as! AppDelegate) let managedObjectContext = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext override func viewDidLoad() { super.viewDidLoad() tableView.dataSource = self tableView.delegate = self tableCostDetail += [costDetail.category, costDetail.name, costDetail.toAccount, Date.toString(date: costDetail.date), "\(costDetail.repeat)"] navigationController?.navigationBar.barTintColor = UIColor(red: 243/255, green: 241/255, blue: 230/255, alpha: 1.0) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } //UITableViewDataSorce func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 2 } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if section == 0 { return 4 }else { return 1 } } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { var cell:UITableViewCell = tableView.dequeueReusableCellWithIdentifier("cell") as! UITableViewCell if indexPath.section == 1 { cell.imageView?.image = UIImage(named: "iconRepeat") cell.textLabel?.text = "Repeats each month on \(tableCostDetail[4])" }else { cell.imageView?.image = UIImage(named: tableImage[indexPath.row]) cell.textLabel?.text = tableCostDetail[indexPath.row] } return cell } //UITableViewDataSorce - Header func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { if section == 0 { var costView:UIView = UIView(frame: CGRect(x: 0, y: 0, width: view.frame.width, height: 100)) costView.backgroundColor = UIColor(red: 243/255, green: 241/255, blue: 230/255, alpha: 1.0) var costLabel: UILabel = UILabel() costLabel.text = String(format: "€%.2f", (costDetail.cost).floatValue) costLabel.font = UIFont(name: "Superclarendon", size: 45) costLabel.textColor = UIColor(red: 79/255, green: 77/255, blue: 79/255, alpha: 1.0) costLabel.sizeToFit() costLabel.center = CGPoint(x: costView.frame.width * 1.0/2.0, y: costView.frame.height * 1.0/4.0 * 2) costView.addSubview(costLabel) return costView }else { var costView:UIView = UIView(frame: CGRect(x: 0, y: 0, width: view.frame.width, height: 44)) costView.backgroundColor = UIColor(red: 243/255, green: 241/255, blue: 230/255, alpha: 1.0) return costView } } func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { if section == 0 { return 100 } else { return 44 } } //UITableViewDataSorce - Footer func tableView(tableView: UITableView, viewForFooterInSection section: Int) -> UIView? { if section == 1 { var costView:UIView = UIView(frame: CGRect(x: 0, y: 0, width: view.frame.width, height: view.bounds.height - tableView.bounds.height)) costView.backgroundColor = UIColor(red: 243/255, green: 241/255, blue: 230/255, alpha: 1.0) var deleteButton = UIButton(frame: CGRect(x: 10, y: 15, width: view.frame.width - 20, height: 30)) deleteButton.setTitleColor(UIColor.redColor(), forState: UIControlState.Normal) deleteButton.setTitle("Delete", forState: UIControlState.Normal) deleteButton.addTarget(self, action: "removeDataFromCoreDataButton:", forControlEvents: UIControlEvents.TouchUpInside) costView.addSubview(deleteButton) return costView } return nil } func tableView(tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { if section == 1 { return 220 } else { return 0 } } //ButtonDelete func removeDataFromCoreDataButton(button: UIButton){ let fetchRequest = NSFetchRequest(entityName: "DateDay") let exprTitle = NSExpression(forKeyPath: "date") let exprValue = NSExpression(forConstantValue: costDetail.date) let predicate = NSComparisonPredicate(leftExpression: exprTitle, rightExpression: exprValue, modifier: NSComparisonPredicateModifier.DirectPredicateModifier, type: NSPredicateOperatorType.EqualToPredicateOperatorType, options: nil) fetchRequest.predicate = predicate var requestDateDay = managedObjectContext!.executeFetchRequest(fetchRequest, error: nil) as! [DateDay] if requestDateDay[0].numberCost.intValue > 1 { requestDateDay[0].numberCost = requestDateDay[0].numberCost.integerValue - 1 requestDateDay[0].costs = requestDateDay[0].costs.floatValue - costDetail.cost.floatValue }else{ managedObjectContext!.deleteObject(requestDateDay[0]) } managedObjectContext!.deleteObject(costDetail) appDelegete.saveContext() navigationController?.popViewControllerAnimated(true) } }
mit
7e925d3e88005862e66cdd9a959c35b6
39.917241
239
0.641665
4.72749
false
false
false
false
rayfix/toyland
BeanMachine/BeanMachine.playground/Contents.swift
1
576
import UIKit import XCPlayground //: ## Swift Bean Machine //: A simplified bean machine simulation. //: //: [Wikipedia Article](https://en.wikipedia.org/wiki/Bean_machine) XCPlaygroundPage.currentPage.needsIndefiniteExecution = true func run() { let size = 50 let depth = 50 let trials = 1000 var results = Results(size: size) for _ in 1...trials { let finalPosition = dropBall(startPosition: size/2, depth: depth, range: 0..<size) results.add(finalPosition) results // Watch this variable with quick look } } // Uncomment to run // run()
mit
5303f1bf4b4031bd8205259e267a6f29
18.2
86
0.689236
3.891892
false
false
false
false
JohnSansoucie/MyProject2
BlueCapKit/Location/BeaconRegion.swift
1
3297
// // BeaconRegion.swift // BlueCap // // Created by Troy Stribling on 9/14/14. // Copyright (c) 2014 gnos.us. All rights reserved. // import UIKit import CoreLocation public class BeaconRegion : Region { internal var _beacons = [Beacon]() internal var beaconPromise : StreamPromise<[Beacon]> internal var clBeaconRegion : CLBeaconRegion { return self._region as CLBeaconRegion } public var beacons : [Beacon] { return sorted(self._beacons, {(b1:Beacon, b2:Beacon) -> Bool in switch b1.discoveredAt.compare(b2.discoveredAt) { case .OrderedSame: return true case .OrderedDescending: return false case .OrderedAscending: return true } }) } public var proximityUUID : NSUUID! { return (self._region as CLBeaconRegion).proximityUUID } public var major : Int? { if let _major = self.clBeaconRegion.major { return _major.integerValue } else { return nil } } public var minor : Int? { if let _minor = self.clBeaconRegion.minor { return _minor.integerValue } else { return nil } } public var notifyEntryStateOnDisplay : Bool { get { return self.clBeaconRegion.notifyEntryStateOnDisplay } set { self.clBeaconRegion.notifyEntryStateOnDisplay = newValue } } internal override init(region:CLRegion, capacity:Int? = nil) { if let capacity = capacity { self.beaconPromise = StreamPromise<[Beacon]>(capacity:capacity) } else { self.beaconPromise = StreamPromise<[Beacon]>() } super.init(region:region, capacity:capacity) self.notifyEntryStateOnDisplay = true } public convenience init(proximityUUID:NSUUID, identifier:String, capacity:Int? = nil) { let beaconRegion = CLBeaconRegion(proximityUUID:proximityUUID, identifier:identifier) self.init(region:beaconRegion, capacity:capacity) } public convenience init(proximityUUID:NSUUID, identifier:String, major:UInt16, capacity:Int? = nil) { let beaconMajor : CLBeaconMajorValue = major let beaconRegion = CLBeaconRegion(proximityUUID:proximityUUID, major:beaconMajor, identifier:identifier) self.init(region:beaconRegion, capacity:capacity) } public convenience init(proximityUUID:NSUUID, identifier:String, major:UInt16, minor:UInt16, capacity:Int? = nil) { let beaconMinor : CLBeaconMinorValue = minor let beaconMajor : CLBeaconMajorValue = major let beaconRegion = CLBeaconRegion(proximityUUID:proximityUUID, major:beaconMajor, minor:beaconMinor, identifier:identifier) self.init(region:beaconRegion, capacity:capacity) } public func peripheralDataWithMeasuredPower(measuredPower:Int? = nil) -> NSMutableDictionary { if let measuredPower = measuredPower { return self.clBeaconRegion.peripheralDataWithMeasuredPower(NSNumber(integer:measuredPower)) } else { return self.clBeaconRegion.peripheralDataWithMeasuredPower(nil) } } }
mit
5eef0c490f8a9b207c62a4bc43d2adfd
32.30303
131
0.639672
4.935629
false
false
false
false
movabletype/smartphone-app
MT_iOS/MT_iOS/Classes/ViewController/LoginTableViewController.swift
1
17510
// // LoginTableViewController.swift // MT_iOS // // Created by CHEEBOW on 2015/05/28. // Copyright (c) 2015年 Six Apart, Ltd. All rights reserved. // import UIKit import SwiftyJSON import SVProgressHUD class LoginTableViewController: BaseTableViewController, UITextFieldDelegate { enum Section: Int { case Logo = 0, AuthInfo, Spacer1, BasicAuth, Spacer2, LoginButton, Spacer3, _Num } enum AuthInfoItem: Int { case Username = 0, Password, Endpoint, _Num } enum BasicAuthItem: Int { case Button = 0, Spacer1, Username, Password, _Num } enum FieldType: Int { case Username = 1, Password, Endpoint, BasicAuthUsername, BasicAuthPassword } var auth = AuthInfo() var basicAuthVisibled = false let gradientLayer = CAGradientLayer() override func viewDidLoad() { super.viewDidLoad() gradientLayer.frame = self.view.bounds let startColor = Color.loginBgStart.CGColor let endColor = Color.loginBgEnd.CGColor gradientLayer.colors = [startColor, endColor] gradientLayer.locations = [0.0, 1.0] self.view.layer.insertSublayer(gradientLayer, atIndex: 0) // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Uncomment the following line to display an Edit button in the navigation bar for this view controller. // self.navigationItem.rightBarButtonItem = self.editButtonItem() self.navigationController?.navigationBarHidden = true self.tableView.registerNib(UINib(nibName: "LogoTableViewCell", bundle: nil), forCellReuseIdentifier: "LogoTableViewCell") self.tableView.registerNib(UINib(nibName: "TextFieldTableViewCell", bundle: nil), forCellReuseIdentifier: "TextFieldTableViewCell") self.tableView.registerNib(UINib(nibName: "ButtonTableViewCell", bundle: nil), forCellReuseIdentifier: "ButtonTableViewCell") self.tableView.separatorStyle = UITableViewCellSeparatorStyle.None self.tableView.backgroundColor = Color.clear let app: AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate let authInfo = app.authInfo if authInfo.username.isEmpty && authInfo.endpoint.isEmpty { authInfo.clear() authInfo.save() } auth.username = authInfo.username auth.password = authInfo.password auth.endpoint = authInfo.endpoint auth.basicAuthUsername = authInfo.basicAuthUsername auth.basicAuthPassword = authInfo.basicAuthPassword if !auth.basicAuthUsername.isEmpty { basicAuthVisibled = true } } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) self.navigationController?.navigationBarHidden = true } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { // #warning Potentially incomplete method implementation. // Return the number of sections. return Section._Num.rawValue } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete method implementation. // Return the number of rows in the section. switch section { case Section.Logo.rawValue: return 1 case Section.AuthInfo.rawValue: return AuthInfoItem._Num.rawValue case Section.BasicAuth.rawValue: if basicAuthVisibled { return BasicAuthItem._Num.rawValue } else { return 1 } case Section.LoginButton.rawValue: return 1 default: return 1 } } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { var cell = UITableViewCell() //tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath) as! UITableViewCell switch indexPath.section { case Section.Logo.rawValue: let c = tableView.dequeueReusableCellWithIdentifier("LogoTableViewCell", forIndexPath: indexPath) as! LogoTableViewCell cell = c case Section.AuthInfo.rawValue: switch indexPath.row { case AuthInfoItem.Username.rawValue: let c = tableView.dequeueReusableCellWithIdentifier("TextFieldTableViewCell", forIndexPath: indexPath) as! TextFieldTableViewCell c.textField.placeholder = NSLocalizedString("username", comment: "username") c.textField.keyboardType = UIKeyboardType.Default c.textField.returnKeyType = UIReturnKeyType.Done c.textField.secureTextEntry = false c.textField.autocorrectionType = UITextAutocorrectionType.No c.textField.text = auth.username c.textField.tag = FieldType.Username.rawValue c.textField.delegate = self c.textField.addTarget(self, action: "textFieldChanged:", forControlEvents: UIControlEvents.EditingChanged) c.bgImageView.image = UIImage(named: "signin_table_1") cell = c case AuthInfoItem.Password.rawValue: let c = tableView.dequeueReusableCellWithIdentifier("TextFieldTableViewCell", forIndexPath: indexPath) as! TextFieldTableViewCell c.textField.placeholder = NSLocalizedString("password", comment: "password") c.textField.keyboardType = UIKeyboardType.Default c.textField.returnKeyType = UIReturnKeyType.Done c.textField.secureTextEntry = true c.textField.autocorrectionType = UITextAutocorrectionType.No c.textField.text = auth.password c.textField.tag = FieldType.Password.rawValue c.textField.delegate = self c.textField.addTarget(self, action: "textFieldChanged:", forControlEvents: UIControlEvents.EditingChanged) c.bgImageView.image = UIImage(named: "signin_table_2") cell = c case AuthInfoItem.Endpoint.rawValue: let c = tableView.dequeueReusableCellWithIdentifier("TextFieldTableViewCell", forIndexPath: indexPath) as! TextFieldTableViewCell c.textField.placeholder = NSLocalizedString("endpoint", comment: "endpoint") c.textField.keyboardType = UIKeyboardType.URL c.textField.returnKeyType = UIReturnKeyType.Done c.textField.secureTextEntry = false c.textField.autocorrectionType = UITextAutocorrectionType.No c.textField.text = auth.endpoint c.textField.tag = FieldType.Endpoint.rawValue c.textField.delegate = self c.textField.addTarget(self, action: "textFieldChanged:", forControlEvents: UIControlEvents.EditingChanged) c.bgImageView.image = UIImage(named: "signin_table_3") cell = c default: break } case Section.BasicAuth.rawValue: switch indexPath.row { case BasicAuthItem.Button.rawValue: let c = tableView.dequeueReusableCellWithIdentifier("ButtonTableViewCell", forIndexPath: indexPath) as! ButtonTableViewCell c.button.setTitle(NSLocalizedString("Basic Auth", comment: "Basic Auth"), forState: UIControlState.Normal) c.button.titleLabel?.font = UIFont.systemFontOfSize(16.0) c.button.setTitleColor(Color.buttonText, forState: UIControlState.Normal) if self.basicAuthVisibled { c.button.setBackgroundImage(UIImage(named: "btn_basic_open"), forState: UIControlState.Normal) } else { c.button.setBackgroundImage(UIImage(named: "btn_basic_close"), forState: UIControlState.Normal) } c.button.addTarget(self, action: "basicAuthButtonPushed:", forControlEvents: UIControlEvents.TouchUpInside) cell = c case BasicAuthItem.Username.rawValue: let c = tableView.dequeueReusableCellWithIdentifier("TextFieldTableViewCell", forIndexPath: indexPath) as! TextFieldTableViewCell c.textField.placeholder = NSLocalizedString("username", comment: "username") c.textField.keyboardType = UIKeyboardType.Default c.textField.returnKeyType = UIReturnKeyType.Done c.textField.secureTextEntry = false c.textField.autocorrectionType = UITextAutocorrectionType.No c.textField.text = auth.basicAuthUsername c.textField.tag = FieldType.BasicAuthUsername.rawValue c.textField.delegate = self c.textField.addTarget(self, action: "textFieldChanged:", forControlEvents: UIControlEvents.EditingChanged) c.bgImageView.image = UIImage(named: "signin_table_1") cell = c case BasicAuthItem.Password.rawValue: let c = tableView.dequeueReusableCellWithIdentifier("TextFieldTableViewCell", forIndexPath: indexPath) as! TextFieldTableViewCell c.textField.placeholder = NSLocalizedString("password", comment: "password") c.textField.keyboardType = UIKeyboardType.Default c.textField.returnKeyType = UIReturnKeyType.Done c.textField.secureTextEntry = true c.textField.autocorrectionType = UITextAutocorrectionType.No c.textField.text = auth.basicAuthPassword c.textField.tag = FieldType.BasicAuthPassword.rawValue c.textField.delegate = self c.textField.addTarget(self, action: "textFieldChanged:", forControlEvents: UIControlEvents.EditingChanged) c.bgImageView.image = UIImage(named: "signin_table_3") cell = c default: break } case Section.LoginButton.rawValue: let c = tableView.dequeueReusableCellWithIdentifier("ButtonTableViewCell", forIndexPath: indexPath) as! ButtonTableViewCell c.button.setTitle(NSLocalizedString("Sign In", comment: "Sign In"), forState: UIControlState.Normal) c.button.titleLabel?.font = UIFont.systemFontOfSize(17.0) c.button.setTitleColor(Color.buttonText, forState: UIControlState.Normal) c.button.setTitleColor(Color.buttonDisableText, forState: UIControlState.Disabled) c.button.setBackgroundImage(UIImage(named: "btn_signin"), forState: UIControlState.Normal) c.button.setBackgroundImage(UIImage(named: "btn_signin_highlight"), forState: UIControlState.Highlighted) c.button.setBackgroundImage(UIImage(named: "btn_signin_disable"), forState: UIControlState.Disabled) c.button.enabled = self.validate() c.button.addTarget(self, action: "signInButtonPushed:", forControlEvents: UIControlEvents.TouchUpInside) cell = c default: break } //tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath) as! UITableViewCell // Configure the cell... cell.backgroundColor = Color.clear cell.selectionStyle = UITableViewCellSelectionStyle.None return cell } //MARK: - Table view delegate override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { switch indexPath.section { case Section.Logo.rawValue: return 175.0 case Section.AuthInfo.rawValue: switch indexPath.row { case AuthInfoItem.Username.rawValue: return 48.0 case AuthInfoItem.Password.rawValue: return 48.0 case AuthInfoItem.Endpoint.rawValue: return 48.0 default: return 0.0 } case Section.BasicAuth.rawValue: switch indexPath.row { case BasicAuthItem.Button.rawValue: return 40.0 case BasicAuthItem.Username.rawValue: return 48.0 case BasicAuthItem.Password.rawValue: return 48.0 default: return 12.0 } case Section.LoginButton.rawValue: return 40.0 case Section.Spacer3.rawValue: return 17.0 default: return 12.0 } } /* // Override to support conditional editing of the table view. override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return NO if you do not want the specified item to be editable. return true } */ /* // Override to support editing the table view. override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { // Delete the row from the data source tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } else if editingStyle == .Insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } */ /* // Override to support rearranging the table view. override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return NO if you do not want the item to be re-orderable. return true } */ /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using [segue destinationViewController]. // Pass the selected object to the new view controller. } */ @IBAction func signInButtonPushed(sender: AnyObject) { let app = UIApplication.sharedApplication().delegate as! AppDelegate app.signIn(self.auth, showHud: true) } @IBAction func forgetPasswordButtonPushed(sender: AnyObject) { let vc = ResetPasswordTableViewController() self.navigationController?.pushViewController(vc, animated: true) } @IBAction func basicAuthButtonPushed(sender: AnyObject) { basicAuthVisibled = !basicAuthVisibled let indexPaths = [ NSIndexPath(forRow: BasicAuthItem.Spacer1.rawValue, inSection: Section.BasicAuth.rawValue), NSIndexPath(forRow: BasicAuthItem.Username.rawValue, inSection: Section.BasicAuth.rawValue), NSIndexPath(forRow: BasicAuthItem.Password.rawValue, inSection: Section.BasicAuth.rawValue) ] self.tableView.beginUpdates() if basicAuthVisibled { self.tableView.insertRowsAtIndexPaths(indexPaths, withRowAnimation: UITableViewRowAnimation.Top) } else { self.tableView.deleteRowsAtIndexPaths(indexPaths, withRowAnimation: UITableViewRowAnimation.Top) } self.tableView.reloadRowsAtIndexPaths([NSIndexPath(forRow: BasicAuthItem.Button.rawValue, inSection: Section.BasicAuth.rawValue)], withRowAnimation: UITableViewRowAnimation.None) self.tableView.endUpdates() } private func validate()-> Bool { if auth.username.isEmpty || auth.password.isEmpty || auth.endpoint.isEmpty { return false } return true } func textFieldShouldReturn(textField: UITextField) -> Bool { textField.resignFirstResponder() return true } @IBAction func textFieldChanged(field: UITextField) { switch field.tag { case FieldType.Username.rawValue: auth.username = field.text! case FieldType.Password.rawValue: auth.password = field.text! case FieldType.Endpoint.rawValue: auth.endpoint = field.text! case FieldType.BasicAuthUsername.rawValue: auth.basicAuthUsername = field.text! case FieldType.BasicAuthPassword.rawValue: auth.basicAuthPassword = field.text! default: break } let cell = tableView.cellForRowAtIndexPath(NSIndexPath(forRow:0 , inSection: Section.LoginButton.rawValue)) as! ButtonTableViewCell cell.button.enabled = self.validate() } }
mit
33fa07b66f94f2714c639e7dddb3a185
41.911765
186
0.643534
5.649564
false
false
false
false
Marketcloud/marketcloud-swift-sdk
Marketcloud/Marketcloud.swift
2
8863
import Foundation open class Marketcloud { open static var version:String = "0.3.3" fileprivate var publicKey:String fileprivate var token:String fileprivate var user_id:Int fileprivate var products:Product fileprivate var currencies:Currencies fileprivate var categories:Categories fileprivate var brands:Brands fileprivate var carts:Carts fileprivate var addresses:Addresses fileprivate var users:Users fileprivate var orders:Orders fileprivate var shippings:Shippings open var utils:Utils public init(key: String) { publicKey = key token = "" user_id = -1 products = Product(key: publicKey) currencies = Currencies(key: publicKey) categories = Categories(key: publicKey) brands = Brands(key: publicKey) carts = Carts(key:publicKey) addresses = Addresses(key:publicKey) users = Users(key:publicKey) shippings = Shippings(key:publicKey) orders = Orders(key:publicKey) utils = Utils() //these classes will be reinitialized if an user logs in } open func getKey() -> String { return self.publicKey } open func getUserId() -> Int { return self.user_id } open func getToken() -> String { return self.token } //------------------------------------------------------- open func getProducts() -> NSDictionary { return products.getProducts() } open func getProducts(_ filter:[String: Any]) -> NSDictionary { return products.getProducts(filter) } open func getProductById(_ id:Int) -> NSDictionary { return products.getProductById(id) } open func getProductById(_ id:String) -> NSDictionary { return products.getProductById(Int(id)!) } open func getProductsByCategory(_ id:Int) -> NSDictionary { return products.getProductsByCategory(id) } open func getProductsByCategory(_ id:String) -> NSDictionary { return products.getProductsByCategory(Int(id)!) } //------------------------------------------------------- open func getCategories() -> NSDictionary { return categories.getCategories() } open func getCategoryById(_ id:Int) -> NSDictionary { return categories.getCategoryById(id) } open func getCategoryById(_ id:String) -> NSDictionary { return categories.getCategoryById(Int(id)!) } //------------------------------------------------------- open func getBrands() -> NSDictionary { return brands.getBrands() } open func getBrandById(_ id:Int) -> NSDictionary { return brands.getBrandById(id) } open func getBrandById(_ id:String) -> NSDictionary { return brands.getBrandById(Int(id)!) } //------------------------------------------------------- open func createEmptyCart() -> NSDictionary { return carts.createEmptyCart() } open func getCart() -> NSDictionary { return carts.getCart() } open func getCart(_ id:Int) -> NSDictionary { return carts.getCart(id) } open func getCart(_ id:String) -> NSDictionary { return carts.getCart(Int(id)!) } open func addToCart(_ id:Int, data:[Any]) -> NSDictionary { return carts.addToCart(id, data:data) } open func addToCart(_ id:String, data:[Any]) -> NSDictionary { return carts.addToCart(Int(id)!, data:data) } open func updateCart(_ id:Int, data:[Any]) -> NSDictionary { return carts.updateCart(id, data:data) } open func updateCart(_ id:String, data:[Any]) -> NSDictionary { return carts.updateCart(Int(id)!, data:data) } open func removeFromCart(_ id:Int, data:[Any]) -> NSDictionary { return carts.removeFromCart(id, data:data) } open func removeFromCart(_ id:String, data:[Any]) -> NSDictionary { return carts.removeFromCart(Int(id)!, data:data) } //--------------------------------------------------------- open func createAddress(_ datas:[String:Any]) -> NSDictionary { return addresses.createAddress(datas) } open func getAddresses() -> NSDictionary { return addresses.getAddresses() } open func getAddress(_ id:Int) -> NSDictionary { return addresses.getAddress(id) } open func getAddress(_ id:String) -> NSDictionary { return addresses.getAddress(Int(id)!) } open func updateAddress(_ id:Int, datas:[String:Any]) -> NSDictionary { return addresses.updateAddress(id, datas: datas) } open func updateAddress(_ id:String, datas:[String:Any]) -> NSDictionary { return addresses.updateAddress(Int(id)!, datas: datas) } open func removeAddress(_ id:Int) -> NSDictionary { return addresses.removeAddress(id) } open func removeAddress(_ id:String) -> NSDictionary { return addresses.removeAddress(Int(id)!) } //--------------------------------------------------------- open func createUser(_ datas:[String:String]) -> NSDictionary { return users.createUser(datas) } open func updateUser(_ datas:[String:String], id:Int) -> NSDictionary { return users.updateUser(datas,userId: id) } open func logIn(_ datas:[String:String]) -> NSDictionary { let r:NSDictionary = users.logIn(datas) guard (r["token"] != nil || r["user_id"] != nil) else { //something went wrong... return r } self.token = String(describing: r["token"]!) self.user_id = Int(String(describing: r["user_id"]!))! //print("token setted -> \(self.token)") //print("user_id setted -> \(self.user_id)") self.products = Product(key: publicKey, token: token) self.currencies = Currencies(key: publicKey, token: token) self.categories = Categories(key: publicKey, token: token) self.brands = Brands(key: publicKey, token: token) self.carts = Carts(key: publicKey, token: token) self.addresses = Addresses(key: publicKey, token: token) self.users = Users(key: publicKey, token:token) self.orders = Orders(key: publicKey, token:token) self.shippings = Shippings(key: publicKey, token:token) //print("ready!") return ["Ok":"Logged In"] } open func logOut() -> NSDictionary { if(users.logOut()) { self.token = "" self.user_id = -1 //print("token setted -> \(self.token)") //print("user_id setted -> \(self.user_id)") self.products = Product(key: publicKey) self.currencies = Currencies(key: publicKey) self.categories = Categories(key: publicKey) self.brands = Brands(key: publicKey) self.carts = Carts(key: publicKey) self.addresses = Addresses(key: publicKey) self.users = Users(key: publicKey) self.orders = Orders(key: publicKey) self.shippings = Shippings(key: publicKey) //print("logged out!") return ["Ok":"Logged Out"] } else { return ["Error":"unable to logOut. Are you sure you were logged In?"] } } //------------------------------------------------------ open func createOrder(_ shippingId:Int, billingId:Int, cartId:Int) -> NSDictionary{ return orders.createOrder(shippingId, billingId: billingId, cart_id: cartId) } open func createOrder(_ shippingId:String, billingId:String, cartId:String) -> NSDictionary{ return orders.createOrder(Int(shippingId)!, billingId: Int(billingId)!, cart_id: Int(cartId)!) } open func completeOrder(_ orderId:Int, stripeToken:String) -> NSDictionary { return orders.completeOrder(orderId, stripeToken: stripeToken) } open func completeOrder(_ orderId:String, stripeToken:String) -> NSDictionary { return orders.completeOrder(Int(orderId)!, stripeToken: stripeToken) } //------------------------------------------------------ open func getCurrencies() -> NSDictionary { return currencies.getCurrencies() } //------------------------------------------------------ open func getShippings() -> NSDictionary { return shippings.getShippings() } open func getShippingById(_ id:Int) -> NSDictionary { return shippings.getShippingById(id) } open func getShippingById(_ id:String) -> NSDictionary { return shippings.getShippingById(Int(id)!) } }
apache-2.0
4091deb12b9bf46ebd1a19449aab7a8d
32.828244
102
0.570461
4.620959
false
false
false
false
overtake/TelegramSwift
Telegram-Mac/TwoStepVerificationUnlockController.swift
1
72345
// // TwoStepVerificationUnlockController.swift // Telegram // // Created by keepcoder on 16/10/2017. // Copyright © 2017 Telegram. All rights reserved. // import Cocoa import TGUIKit import SwiftSignalKit import TelegramCore import Postbox private struct TwoStepVerificationUnlockSettingsControllerState: Equatable { let passwordText: String let checking: Bool let emailCode: String let errors:[InputDataIdentifier : InputDataValueError] let data: TwoStepVerificationUnlockSettingsControllerData init(passwordText: String, checking: Bool, emailCode: String, errors: [InputDataIdentifier : InputDataValueError], data: TwoStepVerificationUnlockSettingsControllerData) { self.passwordText = passwordText self.checking = checking self.emailCode = emailCode self.errors = errors self.data = data } func withUpdatedError(_ error: InputDataValueError?, for key: InputDataIdentifier) -> TwoStepVerificationUnlockSettingsControllerState { var errors = self.errors if let error = error { errors[key] = error } else { errors.removeValue(forKey: key) } return TwoStepVerificationUnlockSettingsControllerState(passwordText: self.passwordText, checking: self.checking, emailCode: self.emailCode, errors: errors, data: self.data) } func withUpdatedPasswordText(_ passwordText: String) -> TwoStepVerificationUnlockSettingsControllerState { return TwoStepVerificationUnlockSettingsControllerState(passwordText: passwordText, checking: self.checking, emailCode: self.emailCode, errors: self.errors, data: self.data) } func withUpdatedEmailCode(_ emailCode: String) -> TwoStepVerificationUnlockSettingsControllerState { return TwoStepVerificationUnlockSettingsControllerState(passwordText: self.passwordText, checking: self.checking, emailCode: emailCode, errors: self.errors, data: self.data) } func withUpdatedChecking(_ checking: Bool) -> TwoStepVerificationUnlockSettingsControllerState { return TwoStepVerificationUnlockSettingsControllerState(passwordText: self.passwordText, checking: checking, emailCode: self.emailCode, errors: self.errors, data: self.data) } func withUpdatedControllerData(_ data: TwoStepVerificationUnlockSettingsControllerData) -> TwoStepVerificationUnlockSettingsControllerState { return TwoStepVerificationUnlockSettingsControllerState(passwordText: self.passwordText, checking: self.checking, emailCode: self.emailCode, errors: self.errors, data: data) } } enum TwoStepVerificationUnlockSettingsControllerMode { case access(TwoStepVeriticationAccessConfiguration?) case manage(password: String, email: String, pendingEmail: TwoStepVerificationPendingEmail?, hasSecureValues: Bool) } private enum TwoStepVerificationUnlockSettingsControllerData : Equatable { case access(configuration: TwoStepVeriticationAccessConfiguration?) case manage(password: String, emailSet: Bool, pendingEmail: TwoStepVerificationPendingEmail?, hasSecureValues: Bool) } struct PendingEmailState : Equatable { let password: String? let email: TwoStepVerificationPendingEmail } private final class TwoStepVerificationPasswordEntryControllerArguments { let updateEntryText: (String) -> Void let next: () -> Void let skipEmail:() ->Void init(updateEntryText: @escaping (String) -> Void, next: @escaping () -> Void, skipEmail:@escaping()->Void) { self.updateEntryText = updateEntryText self.next = next self.skipEmail = skipEmail } } enum PasswordEntryStage: Equatable { case entry(text: String) case reentry(first: String, text: String) case hint(password: String, text: String) case email(password: String, hint: String, text: String, change: Bool) case code(text: String, codeLength: Int32?, pattern: String) func updateCurrentText(_ text: String) -> PasswordEntryStage { switch self { case .entry: return .entry(text: text) case let .reentry(first, _): return .reentry(first: first, text: text) case let .hint(password, _): return .hint(password: password, text: text) case let .email(password, hint, _, change): return .email(password: password, hint: hint, text: text, change: change) case let .code(_, codeLength, pattern): return .code(text: text, codeLength: codeLength, pattern: pattern) } } } private struct TwoStepVerificationPasswordEntryControllerState: Equatable { let stage: PasswordEntryStage let updating: Bool let errors: [InputDataIdentifier : InputDataValueError] init(stage: PasswordEntryStage, updating: Bool, errors: [InputDataIdentifier : InputDataValueError]) { self.stage = stage self.updating = updating self.errors = errors } func withUpdatedError(_ error: InputDataValueError?, for key: InputDataIdentifier) -> TwoStepVerificationPasswordEntryControllerState { var errors = self.errors if let error = error { errors[key] = error } else { errors.removeValue(forKey: key) } return TwoStepVerificationPasswordEntryControllerState(stage: self.stage, updating: self.updating, errors: errors) } func withUpdatedStage(_ stage: PasswordEntryStage) -> TwoStepVerificationPasswordEntryControllerState { return TwoStepVerificationPasswordEntryControllerState(stage: stage, updating: self.updating, errors: self.errors) } func withUpdatedUpdating(_ updating: Bool) -> TwoStepVerificationPasswordEntryControllerState { return TwoStepVerificationPasswordEntryControllerState(stage: self.stage, updating: updating, errors: self.errors) } } enum TwoStepVerificationPasswordEntryMode { case setup case change(current: String) case setupEmail(password: String, change: Bool) case enterCode(codeLength: Int32?, pattern: String) } enum TwoStepVeriticationAccessConfiguration : Equatable { case notSet(pendingEmail: PendingEmailState?) case set(hint: String, hasRecoveryEmail: Bool, hasSecureValues: Bool, pendingResetTimestamp: Int32?) init(configuration: TwoStepVerificationConfiguration, password: String?) { switch configuration { case let .notSet(pendingEmail): self = .notSet(pendingEmail: pendingEmail.flatMap({ PendingEmailState(password: password, email: $0) })) case let .set(hint, hasRecoveryEmail, _, hasSecureValues, pendingResetTimestamp): self = .set(hint: hint, hasRecoveryEmail: hasRecoveryEmail, hasSecureValues: hasSecureValues, pendingResetTimestamp: pendingResetTimestamp) } } } enum SetupTwoStepVerificationStateUpdate { case noPassword case awaitingEmailConfirmation(password: String, pattern: String, codeLength: Int32?) case passwordSet(password: String?, hasRecoveryEmail: Bool, hasSecureValues: Bool) case emailSet } final class TwoStepVerificationResetControllerArguments { let updateEntryText: (String) -> Void let next: () -> Void let openEmailInaccessible: () -> Void init(updateEntryText: @escaping (String) -> Void, next: @escaping () -> Void, openEmailInaccessible: @escaping () -> Void) { self.updateEntryText = updateEntryText self.next = next self.openEmailInaccessible = openEmailInaccessible } } struct TwoStepVerificationResetControllerState: Equatable { let codeText: String let checking: Bool init(codeText: String, checking: Bool) { self.codeText = codeText self.checking = checking } func withUpdatedCodeText(_ codeText: String) -> TwoStepVerificationResetControllerState { return TwoStepVerificationResetControllerState(codeText: codeText, checking: self.checking) } func withUpdatedChecking(_ checking: Bool) -> TwoStepVerificationResetControllerState { return TwoStepVerificationResetControllerState(codeText: self.codeText, checking: checking) } } private let _id_input_enter_pwd = InputDataIdentifier("input_password") private let _id_change_pwd = InputDataIdentifier("change_pwd") private let _id_remove_pwd = InputDataIdentifier("remove_pwd") private let _id_setup_email = InputDataIdentifier("setup_email") private let _id_enter_email_code = InputDataIdentifier("enter_email_code") private let _id_set_password = InputDataIdentifier("set_password") private let _id_input_enter_email_code = InputDataIdentifier("_id_input_enter_email_code") private func twoStepVerificationUnlockSettingsControllerEntries(state: TwoStepVerificationUnlockSettingsControllerState, context: AccountContext, forgotPassword:@escaping()->Void, cancelReset:@escaping() -> Void, abort:@escaping()-> Void) -> [InputDataEntry] { var entries: [InputDataEntry] = [] var sectionId:Int32 = 0 entries.append(.sectionId(sectionId, type: .normal)) sectionId += 1 var index: Int32 = 0 switch state.data { case let .access(configuration): if let configuration = configuration { switch configuration { case let .notSet(pendingEmail): if let pendingEmail = pendingEmail { entries.append(.input(sectionId: sectionId, index: index, value: .string(state.emailCode), error: state.errors[_id_input_enter_email_code], identifier: _id_input_enter_email_code, mode: .plain, data: InputDataRowData(viewType: .singleItem), placeholder: nil, inputPlaceholder: strings().twoStepAuthRecoveryCode, filter: {String($0.unicodeScalars.filter { CharacterSet.decimalDigits.contains($0)})}, limit: pendingEmail.email.codeLength ?? 255)) index += 1 entries.append(.desc(sectionId: sectionId, index: index, text: .markdown(strings().twoStepAuthConfirmationTextNew + "\n\n\(pendingEmail.email.pattern)\n\n[" + strings().twoStepAuthConfirmationAbort + "]()", linkHandler: { url in abort() }), data: InputDataGeneralTextData(detectBold: false, viewType: .textBottomItem))) index += 1 } else { entries.append(.general(sectionId: sectionId, index: index, value: .string(nil), error: nil, identifier: _id_set_password, data: InputDataGeneralData(name: strings().twoStepAuthSetPassword, color: theme.colors.text, icon: nil, type: .none, viewType: .singleItem, action: nil))) index += 1 entries.append(.desc(sectionId: sectionId, index: index, text: .plain(strings().twoStepAuthSetPasswordHelp), data: InputDataGeneralTextData(viewType: .textBottomItem))) index += 1 } case let .set(hint, hasRecoveryEmail, _, pendingResetTimestamp): entries.append(.input(sectionId: sectionId, index: index, value: .string(state.passwordText), error: state.errors[_id_input_enter_pwd], identifier: _id_input_enter_pwd, mode: .secure, data: InputDataRowData(viewType: .singleItem), placeholder: nil, inputPlaceholder: strings().twoStepAuthEnterPasswordPassword, filter: { $0 }, limit: 255)) index += 1 if let timestamp = pendingResetTimestamp { if timestamp.isFuture { entries.append(.desc(sectionId: sectionId, index: index, text: .markdown(strings().twoStepAuthEnterPasswordHelp + "\n\n" + strings().twoStepAuthResetPending(autoremoveLocalized(Int(timestamp - Int32(Date().timeIntervalSince1970)))) + "\n[" + strings().twoStepAuthCancelReset + "](reset)", linkHandler: { link in confirm(for: context.window, header: strings().twoStepAuthCancelResetConfirm, information: strings().twoStepAuthCancelResetText, okTitle: strings().alertYes, cancelTitle: strings().alertNO, successHandler: { _ in cancelReset() }) }), data: InputDataGeneralTextData(viewType: .textBottomItem))) } else { entries.append(.desc(sectionId: sectionId, index: index, text: .markdown(strings().twoStepAuthEnterPasswordHelp + "\n\n" + "[" + strings().twoStepAuthReset + "](reset)", linkHandler: { link in forgotPassword() }), data: InputDataGeneralTextData(viewType: .textBottomItem))) } index += 1 } else { let forgot:()->Void = { if !hasRecoveryEmail { confirm(for: context.window, header: strings().twoStepAuthErrorHaventEmailResetHeader, information: strings().twoStepAuthErrorHaventEmailNew, okTitle: strings().twoStepAuthErrorHaventEmailReset, successHandler: { _ in forgotPassword() }) } else { forgotPassword() } } if hint.isEmpty { entries.append(.desc(sectionId: sectionId, index: index, text: .markdown(strings().twoStepAuthEnterPasswordHelp + "\n\n[" + strings().twoStepAuthEnterPasswordForgot + "](forgot)", linkHandler: { link in forgot() }), data: InputDataGeneralTextData(viewType: .textBottomItem))) } else { entries.append(.desc(sectionId: sectionId, index: index, text: .markdown(strings().twoStepAuthEnterPasswordHint(hint) + "\n\n" + strings().twoStepAuthEnterPasswordHelp + "\n\n[" + strings().twoStepAuthEnterPasswordForgot + "](forgot)", linkHandler: { link in forgot() }), data: InputDataGeneralTextData(viewType: .textBottomItem))) } index += 1 } } } else { return [.loading] } case let .manage(_, emailSet, pendingEmail, _): entries.append(.general(sectionId: sectionId, index: index, value: .string(nil), error: nil, identifier: _id_change_pwd, data: InputDataGeneralData(name: strings().twoStepAuthChangePassword, color: theme.colors.text, icon: nil, type: .none, viewType: .firstItem, action: nil))) index += 1 entries.append(.general(sectionId: sectionId, index: index, value: .string(nil), error: nil, identifier: _id_remove_pwd, data: InputDataGeneralData(name: strings().twoStepAuthRemovePassword, color: theme.colors.text, icon: nil, type: .none, viewType: .innerItem, action: nil))) index += 1 entries.append(.general(sectionId: sectionId, index: index, value: .string(nil), error: nil, identifier: _id_setup_email, data: InputDataGeneralData(name: emailSet ? strings().twoStepAuthChangeEmail : strings().twoStepAuthSetupEmail, color: theme.colors.text, icon: nil, type: .none, viewType: .lastItem, action: nil))) index += 1 if let _ = pendingEmail { entries.append(.sectionId(sectionId, type: .normal)) sectionId += 1 entries.append(.general(sectionId: sectionId, index: index, value: .string(nil), error: nil, identifier: _id_enter_email_code, data: InputDataGeneralData(name: strings().twoStepAuthEnterEmailCode, color: theme.colors.text, icon: nil, type: .none, viewType: .singleItem, action: nil))) index += 1 entries.append(.desc(sectionId: sectionId, index: index, text: .plain(strings().twoStepAuthEmailSent), data: InputDataGeneralTextData(viewType: .textBottomItem))) index += 1 } else { entries.append(.desc(sectionId: sectionId, index: index, text: .plain(strings().twoStepAuthGenericHelp), data: InputDataGeneralTextData(viewType: .textBottomItem))) index += 1 } } entries.append(.sectionId(sectionId, type: .normal)) sectionId += 1 return entries } func twoStepVerificationUnlockController(context: AccountContext, mode: TwoStepVerificationUnlockSettingsControllerMode, presentController:@escaping((controller: ViewController, root:Bool, animated: Bool))->Void) -> InputDataController { let actionsDisposable = DisposableSet() let checkDisposable = MetaDisposable() actionsDisposable.add(checkDisposable) let setupDisposable = MetaDisposable() actionsDisposable.add(setupDisposable) let setupResultDisposable = MetaDisposable() actionsDisposable.add(setupResultDisposable) let data: TwoStepVerificationUnlockSettingsControllerData switch mode { case let .access(configuration): data = .access(configuration: configuration) case let .manage(password, email, pendingEmail, hasSecureValues): data = .manage(password: password, emailSet: !email.isEmpty, pendingEmail: pendingEmail, hasSecureValues: hasSecureValues) } // let initialState = TwoStepVerificationUnlockSettingsControllerState(passwordText: "", checking: false, emailCode: "", errors: [:], data: data) let statePromise = ValuePromise(initialState, ignoreRepeated: true) let stateValue = Atomic(value: initialState) let updateState: ((TwoStepVerificationUnlockSettingsControllerState) -> TwoStepVerificationUnlockSettingsControllerState) -> Void = { f in statePromise.set(stateValue.modify (f)) } switch mode { case .access: actionsDisposable.add((context.engine.auth.twoStepVerificationConfiguration() |> map { TwoStepVerificationUnlockSettingsControllerData.access(configuration: TwoStepVeriticationAccessConfiguration(configuration: $0, password: nil)) } |> deliverOnMainQueue).start(next: { data in updateState { $0.withUpdatedControllerData(data) } })) default: break } let disablePassword: () -> InputDataValidation = { return .fail(.doSomething { f in switch data { case .access: break case let .manage(password, _, _, hasSecureValues): var text: String = strings().twoStepAuthConfirmDisablePassword if hasSecureValues { text += "\n\n" text += strings().secureIdWarningDataLost } confirm(for: context.window, information: text, successHandler: { result in var disablePassword = false updateState { state in if state.checking { return state } else { disablePassword = true return state.withUpdatedChecking(true) } } context.hasPassportSettings.set(.single(false)) if disablePassword { let resetPassword = context.engine.auth.updateTwoStepVerificationPassword(currentPassword: password, updatedPassword: .none) |> deliverOnMainQueue setupDisposable.set(resetPassword.start(next: { value in updateState { $0.withUpdatedChecking(false) } context.resetTemporaryPwd() presentController((controller: twoStepVerificationUnlockController(context: context, mode: .access(.notSet(pendingEmail: nil)), presentController: presentController), root: true, animated: true)) _ = showModalSuccess(for: context.window, icon: theme.icons.successModalProgress, delay: 1.0).start() }, error: { error in alert(for: context.window, info: strings().unknownError) })) } }) } }) } let checkEmailConfirmation: () -> InputDataValidation = { return .fail(.doSomething { f in let data: TwoStepVerificationUnlockSettingsControllerData = stateValue.with { $0.data } var pendingEmailData: PendingEmailState? switch data { case let .access(configuration): guard let configuration = configuration else { return } switch configuration { case let .notSet(pendingEmail): pendingEmailData = pendingEmail case .set: break } case let .manage(password, _, pendingEmail, _): if let pendingEmail = pendingEmail { pendingEmailData = PendingEmailState(password: password, email: pendingEmail) } } if let pendingEmail = pendingEmailData { var code: String? updateState { state in if !state.checking { code = state.emailCode return state.withUpdatedChecking(true) } return state } if let code = code { setupDisposable.set((context.engine.auth.confirmTwoStepRecoveryEmail(code: code) |> deliverOnMainQueue).start(error: { error in updateState { state in return state.withUpdatedChecking(false) } let text: String switch error { case .invalidEmail: text = strings().twoStepAuthEmailInvalid case .invalidCode: text = strings().twoStepAuthEmailCodeInvalid case .expired: text = strings().twoStepAuthEmailCodeExpired case .flood: text = strings().twoStepAuthFloodError case .generic: text = strings().unknownError } updateState { $0.withUpdatedError(InputDataValueError(description: text, target: .data), for: _id_input_enter_email_code) } f(.fail(.fields([_id_input_enter_email_code:.shake]))) }, completed: { switch data { case .access: if let password = pendingEmail.password { presentController((controller: twoStepVerificationUnlockController(context: context, mode: .manage(password: password, email: "", pendingEmail: nil, hasSecureValues: false), presentController: presentController), root: true, animated: true)) } else { presentController((controller: twoStepVerificationUnlockController(context: context, mode: .access(.set(hint: "", hasRecoveryEmail: true, hasSecureValues: false, pendingResetTimestamp: nil)), presentController: presentController), root: true, animated: true)) } case let .manage(manage): presentController((controller: twoStepVerificationUnlockController(context: context, mode: .manage(password: manage.password, email: "", pendingEmail: nil, hasSecureValues: manage.hasSecureValues), presentController: presentController), root: true, animated: true)) } updateState { state in return state.withUpdatedChecking(false).withUpdatedEmailCode("") } })) } } }) } let validateAccessPassword:([InputDataIdentifier : InputDataValue]) -> InputDataValidation = { data in var wasChecking: Bool = false updateState { state in wasChecking = state.checking return state } updateState { state in return state.withUpdatedChecking(!wasChecking) } if !wasChecking, let password = data[_id_input_enter_pwd]?.stringValue { return .fail(.doSomething(next: { f in checkDisposable.set((context.engine.auth.requestTwoStepVerifiationSettings(password: password) |> mapToSignal { settings -> Signal<(TwoStepVerificationSettings, TwoStepVerificationPendingEmail?), AuthorizationPasswordVerificationError> in return context.engine.auth.twoStepVerificationConfiguration() |> mapError { _ -> AuthorizationPasswordVerificationError in return .generic } |> map { configuration in var pendingEmail: TwoStepVerificationPendingEmail? if case let .set(configuration) = configuration { pendingEmail = configuration.pendingEmail } return (settings, pendingEmail) } } |> deliverOnMainQueue).start(next: { settings, pendingEmail in updateState { $0.withUpdatedChecking(false) } presentController((controller: twoStepVerificationUnlockController(context: context, mode: .manage(password: password, email: settings.email, pendingEmail: pendingEmail, hasSecureValues: settings.secureSecret != nil), presentController: presentController), root: true, animated: true)) f(.none) }, error: { error in let text: String switch error { case .limitExceeded: text = strings().twoStepAuthErrorLimitExceeded case .invalidPassword: text = strings().twoStepAuthInvalidPasswordError case .generic: text = strings().twoStepAuthErrorGeneric } updateState { $0.withUpdatedChecking(false).withUpdatedError(InputDataValueError(description: text, target: .data), for: _id_input_enter_pwd) } f(.fail(.fields([_id_input_enter_pwd : .shake]))) })) })) } else { checkDisposable.set(nil) } return .none } let proccessEntryResult:(SetupTwoStepVerificationStateUpdate) -> Void = { update in switch update { case .noPassword: presentController((controller: twoStepVerificationUnlockController(context: context, mode: .access(.notSet(pendingEmail: nil)), presentController: presentController), root: true, animated: true)) case let .awaitingEmailConfirmation(password, pattern, codeLength): let data = stateValue.with {$0.data} let hasSecureValues: Bool switch data { case let .manage(_, _, _, _hasSecureValues): hasSecureValues = _hasSecureValues case .access: hasSecureValues = false } let pendingEmail = TwoStepVerificationPendingEmail(pattern: pattern, codeLength: codeLength) let root = twoStepVerificationUnlockController(context: context, mode: .manage(password: password, email: "", pendingEmail: pendingEmail, hasSecureValues: hasSecureValues), presentController: presentController) presentController((controller: root, root: true, animated: false)) presentController((controller: twoStepVerificationPasswordEntryController(context: context, mode: .enterCode(codeLength: pendingEmail.codeLength, pattern: pendingEmail.pattern), initialStage: nil, result: { _ in presentController((controller: twoStepVerificationUnlockController(context: context, mode: .manage(password: password, email: "email", pendingEmail: nil, hasSecureValues: hasSecureValues), presentController: presentController), root: true, animated: true)) _ = showModalSuccess(for: context.window, icon: theme.icons.successModalProgress, delay: 1.0).start() }, presentController: presentController), root: false, animated: true)) case .emailSet: let data = stateValue.with {$0.data} switch data { case let .manage(password, _, _, hasSecureValues): presentController((controller: twoStepVerificationUnlockController(context: context, mode: .manage(password: password, email: "email", pendingEmail: nil, hasSecureValues: hasSecureValues), presentController: presentController), root: true, animated: true)) _ = showModalSuccess(for: context.window, icon: theme.icons.successModalProgress, delay: 1.0).start() default: break } case let .passwordSet(password, hasRecoveryEmail, hasSecureValues): if let password = password { presentController((controller: twoStepVerificationUnlockController(context: context, mode: .manage(password: password, email: hasRecoveryEmail ? "email" : "", pendingEmail: nil, hasSecureValues: hasSecureValues), presentController: presentController), root: true, animated: true)) _ = showModalSuccess(for: context.window, icon: theme.icons.successModalProgress, delay: 1.0).start() } else { presentController((controller: twoStepVerificationUnlockController(context: context, mode: .access(.set(hint: "", hasRecoveryEmail: hasRecoveryEmail, hasSecureValues: hasSecureValues, pendingResetTimestamp: nil)), presentController: presentController), root: true, animated: true)) } } } let setupPassword:() -> InputDataValidation = { let controller = twoStepVerificationPasswordEntryController(context: context, mode: .setup, initialStage: nil, result: proccessEntryResult, presentController: presentController) presentController((controller: controller, root: false, animated: true)) return .none } let changePassword: (_ current: String) -> InputDataValidation = { current in let controller = twoStepVerificationPasswordEntryController(context: context, mode: .change(current: current), initialStage: nil, result: proccessEntryResult, presentController: presentController) presentController((controller: controller, root: false, animated: true)) return .none } let setupRecoveryEmail:() -> InputDataValidation = { let data = stateValue.with {$0.data} switch data { case .access: break case let .manage(password, emailSet, _, _): let controller = twoStepVerificationPasswordEntryController(context: context, mode: .setupEmail(password: password, change: emailSet), initialStage: nil, result: proccessEntryResult, presentController: presentController) presentController((controller: controller, root: false, animated: true)) } return .none } let enterCode:() -> InputDataValidation = { let data = stateValue.with {$0.data} switch data { case .access: break case let .manage(_, _, pendingEmail, _): if let pendingEmail = pendingEmail { let controller = twoStepVerificationPasswordEntryController(context: context, mode: .enterCode(codeLength: pendingEmail.codeLength, pattern: pendingEmail.pattern), initialStage: nil, result: proccessEntryResult, presentController: presentController) presentController((controller: controller, root: false, animated: true)) } } return .none } let cancelReset: () -> Void = { let _ = (context.engine.auth.declineTwoStepPasswordReset() |> deliverOnMainQueue).start(completed: { _ = showModalProgress(signal: context.engine.auth.twoStepVerificationConfiguration(), for: context.window).start(next: { configuration in updateState { $0.withUpdatedControllerData(.access(configuration: .init(configuration: configuration, password: nil))) } }) }) } let forgotPassword:() -> Void = { let data = stateValue.with {$0.data} switch data { case let .access(configuration): if let configuration = configuration { switch configuration { case let .set(hint, hasRecoveryEmail, hasSecureValues, _): if hasRecoveryEmail { updateState { state in return state.withUpdatedChecking(true) } setupResultDisposable.set((context.engine.auth.requestTwoStepVerificationPasswordRecoveryCode() |> deliverOnMainQueue).start(next: { emailPattern in updateState { state in return state.withUpdatedChecking(false) } presentController((controller: twoStepVerificationResetPasswordController(context: context, emailPattern: emailPattern, success: { presentController((controller: twoStepVerificationUnlockController(context: context, mode: .access(.notSet(pendingEmail: nil)), presentController: presentController), root: true, animated: true)) }), root: false, animated: true)) }, error: { _ in updateState { state in return state.withUpdatedChecking(false) } alert(for: context.window, info: strings().twoStepAuthAnError) })) } else { let reset:()->Void = { _ = showModalProgress(signal: context.engine.auth.requestTwoStepPasswordReset(), for: context.window).start(next: { result in switch result { case .done: updateState { $0.withUpdatedControllerData(.access(configuration: .notSet(pendingEmail: nil))) } confirm(for: context.window, header: strings().twoStepAuthResetSuccessHeader, information: strings().twoStepAuthResetSuccess, okTitle: strings().alertYes, cancelTitle: strings().alertNO, successHandler: { _ in let controller = twoStepVerificationPasswordEntryController(context: context, mode: .setup, initialStage: nil, result: proccessEntryResult, presentController: presentController) presentController((controller: controller, root: true, animated: true)) }) case let .error(reason): switch reason { case let .limitExceeded(retryin): if let retryin = retryin { let formatter = DateFormatter() formatter.dateStyle = .medium formatter.timeStyle = .medium formatter.timeZone = NSTimeZone.local alert(for: context.window, info: strings().twoStepAuthUnableToReset(formatter.string(from: Date.init(timeIntervalSince1970: TimeInterval(retryin))))) } else { alert(for: context.window, info: strings().errorAnError) } default: alert(for: context.window, info: strings().errorAnError) } case .declined: break case let .waitingForReset(resetAtTimestamp): updateState { $0.withUpdatedControllerData(.access(configuration: .set(hint: hint, hasRecoveryEmail: hasRecoveryEmail, hasSecureValues: hasSecureValues, pendingResetTimestamp: resetAtTimestamp))) } } }) } reset() } default: break } } case .manage: break } } let abort: () -> Void = { updateState { $0.withUpdatedChecking(true) } let resetPassword = context.engine.auth.updateTwoStepVerificationPassword(currentPassword: nil, updatedPassword: .none) |> deliverOnMainQueue setupDisposable.set(resetPassword.start(next: { value in updateState { $0.withUpdatedChecking(false) } presentController((controller: twoStepVerificationUnlockController(context: context, mode: .access(.notSet(pendingEmail: nil)), presentController: presentController), root: true, animated: true)) }, error: { error in alert(for: context.window, info: strings().unknownError) })) } let _repeat:Signal<Void, NoError> = (.single(Void()) |> then(.single(Void()) |> suspendAwareDelay(1, queue: Queue.concurrentDefaultQueue()))) |> restart let signal: Signal<[InputDataEntry], NoError> = combineLatest(statePromise.get(), _repeat) |> map { state, _ -> [InputDataEntry] in return twoStepVerificationUnlockSettingsControllerEntries(state: state, context: context, forgotPassword: forgotPassword, cancelReset: cancelReset, abort: abort) } return InputDataController(dataSignal: signal |> map { InputDataSignalValue(entries: $0) }, title: strings().privacySettingsTwoStepVerification, validateData: { validateData -> InputDataValidation in let data = stateValue.with {$0.data} let loading = stateValue.with {$0.checking} if !loading { switch mode { case .access: switch data { case let .access(configuration): if let configuration = configuration { switch configuration { case let .notSet(pendingEmail): if let _ = pendingEmail { return checkEmailConfirmation() } else { return setupPassword() } case .set: return validateAccessPassword(validateData) } } case .manage: break } case let .manage(password, _, _, _): if let _ = validateData[_id_remove_pwd] { return disablePassword() } else if let _ = validateData[_id_change_pwd] { return changePassword(password) } else if let _ = validateData[_id_setup_email] { return setupRecoveryEmail() } else if let _ = validateData[_id_enter_email_code] { return enterCode() } } } else { NSSound.beep() } return .none }, updateDatas: { data in if let password = data[_id_input_enter_pwd]?.stringValue { updateState { state in return state.withUpdatedPasswordText(password).withUpdatedError(nil, for: _id_input_enter_pwd) } } else if let code = data[_id_input_enter_email_code]?.stringValue { updateState { state in return state.withUpdatedEmailCode(code).withUpdatedError(nil, for: _id_input_enter_email_code) } } return .none }, afterDisappear: { actionsDisposable.dispose() }, updateDoneValue: { data in return { f in let data = stateValue.with {$0.data} switch mode { case .access: switch data { case let .access(configuration: configuration): if let configuration = configuration { switch configuration { case let .notSet(pendingEmail): if let _ = pendingEmail { var checking: Bool = false var codeEmpty: Bool = true updateState { state in checking = state.checking codeEmpty = state.emailCode.isEmpty return state } return f(checking ? .loading : codeEmpty ? .disabled(strings().navigationDone) : .enabled(strings().navigationDone)) } else { } case .set: var checking: Bool = false var pwdEmpty: Bool = true updateState { state in checking = state.checking pwdEmpty = state.passwordText.isEmpty return state } return f(checking ? .loading : pwdEmpty ? .disabled(strings().navigationDone) : .enabled(strings().navigationDone)) } } else { return f(.invisible) } case .manage: break } default: break } var checking: Bool = false updateState { state in checking = state.checking return state } return f(checking ? .loading : .invisible) } }, removeAfterDisappear: false, hasDone: true, identifier: "tsv-unlock") } private struct TwoStepVerificationResetState : Equatable { let code: String let checking: Bool let emailPattern: String let errors: [InputDataIdentifier : InputDataValueError] init(emailPattern: String, code: String, checking: Bool, errors: [InputDataIdentifier : InputDataValueError] = [:]) { self.code = code self.checking = checking self.emailPattern = emailPattern self.errors = errors } func withUpdatedCode(_ code: String) -> TwoStepVerificationResetState { return TwoStepVerificationResetState(emailPattern: self.emailPattern, code: code, checking: self.checking, errors: self.errors) } func withUpdatedChecking(_ checking: Bool) -> TwoStepVerificationResetState { return TwoStepVerificationResetState(emailPattern: self.emailPattern, code: self.code, checking: checking, errors: self.errors) } func withUpdatedError(_ error: InputDataValueError?, for key: InputDataIdentifier) -> TwoStepVerificationResetState { var errors = self.errors if let error = error { errors[key] = error } else { errors.removeValue(forKey: key) } return TwoStepVerificationResetState(emailPattern: self.emailPattern, code: self.code, checking: checking, errors: errors) } } private let _id_input_recovery_code = InputDataIdentifier("_id_input_recovery_code") private func twoStepVerificationResetPasswordEntries( state: TwoStepVerificationResetState, unavailable: @escaping()-> Void) -> [InputDataEntry] { var entries: [InputDataEntry] = [] var sectionId: Int32 = 0 var index: Int32 = 0 entries.append(.sectionId(sectionId, type: .normal)) sectionId += 1 entries.append(.input(sectionId: sectionId, index: index, value: .string(state.code), error: state.errors[_id_input_recovery_code], identifier: _id_input_recovery_code, mode: .plain, data: InputDataRowData(viewType: .singleItem), placeholder: nil, inputPlaceholder: strings().twoStepAuthRecoveryCode, filter: {String($0.unicodeScalars.filter { CharacterSet.decimalDigits.contains($0)})}, limit: 255)) index += 1 let info = strings().twoStepAuthRecoveryCodeHelp + "\n\n\(strings().twoStepAuthRecoveryEmailUnavailableNew(state.emailPattern))" entries.append(.desc(sectionId: sectionId, index: index, text: .markdown(info, linkHandler: { _ in unavailable() }), data: InputDataGeneralTextData(detectBold: false, viewType: .textBottomItem))) entries.append(.sectionId(sectionId, type: .normal)) sectionId += 1 return entries } private func twoStepVerificationResetPasswordController(context: AccountContext, emailPattern: String, success: @escaping()->Void) -> InputDataController { let initialState = TwoStepVerificationResetState(emailPattern: emailPattern, code: "", checking: false) let statePromise = ValuePromise(initialState, ignoreRepeated: true) let stateValue = Atomic(value: initialState) let updateState: ((TwoStepVerificationResetState) -> TwoStepVerificationResetState) -> Void = { f in statePromise.set(stateValue.modify(f)) } let resetDisposable = MetaDisposable() let signal: Signal<[InputDataEntry], NoError> = statePromise.get() |> map { state in return twoStepVerificationResetPasswordEntries(state: state, unavailable: { alert(for: context.window, info: strings().twoStepAuthRecoveryFailed) }) } let checkRecoveryCode: (String) -> InputDataValidation = { code in return .fail(.doSomething { f in updateState { return $0.withUpdatedChecking(true) } resetDisposable.set((context.engine.auth.checkPasswordRecoveryCode(code: code) |> deliverOnMainQueue).start(error: { error in let errorText: String switch error { case .generic: errorText = strings().twoStepAuthGenericError case .invalidCode: errorText = strings().twoStepAuthRecoveryCodeInvalid case .expired: errorText = strings().twoStepAuthRecoveryCodeExpired case .limitExceeded: errorText = strings().twoStepAuthFloodError } updateState { return $0.withUpdatedError(InputDataValueError(description: errorText, target: .data), for: _id_input_recovery_code).withUpdatedChecking(false) } f(.fail(.fields([_id_input_recovery_code: .shake]))) }, completed: { updateState { return $0.withUpdatedChecking(false) } success() })) }) } return InputDataController(dataSignal: signal |> map { InputDataSignalValue(entries: $0) }, title: strings().twoStepAuthRecoveryTitle, validateData: { data in let code = stateValue.with {$0.code} let loading = stateValue.with {$0.checking} if !loading { return checkRecoveryCode(code) } else { NSSound.beep() } return .none }, updateDatas: { data in updateState { current in return current.withUpdatedCode(data[_id_input_recovery_code]?.stringValue ?? current.code).withUpdatedError(nil, for: _id_input_recovery_code) } return .none }, afterDisappear: { resetDisposable.dispose() }, updateDoneValue: { data in return { f in let code = stateValue.with {$0.code} let loading = stateValue.with {$0.checking} f(loading ? .loading : code.isEmpty ? .disabled(strings().navigationDone) : .enabled(strings().navigationDone)) } }, removeAfterDisappear: true, hasDone: true, identifier: "tsv-reset") } private let _id_input_entry_pwd = InputDataIdentifier("_id_input_entry_pwd") private let _id_input_reentry_pwd = InputDataIdentifier("_id_input_reentry_pwd") private let _id_input_entry_hint = InputDataIdentifier("_id_input_entry_hint") private let _id_input_entry_email = InputDataIdentifier("_id_input_entry_email") private let _id_input_entry_code = InputDataIdentifier("_id_input_entry_code") private func twoStepVerificationPasswordEntryControllerEntries(state: TwoStepVerificationPasswordEntryControllerState, mode: TwoStepVerificationPasswordEntryMode) -> [InputDataEntry] { var entries: [InputDataEntry] = [] var sectionId:Int32 = 0 entries.append(.sectionId(sectionId, type: .normal)) sectionId += 1 var index: Int32 = 0 switch state.stage { case let .entry(text): let placeholder:String switch mode { case .change: placeholder = strings().twoStepAuthEnterPasswordPassword default: placeholder = strings().twoStepAuthEnterPasswordPassword } entries.append(.input(sectionId: sectionId, index: index, value: .string(text), error: state.errors[_id_input_entry_pwd], identifier: _id_input_entry_pwd, mode: .secure, data: InputDataRowData(viewType: .singleItem), placeholder: nil, inputPlaceholder: placeholder, filter: { $0 }, limit: 255)) index += 1 switch mode { case .setup: entries.append(.desc(sectionId: sectionId, index: index, text: .plain(strings().twoStepAuthSetupPasswordDesc), data: InputDataGeneralTextData(viewType: .textBottomItem))) index += 1 case .change: entries.append(.desc(sectionId: sectionId, index: index, text: .plain(strings().twoStepAuthChangePasswordDesc), data: InputDataGeneralTextData(viewType: .textBottomItem))) index += 1 default: break } case let .reentry(_, text): entries.append(.input(sectionId: sectionId, index: index, value: .string(text), error: state.errors[_id_input_reentry_pwd], identifier: _id_input_reentry_pwd, mode: .secure, data: InputDataRowData(viewType: .singleItem), placeholder: nil, inputPlaceholder: strings().twoStepAuthEnterPasswordPassword, filter: { $0 }, limit: 255)) index += 1 entries.append(.desc(sectionId: sectionId, index: index, text: .plain(strings().twoStepAuthSetupPasswordConfirmPassword), data: InputDataGeneralTextData(viewType: .textBottomItem))) index += 1 case let .hint(_, text): entries.append(.input(sectionId: sectionId, index: index, value: .string(text), error: state.errors[_id_input_entry_hint], identifier: _id_input_entry_hint, mode: .plain, data: InputDataRowData(viewType: .singleItem), placeholder: nil, inputPlaceholder: strings().twoStepAuthSetupHintPlaceholder, filter: { $0 }, limit: 255)) index += 1 entries.append(.desc(sectionId: sectionId, index: index, text: .plain(strings().twoStepAuthSetupHintDesc), data: InputDataGeneralTextData(viewType: .textBottomItem))) index += 1 case let .email(_, _, text, change): entries.append(.input(sectionId: sectionId, index: index, value: .string(text), error: state.errors[_id_input_entry_email], identifier: _id_input_entry_email, mode: .plain, data: InputDataRowData(viewType: .singleItem), placeholder: nil, inputPlaceholder: strings().twoStepAuthEmail, filter: { $0 }, limit: 255)) index += 1 entries.append(.desc(sectionId: sectionId, index: index, text: .plain(change ? strings().twoStepAuthEmailHelpChange : strings().twoStepAuthEmailHelp), data: InputDataGeneralTextData(viewType: .textBottomItem))) case let .code(text, codeLength, pattern): entries.append(.input(sectionId: sectionId, index: index, value: .string(text), error: state.errors[_id_input_entry_code], identifier: _id_input_entry_code, mode: .plain, data: InputDataRowData(viewType: .singleItem), placeholder: nil, inputPlaceholder: strings().twoStepAuthRecoveryCode, filter: {String($0.unicodeScalars.filter { CharacterSet.decimalDigits.contains($0)})}, limit: codeLength ?? 255)) index += 1 entries.append(.desc(sectionId: sectionId, index: index, text: .plain(strings().twoStepAuthConfirmEmailCodeDesc(pattern)), data: InputDataGeneralTextData(detectBold: false, viewType: .textBottomItem))) } entries.append(.sectionId(sectionId, type: .normal)) sectionId += 1 return entries } func twoStepVerificationPasswordEntryController(context: AccountContext, mode: TwoStepVerificationPasswordEntryMode, initialStage: PasswordEntryStage?, result: @escaping(SetupTwoStepVerificationStateUpdate) -> Void, presentController: @escaping((controller: ViewController, root: Bool, animated: Bool)) -> Void) -> InputDataController { let network = context.account.network var initialStage: PasswordEntryStage! = initialStage if initialStage == nil { switch mode { case .setup, .change: initialStage = .entry(text: "") case let .setupEmail(password, change): initialStage = .email(password: password, hint: "", text: "", change: change) case let .enterCode(codeLength, pattern): initialStage = .code(text: "", codeLength: codeLength, pattern: pattern) } } let initialState = TwoStepVerificationPasswordEntryControllerState(stage: initialStage, updating: false, errors: [:]) let statePromise = ValuePromise(initialState, ignoreRepeated: true) let stateValue = Atomic(value: initialState) let updateState: ((TwoStepVerificationPasswordEntryControllerState) -> TwoStepVerificationPasswordEntryControllerState) -> Void = { f in statePromise.set(stateValue.modify { f($0) }) } let signal: Signal<[InputDataEntry], NoError> = statePromise.get() |> map { state in return twoStepVerificationPasswordEntryControllerEntries(state: state, mode: mode) } let actionsDisposable = DisposableSet() let updatePasswordDisposable = MetaDisposable() actionsDisposable.add(updatePasswordDisposable) func checkAndSaveState(context:AccountContext) -> InputDataValidation { var passwordHintEmail: (String, String, String)? var enterCode: String? updateState { state in if state.updating { return state } else { switch state.stage { case .entry: break case .reentry: break case let .hint(password, text): switch mode { case .change: passwordHintEmail = (password, text, "") default: preconditionFailure() } case let .email(password, hint, text, _): passwordHintEmail = (password, hint, text) case let .code(text, _, _): enterCode = text } } return state } return .fail(.doSomething { f in if let (password, hint, email) = passwordHintEmail { updateState { $0.withUpdatedUpdating(true) } switch mode { case .setup, .change: var currentPassword: String? if case let .change(current) = mode { currentPassword = current } updatePasswordDisposable.set((context.engine.auth.updateTwoStepVerificationPassword(currentPassword: currentPassword, updatedPassword: .password(password: password, hint: hint, email: email)) |> deliverOnMainQueue).start(next: { update in updateState { $0.withUpdatedUpdating(false) } switch update { case let .password(password, pendingEmail): if let pendingEmail = pendingEmail { result(.awaitingEmailConfirmation(password: password, pattern: email, codeLength: pendingEmail.codeLength)) } else { result(.passwordSet(password: password, hasRecoveryEmail: false, hasSecureValues: false)) } case .none: break } }, error: { error in updateState { $0.withUpdatedUpdating(false) } switch error { case .generic: alert(for: context.window, info: strings().twoStepAuthErrorGeneric) case .invalidEmail: updateState { $0.withUpdatedError(InputDataValueError(description: strings().twoStepAuthErrorInvalidEmail, target: .data), for: _id_input_entry_email) } f(.fail(.fields([_id_input_entry_email: .shake]))) } })) case let .setupEmail(password, _): updatePasswordDisposable.set((context.engine.auth.updateTwoStepVerificationEmail(currentPassword: password, updatedEmail: email) |> deliverOnMainQueue).start(next: { update in updateState { $0.withUpdatedUpdating(false) } switch update { case let .password(password, pendingEmail): if let pendingEmail = pendingEmail { result(.awaitingEmailConfirmation(password: password, pattern: email, codeLength: pendingEmail.codeLength)) } else { result(.passwordSet(password: password, hasRecoveryEmail: true, hasSecureValues: false)) } case .none: break } }, error: { error in updateState { $0.withUpdatedUpdating(false) } let errorText: String switch error { case .generic: errorText = strings().twoStepAuthErrorGeneric case .invalidEmail: errorText = strings().twoStepAuthErrorInvalidEmail } updateState { $0.withUpdatedError(InputDataValueError(description: errorText, target: .data), for: _id_input_entry_email) } f(.fail(.fields([_id_input_entry_email: .shake]))) })) case .enterCode: fatalError() } } else if let code = enterCode { updateState { $0.withUpdatedUpdating(true) } updatePasswordDisposable.set((context.engine.auth.confirmTwoStepRecoveryEmail(code: code) |> deliverOnMainQueue).start(error: { error in updateState { $0.withUpdatedUpdating(false) } let errorText: String switch error { case .generic: errorText = strings().twoStepAuthGenericError case .invalidCode: errorText = strings().twoStepAuthRecoveryCodeInvalid case .expired: errorText = strings().twoStepAuthRecoveryCodeExpired case .flood: errorText = strings().twoStepAuthFloodError case .invalidEmail: errorText = strings().twoStepAuthErrorInvalidEmail } updateState { $0.withUpdatedError(InputDataValueError(description: errorText, target: .data), for: _id_input_entry_code) } f(.fail(.fields([_id_input_entry_code: .shake]))) }, completed: { updateState { $0.withUpdatedUpdating(false) } result(.emailSet) })) } }) } return InputDataController(dataSignal: signal |> map { InputDataSignalValue(entries: $0) }, title: "", validateData: { data -> InputDataValidation in var stage: PasswordEntryStage? var allowPerform: Bool = true let loading = stateValue.with {$0.updating} if !loading { return .fail(.doSomething { f in var skipEmail: Bool = false updateState { state in var state = state if state.updating { return state } else { switch state.stage { case let .entry(text): if text.isEmpty { return state } else { stage = .reentry(first: text, text: "") } case let .reentry(first, text): if text.isEmpty { } else if text != first { state = state.withUpdatedError(InputDataValueError(description: strings().twoStepAuthSetupPasswordConfirmFailed, target: .data), for: _id_input_reentry_pwd) f(.fail(.fields([_id_input_reentry_pwd : .shake]))) } else { stage = .hint(password: text, text: "") } case let .hint(password, text): switch mode { case .setup: stage = .email(password: password, hint: text, text: "", change: false) default: break } case let .email(_, _, text, _): if text.isEmpty { skipEmail = true } case let .code(text, codeLength, _): if text.isEmpty { allowPerform = false } else if let codeLength = codeLength, text.length != codeLength { allowPerform = false } else { allowPerform = true } } return state } } if allowPerform { if let stage = stage { presentController((controller: twoStepVerificationPasswordEntryController(context: context, mode: mode, initialStage: stage, result: result, presentController: presentController), root: false, animated: true)) } else { if skipEmail { confirm(for: context.window, information: strings().twoStepAuthEmailSkipAlert, okTitle: strings().twoStepAuthEmailSkip, successHandler: { _ in f(checkAndSaveState(context: context)) }) } else { f(checkAndSaveState(context: context)) } } } }) } else { NSSound.beep() return .none } }, updateDatas: { data -> InputDataValidation in let previousCode: String? switch stateValue.with ({ $0.stage }) { case let .code(text, _, _): previousCode = text default: previousCode = nil } updateState { state in switch state.stage { case let .entry(text): return state.withUpdatedStage(.entry(text: data[_id_input_entry_pwd]?.stringValue ?? text)) case let .reentry(first, text): return state.withUpdatedStage(.reentry(first: first, text: data[_id_input_reentry_pwd]?.stringValue ?? text)).withUpdatedError(nil, for: _id_input_reentry_pwd) case let .hint(password, text): return state.withUpdatedStage(.hint(password: password, text: data[_id_input_entry_hint]?.stringValue ?? text)).withUpdatedError(nil, for: _id_input_entry_hint) case let .email(password, hint, text, change): return state.withUpdatedStage(.email(password: password, hint: hint, text: data[_id_input_entry_email]?.stringValue ?? text, change: change)).withUpdatedError(nil, for: _id_input_entry_email) case let .code(text, codeLength, pattern): return state.withUpdatedStage(.code(text: data[_id_input_entry_code]?.stringValue ?? text, codeLength: codeLength, pattern: pattern)).withUpdatedError(nil, for: _id_input_entry_code) } } switch stateValue.with ({ $0.stage }) { case let .code(text, codeLength, _): if Int32(text.length) == codeLength, previousCode != text { return checkAndSaveState(context: context) } default: break } return .none }, afterDisappear: { actionsDisposable.dispose() }, updateDoneValue: { data in return { f in updateState { state in if state.updating { f(.loading) } else { switch state.stage { case let .entry(text): if text.isEmpty { f(.disabled(strings().navigationNext)) } else { f(.enabled(strings().navigationNext)) } case let .reentry(_, text): if text.isEmpty { f(.disabled(strings().navigationNext)) } else { f(.enabled(strings().navigationNext)) } case let .hint(_, text): if text.isEmpty { f(.enabled(strings().twoStepAuthEmailSkip)) } else { f(.enabled(strings().navigationNext)) } case let .email(_, _, text, _): switch mode { case .setupEmail: f(text.isEmpty ? .disabled(strings().navigationNext) : .enabled(strings().navigationNext)) default: f(text.isEmpty ? .enabled(strings().twoStepAuthEmailSkip) : .enabled(strings().navigationNext)) } case let .code(text, codeLength, _): if let codeLength = codeLength { f(text.length < codeLength ? .disabled(strings().navigationNext) : .enabled(strings().navigationNext)) } else { f(text.isEmpty ? .disabled(strings().navigationNext) : .enabled(strings().navigationNext)) } } } return state } } }, removeAfterDisappear: false, hasDone: true, identifier: "tsv-entry", afterTransaction: { controller in var stage: PasswordEntryStage? updateState { state in stage = state.stage return state } if let stage = stage { var title: String = "" switch stage { case .entry: switch mode { case .change: title = strings().twoStepAuthChangePassword case .setup: title = strings().twoStepAuthSetupPasswordTitle case .setupEmail: title = strings().twoStepAuthSetupPasswordTitle case .enterCode: preconditionFailure() } case .reentry: switch mode { case .change: title = strings().twoStepAuthChangePassword case .setup: title = strings().twoStepAuthSetupPasswordTitle case .setupEmail: title = strings().twoStepAuthSetupPasswordTitle case .enterCode: preconditionFailure() } case .hint: title = strings().twoStepAuthSetupHintTitle case .email: title = strings().twoStepAuthSetupEmailTitle case .code: title = strings().twoStepAuthSetupEmailTitle } controller.setCenterTitle(title) } }) }
gpl-2.0
ea02dcd5373c1b3aed93fe56c218fc62
47.585628
464
0.56194
5.457865
false
false
false
false
overtake/TelegramSwift
packages/TGUIKit/Sources/Control.swift
1
18121
// // Control.swift // TGUIKit // // Created by keepcoder on 25/09/2016. // Copyright © 2016 Telegram. All rights reserved. // import Cocoa import SwiftSignalKit import AppKit public enum ControlState { case Normal case Hover case Highlight case Other } public enum ControlEvent { case Down case Up case Click case DoubleClick case SingleClick case RightClick case RightDown case RightUp case MouseDragging case LongMouseDown case LongMouseUp case LongOver } private let longHandleDisposable = MetaDisposable() private let longOverHandleDisposable = MetaDisposable() internal struct ControlEventHandler : Hashable { static func == (lhs: ControlEventHandler, rhs: ControlEventHandler) -> Bool { return lhs.identifier == rhs.identifier } let identifier: UInt32 let handler:(Control)->Void let event:ControlEvent let `internal`: Bool func hash(into hasher: inout Hasher) { hasher.combine(identifier) } } internal struct ControlStateHandler : Hashable { static func == (lhs: ControlStateHandler, rhs: ControlStateHandler) -> Bool { return lhs.identifier == rhs.identifier } let identifier: UInt32 let handler:(Control)->Void let state:ControlState let `internal`: Bool func hash(into hasher: inout Hasher) { hasher.combine(identifier) } } open class Control: View { public var contextObject: Any? public internal(set) weak var popover: Popover? open var isEnabled:Bool = true { didSet { if isEnabled != oldValue { apply(state: controlState) } } } open var hideAnimated:Bool = false public var appTooltip: String? open var isSelected:Bool { didSet { updateState() if isSelected != oldValue { apply(state: isSelected ? .Highlight : self.controlState) } updateSelected(isSelected) } } open func updateSelected(_ isSelected: Bool) { } open var animationStyle:AnimationStyle = AnimationStyle(duration:0.3, function:CAMediaTimingFunctionName.spring) var trackingArea:NSTrackingArea? private var handlers:[ControlEventHandler] = [] private var stateHandlers:[ControlStateHandler] = [] private(set) internal var backgroundState:[ControlState:NSColor] = [:] private var mouseMovedInside: Bool = true private var longInvoked: Bool = false public var handleLongEvent: Bool = true public var scaleOnClick: Bool = false open override var backgroundColor: NSColor { get{ return self.style.backgroundColor } set { if self.style.backgroundColor != newValue { self.style.backgroundColor = newValue self.setNeedsDisplayLayer() } } } public var style:ControlStyle = ControlStyle() { didSet { if style != oldValue { apply(style:style) } } } open override func viewDidMoveToWindow() { super.viewDidMoveToWindow() if window == nil { self.controlState = .Normal } updateTrackingAreas() } public var controlState:ControlState = .Normal { didSet { stateDidUpdate(controlState) if oldValue != controlState { apply(state: isSelected ? .Highlight : controlState) for value in stateHandlers { if value.state == controlState { value.handler(self) } } if let tp = appTooltip, controlState == .Hover { tooltip(for: self, text: tp) } } } } public func apply(state:ControlState) -> Void { let state:ControlState = self.isSelected ? .Highlight : state if isEnabled { if let color = backgroundState[state] { self.layer?.backgroundColor = color.cgColor } else { self.layer?.backgroundColor = backgroundState[.Normal]?.cgColor ?? self.backgroundColor.cgColor } } else { self.layer?.backgroundColor = backgroundState[.Normal]?.cgColor ?? self.backgroundColor.cgColor } if animates { self.layer?.animateBackground() } } private var previousState: ControlState? open func stateDidUpdate(_ state: ControlState) { if self.scaleOnClick { if state != previousState { if state == .Highlight { self.layer?.animateScaleSpring(from: 1, to: 0.96, duration: 0.3, removeOnCompletion: false) } else if self.layer?.animation(forKey: "transform") != nil, previousState == ControlState.Highlight { self.layer?.animateScaleSpring(from: 0.96, to: 1.0, duration: 0.3) } } } previousState = state } private var mouseIsDown:Bool { return (NSEvent.pressedMouseButtons & (1 << 0)) != 0 } open override func updateTrackingAreas() { super.updateTrackingAreas(); if let trackingArea = trackingArea { self.removeTrackingArea(trackingArea) } trackingArea = nil if let _ = window { let options:NSTrackingArea.Options = [.cursorUpdate, .mouseEnteredAndExited, .mouseMoved, .activeInActiveApp, .assumeInside, .inVisibleRect] self.trackingArea = NSTrackingArea(rect: self.bounds, options: options, owner: self, userInfo: nil) self.addTrackingArea(self.trackingArea!) } } open override func acceptsFirstMouse(for event: NSEvent?) -> Bool { return true } open override func viewDidMoveToSuperview() { super.viewDidMoveToSuperview() updateTrackingAreas() } deinit { if let trackingArea = self.trackingArea { self.removeTrackingArea(trackingArea) } self.popover?.hide() // longHandleDisposable.dispose() // longOverHandleDisposable.dispose() } public var controlIsHidden: Bool { return super.isHidden || layer!.opacity < Float(1.0) } open override var isHidden: Bool { get { return super.isHidden } set { if newValue != super.isHidden { if hideAnimated { if !newValue { super.isHidden = newValue } self.layer?.opacity = newValue ? 0.0 : 1.0 self.layer?.animateAlpha(from: newValue ? 1.0 : 0.0, to: newValue ? 0.0 : 1.0, duration: 0.2, completion:{ [weak self] completed in if completed { self?.updateHiddenState(newValue) } }) } else { updateHiddenState(newValue) } } } } public func forceHide() -> Void { super.isHidden = true self.layer?.removeAllAnimations() } private func updateHiddenState(_ value:Bool) -> Void { super.isHidden = value } public var canHighlight: Bool = true @discardableResult public func set(handler:@escaping (Control) -> Void, for event:ControlEvent) -> UInt32 { return set(handler: handler, for: event, internal: false) } @discardableResult public func set(handler:@escaping (Control) -> Void, for state:ControlState) -> UInt32 { return set(handler: handler, for: state, internal: false) } @discardableResult internal func set(handler:@escaping (Control) -> Void, for event:ControlEvent, internal: Bool) -> UInt32 { let new = ControlEventHandler(identifier: arc4random(), handler: handler, event: event, internal: `internal`) handlers.append(new) return new.identifier } @discardableResult internal func set(handler:@escaping (Control) -> Void, for state:ControlState, internal: Bool) -> UInt32 { let new = ControlStateHandler(identifier: arc4random(), handler: handler, state: state, internal: `internal`) stateHandlers.append(new) return new.identifier } public func set(background:NSColor, for state:ControlState) -> Void { backgroundState[state] = background apply(state: self.controlState) self.setNeedsDisplayLayer() } public func removeLastHandler() -> ((Control)->Void)? { var last: ControlEventHandler? for handler in handlers.reversed() { if !handler.internal { last = handler break } } if let last = last { self.handlers.removeAll(where: { last.identifier == $0.identifier }) return last.handler } return nil } public func removeLastStateHandler() -> Void { var last: ControlStateHandler? for handler in stateHandlers.reversed() { if !handler.internal { last = handler break } } if let last = last { self.stateHandlers.removeAll(where: { last.identifier == $0.identifier }) } } public func removeStateHandler(_ identifier: UInt32) -> Void { self.stateHandlers.removeAll(where: { identifier == $0.identifier }) } public func removeHandler(_ identifier: UInt32) -> Void { self.handlers.removeAll(where: { identifier == $0.identifier }) } public func removeAllStateHandlers() -> Void { self.stateHandlers.removeAll(where: { !$0.internal }) } public func removeAllHandlers() ->Void { self.handlers.removeAll(where: { !$0.internal }) } override open func mouseDown(with event: NSEvent) { longInvoked = false longOverHandleDisposable.set(nil) if event.modifierFlags.contains(.control) { if let menu = self.contextMenu?(), event.clickCount == 1 { AppMenu.show(menu: menu, event: event, for: self) } for handler in handlers { if handler.event == .RightDown { handler.handler(self) } } super.mouseDown(with: event) return } if userInteractionEnabled { updateState() } if self.handlers.isEmpty, let menu = self.contextMenu?(), event.clickCount == 1 { AppMenu.show(menu: menu, event: event, for: self) } if userInteractionEnabled { updateState() send(event: .Down) if handleLongEvent { let point = event.locationInWindow let disposable = (Signal<Void,Void>.single(Void()) |> delay(0.35, queue: Queue.mainQueue())).start(next: { [weak self] in self?.invokeLongDown(event, point: point) }) longHandleDisposable.set(disposable) } else { longHandleDisposable.set(nil) } } else { super.mouseDown(with: event) } } private func invokeLongDown(_ event: NSEvent, point: NSPoint) { if self.mouseInside(), let wPoint = self.window?.mouseLocationOutsideOfEventStream, NSPointInRect(point, NSMakeRect(wPoint.x - 2, wPoint.y - 2, 4, 4)) { self.longInvoked = true if let menu = self.contextMenu?(), handlers.filter({ $0.event == .LongMouseDown }).isEmpty { AppMenu.show(menu: menu, event: event, for: self) } self.send(event: .LongMouseDown) } } override open func mouseUp(with event: NSEvent) { longHandleDisposable.set(nil) longOverHandleDisposable.set(nil) if userInteractionEnabled && !event.modifierFlags.contains(.control) { if isEnabled && layer!.opacity > 0 { send(event: .Up) if longInvoked { send(event: .LongMouseUp) } if mouseInside() && !longInvoked { if event.clickCount == 1 { send(event: .SingleClick) } if event.clickCount == 2 { send(event: .DoubleClick) } send(event: .Click) } } else { if mouseInside() && !longInvoked { NSSound.beep() } } updateState() } else { if userInteractionEnabled && event.modifierFlags.contains(.control) { send(event: .RightUp) return } super.mouseUp(with: event) } } func performSuperMouseUp(_ event: NSEvent) { super.mouseUp(with: event) } func performSuperMouseDown(_ event: NSEvent) { super.mouseDown(with: event) } public var contextMenu:(()->ContextMenu?)? = nil public func send(event:ControlEvent) -> Void { for value in handlers { if value.event == event { value.handler(self) } } } override open func mouseMoved(with event: NSEvent) { updateState() if userInteractionEnabled { } else { super.mouseMoved(with: event) } } open override func rightMouseDown(with event: NSEvent) { if let menu = self.contextMenu?(), event.clickCount == 1, userInteractionEnabled { AppMenu.show(menu: menu, event: event, for: self) return } if userInteractionEnabled { updateState() send(event: .RightDown) super.rightMouseDown(with: event) } else { super.rightMouseDown(with: event) } } open override func rightMouseUp(with event: NSEvent) { if userInteractionEnabled { updateState() send(event: .RightUp) } else { super.rightMouseUp(with: event) } } public func updateState() -> Void { if mouseInside(), !inLiveResize { if mouseIsDown && canHighlight { self.controlState = .Highlight } else if mouseMovedInside { self.controlState = .Hover } else { self.controlState = .Normal } } else { self.controlState = .Normal } } public var continuesAction: Bool = false override open func mouseEntered(with event: NSEvent) { updateState() if userInteractionEnabled { let disposable = (Signal<Void,Void>.single(Void()) |> delay(0.3, queue: Queue.mainQueue())).start(next: { [weak self] in if let strongSelf = self, strongSelf.mouseInside(), strongSelf.controlState == .Hover { strongSelf.send(event: .LongOver) } }) longOverHandleDisposable.set(disposable) } else { super.mouseEntered(with: event) } } override open func mouseExited(with event: NSEvent) { updateState() longOverHandleDisposable.set(nil) if userInteractionEnabled { } else { super.mouseExited(with: event) } } open override func draggingEntered(_ sender: NSDraggingInfo) -> NSDragOperation { return NSDragOperation.generic } override open func mouseDragged(with event: NSEvent) { if userInteractionEnabled { send(event: .MouseDragging) updateState() } else { super.mouseDragged(with: event) } } func apply(style:ControlStyle) -> Void { set(background: style.backgroundColor, for: .Normal) self.backgroundColor = style.backgroundColor if self.animates { self.layer?.animateBackground() } self.setNeedsDisplayLayer() } required public init(frame frameRect: NSRect) { self.isSelected = false super.init(frame: frameRect) animates = false // layer?.disableActions() guard #available(OSX 10.12, *) else { layer?.opacity = 0.99 return } //self.wantsLayer = true //self.layer?.isOpaque = true } public override init() { self.isSelected = false super.init(frame: NSZeroRect) animates = false layer?.disableActions() guard #available(OSX 10.12, *) else { layer?.opacity = 0.99 return } //self.wantsLayer = true //self.layer?.isOpaque = true } required public init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } open override func becomeFirstResponder() -> Bool { if let window = kitWindow { return window.makeFirstResponder(self) } return false } public var forceMouseDownCanMoveWindow: Bool = false open override var mouseDownCanMoveWindow: Bool { return !self.userInteractionEnabled || forceMouseDownCanMoveWindow } }
gpl-2.0
38eb815f7626024e6fe06851a8a681e0
28.607843
160
0.545419
5.153584
false
false
false
false
pascaljette/PokeBattleDemo
PokeBattleDemo/PokeBattleDemo/Views/IntroScreen/IntroScreenViewController.swift
1
11247
// The MIT License (MIT) // // Copyright (c) 2015 pascaljette // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. import Foundation import UIKit import GearKit class IntroScreenViewController : GKViewControllerBase { // // MARK: Nested types // /// Status of the fetching operations. enum Status { /// Initial state, fetching operations are not executing. case IDLE /// Fetching the list of all pokemons to retrieve info from their URLs. case FETCHING_POKEMON_LIST /// Fetching the initial draw for each player from the pokemon list. case FETCHING_INITIAL_DRAW /// Fetching operations completed, ready to proceed. case READY } // // MARK: IBOutlets // /// Start button. @IBOutlet weak var startButton: UIButton! /// Activity indicator. @IBOutlet weak var activityIndicator: UIActivityIndicatorView! // // MARK: Stored properties // /// Reference on the fetcher that gets the full pokemon list. private let allPokemonFetcher: AllPokemonListFetcher /// Reference on the fetcher that gets detailed for each pokemon (chosen randomly). private let multiplePokemonFetcher: MultiplePokemonFetcher /// Reference on the pokemon list retrieved by the AllPokemonListFetcher. private var pokemonList: AllPokemonList = AllPokemonList() /// Initial draw containing all pokemon for all players.. private var initialDraw: [Pokemon] = [] /// Dispatch group for thread synchronization. private let dispatchGroup = dispatch_group_create(); /// Current status of the view controller. private var status: Status = .IDLE /// Sets up elements with respect to the view controller's loading status. private var loading: Bool = false { didSet { if loading { activityIndicator.startAnimating() startButton.hidden = true } else { activityIndicator.stopAnimating() startButton.hidden = false } } } // // MARK: Initializers // /// Initialize with the proper injected properties. Also sets the view controller's delegates. /// /// - parameter allPokemonListFetcher: Instance of the fetcher that gets the list of all pokemon. /// - parameter multiplePokemonFetcher: Instance of the fetcher that gets the initial draw for all players. init(allPokemonListFetcher: AllPokemonListFetcher, multiplePokemonFetcher: MultiplePokemonFetcher) { self.allPokemonFetcher = allPokemonListFetcher self.multiplePokemonFetcher = multiplePokemonFetcher super.init(nibName: "IntroScreenViewController", bundle: nil) allPokemonFetcher.delegate = self } /// Required initialiser. Unsupported so make it crash as soon as possible. /// /// - parameter coder: Coder used to initialize the view controller (when instantiated from a storyboard). required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented (storyboard not supported)") } } extension IntroScreenViewController { // // MARK: UIViewController lifecycle // /// View did load. override func viewDidLoad() { super.viewDidLoad() self.navigationItem.title = NSLocalizedString("POKERMON", comment: "Pokermon") dispatch_group_enter(dispatchGroup) allPokemonFetcher.fetch() status = .FETCHING_POKEMON_LIST multiplePokemonFetcher.delegate = self } /// View will appear. /// /// - parameter animated: Whether the view is animated when it appears. override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) loading = false } } extension IntroScreenViewController { // // MARK: Public methods // /// Shuffle the initial draw func reshuffleDraw() { loading = true dispatch_group_enter(dispatchGroup) multiplePokemonFetcher.fetch(self.pokemonList) status = .FETCHING_INITIAL_DRAW } } extension IntroScreenViewController { // // MARK: Private utility methods // /// Check the current status of the viewcontroller and move to the next view controller if ready. /// Basically, there should be no way to get to this method without being in the ready state, /// but it is checked anyways as a sanity check. private func proceedToBattleViewController() { switch status { case .READY: // Might have to wait on the next UI cycle here, but it doesn't matter much because // this is not a performance bottleneck. GKThread.dispatchOnUiThread { [weak self] in guard let strongSelf = self else { return } // Build player1 deck from the bottom half. let player1: Player = Player(id: .PLAYER_1, pokemonDraw: Array(strongSelf.initialDraw[0..<GlobalConstants.NUMBER_OF_POKEMON_PER_PLAYER])) // Build player2 deck from the upper half. let player2: Player = Player(id: .PLAYER_2, pokemonDraw: Array(strongSelf.initialDraw[GlobalConstants.NUMBER_OF_POKEMON_PER_PLAYER..<strongSelf.initialDraw.count])) // Build pokemon fetcher used in the battle screen. let pokemonFetcher = RandomPokemonFetcher(allPokemonList: strongSelf.pokemonList) strongSelf.navigationController?.pushViewController( BattleScreenViewController(pokemonList: strongSelf.pokemonList , player1: player1 , player2: player2 , pokemonFetcher: pokemonFetcher , stateMachine: StateMachine() , battleEngine: BattleEngine()) , animated: true) } case .IDLE: break case .FETCHING_POKEMON_LIST: break case .FETCHING_INITIAL_DRAW: break } } } extension IntroScreenViewController : AllPokemonListFetcherDelegate { // // MARK: AllPokemonListDelegate implementation // /// Did get the list of all possible pokemon. /// /// - parameter success: Whether the list retrieval succeeded. /// - parameter result: Retrieved list or nil on failure. /// - parameter error: Error object or nil on failure. func didGetAllPokemonList(success: Bool, result: AllPokemonList?, error: NSError?) { if success { self.pokemonList = result ?? AllPokemonList() multiplePokemonFetcher.fetch(self.pokemonList) status = .FETCHING_INITIAL_DRAW } else { status = .IDLE // TODO push this into GearKit let alertController = UIAlertController(title: NSLocalizedString("ERROR", comment: "Error"), message: "Could not retrieve list of all pokemon", preferredStyle: .Alert) let defaultAction = UIAlertAction(title: "OK", style: .Default, handler: nil) alertController.addAction(defaultAction) presentViewController(alertController, animated: true, completion: { [weak self] in guard let strongSelf = self else { return } strongSelf.loading = false }) } } } extension IntroScreenViewController : MultiplePokemonFetcherDelegate { // // MARK: MultiplePokemonFetcherDelegate implementation // /// Did get the pokemon array for the initial draw. /// /// - parameter success: Whether the list retrieval succeeded. /// - parameter result: Retrieved list or nil on failure. /// - parameter error: Error object or nil on failure. func didGetPokemonArray(success: Bool, result: [Pokemon]?, error: NSError?) { defer { dispatch_group_leave(dispatchGroup) } if success { self.initialDraw = result ?? [] status = .READY } else { status = .IDLE // TODO push this into GearKit let alertController = UIAlertController(title: NSLocalizedString("ERROR", comment: "Error"), message: "Could not retrieve initial draw", preferredStyle: .Alert) let defaultAction = UIAlertAction(title: "OK", style: .Default, handler: nil) alertController.addAction(defaultAction) presentViewController(alertController, animated: true, completion: { [weak self] in guard let strongSelf = self else { return } strongSelf.loading = false }) } } } extension IntroScreenViewController { // // MARK: IBActions // /// Called when the start button (the big pokeball) is pressed.. /// /// - parameter sender: Reference on the object sending the event. @IBAction func startButtonPressed(sender: AnyObject) { loading = true dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0)) { [weak self] in guard let strongSelf = self else { return } dispatch_group_wait(strongSelf.dispatchGroup, DISPATCH_TIME_FOREVER) strongSelf.proceedToBattleViewController() } } }
mit
6b016f76fc6f8c5d78bc758937353383
31.790087
180
0.598649
5.470331
false
false
false
false
NinjaSudo/GoodFeelsApp
GoodFeels/Clients/ContactsManager.swift
1
2416
// // ContactsManager.swift // GoodFeels // // Created by Edward Freeman on 12/21/15. // Copyright © 2015 NinjaSudo LLC. All rights reserved. // import Foundation import Contacts let ContactsManagerAddedContentNotification = "com.ninjasudo.GoodFeels.ContactsManagerContactsAdded" let ContactsManagerContentUpdateNotification = "com.ninjasudo.GoodFeels.ContactsManagerContactsUpdated" class ContactsManager: NSObject { private let contactStore = CNContactStore() private let keysToFetch = [CNContactFormatter.descriptorForRequiredKeysForStyle(CNContactFormatterStyle.FullName), CNContactPhoneNumbersKey] private let concurrentContactsQueue = dispatch_queue_create( "com.ninjasudo.GoodFeels.contactsQueue", DISPATCH_QUEUE_CONCURRENT) func isContactAvailable(contact : CNContact) { // Checking if phone number is available for the given contact. if (contact.isKeyAvailable(CNContactPhoneNumbersKey)) { print("\(contact.phoneNumbers)") } else { //Refetch the keys let refetchedContact = try! contactStore.unifiedContactWithIdentifier(contact.identifier, keysToFetch: keysToFetch) print("\(refetchedContact.phoneNumbers)") dispatch_async(dispatch_get_main_queue()) { NSNotificationCenter.defaultCenter().postNotificationName(ContactsManagerContentUpdateNotification, object: nil) } } } func fetchUnifiedContacts() { dispatch_async(concurrentContactsQueue) { do { try self.contactStore.enumerateContactsWithFetchRequest(CNContactFetchRequest(keysToFetch: self.keysToFetch)) { (contact, cursor) -> Void in if !contact.phoneNumbers.isEmpty && !GoodFeelsClient.sharedInstance.contacts.contains(contact) { GoodFeelsClient.sharedInstance.contacts.append(contact) } } } catch let error as NSError { print(error.description, separator: "", terminator: "\n") } dispatch_async(GlobalMainQueue) { self.postContentAddedNotification() } } } private func postContentAddedNotification() { NSNotificationCenter.defaultCenter().postNotificationName(ContactsManagerAddedContentNotification, object: nil) } }
mit
4235a452b1fe2dd89ffcc8f72592a94c
41.368421
144
0.677019
5.182403
false
false
false
false
yannickl/Splitflap
Tests/SplitflapTests.swift
1
4634
/* * Splitflap * * Copyright 2015-present Yannick Loriot. * http://yannickloriot.com * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * */ import UIKit import XCTest class SplitflapTests: XCTTestCaseTemplate { func testDefaultSplitflap() { let splitflap = Splitflap() XCTAssertNil(splitflap.datasource) XCTAssertNil(splitflap.delegate) XCTAssertEqual(splitflap.numberOfFlaps, 0) XCTAssertEqual(splitflap.tokens, []) XCTAssertEqual(splitflap.flapSpacing, 2) XCTAssertNil(splitflap.text) // 'didMoveToWindow' calls the 'reload' method splitflap.didMoveToWindow() XCTAssertNil(splitflap.datasource) XCTAssertNil(splitflap.delegate) XCTAssertEqual(splitflap.numberOfFlaps, 0) XCTAssertEqual(splitflap.tokens, SplitflapTokens.Alphanumeric) XCTAssertEqual(splitflap.flapSpacing, 2) XCTAssertNil(splitflap.text) } func testText() { class DataSourceMock: SplitflapDataSource { func numberOfFlapsInSplitflap(_ splitflap: Splitflap) -> Int { return 5 } } // By default, length is 0 let splitflap = Splitflap() XCTAssertNil(splitflap.text) splitflap.text = "Alongtext" XCTAssertNil(splitflap.text) // String with length 5 let datasourceMock = DataSourceMock() splitflap.datasource = datasourceMock splitflap.reload() XCTAssertNil(splitflap.text) splitflap.text = "hello" XCTAssertEqual(splitflap.text, "hello") splitflap.text = "helloworld" XCTAssertEqual(splitflap.text, "hello") splitflap.text = "$invalid!" XCTAssertNil(splitflap.text) } func testSetText() { class DataSourceMock: SplitflapDataSource { func numberOfFlapsInSplitflap(_ splitflap: Splitflap) -> Int { return 9 } } class DelegateMock: SplitflapDelegate { private func splitflap(splitflap: Splitflap, rotationDurationForFlapAtIndex index: Int) -> Double { return 0.01 } } // By default, length is 0 let splitflap = Splitflap() XCTAssertNil(splitflap.text) splitflap.setText("Alongtext", animated: true) XCTAssertNil(splitflap.text) // String with length 9 let datasourceMock = DataSourceMock() let delegateMock = DelegateMock() splitflap.datasource = datasourceMock splitflap.delegate = delegateMock splitflap.reload() var expect = expectation(description: "Block completed immediatly when no animation") splitflap.setText("Alongtext", animated: false, completionBlock: { expect.fulfill() }) waitForExpectations(timeout: 0.1, handler:nil) expect = expectation(description: "Block animation completed") splitflap.setText("Alongtext", animated: true, completionBlock: { expect.fulfill() }) XCTAssertEqual(splitflap.text, "Alongtext") waitForExpectations(timeout: 2.0, handler:nil) expect = expectation(description: "Block animation completed even with invalid text") splitflap.setText("$invalid!", animated: true, completionBlock: { expect.fulfill() }) XCTAssertNil(splitflap.text) waitForExpectations(timeout: 2.0, handler:nil) } func testReload() { class DataSourceMock: SplitflapDataSource { func numberOfFlapsInSplitflap(_ splitflap: Splitflap) -> Int { return 2 } } let datasourceMock = DataSourceMock() let splitflap = Splitflap() splitflap.datasource = datasourceMock splitflap.reload() XCTAssertEqual(splitflap.numberOfFlaps, 2) splitflap.reload() XCTAssertEqual(splitflap.numberOfFlaps, 2) } }
mit
0b41ec5bca634fd8e5065f6970f2b14d
30.310811
105
0.71407
4.119111
false
false
false
false
colemancda/NetworkObjectsDemo
CoreMessages/CoreMessages/Message.swift
1
1022
// // Message.swift // CoreMessages // // Created by Alsey Coleman Miller on 9/14/15. // Copyright © 2015 ColemanCDA. All rights reserved. // import SwiftFoundation import CoreData public class Message: NSManagedObject { public enum Attribute: String { case Date = "date" case Text = "text" } public static var EntityName: String { return "Message" } public var text: String? { let key = Attribute.Text.rawValue self.willAccessValueForKey(key) let value = self.primitiveValueForKey(key) as? String self.didAccessValueForKey(key) return value } public var date: Date? { let key = Attribute.Date.rawValue self.willAccessValueForKey(key) let value = self.primitiveValueForKey(key) as? NSDate self.didAccessValueForKey(key) if let dateValue = value { return Date(foundation: dateValue) } else { return nil } } }
mit
9be515d8434a5d7b8cab60e56a13068e
22.744186
91
0.60431
4.599099
false
false
false
false
tinrobots/CoreDataPlus
Tests/NSManagedObjectContextHistoryTests.swift
1
21382
// CoreDataPlus import XCTest import CoreData @testable import CoreDataPlus @available(iOS 13.0, iOSApplicationExtension 13.0, macCatalyst 13.0, tvOS 13.0, watchOS 6.0, macOS 10.15, *) final class NSManagedObjectContextHistoryTests: BaseTestCase { func testMergeHistoryAfterDate() throws { // Given let id = UUID() let container1 = OnDiskPersistentContainer.makeNew(id: id) let container2 = OnDiskPersistentContainer.makeNew(id: id) let expectation1 = expectation(description: "\(#function)\(#line)") let viewContext1 = container1.viewContext viewContext1.name = "viewContext1" let viewContext2 = container2.viewContext viewContext2.name = "viewContext2" viewContext1.fillWithSampleData() try viewContext1.save() XCTAssertFalse(viewContext1.registeredObjects.isEmpty) XCTAssertTrue(viewContext2.registeredObjects.isEmpty) // When, Then let cancellable = NotificationCenter.default.publisher(for: .NSManagedObjectContextObjectsDidChange, object: viewContext2) .sink { _ in expectation1.fulfill() } let transactionsFromDistantPast = try viewContext2.historyTransactions(using: NSPersistentHistoryChangeRequest.fetchHistory(after: .distantPast)) XCTAssertEqual(transactionsFromDistantPast.count, 1) let result = try viewContext2.mergeTransactions(transactionsFromDistantPast) XCTAssertNotNil(result) XCTAssertTrue(viewContext2.registeredObjects.isEmpty) waitForExpectations(timeout: 5, handler: nil) cancellable.cancel() let status = try viewContext2.deleteHistory(before: result!.0) XCTAssertTrue(status) // cleaning avoiding SQLITE warnings let psc1 = viewContext1.persistentStoreCoordinator! try psc1.persistentStores.forEach { store in try psc1.remove(store) } let psc2 = viewContext2.persistentStoreCoordinator! try psc2.persistentStores.forEach { store in try psc2.remove(store) } try container1.destroy() } func testMergeHistoryAfterDateWithMultipleTransactions() throws { // Given let id = UUID() let container1 = OnDiskPersistentContainer.makeNew(id: id) let container2 = OnDiskPersistentContainer.makeNew(id: id) let expectation1 = expectation(description: "\(#function)\(#line)") let expectation2 = expectation(description: "\(#function)\(#line)") let expectation3 = expectation(description: "\(#function)\(#line)") let viewContext1 = container1.viewContext viewContext1.name = "viewContext1" viewContext1.transactionAuthor = "\(#function)" let viewContext2 = container2.viewContext viewContext2.name = "viewContext2" let person1 = Person(context: viewContext1) person1.firstName = "Edythe" person1.lastName = "Moreton" let person2 = Person(context: viewContext1) person2.firstName = "Ellis" person2.lastName = "Khoury" try viewContext1.save() // When, Then // we don't care about the first insert because viewContext2 will fetch everything from the the db try viewContext1.deleteHistory(before: .distantFuture) let persons = try Person.fetch(in: viewContext2) // materialize all the objects to listen to updates/merges in addition to inserts and deletes try persons.materializeFaults() XCTAssertEqual(persons.count, 2) let person3 = Person(context: viewContext1) person3.firstName = "Faron" person3.lastName = "Moreton" let person4 = Person(context: viewContext1) person4.firstName = "Darin" person4.lastName = "Meadow" let person5 = Person(context: viewContext1) person5.firstName = "Juliana" person5.lastName = "Pyke" try viewContext1.save() // 3 inserts person1.firstName = person1.firstName + "*" try viewContext1.save() // 1 update person2.delete() try viewContext1.save() // 1 delete let cancellable = NotificationCenter.default.publisher(for: .NSManagedObjectContextObjectsDidChange, object: viewContext2) .map { ManagedObjectContextObjectsDidChange(notification: $0) } .sink { payload in XCTAssertTrue(payload.managedObjectContext === viewContext2) if !payload.insertedObjects.isEmpty { expectation1.fulfill() } else if !payload.updatedObjects.isEmpty || !payload.refreshedObjects.isEmpty { expectation2.fulfill() } else if !payload.deletedObjects.isEmpty { expectation3.fulfill() } } let transactionsFromDistantPast = try viewContext2.historyTransactions(using: NSPersistentHistoryChangeRequest.fetchHistory(after: .distantPast)) XCTAssertEqual(transactionsFromDistantPast.count, 3) let result = try viewContext2.mergeTransactions(transactionsFromDistantPast) XCTAssertNotNil(result) waitForExpectations(timeout: 5, handler: nil) try viewContext2.save() print(viewContext2.insertedObjects) cancellable.cancel() let status = try viewContext2.deleteHistory(before: result!.0) XCTAssertTrue(status) // cleaning avoiding SQLITE warnings let psc1 = viewContext1.persistentStoreCoordinator! try psc1.persistentStores.forEach { store in try psc1.remove(store) } let psc2 = viewContext2.persistentStoreCoordinator! try psc2.persistentStores.forEach { store in try psc2.remove(store) } try container1.destroy() } func testMergeHistoryAfterNilTokenWithoutAnyHistoryChanges() throws { let container1 = OnDiskPersistentContainer.makeNew() let stores = container1.persistentStoreCoordinator.persistentStores XCTAssertEqual(stores.count, 1) let currentToken = container1.persistentStoreCoordinator.currentPersistentHistoryToken(fromStores: stores) // it's a new store, there shouldn't be any transactions let requestToken: NSPersistentHistoryToken? = nil let transactions = try container1.viewContext.historyTransactions(using: NSPersistentHistoryChangeRequest.fetchHistory(after: requestToken)) XCTAssertTrue(transactions.isEmpty) XCTAssertNotNil(currentToken) let transactionsAfterCurrentToken = try container1.viewContext.historyTransactions(using: NSPersistentHistoryChangeRequest.fetchHistory(after: currentToken)) let result = try container1.viewContext.mergeTransactions(transactionsAfterCurrentToken) XCTAssertNil(result) let result2 = try container1.viewContext.mergeTransactions(transactions) XCTAssertNil(result2) try container1.destroy() } func testPersistentHistoryTrackingEnabledGenerateHistoryTokens() throws { // Given let psc = NSPersistentStoreCoordinator(managedObjectModel: model) let storeURL = URL.newDatabaseURL(withID: UUID()) let options: PersistentStoreOptions = [NSPersistentHistoryTrackingKey: true as NSNumber] // enable History Tracking try psc.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: storeURL, options: options) let expectation1 = expectation(description: "\(#function)\(#line)") let context = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType) context.persistentStoreCoordinator = psc // When, Then let cancellable = NotificationCenter.default.publisher(for: .NSManagedObjectContextDidSave, object: context) .map { ManagedObjectContextDidSaveObjects(notification: $0) } .sink { payload in XCTAssertNotNil(payload.historyToken) expectation1.fulfill() } let person1 = Person(context: context) person1.firstName = "Edythe" person1.lastName = "Moreton" try context.save() waitForExpectations(timeout: 5, handler: nil) cancellable.cancel() let result = try context.deleteHistory() XCTAssertTrue(result) // cleaning avoiding SQLITE warnings try psc.persistentStores.forEach { try psc.remove($0) } try NSPersistentStoreCoordinator.destroyStore(at: storeURL) } func testPersistentHistoryTrackingDisabledDoesntGenerateHistoryTokens() throws { // Given let psc = NSPersistentStoreCoordinator(managedObjectModel: model) let storeURL = URL.newDatabaseURL(withID: UUID()) try psc.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: storeURL, options: nil) let expectation1 = expectation(description: "\(#function)\(#line)") let context = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType) context.persistentStoreCoordinator = psc // When, Then let cancellable = NotificationCenter.default.publisher(for: .NSManagedObjectContextDidSave, object: context) .map { ManagedObjectContextDidSaveObjects(notification: $0) } .sink { payload in XCTAssertNil(payload.historyToken, "The Persistent Store Coordinator doesn't have the NSPersistentStoreRemoteChangeNotificationPostOptionKey option enabled.") expectation1.fulfill() } let person1 = Person(context: context) person1.firstName = "Edythe" person1.lastName = "Moreton" try context.save() waitForExpectations(timeout: 5, handler: nil) cancellable.cancel() // cleaning avoiding SQLITE warnings try psc.persistentStores.forEach { try psc.remove($0) } try NSPersistentStoreCoordinator.destroyStore(at: storeURL) } func testDeleteHistoryAfterTransaction() throws { let container = OnDiskPersistentContainer.makeNew() let viewContext = container.viewContext // Transaction #1 let car1 = Car(context: viewContext) car1.maker = "FIAT" car1.model = "Panda" car1.numberPlate = "1" try viewContext.save() // Transaction #2 let car2 = Car(context: viewContext) car2.maker = "FIAT" car2.model = "Punto" car2.numberPlate = "2" try viewContext.save() let transactions1 = try viewContext.historyTransactions(using: NSPersistentHistoryChangeRequest.fetchHistory(after: .distantPast)) XCTAssertEqual(transactions1.count, 2) let firstTransaction1 = try XCTUnwrap(transactions1.first) // Removes all the transactions before the first one: no transactions are actually deleted let result1 = try XCTUnwrap(try viewContext.deleteHistory(before: firstTransaction1)) XCTAssertTrue(result1) let transactions2 = try viewContext.historyTransactions(using: NSPersistentHistoryChangeRequest.fetchHistory(after: .distantPast)) XCTAssertEqual(transactions2.count, 2) let lastTransaction2 = try XCTUnwrap(transactions2.last) // Removes all the transactions before the last one: 1 transaction gets deleted let result2 = try XCTUnwrap(try viewContext.deleteHistory(before: lastTransaction2)) XCTAssertTrue(result2) let transactions3 = try viewContext.historyTransactions(using: NSPersistentHistoryChangeRequest.fetchHistory(after: .distantPast)) XCTAssertEqual(transactions3.count, 1) } func testFetchHistoryChangesUsingFetchRequest() throws { // Given let id = UUID() let container1 = OnDiskPersistentContainer.makeNew(id: id) let container2 = OnDiskPersistentContainer.makeNew(id: id) let viewContext1 = container1.viewContext viewContext1.name = "viewContext1" viewContext1.transactionAuthor = "author1" let viewContext2 = container2.viewContext viewContext2.name = "viewContext2" viewContext2.transactionAuthor = "author2" let lastHistoryToken = try XCTUnwrap(container2.persistentStoreCoordinator.currentPersistentHistoryToken(fromStores: viewContext2.persistentStores)) viewContext1.fillWithSampleData() try viewContext1.save() let newHistoryToken = try XCTUnwrap(container2.persistentStoreCoordinator.currentPersistentHistoryToken(fromStores: viewContext2.persistentStores)) let tokenGreaterThanLastHistoryTokenPredicate = NSPredicate(format: "%@ < token", lastHistoryToken) let tokenGreaterThanNewHistoryTokenPredicate = NSPredicate(format: "%@ < token", newHistoryToken) let notAuthor2Predicate = NSPredicate(format: "author != %@", "author2") let notAuthor1Predicate = NSPredicate(format: "author != %@", "author1") do { let predicate = NSCompoundPredicate(type: .and, subpredicates: [tokenGreaterThanLastHistoryTokenPredicate, notAuthor1Predicate]) let request = try XCTUnwrap(NSPersistentHistoryChangeRequest.historyTransactionFetchRequest(with: viewContext2, where: predicate)) let allTransactions = try viewContext2.historyTransactions(using: request) XCTAssertTrue(allTransactions.isEmpty) let result = try viewContext2.mergeTransactions(allTransactions) XCTAssertNil(result) } do { let predicate = tokenGreaterThanNewHistoryTokenPredicate let request = try XCTUnwrap(NSPersistentHistoryChangeRequest.historyTransactionFetchRequest(with: viewContext2, where: predicate)) let allTransactions = try viewContext2.historyTransactions(using: request) XCTAssertTrue(allTransactions.isEmpty) XCTAssertTrue(allTransactions.isEmpty) let result = try viewContext2.mergeTransactions(allTransactions) XCTAssertNil(result) } do { let predicate = NSCompoundPredicate(type: .and, subpredicates: [tokenGreaterThanLastHistoryTokenPredicate, notAuthor2Predicate]) let request = try XCTUnwrap(NSPersistentHistoryChangeRequest.historyTransactionFetchRequest(with: viewContext2, where: predicate)) let allTransactions = try viewContext2.historyTransactions(using: request) XCTAssertFalse(allTransactions.isEmpty) let result = try viewContext2.mergeTransactions(allTransactions) XCTAssertNotNil(result) } // cleaning avoiding SQLITE warnings let psc1 = viewContext1.persistentStoreCoordinator! try psc1.persistentStores.forEach { store in try psc1.remove(store) } let psc2 = viewContext2.persistentStoreCoordinator! try psc2.persistentStores.forEach { store in try psc2.remove(store) } try container1.destroy() } func testInvestigationHistoryFetches() throws { // Given let id = UUID() let container1 = OnDiskPersistentContainer.makeNew(id: id) let container2 = OnDiskPersistentContainer.makeNew(id: id) let viewContext1 = container1.viewContext viewContext1.name = "viewContext1" viewContext1.transactionAuthor = "author1" let viewContext2 = container2.viewContext viewContext2.name = "viewContext2" viewContext2.transactionAuthor = "author2" var tokens = [NSPersistentHistoryToken]() let initialToken = try XCTUnwrap(container2.persistentStoreCoordinator.currentPersistentHistoryToken(fromStores: viewContext1.persistentStores)) tokens.append(initialToken) // Transaction #1 - 2 Cars, 1 SportCar let car1 = Car(context: viewContext1) car1.maker = "FIAT" car1.model = "Panda" car1.numberPlate = "1" let car2 = Car(context: viewContext1) car2.maker = "FIAT" car2.model = "Punto" car2.numberPlate = "2" let sportCar1 = SportCar(context: viewContext1) sportCar1.maker = "McLaren" sportCar1.model = "570GT" sportCar1.numberPlate = "3" try viewContext1.save() let token1 = try XCTUnwrap(container2.persistentStoreCoordinator.currentPersistentHistoryToken(fromStores: viewContext1.persistentStores)) tokens.append(token1) // Transaction #2 - 1 Person let person = Person(context: viewContext1) person.firstName = "Alessandro" person.lastName = "Marzoli" try viewContext1.save() let token2 = try XCTUnwrap(container2.persistentStoreCoordinator.currentPersistentHistoryToken(fromStores: viewContext1.persistentStores)) tokens.append(token2) // Transaction #3 - 1 Person updated, 1 Car deleted person.firstName = "Alex" car2.delete() try viewContext1.save() let token3 = try XCTUnwrap(container2.persistentStoreCoordinator.currentPersistentHistoryToken(fromStores: viewContext1.persistentStores)) tokens.append(token3) XCTAssertEqual(tokens.count, 4) let currentToken = try XCTUnwrap(container2.persistentStoreCoordinator.currentPersistentHistoryToken(fromStores: viewContext2.persistentStores)) let lastToken = try XCTUnwrap(tokens.last) let secondLastToken = try XCTUnwrap(tokens.suffix(2).first) XCTAssertEqual(lastToken, currentToken) do { // ⏺ Query the Transaction entity let predicate = NSPredicate(format: "%K > %@", #keyPath(NSPersistentHistoryTransaction.token), secondLastToken) let transactionsRequest = try XCTUnwrap(NSPersistentHistoryChangeRequest.historyTransactionFetchRequest(with: viewContext2, where: predicate)) // same as (but during tests the request it's nil): // let transactionFetchRequest = NSPersistentHistoryTransaction.fetchRequest //transactionsRequest.predicate = NSPredicate(format: "token == %@", lastToken) transactionsRequest.resultType = .transactionsOnly let transactions = try viewContext2.performAndWaitResult { context ->[NSPersistentHistoryTransaction] in // swiftlint:disable force_cast let history = try context.execute(transactionsRequest) as! NSPersistentHistoryResult let transactions = history.result as! [NSPersistentHistoryTransaction] // ordered from the oldest to the most recent // swiftlint:enable force_cast return transactions } XCTAssertEqual(transactions.count, 1) let first = try XCTUnwrap(transactions.first) XCTAssertEqual(first.token, tokens.last) XCTAssertNil(first.changes) // result type is transactionsOnly } catch { XCTFail("Querying the Transaction entity failed: \(error.localizedDescription)") } do { // ⏺ Query the Change entity let predicate = NSCompoundPredicate(andPredicateWithSubpredicates: [ NSPredicate(format: "changeType == %d", NSPersistentHistoryChangeType.update.rawValue), // Change condition // ⚠️ Even if it seems that some Transaction fields like "token" can be used here, the behavior is not predicatble // it's best if we stick with Change fields // NSPredicate(format: "token > %@", secondLastToken) // Transaction condition (working) // NSPredicate(format: "token == %@") // Transaction condition (not working) // NSPredicate(format: "author != %@", "author1") // Transaction condition (exception) ]) let changesRequest = try XCTUnwrap(NSPersistentHistoryChangeRequest.historyChangeFetchRequest(with: viewContext2, where: predicate)) changesRequest.resultType = .transactionsAndChanges let transactions = try viewContext2.performAndWaitResult { context ->[NSPersistentHistoryTransaction] in let history = try context.execute(changesRequest) as! NSPersistentHistoryResult let transactions = history.result as! [NSPersistentHistoryTransaction] // ordered from the oldest to the most recent return transactions } XCTAssertEqual(transactions.count, 1) let first = try XCTUnwrap(transactions.first) XCTAssertEqual(first.token, tokens.last) let changes = try XCTUnwrap(first.changes) XCTAssertFalse(changes.isEmpty) // result type is transactionsAndChanges } catch { XCTFail("Querying the Change entity failed: \(error.localizedDescription)") } do { // ⏺ Query the Change entity let predicate = NSCompoundPredicate(andPredicateWithSubpredicates: [ NSPredicate(format: "changeType == %d", NSPersistentHistoryChangeType.insert.rawValue), NSPredicate(format: "changedEntity == %@ || changedEntity == %@", Car.entity(), Person.entity()) // ignores sub entities ]) let changesRequest = try XCTUnwrap(NSPersistentHistoryChangeRequest.historyChangeFetchRequest(with: viewContext2, where: predicate)) changesRequest.resultType = .changesOnly // ⚠️ impact the return type let changes = try viewContext2.historyChanges(using: changesRequest) XCTAssertEqual(changes.count, 3) // 2 Cars + 1 Person } catch { XCTFail("Querying the Change entity failed: \(error.localizedDescription)") } do { // ⏺ Query the Change entity let changeEntity = NSPersistentHistoryChange.entityDescription(with: viewContext1)! XCTAssertNil(changeEntity.attributesByName["changedObjectID"], "Shown on WWDC 2020 but currently nil.") // FB8353599 let request = NSFetchRequest<NSFetchRequestResult>() request.entity = changeEntity let columnName = changeEntity.attributesByName["changedEntity"]!.name // WWDC 2020 request.predicate = NSPredicate(format: "%K = %@", columnName, Car.entity()) let historyFetchRequest = NSPersistentHistoryChangeRequest.fetchHistory(after: secondLastToken) historyFetchRequest.fetchRequest = request // ⚠️ WWDC 2020: history requests can be tailored using the fetchRequest property historyFetchRequest.resultType = .changesOnly // ⚠️ impact the return type let changes = try viewContext2.historyChanges(using: historyFetchRequest) XCTAssertEqual(changes.count, 1) // Car2 has been eliminated in the last token let first = try XCTUnwrap(changes.first) XCTAssertEqual(first.changedObjectID.uriRepresentation(), car2.objectID.uriRepresentation()) XCTAssertEqual(first.changeType, NSPersistentHistoryChangeType.delete) } catch { XCTFail("Querying the Change entity failed: : \(error.localizedDescription)") } } }
mit
dd2cf6f7601ef53bf4a1e9f7ea482fac
40.633528
166
0.743
4.744114
false
false
false
false
lastobelus/eidolon
Kiosk/App/Networking/ArtsyAPI.swift
2
12628
import Foundation import ReactiveCocoa import Moya enum ArtsyAPI { case XApp case XAuth(email: String, password: String) case TrustToken(number: String, auctionPIN: String) case SystemTime case Ping case Me case MyCreditCards case CreatePINForBidder(bidderID: String) case FindBidderRegistration(auctionID: String, phone: String) case RegisterToBid(auctionID: String) case Artwork(id: String) case Artist(id: String) case Auctions case AuctionListings(id: String, page: Int, pageSize: Int) case AuctionInfo(auctionID: String) case AuctionInfoForArtwork(auctionID: String, artworkID: String) case ActiveAuctions case MyBiddersForAuction(auctionID: String) case MyBidPositionsForAuctionArtwork(auctionID: String, artworkID: String) case PlaceABid(auctionID: String, artworkID: String, maxBidCents: String) case UpdateMe(email: String, phone: String, postCode: String, name: String) case CreateUser(email: String, password: String, phone: String, postCode: String, name: String) case RegisterCard(stripeToken: String) case BidderDetailsNotification(auctionID: String, identifier: String) case LostPasswordNotification(email: String) case FindExistingEmailRegistration(email: String) } extension ArtsyAPI : MoyaTarget { var path: String { switch self { case .XApp: return "/api/v1/xapp_token" case .XAuth: return "/oauth2/access_token" case AuctionInfo(let id): return "/api/v1/sale/\(id)" case Auctions: return "/api/v1/sales" case AuctionListings(let id, _, _): return "/api/v1/sale/\(id)/sale_artworks" case AuctionInfoForArtwork(let auctionID, let artworkID): return "/api/v1/sale/\(auctionID)/sale_artwork/\(artworkID)" case SystemTime: return "/api/v1/system/time" case Ping: return "/api/v1/system/ping" case RegisterToBid: return "/api/v1/bidder" case MyCreditCards: return "/api/v1/me/credit_cards" case CreatePINForBidder(let bidderID): return "/api/v1/bidder/\(bidderID)/pin" case ActiveAuctions: return "/api/v1/sales" case Me: return "/api/v1/me" case UpdateMe: return "/api/v1/me" case CreateUser: return "/api/v1/user" case MyBiddersForAuction: return "/api/v1/me/bidders" case MyBidPositionsForAuctionArtwork: return "/api/v1/me/bidder_positions" case Artwork(let id): return "/api/v1/artwork/\(id)" case Artist(let id): return "/api/v1/artist/\(id)" case FindBidderRegistration: return "/api/v1/bidder" case PlaceABid: return "/api/v1/me/bidder_position" case RegisterCard: return "/api/v1/me/credit_cards" case TrustToken: return "/api/v1/me/trust_token" case BidderDetailsNotification: return "/api/v1/bidder/bidding_details_notification" case LostPasswordNotification: return "/api/v1/users/send_reset_password_instructions" case FindExistingEmailRegistration: return "/api/v1/user" } } var base: String { return AppSetup.sharedState.useStaging ? "https://stagingapi.artsy.net" : "https://api.artsy.net" } var baseURL: NSURL { return NSURL(string: base)! } var parameters: [String: AnyObject] { switch self { case XAuth(let email, let password): return [ "client_id": APIKeys.sharedKeys.key ?? "", "client_secret": APIKeys.sharedKeys.secret ?? "", "email": email, "password": password, "grant_type": "credentials" ] case XApp: return ["client_id": APIKeys.sharedKeys.key ?? "", "client_secret": APIKeys.sharedKeys.secret ?? ""] case Auctions: return ["is_auction": "true"] case RegisterToBid(let auctionID): return ["sale_id": auctionID] case MyBiddersForAuction(let auctionID): return ["sale_id": auctionID] case PlaceABid(let auctionID, let artworkID, let maxBidCents): return [ "sale_id": auctionID, "artwork_id": artworkID, "max_bid_amount_cents": maxBidCents ] case TrustToken(let number, let auctionID): return ["number": number, "auction_pin": auctionID] case CreateUser(let email, let password,let phone,let postCode, let name): return [ "email": email, "password": password, "phone": phone, "name": name, "location": [ "postal_code": postCode ] ] case UpdateMe(let email, let phone,let postCode, let name): return [ "email": email, "phone": phone, "name": name, "location": [ "postal_code": postCode ] ] case RegisterCard(let token): return ["provider": "stripe", "token": token] case FindBidderRegistration(let auctionID, let phone): return ["sale_id": auctionID, "number": phone] case BidderDetailsNotification(let auctionID, let identifier): return ["sale_id": auctionID, "identifier": identifier] case LostPasswordNotification(let email): return ["email": email] case FindExistingEmailRegistration(let email): return ["email": email] case AuctionListings(_, let page, let pageSize): return ["size": pageSize, "page": page] case ActiveAuctions: return ["is_auction": true, "live": true] case MyBidPositionsForAuctionArtwork(let auctionID, let artworkID): return ["sale_id": auctionID, "artwork_id": artworkID] default: return [:] } } var method: Moya.Method { switch self { case .LostPasswordNotification, .CreateUser, .PlaceABid, .RegisterCard, .RegisterToBid, .CreatePINForBidder: return .POST case .FindExistingEmailRegistration: return .HEAD case .UpdateMe, .BidderDetailsNotification: return .PUT default: return .GET } } var sampleData: NSData { switch self { case XApp: return stubbedResponse("XApp") case XAuth: return stubbedResponse("XAuth") case TrustToken: return stubbedResponse("XAuth") case Auctions: return stubbedResponse("Auctions") case AuctionListings: return stubbedResponse("AuctionListings") case SystemTime: return stubbedResponse("SystemTime") case CreatePINForBidder: return stubbedResponse("CreatePINForBidder") case ActiveAuctions: return stubbedResponse("ActiveAuctions") case MyCreditCards: return stubbedResponse("MyCreditCards") case RegisterToBid: return stubbedResponse("RegisterToBid") case MyBiddersForAuction: return stubbedResponse("MyBiddersForAuction") case Me: return stubbedResponse("Me") case UpdateMe: return stubbedResponse("Me") case CreateUser: return stubbedResponse("Me") // This API returns a 302, so stubbed response isn't valid case FindBidderRegistration: return stubbedResponse("Me") case PlaceABid: return stubbedResponse("CreateABid") case Artwork: return stubbedResponse("Artwork") case Artist: return stubbedResponse("Artist") case AuctionInfo: return stubbedResponse("AuctionInfo") case RegisterCard: return stubbedResponse("RegisterCard") case BidderDetailsNotification: return stubbedResponse("RegisterToBid") case LostPasswordNotification: return stubbedResponse("ForgotPassword") case FindExistingEmailRegistration: return stubbedResponse("ForgotPassword") case AuctionInfoForArtwork: return stubbedResponse("AuctionInfoForArtwork") case MyBidPositionsForAuctionArtwork: return stubbedResponse("MyBidPositionsForAuctionArtwork") case Ping: return stubbedResponse("Ping") } } } // MARK: - Provider setup func endpointResolver() -> ((endpoint: Endpoint<ArtsyAPI>) -> (NSURLRequest)) { return { (endpoint: Endpoint<ArtsyAPI>) -> (NSURLRequest) in let request: NSMutableURLRequest = endpoint.urlRequest.mutableCopy() as! NSMutableURLRequest request.HTTPShouldHandleCookies = false return request } } class ArtsyProvider<T where T: MoyaTarget>: ReactiveCocoaMoyaProvider<T> { typealias OnlineSignalClosure = () -> RACSignal // Closure that returns a signal which completes once the app is online. let onlineSignal: OnlineSignalClosure init(endpointClosure: MoyaEndpointsClosure = MoyaProvider.DefaultEndpointMapping, endpointResolver: MoyaEndpointResolution = MoyaProvider.DefaultEnpointResolution, stubBehavior: MoyaStubbedBehavior = MoyaProvider.NoStubbingBehavior, networkActivityClosure: Moya.NetworkActivityClosure? = nil, onlineSignal: OnlineSignalClosure = connectedToInternetSignal) { self.onlineSignal = onlineSignal super.init(endpointClosure: endpointClosure, endpointResolver: endpointResolver, stubBehavior: stubBehavior, networkActivityClosure: networkActivityClosure) } } struct Provider { private static var endpointsClosure = { (target: ArtsyAPI) -> Endpoint<ArtsyAPI> in var endpoint: Endpoint<ArtsyAPI> = Endpoint<ArtsyAPI>(URL: url(target), sampleResponse: .Success(200, {target.sampleData}), method: target.method, parameters: target.parameters) // Sign all non-XApp token requests switch target { case .XApp: return endpoint case .XAuth: return endpoint default: return endpoint.endpointByAddingHTTPHeaderFields(["X-Xapp-Token": XAppToken().token ?? ""]) } } static func APIKeysBasedStubBehaviour(target: ArtsyAPI) -> Moya.StubbedBehavior { return APIKeys.sharedKeys.stubResponses ? .Immediate : .NoStubbing } // init(endpointClosure: MoyaEndpointsClosure = MoyaProvider.DefaultEndpointMapping, endpointResolver: MoyaEndpointResolution = MoyaProvider.DefaultEnpointResolution, stubBehavior: MoyaStubbedBehavior = MoyaProvider.NoStubbingBehavior, networkActivityClosure: Moya.NetworkActivityClosure? = nil, onlineSignal: OnlineSignalClosure = connectedToInternetSignal) { static func DefaultProvider() -> ArtsyProvider<ArtsyAPI> { return ArtsyProvider(endpointClosure: endpointsClosure, endpointResolver: endpointResolver(), stubBehavior: APIKeysBasedStubBehaviour) } static func StubbingProvider() -> ArtsyProvider<ArtsyAPI> { return ArtsyProvider(endpointClosure: endpointsClosure, endpointResolver: endpointResolver(), stubBehavior: MoyaProvider.ImmediateStubbingBehaviour, onlineSignal: { RACSignal.empty() }) } private struct SharedProvider { static var instance = Provider.DefaultProvider() } static var sharedProvider: ArtsyProvider<ArtsyAPI> { get { return SharedProvider.instance } set (newSharedProvider) { SharedProvider.instance = newSharedProvider } } } // MARK: - Provider support private func stubbedResponse(filename: String) -> NSData! { @objc class TestClass: NSObject { } let bundle = NSBundle(forClass: TestClass.self) let path = bundle.pathForResource(filename, ofType: "json") return NSData(contentsOfFile: path!) } private extension String { var URLEscapedString: String { return self.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLHostAllowedCharacterSet())! } } func url(route: MoyaTarget) -> String { return route.baseURL.URLByAppendingPathComponent(route.path).absoluteString }
mit
fa6b45c2e8de6b9f2ec473d9c1d5aa7a
30.57
364
0.6309
4.902174
false
false
false
false
deliangyang/WordPress-iOS
WordPress/WordPressTest/ReaderTopicServiceTest.swift
1
13196
import Foundation import CoreData import WordPress class ReaderTopicSwiftTest : XCTestCase { var testContextManager: TestContextManager? // MARK: - Lifecycle override func setUp() { super.setUp() testContextManager = TestContextManager() } override func tearDown() { super.tearDown() testContextManager = nil } // MARK: - Config / Helpers func seedTopics() { let context = ContextManager.sharedInstance().mainContext let topic1 = NSEntityDescription.insertNewObjectForEntityForName(ReaderListTopic.classNameWithoutNamespaces(),inManagedObjectContext: context) as! ReaderListTopic topic1.path = "/list/topic1" topic1.title = "topic1" topic1.type = ReaderListTopic.TopicType let topic2 = NSEntityDescription.insertNewObjectForEntityForName(ReaderTagTopic.classNameWithoutNamespaces(),inManagedObjectContext: context) as! ReaderTagTopic topic2.path = "/tags/topic2" topic2.title = "topic2" topic2.type = ReaderTagTopic.TopicType let topic3 = NSEntityDescription.insertNewObjectForEntityForName(ReaderTagTopic.classNameWithoutNamespaces(),inManagedObjectContext: context) as! ReaderTagTopic topic3.path = "/list/topic3" topic3.title = "topic3" topic3.type = ReaderTagTopic.TopicType do { try context.save(); } catch let error as NSError{ XCTAssertNil(error, "Error seeding topics") } } func countTopics() -> Int { let context = ContextManager.sharedInstance().mainContext let request = NSFetchRequest(entityName: ReaderAbstractTopic.classNameWithoutNamespaces()) var error: NSError? return context.countForFetchRequest(request, error: &error) } func seedPostsForTopic(topic: ReaderAbstractTopic) { let context = ContextManager.sharedInstance().mainContext let post1 = NSEntityDescription.insertNewObjectForEntityForName(ReaderPost.classNameWithoutNamespaces(),inManagedObjectContext: context) as! ReaderPost post1.postID = NSNumber(int:1) post1.postTitle = "post1" post1.content = "post1" post1.topic = topic let post2 = NSEntityDescription.insertNewObjectForEntityForName(ReaderPost.classNameWithoutNamespaces(),inManagedObjectContext: context) as! ReaderPost post2.postID = NSNumber(int:2) post2.postTitle = "post2" post2.content = "post2" post2.topic = topic let post3 = NSEntityDescription.insertNewObjectForEntityForName(ReaderPost.classNameWithoutNamespaces(),inManagedObjectContext: context) as! ReaderPost post3.postID = NSNumber(int:3) post3.postTitle = "post3" post3.content = "post3" post3.topic = topic do { try context.save() } catch let error as NSError { XCTAssertNil(error, "Error seeding posts") } } func remoteTopicsForTests() -> [RemoteReaderTopic] { let foo = RemoteReaderTopic() foo.topicID = 1 foo.title = "foo" foo.path = "/tags/foo" foo.isSubscribed = true foo.isMenuItem = true let bar = RemoteReaderTopic() bar.topicID = 2 bar.title = "bar" bar.path = "/tags/bar" bar.isSubscribed = true bar.isMenuItem = true let baz = RemoteReaderTopic() baz.topicID = 3 baz.title = "baz" baz.path = "/tags/baz" baz.isSubscribed = true baz.isMenuItem = true return [foo, bar, baz] } func remoteAndDefaultTopicForTests() -> [RemoteReaderTopic] { var remoteTopics = remoteTopicsForTests() let def = RemoteReaderTopic() def.topicID = 4 def.title = "def" def.path = "/def" def.isSubscribed = true def.isMenuItem = true remoteTopics.append(def) return remoteTopics } // MARK: Tests /** Ensure that topics a user unsubscribes from are removed from core data when merging results from the REST API. */ func testUnsubscribedTopicIsRemovedDuringSync() { let remoteTopics = remoteTopicsForTests() // Setup var expectation = expectationWithDescription("topics saved expectation") let context = ContextManager.sharedInstance().mainContext let service = ReaderTopicService(managedObjectContext: context); service.mergeMenuTopics(remoteTopics, withSuccess: { () -> Void in expectation.fulfill() }) waitForExpectationsWithTimeout(2.0, handler: nil) // Topics exist in the context let request = NSFetchRequest(entityName: ReaderTagTopic.classNameWithoutNamespaces()) var error:NSError? var count = context.countForFetchRequest(request, error: &error) XCTAssertEqual(count, remoteTopics.count, "Number of topics in context did not match expectations") // Merge new set of topics expectation = expectationWithDescription("topics saved expectation") let foo = remoteTopics.first as RemoteReaderTopic! service.mergeMenuTopics([foo], withSuccess: { () -> Void in expectation.fulfill() }) waitForExpectationsWithTimeout(2.0, handler: nil) // Make sure the missing topics were removed when merged count = context.countForFetchRequest(request, error: &error) XCTAssertEqual(count, 1, "Number of topics in context did not match expectations") do { let results = try context.executeFetchRequest(request) let topic = results.first as! ReaderTagTopic XCTAssertEqual(topic.tagID, foo.topicID, "The topic returned was not the one expected.") } catch let error as NSError { XCTAssertNil(error, "Error executing fetch request.") } } /** Ensure that topics a user subscribes to are added to core data when merging results from the REST API. */ func testNewlySubscribedTopicIsAddedDuringSync() { var remoteTopics = remoteTopicsForTests() let foo = remoteTopics.first let startingTopics:[RemoteReaderTopic] = [remoteTopics[1], remoteTopics[2]] // Setup var expectation = expectationWithDescription("topics saved expectation") let context = ContextManager.sharedInstance().mainContext let service = ReaderTopicService(managedObjectContext: context); service.mergeMenuTopics(startingTopics, withSuccess: { () -> Void in expectation.fulfill() }) waitForExpectationsWithTimeout(2.0, handler: nil) // Topics exist in context let sortDescriptor = NSSortDescriptor(key: "tagID", ascending: true) let request = NSFetchRequest(entityName: ReaderTagTopic.classNameWithoutNamespaces()) request.sortDescriptors = [sortDescriptor] var error:NSError? var count = context.countForFetchRequest(request, error: &error) XCTAssertEqual(count, startingTopics.count, "Number of topics in context did not match expectations") // Merge new set of topics expectation = expectationWithDescription("topics saved expectation") service.mergeMenuTopics(remoteTopics, withSuccess: { () -> Void in expectation.fulfill() }) waitForExpectationsWithTimeout(2.0, handler: nil) // make sure the missing topics were added count = context.countForFetchRequest(request, error: &error) XCTAssertEqual(count, remoteTopics.count, "Number of topics in context did not match expectations") do { let results = try context.executeFetchRequest(request) let topic = results.first as! ReaderTagTopic XCTAssertEqual(topic.tagID, foo!.topicID, "The topic returned was not the one expected.") } catch let error as NSError { XCTAssertNil(error, "Error executing fetch request.") } } /** Ensure that a default topic can be set and retrieved. */ func testGettingSettingCurrentTopic() { let remoteTopics = remoteAndDefaultTopicForTests() // Setup let expectation = expectationWithDescription("topics saved expectation") let context = ContextManager.sharedInstance().mainContext let service = ReaderTopicService(managedObjectContext: context); service.currentTopic = nil // Current topic is not nil after a sync service.mergeMenuTopics(remoteTopics, withSuccess: { () -> Void in expectation.fulfill() }) waitForExpectationsWithTimeout(2.0, handler: nil) XCTAssertNotNil(service.currentTopic, "The current topic was nil.") let sortDescriptor = NSSortDescriptor(key: "title", ascending: true) let request = NSFetchRequest(entityName: ReaderAbstractTopic.classNameWithoutNamespaces()) request.sortDescriptors = [sortDescriptor] let results = try! context.executeFetchRequest(request) var topic = results.last as! ReaderAbstractTopic XCTAssertEqual(service.currentTopic.type, ReaderDefaultTopic.TopicType, "The curent topic should have been a default topic") topic = results.first as! ReaderAbstractTopic service.currentTopic = topic XCTAssertEqual(service.currentTopic.path, topic.path, "The current topic did not match the topic we assiged to it") } /** Ensure all topics are deleted when an account is changed. */ func testDeleteAllTopics() { seedTopics() XCTAssertFalse(countTopics() == 0, "The number of seeded topics should not be zero") let context = ContextManager.sharedInstance().mainContext let service = ReaderTopicService(managedObjectContext: context); service.deleteAllTopics() XCTAssertTrue(countTopics() == 0, "The number of seeded topics should be zero") } /** Ensure all the posts belonging to a topic are deleted when the topic is deleted. */ func testPostsDeletedWhenTopicDeleted() { // setup var context = ContextManager.sharedInstance().mainContext let topic = NSEntityDescription.insertNewObjectForEntityForName(ReaderListTopic.classNameWithoutNamespaces(),inManagedObjectContext: context) as! ReaderListTopic topic.path = "/list/topic" topic.title = "topic" topic.type = ReaderListTopic.TopicType seedPostsForTopic(topic) XCTAssertTrue(topic.posts.count == 3, "Topic should have posts relationship with three posts.") // Save the new topic + posts in the contet var expectation = expectationWithDescription("topics saved expectation") ContextManager.sharedInstance().saveContext(context, withCompletionBlock: { () -> Void in expectation.fulfill() }) waitForExpectationsWithTimeout(2.0, handler: nil) // Delete the topic and posts from the context context.deleteObject(topic) expectation = expectationWithDescription("topics saved expectation") context = ContextManager.sharedInstance().mainContext ContextManager.sharedInstance().saveContext(context, withCompletionBlock: { () -> Void in expectation.fulfill() }) waitForExpectationsWithTimeout(2.0, handler: nil) var request = NSFetchRequest(entityName: ReaderAbstractTopic.classNameWithoutNamespaces()) var error:NSError? var count = context.countForFetchRequest(request, error: &error) XCTAssertTrue(count == 0, "Topic was not deleted successfully") request = NSFetchRequest(entityName: ReaderPost.classNameWithoutNamespaces()) count = context.countForFetchRequest(request, error: &error) XCTAssertTrue(count == 0, "Topic posts were not deleted successfully") } func testTopicTitleFormatting() { let context = ContextManager.sharedInstance().mainContext let service = ReaderTopicService(managedObjectContext: context); var unformatted = "WordPress" var formatted = service.formatTitle(unformatted) XCTAssertTrue(formatted == unformatted, "WordPress should have maintained its case") // Lowercase should be capitalized unformatted = "art & entertainment" formatted = service.formatTitle(unformatted) XCTAssertTrue(formatted == "Art & Entertainment", "Lower cased words should be capitalized") // Special consideration for the casing of "techy" words like iPhone and ePaper. unformatted = "iPhone" formatted = service.formatTitle(unformatted) XCTAssertTrue(formatted == unformatted, "iPhone should have maintained its case") unformatted = "ePaper" formatted = service.formatTitle(unformatted) XCTAssertTrue(formatted == unformatted, "ePaper should have maintained its case") // All caps stays all caps. unformatted = "VINE"; formatted = service.formatTitle(unformatted) XCTAssertTrue(formatted == unformatted, "VINE should have remained all caps") } }
gpl-2.0
6d1277bfd88c0ed8c309debe9933e0bd
38.391045
170
0.676341
5.269968
false
true
false
false
Holmusk/HMRequestFramework-iOS
HMRequestFramework-FullDemo/model/User.swift
1
6406
// // User.swift // HMRequestFramework-FullDemo // // Created by Hai Pham on 17/1/18. // Copyright © 2018 Holmusk. All rights reserved. // import CoreData import HMRequestFramework /// In a parallel object model, a single entity comprises 3 objects: /// /// - The managed object (which we prefix with CD). /// - The pure object. /// - The pure object builder (which is necessary for immutability). /// /// I'd say the most tedious step of adopting this framework is the translation /// of object models into this one. Usage of the framework is straightforward /// after that. public protocol UserType { var id: String? { get } var name: String? { get } var age: NSNumber? { get } var visible: NSNumber? { get } var updatedAt: Date? { get } } public extension UserType { public func primaryKey() -> String { return "id" } public func primaryValue() -> String? { return id } public func stringRepresentationForResult() -> String { return id.getOrElse("") } } public final class CDUser: NSManagedObject { @NSManaged public var id: String? @NSManaged public var name: String? @NSManaged public var age: NSNumber? @NSManaged public var visible: NSNumber? @NSManaged public var updatedAt: Date? } public struct User { public static let updatedAtKey = "updatedAt" fileprivate var _id: String? fileprivate var _name: String? fileprivate var _age: NSNumber? fileprivate var _visible: NSNumber? fileprivate var _updatedAt: Date? public var id: String? { return _id } public var name: String? { return _name } public var age: NSNumber? { return _age } public var visible: NSNumber? { return _visible } public var updatedAt: Date? { return _updatedAt } fileprivate init() { _updatedAt = Date() } } ///////////////////////////////// EXTENSIONS ///////////////////////////////// extension CDUser: UserType {} //extension CDUser: HMCDObjectMasterType { /// Version control to enable optimistic locking. extension CDUser: HMCDVersionableMasterType { public typealias PureObject = User public static func cdAttributes() throws -> [NSAttributeDescription]? { return [ NSAttributeDescription.builder() .with(name: "id") .with(type: .stringAttributeType) .with(optional: false) .build(), NSAttributeDescription.builder() .with(name: "name") .with(type: .stringAttributeType) .with(optional: false) .build(), NSAttributeDescription.builder() .with(name: "age") .with(type: .integer64AttributeType) .with(optional: false) .build(), NSAttributeDescription.builder() .with(name: "visible") .with(type: .booleanAttributeType) .with(optional: false) .build(), NSAttributeDescription.builder() .with(name: "updatedAt") .with(type: .dateAttributeType) .with(optional: false) .build(), ] } /// This is where we update the current managed object to mutate it in /// the internal disposable context. public func mutateWithPureObject(_ object: PureObject) { id = object.id name = object.name age = object.age visible = object.visible updatedAt = object.updatedAt } fileprivate func versionDateFormat() -> String { return "yyyy/MM/dd hh:mm:ss a" } fileprivate func formatDateForVersioning(_ date: Date) -> String { let formatter = DateFormatter() formatter.dateFormat = versionDateFormat() return formatter.string(from: date) } fileprivate func convertVersionToDate(_ string: String) -> Date? { let formatter = DateFormatter() formatter.dateFormat = versionDateFormat() return formatter.date(from: string) } /// Implement the version update with updateAt date flag. public func currentVersion() -> String? { return updatedAt.map({formatDateForVersioning($0)}) } public func oneVersionHigher() -> String? { return formatDateForVersioning(Date()) } public func hasPreferableVersion(over obj: HMVersionableType) throws -> Bool { let date = obj.currentVersion().flatMap({convertVersionToDate($0)}) return updatedAt.zipWith(date, {$0 >= $1}).getOrElse(false) } public func mergeWithOriginalVersion(_ obj: HMVersionableType) throws { name = "MergedDueToVersionConflict" age = 999 } public func updateVersion(_ version: String?) throws { updatedAt = version.flatMap({convertVersionToDate($0)}) } } extension User: UserType {} extension User: HMCDPureObjectMasterType { public typealias CDClass = CDUser public static func builder() -> Builder { return Builder() } public final class Builder: HMCDPureObjectBuilderMasterType { public typealias Buildable = User fileprivate var user: Buildable public init() { user = User() } public func with(id: String?) -> Self { user._id = id return self } public func with(name: String?) -> Self { user._name = name return self } public func with(age: NSNumber?) -> Self { user._age = age return self } public func with(visible: NSNumber?) -> Self { user._visible = visible return self } /// Do not allow external modifications since this is also used for /// version control. fileprivate func with(updatedAt date: Date?) -> Self { user._updatedAt = date return self } public func with(user: UserType?) -> Self { return user.map({self .with(id: $0.id) .with(name: $0.name) .with(age: $0.age) .with(visible: $0.visible) .with(updatedAt: $0.updatedAt) }).getOrElse(self) } public func with(buildable: Buildable?) -> Self { return with(user: buildable) } public func with(cdObject: Buildable.CDClass) -> Self { return with(user: cdObject) } public func build() -> Buildable { return user } } } extension User: CustomStringConvertible { public var description: String { return id.getOrElse("No id present") } } extension User: Equatable { public static func ==(lhs: User, rhs: User) -> Bool { return true && lhs.id == rhs.id && lhs.name == rhs.name && lhs.age == rhs.age && lhs.visible == rhs.visible && lhs.updatedAt == rhs.updatedAt } }
apache-2.0
189404e60a86be2a7443f06b60bf6513
23.353612
80
0.642779
4.211045
false
false
false
false
zhaobin19918183/zhaobinCode
swift_NavigationController/swift_iPad/NetWorkManager/NetWorkManager.swift
1
6059
// // NetWorkManager.swift // EveryOne // // Created by Zhao.bin on 16/1/22. // Copyright © 2016年 Zhao.bin. All rights reserved. // import UIKit import Foundation import Alamofire extension String { var newdata: NSData { return self.dataUsingEncoding(NSUTF8StringEncoding)! } } /* Swift 2.0 Network request packaging*/ class NetWorkRequest { static func request(method: String, url: String, params: Dictionary<String, AnyObject> = Dictionary<String, AnyObject>(), callback: (data: NSString!, response: NSURLResponse!, error: NSError!) -> Void){ let manager = NetWorkSwiftManager(url: url, method: method,params:params,callback: callback) manager.fire() } /*get request,With no Arguments*/ static func get(url: String, callback: (data: NSString!, response: NSURLResponse!, error: NSError!) -> Void) { let manager = NetWorkSwiftManager(url: url, method: "GET", callback: callback) manager.fire() } /*get request,With Arguments*/ static func get(url: String, params: Dictionary<String, AnyObject>, callback: (data: NSString!, response: NSURLResponse!, error: NSError!) -> Void) { let manager = NetWorkSwiftManager(url: url, method: "GET", params: params, callback: callback) manager.fire() } /*POST request,With no Arguments*/ static func post(url: String, callback: (data: NSString!, response: NSURLResponse!, error: NSError!) -> Void) { let manager = NetWorkSwiftManager(url: url, method: "POST", callback: callback) manager.fire() } /*POST request,With Arguments*/ static func post(url: String, params: Dictionary<String, AnyObject>, callback: (data: NSString!, response: NSURLResponse!, error: NSError!) -> Void) { let manager = NetWorkSwiftManager(url: url, method: "POST", params: params, callback: callback) manager.fire() } /*PUT request,With no Arguments*/ static func put(url: String, callback: (data: NSString!, response: NSURLResponse!, error: NSError!) -> Void) { let manager = NetWorkSwiftManager(url: url, method: "PUT", callback: callback) manager.fire() } /*PUT request,With Arguments*/ static func put(url: String, params: Dictionary<String, AnyObject>, callback: (data: NSString!, response: NSURLResponse!, error: NSError!) -> Void) { let manager = NetWorkSwiftManager(url: url, method: "PUT", params: params, callback: callback) manager.fire() } /*DELETE request,With Arguments*/ static func delete(url: String, params: Dictionary<String, AnyObject>, callback: (data: NSString!, response: NSURLResponse!, error: NSError!) -> Void) { let manager = NetWorkSwiftManager(url: url, method: "DELETE", params: params, callback: callback) manager.fire() } } /*ententions*/ class NetWorkSwiftManager { let method: String! let params: Dictionary<String, AnyObject> let callback: (data: NSString!, response: NSURLResponse!, error: NSError!) -> Void var session = NSURLSession.sharedSession() let url: String! var request: NSMutableURLRequest! var task: NSURLSessionTask! /*带参数 构造器*/ init(url: String, method: String, params: Dictionary<String, AnyObject> = Dictionary<String, AnyObject>(), callback: (data: NSString!, response: NSURLResponse!, error: NSError!) -> Void) { self.url = url self.request = NSMutableURLRequest(URL: NSURL(string: url)!) self.method = method self.params = params self.callback = callback } func buildRequest() { if self.method == "GET" && self.params.count > 0 { self.request = NSMutableURLRequest(URL: NSURL(string: url + "?" + buildParams(self.params))!) } request.HTTPMethod = self.method if self.params.count > 0 { request.addValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type") } } func buildBody() { if self.params.count > 0 && self.method != "GET" { request.HTTPBody = buildParams(self.params).newdata } } func fireTask() { task = session.dataTaskWithRequest(request,completionHandler: { (data, response, error) -> Void in self.callback(data: NSString(data:data!, encoding: NSUTF8StringEncoding), response: response, error: error) }) task.resume() } //借用 Alamofire 函数 func buildParams(parameters: [String: AnyObject]) -> String { var components: [(String, String)] = [] for key in parameters.keys.sort() { let value: AnyObject! = parameters[key] //拼接url components += self.queryComponents(key, value) } return (components.map { "\($0)=\($1)" } as [String]).joinWithSeparator("&") } func queryComponents(key: String, _ value: AnyObject) -> [(String, String)] { var components: [(String, String)] = [] if let dictionary = value as? [String: AnyObject] { for (nestedKey, value) in dictionary { components += queryComponents("\(key)[\(nestedKey)]", value) } } else if let array = value as? [AnyObject] { for value in array { components += queryComponents("\(key)", value) } } else { components.appendContentsOf([(escape(key), escape("\(value)"))]) } return components } func escape(string: String) -> String { let legalURLCharactersToBeEscaped: CFStringRef = ":&=;+!@#$()',*" return string.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.init(contentsOfFile: legalURLCharactersToBeEscaped as String)!)! } func fire() { buildRequest() buildBody() fireTask() } }
gpl-3.0
d73431b35fd64cf89e2659cb89aca14b
33.791908
206
0.614158
4.548753
false
false
false
false
raphaelmor/GeoJSON
GeoJSON/Geometry/GeometryCollection.swift
1
3916
// GeometryCollection.swift // // The MIT License (MIT) // // Copyright (c) 2014 Raphaël Mor // // 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 final class GeometryCollection : GeoJSONEncodable { /// Public geometries public var geometries: [GeoJSON] { return _geometries } /// Prefix used for GeoJSON Encoding public var prefix: String { return "geometries" } /// Private var to store geometries private var _geometries: [GeoJSON] = [] /** Designated initializer for creating a GeometryCollection from a SwiftyJSON object :param: json The SwiftyJSON Object. :returns: The created GeometryCollection object. */ public init?(json: JSON) { if let jsonGeometries = json.array { _geometries = jsonGeometries.map { jsonObject in return GeoJSON(json: jsonObject) } ?? [] let validGeometries = _geometries.filter { geoJSON in return geoJSON.type != .Unknown } if validGeometries.count != _geometries.count { return nil } } else { return nil } } /** Designated initializer for creating a GeometryCollection from [GeoJSON] :param: lineStrings The LineString array. :returns: The created MultiLineString object. */ public init?(geometries: [GeoJSON]) { _geometries = geometries } /** Build a object that can be serialized to JSON :returns: Representation of the GeometryCollection Object */ public func json() -> AnyObject { return _geometries.map { $0.json() } } } /// Array forwarding methods public extension GeometryCollection { /// number of GeoJSON objects public var count: Int { return geometries.count } /// subscript to access the Nth GeoJSON public subscript(index: Int) -> GeoJSON { get { return geometries[index] } set(newValue) { _geometries[index] = newValue } } } /// GeometryCollection related methods on GeoJSON public extension GeoJSON { /// Optional GeometryCollection public var geometryCollection: GeometryCollection? { get { switch type { case .GeometryCollection: return object as? GeometryCollection default: return nil } } set { _object = newValue ?? NSNull() } } /** Convenience initializer for creating a GeoJSON Object from a GeometryCollection :param: geometryCollection The GeometryCollection object. :returns: The created GeoJSON object. */ convenience public init(geometryCollection: GeometryCollection) { self.init() object = geometryCollection } }
mit
97c8fd041ef04aa3f567577c48637453
30.837398
85
0.648276
5.117647
false
false
false
false
mikemee/SQLite.swift2
SQLite/Core/Connection.swift
1
24426
// // SQLite.swift // https://github.com/stephencelis/SQLite.swift // Copyright © 2014-2015 Stephen Celis. // // 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 Dispatch import SQLite3 /// A connection to SQLite. public final class Connection { /// The location of a SQLite database. public enum Location { /// An in-memory database (equivalent to `.URI(":memory:")`). /// /// See: <https://www.sqlite.org/inmemorydb.html#sharedmemdb> case InMemory /// A temporary, file-backed database (equivalent to `.URI("")`). /// /// See: <https://www.sqlite.org/inmemorydb.html#temp_db> case Temporary /// A database located at the given URI filename (or path). /// /// See: <https://www.sqlite.org/uri.html> /// /// - Parameter filename: A URI filename case URI(String) } public var handle: COpaquePointer { return _handle } private var _handle: COpaquePointer = nil /// Initializes a new SQLite connection. /// /// - Parameters: /// /// - location: The location of the database. Creates a new database if it /// doesn’t already exist (unless in read-only mode). /// /// Default: `.InMemory`. /// /// - readonly: Whether or not to open the database in a read-only state. /// /// Default: `false`. /// /// - Returns: A new database connection. public init(_ location: Location = .InMemory, readonly: Bool = false) throws { let flags = readonly ? SQLITE_OPEN_READONLY : SQLITE_OPEN_CREATE | SQLITE_OPEN_READWRITE try check(sqlite3_open_v2(location.description, &_handle, flags | SQLITE_OPEN_FULLMUTEX, nil)) dispatch_queue_set_specific(queue, Connection.queueKey, queueContext, nil) } /// Initializes a new connection to a database. /// /// - Parameters: /// /// - filename: The location of the database. Creates a new database if /// it doesn’t already exist (unless in read-only mode). /// /// - readonly: Whether or not to open the database in a read-only state. /// /// Default: `false`. /// /// - Throws: `Result.Error` iff a connection cannot be established. /// /// - Returns: A new database connection. public convenience init(_ filename: String, readonly: Bool = false) throws { try self.init(.URI(filename), readonly: readonly) } deinit { sqlite3_close(handle) } // MARK: - /// Whether or not the database was opened in a read-only state. public var readonly: Bool { return sqlite3_db_readonly(handle, nil) == 1 } /// The last rowid inserted into the database via this connection. public var lastInsertRowid: Int64? { let rowid = sqlite3_last_insert_rowid(handle) return rowid > 0 ? rowid : nil } /// The last number of changes (inserts, updates, or deletes) made to the /// database via this connection. public var changes: Int { return Int(sqlite3_changes(handle)) } /// The total number of changes (inserts, updates, or deletes) made to the /// database via this connection. public var totalChanges: Int { return Int(sqlite3_total_changes(handle)) } // MARK: - Execute /// Executes a batch of SQL statements. /// /// - Parameter SQL: A batch of zero or more semicolon-separated SQL /// statements. /// /// - Throws: `Result.Error` if query execution fails. public func execute(SQL: String) throws { try sync { try self.check(sqlite3_exec(self.handle, SQL, nil, nil, nil)) } } // MARK: - Prepare /// Prepares a single SQL statement (with optional parameter bindings). /// /// - Parameters: /// /// - statement: A single SQL statement. /// /// - bindings: A list of parameters to bind to the statement. /// /// - Returns: A prepared statement. @warn_unused_result public func prepare(statement: String, _ bindings: Binding?...) throws -> Statement { if !bindings.isEmpty { return try prepare(statement, bindings) } return try Statement(self, statement) } /// Prepares a single SQL statement and binds parameters to it. /// /// - Parameters: /// /// - statement: A single SQL statement. /// /// - bindings: A list of parameters to bind to the statement. /// /// - Returns: A prepared statement. @warn_unused_result public func prepare(statement: String, _ bindings: [Binding?]) throws -> Statement { return try prepare(statement).bind(bindings) } /// Prepares a single SQL statement and binds parameters to it. /// /// - Parameters: /// /// - statement: A single SQL statement. /// /// - bindings: A dictionary of named parameters to bind to the statement. /// /// - Returns: A prepared statement. @warn_unused_result public func prepare(statement: String, _ bindings: [String: Binding?]) throws -> Statement { return try prepare(statement).bind(bindings) } // MARK: - Run /// Runs a single SQL statement (with optional parameter bindings). /// /// - Parameters: /// /// - statement: A single SQL statement. /// /// - bindings: A list of parameters to bind to the statement. /// /// - Throws: `Result.Error` if query execution fails. /// /// - Returns: The statement. public func run(statement: String, _ bindings: Binding?...) throws -> Statement { return try run(statement, bindings) } /// Prepares, binds, and runs a single SQL statement. /// /// - Parameters: /// /// - statement: A single SQL statement. /// /// - bindings: A list of parameters to bind to the statement. /// /// - Throws: `Result.Error` if query execution fails. /// /// - Returns: The statement. public func run(statement: String, _ bindings: [Binding?]) throws -> Statement { return try prepare(statement).run(bindings) } /// Prepares, binds, and runs a single SQL statement. /// /// - Parameters: /// /// - statement: A single SQL statement. /// /// - bindings: A dictionary of named parameters to bind to the statement. /// /// - Throws: `Result.Error` if query execution fails. /// /// - Returns: The statement. public func run(statement: String, _ bindings: [String: Binding?]) throws -> Statement { return try prepare(statement).run(bindings) } // MARK: - Scalar /// Runs a single SQL statement (with optional parameter bindings), /// returning the first value of the first row. /// /// - Parameters: /// /// - statement: A single SQL statement. /// /// - bindings: A list of parameters to bind to the statement. /// /// - Returns: The first value of the first row returned. @warn_unused_result public func scalar(statement: String, _ bindings: Binding?...) -> Binding? { return scalar(statement, bindings) } /// Runs a single SQL statement (with optional parameter bindings), /// returning the first value of the first row. /// /// - Parameters: /// /// - statement: A single SQL statement. /// /// - bindings: A list of parameters to bind to the statement. /// /// - Returns: The first value of the first row returned. @warn_unused_result public func scalar(statement: String, _ bindings: [Binding?]) -> Binding? { return try! prepare(statement).scalar(bindings) } /// Runs a single SQL statement (with optional parameter bindings), /// returning the first value of the first row. /// /// - Parameters: /// /// - statement: A single SQL statement. /// /// - bindings: A dictionary of named parameters to bind to the statement. /// /// - Returns: The first value of the first row returned. @warn_unused_result public func scalar(statement: String, _ bindings: [String: Binding?]) -> Binding? { return try! prepare(statement).scalar(bindings) } // MARK: - Transactions /// The mode in which a transaction acquires a lock. public enum TransactionMode : String { /// Defers locking the database till the first read/write executes. case Deferred = "DEFERRED" /// Immediately acquires a reserved lock on the database. case Immediate = "IMMEDIATE" /// Immediately acquires an exclusive lock on all databases. case Exclusive = "EXCLUSIVE" } // TODO: Consider not requiring a throw to roll back? /// Runs a transaction with the given mode. /// /// - Note: Transactions cannot be nested. To nest transactions, see /// `savepoint()`, instead. /// /// - Parameters: /// /// - mode: The mode in which a transaction acquires a lock. /// /// Default: `.Deferred` /// /// - block: A closure to run SQL statements within the transaction. /// The transaction will be committed when the block returns. The block /// must throw to roll the transaction back. /// /// - Throws: `Result.Error`, and rethrows. public func transaction(mode: TransactionMode = .Deferred, block: () throws -> Void) throws { try transaction("BEGIN \(mode.rawValue) TRANSACTION", block, "COMMIT TRANSACTION", or: "ROLLBACK TRANSACTION") } // TODO: Consider not requiring a throw to roll back? // TODO: Consider removing ability to set a name? /// Runs a transaction with the given savepoint name (if omitted, it will /// generate a UUID). /// /// - SeeAlso: `transaction()`. /// /// - Parameters: /// /// - savepointName: A unique identifier for the savepoint (optional). /// /// - block: A closure to run SQL statements within the transaction. /// The savepoint will be released (committed) when the block returns. /// The block must throw to roll the savepoint back. /// /// - Throws: `SQLite.Result.Error`, and rethrows. public func savepoint(name: String = NSUUID().UUIDString, block: () throws -> Void) throws { let name = name.quote("'") let savepoint = "SAVEPOINT \(name)" try transaction(savepoint, block, "RELEASE \(savepoint)", or: "ROLLBACK TO \(savepoint)") } private func transaction(begin: String, _ block: () throws -> Void, _ commit: String, or rollback: String) throws { return try sync { try self.run(begin) do { try block() } catch { try self.run(rollback) throw error } try self.run(commit) } } /// Interrupts any long-running queries. public func interrupt() { sqlite3_interrupt(handle) } // MARK: - Handlers /// The number of seconds a connection will attempt to retry a statement /// after encountering a busy signal (lock). public var busyTimeout: Double = 0 { didSet { sqlite3_busy_timeout(handle, Int32(busyTimeout * 1_000)) } } /// Sets a handler to call after encountering a busy signal (lock). /// /// - Parameter callback: This block is executed during a lock in which a /// busy error would otherwise be returned. It’s passed the number of /// times it’s been called for this lock. If it returns `true`, it will /// try again. If it returns `false`, no further attempts will be made. public func busyHandler(callback: ((tries: Int) -> Bool)?) { guard let callback = callback else { sqlite3_busy_handler(handle, nil, nil) busyHandler = nil return } let box: BusyHandler = { callback(tries: Int($0)) ? 1 : 0 } sqlite3_busy_handler(handle, { callback, tries in unsafeBitCast(callback, BusyHandler.self)(tries) }, unsafeBitCast(box, UnsafeMutablePointer<Void>.self)) busyHandler = box } private typealias BusyHandler = @convention(block) Int32 -> Int32 private var busyHandler: BusyHandler? /// Sets a handler to call when a statement is executed with the compiled /// SQL. /// /// - Parameter callback: This block is invoked when a statement is executed /// with the compiled SQL as its argument. /// /// db.trace { SQL in print(SQL) } public func trace(callback: (String -> Void)?) { guard let callback = callback else { sqlite3_trace(handle, nil, nil) trace = nil return } let box: Trace = { callback(String.fromCString($0)!) } sqlite3_trace(handle, { callback, SQL in unsafeBitCast(callback, Trace.self)(SQL) }, unsafeBitCast(box, UnsafeMutablePointer<Void>.self)) trace = box } private typealias Trace = @convention(block) UnsafePointer<Int8> -> Void private var trace: Trace? /// Registers a callback to be invoked whenever a row is inserted, updated, /// or deleted in a rowid table. /// /// - Parameter callback: A callback invoked with the `Operation` (one of /// `.Insert`, `.Update`, or `.Delete`), database name, table name, and /// rowid. public func updateHook(callback: ((operation: Operation, db: String, table: String, rowid: Int64) -> Void)?) { guard let callback = callback else { sqlite3_update_hook(handle, nil, nil) updateHook = nil return } let box: UpdateHook = { callback( operation: Operation(rawValue: $0), db: String.fromCString($1)!, table: String.fromCString($2)!, rowid: $3 ) } sqlite3_update_hook(handle, { callback, operation, db, table, rowid in unsafeBitCast(callback, UpdateHook.self)(operation, db, table, rowid) }, unsafeBitCast(box, UnsafeMutablePointer<Void>.self)) updateHook = box } private typealias UpdateHook = @convention(block) (Int32, UnsafePointer<Int8>, UnsafePointer<Int8>, Int64) -> Void private var updateHook: UpdateHook? /// Registers a callback to be invoked whenever a transaction is committed. /// /// - Parameter callback: A callback invoked whenever a transaction is /// committed. If this callback throws, the transaction will be rolled /// back. public func commitHook(callback: (() throws -> Void)?) { guard let callback = callback else { sqlite3_commit_hook(handle, nil, nil) commitHook = nil return } let box: CommitHook = { do { try callback() } catch { return 1 } return 0 } sqlite3_commit_hook(handle, { callback in unsafeBitCast(callback, CommitHook.self)() }, unsafeBitCast(box, UnsafeMutablePointer<Void>.self)) commitHook = box } private typealias CommitHook = @convention(block) () -> Int32 private var commitHook: CommitHook? /// Registers a callback to be invoked whenever a transaction rolls back. /// /// - Parameter callback: A callback invoked when a transaction is rolled /// back. public func rollbackHook(callback: (() -> Void)?) { guard let callback = callback else { sqlite3_rollback_hook(handle, nil, nil) rollbackHook = nil return } let box: RollbackHook = { callback() } sqlite3_rollback_hook(handle, { callback in unsafeBitCast(callback, RollbackHook.self)() }, unsafeBitCast(box, UnsafeMutablePointer<Void>.self)) rollbackHook = box } private typealias RollbackHook = @convention(block) () -> Void private var rollbackHook: RollbackHook? /// Creates or redefines a custom SQL function. /// /// - Parameters: /// /// - function: The name of the function to create or redefine. /// /// - argumentCount: The number of arguments that the function takes. If /// `nil`, the function may take any number of arguments. /// /// Default: `nil` /// /// - deterministic: Whether or not the function is deterministic (_i.e._ /// the function always returns the same result for a given input). /// /// Default: `false` /// /// - block: A block of code to run when the function is called. The block /// is called with an array of raw SQL values mapped to the function’s /// parameters and should return a raw SQL value (or nil). public func createFunction(function: String, argumentCount: UInt? = nil, deterministic: Bool = false, _ block: (args: [Binding?]) -> Binding?) { let argc = argumentCount.map { Int($0) } ?? -1 let box: Function = { context, argc, argv in let arguments: [Binding?] = (0..<Int(argc)).map { idx in let value = argv[idx] switch sqlite3_value_type(value) { case SQLITE_BLOB: return Blob(bytes: sqlite3_value_blob(value), length: Int(sqlite3_value_bytes(value))) case SQLITE_FLOAT: return sqlite3_value_double(value) case SQLITE_INTEGER: return sqlite3_value_int64(value) case SQLITE_NULL: return nil case SQLITE_TEXT: return String.fromCString(UnsafePointer(sqlite3_value_text(value)))! case let type: fatalError("unsupported value type: \(type)") } } let result = block(args: arguments) if let result = result as? Blob { sqlite3_result_blob(context, result.bytes, Int32(result.bytes.count), nil) } else if let result = result as? Double { sqlite3_result_double(context, result) } else if let result = result as? Int64 { sqlite3_result_int64(context, result) } else if let result = result as? String { sqlite3_result_text(context, result, Int32(result.characters.count), SQLITE_TRANSIENT) } else if result == nil { sqlite3_result_null(context) } else { fatalError("unsupported result type: \(result)") } } var flags = SQLITE_UTF8 if deterministic { flags |= SQLITE_DETERMINISTIC } sqlite3_create_function_v2(handle, function, Int32(argc), flags, unsafeBitCast(box, UnsafeMutablePointer<Void>.self), { context, argc, value in unsafeBitCast(sqlite3_user_data(context), Function.self)(context, argc, value) }, nil, nil, nil) if functions[function] == nil { self.functions[function] = [:] } functions[function]?[argc] = box } private typealias Function = @convention(block) (COpaquePointer, Int32, UnsafeMutablePointer<COpaquePointer>) -> Void private var functions = [String: [Int: Function]]() /// The return type of a collation comparison function. public typealias ComparisonResult = NSComparisonResult /// Defines a new collating sequence. /// /// - Parameters: /// /// - collation: The name of the collation added. /// /// - block: A collation function that takes two strings and returns the /// comparison result. public func createCollation(collation: String, _ block: (lhs: String, rhs: String) -> ComparisonResult) { let box: Collation = { lhs, rhs in Int32(block(lhs: String.fromCString(UnsafePointer<Int8>(lhs))!, rhs: String.fromCString(UnsafePointer<Int8>(rhs))!).rawValue) } try! check(sqlite3_create_collation_v2(handle, collation, SQLITE_UTF8, unsafeBitCast(box, UnsafeMutablePointer<Void>.self), { callback, _, lhs, _, rhs in unsafeBitCast(callback, Collation.self)(lhs, rhs) }, nil)) collations[collation] = box } private typealias Collation = @convention(block) (UnsafePointer<Void>, UnsafePointer<Void>) -> Int32 private var collations = [String: Collation]() // MARK: - Error Handling func sync<T>(block: () throws -> T) rethrows -> T { var success: T? var failure: ErrorType? let box: () -> Void = { do { success = try block() } catch { failure = error } } if dispatch_get_specific(Connection.queueKey) == queueContext { box() } else { dispatch_sync(queue, box) // FIXME: rdar://problem/21389236 } if let failure = failure { try { () -> Void in throw failure }() } return success! } func check(resultCode: Int32, statement: Statement? = nil) throws -> Int32 { guard let error = Result(errorCode: resultCode, connection: self, statement: statement) else { return resultCode } throw error } private var queue = dispatch_queue_create("SQLite.Database", DISPATCH_QUEUE_SERIAL) private static let queueKey = unsafeBitCast(Connection.self, UnsafePointer<Void>.self) private lazy var queueContext: UnsafeMutablePointer<Void> = unsafeBitCast(self, UnsafeMutablePointer<Void>.self) } extension Connection : CustomStringConvertible { public var description: String { return String.fromCString(sqlite3_db_filename(handle, nil))! } } extension Connection.Location : CustomStringConvertible { public var description: String { switch self { case .InMemory: return ":memory:" case .Temporary: return "" case .URI(let URI): return URI } } } /// An SQL operation passed to update callbacks. public enum Operation { /// An INSERT operation. case Insert /// An UPDATE operation. case Update /// A DELETE operation. case Delete private init(rawValue: Int32) { switch rawValue { case SQLITE_INSERT: self = .Insert case SQLITE_UPDATE: self = .Update case SQLITE_DELETE: self = .Delete default: fatalError("unhandled operation code: \(rawValue)") } } } public enum Result : ErrorType { private static let successCodes: Set = [SQLITE_OK, SQLITE_ROW, SQLITE_DONE] case Error(message: String, code: Int32, statement: Statement?) init?(errorCode: Int32, connection: Connection, statement: Statement? = nil) { guard !Result.successCodes.contains(errorCode) else { return nil } let message = String.fromCString(sqlite3_errmsg(connection.handle))! self = Error(message: message, code: errorCode, statement: statement) } } extension Result : CustomStringConvertible { public var description: String { switch self { case let .Error(message, _, statement): guard let statement = statement else { return message } return "\(message) (\(statement))" } } }
mit
09cb6bbf67c561cc0bdd6f5fad732a0f
34.642336
161
0.605734
4.502951
false
false
false
false
Egibide-DAM/swift
02_ejemplos/06_tipos_personalizados/06_herencia/04_jerarquia_herencia.playground/Contents.swift
1
564
class Vehicle { var currentSpeed = 0.0 var description: String { return "traveling at \(currentSpeed) miles per hour" } func makeNoise() { // do nothing - an arbitrary vehicle doesn't necessarily make a noise } } class Bicycle: Vehicle { var hasBasket = false } class Tandem: Bicycle { var currentNumberOfPassengers = 0 } let tandem = Tandem() tandem.hasBasket = true tandem.currentNumberOfPassengers = 2 tandem.currentSpeed = 22.0 print("Tandem: \(tandem.description)") // Tandem: traveling at 22.0 miles per hour
apache-2.0
7416821d442c96e27f4cba9ddde2df4b
20.692308
77
0.68617
3.735099
false
false
false
false
DeskConnect/SDCAlertView
Example.playground/Contents.swift
1
497
import XCPlayground import SDCAlertView let viewController = UIViewController() viewController.view.backgroundColor = UIColor.whiteColor() XCPlaygroundPage.currentPage.liveView = viewController XCPlaygroundPage.currentPage.needsIndefiniteExecution = true /*** Create, customize, and present your alert below ***/ let alert = AlertController(title: "Title", message: "Hey user, you're being alerted about something") alert.addAction(AlertAction(title: "OK", style: .Preferred)) alert.present()
mit
93dfaadecc35fe76d60e74bedb472b55
34.5
102
0.800805
4.778846
false
false
false
false
Fenrikur/ef-app_ios
Domain Model/EurofurenceModelTests/Test Doubles/Observers/CapturingAuthenticationStateObserver.swift
1
447
import EurofurenceModel import Foundation class CapturingAuthenticationStateObserver: AuthenticationStateObserver { private(set) var capturedLoggedInUser: User? func userDidLogin(_ user: User) { capturedLoggedInUser = user } var loggedOut = false func userDidLogout() { loggedOut = true } private(set) var logoutDidFail = false func userDidFailToLogout() { logoutDidFail = true } }
mit
4031564cb45eafab8744bf841fe49320
20.285714
73
0.691275
4.858696
false
false
false
false
Baglan/MCButtoneer
MCButtoneer/RoundRectView.swift
1
1081
// // RoundRectView.swift // Coffee // // Created by Baglan on 11/8/15. // // import Foundation import UIKit @IBDesignable class RoundRectView: UIView { @IBInspectable var strokeWidth: CGFloat = 1 { didSet { setNeedsDisplay() } } @IBInspectable var strokeColor: UIColor? { didSet { setNeedsDisplay() } } @IBInspectable var isFilled: Bool = false { didSet { setNeedsDisplay() } } @IBInspectable var fillColor: UIColor? { didSet { setNeedsDisplay() } } override func draw(_ rect: CGRect) { super.draw(rect) let boundsRect = CGRect(x: strokeWidth / 2, y: strokeWidth / 2, width: bounds.width - strokeWidth, height: bounds.height - strokeWidth) let path = UIBezierPath(roundedRect: boundsRect, cornerRadius: boundsRect.height) path.lineWidth = strokeWidth if isFilled, let fillColor = fillColor { fillColor.setFill() path.fill() } if let color = strokeColor { color.setStroke() path.stroke() } } }
mit
df83d19c191296edfc78195920e39690
28.216216
143
0.609621
4.679654
false
false
false
false
artFintch/Algorithms_and_Data_Structures
DataStructures/Queue/Queue.swift
1
1326
// // Queue.swift // Queue // // Created by Vyacheslav Khorkov on 31/07/2017. // Copyright © 2017 Vyacheslav Khorkov. All rights reserved. // import Foundation public struct Queue<T> { public var first: T? { return isEmpty ? nil : array[head] } public var count: Int { return array.count - head } public var isEmpty: Bool { return count == 0 } init(maxEmptySpacesPercent: Float = Const.maxEmptySpacesPercent, minCountForOptimise: Int = Const.minCountForOptimise) { self.maxEmptySpacesPercent = maxEmptySpacesPercent self.minCountForOptimise = minCountForOptimise } public mutating func enque(_ newElement: T?) { array.append(newElement) } public mutating func deque() -> T? { guard let first = first else { return nil } array[head] = nil head += 1 if array.count >= minCountForOptimise && Float(head) / Float(array.count) > maxEmptySpacesPercent { array.removeFirst(head) head = 0 } return first } // MARK: - Private private enum Const { // Static stored properties not yet supported in generic types. static var maxEmptySpacesPercent: Float { return 0.25 } static var minCountForOptimise: Int { return 50 } } private var head = 0 private var array = [T?]() private let maxEmptySpacesPercent: Float private let minCountForOptimise: Int }
mit
b1936cc2bd4c2b95310a663dbb76d917
22.660714
65
0.701887
3.414948
false
false
false
false
1amageek/StripeAPI
StripeAPI/Models/CORE_RESOURCES/Customer.swift
1
4655
// // Customer.swift // StripeAPI // // Created by 1amageek on 2017/10/01. // Copyright © 2017年 Stamp Inc. All rights reserved. // import Foundation import APIKit public struct Customer: StripeModel, ListProtocol { public static var path: String { return "/customers" } private enum CodingKeys: String, CodingKey { case id case object case accountBalance = "account_balance" case created case currency case defaultSource = "default_source" case delinquent case desc = "description" case discount case email case livemode case metadata case shipping case sources case subscriptions } public let id: String public let object: String public let accountBalance: Int public let created: TimeInterval public let currency: Currency? public let defaultSource: Source? public let delinquent: Bool public let desc: String? public let discount: Discount? public let email: String? public let livemode: Bool public let metadata: [String: String]? public let shipping: Shipping? public let sources: List<Source>? public let subscriptions: List<Subscription>? } extension Customer { // MARK: - Create public struct Create: StripeParametersAPI { public typealias Response = Customer public var method: HTTPMethod { return .post } public var path: String { return Customer.path } public var _parameters: Any? public init() { self._parameters = Parameters() } public init(parameters: Parameters) { self._parameters = parameters } public struct Parameters: Codable { private enum CodingKeys: String, CodingKey { case accountBalance case businessVatID case coupon case defaultSource case description case email case metadata case shipping case source } public var accountBalance: Int? = nil public var businessVatID: String? = nil public var coupon: Coupon? = nil public var defaultSource: String? = nil public var description: String? = nil public var email: String? = nil public var metadata: [String: String]? = nil public var shipping: Shipping? = nil public var source: Source? = nil } } // MARK: - Retrieve public struct Retrieve: StripeAPI { public typealias Response = Customer public var method: HTTPMethod { return .get } public var path: String { return "\(Customer.path)/\(id)" } public let id: String public init(id: String) { self.id = id } } // MARK: - Update public struct Update: StripeParametersAPI { public typealias Response = Customer public var method: HTTPMethod { return .post } public var path: String { return "\(Customer.path)/\(id)" } public let id: String public var _parameters: Any? public init(id: String, parameters: Parameters) { self.id = id self._parameters = parameters } public struct Parameters: Codable { private enum CodingKeys: String, CodingKey { case accountBalance case businessVatID case coupon case defaultSource case description case email case metadata case shipping case source } public var accountBalance: Int? = nil public var businessVatID: String? = nil public var coupon: Coupon? = nil public var defaultSource: String? = nil public var description: String? = nil public var email: String? = nil public var metadata: [String: String]? = nil public var shipping: Shipping? = nil public var source: Source? = nil } } // MARK: - Delete public struct Delete: StripeAPI { public var method: HTTPMethod { return .delete } public var path: String { return "\(Customer.path)/\(id)" } public let id: String public init(id: String) { self.id = id } public struct Response: Codable { public let deleted: Bool public let id: String } } }
mit
1b361df0caa895abb6349aeeab5eb59d
24.844444
67
0.568143
5.232846
false
false
false
false
ahoppen/swift
test/Generics/sr11153.swift
2
978
// RUN: %target-swift-frontend -typecheck -debug-generic-signatures %s 2>&1 | %FileCheck %s // RUN: %target-swift-frontend -emit-ir %s // CHECK: Requirement signature: <Self where Self.[VectorSpace]Field : FieldAlgebra> public protocol VectorSpace { associatedtype Field: FieldAlgebra } // CHECK: Requirement signature: <Self where Self : VectorSpace, Self == Self.[VectorSpace]Field, Self.[FieldAlgebra]ComparableSubalgebra : ComparableFieldAlgebra> public protocol FieldAlgebra: VectorSpace where Self.Field == Self { associatedtype ComparableSubalgebra: ComparableFieldAlgebra static var zero: Self { get } } // CHECK: Requirement signature: <Self where Self : FieldAlgebra, Self == Self.[FieldAlgebra]ComparableSubalgebra> public protocol ComparableFieldAlgebra: FieldAlgebra where Self.ComparableSubalgebra == Self { } // CHECK: Generic signature: <F where F : FieldAlgebra> public func test<F: FieldAlgebra>(_ f: F) { _ = F.ComparableSubalgebra.zero }
apache-2.0
b2825f733b69203349f70d0de6032567
43.454545
163
0.760736
4.041322
false
false
false
false
banDedo/BDModules
HarnessModules/MainViewController/MainViewController.swift
1
4639
// // MainViewController.swift // BDModules // // Created by Patrick Hogan on 10/24/14. // Copyright (c) 2014 bandedo. All rights reserved. // import UIKit public protocol MainViewControllerDelegate: class { func mainViewControllerDidLogout(mainViewController: MainViewController) } public class MainViewController: LifecycleViewController, MenuNavigationControllerDelegate, MenuViewControllerDelegate { // MARK:- Injectable public lazy var menuViewController = MenuViewController() public lazy var mainFactory = MainFactory() weak public var delegate: MainViewControllerDelegate? // MARK:- Properties public lazy var navigationDrawerViewController: NavigationDrawerViewController = { let navigationDrawerViewController = NavigationDrawerViewController() navigationDrawerViewController.statusBarBlockerView.backgroundColor = Color.clearColor navigationDrawerViewController.replaceLeftViewController(self.menuNavigationController) navigationDrawerViewController.replaceCenterViewController(self.mainNavigationController) return navigationDrawerViewController }() public lazy var menuNavigationController: NavigationController = { let menuNavigationController = NavigationController() menuNavigationController.setNavigationBarHidden(true, animated: false) menuNavigationController.viewControllers = [ self.menuViewController ] return menuNavigationController }() public lazy var mainNavigationController: NavigationController = { return self.mainNavigationController(self.mainFactory.mapViewController(delegate: self)) }() // MARK:- View lifecycle public override func viewDidLoad() { super.viewDidLoad() replaceRootViewController(navigationDrawerViewController) } // MARK:- Status bar public override func preferredStatusBarStyle() -> UIStatusBarStyle { switch navigationDrawerViewController.orientation { case .Default: return mainNavigationController.preferredStatusBarStyle() case .PartialRevealLeft, .RevealLeft: return menuViewController.preferredStatusBarStyle() } } // MARK:- Main Navigation Controller private func mainNavigationController(rootViewController: LifecycleViewController) -> NavigationController { let mainNavigationController = NavigationController() mainNavigationController.viewControllers = [ rootViewController ] return mainNavigationController } // MARK:- Menu private func updateMenu() { let orientation: NavigationDrawerViewController.Orientation switch navigationDrawerViewController.orientation { case .Default: orientation = .PartialRevealLeft break case .PartialRevealLeft, .RevealLeft: orientation = .Default break } navigationDrawerViewController.anchorDrawer( orientation, animated: true ) } private func replaceMainNavigationViewController(viewController: LifecycleViewController, animated: Bool) { navigationDrawerViewController.replaceCenterViewController({ [weak self] in if let strongSelf = self { strongSelf.mainNavigationController = strongSelf.mainNavigationController(viewController) return strongSelf.mainNavigationController } else { return UIViewController() } }, animated: animated) } // MARK:- MenuNavigationControllerDelegate public func viewController(viewController: UIViewController, didTapMenuButton sender: UIButton) { updateMenu() } // MARK:- MenuViewControllerDelegate public func menuViewController(menuViewController: MenuViewController, didSelectRow row: MenuViewController.Row) { switch row { case .Map: replaceMainNavigationViewController(mainFactory.mapViewController(delegate: self), animated: true) break case .Favorites: replaceMainNavigationViewController(mainFactory.favoritesViewController(delegate: self), animated: true) break case .Settings: replaceMainNavigationViewController(mainFactory.settingsViewController(delegate: self), animated: true) break case .Logout: delegate?.mainViewControllerDidLogout(self) break case .Footer: break } } }
apache-2.0
ea0c9568e1c02acda0ed1e2f0ef3a8fd
34.96124
120
0.697133
6.842183
false
false
false
false
emilstahl/swift
test/Interpreter/generic_objc_subclass.swift
10
2057
// RUN: rm -rf %t // RUN: mkdir -p %t // // RUN: %target-clang -fobjc-arc %S/Inputs/ObjCClasses/ObjCClasses.m -c -o %t/ObjCClasses.o // RUN: %target-build-swift -I %S/Inputs/ObjCClasses/ -Xlinker %t/ObjCClasses.o %s -o %t/a.out // RUN: %target-run %t/a.out | FileCheck %s // REQUIRES: executable_test // XFAIL: linux // rdar://19583881 import Foundation import ObjCClasses @objc protocol P { func calculatePrice() -> Int } class A<T> : HasHiddenIvars, P { var x: Int = 16 var t: T? = nil var y: Int = 61 override var description: String { return "Grilled artichokes" } func calculatePrice() -> Int { return 400 } } let a = A<Int>() // CHECK: Grilled artichokes // CHECK: Grilled artichokes print(a.description) print((a as NSObject).description) // CHECK: 0 // CHECK: 16 // CHECK: nil // CHECK: 61 print(a.count) print(a.x) print(a.t) print(a.y) // CHECK: 25 // CHECK: 16 // CHECK: nil // CHECK: 61 a.count = 25 print(a.count) print(a.x) print(a.t) print(a.y) // CHECK: 25 // CHECK: 36 // CHECK: nil // CHECK: 61 a.x = 36 print(a.count) print(a.x) print(a.t) print(a.y) // CHECK: 25 // CHECK: 36 // CHECK: 121 // CHECK: 61 a.t = 121 print(a.count) print(a.x) print(a.t) print(a.y) let aa = A<(Int, Int)>() // CHECK: 0 // CHECK: 16 // CHECK: nil // CHECK: 61 print(aa.count) print(aa.x) print(aa.t) print(aa.y) aa.count = 101 aa.t = (19, 84) aa.y = 17 // CHECK: 101 // CHECK: 16 // CHECK: (19, 84) // CHECK: 17 print(aa.count) print(aa.x) print(aa.t) print(aa.y) class B : A<(Int, Int)> { override var description: String { return "Salmon" } @nonobjc override func calculatePrice() -> Int { return 1675 } } class C : A<(Int, Int)> { @nonobjc override var description: String { return "Invisible Chicken" } override func calculatePrice() -> Int { return 650 } } // CHECK: 400 // CHECK: 650 print((B() as P).calculatePrice()) print((C() as P).calculatePrice()) // CHECK: Salmon // CHECK: Grilled artichokes print((B() as NSObject).description) print((C() as NSObject).description)
apache-2.0
174c5512e695822d968c8097cbb6882b
14.583333
94
0.629071
2.720899
false
false
false
false
AaronMT/firefox-ios
Account/SyncAuthState.swift
7
6790
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import Shared import XCGLogger import SwiftyJSON import MozillaAppServices public let FxAClientErrorDomain = "org.mozilla.fxa.error" public let FxAClientUnknownError = NSError(domain: FxAClientErrorDomain, code: 999, userInfo: [NSLocalizedDescriptionKey: "Invalid server response"]) public struct FxAccountRemoteError { static let AttemptToOperateOnAnUnverifiedAccount: Int32 = 104 static let InvalidAuthenticationToken: Int32 = 110 static let EndpointIsNoLongerSupported: Int32 = 116 static let IncorrectLoginMethodForThisAccount: Int32 = 117 static let IncorrectKeyRetrievalMethodForThisAccount: Int32 = 118 static let IncorrectAPIVersionForThisAccount: Int32 = 119 static let UnknownDevice: Int32 = 123 static let DeviceSessionConflict: Int32 = 124 static let UnknownError: Int32 = 999 } public enum FxAClientError: Error, CustomStringConvertible { case remote(RemoteError) case local(NSError) public var description : String { switch self { case .remote(let err): return "FxA remote error: \(err)" case .local(let err): return "FxA local error: \(err)" } } } public struct RemoteError { let code: Int32 let errno: Int32 let error: String? let message: String? let info: String? var isUpgradeRequired: Bool { return errno == FxAccountRemoteError.EndpointIsNoLongerSupported || errno == FxAccountRemoteError.IncorrectLoginMethodForThisAccount || errno == FxAccountRemoteError.IncorrectKeyRetrievalMethodForThisAccount || errno == FxAccountRemoteError.IncorrectAPIVersionForThisAccount } var isInvalidAuthentication: Bool { return code == 401 } var isUnverified: Bool { return errno == FxAccountRemoteError.AttemptToOperateOnAnUnverifiedAccount } } private let CurrentSyncAuthStateCacheVersion = 1 private let log = Logger.syncLogger public struct SyncAuthStateCache { let token: TokenServerToken let forKey: Data let expiresAt: Timestamp } public protocol SyncAuthState { func invalidate() func token(_ now: Timestamp, canBeExpired: Bool) -> Deferred<Maybe<(token: TokenServerToken, forKey: Data)>> var enginesEnablements: [String: Bool]? { get set } var clientName: String? { get set } } public func syncAuthStateCachefromJSON(_ json: JSON) -> SyncAuthStateCache? { if let version = json["version"].int { if version != CurrentSyncAuthStateCacheVersion { log.warning("Sync Auth State Cache is wrong version; dropping.") return nil } if let token = TokenServerToken.fromJSON(json["token"]), let forKey = json["forKey"].string?.hexDecodedData, let expiresAt = json["expiresAt"].int64 { return SyncAuthStateCache(token: token, forKey: forKey, expiresAt: Timestamp(expiresAt)) } } return nil } extension SyncAuthStateCache: JSONLiteralConvertible { public func asJSON() -> JSON { return JSON([ "version": CurrentSyncAuthStateCacheVersion, "token": token.asJSON(), "forKey": forKey.hexEncodedString, "expiresAt": NSNumber(value: expiresAt), ] as NSDictionary) } } open class FirefoxAccountSyncAuthState: SyncAuthState { fileprivate let cache: KeychainCache<SyncAuthStateCache> public var enginesEnablements: [String: Bool]? public var clientName: String? init(cache: KeychainCache<SyncAuthStateCache>) { self.cache = cache } // If a token gives you a 401, invalidate it and request a new one. open func invalidate() { log.info("Invalidating cached token server token.") self.cache.value = nil } open func token(_ now: Timestamp, canBeExpired: Bool) -> Deferred<Maybe<(token: TokenServerToken, forKey: Data)>> { if let value = cache.value { // Give ourselves some room to do work. let isExpired = value.expiresAt < now + 5 * OneMinuteInMilliseconds if canBeExpired { if isExpired { log.info("Returning cached expired token.") } else { log.info("Returning cached token, which should be valid.") } return deferMaybe((token: value.token, forKey: value.forKey)) } if !isExpired { log.info("Returning cached token, which should be valid.") return deferMaybe((token: value.token, forKey: value.forKey)) } } let deferred = Deferred<Maybe<(token: TokenServerToken, forKey: Data)>>() RustFirefoxAccounts.shared.accountManager.uponQueue(.main) { accountManager in accountManager.getTokenServerEndpointURL() { result in guard case .success(let tokenServerEndpointURL) = result else { deferred.fill(Maybe(failure: FxAClientError.local(NSError()))) return } let client = TokenServerClient(url: tokenServerEndpointURL) accountManager.getAccessToken(scope: OAuthScope.oldSync) { res in switch res { case .failure(let err): deferred.fill(Maybe(failure: err as MaybeErrorType)) case .success(let accessToken): log.debug("Fetching token server token.") client.token(token: accessToken.token, kid: accessToken.key!.kid).upon { result in guard let token = result.successValue else { deferred.fill(Maybe(failure: result.failureValue!)) return } let kSync = accessToken.key!.k.base64urlSafeDecodedData! let newCache = SyncAuthStateCache(token: token, forKey: kSync,expiresAt: now + 1000 * token.durationInSeconds) log.debug("Fetched token server token! Token expires at \(newCache.expiresAt).") self.cache.value = newCache deferred.fill(Maybe(success: (token: token, forKey: kSync))) } } } } } return deferred } }
mpl-2.0
6f6f971fc948453ff79c4c8f7b3c3d20
37.8
138
0.613991
5.247295
false
false
false
false