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
OmarBizreh/IOSTrainingApp
IOSTrainingApp/Views/MainTableViewController.swift
1
8863
// // MainTableViewController.swift // IOSTrainingApp // // Created by Omar Bizreh on 2/6/16. // Copyright © 2016 Omar Bizreh. All rights reserved. // import UIKit import CoreSpotlight import MobileCoreServices import CoreData class MainTableViewController: UITableViewController, UISearchResultsUpdating { var Names: [String] = [String]() var people: [NSManagedObject] = [NSManagedObject]() var filteredPeople: [NSManagedObject] = [NSManagedObject]() let cellIdentifier = "reuseIdentifier" let searchController: UISearchController = UISearchController(searchResultsController: nil) let searchScopes: [String] = ["First Name", "Last Name"] override func viewDidLoad() { super.viewDidLoad() // 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() let btnRefresh = UIBarButtonItem(title: "Refresh", style: UIBarButtonItemStyle.Plain, target: self, action: "loadData") self.navigationItem.rightBarButtonItem = btnRefresh let btnAdd = UIBarButtonItem(title: "Add", style: UIBarButtonItemStyle.Done, target: self, action: "AddName") self.navigationItem.leftBarButtonItem = btnAdd self.tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: self.cellIdentifier) searchController.dimsBackgroundDuringPresentation = false searchController.definesPresentationContext = true searchController.searchResultsUpdater = self searchController.searchBar.scopeButtonTitles = self.searchScopes tableView.tableHeaderView = searchController.searchBar } func updateSearchResultsForSearchController(searchController: UISearchController) { guard let text = searchController.searchBar.text else{ return } self.filterContentForSearchText(text, scope: self.searchController.searchBar.scopeButtonTitles![self.searchController.searchBar.selectedScopeButtonIndex]) } func filterContentForSearchText(searchText: String, scope: String = "Both"){ self.filteredPeople = self.people.filter({ (object) -> Bool in if scope == self.searchScopes[0]{ return (object.valueForKey("name") as! String).lowercaseString.containsString(searchText.lowercaseString) } else{ return false } }) self.tableView.reloadData() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func indexData(){ if CSSearchableIndex.isIndexingAvailable() { // Create attribute set and set itemContentType to String let attributeSet = CSSearchableItemAttributeSet(itemContentType: kUTTypeText as String) attributeSet.title = (self.people[self.people.count - 1].valueForKey("name") as! String) attributeSet.contentDescription = "Index from IOSTrainingApp" let item = CSSearchableItem(uniqueIdentifier: "1", domainIdentifier: "com.IOSTrainingApp", attributeSet: attributeSet) item.expirationDate = NSDate.distantFuture() CSSearchableIndex.defaultSearchableIndex().indexSearchableItems([item]) { (error: NSError?) -> Void in if let mError = error{ print("Error indexing: \(mError)") }else{ print("Successfully Indexed item") } } } } func loadData(){ self.fetchPersons() } func AddName(){ let alert = UIAlertController(title: "New Name", message: "Add a new name", preferredStyle: .Alert) let saveAction = UIAlertAction(title: "Save", style: .Default, handler: {(action: UIAlertAction) -> Void in let textField = alert.textFields!.first // self.Names.append(textField!.text!) self.saveName(textField!.text!) self.tableView.reloadData() self.indexData() }) let cancelAction = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Default) { (action:UIAlertAction) -> Void in } alert.addAction(cancelAction) alert.addAction(saveAction) alert.addTextFieldWithConfigurationHandler { (txt:UITextField) -> Void in } self.presentViewController(alert, animated: true, completion: nil) } func saveName(name: String){ let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate let managedContext = appDelegate.managedObjectContext let mPersonEntity = NSEntityDescription.entityForName("Person", inManagedObjectContext: managedContext) let mPerson = NSManagedObject(entity: mPersonEntity!, insertIntoManagedObjectContext: managedContext) mPerson.setValue(name, forKey: "name") do{ try managedContext.save() self.people.append(mPerson) }catch let error as NSError{ print("Could not save \(error), \(error.userInfo)") } } func fetchPersons(){ let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate let managedContext = appDelegate.managedObjectContext let fetchRequest = NSFetchRequest(entityName: "Person") do{ let results = try managedContext.executeFetchRequest(fetchRequest) self.people = results as! [NSManagedObject] self.tableView.reloadData() }catch let error as NSError{ print("Could not fetch \(error), \(error.userInfo)") } } override func numberOfSectionsInTableView(tableView: UITableView) -> Int { // #warning Incomplete implementation, return the number of sections return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if self.searchController.active && self.searchController.searchBar.text != ""{ return self.filteredPeople.count } return self.people.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier(self.cellIdentifier, forIndexPath: indexPath) //cell.textLabel?.text = self.Names[indexPath.row] if self.searchController.active && self.searchController.searchBar.text != ""{ cell.textLabel?.text = self.filteredPeople[indexPath.row].valueForKey("name") as? String }else{ cell.textLabel?.text = self.people[indexPath.row].valueForKey("name") as? String } return cell } // Override to support conditional editing of the table view. override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } /* // Override 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 false 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. } */ }
mit
171cc10752483d904ad32139c1d762be
39.651376
162
0.664297
5.598231
false
false
false
false
lvogelzang/Blocky
Blocky/Levels/Level57.swift
1
877
// // Level57.swift // Blocky // // Created by Lodewijck Vogelzang on 07-12-18 // Copyright (c) 2018 Lodewijck Vogelzang. All rights reserved. // import UIKit final class Level57: Level { let levelNumber = 57 var tiles = [[0, 1, 0, 1, 0], [1, 1, 1, 1, 1], [0, 1, 0, 1, 0], [0, 1, 0, 1, 0]] let cameraFollowsBlock = false let blocky: Blocky let enemies: [Enemy] let foods: [Food] init() { blocky = Blocky(startLocation: (0, 1), endLocation: (4, 1)) let pattern0 = [("S", 0.5), ("S", 0.5), ("S", 0.5), ("N", 0.5), ("N", 0.5), ("N", 0.5)] let enemy0 = Enemy(enemyNumber: 0, startLocation: (1, 3), animationPattern: pattern0) let pattern1 = [("S", 0.5), ("S", 0.5), ("S", 0.5), ("N", 0.5), ("N", 0.5), ("N", 0.5)] let enemy1 = Enemy(enemyNumber: 1, startLocation: (3, 3), animationPattern: pattern1) enemies = [enemy0, enemy1] foods = [] } }
mit
035263a65e8011dc61d01a4c38badfac
24.794118
89
0.573546
2.649547
false
false
false
false
nodes-ios/Serializable
Serpent/Example/SerpentExample/Classes/Models/User.swift
2
1946
// // User.swift // SerpentExample // // Created by Dominik Hádl on 17/04/16. // Copyright © 2016 Nodes ApS. All rights reserved. // import Serpent enum Gender: String { case Male = "male" case Female = "female" } struct User { var gender = Gender.Male var name = NameInfo() var location = Location() var email = "" var loginInfo = LoginInfo() // <-login var registrationDate = 0 // <-registered var birthDate = 0 // <-dob var phoneNumber = "" // <-phone var cellNumber = "" // <-cell var identification = Identification() // <-id var picture = ProfilePicture() } extension User: Serializable { init(dictionary: NSDictionary?) { gender <== (self, dictionary, "gender") name <== (self, dictionary, "name") location <== (self, dictionary, "location") email <== (self, dictionary, "email") loginInfo <== (self, dictionary, "login") registrationDate <== (self, dictionary, "registered") birthDate <== (self, dictionary, "dob") phoneNumber <== (self, dictionary, "phone") cellNumber <== (self, dictionary, "cell") identification <== (self, dictionary, "id") picture <== (self, dictionary, "picture") } func encodableRepresentation() -> NSCoding { let dict = NSMutableDictionary() (dict, "gender") <== gender (dict, "name") <== name (dict, "location") <== location (dict, "email") <== email (dict, "login") <== loginInfo (dict, "registered") <== registrationDate (dict, "dob") <== birthDate (dict, "phone") <== phoneNumber (dict, "cell") <== cellNumber (dict, "id") <== identification (dict, "picture") <== picture return dict } }
mit
fa723310cf36f55fc7bd0a02c70760cc
28.454545
61
0.523663
4.32
false
false
false
false
proversity-org/edx-app-ios
Source/WebView/URL+PathExtension.swift
2
1014
// // URL+PathExtension.swift // edX // // Created by Zeeshan Arif on 7/13/18. // Copyright © 2018 edX. All rights reserved. // import Foundation extension URL { var appURLHost: String { return host ?? "" } var isValidAppURLScheme: Bool { return scheme ?? "" == URIString.appURLScheme.rawValue ? true : false } var queryParameters: [String: Any]? { guard let queryString = query else { return nil } var queryParameters = [String: Any]() let parameters = queryString.components(separatedBy: "&") for parameter in parameters { let keyValuePair = parameter.components(separatedBy: "=") // Parameter will be ignored if invalid data for keyValuePair if keyValuePair.count == 2 { let key = keyValuePair[0] let value = keyValuePair[1] queryParameters[key] = value } } return queryParameters } }
apache-2.0
537474189ceac2b408ab471db2b9a016
25.657895
77
0.568608
4.755869
false
false
false
false
timpalpant/SwiftConstraint
ConstraintSolver/Solver.swift
1
9111
// // ConstraintSolver.swift // ConstraintSolver // // Adapted from Python source by Timothy Palpant on 7/29/14. // // Copyright (c) 2005-2014 - Gustavo Niemeyer <[email protected]> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // import Foundation public protocol Solver { func solve<T: Hashable>(problem: Problem<T>, single:Bool) -> [[T]] } public class BacktrackingSolver : Solver { let forwardCheck: Bool public init(forwardCheck: Bool=true) { self.forwardCheck = forwardCheck } public func solve<T: Hashable>(problem: Problem<T>, single:Bool=false) -> [[T]] { problem.preprocess() var queue: [(variable: Variable<T>, values: [T], pushdomains: [Domain<T>])] = [] var variable: Variable<T>! var values: [T] = [] var pushdomains: [Domain<T>] = [] while true { // Mix the Degree and Minimum Remaining Values (MRV) heuristics var lst = problem.variables.map { variable in (-variable.constraints.count, variable.domain.count, variable) } lst.sort { $0.0 == $1.0 ? $0.1 < $1.1 : $0.0 < $1.0 } variable = nil for (_, _, v) in lst { if v.assignment == nil { // Found unassigned variable variable = v values = Array(v.domain) pushdomains = [] if self.forwardCheck { for x in problem.variables { if x.assignment == nil && x !== v { pushdomains.append(x.domain) } } } break } } if variable == nil { // No unassigned variables. We have a solution // Go back to last variable, if there is one let sol = problem.variables.map { v in v.assignment! } problem.solutions.append(sol) if queue.isEmpty { // last solution return problem.solutions } let t = queue.removeLast() variable = t.variable values = t.values pushdomains = t.pushdomains for domain in pushdomains { domain.popState() } } while true { // We have a variable. Do we have any values left? if values.count == 0 { // No. Go back to the last variable, if there is one. variable.assignment = nil while !queue.isEmpty { let t = queue.removeLast() variable = t.variable values = t.values pushdomains = t.pushdomains for domain in pushdomains { domain.popState() } if !values.isEmpty { break } variable.assignment = nil } if values.isEmpty { return problem.solutions } } // Got a value; check it variable.assignment = values.removeLast() for domain in pushdomains { domain.pushState() } var good = true for constraint in variable.constraints { if !constraint.evaluate(self.forwardCheck) { good = false break // Value is not good } } if good { break } for domain in pushdomains { domain.popState() } } // Push state before looking for next variable. queue += [(variable: variable!, values: values, pushdomains: pushdomains)] } } } public class RecursiveBacktrackingSolver : Solver { let forwardCheck: Bool public init(forwardCheck: Bool) { self.forwardCheck = forwardCheck } public convenience init() { self.init(forwardCheck: true) } private func recursiveBacktracking<T: Hashable>(var problem: Problem<T>, single:Bool=false) -> [[T]] { var pushdomains = [Domain<T>]() // Mix the Degree and Minimum Remaining Values (MRV) heuristics var lst = problem.variables.map { variable in (-variable.constraints.count, variable.domain.count, variable) } lst.sort { $0.0 == $1.0 ? $0.1 < $1.1 : $0.0 < $1.0 } var missing: Variable<T>? for (_, _, variable) in lst { if variable.assignment == nil { missing = variable } } if var variable = missing { pushdomains.removeAll() if forwardCheck { for v in problem.variables { if v.assignment == nil { pushdomains.append(v.domain) } } } for value in variable.domain { variable.assignment = value for domain in pushdomains { domain.pushState() } var good = true for constraint in variable.constraints { if !constraint.evaluate(forwardCheck) { good = false break // Value is not good } } if good { // Value is good. Recurse and get next variable recursiveBacktracking(problem, single: single) if !problem.solutions.isEmpty && single { return problem.solutions } } for domain in pushdomains { domain.popState() } } variable.assignment = nil return problem.solutions } // No unassigned variables. We have a solution let values = problem.variables.map { variable in variable.assignment! } problem.solutions.append(values) return problem.solutions } public func solve<T : Hashable>(problem: Problem<T>, single:Bool=false) -> [[T]] { problem.preprocess() return recursiveBacktracking(problem, single: single) } } func random_choice<T>(a: [T]) -> T { let index = Int(arc4random_uniform(UInt32(a.count))) return a[index] } func shuffle<C: MutableCollectionType where C.Index == Int>(var list: C) -> C { let c = count(list) for i in 0..<(c - 1) { let j = Int(arc4random_uniform(UInt32(c - i))) + i swap(&list[i], &list[j]) } return list } public class MinConflictsSolver : Solver { let steps: Int public init(steps: Int=1_000) { self.steps = steps } public func solve<T : Hashable>(problem: Problem<T>, single:Bool=false) -> [[T]] { problem.preprocess() // Initial assignment for variable in problem.variables { variable.assignment = random_choice(variable.domain.elements) } for _ in 1...self.steps { var conflicted = false let lst = shuffle(problem.variables) for variable in lst { // Check if variable is not in conflict var allSatisfied = true for constraint in variable.constraints { if !constraint.evaluate(false) { allSatisfied = false break } } if allSatisfied { continue } // Variable has conflicts. Find values with less conflicts var mincount = variable.constraints.count var minvalues: [T] = [] for value in variable.domain { variable.assignment = value var count = 0 for constraint in variable.constraints { if !constraint.evaluate(false) { count += 1 } } if count == mincount { minvalues.append(value) } else if count < mincount { mincount = count minvalues.removeAll() minvalues.append(value) } } // Pick a random one from these values variable.assignment = random_choice(minvalues) conflicted = true } if !conflicted { let solution = problem.variables.map { variable in variable.assignment! } problem.solutions.append(solution) return problem.solutions } } return problem.solutions } }
lgpl-2.1
27e2b84d08132e96913453bbbdc5d486
29.172185
104
0.585227
4.409971
false
false
false
false
LightD/ivsa-server
Sources/App/Middlewares/AdminSessionAuthMiddleware.swift
1
2051
// // AdminSessionAuthMiddleware.swift // ivsa // // Created by Light Dream on 26/02/2017. // // import Foundation import HTTP import Vapor import Auth import TurnstileWeb final class AdminSessionAuthMiddleware: Middleware { func respond(to request: Request, chainingTo next: Responder) throws -> Response { do { // check if the access token is valid guard let _ = try request.adminSessionAuth.admin() else { throw "admin wasn't found" } // authenticated and everything, perform the request return try next.respond(to: request) } catch { // if there's an error, we redirect to root page, and that one decides return Response(redirect: "/admin") } } } public final class AdminSessionAuthHelper { let request: Request init(request: Request) { self.request = request } public var header: Authorization? { guard let authorization = request.headers["Authorization"] else { return nil } return Authorization(header: authorization) } func login(_ credentials: Credentials) throws -> IVSAAdmin { let user = try IVSAAdmin.authenticate(credentials: credentials) as! IVSAAdmin try request.session().data["user_id"] = user.id return user } func logout() throws { try request.session().destroy() } func admin() throws -> IVSAAdmin? { let userId: String? = try request.session().data["user_id"]?.string guard let id = userId else { return nil } guard let user = try IVSAAdmin.find(id) else { return nil } return user } } extension Request { public var adminSessionAuth: AdminSessionAuthHelper { let helper = AdminSessionAuthHelper(request: self) return helper } }
mit
e70ff69f795308eb32579471b6b9fb00
23.416667
86
0.570453
4.792056
false
false
false
false
adib/Cheesy-Movies
BadFlix/Managers/GenreList.swift
1
3817
// Cheesy Movies // Copyright (C) 2016 Sasmito Adibowo – http://cutecoder.org // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. import Foundation private let genreListFileName = "GenreList.plist" class GenreList { static let defaultInstance = GenreList() /// Mapping between ID and Genre, for the current language var currentMapping : Dictionary<Int64,GenreEntity>? func refresh(_ completionHandler: ((Error?) -> Void)? ) { // TODO: refresh list of genres MovieBackend.defaultInstance.requestJSON(path: "genre/movie/list") { (result, error) in guard error == nil else { completionHandler?(error) return } if let resultDict = result as? [String:AnyObject] { if let genresArray = resultDict["genres"] as? [[String:AnyObject]] { var mapping = Dictionary<Int64,GenreEntity>(minimumCapacity:genresArray.count) for genreDict in genresArray { let genreObj = GenreEntity(json: genreDict) if genreObj.genreID != 0 { mapping[genreObj.genreID] = genreObj } } if mapping.count > 0 { self.currentMapping = mapping self.save() } } } completionHandler?(nil) } } required init() { let fileManager = FileManager.default if let cachesDir = fileManager.urls(for: .cachesDirectory, in: .userDomainMask).first { let genrePathString = cachesDir.appendingPathComponent(genreListFileName).path if let dict = NSKeyedUnarchiver.unarchiveObject(withFile: genrePathString) as? Dictionary<NSNumber,GenreEntity> { var ourDict = Dictionary<Int64,GenreEntity>() for (k,v) in dict { ourDict[k.int64Value] = v } self.currentMapping = ourDict } } } /// Save the genre list into folder func save() { guard let mapping = self.currentMapping else { return } let processInfo = ProcessInfo.processInfo let activityToken = processInfo.beginActivity(options: [.background], reason: "Saving genre information") DispatchQueue.global(qos: DispatchQoS.QoSClass.background).async { defer { processInfo.endActivity(activityToken) } let fileManager = FileManager.default guard let cachesDir = fileManager.urls(for: .cachesDirectory, in: .userDomainMask).first else { return } let genrePathString = cachesDir.appendingPathComponent(genreListFileName).path let serializedDict = NSMutableDictionary(capacity: mapping.count) for (k,v) in mapping { serializedDict.setObject(v, forKey: NSNumber(value: k as Int64)) } NSKeyedArchiver.archiveRootObject(serializedDict, toFile: genrePathString) } } }
gpl-3.0
6174ba470f3669bc54a8b6e9816d99cc
37.928571
125
0.595282
5.079893
false
false
false
false
wireapp/wire-ios-data-model
Tests/Source/Model/Observer/StringKeyPathTests.swift
1
1917
// // Wire // Copyright (C) 2016 Wire Swiss GmbH // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see http://www.gnu.org/licenses/. // import Foundation class StringKeyPathTests: ZMBaseManagedObjectTest { func testThatItCreatesASimpleKeyPath() { let sut = StringKeyPath.keyPathForString("name") XCTAssertEqual(sut.rawValue, "name") XCTAssertEqual(sut.count, 1) XCTAssertFalse(sut.isPath) } func testThatItCreatesKeyPathThatIsAPath() { let sut = StringKeyPath.keyPathForString("foo.name") XCTAssertEqual(sut.rawValue, "foo.name") XCTAssertEqual(sut.count, 2) XCTAssertTrue(sut.isPath) } func testThatItDecomposesSimpleKeys() { let sut = StringKeyPath.keyPathForString("name") if let (a, b) = sut.decompose { XCTAssertEqual(a, StringKeyPath.keyPathForString("name")) XCTAssertEqual(b, nil) } else { XCTFail("Did not decompose") } } func testThatItDecomposesKeyPaths() { let sut = StringKeyPath.keyPathForString("foo.name") if let (a, b) = sut.decompose { XCTAssertEqual(a, StringKeyPath.keyPathForString("foo")) XCTAssertEqual(b, StringKeyPath.keyPathForString("name")) } else { XCTFail("Did not decompose") } } }
gpl-3.0
0900306c2960deae31e0fa9ae745da93
33.232143
71
0.669797
4.417051
false
true
false
false
congncif/SiFUtilities
Localize/UITextField+Localize.swift
1
1532
// // UITextField+Localize.swift // SiFUtilities // // Created by FOLY on 12/8/18. // import Foundation import UIKit // @IBDesignable extension UITextField { @IBInspectable public var placeholderLocalizedKey: String? { get { return getStringValue(by: &RunTimeKey.localizedPlaceholderTextKey) } set { setStringValue(newValue, forRuntimeKey: &RunTimeKey.localizedPlaceholderTextKey) } } @IBInspectable public var textLocalizedKey: String? { get { return getAssociatedObject(key: &RunTimeKey.localizedTextKey) } set { if let value = newValue, !newValue.isNoValue { setAssociatedObject(key: &RunTimeKey.localizedTextKey, value: value) registerLocalizeUpdateNotification() } } } @objc override open func updateLocalize(attributes: [LocalizedKey: String]) { if let text = attributes[.localizedTextKey]?.localized { self.text = text } if let text = attributes[.localizedPlaceholderTextKey]?.localized { placeholder = text } } @objc override open func updateLanguage() { if let key = textLocalizedKey { updateLocalize(attributes: [.localizedTextKey: key]) } if let key = placeholderLocalizedKey { updateLocalize(attributes: [.localizedPlaceholderTextKey: key]) } } }
mit
7472aa9f2965d6298c2db78336c75606
26.357143
92
0.592689
5.106667
false
false
false
false
iAladdin/SwiftyFORM
Example/Usecases/RateAppViewController.swift
1
1291
// // RateAppViewController.swift // SwiftyFORM // // Created by Simon Strandgaard on 22-01-15. // Copyright (c) 2015 Simon Strandgaard. All rights reserved. // import UIKit import SwiftyFORM class RateAppViewController: FormViewController { override func populate(builder: FormBuilder) { builder.navigationTitle = "Rate" builder.toolbarMode = .None builder.demo_showInfo("Rate this app") builder += SectionHeaderTitleFormItem().title("Is it good?") builder += goodSlider builder += SectionHeaderTitleFormItem().title("Is the look ok?") builder += lookSlider builder += SectionHeaderTitleFormItem().title("Thank you") builder += submitButton } lazy var goodSlider: SliderFormItem = { let instance = SliderFormItem() instance.minimumValue(-100.0).maximumValue(100.0).value(0) return instance }() lazy var lookSlider: SliderFormItem = { let instance = SliderFormItem() instance.minimumValue(-100.0).maximumValue(100.0).value(0) return instance }() lazy var submitButton: ButtonFormItem = { let instance = ButtonFormItem() instance.title("Submit My Rating") instance.action = { [weak self] in self?.submitMyRating() } return instance }() func submitMyRating() { self.form_simpleAlert("Submit Rating", "Button clicked") } }
mit
49f75632f7a653c3090a191ad809ac2a
25.346939
66
0.721921
3.819527
false
false
false
false
mirai418/leaflet-ios
leaflet/Story.swift
1
744
// // Story.swift // leaflet // // Created by Mirai Akagawa on 4/26/15. // Copyright (c) 2015 parks-and-rec. All rights reserved. // import UIKit class Story: NSObject { var id: Int! var title: String var content: String var pointsOfInterest: [FecPoi] var color: CGColor var picture: String var storyIcon: String init(id: Int, title: String, content: String, pointsOfInterest: [FecPoi], color: CGColor, picture: String, storyIcon: String) { self.id = id self.title = title self.content = content self.pointsOfInterest = pointsOfInterest self.color = color self.picture = picture self.storyIcon = storyIcon super.init() } }
mit
8a0b8bdc37d580eca25f81208b49c71c
22.25
131
0.620968
3.757576
false
false
false
false
superk589/CGSSGuide
DereGuide/Unit/Information/Controller/UnitInformationController.swift
2
3535
// // UnitInformationController.swift // DereGuide // // Created by zzk on 2017/5/16. // Copyright © 2017 zzk. All rights reserved. // import UIKit class UnitInformationController: BaseTableViewController, UnitDetailConfigurable { var unit: Unit { didSet { self.tableView.reloadData() } } weak var parentTabController: UDTabViewController? init(unit: Unit) { self.unit = unit super.init(nibName: nil, bundle: nil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() tableView.rowHeight = UITableView.automaticDimension tableView.estimatedRowHeight = 100 tableView.showsVerticalScrollIndicator = false tableView.tableFooterView = UIView() tableView.register(UnitInformationUnitCell.self, forCellReuseIdentifier: UnitInformationUnitCell.description()) tableView.register(UnitInformationLeaderSkillCell.self, forCellReuseIdentifier: UnitInformationLeaderSkillCell.description()) tableView.register(UnitInformationAppealCell.self, forCellReuseIdentifier: UnitInformationAppealCell.description()) tableView.register(UnitInformationSkillListCell.self, forCellReuseIdentifier: UnitInformationSkillListCell.description()) // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 4 } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { // print("load cell \(indexPath.row)") switch indexPath.row { case 0: let cell = tableView.dequeueReusableCell(withIdentifier: UnitInformationUnitCell.description(), for: indexPath) as! UnitInformationUnitCell cell.setup(with: unit) cell.delegate = self return cell case 1: let cell = tableView.dequeueReusableCell(withIdentifier: UnitInformationLeaderSkillCell.description(), for: indexPath) as! UnitInformationLeaderSkillCell cell.setup(with: unit) return cell case 2: let cell = tableView.dequeueReusableCell(withIdentifier: UnitInformationAppealCell.description(), for: indexPath) as! UnitInformationAppealCell cell.setup(with: unit) return cell case 3: let cell = tableView.dequeueReusableCell(withIdentifier: UnitInformationSkillListCell.description(), for: indexPath) as! UnitInformationSkillListCell cell.setup(with: unit) return cell default: return UITableViewCell() } } } extension UnitInformationController: UnitInformationUnitCellDelegate { func unitInformationUnitCell(_ unitInformationUnitCell: UnitInformationUnitCell, didClick cardIcon: CGSSCardIconView) { if let id = cardIcon.cardID, let card = CGSSDAO.shared.findCardById(id) { let vc = CDTabViewController(card: card) navigationController?.pushViewController(vc, animated: true) } } }
mit
e8830b4eb2a50359de4201557f68f4dd
35.8125
165
0.680532
5.487578
false
false
false
false
iOS-Swift-Developers/Swift
实战项目一/JQLiveTV/JQLiveTV/Classes/Home/Model/AnchorModel.swift
1
549
// // AnchorModel.swift // JQLiveTV // // Created by 韩俊强 on 2017/7/31. // Copyright © 2017年 HaRi. All rights reserved. // 欢迎加入iOS交流群: ①群:446310206 ②群:426087546 import UIKit class AnchorModel: BaseModel { var roomid : Int = 0 var name : String = "" var pic51 : String = "" var pic74 : String = "" var live : Int = 0 // 是否在直播 var push : Int = 0 // 直播显示方式 var focus : Int = 0 // 关注数 var uid : String = "" var isEvenIndex : Bool = false }
mit
315ff862c486b34a100fae60418e4c41
20.304348
48
0.581633
2.934132
false
false
false
false
pankcuf/DataContext
DataContext/Classes/URLSessionTransport.swift
1
1408
// // URLSessionTransport.swift // DataContext // // Created by Vladimir Pirogov on 18/10/16. // Copyright © 2016 Vladimir Pirogov. All rights reserved. // import Foundation open class URLSessionTransport: DataTransport { fileprivate var tasksQueue:[String:URLSessionDataTask] = [:] open class var shared: URLSessionTransport { struct Singleton { static let instance = URLSessionTransport() } return Singleton.instance } open var session: URLSession { return URLSession.shared } open override func doAction(requestContext: DataRequestContext<DataResponseContext>, callback: @escaping ActionCallback) { let urlRequest = requestContext as! URLRequestContext self._makeDataRequest(urlRequest.toURLRequest(), callback: self.responder(requestContext: requestContext, callback: callback)) } @discardableResult fileprivate func _makeDataRequest(_ request: URLRequest, callback: @escaping TransportCallback) -> String { UIApplication.shared.isNetworkActivityIndicatorVisible = true let task = self.session.dataTask(with: request) { data, response, error in UIApplication.shared.isNetworkActivityIndicatorVisible = false callback(data) } return self.requestyy(task) } open func requestyy(_ task:URLSessionDataTask) -> ActionID { let requestID = UUID().uuidString self.tasksQueue[requestID] = task task.resume() return requestID } }
mit
855f342b2e35ff54efc6155e40505028
25.54717
128
0.755508
4.289634
false
false
false
false
chenzhe555/core-ios-swift
core-ios-swift/Source/BaseHttpStruct_s.swift
1
1895
// // BaseHttpStruct_s.swift // core-ios-swift // // Created by 陈哲#[email protected] on 16/2/25. // Copyright © 2016年 陈哲是个好孩子. All rights reserved. // import UIKit /** * 网络请求接口数据结构 */ class BaseHttpRequest_s: NSObject { /** * 请求方式:GET,POST,PUT,DELETE,HEAD,OPTIONS */ var requestMethod: String = "POST"; /** * 请求参数 */ var paramaters: NSMutableDictionary = [:]; /** * 请求的服务器地址 */ var url: String = ""; /** * 请求的超时 */ var timeOut: NSInteger = 30; /** * 请求参数是否加密 */ var isEncryption: Bool = true; /** * 是否需要Token */ var isNeedToken: Bool = true; /** * 针对特定网络请求Service,设置请求失败后的弹框提示类型 */ var alertType: BaseHttpAlertType_s = .BaseHttpAlertTypeNative; } class BaseHttpResponse_s: NSObject{ /** * 进行网络请求时传入的tag值,用于标识是哪个Service请求 */ var tag: UInt = 0; /** * alamofire框架返回的服务器数据 */ var object: AnyObject?; /** * 无论网络失败还是网络请求成功但是返回异常,错误信息都是在errorInfo里面 */ var errorInfo: NSError?; /** * 判断是网络请求成功里面服务器返回的失败还是没有服务器网络请求回来的失败 yes代表成功里面的失败 no代表就是纯粹网络失败 */ var isRequestSuccessFail: Bool = false; /** * 针对特定网络请求Service,设置请求失败后的弹框提示类型 */ var alertType: BaseHttpAlertType_s = .BaseHttpAlertTypeNative; /** * 返回数据的服务器地址 */ var requestUrl: String = ""; }
mit
5eea96b9befbed9d4d0077f209ea8d97
16.851852
69
0.554633
3.30137
false
false
false
false
shamugia/WatchKit-TicTacToe-Game
Tic-Tac-Toe WatchKit Extension/Board.swift
1
2497
// // Board.swift // Tic-Tac-Toe // // Created by George Shamugia on 27/11/2014. // Copyright (c) 2014 George Shamugia. All rights reserved. // import Foundation class Board { let X = "X" let O = "O" let EMPTY_SYMBOL = " " let TIE = "T" let BOARD_SIZE = 9 var boardArray:[String] = [] init() { for i in 0 ..< self.BOARD_SIZE { self.boardArray.append(EMPTY_SYMBOL) } } func resetBoard() { for i in 0 ..< BOARD_SIZE { self.boardArray[i] = EMPTY_SYMBOL } } func getSymbolAtLocation(indx:Int) -> String? { if indx >= 0 && indx < self.BOARD_SIZE { return self.boardArray[indx] } else { return nil; } } func setOnBoard(symbol:String, atIndex indx:Int) -> String? { if indx >= 0 && indx < self.BOARD_SIZE && (symbol == X || symbol == O) { self.boardArray[indx] = symbol return winner() } else { return nil; } } func winner() -> String? { let WINNING_ROWS:[[Int]] = [[0,1,2], [3,4,5], [6,7,8], [0,3,6], [1,4,7], [2,5,8], [0,4,8], [2,4,6]] for row in 0 ..< WINNING_ROWS.count { if self.boardArray[WINNING_ROWS[row][0]] != EMPTY_SYMBOL && self.boardArray[WINNING_ROWS[row][0]] == self.boardArray[WINNING_ROWS[row][1]] && self.boardArray[WINNING_ROWS[row][1]] == self.boardArray[WINNING_ROWS[row][2]] { return self.boardArray[WINNING_ROWS[row][0]] } } for i in 0 ..< self.boardArray.count { if self.boardArray[i] == EMPTY_SYMBOL { return nil } } return self.TIE } func getWinningCellIndexes() -> [Int]? { let WINNING_ROWS:[[Int]] = [[0,1,2], [3,4,5], [6,7,8], [0,3,6], [1,4,7], [2,5,8], [0,4,8], [2,4,6]] for row in 0 ..< WINNING_ROWS.count { if self.boardArray[WINNING_ROWS[row][0]] != EMPTY_SYMBOL && self.boardArray[WINNING_ROWS[row][0]] == self.boardArray[WINNING_ROWS[row][1]] && self.boardArray[WINNING_ROWS[row][1]] == self.boardArray[WINNING_ROWS[row][2]] { return [WINNING_ROWS[row][0], WINNING_ROWS[row][1], WINNING_ROWS[row][2]] } } return nil } }
unlicense
8dc7480baae260a4f5c01ea49c8e83d2
24.742268
232
0.476572
3.276903
false
false
false
false
WhisperSystems/Signal-iOS
Signal/src/ViewControllers/ConversationView/ConversationMessageMapping.swift
1
13027
// // Copyright (c) 2019 Open Whisper Systems. All rights reserved. // import Foundation @objc public class ConversationMessageMapping: NSObject { // The desired number of the items to load BEFORE the pivot (see below). @objc public private(set) var desiredLength: UInt private let isNoteToSelf: Bool private let interactionFinder: InteractionFinder // When we enter a conversation, we want to load up to N interactions. This // is the "initial load window". // // We subsequently expand the load window in two directions using two very // different behaviors. // // * We expand the load window "upwards" (backwards in time) only when // loadMore() is called, in "pages". // * We auto-expand the load window "downwards" (forward in time) to include // any new interactions created after the initial load. // // We define the "pivot" as the last item in the initial load window. This // value is only set once. // // For example, if you enter a conversation with messages, 1..15: // // 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 // // We initially load just the last 5 (if 5 is the initial desired length): // // 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 // | pivot ^ | <-- load window // pivot: 15, desired length=5. // // If a few more messages (16..18) are sent or received, we'll always load // them immediately (they're after the pivot): // // 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 // | pivot ^ | <-- load window // pivot: 15, desired length=5. // // To load an additional page of items (perhaps due to user scrolling // upward), we extend the desired length and thereby load more items // before the pivot. // // 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 // | pivot ^ | <-- load window // pivot: 15, desired length=10. // // To reiterate: // // * The pivot doesn't move. // * The desired length applies _before_ the pivot. // * Everything after the pivot is auto-loaded. // // One last optimization: // // After an update, we _can sometimes_ move the pivot (for perf // reasons), but we also adjust the "desired length" so that this // no effect on the load behavior. // // And note: we use the pivot's sort id, not its uniqueId, which works // even if the pivot itself is deleted. private var pivotSortId: UInt64? @objc public var canLoadMore = false let thread: TSThread @objc public required init(thread: TSThread, desiredLength: UInt, isNoteToSelf: Bool) { self.thread = thread self.interactionFinder = InteractionFinder(threadUniqueId: thread.uniqueId) self.desiredLength = desiredLength self.isNoteToSelf = isNoteToSelf } @objc private(set) var loadedInteractions: [TSInteraction] = [] { didSet { AssertIsOnMainThread() loadedUniqueIds = loadedInteractions.map { $0.uniqueId } } } @objc private(set) var loadedUniqueIds: [String] = [] @objc public func contains(uniqueId: String) -> Bool { return loadedUniqueIds.contains(uniqueId) } // This method can be used to extend the desired length // and update. @objc public func update(withDesiredLength desiredLength: UInt, transaction: SDSAnyReadTransaction) throws { assert(desiredLength >= self.desiredLength) self.desiredLength = desiredLength try update(transaction: transaction) } @objc var shouldShowThreadDetails: Bool { return !canLoadMore && !isNoteToSelf && FeatureFlags.messageRequest } // This is the core method of the class. It updates the state to // reflect the latest database state & the current desired length. @objc public func update(transaction: SDSAnyReadTransaction) throws { AssertIsOnMainThread() // If we have a "pivot", load all items AFTER the pivot and up to minDesiredLength items BEFORE the pivot. // If we do not have a "pivot", load up to minDesiredLength BEFORE the pivot. var newInteractions: [TSInteraction] = [] var canLoadMore = false let desiredLength = self.desiredLength // Not all items "count" towards the desired length. On an initial load, all items count. Subsequently, // only items above the pivot count. var afterPivotCount: UInt = 0 var beforePivotCount: UInt = 0 // (void (^)(NSString *collection, NSString *key, id object, NSUInteger index, BOOL *stop))block; try interactionFinder.enumerateInteractions(transaction: transaction) { interaction, stopPtr in // Load "uncounted" items after the pivot if possible. // // As an optimization, we can skip this check (which requires // deserializing the interaction) if beforePivotCount is non-zero, // e.g. after we "pass" the pivot. if beforePivotCount == 0, let pivotSortId = self.pivotSortId { let sortId = interaction.sortId let isAfterPivot = sortId > pivotSortId if isAfterPivot { newInteractions.append(interaction) afterPivotCount += 1 return } } // Load "counted" items unless the load window overflows. if beforePivotCount >= desiredLength { // Overflow canLoadMore = true stopPtr.pointee = true } else { newInteractions.append(interaction) beforePivotCount += 1 } } self.canLoadMore = canLoadMore if self.shouldShowThreadDetails { // We only show the thread details if we're at the start of the conversation let details = ThreadDetailsInteraction(thread: self.thread, timestamp: NSDate.ows_millisecondTimeStamp()) self.loadedInteractions = [details] + Array(newInteractions.reversed()) } else { // The items need to be reversed, since we load them in reverse order. self.loadedInteractions = Array(newInteractions.reversed()) } // Establish the pivot, if necessary and possible. // // Deserializing interactions is expensive. We only need to deserialize // interactions that are "after" the pivot. So there would be performance // benefits to moving the pivot after each update to the last loaded item. // // However, this would undesirable side effects. The desired length for // conversations with very short disappearing message durations would // continuously grow as messages appeared and disappeared. // // Therefore, we only move the pivot when we've accumulated N items after // the pivot. This puts an upper bound on the number of interactions we // have to deserialize while minimizing "load window size creep". let kMaxItemCountAfterPivot = 32 let shouldSetPivot = (self.pivotSortId == nil || afterPivotCount > kMaxItemCountAfterPivot) if shouldSetPivot, let newOldestInteraction = newInteractions.first { let sortId = newOldestInteraction.sortId // Update the pivot. if self.pivotSortId != nil { self.desiredLength += afterPivotCount } self.pivotSortId = UInt64(sortId) } } // Tries to ensure that the load window includes a given item. // On success, returns the index path of that item. // On failure, returns nil. @objc(ensureLoadWindowContainsUniqueId:transaction:error:) public func ensureLoadWindowContains(uniqueId: String, transaction: SDSAnyReadTransaction) throws -> IndexPath { if let oldIndex = loadedUniqueIds.firstIndex(of: uniqueId) { return IndexPath(row: oldIndex, section: 0) } guard let index = try interactionFinder.sortIndex(interactionUniqueId: uniqueId, transaction: transaction) else { throw assertionError("could not find interaction") } let threadInteractionCount = interactionFinder.count(transaction: transaction) guard index < threadInteractionCount else { throw assertionError("invalid index") } // This math doesn't take into account the number of items loaded _after_ the pivot. // That's fine; it's okay to load too many interactions here. let desiredWindowSize: UInt = threadInteractionCount - index try self.update(withDesiredLength: desiredWindowSize, transaction: transaction) guard let newIndex = loadedUniqueIds.firstIndex(of: uniqueId) else { throw assertionError("couldn't find new index") } return IndexPath(row: newIndex, section: 0) } @objc public class ConversationMessageMappingDiff: NSObject { @objc public let addedItemIds: Set<String> @objc public let removedItemIds: Set<String> @objc public let updatedItemIds: Set<String> init(addedItemIds: Set<String>, removedItemIds: Set<String>, updatedItemIds: Set<String>) { self.addedItemIds = addedItemIds self.removedItemIds = removedItemIds self.updatedItemIds = updatedItemIds } } // Updates and then calculates which items were inserted, removed or modified. @objc public func updateAndCalculateDiff(transaction: SDSAnyReadTransaction, updatedInteractionIds: Set<String>) throws -> ConversationMessageMappingDiff { let oldItemIds = Set(self.loadedUniqueIds) try self.update(transaction: transaction) let newItemIds = Set(self.loadedUniqueIds) let removedItemIds = oldItemIds.subtracting(newItemIds) let addedItemIds = newItemIds.subtracting(oldItemIds) // We only notify for updated items that a) were previously loaded b) weren't also inserted or removed. let exclusivelyUpdatedInteractionIds = updatedInteractionIds.subtracting(addedItemIds) .subtracting(removedItemIds) .intersection(oldItemIds) return ConversationMessageMappingDiff(addedItemIds: addedItemIds, removedItemIds: removedItemIds, updatedItemIds: exclusivelyUpdatedInteractionIds) } // For performance reasons, the database modification notifications are used // to determine which items were modified. If YapDatabase ever changes the // structure or semantics of these notifications, we'll need to update this // code to reflect that. @objc public func updatedItemIds(for notifications: [NSNotification]) -> Set<String> { // We'll move this into the Yap adapter when addressing updates/observation let viewName: String = TSMessageDatabaseViewExtensionName var updatedItemIds = Set<String>() for notification in notifications { // Unpack the YDB notification, looking for row changes. guard let userInfo = notification.userInfo else { owsFailDebug("Missing userInfo.") continue } guard let viewChangesets = userInfo[YapDatabaseExtensionsKey] as? NSDictionary else { // No changes for any views, skip. continue } guard let changeset = viewChangesets[viewName] as? NSDictionary else { // No changes for this view, skip. continue } // This constant matches a private constant in YDB. let changeset_key_changes: String = "changes" guard let changesetChanges = changeset[changeset_key_changes] as? [Any] else { owsFailDebug("Missing changeset changes.") continue } for change in changesetChanges { if change as? YapDatabaseViewSectionChange != nil { // Ignore. } else if let rowChange = change as? YapDatabaseViewRowChange { updatedItemIds.insert(rowChange.collectionKey.key) } else { owsFailDebug("Invalid change: \(type(of: change)).") continue } } } return updatedItemIds } private func assertionError(_ description: String) -> Error { return OWSErrorMakeAssertionError(description) } }
gpl-3.0
52df5de2d8654d015483f296b1952869
40.094637
121
0.61741
5.027788
false
false
false
false
blockchain/My-Wallet-V3-iOS
Modules/Platform/Sources/PlatformUIKit/Components/ContentLabelView/ContentLabelViewPresenter.swift
1
2457
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import PlatformKit import RIBs import RxCocoa import RxSwift import ToolKit /// Presenter for `ContentLabelView`. final class ContentLabelViewPresenter { // MARK: - Types private typealias AccessibilityId = Accessibility.Identifier.ContentLabelView // MARK: - Title LabelContent /// An input relay for the title. let titleRelay: BehaviorRelay<String> /// Driver emitting the title `LabelContent`. let titleLabelContent: Driver<LabelContent> // MARK: - Description LabelContent let descriptionLabelContent: Driver<LabelContent> var containsDescription: Driver<Bool> { interactor.contentCalculationState .map(\.isValue) .asDriver(onErrorJustReturn: false) } // MARK: - Tap Interaction var tap: Signal<Void> { tapRelay.asSignal() } let tapRelay = PublishRelay<Void>() // MARK: - Interactor private let interactor: ContentLabelViewInteractorAPI // MARK: - Init init( title: String, alignment: NSTextAlignment, adjustsFontSizeToFitWidth: LabelContent.FontSizeAdjustment = .false, interactor: ContentLabelViewInteractorAPI, accessibilityPrefix: String ) { self.interactor = interactor titleRelay = BehaviorRelay<String>(value: title) titleLabelContent = titleRelay .asDriver() .map { title in LabelContent( text: title, font: .main(.medium, 12), color: .secondary, alignment: alignment, adjustsFontSizeToFitWidth: adjustsFontSizeToFitWidth, accessibility: .id("\(accessibilityPrefix).\(Accessibility.Identifier.ContentLabelView.title)") ) } descriptionLabelContent = interactor.contentCalculationState .compactMap(\.value) .map { LabelContent( text: $0, font: .main(.semibold, 14), color: .titleText, alignment: alignment, adjustsFontSizeToFitWidth: adjustsFontSizeToFitWidth, accessibility: .id("\(accessibilityPrefix).\(AccessibilityId.description)") ) } .asDriver(onErrorJustReturn: .empty) } }
lgpl-3.0
731181fd07c63261cc2ec2c43e2d7345
28.590361
115
0.601384
5.738318
false
false
false
false
toshiapp/toshi-ios-client
Toshi/APIClients/ToshiError.swift
1
3966
// Copyright (c) 2018 Token Browser, Inc // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. import Foundation import Teapot struct ToshiError: Error, CustomStringConvertible { static func dataTaskError(withUnderLyingError error: Error) -> TeapotError { let errorDescription = String(format: Localized.toshi_error_data_task_error, error.localizedDescription) return TeapotError(withType: .dataTaskError, description: errorDescription, underlyingError: error) } static let invalidPayload = ToshiError(withType: .invalidPayload, description: Localized.toshi_error_invalid_payload) static let invalidResponseJSON = ToshiError(withType: .invalidResponseJSON, description: Localized.toshi_error_invalid_response_json) static func invalidResponseStatus(_ status: Int) -> ToshiError { let errorDescription = String(format: NSLocalizedString("teapot_invalid_response_status", bundle: Teapot.localizationBundle, comment: ""), status) return ToshiError(withType: .invalidResponseStatus, description: errorDescription, responseStatus: status) } static let genericError = ToshiError(withType: .generic, description: Localized.toshi_generic_error) enum ErrorType: Int { case dataTaskError case invalidPayload case invalidRequestPath case invalidResponseStatus case invalidResponseJSON case generic } let type: ErrorType let description: String let responseStatus: Int? let underlyingError: Error? init(withType errorType: ErrorType, description: String, responseStatus: Int? = nil, underlyingError: Error? = nil) { self.type = errorType self.description = description self.responseStatus = responseStatus self.underlyingError = underlyingError } } extension ToshiError { static func teapotErrorTypeToToshiErrorType(_ teapotErrorType: TeapotError.ErrorType) -> ErrorType { switch teapotErrorType { case .invalidResponseStatus: return .invalidResponseStatus case .dataTaskError: return .dataTaskError case .invalidPayload: return .invalidPayload case .invalidRequestPath: return .invalidRequestPath default: return .generic } } init(withTeapotError teapotError: TeapotError, errorDescription: String? = nil) { let errorType = ToshiError.teapotErrorTypeToToshiErrorType(teapotError.type) let validErrorDescription = errorDescription ?? teapotError.description self.init(withType: errorType, description: validErrorDescription, responseStatus: teapotError.responseStatus, underlyingError: teapotError.underlyingError) } init(errorResult: NetworkResult) { switch errorResult { case .success: fatalError("Don't pass a success result in here!") case .failure(let json, _, let teapotError): guard let errorData = json?.data, let wrapper = APIErrorWrapper.optionalFromJSONData(errorData), let firstMessage = wrapper.errors.first?.message else { self.init(withTeapotError: teapotError) return } self.init(withTeapotError: teapotError, errorDescription: firstMessage) } } }
gpl-3.0
5fecc89948b7f7b324c601d2b25be2d7
39.469388
164
0.70348
4.932836
false
false
false
false
gustavoavena/BandecoUnicamp
BandecoUnicamp/ConfiguracoesTableViewController.swift
1
10188
// // ConfuiguracoesTableViewController.swift // BandecoUnicamp // // Created by Gustavo Avena on 10/06/17. // Copyright © 2017 Gustavo Avena. All rights reserved. // import UIKit import UserNotifications class ConfiguracoesTableViewController: UITableViewController { @IBOutlet weak var dietaSwitch: UISwitch! @IBOutlet weak var veggieTableViewCell: UITableViewCell! @IBOutlet weak var notificationSwitch: UISwitch! @IBOutlet weak var almocoNotificationCell: UITableViewCell! @IBOutlet weak var jantarNotificationCell: UITableViewCell! /// Responsavel por atualizar todo o UI relacionado as notificacoes. Toda vez que alguma opcao de notificacao for alterada, esse metodo deve ser chamado para // garantir que os textos dos horarios estejamo corretos e as linhas das notificacoes das refeicoes aparecam somente se ativadas. func loadNotificationOptions() { notificationSwitch.isOn = UserDefaults.standard.bool(forKey: NOTIFICATION_KEY_STRING) // TODO: setar o numero de linhas e as opcoes de notificacoes (ativadas ou nao, horario, etc) baseadp no User Defaults. // e.g. notificacao_almoco = "12:00" e notificacao_jantar = nil if let hora_almoco = UserDefaults.standard.string(forKey: ALMOCO_TIME_KEY_STRING) { print("Setando horario da notificacao do almoco: \(hora_almoco)") almocoNotificationCell.detailTextLabel?.text = hora_almoco } else { print("Horario pra notificacao do almoco nao encontrado.") // nao colocar linhas a mais na table view... } if let hora_jantar = UserDefaults.standard.string(forKey: JANTAR_TIME_KEY_STRING) { print("Setando horario da notificacao do jantar: \(hora_jantar)") jantarNotificationCell.detailTextLabel?.text = hora_jantar } else { // nao colocar linhas a mais na table view... print("Horario pra notificacao do jantar nao encontrado.") } } override func viewDidLoad() { super.viewDidLoad() dietaSwitch.isOn = UserDefaults(suiteName: "group.bandex.shared")!.bool(forKey: VEGETARIANO_KEY_STRING) // back button color self.navigationController?.navigationBar.tintColor = UIColor(red:0.96, green:0.42, blue:0.38, alpha:1.0) // disable highlight on veggie's cell. its only possible to click on switch self.veggieTableViewCell.selectionStyle = .none; tableView.reloadData() loadNotificationOptions() // 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() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) trackScreenView() } @IBAction func dietaValueChanged(_ sender: UISwitch) { UserDefaults(suiteName: "group.bandex.shared")!.set(sender.isOn, forKey: VEGETARIANO_KEY_STRING) CardapioServices.shared.registerDeviceToken() } // Abre o feedback form no Safari override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if indexPath.section == 2 && indexPath.row == 0 { UIApplication.shared.openURL(URL(string: "https://docs.google.com/forms/d/e/1FAIpQLSekvO0HnnfGnk0-FLTX86mVxAOB5Uajq8MPmB0Sv1pXPuQiCg/viewform")!) tableView.deselectRow(at: indexPath, animated: true) } } // - MARK: notifications @IBAction func notificationSwitchToggled(_ sender: UISwitch) { UserDefaults.standard.set(sender.isOn, forKey: NOTIFICATION_KEY_STRING) if(sender.isOn) { if #available(iOS 10.0, *) { registerForPushNotifications() } else { // Fallback on earlier versions } } else { // Desabilitar notificacao if #available(iOS 10.0, *) { if let token = UserDefaults.standard.object(forKey: "deviceToken") as? String { CardapioServices.shared.unregisterDeviceToken(token: token) UserDefaults.standard.set(nil, forKey: ALMOCO_TIME_KEY_STRING) UserDefaults.standard.set(nil, forKey: JANTAR_TIME_KEY_STRING) self.loadNotificationOptions() } else { print("Device token nao encontrado para ser removido") } } else { // Fallback on earlier versions } } tableView.reloadData() } @available(iOS 10.0, *) func registerForPushNotifications() { UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound]) { (granted, error) in // print("Permission granted: \(granted)") guard granted else { return } self.getNotificationSettings() } } @available(iOS 10.0, *) func getNotificationSettings() { UNUserNotificationCenter.current().getNotificationSettings { (settings) in // print("Notification settings: \(settings)") guard settings.authorizationStatus == .authorized else { return } // Executing is main queue because of warning from XCode 9 thread sanitizer. DispatchQueue.main.async { UIApplication.shared.registerForRemoteNotifications() // TODO: atualizar opcoes de notificacoes no User Defaults. if UserDefaults.standard.string(forKey: ALMOCO_TIME_KEY_STRING) == nil { print("Configurando horario para notificacao do almoco pela primeira vez") UserDefaults.standard.set("11:00", forKey: ALMOCO_TIME_KEY_STRING) } if UserDefaults.standard.string(forKey: JANTAR_TIME_KEY_STRING) == nil{ print("Configurando horario para notificacao do jantar pela primeira vez") UserDefaults.standard.set("17:00", forKey: JANTAR_TIME_KEY_STRING) } // atualizar UI. self.loadNotificationOptions() } } } // MARK: Time of notifications override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if let destiny = segue.destination as? NotificationTimeViewController { destiny.notificationTimeDisplayDelegate = self if segue.identifier == "SegueAlmocoTime" { destiny.refeicao = TipoRefeicao.almoco destiny.pickerTimeOptions = destiny.ALMOCO_TIME_OPTIONS //destiny.selectedTime = } if segue.identifier == "SegueJantarTime" { destiny.refeicao = TipoRefeicao.jantar destiny.pickerTimeOptions = destiny.JANTAR_TIME_OPTIONS } } } override func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { if #available(iOS 10, *) { } else { // ios 9 only if(section == 1){ return 0.01 } } return UITableViewAutomaticDimension } override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { if #available(iOS 9, *) { if #available(iOS 10, *) { } else { // ios 9 only if(section == 1){ return 0.01 } } } return UITableViewAutomaticDimension } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { var rows = [1,notificationSwitch.isOn ? 3 : 1,2] if #available(iOS 9, *) { if #available(iOS 10, *) { } else { // ios 9 only if(section == 1){ rows[section] = 0 } } } return rows[section] } override func tableView(_ tableView: UITableView, titleForFooterInSection section: Int) -> String? { var title = super.tableView(tableView, titleForFooterInSection: section) if #available(iOS 9, *) { if #available(iOS 10, *) { } else { // ios 9 only if section == 1 { title = "" } } } return title } override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { var title = super.tableView(tableView, titleForHeaderInSection: section) if #available(iOS 9, *) { if #available(iOS 10, *) { } else { // ios 9 only if section == 1 { title = "" } } } return title } } extension ConfiguracoesTableViewController: NotificationTimeDisplayDelegate { func updateTimeString(time: String, refeicao: TipoRefeicao) { let cell = refeicao == .almoco ? almocoNotificationCell : jantarNotificationCell cell?.detailTextLabel?.text = time } }
mit
10445774a509ef6b139d45ec729a7277
32.509868
161
0.558751
4.928399
false
false
false
false
ajohnson388/rss-reader
RSS Reader/RSS Reader/MockFactory.swift
1
895
// // MockFactory.swift // RSS Reader // // Created by Andrew Johnson on 9/17/16. // Copyright © 2016 Andrew Johnson. All rights reserved. // import Foundation struct MockFactory { static func generateMockFeeds() -> [Feed] { let titles = ["Space Station", "Agriculture", "Biosynthesis", "KOTR"] let subtitles = ["NASA", "FDA", "NIMH", "Thrasher"] let categories = ["Government", "Government", "Government", "Skateboarding"] let favorite = [true, false, false, true] var ret = [Feed]() for i in 0...3 { var feed = Feed() feed.title = titles[i] feed.subtitle = subtitles[i] feed.category = categories[i] feed.favorite = favorite[i] feed.url = URL(string: "https://www.google.com") ret.append(feed) } return ret } }
apache-2.0
5321b3c79bf0572c46507e63e0bc5880
26.9375
84
0.549217
3.853448
false
false
false
false
wikimedia/apps-ios-wikipedia
Wikipedia/Code/CircledRankView.swift
1
1828
class CircledRankView: SizeThatFitsView { fileprivate let label: UILabel = UILabel() let padding = UIEdgeInsets(top: 3, left: 3, bottom: 3, right: 3) public var rankColor: UIColor = .wmf_blue { didSet { guard !label.textColor.isEqual(rankColor) else { return } label.textColor = rankColor layer.borderColor = rankColor.cgColor } } override func setup() { super.setup() layer.borderWidth = 1 label.isOpaque = true addSubview(label) } var rank: Int = 0 { didSet { label.text = String.localizedStringWithFormat("%d", rank) setNeedsLayout() } } var labelBackgroundColor: UIColor? { didSet { label.backgroundColor = labelBackgroundColor } } override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) { super.traitCollectionDidChange(previousTraitCollection) label.font = UIFont.wmf_font(.footnote, compatibleWithTraitCollection: traitCollection) } override func sizeThatFits(_ size: CGSize, apply: Bool) -> CGSize { let insetSize = CGRect(origin: .zero, size: size).inset(by: padding) let labelSize = label.sizeThatFits(insetSize.size) if (apply) { layer.cornerRadius = 0.5*size.width label.frame = CGRect(origin: CGPoint(x: 0.5*size.width - 0.5*labelSize.width, y: 0.5*size.height - 0.5*labelSize.height), size: labelSize) } let width = labelSize.width + padding.left + padding.right let height = labelSize.height + padding.top + padding.bottom let dimension = max(width, height) return CGSize(width: dimension, height: dimension) } }
mit
4ee07025455ce5b20dcfb700cd3b90a0
34.153846
150
0.610503
4.675192
false
false
false
false
duliodenis/v
V/V/Infrastructure/Constants.swift
1
594
// // Constants.swift // V // // Created by Dulio Denis on 8/16/16. // Copyright © 2016 Dulio Denis. All rights reserved. // import UIKit // MARK: Colors let BUTTON_COLOR: UIColor = UIColor.flatWhite() let BUTTON_TITLE_COLOR: UIColor = UIColor.flatBlack() // MARK: Strings let STRING_SIGNUP_TEXT = "Sign-Up to V" let STRING_PHONE_NUMBER_ERROR = "Please include your phone number." let STRING_EMAIL_ERROR = "Please include your email address." let STRING_PASSWORD_ERROR = "Password must be at least six characters." // MARK: URLS let FIREBASE_URL = "https://<YOUR-DB>.firebaseio.com"
mit
71ac6c78386c8bfedfa00e70f6fbf6c2
22.76
71
0.713322
3.312849
false
false
false
false
tlax/GaussSquad
GaussSquad/Model/Settings/MSettings.swift
1
624
import Foundation class MSettings { let items:[MSettingsItem] init() { let itemVersion:MSettingsItemVersion = MSettingsItemVersion() let itemFractionDigits:MSettingsItemFractionDigits = MSettingsItemFractionDigits() let itemSupport:MSettingsItemSupport = MSettingsItemSupport() let itemReview:MSettingsItemReview = MSettingsItemReview() let itemShare:MSettingsItemShare = MSettingsItemShare() items = [ itemVersion, itemFractionDigits, itemSupport, itemReview, itemShare ] } }
mit
03937aed29f4be1a26a830732ab3c641
26.130435
90
0.642628
5.426087
false
false
false
false
quire-io/SwiftyChrono
Sources/Parsers/EN/ENWeekdayParser.swift
1
2977
// // ENWeekdayParser.swift // SwiftyChrono // // Created by Jerry Chen on 1/23/17. // Copyright © 2017 Potix. All rights reserved. // import Foundation private let PATTERN = "(\\W|^)" + "(?:(?:\\,|\\(|\\()\\s*)?" + "(?:on\\s*?)?" + "(?:(this|last|past|next)\\s*)?" + "(\(EN_WEEKDAY_OFFSET_PATTERN))" + "(?:\\s*(?:\\,|\\)|\\)))?" + "(?:\\s*(this|last|past|next)\\s*week)?" + "(?=\\W|$)" private let prefixGroup = 2 private let weekdayGroup = 3 private let postfixGroup = 4 public func updateParsedComponent(result: ParsedResult, ref: Date, offset: Int, modifier: String) -> ParsedResult { var result = result var startMoment = ref var startMomentFixed = false let refOffset = startMoment.weekday var weekday: Int if modifier == "last" || modifier == "past" { weekday = offset - 7 startMomentFixed = true } else if modifier == "next" { weekday = offset + 7 startMomentFixed = true } else if modifier == "this" { weekday = offset } else { if abs(offset - 7 - refOffset) < abs(offset - refOffset) { weekday = offset - 7 } else if abs(offset + 7 - refOffset) < abs(offset - refOffset) { weekday = offset + 7 } else { weekday = offset } } startMoment = startMoment.setOrAdded(weekday, .weekday) result.start.assign(.weekday, value: offset) if startMomentFixed { result.start.assign(.day, value: startMoment.day) result.start.assign(.month, value: startMoment.month) result.start.assign(.year, value: startMoment.year) } else { result.start.imply(.day, to: startMoment.day) result.start.imply(.month, to: startMoment.month) result.start.imply(.year, to: startMoment.year) } return result } public class ENWeekdayParser: Parser { override var pattern: String { return PATTERN } override public func extract(text: String, ref: Date, match: NSTextCheckingResult, opt: [OptionType: Int]) -> ParsedResult? { let (matchText, index) = matchTextAndIndex(from: text, andMatchResult: match) var result = ParsedResult(ref: ref, index: index, text: matchText) let dayOfWeek = match.string(from: text, atRangeIndex: weekdayGroup).lowercased() guard let offset = EN_WEEKDAY_OFFSET[dayOfWeek] else { return nil } let prefix: String? = match.isNotEmpty(atRangeIndex: prefixGroup) ? match.string(from: text, atRangeIndex: prefixGroup) : nil let postfix: String? = match.isNotEmpty(atRangeIndex: postfixGroup) ? match.string(from: text, atRangeIndex: postfixGroup) : nil let norm = (prefix ?? postfix ?? "").lowercased() result = updateParsedComponent(result: result, ref: ref, offset: offset, modifier: norm) result.tags[.enWeekdayParser] = true return result } }
mit
a31da42f9a051dd9069de1cbeb8990eb
33.16092
136
0.606999
3.95739
false
false
false
false
Eonil/HomeworkApp1
Modules/Monolith/CancellableBlockingIO/Sources/Trigger.swift
3
1163
// // SwitchAndWatch.swift // EonilCancellableBlockingIO // // Created by Hoon H. on 11/8/14. // Copyright (c) 2014 Eonil. All rights reserved. // import Foundation public final class Trigger { private var _flag = AtomicBoolSlot(false) private var _watches = [] as [WeakBox<Watch>] private let _sync = NSLock() public init() { } public var state:Bool { get { return _flag.value } } /// Becomes no-op after once set. public func set() { Debug.log("Cancellation triggered.") if _flag.compareAndSwapBarrier(oldValue: false, newValue: true) { for w1 in _watches { w1.value!._f() } } } public final class Watch { private let _f:()->() private let _t:Trigger private init(_ f:()->(), _ t:Trigger) { self._f = f self._t = t _t._sync.lock() _t._watches.append(WeakBox(self)) _t._sync.unlock() } deinit { _t._sync.lock() _t._watches = _t._watches.filter {$0.value != nil} _t._sync.unlock() } } } public extension Trigger { /// Watches for this trigger and runs supplied function /// when the trigger triggers. public func watch(f:()->()) -> Watch { return Watch(f, self) } }
mit
14d2cb4016c65cbd490907f6e16d5c4b
18.383333
67
0.618229
2.76247
false
false
false
false
Antondomashnev/Sourcery
SourceryTests/Stub/Performance-Code/Kiosk/App/Views/Text Fields/TextField.swift
2
3613
import UIKit class TextField: UITextField { var shouldAnimateStateChange: Bool = true var shouldChangeColorWhenEditing: Bool = true override init(frame: CGRect) { super.init(frame: frame) setup() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setup() } override func awakeFromNib() { super.awakeFromNib() setup() } func setup() { borderStyle = .none layer.cornerRadius = 0 layer.masksToBounds = true layer.borderWidth = 1 tintColor = .black font = UIFont.serifFont(withSize: self.font?.pointSize ?? 26) stateChangedAnimated(false) setupEvents() } func setupEvents () { addTarget(self, action: #selector(TextField.editingDidBegin(_:)), for: .editingDidBegin) addTarget(self, action: #selector(TextField.editingDidFinish(_:)), for: .editingDidEnd) } func editingDidBegin (_ sender: AnyObject) { stateChangedAnimated(shouldAnimateStateChange) } func editingDidFinish(_ sender: AnyObject) { stateChangedAnimated(shouldAnimateStateChange) } func stateChangedAnimated(_ animated: Bool) { let newBorderColor = borderColorForState().cgColor if newBorderColor == layer.borderColor { return } if animated { let fade = CABasicAnimation() if layer.borderColor == nil { layer.borderColor = UIColor.clear.cgColor } fade.fromValue = self.layer.borderColor ?? UIColor.clear.cgColor fade.toValue = newBorderColor fade.duration = AnimationDuration.Short layer.add(fade, forKey: "borderColor") } layer.borderColor = newBorderColor } func borderColorForState() -> UIColor { if isEditing && shouldChangeColorWhenEditing { return .artsyPurpleRegular() } else { return .artsyGrayMedium() } } func setBorderColor(_ color: UIColor) { self.layer.borderColor = color.cgColor } override func textRect(forBounds bounds: CGRect) -> CGRect { return bounds.insetBy(dx: 10, dy: 0 ) } override func editingRect(forBounds bounds: CGRect) -> CGRect { return bounds.insetBy(dx: 10, dy: 0 ) } } class SecureTextField: TextField { var actualText: String = "" override var text: String! { get { if isEditing { return super.text } else { return actualText } } set { super.text=(newValue) } } override func setup() { super.setup() clearsOnBeginEditing = true } override func setupEvents () { super.setupEvents() addTarget(self, action: #selector(SecureTextField.editingDidChange(_:)), for: .editingChanged) } override func editingDidBegin (_ sender: AnyObject) { super.editingDidBegin(sender) isSecureTextEntry = true actualText = text } func editingDidChange(_ sender: AnyObject) { actualText = text } override func editingDidFinish(_ sender: AnyObject) { super.editingDidFinish(sender) isSecureTextEntry = false actualText = text text = dotPlaceholder() } func dotPlaceholder() -> String { var index = 0 let dots = NSMutableString() while (index < text.count) { dots.append("•") index += 1 } return dots as String } }
mit
b0a4bf4e211868294185b6e122aa579d
25.166667
102
0.592634
4.987569
false
false
false
false
AndreMuis/TISensorTag
TISensorTag/Library/Extensions/TSTAnimationEngine+Common.swift
1
5041
// // TSTAnimationEngine+Common.swift // TISensorTag // // Created by Andre Muis on 5/22/16. // Copyright © 2016 Andre Muis. All rights reserved. // import SceneKit extension TSTAnimationEngine { func addLights(ambientLightColor ambientLightColor : UIColor, omnidirectionalLightColor : UIColor, omnidirectionalLightPosition : SCNVector3) { let omnidirectionalLight : SCNLight = SCNLight() omnidirectionalLight.type = SCNLightTypeOmni omnidirectionalLight.color = omnidirectionalLightColor let omnidirectionalLightNode : SCNNode = SCNNode() omnidirectionalLightNode.light = omnidirectionalLight omnidirectionalLightNode.position = omnidirectionalLightPosition self.scene.rootNode.addChildNode(omnidirectionalLightNode) let ambientLight : SCNLight = SCNLight() ambientLight.type = SCNLightTypeAmbient ambientLight.color = ambientLightColor let ambientLightNode = SCNNode() ambientLightNode.light = ambientLight self.scene.rootNode.addChildNode(ambientLightNode) } func addSensorTag(eulerAngles eulerAngles : SCNVector3, width : CGFloat, height : CGFloat, depth : CGFloat, chamferRadius : CGFloat, holeDiameter : CGFloat, holeVerticalDisplacement : CGFloat, coverColor : UIColor, baseColor : UIColor, holeColor : UIColor) { let coverMaterial : SCNMaterial = SCNMaterial() coverMaterial.diffuse.contents = coverColor coverMaterial.specular.contents = UIColor.whiteColor() let baseMaterial : SCNMaterial = SCNMaterial() baseMaterial.diffuse.contents = baseColor baseMaterial.specular.contents = UIColor.whiteColor() let sensorTagGeometry : SCNBox = SCNBox(width: width, height: height, length: depth, chamferRadius: chamferRadius) sensorTagGeometry.materials = [coverMaterial, coverMaterial, baseMaterial, coverMaterial, coverMaterial, baseMaterial] self.sensorTagNode.geometry = sensorTagGeometry let holeMaterial : SCNMaterial = SCNMaterial() holeMaterial.diffuse.contents = holeColor holeMaterial.specular.contents = UIColor.whiteColor() let cylinder : SCNCylinder = SCNCylinder(radius: holeDiameter / 2.0, height: depth / 2.0) cylinder.materials = [holeMaterial] let holeNode = SCNNode(geometry: cylinder) holeNode.position = SCNVector3(0.0, holeVerticalDisplacement, depth / 4.0 + 0.01) holeNode.eulerAngles = SCNVector3(Float(M_PI) / 2.0, 0.0, 0.0) self.sensorTagNode.addChildNode(holeNode) self.sensorTagNode.eulerAngles = eulerAngles self.scene.rootNode.addChildNode(self.sensorTagNode) } func addAxes(axisLength axisLength : Float, axisRadius : Float) { let xAxisGeometry : SCNCylinder = SCNCylinder(radius: CGFloat(axisRadius), height: CGFloat(axisLength)) let xAxisNode = SCNNode(geometry: xAxisGeometry) xAxisNode.position = SCNVector3(x: axisLength / 2.0, y: 0.0, z: 0.0) xAxisNode.rotation = SCNVector4(0.0, 0.0, 1.0, M_PI / 2.0) self.scene.rootNode.addChildNode(xAxisNode) let yAxisGeometry : SCNCylinder = SCNCylinder(radius: CGFloat(axisRadius), height: CGFloat(axisLength)) let yAxisNode = SCNNode(geometry: yAxisGeometry) yAxisNode.position = SCNVector3(x: 0.0, y: axisLength / 2.0, z: 0.0) self.scene.rootNode.addChildNode(yAxisNode) let zAxisGeometry : SCNCylinder = SCNCylinder(radius: CGFloat(axisRadius), height: CGFloat(axisLength)) let zAxisNode = SCNNode(geometry: zAxisGeometry) zAxisNode.position = SCNVector3(x: 0.0, y: 0.0, z: axisLength / 2.0) zAxisNode.rotation = SCNVector4(1.0, 0.0, 0.0, M_PI / 2.0) self.scene.rootNode.addChildNode(zAxisNode) } }
mit
7ab758dd8f946964cb3433528a2b9a5e
32.6
126
0.5375
5.436893
false
false
false
false
edmw/Volumio_ios
Volumio/BundleInfo.swift
1
2478
// // BundleInfo.swift // // Created by Michael Baumgärtner on 25.11.16. // Copyright © 2016 Michael Baumgärtner. All rights reserved. // import Foundation /// Statically-typed Bundle info dictionary public struct SafeBundleInfo { fileprivate let bundle: Bundle fileprivate init(_ bundle: Bundle) { self.bundle = bundle } public class Proxy { fileprivate let info: [String:Any] fileprivate let key: String fileprivate init(_ info: [String:Any], _ key: String) { self.info = info self.key = key } public var string: String? { return info[key] as? String } public var int: Int? { return info[key] as? Int } } public subscript(key: String) -> Proxy? { guard let info = bundle.infoDictionary else { return nil } return Proxy(info, key) } public subscript(key: String) -> Any? { let proxy: Proxy? = self[key] return proxy } public func has(key: String) -> Bool { guard let info = bundle.infoDictionary else { return false } return info[key] != nil } } // global bundle info public let BundleInfo = SafeBundleInfo(Bundle.main) // keys public class InfoKeys { fileprivate init() {} } // generic key public class InfoKey<ValueType>: InfoKeys { public let key: String public init(_ key: String) { self.key = key super.init() } public convenience init(_ uuid: UUID) { self.init(uuid.uuidString) } } // generic functions extension SafeBundleInfo { public func has<T>(key: InfoKey<T>) -> Bool { guard let info = bundle.infoDictionary else { return false } return info[key.key] != nil } } // typed subscripts extension SafeBundleInfo { public subscript(key: InfoKey<String?>) -> String? { return self[key.key]?.string } public subscript(key: InfoKey<String>) -> String { return self[key.key]?.string ?? "" } public subscript(key: InfoKey<Int?>) -> Int? { return self[key.key]?.int } public subscript(key: InfoKey<Int>) -> Int { return self[key.key]?.int ?? 0 } } // defined keys extension InfoKeys { static let bundleIdentifier = InfoKey<String?>("CFBundleIdentifier") static let bundleName = InfoKey<String?>("CFBundleName") static let bundleVersion = InfoKey<String?>("CFBundleVersion") }
gpl-3.0
97a0ac083de8211c1221c899c62e6472
19.798319
72
0.606465
4.011345
false
false
false
false
mikelikespie/swiftled
src/main/swift/Visualizations/MyShape.swift
1
11578
// // Shape.swift // swiftled-2 // // Created by Michael Lewis on 8/3/16. // // import Foundation import OPC import Cleanse private enum Direction { case Forward case Reverse var complement: Direction { switch self { case .Forward: return .Reverse case .Reverse: return .Forward } } } // Edge in a directional graph struct Edge : DelegatedHashable { var a: Int var b: Int init(a: Int, b: Int) { self.a = a self.b = b } var hashable: CombinedHashable<Int, Int> { return CombinedHashable(a, b) } var complement: Edge { return Edge(a: b, b: a) } } private let edgeToVertices : [(Int, Int)] = [ (0, 1), // 0 (0, 2), (0, 3), (0, 4), (0, 5), // 4 (1, 2), // 5 (2, 3), (3, 4), (4, 5), (5, 1), // 9 (1, 6), // 10 (2, 7), (3, 8), (4, 9), (5, 10), // 14 (1, 10), // 15 (2, 6), (3, 7), (4, 8), (5, 9), // 19 (9, 10), // 20 (10, 6), (6, 7), (7, 8), (8, 9), // 24 (9, 11), // 25 (10, 11), (6, 11), (7, 11), (8, 11), // 29 ] private let edgeToSegmentMappingIndex: [Edge: Int] = { var result = [Edge: Int]() for (i, (a, b)) in edgeToVertices.enumerated() { result[Edge(a: a, b: b)] = i } return result }() struct Face: DelegatedHashable { let a: Int let b: Int let c: Int var hashable: CombinedHashable<CombinedHashable<Int, Int>, Int> { return CombinedHashable(CombinedHashable(a, b), c) } init(a: Int, b: Int, c: Int) { let minVertex = min(a, b, c) switch minVertex { case a: self.a = a self.b = b self.c = c case b: self.a = b self.b = c self.c = a case c: self.a = c self.b = a self.c = b default: fatalError() } } var edges: (a: Edge, b: Edge, c: Edge) { return ( Edge(a: a, b: b), Edge(a: b, b: c), Edge(a: c, b: a) ) } } private let allEdges: Set<Edge> = { var edges = Set<Edge>(minimumCapacity: edgeToVertices.count * 2) for e in edgeToVertices { let e1 = Edge(a: e.0, b: e.1) let e2 = e1.complement edges.insert(e1) edges.insert(e2) } return edges }() private let edgesByOriginatingVertex: [Set<Int>] = { var result = [Set<Int>](repeating: [], count: 12) for e in allEdges { result[e.a].insert(e.b) } return result }() private func calculateAllFaces(edgeToVertices: [(Int, Int)]) -> Set<Face> { var result = Set<Face>(minimumCapacity: 40) for (v_a, edges) in edgesByOriginatingVertex.enumerated() { for v_b in edges { for v_c in edgesByOriginatingVertex[v_b] { guard edgesByOriginatingVertex[v_c].contains(v_a) else { continue } result.insert(Face(a: v_a, b: v_b, c: v_c)) } } } return result } private let allFaces = calculateAllFaces(edgeToVertices: edgeToVertices) private let segmentMap: [(Direction, Int)] = [ (.Forward, 0), (.Reverse, 2), (.Forward, 9), (.Reverse, 8), (.Forward, 3), (.Forward, 1), (.Forward, 17), (.Forward, 10), (.Reverse, 7), (.Forward, 4), (.Reverse, 15), (.Reverse, 28), (.Forward, 18), (.Forward, 11), (.Reverse, 6), (.Forward, 5), (.Reverse, 16), (.Reverse, 29), (.Forward, 19), (.Reverse, 12), (.Forward, 13), (.Forward, 14), (.Forward, 27), (.Reverse, 24), (.Forward, 20), (.Forward, 21), (.Reverse, 22), (.Reverse, 26), (.Forward, 25), (.Reverse, 23), ] private let inverseSegmentMap = segmentMap .enumerated() .sorted { $0.1.1 < $1.1.1 } .map { ($0.1.0, $0.0) } private func segment(edge: Edge) -> (Direction, Int) { let direction: Direction let segmentMappingIndex: Int if let mappingIndex = edgeToSegmentMappingIndex[edge] { segmentMappingIndex = mappingIndex direction = .Forward } else { segmentMappingIndex = edgeToSegmentMappingIndex[edge.complement]! direction = .Reverse } return (direction, segmentMappingIndex) } struct ShapeSegmentString : Collection { var startIndex: Int { return 0 } var endIndex: Int { return count - 1 } var count: Int { return segmentLength * segmentIndexes.count } func index(after i: Int) -> Int { return i.advanced(by: 1) } let segmentIndexes: [Int] unowned let shape: MyShape let segmentLength: Int subscript(index: Int) -> RGBFloat { get { return shape.buffer[bufferIndex(segmentIndex: index)] } set { shape.buffer[bufferIndex(segmentIndex: index)] = newValue } } private func bufferIndex(segmentIndex: Int) -> Int { return segmentIndexes[segmentIndex / segmentLength] * segmentLength + segmentIndex % segmentLength } } final class MyShape { var buffer: [RGBFloat] let ledCount: Int let segmentLength: Int let segmentCount: Int let faces: [Face] var faceBuffer: [RGBAFloat] var edgeBuffer: [RGBAFloat] public init( ledCount: TaggedProvider<LedCount>, segmentLength: TaggedProvider<SegmentLength>, segmentCount: TaggedProvider<SegmentCount>) { self.ledCount = ledCount.get() self.segmentLength = segmentLength.get() self.segmentCount = segmentCount.get() self.buffer = Array(repeating: .black, count: self.ledCount) self.faceBuffer = Array(repeating: .clear, count: self.segmentLength * 3) self.edgeBuffer = Array(repeating: .clear, count: self.segmentLength) self.faces = Array(allFaces) } func clear() { self.buffer.withUnsafeMutableBufferPointer { ptr in let ptr = ptr applyOverRange(ptr.indices) { bounds in for i in bounds { ptr[i] = .black } } } } private func remapLed(_ index: Int) -> Int { let virtualSegment = index / segmentLength let mapping = inverseSegmentMap[virtualSegment] let segmentOffset: Int let physicalSegment: Int switch mapping { case let (.Forward, physicalSegment_): physicalSegment = physicalSegment_ segmentOffset = index % segmentLength case let (.Reverse, physicalSegment_): physicalSegment = physicalSegment_ segmentOffset = segmentLength - (index % segmentLength) - 1 } return physicalSegment * segmentLength + segmentOffset } func withSegment(segment: Int, closure: ( _ ptr: inout UnsafeMutableBufferPointer<RGBFloat>) -> () ) { let segmentOffset = segment * segmentLength self .buffer[segmentOffset..<(segmentOffset + segmentLength)] .withUnsafeMutableBufferPointer { ( ptr: inout UnsafeMutableBufferPointer<RGBFloat>) -> () in closure(&ptr) return () } } func withGroup(group: Int, closure: ( _ ptr: inout UnsafeMutableBufferPointer<RGBFloat>) -> () ) { let segmentOffset = group * 5 * segmentLength self .buffer[segmentOffset..<(segmentOffset + segmentLength * 5)] .withUnsafeMutableBufferPointer { ( ptr: inout UnsafeMutableBufferPointer<RGBFloat>) -> () in closure(&ptr) return () } } func withFace(face: Int, closure: ( _ ptr: inout UnsafeMutableBufferPointer<RGBAFloat>) -> () ) { faceBuffer.replaceSubrange(0..<faceBuffer.count, with: repeatElement(.clear, count: faceBuffer.count)) faceBuffer .withUnsafeMutableBufferPointer { ptr in closure(&ptr) } let face = self.faces[face] let (edgeA, edgeB, edgeC) = face.edges for (i, edge) in [edgeA, edgeB, edgeC].enumerated() { let (direction, segmentIndex) = segment(edge: edge) let bufferRange = range(segment: segmentIndex) let faceBufferRange = range(segment: i) // buffer.withUnsafeMutableBufferPointer { ptr in // ptr[bufferRange].merge(other: faceBuffer[faceBufferRange]) // } switch direction { case .Forward: for (bi, fbi) in zip(bufferRange, faceBufferRange) { buffer[bi] += faceBuffer[fbi] } case .Reverse: for (bi, fbi) in zip(bufferRange, faceBufferRange.reversed()) { buffer[bi] += faceBuffer[fbi] } } } } private func range(segment: Int) -> CountableRange<Int> { let segmentStart = segment * segmentLength return segmentStart..<(segmentStart + segmentLength) } func withSegments(closure: ( _ segment: Int, _ ptr: inout UnsafeMutableBufferPointer<RGBFloat>) -> () ) { for segment in 0..<segmentCount { withSegment(segment: segment) { closure(segment, &$0) } } } func withEdges(adjacentToVertex vertex: Int, closure: (_ edge: Edge, _ ptr: inout UnsafeMutableBufferPointer<RGBAFloat>) -> ()) { let adjacentVertices = edgesByOriginatingVertex[vertex] for b in adjacentVertices { let edge = Edge(a: vertex, b: b) withEdge(edge: edge) { ptr in closure(edge, &ptr) } } } func withEdge(edge: Edge, closure: (_ ptr: inout UnsafeMutableBufferPointer<RGBAFloat>) -> ()) { edgeBuffer.replaceSubrange(0..<edgeBuffer.count, with: repeatElement(.clear, count: edgeBuffer.count)) edgeBuffer .withUnsafeMutableBufferPointer { ptr in closure(&ptr) } let (direction, segmentIndex) = segment(edge: edge) let bufferRange = range(segment: segmentIndex) switch direction { case .Forward: for (bi, fbi) in zip(bufferRange, edgeBuffer.indices) { buffer[bi] += edgeBuffer[fbi] } case .Reverse: for (bi, fbi) in zip(bufferRange, edgeBuffer.indices.reversed()) { buffer[bi] += edgeBuffer[fbi] } } } func copyToBuffer(buffer: UnsafeMutableBufferPointer<RGBFloat>) { self.buffer.withUnsafeBufferPointer { ptr in applyOverRange(buffer.indices) { bounds in let buffer = buffer for idx in bounds { buffer[idx] = ptr[self.remapLed(idx)] } } } } struct Module : Cleanse.Module { static func configure(binder: Binder<Unscoped>) { binder.bind().to(factory: MyShape.init) } } }
mit
d82ce69e53635791fb56a2239357b97c
24.279476
133
0.525652
4.137956
false
false
false
false
esttorhe/RxSwift
RxSwift/RxSwift/RxResult.swift
1
8058
// // RxResult.swift // Rx // // Created by Krunoslav Zaher on 2/12/15. // Copyright (c) 2015 Krunoslav Zaher. All rights reserved. // import Foundation // Represents computation result. // // The result can be either successful or failure. // // It's a port of Scala (originally Twitter) `Try` type // http://www.scala-lang.org/api/2.10.2/index.html#scala.util.Try // The name `Result` was chosen because it better describes it's common usage. // // The reason why it's named differently is because `Try` doesn't make sense in the context // of swift. // // In scala it would be used like `Try { throw new Exception("oh dear") }` // // The reason why `Result` has `Rx` prefix is because there could be name collisions with other // result types. // public enum RxResult<T> { // Box is used is because swift compiler doesn't know // how to handle `Success(ResultType)` and it crashes. case Success(T) case Failure(ErrorType) } extension RxResult { // Returns true if `self` is a `Success`, false otherwise. public var isSuccess: Bool { get { switch self { case .Success: return true default: return false } } } // Returns true if `self` is a `Failure`, false otherwise. public var isFailure: Bool { get { switch self { case .Failure: return true default: return false } } } // Returns the given function applied to the value from `Success` or returns `self` if this is a `Failure`. public func flatMap<U>(@noescape f: T -> RxResult<U>) -> RxResult<U> { switch self { case .Success(let value): return f(value) case .Failure(let error): return failure(error) } } // Maps the given function to the value from `Success` or returns `self` if this is a `Failure`. public func map<U>(@noescape f: T -> U) -> RxResult<U> { switch self { case .Success(let value): return success(f(value)) case .Failure(let error): return failure(error) } } // Applies the given function `f` if this is a `Failure`, otherwise returns `self` if this is a `Success`. public func recover(@noescape f: (ErrorType) -> T) -> RxResult<T> { switch self { case .Success(_): return self case .Failure(let error): return success(f(error)) } } // Applies the given function `f` if this is a `Failure`, otherwise returns `self` if this is a `Success`. public func recoverWith(@noescape f: (ErrorType) -> RxResult<T>) -> RxResult<T> { switch self { case .Success(_): return self case .Failure(let error): return f(error) } } // Returns the value if `Success` or throws the exception if this is a Failure. public func get() -> T { switch self { case .Success(let value): return value case .Failure(let error): rxFatalError("Result represents failure: \(error)") return (nil as T?)! } } // Returns the value if `Success` or the given `defaultValue` if this is a `Failure`. public func getOrElse(defaultValue: T) -> T { switch self { case .Success(let value): return value case .Failure(_): return defaultValue } } // Returns `self` if `Success` or the given `defaultValue` if this is a `Failure`. public func getOrElse(defaultValue: RxResult<T>) -> RxResult<T> { switch self { case .Success(_): return self case .Failure(_): return defaultValue } } // Returns `nil` if this is a `Failure` or a `T` containing the value if this is a `Success` public func toOptional() -> T? { switch self { case .Success(let value): return value case .Failure(_): return nil } } } // convenience constructor public func success<T>(value: T) -> RxResult<T> { return .Success(value) } public func failure<T>(error: ErrorType) -> RxResult<T> { return .Failure(error) } public let SuccessResult = success(()) // lift functions // "Lifts" functions that take normal arguments to functions that take `Result` monad arguments. // Unfortunately these are not generic `Monad` lift functions because // Creating generic lift functions that work for arbitrary monads is a lot more tricky. func lift<T1, TRet>(function: (T1) -> TRet) -> (RxResult<T1>) -> RxResult<TRet> { return { arg1 in return arg1.map { value1 in return function(value1) } } } func lift<T1, T2, TRet>(function: (T1, T2) -> TRet) -> (RxResult<T1>, RxResult<T2>) -> RxResult<TRet> { return { arg1, arg2 in return arg1.flatMap { value1 in return arg2.map { value2 in return function(value1, value2) } } } } func lift<T1, T2, T3, TRet>(function: (T1, T2, T3) -> TRet) -> (RxResult<T1>, RxResult<T2>, RxResult<T3>) -> RxResult<TRet> { return { arg1, arg2, arg3 in return arg1.flatMap { value1 in return arg2.flatMap { value2 in return arg3.map { value3 in return function(value1, value2, value3) } } } } } // depricated @available(*, deprecated=1.4, message="Replaced by success") public func `return`<T>(value: T) -> RxResult<T> { return .Success(value) } infix operator >== { associativity left precedence 95 } @available(*, deprecated=1.4, message="Replaced by flatMap") public func >== <In, Out>(lhs: RxResult<In>, @noescape rhs: (In) -> RxResult<Out>) -> RxResult<Out> { switch lhs { case .Success(let result): return rhs(result) case .Failure(let error): return .Failure(error) } } @available(*, deprecated=1.4, message="Replaced by map") public func >== <In, Out>(lhs: RxResult<In>, @noescape rhs: (In) -> Out) -> RxResult<Out> { switch lhs { case .Success(let result): return success(rhs(result)) case .Failure(let error): return .Failure(error) } } infix operator >>> { associativity left precedence 95 } @available(*, deprecated=1.4, message="Replaced by map") public func >>> <In, Out>(lhs: RxResult<In>, @noescape rhs: () -> Out) -> RxResult<Out> { switch lhs { case .Success: return success(rhs()) case .Failure(let error): return .Failure(error) } } @available(*, deprecated=1.4, message="Replaced by flatMap") public func >>> <In, Out>(lhs: RxResult<In>, @noescape rhs: () -> RxResult<Out>) -> RxResult<Out> { switch lhs { case .Success: return rhs() case .Failure(let error): return .Failure(error) } } infix operator >>! { associativity left precedence 95 } @available(*, deprecated=1.4, message="Replaced by recoverWith") public func >>! <In>(lhs: RxResult<In>, @noescape rhs: (ErrorType) -> RxResult<In>) -> RxResult<In> { switch lhs { case .Failure(let error): return rhs(error) default: return lhs } } prefix operator * { } @available(*, deprecated=1.4, message="Replaced by get") public prefix func *<T>(result: RxResult<T>) -> T { switch result { case .Success(let value): return value default: let result: T? = nil return result! } } @available(*, deprecated=1.4, message="Replaced by recover") public func replaceErrorWith<T>(result: RxResult<T>, errorValue: T) -> T { switch result { case .Success(let value): return value case .Failure: return errorValue } } @available(*, deprecated=1.4, message="Replaced by recoverWith") public func replaceErrorWithNil<T>(result: RxResult<T>) -> T? { switch result { case .Success(let value): return value case .Failure: return nil } }
mit
ab6756286a83160fe3b7de7854b62505
28.195652
125
0.593323
3.902179
false
false
false
false
brave/browser-ios
Client/Frontend/Browser/BrowserViewController/BrowserViewController+ToolbarAndUrlbarDelegate.swift
1
9718
/* 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 Shared import Storage private let log = Logger.browserLogger extension BrowserViewController: URLBarDelegate { fileprivate func showSearchController() { if searchController != nil { return } let isPrivate = tabManager.selectedTab?.isPrivate ?? false searchController = SearchViewController(isPrivate: isPrivate) searchController!.searchEngines = profile.searchEngines searchController!.searchDelegate = self //searchController!.profile = self.profile searchLoader.addListener(searchController!) addChildViewController(searchController!) view.addSubview(searchController!.view) searchController!.view.snp.makeConstraints { make in make.top.equalTo(self.header.snp.bottom) make.left.right.bottom.equalTo(self.view) return } homePanelController?.view?.isHidden = true searchController!.didMove(toParentViewController: self) } fileprivate func hideSearchController() { if let searchController = searchController { searchController.willMove(toParentViewController: nil) searchController.view.removeFromSuperview() searchController.removeFromParentViewController() self.searchController = nil homePanelController?.view?.isHidden = false } } func cancelSearch() { urlBar.leaveSearchMode() hideSearchController() updateInContentHomePanel(tabManager.selectedTab?.url) } func urlBarDidPressReload(_ urlBar: URLBarView) { tabManager.selectedTab?.reload() } func urlBarDidPressStop(_ urlBar: URLBarView) { tabManager.selectedTab?.stop() } func urlBarDidPressTabs(_ urlBar: URLBarView) { self.webViewContainerToolbar.isHidden = true updateFindInPageVisibility(false) let tabTrayController = self.tabTrayController ?? TabTrayController(tabManager: tabManager, profile: profile, tabTrayDelegate: self) for t in tabManager.tabs.internalTabList { screenshotHelper.takeScreenshot(t) } tabTrayController.modalPresentationStyle = .overCurrentContext tabTrayController.modalTransitionStyle = .crossDissolve // Allowing the tab tray to handle its own animation self.navigationController?.present(tabTrayController, animated: false, completion: nil) self.tabTrayController = tabTrayController } func urlBarDidPressReaderMode(_ urlBar: URLBarView) { if let tab = tabManager.selectedTab { if let readerMode = tab.getHelper(ReaderMode.self) { switch readerMode.state { case .Available: enableReaderMode() case .Active: disableReaderMode() case .Unavailable: break } } } } func urlBarDidLongPressReaderMode(_ urlBar: URLBarView) -> Bool { guard let tab = tabManager.selectedTab, let url = tab.displayURL, let result = profile.readingList?.createRecordWithURL(url.absoluteString, title: tab.title ?? "", addedBy: UIDevice.current.name) else { UIAccessibilityPostNotification(UIAccessibilityAnnouncementNotification, Strings.Could_not_add_page_to_Reading_List) return false } switch result { case .success: UIAccessibilityPostNotification(UIAccessibilityAnnouncementNotification, Strings.Added_page_to_reading_list) // TODO: https://bugzilla.mozilla.org/show_bug.cgi?id=1158503 provide some form of 'this has been added' visual feedback? case .failure(let error): UIAccessibilityPostNotification(UIAccessibilityAnnouncementNotification, Strings.Could_not_add_page_to_Reading_List) log.error("readingList.createRecordWithURL(url: \"\(url.absoluteString)\", ...) failed with error: \(error)") } return true } func locationActionsForURLBar(_ urlBar: URLBarView) -> [AccessibleAction] { if UIPasteboard.general.string != nil { return [pasteGoAction, pasteAction, copyAddressAction] } else { return [copyAddressAction] } } func urlBarDisplayTextForURL(_ url: URL?) -> String? { // use the initial value for the URL so we can do proper pattern matching with search URLs var searchURL = self.tabManager.selectedTab?.currentInitialURL if searchURL == nil || ErrorPageHelper.isErrorPageURL(searchURL!) { searchURL = url } return profile.searchEngines.queryForSearchURL(searchURL) ?? url?.absoluteString } func urlBarDidLongPressLocation(_ urlBar: URLBarView) { let longPressAlertController = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet) for action in locationActionsForURLBar(urlBar) { longPressAlertController.addAction(action.alertAction(style: .default)) } let cancelAction = UIAlertAction(title: Strings.Cancel, style: .cancel, handler: { (alert: UIAlertAction) -> Void in }) longPressAlertController.addAction(cancelAction) let setupPopover = { [unowned self] in if let popoverPresentationController = longPressAlertController.popoverPresentationController { popoverPresentationController.sourceView = urlBar popoverPresentationController.sourceRect = urlBar.frame popoverPresentationController.permittedArrowDirections = .any popoverPresentationController.delegate = self } } setupPopover() if longPressAlertController.popoverPresentationController != nil { displayedPopoverController = longPressAlertController updateDisplayedPopoverProperties = setupPopover } self.present(longPressAlertController, animated: true, completion: nil) } func urlBarDidPressScrollToTop(_ urlBar: URLBarView) { if let selectedTab = tabManager.selectedTab { // Only scroll to top if we are not showing the home view controller if homePanelController == nil { selectedTab.webView?.scrollView.setContentOffset(CGPoint.zero, animated: true) } } } func urlBarLocationAccessibilityActions(_ urlBar: URLBarView) -> [UIAccessibilityCustomAction]? { return locationActionsForURLBar(urlBar).map { $0.accessibilityCustomAction } } func urlBar(_ urlBar: URLBarView, didEnterText text: String) { searchLoader.query = text if text.isEmpty { hideSearchController() } else { showSearchController() searchController!.searchQuery = text } } func urlBar(_ urlBar: URLBarView, didSubmitText text: String) { // If we can't make a valid URL, do a search query. // If we still don't have a valid URL, something is broken. Give up. guard let url = URIFixup.getURL(text) ?? profile.searchEngines.defaultEngine().searchURLForQuery(text) else { log.error("Error handling URL entry: \"\(text)\".") return } finishEditingAndSubmit(url) } func urlBarDidEnterSearchMode(_ urlBar: URLBarView) { showHomePanelController(false) } func urlBarDidLeaveSearchMode(_ urlBar: URLBarView) { hideSearchController() updateInContentHomePanel(tabManager.selectedTab?.url) } } extension BrowserViewController: BrowserToolbarDelegate { func browserToolbarDidPressBack(_ browserToolbar: BrowserToolbarProtocol, button: UIButton) { tabManager.selectedTab?.goBack() } func browserLocationViewDidPressReload(_ browserToolbar: BrowserToolbarProtocol, button: UIButton) { tabManager.selectedTab?.reload() } func browserLocationViewDidPressStop(_ browserToolbar: BrowserToolbarProtocol, button: UIButton) { tabManager.selectedTab?.stop() } func browserToolbarDidPressForward(_ browserToolbar: BrowserToolbarProtocol, button: UIButton) { tabManager.selectedTab?.goForward() } func browserToolbarDidPressBookmark(_ browserToolbar: BrowserToolbarProtocol, button: UIButton) { guard let tab = tabManager.selectedTab, let url = tab.url else { log.error("Bookmark error: No tab is selected, or no URL in tab.") return } let isBookmarked = Bookmark.contains(url: url) if isBookmarked { self.removeBookmark(url) } else { self.addBookmark(url, title: tab.title) } } func browserToolbarDidPressShare(_ browserToolbar: BrowserToolbarProtocol, button: UIButton) { if let tab = tabManager.selectedTab, let url = tab.displayURL { let sourceView = self.navigationToolbar.shareButton presentActivityViewController(url, tab: tab, sourceView: sourceView.superview, sourceRect: sourceView.frame, arrowDirection: .up) } } func browserToolbarDidPressPwdMgr(browserToolbar: BrowserToolbarProtocol, button: UIButton) { if let loginsHelper = tabManager.selectedTab?.getHelper(LoginsHelper.self) { loginsHelper.onExecuteTapped(button) } } }
mpl-2.0
41ccd4929cb1ab64fda5ddecc09b182d
38.028112
198
0.664026
5.97663
false
false
false
false
CanBeMyQueen/DouYuZB
DouYu/DouYu/Classes/Home/View/RecommendClclesView.swift
1
3837
// // RecommendClclesView.swift // DouYu // // Created by 张萌 on 2017/10/17. // Copyright © 2017年 JiaYin. All rights reserved. // import UIKit private let kCycleCellID = "kCycleCellID" private let kCycleViewHeight : CGFloat = kScreenW * 3 / 8 class RecommendClclesView: UIView { /// 定义定时器 var cycleTimer : Timer? var cycleModles : [CycleModel]? { didSet { collectionView.reloadData() pageControl.numberOfPages = cycleModles?.count ?? 0 let indexPath = IndexPath(item: (cycleModles?.count ?? 0) * 1000, section: 0) collectionView.scrollToItem(at: indexPath, at: .left, animated: false) removeCycleTimer() addCycleTimer() } } // 属性控件 @IBOutlet weak var collectionView: UICollectionView! @IBOutlet weak var pageControl: UIPageControl! override func awakeFromNib() { super.awakeFromNib() // 设置控件不随着父控件的拉伸而拉伸 // self.autoresizingMask = autoresizingNone // 注册 cell collectionView.register(UINib(nibName: "CycleCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: kCycleCellID) } override func layoutSubviews() { super.layoutSubviews() // 设置 collectionView的 layout let layout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout layout.minimumLineSpacing = 0 layout.minimumInteritemSpacing = 0 layout.itemSize = collectionView.bounds.size layout.scrollDirection = .horizontal collectionView.isPagingEnabled = true collectionView.delegate = self; } } // 提供一个快速创建 View 的类方法 extension RecommendClclesView { class func recommendCyclesView() -> RecommendClclesView { return Bundle.main.loadNibNamed("RecommendClclesView", owner: nil, options: nil)?.first as! RecommendClclesView } } // UICollectionViewDataSource 协议 extension RecommendClclesView : UICollectionViewDataSource { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return (cycleModles?.count ?? 0) * 100000 } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: kCycleCellID, for: indexPath) as! CycleCollectionViewCell cell.cycleModel = cycleModles![indexPath.item % cycleModles!.count] return cell } } extension RecommendClclesView : UICollectionViewDelegate { func scrollViewDidScroll(_ scrollView: UIScrollView) { let offsetX = scrollView.contentOffset.x + scrollView.bounds.size.width * 0.5 pageControl.currentPage = Int(offsetX / scrollView.bounds.size.width) % (cycleModles?.count ?? 1) } func scrollViewWillBeginDragging(_ scrollView: UIScrollView) { removeCycleTimer() } func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) { addCycleTimer() } } /// 对定时器的操作方法 extension RecommendClclesView { private func addCycleTimer() { cycleTimer = Timer(timeInterval: 3.0, target: self, selector: #selector(self.scrollToNext), userInfo: nil, repeats: true) RunLoop.main.add(cycleTimer!, forMode: RunLoopMode.commonModes) } private func removeCycleTimer() { cycleTimer?.invalidate() /// 从运行循环中移出 cycleTimer = nil } @objc private func scrollToNext() { let currentOffsetX = collectionView.contentOffset.x let offsetX = currentOffsetX + collectionView.bounds.size.width collectionView.setContentOffset(CGPoint(x:offsetX, y: 0), animated: true) } }
mit
0dc70bb8bf88ef19ecdfa488b1812df3
33.018349
132
0.693905
4.950601
false
false
false
false
diversario/floating-image-views
FloatingImageViews/FloatingImageViews.swift
1
4836
// // File.swift // animation-test // // Created by Ilya Shaisultanov on 1/21/16. // Copyright © 2016 Ilya Shaisultanov. All rights reserved. // import Foundation import UIKit class FloatingImageViews { private var _views: [UIView] private let _superview: UIView private let _speed: Double private let _speed_variance: Double private var _view_speeds: [CGFloat] private let _alpha_base: Double private let _alpha_variance: Double private let _scale_base: CGFloat private let _scale_variance: CGFloat private let _image: UIImage? private var _stop = false init (superview: UIView, imageName: String, speedBase: Double = 10, speedVariance: Double = 20, alphaBase: Double = 0.5, alphaVariance: Double = 0.2, scaleBase: Double = 1, scaleVariance: Double = 1) { self._superview = superview //self._imgName = imageName self._image = UIImage(named: imageName) self._views = [UIView]() self._speed = speedBase < 1 ? 1 : speedBase self._speed_variance = speedVariance self._view_speeds = [CGFloat]() self._alpha_base = alphaBase self._alpha_variance = alphaVariance self._scale_base = CGFloat(scaleBase) self._scale_variance = CGFloat(scaleVariance) } func animate (numberOfViews: Int) { for _ in 0...numberOfViews { let v = self._createView() self._configureView(v) self._views.append(v) self._superview.addSubview(v) _view_speeds.append(CGFloat(self._getValueWithVariance(self._speed, range: self._speed_variance))) _move(v, cb: _recycle) } } func fadeAndStop () { UIView.animateWithDuration(1, animations: { () -> Void in for view in self._views { view.alpha = 0 } }) { (_) -> Void in self._stop = true for view in self._views { view.removeFromSuperview() } } } private func _recycle (v: UIImageView) { if self._stop { return } self._configureView(v) _move(v, cb: _recycle) } private func _createView () -> UIImageView { //let img = UIImage(named: self._imgName) let view = UIImageView() view.image = self._image return view } private func _configureView (view: UIImageView) { let img = view.image var scale = self._scale_base let scale_variance = CGFloat(_getValueWithVariance(Double(self._scale_base), range: Double(self._scale_variance))) if coinToss() { scale *= scale_variance } else { scale /= scale_variance } let alpha = CGFloat(_getValueWithVariance(Double(self._alpha_base), range: Double(self._alpha_variance))) let width = img!.size.width * -1 * scale let height = img!.size.height * scale let x = CGFloat(0) let y = CGFloat(arc4random_uniform(UInt32(self._superview.frame.height))) let x_offset = CGFloat(arc4random_uniform(UInt32(100))) * -1 let y_offset = CGFloat(arc4random_uniform(UInt32(height/2))) * -1 let rect = CGRectMake( x + x_offset, y + y_offset, width, height ) view.frame = rect view.image = img view.alpha = alpha } private func _move (v: UIImageView, cb: (v: UIImageView)->()) { UIView.animateWithDuration(1, delay: 0, options: [.CurveLinear], animations: { () -> Void in let view_index = self._views.indexOf(v)! let speed = self._view_speeds[view_index] v.center.x += speed }) { (_) -> Void in if v.frame.origin.x < self._superview.frame.width { self._move(v, cb: cb) } else { cb(v: v) } } } private func coinToss () -> Bool { return arc4random_uniform(2) % 2 == 0 } private func _randInRange(from: UInt32, _ to: UInt32) -> Int { var r = arc4random_uniform(to) + from if r > to { r = to } return Int(r) } private func _getValueWithVariance (base: Double, range: Double) -> Double { let from = UInt32(1000) let to = UInt32(range * 1000) let result: Double let variance = Double(_randInRange(from, to)) / 1000.0 if coinToss() { result = base * variance } else { result = base / variance } return result } }
mit
2089ca3807f7242d52bbd0a37a4ce65a
28.126506
205
0.53485
4.230096
false
false
false
false
yuhaifei123/WeiBo_Swift
WeiBo_Swift/WeiBo_Swift/class/tool(工具)/PopviewController/Pop_PresentationController.swift
1
1679
// // Pop_ViewController.swift // WeiBo_Swift // // Created by 虞海飞 on 2016/11/20. // Copyright © 2016年 虞海飞. All rights reserved. // import UIKit class Pop_ViewController: UIPresentationController { /// /// /// - Parameters: /// - presentedViewController: 被展示的控制器 /// - presentingViewController: 发起的控制器 override init(presentedViewController: UIViewController, presenting presentingViewController: UIViewController?) { super.init(presentedViewController: presentedViewController, presenting: presentingViewController); print(presentedViewController); } /// 转场过程中,初始化方法 override func containerViewWillLayoutSubviews() { super.containerViewWillLayoutSubviews(); //containerView 容器视图 //presentedView 展示视图 presentedView?.frame = CGRect(x: 100, y: 60, width: 200, height: 200); containerView?.insertSubview(backgroundView, at: 0); } //懒加载 背景试图 private lazy var backgroundView : UIView = { let view = UIView(); view.backgroundColor = UIColor(white: 0.0, alpha: 0.2); view.frame = UIScreen.main.bounds;//屏幕大小 //因为这个是 oc 的方法所以 #selector(self.closea) let tap = UITapGestureRecognizer(target: self, action:#selector(self.closea)); view.addGestureRecognizer(tap) return view; }(); @objc private func closea(){ presentedViewController.dismiss(animated: true, completion: nil); } }
apache-2.0
d18a891d843441ff3957aa87a9ccbdec
25.862069
118
0.627086
4.99359
false
false
false
false
cosnovae/FPlabelNode
FPLabelNodeDemo/FPLabelNodeDemo/GameScene.swift
1
1833
// // GameScene.swift // FPLabelNodeDemo // // Created by Kuo-Chuan Pan on 11/10/15. // Copyright (c) 2015 Kuo-Chuan Pan. All rights reserved. // import SpriteKit class GameScene: SKScene { let label = FPLabelNode(fontNamed:"Helvetica") override func didMoveToView(view: SKView) { /* Setup your scene here */ backgroundColor = SKColor.blackColor() label.width = CGRectGetMaxX(self.frame) label.height = CGRectGetMaxY(self.frame) - 200 label.fontColor = SKColor.whiteColor() //label.fontSize = 30 //label.spacing = 1.5 //label.buffer = 80 label.verticalAlignmentMode = .Center label.horizontalAlignmentMode = .Center label.position = CGPoint(x: 0, y: CGRectGetMaxY(self.frame) - 200) self.addChild(label) // Pushing many texts label.pushTexts(["Each String will become a line.", "If you want to break your String to multi-lines, just split it to an array of String.", "", "You can also push a very long string. FPLabelNode will automatically break the string for you, depending on the width of your FPLabelNode." ]) // Push a long string with "\n" label.pushString("This \nstring\nislike\nthe\nold\nway.") label.pushText("Tap the screen to add more text...") } override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { /* Called when a touch begins */ label.pushText("You can also push more texts later. If the string exceeds its maximun height, it will automatically clear the previous text for you. ") } override func update(currentTime: CFTimeInterval) { /* Called before each frame is rendered */ } }
mit
797088356999119d6a1404085a372e04
33.584906
159
0.624113
4.514778
false
false
false
false
mansoor92/MaksabComponents
MaksabComponents/Classes/Trips/cells/TripInfoTableViewCell.swift
1
1617
// // TripInfoTableViewCell.swift // Maksab // // Created by Incubasys on 16/08/2017. // Copyright © 2017 Incubasys. All rights reserved. // import UIKit import StylingBoilerPlate public class TripInfoTableViewCell: UITableViewCell, NibLoadableView { @IBOutlet weak public var dateTime: CaptionLabel! @IBOutlet weak public var tripStatus: CaptionLabel! @IBOutlet weak public var carName: TextLabel! @IBOutlet weak public var price: TextLabel! @IBOutlet weak public var webView: UIWebView! override public func awakeFromNib() { super.awakeFromNib() hideDefaultSeparator() backgroundColor = UIColor.appColor(color: .Medium) price.textColor = UIColor.appColor(color: .Primary) } override public func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) } public func config(endedTime: String, carName: String, status: String, statusColor: UIColor, actualCost: String) { dateTime.text = endedTime self.carName.text = carName tripStatus.text = status tripStatus.textColor = statusColor price.text = actualCost } }
mit
b5f0a0587e92bdd33a7bfeeab8b90ea0
41.526316
407
0.51547
5.855072
false
false
false
false
ahmetkgunay/AKGPushAnimator
Source/AKGPushAnimatorConstants.swift
2
657
// // AKGPushAnimatorConstants.swift // AKGPushAnimatorDemo // // Created by AHMET KAZIM GUNAY on 30/04/2017. // Copyright © 2017 AHMET KAZIM GUNAY. All rights reserved. // import UIKit struct AKGPushAnimatorConstants { struct Common { static let duration = 0.27 static let dismissPosition : CGFloat = -50 static let shadowOpacity : Float = 1 static let shadowColor : UIColor = .black } struct Push { static let animateOption : UIViewAnimationOptions = .curveEaseOut } struct Pop { static let animateOption : UIViewAnimationOptions = .curveEaseInOut } }
mit
1b439582e544387992cbca154c92babd
22.428571
75
0.64939
4.344371
false
false
false
false
hhcszgd/cszgdCode
weibo1/weibo1/classes/Module/NewFeatureCollectionVC.swift
1
6768
// // NewFeatureCollectionVC.swift // weibo1 // // Created by WY on 15/11/29. // Copyright © 2015年 WY. All rights reserved. // import UIKit import SnapKit private let reuseIdentifier = "Cell" let imemCount = 4 class NewFeatureCollectionVC: UICollectionViewController { init () { let layout1 = UICollectionViewFlowLayout() //尼玛为什么没有提示 layout1.itemSize = UIScreen.mainScreen().bounds.size // layout1.minimumInteritemSpacing = 220//行间距 layout1.minimumLineSpacing = 0//列间距 layout1.scrollDirection = UICollectionViewScrollDirection.Horizontal super.init(collectionViewLayout: layout1) collectionView?.pagingEnabled = true//要放在父类初始化方法以后, 才会有collectionView collectionView?.bounces = false collectionView?.showsHorizontalScrollIndicator = false } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Register cell classes self.collectionView!.registerClass(CustomCell.self, forCellWithReuseIdentifier: reuseIdentifier) // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using [segue destinationViewController]. // Pass the selected object to the new view controller. } */ // MARK: UICollectionViewDataSource override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of items return imemCount } override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! CustomCell // Configure the cell cell.backgroundColor = indexPath.item % 2 == 0 ? UIColor.redColor() : UIColor.greenColor() cell.idx = indexPath.item return cell } override func collectionView(collectionView: UICollectionView, didEndDisplayingCell cell: UICollectionViewCell, forItemAtIndexPath indexPath: NSIndexPath) { print(indexPath.item) let cell = collectionView.visibleCells().last as! CustomCell let index = collectionView.indexPathForCell(cell) let indexItem = index?.item ?? 0 if indexItem == imemCount - 1 {//判断是不是最后一页 cell.btnStartAnimat() } } // MARK: UICollectionViewDelegate /* // Uncomment this method to specify if the specified item should be highlighted during tracking override func collectionView(collectionView: UICollectionView, shouldHighlightItemAtIndexPath indexPath: NSIndexPath) -> Bool { return true } */ /* // Uncomment this method to specify if the specified item should be selected override func collectionView(collectionView: UICollectionView, shouldSelectItemAtIndexPath indexPath: NSIndexPath) -> Bool { return true } */ /* // Uncomment these methods to specify if an action menu should be displayed for the specified item, and react to actions performed on the item override func collectionView(collectionView: UICollectionView, shouldShowMenuForItemAtIndexPath indexPath: NSIndexPath) -> Bool { return false } override func collectionView(collectionView: UICollectionView, canPerformAction action: Selector, forItemAtIndexPath indexPath: NSIndexPath, withSender sender: AnyObject?) -> Bool { return false } override func collectionView(collectionView: UICollectionView, performAction action: Selector, forItemAtIndexPath indexPath: NSIndexPath, withSender sender: AnyObject?) { } */ } //MARK: 自定义cell class CustomCell : UICollectionViewCell { //添加一个记录下标的属性用来标记图片 var idx = 0{ didSet{ imgView.image = UIImage(named: "new_feature_\(idx + 1)")///////////// btn.hidden = true // if idx == 3 {btn.hidden = false} } } //添加一个imageView属性和按钮属性 lazy var imgView = UIImageView(image: UIImage(named: "new_feature_1")) lazy var btn : UIButton = { var temp = UIButton() temp.setTitle("点击体验", forState: UIControlState.Normal) temp.setBackgroundImage(UIImage(named: "new_feature_finish_button"), forState: .Normal) temp.setBackgroundImage(UIImage(named: "new_feature_finish_button_highlighted"), forState: .Highlighted) temp.sizeToFit() return temp }() override func bringSubviewToFront(view: UIView) { } //调整每个cell的图片 override init(frame: CGRect) { super.init(frame: frame) btn.addTarget(self, action: "jumpTabBarVC", forControlEvents: .TouchUpInside) layoutUI() } func jumpTabBarVC(){ // print(" 新特性展示成功 , 点击跳转到主控制器界面 ") //发送通知让appdelegate去跳转 NSNotificationCenter.defaultCenter().postNotificationName(JumpVCNotification, object: nil) } func layoutUI(){ contentView.addSubview(imgView) contentView.addSubview(btn) imgView.snp_makeConstraints { (make) -> Void in make.edges.equalTo(contentView.snp_edges) } btn.snp_makeConstraints { (make) -> Void in make.centerX.equalTo(contentView.snp_centerX) make.centerY.equalTo(contentView.snp_bottom).offset(-110) } } func btnStartAnimat (){ btn.hidden = false btn.transform = CGAffineTransformMakeScale(0, 0) UIView.animateWithDuration(2.0, delay: 0, options: [], animations: { () -> Void in //执行动画 self.btn.transform = CGAffineTransformMakeScale(1, 1) }) { (_ ) -> Void in //啥也不干 } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
apache-2.0
de4d15f45b975744e7196094a51c0555
34.521739
185
0.673757
5.190627
false
false
false
false
zhou9734/Warm
Warm/Classes/Home/View/PageScrollView.swift
1
6529
// // PageScrollView.swift // Warm // // Created by zhoucj on 16/9/13. // Copyright © 2016年 zhoucj. All rights reserved. // import UIKit import SDWebImage class PageScrollView: UIView { private var timer:NSTimer? let pageWidth = Int(UIScreen.mainScreen().bounds.width) let pageHeight = 160 private var currentPage = 0 let imageView0:UIImageView = UIImageView() let imageView1:UIImageView = UIImageView() let imageView2:UIImageView = UIImageView() /// 图片数组 var rounds: [WRound] = [WRound](){ willSet{ currentPage = 0 pageControl.numberOfPages = newValue.count stopTimer() } didSet{ startTimer() updateImageData() } } override init(frame: CGRect) { super.init(frame: frame) setupUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func setupUI(){ addSubview(scrollView) addSubview(pageControl) } private lazy var scrollView: UIScrollView = { //scrollView的初始化 let scrollView = UIScrollView() scrollView.frame = ScreenBounds //为了让内容横向滚动,设置横向内容宽度为3个页面的宽度总和 scrollView.contentSize=CGSizeMake(CGFloat(self.pageWidth*3), CGFloat(self.pageHeight)) //一页一页的滚动 scrollView.pagingEnabled = true scrollView.showsHorizontalScrollIndicator = false scrollView.showsVerticalScrollIndicator = false scrollView.scrollsToTop = false scrollView.delegate = self self.imageView0.frame = CGRect(x: 0, y: 0, width: self.pageWidth, height: self.pageHeight) self.imageView1.frame = CGRect(x: self.pageWidth, y: 0, width: self.pageWidth, height: self.pageHeight) self.imageView2.frame = CGRect(x: self.pageWidth * 2, y: 0, width: self.pageWidth, height: self.pageHeight) //添加手势点击 let tap = UITapGestureRecognizer(target: self, action: "imageViewClick:") scrollView.addGestureRecognizer(tap) scrollView.addSubview(self.imageView0) scrollView.addSubview(self.imageView1) scrollView.addSubview(self.imageView2) return scrollView }() private lazy var pageControl: UIPageControl = { let pageCrl = UIPageControl() pageCrl.hidesForSinglePage = true pageCrl.pageIndicatorTintColor = UIColor.darkGrayColor() pageCrl.currentPageIndicatorTintColor = UIColor.whiteColor() pageCrl.numberOfPages = self.rounds.count pageCrl.currentPage = 0 let screenWidth = UIScreen.mainScreen().bounds.width let pageW: CGFloat = 80 let pageH: CGFloat = 20 let pageX: CGFloat = screenWidth/2 - pageW/2 let pageY: CGFloat = CGFloat(self.pageHeight) - 30.0 pageCrl.frame = CGRectMake(pageX, pageY, pageW, pageH) return pageCrl }() //开始定时器 private func startTimer(){ timer = nil timer = NSTimer.scheduledTimerWithTimeInterval(3.0, target: self, selector: "autoTurnNextView", userInfo: nil, repeats: true) } //结束定时器 private func stopTimer(){ guard let timer = self.timer else{ return } if timer.valid{ timer.invalidate() } } @objc private func autoTurnNextView(){ //跳转到下一个 if currentPage == rounds.count - 1{ currentPage = 0 }else{ currentPage += 1 } updateImageData() } // MARK: - 点击图片调转 @objc private func imageViewClick(tap: UITapGestureRecognizer) { NSNotificationCenter.defaultCenter().postNotificationName(RoundImageClick, object: self, userInfo: [ "index" : currentPage]) } deinit{ stopTimer() } } extension PageScrollView: UIScrollViewDelegate{ //停止滚动 func scrollViewDidEndDecelerating(scrollView: UIScrollView) { let ratio = scrollView.contentOffset.x/scrollView.frame.size.width endScrollMethod(ratio) } //停止拖动 func scrollViewDidEndDragging(scrollView: UIScrollView, willDecelerate decelerate: Bool) { if !decelerate{ let ratio = scrollView.contentOffset.x/scrollView.frame.size.width endScrollMethod(ratio) } } //将要开始拖动 func scrollViewWillBeginDragging(scrollView: UIScrollView) { stopTimer() } private func endScrollMethod(ratio:CGFloat){ if ratio <= 0.7{ if currentPage - 1 < 0{ currentPage = rounds.count - 1 }else{ currentPage -= 1 } } if ratio >= 1.3{ if currentPage == rounds.count - 1{ currentPage = 0 }else{ currentPage += 1 } } updateImageData() startTimer() } //MARK: - 重新设置数据 private func updateImageData(){ if currentPage == 0{ imageView0.sd_setImageWithURL(NSURL(string: rounds.last!.rdata!.avatar!), placeholderImage: placeholderImage) imageView1.sd_setImageWithURL(NSURL(string: rounds[currentPage].rdata!.avatar!), placeholderImage: placeholderImage) imageView2.sd_setImageWithURL(NSURL(string: rounds[currentPage + 1].rdata!.avatar!), placeholderImage: placeholderImage) }else if currentPage == rounds.count - 1{ imageView0.sd_setImageWithURL(NSURL(string: rounds[currentPage - 1].rdata!.avatar!), placeholderImage: placeholderImage) imageView1.sd_setImageWithURL(NSURL(string: rounds[currentPage].rdata!.avatar!), placeholderImage: placeholderImage) imageView2.sd_setImageWithURL(NSURL(string: rounds.first!.rdata!.avatar!), placeholderImage: placeholderImage) }else{ imageView0.sd_setImageWithURL(NSURL(string: rounds[currentPage - 1].rdata!.avatar!), placeholderImage: placeholderImage) imageView1.sd_setImageWithURL(NSURL(string: rounds[currentPage].rdata!.avatar!), placeholderImage: placeholderImage) imageView2.sd_setImageWithURL(NSURL(string: rounds[currentPage + 1].rdata!.avatar!), placeholderImage: placeholderImage) } pageControl.currentPage = currentPage scrollView.contentOffset = CGPoint(x: scrollView.frame.size.width, y: 0) } }
mit
7d98cbe9e42740c17d4847b5440dc71d
35.471264
133
0.639931
4.76069
false
false
false
false
andrea-prearo/ContactList
ContactList/Extensions/Equatable+Util.swift
1
1011
// // Array+Equatable.swift // ContactList // // Created by Andrea Prearo on 4/29/16. // Copyright © 2016 Andrea Prearo // import Foundation // MARK: Array comparison methods // These methods couldn't put into an Array extension // because of a current limitation of the type system // https://forums.developer.apple.com/thread/7172 func ==<T: Equatable>(lhs: [T]?, rhs: [T]?) -> Bool { switch (lhs,rhs) { case (.some(let lhs), .some(let rhs)): return lhs == rhs case (.none, .none): return true default: return false } } func ==<T: Equatable>(lhs: [T?]?, rhs: [T?]?) -> Bool { switch (lhs,rhs) { case (.some(let lhs), .some(let rhs)): if let lhsNonNil = lhs.unwrap(), let rhsNonNil = rhs.unwrap() , lhsNonNil.count == rhsNonNil.count { return lhsNonNil == rhsNonNil } else { return false } case (.none, .none): return true default: return false } }
mit
d692859eed17c2fdb56853152b137a85
23.047619
55
0.568317
3.726937
false
false
false
false
HHuckebein/HorizontalPicker
HorizontalPicker/Classes/CollectionView/HPCollectionViewFlowlayout.swift
1
1957
// // HPCollectionViewFlowlayout.swift // HorizontalPickerDemo // // Created by Bernd Rabe on 13.12.15. // Copyright © 2015 RABE_IT Services. All rights reserved. // import UIKit import GLKit class HPCollectionViewFlowlayout: UICollectionViewFlowLayout { var activeDistance: CGFloat = 0.0 var midX: CGFloat = 0 var lastElementIndex = 0 let maxAngle = CGFloat(GLKMathDegreesToRadians(HorizontalPickerViewConstants.maxRotationAngle)) override func prepare () { minimumInteritemSpacing = 0.0 scrollDirection = .horizontal } override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? { guard let array = super.layoutAttributesForElements(in: rect) , let cv = collectionView else { return nil } let visibleRect = CGRect(origin: cv.contentOffset, size: cv.bounds.size) var attributesCopy = [UICollectionViewLayoutAttributes]() for itemAttributes in array { let itemAttributesCopy = itemAttributes.copy() as! UICollectionViewLayoutAttributes let distance = visibleRect.midX - itemAttributesCopy.center.x let normalizedDistance = distance / activeDistance if abs(distance) < activeDistance { itemAttributesCopy.alpha = 1.0 - abs(normalizedDistance) let rotationAngle = maxAngle * normalizedDistance itemAttributesCopy.transform3D = CATransform3DMakeRotation(rotationAngle, 0, 1, 0) } else { itemAttributesCopy.transform3D = CATransform3DMakeRotation(maxAngle, 0, 1, 0) itemAttributesCopy.alpha = 0.1 } attributesCopy.append(itemAttributesCopy) } return attributesCopy } override func shouldInvalidateLayout(forBoundsChange newBounds: CGRect) -> Bool { return true } }
mit
891d5f6debcb583490958de48f18a531
35.222222
103
0.661554
5.315217
false
false
false
false
lvogelzang/Blocky
Blocky/Levels/Level77.swift
1
877
// // Level77.swift // Blocky // // Created by Lodewijck Vogelzang on 07-12-18 // Copyright (c) 2018 Lodewijck Vogelzang. All rights reserved. // import UIKit final class Level77: Level { let levelNumber = 77 var tiles = [[0, 1, 0, 1, 0], [1, 1, 1, 1, 1], [0, 1, 0, 1, 0], [0, 1, 0, 1, 0]] let cameraFollowsBlock = false let blocky: Blocky let enemies: [Enemy] let foods: [Food] init() { blocky = Blocky(startLocation: (0, 1), endLocation: (4, 1)) let pattern0 = [("S", 0.5), ("S", 0.5), ("S", 0.5), ("N", 0.5), ("N", 0.5), ("N", 0.5)] let enemy0 = Enemy(enemyNumber: 0, startLocation: (1, 3), animationPattern: pattern0) let pattern1 = [("S", 0.5), ("S", 0.5), ("S", 0.5), ("N", 0.5), ("N", 0.5), ("N", 0.5)] let enemy1 = Enemy(enemyNumber: 1, startLocation: (3, 3), animationPattern: pattern1) enemies = [enemy0, enemy1] foods = [] } }
mit
5e2a06b73d5f13dc5aad50a7acb9032a
24.794118
89
0.573546
2.649547
false
false
false
false
adrianAlvarezFernandez/CameraResolutionHelper
CameraResolutionHelperTests/CameraResolutionHelperTests.swift
1
2352
// // CameraResolutionHelperTests.swift // CameraResolutionHelperTests // // Created by Adrián Álvarez Fernández on 13/05/2017. // Copyright © 2017 Electronic ID. All rights reserved. // import XCTest @testable import CameraResolutionHelper class CameraResolutionHelperTests: XCTestCase { private let screen4inches : CGSize = CGSize(width: 320, height: 568) private let screen47inches : CGSize = CGSize(width: 320, height: 568) private let screen55inches : CGSize = CGSize(width: 375, height: 667) private let iphone4InchesIdentifierExample : String = "iPhone5,1" private let iphone47InchesIdentifierExample : String = "iPhone8,1" private let iphone55InchesIdentifierExample : String = "iPhone8,2" override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testiPhone4InchesInGroupiPhone567CameraRetrieves() { let resolutions = CameraResolutionHelper.getResolutionWithSameAspectRatioAsView(deviceModel: iphone4InchesIdentifierExample, sizeOfView: screen4inches) let backCameraResolution : String = resolutions?.value(forKey: "back") as! String let frontCameraResolution : String = resolutions?.value(forKey: "front") as! String XCTAssertEqual(backCameraResolution, "AVCaptureSessionPresetHigh") XCTAssertEqual(frontCameraResolution, "AVCaptureSessionPreset1280x720") } // func testiPhone47InchesInGroupiPhone567CameraRetrieves() { // // let resolutions = CameraResolutionHelper.getResolutionWithSameAspectRatioAsView(deviceModel: iphone4InchesIdentifierExample, sizeOfView: screen47inches) // let backCameraResolution : String = resolutions?.value(forKey: "back") as! String // let frontCameraResolution : String = resolutions?.value(forKey: "front") as! String // // // XCTAssertEqual(backCameraResolution, "AVCaptureSessionPresetHigh") // // XCTAssertEqual(frontCameraResolution, "AVCaptureSessionPreset1280x720") // // } }
mit
94f8c74ca1e6fd9ad8eafce1b68defdd
38.79661
162
0.707836
4.714859
false
true
false
false
lyft/SwiftLint
Tests/SwiftLintFrameworkTests/ImplicitlyUnwrappedOptionalRuleTests.swift
1
1100
import Foundation @testable import SwiftLintFramework import XCTest class ImplicitlyUnwrappedOptionalRuleTests: XCTestCase { func testImplicitlyUnwrappedOptionalRuleDefaultConfiguration() { let rule = ImplicitlyUnwrappedOptionalRule() XCTAssertEqual(rule.configuration.mode, .allExceptIBOutlets) XCTAssertEqual(rule.configuration.severity.severity, .warning) } func testImplicitlyUnwrappedOptionalRuleWarnsOnOutletsInAllMode() { let baseDescription = ImplicitlyUnwrappedOptionalRule.description let triggeringExamples = [ "@IBOutlet private var label: UILabel!", "@IBOutlet var label: UILabel!", "let int: Int!" ] let nonTriggeringExamples = ["if !boolean {}"] let description = baseDescription.with(nonTriggeringExamples: nonTriggeringExamples) .with(triggeringExamples: triggeringExamples) verifyRule(description, ruleConfiguration: ["mode": "all"], commentDoesntViolate: true, stringDoesntViolate: true) } }
mit
24f7bb2f45157ae7d1f3df00b60eac76
38.285714
92
0.690909
6.179775
false
true
false
false
patrick-sheehan/cwic
Source/PositionViewController.swift
1
1216
// // PositionViewController.swift // CWIC // // Created by Patrick Sheehan on 12/6/17. // Copyright © 2017 Síocháin Solutions. All rights reserved. // import UIKit import MapKit class PositionViewController: UIViewController { @IBOutlet var mapView: MKMapView! var position: Position? var positionTitle = "Event Location" var positionSubtitle = "" override func viewDidLoad() { super.viewDidLoad() mapView.mapType = MKMapType.hybrid mapView.showsCompass = true mapView.showsScale = true if let position = position { let location = CLLocationCoordinate2D(latitude: position.lat, longitude: position.lon) let span = MKCoordinateSpanMake(0.05, 0.05) let region = MKCoordinateRegion(center: location, span: span) mapView.setRegion(region, animated: true) let annotation = MKPointAnnotation() annotation.coordinate = location annotation.title = positionTitle annotation.subtitle = positionSubtitle mapView.addAnnotation(annotation) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
gpl-3.0
a91fa324ee9f4df5882858734407baa6
24.270833
92
0.693322
4.70155
false
false
false
false
mobgeek/swift
Swift em 4 Semanas/Playgrounds/Semana 4/6-Optional Chaining.playground/Contents.swift
2
3909
// Playground - noun: a place where people can play import UIKit // Optional Chaining class Endereço { var nomePrédio: String? var númeroPrédio: String? var rua: String? func identificadorPrédio() -> String? { if nomePrédio != nil { return nomePrédio } else if númeroPrédio != nil { return númeroPrédio } else { return nil } } } class Cômodo { let nome: String init(nome:String) { self.nome = nome } } class Residência { var endereço: Endereço? var comodos = [Cômodo]() var numeroDeComodos: Int { //propriedade computada que retorna a quantidade de itens no array de cômodos return comodos.count } subscript (i: Int) -> Cômodo { return comodos[i] } func imprimeNumeroDeCômodos() { println("O numero de quartos é \(numeroDeComodos)") } } class Pessoa { var primeiraResidência = Residência() //Swift infere que residência é do tipo Residência var segundaResidência: Residência? } let renan = Pessoa() var dinheiro: String? //renan.segundaResidência!.numeroDeComodos //erro, o programa para de exeutar tudo que está abaixo pois está tentando desempacotar um valor que não existe. renan.segundaResidência?.numeroDeComodos // Acessando propriedades if let quantidadeComodos = renan.segundaResidência?.numeroDeComodos { println("A residência do Renan tem \(quantidadeComodos) quarto(s).") } else { println("Não foi possível consultar o número de quartos.") } let casaDoRenan = Residência() casaDoRenan.comodos += [Cômodo(nome: "Sala de Estar")] casaDoRenan.comodos += [Cômodo(nome: "Cozinha")] renan.segundaResidência = casaDoRenan renan.segundaResidência?.numeroDeComodos if let quantidadeComodos = renan.segundaResidência?.numeroDeComodos { //retorna um valor do tipo Int? println("A residência do Renan tem \(quantidadeComodos) cômodo(s).") } else { println("Não foi possível consultar o número de cômodos.") } // Chamando métodos if renan.segundaResidência?.imprimeNumeroDeCômodos() != nil { //retorna um Void? (Optional Void) println("Foi possível enviar a mensagem com o número de quartos.") } else { println("Não foi possível enviar a mensagem com o número de quartos.") } var umEndereço = Endereço() if (renan.segundaResidência?.endereço = umEndereço) != nil { println("Endereço foi atualizado com sucesso.") } else { println("Não foi possível atualizar o endereço com sucesso.") } // Múltiplos níveis if let ruaDoRenan = renan.segundaResidência?.endereço?.rua { //retorna um String? println("A rua do Renan é \(ruaDoRenan).") } else { println("Não foi possível obter o endereço.") } // Chamando métodos que retornam valores opcionais if let identificadorPredio = renan.primeiraResidência.endereço?.identificadorPrédio() { println("Identificador do prédio do Renan: \(identificadorPredio).") } renan.segundaResidência?.endereço?.nomePrédio = "Condominio das Flores" if let comecaComCondominio = renan.segundaResidência?.endereço?.identificadorPrédio()?.hasPrefix("Condominio") { println("Identificador do Prédio começa com\"Condomínio\".") } // Subscripts if let primeiroNomeDoCômodo = renan.segundaResidência?[0].nome { //String? println("O primeiro nome do comodo é \(primeiroNomeDoCômodo)") } else { println("Não foi possível retornar o primeiro nome do Comodo") }
mit
36c7ebb41843db35c0105671f52e29a0
18.869792
156
0.636173
2.9735
false
false
false
false
dexafree/SayCheese
SayCheese/ScreenshotWindow.swift
2
6406
// // ScreenshotWindow.swift // SayCheese // // Created by Jorge Martín Espinosa on 13/6/14. // Copyright (c) 2014 Jorge Martín Espinosa. All rights reserved. // import Cocoa import QuartzCore class ScreenshotWindow: NSWindowController, ScreenshotDelegate, NSWindowDelegate { var selectedImage: NSImage? var backgroundImage: NSImage? var imageView: CroppingNSView? var savePanel: NSSavePanel? var imgurClient: ImgurClient? var selectActionView: SelectActionViewController? var confirmAnonymous: ConfirmAnonymousUploadPanelController? override init(window: NSWindow!) { super.init(window: window) window.delegate = self window.releasedWhenClosed = false } required init?(coder: NSCoder) { super.init(coder: coder) } override func showWindow(sender: AnyObject!) { window!.makeKeyAndOrderFront(self) // Set level to screensaver level window!.level = 1000 // Set image cropping view as the contentView imageView = CroppingNSView(frame: window!.frame) imageView!.screenshotDelegate = self window!.contentView = imageView! } func paintImage(image: NSImage, withSize size: NSSize) { backgroundImage = image imageView!.setImageForBackground(backgroundImage!, withSize: size) } func regionSelected(image: NSImage) { // Add SelectActionViewController to the middle-bottom of the screen selectActionView = SelectActionViewController() selectActionView!.screenshotDelegate = self let newFrame = NSRectFromCGRect(CGRectMake(window!.frame.size.width/2 - selectActionView!.view.frame.width/2, 60, selectActionView!.view.frame.width, selectActionView!.view.frame.height)) selectActionView!.view.frame = newFrame (window!.contentView as! NSView).addSubview(selectActionView!.view) // Keep a reference to the selected image so it can be saved or uploaded later selectedImage = image } func uploadPicture(image: NSImage) { imgurClient!.uploadImage(image) } func savePicture(image: NSImage) { // Instantiate savePanel savePanel = NSSavePanel() savePanel!.allowedFileTypes = ["png", "jpg"] savePanel!.allowsOtherFileTypes = false savePanel!.extensionHidden = false let fileFormatView = NSView(frame: NSMakeRect(0, 0, savePanel!.frame.size.width, 40)) let center = savePanel!.frame.size.width/2 let pullDownView = NSPopUpButton(frame: NSMakeRect(center+40, 0, 80, 40)) // Add an "Extension:" label let extensionLabel = NSTextField(frame: NSMakeRect(center-50, 10, 80, 20)) extensionLabel.stringValue = "Extension: " extensionLabel.bezeled = false extensionLabel.drawsBackground = false extensionLabel.editable = false extensionLabel.selectable = false extensionLabel.alignment = NSTextAlignment.RightTextAlignment // Add a NSPopUpMenu with the available extensions pullDownView.addItemsWithTitles(savePanel!.allowedFileTypes!) pullDownView.action = "dropMenuChange:" pullDownView.target = self fileFormatView.addSubview(pullDownView) fileFormatView.addSubview(extensionLabel) // Set the container view as the accessory view savePanel!.accessoryView = fileFormatView // Send window back so we can see the modal NSSavePanel window!.level = 2 // Launch save dialog let saveResult = savePanel!.runModal() // If user selects "Save" if saveResult == NSOKButton { // Get image as bitmap image.lockFocus() let bitmapRepresentation = NSBitmapImageRep(focusedViewRect: NSMakeRect(0, 0, image.size.width, image.size.height)) image.unlockFocus() // Search file type according to the previous NSPopUpMenu selection var fileType: NSBitmapImageFileType = .NSPNGFileType switch savePanel!.allowedFileTypes![0] as! String { case "png": fileType = NSBitmapImageFileType.NSPNGFileType case "jpg": fileType = NSBitmapImageFileType.NSJPEGFileType default: fileType = .NSPNGFileType; } var temp: [NSObject: AnyObject] = [NSObject: AnyObject]() // Convert bitmap to data let data: NSData? = bitmapRepresentation!.representationUsingType(fileType, properties: temp) as NSData? // Save data to selected file data!.writeToFile(savePanel!.URL!.path!, atomically: false) } } func dropMenuChange(sender: NSPopUpButton) { let extensions: [String] = [sender.selectedItem!.title] savePanel!.allowedFileTypes = extensions } func windowWillClose(notification: NSNotification) { // Free some resources backgroundImage = nil imageView!.releaseImage() selectedImage = nil } func saveImage() { savePicture(selectedImage!) closeWindow() } func uploadImage() { if imgurClient!.hasAccount() == true { // If has account, upload it and close imgurClient!.uploadImage(selectedImage!) } else { // Else, check if the user wants anonymously uploads let defaults = NSUserDefaults.standardUserDefaults() if defaults.boolForKey("upload_anonymously") { // If yes, upload it imgurClient!.uploadImage(selectedImage!) } else { // Else, ask confirmAnonymous = ConfirmAnonymousUploadPanelController() window!.level = 2 let result = NSApp.runModalForWindow(confirmAnonymous!.window!) if result == NSOKButton { imgurClient!.uploadImage(selectedImage!) } } } closeWindow() } func closeWindow() { if selectActionView != nil { selectActionView!.view.removeFromSuperview() } close() } }
apache-2.0
fa4c44e2fe88e6d9b58dcc6d69456b7a
34.776536
127
0.619457
5.301325
false
false
false
false
adrfer/swift
stdlib/public/core/Reverse.swift
1
8935
//===--- Reverse.swift - Lazy sequence reversal ---------------*- swift -*-===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// public protocol ReverseIndexType : BidirectionalIndexType { associatedtype Base : BidirectionalIndexType /// A type that can represent the number of steps between pairs of /// `ReverseIndex` values where one value is reachable from the other. associatedtype Distance: _SignedIntegerType = Base.Distance /// The successor position in the underlying (un-reversed) /// collection. /// /// If `self` is `advance(c.reverse.startIndex, n)`, then: /// - `self.base` is `advance(c.endIndex, -n)`. /// - if `n` != `c.count`, then `c.reverse[self]` is /// equivalent to `[self.base.predecessor()]`. var base: Base { get } init(_ base: Base) } extension BidirectionalIndexType where Self : ReverseIndexType { /// Returns the next consecutive value after `self`. /// /// - Requires: The next value is representable. public func successor() -> Self { return Self(base.predecessor()) } /// Returns the previous consecutive value before `self`. /// /// - Requires: The previous value is representable. public func predecessor() -> Self { return Self(base.successor()) } } /// A wrapper for a `BidirectionalIndexType` that reverses its /// direction of traversal. public struct ReverseIndex<Base: BidirectionalIndexType> : BidirectionalIndexType, ReverseIndexType { public typealias Distance = Base.Distance public init(_ base: Base) { self.base = base } /// The successor position in the underlying (un-reversed) /// collection. /// /// If `self` is `advance(c.reverse.startIndex, n)`, then: /// - `self.base` is `advance(c.endIndex, -n)`. /// - if `n` != `c.count`, then `c.reverse[self]` is /// equivalent to `[self.base.predecessor()]`. public let base: Base @available(*, unavailable, renamed="Base") public typealias I = Base } @warn_unused_result public func == <Base> ( lhs: ReverseIndex<Base>, rhs: ReverseIndex<Base> ) -> Bool { return lhs.base == rhs.base } /// A wrapper for a `RandomAccessIndexType` that reverses its /// direction of traversal. public struct ReverseRandomAccessIndex<Base: RandomAccessIndexType> : RandomAccessIndexType, ReverseIndexType { public typealias Distance = Base.Distance public init(_ base: Base) { self.base = base } /// The successor position in the underlying (un-reversed) /// collection. /// /// If `self` is `advance(c.reverse.startIndex, n)`, then: /// - `self.base` is `advance(c.endIndex, -n)`. /// - if `n` != `c.count`, then `c.reverse[self]` is /// equivalent to `[self.base.predecessor()]`. public let base: Base public func distanceTo(other: ReverseRandomAccessIndex) -> Distance { return other.base.distanceTo(base) } public func advancedBy(n: Distance) -> ReverseRandomAccessIndex { return ReverseRandomAccessIndex(base.advancedBy(-n)) } @available(*, unavailable, renamed="Base") public typealias I = Base } public protocol _ReverseCollectionType : CollectionType { associatedtype Index : ReverseIndexType associatedtype Base : CollectionType var _base: Base { get } } extension CollectionType where Self : _ReverseCollectionType, Self.Base.Index : RandomAccessIndexType { public var startIndex : ReverseRandomAccessIndex<Self.Base.Index> { return ReverseRandomAccessIndex(_base.endIndex) } } extension _ReverseCollectionType where Self : CollectionType, Self.Index.Base == Self.Base.Index { public var startIndex : Index { return Self.Index(_base.endIndex) } public var endIndex : Index { return Self.Index(_base.startIndex) } public subscript(position: Index) -> Self.Base.Generator.Element { return _base[position.base.predecessor()] } } /// A Collection that presents the elements of its `Base` collection /// in reverse order. /// /// - Note: This type is the result of `x.reverse()` where `x` is a /// collection having bidirectional indices. /// /// The `reverse()` method is always lazy when applied to a collection /// with bidirectional indices, but does not implicitly confer /// laziness on algorithms applied to its result. In other words, for /// ordinary collections `c` having bidirectional indices: /// /// * `c.reverse()` does not create new storage /// * `c.reverse().map(f)` maps eagerly and returns a new array /// * `c.lazy.reverse().map(f)` maps lazily and returns a `LazyMapCollection` /// /// - See also: `ReverseRandomAccessCollection` public struct ReverseCollection< Base : CollectionType where Base.Index : BidirectionalIndexType > : CollectionType, _ReverseCollectionType { /// Creates an instance that presents the elements of `base` in /// reverse order. /// /// - Complexity: O(1) public init(_ base: Base) { self._base = base } /// A type that represents a valid position in the collection. /// /// Valid indices consist of the position of every element and a /// "past the end" position that's not valid for use as a subscript. public typealias Index = ReverseIndex<Base.Index> /// A type that provides the *sequence*'s iteration interface and /// encapsulates its iteration state. public typealias Generator = IndexingGenerator<ReverseCollection> public let _base: Base @available(*, unavailable, renamed="Base") public typealias T = Base } /// A Collection that presents the elements of its `Base` collection /// in reverse order. /// /// - Note: This type is the result of `x.reverse()` where `x` is a /// collection having random access indices. /// - See also: `ReverseCollection` public struct ReverseRandomAccessCollection< Base : CollectionType where Base.Index : RandomAccessIndexType > : _ReverseCollectionType { /// Creates an instance that presents the elements of `base` in /// reverse order. /// /// - Complexity: O(1) public init(_ base: Base) { self._base = base } /// A type that represents a valid position in the collection. /// /// Valid indices consist of the position of every element and a /// "past the end" position that's not valid for use as a subscript. public typealias Index = ReverseRandomAccessIndex<Base.Index> /// A type that provides the *sequence*'s iteration interface and /// encapsulates its iteration state. public typealias Generator = IndexingGenerator< ReverseRandomAccessCollection > public let _base: Base @available(*, unavailable, renamed="Base") public typealias T = Base } extension CollectionType where Index : BidirectionalIndexType { /// Return the elements of `self` in reverse order. /// /// - Complexity: O(1) @warn_unused_result public func reverse() -> ReverseCollection<Self> { return ReverseCollection(self) } } extension CollectionType where Index : RandomAccessIndexType { /// Return the elements of `self` in reverse order. /// /// - Complexity: O(1) @warn_unused_result public func reverse() -> ReverseRandomAccessCollection<Self> { return ReverseRandomAccessCollection(self) } } extension LazyCollectionType where Index : BidirectionalIndexType, Elements.Index : BidirectionalIndexType { /// Return the elements of `self` in reverse order. /// /// - Complexity: O(1) @warn_unused_result public func reverse() -> LazyCollection< ReverseCollection<Elements> > { return ReverseCollection(elements).lazy } } extension LazyCollectionType where Index : RandomAccessIndexType, Elements.Index : RandomAccessIndexType { /// Return the elements of `self` in reverse order. /// /// - Complexity: O(1) @warn_unused_result public func reverse() -> LazyCollection< ReverseRandomAccessCollection<Elements> > { return ReverseRandomAccessCollection(elements).lazy } } /// Return an `Array` containing the elements of `source` in reverse /// order. @available(*, unavailable, message="call the 'reverse()' method on the collection") public func reverse<C:CollectionType where C.Index: BidirectionalIndexType>( source: C ) -> [C.Generator.Element] { fatalError("unavailable function can't be called") } @available(*, unavailable, renamed="ReverseCollection") public struct BidirectionalReverseView< Base : CollectionType where Base.Index : BidirectionalIndexType > {} @available(*, unavailable, renamed="ReverseRandomAccessCollection") public struct RandomAccessReverseView< Base : CollectionType where Base.Index : RandomAccessIndexType > {} // ${'Local Variables'}: // eval: (read-only-mode 1) // End:
apache-2.0
a50b8a7ea3e38822855b72812ffeebfa
31.609489
83
0.700951
4.350049
false
false
false
false
khizkhiz/swift
stdlib/public/core/Reverse.swift
1
9506
//===--- Reverse.swift - Lazy sequence reversal ---------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// /// An index that traverses the same positions as an underlying index, /// with inverted traversal direction. public protocol ReverseIndexProtocol : BidirectionalIndex { associatedtype Base : BidirectionalIndex /// A type that can represent the number of steps between pairs of /// `ReverseIndex` values where one value is reachable from the other. associatedtype Distance : _SignedInteger = Base.Distance /// The successor position in the underlying (un-reversed) /// collection. /// /// If `self` is `advance(c.reverse.startIndex, n)`, then: /// - `self.base` is `advance(c.endIndex, -n)`. /// - if `n` != `c.count`, then `c.reverse[self]` is /// equivalent to `[self.base.predecessor()]`. var base: Base { get } init(_ base: Base) } extension BidirectionalIndex where Self : ReverseIndexProtocol { /// Returns the next consecutive value after `self`. /// /// - Precondition: The next value is representable. public func successor() -> Self { return Self(base.predecessor()) } /// Returns the previous consecutive value before `self`. /// /// - Precondition: The previous value is representable. public func predecessor() -> Self { return Self(base.successor()) } } /// A wrapper for a `BidirectionalIndex` that reverses its /// direction of traversal. public struct ReverseIndex<Base : BidirectionalIndex> : BidirectionalIndex, ReverseIndexProtocol { public typealias Distance = Base.Distance public init(_ base: Base) { self.base = base } /// The successor position in the underlying (un-reversed) /// collection. /// /// If `self` is `advance(c.reverse.startIndex, n)`, then: /// - `self.base` is `advance(c.endIndex, -n)`. /// - if `n` != `c.count`, then `c.reverse[self]` is /// equivalent to `[self.base.predecessor()]`. public let base: Base } @warn_unused_result public func == <Base> ( lhs: ReverseIndex<Base>, rhs: ReverseIndex<Base> ) -> Bool { return lhs.base == rhs.base } /// A wrapper for a `RandomAccessIndex` that reverses its /// direction of traversal. public struct ReverseRandomAccessIndex<Base: RandomAccessIndex> : RandomAccessIndex, ReverseIndexProtocol { public typealias Distance = Base.Distance public init(_ base: Base) { self.base = base } /// The successor position in the underlying (un-reversed) /// collection. /// /// If `self` is `advance(c.reverse.startIndex, n)`, then: /// - `self.base` is `advance(c.endIndex, -n)`. /// - if `n` != `c.count`, then `c.reverse[self]` is /// equivalent to `[self.base.predecessor()]`. public let base: Base public func distance(to other: ReverseRandomAccessIndex) -> Distance { return other.base.distance(to: base) } public func advanced(by n: Distance) -> ReverseRandomAccessIndex { return ReverseRandomAccessIndex(base.advanced(by: -n)) } } public protocol _ReverseCollection : Collection { associatedtype Index : ReverseIndexProtocol associatedtype Base : Collection var _base: Base { get } } extension Collection where Self : _ReverseCollection, Self.Base.Index : RandomAccessIndex { public var startIndex : ReverseRandomAccessIndex<Self.Base.Index> { return ReverseRandomAccessIndex(_base.endIndex) } } extension _ReverseCollection where Self : Collection, Self.Index.Base == Self.Base.Index { public var startIndex : Index { return Self.Index(_base.endIndex) } public var endIndex : Index { return Self.Index(_base.startIndex) } public subscript(position: Index) -> Self.Base.Iterator.Element { return _base[position.base.predecessor()] } } /// A Collection that presents the elements of its `Base` collection /// in reverse order. /// /// - Note: This type is the result of `x.reversed()` where `x` is a /// collection having bidirectional indices. /// /// The `reversed()` method is always lazy when applied to a collection /// with bidirectional indices, but does not implicitly confer /// laziness on algorithms applied to its result. In other words, for /// ordinary collections `c` having bidirectional indices: /// /// * `c.reversed()` does not create new storage /// * `c.reversed().map(f)` maps eagerly and returns a new array /// * `c.lazy.reversed().map(f)` maps lazily and returns a `LazyMapCollection` /// /// - See also: `ReverseRandomAccessCollection` public struct ReverseCollection< Base : Collection where Base.Index : BidirectionalIndex > : Collection, _ReverseCollection { /// Creates an instance that presents the elements of `base` in /// reverse order. /// /// - Complexity: O(1) internal init(_base: Base) { self._base = _base } /// A type that represents a valid position in the collection. /// /// Valid indices consist of the position of every element and a /// "past the end" position that's not valid for use as a subscript. public typealias Index = ReverseIndex<Base.Index> /// A type that provides the sequence's iteration interface and /// encapsulates its iteration state. public typealias Iterator = IndexingIterator<ReverseCollection> public let _base: Base } /// A Collection that presents the elements of its `Base` collection /// in reverse order. /// /// - Note: This type is the result of `x.reversed()` where `x` is a /// collection having random access indices. /// - See also: `ReverseCollection` public struct ReverseRandomAccessCollection< Base : Collection where Base.Index : RandomAccessIndex > : _ReverseCollection { /// Creates an instance that presents the elements of `base` in /// reverse order. /// /// - Complexity: O(1) internal init(_base: Base) { self._base = _base } /// A type that represents a valid position in the collection. /// /// Valid indices consist of the position of every element and a /// "past the end" position that's not valid for use as a subscript. public typealias Index = ReverseRandomAccessIndex<Base.Index> /// A type that provides the sequence's iteration interface and /// encapsulates its iteration state. public typealias Iterator = IndexingIterator< ReverseRandomAccessCollection > public let _base: Base } extension Collection where Index : BidirectionalIndex { /// Returns the elements of `self` in reverse order. /// /// - Complexity: O(1) @warn_unused_result public func reversed() -> ReverseCollection<Self> { return ReverseCollection(_base: self) } } extension Collection where Index : RandomAccessIndex { /// Returns the elements of `self` in reverse order. /// /// - Complexity: O(1) @warn_unused_result public func reversed() -> ReverseRandomAccessCollection<Self> { return ReverseRandomAccessCollection(_base: self) } } extension LazyCollectionProtocol where Index : BidirectionalIndex, Elements.Index : BidirectionalIndex { /// Returns the elements of `self` in reverse order. /// /// - Complexity: O(1) @warn_unused_result public func reversed() -> LazyCollection< ReverseCollection<Elements> > { return ReverseCollection(_base: elements).lazy } } extension LazyCollectionProtocol where Index : RandomAccessIndex, Elements.Index : RandomAccessIndex { /// Returns the elements of `self` in reverse order. /// /// - Complexity: O(1) @warn_unused_result public func reversed() -> LazyCollection< ReverseRandomAccessCollection<Elements> > { return ReverseRandomAccessCollection(_base: elements).lazy } } extension ReverseCollection { @available(*, unavailable, message="use the 'reversed()' method on the collection") public init(_ base: Base) { fatalError("unavailable function can't be called") } } extension ReverseRandomAccessCollection { @available(*, unavailable, message="use the 'reversed()' method on the collection") public init(_ base: Base) { fatalError("unavailable function can't be called") } } extension Collection where Index : BidirectionalIndex { @available(*, unavailable, renamed="reversed") public func reverse() -> ReverseCollection<Self> { fatalError("unavailable function can't be called") } } extension Collection where Index : RandomAccessIndex { @available(*, unavailable, renamed="reversed") public func reverse() -> ReverseRandomAccessCollection<Self> { fatalError("unavailable function can't be called") } } extension LazyCollectionProtocol where Index : BidirectionalIndex, Elements.Index : BidirectionalIndex { @available(*, unavailable, renamed="reversed") public func reverse() -> LazyCollection< ReverseCollection<Elements> > { fatalError("unavailable function can't be called") } } extension LazyCollectionProtocol where Index : RandomAccessIndex, Elements.Index : RandomAccessIndex { @available(*, unavailable, renamed="reversed") public func reverse() -> LazyCollection< ReverseRandomAccessCollection<Elements> > { fatalError("unavailable function can't be called") } } // ${'Local Variables'}: // eval: (read-only-mode 1) // End:
apache-2.0
773c41d840a559f70926d777ffb61dd4
31.006734
85
0.698401
4.322874
false
false
false
false
bumpersfm/handy
Handy/UIButton.swift
1
3522
// // UIButton.swift // Pods // // Created by Dani Postigo on 8/31/16. // // import Foundation import UIKit extension UIButton { public convenience init(title: String) { self.init(); self.setTitle(title, forState: .Normal) } public convenience init(title: String, font: UIFont) { self.init(title: title) self.titleLabel?.font = font } public convenience init(title: String, font: UIFont, color: UIColor) { self.init(title: title, font: font) self.setTitleColor(color, forState: .Normal) } public convenience init(title: String, backgroundColor: UIColor) { self.init(title: title); self.backgroundColor = backgroundColor } public convenience init(title: String, font: UIFont, color: UIColor, backgroundColor: UIColor) { self.init(title: title, font: font, color: color) self.backgroundColor = backgroundColor } public convenience init(title: String, font: UIFont, color: UIColor, contentEdgeInsets: UIEdgeInsets) { self.init(title: title, font: font, color: color) self.contentEdgeInsets = contentEdgeInsets } public convenience init(title: String, titleColor: UIColor) { self.init(title: title); self.setTitleColor(titleColor, forState: .Normal) } public convenience init(attributedTitle: NSAttributedString) { self.init() self.setAttributedTitle(attributedTitle, forState: .Normal) } public convenience init(image: UIImage?) { self.init() self.setImage(image, forState: .Normal) } public convenience init(image: UIImage?, selectedImage: UIImage?) { self.init(image: image); self.setImage(selectedImage, forState: .Selected) } public convenience init(image: UIImage?, contentEdgeInsets: UIEdgeInsets) { self.init(image: image) self.contentEdgeInsets = contentEdgeInsets } public convenience init(userInteractionEnabled: Bool) { self.init() self.userInteractionEnabled = userInteractionEnabled } // MARK: public convenience init(title: String, color: UIColor) { self.init(title: title, titleColor: color) } // MARK: Attributed strings public var attributes: [String: AnyObject]? { set { guard let newValue = newValue, current = self.attributedTitle else { return } self.attributedTitle = NSAttributedString(string: current.string, attributes: newValue) } get { return self.attributesForState(self.state) } } public var attributedTitle: NSAttributedString? { get { return self.currentAttributedTitle } set { self.setAttributedTitle(newValue, forState: self.state) } } public func replaceAttribute(attribute: String, value: AnyObject?) { guard let string = self.currentMutableAttributedTitle else { return } string.replaceAttribute(attribute, value: value) self.attributedTitle = string } func attributesForState(state: UIControlState) -> [String: AnyObject]? { guard let string = self.attributedTitleForState(state) else { return nil } return string.attributesAtIndex(0, longestEffectiveRange: nil, inRange: NSMakeRange(0, string.length)) } private var currentMutableAttributedTitle: NSMutableAttributedString? { return self.currentAttributedTitle?.mutableCopy() as? NSMutableAttributedString } }
mit
7b39b7880618b65079d468347941df63
33.194175
110
0.665531
4.824658
false
false
false
false
ahoppen/swift
stdlib/public/Concurrency/SourceCompatibilityShims.swift
5
10904
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2020 - 2021 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // This file provides source compatibility shims to help migrate code // using earlier versions of the concurrency library to the latest syntax. //===----------------------------------------------------------------------===// import Swift @_implementationOnly import _SwiftConcurrencyShims @available(SwiftStdlib 5.1, *) extension Task where Success == Never, Failure == Never { @available(*, deprecated, message: "Task.Priority has been removed; use TaskPriority") public typealias Priority = TaskPriority @available(*, deprecated, message: "Task.Handle has been removed; use Task") public typealias Handle = _Concurrency.Task @available(*, deprecated, message: "Task.CancellationError has been removed; use CancellationError") @_alwaysEmitIntoClient public static func CancellationError() -> _Concurrency.CancellationError { return _Concurrency.CancellationError() } @available(*, deprecated, renamed: "yield()") @_alwaysEmitIntoClient public static func suspend() async { await yield() } } @available(SwiftStdlib 5.1, *) extension TaskPriority { @available(*, deprecated, message: "unspecified priority will be removed; use nil") @_alwaysEmitIntoClient public static var unspecified: TaskPriority { .init(rawValue: 0x00) } @available(*, deprecated, message: "userInteractive priority will be removed") @_alwaysEmitIntoClient public static var userInteractive: TaskPriority { .init(rawValue: 0x21) } } @available(SwiftStdlib 5.1, *) @_alwaysEmitIntoClient public func withTaskCancellationHandler<T>( handler: @Sendable () -> Void, operation: () async throws -> T ) async rethrows -> T { try await withTaskCancellationHandler(operation: operation, onCancel: handler) } @available(SwiftStdlib 5.1, *) extension Task where Success == Never, Failure == Never { @available(*, deprecated, message: "`Task.withCancellationHandler` has been replaced by `withTaskCancellationHandler` and will be removed shortly.") @_alwaysEmitIntoClient public static func withCancellationHandler<T>( handler: @Sendable () -> Void, operation: () async throws -> T ) async rethrows -> T { try await withTaskCancellationHandler(handler: handler, operation: operation) } } @available(SwiftStdlib 5.1, *) extension Task where Failure == Error { @discardableResult @_alwaysEmitIntoClient @available(*, deprecated, message: "`Task.runDetached` was replaced by `Task.detached` and will be removed shortly.") public static func runDetached( priority: TaskPriority? = nil, operation: __owned @Sendable @escaping () async throws -> Success ) -> Task<Success, Failure> { detached(priority: priority, operation: operation) } } @discardableResult @available(SwiftStdlib 5.1, *) @available(*, deprecated, message: "`detach` was replaced by `Task.detached` and will be removed shortly.") @_alwaysEmitIntoClient public func detach<T>( priority: TaskPriority? = nil, operation: __owned @Sendable @escaping () async -> T ) -> Task<T, Never> { Task.detached(priority: priority, operation: operation) } @discardableResult @available(SwiftStdlib 5.1, *) @available(*, deprecated, message: "`detach` was replaced by `Task.detached` and will be removed shortly.") @_alwaysEmitIntoClient public func detach<T>( priority: TaskPriority? = nil, operation: __owned @Sendable @escaping () async throws -> T ) -> Task<T, Error> { Task.detached(priority: priority, operation: operation) } @discardableResult @available(SwiftStdlib 5.1, *) @available(*, deprecated, message: "`asyncDetached` was replaced by `Task.detached` and will be removed shortly.") @_alwaysEmitIntoClient public func asyncDetached<T>( priority: TaskPriority? = nil, @_implicitSelfCapture operation: __owned @Sendable @escaping () async -> T ) -> Task<T, Never> { return Task.detached(priority: priority, operation: operation) } @discardableResult @available(SwiftStdlib 5.1, *) @available(*, deprecated, message: "`asyncDetached` was replaced by `Task.detached` and will be removed shortly.") @_alwaysEmitIntoClient public func asyncDetached<T>( priority: TaskPriority? = nil, @_implicitSelfCapture operation: __owned @Sendable @escaping () async throws -> T ) -> Task<T, Error> { return Task.detached(priority: priority, operation: operation) } @available(SwiftStdlib 5.1, *) @available(*, deprecated, message: "`async` was replaced by `Task.init` and will be removed shortly.") @discardableResult @_alwaysEmitIntoClient public func async<T>( priority: TaskPriority? = nil, @_inheritActorContext @_implicitSelfCapture operation: __owned @Sendable @escaping () async -> T ) -> Task<T, Never> { .init(priority: priority, operation: operation) } @available(SwiftStdlib 5.1, *) @available(*, deprecated, message: "`async` was replaced by `Task.init` and will be removed shortly.") @discardableResult @_alwaysEmitIntoClient public func async<T>( priority: TaskPriority? = nil, @_inheritActorContext @_implicitSelfCapture operation: __owned @Sendable @escaping () async throws -> T ) -> Task<T, Error> { .init(priority: priority, operation: operation) } @available(SwiftStdlib 5.1, *) extension Task where Success == Never, Failure == Never { @available(*, deprecated, message: "`Task.Group` was replaced by `ThrowingTaskGroup` and `TaskGroup` and will be removed shortly.") public typealias Group<TaskResult: Sendable> = ThrowingTaskGroup<TaskResult, Error> @available(*, deprecated, message: "`Task.withGroup` was replaced by `withThrowingTaskGroup` and `withTaskGroup` and will be removed shortly.") @_alwaysEmitIntoClient public static func withGroup<TaskResult: Sendable, BodyResult>( resultType: TaskResult.Type, returning returnType: BodyResult.Type = BodyResult.self, body: (inout Task.Group<TaskResult>) async throws -> BodyResult ) async rethrows -> BodyResult { try await withThrowingTaskGroup(of: resultType) { group in try await body(&group) } } } @available(SwiftStdlib 5.1, *) extension Task { @available(*, deprecated, message: "get() has been replaced by .value") @_alwaysEmitIntoClient public func get() async throws -> Success { return try await value } @available(*, deprecated, message: "getResult() has been replaced by .result") @_alwaysEmitIntoClient public func getResult() async -> Result<Success, Failure> { return await result } } @available(SwiftStdlib 5.1, *) extension Task where Failure == Never { @available(*, deprecated, message: "get() has been replaced by .value") @_alwaysEmitIntoClient public func get() async -> Success { return await value } } @available(SwiftStdlib 5.1, *) extension TaskGroup { @available(*, deprecated, renamed: "addTask(priority:operation:)") @_alwaysEmitIntoClient public mutating func add( priority: TaskPriority? = nil, operation: __owned @Sendable @escaping () async -> ChildTaskResult ) async -> Bool { return self.addTaskUnlessCancelled(priority: priority) { await operation() } } @available(*, deprecated, renamed: "addTask(priority:operation:)") @_alwaysEmitIntoClient public mutating func spawn( priority: TaskPriority? = nil, operation: __owned @Sendable @escaping () async -> ChildTaskResult ) { addTask(priority: priority, operation: operation) } @available(*, deprecated, renamed: "addTaskUnlessCancelled(priority:operation:)") @_alwaysEmitIntoClient public mutating func spawnUnlessCancelled( priority: TaskPriority? = nil, operation: __owned @Sendable @escaping () async -> ChildTaskResult ) -> Bool { addTaskUnlessCancelled(priority: priority, operation: operation) } @available(*, deprecated, renamed: "addTask(priority:operation:)") @_alwaysEmitIntoClient public mutating func async( priority: TaskPriority? = nil, operation: __owned @Sendable @escaping () async -> ChildTaskResult ) { addTask(priority: priority, operation: operation) } @available(*, deprecated, renamed: "addTaskUnlessCancelled(priority:operation:)") @_alwaysEmitIntoClient public mutating func asyncUnlessCancelled( priority: TaskPriority? = nil, operation: __owned @Sendable @escaping () async -> ChildTaskResult ) -> Bool { addTaskUnlessCancelled(priority: priority, operation: operation) } } @available(SwiftStdlib 5.1, *) extension ThrowingTaskGroup { @available(*, deprecated, renamed: "addTask(priority:operation:)") @_alwaysEmitIntoClient public mutating func add( priority: TaskPriority? = nil, operation: __owned @Sendable @escaping () async throws -> ChildTaskResult ) async -> Bool { return self.addTaskUnlessCancelled(priority: priority) { try await operation() } } @available(*, deprecated, renamed: "addTask(priority:operation:)") @_alwaysEmitIntoClient public mutating func spawn( priority: TaskPriority? = nil, operation: __owned @Sendable @escaping () async throws -> ChildTaskResult ) { addTask(priority: priority, operation: operation) } @available(*, deprecated, renamed: "addTaskUnlessCancelled(priority:operation:)") @_alwaysEmitIntoClient public mutating func spawnUnlessCancelled( priority: TaskPriority? = nil, operation: __owned @Sendable @escaping () async throws -> ChildTaskResult ) -> Bool { addTaskUnlessCancelled(priority: priority, operation: operation) } @available(*, deprecated, renamed: "addTask(priority:operation:)") @_alwaysEmitIntoClient public mutating func async( priority: TaskPriority? = nil, operation: __owned @Sendable @escaping () async throws -> ChildTaskResult ) { addTask(priority: priority, operation: operation) } @available(*, deprecated, renamed: "addTaskUnlessCancelled(priority:operation:)") @_alwaysEmitIntoClient public mutating func asyncUnlessCancelled( priority: TaskPriority? = nil, operation: __owned @Sendable @escaping () async throws -> ChildTaskResult ) -> Bool { addTaskUnlessCancelled(priority: priority, operation: operation) } } @available(SwiftStdlib 5.1, *) @available(*, deprecated, message: "please use UnsafeContinuation<..., Error>") public typealias UnsafeThrowingContinuation<T> = UnsafeContinuation<T, Error> @available(SwiftStdlib 5.1, *) @available(*, deprecated, renamed: "UnownedJob") public typealias PartialAsyncTask = UnownedJob
apache-2.0
346428e8b20b724e6d9bd4fbb6df50b4
34.986799
150
0.71084
4.643952
false
false
false
false
JGiola/swift
test/SILOptimizer/closure_lifetime_fixup_objc.swift
1
8604
// RUN: %target-swift-frontend %s -sil-verify-all -emit-sil -enable-copy-propagation=false -o - -I %S/Inputs/usr/include | %FileCheck %s // REQUIRES: objc_interop // Using -enable-copy-propagation=false to pattern match against older SIL // output. At least until -enable-copy-propagation has been around // long enough in the same form to be worth rewriting CHECK lines. import Foundation import ClosureLifetimeFixupObjC @objc public protocol DangerousEscaper { @objc func malicious(_ mayActuallyEscape: () -> ()) } // CHECK: sil @$s27closure_lifetime_fixup_objc19couldActuallyEscapeyyyyc_AA16DangerousEscaper_ptF : $@convention(thin) (@guaranteed @callee_guaranteed () -> (), @guaranteed DangerousEscaper) -> () { // CHECK: bb0([[ARG:%.*]] : $@callee_guaranteed () -> (), [[SELF:%.*]] : $DangerousEscaper): // CHECK: [[OE:%.*]] = open_existential_ref [[SELF]] // Extend the lifetime to the end of this function (2). // CHECK: strong_retain [[ARG]] : $@callee_guaranteed () -> () // CHECK: [[NE:%.*]] = convert_escape_to_noescape [[ARG]] : $@callee_guaranteed () -> () to $@noescape @callee_guaranteed () -> () // CHECK: [[WITHOUT_ACTUALLY_ESCAPING_THUNK:%.*]] = function_ref @$sIg_Ieg_TR : $@convention(thin) (@noescape @callee_guaranteed () -> ()) -> () // CHECK: [[C:%.*]] = partial_apply [callee_guaranteed] [[WITHOUT_ACTUALLY_ESCAPING_THUNK]]([[NE]]) : $@convention(thin) (@noescape @callee_guaranteed () -> ()) -> () // Sentinel without actually escaping closure (3). // CHECK: [[SENTINEL:%.*]] = mark_dependence [[C]] : $@callee_guaranteed () -> () on [[NE]] : $@noescape @callee_guaranteed () -> () // Copy of sentinel (4). // CHECK: strong_retain [[SENTINEL]] : $@callee_guaranteed () -> () // CHECK: [[BLOCK_STORAGE:%.*]] = alloc_stack $@block_storage @callee_guaranteed () -> () // CHECK: [[CLOSURE_ADDR:%.*]] = project_block_storage [[BLOCK_STORAGE]] : $*@block_storage @callee_guaranteed () -> () // CHECK: store [[SENTINEL]] to [[CLOSURE_ADDR]] : $*@callee_guaranteed () -> () // CHECK: [[BLOCK_INVOKE:%.*]] = function_ref @$sIeg_IyB_TR : $@convention(c) (@inout_aliasable @block_storage @callee_guaranteed () -> ()) -> () // CHECK: [[BLOCK:%.*]] = init_block_storage_header [[BLOCK_STORAGE]] : $*@block_storage @callee_guaranteed () -> (), invoke [[BLOCK_INVOKE]] : $@convention(c) (@inout_aliasable @block_storage @callee_guaranteed () -> ()) -> (), type $@convention(block) @noescape () -> () // Copy of sentinel closure (5). // CHECK: [[BLOCK_COPY:%.*]] = copy_block [[BLOCK]] : $@convention(block) @noescape () -> () // Release of sentinel closure (3). // CHECK: destroy_addr [[CLOSURE_ADDR]] : $*@callee_guaranteed () -> () // CHECK: dealloc_stack [[BLOCK_STORAGE]] : $*@block_storage @callee_guaranteed () -> () // CHECK: [[METH:%.*]] = objc_method [[OE]] : $@opened("{{.*}}", DangerousEscaper) Self, #DangerousEscaper.malicious!foreign : <Self where Self : DangerousEscaper> (Self) -> (() -> ()) -> (), $@convention(objc_method) <τ_0_0 where τ_0_0 : DangerousEscaper> (@convention(block) @noescape () -> (), τ_0_0) -> () // CHECK: apply [[METH]]<@opened("{{.*}}", DangerousEscaper) Self>([[BLOCK_COPY]], [[OE]]) : $@convention(objc_method) <τ_0_0 where τ_0_0 : DangerousEscaper> (@convention(block) @noescape () -> (), τ_0_0) -> () // Release sentinel closure copy (5). // CHECK: strong_release [[BLOCK_COPY]] : $@convention(block) @noescape () -> () // CHECK: [[ESCAPED:%.*]] = is_escaping_closure [objc] [[SENTINEL]] // CHECK: cond_fail [[ESCAPED]] : $Builtin.Int1 // Release of sentinel copy (4). // CHECK: strong_release [[SENTINEL]] // Extendend lifetime (2). // CHECK: strong_release [[ARG]] // CHECK: return // CHECK: } // end sil function '$s27closure_lifetime_fixup_objc19couldActuallyEscapeyyyyc_AA16DangerousEscaper_ptF' public func couldActuallyEscape(_ closure: @escaping () -> (), _ villian: DangerousEscaper) { villian.malicious(closure) } // Make sure that we respect the ownership verifier. // // CHECK-LABEL: sil @$s27closure_lifetime_fixup_objc27couldActuallyEscapeWithLoopyyyyc_AA16DangerousEscaper_ptF : $@convention(thin) (@guaranteed @callee_guaranteed () -> (), @guaranteed DangerousEscaper) -> () { public func couldActuallyEscapeWithLoop(_ closure: @escaping () -> (), _ villian: DangerousEscaper) { for _ in 0..<2 { villian.malicious(closure) } } // We need to store nil on the back-edge. // CHECK-LABEL: sil @$s27closure_lifetime_fixup_objc9dontCrashyyF : $@convention(thin) () -> () { // CHECK: bb0: // CHECK: [[NONE:%.*]] = enum $Optional<{{.*}}>, #Optional.none!enumelt // CHECK: br bb1 // // CHECK: bb1: // CHECK: br bb2 // // CHECK: bb2: // CHECK: br [[LOOP_HEADER_BB:bb[0-9]+]]([[NONE]] // // CHECK: [[LOOP_HEADER_BB]]([[LOOP_IND_VAR:%.*]] : $Optional // CHECK: switch_enum {{.*}} : $Optional<Int>, case #Optional.some!enumelt: [[SUCC_BB:bb[0-9]+]], case #Optional.none!enumelt: [[NONE_BB:bb[0-9]+]] // // CHECK: [[SUCC_BB]]( // CHECK: [[THUNK_FUNC:%.*]] = function_ref @$sIg_Ieg_TR : // CHECK: [[PAI:%.*]] = partial_apply [callee_guaranteed] [[THUNK_FUNC]]( // CHECK: [[MDI:%.*]] = mark_dependence [[PAI]] // CHECK: strong_retain [[MDI]] // CHECK: [[BLOCK_SLOT:%.*]] = alloc_stack $@block_storage @callee_guaranteed () -> () // CHECK: [[BLOCK_PROJ:%.*]] = project_block_storage [[BLOCK_SLOT]] // CHECK: store [[MDI]] to [[BLOCK_PROJ]] : // CHECK: [[BLOCK:%.*]] = init_block_storage_header [[BLOCK_SLOT]] // CHECK: release_value [[LOOP_IND_VAR]] // CHECK: [[SOME:%.*]] = enum $Optional<{{.*}}>, #Optional.some!enumelt, [[MDI]] // CHECK: [[BLOCK_COPY:%.*]] = copy_block [[BLOCK]] // CHECK: destroy_addr [[BLOCK_PROJ]] // CHECK: [[DISPATCH_SYNC_FUNC:%.*]] = function_ref @dispatch_sync : // CHECK: apply [[DISPATCH_SYNC_FUNC]]({{%.*}}, [[BLOCK_COPY]]) // CHECK: strong_release [[BLOCK_COPY]] // CHECK: is_escaping_closure [objc] [[SOME]] // CHECK: release_value [[SOME]] // CHECK: [[NONE_FOR_BACKEDGE:%.*]] = enum $Optional<{{.*}}>, #Optional.none // CHECK: br [[LOOP_HEADER_BB]]([[NONE_FOR_BACKEDGE]] : // // CHECK: [[NONE_BB]]: // CHECK: release_value [[LOOP_IND_VAR]] // CHECK: return // CHECK: } // end sil function '$s27closure_lifetime_fixup_objc9dontCrashyyF' public func dontCrash() { for i in 0 ..< 2 { let queue = DispatchQueue(label: "Foo") queue.sync { } } } @_silgen_name("getDispatchQueue") func getDispatchQueue() -> DispatchQueue // We must not release the closure after calling super.deinit. // CHECK: sil hidden @$s27closure_lifetime_fixup_objc1CCfD : $@convention(method) (@owned C) -> () { // CHECK: bb0([[SELF:%.*]] : $C): // CHECK: [[F:%.*]] = function_ref @$s27closure_lifetime_fixup_objc1CCfdyyXEfU_ // CHECK: [[PA:%.*]] = partial_apply [callee_guaranteed] [[F]]([[SELF]]) // CHECK: [[DEINIT:%.*]] = objc_super_method [[SELF]] : $C, #NSObject.deinit!deallocator.foreign // CHECK: strong_release [[PA]] // CHECK: [[SUPER:%.*]] = upcast [[SELF]] : $C to $NSObject // CHECK-NEXT: apply [[DEINIT]]([[SUPER]]) : $@convention(objc_method) (NSObject) -> () // CHECK-NEXT: [[T:%.*]] = tuple () // CHECK-NEXT: return [[T]] : $() // CHECK: } // end sil function '$s27closure_lifetime_fixup_objc1CCfD' class C: NSObject { deinit { getDispatchQueue().sync(execute: { _ = self }) } } // Make sure even if we have a loop, we do not release the value after calling super.deinit // CHECK-LABEL: sil hidden @$s27closure_lifetime_fixup_objc9CWithLoopCfD : $@convention(method) (@owned CWithLoop) -> () { // CHECK: [[METH:%.*]] = objc_super_method // CHECK-NEXT: release_value // CHECK-NEXT: release_value // CHECK-NEXT: upcast {{%.*}} : $CWithLoop to $NSObject // CHECK-NEXT: apply [[METH]]({{%.*}}) : $@convention(objc_method) (NSObject) -> () // CHECK-NEXT: tuple () // CHECK-NEXT: return // CHECK: } // end sil function '$s27closure_lifetime_fixup_objc9CWithLoopCfD' class CWithLoop : NSObject { deinit { for _ in 0..<2 { getDispatchQueue().sync(execute: { _ = self }) } } } class CWithLoopReturn : NSObject { deinit { for _ in 0..<2 { getDispatchQueue().sync(execute: { _ = self }) return } } } // Make sure that we obey ownership invariants when we emit load_borrow. internal typealias MyBlock = @convention(block) () -> Void func getBlock(noEscapeBlock: () -> Void ) -> MyBlock { return block_create_noescape(noEscapeBlock) } func getBlockWithLoop(noEscapeBlock: () -> Void ) -> MyBlock { for _ in 0..<2 { return block_create_noescape(noEscapeBlock) } return (Optional<MyBlock>.none)! }
apache-2.0
0d2b248ea5e59bd29e8f893c7cf160c0
46.502762
311
0.625611
3.409199
false
false
false
false
choofie/MusicTinder
MusicTinder/Classes/BusinessLogic/Services/Artist/ArtistService.swift
1
10487
// // ArtistService.swift // MusicTinder // // Created by Mate Lorincz on 05/11/16. // Copyright © 2016 MateLorincz. All rights reserved. // import Foundation protocol SearchDelegate : class { func searchFinishedWithResult(_ result: [Artist]) func searchFinishedWithError(_ error: String) } protocol GetSimilarDelegate : class { func getSimilarFinishedWithResult(_ result: [Artist]) func getSimilarFinishedWithError(_ error: String) } protocol GetInfoDelegate : class { func getInfoFinishedWithResult(_ result: String) func getInfoFinishedWithError(_ error: String) } class ArtistService { weak var searchDelegate: SearchDelegate? weak var getSimilarDelegate: GetSimilarDelegate? weak var getInfoDelegate: GetInfoDelegate? init(searchDelegate: SearchDelegate) { self.searchDelegate = searchDelegate } init(getSimilarDelegate: GetSimilarDelegate) { self.getSimilarDelegate = getSimilarDelegate } init(getInfoDelegate: GetInfoDelegate) { self.getInfoDelegate = getInfoDelegate } func search(_ artistName: String) { let validatedArtistName = artistName.folding(options: .diacriticInsensitive, locale: nil) guard let urlString = URLProvider.artistSearchURLString(validatedArtistName) else { self.loadSearchCachedResponse() return } guard let url = URL(string: urlString.appendResultFormat(.JSON)) else { return } var request = URLRequest(url: url) request.httpMethod = "GET" request.timeoutInterval = DefaultTimeoutInterval let session = URLSession.shared let task = session.dataTask(with: request) { (data, response, error) -> Void in if let _ = error { self.loadSearchCachedResponse() } else { guard let data = data else { self.loadSearchCachedResponse() return } do { let jsonResult = try JSONSerialization.jsonObject(with: data, options:.allowFragments) self.searchDelegate?.searchFinishedWithResult(self.processSearchResult(jsonResult as AnyObject)) } catch _ as NSError { self.loadSearchCachedResponse() } } } task.resume() } func getSimilar(_ artistName: String) { let validatedArtistName = artistName.folding(options: .diacriticInsensitive, locale: nil) guard let urlString = URLProvider.similartArtistsURLString(validatedArtistName) else { self.loadGetSimilarCachedResponse() return } guard let url = URL(string: urlString.appendResultFormat(.JSON)) else { return } var request = URLRequest(url: url) request.httpMethod = "GET" request.timeoutInterval = DefaultTimeoutInterval let session = URLSession.shared let task = session.dataTask(with: request) { (data, response, error) -> Void in if let _ = error { self.loadGetSimilarCachedResponse() } else { guard let data = data else { self.loadGetSimilarCachedResponse() return } do { let jsonResult = try JSONSerialization.jsonObject(with: data, options:.allowFragments) self.getSimilarDelegate?.getSimilarFinishedWithResult(self.processGetSimilarResult(jsonResult as AnyObject)) } catch _ as NSError { self.loadGetSimilarCachedResponse() } } } task.resume() } func getInfo(_ artistName: String) { let validatedArtistName = artistName.folding(options: .diacriticInsensitive, locale: nil) guard let urlString = URLProvider.artistInfoURLString(validatedArtistName) else { self.loadGetInfoCachedResponse() return } guard let url = URL(string: urlString.appendResultFormat(.JSON)) else { return } var request = URLRequest(url: url) request.httpMethod = "GET" request.timeoutInterval = DefaultTimeoutInterval let session = URLSession.shared let task = session.dataTask(with: request) { (data, response, error) -> Void in if let _ = error { self.loadGetInfoCachedResponse() } else { guard let data = data else { self.loadGetInfoCachedResponse() return } do { let jsonResult = try JSONSerialization.jsonObject(with: data, options:.allowFragments) self.getInfoDelegate?.getInfoFinishedWithResult(self.processGetInfoResult(jsonResult as AnyObject)) } catch _ as NSError { self.loadGetInfoCachedResponse() } } } task.resume() } } private extension ArtistService { func loadSearchCachedResponse() { if let path = Bundle.main.path(forResource: "search", ofType: "json") { do { let jsonData = try Data(contentsOf: URL(fileURLWithPath: path), options: NSData.ReadingOptions.mappedIfSafe) let jsonResult = try JSONSerialization.jsonObject(with: jsonData, options:.allowFragments) searchDelegate?.searchFinishedWithResult(processSearchResult(jsonResult as AnyObject)) } catch let error as NSError { searchDelegate?.searchFinishedWithError(error.localizedDescription) } } else { searchDelegate?.searchFinishedWithError("Invalid filename/path") } } func loadGetSimilarCachedResponse() { if let path = Bundle.main.path(forResource: "getSimilar", ofType: "json") { do { let jsonData = try Data(contentsOf: URL(fileURLWithPath: path), options: NSData.ReadingOptions.mappedIfSafe) let jsonResult = try JSONSerialization.jsonObject(with: jsonData, options:.allowFragments) getSimilarDelegate?.getSimilarFinishedWithResult(processGetSimilarResult(jsonResult as AnyObject)) } catch let error as NSError { getSimilarDelegate?.getSimilarFinishedWithError(error.localizedDescription) } } else { getSimilarDelegate?.getSimilarFinishedWithError("Invalid filename/path") } } func loadGetInfoCachedResponse() { if let path = Bundle.main.path(forResource: "getInfo", ofType: "json") { do { let jsonData = try Data(contentsOf: URL(fileURLWithPath: path), options: NSData.ReadingOptions.mappedIfSafe) let jsonResult = try JSONSerialization.jsonObject(with: jsonData, options:.allowFragments) getInfoDelegate?.getInfoFinishedWithResult(processGetInfoResult(jsonResult as AnyObject)) } catch let error as NSError { getInfoDelegate?.getInfoFinishedWithError(error.localizedDescription) } } else { getInfoDelegate?.getInfoFinishedWithError("Invalid filename/path") } } func processSearchResult(_ resultData: AnyObject) -> [Artist] { var result: [Artist] = [] if let resultsDictionary = resultData["results"] as? [String : AnyObject] { if let matchesDictionary = resultsDictionary["artistmatches"] as? [String : AnyObject] { if let artistArray = matchesDictionary["artist"] as? [AnyObject] { for artistData in artistArray { if let artistData = artistData as? [String : AnyObject] { if let name = artistData["name"] as? String, let mbid = artistData["mbid"] as? String, let images = artistData["image"] as? [[String : String]] { if let imageURL = images[images.count - 2]["#text"], imageURL.isEmpty == false { result.append(Artist(name: name , mbid: mbid , info: "no info", genre: "no genre", imageURL: URL(string:imageURL)!)) } } } } } } } return result } func processGetSimilarResult(_ resultData: AnyObject) -> [Artist] { var result: [Artist] = [] if let similarDictionary = resultData["similarartists"] as? [String : AnyObject] { if let artistArray = similarDictionary["artist"] as? [AnyObject] { for artistData in artistArray { if let artistData = artistData as? [String : AnyObject] { if let name = artistData["name"] as? String, let mbid = artistData["mbid"] as? String, let images = artistData["image"] as? [[String : String]] { if let imageURL = images[images.count - 3]["#text"], imageURL.isEmpty == false { result.append(Artist(name: name , mbid: mbid , info: "no info", genre: "no genre", imageURL: URL(string:imageURL)!)) } } } } } } return result } func processGetInfoResult(_ resultData: AnyObject) -> String { var result: String = "" if let artistDictionary = resultData["artist"] as? [String : AnyObject] { if let bioDictionary = artistDictionary["bio"] as? [String : AnyObject] { if let info = bioDictionary["summary"] as? String { result = info } } } return result.replacingOccurrences(of: "<[^>]+>", with: "", options: .regularExpression, range: nil) } }
mit
7049218fc9f0bf1c930867b1645028ef
36.719424
173
0.561129
5.438797
false
false
false
false
ahoppen/swift
test/attr/attributes.swift
4
13644
// RUN: %target-typecheck-verify-swift -enable-objc-interop @unknown func f0() {} // expected-error{{unknown attribute 'unknown'}} @unknown(x,y) func f1() {} // expected-error{{unknown attribute 'unknown'}} enum binary { case Zero case One init() { self = .Zero } } func f5(x: inout binary) {} //===--- //===--- IB attributes //===--- @IBDesignable class IBDesignableClassTy { @IBDesignable func foo() {} // expected-error {{'@IBDesignable' attribute cannot be applied to this declaration}} {{3-17=}} } @IBDesignable // expected-error {{'@IBDesignable' attribute cannot be applied to this declaration}} {{1-15=}} struct IBDesignableStructTy {} @IBDesignable // expected-error {{'@IBDesignable' attribute cannot be applied to this declaration}} {{1-15=}} protocol IBDesignableProtTy {} @IBDesignable // expected-error {{@IBDesignable can only be applied to classes and extensions of classes}} {{1-15=}} extension IBDesignableStructTy {} class IBDesignableClassExtensionTy {} @IBDesignable // okay extension IBDesignableClassExtensionTy {} class Inspect { @IBInspectable var value : Int = 0 // okay @GKInspectable var value2: Int = 0 // okay @IBInspectable func foo() {} // expected-error {{@IBInspectable may only be used on 'var' declarations}} {{3-18=}} @GKInspectable func foo2() {} // expected-error {{@GKInspectable may only be used on 'var' declarations}} {{3-18=}} @IBInspectable class var cval: Int { return 0 } // expected-error {{only instance properties can be declared @IBInspectable}} {{3-18=}} @GKInspectable class var cval2: Int { return 0 } // expected-error {{only instance properties can be declared @GKInspectable}} {{3-18=}} } @IBInspectable var ibinspectable_global : Int // expected-error {{only instance properties can be declared @IBInspectable}} {{1-16=}} @GKInspectable var gkinspectable_global : Int // expected-error {{only instance properties can be declared @GKInspectable}} {{1-16=}} func foo(x: @convention(block) Int) {} // expected-error {{@convention attribute only applies to function types}} func foo(x: @convention(block) (Int) -> Int) {} @_transparent func zim() {} @_transparent func zung<T>(_: T) {} @_transparent // expected-error{{'@_transparent' attribute cannot be applied to stored properties}} {{1-15=}} var zippity : Int func zoom(x: @_transparent () -> ()) { } // expected-error{{attribute can only be applied to declarations, not types}} {{1-1=@_transparent }} {{14-28=}} protocol ProtoWithTransparent { @_transparent// expected-error{{'@_transparent' attribute is not supported on declarations within protocols}} {{3-16=}} func transInProto() } class TestTranspClass : ProtoWithTransparent { @_transparent // expected-error{{'@_transparent' attribute is not supported on declarations within classes}} {{3-17=}} init () {} @_transparent // expected-error{{'@_transparent' attribute cannot be applied to this declaration}} {{3-17=}} deinit {} @_transparent // expected-error{{'@_transparent' attribute is not supported on declarations within classes}} {{3-17=}} class func transStatic() {} @_transparent// expected-error{{'@_transparent' attribute is not supported on declarations within classes}} {{3-16=}} func transInProto() {} } struct TestTranspStruct : ProtoWithTransparent{ @_transparent init () {} @_transparent init <T> (x : T) { } @_transparent static func transStatic() {} @_transparent func transInProto() {} } @_transparent // expected-error{{'@_transparent' attribute cannot be applied to this declaration}} {{1-15=}} struct CannotHaveTransparentStruct { func m1() {} } @_transparent // expected-error{{'@_transparent' attribute cannot be applied to this declaration}} {{1-15=}} extension TestTranspClass { func tr1() {} } @_transparent // expected-error{{'@_transparent' attribute cannot be applied to this declaration}} {{1-15=}} extension TestTranspStruct { func tr1() {} } @_transparent // expected-error{{'@_transparent' attribute cannot be applied to this declaration}} {{1-15=}} extension binary { func tr1() {} } class transparentOnClassVar { @_transparent var max: Int { return 0xFF }; // expected-error {{'@_transparent' attribute is not supported on declarations within classes}} {{3-17=}} func blah () { var _: Int = max } }; class transparentOnClassVar2 { var max: Int { @_transparent // expected-error {{'@_transparent' attribute is not supported on declarations within classes}} {{5-19=}} get { return 0xFF } } func blah () { var _: Int = max } }; @thin // expected-error {{attribute can only be applied to types, not declarations}} func testThinDecl() -> () {} protocol Class : class {} protocol NonClass {} @objc class Ty0 : Class, NonClass { init() { } } // Attributes that should be reported by parser as unknown // See rdar://19533915 @__setterAccess struct S__accessibility {} // expected-error{{unknown attribute '__setterAccess'}} @__raw_doc_comment struct S__raw_doc_comment {} // expected-error{{unknown attribute '__raw_doc_comment'}} @__objc_bridged struct S__objc_bridged {} // expected-error{{unknown attribute '__objc_bridged'}} weak var weak0 : Ty0? weak var weak0x : Ty0? weak unowned var weak1 : Ty0? // expected-error {{duplicate modifier}} expected-note {{modifier already specified here}} weak weak var weak2 : Ty0? // expected-error {{duplicate modifier}} expected-note {{modifier already specified here}} unowned var weak3 : Ty0 unowned var weak3a : Ty0 unowned(safe) var weak3b : Ty0 unowned(unsafe) var weak3c : Ty0 unowned unowned var weak4 : Ty0 // expected-error {{duplicate modifier}} expected-note {{modifier already specified here}} unowned weak var weak5 : Ty0 // expected-error {{duplicate modifier}} expected-note {{modifier already specified here}} weak var weak6 : Int? // expected-error {{'weak' may only be applied to class and class-bound protocol types, not 'Int'}} unowned var weak7 : Int // expected-error {{'unowned' may only be applied to class and class-bound protocol types, not 'Int'}} weak var weak8 : Class? = Ty0() // expected-warning@-1 {{instance will be immediately deallocated because variable 'weak8' is 'weak'}} // expected-note@-2 {{a strong reference is required to prevent the instance from being deallocated}} // expected-note@-3 {{'weak8' declared here}} unowned var weak9 : Class = Ty0() // expected-warning@-1 {{instance will be immediately deallocated because variable 'weak9' is 'unowned'}} // expected-note@-2 {{a strong reference is required to prevent the instance from being deallocated}} // expected-note@-3 {{'weak9' declared here}} weak var weak10 : NonClass? = Ty0() // expected-error {{'weak' must not be applied to non-class-bound 'any NonClass'; consider adding a protocol conformance that has a class bound}} unowned var weak11 : NonClass = Ty0() // expected-error {{'unowned' must not be applied to non-class-bound 'any NonClass'; consider adding a protocol conformance that has a class bound}} unowned var weak12 : NonClass = Ty0() // expected-error {{'unowned' must not be applied to non-class-bound 'any NonClass'; consider adding a protocol conformance that has a class bound}} unowned var weak13 : NonClass = Ty0() // expected-error {{'unowned' must not be applied to non-class-bound 'any NonClass'; consider adding a protocol conformance that has a class bound}} weak var weak14 : Ty0 // expected-error {{'weak' variable should have optional type 'Ty0?'}} weak var weak15 : Class // expected-error {{'weak' variable should have optional type '(any Class)?'}} weak var weak16 : Class! @weak var weak17 : Class? // expected-error {{'weak' is a declaration modifier, not an attribute}} {{1-2=}} @_exported var exportVar: Int // expected-error {{@_exported may only be used on 'import' declarations}}{{1-12=}} @_exported func exportFunc() {} // expected-error {{@_exported may only be used on 'import' declarations}}{{1-12=}} @_exported struct ExportStruct {} // expected-error {{@_exported may only be used on 'import' declarations}}{{1-12=}} // Function result type attributes. var func_result_type_attr : () -> @xyz Int // expected-error {{unknown attribute 'xyz'}} func func_result_attr() -> @xyz Int { // expected-error {{unknown attribute 'xyz'}} return 4 } func func_with_unknown_attr1(@unknown(*) x: Int) {} // expected-error {{unknown attribute 'unknown'}} func func_with_unknown_attr2(x: @unknown(_) Int) {} // expected-error {{unknown attribute 'unknown'}} func func_with_unknown_attr3(x: @unknown(Int) -> Int) {} // expected-error {{unknown attribute 'unknown'}} func func_with_unknown_attr4(x: @unknown(Int) throws -> Int) {} // expected-error {{unknown attribute 'unknown'}} func func_with_unknown_attr5(x: @unknown (x: Int, y: Int)) {} // expected-error {{unknown attribute 'unknown'}} func func_with_unknown_attr6(x: @unknown(x: Int, y: Int)) {} // expected-error {{unknown attribute 'unknown'}} func func_with_unknown_attr7(x: @unknown (Int) () -> Int) {} // expected-error {{unknown attribute 'unknown'}} func func_type_attribute_with_space(x: @convention (c) () -> Int) {} // OK. Known attributes can have space before its paren. // @thin and @pseudogeneric are not supported except in SIL. var thinFunc : @thin () -> () // expected-error {{unknown attribute 'thin'}} var pseudoGenericFunc : @pseudogeneric () -> () // expected-error {{unknown attribute 'pseudogeneric'}} @inline(never) func nolineFunc() {} @inline(never) var noinlineVar : Int { return 0 } @inline(never) class FooClass { // expected-error {{'@inline(never)' attribute cannot be applied to this declaration}} {{1-16=}} } @inline(__always) func AlwaysInlineFunc() {} @inline(__always) var alwaysInlineVar : Int { return 0 } @inline(__always) class FooClass2 { // expected-error {{'@inline(__always)' attribute cannot be applied to this declaration}} {{1-19=}} } @_optimize(speed) func OspeedFunc() {} @_optimize(speed) var OpeedVar : Int // expected-error {{'@_optimize(speed)' attribute cannot be applied to stored properties}} {{1-19=}} @_optimize(speed) class OspeedClass { // expected-error {{'@_optimize(speed)' attribute cannot be applied to this declaration}} {{1-19=}} } class A { @inline(never) init(a : Int) {} var b : Int { @inline(never) get { return 42 } @inline(never) set { } } } class B { @inline(__always) init(a : Int) {} var b : Int { @inline(__always) get { return 42 } @inline(__always) set { } } } class C { @_optimize(speed) init(a : Int) {} var b : Int { @_optimize(none) get { return 42 } @_optimize(size) set { } } @_optimize(size) var c : Int // expected-error {{'@_optimize(size)' attribute cannot be applied to stored properties}} } @exclusivity(checked) // ok var globalCheckedVar = 1 @exclusivity(unchecked) // ok var globalUncheckedVar = 1 @exclusivity(abc) // // expected-error {{unknown option 'abc' for attribute 'exclusivity'}} var globalUnknownVar = 1 struct ExclusivityAttrStruct { @exclusivity(unchecked) // expected-error {{@exclusivity can only be used on class properties, static properties and global variables}} var instanceVar: Int = 27 @exclusivity(unchecked) // ok static var staticVar: Int = 27 @exclusivity(unchecked) // expected-error {{@exclusivity can only be used on stored properties}} static var staticComputedVar: Int { return 1 } } class ExclusivityAttrClass { @exclusivity(unchecked) // ok var instanceVar: Int = 27 @exclusivity(unchecked) // ok static var staticVar: Int = 27 @exclusivity(unchecked) // expected-error {{@exclusivity can only be used on stored properties}} static var staticComputedVar: Int { return 1 } } class HasStorage { @_hasStorage var x : Int = 42 // ok, _hasStorage is allowed here } @_show_in_interface protocol _underscored {} @_show_in_interface class _notapplicable {} // expected-error {{may only be used on 'protocol' declarations}} // Error recovery after one invalid attribute @_invalid_attribute_ // expected-error {{unknown attribute '_invalid_attribute_'}} @inline(__always) public func sillyFunction() {} // rdar://problem/45732251: unowned/unowned(unsafe) optional lets are permitted func unownedOptionals(x: C) { unowned let y: C? = x unowned(unsafe) let y2: C? = x _ = y _ = y2 } // @_nonEphemeral attribute struct S1<T> { func foo(@_nonEphemeral _ x: String) {} // expected-error {{@_nonEphemeral attribute only applies to pointer types}} func bar(@_nonEphemeral _ x: T) {} // expected-error {{@_nonEphemeral attribute only applies to pointer types}} func baz<U>(@_nonEphemeral _ x: U) {} // expected-error {{@_nonEphemeral attribute only applies to pointer types}} func qux(@_nonEphemeral _ x: UnsafeMutableRawPointer) {} func quux(@_nonEphemeral _ x: UnsafeMutablePointer<Int>?) {} } @_nonEphemeral struct S2 {} // expected-error {{@_nonEphemeral may only be used on 'parameter' declarations}} protocol P {} extension P { // Allow @_nonEphemeral on the protocol Self type, as the protocol could be adopted by a pointer type. func foo(@_nonEphemeral _ x: Self) {} func bar(@_nonEphemeral _ x: Self?) {} } enum E1 { case str(@_nonEphemeral _: String) // expected-error {{expected parameter name followed by ':'}} case ptr(@_nonEphemeral _: UnsafeMutableRawPointer) // expected-error {{expected parameter name followed by ':'}} func foo() -> @_nonEphemeral UnsafeMutableRawPointer? { return nil } // expected-error {{attribute can only be applied to declarations, not types}} } @_custom func testCustomAttribute() {} // expected-error {{unknown attribute '_custom'}}
apache-2.0
7377f4ca50f85a3e0a30823a46f31860
38.433526
178
0.698476
3.960522
false
false
false
false
overtake/TelegramSwift
Telegram-Mac/CoreExtension.swift
1
125267
// // CoreExtension.swift // Telegram-Mac // // Created by keepcoder on 06/11/2016. // Copyright © 2016 Telegram. All rights reserved. // import Cocoa import TelegramCore import Localization import Postbox import SwiftSignalKit import TGUIKit import ApiCredentials import MtProtoKit import TGPassportMRZ import InAppSettings import ColorPalette import ThemeSettings import Accelerate import TGModernGrowingTextView extension RenderedChannelParticipant { func withUpdatedBannedRights(_ info: ChannelParticipantBannedInfo) -> RenderedChannelParticipant { let updated: ChannelParticipant switch participant { case let.member(id, invitedAt, adminInfo, _, rank): updated = ChannelParticipant.member(id: id, invitedAt: invitedAt, adminInfo: adminInfo, banInfo: info, rank: rank) case let .creator(id, info, rank): updated = ChannelParticipant.creator(id: id, adminInfo: info, rank: rank) } return RenderedChannelParticipant(participant: updated, peer: peer, presences: presences) } func withUpdatedAdditionalPeers(_ additional:[PeerId:Peer]) -> RenderedChannelParticipant { return RenderedChannelParticipant(participant: participant, peer: peer, peers: peers + additional, presences: presences) } var isCreator: Bool { return participant.isCreator } } extension ChannelParticipant { var isCreator:Bool { switch self { case .creator: return true default: return false } } } extension TelegramChatAdminRightsFlags { var localizedString:String { switch self { case TelegramChatAdminRightsFlags.canAddAdmins: return strings().eventLogServicePromoteAddNewAdmins case TelegramChatAdminRightsFlags.canBanUsers: return strings().eventLogServicePromoteBanUsers case TelegramChatAdminRightsFlags.canChangeInfo: return strings().eventLogServicePromoteChangeInfo case TelegramChatAdminRightsFlags.canInviteUsers: return strings().eventLogServicePromoteAddUsers case TelegramChatAdminRightsFlags.canDeleteMessages: return strings().eventLogServicePromoteDeleteMessages case TelegramChatAdminRightsFlags.canEditMessages: return strings().eventLogServicePromoteEditMessages case TelegramChatAdminRightsFlags.canPinMessages: return strings().eventLogServicePromotePinMessages case TelegramChatAdminRightsFlags.canPostMessages: return strings().eventLogServicePromotePostMessages case TelegramChatAdminRightsFlags.canBeAnonymous: return strings().eventLogServicePromoteRemainAnonymous case TelegramChatAdminRightsFlags.canManageCalls: return strings().channelAdminLogCanManageCalls case TelegramChatAdminRightsFlags.canManageTopics: return strings().channelAdminLogCanManageTopics default: return "Undefined Promotion" } } } extension TelegramChatBannedRightsFlags { var localizedString:String { switch self { case TelegramChatBannedRightsFlags.banSendGifs: return strings().eventLogServiceDemoteSendGifs case TelegramChatBannedRightsFlags.banPinMessages: return strings().eventLogServiceDemotePinMessages case TelegramChatBannedRightsFlags.banAddMembers: return strings().eventLogServiceDemoteAddMembers case TelegramChatBannedRightsFlags.banSendPolls: return strings().eventLogServiceDemotePostPolls case TelegramChatBannedRightsFlags.banEmbedLinks: return strings().eventLogServiceDemoteEmbedLinks case TelegramChatBannedRightsFlags.banReadMessages: return "" case TelegramChatBannedRightsFlags.banSendGames: return strings().eventLogServiceDemoteEmbedLinks case TelegramChatBannedRightsFlags.banSendInline: return strings().eventLogServiceDemoteSendInline case TelegramChatBannedRightsFlags.banSendMedia: return strings().eventLogServiceDemoteSendMedia case TelegramChatBannedRightsFlags.banSendMessages: return strings().eventLogServiceDemoteSendMessages case TelegramChatBannedRightsFlags.banSendStickers: return strings().eventLogServiceDemoteSendStickers case TelegramChatBannedRightsFlags.banChangeInfo: return strings().eventLogServiceDemoteChangeInfo default: return "" } } } /* public struct TelegramChatBannedRightsFlags: OptionSet { public var rawValue: Int32 public init(rawValue: Int32) { self.rawValue = rawValue } public init() { self.rawValue = 0 } public static let banReadMessages = TelegramChatBannedRightsFlags(rawValue: 1 << 0) public static let banSendMessages = TelegramChatBannedRightsFlags(rawValue: 1 << 1) public static let banSendMedia = TelegramChatBannedRightsFlags(rawValue: 1 << 2) public static let banSendStickers = TelegramChatBannedRightsFlags(rawValue: 1 << 3) public static let banSendGifs = TelegramChatBannedRightsFlags(rawValue: 1 << 4) public static let banSendGames = TelegramChatBannedRightsFlags(rawValue: 1 << 5) public static let banSendInline = TelegramChatBannedRightsFlags(rawValue: 1 << 6) public static let banEmbedLinks = TelegramChatBannedRightsFlags(rawValue: 1 << 7) } */ extension TelegramChatBannedRights { var formattedUntilDate: String { let formatter = DateFormatter() formatter.dateStyle = .short //formatter.timeZone = NSTimeZone.local formatter.timeZone = NSTimeZone.local formatter.timeStyle = .short return formatter.string(from: Date(timeIntervalSince1970: TimeInterval(untilDate))) } } func permissionText(from peer: Peer, for flags: TelegramChatBannedRightsFlags) -> String? { let bannedPermission: (Int32, Bool)? if let channel = peer as? TelegramChannel { bannedPermission = channel.hasBannedPermission(flags) } else if let group = peer as? TelegramGroup { if group.hasBannedPermission(flags) { bannedPermission = (Int32.max, false) } else { bannedPermission = nil } } else { bannedPermission = nil } if let (untilDate, personal) = bannedPermission { switch flags { case .banSendMessages: if personal && untilDate != 0 && untilDate != Int32.max { return strings().channelPersmissionDeniedSendMessagesUntil(stringForFullDate(timestamp: untilDate)) } else if personal { return strings().channelPersmissionDeniedSendMessagesForever } else { return strings().channelPersmissionDeniedSendMessagesDefaultRestrictedText } case .banSendStickers: if personal && untilDate != 0 && untilDate != Int32.max { return strings().channelPersmissionDeniedSendStickersUntil(stringForFullDate(timestamp: untilDate)) } else if personal { return strings().channelPersmissionDeniedSendStickersForever } else { return strings().channelPersmissionDeniedSendStickersDefaultRestrictedText } case .banSendGifs: if personal && untilDate != 0 && untilDate != Int32.max { return strings().channelPersmissionDeniedSendGifsUntil(stringForFullDate(timestamp: untilDate)) } else if personal { return strings().channelPersmissionDeniedSendGifsForever } else { return strings().channelPersmissionDeniedSendGifsDefaultRestrictedText } case .banSendMedia: if personal && untilDate != 0 && untilDate != Int32.max { return strings().channelPersmissionDeniedSendMediaUntil(stringForFullDate(timestamp: untilDate)) } else if personal { return strings().channelPersmissionDeniedSendMediaForever } else { return strings().channelPersmissionDeniedSendMediaDefaultRestrictedText } case .banSendPolls: if personal && untilDate != 0 && untilDate != Int32.max { return strings().channelPersmissionDeniedSendPollUntil(stringForFullDate(timestamp: untilDate)) } else if personal { return strings().channelPersmissionDeniedSendPollForever } else { return strings().channelPersmissionDeniedSendPollDefaultRestrictedText } case .banSendInline: if personal && untilDate != 0 && untilDate != Int32.max { return strings().channelPersmissionDeniedSendInlineUntil(stringForFullDate(timestamp: untilDate)) } else if personal { return strings().channelPersmissionDeniedSendInlineForever } else { return strings().channelPersmissionDeniedSendInlineDefaultRestrictedText } default: return nil } } return nil } extension RenderedPeer { convenience init(_ foundPeer: FoundPeer) { self.init(peerId: foundPeer.peer.id, peers: SimpleDictionary([foundPeer.peer.id : foundPeer.peer]), associatedMedia: [:]) } } extension TelegramMediaFile { var videoSize:NSSize { for attr in attributes { if case let .Video(_,size, _) = attr { return size.size } } return NSZeroSize } var isStreamable: Bool { for attr in attributes { if case let .Video(_, _, flags) = attr { return flags.contains(.supportsStreaming) } } return true } // var streaming: MediaPlayerStreaming { // for attr in attributes { // if case let .Video(_, _, flags) = attr { // if flags.contains(.supportsStreaming) { // return .earlierStart // } else { // return .none // } // } // } // return .none // } var imageSize:NSSize { for attr in attributes { if case let .ImageSize(size) = attr { return size.size } } return NSZeroSize } var videoDuration:Int { for attr in attributes { if case let .Video(duration,_, _) = attr { return duration } } return 0 } var isTheme: Bool { return mimeType == "application/x-tgtheme-macos" } func withUpdatedResource(_ resource: TelegramMediaResource) -> TelegramMediaFile { return TelegramMediaFile(fileId: self.fileId, partialReference: self.partialReference, resource: resource, previewRepresentations: self.previewRepresentations, videoThumbnails: self.videoThumbnails, immediateThumbnailData: self.immediateThumbnailData, mimeType: self.mimeType, size: self.size, attributes: self.attributes) } func withUpdatedFileId(_ fileId: MediaId) -> TelegramMediaFile { return TelegramMediaFile(fileId: fileId, partialReference: self.partialReference, resource: self.resource, previewRepresentations: self.previewRepresentations, videoThumbnails: self.videoThumbnails, immediateThumbnailData: self.immediateThumbnailData, mimeType: self.mimeType, size: self.size, attributes: self.attributes) } } extension ChatContextResult { var maybeId:Int64 { var t:String = "" var d:String = "" if let title = title { t = title } if let description = description { d = description } let maybe = id + type + t + d return Int64(maybe.hash) } } extension TelegramMediaFile { var elapsedSize: Int64 { if let size = size { return size } if let resource = resource as? LocalFileReferenceMediaResource, let size = resource.size { return Int64(size) } return 0 } } extension Media { var isInteractiveMedia: Bool { if self is TelegramMediaImage { return true } else if let file = self as? TelegramMediaFile { return (file.isVideo && !file.isWebm) || (file.isAnimated && !file.mimeType.lowercased().hasSuffix("gif") && !file.isWebm) } else if let map = self as? TelegramMediaMap { return map.venue == nil } else if self is TelegramMediaDice { return false } return false } var canHaveCaption: Bool { if supposeToBeSticker { return false } if self is TelegramMediaImage { return true } else if let file = self as? TelegramMediaFile { if file.isInstantVideo || file.isAnimatedSticker || file.isStaticSticker || file.isVoice { return false } else { return true } } return false } } enum ChatListIndexRequest :Equatable { case Initial(Int, TableScrollState?) case Index(EngineChatList.Item.Index, TableScrollState?) } public extension PeerView { var isMuted:Bool { if let settings = self.notificationSettings as? TelegramPeerNotificationSettings { switch settings.muteState { case let .muted(until): return until > Int32(Date().timeIntervalSince1970) case .unmuted: return false case .default: return false } } else { return false } } } public extension TelegramPeerNotificationSettings { var isMuted:Bool { switch self.muteState { case let .muted(until): return until > Int32(Date().timeIntervalSince1970) case .unmuted: return false case .default: return false } } } public extension TelegramMediaFile { var stickerText:String? { for attr in attributes { if case let .Sticker(displayText, _, _) = attr { return displayText } } return nil } var customEmojiText:String? { for attr in attributes { if case let .CustomEmoji(_, alt, _) = attr { return alt } } return nil } var stickerReference:StickerPackReference? { for attr in attributes { if case let .Sticker(_, reference, _) = attr { return reference } } return nil } var emojiReference:StickerPackReference? { for attr in attributes { if case let .CustomEmoji(_, _, reference) = attr { return reference } } return nil } var maskData: StickerMaskCoords? { for attr in attributes { if case let .Sticker(_, _, mask) = attr { return mask } } return nil } var isEmojiAnimatedSticker: Bool { if let fileName = fileName { return fileName.hasPrefix("telegram-animoji") && fileName.hasSuffix("tgs") && isSticker } return false } var animatedEmojiFitzModifier: EmojiFitzModifier? { if isEmojiAnimatedSticker, let fitz = self.stickerText?.basicEmoji.1 { return EmojiFitzModifier(emoji: fitz) } else { return nil } } var musicText:(String,String) { var audioTitle:String? var audioPerformer:String? let file = self for attribute in file.attributes { if case let .Audio(_, _, title, performer, _) = attribute { audioTitle = title audioPerformer = performer break } } if let audioTitle = audioTitle, let audioPerformer = audioPerformer { if audioTitle.isEmpty && audioPerformer.isEmpty { return (file.fileName ?? "", "") } else { return (audioTitle, audioPerformer) } } else { return (file.fileName ?? "", "") } } } public extension MessageHistoryView { func index(for messageId: MessageId) -> Int? { for i in 0 ..< entries.count { if entries[i].index.id == messageId { return i } } return nil } } extension MessageReaction.Reaction { func toUpdate(_ file: TelegramMediaFile? = nil) -> UpdateMessageReaction { switch self { case let .custom(fileId): return .custom(fileId: fileId, file: file) case let .builtin(emoji): return .builtin(emoji) } } } public extension Message { var replyMarkup:ReplyMarkupMessageAttribute? { for attr in attributes { if let attr = attr as? ReplyMarkupMessageAttribute { return attr } } return nil } var hasExtendedMedia: Bool { if let media = self.media.first as? TelegramMediaInvoice { return media.extendedMedia != nil } return false } var consumableContent: ConsumableContentMessageAttribute? { for attr in attributes { if let attr = attr as? ConsumableContentMessageAttribute { return attr } } return nil } var entities:[MessageTextEntity] { return self.textEntities?.entities ?? [] } var audioTranscription:AudioTranscriptionMessageAttribute? { for attr in attributes { if let attr = attr as? AudioTranscriptionMessageAttribute { return attr } } return nil } var isImported: Bool { if let forwardInfo = self.forwardInfo, forwardInfo.flags.contains(.isImported) { return true } return false } var itHasRestrictedContent: Bool { #if APP_STORE || DEBUG for attr in attributes { if let attr = attr as? RestrictedContentMessageAttribute { for rule in attr.rules { if rule.platform == "ios" || rule.platform == "macos" { return true } } } } #endif return false } func restrictedText(_ contentSettings: ContentSettings) -> String? { #if APP_STORE || DEBUG for attr in attributes { if let attr = attr as? RestrictedContentMessageAttribute { for rule in attr.rules { if rule.platform == "ios" || rule.platform == "all" || contentSettings.addContentRestrictionReasons.contains(rule.platform) { if !contentSettings.ignoreContentRestrictionReasons.contains(rule.reason) { return rule.text } } } } } #endif return nil } var file: TelegramMediaFile? { if let file = self.effectiveMedia as? TelegramMediaFile { return file } else if let webpage = self.effectiveMedia as? TelegramMediaWebpage { switch webpage.content { case let .Loaded(content): return content.file default: break } } return nil } var textEntities: TextEntitiesMessageAttribute? { for attr in attributes { if let attr = attr as? TextEntitiesMessageAttribute { return attr } } return nil } var isAnonymousMessage: Bool { if let author = self.author as? TelegramChannel, sourceReference == nil, self.id.peerId == author.id { return true } else { return false } } var threadAttr: ReplyThreadMessageAttribute? { for attr in attributes { if let attr = attr as? ReplyThreadMessageAttribute { return attr } } return nil } var effectiveMedia: Media? { if let media = self.media.first as? TelegramMediaInvoice { if let extended = media.extendedMedia { switch extended { case let .full(media): return media default: break } } } return media.first } func newReactions(with reaction: UpdateMessageReaction) -> [UpdateMessageReaction] { var updated:[UpdateMessageReaction] = [] if let reactions = self.effectiveReactions { let sorted = reactions.sorted(by: <) updated = sorted.compactMap { value in if value.isSelected { switch value.value { case let .builtin(emoji): return .builtin(emoji) case let .custom(fileId): let mediaId = MediaId(namespace: Namespaces.Media.CloudFile, id: fileId) let file = self.associatedMedia[mediaId] as? TelegramMediaFile return .custom(fileId: fileId, file: file) } } return nil } if let index = updated.firstIndex(where: { $0.reaction == reaction.reaction }) { updated.remove(at: index) } else { updated.append(reaction) } } else { updated.append(reaction) } return updated } func effectiveReactions(_ accountPeerId: PeerId) -> ReactionsMessageAttribute? { return mergedMessageReactions(attributes: self.attributes) } func isCrosspostFromChannel(account: Account) -> Bool { var sourceReference: SourceReferenceMessageAttribute? for attribute in self.attributes { if let attribute = attribute as? SourceReferenceMessageAttribute { sourceReference = attribute break } } var isCrosspostFromChannel = false if let _ = sourceReference { if self.id.peerId != account.peerId { isCrosspostFromChannel = true } } return isCrosspostFromChannel } var channelViewsCount: Int32? { for attribute in self.attributes { if let attribute = attribute as? ViewCountMessageAttribute { return Int32(attribute.count) } } return nil } var isScheduledMessage: Bool { return self.id.namespace == Namespaces.Message.ScheduledCloud || self.id.namespace == Namespaces.Message.ScheduledLocal } var wasScheduled: Bool { for attr in attributes { if attr is OutgoingScheduleInfoMessageAttribute { return true } } return self.flags.contains(.WasScheduled) } var isPublicPoll: Bool { if let media = self.effectiveMedia as? TelegramMediaPoll { return media.publicity == .public } return false } var isHasInlineKeyboard: Bool { return replyMarkup?.flags.contains(.inline) ?? false } func isIncoming(_ account: Account, _ isBubbled: Bool) -> Bool { if isBubbled, let peer = coreMessageMainPeer(self), peer.isChannel { return true } if id.peerId == account.peerId { if let _ = forwardInfo { return true } return false } return flags.contains(.Incoming) } func chatPeer(_ accountPeerId: PeerId) -> Peer? { var _peer: Peer? if let _ = adAttribute { return author } for attr in attributes { if let source = attr as? SourceReferenceMessageAttribute { if let info = forwardInfo { if let peer = peers[source.messageId.peerId], peer is TelegramChannel, accountPeerId != id.peerId, repliesPeerId != id.peerId { _peer = peer } else { _peer = info.author } } break } } if let peer = coreMessageMainPeer(self) as? TelegramChannel, case .broadcast(_) = peer.info { _peer = peer } else if let author = effectiveAuthor, _peer == nil { if author is TelegramSecretChat { return coreMessageMainPeer(self) } else { _peer = author } } return _peer } var replyAttribute: ReplyMessageAttribute? { for attr in attributes { if let attr = attr as? ReplyMessageAttribute { return attr } } return nil } var editedAttribute: EditedMessageAttribute? { for attr in attributes { if let attr = attr as? EditedMessageAttribute, !attr.isHidden { return attr } } return nil } var autoremoveAttribute:AutoremoveTimeoutMessageAttribute? { for attr in attributes { if let attr = attr as? AutoremoveTimeoutMessageAttribute { return attr } } return nil } var hasInlineAttribute: Bool { for attribute in attributes { if let _ = attribute as? InlineBotMessageAttribute { return true } } return false } var inlinePeer:Peer? { for attribute in attributes { if let attribute = attribute as? InlineBotMessageAttribute, let peerId = attribute.peerId { return peers[peerId] } } if let peer = coreMessageMainPeer(self), peer.isBot { return peer } return nil } func withUpdatedStableId(_ stableId:UInt32) -> Message { return Message(stableId: stableId, stableVersion: stableVersion, id: id, globallyUniqueId: globallyUniqueId, groupingKey: groupingKey, groupInfo: groupInfo, threadId: threadId, timestamp: timestamp, flags: flags, tags: tags, globalTags: globalTags, localTags: localTags, forwardInfo: forwardInfo, author: author, text: text, attributes: attributes, media: media, peers: peers, associatedMessages: associatedMessages, associatedMessageIds: associatedMessageIds, associatedMedia: self.associatedMedia, associatedThreadInfo: self.associatedThreadInfo) } func withUpdatedId(_ messageId:MessageId) -> Message { return Message(stableId: stableId, stableVersion: stableVersion, id: messageId, globallyUniqueId: globallyUniqueId, groupingKey: groupingKey, groupInfo: groupInfo, threadId: threadId, timestamp: timestamp, flags: flags, tags: tags, globalTags: globalTags, localTags: localTags, forwardInfo: forwardInfo, author: author, text: text, attributes: attributes, media: media, peers: peers, associatedMessages: associatedMessages, associatedMessageIds: associatedMessageIds, associatedMedia: self.associatedMedia, associatedThreadInfo: self.associatedThreadInfo) } func withUpdatedGroupingKey(_ groupingKey:Int64?) -> Message { return Message(stableId: stableId, stableVersion: stableVersion, id: id, globallyUniqueId: globallyUniqueId, groupingKey: groupingKey, groupInfo: groupInfo, threadId: threadId, timestamp: timestamp, flags: flags, tags: tags, globalTags: globalTags, localTags: localTags, forwardInfo: forwardInfo, author: author, text: text, attributes: attributes, media: media, peers: peers, associatedMessages: associatedMessages, associatedMessageIds: associatedMessageIds, associatedMedia: self.associatedMedia, associatedThreadInfo: self.associatedThreadInfo) } func withUpdatedTimestamp(_ timestamp: Int32) -> Message { return Message(stableId: self.stableId, stableVersion: self.stableVersion, id: self.id, globallyUniqueId: self.globallyUniqueId, groupingKey: self.groupingKey, groupInfo: self.groupInfo, threadId: threadId, timestamp: timestamp, flags: self.flags, tags: self.tags, globalTags: self.globalTags, localTags: self.localTags, forwardInfo: self.forwardInfo, author: self.author, text: self.text, attributes: self.attributes, media: self.media, peers: self.peers, associatedMessages: self.associatedMessages, associatedMessageIds: self.associatedMessageIds, associatedMedia: self.associatedMedia, associatedThreadInfo: self.associatedThreadInfo) } func withUpdatedText(_ text:String) -> Message { return Message(stableId: stableId, stableVersion: stableVersion, id: id, globallyUniqueId: globallyUniqueId, groupingKey: groupingKey, groupInfo: groupInfo, threadId: threadId, timestamp: timestamp, flags: flags, tags: tags, globalTags: globalTags, localTags: localTags, forwardInfo: forwardInfo, author: author, text: text, attributes: attributes, media: media, peers: peers, associatedMessages: associatedMessages, associatedMessageIds: associatedMessageIds, associatedMedia: self.associatedMedia, associatedThreadInfo: self.associatedThreadInfo) } func possibilityForwardTo(_ peer:Peer) -> Bool { if !peer.canSendMessage(false) { return false } else if let peer = peer as? TelegramChannel { if let media = media.first, !(media is TelegramMediaWebpage) { if let media = media as? TelegramMediaFile { if media.isStaticSticker { return !peer.hasBannedRights(.banSendStickers) } else if media.isVideo && media.isAnimated { return !peer.hasBannedRights(.banSendGifs) } } return !peer.hasBannedRights(.banSendMedia) } } return true } convenience init(_ media: Media, stableId: UInt32, messageId: MessageId) { self.init(stableId: stableId, stableVersion: 0, id: messageId, globallyUniqueId: nil, groupingKey: nil, groupInfo: nil, threadId: nil, timestamp: 0, flags: [], tags: [], globalTags: [], localTags: [], forwardInfo: nil, author: nil, text: "", attributes: [], media: [media], peers: SimpleDictionary(), associatedMessages: SimpleDictionary(), associatedMessageIds: [], associatedMedia: [:], associatedThreadInfo: nil) } } extension ChatLocation : Hashable { func hash(into hasher: inout Hasher) { } } extension AvailableReactions { var enabled: [AvailableReactions.Reaction] { return self.reactions.filter { $0.isEnabled } } } extension SuggestedLocalizationInfo { func localizedKey(_ key:String) -> String { for entry in extractedEntries { switch entry { case let.string(_key, _value): if _key == key { return _value } default: break } } return NSLocalizedString(key, comment: "") } } public extension MessageId { var string: String { return "_id_\(id)_\(peerId.id._internalGetInt64Value())" } } public extension ReplyMarkupMessageAttribute { var hasButtons:Bool { return !self.rows.isEmpty } } fileprivate let edit_limit_time:Int32 = 48*60*60 func canDeleteMessage(_ message:Message, account:Account, mode: ChatMode) -> Bool { if mode.threadId == message.id { return false } if message.adAttribute != nil { return false } if let channel = message.peers[message.id.peerId] as? TelegramChannel { if case .broadcast = channel.info { if !message.flags.contains(.Incoming) { return channel.hasPermission(.sendMessages) } return channel.hasPermission(.deleteAllMessages) } return channel.hasPermission(.deleteAllMessages) || !message.flags.contains(.Incoming) } else if message.peers[message.id.peerId] is TelegramSecretChat { return true } else { return true } } func uniquePeers(from peers:[Peer], defaultExculde:[PeerId] = []) -> [Peer] { var excludePeerIds:[PeerId:PeerId] = [:] for peerId in defaultExculde { excludePeerIds[peerId] = peerId } return peers.filter { peer -> Bool in let first = excludePeerIds[peer.id] == nil excludePeerIds[peer.id] = peer.id return first } } func canForwardMessage(_ message:Message, chatInteraction: ChatInteraction) -> Bool { if message.peers[message.id.peerId] is TelegramSecretChat { return false } if message.flags.contains(.Failed) || message.flags.contains(.Unsent) { return false } if message.isScheduledMessage { return false } if message.adAttribute != nil { return false } if message.effectiveMedia is TelegramMediaAction { return false } if let peer = message.peers[message.id.peerId] as? TelegramGroup { if peer.flags.contains(.copyProtectionEnabled) { return false } } if let peer = message.peers[message.id.peerId] as? TelegramChannel { if peer.flags.contains(.copyProtectionEnabled) { return false } } if let peer = message.peers[message.id.peerId] as? TelegramUser { if peer.isUser, let timer = message.autoremoveAttribute { if !chatInteraction.hasSetDestructiveTimer { return false } else if timer.timeout <= 60 { return false; } } } return true } public struct ChatAvailableMessageActionOptions: OptionSet { public var rawValue: Int32 public init(rawValue: Int32) { self.rawValue = rawValue } public init() { self.rawValue = 0 } public static let deleteLocally = ChatAvailableMessageActionOptions(rawValue: 1 << 0) public static let deleteGlobally = ChatAvailableMessageActionOptions(rawValue: 1 << 1) public static let unsendPersonal = ChatAvailableMessageActionOptions(rawValue: 1 << 7) } func canDeleteForEveryoneMessage(_ message:Message, context: AccountContext) -> Bool { if message.peers[message.id.peerId] is TelegramChannel || message.peers[message.id.peerId] is TelegramSecretChat { return false } else if message.peers[message.id.peerId] is TelegramUser || message.peers[message.id.peerId] is TelegramGroup { if message.id.peerId == repliesPeerId { return false } if context.limitConfiguration.canRemoveIncomingMessagesInPrivateChats && message.peers[message.id.peerId] is TelegramUser { if message.effectiveMedia is TelegramMediaDice, message.peers[message.id.peerId] is TelegramUser { if Int(message.timestamp) + 24 * 60 * 60 > context.timestamp { return false } } return true } if let peer = message.peers[message.id.peerId] as? TelegramGroup { switch peer.role { case .creator, .admin: return true default: if Int(context.limitConfiguration.maxMessageEditingInterval) + Int(message.timestamp) > Int(Date().timeIntervalSince1970) { if context.account.peerId == message.effectiveAuthor?.id { return !(message.effectiveMedia is TelegramMediaAction) } } return false } } else if Int(context.limitConfiguration.maxMessageEditingInterval) + Int(message.timestamp) > Int(Date().timeIntervalSince1970) { if context.account.peerId == message.author?.id { return !(message.effectiveMedia is TelegramMediaAction) } } } return false } func mustDeleteForEveryoneMessage(_ message:Message) -> Bool { if message.peers[message.id.peerId] is TelegramChannel || message.peers[message.id.peerId] is TelegramSecretChat { return true } return false } func canReplyMessage(_ message: Message, peerId: PeerId, mode: ChatMode, threadData: MessageHistoryThreadData? = nil) -> Bool { if let peer = coreMessageMainPeer(message) { if message.isScheduledMessage { return false } if peerId == message.id.peerId, !message.flags.contains(.Unsent) && !message.flags.contains(.Failed) && (message.id.namespace != Namespaces.Message.Local || message.id.peerId.namespace == Namespaces.Peer.SecretChat) { switch mode { case .history: return peer.canSendMessage(false, threadData: threadData) case .scheduled: return false case let .thread(data, mode): switch mode { case .comments: if message.id == data.messageId { return false } return peer.canSendMessage(true, threadData: threadData) case .replies: return peer.canSendMessage(true, threadData: threadData) case .topic: return peer.canSendMessage(true, threadData: threadData) } case .pinned: return false } } } return false } func canEditMessage(_ message:Message, chatInteraction: ChatInteraction, context: AccountContext, ignorePoll: Bool = false) -> Bool { if message.forwardInfo != nil { return false } if message.flags.contains(.Unsent) || message.flags.contains(.Failed) || message.id.namespace == Namespaces.Message.Local { return false } if message.peers[message.id.peerId] is TelegramSecretChat { return false } if let media = message.effectiveMedia { if let file = media as? TelegramMediaFile { if file.isStaticSticker || (file.isAnimatedSticker && !file.isEmojiAnimatedSticker) { return false } if file.isInstantVideo { return false } // if file.isVoice { // return false // } } if media is TelegramMediaContact { return false } if media is TelegramMediaAction { return false } if media is TelegramMediaMap { return false } if media is TelegramMediaPoll, !ignorePoll { return false } if media is TelegramMediaDice { return false } } for attr in message.attributes { if attr is InlineBotMessageAttribute { return false } else if attr is AutoremoveTimeoutMessageAttribute { if !chatInteraction.hasSetDestructiveTimer { return false } } } var timeInCondition = Int(message.timestamp) + Int(context.limitConfiguration.maxMessageEditingInterval) > context.account.network.getApproximateRemoteTimestamp() if let peer = coreMessageMainPeer(message) as? TelegramChannel { if case .broadcast = peer.info { if message.isScheduledMessage { return peer.hasPermission(.sendMessages) || peer.hasPermission(.editAllMessages) } if peer.hasPermission(.pinMessages) { timeInCondition = true } if peer.hasPermission(.editAllMessages) { return timeInCondition } else if peer.hasPermission(.sendMessages) { return timeInCondition && message.author?.id == chatInteraction.context.peerId } return false } else if case .group = peer.info { if !message.flags.contains(.Incoming) { if peer.hasPermission(.pinMessages) { return true } return timeInCondition } } } if message.id.peerId == context.account.peerId { return true } if message.flags.contains(.Incoming) { return false } if Int(message.timestamp) + Int(context.limitConfiguration.maxMessageEditingInterval) < context.account.network.getApproximateRemoteTimestamp() { return false } return !message.flags.contains(.Unsent) && !message.flags.contains(.Failed) } func canPinMessage(_ message:Message, for peer:Peer, account:Account) -> Bool { return false } func canReportMessage(_ message: Message, _ account: Account) -> Bool { if message.isScheduledMessage || message.flags.contains(.Failed) || message.flags.contains(.Sending) { return false } if let peer = coreMessageMainPeer(message), message.author?.id != account.peerId { return peer.isChannel || peer.isGroup || peer.isSupergroup || (message.chatPeer(account.peerId)?.isBot == true) } else { return false } } func mustManageDeleteMessages(_ messages:[Message], for peer:Peer, account: Account) -> Bool { if let peer = peer as? TelegramChannel, peer.isSupergroup, peer.hasPermission(.deleteAllMessages) { let peerId:PeerId? = messages[0].author?.id if account.peerId != peerId { for message in messages { if peerId != message.author?.id || !message.flags.contains(.Incoming) { return false } } return true } } return false } extension Media { var isGraphicFile:Bool { if let media = self as? TelegramMediaFile { return media.mimeType.hasPrefix("image") && (media.mimeType.contains("png") || media.mimeType.contains("jpg") || media.mimeType.contains("jpeg") || media.mimeType.contains("tiff") || media.mimeType.contains("heic")) } return false } var isWebm: Bool { if let media = self as? TelegramMediaFile { return media.mimeType == "video/webm" } return false } var probablySticker: Bool { guard let file = self as? TelegramMediaFile else { return false } if file.isAnimatedSticker { return true } if file.isStaticSticker { return true } if file.isVideoSticker { return true } if file.mimeType == "image/webp" { return true } return false } var isVideoFile:Bool { if let media = self as? TelegramMediaFile { return media.mimeType.hasPrefix("video/mp4") || media.mimeType.hasPrefix("video/mov") || media.mimeType.hasPrefix("video/avi") } return false } var isMusicFile: Bool { if let media = self as? TelegramMediaFile { for attr in media.attributes { switch attr { case let .Audio(isVoice, _, _, _, _): return !isVoice default: return false } } } return false } var supposeToBeSticker:Bool { if let media = self as? TelegramMediaFile { if media.mimeType.hasPrefix("image/webp") { return true } } return false } } extension AddressNameFormatError { var description:String { switch self { case .startsWithUnderscore: return strings().errorUsernameUnderscopeStart case .endsWithUnderscore: return strings().errorUsernameUnderscopeEnd case .startsWithDigit: return strings().errorUsernameNumberStart case .invalidCharacters: return strings().errorUsernameInvalid case .tooShort: return strings().errorUsernameMinimumLength } } } extension AddressNameAvailability { func description(for username: String) -> String { switch self { case .available: return strings().usernameSettingsAvailable(username) case .invalid: return strings().errorUsernameInvalid case .taken: return strings().errorUsernameAlreadyTaken } } } func <(lhs:RenderedChannelParticipant, rhs: RenderedChannelParticipant) -> Bool { let lhsInvitedAt: Int32 let rhsInvitedAt: Int32 switch lhs.participant { case .creator: lhsInvitedAt = Int32.min case .member(_, let invitedAt, _, _, _): lhsInvitedAt = invitedAt } switch rhs.participant { case .creator: rhsInvitedAt = Int32.min case .member(_, let invitedAt, _, _, _): rhsInvitedAt = invitedAt } return lhsInvitedAt < rhsInvitedAt } extension TelegramGroup { var canPinMessage: Bool { return !hasBannedRights(.banPinMessages) } } extension Peer { var isUser:Bool { return self is TelegramUser } var isSecretChat:Bool { return self is TelegramSecretChat } var isGroup:Bool { return self is TelegramGroup } var canManageDestructTimer: Bool { if self is TelegramSecretChat { return true } if self.isUser && !self.isBot { return true } if let peer = self as? TelegramChannel { if let adminRights = peer.adminRights, adminRights.rights.contains(.canDeleteMessages) { return true } else if peer.groupAccess.isCreator { return true } return false } if let peer = self as? TelegramGroup { switch peer.role { case .admin, .creator: return true default: break } } return false } var canClearHistory: Bool { if self.isGroup || self.isUser || (self.isSupergroup && self.addressName == nil) { if let peer = self as? TelegramChannel, peer.flags.contains(.hasGeo) {} else { return true } } if self is TelegramSecretChat { return true } return false } func isRestrictedChannel(_ contentSettings: ContentSettings) -> Bool { if let peer = self as? TelegramChannel { if let restrictionInfo = peer.restrictionInfo { for rule in restrictionInfo.rules { #if APP_STORE if rule.platform == "ios" || rule.platform == "all" { return !contentSettings.ignoreContentRestrictionReasons.contains(rule.reason) } #endif } } } return false } var restrictionText:String? { if let peer = self as? TelegramChannel { if let restrictionInfo = peer.restrictionInfo { for rule in restrictionInfo.rules { if rule.platform == "ios" || rule.platform == "all" { return rule.text } } } } return nil } var botInfo: BotUserInfo? { if let peer = self as? TelegramUser { return peer.botInfo } return nil } var isSupergroup:Bool { if let peer = self as? TelegramChannel { switch peer.info { case .group: return true default: return false } } return false } var isBot:Bool { if let user = self as? TelegramUser { return user.botInfo != nil } return false } var canCall:Bool { return isUser && !isBot && ((self as! TelegramUser).phone != "42777") && ((self as! TelegramUser).phone != "42470") && ((self as! TelegramUser).phone != "4240004") } var isChannel:Bool { if let peer = self as? TelegramChannel { switch peer.info { case .broadcast: return true default: return false } } return false } var isAdmin: Bool { if let peer = self as? TelegramChannel { return peer.adminRights != nil || peer.flags.contains(.isCreator) } return false } var isGigagroup:Bool { if let peer = self as? TelegramChannel { return peer.flags.contains(.isGigagroup) } return false } } public enum AddressNameAvailabilityState : Equatable { case none(username: String?) case success(username: String?) case progress(username: String?) case fail(username: String?, formatError: AddressNameFormatError?, availability: AddressNameAvailability) public var username:String? { switch self { case let .none(username:username): return username case let .success(username:username): return username case let .progress(username:username): return username case let .fail(fail): return fail.username } } } public func ==(lhs:AddressNameAvailabilityState, rhs:AddressNameAvailabilityState) -> Bool { switch lhs { case let .none(username:lhsName): if case let .none(username:rhsName) = rhs, lhsName == rhsName { return true } return false case let .success(username:lhsName): if case let .success(username:rhsName) = rhs, lhsName == rhsName { return true } return false case let .progress(username:lhsName): if case let .progress(username:rhsName) = rhs, lhsName == rhsName { return true } return false case let .fail(lhsData): if case let .fail(rhsData) = rhs, lhsData.formatError == rhsData.formatError && lhsData.username == rhsData.username && lhsData.availability == rhsData.availability { return true } return false } } extension Signal { public static func next(_ value: T) -> Signal<T, E> { return Signal<T, E> { subscriber in subscriber.putNext(value) return EmptyDisposable } } } extension SentSecureValueType { var rawValue: String { switch self { case .email: return strings().secureIdRequestPermissionEmail case .phone: return strings().secureIdRequestPermissionPhone case .passport: return strings().secureIdRequestPermissionPassport case .address: return strings().secureIdRequestPermissionResidentialAddress case .personalDetails: return strings().secureIdRequestPermissionPersonalDetails case .driversLicense: return strings().secureIdRequestPermissionDriversLicense case .utilityBill: return strings().secureIdRequestPermissionUtilityBill case .rentalAgreement: return strings().secureIdRequestPermissionTenancyAgreement case .idCard: return strings().secureIdRequestPermissionIDCard case .bankStatement: return strings().secureIdRequestPermissionBankStatement case .internalPassport: return strings().secureIdRequestPermissionInternalPassport case .passportRegistration: return strings().secureIdRequestPermissionPassportRegistration case .temporaryRegistration: return strings().secureIdRequestPermissionTemporaryRegistration } } } extension TwoStepVerificationPendingEmail : Equatable { public static func == (lhs: TwoStepVerificationPendingEmail, rhs: TwoStepVerificationPendingEmail) -> Bool { return lhs.codeLength == rhs.codeLength && lhs.pattern == rhs.pattern } } extension UpdateTwoStepVerificationPasswordResult : Equatable { public static func ==(lhs: UpdateTwoStepVerificationPasswordResult, rhs: UpdateTwoStepVerificationPasswordResult) -> Bool { switch lhs { case .none: if case .none = rhs { return true } else { return false } case let .password(password, lhsPendingEmailPattern): if case .password(password, let rhsPendingEmailPattern) = rhs { return lhsPendingEmailPattern == rhsPendingEmailPattern } else { return false } } } } extension SecureIdGender { static func gender(from mrz: TGPassportMRZ) -> SecureIdGender { switch mrz.gender.lowercased() { case "f": return .female default: return .male } } } extension SecureIdRequestedFormField { var isIdentityField: Bool { switch self { case let .just(field): switch field { case .idCard, .passport, .driversLicense, .internalPassport: return true default: return false } case let .oneOf(fields): switch fields[0] { case .idCard, .passport, .driversLicense, .internalPassport: return true default: return false } } } var valueKey: SecureIdValueKey? { switch self { case let .just(field): return field.valueKey default: return nil } } var fieldValue: SecureIdRequestedFormFieldValue? { switch self { case let .just(field): return field default: return nil } } var isAddressField: Bool { switch self { case let .just(field): switch field { case .utilityBill, .bankStatement, .rentalAgreement, .passportRegistration, .temporaryRegistration: return true default: return false } case let .oneOf(fields): switch fields[0] { case .utilityBill, .bankStatement, .rentalAgreement, .passportRegistration, .temporaryRegistration: return true default: return false } } } } extension SecureIdForm { func searchContext(for field: SecureIdRequestedFormFieldValue) -> SecureIdValueWithContext? { let index = values.index(where: { context -> Bool in switch context.value { case .address: if case .address = field { return true } else { return false } case .bankStatement: if case .bankStatement = field { return true } else { return false } case .driversLicense: if case .driversLicense = field { return true } else { return false } case .idCard: if case .idCard = field { return true } else { return false } case .passport: if case .passport = field { return true } else { return false } case .personalDetails: if case .personalDetails = field { return true } else { return false } case .rentalAgreement: if case .rentalAgreement = field { return true } else { return false } case .utilityBill: if case .utilityBill = field { return true } else { return false } case .phone: if case .phone = field { return true } else { return false } case .email: if case .email = field { return true } else { return false } case .internalPassport: if case .internalPassport = field { return true } else { return false } case .passportRegistration: if case .passportRegistration = field { return true } else { return false } case .temporaryRegistration: if case .temporaryRegistration = field { return true } else { return false } } }) if let index = index { return values[index] } else { return nil } } } extension SecureIdValue { func isSame(of value: SecureIdValue) -> Bool { switch self { case .address: if case .address = value { return true } else { return false } case .bankStatement: if case .bankStatement = value { return true } else { return false } case .driversLicense: if case .driversLicense = value { return true } else { return false } case .idCard: if case .idCard = value { return true } else { return false } case .passport: if case .passport = value { return true } else { return false } case .personalDetails: if case .personalDetails = value { return true } else { return false } case .rentalAgreement: if case .rentalAgreement = value { return true } else { return false } case .utilityBill: if case .utilityBill = value { return true } else { return false } case .phone: if case .phone = value { return true } else { return false } case .email: if case .email = value { return true } else { return false } case .internalPassport(_): if case .internalPassport = value { return true } else { return false } case .passportRegistration(_): if case .passportRegistration = value { return true } else { return false } case .temporaryRegistration(_): if case .temporaryRegistration = value { return true } else { return false } } } func isSame(of value: SecureIdValueKey) -> Bool { return self.key == value } var secureIdValueAccessContext: SecureIdValueAccessContext? { switch self { case .email: return generateSecureIdValueEmptyAccessContext() case .phone: return generateSecureIdValueEmptyAccessContext() default: return generateSecureIdValueAccessContext() } } var addressValue: SecureIdAddressValue? { switch self { case let .address(value): return value default: return nil } } var identifier: String? { switch self { case let .passport(value): return value.identifier case let .driversLicense(value): return value.identifier case let .idCard(value): return value.identifier case let .internalPassport(value): return value.identifier default: return nil } } var personalDetails: SecureIdPersonalDetailsValue? { switch self { case let .personalDetails(value): return value default: return nil } } var selfieVerificationDocument: SecureIdVerificationDocumentReference? { switch self { case let .idCard(value): return value.selfieDocument case let .passport(value): return value.selfieDocument case let .driversLicense(value): return value.selfieDocument case let .internalPassport(value): return value.selfieDocument default: return nil } } var verificationDocuments: [SecureIdVerificationDocumentReference]? { switch self { case let .bankStatement(value): return value.verificationDocuments case let .rentalAgreement(value): return value.verificationDocuments case let .utilityBill(value): return value.verificationDocuments case let .passportRegistration(value): return value.verificationDocuments case let .temporaryRegistration(value): return value.verificationDocuments default: return nil } } var translations: [SecureIdVerificationDocumentReference]? { switch self { case let .passport(value): return value.translations case let .idCard(value): return value.translations case let .driversLicense(value): return value.translations case let .internalPassport(value): return value.translations case let .utilityBill(value): return value.translations case let .rentalAgreement(value): return value.translations case let .temporaryRegistration(value): return value.translations case let .passportRegistration(value): return value.translations case let .bankStatement(value): return value.translations default: return nil } } var frontSideVerificationDocument: SecureIdVerificationDocumentReference? { switch self { case let .idCard(value): return value.frontSideDocument case let .passport(value): return value.frontSideDocument case let .driversLicense(value): return value.frontSideDocument case let .internalPassport(value): return value.frontSideDocument default: return nil } } var backSideVerificationDocument: SecureIdVerificationDocumentReference? { switch self { case let .idCard(value): return value.backSideDocument case let .driversLicense(value): return value.backSideDocument default: return nil } } var hasBacksideDocument: Bool { switch self { case .idCard: return true case .driversLicense: return true default: return false } } var passportValue: SecureIdPassportValue? { switch self { case let .passport(value): return value default: return nil } } var phoneValue: SecureIdPhoneValue? { switch self { case let .phone(value): return value default: return nil } } var emailValue: SecureIdEmailValue? { switch self { case let .email(value): return value default: return nil } } var requestFieldType: SecureIdRequestedFormFieldValue { return key.requestFieldType } var expiryDate: SecureIdDate? { switch self { case let .idCard(value): return value.expiryDate case let .passport(value): return value.expiryDate case let .driversLicense(value): return value.expiryDate default: return nil } } } extension SecureIdValueKey { var requestFieldType: SecureIdRequestedFormFieldValue { switch self { case .address: return .address case .bankStatement: return .bankStatement(translation: true) case .driversLicense: return .driversLicense(selfie: true, translation: true) case .email: return .email case .idCard: return .idCard(selfie: true, translation: true) case .internalPassport: return .internalPassport(selfie: true, translation: true) case .passport: return .passport(selfie: true, translation: true) case .passportRegistration: return .passportRegistration(translation: true) case .personalDetails: return .personalDetails(nativeName: true) case .phone: return .phone case .rentalAgreement: return .rentalAgreement(translation: true) case .temporaryRegistration: return .temporaryRegistration(translation: true) case .utilityBill: return .utilityBill(translation: true) } } } extension SecureIdRequestedFormFieldValue { var rawValue: String { switch self { case .email: return strings().secureIdRequestPermissionEmail case .phone: return strings().secureIdRequestPermissionPhone case .address: return strings().secureIdRequestPermissionResidentialAddress case .utilityBill: return strings().secureIdRequestPermissionUtilityBill case .bankStatement: return strings().secureIdRequestPermissionBankStatement case .rentalAgreement: return strings().secureIdRequestPermissionTenancyAgreement case .passport: return strings().secureIdRequestPermissionPassport case .idCard: return strings().secureIdRequestPermissionIDCard case .driversLicense: return strings().secureIdRequestPermissionDriversLicense case .personalDetails: return strings().secureIdRequestPermissionPersonalDetails case .internalPassport: return strings().secureIdRequestPermissionInternalPassport case .passportRegistration: return strings().secureIdRequestPermissionPassportRegistration case .temporaryRegistration: return strings().secureIdRequestPermissionTemporaryRegistration } } func isKindOf(_ fieldValue: SecureIdRequestedFormFieldValue) -> Bool { switch self { case .email: if case .email = fieldValue { return true } else { return false } case .phone: if case .phone = fieldValue { return true } else { return false } case .address: if case .address = fieldValue { return true } else { return false } case .utilityBill: if case .utilityBill = fieldValue { return true } else { return false } case .bankStatement: if case .bankStatement = fieldValue { return true } else { return false } case .rentalAgreement: if case .rentalAgreement = fieldValue { return true } else { return false } case .passport: if case .passport = fieldValue { return true } else { return false } case .idCard: if case .idCard = fieldValue { return true } else { return false } case .driversLicense: if case .driversLicense = fieldValue { return true } else { return false } case .personalDetails: if case .personalDetails = fieldValue { return true } else { return false } case .internalPassport: if case .internalPassport = fieldValue { return true } else { return false } case .passportRegistration: if case .passportRegistration = fieldValue { return true } else { return false } case .temporaryRegistration: if case .temporaryRegistration = fieldValue { return true } else { return false } } } var uploadFrontTitleText: String { switch self { case .idCard: return strings().secureIdUploadFront case .driversLicense: return strings().secureIdUploadFront default: return strings().secureIdUploadMain } } var uploadBackTitleText: String { switch self { case .idCard: return strings().secureIdUploadReverse case .driversLicense: return strings().secureIdUploadReverse default: return strings().secureIdUploadMain } } var hasBacksideDocument: Bool { switch self { case .idCard: return true case .driversLicense: return true default: return false } } var hasSelfie: Bool { switch self { case let .passport(selfie, _), let .idCard(selfie, _), let .driversLicense(selfie, _), let .internalPassport(selfie, _): return selfie default: return false } } var hasTranslation: Bool { switch self { case let .passport(_, translation), let .idCard(_, translation), let .driversLicense(_, translation), let .internalPassport(_, translation): return translation case let .utilityBill(translation), let .rentalAgreement(translation), let .bankStatement(translation), let .passportRegistration(translation), let .temporaryRegistration(translation): return translation default: return false } } var emptyDescription: String { switch self { case .email: return strings().secureIdRequestPermissionEmailEmpty case .phone: return strings().secureIdRequestPermissionPhoneEmpty case .utilityBill: return strings().secureIdEmptyDescriptionUtilityBill case .bankStatement: return strings().secureIdEmptyDescriptionBankStatement case .rentalAgreement: return strings().secureIdEmptyDescriptionTenancyAgreement case .passportRegistration: return strings().secureIdEmptyDescriptionPassportRegistration case .temporaryRegistration: return strings().secureIdEmptyDescriptionTemporaryRegistration case .passport: return strings().secureIdEmptyDescriptionPassport case .driversLicense: return strings().secureIdEmptyDescriptionDriversLicense case .idCard: return strings().secureIdEmptyDescriptionIdentityCard case .internalPassport: return strings().secureIdEmptyDescriptionInternalPassport case .personalDetails: return strings().secureIdEmptyDescriptionPersonalDetails case .address: return strings().secureIdEmptyDescriptionAddress } } var descAdd: String { switch self { case .email: return "" case .phone: return "" case .address: return strings().secureIdAddResidentialAddress case .utilityBill: return strings().secureIdAddUtilityBill case .bankStatement: return strings().secureIdAddBankStatement case .rentalAgreement: return strings().secureIdAddTenancyAgreement case .passport: return strings().secureIdAddPassport case .idCard: return strings().secureIdAddID case .driversLicense: return strings().secureIdAddDriverLicense case .personalDetails: return strings().secureIdAddPersonalDetails case .internalPassport: return strings().secureIdAddInternalPassport case .passportRegistration: return strings().secureIdAddPassportRegistration case .temporaryRegistration: return strings().secureIdAddTemporaryRegistration } } var descEdit: String { switch self { case .email: return "" case .phone: return "" case .address: return strings().secureIdEditResidentialAddress case .utilityBill: return strings().secureIdEditUtilityBill case .bankStatement: return strings().secureIdEditBankStatement case .rentalAgreement: return strings().secureIdEditTenancyAgreement case .passport: return strings().secureIdEditPassport case .idCard: return strings().secureIdEditID case .driversLicense: return strings().secureIdEditDriverLicense case .personalDetails: return strings().secureIdEditPersonalDetails case .internalPassport: return strings().secureIdEditInternalPassport case .passportRegistration: return strings().secureIdEditPassportRegistration case .temporaryRegistration: return strings().secureIdEditTemporaryRegistration } } } var dateFormatter: DateFormatter { let formatter = DateFormatter() formatter.dateFormat = "dd.MM.yyyy" // formatter.timeZone = TimeZone(secondsFromGMT: 0) formatter.locale = Locale(identifier: "en_US_POSIX") return formatter } extension SecureIdRequestedFormFieldValue { var valueKey: SecureIdValueKey { switch self { case .address: return .address case .bankStatement: return .bankStatement case .driversLicense: return .driversLicense case .email: return .email case .idCard: return .idCard case .passport: return .passport case .personalDetails: return .personalDetails case .phone: return .phone case .rentalAgreement: return .rentalAgreement case .utilityBill: return .utilityBill case .internalPassport: return .internalPassport case .passportRegistration: return .passportRegistration case .temporaryRegistration: return .temporaryRegistration } } var primary: SecureIdRequestedFormFieldValue { if SecureIdRequestedFormField.just(self).isIdentityField { return .personalDetails(nativeName: true) } if SecureIdRequestedFormField.just(self).isAddressField { return .address } return self } func isEqualToMRZ(_ mrz: TGPassportMRZ) -> Bool { switch mrz.documentType.lowercased() { case "p": if case .passport = self { return true } else { return false } default: return false } } } extension InputDataValue { var secureIdDate: SecureIdDate? { switch self { case let .date(day, month, year): if let day = day, let month = month, let year = year { return SecureIdDate(day: day, month: month, year: year) } return nil default: return nil } } } extension SecureIdDate { var inputDataValue: InputDataValue { return .date(day, month, year) } } public func peerCompactDisplayTitles(_ peerIds: [PeerId], _ dict: SimpleDictionary<PeerId, Peer>) -> String { var names:String = "" for peerId in peerIds { if let peer = dict[peerId] { names += peer.compactDisplayTitle if peerId != peerIds.last { names += ", " } } } return names } func mediaResource(from media:Media?) -> TelegramMediaResource? { if let media = media as? TelegramMediaFile { return media.resource } else if let media = media as? TelegramMediaImage { return largestImageRepresentation(media.representations)?.resource } return nil } func mediaResourceMIMEType(from media:Media?) -> String? { if let media = media as? TelegramMediaFile { return media.mimeType } else if media is TelegramMediaImage { return "image/jpeg" } return nil } func mediaResourceName(from media:Media?, ext:String?) -> String { let dateFormatter = DateFormatter() dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss" let ext = ext ?? ".file" if let media = media as? TelegramMediaFile { return media.fileName ?? "FILE " + dateFormatter.string(from: Date()) + "." + ext } else if media is TelegramMediaImage { return "IMAGE " + dateFormatter.string(from: Date()) + "." + ext } return "FILE " + dateFormatter.string(from: Date()) + "." + ext } func removeChatInteractively(context: AccountContext, peerId:PeerId, threadId: Int64? = nil, userId: PeerId? = nil, deleteGroup: Bool = false) -> Signal<Bool, NoError> { return context.account.postbox.peerView(id: peerId) |> take(1) |> map { peerViewMainPeer($0) } |> filter { $0 != nil } |> map { $0! } |> deliverOnMainQueue |> mapToSignal { peer -> Signal<Bool, NoError> in let text:String var okTitle: String? = nil var thridTitle: String? = nil var canRemoveGlobally: Bool = false if let _ = threadId { okTitle = strings().confirmDelete text = strings().chatContextDeleteTopic } else { if let peer = peer as? TelegramChannel { switch peer.info { case .broadcast: if peer.flags.contains(.isCreator) && deleteGroup { text = strings().confirmDeleteAdminedChannel okTitle = strings().confirmDelete } else { text = strings().peerInfoConfirmLeaveChannel } case .group: if deleteGroup && peer.flags.contains(.isCreator) { text = strings().peerInfoConfirmDeleteGroupConfirmation okTitle = strings().confirmDelete } else { text = strings().confirmLeaveGroup okTitle = strings().peerInfoConfirmLeave } } } else if let peer = peer as? TelegramGroup { text = strings().peerInfoConfirmDeleteChat(peer.title) okTitle = strings().confirmDelete } else { text = strings().peerInfoConfirmDeleteUserChat okTitle = strings().confirmDelete } if peerId.namespace == Namespaces.Peer.CloudUser && peerId != context.account.peerId && !peer.isBot { if context.limitConfiguration.maxMessageRevokeIntervalInPrivateChats == LimitsConfiguration.timeIntervalForever { canRemoveGlobally = true } } if peerId.namespace == Namespaces.Peer.SecretChat { canRemoveGlobally = false } if canRemoveGlobally { thridTitle = strings().chatMessageDeleteForMeAndPerson(peer.displayTitle) } else if peer.isBot { thridTitle = strings().peerInfoStopBot } if peer.groupAccess.isCreator, deleteGroup { canRemoveGlobally = true thridTitle = strings().deleteChatDeleteGroupForAll } } return combineLatest(modernConfirmSignal(for: context.window, account: context.account, peerId: userId ?? peerId, information: text, okTitle: okTitle ?? strings().alertOK, thridTitle: thridTitle, thridAutoOn: false), context.globalPeerHandler.get() |> take(1)) |> map { result, location -> Bool in if let threadId = threadId { _ = context.engine.peers.removeForumChannelThread(id: peerId, threadId: threadId).start() } else { _ = context.engine.peers.removePeerChat(peerId: peerId, reportChatSpam: false, deleteGloballyIfPossible: canRemoveGlobally).start() if peer.isBot && result == .thrid { _ = context.blockedPeersContext.add(peerId: peerId).start() } } switch location { case let .peer(id): if id == peerId { context.bindings.rootNavigation().close() } case let .thread(data): if threadId == nil { if data.messageId.peerId == peerId { context.bindings.rootNavigation().close() } } else { if makeMessageThreadId(data.messageId) == threadId { context.bindings.rootNavigation().close() } } case .none: break } return true } } } func applyExternalProxy(_ server:ProxyServerSettings, accountManager: AccountManager<TelegramAccountManagerTypes>) { var textInfo = strings().proxyForceEnableTextIP(server.host) + "\n" + strings().proxyForceEnableTextPort(Int(server.port)) switch server.connection { case let .socks5(username, password): if let user = username { textInfo += "\n" + strings().proxyForceEnableTextUsername(user) } if let pass = password { textInfo += "\n" + strings().proxyForceEnableTextPassword(pass) } case let .mtp(secret): textInfo += "\n" + strings().proxyForceEnableTextSecret(MTProxySecret.parseData(secret)?.serializeToString() ?? "") } textInfo += "\n\n" + strings().proxyForceEnableText if case .mtp = server.connection { textInfo += "\n\n" + strings().proxyForceEnableMTPDesc } modernConfirm(for: mainWindow, account: nil, peerId: nil, header: strings().proxyForceEnableHeader1, information: textInfo, okTitle: strings().proxyForceEnableOK, thridTitle: strings().proxyForceEnableEnable, successHandler: { result in _ = updateProxySettingsInteractively(accountManager: accountManager, { current -> ProxySettings in var current = current.withAddedServer(server) if result == .thrid { current = current.withUpdatedActiveServer(server).withUpdatedEnabled(true) } return current }).start() }) } extension SecureIdGender { var stringValue: String { switch self { case .female: return strings().secureIdGenderFemale case .male: return strings().secureIdGenderMale } } } extension SecureIdDate { var stringValue: String { return "\(day).\(month).\(year)" } } func moveWallpaperToCache(postbox: Postbox, resource: TelegramMediaResource, reference: WallpaperReference?, settings: WallpaperSettings, isPattern: Bool) -> Signal<String, NoError> { let resourceData: Signal<MediaResourceData, NoError> if isPattern { resourceData = postbox.mediaBox.cachedResourceRepresentation(resource, representation: CachedPatternWallpaperMaskRepresentation(size: nil, settings: settings), complete: true) } else if settings.blur { resourceData = postbox.mediaBox.cachedResourceRepresentation(resource, representation: CachedBlurredWallpaperRepresentation(), complete: true) } else { resourceData = postbox.mediaBox.resourceData(resource) } return combineLatest(fetchedMediaResource(mediaBox: postbox.mediaBox, reference: MediaResourceReference.wallpaper(wallpaper: reference, resource: resource), reportResultStatus: true) |> `catch` { _ in return .complete() }, resourceData) |> mapToSignal { _, data in if data.complete { return moveWallpaperToCache(postbox: postbox, path: data.path, resource: resource, settings: settings) } else { return .complete() } } } func moveWallpaperToCache(postbox: Postbox, wallpaper: Wallpaper) -> Signal<Wallpaper, NoError> { switch wallpaper { case let .image(reps, settings): return moveWallpaperToCache(postbox: postbox, resource: largestImageRepresentation(reps)!.resource, reference: nil, settings: settings, isPattern: false) |> map { _ in return wallpaper} case let .custom(representation, blurred): return moveWallpaperToCache(postbox: postbox, resource: representation.resource, reference: nil, settings: WallpaperSettings(blur: blurred), isPattern: false) |> map { _ in return wallpaper} case let .file(slug, file, settings, isPattern): return moveWallpaperToCache(postbox: postbox, resource: file.resource, reference: .slug(slug), settings: settings, isPattern: isPattern) |> map { _ in return wallpaper} default: return .single(wallpaper) } } func moveWallpaperToCache(postbox: Postbox, path: String, resource: TelegramMediaResource, settings: WallpaperSettings) -> Signal<String, NoError> { return Signal { subscriber in let wallpapers = ApiEnvironment.containerURL!.appendingPathComponent("Wallpapers").path try? FileManager.default.createDirectory(at: URL(fileURLWithPath: wallpapers), withIntermediateDirectories: true, attributes: nil) let out = wallpapers + "/" + resource.id.stringRepresentation + "\(settings.stringValue)" + ".png" if !FileManager.default.fileExists(atPath: out) { try? FileManager.default.removeItem(atPath: out) try? FileManager.default.copyItem(atPath: path, toPath: out) } subscriber.putNext(out) subscriber.putCompletion() return EmptyDisposable } } extension WallpaperSettings { var stringValue: String { var value: String = "" if let top = self.colors.first { value += "ctop\(top)" } if let top = self.colors.last, self.colors.count == 2 { value += "cbottom\(top)" } if let rotation = self.rotation { value += "rotation\(rotation)" } if self.blur { value += "blur" } return value } } func wallpaperPath(_ resource: TelegramMediaResource, settings: WallpaperSettings) -> String { return ApiEnvironment.containerURL!.appendingPathComponent("Wallpapers").path + "/" + resource.id.stringRepresentation + "\(settings.stringValue)" + ".png" } func canCollagesFromUrl(_ urls:[URL]) -> Bool { var canCollage: Bool = urls.count > 1 && urls.count <= 10 var musicCount: Int = 0 var voiceCount: Int = 0 var gifCount: Int = 0 if canCollage { for url in urls { let mime = MIMEType(url.path) let attrs = Sender.fileAttributes(for: mime, path: url.path, isMedia: true, inCollage: true) let isGif = attrs.contains(where: { attr -> Bool in switch attr { case .Animated: return true default: return false } }) let isMusic = attrs.contains(where: { attr -> Bool in switch attr { case let .Audio(isVoice, _, _, _, _): return !isVoice default: return false } }) let isVoice = attrs.contains(where: { attr -> Bool in switch attr { case let .Audio(isVoice, _, _, _, _): return isVoice default: return false } }) if mime == "image/webp" { return false } if isMusic { musicCount += 1 } if isVoice { voiceCount += 1 } if isGif { gifCount += 1 } } } if musicCount > 0 { if musicCount == urls.count { return true } else { return false } } if voiceCount > 0 { return false } if gifCount > 0 { return false } return canCollage } extension AutomaticMediaDownloadSettings { func isDownloable(_ message: Message) -> Bool { if !automaticDownload { return false } func ability(_ category: AutomaticMediaDownloadCategoryPeers, _ peer: Peer) -> Bool { if peer.isGroup || peer.isSupergroup { return category.groupChats } else if peer.isChannel { return category.channels } else { return category.privateChats } } func checkFile(_ media: TelegramMediaFile, _ peer: Peer, _ categories: AutomaticMediaDownloadCategories) -> Bool { let size = Int64(media.size ?? 0) let dangerExts = "action app bin command csh osx workflow terminal url caction mpkg pkg xhtm webarchive" if let ext = media.fileName?.nsstring.pathExtension.lowercased(), dangerExts.components(separatedBy: " ").contains(ext) { return false } switch true { case media.isInstantVideo: return ability(categories.video, peer) && size <= (categories.video.fileSize ?? INT32_MAX) case media.isVideo && media.isAnimated: return ability(categories.video, peer) && size <= (categories.video.fileSize ?? INT32_MAX) case media.isVideo: return ability(categories.video, peer) && size <= (categories.video.fileSize ?? INT32_MAX) case media.isVoice: return size <= 1 * 1024 * 1024 default: return ability(categories.files, peer) && size <= (categories.files.fileSize ?? INT32_MAX) } } if let peer = coreMessageMainPeer(message) { if let _ = message.effectiveMedia as? TelegramMediaImage { return ability(categories.photo, peer) } else if let media = message.effectiveMedia as? TelegramMediaFile { return checkFile(media, peer, categories) } else if let media = message.effectiveMedia as? TelegramMediaWebpage { switch media.content { case let .Loaded(content): if content.type == "telegram_background" { return ability(categories.photo, peer) } if let file = content.file { return checkFile(file, peer, categories) } else if let _ = content.image { return ability(categories.photo, peer) } default: break } } else if let media = message.effectiveMedia as? TelegramMediaGame { if let file = media.file { return checkFile(file, peer, categories) } else if let _ = media.image { return ability(categories.photo, peer) } } } return false } } func fileExtenstion(_ file: TelegramMediaFile) -> String { return fileExt(file.mimeType) ?? file.fileName?.nsstring.pathExtension ?? "" } func proxySettings(accountManager: AccountManager<TelegramAccountManagerTypes>) -> Signal<ProxySettings, NoError> { return accountManager.sharedData(keys: [SharedDataKeys.proxySettings]) |> map { view in return view.entries[SharedDataKeys.proxySettings]?.get(ProxySettings.self) ?? ProxySettings.defaultSettings } } extension ProxySettings { func withUpdatedActiveServer(_ activeServer: ProxyServerSettings?) -> ProxySettings { return ProxySettings(enabled: self.enabled, servers: servers, activeServer: activeServer, useForCalls: self.useForCalls) } func withUpdatedEnabled(_ enabled: Bool) -> ProxySettings { return ProxySettings(enabled: enabled, servers: self.servers, activeServer: self.activeServer, useForCalls: self.useForCalls) } func withAddedServer(_ proxy: ProxyServerSettings) -> ProxySettings { var servers = self.servers if servers.first(where: {$0 == proxy}) == nil { servers.append(proxy) } return ProxySettings(enabled: self.enabled, servers: servers, activeServer: self.activeServer, useForCalls: self.useForCalls) } func withUpdatedServer(_ current: ProxyServerSettings, with updated: ProxyServerSettings) -> ProxySettings { var servers = self.servers if let index = servers.firstIndex(where: {$0 == current}) { servers[index] = updated } else { servers.append(updated) } var activeServer = self.activeServer if activeServer == current { activeServer = updated } return ProxySettings(enabled: self.enabled, servers: servers, activeServer: activeServer, useForCalls: self.useForCalls) } func withUpdatedUseForCalls(_ enable: Bool) -> ProxySettings { return ProxySettings(enabled: self.enabled, servers: servers, activeServer: self.activeServer, useForCalls: enable) } func withRemovedServer(_ proxy: ProxyServerSettings) -> ProxySettings { var servers = self.servers var activeServer = self.activeServer var enabled: Bool = self.enabled if let index = servers.firstIndex(where: {$0 == proxy}) { _ = servers.remove(at: index) } if proxy == activeServer { activeServer = nil enabled = false } return ProxySettings(enabled: enabled, servers: servers, activeServer: activeServer, useForCalls: self.useForCalls) } } extension ProxyServerSettings { var link: String { let prefix: String switch self.connection { case .mtp: prefix = "proxy" case .socks5: prefix = "socks" } var link = "tg://\(prefix)?server=\(self.host)&port=\(self.port)" switch self.connection { case let .mtp(secret): link += "&secret=\((secret as NSData).hexString)" case let .socks5(username, password): if let username = username { link += "&user=\(username)" } if let password = password { link += "&pass=\(password)" } } return link } var isEmpty: Bool { if host.isEmpty { return true } if port == 0 { return true } switch self.connection { case let .mtp(secret): if secret.isEmpty { return true } default: break } return false } } struct SecureIdDocumentValue { let document: SecureIdVerificationDocument let stableId: AnyHashable let context: SecureIdAccessContext init(document: SecureIdVerificationDocument, context: SecureIdAccessContext, stableId: AnyHashable) { self.document = document self.stableId = stableId self.context = context } var image: TelegramMediaImage { return TelegramMediaImage(imageId: MediaId(namespace: 0, id: 0), representations: [TelegramMediaImageRepresentation(dimensions: PixelDimensions(100, 100), resource: document.resource, progressiveSizes: [], immediateThumbnailData: nil, hasVideo: false)], immediateThumbnailData: nil, reference: nil, partialReference: nil, flags: []) } } enum FaqDestination { case telegram case ton case walletTOS var url:String { switch self { case .telegram: return "https://telegram.org/faq/" case .ton: return "https://telegram.org/faq/gram_wallet/" case .walletTOS: return "https://telegram.org/tos/wallet/" } } } func openFaq(context: AccountContext, dest: FaqDestination = .telegram) { let language = appCurrentLanguage.languageCode[appCurrentLanguage.languageCode.index(appCurrentLanguage.languageCode.endIndex, offsetBy: -2) ..< appCurrentLanguage.languageCode.endIndex] _ = showModalProgress(signal: webpagePreview(account: context.account, url: dest.url) |> deliverOnMainQueue, for: context.window).start(next: { webpage in if let webpage = webpage { showInstantPage(InstantPageViewController(context, webPage: webpage, message: nil)) } else { execute(inapp: .external(link: dest.url + language, true)) } }) } func isNotEmptyStrings(_ strings: [String?]) -> String { for string in strings { if let string = string, !string.isEmpty { return string } } return "" } extension TelegramMediaImage { var isLocalResource: Bool { if let resource = representations.last?.resource { if resource is LocalFileMediaResource { return true } if resource is LocalFileReferenceMediaResource { return true } } return false } } extension TelegramMediaFile { var isLocalResource: Bool { if resource is LocalFileMediaResource { return true } if resource is LocalFileReferenceMediaResource { return true } return false } var premiumEffect: TelegramMediaFile.VideoThumbnail? { if let resource = self.videoThumbnails.first(where: { thumbnail in if let resource = thumbnail.resource as? CloudDocumentSizeMediaResource, resource.sizeSpec == "f" { return true } else { return false } }) { return resource } return nil } } extension MessageIndex { func withUpdatedTimestamp(_ timestamp: Int32) -> MessageIndex { return MessageIndex(id: self.id, timestamp: timestamp) } init(_ message: Message) { self.init(id: message.id, timestamp: message.timestamp) } } func requestMicrophonePermission() -> Signal<Bool, NoError> { return requestMediaPermission(.audio) } func requestCameraPermission() -> Signal<Bool, NoError> { return requestMediaPermission(.video) } func requestScreenCapturPermission() -> Signal<Bool, NoError> { return Signal { subscriber in subscriber.putNext(requestScreenCaptureAccess()) subscriber.putCompletion() return EmptyDisposable } |> runOn(.mainQueue()) } func screenCaptureAvailable() -> Bool { let stream = CGDisplayStream(dispatchQueueDisplay: CGMainDisplayID(), outputWidth: 1, outputHeight: 1, pixelFormat: Int32(kCVPixelFormatType_32BGRA), properties: nil, queue: DispatchQueue.main, handler: { _, _, _, _ in }) let result = stream != nil return result } func requestScreenCaptureAccess() -> Bool { if #available(OSX 11.0, *) { if !CGPreflightScreenCaptureAccess() { return CGRequestScreenCaptureAccess() } else { return true } } else { return screenCaptureAvailable() } } func requestMediaPermission(_ type: AVFoundation.AVMediaType) -> Signal<Bool, NoError> { if #available(OSX 10.14, *) { return Signal { subscriber in let status = AVCaptureDevice.authorizationStatus(for: type) var cancelled: Bool = false switch status { case .notDetermined: AVCaptureDevice.requestAccess(for: type, completionHandler: { completed in if !cancelled { subscriber.putNext(completed) subscriber.putCompletion() } }) case .authorized: subscriber.putNext(true) subscriber.putCompletion() case .denied: subscriber.putNext(false) subscriber.putCompletion() case .restricted: subscriber.putNext(false) subscriber.putCompletion() @unknown default: subscriber.putNext(false) subscriber.putCompletion() } return ActionDisposable { cancelled = true } } |> runOn(.concurrentDefaultQueue()) |> deliverOnMainQueue } else { return .single(true) } } enum SystemSettingsCategory : String { case microphone = "Privacy_Microphone" case camera = "Privacy_Camera" case storage = "Storage" case sharing = "Privacy_ScreenCapture" case accessibility = "Privacy_Accessibility" case notifications = "Notifications" case none = "" } func openSystemSettings(_ category: SystemSettingsCategory) { switch category { case .storage: //if let url = URL(string: "/System/Applications/Utilities/System%20Information.app") { NSWorkspace.shared.launchApplication("/System/Applications/Utilities/System Information.app") // [[NSWorkspace sharedWorkspace] launchApplication:@"/Applications/Safari.app"]; // } case .microphone, .camera, .sharing: if let url = URL(string: "x-apple.systempreferences:com.apple.preference.security?\(category.rawValue)") { NSWorkspace.shared.open(url) } case .notifications: if let url = URL(string: "x-apple.systempreferences:com.apple.preference.notifications") { NSWorkspace.shared.open(url) } default: break } } extension MessageHistoryAnchorIndex { func withSubstractedTimestamp(_ timestamp: Int32) -> MessageHistoryAnchorIndex { switch self { case let .message(index): return MessageHistoryAnchorIndex.message(MessageIndex(id: index.id, timestamp: index.timestamp - timestamp)) default: return self } } } extension ChatContextResultCollection { func withAdditionalCollection(_ collection: ChatContextResultCollection) -> ChatContextResultCollection { return ChatContextResultCollection(botId: collection.botId, peerId: collection.peerId, query: collection.query, geoPoint: collection.geoPoint, queryId: collection.queryId, nextOffset: collection.nextOffset, presentation: collection.presentation, switchPeer: collection.switchPeer, results: self.results + collection.results, cacheTimeout: collection.cacheTimeout) } } extension LocalFileReferenceMediaResource : Equatable { public static func ==(lhs: LocalFileReferenceMediaResource, rhs: LocalFileReferenceMediaResource) -> Bool { return lhs.isEqual(to: rhs) } } public func removeFile(at path: String) { try? FileManager.default.removeItem(atPath: path) } extension FileManager { func modificationDateForFileAtPath(path:String) -> NSDate? { guard let attributes = try? self.attributesOfItem(atPath: path) else { return nil } return attributes[.modificationDate] as? NSDate } func creationDateForFileAtPath(path:String) -> NSDate? { guard let attributes = try? self.attributesOfItem(atPath: path) else { return nil } return attributes[.creationDate] as? NSDate } } extension MessageForwardInfo { var authorTitle: String { return author?.displayTitle ?? authorSignature ?? "" } } func bigEmojiMessage(_ sharedContext: SharedAccountContext, message: Message) -> Bool { let text = message.text.replacingOccurrences(of: " ", with: "").replacingOccurrences(of: "\n", with: "") return sharedContext.baseSettings.bigEmoji && message.media.isEmpty && message.replyMarkup == nil && text.containsOnlyEmoji } struct PeerEquatable: Equatable { let peer: Peer init(peer: Peer) { self.peer = peer } init(_ peer: Peer) { self.peer = peer } init?(_ peer: Peer?) { if let peer = peer { self.peer = peer } else { return nil } } static func ==(lhs: PeerEquatable, rhs: PeerEquatable) -> Bool { return lhs.peer.isEqual(rhs.peer) } } struct CachedDataEquatable: Equatable { let data: CachedPeerData init?(data: CachedPeerData?) { if let data = data { self.data = data } else { return nil } } init?(_ data: CachedPeerData?) { self.init(data: data) } static func ==(lhs: CachedDataEquatable, rhs: CachedDataEquatable) -> Bool { return lhs.data.isEqual(to: rhs.data) } } extension CGImage { var cvPixelBuffer: CVPixelBuffer? { var pixelBuffer: CVPixelBuffer? = nil let options: [NSObject: Any] = [ kCVPixelBufferCGImageCompatibilityKey: false, kCVPixelBufferCGBitmapContextCompatibilityKey: false, ] let status = CVPixelBufferCreate(kCFAllocatorDefault, Int(size.width), Int(size.height), kCVPixelFormatType_32BGRA, options as CFDictionary, &pixelBuffer) CVPixelBufferLockBaseAddress(pixelBuffer!, CVPixelBufferLockFlags(rawValue: 0)) let pixelData = CVPixelBufferGetBaseAddress(pixelBuffer!) let rgbColorSpace = CGColorSpaceCreateDeviceRGB() let context = CGContext(data: pixelData, width: Int(size.width), height: Int(size.height), bitsPerComponent: 8, bytesPerRow: CVPixelBufferGetBytesPerRow(pixelBuffer!), space: rgbColorSpace, bitmapInfo: CGBitmapInfo.byteOrder32Little.rawValue) context?.draw(self, in: CGRect(origin: .zero, size: size)) CVPixelBufferUnlockBaseAddress(pixelBuffer!, CVPixelBufferLockFlags(rawValue: 0)) return pixelBuffer } } private let emojis: [String: (String, CGFloat)] = [ "👍": ("thumbs_up_1", 450.0), "👍🏻": ("thumbs_up_2", 450.0), "👍🏼": ("thumbs_up_3", 450.0), "👍🏽": ("thumbs_up_4", 450.0), "👍🏾": ("thumbs_up_5", 450.0), "👍🏿": ("thumbs_up_6", 450.0), "😂": ("lol", 350.0), "😒": ("meh", 350.0), "❤️": ("heart", 350.0), "♥️": ("heart", 350.0), "🥳": ("celeb", 430.0), "😳": ("confused", 350.0) ] func animatedEmojiResource(emoji: String) -> (LocalBundleResource, CGFloat)? { if let (name, size) = emojis[emoji] { return (LocalBundleResource(name: name, ext: "tgs"), size) } else { return nil } } extension TelegramMediaWebpageLoadedContent { func withUpdatedYoutubeTimecode(_ timecode: Double) -> TelegramMediaWebpageLoadedContent { var newUrl = self.url if let range = self.url.range(of: "t=") { let substr = String(newUrl[range.upperBound...]) var parsed: String = "" for char in substr { if "0987654321".contains(char) { parsed += String(char) } else { break } } newUrl = newUrl.replacingOccurrences(of: parsed, with: "\(Int(timecode))", options: .caseInsensitive, range: range.lowerBound ..< newUrl.endIndex) } else { if url.contains("?") { newUrl = self.url + "&t=\(Int(timecode))" } else { newUrl = self.url + "?t=\(Int(timecode))" } } return TelegramMediaWebpageLoadedContent(url: newUrl, displayUrl: self.displayUrl, hash: self.hash, type: self.type, websiteName: self.websiteName, title: self.title, text: self.text, embedUrl: self.embedUrl, embedType: self.embedType, embedSize: self.embedSize, duration: self.duration, author: self.author, image: self.image, file: self.file, attributes: self.attributes, instantPage: self.instantPage) } func withUpdatedFile(_ file: TelegramMediaFile) -> TelegramMediaWebpageLoadedContent { return TelegramMediaWebpageLoadedContent(url: self.url, displayUrl: self.displayUrl, hash: self.hash, type: self.type, websiteName: self.websiteName, title: self.title, text: self.text, embedUrl: self.embedUrl, embedType: self.embedType, embedSize: self.embedSize, duration: self.duration, author: self.author, image: self.image, file: file, attributes: self.attributes, instantPage: self.instantPage) } var isCrossplatformTheme: Bool { for attr in attributes { switch attr { case let .theme(theme): var hasFile: Bool = false for file in theme.files { if file.mimeType == "application/x-tgtheme-macos", !file.previewRepresentations.isEmpty { hasFile = true } } if let _ = theme.settings, !hasFile { return true } default: break } } return false } var crossplatformPalette: ColorPalette? { for attr in attributes { switch attr { case let .theme(theme): return theme.settings?.palette default: break } } return nil } var crossplatformWallpaper: Wallpaper? { for attr in attributes { switch attr { case let .theme(theme): return theme.settings?.background?.uiWallpaper default: break } } return nil } var themeSettings: TelegramThemeSettings? { for attr in attributes { switch attr { case let .theme(theme): return theme.settings default: break } } return nil } } extension TelegramBaseTheme { var palette: ColorPalette { switch self { case .classic: return dayClassicPalette case .day: return whitePalette case .night, .tinted: return nightAccentPalette } } } extension TelegramThemeSettings { var palette: ColorPalette { return baseTheme.palette.withAccentColor(accent) } var accent: PaletteAccentColor { let messages = self.messageColors.map { NSColor(rgb: UInt32(bitPattern: $0)) } return PaletteAccentColor(NSColor(rgb: UInt32(bitPattern: self.accentColor)), messages) } var background: TelegramWallpaper? { if let wallpaper = self.wallpaper { return wallpaper } else { if self.baseTheme == .classic { return .builtin(WallpaperSettings()) } } return nil } var desc: String { let wString: String if let wallpaper = self.wallpaper { wString = "\(wallpaper)" } else { wString = "" } let colors = messageColors.map { "\($0)" }.split(separator: "-").joined() return "\(self.accentColor)-\(self.baseTheme)-\(colors)-\(wString)" } } extension TelegramWallpaper { var uiWallpaper: Wallpaper { let t: Wallpaper switch self { case .builtin: t = .builtin case let .color(color): t = .color(color) case let .file(values): t = .file(slug: values.slug, file: values.file, settings: values.settings, isPattern: values.isPattern) case let .gradient(gradient): t = .gradient(gradient.id, gradient.colors, gradient.settings.rotation) case let .image(reps, settings): t = .image(reps, settings: settings) } return t } } extension Wallpaper { var cloudWallpaper: TelegramWallpaper? { switch self { case .builtin: return .builtin(WallpaperSettings()) case let .color(color): return .color(color) case let .gradient(id, colors, rotation): return .gradient(.init(id: id, colors: colors, settings: WallpaperSettings(rotation: rotation))) default: break } return nil } } // extension CachedChannelData.LinkedDiscussionPeerId { var peerId: PeerId? { switch self { case let .known(peerId): return peerId case .unknown: return nil } } } func permanentExportedInvitation(context: AccountContext, peerId: PeerId) -> Signal<ExportedInvitation?, NoError> { return context.account.postbox.transaction { transaction -> ExportedInvitation? in let cachedData = transaction.getPeerCachedData(peerId: peerId) if let cachedData = cachedData as? CachedChannelData { return cachedData.exportedInvitation } if let cachedData = cachedData as? CachedGroupData { return cachedData.exportedInvitation } return nil } |> mapToSignal { invitation in if invitation == nil { return context.engine.peers.revokePersistentPeerExportedInvitation(peerId: peerId) } else { return .single(invitation) } } } extension CachedPeerAutoremoveTimeout { var timeout: CachedPeerAutoremoveTimeout.Value? { switch self { case let .known(timeout): return timeout case .unknown: return nil } } } func clearHistory(context: AccountContext, peer: Peer, mainPeer: Peer, canDeleteForAll: Bool? = nil) { var thridTitle: String? = nil var canRemoveGlobally: Bool = canDeleteForAll ?? false if peer.id.namespace == Namespaces.Peer.CloudUser && peer.id != context.account.peerId && !peer.isBot { if context.limitConfiguration.maxMessageRevokeIntervalInPrivateChats == LimitsConfiguration.timeIntervalForever { canRemoveGlobally = true } } if canRemoveGlobally { if let peer = peer as? TelegramUser { thridTitle = strings().chatMessageDeleteForMeAndPerson(peer.displayTitle) } else { thridTitle = strings().chatMessageDeleteForAll } } let information = mainPeer is TelegramUser || mainPeer is TelegramSecretChat ? peer.id == context.peerId ? strings().peerInfoConfirmClearHistorySavedMesssages : canRemoveGlobally || peer.id.namespace == Namespaces.Peer.SecretChat ? strings().peerInfoConfirmClearHistoryUserBothSides : strings().peerInfoConfirmClearHistoryUser : strings().peerInfoConfirmClearHistoryGroup modernConfirm(for: context.window, account: context.account, peerId: mainPeer.id, information:information , okTitle: strings().peerInfoConfirmClear, thridTitle: thridTitle, thridAutoOn: false, successHandler: { result in _ = context.engine.messages.clearHistoryInteractively(peerId: peer.id, threadId: nil, type: result == .thrid ? .forEveryone : .forLocalPeer).start() }) } func coreMessageMainPeer(_ message: Message) -> Peer? { return messageMainPeer(.init(message))?._asPeer() } func showProtectedCopyAlert(_ message: Message, for window: Window) { if let peer = message.peers[message.id.peerId] { let text: String if peer.isGroup || peer.isSupergroup { text = strings().copyRestrictedGroup } else { text = strings().copyRestrictedChannel } showModalText(for: window, text: text) } } func showProtectedCopyAlert(_ peer: Peer, for window: Window) { let text: String if peer.isGroup || peer.isSupergroup { text = strings().copyRestrictedGroup } else { text = strings().copyRestrictedChannel } showModalText(for: window, text: text) } extension Peer { var isCopyProtected: Bool { if let peer = self as? TelegramGroup { return peer.flags.contains(.copyProtectionEnabled) && !peer.groupAccess.isCreator } else if let peer = self as? TelegramChannel { return peer.flags.contains(.copyProtectionEnabled) && !(peer.adminRights != nil || peer.groupAccess.isCreator) } else { return false } } var emojiStatus: PeerEmojiStatus? { if let peer = self as? TelegramUser { return peer.emojiStatus } return nil } } extension ChatListFilter { var icon: CGImage { if let data = self.data { if data.categories == .all && data.excludeMuted && !data.excludeRead { return theme.icons.chat_filter_unmuted } else if data.categories == .all && !data.excludeMuted && data.excludeRead { return theme.icons.chat_filter_unread } else if data.categories == .groups { return theme.icons.chat_filter_groups } else if data.categories == .channels { return theme.icons.chat_filter_channels } else if data.categories == .contacts { return theme.icons.chat_filter_private_chats } else if data.categories == .nonContacts { return theme.icons.chat_filter_non_contacts } else if data.categories == .bots { return theme.icons.chat_filter_bots } } return theme.icons.chat_filter_custom } } extension SoftwareVideoSource { func preview(size: NSSize, backingScale: Int) -> CGImage? { let frameAndLoop = self.readFrame(maxPts: nil) if frameAndLoop.0 == nil { return nil } guard let frame = frameAndLoop.0 else { return nil } let s:(w: Int, h: Int) = (w: Int(size.width) * backingScale, h: Int(size.height) * backingScale) let destBytesPerRow = DeviceGraphicsContextSettings.shared.bytesPerRow(forWidth: s.w) let bufferSize = s.h * DeviceGraphicsContextSettings.shared.bytesPerRow(forWidth: s.w) let memoryData = malloc(bufferSize)! let bytes = memoryData.assumingMemoryBound(to: UInt8.self) let imageBuffer = CMSampleBufferGetImageBuffer(frame.sampleBuffer) CVPixelBufferLockBaseAddress(imageBuffer!, CVPixelBufferLockFlags(rawValue: 0)) let bytesPerRow = CVPixelBufferGetBytesPerRow(imageBuffer!) let width = CVPixelBufferGetWidth(imageBuffer!) let height = CVPixelBufferGetHeight(imageBuffer!) let srcData = CVPixelBufferGetBaseAddress(imageBuffer!) var sourceBuffer = vImage_Buffer(data: srcData, height: vImagePixelCount(height), width: vImagePixelCount(width), rowBytes: bytesPerRow) var destBuffer = vImage_Buffer(data: bytes, height: vImagePixelCount(s.h), width: vImagePixelCount(s.w), rowBytes: destBytesPerRow) let _ = vImageScale_ARGB8888(&sourceBuffer, &destBuffer, nil, vImage_Flags(kvImageDoNotTile)) CVPixelBufferUnlockBaseAddress(imageBuffer!, CVPixelBufferLockFlags(rawValue: 0)) return generateImagePixel(size, scale: CGFloat(backingScale), pixelGenerator: { (_, pixelData, bytesPerRow) in memcpy(pixelData, bytes, bufferSize) }) } } func installAttachMenuBot(context: AccountContext, peer: Peer, completion: @escaping(Bool)->Void) { confirm(for: context.window, information: strings().webAppAttachConfirm(peer.displayTitle), okTitle: strings().webAppAttachConfirmOK, successHandler: { _ in _ = showModalProgress(signal: context.engine.messages.addBotToAttachMenu(botId: peer.id), for: context.window).start(next: { value in if value { showModalText(for: context.window, text: strings().webAppAttachSuccess(peer.displayTitle)) completion(value) } }) }) } extension NSAttributedString { static func makeAnimated(_ file: TelegramMediaFile, text: String, info: ItemCollectionId? = nil, fromRect: NSRect? = nil) -> NSAttributedString { let attach = NSMutableAttributedString() _ = attach.append(string: text) attach.addAttribute(.init(rawValue: TGAnimatedEmojiAttributeName), value: TGTextAttachment(identifier: "\(arc4random())", fileId: file.fileId.id, file: file, text: text, info: info, from: fromRect ?? .zero), range: NSMakeRange(0, text.length)) return attach } static func makeEmojiHolder(_ emoji: String, fromRect: NSRect?) -> NSAttributedString { let attach = NSMutableAttributedString() _ = attach.append(string: emoji) if let fromRect = fromRect, FastSettings.animateInputEmoji { let tag = TGInputTextEmojiHolder(uniqueId: arc4random64(), emoji: emoji, rect: fromRect, attribute: TGInputTextAttribute(name: NSAttributedString.Key.foregroundColor.rawValue, value: NSColor.clear)) attach.addAttribute(.init(rawValue: TGEmojiHolderAttributeName), value: tag, range: NSMakeRange(0, emoji.length)) } return attach } } extension String { var isSavedMessagesText: Bool { let query = self.lowercased() if Telegram.strings().peerSavedMessages.lowercased().hasPrefix(query) { return true } if NSLocalizedString("Peer.SavedMessages", comment: "nil").hasPrefix(query.lowercased()) { return true } return false } } func joinChannel(context: AccountContext, peerId: PeerId) { _ = showModalProgress(signal: context.engine.peers.joinChannel(peerId: peerId, hash: nil) |> deliverOnMainQueue, for: context.window).start(error: { error in let text: String switch error { case .generic: text = strings().unknownError case .tooMuchJoined: showInactiveChannels(context: context, source: .join) return case .tooMuchUsers: text = strings().groupUsersTooMuchError case .inviteRequestSent: showModalText(for: context.window, text: strings().chatSendJoinRequestInfo, title: strings().chatSendJoinRequestTitle) return } alert(for: context.window, info: text) }, completed: { _ = showModalSuccess(for: context.window, icon: theme.icons.successModalProgress, delay: 1.5).start() }) }
gpl-2.0
8a3aeea8dc8240f51be25f521dd543d8
32.951464
646
0.585826
4.99972
false
false
false
false
CocoaFlow/MessageBroker
MessageBrokerTests/MessageBrokerSpec.swift
1
5733
// // MessageBrokerSpec.swift // MessageBroker // // Created by Paul Young on 03/09/2014. // Copyright (c) 2014 CocoaFlow. All rights reserved. // import Foundation import Quick import Nimble import MessageBroker import JSONLib class MessageBrokerSpec: QuickSpec { override func spec() { describe("Message broker") { describe("receiving a message") { context("without a payload") { it("should forward the message to the message receiver") { let messageBroker = MessageBroker() let brokerChannel = "channel" let brokerTopic = "topic" let brokerPayload: JSON? = nil var receiverChannel: String! var receiverTopic: String! var receiverPayload: JSON? let messageReceiver = FakeMessageReceiver(messageBroker) { (channel, topic, payload) in receiverChannel = channel receiverTopic = topic receiverPayload = payload } messageBroker.receive(brokerChannel, brokerTopic, brokerPayload) expect(receiverChannel).to(equal(brokerChannel)) expect(receiverTopic).to(equal(brokerTopic)) expect(receiverPayload).to(beNil()) } } context("with a payload") { it("should forward the message to the message receiver") { let messageBroker = MessageBroker() let brokerChannel = "channel" let brokerTopic = "topic" let brokerPayload = "{\"key\":\"value\"}" var receiverChannel: String! var receiverTopic: String! var receiverPayload: JSON? let messageReceiver = FakeMessageReceiver(messageBroker) { (channel, topic, payload) in receiverChannel = channel receiverTopic = topic receiverPayload = payload } messageBroker.receive(brokerChannel, brokerTopic, JSON.parse(brokerPayload).value!) expect(receiverChannel).to(equal(brokerChannel)) expect(receiverTopic).to(equal(brokerTopic)) expect(receiverPayload).to(equal(JSON.parse(brokerPayload).value)) } } } describe("sending a message") { context("without a payload") { it("should forward the message to the message sender") { let messageBroker = MessageBroker() let brokerChannel = "channel" let brokerTopic = "topic" let brokerPayload: JSON? = nil var senderChannel: String! var senderTopic: String! var senderPayload: JSON? let messageSender = FakeMessageSender(messageBroker) { (channel, topic, payload) in senderChannel = channel senderTopic = topic senderPayload = payload } messageBroker.send(brokerChannel, brokerTopic, brokerPayload) expect(senderChannel).to(equal(brokerChannel)) expect(senderTopic).to(equal(brokerTopic)) expect(senderPayload).to(beNil()) } } context("with a payload") { it("should forward the message to the message sender") { let messageBroker = MessageBroker() let brokerChannel = "channel" let brokerTopic = "topic" let brokerPayload = "{\"key\":\"value\"}" var senderChannel: String! var senderTopic: String! var senderPayload: JSON? let messageSender = FakeMessageSender(messageBroker) { (channel, topic, payload) in senderChannel = channel senderTopic = topic senderPayload = payload } messageBroker.send(brokerChannel, brokerTopic, JSON.parse(brokerPayload).value!) expect(senderChannel).to(equal(brokerChannel)) expect(senderTopic).to(equal(brokerTopic)) expect(senderPayload).to(equal(JSON.parse(brokerPayload).value)) } } } } } }
apache-2.0
4c17e1a6616729e58d29037fd4d52c34
41.154412
111
0.421071
7.042998
false
false
false
false
BBRick/wp
wp/Model/DealModel.swift
1
3644
// // DealModel.swift // wp // // Created by 木柳 on 2016/12/26. // Copyright © 2016年 com.yundian. All rights reserved. // import UIKit import RealmSwift class DealModel: BaseModel { enum ChartType: Int { case timeLine = 1 } var isFirstGetPrice = false var difftime = 0 private static var model: DealModel = DealModel() class func share() -> DealModel{ return model } //所有商品列表 dynamic var allProduct: [ProductModel] = [] //商品分类列表 dynamic var productKinds: [ProductModel] = [] //所选择的商品大类 dynamic var selectProduct: ProductModel? dynamic var selectProductIndex: Int = 0 //所选择的商品小类 var buyProduct: ProductModel? //买涨买跌 var dealUp: Bool = true var buyModel: PositionModel = PositionModel() //是否是持仓详情 var isDealDetail: Bool = false //数据库是否已经有数据 var haveDealModel: Bool = false //当前k线类型 var klineTye: KLineModel.KLineType = .miu //当前选择K线索引 var selectIndex: NSInteger!{ didSet{ switch selectIndex { case 0: klineTye = .miu break case 1: klineTye = .miu5 break case 2: klineTye = .miu15 break case 3: klineTye = .miu30 break case 4: klineTye = .miu60 break default: klineTye = .miu break } } } class func checkIfSuspended() -> Bool { let realm = try! Realm() let model = realm.objects(KChartModel.self).sorted(byProperty: "priceTime", ascending: false).first guard model != nil else { return true } return model!.systemTime - model!.priceTime > 60 } // 缓存建仓数据 class func cachePosition(position: PositionModel){ let realm = try! Realm() try! realm.write { realm.add(position, update: true) } DealModel.refreshDifftime() } class func getAllPositionModel() -> Results<PositionModel>{ let realm = try! Realm() return realm.objects(PositionModel.self).filter("closeTime > \(Int(NSDate().timeIntervalSince1970) + DealModel.share().difftime)").sorted(byProperty: "positionTime", ascending: false) } class func getHistoryPositionModel() -> Results<PositionModel>{ let realm = try! Realm() return realm.objects(PositionModel.self).filter("grossProfit > 0").sorted(byProperty: "positionTime", ascending: false) } class func cachePositionWithArray(positionArray:Array<PositionModel>) { let realm = try! Realm() try! realm.write { for positionModel in positionArray { realm.add(positionModel, update: true) } } } class func getAHistoryPositionModel() -> Results<PositionModel>{ let realm = try! Realm() return realm.objects(PositionModel.self).filter("closeTime < \(Int(NSDate().timeIntervalSince1970))").sorted(byProperty: "positionTime", ascending: false) } class func refreshDifftime() { let model = getAllPositionModel().first guard model != nil else {return} DealModel.share().difftime = model!.closeTime - model!.interval - Int(NSDate().timeIntervalSince1970) } }
apache-2.0
cca9da24f50eef322fe03583f530b57f
28.191667
191
0.568655
4.389724
false
false
false
false
novifinancial/serde-reflection
serde-generate/runtime/swift/Sources/Serde/Tuple5.swift
1
675
// Copyright (c) Facebook, Inc. and its affiliates. import Foundation // Swift tuples are not properly equatable or hashable. This ruins our data model so we must use homemade structs as in Java. public struct Tuple5<T0: Hashable, T1: Hashable, T2: Hashable, T3: Hashable, T4: Hashable>: Hashable { public var field0: T0 public var field1: T1 public var field2: T2 public var field3: T3 public var field4: T4 public init(_ field0: T0, _ field1: T1, _ field2: T2, _ field3: T3, _ field4: T4) { self.field0 = field0 self.field1 = field1 self.field2 = field2 self.field3 = field3 self.field4 = field4 } }
apache-2.0
11cb526b2d85222e33f2a65ac4b45360
31.142857
125
0.656296
3.292683
false
false
false
false
martinschilliger/SwissGrid
Pods/Alamofire/Source/Request.swift
2
24273
// // Request.swift // // Copyright (c) 2014-2017 Alamofire Software Foundation (http://alamofire.org/) // // 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 /// A type that can inspect and optionally adapt a `URLRequest` in some manner if necessary. public protocol RequestAdapter { /// Inspects and adapts the specified `URLRequest` in some manner if necessary and returns the result. /// /// - parameter urlRequest: The URL request to adapt. /// /// - throws: An `Error` if the adaptation encounters an error. /// /// - returns: The adapted `URLRequest`. func adapt(_ urlRequest: URLRequest) throws -> URLRequest } // MARK: - /// A closure executed when the `RequestRetrier` determines whether a `Request` should be retried or not. public typealias RequestRetryCompletion = (_ shouldRetry: Bool, _ timeDelay: TimeInterval) -> Void /// A type that determines whether a request should be retried after being executed by the specified session manager /// and encountering an error. public protocol RequestRetrier { /// Determines whether the `Request` should be retried by calling the `completion` closure. /// /// This operation is fully asynchronous. Any amount of time can be taken to determine whether the request needs /// to be retried. The one requirement is that the completion closure is called to ensure the request is properly /// cleaned up after. /// /// - parameter manager: The session manager the request was executed on. /// - parameter request: The request that failed due to the encountered error. /// - parameter error: The error encountered when executing the request. /// - parameter completion: The completion closure to be executed when retry decision has been determined. func should(_ manager: SessionManager, retry request: Request, with error: Error, completion: @escaping RequestRetryCompletion) } // MARK: - protocol TaskConvertible { func task(session: URLSession, adapter: RequestAdapter?, queue: DispatchQueue) throws -> URLSessionTask } /// A dictionary of headers to apply to a `URLRequest`. public typealias HTTPHeaders = [String: String] // MARK: - /// Responsible for sending a request and receiving the response and associated data from the server, as well as /// managing its underlying `URLSessionTask`. open class Request { // MARK: Helper Types /// A closure executed when monitoring upload or download progress of a request. public typealias ProgressHandler = (Progress) -> Void enum RequestTask { case data(TaskConvertible?, URLSessionTask?) case download(TaskConvertible?, URLSessionTask?) case upload(TaskConvertible?, URLSessionTask?) case stream(TaskConvertible?, URLSessionTask?) } // MARK: Properties /// The delegate for the underlying task. open internal(set) var delegate: TaskDelegate { get { taskDelegateLock.lock(); defer { taskDelegateLock.unlock() } return taskDelegate } set { taskDelegateLock.lock(); defer { taskDelegateLock.unlock() } taskDelegate = newValue } } /// The underlying task. open var task: URLSessionTask? { return delegate.task } /// The session belonging to the underlying task. open let session: URLSession /// The request sent or to be sent to the server. open var request: URLRequest? { return task?.originalRequest } /// The response received from the server, if any. open var response: HTTPURLResponse? { return task?.response as? HTTPURLResponse } /// The number of times the request has been retried. open internal(set) var retryCount: UInt = 0 let originalTask: TaskConvertible? var startTime: CFAbsoluteTime? var endTime: CFAbsoluteTime? var validations: [() -> Void] = [] private var taskDelegate: TaskDelegate private var taskDelegateLock = NSLock() // MARK: Lifecycle init(session: URLSession, requestTask: RequestTask, error: Error? = nil) { self.session = session switch requestTask { case let .data(originalTask, task): taskDelegate = DataTaskDelegate(task: task) self.originalTask = originalTask case let .download(originalTask, task): taskDelegate = DownloadTaskDelegate(task: task) self.originalTask = originalTask case let .upload(originalTask, task): taskDelegate = UploadTaskDelegate(task: task) self.originalTask = originalTask case let .stream(originalTask, task): taskDelegate = TaskDelegate(task: task) self.originalTask = originalTask } delegate.error = error delegate.queue.addOperation { self.endTime = CFAbsoluteTimeGetCurrent() } } // MARK: Authentication /// Associates an HTTP Basic credential with the request. /// /// - parameter user: The user. /// - parameter password: The password. /// - parameter persistence: The URL credential persistence. `.ForSession` by default. /// /// - returns: The request. @discardableResult open func authenticate( user: String, password: String, persistence: URLCredential.Persistence = .forSession) -> Self { let credential = URLCredential(user: user, password: password, persistence: persistence) return authenticate(usingCredential: credential) } /// Associates a specified credential with the request. /// /// - parameter credential: The credential. /// /// - returns: The request. @discardableResult open func authenticate(usingCredential credential: URLCredential) -> Self { delegate.credential = credential return self } /// Returns a base64 encoded basic authentication credential as an authorization header tuple. /// /// - parameter user: The user. /// - parameter password: The password. /// /// - returns: A tuple with Authorization header and credential value if encoding succeeds, `nil` otherwise. open static func authorizationHeader(user: String, password: String) -> (key: String, value: String)? { guard let data = "\(user):\(password)".data(using: .utf8) else { return nil } let credential = data.base64EncodedString(options: []) return (key: "Authorization", value: "Basic \(credential)") } // MARK: State /// Resumes the request. open func resume() { guard let task = task else { delegate.queue.isSuspended = false; return } if startTime == nil { startTime = CFAbsoluteTimeGetCurrent() } task.resume() NotificationCenter.default.post( name: Notification.Name.Task.DidResume, object: self, userInfo: [Notification.Key.Task: task] ) } /// Suspends the request. open func suspend() { guard let task = task else { return } task.suspend() NotificationCenter.default.post( name: Notification.Name.Task.DidSuspend, object: self, userInfo: [Notification.Key.Task: task] ) } /// Cancels the request. open func cancel() { guard let task = task else { return } task.cancel() NotificationCenter.default.post( name: Notification.Name.Task.DidCancel, object: self, userInfo: [Notification.Key.Task: task] ) } } // MARK: - CustomStringConvertible extension Request: CustomStringConvertible { /// The textual representation used when written to an output stream, which includes the HTTP method and URL, as /// well as the response status code if a response has been received. open var description: String { var components: [String] = [] if let HTTPMethod = request?.httpMethod { components.append(HTTPMethod) } if let urlString = request?.url?.absoluteString { components.append(urlString) } if let response = response { components.append("(\(response.statusCode))") } return components.joined(separator: " ") } } // MARK: - CustomDebugStringConvertible extension Request: CustomDebugStringConvertible { /// The textual representation used when written to an output stream, in the form of a cURL command. open var debugDescription: String { return cURLRepresentation() } func cURLRepresentation() -> String { var components = ["$ curl -v"] guard let request = self.request, let url = request.url, let host = url.host else { return "$ curl command could not be created" } if let httpMethod = request.httpMethod, httpMethod != "GET" { components.append("-X \(httpMethod)") } if let credentialStorage = self.session.configuration.urlCredentialStorage { let protectionSpace = URLProtectionSpace( host: host, port: url.port ?? 0, protocol: url.scheme, realm: host, authenticationMethod: NSURLAuthenticationMethodHTTPBasic ) if let credentials = credentialStorage.credentials(for: protectionSpace)?.values { for credential in credentials { guard let user = credential.user, let password = credential.password else { continue } components.append("-u \(user):\(password)") } } else { if let credential = delegate.credential, let user = credential.user, let password = credential.password { components.append("-u \(user):\(password)") } } } if session.configuration.httpShouldSetCookies { if let cookieStorage = session.configuration.httpCookieStorage, let cookies = cookieStorage.cookies(for: url), !cookies.isEmpty { let string = cookies.reduce("") { $0 + "\($1.name)=\($1.value);" } #if swift(>=3.2) components.append("-b \"\(string[..<string.index(before: string.endIndex)])\"") #else components.append("-b \"\(string.substring(to: string.characters.index(before: string.endIndex)))\"") #endif } } var headers: [AnyHashable: Any] = [:] if let additionalHeaders = session.configuration.httpAdditionalHeaders { for (field, value) in additionalHeaders where field != AnyHashable("Cookie") { headers[field] = value } } if let headerFields = request.allHTTPHeaderFields { for (field, value) in headerFields where field != "Cookie" { headers[field] = value } } for (field, value) in headers { components.append("-H \"\(field): \(value)\"") } if let httpBodyData = request.httpBody, let httpBody = String(data: httpBodyData, encoding: .utf8) { var escapedBody = httpBody.replacingOccurrences(of: "\\\"", with: "\\\\\"") escapedBody = escapedBody.replacingOccurrences(of: "\"", with: "\\\"") components.append("-d \"\(escapedBody)\"") } components.append("\"\(url.absoluteString)\"") return components.joined(separator: " \\\n\t") } } // MARK: - /// Specific type of `Request` that manages an underlying `URLSessionDataTask`. open class DataRequest: Request { // MARK: Helper Types struct Requestable: TaskConvertible { let urlRequest: URLRequest func task(session: URLSession, adapter: RequestAdapter?, queue: DispatchQueue) throws -> URLSessionTask { do { let urlRequest = try self.urlRequest.adapt(using: adapter) return queue.sync { session.dataTask(with: urlRequest) } } catch { throw AdaptError(error: error) } } } // MARK: Properties /// The request sent or to be sent to the server. open override var request: URLRequest? { if let request = super.request { return request } if let requestable = originalTask as? Requestable { return requestable.urlRequest } return nil } /// The progress of fetching the response data from the server for the request. open var progress: Progress { return dataDelegate.progress } var dataDelegate: DataTaskDelegate { return delegate as! DataTaskDelegate } // MARK: Stream /// Sets a closure to be called periodically during the lifecycle of the request as data is read from the server. /// /// This closure returns the bytes most recently received from the server, not including data from previous calls. /// If this closure is set, data will only be available within this closure, and will not be saved elsewhere. It is /// also important to note that the server data in any `Response` object will be `nil`. /// /// - parameter closure: The code to be executed periodically during the lifecycle of the request. /// /// - returns: The request. @discardableResult open func stream(closure: ((Data) -> Void)? = nil) -> Self { dataDelegate.dataStream = closure return self } // MARK: Progress /// Sets a closure to be called periodically during the lifecycle of the `Request` as data is read from the server. /// /// - parameter queue: The dispatch queue to execute the closure on. /// - parameter closure: The code to be executed periodically as data is read from the server. /// /// - returns: The request. @discardableResult open func downloadProgress(queue: DispatchQueue = DispatchQueue.main, closure: @escaping ProgressHandler) -> Self { dataDelegate.progressHandler = (closure, queue) return self } } // MARK: - /// Specific type of `Request` that manages an underlying `URLSessionDownloadTask`. open class DownloadRequest: Request { // MARK: Helper Types /// A collection of options to be executed prior to moving a downloaded file from the temporary URL to the /// destination URL. public struct DownloadOptions: OptionSet { /// Returns the raw bitmask value of the option and satisfies the `RawRepresentable` protocol. public let rawValue: UInt /// A `DownloadOptions` flag that creates intermediate directories for the destination URL if specified. public static let createIntermediateDirectories = DownloadOptions(rawValue: 1 << 0) /// A `DownloadOptions` flag that removes a previous file from the destination URL if specified. public static let removePreviousFile = DownloadOptions(rawValue: 1 << 1) /// Creates a `DownloadFileDestinationOptions` instance with the specified raw value. /// /// - parameter rawValue: The raw bitmask value for the option. /// /// - returns: A new log level instance. public init(rawValue: UInt) { self.rawValue = rawValue } } /// A closure executed once a download request has successfully completed in order to determine where to move the /// temporary file written to during the download process. The closure takes two arguments: the temporary file URL /// and the URL response, and returns a two arguments: the file URL where the temporary file should be moved and /// the options defining how the file should be moved. public typealias DownloadFileDestination = ( _ temporaryURL: URL, _ response: HTTPURLResponse) -> (destinationURL: URL, options: DownloadOptions) enum Downloadable: TaskConvertible { case request(URLRequest) case resumeData(Data) func task(session: URLSession, adapter: RequestAdapter?, queue: DispatchQueue) throws -> URLSessionTask { do { let task: URLSessionTask switch self { case let .request(urlRequest): let urlRequest = try urlRequest.adapt(using: adapter) task = queue.sync { session.downloadTask(with: urlRequest) } case let .resumeData(resumeData): task = queue.sync { session.downloadTask(withResumeData: resumeData) } } return task } catch { throw AdaptError(error: error) } } } // MARK: Properties /// The request sent or to be sent to the server. open override var request: URLRequest? { if let request = super.request { return request } if let downloadable = originalTask as? Downloadable, case let .request(urlRequest) = downloadable { return urlRequest } return nil } /// The resume data of the underlying download task if available after a failure. open var resumeData: Data? { return downloadDelegate.resumeData } /// The progress of downloading the response data from the server for the request. open var progress: Progress { return downloadDelegate.progress } var downloadDelegate: DownloadTaskDelegate { return delegate as! DownloadTaskDelegate } // MARK: State /// Cancels the request. open override func cancel() { downloadDelegate.downloadTask.cancel { self.downloadDelegate.resumeData = $0 } NotificationCenter.default.post( name: Notification.Name.Task.DidCancel, object: self, userInfo: [Notification.Key.Task: task as Any] ) } // MARK: Progress /// Sets a closure to be called periodically during the lifecycle of the `Request` as data is read from the server. /// /// - parameter queue: The dispatch queue to execute the closure on. /// - parameter closure: The code to be executed periodically as data is read from the server. /// /// - returns: The request. @discardableResult open func downloadProgress(queue: DispatchQueue = DispatchQueue.main, closure: @escaping ProgressHandler) -> Self { downloadDelegate.progressHandler = (closure, queue) return self } // MARK: Destination /// Creates a download file destination closure which uses the default file manager to move the temporary file to a /// file URL in the first available directory with the specified search path directory and search path domain mask. /// /// - parameter directory: The search path directory. `.DocumentDirectory` by default. /// - parameter domain: The search path domain mask. `.UserDomainMask` by default. /// /// - returns: A download file destination closure. open class func suggestedDownloadDestination( for directory: FileManager.SearchPathDirectory = .documentDirectory, in domain: FileManager.SearchPathDomainMask = .userDomainMask) -> DownloadFileDestination { return { temporaryURL, response in let directoryURLs = FileManager.default.urls(for: directory, in: domain) if !directoryURLs.isEmpty { return (directoryURLs[0].appendingPathComponent(response.suggestedFilename!), []) } return (temporaryURL, []) } } } // MARK: - /// Specific type of `Request` that manages an underlying `URLSessionUploadTask`. open class UploadRequest: DataRequest { // MARK: Helper Types enum Uploadable: TaskConvertible { case data(Data, URLRequest) case file(URL, URLRequest) case stream(InputStream, URLRequest) func task(session: URLSession, adapter: RequestAdapter?, queue: DispatchQueue) throws -> URLSessionTask { do { let task: URLSessionTask switch self { case let .data(data, urlRequest): let urlRequest = try urlRequest.adapt(using: adapter) task = queue.sync { session.uploadTask(with: urlRequest, from: data) } case let .file(url, urlRequest): let urlRequest = try urlRequest.adapt(using: adapter) task = queue.sync { session.uploadTask(with: urlRequest, fromFile: url) } case let .stream(_, urlRequest): let urlRequest = try urlRequest.adapt(using: adapter) task = queue.sync { session.uploadTask(withStreamedRequest: urlRequest) } } return task } catch { throw AdaptError(error: error) } } } // MARK: Properties /// The request sent or to be sent to the server. open override var request: URLRequest? { if let request = super.request { return request } guard let uploadable = originalTask as? Uploadable else { return nil } switch uploadable { case let .data(_, urlRequest), let .file(_, urlRequest), let .stream(_, urlRequest): return urlRequest } } /// The progress of uploading the payload to the server for the upload request. open var uploadProgress: Progress { return uploadDelegate.uploadProgress } var uploadDelegate: UploadTaskDelegate { return delegate as! UploadTaskDelegate } // MARK: Upload Progress /// Sets a closure to be called periodically during the lifecycle of the `UploadRequest` as data is sent to /// the server. /// /// After the data is sent to the server, the `progress(queue:closure:)` APIs can be used to monitor the progress /// of data being read from the server. /// /// - parameter queue: The dispatch queue to execute the closure on. /// - parameter closure: The code to be executed periodically as data is sent to the server. /// /// - returns: The request. @discardableResult open func uploadProgress(queue: DispatchQueue = DispatchQueue.main, closure: @escaping ProgressHandler) -> Self { uploadDelegate.uploadProgressHandler = (closure, queue) return self } } // MARK: - #if !os(watchOS) /// Specific type of `Request` that manages an underlying `URLSessionStreamTask`. @available(iOS 9.0, macOS 10.11, tvOS 9.0, *) open class StreamRequest: Request { enum Streamable: TaskConvertible { case stream(hostName: String, port: Int) case netService(NetService) func task(session: URLSession, adapter _: RequestAdapter?, queue: DispatchQueue) throws -> URLSessionTask { let task: URLSessionTask switch self { case let .stream(hostName, port): task = queue.sync { session.streamTask(withHostName: hostName, port: port) } case let .netService(netService): task = queue.sync { session.streamTask(with: netService) } } return task } } } #endif
mit
722e0bcf4a32492ae8587820dfe038e8
36.343077
131
0.640176
5.152409
false
false
false
false
STShenZhaoliang/iOS-GuidesAndSampleCode
精通Swift设计模式/Chapter 07/SportsStore/SportsStore/Product.swift
2
1271
import Foundation class Product : NSObject, NSCopying { fileprivate(set) var name:String; fileprivate(set) var productDescription:String; fileprivate(set) var category:String; fileprivate var stockLevelBackingValue:Int = 0; fileprivate var priceBackingValue:Double = 0; init(name:String, description:String, category:String, price:Double, stockLevel:Int) { self.name = name; self.productDescription = description; self.category = category; super.init(); self.price = price; self.stockLevel = stockLevel; } var stockLevel:Int { get { return stockLevelBackingValue;} set { stockLevelBackingValue = max(0, newValue);} } fileprivate(set) var price:Double { get { return priceBackingValue;} set { priceBackingValue = max(1, newValue);} } var stockValue:Double { get { return price * Double(stockLevel); } } func copy(with zone: NSZone?) -> Any { return Product(name: self.name, description: self.description, category: self.category, price: self.price, stockLevel: self.stockLevel); } }
mit
23ed622baeca43515588723f6cd1e613
27.886364
72
0.594807
4.690037
false
false
false
false
cdmx/MiniMancera
miniMancera/View/Option/TamalesOaxaquenos/Node/VOptionTamalesOaxaquenosFloorGroundGullyStart.swift
1
2270
import UIKit class VOptionTamalesOaxaquenosFloorGroundGullyStart:VOptionTamalesOaxaquenosFloor { private weak var viewGround:VOptionTamalesOaxaquenosFloorGround! private weak var viewGully:VOptionTamalesOaxaquenosFloorGullyStart! private let positionX:CGFloat private let height_2:CGFloat private let groundPositionY:CGFloat private let gullyPositionY:CGFloat private let kVerticalAlign:CGFloat = 150 private let kGroundXPosition:CGFloat = -10 init( controller:ControllerGame<MOptionTamalesOaxaquenos>, model:MOptionTamalesOaxaquenosAreaFloorItemGroundGullyStart) { positionX = model.positionX let viewGround:VOptionTamalesOaxaquenosFloorGround = VOptionTamalesOaxaquenosFloorGround( controller:controller, model:model) self.viewGround = viewGround let viewGully:VOptionTamalesOaxaquenosFloorGullyStart = VOptionTamalesOaxaquenosFloorGullyStart( controller:controller) self.viewGully = viewGully let textureGround:MGameTexture = model.textureGround let width:CGFloat = textureGround.width let groundHeight:CGFloat = textureGround.height let gullyHeight:CGFloat = viewGully.size.height let gullyHeight_2:CGFloat = gullyHeight / 2.0 let height:CGFloat = groundHeight + gullyHeight height_2 = height / 2.0 groundPositionY = textureGround.height_2 - height_2 gullyPositionY = groundPositionY + textureGround.height_2 + gullyHeight_2 let size:CGSize = CGSize(width:width, height:height) super.init(controller:controller, size:size) addChild(viewGround) addChild(viewGully) } required init?(coder:NSCoder) { return nil } override func positionStart() { let sceneHeight:CGFloat = MGame.sceneSize.height let sceneHeight_2:CGFloat = sceneHeight / 2.0 let positionY:CGFloat = sceneHeight_2 - (kVerticalAlign + height_2) position = CGPoint(x:positionX, y:positionY) viewGround.position = CGPoint(x:kGroundXPosition, y:groundPositionY) viewGully.position = CGPoint(x:0, y:gullyPositionY) } }
mit
d709fb606ef545de178117744e1ea62e
36.213115
104
0.696035
4.521912
false
false
false
false
linhaosunny/smallGifts
小礼品/小礼品/Classes/Module/Classify/Controllers/AllClassifyViewController.swift
1
2906
// // AllClassifyViewController.swift // 小礼品 // // Created by 李莎鑫 on 2017/4/23. // Copyright © 2017年 李莎鑫. All rights reserved. // import UIKit import SnapKit fileprivate let cellColumns = 1 fileprivate let cellScale:CGFloat = 340.0 / 90.0 class AllClassifyViewController: UIViewController { //MARK: 属性 fileprivate let allClassifyIdentifier = "allClassifyCell" //MARK: 懒加载 lazy var colleciontView:UICollectionView = { () -> UICollectionView in let view = UICollectionView(frame: CGRect.zero, collectionViewLayout: AllClassifyViewFlowLayout()) view.delegate = self view.dataSource = self view.backgroundColor = UIColor.white view.showsVerticalScrollIndicator = false view.register(StrategyColumnSubCell.self, forCellWithReuseIdentifier: self.allClassifyIdentifier) return view }() //MARK: 系统方法 override func viewDidLoad() { super.viewDidLoad() setupAllClassifyView() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() setupAllClassifyViewSubView() } //MARK: 私有方法 private func setupAllClassifyView() { title = "全部分类" view.addSubview(colleciontView) } private func setupAllClassifyViewSubView() { colleciontView.snp.makeConstraints { (make) in make.edges.equalToSuperview().inset(UIEdgeInsets.zero) } } } //MARK: 代理方法 -> extension AllClassifyViewController:UICollectionViewDelegate,UICollectionViewDataSource{ func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return 15 } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: allClassifyIdentifier, for: indexPath) as! StrategyColumnSubCell cell.viewModel = StrategyColumnSubCellViewModel(withModel: StrategyColumnSubCellDataModel()) return cell } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { } } class AllClassifyViewFlowLayout: UICollectionViewFlowLayout { override func prepare() { minimumLineSpacing = margin minimumInteritemSpacing = margin * 0.5 let width = collectionView!.bounds.width - (CGFloat(cellColumns + 1) * cellMargin) let height = width / cellScale itemSize = CGSize(width: width, height: height) sectionInset = UIEdgeInsets(top: margin, left: margin, bottom: margin, right: margin) scrollDirection = .vertical } }
mit
37af2863a58d2c2e393b61d4c3525a6c
31.306818
139
0.69891
5.076786
false
false
false
false
atrick/swift
stdlib/public/core/StringUTF16View.swift
1
28753
//===--- StringUTF16.swift ------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // FIXME(ABI)#71 : The UTF-16 string view should have a custom iterator type to // allow performance optimizations of linear traversals. extension String { /// A view of a string's contents as a collection of UTF-16 code units. /// /// You can access a string's view of UTF-16 code units by using its `utf16` /// property. A string's UTF-16 view encodes the string's Unicode scalar /// values as 16-bit integers. /// /// let flowers = "Flowers 💐" /// for v in flowers.utf16 { /// print(v) /// } /// // 70 /// // 108 /// // 111 /// // 119 /// // 101 /// // 114 /// // 115 /// // 32 /// // 55357 /// // 56464 /// /// Unicode scalar values that make up a string's contents can be up to 21 /// bits long. The longer scalar values may need two `UInt16` values for /// storage. Those "pairs" of code units are called *surrogate pairs*. /// /// let flowermoji = "💐" /// for v in flowermoji.unicodeScalars { /// print(v, v.value) /// } /// // 💐 128144 /// /// for v in flowermoji.utf16 { /// print(v) /// } /// // 55357 /// // 56464 /// /// To convert a `String.UTF16View` instance back into a string, use the /// `String` type's `init(_:)` initializer. /// /// let favemoji = "My favorite emoji is 🎉" /// if let i = favemoji.utf16.firstIndex(where: { $0 >= 128 }) { /// let asciiPrefix = String(favemoji.utf16[..<i])! /// print(asciiPrefix) /// } /// // Prints "My favorite emoji is " /// /// UTF16View Elements Match NSString Characters /// ============================================ /// /// The UTF-16 code units of a string's `utf16` view match the elements /// accessed through indexed `NSString` APIs. /// /// print(flowers.utf16.count) /// // Prints "10" /// /// let nsflowers = flowers as NSString /// print(nsflowers.length) /// // Prints "10" /// /// Unlike `NSString`, however, `String.UTF16View` does not use integer /// indices. If you need to access a specific position in a UTF-16 view, use /// Swift's index manipulation methods. The following example accesses the /// fourth code unit in both the `flowers` and `nsflowers` strings: /// /// print(nsflowers.character(at: 3)) /// // Prints "119" /// /// let i = flowers.utf16.index(flowers.utf16.startIndex, offsetBy: 3) /// print(flowers.utf16[i]) /// // Prints "119" /// /// Although the Swift overlay updates many Objective-C methods to return /// native Swift indices and index ranges, some still return instances of /// `NSRange`. To convert an `NSRange` instance to a range of /// `String.Index`, use the `Range(_:in:)` initializer, which takes an /// `NSRange` and a string as arguments. /// /// let snowy = "❄️ Let it snow! ☃️" /// let nsrange = NSRange(location: 3, length: 12) /// if let range = Range(nsrange, in: snowy) { /// print(snowy[range]) /// } /// // Prints "Let it snow!" @frozen public struct UTF16View: Sendable { @usableFromInline internal var _guts: _StringGuts @inlinable internal init(_ guts: _StringGuts) { self._guts = guts _invariantCheck() } } } extension String.UTF16View { #if !INTERNAL_CHECKS_ENABLED @inlinable @inline(__always) internal func _invariantCheck() {} #else @usableFromInline @inline(never) @_effects(releasenone) internal func _invariantCheck() { _internalInvariant( startIndex.transcodedOffset == 0 && endIndex.transcodedOffset == 0) } #endif // INTERNAL_CHECKS_ENABLED } extension String.UTF16View: BidirectionalCollection { public typealias Index = String.Index /// The position of the first code unit if the `String` is /// nonempty; identical to `endIndex` otherwise. @inlinable @inline(__always) public var startIndex: Index { return _guts.startIndex } /// The "past the end" position---that is, the position one greater than /// the last valid subscript argument. /// /// In an empty UTF-16 view, `endIndex` is equal to `startIndex`. @inlinable @inline(__always) public var endIndex: Index { return _guts.endIndex } @inlinable @inline(__always) public func index(after idx: Index) -> Index { var idx = _guts.ensureMatchingEncoding(idx) _precondition(idx._encodedOffset < _guts.count, "String index is out of bounds") if _slowPath(_guts.isForeign) { return _foreignIndex(after: idx) } if _guts.isASCII { return idx.nextEncoded._scalarAligned._encodingIndependent } // For a BMP scalar (1-3 UTF-8 code units), advance past it. For a non-BMP // scalar, use a transcoded offset first. // TODO: If transcoded is 1, can we just skip ahead 4? idx = _utf16AlignNativeIndex(idx) let len = _guts.fastUTF8ScalarLength(startingAt: idx._encodedOffset) if len == 4 && idx.transcodedOffset == 0 { return idx.nextTranscoded._knownUTF8 } return idx .strippingTranscoding .encoded(offsetBy: len) ._scalarAligned ._knownUTF8 } @inlinable @inline(__always) public func index(before idx: Index) -> Index { var idx = _guts.ensureMatchingEncoding(idx) _precondition(!idx.isZeroPosition && idx <= endIndex, "String index is out of bounds") if _slowPath(_guts.isForeign) { return _foreignIndex(before: idx) } if _guts.isASCII { return idx.priorEncoded._scalarAligned._encodingIndependent } if idx.transcodedOffset != 0 { _internalInvariant(idx.transcodedOffset == 1) return idx.strippingTranscoding._scalarAligned._knownUTF8 } idx = _utf16AlignNativeIndex(idx) let len = _guts.fastUTF8ScalarLength(endingAt: idx._encodedOffset) if len == 4 { // 2 UTF-16 code units comprise this scalar; advance to the beginning and // start mid-scalar transcoding return idx.encoded(offsetBy: -len).nextTranscoded._knownUTF8 } // Single UTF-16 code unit _internalInvariant((1...3) ~= len) return idx.encoded(offsetBy: -len)._scalarAligned._knownUTF8 } public func index(_ i: Index, offsetBy n: Int) -> Index { let i = _guts.ensureMatchingEncoding(i) _precondition(i <= endIndex, "String index is out of bounds") if _slowPath(_guts.isForeign) { return _foreignIndex(i, offsetBy: n) } let lowerOffset = _nativeGetOffset(for: i) let result = _nativeGetIndex(for: lowerOffset + n) return result } public func index( _ i: Index, offsetBy n: Int, limitedBy limit: Index ) -> Index? { let limit = _guts.ensureMatchingEncoding(limit) guard _fastPath(limit <= endIndex) else { return index(i, offsetBy: n) } let i = _guts.ensureMatchingEncoding(i) _precondition(i <= endIndex, "String index is out of bounds") if _slowPath(_guts.isForeign) { return _foreignIndex(i, offsetBy: n, limitedBy: limit) } let iOffset = _nativeGetOffset(for: i) let limitOffset = _nativeGetOffset(for: limit) // If distance < 0, limit has no effect if it is greater than i. if _slowPath(n < 0 && limit <= i && limitOffset > iOffset + n) { return nil } // If distance > 0, limit has no effect if it is less than i. if _slowPath(n >= 0 && limit >= i && limitOffset < iOffset + n) { return nil } let result = _nativeGetIndex(for: iOffset + n) return result } public func distance(from start: Index, to end: Index) -> Int { let start = _guts.ensureMatchingEncoding(start) let end = _guts.ensureMatchingEncoding(end) _precondition(start._encodedOffset <= _guts.count, "String index is out of bounds") _precondition(end._encodedOffset <= _guts.count, "String index is out of bounds") if _slowPath(_guts.isForeign) { return _foreignDistance(from: start, to: end) } let lower = _nativeGetOffset(for: start) let upper = _nativeGetOffset(for: end) return upper &- lower } @inlinable public var count: Int { if _slowPath(_guts.isForeign) { return _foreignCount() } return _nativeGetOffset(for: endIndex) } /// Accesses the code unit at the given position. /// /// The following example uses the subscript to print the value of a /// string's first UTF-16 code unit. /// /// let greeting = "Hello, friend!" /// let i = greeting.utf16.startIndex /// print("First character's UTF-16 code unit: \(greeting.utf16[i])") /// // Prints "First character's UTF-16 code unit: 72" /// /// - Parameter position: A valid index of the view. `position` must be /// less than the view's end index. @inlinable @inline(__always) public subscript(idx: Index) -> UTF16.CodeUnit { let idx = _guts.ensureMatchingEncoding(idx) _precondition(idx._encodedOffset < _guts.count, "String index is out of bounds") return self[_unchecked: idx] } @_alwaysEmitIntoClient @inline(__always) internal subscript(_unchecked idx: Index) -> UTF16.CodeUnit { if _fastPath(_guts.isFastUTF8) { let scalar = _guts.fastUTF8Scalar( startingAt: _guts.scalarAlign(idx)._encodedOffset) return scalar.utf16[idx.transcodedOffset] } return _foreignSubscript(position: idx) } } extension String.UTF16View { @frozen public struct Iterator: IteratorProtocol, Sendable { @usableFromInline internal var _guts: _StringGuts @usableFromInline internal var _position: Int = 0 @usableFromInline internal var _end: Int // If non-nil, return this value for `next()` (and set it to nil). // // This is set when visiting a non-BMP scalar: the leading surrogate is // returned, this field is set with the value of the trailing surrogate, and // `_position` is advanced to the start of the next scalar. @usableFromInline internal var _nextIsTrailingSurrogate: UInt16? = nil @inlinable internal init(_ guts: _StringGuts) { self._end = guts.count self._guts = guts } @inlinable public mutating func next() -> UInt16? { if _slowPath(_nextIsTrailingSurrogate != nil) { let trailing = self._nextIsTrailingSurrogate._unsafelyUnwrappedUnchecked self._nextIsTrailingSurrogate = nil return trailing } guard _fastPath(_position < _end) else { return nil } let (scalar, len) = _guts.errorCorrectedScalar(startingAt: _position) _position &+= len if _slowPath(scalar.value > UInt16.max) { self._nextIsTrailingSurrogate = scalar.utf16[1] return scalar.utf16[0] } return UInt16(truncatingIfNeeded: scalar.value) } } @inlinable public __consuming func makeIterator() -> Iterator { return Iterator(_guts) } } extension String.UTF16View: CustomStringConvertible { @inlinable @inline(__always) public var description: String { return String(_guts) } } extension String.UTF16View: CustomDebugStringConvertible { public var debugDescription: String { return "StringUTF16(\(self.description.debugDescription))" } } extension String { /// A UTF-16 encoding of `self`. @inlinable public var utf16: UTF16View { @inline(__always) get { return UTF16View(_guts) } @inline(__always) set { self = String(newValue._guts) } } /// Creates a string corresponding to the given sequence of UTF-16 code units. @inlinable @inline(__always) @available(swift, introduced: 4.0) public init(_ utf16: UTF16View) { self.init(utf16._guts) } } // Index conversions extension String.UTF16View.Index { /// Creates an index in the given UTF-16 view that corresponds exactly to the /// specified string position. /// /// If the index passed as `sourcePosition` represents either the start of a /// Unicode scalar value or the position of a UTF-16 trailing surrogate, /// then the initializer succeeds. If `sourcePosition` does not have an /// exact corresponding position in `target`, then the result is `nil`. For /// example, an attempt to convert the position of a UTF-8 continuation byte /// results in `nil`. /// /// The following example finds the position of a space in a string and then /// converts that position to an index in the string's `utf16` view. /// /// let cafe = "Café 🍵" /// /// let stringIndex = cafe.firstIndex(of: "é")! /// let utf16Index = String.Index(stringIndex, within: cafe.utf16)! /// /// print(String(cafe.utf16[...utf16Index])!) /// // Prints "Café" /// /// - Parameters: /// - sourcePosition: A position in at least one of the views of the string /// shared by `target`. /// - target: The `UTF16View` in which to find the new position. public init?( _ idx: String.Index, within target: String.UTF16View ) { // As a special exception, we allow `idx` to be an UTF-16 index when `self` // is a UTF-8 string, to preserve compatibility with (broken) code that // keeps using indices from a bridged string after converting the string to // a native representation. Such indices are invalid, but returning nil here // can break code that appeared to work fine for ASCII strings in Swift // releases prior to 5.7. guard let idx = target._guts.ensureMatchingEncodingNoTrap(idx), idx._encodedOffset <= target._guts.count else { return nil } if _slowPath(target._guts.isForeign) { guard idx._foreignIsWithin(target) else { return nil } } else { // fast UTF-8 guard ( // If the transcoded offset is non-zero, then `idx` addresses a trailing // surrogate, so its encoding offset is on a scalar boundary, and it's a // valid UTF-16 index. idx.transcodedOffset != 0 /// Otherwise we need to reject indices that aren't scalar aligned. || target._guts.isOnUnicodeScalarBoundary(idx) ) else { return nil } } self = idx } /// Returns the position in the given view of Unicode scalars that /// corresponds exactly to this index. /// /// This index must be a valid index of `String(unicodeScalars).utf16`. /// /// This example first finds the position of a space (UTF-16 code point `32`) /// in a string's `utf16` view and then uses this method to find the same /// position in the string's `unicodeScalars` view. /// /// let cafe = "Café 🍵" /// let i = cafe.utf16.firstIndex(of: 32)! /// let j = i.samePosition(in: cafe.unicodeScalars)! /// print(String(cafe.unicodeScalars[..<j])) /// // Prints "Café" /// /// - Parameter unicodeScalars: The view to use for the index conversion. /// This index must be a valid index of at least one view of the string /// shared by `unicodeScalars`. /// - Returns: The position in `unicodeScalars` that corresponds exactly to /// this index. If this index does not have an exact corresponding /// position in `unicodeScalars`, this method returns `nil`. For example, /// an attempt to convert the position of a UTF-16 trailing surrogate /// returns `nil`. public func samePosition( in unicodeScalars: String.UnicodeScalarView ) -> String.UnicodeScalarIndex? { return String.UnicodeScalarIndex(self, within: unicodeScalars) } } #if SWIFT_ENABLE_REFLECTION // Reflection extension String.UTF16View: CustomReflectable { /// Returns a mirror that reflects the UTF-16 view of a string. public var customMirror: Mirror { return Mirror(self, unlabeledChildren: self) } } #endif // Slicing extension String.UTF16View { public typealias SubSequence = Substring.UTF16View public subscript(r: Range<Index>) -> Substring.UTF16View { let r = _guts.validateSubscalarRange(r) return Substring.UTF16View(self, _bounds: r) } } // Foreign string support extension String.UTF16View { @usableFromInline @inline(never) @_effects(releasenone) internal func _foreignIndex(after i: Index) -> Index { _internalInvariant(_guts.isForeign) return i.strippingTranscoding.nextEncoded._knownUTF16 } @usableFromInline @inline(never) @_effects(releasenone) internal func _foreignIndex(before i: Index) -> Index { _internalInvariant(_guts.isForeign) return i.strippingTranscoding.priorEncoded._knownUTF16 } @usableFromInline @inline(never) @_effects(releasenone) internal func _foreignSubscript(position i: Index) -> UTF16.CodeUnit { _internalInvariant(_guts.isForeign) return _guts.foreignErrorCorrectedUTF16CodeUnit(at: i.strippingTranscoding) } @usableFromInline @inline(never) @_effects(releasenone) internal func _foreignDistance(from start: Index, to end: Index) -> Int { _internalInvariant(_guts.isForeign) // Ignore transcoded offsets, i.e. scalar align if-and-only-if from a // transcoded view return end._encodedOffset - start._encodedOffset } @usableFromInline @inline(never) @_effects(releasenone) internal func _foreignIndex( _ i: Index, offsetBy n: Int, limitedBy limit: Index ) -> Index? { _internalInvariant(_guts.isForeign) let l = limit._encodedOffset - i._encodedOffset if n > 0 ? l >= 0 && l < n : l <= 0 && n < l { return nil } let offset = i._encodedOffset &+ n _precondition(offset >= 0 && offset <= _guts.count, "String index is out of bounds") return Index(_encodedOffset: offset)._knownUTF16 } @usableFromInline @inline(never) @_effects(releasenone) internal func _foreignIndex(_ i: Index, offsetBy n: Int) -> Index { _internalInvariant(_guts.isForeign) let offset = i._encodedOffset &+ n _precondition(offset >= 0 && offset <= _guts.count, "String index is out of bounds") return Index(_encodedOffset: offset)._knownUTF16 } @usableFromInline @inline(never) @_effects(releasenone) internal func _foreignCount() -> Int { _internalInvariant(_guts.isForeign) return endIndex._encodedOffset - startIndex._encodedOffset } // Align a native UTF-8 index to a valid UTF-16 position. If there is a // transcoded offset already, this is already a valid UTF-16 position // (referring to the second surrogate) and returns `idx`. Otherwise, this will // scalar-align the index. This is needed because we may be passed a // non-scalar-aligned index from the UTF8View. @_alwaysEmitIntoClient // Swift 5.1 @inline(__always) internal func _utf16AlignNativeIndex(_ idx: String.Index) -> String.Index { _internalInvariant(!_guts.isForeign) guard idx.transcodedOffset == 0 else { return idx } return _guts.scalarAlign(idx) } } extension String.Index { @usableFromInline @inline(never) // opaque slow-path @_effects(releasenone) internal func _foreignIsWithin(_ target: String.UTF16View) -> Bool { _internalInvariant(target._guts.isForeign) // If we're transcoding, we're a UTF-8 view index, not UTF-16. return self.transcodedOffset == 0 } } // Breadcrumb-aware acceleration extension _StringGuts { @inline(__always) fileprivate func _useBreadcrumbs(forEncodedOffset offset: Int) -> Bool { return hasBreadcrumbs && offset >= _StringBreadcrumbs.breadcrumbStride } } extension String.UTF16View { #if SWIFT_STDLIB_ENABLE_VECTOR_TYPES @inline(__always) internal func _utf16Length<U: SIMD, S: SIMD>( readPtr: inout UnsafeRawPointer, endPtr: UnsafeRawPointer, unsignedSIMDType: U.Type, signedSIMDType: S.Type ) -> Int where U.Scalar == UInt8, S.Scalar == Int8 { var utf16Count = 0 while readPtr + MemoryLayout<U>.stride < endPtr { //Find the number of continuations (0b10xxxxxx) let sValue = Builtin.loadRaw(readPtr._rawValue) as S let continuations = S.zero.replacing(with: S.one, where: sValue .< -65 + 1) //Find the number of 4 byte code points (0b11110xxx) let uValue = Builtin.loadRaw(readPtr._rawValue) as U let fourBytes = S.zero.replacing( with: S.one, where: unsafeBitCast( uValue .>= 0b11110000, to: SIMDMask<S.MaskStorage>.self ) ) utf16Count &+= U.scalarCount + Int((fourBytes &- continuations).wrappedSum()) readPtr += MemoryLayout<U>.stride } return utf16Count } #endif @inline(__always) internal func _utf16Distance(from start: Index, to end: Index) -> Int { _internalInvariant(end.transcodedOffset == 0 || end.transcodedOffset == 1) return (end.transcodedOffset - start.transcodedOffset) + _guts.withFastUTF8( range: start._encodedOffset ..< end._encodedOffset ) { utf8 in let rawBuffer = UnsafeRawBufferPointer(utf8) guard rawBuffer.count > 0 else { return 0 } var utf16Count = 0 var readPtr = rawBuffer.baseAddress.unsafelyUnwrapped let initialReadPtr = readPtr let endPtr = readPtr + rawBuffer.count //eat leading continuations while readPtr < endPtr { let byte = readPtr.load(as: UInt8.self) if !UTF8.isContinuation(byte) { break } readPtr += 1 } #if SWIFT_STDLIB_ENABLE_VECTOR_TYPES // TODO: Currently, using SIMD sizes above SIMD8 is slower // Once that's fixed we should go up to SIMD64 here utf16Count &+= _utf16Length( readPtr: &readPtr, endPtr: endPtr, unsignedSIMDType: SIMD8<UInt8>.self, signedSIMDType: SIMD8<Int8>.self ) //TO CONSIDER: SIMD widths <8 here //back up to the start of the current scalar if we may have a trailing //incomplete scalar if utf16Count > 0 && UTF8.isContinuation(readPtr.load(as: UInt8.self)) { while readPtr > initialReadPtr && UTF8.isContinuation(readPtr.load(as: UInt8.self)) { readPtr -= 1 } //The trailing scalar may be incomplete, subtract it out and check below let byte = readPtr.load(as: UInt8.self) let len = _utf8ScalarLength(byte) utf16Count &-= len == 4 ? 2 : 1 if readPtr == initialReadPtr { //if we backed up all the way and didn't hit a non-continuation, then //we don't have any complete scalars, and we should bail. return 0 } } #endif //trailing bytes while readPtr < endPtr { let byte = readPtr.load(as: UInt8.self) let len = _utf8ScalarLength(byte) // if we don't have enough bytes left, we don't have a complete scalar, // so don't add it to the count. if readPtr + len <= endPtr { utf16Count &+= len == 4 ? 2 : 1 } readPtr += len } return utf16Count } } @usableFromInline @_effects(releasenone) internal func _nativeGetOffset(for idx: Index) -> Int { _internalInvariant(idx._encodedOffset <= _guts.count) // Trivial and common: start if idx == startIndex { return 0 } if _guts.isASCII { _internalInvariant(idx.transcodedOffset == 0) return idx._encodedOffset } let idx = _utf16AlignNativeIndex(idx) guard _guts._useBreadcrumbs(forEncodedOffset: idx._encodedOffset) else { return _utf16Distance(from: startIndex, to: idx) } // Simple and common: endIndex aka `length`. let breadcrumbsPtr = _guts.getBreadcrumbsPtr() if idx == endIndex { return breadcrumbsPtr.pointee.utf16Length } // Otherwise, find the nearest lower-bound breadcrumb and count from there let (crumb, crumbOffset) = breadcrumbsPtr.pointee.getBreadcrumb( forIndex: idx) return crumbOffset + _utf16Distance(from: crumb, to: idx) } @usableFromInline @_effects(releasenone) internal func _nativeGetIndex(for offset: Int) -> Index { _precondition(offset >= 0, "String index is out of bounds") // Trivial and common: start if offset == 0 { return startIndex } if _guts.isASCII { return Index( _encodedOffset: offset )._scalarAligned._encodingIndependent } guard _guts._useBreadcrumbs(forEncodedOffset: offset) else { return _index(startIndex, offsetBy: offset)._knownUTF8 } // Simple and common: endIndex aka `length`. let breadcrumbsPtr = _guts.getBreadcrumbsPtr() if offset == breadcrumbsPtr.pointee.utf16Length { return endIndex } // Otherwise, find the nearest lower-bound breadcrumb and advance that let (crumb, remaining) = breadcrumbsPtr.pointee.getBreadcrumb( forOffset: offset) if remaining == 0 { return crumb } return _guts.withFastUTF8 { utf8 in var readIdx = crumb._encodedOffset let readEnd = utf8.count _internalInvariant(readIdx < readEnd) var utf16I = 0 let utf16End: Int = remaining // Adjust for sub-scalar initial transcoding: If we're starting the scan // at a trailing surrogate, then we set our starting count to be -1 so as // offset counting the leading surrogate. if crumb.transcodedOffset != 0 { utf16I = -1 } while true { _precondition(readIdx < readEnd, "String index is out of bounds") let len = _utf8ScalarLength(utf8[_unchecked: readIdx]) let utf16Len = len == 4 ? 2 : 1 utf16I &+= utf16Len if utf16I >= utf16End { // Uncommon: final sub-scalar transcoded offset if _slowPath(utf16I > utf16End) { _internalInvariant(utf16Len == 2) return Index( encodedOffset: readIdx, transcodedOffset: 1 )._knownUTF8 } return Index( _encodedOffset: readIdx &+ len )._scalarAligned._knownUTF8 } readIdx &+= len } } } // Copy (i.e. transcode to UTF-16) our contents into a buffer. `alignedRange` // means that the indices are part of the UTF16View.indices -- they are either // scalar-aligned or transcoded (e.g. derived from the UTF-16 view). They do // not need to go through an alignment check. internal func _nativeCopy( into buffer: UnsafeMutableBufferPointer<UInt16>, alignedRange range: Range<String.Index> ) { _internalInvariant(_guts.isFastUTF8) _internalInvariant( range.lowerBound == _utf16AlignNativeIndex(range.lowerBound)) _internalInvariant( range.upperBound == _utf16AlignNativeIndex(range.upperBound)) if _slowPath(range.isEmpty) { return } let isASCII = _guts.isASCII return _guts.withFastUTF8 { utf8 in var writeIdx = 0 let writeEnd = buffer.count var readIdx = range.lowerBound._encodedOffset let readEnd = range.upperBound._encodedOffset if isASCII { _internalInvariant(range.lowerBound.transcodedOffset == 0) _internalInvariant(range.upperBound.transcodedOffset == 0) while readIdx < readEnd { _internalInvariant(utf8[readIdx] < 0x80) buffer[_unchecked: writeIdx] = UInt16( truncatingIfNeeded: utf8[_unchecked: readIdx]) readIdx &+= 1 writeIdx &+= 1 } return } // Handle mid-transcoded-scalar initial index if _slowPath(range.lowerBound.transcodedOffset != 0) { _internalInvariant(range.lowerBound.transcodedOffset == 1) let (scalar, len) = _decodeScalar(utf8, startingAt: readIdx) buffer[writeIdx] = scalar.utf16[1] readIdx &+= len writeIdx &+= 1 } // Transcode middle while readIdx < readEnd { let (scalar, len) = _decodeScalar(utf8, startingAt: readIdx) buffer[writeIdx] = scalar.utf16[0] readIdx &+= len writeIdx &+= 1 if _slowPath(scalar.utf16.count == 2) { buffer[writeIdx] = scalar.utf16[1] writeIdx &+= 1 } } // Handle mid-transcoded-scalar final index if _slowPath(range.upperBound.transcodedOffset == 1) { _internalInvariant(writeIdx < writeEnd) let (scalar, _) = _decodeScalar(utf8, startingAt: readIdx) _internalInvariant(scalar.utf16.count == 2) buffer[writeIdx] = scalar.utf16[0] writeIdx &+= 1 } _internalInvariant(writeIdx <= writeEnd) } } }
apache-2.0
e7ca400fcfb2011bcca452fb9ee94a0f
32.711268
93
0.644175
4.144589
false
false
false
false
salesawagner/wascar
Pods/SwiftLocation/src/BeaconsManager.swift
1
13259
// // SwiftLocation.swift // SwiftLocations // // Copyright (c) 2016 Daniele Margutti // Web: http://www.danielemargutti.com // Mail: [email protected] // Twitter: @danielemargutti // // // 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 CoreLocation import CoreBluetooth public let Beacons :BeaconsManager = BeaconsManager.shared open class BeaconsManager : NSObject, CLLocationManagerDelegate, CBPeripheralManagerDelegate { open static let shared = BeaconsManager() //MARK Private Variables internal var manager: CLLocationManager internal var peripheralManager: CBPeripheralManager? internal var monitoredGeoRegions: [GeoRegionRequest] = [] internal var monitoredBeaconRegions: [BeaconRegionRequest] = [] internal var advertisedDevices: [BeaconAdvertiseRequest] = [] /// This identify the largest boundary distance allowed from a region’s center point. /// Attempting to monitor a region with a distance larger than this value causes the location manager /// to send a regionMonitoringFailure error when you monitor a region. open var maximumRegionMonitoringDistance: CLLocationDistance { get { return self.manager.maximumRegionMonitoringDistance } } // List of region requests currently being tracked using ranging. open var rangedRegions: [BeaconRegionRequest] { let trackedRegions = self.manager.rangedRegions return self.monitoredBeaconRegions.filter({ trackedRegions.contains($0.region) }) } fileprivate override init() { self.manager = CLLocationManager() super.init() self.cleanAllMonitoredRegions() self.manager.delegate = self } /** Remove any monitored region (it will be executed automatically on login) */ open func cleanAllMonitoredRegions() { self.manager.monitoredRegions.forEach { self.manager.stopMonitoring(for: $0) } } //MARK: Public Methods /** You can use the region-monitoring service to be notified when the user crosses a region-based boundary. - parameter coordinates: the center point of the region - parameter radius: the radius of the region in meters - parameter onStateDidChange: event fired when region in/out events are catched - parameter onError: event fired in case of error. request is aborted automatically - throws: throws an exception if monitor is not supported or invalid region was specified - returns: request */ open func monitor(geographicRegion coordinates: CLLocationCoordinate2D, radius: CLLocationDistance, onStateDidChange: @escaping RegionStateDidChange, onError: @escaping RegionMonitorError) throws -> GeoRegionRequest { if CLLocationManager.isMonitoringAvailable(for: CLCircularRegion.self) == false { throw LocationError.notSupported } let request = GeoRegionRequest(coordinates: coordinates, radius: radius) request.onStateDidChange = onStateDidChange request.onError = onError _ = self.add(request: request) return request } /** Monitor for beacon region in/out events or/and ranging events - parameter beacon: beacon to observe - parameter events: events you want to observe; you can monitor region boundary events (.RegionBoundary), beacon ranging (.Ranging) or both (.All). - parameter onStateDidChange: event fired when region in/out events are catched (only if event is set) - parameter onRangingBeacons: event fired when beacon is ranging (only if event is set) - parameter onError: event fired in case of error. request is aborted automatically - throws: throws an exception if monitor is not supported or invalid region was specified - returns: request */ open func monitor(beacon: Beacon, events: Event, onStateDidChange: RegionStateDidChange?, onRangingBeacons: RegionBeaconsRanging?, onError: @escaping RegionMonitorError) throws -> BeaconRegionRequest { let request = try self.createRegion(withBeacon: beacon, monitor: events) request.onStateDidChange = onStateDidChange request.onRangingBeacons = onRangingBeacons request.onError = onError request.start() return request } open func advertise(beaconName name: String, UUID: String, major: CLBeaconMajorValue?, minor: CLBeaconMinorValue?, powerRSSI: NSNumber, serviceUUIDs: [String]) -> Bool { let idx = self.advertisedDevices.index { $0.name == name } if idx != nil { return false } guard let request = BeaconAdvertiseRequest(name: name, proximityUUID: UUID, major: major, minor: minor) else { return false } request.start() return true } //MARK: Private Methods internal func stopAdvertise(_ beaconName: String, error: LocationError?) -> Bool { guard let idx = self.advertisedDevices.index(where: { $0.name == beaconName }) else { return false } let request = self.advertisedDevices[idx] request.rState = .cancelled(error: error) self.advertisedDevices.remove(at: idx) self.updateBeaconAdvertise() return false } fileprivate func createRegion(withBeacon beacon: Beacon, monitor: Event) throws -> BeaconRegionRequest { if CLLocationManager.isMonitoringAvailable(for: CLBeaconRegion.self) == false { throw LocationError.notSupported } guard let request = BeaconRegionRequest(beacon: beacon, monitor: monitor) else { throw LocationError.invalidBeaconData } return request } internal func updateBeaconAdvertise() { let active = self.advertisedDevices.filter { $0.rState.isRunning } if active.count == 0 { self.peripheralManager?.stopAdvertising() self.peripheralManager = nil } else { if self.peripheralManager == nil { self.peripheralManager = CBPeripheralManager(delegate: self, queue: nil) } active.forEach({ if $0.rState.isPending == true { self.peripheralManager?.startAdvertising($0.dataToAdvertise()) } }) } } internal func add(request: Request) -> Bool { if request.rState.canStart == false { return false } if self.monitoredGeoRegions.filter({ $0.UUID == request.UUID }).first != nil { return false } do { if let request = request as? GeoRegionRequest { self.monitoredGeoRegions.append(request) if try self.requestLocationServiceAuthorizationIfNeeded() == false { self.manager.startMonitoring(for: request.region) return true } return false } else if let request = request as? BeaconRegionRequest { self.monitoredBeaconRegions.append(request) if try self.requestLocationServiceAuthorizationIfNeeded() == false { if request.type.contains(Event.RegionBoundary) { self.manager.startMonitoring(for: request.region) self.manager.requestState(for: request.region) } if request.type.contains(Event.Ranging) { self.manager.startRangingBeacons(in: request.region) } return true } return false } return false } catch let err { _ = self.remove(request: request, error: (err as? LocationError) ) return false } } internal func remove(request: Request?, error: LocationError? = nil) -> Bool { guard let request = request else { return false } if let request = request as? GeoRegionRequest { guard let idx = self.monitoredGeoRegions.index(where: { $0.UUID == request.UUID }) else { return false } request.rState = .cancelled(error: error) self.manager.stopMonitoring(for: request.region) self.monitoredGeoRegions.remove(at: idx) return true } else if let request = request as? BeaconRegionRequest { guard let idx = self.monitoredBeaconRegions.index(where: { $0.UUID == request.UUID }) else { return false } request.rState = .cancelled(error: error) if request.type.contains(Event.RegionBoundary) { self.manager.stopMonitoring(for: request.region) } if request.type.contains(Event.Ranging) { self.monitoredBeaconRegions.remove(at: idx) } return true } return false } fileprivate func requestLocationServiceAuthorizationIfNeeded() throws -> Bool { if CLLocationManager.locationAuthStatus == .authorized(always: true) || CLLocationManager.locationAuthStatus == .authorized(always: false) { return false } switch CLLocationManager.bundleLocationAuthType { case .none: throw LocationError.missingAuthorizationInPlist case .always: self.manager.requestAlwaysAuthorization() case .onlyInUse: self.manager.requestWhenInUseAuthorization() } return true } internal func cancelAllMonitorsForRegion(_ error: LocationError) { let list: [[AnyObject]] = [self.monitoredBeaconRegions,self.monitoredGeoRegions] list.forEach { queue in queue.forEach({ request in _ = self.remove(request: (request as! Request) , error: error) }) } } internal func startPendingMonitors() { let list: [[AnyObject]] = [self.monitoredBeaconRegions,self.monitoredGeoRegions] list.forEach { queue in queue.forEach({ request in (request as! Request).start() }) } } fileprivate func dispatchAuthorizationDidChange(_ newStatus: CLAuthorizationStatus) { func _dispatch(_ request: Request) { request.onAuthorizationDidChange?(newStatus) } self.monitoredBeaconRegions.forEach({ _dispatch($0) }) self.monitoredGeoRegions.forEach({ _dispatch($0) }) } @objc open func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) { switch status { case .denied, .restricted: let err = LocationError.authorizationDidChange(newStatus: status) self.cancelAllMonitorsForRegion(err) break case .authorizedAlways, .authorizedWhenInUse: self.startPendingMonitors() break default: break } self.dispatchAuthorizationDidChange(status) } @objc open func peripheralManagerDidUpdateState(_ peripheral: CBPeripheralManager) { if peripheral.state == .poweredOn { self.advertisedDevices.forEach({ $0.start() }) } else { let err = NSError(domain: NSCocoaErrorDomain, code: 0, userInfo: [NSLocalizedDescriptionKey : "Peripheral state changed to \(peripheral.state)"]) self.advertisedDevices.forEach({ $0.rState = .cancelled(error: LocationError.locationManager(error: err)) }) self.advertisedDevices.removeAll() } } //MARK: Location Manager Beacon/Geographic Regions @objc open func locationManager(_ manager: CLLocationManager, didEnterRegion region: CLRegion) { self.monitoredGeoRegions.filter { $0.region.identifier == region.identifier }.first?.onStateDidChange?(.entered) self.monitoredBeaconRegions.filter { $0.region.identifier == region.identifier }.first?.onStateDidChange?(.entered) } @objc open func locationManager(_ manager: CLLocationManager, didExitRegion region: CLRegion) { self.monitoredGeoRegions.filter { $0.region.identifier == region.identifier }.first?.onStateDidChange?(.exited) self.monitoredBeaconRegions.filter { $0.region.identifier == region.identifier }.first?.onStateDidChange?(.exited) } @objc open func locationManager(_ manager: CLLocationManager, monitoringDidFailFor region: CLRegion?, withError error: Error) { let error = LocationError.locationManager(error: error as NSError?) _ = self.remove(request: self.monitoredGeo(forRegion: region), error: error) _ = self.remove(request: self.monitoredBeacon(forRegion: region), error: error) } //MARK: Location Manager Beacons @objc open func locationManager(_ manager: CLLocationManager, rangingBeaconsDidFailFor region: CLBeaconRegion, withError error: Error) { self.monitoredBeaconRegions.forEach { $0.cancel(LocationError.locationManager(error: error as NSError?)) } } @objc open func locationManager(_ manager: CLLocationManager, didRangeBeacons beacons: [CLBeacon], in region: CLBeaconRegion) { self.monitoredBeaconRegions.filter { $0.region.identifier == region.identifier }.first?.onRangingBeacons?(beacons) } //MARK: Helper Methods fileprivate func monitoredGeo(forRegion region: CLRegion?) -> Request? { guard let region = region else { return nil } let request = self.monitoredGeoRegions.filter { $0.region.identifier == region.identifier }.first return request } fileprivate func monitoredBeacon(forRegion region: CLRegion?) -> Request? { guard let region = region else { return nil } let request = self.monitoredBeaconRegions.filter { $0.region.identifier == region.identifier }.first return request } }
mit
5fa81e3566f565f7d80fc17ad930ae11
37.204611
218
0.746851
4.097991
false
false
false
false
talk2junior/iOSND-Beginning-iOS-Swift-3.0
Playground Collection/Part 6 - Alien Adventure 3/Classes/Classes.playground/Pages/Value vs. Reference.xcplaygroundpage/Contents.swift
1
2353
//: [Previous](@previous) /*: ## Value vs. Reference */ //: ### Note struct struct Note { // ... needs volume, tone, duration, etc. } //: ### Instrument protocol protocol Instrument { func playNote(note: Note) } //: ### Fiddle is-an Instrument struct Fiddle: Instrument { func playNote(note: Note) {} } //: ### Banjo is-an Instrument struct Banjo: Instrument { func playNote(note: Note) {} } //: ### Musician class (REFERENCE TYPE) class Musician { var instrument: Instrument init(instrument: Instrument) { self.instrument = instrument } func perform(notes: [Note]) { for note in notes { // Our musician plays the notes exactly "as written." // But other musician implementations could manipulate // the note, by using vibrato, adding a swing feel, etc. instrument.playNote(note: note) } } } //: ### MusicianStruct struct (VALUE TYPE) struct MusicianStruct { var instrument: Instrument init(instrument: Instrument) { self.instrument = instrument } func perform(notes: [Note]) { for note in notes { // Our musician plays the notes exactly "as written." // But other musician implementations could manipulate // the note, by using vibrato, adding a swing feel, etc. instrument.playNote(note: note) } } } func prepareForDuelingBanjos(musician: Musician) { musician.instrument = Banjo() musician.instrument } func prepareForDuelingBanjos(musician: MusicianStruct) { var musicianCopy = musician musicianCopy.instrument = Banjo() musicianCopy.instrument } let musicianStruct = MusicianStruct(instrument: Fiddle()) // Because this call to the prepareForDuelingBanjos func operators on a MusicianStruct (value type) it modifies a copy of the musician parameter. prepareForDuelingBanjos(musician: musicianStruct) // Therefore the musicianStruct's instrument does not change! musicianStruct.instrument // But in this example prepareForDuelingBanjos is called using a Musician (reference type) and the instrument is changed! let duo = [Musician(instrument: Fiddle()), Musician(instrument: Banjo())] let musician = duo[0] prepareForDuelingBanjos(musician: musician) musician.instrument //: [Next](@next)
mit
c99e7ffea97043997ec1d862c012f641
26.045977
145
0.671483
4.036021
false
false
false
false
neonichu/emoji-search-keyboard
Keyboard/Catboard.swift
1
4830
// // Catboard.swift // TransliteratingKeyboard // // Created by Alexei Baboulevitch on 9/24/14. // Copyright (c) 2014 Apple. All rights reserved. // import UIKit /* This is the demo keyboard. If you're implementing your own keyboard, simply follow the example here and then set the name of your KeyboardViewController subclass in the Info.plist file. */ let kCatTypeEnabled = "kCatTypeEnabled" class Catboard: KeyboardViewController { let takeDebugScreenshot: Bool = false override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) { NSUserDefaults.standardUserDefaults().registerDefaults([kCatTypeEnabled: true]) super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func keyPressed(key: Key) { let textDocumentProxy = self.textDocumentProxy let keyOutput = key.outputForCase(self.shiftState.uppercase()) if !NSUserDefaults.standardUserDefaults().boolForKey(kCatTypeEnabled) { textDocumentProxy.insertText(keyOutput) return } if key.type == .Character || key.type == .SpecialCharacter { if let context = textDocumentProxy.documentContextBeforeInput { if context.characters.count < 2 { textDocumentProxy.insertText(keyOutput) return } var index = context.endIndex index = index.predecessor() if context[index] != " " { textDocumentProxy.insertText(keyOutput) return } index = index.predecessor() if context[index] == " " { textDocumentProxy.insertText(keyOutput) return } textDocumentProxy.insertText("\(randomCat())") textDocumentProxy.insertText(" ") textDocumentProxy.insertText(keyOutput) return } else { textDocumentProxy.insertText(keyOutput) return } } else { textDocumentProxy.insertText(keyOutput) return } } override func setupKeys() { super.setupKeys() if takeDebugScreenshot { if self.layout == nil { return } for page in keyboard.pages { for rowKeys in page.rows { for key in rowKeys { if let keyView = self.layout!.viewForKey(key) { keyView.addTarget(self, action: "takeScreenshotDelay", forControlEvents: .TouchDown) } } } } } } override func createBanner() -> ExtraView? { return CatboardBanner(globalColors: self.dynamicType.globalColors, darkMode: false, solidColorMode: self.solidColorMode()) } func takeScreenshotDelay() { _ = NSTimer.scheduledTimerWithTimeInterval(0.1, target: self, selector: Selector("takeScreenshot"), userInfo: nil, repeats: false) } func takeScreenshot() { if !CGRectIsEmpty(self.view.bounds) { UIDevice.currentDevice().beginGeneratingDeviceOrientationNotifications() let oldViewColor = self.view.backgroundColor self.view.backgroundColor = UIColor(hue: (216/360.0), saturation: 0.05, brightness: 0.86, alpha: 1) let rect = self.view.bounds UIGraphicsBeginImageContextWithOptions(rect.size, true, 0) _ = UIGraphicsGetCurrentContext() self.view.drawViewHierarchyInRect(self.view.bounds, afterScreenUpdates: true) let capturedImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() let name = (self.interfaceOrientation.isPortrait ? "Screenshot-Portrait" : "Screenshot-Landscape") let imagePath = "/Users/archagon/Documents/Programming/OSX/RussianPhoneticKeyboard/External/tasty-imitation-keyboard/\(name).png" if let data = UIImagePNGRepresentation(capturedImage) { data.writeToFile(imagePath, atomically: true) } self.view.backgroundColor = oldViewColor } } } func randomCat() -> String { let cats = "🐱😺😸😹😽😻😿😾😼🙀" let numCats = cats.characters.count let randomCat = arc4random() % UInt32(numCats) let index = cats.startIndex.advancedBy(Int(randomCat)) let character = cats[index] return String(character) }
bsd-3-clause
baa81a4a61f5e128a55990872485e6d2
33.532374
141
0.590625
5.345212
false
false
false
false
dcordero/TvOSTextViewer
TvOSTextViewer/Sources/FadedTextView.swift
1
1180
// // FadedTextView.swift // TvOSTextViewer // // Created by David Cordero on 15.02.17. // Copyright © 2017 David Cordero. All rights reserved. // import UIKit private let containerInset: CGFloat = 40 private let gradientOffsetTop: NSNumber = 0.05 private let gradientOffsetBottom: NSNumber = 0.95 class FadedTextView: UITextView { override func layoutSubviews() { super.layoutSubviews() let maskLayer = CALayer() maskLayer.frame = bounds let gradientLayer = CAGradientLayer() gradientLayer.frame = CGRect(x: bounds.origin.x, y: 0, width: bounds.width, height: bounds.height) gradientLayer.colors = [UIColor.clear.cgColor, UIColor.white.cgColor, UIColor.white.cgColor, UIColor.clear.cgColor] gradientLayer.locations = [0.0, gradientOffsetTop, gradientOffsetBottom, 1.0] maskLayer.addSublayer(gradientLayer) self.layer.mask = maskLayer textContainerInset = UIEdgeInsets(top: containerInset, left: 0, bottom: containerInset, right: 0) } }
mit
980ad2e4512c8a8142e1ecde26f761f3
30.026316
106
0.622561
4.678571
false
false
false
false
ndevenish/KerbalHUD
KerbalHUD/NavBallWidget.swift
1
15541
// // NavBall.swift // KerbalHUD // // Created by Nicholas Devenish on 29/08/2015. // Copyright © 2015 Nicholas Devenish. All rights reserved. // import Foundation import GLKit private prefix func -(dir : NavBallWidget.FlightData.Direction) -> NavBallWidget.FlightData.Direction { return NavBallWidget.FlightData.Direction(p: -dir.Pitch, y: dir.Yaw+180) } class NavBallWidget : Widget { private struct FlightData { var Roll : Float = 0 var Pitch : Float = 0 var Heading : Float = 0 var speedDisplay : SpeedDisplay = .Orbit private struct Ends { var Pro : Direction var Retro : Direction init(data : [String:JSON], pro: String, ret: String) { Pro = Direction(data: data, name: pro) Retro = Direction(data: data, name: ret) } init(data : [String:JSON], pro: String) { Pro = Direction(data: data, name: pro) Retro = -Pro } } private struct Direction { var Pitch : Float var Yaw : Float init(data : [String:JSON], name: String) { Pitch = data["rpm.PITCH" + name]?.floatValue ?? 0 Yaw = data["rpm.YAW" + name]?.floatValue ?? 0 } init(p: Float, y: Float) { Pitch = p Yaw = y } } var markers : [String:Direction] = [:] } private(set) var bounds : Bounds let variables : [String] private(set) var configuration : [String : Any] = [:] private let drawing : DrawingTools private let sphere : Drawable private let sphereTexture : Texture private var data = FlightData() init(tools : DrawingTools, bounds : Bounds) { drawing = tools var varList = [Vars.Flight.Roll, Vars.Flight.Pitch, Vars.Flight.Heading, Vars.Node.Exists, Vars.Target.Exists, Vars.Aero.AngleOfAttack, Vars.Aero.Sideslip, Vars.Vessel.SpeedDisplay] varList.appendContentsOf(Vars.RPM.Direction.allCardinal) varList.appendContentsOf(Vars.RPM.Direction.Node.all) varList.appendContentsOf(Vars.RPM.Direction.Target.all) variables = varList self.bounds = bounds glPushGroupMarkerEXT(0, "Navball Texture Generation") sphereTexture = NavBallTextureRendering(tools: drawing).generate() glPopGroupMarkerEXT() sphere = tools.LoadTriangles(generateSphereTriangles(1, latSteps: 50, longSteps: 100), texture: sphereTexture) } func update(data : [String : JSON]) { var out = FlightData() out.Roll = (data[Vars.Flight.Roll]?.floatValue ?? 0) out.Pitch = data[Vars.Flight.Pitch]?.floatValue ?? 0 out.Heading = data[Vars.Flight.Heading]?.floatValue ?? 0 out.speedDisplay = SpeedDisplay(rawValue: data[Vars.Vessel.SpeedDisplay]?.intValue ?? 1) ?? .Orbit var markers : [String:FlightData.Direction] = [:] switch out.speedDisplay { case .Orbit: let primary = FlightData.Ends(data: data, pro: "PROGRADE") let normal = FlightData.Ends(data: data, pro: "NORMALPLUS") let radial = FlightData.Ends(data: data, pro: "RADIALIN") markers = [ "Prograde": primary.Pro, "Retrograde": primary.Retro, "RadialIn": radial.Pro, "RadialOut": radial.Retro, "Normal": normal.Pro, "AntiNormal": normal.Retro ] if data[Vars.Node.Exists]?.boolValue ?? false { markers["Maneuver"] = FlightData.Direction(data: data, name: "NODE") } if data[Vars.Target.Exists]?.boolValue ?? false { markers["TargetPrograde"] = FlightData.Direction(data: data, name: "TARGET") } case .Surface: if let pitch = data[Vars.Aero.AngleOfAttack]?.floatValue, let yaw = data[Vars.Aero.Sideslip]?.floatValue { markers["Prograde"] = FlightData.Direction(p: pitch, y: yaw) } case .Target: break } out.markers = markers self.data = out } /// Draw something func draw() { drawing.bind(sphereTexture) drawing.program.setColor(red: 1, green: 1, blue: 1) var sphMat = GLKMatrix4Identity // sphMat = GLKMatrix4Translate(sphMat, 320, 338, 0) sphMat = GLKMatrix4Translate(sphMat, bounds.left+bounds.width/2, bounds.bottom+bounds.height/2, 0) sphMat = GLKMatrix4Scale(sphMat, bounds.width/2, bounds.height/2, 1) // Roll sphMat = GLKMatrix4Rotate(sphMat, -(data.Roll) * π/180, 0, 0, 1) // Pitch? sphMat = GLKMatrix4Rotate(sphMat, (data.Pitch) * π/180, 1, 0, 0) // Heading sphMat = GLKMatrix4Rotate(sphMat, data.Heading * π/180, 0, -1, 0) // Proper orientation to start from. Heading 0, pitch 0, roll 0. sphMat = GLKMatrix4Rotate(sphMat, π/2, 0, 0, 1) sphMat = GLKMatrix4Rotate(sphMat, π/2, 0, 1, 0) drawing.program.setModelView(sphMat) drawing.draw(sphere) var mkMat = GLKMatrix4Identity // Middle of the screen, forwards mkMat = GLKMatrix4Translate(mkMat, bounds.center.x, bounds.center.y, 1) mkMat = GLKMatrix4Scale(mkMat, bounds.width/2, bounds.height/2, 1) // sphMat = GLKMatrix4Scale(sphMat, bounds.width/2, bounds.height/2, 1) glPushGroupMarkerEXT(0, "Drawing NavBall Markers") defer { glPopGroupMarkerEXT() } drawing.program.setModelView(mkMat) // Draw all the nav markers for (name, dir) in data.markers { guard let tex = drawing.images[name] else { continue } drawing.bind(tex) // Work out where to draw this.... var spec = mkMat // Now rotate off-center spec = GLKMatrix4Rotate(spec, (dir.Pitch) * π/180, 1, 0, 0) spec = GLKMatrix4Rotate(spec, (-dir.Yaw ) * π/180, 0, -1, 0) spec = GLKMatrix4Translate(spec, 0,0,1) spec = GLKMatrix4Rotate(spec, (-dir.Pitch) * π/180, 1, 0, 0) spec = GLKMatrix4Rotate(spec, (dir.Yaw ) * π/180, 0, -1, 0) spec = GLKMatrix4Scale(spec, 0.3, 0.3, 1) drawing.program.setModelView(spec) // What colour? White, other than the transparency... let zPosition = cos(dir.Yaw * π/180)*cos(dir.Pitch * π/180) drawing.program.setColor(Color4(r: 1, g: 1, b: 1, a: min(1,2*(zPosition+0.5)))) drawing.draw(drawing.texturedCenterSquare!) } drawing.program.setColor(Color4.White) } } class NavBallTextureRendering { var drawing : DrawingTools var textures : [Int : Texture] = [:] init(tools : DrawingTools) { drawing = tools generateTextTextures() } deinit { // Delete all text textures for t in textures.values { drawing.deleteTexture(t) } textures.removeAll() } func generateTextTextures() { processGLErrors() let text = drawing.textRenderer("Menlo-Bold") as! AtlasTextRenderer processGLErrors() for var angle = -80; angle <= 80; angle += 10 { let str = angle == 0 ? "N" : String(angle) textures[angle] = text.drawToTexture(str, size: 45) } for var angle = 45; angle <= 360; angle += 45 { textures[angle] = text.drawToTexture(String(angle), size: 45) textures[-angle] = textures[angle]! } } func drawTextStrip(longitude: Float, upper : Bool) { let range : (Int, Int) = upper ? (10, 80) : (-80, -10) for var angle = range.0; angle <= range.1; angle += 10 { // Don't render the central signs if angle == 0 { continue } // Bind the texture and calculate the size let tex = textures[angle]! let textHeight : Float = 4 let textOffset : Float = 5 let size : Size2D<Float> if angle == 80 || angle == -80 { size = Size2D(w: tex.size!.aspect*textHeight*0.7, h: textHeight*0.7) } else { size = Size2D(w: tex.size!.aspect*textHeight, h: textHeight) } drawing.bind(tex) drawing.drawProjectedGridOntoSphere( position: SphericalPoint(lat: Float(angle), long: longitude, r: 0), left: textOffset, bottom: -size.h/2, right: textOffset+size.w, top: size.h/2, xSteps: 10, ySteps: 5, slicePoint: 0) drawing.drawProjectedGridOntoSphere( position: SphericalPoint(lat: Float(angle), long: longitude, r: 0), left: -textOffset-size.w, bottom: -size.h/2, right: -textOffset, top: size.h/2, xSteps: 10, ySteps: 5, slicePoint: 0) } } func generate() -> Texture { let texture = drawing.createTextureFramebuffer(Size2D(w: 2048, h: 1024), depth: false, stencil: false) drawing.bind(texture) drawing.setOrthProjection(left: -180, right: 180, bottom: -90, top: 90) drawing.program.setModelView(GLKMatrix4Identity) let upperBackground = Color4(r: 93.0/255, g: 177.0/255, b: 228.0/225, a: 1) let lowerBackground = Color4(r: 4.0/255, g: 80.0/255, b: 117.0/255, a: 1) let white = Color4(r: 1, g: 1, b: 1, a: 1) let upperBlue = Color4(r: 4.0/255, g: 80.0/255, b: 117.0/255, a: 1) // Upper and lower halves drawing.program.setColor(upperBackground) drawing.DrawSquare(-180, bottom: 0, right: 180, top: 90) drawing.program.setColor(lowerBackground) drawing.DrawSquare(-180, bottom: -90, right: 180, top: 0) drawing.program.setModelView(GLKMatrix4Identity) let thetaSet = [-180, -90, 0, 90, 180] // Draw the vertical bands of text // Angles to draw: // drawing.program.setColor(red: 33.0/255, green: 48.0/255, blue: 82.0/255) drawing.program.setColor(upperBlue) for longitude in thetaSet { drawTextStrip(Float(longitude), upper: true) } drawing.program.setColor(white) for longitude in thetaSet { drawTextStrip(Float(longitude), upper: false) } drawing.program.setModelView(GLKMatrix4Identity) // Cross-bars locations // Blue uppers drawing.program.setColor(upperBlue) drawVerticalBand(90, width: 1.5, upper: true) drawVerticalBand(-90, width: 1.5, upper: true) drawVerticalBand(180, width: 1.5, upper: true) drawVerticalBand(-180, width: 1.5, upper: true) // Cross-bars for longitude in [225, 315, 45, 135] { drawVerticalBand(Float(longitude), width: 1, upper: true) } drawing.DrawSquare(-180, bottom: 44.5, right: 180, top: 45.5) drawing.DrawSquare(-180, bottom: 84.75, right: 180, top: 85.25) // Fill in the anti-color on the top drawing.DrawSquare(-180, bottom: 89.5, right: 180, top: 90) drawing.program.setModelView(GLKMatrix4Identity) drawSpurs(upper: true) // Really thin top spur that is a circle // drawing.DrawSquare(-180, bottom: 84.75, right: 180, top: 85.25) // White lowers drawing.program.setColor(red: 1, green: 1, blue: 1) drawVerticalBand(90, width: 1.5, upper: false) drawVerticalBand(-90, width: 1.5, upper: false) drawVerticalBand(180, width: 1.5, upper: false) drawVerticalBand(-180, width: 1.5, upper: false) // Cross-bars for longitude in [225, 315, 45, 135] { drawVerticalBand(Float(longitude), width: 1, upper: false) } drawing.DrawSquare(-180, bottom: -45.5, right: 180, top: -44.5) drawing.program.setModelView(GLKMatrix4Identity) drawSpurs(upper: false) // Orange bands drawing.program.setColor(red: 247.0/255, green: 101.0/255, blue: 3.0/255) drawVerticalBand(0, width: 2.5, upper: true) drawVerticalBand(0, width: 2.5, upper: false) drawing.DrawSquare(-180, bottom: -1, right: 180, top: 1) drawing.program.setModelView(GLKMatrix4Identity) // Lower middle text for longitude in [-180, 0, 45, 135, 180, 225, 315] { let size = longitude == 0 ? 9 : 7 drawText(longitude, size : Float(size), position : SphericalPoint(lat: -45, long: Float(longitude), r: 0), fillBackground: lowerBackground, foregroundColor: white) } // Upper text for longitude in [0, 45, 90, 135, 225, 315] { let size = longitude == 0 ? 9 : 7 drawText(longitude, size : Float(size), position : SphericalPoint(lat: 5, long: Float(longitude), r: 0), fillBackground: upperBackground, foregroundColor: upperBlue) } for longitude in [-180, 0, 45, 90, 135, 180, 225, 270, 315] { let size = longitude == 0 ? 9 : 7 drawText(longitude, size : Float(size), position : SphericalPoint(lat: 45, long: Float(longitude), r: 0), fillBackground: upperBackground, foregroundColor: upperBlue) } // White across top and bottom drawing.program.setColor(white) drawing.DrawSquare(-180, bottom: 88.5, right: 180, top: 89.5) drawing.DrawSquare(-180, bottom: -89.5, right: 180, top: -88.5) drawing.bind(Framebuffer.Default) let tex = texture.texture drawing.deleteFramebuffer(texture, texture: false) tex.debugName("NavBall") return tex } func drawText(angle : Int, size : Float, position : SphericalPoint, fillBackground : Color4? = nil, foregroundColor: Color4? = nil) { let tex = textures[angle]! let size = Size2D(w: tex.size!.aspect*size, h: size) if let color = fillBackground { drawing.program.setColor(color) drawing.bind(Texture.None) drawing.drawProjectedGridOntoSphere( position: position, left: -size.w/2, bottom: -size.h/2, right: size.w/2, top: size.h/2, xSteps: 10, ySteps: 5, slicePoint: 0) drawing.program.setColor(foregroundColor!) } drawing.bind(tex) drawing.drawProjectedGridOntoSphere( position: position, left: -size.w/2, bottom: -size.h/2, right: size.w/2, top: size.h/2, xSteps: 10, ySteps: 5, slicePoint: 0) } private enum BulkSpherePosition { case Left case Right case Middle } func drawVerticalBand(longitude: Float, width : Float, upper: Bool = true) { // Work out the maximum projection for this width let maxDisplacement = (width/2) / tan(sin(width/2/59)) - 0.01 let points : ((GLfloat, GLfloat), (GLfloat, GLfloat)) if upper { points = ((0, 50),(50, maxDisplacement)) } else { points = ((-50, 0), (-58.9, -50)) } // Draw in two portions as it stretches out at high points drawing.bind(Texture.None) drawing.drawProjectedGridOntoSphere( position: SphericalPoint(lat: 0, long: longitude, r: 0), left: -width/2, bottom: points.0.0, right: width/2, top: points.0.1, xSteps: 1, ySteps: 10, slicePoint: 0) drawing.drawProjectedGridOntoSphere( position: SphericalPoint(lat: 0, long: longitude, r: 0), left: -width/2, bottom: points.1.0, right: width/2, top: points.1.1, xSteps: 1, ySteps: 100, slicePoint: 0) } func drawSpurs(upper upper : Bool) { // Spurs! for longitude in [-180, -90, 0, 90, 180] { let offset : Float = 1.5 let h : Float = 0.5 * (upper ? 1 : -1) for var lat = 5; lat <= 80; lat += 5 { if lat == 45 { continue } let latitude = lat * (upper ? 1 : -1) let w : Float = latitude % 10 == 0 ? 3 : 2 drawing.drawProjectedGridOntoSphere( position: SphericalPoint(lat: Float(latitude), long: Float(longitude), r: 0), left: -offset-w, bottom: -h/2, right: -offset, top: h/2, xSteps: 1, ySteps: 1, slicePoint: 0) drawing.drawProjectedGridOntoSphere( position: SphericalPoint(lat: Float(latitude), long: Float(longitude), r: 0), left: offset, bottom: -h/2, right: w+offset, top: h/2, xSteps: 1, ySteps: 1, slicePoint: 0) } } } }
mit
90c88481d0515551880620179023e1bf
33.975225
114
0.622899
3.464748
false
false
false
false
MrReality/MRCommon
MRCommon_Swift/Function/MRGCDFunction.swift
1
1051
// // MRGCDFunction.swift // test // // Created by mac on 2018/9/21. // Copyright © 2018年 mixReality. All rights reserved. // import UIKit // MARK: gcd 相关方法 typealias Task = (_ cancel: Bool) -> Void /// 延时调用 func delay(_ time: TimeInterval, task: @escaping () -> ()) -> Task? { func dispatch_later(block: @escaping () -> ()) { let t = DispatchTime.now() + time DispatchQueue.main.asyncAfter(deadline: t, execute: block) } var closure: (() -> Void)? = task var result: Task? let delayedClosure: Task = { cancel in if let internalClosure = closure { if (cancel == false) { DispatchQueue.main.async(execute: internalClosure) } } closure = nil result = nil } result = delayedClosure dispatch_later { if let delayedClosure = result { delayedClosure(false) } } return result } /// 取消延时调用 func cancel(_ task: Task?) { task?(true) }
mit
db2cd53b9c3aaa1348b4d17aa3c1a29c
19.4
69
0.551961
4.015748
false
false
false
false
n8iveapps/N8iveKit
InterfaceKit/InterfaceKit/source/models/NKTabBarLayout.swift
1
3179
// // NKTabBarLayout.swift // N8iveKit // // Created by Muhammad Bassio on 6/16/17. // Copyright © 2017 N8ive Apps. All rights reserved. // import UIKit public enum NKTabBarOrientation { case horizontal, vertical } open class NKTabBarLayout: UICollectionViewLayout { open var orientation:NKTabBarOrientation = .horizontal open var layoutAttributes:[UICollectionViewLayoutAttributes] = [] open var contentSize = CGSize.zero open var itemVariableDimension:CGFloat = 0 open var itemFixedDimension:CGFloat = 0 open var verticalHeight:CGFloat = 80 open var navigationBarHeight:CGFloat = 20 // cache open override func prepare() { super.prepare() self.layoutAttributes = [] var yOffset:CGFloat = 0 var xOffset:CGFloat = 0 // we only have one section let numberOfItems = self.collectionView!.numberOfItems(inSection: 0) if self.orientation == .horizontal { if let cv = self.collectionView { self.itemFixedDimension = cv.bounds.height self.itemVariableDimension = cv.bounds.width / CGFloat(numberOfItems) } } else { if let cv = self.collectionView { yOffset = self.navigationBarHeight self.itemFixedDimension = cv.bounds.width self.itemVariableDimension = cv.bounds.height / CGFloat(numberOfItems) if self.verticalHeight < self.itemVariableDimension { self.itemVariableDimension = self.verticalHeight } } } for item in 0 ..< numberOfItems { let indexPath = IndexPath(item: item, section: 0) let attributes = UICollectionViewLayoutAttributes(forCellWith: indexPath) if self.orientation == .horizontal { // increase xOffset, yOffset = 0 attributes.frame = CGRect(x: xOffset, y: yOffset, width: self.itemVariableDimension, height: self.itemFixedDimension) xOffset += self.itemVariableDimension } else { // increase yOffset, xOffset = 0 attributes.frame = CGRect(x: xOffset, y: yOffset, width: self.itemFixedDimension, height: self.itemVariableDimension) yOffset += self.itemVariableDimension } self.layoutAttributes.append(attributes) } } // clear cache open override func invalidateLayout() { self.layoutAttributes = [] } open override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? { return self.layoutAttributes.filter { $0.frame.intersects(rect) } } open override func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? { return self.layoutAttributes.first { $0.indexPath == indexPath } } open override func shouldInvalidateLayout(forBoundsChange newBounds: CGRect) -> Bool { return true /*if let cv = self.collectionView { return !newBounds.size.equalTo(cv.frame.size) } return false*/ } open override var collectionViewContentSize: CGSize { if let cv = self.collectionView { return cv.frame.size } return CGSize.zero } open func layoutKeyForIndexPath(_ indexPath : IndexPath) -> String { return "\(indexPath.section)_\(indexPath.row)" } }
mit
c094126c3c6baf77f57e51a7e83d6011
31.428571
125
0.694462
4.646199
false
false
false
false
zapdroid/RXWeather
Pods/Nimble/Sources/Nimble/Adapters/NimbleEnvironment.swift
1
1375
import Dispatch import Foundation /// "Global" state of Nimble is stored here. Only DSL functions should access / be aware of this /// class' existance internal class NimbleEnvironment { static var activeInstance: NimbleEnvironment { get { let env = Thread.current.threadDictionary["NimbleEnvironment"] if let env = env as? NimbleEnvironment { return env } else { let newEnv = NimbleEnvironment() activeInstance = newEnv return newEnv } } set { Thread.current.threadDictionary["NimbleEnvironment"] = newValue } } // TODO: eventually migrate the global to this environment value var assertionHandler: AssertionHandler { get { return NimbleAssertionHandler } set { NimbleAssertionHandler = newValue } } var suppressTVOSAssertionWarning: Bool = false var awaiter: Awaiter init() { let timeoutQueue: DispatchQueue if #available(OSX 10.10, *) { timeoutQueue = DispatchQueue.global(qos: .userInitiated) } else { timeoutQueue = DispatchQueue.global(priority: .high) } awaiter = Awaiter( waitLock: AssertionWaitLock(), asyncQueue: .main, timeoutQueue: timeoutQueue) } }
mit
2a4b736d14044424a158b2d240b498f2
29.555556
96
0.602182
5.228137
false
false
false
false
venticake/RetricaImglyKit-iOS
RetricaImglyKit/Classes/Frontend/Renderer/PhotoEffectThumbnailRenderer.swift
1
4613
// This file is part of the PhotoEditor Software Development Kit. // Copyright (C) 2016 9elements GmbH <[email protected]> // All rights reserved. // Redistribution and use in source and binary forms, without // modification, are permitted provided that the following license agreement // is approved and a legal/financial contract was signed by the user. // The license agreement can be found under the following link: // https://www.photoeditorsdk.com/LICENSE.txt import UIKit /** * A `PhotoEffectThumbnailRenderer` can be used to generate thumbnails of a given input image * for multiple photo effects. */ @available(iOS 8, *) @objc(IMGLYPhotoEffectThumbnailRenderer) public class PhotoEffectThumbnailRenderer: NSObject { // MARK: - Properties /// The input image that will be used to generate the thumbnails. public let inputImage: UIImage private let renderQueue = dispatch_queue_create("photo_effect_thumbnail_rendering", DISPATCH_QUEUE_SERIAL) private let ciContext: CIContext private let eaglContext: EAGLContext private let lutConverter = LUTToNSDataConverter(identityLUTAtURL: NSBundle.imglyKitBundle.URLForResource("Identity", withExtension: "png")!) private var thumbnailImage: UIImage? // MARK: - Initializers /** Returns a newly initialized photo effect thumbnail renderer with the given input image. - parameter inputImage: The input image that will be used to generate the thumbnails. - returns: A newly initialized `PhotoEffectThumbnailRenderer` object. */ public init(inputImage: UIImage) { self.inputImage = inputImage eaglContext = EAGLContext(API: .OpenGLES2) ciContext = CIContext(EAGLContext: eaglContext) super.init() } // MARK: - Rendering /** Generates thumbnails for multiple photo effects of the given size. - parameter photoEffects: The photo effects that should be used to generate thumbnails. - parameter size: The size of the thumbnails. - parameter singleCompletion: This handler will be called for each thumbnail that has been created successfully. */ public func generateThumbnailsForPhotoEffects(photoEffects: [PhotoEffect], ofSize size: CGSize, singleCompletion: ((thumbnail: UIImage, index: Int) -> Void)) { dispatch_async(renderQueue) { self.renderBaseThumbnailIfNeededOfSize(size) var index = 0 for effect in photoEffects { autoreleasepool { let thumbnail: UIImage? if let filter = effect.newEffectFilter { if let filterName = effect.CIFilterName where (filterName == "CIColorCube" || filterName == "CIColorCubeWithColorSpace") && effect.options?["inputCubeData"] == nil { self.lutConverter.lutURL = effect.lutURL filter.setValue(self.lutConverter.colorCubeData, forKey: "inputCubeData") } thumbnail = self.renderThumbnailWithFilter(filter) } else { thumbnail = self.thumbnailImage } if let thumbnail = thumbnail { singleCompletion(thumbnail: thumbnail, index: index) } index = index + 1 } } } } private func renderBaseThumbnailIfNeededOfSize(size: CGSize) { let renderThumbnail = { UIGraphicsBeginImageContextWithOptions(size, false, 0) self.inputImage.drawInRect(CGRect(origin: CGPoint.zero, size: size), withContentMode: .ScaleAspectFill) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() self.thumbnailImage = image } if let thumbnailImage = thumbnailImage where thumbnailImage.size != size { renderThumbnail() } else if thumbnailImage == nil { renderThumbnail() } } private func renderThumbnailWithFilter(filter: CIFilter) -> UIImage? { guard let thumbnailImage = thumbnailImage?.CGImage else { return nil } let inputImage = CIImage(CGImage: thumbnailImage) filter.setValue(inputImage, forKey: kCIInputImageKey) guard let outputImage = filter.outputImage else { return nil } let cgOutputImage = ciContext.createCGImage(outputImage, fromRect: outputImage.extent) return UIImage(CGImage: cgOutputImage) } }
mit
3db0b133153df5203789de2e73524d85
38.42735
189
0.653371
5.278032
false
false
false
false
tresorit/ZeroKit-Realm-encrypted-tasks
ios/RealmTasks iOS/TableViewCell.swift
1
16035
//////////////////////////////////////////////////////////////////////////// // // Copyright 2016 Realm Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////// // FIXME: This file should be split up. // swiftlint:disable file_length import AudioToolbox import Cartography import RealmSwift import UIKit // MARK: Shared Functions func vibrate() { let isDevice = { return TARGET_OS_SIMULATOR == 0 }() if isDevice { AudioServicesPlaySystemSound(kSystemSoundID_Vibrate) } } // MARK: Private Declarations private enum ReleaseAction { case complete, delete } private let iconWidth: CGFloat = 60 // MARK: Table View Cell // FIXME: This class should be split up. // swiftlint:disable type_body_length final class TableViewCell<Item: Object>: UITableViewCell, UITextViewDelegate where Item: CellPresentable { // MARK: Properties lazy var dateFormatter: DateFormatter = { let dateFormatter = DateFormatter() dateFormatter.dateStyle = .medium dateFormatter.timeStyle = .short dateFormatter.doesRelativeDateFormatting = true return dateFormatter }() // Stored Properties let textView = CellTextView() let dateLabel = CellDateLabel() var item: Item! { didSet { let newItem = item textView.text = item.text item.plainText { [weak self] (plainText, _) in if let plainText = plainText, let item = self?.item, item == newItem { self?.textView.text = plainText } } if item.date != nil { dateLabel.isHidden = false dateLabel.text = dateFormatter.string(from: item.date!) } else { dateLabel.isHidden = true } setLayoutConstraints(dateLabelHidden: dateLabel.isHidden) setCompleted(item.completed) if let item = item as? TaskList { let count = item.items.filter("completed == false").count countLabel.text = String(count) if count == 0 { textView.alpha = 0.3 countLabel.alpha = 0.3 } else { countLabel.alpha = 1 } } } } let navHintView = NavHintView() // Callbacks var presenter: CellPresenter<Item>! // Private Properties private var originalDoneIconCenter = CGPoint() private var originalDeleteIconCenter = CGPoint() private var releaseAction: ReleaseAction? private let overlayView = UIView() private let countLabel = UILabel() private let constraintGroup = ConstraintGroup() // Assets private let doneIconView = UIImageView(image: UIImage(named: "DoneIcon")) private let deleteIconView = UIImageView(image: UIImage(named: "DeleteIcon")) // MARK: Initializers override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) selectionStyle = .none setupUI() setupPanGestureRecognizer() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: UI private func setupUI() { setupBackgroundView() setupIconViews() setupOverlayView() setupTextView() setupDateLabel() setupBorders() if Item.self == TaskList.self { setupCountBadge() } setupNavHintView() setLayoutConstraints(dateLabelHidden: true) } func reset() { presenter = nil } private func setupBackgroundView() { backgroundColor = .clear backgroundView = UIView() constrain(backgroundView!) { backgroundView in backgroundView.edges == backgroundView.superview!.edges } } private func setupIconViews() { doneIconView.center = center doneIconView.frame.origin.x = 20 doneIconView.alpha = 0 doneIconView.autoresizingMask = [.flexibleRightMargin, .flexibleTopMargin, .flexibleBottomMargin] insertSubview(doneIconView, belowSubview: contentView) deleteIconView.center = center deleteIconView.frame.origin.x = bounds.width - deleteIconView.bounds.width - 20 deleteIconView.alpha = 0 deleteIconView.autoresizingMask = [.flexibleLeftMargin, .flexibleTopMargin, .flexibleBottomMargin] insertSubview(deleteIconView, belowSubview: contentView) } private func setupOverlayView() { overlayView.backgroundColor = .completeDimBackground overlayView.isHidden = true contentView.addSubview(overlayView) constrain(overlayView) { backgroundOverlayView in backgroundOverlayView.edges == backgroundOverlayView.superview!.edges } } private func setupTextView() { textView.delegate = self contentView.addSubview(textView) constrain(textView) { textView in textView.top == textView.superview!.top + 17 textView.left == textView.superview!.left + 8 if Item.self == TaskList.self { textView.right == textView.superview!.right - 68 } else { textView.right == textView.superview!.right - 8 } } } private func setupDateLabel() { contentView.addSubview(dateLabel) constrain(textView, dateLabel) { textView, dateLabel in dateLabel.left == dateLabel.superview!.left + 14 dateLabel.bottom == dateLabel.superview!.bottom - 17 dateLabel.right == dateLabel.superview!.right - 8 } } private func setLayoutConstraints(dateLabelHidden: Bool) { if dateLabelHidden { constrain(textView, replace: constraintGroup) { textView in textView.bottom == textView.superview!.bottom - 7 } } else { constrain(textView, dateLabel, replace: constraintGroup) { textView, dateLabel in textView.bottom == dateLabel.top + 10 } } } private func setupBorders() { let singlePixelInPoints = 1 / UIScreen.main.scale let highlightLine = UIView() highlightLine.backgroundColor = UIColor(white: 1, alpha: 0.05) addSubview(highlightLine) constrain(highlightLine) { highlightLine in highlightLine.top == highlightLine.superview!.top highlightLine.left == highlightLine.superview!.left highlightLine.right == highlightLine.superview!.right highlightLine.height == singlePixelInPoints } let shadowLine = UIView() shadowLine.backgroundColor = UIColor(white: 0, alpha: 0.05) addSubview(shadowLine) constrain(shadowLine) { shadowLine in shadowLine.bottom == shadowLine.superview!.bottom shadowLine.left == shadowLine.superview!.left shadowLine.right == shadowLine.superview!.right shadowLine.height == singlePixelInPoints } } private func setupCountBadge() { let badgeBackground = UIView() badgeBackground.backgroundColor = UIColor(white: 1, alpha: 0.15) contentView.addSubview(badgeBackground) constrain(badgeBackground) { badgeBackground in badgeBackground.top == badgeBackground.superview!.top badgeBackground.bottom == badgeBackground.superview!.bottom badgeBackground.right == badgeBackground.superview!.right badgeBackground.width == 60 } badgeBackground.addSubview(countLabel) countLabel.backgroundColor = .clear countLabel.textColor = .white countLabel.font = .systemFont(ofSize: 18) constrain(countLabel) { countLabel in countLabel.center == countLabel.superview!.center } } private func setupNavHintView() { navHintView.alpha = 0 contentView.addSubview(navHintView) constrain(navHintView) { navHintView in navHintView.edges == navHintView.superview!.edges } } // MARK: Pan Gesture Recognizer private func setupPanGestureRecognizer() { let recognizer = UIPanGestureRecognizer(target: self, action: #selector(handlePan(recognizer:))) recognizer.delegate = self addGestureRecognizer(recognizer) } func handlePan(recognizer: UIPanGestureRecognizer) { switch recognizer.state { case .began: handlePanBegan() case .changed: handlePanChanged(translation: recognizer.translation(in: self).x) case .ended: handlePanEnded() default: break } } private func handlePanBegan() { originalDeleteIconCenter = deleteIconView.center originalDoneIconCenter = doneIconView.center releaseAction = nil } private func handlePanChanged(translation: CGFloat) { if !item.isCompletable && translation > 0 { releaseAction = nil return } let x: CGFloat // Slow down translation if translation < 0 { x = translation / 2 if x < -iconWidth { deleteIconView.center = CGPoint(x: originalDeleteIconCenter.x + iconWidth + x, y: originalDeleteIconCenter.y) } } else if translation > iconWidth { let offset = (translation - iconWidth) / 3 doneIconView.center = CGPoint(x: originalDoneIconCenter.x + offset, y: originalDoneIconCenter.y) x = iconWidth + offset } else { x = translation } contentView.frame.origin.x = x let fractionOfThreshold = min(1, Double(abs(x) / iconWidth)) releaseAction = fractionOfThreshold >= 1 ? (x > 0 ? .complete : .delete) : nil if x > 0 { doneIconView.alpha = CGFloat(fractionOfThreshold) } else { deleteIconView.alpha = CGFloat(fractionOfThreshold) } if !item.isInvalidated && !item.completed { overlayView.backgroundColor = .completeGreenBackground overlayView.isHidden = releaseAction != .complete if contentView.frame.origin.x > 0 { textView.unstrike() textView.strike(fraction: fractionOfThreshold) } else { releaseAction == .complete ? textView.strike() : textView.unstrike() } } else { overlayView.isHidden = releaseAction == .complete textView.alpha = releaseAction == .complete ? 1 : 0.3 if contentView.frame.origin.x > 0 { textView.unstrike() textView.strike(fraction: 1 - fractionOfThreshold) } else { releaseAction == .complete ? textView.unstrike() : textView.strike() } } } private func handlePanEnded() { guard item != nil && !item.isInvalidated else { return } let animationBlock: () -> Void let completionBlock: () -> Void // If not deleting, slide it back into the middle // If we are deleting, slide it all the way out of the view switch releaseAction { case .complete?: animationBlock = { self.contentView.frame.origin.x = 0 } completionBlock = { self.setCompleted(!self.item.completed, animated: true) } case .delete?: animationBlock = { self.alpha = 0 self.contentView.alpha = 0 self.contentView.frame.origin.x = -self.contentView.bounds.width - iconWidth self.deleteIconView.frame.origin.x = -iconWidth + self.deleteIconView.bounds.width + 20 } completionBlock = { self.presenter.delete(item: self.item) } case nil: item.completed ? textView.strike() : textView.unstrike() animationBlock = { self.contentView.frame.origin.x = 0 } completionBlock = {} } UIView.animate(withDuration: 0.2, animations: animationBlock) { _ in if self.item != nil && !self.item.isInvalidated { completionBlock() } self.doneIconView.frame.origin.x = 20 self.doneIconView.alpha = 0 self.deleteIconView.frame.origin.x = self.bounds.width - self.deleteIconView.bounds.width - 20 self.deleteIconView.alpha = 0 } } override func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool { guard let panGestureRecognizer = gestureRecognizer as? UIPanGestureRecognizer else { return false } let translation = panGestureRecognizer.translation(in: superview!) return fabs(translation.x) > fabs(translation.y) } // MARK: Reuse override func prepareForReuse() { super.prepareForReuse() alpha = 1 contentView.alpha = 1 textView.unstrike() // Force any active gesture recognizers to reset for gestureRecognizer in gestureRecognizers! { gestureRecognizer.reset() } } // MARK: Actions private func setCompleted(_ completed: Bool, animated: Bool = false) { completed ? textView.strike() : textView.unstrike() overlayView.isHidden = !completed let updateColor = { [unowned self] in self.overlayView.backgroundColor = completed ? .completeDimBackground : .completeGreenBackground self.textView.alpha = completed ? 0.3 : 1 } if animated { try! item.realm?.write { item.completed = completed } vibrate() UIView.animate(withDuration: 0.2, animations: updateColor) presenter.complete(item: item) } else { updateColor() } } // MARK: UITextViewDelegate methods func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool { if text == "\n" { textView.resignFirstResponder() return false } return true } func textViewShouldBeginEditing(_ textView: UITextView) -> Bool { // disable editing of completed to-do items return !item.completed } func textViewDidBeginEditing(_ textView: UITextView) { presenter.cellDidBeginEditing(self) } func textViewDidEndEditing(_ textView: UITextView) { let newText = textView.text.trimmingCharacters(in: .whitespacesAndNewlines) item.setPlainText(newText) { error in if let error = error { print("Failed to set text:", error) (UIApplication.shared.delegate as! AppDelegate).present(error: error as NSError) } } textView.isUserInteractionEnabled = false presenter.cellDidEndEditing(self) } func textViewDidChange(_ textView: UITextView) { presenter.cellDidChangeText(self) } } // Mark: Gesture Recognizer Reset extension UIGestureRecognizer { func reset() { isEnabled = false isEnabled = true } }
bsd-3-clause
49446cecae8b3e43fceef44577e37ee8
32.061856
125
0.605488
5.224829
false
false
false
false
LeeMZC/MZCWB
MZCWB/MZCWB/Classes/SendTwitter-发微博/Controller/MZCEditMessagePictureCollectionViewController.swift
1
4939
// // MZCEditMessagePictureCollectionViewController.swift // MZCWB // // Created by 马纵驰 on 16/8/18. // Copyright © 2016年 马纵驰. All rights reserved. // import UIKit import QorumLogs private let EditMessagePictureCell = "EditMessagePictureCell" class MZCEditMessagePictureCollectionViewController: UICollectionViewController { var images : [UIImage] = [] override func loadView() { collectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: MZCEditMessagePictureFlowLayout()) } override func viewDidLoad() { super.viewDidLoad() setupUI() } } //MARK:- private extension MZCEditMessagePictureCollectionViewController { private func setupUI(){ // 注册cell collectionView!.registerNib(UINib(nibName: "MZCEditMessagePictureCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: EditMessagePictureCell) } // 压缩图片 private func drawImage(image : UIImage, width : CGFloat) -> UIImage { // 0.获取图片的size let height = (image.size.height / image.size.width) * width let size = CGSize(width: width, height: height) // 1.开启图片上下文 UIGraphicsBeginImageContext(size) // 2.将图片画到上下文 image.drawInRect(CGRect(x: 0, y: 0, width: size.width, height: size.height)) // 3.从上下文中获取新的图片 let newImage = UIGraphicsGetImageFromCurrentImageContext() // 4.关闭上下文 UIGraphicsEndImageContext() // 5.返回新的图片 return newImage } } //MARK:- delegate extension MZCEditMessagePictureCollectionViewController : MZCEditMessagePictureDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate{ override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of items return images.count + 1 } override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> MZCEditMessagePictureCollectionViewCell { let cell = collectionView.dequeueReusableCellWithReuseIdentifier(EditMessagePictureCell, forIndexPath: indexPath) as! MZCEditMessagePictureCollectionViewCell if images.count == indexPath.item { cell.img = nil }else { cell.img = images[indexPath.item] } cell.delegate = self return cell } func openPicture() { guard UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.PhotoLibrary) else { print("照片源不可用") return } // 2.创建照片选择控制器 let ipc = UIImagePickerController() // 3.设置照片源 ipc.sourceType = .PhotoLibrary // 4.设置代理 ipc.delegate = self // 5.弹出照片选择控制器 presentViewController(ipc, animated: true, completion: nil) } func deletePicture(cell: MZCEditMessagePictureCollectionViewCell) { } func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) { // 1.获取选择的照片 let image = info["UIImagePickerControllerOriginalImage"] as! UIImage // 2.退出控制器 picker.dismissViewControllerAnimated(true, completion: nil) // 3.用collectionView显示照片 // 3.0.压缩照片 let newImage = drawImage(image, width: 450) // 3.1.将照片存放到数组中 images.append(newImage) // 3.2.刷新表格 collectionView?.reloadData() } } private let MZCPictureCol : CGFloat = 3 class MZCEditMessagePictureFlowLayout: UICollectionViewFlowLayout { // 准备布局 override func prepareLayout() { // 1.设置每个cell的尺寸 let wh = (MZCScreenSize.width - MZCMargin * (MZCPictureCol + 1)) / MZCPictureCol itemSize = CGSizeMake(wh, wh) // 2.设置cell之间的间隙 minimumInteritemSpacing = MZCMargin minimumLineSpacing = MZCMargin //设置CollectionView内边距 sectionInset = UIEdgeInsetsMake(MZCMargin, MZCMargin, 0, MZCMargin) // 3.设置滚动方向 // scrollDirection = UICollectionViewScrollDirection.Horizontal scrollDirection = UICollectionViewScrollDirection.Vertical // 5.禁用回弹 collectionView?.bounces = false // 6.取出滚动条 collectionView?.showsHorizontalScrollIndicator = false collectionView?.showsVerticalScrollIndicator = false } }
artistic-2.0
d682c03ecf1d75411d6c8e82a28d1307
29.993289
165
0.652014
5.159777
false
false
false
false
crazypoo/PTools
Pods/FluentDarkModeKit/Sources/FluentDarkModeKit/Extensions/UIView+DarkModeKit.swift
1
1041
// // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // extension UIView { static let swizzleWillMoveToWindowOnce: Void = { if #available(iOS 13.0, *) { return } else { let selector = #selector(willMove(toWindow:)) guard let method = class_getInstanceMethod(UIView.self, selector) else { assertionFailure(DarkModeManager.messageForSwizzlingFailed(class: UIView.self, selector: selector)) return } let imp = method_getImplementation(method) class_replaceMethod(UIView.self, selector, imp_implementationWithBlock({ (self: UIView, window: UIWindow?) -> Void in let oldIMP = unsafeBitCast(imp, to: (@convention(c) (UIView, Selector, UIWindow?) -> Void).self) oldIMP(self, selector, window) if window != nil { self.dm_updateDynamicColors() self.dm_updateDynamicImages() } } as @convention(block) (UIView, UIWindow?) -> Void), method_getTypeEncoding(method)) } }() }
mit
4db5a742a58e0c6e0c5f5e011310edc7
34.896552
123
0.6561
4.266393
false
false
false
false
Marquis103/FitJourney
FitJourney/DiaryEntryAlert.swift
1
1223
// // DiaryEntryAlert.swift // FitJourney // // Created by Marquis Dennis on 4/26/16. // Copyright © 2016 Marquis Dennis. All rights reserved. // import UIKit class DiaryEntryAlert: UIAlertController { static func getUIDiaryAlert(withTitle title:String, message:String) -> DiaryEntryAlert{ let alert = DiaryEntryAlert(title: title, message: message, preferredStyle: .Alert) let action = UIAlertAction(title: "OK", style: .Default, handler: nil) alert.addAction(action) return alert } /*static func getUIDiaryActionSheet(withTitle title:String, message:String?) -> DiaryEntryAlert { let actionSheet = DiaryEntryAlert(title: title:, message: message, preferredStyle: .ActionSheet) let cameraAction = UIAlertAction(title: "Camera", style: .Default) { (action) in promptForCamera() } let photosAction = UIAlertAction(title: "Photo Roll", style: .Default) { (action) in promptForPhotoLibrary() } let cancelAction = UIAlertAction(title: "Cancel", style: .Cancel) { (action) in } actionSheet.addAction(cameraAction) actionSheet.addAction(photosAction) actionSheet.addAction(cancelAction) presentViewController(actionSheet, animated: true, completion: nil) }*/ }
gpl-3.0
e411d508d80166f5a7f712d775ce1c3e
29.55
98
0.733224
3.842767
false
false
false
false
ospr/UIPlayground
UIPlayground/MasterViewController.swift
1
2995
// // MasterViewController.swift // UIPlayground // // Created by Kip Nicol on 8/7/16. // Copyright © 2016 Kip Nicol. All rights reserved. // import UIKit import UIPlaygroundUI class MasterViewController: UITableViewController { var catalogItems: [CatalogItem] = [ .powerOff, .appCards, .springBoard, ] override func viewDidLoad() { super.viewDidLoad() splitViewController?.presentsWithGesture = false let catalogItem = catalogItems[0] updateDetailView(withCatalogItem: catalogItem) } override func viewWillAppear(_ animated: Bool) { clearsSelectionOnViewWillAppear = splitViewController!.isCollapsed super.viewWillAppear(animated) } // MARK: - Table View override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return catalogItems.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) let catalogItem = catalogItems[indexPath.row] cell.textLabel?.text = catalogItem.viewController().title return cell } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let catalogItem = catalogItems[indexPath.row] updateDetailView(withCatalogItem: catalogItem) } // MARK: - Working with Detail View func updateDetailView(withCatalogItem catalogItem: CatalogItem) { guard let splitViewController = splitViewController else { assertionFailure("splitViewController unexpectedly nil.") return } let nextViewController = catalogItem.viewController() let detailNavigationController = splitViewController.viewControllers.last as! UINavigationController if splitViewController.isCollapsed { detailNavigationController.pushViewController(nextViewController, animated: true) } else { detailNavigationController.setViewControllers([nextViewController], animated: false) } nextViewController.edgesForExtendedLayout = UIRectEdge() nextViewController.navigationItem.leftBarButtonItem = splitViewController.displayModeButtonItem nextViewController.navigationItem.leftItemsSupplementBackButton = true } } extension MasterViewController { enum CatalogItem { case powerOff case appCards case springBoard func viewController() -> UIViewController { switch self { case .powerOff: return PowerOffViewController() case .appCards: return AppCardsViewController() case .springBoard: return SpringBoardViewController() } } } }
mit
dba9d8803a69847967a89ffeced54201
29.55102
109
0.661991
6.024145
false
false
false
false
richardpiazza/XCServerCoreData
Sources/NSManagedObject+XCServerCoreData.swift
1
793
import Foundation import CoreData extension NSManagedObject { public static var entityName: String { var entityName = NSStringFromClass(self) if let lastPeriodRange = entityName.range(of: ".", options: NSString.CompareOptions.backwards, range: nil, locale: nil) { let range = lastPeriodRange.upperBound..<entityName.endIndex entityName = String(entityName[range]) } return entityName } public convenience init?(managedObjectContext context: NSManagedObjectContext) { guard let entityDescription = NSEntityDescription.entity(forEntityName: type(of: self).entityName, in: context) else { return nil } self.init(entity: entityDescription, insertInto: context) } }
mit
67d9f30b157ba61d11d0f07bddeed860
35.045455
129
0.67087
5.468966
false
false
false
false
MrZoidberg/metapp
metapp/Pods/RealmSwift/RealmSwift/Util.swift
26
7163
//////////////////////////////////////////////////////////////////////////// // // Copyright 2015 Realm Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////// import Foundation import Realm // MARK: Internal Helpers internal func notFoundToNil(index: UInt) -> Int? { if index == UInt(NSNotFound) { return nil } return Int(index) } #if swift(>=3.0) internal func throwRealmException(_ message: String, userInfo: [AnyHashable: Any]? = nil) { NSException(name: NSExceptionName(rawValue: RLMExceptionName), reason: message, userInfo: userInfo).raise() } internal func throwForNegativeIndex(_ int: Int, parameterName: String = "index") { if int < 0 { throwRealmException("Cannot pass a negative value for '\(parameterName)'.") } } internal func gsub(pattern: String, template: String, string: String, error: NSErrorPointer = nil) -> String? { let regex = try? NSRegularExpression(pattern: pattern, options: []) return regex?.stringByReplacingMatches(in: string, options: [], range: NSRange(location: 0, length: string.utf16.count), withTemplate: template) } extension Object { // Must *only* be used to call Realm Objective-C APIs that are exposed on `RLMObject` // but actually operate on `RLMObjectBase`. Do not expose cast value to user. internal func unsafeCastToRLMObject() -> RLMObject { return unsafeBitCast(self, to: RLMObject.self) } } // MARK: CustomObjectiveCBridgeable internal func dynamicBridgeCast<T>(fromObjectiveC x: Any) -> T { if let BridgeableType = T.self as? CustomObjectiveCBridgeable.Type { return BridgeableType.bridging(objCValue: x) as! T } else { return x as! T } } internal func dynamicBridgeCast<T>(fromSwift x: T) -> Any { if let x = x as? CustomObjectiveCBridgeable { return x.objCValue } else { return x } } // Used for conversion from Objective-C types to Swift types internal protocol CustomObjectiveCBridgeable { /* FIXME: Remove protocol once SR-2393 bridges all integer types to `NSNumber` * At this point, use `as! [SwiftType]` to cast between. */ static func bridging(objCValue: Any) -> Self var objCValue: Any { get } } extension Int8: CustomObjectiveCBridgeable { static func bridging(objCValue: Any) -> Int8 { return (objCValue as! NSNumber).int8Value } var objCValue: Any { return NSNumber(value: self) } } extension Int16: CustomObjectiveCBridgeable { static func bridging(objCValue: Any) -> Int16 { return (objCValue as! NSNumber).int16Value } var objCValue: Any { return NSNumber(value: self) } } extension Int32: CustomObjectiveCBridgeable { static func bridging(objCValue: Any) -> Int32 { return (objCValue as! NSNumber).int32Value } var objCValue: Any { return NSNumber(value: self) } } extension Int64: CustomObjectiveCBridgeable { static func bridging(objCValue: Any) -> Int64 { return (objCValue as! NSNumber).int64Value } var objCValue: Any { return NSNumber(value: self) } } extension Optional: CustomObjectiveCBridgeable { static func bridging(objCValue: Any) -> Optional { if objCValue is NSNull { return nil } else { return .some(dynamicBridgeCast(fromObjectiveC: objCValue)) } } var objCValue: Any { if let value = self { return value } else { return NSNull() } } } #else internal func throwRealmException(message: String, userInfo: [String:AnyObject] = [:]) { NSException(name: RLMExceptionName, reason: message, userInfo: userInfo).raise() } internal func throwForNegativeIndex(int: Int, parameterName: String = "index") { if int < 0 { throwRealmException("Cannot pass a negative value for '\(parameterName)'.") } } internal func gsub(pattern: String, template: String, string: String, error: NSErrorPointer = nil) -> String? { let regex = try? NSRegularExpression(pattern: pattern, options: []) return regex?.stringByReplacingMatchesInString(string, options: [], range: NSRange(location: 0, length: string.utf16.count), withTemplate: template) } extension Object { // Must *only* be used to call Realm Objective-C APIs that are exposed on `RLMObject` // but actually operate on `RLMObjectBase`. Do not expose cast value to user. internal func unsafeCastToRLMObject() -> RLMObject { return unsafeBitCast(self, RLMObject.self) } } // MARK: CustomObjectiveCBridgeable internal func dynamicBridgeCast<T>(fromObjectiveC x: AnyObject) -> T { if let BridgeableType = T.self as? CustomObjectiveCBridgeable.Type { return BridgeableType.bridging(objCValue: x) as! T } else { return x as! T } } internal func dynamicBridgeCast<T>(fromSwift x: T) -> AnyObject { if let x = x as? CustomObjectiveCBridgeable { return x.objCValue } else { return x as! AnyObject } } // Used for conversion from Objective-C types to Swift types internal protocol CustomObjectiveCBridgeable { /* FIXME: Remove protocol once SR-2393 bridges all integer types to `NSNumber` * At this point, use `as! [SwiftType]` to cast between. */ static func bridging(objCValue objCValue: AnyObject) -> Self var objCValue: AnyObject { get } } extension Int8: CustomObjectiveCBridgeable { static func bridging(objCValue objCValue: AnyObject) -> Int8 { return (objCValue as! NSNumber).charValue } var objCValue: AnyObject { return NSNumber(char: self) } } extension Int16: CustomObjectiveCBridgeable { static func bridging(objCValue objCValue: AnyObject) -> Int16 { return (objCValue as! NSNumber).shortValue } var objCValue: AnyObject { return NSNumber(short: self) } } extension Int32: CustomObjectiveCBridgeable { static func bridging(objCValue objCValue: AnyObject) -> Int32 { return (objCValue as! NSNumber).intValue } var objCValue: AnyObject { return NSNumber(int: self) } } extension Int64: CustomObjectiveCBridgeable { static func bridging(objCValue objCValue: AnyObject) -> Int64 { return (objCValue as! NSNumber).longLongValue } var objCValue: AnyObject { return NSNumber(longLong: self) } } #endif
mpl-2.0
44242482de36c069008ad2022cdec6cd
31.707763
111
0.650705
4.476875
false
false
false
false
svenbacia/TraktKit
TraktKit/Sources/Resource/Generic/Resource+Factory.swift
1
1462
// // Resource+Factory.swift // TraktKit // // Created by Sven Bacia on 29.10.17. // Copyright © 2017 Sven Bacia. All rights reserved. // import Foundation func buildResource<T: Decodable>(base: String, path: String, params: [String: Any]? = nil, method: Method = .get, decoder: JSONDecoder = .trakt) -> Resource<T> { return Resource(request: buildRequest(base: base, path: path, params: params, method: method), decoder: decoder, parseHandler: parseDecodable) } func buildResource<T>(base: String, path: String, params: [String: Any]? = nil, method: Method = .get, parse: @escaping (Data, JSONDecoder?) throws -> T) -> Resource<T> { return Resource(request: buildRequest(base: base, path: path, params: params, method: method), parseHandler: parse) } func buildResource(base: String, path: String, body: String, method: Method) -> Resource<Any> { return Resource(request: buildRequest(base: base, path: path, params: nil, body: body.data(using: .utf8), method: method), parseHandler: parseJSON) } func buildResource(base: String, path: String, params: [String: Any]? = nil, method: Method = .get) -> Resource<Any> { return buildResource(base: base, path: path, params: params, method: method, parse: parseJSON) } func buildResource(base: String, path: String, params: [String: Any]? = nil, method: Method = .get) -> Resource<Data> { return buildResource(base: base, path: path, params: params, method: method, parse: parseData) }
mit
164c071899e902f628d80dd671f64e33
49.37931
170
0.704997
3.520482
false
false
false
false
ahmetabdi/SwiftCrunch
Crunch/GameScene.swift
1
8125
// // GameScene.swift // Crunch // // Created by Ahmet Abdi on 29/09/2014. // Copyright (c) 2014 Ahmet Abdi. All rights reserved. // import SpriteKit class GameScene: SKScene { var level: Level! let TileWidth: CGFloat = 32.0 let TileHeight: CGFloat = 36.0 let gameLayer = SKNode() let cookiesLayer = SKNode() let tilesLayer = SKNode() var swipeFromColumn: Int? var swipeFromRow: Int? var swipeHandler: ((Swap) -> ())? var selectionSprite = SKSpriteNode() let swapSound = SKAction.playSoundFileNamed("Chomp.wav", waitForCompletion: false) let invalidSwapSound = SKAction.playSoundFileNamed("Error.wav", waitForCompletion: false) let matchSound = SKAction.playSoundFileNamed("Ka-Ching.wav", waitForCompletion: false) let fallingCookieSound = SKAction.playSoundFileNamed("Scrape.wav", waitForCompletion: false) let addCookieSound = SKAction.playSoundFileNamed("Drip.wav", waitForCompletion: false) required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setup() } override init(size: CGSize) { super.init(size: size) setup() } func showSelectionIndicatorForCookie(cookie: Cookie) { if selectionSprite.parent != nil { selectionSprite.removeFromParent() } if let sprite = cookie.sprite { let texture = SKTexture(imageNamed: cookie.cookieType.highlightedSpriteName) selectionSprite.size = texture.size() selectionSprite.runAction(SKAction.setTexture(texture)) sprite.addChild(selectionSprite) selectionSprite.alpha = 1.0 } } func hideSelectionIndicator() { selectionSprite.runAction(SKAction.sequence([ SKAction.fadeOutWithDuration(0.3), SKAction.removeFromParent()])) } func setup() { anchorPoint = CGPoint(x: 0.5, y: 0.5) let background = SKSpriteNode(imageNamed: "Background") addChild(background) addChild(gameLayer) let layerPosition = CGPoint( x: -TileWidth * CGFloat(NumColumns) / 2, y: -TileHeight * CGFloat(NumRows) / 2) cookiesLayer.position = layerPosition tilesLayer.position = layerPosition gameLayer.addChild(tilesLayer) gameLayer.addChild(cookiesLayer) swipeFromColumn = nil swipeFromRow = nil } override func touchesBegan(touches: NSSet, withEvent event: UIEvent) { // 1 let touch = touches.anyObject() as UITouch let location = touch.locationInNode(cookiesLayer) // 2 let (success, column, row) = convertPoint(location) if success { // 3 if let cookie = level.cookieAtColumn(column, row: row) { // 4 showSelectionIndicatorForCookie(cookie) swipeFromColumn = column swipeFromRow = row } } } override func touchesMoved(touches: NSSet, withEvent event: UIEvent) { // 1 if swipeFromColumn == nil { return } // 2 let touch = touches.anyObject() as UITouch let location = touch.locationInNode(cookiesLayer) let (success, column, row) = convertPoint(location) if success { // 3 var horzDelta = 0, vertDelta = 0 if column < swipeFromColumn! { // swipe left horzDelta = -1 } else if column > swipeFromColumn! { // swipe right horzDelta = 1 } else if row < swipeFromRow! { // swipe down vertDelta = -1 } else if row > swipeFromRow! { // swipe up vertDelta = 1 } // 4 if horzDelta != 0 || vertDelta != 0 { trySwapHorizontal(horzDelta, vertical: vertDelta) hideSelectionIndicator() // 5 swipeFromColumn = nil } } } override func touchesEnded(touches: NSSet, withEvent event: UIEvent) { if selectionSprite.parent != nil && swipeFromColumn != nil { hideSelectionIndicator() } swipeFromColumn = nil swipeFromRow = nil } override func touchesCancelled(touches: NSSet, withEvent event: UIEvent) { touchesEnded(touches, withEvent: event) } func animateSwap(swap: Swap, completion: () -> ()) { let spriteA = swap.cookieA.sprite! let spriteB = swap.cookieB.sprite! spriteA.zPosition = 100 spriteB.zPosition = 90 let Duration: NSTimeInterval = 0.3 let moveA = SKAction.moveTo(spriteB.position, duration: Duration) moveA.timingMode = .EaseOut spriteA.runAction(moveA, completion: completion) let moveB = SKAction.moveTo(spriteA.position, duration: Duration) moveB.timingMode = .EaseOut spriteB.runAction(moveB) runAction(swapSound) } func trySwapHorizontal(horzDelta: Int, vertical vertDelta: Int) { // 1 let toColumn = swipeFromColumn! + horzDelta let toRow = swipeFromRow! + vertDelta // 2 if toColumn < 0 || toColumn >= NumColumns { return } if toRow < 0 || toRow >= NumRows { return } // 3 if let toCookie = level.cookieAtColumn(toColumn, row: toRow) { if let fromCookie = level.cookieAtColumn(swipeFromColumn!, row: swipeFromRow!) { // 4 if let handler = swipeHandler { let swap = Swap(cookieA: fromCookie, cookieB: toCookie) handler(swap) } } } } func animateInvalidSwap(swap: Swap, completion: () -> ()) { let spriteA = swap.cookieA.sprite! let spriteB = swap.cookieB.sprite! spriteA.zPosition = 100 spriteB.zPosition = 90 let Duration: NSTimeInterval = 0.2 let moveA = SKAction.moveTo(spriteB.position, duration: Duration) moveA.timingMode = .EaseOut let moveB = SKAction.moveTo(spriteA.position, duration: Duration) moveB.timingMode = .EaseOut spriteA.runAction(SKAction.sequence([moveA, moveB]), completion: completion) spriteB.runAction(SKAction.sequence([moveB, moveA])) runAction(invalidSwapSound) } func convertPoint(point: CGPoint) -> (success: Bool, column: Int, row: Int) { if point.x >= 0 && point.x < CGFloat(NumColumns)*TileWidth && point.y >= 0 && point.y < CGFloat(NumRows)*TileHeight { return (true, Int(point.x / TileWidth), Int(point.y / TileHeight)) } else { return (false, 0, 0) // invalid location } } func addTiles() { for row in 0..<NumRows { for column in 0..<NumColumns { if let tile = level.tileAtColumn(column, row: row) { let tileNode = SKSpriteNode(imageNamed: "Tile") tileNode.position = pointForColumn(column, row: row) tilesLayer.addChild(tileNode) } } } } func addSpritesForCookies(cookies: Set<Cookie>) { for cookie in cookies { let sprite = SKSpriteNode(imageNamed: cookie.cookieType.spriteName) sprite.position = pointForColumn(cookie.column, row:cookie.row) cookiesLayer.addChild(sprite) cookie.sprite = sprite } } func pointForColumn(column: Int, row: Int) -> CGPoint { return CGPoint( x: CGFloat(column)*TileWidth + TileWidth/2, y: CGFloat(row)*TileHeight + TileHeight/2) } override func update(currentTime: CFTimeInterval) { /* Called before each frame is rendered */ } }
mit
fea8447cd2d973d50109d33ccaf8bdf0
32.29918
96
0.570092
4.951249
false
false
false
false
mleiv/MEGameTracker
MEGameTracker/Views/Common/Data Rows/Description/DescriptionType.swift
1
1707
// // DescriptionType.swift // MEGameTracker // // Created by Emily Ivie on 5/27/16. // Copyright © 2016 urdnot. All rights reserved. // import UIKit public struct DescriptionType: TextDataRowType { public typealias RowType = TextDataRow var view: RowType? { return row } public var row: TextDataRow? public var controller: Describable? public var text: String? { if UIWindow.isInterfaceBuilder { // swiftlint:disable line_length return "Dr Mordin Solus is a Salarian biological weapons expert whose technology may hold the key to countering Collector attacks. He is currently operation out of a medical clinic in the slums of Omega." // swiftlint:enable line_length } else { return controller?.descriptionMessage } } public var paddingSides: CGFloat = 15.0 let defaultPaddingTop: CGFloat = 2.0 let defaultPaddingBottom: CGFloat = 10.0 var didSetup: Bool = false public var linkOriginController: UIViewController? { return controller as? UIViewController } var viewController: UIViewController? { return controller as? UIViewController } public init() {} public init(controller: Describable, view: TextDataRow?) { self.controller = controller self.row = view } public mutating func setupView() { setupView(type: RowType.self) } public mutating func setup(view: UIView?) { guard let view = view as? RowType else { return } if UIWindow.isInterfaceBuilder || !didSetup { if view.noPadding == true { view.setPadding(top: 2.0, right: 0, bottom: 2.0, left: 0) } else { view.setPadding( top: defaultPaddingTop, right: paddingSides, bottom: defaultPaddingBottom, left: paddingSides ) } } didSetup = true } }
mit
64d54318acd3b1e5e4d506a8e1f38fbd
26.079365
207
0.720985
3.700651
false
false
false
false
tidepool-org/nutshell-ios
Nutshell/GraphView/GraphUIView.swift
1
5430
/* * Copyright (c) 2015, Tidepool Project * * This program is free software; you can redistribute it and/or modify it under * the terms of the associated License, which is identical to the BSD 2-Clause * License as published by the Open Source Initiative at opensource.org. * * 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 License for more details. * * You should have received a copy of the License along with this program; if * not, you can obtain one from Tidepool Project at tidepool.org. */ import UIKit class GraphUIView: UIView { var layout: GraphLayout fileprivate var graphUtils: GraphingUtils fileprivate var viewSize: CGSize = CGSize.zero fileprivate var graphLayers: [GraphDataLayer] = [] fileprivate var tileIndex: Int fileprivate var cursorView: UIImageView? /// After init, call configure to create the graph. /// /// - parameter startTime: /// The time at the origin of the X axis of the graph. /// /// - parameter timeIntervalForView: /// The time span covered by the graph /// /// - parameter layout: /// Provides the various graph layers and layout parameters for drawing them. init(frame: CGRect, startTime: Date, layout: GraphLayout, tileIndex: Int) { self.viewSize = frame.size self.cellStartTime = startTime self.cellTimeInterval = layout.cellTimeInterval self.layout = layout self.tileIndex = tileIndex self.graphUtils = layout.graphUtilsForTimeInterval(layout.cellTimeInterval, startTime: startTime) super.init(frame: frame) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } /// Graph set up /// /// Queries the core database for relevant events in the specified timeframe, and creates the graph view with that data. func configure() { graphLayers = layout.graphLayers(viewSize, timeIntervalForView: cellTimeInterval, startTime: cellStartTime, tileIndex: tileIndex) graphData() } override func layoutSubviews() { //NSLog("GraphUIView layoutSubviews size: \(self.bounds.size)") } func updateViewSize(_ newSize: CGSize) { // Quick way to update when data haven't changed... let currentSize = self.bounds.size NSLog("GraphUIView bounds: \(currentSize), size: \(viewSize), new size \(newSize)") if self.viewSize == newSize { //NSLog("updateViewSize skipped!") return } self.viewSize = newSize graphUtils.updateViewSize(newSize) for layer in graphLayers { layer.updateViewSize(newSize) } graphData() } /// Handle taps within this graph tile by letting layers check for hits - iterates thru layers in reverse order of drawing, last layer first. If a data point is found at the tap location, it is returned, otherwise nil. func tappedAtPoint(_ point: CGPoint) -> GraphDataType? { var layer = graphLayers.count while layer > 0 { if let dataPoint = graphLayers[layer-1].tappedAtPoint(point) { return dataPoint } layer -= 1 } return nil } /// Update cursor in view if cursor time range overlaps view, otherwise remove any cursor layer. Pass nil to remove. // TODO: If cursor image already exists, just adjust view offset rather than redraw? Probably not worth it if this is just adjusted once a second. func updateCursorView(_ cursorTime: Date?, cursorColor: UIColor) { if cursorView != nil { cursorView!.removeFromSuperview() cursorView = nil } if let cursorTime = cursorTime { let graphCursorLayer = GraphCursorLayer(viewSize: self.viewSize, timeIntervalForView: cellTimeInterval, startTime: cellStartTime, cursorTime: cursorTime) cursorView = graphCursorLayer.imageView(cursorColor) if cursorView != nil { addSubview(cursorView!) } } } // // MARK: - Private data // var cellStartTime: Date var cellTimeInterval: TimeInterval // // MARK: - Private funcs // fileprivate func graphData() { // At this point data should be loaded, and we just need to plot the data // First remove any previously graphed data in case this is a resizing.. let views = self.subviews for view in views { view.removeFromSuperview() } let xAxisImage = graphUtils.imageOfXAxisHeader() if let xAxisImage = xAxisImage { let xAxisImageView = UIImageView(image:xAxisImage) addSubview(xAxisImageView) } // first load the data for all the layers in case there is any data inter-dependency for dataLayer in graphLayers { dataLayer.loadDataItems() } // then draw each layer, and add non-empty layers as subviews for dataLayer in graphLayers { let imageView = dataLayer.imageView() if imageView != nil { addSubview(imageView!) } } // add optional cursor layer... } }
bsd-2-clause
d59fac12d9fbc47a394a5d1d7fde8a5c
35.442953
222
0.643462
4.922937
false
false
false
false
EventsNetwork/Source
LetsTravel/MyTourCell.swift
1
1296
// // MyTourCell.swift // LetsTravel // // Created by TriNgo on 4/26/16. // Copyright © 2016 TriNgo. All rights reserved. // import UIKit class MyTourCell: UITableViewCell { @IBOutlet weak var posterView: UIImageView! @IBOutlet weak var tourName: UILabel! @IBOutlet weak var tourDay: UILabel! @IBOutlet weak var tourStart: UILabel! var tour:Tour? { didSet{ if let t = tour{ tourName.text = t.provinceName! tourDay.text = "\(t.totalDay!) days" if t.startTime > 0 { tourStart.text = Utils.dateTotring(NSDate(timeIntervalSince1970: Double(t.startTime!)), format: "dd/MM/yyyy") } else{ tourStart.text = "---" } posterView.setImageWithURL(NSURL(string: t.imageUrls![0] as String)!, placeholderImage: UIImage(named: "placeholder")) } } } override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }
apache-2.0
514431414b9fe0e01b158559f311a15d
25.428571
134
0.553668
4.480969
false
false
false
false
zgtios/HQPhotoLock
PhotoLock/Application/Defaults.swift
2
7910
// // Defaults.swift // Eleven // // Created by 泉华 官 on 14/11/13. // Copyright (c) 2014年 CQMH. All rights reserved. // import Foundation import UIKit // AppID let HQAppID = "952647119" let UMAppKey = "557a45af67e58edb8b000962" var SharingTimes = Int(0) let SharingTimesNeededForHideAD = Int(5) // 数据库操作者 let DBMasterKey = BaseDBMasterKey(); // Segue Identifier let SegueIdentifierGoSettings = "goSettings" let SegueIdentifierShowAlbum = "showAlbum" let SegueIdentifierShowMainMenu = "showMainMenu" let SegueIdentifierShowPhotos = "showPhotos" let EmptyAlbumIconName = "" let MinPixelsForTiling:CGFloat = 1000 * 1000// 图片长宽超过该值时需要分片 let TileSize:CGFloat = 600// 分片宽度和高度 let TiledSuffix = "tiled" let PlaceholderSuffix = "_Placeholder" // 密码界面是否显示 var passwordInterfaceShown = false var authenticationViewController: AuthenticationViewController! /* please change this value to a 16 length string e.g. let passwordForEncryptPassword = "1234567890123456" */ let passwordForEncryptPassword = passwordForEncryptPasswordDefault // 图片和缩略图的存储文件夹路径 let PictureFoldPath = (NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.LibraryDirectory, NSSearchPathDomainMask.UserDomainMask, true).first as! String).stringByAppendingPathComponent("picture") let ThumbnailFoldPath = (NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.LibraryDirectory, NSSearchPathDomainMask.UserDomainMask, true).first as! String).stringByAppendingPathComponent("thumbnail") let PlaceholderFoldPath = (NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.LibraryDirectory, NSSearchPathDomainMask.UserDomainMask, true).first as! String).stringByAppendingPathComponent("placeholder") let FileSharingFoldPath = (NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).first as! String) let PictureFoldPathTemp = NSTemporaryDirectory().stringByAppendingPathComponent("picture") let ThumbnailFoldPathTemp = NSTemporaryDirectory().stringByAppendingPathComponent("thumbnail") let PlaceholderFoldPathTemp = NSTemporaryDirectory().stringByAppendingPathComponent("placeholder") extension UIColor { class func randomColor(alpha:CGFloat = 0.09) -> UIColor{ var randomRed:CGFloat = CGFloat(drand48()) var randomGreen:CGFloat = CGFloat(drand48()) var randomBlue:CGFloat = CGFloat(drand48()) return UIColor(red: randomRed, green: randomGreen, blue: randomBlue, alpha: alpha) } } extension UIImage { func imageWithInRect(rect: CGRect) -> UIImage { let origin = CGPointMake(-rect.origin.x, -rect.origin.y) UIGraphicsBeginImageContext(CGSizeMake(rect.size.width, rect.size.height)) self .drawAtPoint(origin) let img = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return img } func tileImagesWithTileSize(size: CGSize) -> [[UIImage]] { var imagess = [[UIImage]](); var point = CGPoint(x: 0, y: 0) let imageBound = CGRectMake(0, 0, self.size.width, self.size.height) while imageBound.contains(point) { var images = [UIImage]() while imageBound.contains(point) { let rect = CGRectMake(point.x, point.y, size.width, size.height) images.append(self.imageWithInRect(rect)) point.x += size.width } imagess.append(images) point.x = 0 point.y += size.height } return imagess } } func placeholderFromPhoto(photo:Photo) -> UIImage? { var placeholderData = NSData(contentsOfFile: PlaceholderFoldPath.stringByAppendingPathComponent(photo.originalFilename + PlaceholderSuffix)) placeholderData = placeholderData?.decryptAndDcompress(placeholderData) return placeholderData == nil ? nil : UIImage(data: placeholderData!)! } func thumbnailFromPhoto(photo:Photo) -> UIImage? { var thumbnailData = NSData(contentsOfFile: ThumbnailFoldPath.stringByAppendingPathComponent(photo.thumbnailFilename)) thumbnailData = thumbnailData?.decryptAndDcompress(thumbnailData) return thumbnailData == nil ? nil : UIImage(data: thumbnailData!)! } func pictureFromPhoto(photo:Photo) -> UIImage? { var pictureData: NSData? autoreleasepool { () -> () in pictureData = NSData(contentsOfFile: PictureFoldPath.stringByAppendingPathComponent(photo.originalFilename)) pictureData = pictureData?.decryptAndDcompress(pictureData) } return pictureData == nil ? nil : UIImage(data: pictureData!)! } // 是否隐藏广告 var HideAD = false // AdMob let AdMob = HQAdMob() // BannerAdUnitID for AdMob private let BannerAdUnitID = "ca-app-pub-6958627927268333/2853184404" // IntersititialAdUnitID for AdMob private let IntersititialAdUnitID = "ca-app-pub-6958627927268333/6289898001" class HQAdMob: NSObject, GADBannerViewDelegate, GADInterstitialDelegate { // MARK: - Banner AD private var actionAfterBannerADClicked:(() -> Void)? // Banner Ad func showBannerAdInView(bannerView: GADBannerView!, inViewController viewController: UIViewController!, theActionAfterBannerADClicked:(() -> Void)? = nil) { // after clicking AD actionAfterBannerADClicked = theActionAfterBannerADClicked // ad unit ID bannerView.adUnitID = BannerAdUnitID bannerView.rootViewController = viewController bannerView.delegate = self let request = GADRequest() // Requests test ads on devices you specify. Your test device ID is printed to the console when // an ad request is made. //request.testDevices = NSArray(array: [GAD_SIMULATOR_ID/*, "5041a084760bfe83b6701fa480ea3756"*/]) bannerView.loadRequest(request) } // MARK: - GADBannerViewDelegate func adViewWillLeaveApplication(adView: GADBannerView!) { actionAfterBannerADClicked?() } // MARK: - Interstitial AD private var interstitial:GADInterstitial! private var actionAfterInterstitialADClicked:(() -> Void)? func createAndLoadInterstitial(theActionAfterInterstitialADClicked:(() -> Void)? = nil) -> GADInterstitial{ interstitial = GADInterstitial(adUnitID:IntersititialAdUnitID) interstitial.delegate = self interstitial.loadRequest(GADRequest()) return interstitial } func showInterstitialIfReadyFromViewController(fromViewController: UIViewController) -> Bool { if interstitial == nil { createAndLoadInterstitial() } if interstitial.isReady { interstitial.presentFromRootViewController(fromViewController) return true } return false } // MARK: - GADInterstitialDelegate func interstitialDidDismissScreen(ad: GADInterstitial!) { createAndLoadInterstitial() } func interstitialWillLeaveApplication(ad: GADInterstitial!) { actionAfterInterstitialADClicked?() } } // MARK: Settings func loadData() { // 读取配置 // HideAD let ha: AnyObject? = NSUserDefaults.standardUserDefaults().objectForKey("HideAD") if ha != nil { HideAD = (ha as! Bool) } // SharingTimes let st: AnyObject? = NSUserDefaults.standardUserDefaults().objectForKey("SharingTimes") if st != nil { SharingTimes = (st as! Int) } } func saveData() { // 保存配置 // HideAD NSUserDefaults.standardUserDefaults().setObject(HideAD, forKey: "HideAD") // SharingTimes NSUserDefaults.standardUserDefaults().setObject(SharingTimes, forKey: "SharingTimes") // 写入磁盘 NSUserDefaults.standardUserDefaults().synchronize() }
mit
4016cae62f3166c344990af3dd55e78d
34.806452
211
0.714157
4.723404
false
false
false
false
CSullivan102/LearnApp
LearnKit/TableViewAdapters/FetchedResultsTableDataSource.swift
1
3774
// // FetchedResultsTableDataSource.swift // Learn // // Created by Christopher Sullivan on 9/8/15. // Copyright © 2015 Christopher Sullivan. All rights reserved. // import UIKit import CoreData public class FetchedResultsTableDataSource<D: FetchedResultsTableDataSourceDelegate>: NSObject, UITableViewDataSource, NSFetchedResultsControllerDelegate { public let fetchedResultsController: NSFetchedResultsController let tableView: UITableView let delegate: D public required init(tableView: UITableView, fetchedResultsController: NSFetchedResultsController, delegate: D) { self.tableView = tableView self.fetchedResultsController = fetchedResultsController self.delegate = delegate super.init() fetchedResultsController.delegate = self tableView.dataSource = self try! fetchedResultsController.performFetch() tableView.reloadData() } public func refreshData() { try! fetchedResultsController.performFetch() tableView.reloadData() } public func controller(controller: NSFetchedResultsController, didChangeObject anObject: AnyObject, atIndexPath indexPath: NSIndexPath?, forChangeType type: NSFetchedResultsChangeType, newIndexPath: NSIndexPath?) { tableView.beginUpdates() switch type { case .Delete: guard let unwrappedIndexPath = indexPath else { return } tableView.deleteRowsAtIndexPaths([unwrappedIndexPath], withRowAnimation: .Right) case .Insert: guard let unwrappedIndexPath = indexPath else { return } tableView.insertRowsAtIndexPaths([unwrappedIndexPath], withRowAnimation: .Right) case .Update: guard let unwrappedIndexPath = indexPath, cell = tableView.cellForRowAtIndexPath(unwrappedIndexPath) as? D.Cell, object = anObject as? D.Object else { return } delegate.configureCell(cell, object: object) case .Move: guard let unwrappedOldIndexPath = indexPath, unwrappedNewIndexPath = newIndexPath else { return } tableView.deleteRowsAtIndexPaths([unwrappedOldIndexPath], withRowAnimation: .Right) tableView.insertRowsAtIndexPaths([unwrappedNewIndexPath], withRowAnimation: .Right) } tableView.endUpdates() } public func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { guard let sec = fetchedResultsController.sections?[section] else { return 0 } return sec.numberOfObjects } public func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let obj = objectAtIndexPath(indexPath) let identifier = delegate.cellIdentifierForObject(obj) guard let cell = tableView.dequeueReusableCellWithIdentifier(identifier) as? D.Cell else { fatalError("Unexpected cell type at \(indexPath)") } delegate.configureCell(cell, object: obj) return cell } public func objectAtIndexPath(indexPath: NSIndexPath) -> D.Object { guard let obj = fetchedResultsController.objectAtIndexPath(indexPath) as? D.Object else { fatalError("Unexpected cell type at \(indexPath)") } return obj } } public protocol FetchedResultsTableDataSourceDelegate { typealias Object: ManagedObject typealias Cell: UITableViewCell func cellIdentifierForObject(object: Object) -> String func configureCell(cell: Cell, object: Object) }
mit
2444740cbaeee956f94600aa1fe1aca3
37.121212
218
0.669759
6.226073
false
false
false
false
Geor9eLau/WorkHelper
WorkoutHelper/RecordTable.swift
1
3934
// // RecordTable.swift // WorkoutHelper // // Created by George on 2017/2/13. // Copyright © 2017年 George. All rights reserved. // import UIKit class RecordTable: UIView, UITableViewDataSource, UITableViewDelegate { /* // Only override draw() if you perform custom drawing. // An empty implementation adversely affects performance during animation. override func draw(_ rect: CGRect) { // Drawing code } */ private lazy var tableView: UITableView = { let tmp = UITableView(frame: CGRect(x: 0, y: 0, width: self.frame.size.width, height: self.frame.size.height), style: .plain) tmp.delegate = self tmp.dataSource = self tmp.backgroundColor = UIColor.clear tmp.allowsSelection = false tmp.separatorStyle = .none return tmp }() private var rows: Int = 6 private var dataSource: [Motion] = [] // MARK: -Public public func addRecord(motion: Motion) { dataSource.append(motion) if dataSource.count > rows { rows = rows + 1 } tableView.reloadData() } public func addRecords(motions: [Motion]){ dataSource.removeAll() for motion in motions{ dataSource.append(motion) } if dataSource.count > rows { rows = rows + 1 } tableView.reloadData() } // MARK: - Initialize override init(frame: CGRect) { super.init(frame: frame) tableView.register(UINib.init(nibName: "RecordTableViewCell", bundle: nil), forCellReuseIdentifier: "recordCell") tableView.reloadData() addSubview(tableView) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - UITableViewDataSource func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return rows } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "recordCell", for: indexPath) as! RecordTableViewCell // if indexPath.row == 0 { // cell.numberLbl.text = "No" // // cell.weightLbl.textColor = UIColor.black // cell.repeatsLbl.textColor = UIColor.black // cell.timeLbl.textColor = UIColor.black // // cell.weightLbl.text = "Weight/kg" // cell.repeatsLbl.text = "Repeats" // cell.timeLbl.text = "Time/s" // }else{ cell.numberLbl.text = "\(indexPath.row + 1)" cell.weightLbl.textColor = UIColor.blue cell.repeatsLbl.textColor = UIColor.blue cell.timeLbl.textColor = UIColor.blue if dataSource.count > 0 && dataSource.count > indexPath.row{ let motion = dataSource[indexPath.row] cell.weightLbl.text = "\(motion.weight)" cell.repeatsLbl.text = "\(motion.repeats)" cell.timeLbl.text = "\(motion.timeConsuming)" }else{ cell.weightLbl.text = "" cell.repeatsLbl.text = "" cell.timeLbl.text = "" } // } return cell } // MARK: - UITableViewDelegate func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 30.0 } func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let headerView = RecordTableSectionHeaderView(frame: CGRect(x: 0, y: 0, width: tableView.frame.size.width, height: 30)) return headerView } func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 30.0 } }
mit
ded8a8ee11f2175e9b3efa906aaa7f25
31.758333
133
0.587128
4.630153
false
false
false
false
FAU-Inf2/kwikshop-ios
Kwik Shop/AutoCompletionViewController.swift
1
2567
// // AutoCompletionViewController.swift // Kwik Shop // // Created by Adrian Kretschmer on 24.08.15. // Copyright (c) 2015 FAU-Inf2. All rights reserved. // import UIKit class AutoCompletionViewController: ResizingViewController { private var autoCompleteTextFields = [MLPAutoCompleteTextField]() override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func initializeAutoCompletionTextField(textField: MLPAutoCompleteTextField, withDataSource dataSource: MLPAutoCompleteTextFieldDataSource) { if !autoCompleteTextFields.contains(textField) { autoCompleteTextFields.append(textField) } textField.autoCompleteDataSource = dataSource textField.autoCompleteTableBackgroundColor = UIColor.whiteColor() textField.showAutoCompleteTableWhenEditingBegins = true let orientation = UIApplication.sharedApplication().statusBarOrientation if orientation == .LandscapeLeft || orientation == .LandscapeRight { textField.maximumNumberOfAutoCompleteRows = 3 } else { textField.maximumNumberOfAutoCompleteRows = 5 } } override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) { super.viewWillTransitionToSize(size, withTransitionCoordinator: coordinator) coordinator.animateAlongsideTransition( { [unowned self] (context) -> () in let orientation = UIApplication.sharedApplication().statusBarOrientation let maximumNumberOfAutoCompleteRows : Int if orientation.isLandscape { maximumNumberOfAutoCompleteRows = 3 } else { maximumNumberOfAutoCompleteRows = 5 } for textField in self.autoCompleteTextFields { textField.maximumNumberOfAutoCompleteRows = maximumNumberOfAutoCompleteRows textField.autoCompleteTableViewHidden = true } }, completion: { [unowned self] (context) -> () in for textField in self.autoCompleteTextFields { textField.autoCompleteTableViewHidden = false } }) } }
mit
e825c7fd80ffabe91c33f511cd8b9a0c
37.313433
144
0.650954
6.385572
false
false
false
false
343max/WorldTime
WorldTime/WorldTimeLayout.swift
1
2240
// Copyright 2014-present Max von Webel. All Rights Reserved. import UIKit class WorldTimeLayout: UICollectionViewLayout { var columns = 2 var rows = 0 var minContentHeight: CGFloat? var count: Int = 0 { didSet { columns = min(count, maximumColumns()) rows = Int(ceil(Float(count) / Float(columns))) } } var perfectContentHeight: CGFloat { get { return CGFloat(rows) * TimeZoneCollectionViewCell.preferedHeight } } func prepareLayout(itemCount: Int) { self.count = itemCount } override func prepare() { super.prepare() guard let dataSource = self.collectionView?.dataSource, let collectionView = self.collectionView else { count = 0 return } self.prepareLayout(itemCount: dataSource.collectionView(collectionView, numberOfItemsInSection: 0)) } override var collectionViewContentSize: CGSize { get { guard let collectionView = self.collectionView else { return CGSize.zero } return CGSize(width: collectionView.bounds.width, height: CGFloat(rows) * TimeZoneCollectionViewCell.preferedHeight) } } override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? { guard let collectionView = self.collectionView else { return [] } let itemHeight = minContentHeight != nil ? minContentHeight! / CGFloat(rows) : TimeZoneCollectionViewCell.preferedHeight let itemSize = CGSize(width: collectionView.bounds.width / CGFloat(columns), height: itemHeight) let range = 0..<count return range.map({ (i) -> UICollectionViewLayoutAttributes in let attributes = UICollectionViewLayoutAttributes(forCellWith: IndexPath(item: i, section: 0) as IndexPath) let column = i % columns let row = (i - column) / columns let origin = CGPoint(x: itemSize.width * CGFloat(column), y: itemSize.height * CGFloat(row)) attributes.frame = CGRect(origin: origin, size: itemSize) return attributes }) } }
mit
2f95f8610eacd3209f1320dd80fc9e12
34
128
0.629018
5.270588
false
false
false
false
kickstarter/ios-ksapi
KsApi/models/lenses/CategoryLenses.swift
1
1949
import Prelude extension Category { public enum lens { public static let id = Lens<Category, Int>( view: { $0.id }, set: { Category(color: $1.color, id: $0, name: $1.name, parent: $1.parent, parentId: $1.parentId, position: $1.position, projectsCount: $1.projectsCount, slug: $1.slug) } ) public static let name = Lens<Category, String>( view: { $0.name }, set: { Category(color: $1.color, id: $1.id, name: $0, parent: $1.parent, parentId: $1.parentId, position: $1.position, projectsCount: $1.projectsCount, slug: $1.slug) } ) public static let parent = Lens<Category, Category?>( view: { $0.parent }, set: { Category(color: $1.color, id: $1.id, name: $1.name, parent: $0, parentId: $1.parentId, position: $1.position, projectsCount: $1.projectsCount, slug: $1.slug) } ) public static let parentId = Lens<Category, Int?>( view: { $0.parentId }, set: { Category(color: $1.color, id: $1.id, name: $1.name, parent: $1.parent, parentId: $0, position: $1.position, projectsCount: $1.projectsCount, slug: $1.slug) } ) public static let position = Lens<Category, Int>( view: { $0.position }, set: { Category(color: $1.color, id: $1.id, name: $1.name, parent: $1.parent, parentId: $1.parentId, position: $0, projectsCount: $1.projectsCount, slug: $1.slug) } ) public static let projectsCount = Lens<Category, Int?>( view: { $0.projectsCount }, set: { Category(color: $1.color, id: $1.id, name: $1.name, parent: $1.parent, parentId: $1.parentId, position: $1.position, projectsCount: $0, slug: $1.slug) } ) public static let slug = Lens<Category, String>( view: { $0.slug }, set: { Category(color: $1.color, id: $1.id, name: $1.name, parent: $1.parent, parentId: $1.parentId, position: $1.position, projectsCount: $1.projectsCount, slug: $0) } ) } }
apache-2.0
776ee58b4d255a0d93f8c4b5b1dbc252
40.468085
103
0.604413
3.108453
false
false
false
false
Tim77277/WizardUIKit
WizardUIKit/Options.swift
1
6156
/********************************************************** MIT License WizardUIKit Copyright (c) 2016 Wei-Ting Lin 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 let kAlertTextMinimumHeight: CGFloat = 185.0 let kDefaultAlertCornerRadius: CGFloat = 5 let kWizardBundle = Bundle(for: Wizard.self) var classProgressViewController: ProgressViewController! var classIndicatorViewController: ActivityIndicatorAlertViewController! public enum AnimateDirection { case slideUp case slideDown case fadeIn } public enum IndicatorStyle { case white case black } public struct WizardDatePicker { public var mode: UIDatePickerMode! public var textColor: UIColor public var defaultDate: Date! public var locale: Locale? public var minimumDate: Date? public var maximumDate: Date? init() { self.mode = UIDatePickerMode.date self.defaultDate = Date() self.textColor = .black } public init(mode: UIDatePickerMode, textColor: UIColor, defaultDate: Date, locale: Locale, minimumDate: Date?, maximumDate: Date?) { self.mode = mode self.locale = locale self.minimumDate = minimumDate self.maximumDate = maximumDate self.defaultDate = defaultDate self.textColor = textColor } } public struct WizardProgressBar { public var progressColor: UIColor public var trackColor: UIColor public var cornerRadius: CGFloat init() { self.progressColor = UIColor.WizardBlueColor() self.trackColor = UIColor.groupTableViewBackground self.cornerRadius = 3 } public init(progressColor: UIColor, trackColor: UIColor, cornerRadius: CGFloat) { self.progressColor = progressColor self.trackColor = trackColor self.cornerRadius = cornerRadius } } public struct WizardAnimation { public var direction: AnimateDirection public var duration: TimeInterval init() { direction = .fadeIn duration = 0.3 } public init(direction: AnimateDirection, duration: TimeInterval) { self.direction = direction self.duration = duration } } public struct WizardStatus { public var image: UIImage public var cornerRadius: CGFloat public var backgroundColor: UIColor public var titleLabel: WizardLabel public var contentLabel: WizardLabel public var button: WizardButton public init (image: UIImage = UIImage(), cornerRadius: CGFloat = kDefaultAlertCornerRadius, backgroundColor: UIColor = .white, titleLabel: WizardLabel, contentLabel: WizardLabel, button: WizardButton) { self.image = image self.cornerRadius = cornerRadius self.backgroundColor = backgroundColor self.titleLabel = titleLabel self.contentLabel = contentLabel self.button = button } } public struct WizardLabel { public var text: String public var textColor: UIColor public var textAlignment: NSTextAlignment public var font: UIFont init() { text = "--" textColor = .black textAlignment = .left font = UIFont.systemFont(ofSize: 18) } public init(text: String, textColor: UIColor, textAlignment: NSTextAlignment = .left, font: UIFont) { self.text = text self.textColor = textColor self.textAlignment = textAlignment self.font = font } } public struct WizardTextField { public var font: UIFont public var textColor: UIColor public var placeholder: String public var cornerRadius: CGFloat public var backgroundColor: UIColor public init(placeholder: String, textColor: UIColor, backgroundColor: UIColor, cornerRadius: CGFloat, font: UIFont) { self.font = font self.textColor = textColor self.placeholder = placeholder self.backgroundColor = backgroundColor self.cornerRadius = cornerRadius } } public struct TextViewOptions { public var font: UIFont public var text: String public var textColor: UIColor public var cornerRadius: CGFloat public var backgroundColor: UIColor public init(text: String, textColor: UIColor, backgroundColor: UIColor, cornerRadius: CGFloat, font: UIFont) { self.font = font self.text = text self.textColor = textColor self.backgroundColor = backgroundColor self.cornerRadius = cornerRadius } } public struct WizardButton { public var cornerRadius: CGFloat public var text: String public var textColor: UIColor public var backgroundColor: UIColor public init (text: String = "OK", textColor: UIColor = .darkGray, backgroundColor: UIColor = .groupTableViewBackground, cornerRadius: CGFloat = 3) { self.text = text self.textColor = textColor self.cornerRadius = cornerRadius self.backgroundColor = backgroundColor } }
mit
9aecb03425c0619102333676f184e8a0
32.096774
206
0.675926
5.225806
false
false
false
false
hejunbinlan/swiftmi-app
swiftmi/swiftmi/KeychainWrapper.swift
6
9852
// // KeychainWrapper.swift // KeychainWrapper // // Created by Jason Rendel on 9/23/14. // Copyright (c) 2014 jasonrendel. All rights reserved. // import Foundation let SecMatchLimit: String! = kSecMatchLimit as String let SecReturnData: String! = kSecReturnData as String let SecValueData: String! = kSecValueData as String let SecAttrAccessible: String! = kSecAttrAccessible as String let SecClass: String! = kSecClass as String let SecAttrService: String! = kSecAttrService as String let SecAttrGeneric: String! = kSecAttrGeneric as String let SecAttrAccount: String! = kSecAttrAccount as String let SecAttrAccessGroup: String! = kSecAttrAccessGroup as String /// KeychainWrapper is a class to help make Keychain access in Swift more straightforward. It is designed to make accessing the Keychain services more like using NSUserDefaults, which is much more familiar to people. public class KeychainWrapper { // MARK: Private static Properties private struct internalVars { static var serviceName: String = "" static var accessGroup: String = "" } // MARK: Public Properties /// ServiceName is used for the kSecAttrService property to uniquely identify this keychain accessor. If no service name is specified, KeychainWrapper will default to using the bundleIdentifier. /// ///This is a static property and only needs to be set once public class var serviceName: String { get { if internalVars.serviceName.isEmpty { internalVars.serviceName = NSBundle.mainBundle().bundleIdentifier ?? "SwiftKeychainWrapper" } return internalVars.serviceName } set(newServiceName) { internalVars.serviceName = newServiceName } } /// AccessGroup is used for the kSecAttrAccessGroup property to identify which Keychain Access Group this entry belongs to. This allows you to use the KeychainWrapper with shared keychain access between different applications. /// /// Access Group defaults to an empty string and is not used until a valid value is set. /// /// This is a static property and only needs to be set once. To remove the access group property after one has been set, set this to an empty string. public class var accessGroup: String { get { return internalVars.accessGroup } set(newAccessGroup){ internalVars.accessGroup = newAccessGroup } } // MARK: Public Methods /// Checks if keychain data exists for a specified key. /// /// :param: keyName The key to check for. /// :returns: True if a value exists for the key. False otherwise. public class func hasValueForKey(keyName: String) -> Bool { var keychainData: NSData? = self.dataForKey(keyName) if let data = keychainData { return true } else { return false } } /// Returns a string value for a specified key. /// /// :param: keyName The key to lookup data for. /// :returns: The String associated with the key if it exists. If no data exists, or the data found cannot be encoded as a string, returns nil. public class func stringForKey(keyName: String) -> String? { var keychainData: NSData? = self.dataForKey(keyName) var stringValue: String? if let data = keychainData { stringValue = NSString(data: data, encoding: NSUTF8StringEncoding) as String? } return stringValue } /// Returns an object that conforms to NSCoding for a specified key. /// /// :param: keyName The key to lookup data for. /// :returns: The decoded object associated with the key if it exists. If no data exists, or the data found cannot be decoded, returns nil. public class func objectForKey(keyName: String) -> NSCoding? { let dataValue: NSData? = self.dataForKey(keyName) var objectValue: NSCoding? if let data = dataValue { objectValue = NSKeyedUnarchiver.unarchiveObjectWithData(data) as? NSCoding } return objectValue; } /// Returns a NSData object for a specified key. /// /// :param: keyName The key to lookup data for. /// :returns: The NSData object associated with the key if it exists. If no data exists, returns nil. public class func dataForKey(keyName: String) -> NSData? { var keychainQueryDictionary = self.setupKeychainQueryDictionaryForKey(keyName) var result: AnyObject? // Limit search results to one keychainQueryDictionary[SecMatchLimit] = kSecMatchLimitOne // Specify we want NSData/CFData returned keychainQueryDictionary[SecReturnData] = kCFBooleanTrue // Search let status = withUnsafeMutablePointer(&result) { SecItemCopyMatching(keychainQueryDictionary, UnsafeMutablePointer($0)) } return status == noErr ? result as? NSData : nil } /// Save a String value to the keychain associated with a specified key. If a String value already exists for the given keyname, the string will be overwritten with the new value. /// /// :param: value The String value to save. /// :param: forKey The key to save the String under. /// :returns: True if the save was successful, false otherwise. public class func setString(value: String, forKey keyName: String) -> Bool { if let data = value.dataUsingEncoding(NSUTF8StringEncoding) { return self.setData(data, forKey: keyName) } else { return false } } /// Save an NSCoding compliant object to the keychain associated with a specified key. If an object already exists for the given keyname, the object will be overwritten with the new value. /// /// :param: value The NSCoding compliant object to save. /// :param: forKey The key to save the object under. /// :returns: True if the save was successful, false otherwise. public class func setObject(value: NSCoding, forKey keyName: String) -> Bool { let data = NSKeyedArchiver.archivedDataWithRootObject(value) return self.setData(data, forKey: keyName) } /// Save a NSData object to the keychain associated with a specified key. If data already exists for the given keyname, the data will be overwritten with the new value. /// /// :param: value The NSData object to save. /// :param: forKey The key to save the object under. /// :returns: True if the save was successful, false otherwise. public class func setData(value: NSData, forKey keyName: String) -> Bool { var keychainQueryDictionary: [String:AnyObject] = self.setupKeychainQueryDictionaryForKey(keyName) keychainQueryDictionary[SecValueData] = value // Protect the keychain entry so it's only valid when the device is unlocked keychainQueryDictionary[SecAttrAccessible] = kSecAttrAccessibleWhenUnlocked let status: OSStatus = SecItemAdd(keychainQueryDictionary, nil) if status == errSecSuccess { return true } else if status == errSecDuplicateItem { return self.updateData(value, forKey: keyName) } else { return false } } /// Remove an object associated with a specified key. /// /// :param: keyName The key value to remove data for. /// :returns: True if successful, false otherwise. public class func removeObjectForKey(keyName: String) -> Bool { let keychainQueryDictionary: [String:AnyObject] = self.setupKeychainQueryDictionaryForKey(keyName) // Delete let status: OSStatus = SecItemDelete(keychainQueryDictionary); if status == errSecSuccess { return true } else { return false } } // MARK: Private Methods /// Update existing data associated with a specified key name. The existing data will be overwritten by the new data private class func updateData(value: NSData, forKey keyName: String) -> Bool { let keychainQueryDictionary: [String:AnyObject] = self.setupKeychainQueryDictionaryForKey(keyName) let updateDictionary = [SecValueData:value] // Update let status: OSStatus = SecItemUpdate(keychainQueryDictionary, updateDictionary) if status == errSecSuccess { return true } else { return false } } /// Setup the keychain query dictionary used to access the keychain on iOS for a specified key name. Takes into account the Service Name and Access Group if one is set. /// /// :param: keyName The key this query is for /// :returns: A dictionary with all the needed properties setup to access the keychain on iOS private class func setupKeychainQueryDictionaryForKey(keyName: String) -> [String:AnyObject] { // Setup dictionary to access keychain and specify we are using a generic password (rather than a certificate, internet password, etc) var keychainQueryDictionary: [String:AnyObject] = [SecClass:kSecClassGenericPassword] // Uniquely identify this keychain accessor keychainQueryDictionary[SecAttrService] = KeychainWrapper.serviceName // Set the keychain access group if defined if !KeychainWrapper.accessGroup.isEmpty { keychainQueryDictionary[SecAttrAccessGroup] = KeychainWrapper.accessGroup } // Uniquely identify the account who will be accessing the keychain var encodedIdentifier: NSData? = keyName.dataUsingEncoding(NSUTF8StringEncoding) keychainQueryDictionary[SecAttrGeneric] = encodedIdentifier keychainQueryDictionary[SecAttrAccount] = encodedIdentifier return keychainQueryDictionary } }
mit
f1c4756f459217cdd6317c1b1ca839f9
40.394958
231
0.684125
5.160817
false
false
false
false
isnine/HutHelper-Open
HutHelper/SwiftApp/Moment/MomentTwoPage/Add/MomentAddViewModel.swift
1
4156
// // MomentAddViewModel.swift // HutHelperSwift // // Created by 张驰 on 2020/1/16. // Copyright © 2020 张驰. All rights reserved. // import Foundation import RxCocoa import RxSwift import HandyJSON import SwiftyJSON import Alamofire class MomentAddViewModel { // // 输出 // let goodNameValid: Observable<Bool> // let goodDescribeValid: Observable<Bool> // let goodPriceValid: Observable<Bool> // let goodFinenessValid: Observable<Bool> // let goodPhoneValid: Observable<Bool> // let goodAreaValid: Observable<Bool> // // // let everythingValid: Observable<Bool> // // // 输入 -> 输出 // init(goodName: Observable<String>, // goodDescribe: Observable<String>, // goodPrice:Observable<String>, // goodFineness: Observable<String>, // goodPhone: Observable<String>, // goodArea: Observable<String> // ) { // // goodNameValid = goodName // .map { $0.count >= 1 } // .share(replay: 1) // // goodDescribeValid = goodDescribe // .map { $0.count >= 1 } // .share(replay: 1) // goodPriceValid = goodPrice // .map { $0.count >= 1 && $0.count <= 5 } // .share(replay: 1) // // goodFinenessValid = goodFineness // .map { $0.count >= 1 } // .share(replay: 1) // goodPhoneValid = goodPhone // .map { $0.count >= 1 } // .share(replay: 1) // // goodAreaValid = goodArea // .map { $0.count >= 1 } // .share(replay: 1) // // everythingValid = Observable.combineLatest( goodNameValid,goodDescribeValid,goodPriceValid,goodFinenessValid,goodPhoneValid,goodAreaValid) { $0 && $1 && $2 && $3 && $4 && $5 } // .share(replay: 1) // // } } // MARK:- 网络请求 extension MomentAddViewModel { func PostHandRequst(content: String, hidden: String, type: String, callback: @escaping (_ result: JSON) -> Void) { //print(tit,content,price,attr,phone,adderss,type,hidden) MomentProvider.request(.add(content, hidden, type)) { (result) in if case let .success(response) = result { let value = try? response.mapJSON() if let data = value { let json = JSON(data) print(json) callback(json) } } } } func UploadImgs(images: [UIImage], callback: @escaping (_ result: String?) -> Void) { guard images.count != 0 else { callback("") return } var value = "" var item = 0 for (index, image) in images.enumerated() { print(image, 1) let imageData = UIImage.jpegData(image)(compressionQuality: 0.5) Alamofire.upload(multipartFormData: { (multipartFormData) in let now = Date() let timeForMatter = DateFormatter() timeForMatter.dateFormat = "yyyyMMddHHmmss" let id = timeForMatter.string(from: now) multipartFormData.append(imageData!, withName: "file", fileName: "\(id).jpg", mimeType: "image/jpeg") }, to: getUploadImages(type: 0)) { (encodingResult) in print("个人图片上传地址:\(getUploadImages(type: 0))") switch encodingResult { case .success(let upload, _, _): upload.responseString { response in if let data = response.data { let json = JSON(data) print(json) if json["code"] == 200 { //callback(json["data"].stringValue) value += "//" + json["data"].stringValue item += 1 if item == images.count { callback(value) } } } } case .failure: print("上传失败") } } } } }
lgpl-2.1
66d8cae1d1ba7b00a0e344a1e08bd302
32.892562
185
0.505974
4.176171
false
false
false
false
greycats/Greycats.swift
Greycats/Graphics/Graphics.swift
1
1523
// // Graphics.swift // Greycats // // Created by Rex Sheng on 8/1/16. // Copyright (c) 2016 Interactive Labs. All rights reserved. // import UIKit private var _bitmapInfo: UInt32 = { var bitmapInfo = CGBitmapInfo.byteOrder32Little.rawValue bitmapInfo &= ~CGBitmapInfo.alphaInfoMask.rawValue bitmapInfo |= CGImageAlphaInfo.premultipliedFirst.rawValue return bitmapInfo }() extension CGImage { public func op(_ closure: (CGContext?, CGRect) -> Void) -> CGImage? { let width = self.width let height = self.height let colourSpace = CGColorSpaceCreateDeviceRGB() let context = CGContext(data: nil, width: width, height: height, bitsPerComponent: 8, bytesPerRow: width * 8, space: colourSpace, bitmapInfo: bitmapInfo.rawValue) let rect = CGRect(x: 0, y: 0, width: CGFloat(width), height: CGFloat(height)) closure(context, rect) return context!.makeImage() } public static func op(_ width: Int, _ height: Int, closure: (CGContext?) -> Void) -> CGImage? { let scale = UIScreen.main.scale let w = width * Int(scale) let h = height * Int(scale) let colourSpace = CGColorSpaceCreateDeviceRGB() let context = CGContext(data: nil, width: w, height: h, bitsPerComponent: 8, bytesPerRow: w * 8, space: colourSpace, bitmapInfo: _bitmapInfo) context!.translateBy(x: 0, y: CGFloat(h)) context!.scaleBy(x: scale, y: -scale) closure(context) return context!.makeImage() } }
mit
975faacaa431f44770959c5cb0a1a758
37.075
170
0.659225
4.161202
false
false
false
false
neeemo/MobileComputingLab
ButterIt/ToastTransitionViewController.swift
1
8066
// // ToastTransitionViewController.swift // ButterIt // // Created by Steven Teng on 14/12/14. // Copyright (c) 2014 Team Butter. All rights reserved. // import UIKit import MultipeerConnectivity class ToastTransitionViewController: UIViewController, UITextFieldDelegate { var appDelegate: AppDelegate? = UIApplication.sharedApplication().delegate as? AppDelegate @IBOutlet weak var usernameField: UITextField? @IBOutlet weak var readyLabel: UILabel? //these are defined for animation of controls @IBOutlet var switchContainer: UIView! @IBOutlet var toastContainer: UIView! @IBOutlet var switchConstraint: NSLayoutConstraint! @IBOutlet var toastConstraint: NSLayoutConstraint! let animationDistance: CGFloat = 50 var playerIsReady = false var hostPeerID : MCPeerID? @IBAction func switchPressed () { //check if username field is empty, if not, toggles player readiness if (playerIsReady == false) { animateDown() } //if the player hits the button after indicating readiness, can change his name and won't show up in the network list else { animateUp() } } override func viewDidLoad() { super.viewDidLoad() appDelegate?.mcManager?.setupPeerWithDisplayName(UIDevice.currentDevice().name) appDelegate?.mcManager?.setupSession() readyLabel?.text = "Hit the lever to start" usernameField?.delegate = self usernameField?.placeholder = UIDevice.currentDevice().name //Adding observers to this VC NSNotificationCenter.defaultCenter().addObserver(self, selector: "peerDidChangeStateWithNotification:", name: "ButterIt_DidChangeStateNotification", object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: "didReceiveDataWithNotification:", name: "ButterIt_DidReceiveDataNotification", object: nil) } override func viewDidAppear(animated: Bool) { //appDelegate?.mcManager?.advertiseSelf(true) } //This method is called when our notificationCenter receives state changed notification func peerDidChangeStateWithNotification (notification: NSNotification) { var peerID = notification.userInfo?["peerID"] as MCPeerID var displayName = peerID.displayName var state = notification.userInfo?["state"] as Int if state != MCSessionState.Connecting.rawValue { if state == MCSessionState.Connected.rawValue { //statusLabel?.text = "Waiting for host to start game!" } var peersExist = appDelegate?.mcManager?.session.connectedPeers.count == 0 } } func returnTextMethod(){ usernameField?.resignFirstResponder() if(appDelegate?.mcManager?.peerID != nil){ appDelegate?.mcManager?.disconnect() appDelegate?.mcManager?.peerID = nil appDelegate?.mcManager?.session = nil } if(usernameField?.text == ""){ appDelegate?.mcManager?.setupPeerWithDisplayName(UIDevice.currentDevice().name) } else{ appDelegate?.mcManager?.setupPeerWithDisplayName(usernameField?.text) } appDelegate?.mcManager?.setupSession() } func textFieldDidEndEditing(textField: UITextField) { returnTextMethod() } func textFieldShouldReturn(textField: UITextField!) -> Bool { returnTextMethod() return true } //toggles playerIsReady bool, advertises to the host that the player is ready, and changes the screen messages func toggleReady () { if(playerIsReady == false){ playerIsReady = true readyLabel?.text = "Please wait" usernameField?.enabled = false; appDelegate?.mcManager?.advertiseSelf(true) } else{ playerIsReady = false readyLabel?.text = "Hit the lever to start" usernameField?.enabled = true; appDelegate?.mcManager?.disconnect() } } //used to animate the toast and the switch to the down position, 50 pixels lower func animateDown() { /* let originalSwitchPosition = switchContainer.center let originalToastPosition = toastContainer.center UIView.animateWithDuration(1, animations: { self.switchContainer.center = CGPoint(x: originalSwitchPosition.x, y: (originalSwitchPosition.y + self.animationDistance)) self.toastContainer.center = CGPoint(x: originalToastPosition.x, y: (originalToastPosition.y + self.animationDistance)) }, completion: { finished in self.toggleReady() self.toastContainer.updateConstraints() })*/ switchConstraint.constant -= animationDistance toastConstraint.constant -= animationDistance UIView.animateWithDuration(1, animations: { self.switchContainer.layoutIfNeeded() self.toastContainer.layoutIfNeeded() }, completion: { finished in self.toggleReady() }) } //used to animate the toast and switch to the up position, 50 pixels higher func animateUp() { /* UIView.animateWithDuration(1, animations: { self.switchContainer.center = CGPoint(x: originalSwitchPosition.x, y: (originalSwitchPosition.y - self.animationDistance)) self.toastContainer.center = CGPoint(x: originalToastPosition.x, y: (originalToastPosition.y - self.animationDistance)) }, completion: { finished in self.toggleReady() })*/ switchConstraint.constant += animationDistance toastConstraint.constant += animationDistance UIView.animateWithDuration(1, animations: { self.switchContainer.layoutIfNeeded() self.toastContainer.layoutIfNeeded() }, completion: { finished in self.toggleReady() }) } //This method is called when our notificationCenter receives a data nofitication func didReceiveDataWithNotification(notification: NSNotification){ var peerID = notification.userInfo?["peerID"] as MCPeerID var displayName = peerID.displayName hostPeerID = peerID var receivedData = notification.userInfo?["data"] as NSData var receivedPackage: Package = NSKeyedUnarchiver.unarchiveObjectWithData(receivedData) as Package var type = receivedPackage.getType() //If package type equals enter, //Sender is from host, //Playbool is set to true //Then game has started and we segue into toastVC if(type == "enter"){ if(receivedPackage.getSender() == "butterHost" && receivedPackage.getPlayBool()){ self.performSegueWithIdentifier("toastPlaySegue", sender: self) } } } //Our prepareforsegue method only exist so we can send the correct hostPeerID to our toastVC override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if(segue.identifier == "toastPlaySegue"){ var toastVC = segue.destinationViewController as ToastViewController toastVC.hostPeerID = hostPeerID } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
apache-2.0
743e3664105a27e2dc66850af53a92fe
36.342593
169
0.643814
5.427995
false
false
false
false
OscarSwanros/swift
test/PCMacro/pc_and_log.swift
21
1855
// RUN: rm -rf %t // RUN: mkdir -p %t // RUN: cp %s %t/main.swift // RUN: %target-build-swift -Xfrontend -pc-macro -Xfrontend -playground-high-performance -Xfrontend -playground -Xfrontend -debugger-support -o %t/main %S/Inputs/PCMacroRuntime.swift %t/main.swift %S/../PlaygroundTransform/Inputs/PlaygroundsRuntime.swift // RUN: %target-run %t/main | %FileCheck %s // REQUIRES: executable_test // FIXME: rdar://problem/30234450 PCMacro tests fail on linux in optimized mode // UNSUPPORTED: OS=linux-gnu #sourceLocation(file: "code.exe", line: 15) func foo(_ x: Int) -> Bool { return x == 1 } foo(1) [1,2,3].map(foo) // CHECK: [19:1-19:7] pc before // CHECK-NEXT: [15:1-15:27] pc before // CHECK-NEXT: [15:1-15:27] pc after // CHECK-NEXT: [16:3-16:16] pc before // CHECK-NEXT: [16:3-16:16] pc after // CHECK-NEXT: [16:10-16:11] $builtin_log[='true'] // this next result is unexpected... // CHECK-NEXT: [19:1-19:7] $builtin_log[='true'] // CHECK-NEXT: [19:1-19:7] pc after // now for the array // CHECK-NEXT: [20:1-20:17] pc before // CHECK-NEXT: [15:1-15:27] pc before // CHECK-NEXT: [15:1-15:27] pc after // CHECK-NEXT: [16:3-16:16] pc before // CHECK-NEXT: [16:3-16:16] pc after // this next result is unexpected... // CHECK-NEXT: [16:10-16:11] $builtin_log[='true'] // CHECK-NEXT: [15:1-15:27] pc before // CHECK-NEXT: [15:1-15:27] pc after // CHECK-NEXT: [16:3-16:16] pc before // CHECK-NEXT: [16:3-16:16] pc after // this next result is unexpected... // CHECK-NEXT: [16:10-16:11] $builtin_log[='false'] // CHECK-NEXT: [15:1-15:27] pc before // CHECK-NEXT: [15:1-15:27] pc after // CHECK-NEXT: [16:3-16:16] pc before // CHECK-NEXT: [16:3-16:16] pc after // this next result is unexpected... // CHECK-NEXT: [16:10-16:11] $builtin_log[='false'] // CHECK-NEXT: [20:1-20:17] $builtin_log[='[true, false, false]'] // CHECK-NEXT: [20:1-20:17] pc after
apache-2.0
483cf51df580f07b7ebad3305374881d
36.857143
254
0.653908
2.598039
false
false
false
false
jonnguy/HSTracker
HSTracker/UIs/Preferences/InitialConfiguration.swift
1
5140
/* * This file is part of the HSTracker package. * (c) Benjamin Michotte <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. * * Created on 13/02/16. */ import Cocoa class InitialConfiguration: NSWindowController, NSComboBoxDataSource, NSComboBoxDelegate, NSOpenSavePanelDelegate { @IBOutlet weak var hstrackerLanguage: NSComboBox! @IBOutlet weak var hearthstoneLanguage: NSComboBox! @IBOutlet var saveButton: NSButton! @IBOutlet var hearthstonePath: NSTextField! @IBOutlet weak var choosePath: NSButton! @IBOutlet weak var checkImage: NSImageView! var completionHandler: (() -> Void)? override func windowDidLoad() { super.windowDidLoad() hearthstoneLanguage.reloadData() hstrackerLanguage.reloadData() let hsPath = Settings.hearthstonePath + "/Hearthstone.app" if FileManager.default.fileExists(atPath: hsPath) { hearthstonePath.stringValue = hsPath hearthstonePath.isEnabled = false choosePath.isEnabled = false } else { checkImage.image = NSImage(named: NSImage.Name(rawValue: "error")) let alert = NSAlert() alert.alertStyle = .critical alert.messageText = NSLocalizedString("Can't find Hearthstone, please select" + " the folder containing Hearthstone.app", comment: "") alert.addButton(withTitle: NSLocalizedString("OK", comment: "")) alert.beginSheetModal(for: self.window!, completionHandler: nil) } } // MARK: - Button actions @IBAction func exit(_ sender: Any) { NSApplication.shared.terminate(nil) } @IBAction func save(_ sender: Any) { if hearthstoneLanguage.indexOfSelectedItem < 0 || hstrackerLanguage.indexOfSelectedItem < 0 || hearthstonePath.stringValue == "" { saveButton.isEnabled = false return } let hstracker: Language.HSTracker = Array(Language.HSTracker.allCases)[hstrackerLanguage.indexOfSelectedItem] let hearthstone: Language.Hearthstone = Array(Language.Hearthstone.allCases)[hearthstoneLanguage.indexOfSelectedItem] Settings.hearthstoneLanguage = hearthstone Settings.hsTrackerLanguage = hstracker Settings.hearthstonePath = hearthstonePath.stringValue.replace("Hearthstone.app", with: "") if let completionHandler = self.completionHandler { DispatchQueue.main.async { completionHandler() } } self.window!.close() } @IBAction func choosePath(_ sender: Any) { let openDialog = NSOpenPanel() openDialog.delegate = self openDialog.canChooseDirectories = false openDialog.allowsMultipleSelection = false openDialog.allowedFileTypes = ["app"] openDialog.nameFieldStringValue = "Hearthstone.app" openDialog.title = NSLocalizedString("Please select your Hearthstone app", comment: "") if openDialog.runModal() == NSApplication.ModalResponse.OK { if let url = openDialog.urls.first { let path = url.path hearthstonePath.stringValue = path.replace("/Hearthstone.app", with: "") checkImage.image = NSImage(named: NSImage.Name(rawValue: "check")) } } checkToEnableSave() } // MARK: - NSComboBoxDataSource methods func numberOfItems(in aComboBox: NSComboBox) -> Int { if aComboBox == hstrackerLanguage { return Array(Language.HSTracker.allCases).count } else if aComboBox == hearthstoneLanguage { return Array(Language.Hearthstone.allCases).count } return 0 } func comboBox(_ aComboBox: NSComboBox, objectValueForItemAt index: Int) -> Any? { if aComboBox == hstrackerLanguage && Array(Language.HSTracker.allCases).count > index { return Array(Language.HSTracker.allCases)[index].localizedString } else if aComboBox == hearthstoneLanguage && Array(Language.Hearthstone.allCases).count > index { return Array(Language.Hearthstone.allCases)[index].localizedString } return "" } func comboBoxSelectionDidChange(_ notification: Notification) { checkToEnableSave() } func checkToEnableSave() { saveButton.isEnabled = (hearthstoneLanguage.indexOfSelectedItem != -1 && CoreManager.validatedHearthstonePath(hearthstonePath.stringValue) && hstrackerLanguage.indexOfSelectedItem != -1 && hearthstonePath.stringValue != "") } // MARK: - NSOpenSavePanelDelegate func panel(_ sender: Any, shouldEnable url: URL) -> Bool { if url.path.hasSuffix(".app") { return url.lastPathComponent == "Hearthstone.app" } else { var isDir: ObjCBool = false return FileManager.default.fileExists(atPath: url.path, isDirectory: &isDir) && isDir.boolValue } } }
mit
2c46eaac0c58fa231b12486f38497411
37.074074
125
0.651167
5.029354
false
false
false
false
buyiyang/iosstar
iOSStar/Scenes/Heat/Controllers/BarrageStarVC.swift
3
8587
// // BarrageStarVC.swift // iOSStar // // Created by sum on 2017/7/14. // Copyright © 2017年 YunDian. All rights reserved. // import UIKit import MJRefresh import SDWebImage import Kingfisher class FooterView: UICollectionReusableView { @IBOutlet var tipsLb: UILabel! } import BarrageRenderer let leftConstant = (kScreenWidth >= 375 ? ((kScreenWidth/375.0 ) * 18) : 15) class OrderItem: UICollectionViewCell { @IBOutlet var nameLb: UILabel! @IBOutlet var starImg: UIImageView! func updata(_ data : AnyObject){ if let response = data as? StartModel{ nameLb.text = response.name self.starImg.kf.setImage(with: URL(string:ShareDataModel.share().qiniuHeader + response.pic_url_tail)) } } } class BarrageStarVC: UIViewController ,UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout{ var renderer:BarrageRenderer! var headerview = UIView() var footerLb = UILabel() var imgView = UIImageView() var timer : Timer? var allData = [FansListModel]() var index = 0 //定义一个mjrefrshfooter let footer = MJRefreshAutoNormalFooter() var dataArry = [StartModel]() @IBOutlet var collectView: UICollectionView! // MARK: loadView override func viewDidLoad() { super.viewDidLoad() title = "跳蚤市场" setupInit() buildDanMu() initdata() // Do any additional setup after loading the view. } //Mark :创建renderer func buildDanMu() { self.renderer = BarrageRenderer.init() self.renderer.canvasMargin = UIEdgeInsetsMake( 5, 0,50, 0) self.renderer.view.backgroundColor = UIColor.init(hexString: "FAFAFA") } //Mark :更新view func autoSenderBarrage() { index = index + 1 if index == allData.count{ index = 0 } renderer.receive(walkTextSpriteDescriptorWithDirection(direction: BarrageWalkDirection.R2L.rawValue, data: allData[index])) } //Mark :数据加载 func walkTextSpriteDescriptorWithDirection(direction:UInt,data : FansListModel) -> BarrageDescriptor{ let descriptor:BarrageDescriptor = BarrageDescriptor() descriptor.spriteName = NSStringFromClass(YD_Barrage.self) let attachment = NSTextAttachment() imgView.sd_setImage(with: URL.init(string: (data.user?.headUrl)!)) let imgage = imgView.image imgView.clipsToBounds = true imgView.layer.cornerRadius = 10 if (imgage != nil){ attachment.image = imgage }else{ attachment.image = UIImage.init(named: "avatar_team") } attachment.bounds = CGRect.init(x: 0, y: -3, width: 18, height: 18) let type = data.trades?.buySell == 1 ? "求购" : "转让" let openPrice = String.init(format: "%.2f", (data.trades?.openPrice)!) let name = " \(data.user!.nickname)\(type)\(data.trades!.amount)秒,\(openPrice)元/秒 " let length = 2 + (data.user?.nickname.length())! let color = UIColor.init(hexString: "CB4232")//data.trades?.buySell == 1 ? UIColor.init(hexString: "CB4232") : UIColor.init(hexString: "ffffff") let attributed = NSMutableAttributedString.init(string: name) attributed.addAttribute(NSForegroundColorAttributeName, value: color!, range: NSRange.init(location: length, length: 2)) attributed.insert(NSAttributedString.init(attachment: attachment), at: 1) descriptor.params["attributedText"] = attributed; descriptor.params["backgroundColor"] = UIColor.init(red: 0, green: 0, blue: 0, alpha: 0.5) descriptor.params["fontSize"] = 15 descriptor.params["cornerRadius"] = 5 descriptor.params["textColor"] = UIColor.white descriptor.params["speed"] = Int(arc4random()%50) + 50 descriptor.params["direction"] = direction return descriptor } deinit { timer?.invalidate() renderer.stop() } // MARK: 数据请求 func initdata(){ index = 0 let requestModel = HeatBarrageModel() requestModel.pos = 0 requestModel.count = 50 AppAPIHelper.marketAPI().requstBuyBarrageList(requestModel: requestModel, complete: { [weak self](result) in if let model = result as? BarrageInfo { if (model.positionsList) != nil{ self?.allData = model.positionsList! self?.timer = Timer.scheduledTimer(timeInterval: 1, target: self ?? BarrageStarVC(), selector: #selector(self?.autoSenderBarrage), userInfo: nil, repeats: true) self?.renderer.start() } } }) { (error) in } let requestStarsModel = GetAllStarInfoModel() AppAPIHelper.user().requestAllStarInfo(requestModel: requestStarsModel, complete: { [weak self](result) in if let model = result as? [StartModel]{ self?.dataArry = model self?.collectView.reloadData() } }) { (error) in } } // MARK: 自定义布局 func setupInit() { let layout = UICollectionViewFlowLayout() layout.headerReferenceSize = CGSize.init(width: self.view.frame.size.width, height: 300) layout.footerReferenceSize = CGSize.init(width: self.view.frame.size.width, height: 0) layout.minimumLineSpacing = CGFloat.init(leftConstant) layout.minimumInteritemSpacing = CGFloat.init(leftConstant) layout.itemSize = CGSize.init(width: (self.view.frame.size.width - CGFloat.init(leftConstant) * 5)/4, height: (self.view.frame.size.width - CGFloat.init(leftConstant) * 5)/4 + 20) self.collectView.collectionViewLayout = layout layout.scrollDirection = .vertical footer.setRefreshingTarget(self, refreshingAction: #selector(loadItemData)) //是否自动加载(默认为true,即表格滑到底部就自动加载) footer.isAutomaticallyRefresh = false footer.setTitle("下拉显示更多...", for: .idle) footer.stateLabel.textColor = UIColor.init(hexString: "666666") // self.collectView!.mj_footer = footer footer.stateLabel.font = UIFont.systemFont(ofSize: 14) self.collectView.showsVerticalScrollIndicator = false self.collectView.showsHorizontalScrollIndicator = false } func loadItemData() { } // MARK: collectionView func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "OrderStarItem", for: indexPath) as! OrderItem cell.updata(dataArry[indexPath.row]) return cell } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets{ return UIEdgeInsets(top: 5, left: CGFloat.init(leftConstant), bottom: 5, right: CGFloat.init(leftConstant)) } func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView { let view = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "HeaderView", for: indexPath) headerview = view if let image = UIImage.init(named: "starsBg"){ headerview.backgroundColor = UIColor.init(patternImage:image) renderer.view.backgroundColor = UIColor.init(patternImage:image) } headerview.addSubview(renderer.view) return view } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { let model = StarSortListModel() let data = self.dataArry[indexPath.row] model.symbol = data.code model.name = data.name let introVC = UIStoryboard.init(name: "Discover", bundle: nil).instantiateViewController(withIdentifier: "StarIntroduceViewController") as! StarIntroduceViewController introVC.starModel = model self.navigationController?.pushViewController(introVC, animated: true) } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int{ return self.dataArry.count } }
gpl-3.0
c27d58a68fe16b6277bb8ea4313d6ab6
41.3
187
0.654846
4.570502
false
false
false
false
programmerC/JNews
Pods/Alamofire/Source/Upload.swift
1
15970
// // Upload.swift // // Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) // // 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 Manager { private enum Uploadable { case Data(NSURLRequest, NSData) case File(NSURLRequest, NSURL) case Stream(NSURLRequest, NSInputStream) } private func upload(uploadable: Uploadable) -> Request { var uploadTask: NSURLSessionUploadTask! var HTTPBodyStream: NSInputStream? switch uploadable { case .Data(let request, let data): dispatch_sync(queue) { uploadTask = self.session.uploadTaskWithRequest(request, fromData: data) } case .File(let request, let fileURL): dispatch_sync(queue) { uploadTask = self.session.uploadTaskWithRequest(request, fromFile: fileURL) } case .Stream(let request, let stream): dispatch_sync(queue) { uploadTask = self.session.uploadTaskWithStreamedRequest(request) } HTTPBodyStream = stream } let request = Request(session: session, task: uploadTask) if HTTPBodyStream != nil { request.delegate.taskNeedNewBodyStream = { _, _ in return HTTPBodyStream } } delegate[request.delegate.task] = request.delegate if startRequestsImmediately { request.resume() } return request } // MARK: File /** Creates a request for uploading a file to the specified URL request. If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. - parameter URLRequest: The URL request - parameter file: The file to upload - returns: The created upload request. */ public func upload(URLRequest: URLRequestConvertible, file: NSURL) -> Request { return upload(.File(URLRequest.URLRequest, file)) } /** Creates a request for uploading a file to the specified URL request. If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. - parameter method: The HTTP method. - parameter URLString: The URL string. - parameter headers: The HTTP headers. `nil` by default. - parameter file: The file to upload - returns: The created upload request. */ public func upload( method: Method, _ URLString: URLStringConvertible, headers: [String: String]? = nil, file: NSURL) -> Request { let mutableURLRequest = URLRequest(method, URLString, headers: headers) return upload(mutableURLRequest, file: file) } // MARK: Data /** Creates a request for uploading data to the specified URL request. If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. - parameter URLRequest: The URL request. - parameter data: The data to upload. - returns: The created upload request. */ public func upload(URLRequest: URLRequestConvertible, data: NSData) -> Request { return upload(.Data(URLRequest.URLRequest, data)) } /** Creates a request for uploading data to the specified URL request. If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. - parameter method: The HTTP method. - parameter URLString: The URL string. - parameter headers: The HTTP headers. `nil` by default. - parameter data: The data to upload - returns: The created upload request. */ public func upload( method: Method, _ URLString: URLStringConvertible, headers: [String: String]? = nil, data: NSData) -> Request { let mutableURLRequest = URLRequest(method, URLString, headers: headers) return upload(mutableURLRequest, data: data) } // MARK: Stream /** Creates a request for uploading a stream to the specified URL request. If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. - parameter URLRequest: The URL request. - parameter stream: The stream to upload. - returns: The created upload request. */ public func upload(URLRequest: URLRequestConvertible, stream: NSInputStream) -> Request { return upload(.Stream(URLRequest.URLRequest, stream)) } /** Creates a request for uploading a stream to the specified URL request. If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. - parameter method: The HTTP method. - parameter URLString: The URL string. - parameter headers: The HTTP headers. `nil` by default. - parameter stream: The stream to upload. - returns: The created upload request. */ public func upload( method: Method, _ URLString: URLStringConvertible, headers: [String: String]? = nil, stream: NSInputStream) -> Request { let mutableURLRequest = URLRequest(method, URLString, headers: headers) return upload(mutableURLRequest, stream: stream) } // MARK: MultipartFormData /// Default memory threshold used when encoding `MultipartFormData`. public static let MultipartFormDataEncodingMemoryThreshold: UInt64 = 10 * 1024 * 1024 /** Defines whether the `MultipartFormData` encoding was successful and contains result of the encoding as associated values. - Success: Represents a successful `MultipartFormData` encoding and contains the new `Request` along with streaming information. - Failure: Used to represent a failure in the `MultipartFormData` encoding and also contains the encoding error. */ public enum MultipartFormDataEncodingResult { case Success(request: Request, streamingFromDisk: Bool, streamFileURL: NSURL?) case Failure(ErrorType) } /** Encodes the `MultipartFormData` and creates a request to upload the result to the specified URL request. It is important to understand the memory implications of uploading `MultipartFormData`. If the cummulative payload is small, encoding the data in-memory and directly uploading to a server is the by far the most efficient approach. However, if the payload is too large, encoding the data in-memory could cause your app to be terminated. Larger payloads must first be written to disk using input and output streams to keep the memory footprint low, then the data can be uploaded as a stream from the resulting file. Streaming from disk MUST be used for larger payloads such as video content. The `encodingMemoryThreshold` parameter allows Alamofire to automatically determine whether to encode in-memory or stream from disk. If the content length of the `MultipartFormData` is below the `encodingMemoryThreshold`, encoding takes place in-memory. If the content length exceeds the threshold, the data is streamed to disk during the encoding process. Then the result is uploaded as data or as a stream depending on which encoding technique was used. If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. - parameter method: The HTTP method. - parameter URLString: The URL string. - parameter headers: The HTTP headers. `nil` by default. - parameter multipartFormData: The closure used to append body parts to the `MultipartFormData`. - parameter encodingMemoryThreshold: The encoding memory threshold in bytes. `MultipartFormDataEncodingMemoryThreshold` by default. - parameter encodingCompletion: The closure called when the `MultipartFormData` encoding is complete. */ public func upload( method: Method, _ URLString: URLStringConvertible, headers: [String: String]? = nil, multipartFormData: MultipartFormData -> Void, encodingMemoryThreshold: UInt64 = Manager.MultipartFormDataEncodingMemoryThreshold, encodingCompletion: (MultipartFormDataEncodingResult -> Void)?) { let mutableURLRequest = URLRequest(method, URLString, headers: headers) return upload( mutableURLRequest, multipartFormData: multipartFormData, encodingMemoryThreshold: encodingMemoryThreshold, encodingCompletion: encodingCompletion ) } /** Encodes the `MultipartFormData` and creates a request to upload the result to the specified URL request. It is important to understand the memory implications of uploading `MultipartFormData`. If the cummulative payload is small, encoding the data in-memory and directly uploading to a server is the by far the most efficient approach. However, if the payload is too large, encoding the data in-memory could cause your app to be terminated. Larger payloads must first be written to disk using input and output streams to keep the memory footprint low, then the data can be uploaded as a stream from the resulting file. Streaming from disk MUST be used for larger payloads such as video content. The `encodingMemoryThreshold` parameter allows Alamofire to automatically determine whether to encode in-memory or stream from disk. If the content length of the `MultipartFormData` is below the `encodingMemoryThreshold`, encoding takes place in-memory. If the content length exceeds the threshold, the data is streamed to disk during the encoding process. Then the result is uploaded as data or as a stream depending on which encoding technique was used. If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. - parameter URLRequest: The URL request. - parameter multipartFormData: The closure used to append body parts to the `MultipartFormData`. - parameter encodingMemoryThreshold: The encoding memory threshold in bytes. `MultipartFormDataEncodingMemoryThreshold` by default. - parameter encodingCompletion: The closure called when the `MultipartFormData` encoding is complete. */ public func upload( URLRequest: URLRequestConvertible, multipartFormData: MultipartFormData -> Void, encodingMemoryThreshold: UInt64 = Manager.MultipartFormDataEncodingMemoryThreshold, encodingCompletion: (MultipartFormDataEncodingResult -> Void)?) { dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) { let formData = MultipartFormData() multipartFormData(formData) let URLRequestWithContentType = URLRequest.URLRequest URLRequestWithContentType.setValue(formData.contentType, forHTTPHeaderField: "Content-Type") let isBackgroundSession = self.session.configuration.identifier != nil if formData.contentLength < encodingMemoryThreshold && !isBackgroundSession { do { let data = try formData.encode() let encodingResult = MultipartFormDataEncodingResult.Success( request: self.upload(URLRequestWithContentType, data: data), streamingFromDisk: false, streamFileURL: nil ) dispatch_async(dispatch_get_main_queue()) { encodingCompletion?(encodingResult) } } catch { dispatch_async(dispatch_get_main_queue()) { encodingCompletion?(.Failure(error as NSError)) } } } else { let fileManager = NSFileManager.defaultManager() let tempDirectoryURL = NSURL(fileURLWithPath: NSTemporaryDirectory()) let directoryURL = tempDirectoryURL.URLByAppendingPathComponent("com.alamofire.manager/multipart.form.data") let fileName = NSUUID().UUIDString let fileURL = directoryURL!.URLByAppendingPathComponent(fileName) do { try fileManager.createDirectoryAtURL(directoryURL!, withIntermediateDirectories: true, attributes: nil) try formData.writeEncodedDataToDisk(fileURL!) dispatch_async(dispatch_get_main_queue()) { let encodingResult = MultipartFormDataEncodingResult.Success( request: self.upload(URLRequestWithContentType, file: fileURL!), streamingFromDisk: true, streamFileURL: fileURL ) encodingCompletion?(encodingResult) } } catch { dispatch_async(dispatch_get_main_queue()) { encodingCompletion?(.Failure(error as NSError)) } } } } } } // MARK: - extension Request { // MARK: - UploadTaskDelegate class UploadTaskDelegate: DataTaskDelegate { var uploadTask: NSURLSessionUploadTask? { return task as? NSURLSessionUploadTask } var uploadProgress: ((Int64, Int64, Int64) -> Void)! // MARK: - NSURLSessionTaskDelegate // MARK: Override Closures var taskDidSendBodyData: ((NSURLSession, NSURLSessionTask, Int64, Int64, Int64) -> Void)? // MARK: Delegate Methods func URLSession( session: NSURLSession, task: NSURLSessionTask, didSendBodyData bytesSent: Int64, totalBytesSent: Int64, totalBytesExpectedToSend: Int64) { if initialResponseTime == nil { initialResponseTime = CFAbsoluteTimeGetCurrent() } if let taskDidSendBodyData = taskDidSendBodyData { taskDidSendBodyData(session, task, bytesSent, totalBytesSent, totalBytesExpectedToSend) } else { progress.totalUnitCount = totalBytesExpectedToSend progress.completedUnitCount = totalBytesSent uploadProgress?(bytesSent, totalBytesSent, totalBytesExpectedToSend) } } } }
gpl-3.0
a13f988161ae346c88c809719b53cbf8
41.473404
124
0.649405
5.726067
false
false
false
false