repo_name
stringlengths
6
91
path
stringlengths
8
968
copies
stringclasses
210 values
size
stringlengths
2
7
content
stringlengths
61
1.01M
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6
99.8
line_max
int64
12
1k
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.89
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
wordpress-mobile/WordPress-iOS
WordPress/WordPressTest/NotificationUtility.swift
1
2091
import CoreData import Foundation import XCTest @testable import WordPress class NotificationUtility { private let coreDataStack: CoreDataStack private var context: NSManagedObjectContext { coreDataStack.mainContext } init(coreDataStack: CoreDataStack) { self.coreDataStack = coreDataStack } private var entityName: String { return Notification.classNameWithoutNamespaces() } func loadBadgeNotification() throws -> WordPress.Notification { return try .fixture(fromFile: "notifications-badge.json", insertInto: context) } func loadLikeNotification() throws -> WordPress.Notification { return try .fixture(fromFile: "notifications-like.json", insertInto: context) } func loadFollowerNotification() throws -> WordPress.Notification { return try .fixture(fromFile: "notifications-new-follower.json", insertInto: context) } func loadCommentNotification() throws -> WordPress.Notification { return try .fixture(fromFile: "notifications-replied-comment.json", insertInto: context) } func loadUnapprovedCommentNotification() throws -> WordPress.Notification { return try .fixture(fromFile: "notifications-unapproved-comment.json", insertInto: context) } func loadPingbackNotification() throws -> WordPress.Notification { return try .fixture(fromFile: "notifications-pingback.json", insertInto: context) } func mockCommentContent() throws -> FormattableCommentContent { let dictionary = try JSONObject(fromFileNamed: "notifications-replied-comment.json") let body = dictionary["body"] let blocks = NotificationContentFactory.content(from: body as! [[String: AnyObject]], actionsParser: NotificationActionParser(), parent: WordPress.Notification(context: context)) return blocks.filter { $0.kind == .comment }.first! as! FormattableCommentContent } func mockCommentContext() throws -> ActionContext<FormattableCommentContent> { return try ActionContext(block: mockCommentContent()) } }
gpl-2.0
b7e071249e090d7415dfa0bca67928b9
37.722222
186
0.725968
5.334184
false
false
false
false
jpedrosa/sua
Sources/stat.swift
1
3645
import Glibc // The Stat class presents some higher level features, but it still exposes // some of the lower level APIs for performance reasons. public struct Stat: CustomStringConvertible { var buffer: CStat public init() { buffer = Sys.statBuffer() } public init(buffer: CStat) { self.buffer = buffer } mutating public func stat(path: String) -> Bool { return Sys.stat(path: path, buffer: &buffer) == 0 } mutating public func lstat(path: String) -> Bool { return Sys.lstat(path: path, buffer: &buffer) == 0 } public var dev: UInt { return buffer.st_dev } public var ino: UInt { return buffer.st_ino } public var rawMode: UInt32 { return buffer.st_mode } public var nlink: UInt { return buffer.st_nlink } public var uid: UInt32 { return buffer.st_uid } public var gid: UInt32 { return buffer.st_gid } public var rdev: UInt { return buffer.st_rdev } public var size: Int { return buffer.st_size } public var blksize: Int { return buffer.st_blksize } public var blocks: Int { return buffer.st_blocks } func tsToTime(ts: CTimespec) -> Time { return Time(secondsSinceEpoch: ts.tv_sec, nanoseconds: ts.tv_nsec) } public var atime: CTimespec { return buffer.st_atim } public var atimeAsTime: Time { return tsToTime(ts: buffer.st_atim) } public var mtime: CTimespec { return buffer.st_mtim } public var mtimeAsTime: Time { return tsToTime(ts: buffer.st_mtim) } public var ctime: CTimespec { return buffer.st_ctim } public var ctimeAsTime: Time { return tsToTime(ts: buffer.st_ctim) } public var isRegularFile: Bool { return (rawMode & S_IFMT) == S_IFREG } public var isDirectory: Bool { return (rawMode & S_IFMT) == S_IFDIR } public var isSymlink: Bool { return (rawMode & S_IFMT) == S_IFLNK } public var mode: StatMode { return StatMode(mode: rawMode) } public var description: String { return "StatBuffer(dev: \(dev), ino: \(ino), rawMode: \(rawMode), " + "nlink: \(nlink), uid: \(uid), gid: \(gid), rdev: \(rdev), " + "size: \(size), blksize: \(blksize), blocks: \(blocks), " + "atime: \(atime), mtime: \(mtime), ctime: \(ctime), " + "mode: \(mode))" } } public struct StatMode: CustomStringConvertible { var mode: UInt32 public init(mode: UInt32 = 0) { self.mode = mode } public var isRegularFile: Bool { return (mode & S_IFMT) == S_IFREG } public var isDirectory: Bool { return (mode & S_IFMT) == S_IFDIR } public var isSymlink: Bool { return (mode & S_IFMT) == S_IFLNK } public var isSocket: Bool { return (mode & S_IFMT) == S_IFSOCK } public var isFifo: Bool { return (mode & S_IFMT) == S_IFIFO } public var isBlockDevice: Bool { return (mode & S_IFMT) == S_IFBLK } public var isCharacterDevice: Bool { return (mode & S_IFMT) == S_IFCHR } public var modeTranslated: String { switch mode & S_IFMT { case S_IFREG: return "Regular File" case S_IFDIR: return "Directory" case S_IFLNK: return "Symlink" case S_IFSOCK: return "Socket" case S_IFIFO: return "FIFO/pipe" case S_IFBLK: return "Block Device" case S_IFCHR: return "Character Device" default: return "Unknown" } } public var octal: String { var a: [UInt32] = [] var i = mode var s = "" while i > 7 { a.append(i % 8) i = i / 8 } s = String(i) var j = a.count - 1 while j >= 0 { s += String(a[j]) j -= 1 } return s } public var description: String { return "StatMode(modeTranslated: \(inspect( modeTranslated)), " + "octal: \(inspect( octal)))" } }
apache-2.0
f343a94bfa7385663d19d3886ad13478
24.851064
75
0.631276
3.337912
false
false
false
false
noprom/TodoSwift
Demo/TodoSwift/TaskController.swift
1
3877
// // TaskController.swift // TodoSwift // // Created by Cyril Chandelier on 13/09/14. // Copyright (c) 2014 Cyril Chandelier. All rights reserved. // import Foundation import CoreData class TaskController { // Shared instance class var sharedInstance: TaskController { struct Static { static var instance: TaskController? static var token: dispatch_once_t = 0 } dispatch_once(&Static.token) { Static.instance = TaskController() } return Static.instance! } // Create a task with given content func createTask(content: String) -> Task? { // Trim content let trimmedContent = content.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet()) if trimmedContent == "" { return nil } // Create task var task: Task = NSEntityDescription.insertNewObjectForEntityForName(TaskEntityName, inManagedObjectContext: CoreDataController.sharedInstance.managedObjectContext!) as Task task.createdAt = NSDate() task.completed = false task.label = trimmedContent // Save managed object context CoreDataController.sharedInstance.managedObjectContext?.save(nil) return task } // Update given task with content, trims content before update and delete task if content is empty func updateTask(task: Task, content: String) { // Trim content let trimmedContent = content.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet()) // Delete task if content is empty, update it otherwise if trimmedContent.utf16Count == 0 { CoreDataController.sharedInstance.managedObjectContext?.deleteObject(task) CoreDataController.sharedInstance.managedObjectContext?.save(nil) } else { task.label = trimmedContent task.managedObjectContext.save(nil) } } // Delete given stask from database func deleteTask(task: Task) { // Delete task from main managed object context CoreDataController.sharedInstance.managedObjectContext?.deleteObject(task) // Save managed object context CoreDataController.sharedInstance.managedObjectContext?.save(nil) } // Toggle task status func toggleTask(task: Task) { // Update completion status task.completed = !task.completed.boolValue // Save context task.managedObjectContext.save(nil) } // Clear completed task func clearCompletedTasks() { self.clearTasks(Task.completedPredicate()) } // Clear tasks func clearTasks(predicate: NSPredicate?) { // Build a fetch request to retrieve completed task let fetchRequest = NSFetchRequest(entityName: TaskEntityName) fetchRequest.predicate = predicate // Perform query let tasks = CoreDataController.sharedInstance.managedObjectContext?.executeFetchRequest(fetchRequest, error: nil) // Loop over task to delete them for task in tasks! { CoreDataController.sharedInstance.managedObjectContext?.deleteObject(task as NSManagedObject) } // Save changes CoreDataController.sharedInstance.managedObjectContext?.save(nil) } // Return the filtered task list func taskList(predicate: NSPredicate?) -> [AnyObject]? { let fetchRequest = NSFetchRequest(entityName: TaskEntityName) fetchRequest.predicate = predicate let items = CoreDataController.sharedInstance.managedObjectContext!.executeFetchRequest(fetchRequest, error: nil) return items } }
mit
3b9e0b76a8cd408532a4a874ef4f135b
29.769841
181
0.646118
5.594517
false
false
false
false
DianQK/Flix
Flix/Storyboard/FlixStackView.swift
1
1147
// // FlixStackView.swift // Flix // // Created by DianQK on 24/10/2017. // Copyright © 2017 DianQK. All rights reserved. // import UIKit import RxSwift import RxCocoa public class FlixStackView: UIStackView { public private(set) var providers: [FlixStackItemProvider] = [] public let tableView = UITableView(frame: .zero, style: .grouped) private let disposeBag = DisposeBag() override public func didMoveToSuperview() { super.didMoveToSuperview() tableView.sectionFooterHeight = 0.1 tableView.sectionHeaderHeight = 0.1 tableView.estimatedRowHeight = 0 tableView.estimatedSectionFooterHeight = 0 tableView.estimatedSectionHeaderHeight = 0 for view in self.arrangedSubviews { self.removeArrangedSubview(view) if let provider = view as? FlixStackItemProvider { let height = provider.bounds.height provider.itemHeight = { return height } providers.append(provider) } } self.addArrangedSubview(tableView) tableView.flix.animatable.build(providers) } }
mit
3db19dac87bcc56e81c7ffd1e20cc2fa
26.285714
69
0.658813
4.918455
false
false
false
false
yunzixun/V2ex-Swift
View/TopicDetailCommentCell.swift
1
10619
// // TopicDetailCommentCell.swift // V2ex-Swift // // Created by huangfeng on 1/20/16. // Copyright © 2016 Fin. All rights reserved. // import UIKit import YYText class TopicDetailCommentCell: UITableViewCell{ /// 头像 var avatarImageView: UIImageView = { let avatarImageView = UIImageView() avatarImageView.contentMode=UIViewContentMode.scaleAspectFit avatarImageView.layer.cornerRadius = 3 avatarImageView.layer.masksToBounds = true return avatarImageView }() /// 用户名 var userNameLabel: UILabel = { let userNameLabel = UILabel() userNameLabel.textColor = V2EXColor.colors.v2_TopicListUserNameColor userNameLabel.font=v2Font(14) return userNameLabel }() /// 日期 和 最后发送人 var dateLabel: UILabel = { let dateLabel = UILabel() dateLabel.textColor=V2EXColor.colors.v2_TopicListDateColor dateLabel.font=v2Font(12) return dateLabel }() /// 回复正文 var commentLabel: YYLabel = { let commentLabel = YYLabel(); commentLabel.textColor=V2EXColor.colors.v2_TopicListTitleColor; commentLabel.font = v2Font(14); commentLabel.numberOfLines = 0; commentLabel.displaysAsynchronously = true return commentLabel }() /// 装上面定义的那些元素的容器 var contentPanel: UIView = { let view = UIView() view.backgroundColor = V2EXColor.colors.v2_CellWhiteBackgroundColor return view }() //评论喜欢数 var favoriteIconView:UIImageView = { let favoriteIconView = UIImageView(image: UIImage.imageUsedTemplateMode("ic_favorite_18pt")!) favoriteIconView.tintColor = V2EXColor.colors.v2_TopicListDateColor; favoriteIconView.contentMode = .scaleAspectFit favoriteIconView.isHidden = true return favoriteIconView }() var favoriteLabel:UILabel = { let favoriteLabel = UILabel() favoriteLabel.textColor = V2EXColor.colors.v2_TopicListDateColor; favoriteLabel.font = v2Font(10) return favoriteLabel }() var itemModel:TopicCommentModel? override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier); self.setup(); } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } func setup()->Void{ self.backgroundColor=V2EXColor.colors.v2_backgroundColor; let selectedBackgroundView = UIView() selectedBackgroundView.backgroundColor = V2EXColor.colors.v2_backgroundColor self.selectedBackgroundView = selectedBackgroundView self.contentView.addSubview(self.contentPanel); self.contentPanel.addSubview(self.avatarImageView); self.contentPanel .addSubview(self.userNameLabel); self.contentPanel.addSubview(self.favoriteIconView) self.contentPanel.addSubview(self.favoriteLabel) self.contentPanel.addSubview(self.dateLabel); self.contentPanel.addSubview(self.commentLabel); self.setupLayout() self.avatarImageView.backgroundColor = self.contentPanel.backgroundColor self.userNameLabel.backgroundColor = self.contentPanel.backgroundColor self.dateLabel.backgroundColor = self.contentPanel.backgroundColor self.commentLabel.backgroundColor = self.contentPanel.backgroundColor self.favoriteIconView.backgroundColor = self.contentPanel.backgroundColor self.favoriteLabel.backgroundColor = self.contentPanel.backgroundColor //点击用户头像,跳转到用户主页 self.avatarImageView.isUserInteractionEnabled = true self.userNameLabel.isUserInteractionEnabled = true var userNameTap = UITapGestureRecognizer(target: self, action: #selector(TopicDetailCommentCell.userNameTap(_:))) self.avatarImageView.addGestureRecognizer(userNameTap) userNameTap = UITapGestureRecognizer(target: self, action: #selector(TopicDetailCommentCell.userNameTap(_:))) self.userNameLabel.addGestureRecognizer(userNameTap) //长按手势 self.contentView .addGestureRecognizer( UILongPressGestureRecognizer(target: self, action: #selector(TopicDetailCommentCell.longPressHandle(_:)) ) ) } func setupLayout(){ self.contentPanel.snp.makeConstraints{ (make) -> Void in make.top.left.right.equalTo(self.contentView); } self.avatarImageView.snp.makeConstraints{ (make) -> Void in make.left.top.equalTo(self.contentView).offset(12); make.width.height.equalTo(35); } self.userNameLabel.snp.makeConstraints{ (make) -> Void in make.left.equalTo(self.avatarImageView.snp.right).offset(10); make.top.equalTo(self.avatarImageView); } self.favoriteIconView.snp.makeConstraints{ (make) -> Void in make.centerY.equalTo(self.userNameLabel); make.left.equalTo(self.userNameLabel.snp.right).offset(10) make.width.height.equalTo(10) } self.favoriteLabel.snp.makeConstraints{ (make) -> Void in make.left.equalTo(self.favoriteIconView.snp.right).offset(3) make.centerY.equalTo(self.favoriteIconView) } self.dateLabel.snp.makeConstraints{ (make) -> Void in make.bottom.equalTo(self.avatarImageView); make.left.equalTo(self.userNameLabel); } self.commentLabel.snp.makeConstraints{ (make) -> Void in make.top.equalTo(self.avatarImageView.snp.bottom).offset(12); make.left.equalTo(self.avatarImageView); make.right.equalTo(self.contentPanel).offset(-12); make.bottom.equalTo(self.contentPanel.snp.bottom).offset(-12) } self.contentPanel.snp.makeConstraints{ (make) -> Void in make.bottom.equalTo(self.contentView.snp.bottom).offset(-SEPARATOR_HEIGHT); } } @objc func userNameTap(_ sender:UITapGestureRecognizer) { if let _ = self.itemModel , let username = itemModel?.userName { let memberViewController = MemberViewController() memberViewController.username = username V2Client.sharedInstance.topNavigationController.pushViewController(memberViewController, animated: true) } } func bind(_ model:TopicCommentModel){ if let avata = model.avata { self.avatarImageView.fin_setImageWithUrl(URL(string: "https:" + avata)!, placeholderImage: nil, imageModificationClosure: fin_defaultImageModification()) } if self.itemModel?.number == model.number && self.itemModel?.userName == model.userName { return; } self.userNameLabel.text = model.userName; self.dateLabel.text = String(format: "%i楼 %@", model.number, model.date ?? "") if let layout = model.textLayout { self.commentLabel.textLayout = layout if layout.attachments != nil { for attachment in layout.attachments! { if let image = attachment.content as? V2CommentAttachmentImage{ image.attachmentDelegate = self } } } } self.favoriteIconView.isHidden = model.favorites <= 0 self.favoriteLabel.text = model.favorites <= 0 ? "" : "\(model.favorites)" self.itemModel = model } } //MARK: - 点击图片 extension TopicDetailCommentCell : V2CommentAttachmentImageTapDelegate ,V2PhotoBrowserDelegate { func V2CommentAttachmentImageSingleTap(_ imageView: V2CommentAttachmentImage) { let photoBrowser = V2PhotoBrowser(delegate: self) photoBrowser.currentPageIndex = imageView.index V2Client.sharedInstance.topNavigationController.present(photoBrowser, animated: true, completion: nil) } //V2PhotoBrowser Delegate func numberOfPhotosInPhotoBrowser(_ photoBrowser: V2PhotoBrowser) -> Int { return self.itemModel!.images.count } func photoAtIndexInPhotoBrowser(_ photoBrowser: V2PhotoBrowser, index: Int) -> V2Photo { let photo = V2Photo(url: URL(string: self.itemModel!.images[index] as! String)!) return photo } func guideContentModeInPhotoBrowser(_ photoBrowser: V2PhotoBrowser, index: Int) -> UIViewContentMode { if let attachment = self.itemModel!.textLayout!.attachments?[index] , let image = attachment.content as? V2CommentAttachmentImage{ return image.contentMode } return .center } func guideFrameInPhotoBrowser(_ photoBrowser: V2PhotoBrowser, index: Int) -> CGRect { if let attachment = self.itemModel!.textLayout!.attachments?[index] , let image = attachment.content as? V2CommentAttachmentImage{ return image .convert(image.bounds, to: UIApplication.shared.keyWindow!) } return CGRect.zero } func guideImageInPhotoBrowser(_ photoBrowser: V2PhotoBrowser, index: Int) -> UIImage? { if let attachment = self.itemModel!.textLayout!.attachments?[index] , let image = attachment.content as? V2CommentAttachmentImage{ return image.image } return nil } } //MARK: - 长按复制功能 extension TopicDetailCommentCell { @objc func longPressHandle(_ longPress:UILongPressGestureRecognizer) -> Void { if (longPress.state == .began) { self.becomeFirstResponder() let item = UIMenuItem(title: "复制", action: #selector(TopicDetailCommentCell.copyText)) let menuController = UIMenuController.shared menuController.menuItems = [item] menuController.arrowDirection = .down menuController.setTargetRect(self.frame, in: self.superview!) menuController.setMenuVisible(true, animated: true); } } override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool { if (action == #selector(TopicDetailCommentCell.copyText)){ return true } return super.canPerformAction(action, withSender: sender); } override var canBecomeFirstResponder : Bool { return true } @objc func copyText() -> Void { UIPasteboard.general.string = self.itemModel?.textLayout?.text.string } }
mit
2bb6a1334f1518d4aaefdf05e270f7c0
39.960938
165
0.662026
4.936911
false
false
false
false
bmichotte/HSTracker
HSTracker/Database/Models/Deck.swift
1
4323
// // Deck.swift // HSTracker // // Created by Benjamin Michotte on 19/02/16. // Copyright © 2016 Benjamin Michotte. All rights reserved. // import Foundation import CleanroomLogger import RealmSwift import HearthMirror func generateId() -> String { return "\(UUID().uuidString)-\(Date().timeIntervalSince1970)" } class Deck: Object { dynamic var deckId: String = generateId() dynamic var name = "" private dynamic var _playerClass = CardClass.neutral.rawValue var playerClass: CardClass { get { return CardClass(rawValue: _playerClass)! } set { _playerClass = newValue.rawValue } } dynamic var heroId = "" dynamic var deckMajorVersion: Int = 1 dynamic var deckMinorVersion: Int = 0 dynamic var creationDate = Date() let hearthstatsId = RealmOptional<Int>() let hearthstatsVersionId = RealmOptional<Int>() let hearthStatsArenaId = RealmOptional<Int>() dynamic var isActive = true dynamic var isArena = false let hsDeckId = RealmOptional<Int64>() let cards = List<RealmCard>() let gameStats = List<GameStats>() override static func primaryKey() -> String? { return "deckId" } func add(card: Card) { if card.count == 0 { card.count = 1 } if let _card = cards.filter("id = '\(card.id)'").first { _card.count += card.count } else { cards.append(RealmCard(id: card.id, count: card.count)) } } func remove(card: Card) { if let _card = cards.filter("id = '\(card.id)'").first { _card.count -= 1 if _card.count <= 0 { if let index = cards.index(of: _card) { cards.remove(objectAtIndex: index) } } } reset() } private var _cacheCards: [Card]? var sortedCards: [Card] { if let cards = _cacheCards { return cards } var cache: [Card] = [] for deckCard in cards { if let card = Cards.by(cardId: deckCard.id) { card.count = deckCard.count cache.append(card) } } cache = cache.sortCardList() _cacheCards = cache return cache } func reset() { _cacheCards = nil } func countCards() -> Int { return sortedCards.countCards() } func isValid() -> Bool { let count = countCards() return count == 30 } func arenaFinished() -> Bool { if !isArena { return false } var win = 0 var loss = 0 for stat in gameStats { if stat.result == .loss { loss += 1 } else if stat.result == .win { win += 1 } } return win == 12 || loss == 3 } func standardViable() -> Bool { return !isArena && !sortedCards.any { $0.set != nil && CardSet.wildSets().contains($0.set!) } } /** * Compares the card content to the other deck */ func isContentEqualTo(mirrorDeck: MirrorDeck) -> Bool { let mirrorCards = mirrorDeck.cards for c in self.cards { guard let othercard = mirrorCards.first(where: {$0.cardId == c.id}) else { return false } if c.count != othercard.count.intValue { return false } } return true } func diffTo(mirrorDeck: MirrorDeck) -> (cards: [Card], success: Bool) { var diffs = [Card]() let mirrorCards = mirrorDeck.cards for c in self.cards { guard let othercard = mirrorCards.first(where: {$0.cardId == c.id}) else { diffs.append(Card(fromRealCard: c)) continue } if c.count != othercard.count.intValue { let diffc = Card(fromRealCard: c) diffc.count = abs(c.count - othercard.count.intValue) diffs.append(diffc) } } return (diffs, true) } func incrementVersion(major: Int) { self.deckMajorVersion += major } func incrementVersion(minor: Int) { self.deckMinorVersion += minor } }
mit
01322113f5c20234d669ec13e9551ac9
24.88024
86
0.53031
4.313373
false
false
false
false
southfox/JFAlgo
Example/JFAlgo/PermMissingElemViewController.swift
1
2796
// // PermMissingElemViewController.swift // JFAlgo // // Created by Javier Fuchs on 9/8/16. // Copyright © 2016 CocoaPods. All rights reserved. // import Foundation import JFAlgo /// A zero-indexed array A consisting of N different integers is given. The array contains integers in the range [1..(N + 1)], which means that exactly one element is missing. /// /// Your goal is to find that missing element. /// /// Write a function: /// /// int solution(int A[], int N); /// that, given a zero-indexed array A, returns the value of the missing element. /// /// For example, given array A such that: /// /// A[0] = 2 /// A[1] = 3 /// A[2] = 1 /// A[3] = 5 /// the function should return 4, as it is the missing element. /// /// Assume that: /// /// N is an integer within the range [0..100,000]; /// the elements of A are all distinct; /// each element of array A is an integer within the range [1..(N + 1)]. /// Complexity: /// /// expected worst-case time complexity is O(N); /// expected worst-case space complexity is O(1), beyond input storage (not counting the storage required for input arguments). /// Elements of input arrays can be modified. class PermMissingElemViewController : BaseCollectionViewController { let permMissingElem = PermMissingElem() @IBAction override func runAction() { super.runAction() guard let text = numberField.text, number = Int(text) else { return } if permMissingElem.checkDomainGenerator(number) == false { self.showAlert(permMissingElem.domainErrorMessage(), completion: closure) return } guard var array = A else { self.showAlert("\(number) generates a nil array.", completion: closure) return } let solution = permMissingElem.solution(&array, N: number) if solution != -1 { self.showAlert("array missing element is \(solution).", completion: closure) } else { self.showAlert("No Solution for \(number)", completion: closure) } } @IBAction override func generateAction(sender: AnyObject) { super.generateAction(sender) guard let text = numberField.text, number = Int(text) else { return } if permMissingElem.checkDomainGenerator(number) == false { self.showAlert(permMissingElem.domainErrorMessage(), completion: closure) return } guard let array = permMissingElem.generateDomain(number) else { self.showAlert("\(number) generates a nil array.", completion: closure) return } A = array self.reload() } }
mit
e721cdaf4f850626701c72a5f9d764fa
29.053763
175
0.607871
4.408517
false
false
false
false
dsmelov/simsim
SimSim/Entities/Simulator.swift
1
1860
// // Simulator.swift // SimSim // import Foundation //============================================================================ struct Simulator { var path: String var date: Date private let properties: [AnyHashable : Any] //---------------------------------------------------------------------------- init(dictionary: [AnyHashable : Any], path: String) { self.properties = dictionary self.path = path if let attrs = try? FileManager.default.attributesOfItem(atPath: path), let modificationDate = attrs[FileAttributeKey.modificationDate] as? Date { self.date = modificationDate } else { self.date = Date() } } //---------------------------------------------------------------------------- var name: String { return properties["name"] as? String ?? "Unknown Simulator" } //---------------------------------------------------------------------------- var os: String { guard let runtime = properties["runtime"] as? String else { return "Unknown OS" } return runtime.replacingOccurrences(of: "com.apple.CoreSimulator.SimRuntime.", with: "") .replacingOccurrences(of: "OS-", with: "OS ") .replacingOccurrences(of: "-", with: ".") } //---------------------------------------------------------------------------- func pathForAppGroup(withUUID uuid: String) -> String { return path + "data/Containers/Shared/AppGroup/\(uuid)/" } //---------------------------------------------------------------------------- func pathForAppExtension(withUUID uuid: String) -> String { return path + "data/Containers/Data/PluginKitPlugin/\(uuid)/" } }
mit
42ec5d234144c4c033b0975c4791b88e
29
96
0.416129
6
false
false
false
false
pinterest/plank
Sources/Core/JavaIR.swift
1
16100
// // JavaIR.swift // Core // // Created by Rahul Malik on 1/4/18. // import Foundation struct JavaModifier: OptionSet { let rawValue: Int static let `public` = JavaModifier(rawValue: 1 << 0) static let abstract = JavaModifier(rawValue: 1 << 1) static let final = JavaModifier(rawValue: 1 << 2) static let `static` = JavaModifier(rawValue: 1 << 3) static let `private` = JavaModifier(rawValue: 1 << 4) static let transient = JavaModifier(rawValue: 1 << 5) // https://checkstyle.sourceforge.io/config_modifier.html#ModifierOrder func render() -> String { return [ self.contains(.public) ? "public" : "", self.contains(.private) ? "private" : "", self.contains(.abstract) ? "abstract" : "", self.contains(.static) ? "static" : "", self.contains(.final) ? "final" : "", self.contains(.transient) ? "transient" : "", ].filter { $0 != "" }.joined(separator: " ") } } enum JavaAnnotation: Hashable { case override case nullable case nonnull case serializedName(name: String) case custom(_ annotation: String) var rendered: String { switch self { case .override: return "Override" case .nullable: return "Nullable" case .nonnull: return "NonNull" case let .serializedName(name): return "SerializedName(\"\(name)\")" case let .custom(annotation): return annotation } } } enum JavaNullabilityAnnotationType: String { case androidSupport = "android-support" case androidx var package: String { switch self { case .androidSupport: return "android.support.annotation" case .androidx: return "androidx.annotation" } } } enum JavaLoggingType { case androidLog(level: String) init?(param: String) { switch param { case "android-log-d": self = .androidLog(level: "d") default: fatalError("Unsupported logging type: " + param) } } var imports: [String] { switch self { case .androidLog: return ["android.util.Log"] } } } enum JavaURIType: String, CaseIterable { case androidNetUri = "android.net.Uri" case javaNetURI = "java.net.URI" case okHttp3HttpUrl = "okhttp3.HttpUrl" case string = "String" static var options: String { return allCases.map { "\"\($0.rawValue)\"" }.joined(separator: ", ") } var type: String { switch self { case .androidNetUri: return "Uri" case .javaNetURI: return "URI" case .okHttp3HttpUrl: return "HttpUrl" case .string: return "String" } } var imports: [String] { switch self { case .string: return [] default: return [self.rawValue] } } } // // The json file passed in via java_decorations_beta=model_decorations.json is deserialized into this. // struct JavaDecorations: Codable { var `class`: ClassDecorations? var constructor: MethodDecorations? var properties: [String: PropertyDecorations]? var methods: [String: MethodDecorations]? var variables: [String: VariableDecorations]? var typeAdapterFactories: ClassDecorations? var imports: [String]? func annotationsForClass() -> Set<JavaAnnotation> { guard let classDecorations = `class` else { return [] } guard let annotations = classDecorations.annotations else { return [] } return Set(annotations.map { annotationString in JavaAnnotation.custom(annotationString) }) } func annotationsForConstructor() -> Set<JavaAnnotation> { guard let constructorDecorations = constructor else { return [] } guard let annotations = constructorDecorations.annotations else { return [] } return Set(annotations.map { annotationString in JavaAnnotation.custom(annotationString) }) } func annotationsForPropertyVariable(_ property: String) -> Set<JavaAnnotation> { guard let propertiesDict = properties else { return [] } guard let property = propertiesDict[property] else { return [] } guard let variable = property.variable else { return [] } guard let annotations = variable.annotations else { return [] } return Set(annotations.map { annotationString in JavaAnnotation.custom(annotationString) }) } func annotationsForPropertyGetter(_ property: String) -> Set<JavaAnnotation> { guard let propertiesDict = properties else { return [] } guard let property = propertiesDict[property] else { return [] } guard let getter = property.getter else { return [] } guard let annotations = getter.annotations else { return [] } return Set(annotations.map { annotationString in JavaAnnotation.custom(annotationString) }) } func annotationsForMethod(_ method: String) -> Set<JavaAnnotation> { guard let methodsDict = methods else { return [] } guard let methodDecorations = methodsDict[method] else { return [] } guard let annotations = methodDecorations.annotations else { return [] } return Set(annotations.map { annotationString in JavaAnnotation.custom(annotationString) }) } func annotationsForVariable(_ variable: String) -> Set<JavaAnnotation> { guard let variablesDict = variables else { return [] } guard let variable = variablesDict[variable] else { return [] } guard let annotations = variable.annotations else { return [] } return Set(annotations.map { annotationString in JavaAnnotation.custom(annotationString) }) } func annotationsForTypeAdapterFactories() -> Set<JavaAnnotation> { guard let typeAdapterFactoriesDecorations = typeAdapterFactories else { return [] } guard let annotations = typeAdapterFactoriesDecorations.annotations else { return [] } return Set(annotations.map { annotationString in JavaAnnotation.custom(annotationString) }) } struct ClassDecorations: Codable { var annotations: [String]? var implements: [String]? var extends: String? } struct VariableDecorations: Codable { var annotations: [String]? } struct MethodDecorations: Codable { var annotations: [String]? } struct PropertyDecorations: Codable { var variable: VariableDecorations? var getter: MethodDecorations? } } extension Schema { var isJavaCollection: Bool { switch self { case .array, .map, .set: return true default: return false } } } public struct JavaIR { public struct Method { let annotations: Set<JavaAnnotation> let modifiers: JavaModifier let body: [String] let signature: String let throwableExceptions: [String] func render() -> [String] { // HACK: We should actually have an enum / optionset that we can check for abstract, static, ... let annotationLines = annotations.map { "@\($0.rendered)" }.sorted() let throwsString = throwableExceptions.isEmpty ? "" : " throws " + throwableExceptions.joined(separator: ", ") if modifiers.contains(.abstract) { return annotationLines + ["\(modifiers.render()) \(signature)\(throwsString);"].map { $0.trimmingCharacters(in: .whitespaces) } } var toRender = annotationLines + ["\(modifiers.render()) \(signature)\(throwsString) {"].map { $0.trimmingCharacters(in: .whitespaces) } if !body.isEmpty { toRender.append(-->body) } toRender.append("}") return toRender } } public struct Property { let annotations: Set<JavaAnnotation> let modifiers: JavaModifier let type: String let name: String let initialValue: String func render() -> String { var prop = "" if !annotations.isEmpty { prop.append(annotations.map { "@\($0.rendered)" }.sorted().joined(separator: " ") + " ") } prop.append("\(modifiers.render()) \(type) \(name)") if !initialValue.isEmpty { prop.append(" = " + initialValue) } prop.append(";") return prop } } static func method(annotations: Set<JavaAnnotation> = [], _ modifiers: JavaModifier, _ signature: String, body: () -> [String]) -> JavaIR.Method { return JavaIR.Method(annotations: annotations, modifiers: modifiers, body: body(), signature: signature, throwableExceptions: []) } static func methodThatThrows(annotations: Set<JavaAnnotation> = [], _ modifiers: JavaModifier, _ signature: String, _ throwableExceptions: [String], body: () -> [String]) -> JavaIR.Method { return JavaIR.Method(annotations: annotations, modifiers: modifiers, body: body(), signature: signature, throwableExceptions: throwableExceptions) } static func ifBlock(condition: String, body: () -> [String]) -> String { return [ "if (" + condition + ") {", -->body(), "}", ].joined(separator: "\n") } static func forBlock(condition: String, body: () -> [String]) -> String { return [ "for (" + condition + ") {", -->body(), "}", ].joined(separator: "\n") } static func whileBlock(condition: String, body: () -> [String]) -> String { return [ "while (" + condition + ") {", -->body(), "}", ].joined(separator: "\n") } static func tryCatch(try: [String], catch: Catch) -> String { return [ "try {", -->`try`, "} catch (\(`catch`.argument)) {", // TODO: allow for multiple catches -->`catch`.body, "}", ].joined(separator: "\n") } struct Catch { let argument: String let body: [String] } static func switchBlock(variableToCheck: String, defaultBody: [String], cases: () -> [Case]) -> String { return [ "switch (" + variableToCheck + ") {", -->cases().flatMap { $0.render() }, -->["default:", -->defaultBody], "}", ].joined(separator: "\n") } struct Case { let variableEquals: String let body: [String] let shouldBreak: Bool init(variableEquals: String, body: [String], shouldBreak: Bool = true) { self.variableEquals = variableEquals self.body = body self.shouldBreak = shouldBreak } func render() -> [String] { var lines = [ "case (" + variableEquals + "):", -->body, ] if shouldBreak { lines.append(-->["break;"]) } return lines } } struct Enum { let name: String let values: EnumType func render() -> [String] { switch values { case let .integer(values): let names = values .map { ($0.description, $0.defaultValue) } .map { "@\(JavaAnnotation.serializedName(name: "\($0.1)").rendered) \($0.0.uppercased())(\($0.1))" }.joined(separator: ",\n") let enumInitializer = JavaIR.method([], "\(name)(int value)") { [ "this.value = value;", ] } let getterMethod = JavaIR.method([.public], "int getValue()") { [ "return this.value;", ] } return [ "public enum \(name) {", -->["\(names);", "private final int value;"], -->enumInitializer.render(), -->getterMethod.render(), "}", ] case let .string(values, defaultValue: _): let names = values .map { ($0.description, $0.defaultValue) } .map { "@\(JavaAnnotation.serializedName(name: "\($0.1)").rendered) \($0.0.uppercased())" }.joined(separator: ", ") return [ "public enum \(name) {", -->["\(names);"], "}", ] } } } struct Class { let annotations: Set<JavaAnnotation> let modifiers: JavaModifier let extends: String? let implements: [String]? // Should this be JavaIR.Interface? let name: String let methods: [JavaIR.Method] let enums: [Enum] let innerClasses: [JavaIR.Class] let interfaces: [JavaIR.Interface] let properties: [[JavaIR.Property]] var javadoc: [String]? func render() -> [String] { let implementsList = implements?.joined(separator: ", ") ?? "" let implementsStmt = implementsList.isEmpty ? "" : " implements \(implementsList)" let extendsStmt = extends.map { " extends \($0) " } ?? "" var lines: [String] = [] if let javadoc = javadoc { lines.append("/**") lines += javadoc.map { " * \($0)" } lines.append("**/") } lines += annotations.map { "@\($0.rendered)" }.sorted() + [ "\(modifiers.render()) class \(name)\(extendsStmt)\(implementsStmt) {", ] if !enums.isEmpty { lines.append(-->enums.flatMap { [""] + $0.render() }) } if !properties.isEmpty { lines.append(-->properties.flatMap { [""] + $0.compactMap { $0.render() } }) } if !methods.isEmpty { lines.append(-->methods.flatMap { [""] + $0.render() }) } if !innerClasses.isEmpty { lines.append(-->innerClasses.flatMap { [""] + $0.render() }) } if !interfaces.isEmpty { lines.append(-->interfaces.flatMap { [""] + $0.render() }) } lines.append("}") return lines } } struct Interface { let modifiers: JavaModifier let extends: String? let name: String let methods: [JavaIR.Method] func render() -> [String] { let extendsStmt = extends.map { "extends \($0) " } ?? "" return [ "\(modifiers.render()) interface \(name) \(extendsStmt){", -->methods.compactMap { "\($0.signature);" }, "}", ] } } enum Root: RootRenderer { case packages(names: Set<String>) case imports(names: Set<String>) case classDecl(aClass: JavaIR.Class) case interfaceDecl(aInterface: JavaIR.Interface) func renderImplementation(_: GenerationParameters) -> [String] { switch self { case let .packages(names): return names.sorted().map { "package \($0);" } case let .imports(names): return names.sorted().map { "import \($0);" } case let .classDecl(aClass: cls): return cls.render() case let .interfaceDecl(aInterface: interface): return interface.render() } } } }
apache-2.0
772bf2f2afa92b75b6079b01a587554f
30.20155
193
0.533975
4.681593
false
false
false
false
brenogazzola/CabCentral
CabCentral/MapControllerDrivers.swift
1
2008
// // MapControllerDrivers.swift // CabCentral // // Created by Breno Gazzola on 8/30/15. // Copyright (c) 2015 Breno Gazzola. All rights reserved. // import Foundation import MapKit extension MapController : MKMapViewDelegate { /** Searches drivers in the map. This method has gateways to prevent a search from starting when the last one has not finished yet. */ func searchDrivers(){ if !mapView.showsUserLocation{ return } if (!searchNearUserInProgress){ searchNearUserInProgress = true; searchDriversNearUser() } if (!searchInRegionInProgress){ searchInRegionInProgress = true; searchDriversInDisplayedRegion() } } /* Searches for drivers around the user */ func searchDriversNearUser(){ let userLocation = mapView.userLocation let userRegion = MKCoordinateRegionMakeWithDistance(userLocation.coordinate, regionRadius * 1.25, regionRadius * 1.25) let southwest = userRegion.getSouthwesternEdge() let northeast = userRegion.getNortheasternEdge() Data.searchDriversBetween(southwest, northeast: northeast) { (drivers) in if let driversNearby = drivers { self.updateDrivers(driversNearby) } self.searchNearUserInProgress = false } } /** Searches for drivers in the region the user is currently vieweing */ func searchDriversInDisplayedRegion(){ let displayedRegion = mapView.region let southwest = displayedRegion.getSouthwesternEdge() let northeast = displayedRegion.getNortheasternEdge() Data.searchDriversBetween(southwest, northeast: northeast) { if let driversNearby = $0 { self.updateDrivers(driversNearby) } self.searchInRegionInProgress = false } } }
mit
baa2dfb24e9e068f5ad08350a99b28d0
28.985075
126
0.621514
4.747045
false
false
false
false
dbsystel/DBNetworkStack
Source/URLRequest+Init.swift
1
5195
// // Copyright (C) 2017 DB Systel GmbH. // DB Systel GmbH; Jürgen-Ponto-Platz 1; D-60329 Frankfurt am Main; Germany; http://www.dbsystel.de/ // // 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 URLRequest { /// Convience initializer for easy request creation. /// /// - Parameters: /// - path: path to the resource. /// - baseURL: the base url of the resource. /// - HTTPMethod: the HTTP method for the request. Defaults to `.GET` /// - parameters: url parameters for the request. Defaults to `nil` /// - body: body data payload. Defaults to `nil` /// - allHTTPHeaderFields: HTTP request header fields. Defaults to `nil` /// /// - Important: path must not start with a `/` public init(path: String, baseURL: URL, HTTPMethod: HTTPMethod = .GET, parameters: [String: String]? = nil, body: Data? = nil, allHTTPHeaderFields: Dictionary<String, String>? = nil) { guard let url = URL(string: path, relativeTo: baseURL) else { fatalError("Error creating absolute URL from path: \(path), with baseURL: \(baseURL)") } let urlWithParameters: URL if let parameters = parameters, !parameters.isEmpty { urlWithParameters = url.appending(queryParameters: parameters) } else { urlWithParameters = url } self.init(url: urlWithParameters) self.httpBody = body self.httpMethod = HTTPMethod.rawValue self.allHTTPHeaderFields = allHTTPHeaderFields } } extension Array where Element == URLQueryItem { func appending(queryItems: [URLQueryItem], overrideExisting: Bool = true) -> [URLQueryItem] { var items = overrideExisting ? [URLQueryItem]() : self var itemsToAppend = queryItems if overrideExisting { for item in self { var itemFound = false for (index, value) in itemsToAppend.enumerated() where value.name == item.name { itemFound = true items.append(value) itemsToAppend.remove(at: index) break } if itemFound == false { items.append(item) } } } items.append(contentsOf: itemsToAppend) return items } } extension Dictionary where Key == String, Value == String { func asURLQueryItems() -> [URLQueryItem] { return map { URLQueryItem(name: $0.0, value: $0.1) } } } extension URL { func modifyingComponents(using block:(inout URLComponents) -> Void) -> URL { guard var urlComponents = URLComponents(url: self, resolvingAgainstBaseURL: true) else { fatalError("Could not create url components from \(self.absoluteString)") } block(&urlComponents) guard let absoluteURL = urlComponents.url else { fatalError("Error creating absolute URL from path: \(path), with baseURL: \(baseURL?.absoluteString ?? "No BaseURL found")") } return absoluteURL } func appending(queryItems: [URLQueryItem], overrideExisting: Bool = true) -> URL { return modifyingComponents { urlComponents in let items = urlComponents.queryItems ?? [URLQueryItem]() urlComponents.queryItems = items.appending(queryItems: queryItems, overrideExisting: overrideExisting) } } func appending(queryParameters: [String: String], overrideExisting: Bool = true) -> URL { return appending(queryItems: queryParameters.asURLQueryItems(), overrideExisting: overrideExisting) } func replacingAllQueryItems(with queryItems: [URLQueryItem]) -> URL { return modifyingComponents { urlComonents in urlComonents.queryItems = queryItems } } func replacingAllQueryParameters(with queryParameters: [String: String]) -> URL { return replacingAllQueryItems(with: queryParameters.asURLQueryItems()) } }
mit
d36f407d1696f4687cef19da818e27c6
38.953846
136
0.638814
4.836127
false
false
false
false
danielVebman/iOS-Related
BMButton.swift
1
7999
// // BMB.swift // BurgerMenuButton // // Created by Daniel Vebman on 1/19/17. // Copyright © 2017 Daniel Vebman. All rights reserved. // import Foundation import UIKit /** A 'burger menu' `UIButton` that toggles between the opened and closed states. */ class BMButton: UIButton { /// Whether `self` is currently in the open or closed state private enum Status { case menuOpened case menuClosed } /// The ids of the three bars private enum Ids { case bar1 case bar2 case bar3 } /// `simple` fades the bars when the touch is inside `self`'s frame; `complex` animates the bars' positions public enum SecondaryAnimationStyle { case simple case complex } /// The color of the bars. The default `tintColor` is `UIColor.black`. override var tintColor: UIColor! { willSet(color) { animView.bar1!.backgroundColor = color animView.bar2!.backgroundColor = color animView.bar3!.backgroundColor = color } } /// The current animation style of `self` public var secondaryAnimationStyle = SecondaryAnimationStyle.complex /// The view containing the bars in which the animation occurs. private var animView: AnimView! /// The status of `self`. private var status = Status.menuClosed /// Initialize `self` with the given frame. The default `tintColor` is `UIColor.black`, and the default `secondaryAnimationStyle` is `.complex`. override init(frame: CGRect) { super.init(frame: frame) setupAnimView() tintColor = UIColor.black addTarget(self, action: #selector(toggleButton), for: .touchUpInside) addTarget(self, action: #selector(selected), for: .touchDown) addTarget(self, action: #selector(selected), for: .touchDragEnter) addTarget(self, action: #selector(deselected), for: .touchDragExit) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } /// Initializes `animView` and adds the bars to it. private func setupAnimView() { animView = AnimView(frame: CGRect(origin: CGPoint.zero, size: frame.size)) animView.isUserInteractionEnabled = false let barWidth = min(frame.width, frame.height) * 4 / 5 let barHeight: CGFloat = 3 let bar1 = UIView(frame: CGRect(x: (frame.width - barWidth) / 2, y: frame.height * 1 / 4 - barHeight / 2, width: barWidth, height: barHeight)) let bar2 = UIView(frame: CGRect(x: (frame.width - barWidth) / 2, y: frame.height * 2 / 4 - barHeight / 2, width: barWidth, height: barHeight)) let bar3 = UIView(frame: CGRect(x: (frame.width - barWidth) / 2, y: frame.height * 3 / 4 - barHeight / 2, width: barWidth, height: barHeight)) bar1.backgroundColor = tintColor bar2.backgroundColor = tintColor bar3.backgroundColor = tintColor animView.bar1 = bar1 animView.bar2 = bar2 animView.bar3 = bar3 animView.addSubview(bar2) animView.addSubview(bar3) addSubview(animView) } /// Toggle and animate the state of the button between `.menuOpened` and `.menuClosed`. func toggleButton() { if status == .menuClosed { status = .menuOpened UIView.animate(withDuration: 0.25, animations: { self.animView.bar1!.transform = CGAffineTransform(rotationAngle: CGFloat(M_PI / 4)) self.animView.bar1!.center = CGPoint(x: self.animView.frame.width / 2, y: self.animView.frame.height / 2) self.animView.bar2!.frame.size.width = 0 self.animView.bar2!.alpha = 0 self.animView.bar3!.transform = CGAffineTransform(rotationAngle: -CGFloat(M_PI / 4)) self.animView.bar3!.center = CGPoint(x: self.animView.frame.width / 2, y: self.animView.frame.height / 2) }) } else if status == .menuOpened { status = .menuClosed UIView.animate(withDuration: 0.25, animations: { self.animView.bar1!.transform = CGAffineTransform(rotationAngle: 0) self.animView.bar2!.alpha = 1 self.animView.bar3!.transform = CGAffineTransform(rotationAngle: 0) let barWidth = min(self.frame.width, self.frame.height) * 4 / 5 let barHeight: CGFloat = 3 self.animView.bar2!.frame.size.width = barWidth self.animView.bar1!.frame.origin = CGPoint(x: (self.frame.width - barWidth) / 2, y: self.frame.height * 1 / 4 - barHeight / 2) self.animView.bar2!.frame.origin = CGPoint(x: (self.frame.width - barWidth) / 2, y: self.frame.height * 2 / 4 - barHeight / 2) self.animView.bar3!.frame.origin = CGPoint(x: (self.frame.width - barWidth) / 2, y: self.frame.height * 3 / 4 - barHeight / 2) }) } if secondaryAnimationStyle == .simple { deselected() } } /// Called when the touch enters `self`'s frame. @objc private func selected() { if secondaryAnimationStyle == .complex { if status == .menuClosed { UIView.animate(withDuration: 0.15, animations: { self.animView.bar1!.transform = CGAffineTransform(rotationAngle: CGFloat(M_PI / 10)) self.animView.bar2!.frame.size.width *= 3 / 4 self.animView.bar3!.transform = CGAffineTransform(rotationAngle: -CGFloat(M_PI / 10)) }) } else if status == .menuOpened { UIView.animate(withDuration: 0.15, animations: { self.animView.bar1!.transform = CGAffineTransform(rotationAngle: CGFloat(M_PI / 5)) self.animView.bar3!.transform = CGAffineTransform(rotationAngle: -CGFloat(M_PI / 5)) }) } } else if secondaryAnimationStyle == .simple { UIView.animate(withDuration: 0.15, animations: { for bar in self.animView.bars { bar?.alpha = 0.5 } }) } } /// Called when the touch left `self`'s frame. @objc private func deselected() { if secondaryAnimationStyle == .complex { if status == .menuClosed { UIView.animate(withDuration: 0.25, animations: { self.animView.bar1!.transform = CGAffineTransform(rotationAngle: 0) self.animView.bar2!.frame.size.width *= 4 / 3 self.animView.bar3!.transform = CGAffineTransform(rotationAngle: 0) }) } else if status == .menuOpened { UIView.animate(withDuration: 0.25, animations: { self.animView.bar1!.transform = CGAffineTransform(rotationAngle: CGFloat(M_PI / 4)) self.animView.bar3!.transform = CGAffineTransform(rotationAngle: -CGFloat(M_PI / 4)) }) } } else if secondaryAnimationStyle == .simple { UIView.animate(withDuration: 0.25, animations: { for bar in self.animView.bars { bar?.alpha = 1 } }) } } /// The view containing the bars to be animated. private class AnimView: UIView { var bars: [UIView?] { get { return [bar1, bar2, bar3] } } var bar1: UIView? { willSet(bar) { addSubview(bar!) } } var bar2: UIView? { willSet(bar) { addSubview(bar!) } } var bar3: UIView? { willSet(bar) { addSubview(bar!) } } } }
mit
a103c389a831060e8364027dd353f6cf
38.594059
150
0.568517
4.365721
false
false
false
false
SanctionCo/pilot-ios
Pods/Gallery/Sources/Camera/CameraController.swift
1
5626
import UIKit import AVFoundation class CameraController: UIViewController { var locationManager: LocationManager? lazy var cameraMan: CameraMan = self.makeCameraMan() lazy var cameraView: CameraView = self.makeCameraView() let once = Once() let cart: Cart // MARK: - Init public required init(cart: Cart) { self.cart = cart super.init(nibName: nil, bundle: nil) cart.delegates.add(self) } public required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - Life cycle override func viewDidLoad() { super.viewDidLoad() setup() setupLocation() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) locationManager?.start() } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) locationManager?.stop() } override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { coordinator.animate(alongsideTransition: { _ in if let connection = self.cameraView.previewLayer?.connection, connection.isVideoOrientationSupported { connection.videoOrientation = Utils.videoOrientation() } }, completion: nil) super.viewWillTransition(to: size, with: coordinator) } // MARK: - Setup func setup() { view.addSubview(cameraView) cameraView.g_pinEdges() cameraView.closeButton.addTarget(self, action: #selector(closeButtonTouched(_:)), for: .touchUpInside) cameraView.flashButton.addTarget(self, action: #selector(flashButtonTouched(_:)), for: .touchUpInside) cameraView.rotateButton.addTarget(self, action: #selector(rotateButtonTouched(_:)), for: .touchUpInside) cameraView.stackView.addTarget(self, action: #selector(stackViewTouched(_:)), for: .touchUpInside) cameraView.shutterButton.addTarget(self, action: #selector(shutterButtonTouched(_:)), for: .touchUpInside) cameraView.doneButton.addTarget(self, action: #selector(doneButtonTouched(_:)), for: .touchUpInside) } func setupLocation() { if Config.Camera.recordLocation { locationManager = LocationManager() } } // MARK: - Action @objc func closeButtonTouched(_ button: UIButton) { EventHub.shared.close?() } @objc func flashButtonTouched(_ button: UIButton) { cameraView.flashButton.toggle() if let flashMode = AVCaptureDevice.FlashMode(rawValue: cameraView.flashButton.selectedIndex) { cameraMan.flash(flashMode) } } @objc func rotateButtonTouched(_ button: UIButton) { UIView.animate(withDuration: 0.3, animations: { self.cameraView.rotateOverlayView.alpha = 1 }, completion: { _ in self.cameraMan.switchCamera { UIView.animate(withDuration: 0.7, animations: { self.cameraView.rotateOverlayView.alpha = 0 }) } }) } @objc func stackViewTouched(_ stackView: StackView) { EventHub.shared.stackViewTouched?() } @objc func shutterButtonTouched(_ button: ShutterButton) { guard isBelowImageLimit() else { return } guard let previewLayer = cameraView.previewLayer else { return } button.isEnabled = false UIView.animate(withDuration: 0.1, animations: { self.cameraView.shutterOverlayView.alpha = 1 }, completion: { _ in UIView.animate(withDuration: 0.1, animations: { self.cameraView.shutterOverlayView.alpha = 0 }) }) self.cameraView.stackView.startLoading() cameraMan.takePhoto(previewLayer, location: locationManager?.latestLocation) { [weak self] asset in guard let strongSelf = self else { return } button.isEnabled = true strongSelf.cameraView.stackView.stopLoading() if let asset = asset { strongSelf.cart.add(Image(asset: asset), newlyTaken: true) } } } @objc func doneButtonTouched(_ button: UIButton) { EventHub.shared.doneWithImages?() } fileprivate func isBelowImageLimit() -> Bool { return (Config.Camera.imageLimit == 0 || Config.Camera.imageLimit > cart.images.count) } // MARK: - View func refreshView() { let hasImages = !cart.images.isEmpty cameraView.bottomView.g_fade(visible: hasImages) } // MARK: - Controls func makeCameraMan() -> CameraMan { let man = CameraMan() man.delegate = self return man } func makeCameraView() -> CameraView { let view = CameraView() view.delegate = self return view } } extension CameraController: CartDelegate { func cart(_ cart: Cart, didAdd image: Image, newlyTaken: Bool) { cameraView.stackView.reload(cart.images, added: true) refreshView() } func cart(_ cart: Cart, didRemove image: Image) { cameraView.stackView.reload(cart.images) refreshView() } func cartDidReload(_ cart: Cart) { cameraView.stackView.reload(cart.images) refreshView() } } extension CameraController: PageAware { func pageDidShow() { once.run { cameraMan.setup() } } } extension CameraController: CameraViewDelegate { func cameraView(_ cameraView: CameraView, didTouch point: CGPoint) { cameraMan.focus(point) } } extension CameraController: CameraManDelegate { func cameraManDidStart(_ cameraMan: CameraMan) { cameraView.setupPreviewLayer(cameraMan.session) } func cameraManNotAvailable(_ cameraMan: CameraMan) { cameraView.focusImageView.isHidden = true } func cameraMan(_ cameraMan: CameraMan, didChangeInput input: AVCaptureDeviceInput) { cameraView.flashButton.isHidden = !input.device.hasFlash } }
mit
98b1e3a4f4aaccd805d88a4cdbf8c3b8
25.28972
110
0.693921
4.429921
false
false
false
false
ZeeQL/ZeeQL3
Sources/ZeeQL/Access/TypedFetchSpecification.swift
1
5577
// // TypedFetchSpecification.swift // ZeeQL // // Created by Helge Hess on 06/03/17. // Copyright © 2017 ZeeZide GmbH. All rights reserved. // // TODO: this is not done yet public struct TypedFetchSpecification<Object: DatabaseObject> : FetchSpecification { public var _entity : Entity? = nil public var _entityName : String? public var entity : Entity? { if let entity = _entity { return entity } if let to = Object.self as? EntityType.Type { return to.entity } return nil } public var entityName : String? { if let e = entity { return e.name } if let n = _entityName { return n } return nil } public var fetchAttributeNames : [ String ]? public var qualifier : Qualifier? public var sortOrderings : [ SortOrdering ]? public var fetchLimit : Int? public var fetchOffset : Int? public var hints = [ String : Any ]() public var usesDistinct = false public var locksObjects = false public var deep = false public var fetchesRawRows = false public var fetchesReadOnly = false public var requiresAllQualifierBindingVariables = false public var prefetchingRelationshipKeyPathes : [ String ]? public init(entityName : String? = nil, qualifier : Qualifier? = nil, sortOrderings : [ SortOrdering ]? = nil, limit : Int? = nil) { self._entityName = entityName self.qualifier = qualifier self.sortOrderings = sortOrderings self.fetchLimit = limit } public init(entity : Entity, qualifier : Qualifier? = nil, sortOrderings : [ SortOrdering ]? = nil, limit : Int? = nil) { self._entity = entity self.qualifier = qualifier self.sortOrderings = sortOrderings self.fetchLimit = limit } public init(entity : Entity, _ q : String, sortOrderings : [ SortOrdering ]? = nil, limit : Int? = nil, prefetch : [ String ]? = nil) { self._entity = entity self.qualifier = qualifierWith(format: q) self.sortOrderings = sortOrderings self.fetchLimit = limit self.prefetchingRelationshipKeyPathes = prefetch } } // MARK: - Query Runner public extension TypedFetchSpecification where Object: ActiveRecordType { /** * Like so: * * let _ = try Person.where("login like %@", "*he*") * .limit(4) * .fetch(in: db) * */ func fetch(in db: Database) throws -> [ Object ] { let ds = ActiveDataSource<Object>(database: db) ds.fetchSpecification = self return try ds.fetchObjects() } } // MARK: - Typed QueryBuilder public extension TypedFetchSpecification { // This is a clone of the Control QueryBuilder, but with the Generic type // signature ... // MARK: - Qualifiers func `where`(_ q: Qualifier) -> TypedFetchSpecification<Object> { var fs = self fs.qualifier = q return fs } func and(_ q: Qualifier) -> TypedFetchSpecification<Object> { var fs = self fs.qualifier = ZeeQL.and(fs.qualifier, q) return fs } func or(_ q: Qualifier) -> TypedFetchSpecification<Object> { var fs = self fs.qualifier = ZeeQL.or(fs.qualifier, q) return fs } func `where`(_ q: String, _ args: Any?...) -> TypedFetchSpecification<Object> { var fs = self let parser = QualifierParser(string: q, arguments: args) fs.qualifier = parser.parseQualifier() return fs } func and(_ q: String, _ args: Any?...) -> TypedFetchSpecification<Object> { var fs = self let parser = QualifierParser(string: q, arguments: args) fs.qualifier = ZeeQL.and(fs.qualifier, parser.parseQualifier()) return fs } func or(_ q: String, _ args: Any?...) -> TypedFetchSpecification<Object> { var fs = self let parser = QualifierParser(string: q, arguments: args) fs.qualifier = ZeeQL.or(fs.qualifier, parser.parseQualifier()) return fs } // MARK: - Limits func limit(_ value : Int) -> TypedFetchSpecification<Object> { var fs = self fs.fetchLimit = value return fs } func offset(_ value : Int) -> TypedFetchSpecification<Object> { var fs = self fs.fetchOffset = value return fs } // MARK: - Prefetches func prefetch(_ path: String, _ more: String...) -> TypedFetchSpecification<Object> { var fs = self fs.prefetchingRelationshipKeyPathes = [ path ] + more return fs } // MARK: - Ordering func order(by: SortOrdering, _ e: SortOrdering...) -> TypedFetchSpecification<Object> { var fs = self if let old = fs.sortOrderings { fs.sortOrderings = old + [ by ] + e } else { fs.sortOrderings = [ by ] + e } return fs } func order(by: String, _ e: String...) -> TypedFetchSpecification<Object> { var fs = self var ops = [ SortOrdering ]() if let p = SortOrdering.parse(by) { ops += p } for by in e { if let p = SortOrdering.parse(by) { ops += p } } guard !ops.isEmpty else { return self } if let old = fs.sortOrderings { fs.sortOrderings = old + ops } else { fs.sortOrderings = ops } return fs } }
apache-2.0
c3694605d25050f189c8fe79af2ee7ce
25.42654
77
0.577834
4.1
false
false
false
false
linkedin/ConsistencyManager-iOS
ConsistencyManager/DataStructures/BatchUpdateModel.swift
2
4029
// © 2016 LinkedIn Corp. All rights reserved. // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. import Foundation /** This model is useful if you want to batch updates to the consistency manager or listen to multiple models. It has 3 main use cases: 1. Update multiple models in the consistency model at the same time. This will also cause listeners to only get notified once of this change which can cause better performance. In general, this is better than a for loop of updates. 2. Listen to multiple models at once without an modelIdentifier. If you want to listen to mutliple models, you can use this API. The model will be set to nil if it is deleted. The batch listener uses this class, so you can look there for a sample implementation. 3. Listen to multiple models with an modelIdentifier. If you use a modelIdentifier, you can have two seperate BatchUpdateModels which are kept in sync. This can be useful if you want to keep two different collections in sync. */ public final class BatchUpdateModel: ConsistencyManagerModel { /// The updated models public let models: [ConsistencyManagerModel?] /// The modelIdentifier for this BatchUpdateModel. This can be used to keep two BatchUpdateModels consistent. public let modelIdentifier: String? /** - parameter models: The models you want to listen to or update. - parameter modelIdentifier: An identifier for the batch model. This modelIdentifier must be globally unique (and different from all modelIdentifiers). If two BatchUpdateModels have the same identifier, they will be treated as the same model and should have the same data. */ public init(models: [ConsistencyManagerModel], modelIdentifier: String? = nil) { self.models = models.map { model in model as ConsistencyManagerModel? } self.modelIdentifier = modelIdentifier } /** An initializer that allows you to pass in an array of optional models. This can be useful if you want to continuously listen to multiple models which may be deleted. - parameter models: The models you want to listen to or update. - parameter modelIdentifier: An identifier for the batch model. This modelIdentifier must be globally unique (and different from all modelIdentifiers). If two BatchUpdateModels have the same identifier, they will be treated as the same model and should have the same data. */ public init(models: [ConsistencyManagerModel?], modelIdentifier: String? = nil) { self.models = models self.modelIdentifier = modelIdentifier } public func map(_ transform: (ConsistencyManagerModel) -> ConsistencyManagerModel?) -> ConsistencyManagerModel? { let newModels = models.map { model in return model.flatMap(transform) } return BatchUpdateModel(models: newModels) } public func forEach(_ visit: (ConsistencyManagerModel) -> Void) { models.compactMap { $0 }.forEach(visit) } public func isEqualToModel(_ other: ConsistencyManagerModel) -> Bool { guard let other = other as? BatchUpdateModel else { return false } if other.models.count != models.count { return false } for (index, model) in models.enumerated() { if let model = model, let otherModel = other.models[index] { if !model.isEqualToModel(otherModel) { return false } } else if !(model == nil && other.models[index] == nil) { return false } } return true } }
apache-2.0
9e6cab096bb13f2f10c948d352083f5b
42.782609
125
0.699106
4.766864
false
false
false
false
O--Sher/KnightsTour
KnightsTour/Main VC/View/KTMainViewController.swift
1
3337
// // KTMainViewController.swift // Knight's Tour // // Created by Oleg Sher on 28.05.17. // Copyright © 2017 OSher. All rights reserved. // import UIKit public protocol KTChessboardView { var knightTourPresenterView: KTKnightTourPresenterView? { get } func isReasyToStartSearch() -> Bool func drawChessboard(size: Int) func clearBoard() } // MARK: - class KTMainViewController: UIViewController { // MARK: IBOutlets @IBOutlet fileprivate weak var chessboardContainerView: UIView! @IBOutlet fileprivate weak var sizeLabel: UILabel! @IBOutlet fileprivate weak var sizeStepper: UIStepper! @IBOutlet fileprivate weak var repeatSwitch: UISwitch! @IBOutlet fileprivate weak var actionButton: UIButton! @IBOutlet fileprivate weak var clearButton: UIButton! // MARK: Vars fileprivate var presenter: KTMainPresenter! fileprivate var chessboardView: KTChessboardView? // MARK: View lifecycle override var preferredStatusBarStyle: UIStatusBarStyle { return .lightContent } override func viewDidLoad() { super.viewDidLoad() _setupChessboardView() presenter = KTMainPresenter(presentationView: self) } // MARK: IBActions @IBAction func stepperValueChanged(_ sender: UIStepper) { presenter.boardSizeChanged(size: Int(sender.value)) } @IBAction func switchValueChanged(_ sender: UISwitch) { presenter.repeatModeChanged(enabled: sender.isOn) } @IBAction func action(_ sender: UIButton) { guard let currentState = RunState(rawValue: sender.tag) else { fatalError("Failed to retrieve tag state from button") } presenter.changeRunState(oldValue: currentState) } @IBAction func clearAction(_ sender: Any) { chessboardView?.clearBoard() } // MARK: Private private func _setupChessboardView() { let chessboard = KTChessboardViewController() self.chessboardView = chessboard as KTChessboardView self.embedViewController(chessboard, inView: chessboardContainerView) } } // MARK: - KTMainPresentationView extension KTMainViewController: KTMainPresentationView { var knightTourPresenterView: KTKnightTourPresenterView? { return chessboardView?.knightTourPresenterView } func setBoardSize(_ size: Int) { sizeLabel.text = "\(size)x\(size)" sizeStepper.value = Double(size) chessboardView?.drawChessboard(size: size) } func setRepeatModeEnable(_ param: Bool) { repeatSwitch.isOn = param } func setRunState(_ state: RunState) { actionButton.setTitle(state.actionTitle, for: .normal) actionButton.tag = state.rawValue clearButton.isEnabled = state == .stopped } func displayAlert(message: String) { let alert = UIAlertController(title: nil, message: message, preferredStyle: .alert) alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { (action) in alert.dismiss(animated: true, completion: nil) })) self.present(alert, animated: true, completion: nil) } func isReasyToStartSearch() -> Bool { return chessboardView?.isReasyToStartSearch() ?? false } }
mit
ca2195871a30bbae3aaf1719ca6fd267
28.785714
91
0.672962
4.620499
false
false
false
false
TonnyTao/Acornote
Acornote_iOS/Acornote/View/ImageCollectionViewCell.swift
1
2226
// // ImageCollectionViewCell.swift // Acornote // // Created by Tonny on 24/03/17. // Copyright © 2017 Tonny&Sunm. All rights reserved. // import UIKit import Cache class ImageCollectionViewCell: UICollectionViewCell { @IBOutlet weak var imgView: UIImageView! @IBOutlet weak var titleLbl: UILabel! @IBOutlet weak var desLbl: UILabel! //fix bug override func awakeFromNib() { super.awakeFromNib() imgView = self.viewWithTag(1) as? UIImageView titleLbl = self.viewWithTag(2) as? UILabel desLbl = self.viewWithTag(3) as? UILabel } var imgTask: URLSessionDataTask? var item: Item? { didSet { if let imgUrl = item?.imgPath { imgView.isHidden = false imgView.image = nil titleLbl.text = item?.title desLbl.text = item?.des cache?.async.object(forKey: imgUrl, completion: { [weak self] result in if case .value(let wrapper) = result { DispatchQueue.main.async { self?.imgView.image = wrapper.image } }else if let url = URL(string: imgUrl) { self?.imgTask?.cancel() var request = URLRequest(url: url) request.addValue("image/*", forHTTPHeaderField: "Accept") self?.imgTask = URLSession.shared.dataTask(with: request) {[weak self] (data, response, error) -> Void in if let d = data, let img = UIImage(data: d){ cache?.async.setObject(ImageWrapper(image: img), forKey: imgUrl, completion: { _ in DispatchQueue.main.async { self?.imgView.image = img } }) } } self?.imgTask?.resume() } }) } } } }
apache-2.0
ce4c6e0ac55ee29beb7c319839d87001
31.720588
129
0.456629
5.480296
false
false
false
false
Intercambio/CloudUI
CloudUI/CloudUI/FormButtonItemData.swift
1
585
// // FormButtonItemData.swift // CloudUI // // Created by Tobias Kräntzer on 08.02.17. // Copyright © 2017 Tobias Kräntzer. All rights reserved. // import UIKit class FormButtonItemData: FormButtonItem { var selectable: Bool = false var editable: Bool = false var title: String? var enabled: Bool = true var destructive: Bool = false var destructionMessage: String? let identifier: String var action: Selector init(identifier: String, action: Selector) { self.identifier = identifier self.action = action } }
gpl-3.0
be7ca62d1d0c31d2b576f353139c3f1e
21.384615
58
0.664948
4.06993
false
false
false
false
ploden/viral-bible-ios
Viral-Bible-Ios/Viral-Bible-Ios/Classes/Controllers/ChaptersVC.swift
1
1475
// // ChaptersVC.swift // Viral-Bible-Ios // // Created by Philip Loden on 10/4/15. // Copyright © 2015 Alan Young. All rights reserved. // import UIKit class ChaptersVC: UIViewController { @IBOutlet weak var tableView: UITableView! var bibleBook : BibleBook? override func viewDidLoad() { super.viewDidLoad() self.tableView.registerNib(UINib(nibName: "TableViewCell", bundle: nil), forCellReuseIdentifier: "Cell") } func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if let book = self.bibleBook { return Int(book.numChapters) } else { return 0 } } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let aCell = self.tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! TableViewCell aCell.titleLabel.text = String(indexPath.row + 1) return aCell } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { let vc = VersesDetailVC.VB_instantiateFromStoryboard() as! VersesDetailVC vc.bibleBook = self.bibleBook vc.chapterNumber = Int16(indexPath.row + 1) self.navigationController?.pushViewController(vc, animated: true) } }
mit
9f58051af17bc926bf0b1c1bad469923
29.081633
119
0.666893
4.724359
false
false
false
false
onevcat/CotEditor
CotEditor/Sources/EditorTextView+LineProcessing.swift
1
16029
// // EditorTextView+LineProcessing.swift // // CotEditor // https://coteditor.com // // Created by 1024jp on 2016-01-10. // // --------------------------------------------------------------------------- // // © 2014-2022 1024jp // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import Cocoa extension EditorTextView { // MARK: Action Messages /// move selected line up @IBAction func moveLineUp(_ sender: Any?) { guard let ranges = self.rangesForUserTextChange?.map(\.rangeValue), let editingInfo = self.string.moveLineUp(in: ranges) else { return NSSound.beep() } self.edit(with: editingInfo, actionName: "Move Line".localized) } /// move selected line down @IBAction func moveLineDown(_ sender: Any?) { guard let ranges = self.rangesForUserTextChange?.map(\.rangeValue), let editingInfo = self.string.moveLineDown(in: ranges) else { return NSSound.beep() } self.edit(with: editingInfo, actionName: "Move Line".localized) } /// sort selected lines (only in the first selection) ascending @IBAction func sortLinesAscending(_ sender: Any?) { // process whole document if no text selected let range = self.selectedRange.isEmpty ? self.string.nsRange : self.selectedRange guard let editingInfo = self.string.sortLinesAscending(in: range) else { return } self.edit(with: editingInfo, actionName: "Sort Lines".localized) } /// reverse selected lines (only in the first selection) @IBAction func reverseLines(_ sender: Any?) { // process whole document if no text selected let range = self.selectedRange.isEmpty ? self.string.nsRange : self.selectedRange guard let editingInfo = self.string.reverseLines(in: range) else { return } self.edit(with: editingInfo, actionName: "Reverse Lines".localized) } /// delete duplicate lines in selection @IBAction func deleteDuplicateLine(_ sender: Any?) { guard let selectedRanges = self.rangesForUserTextChange?.map(\.rangeValue) else { return } // process whole document if no text selected let ranges = self.selectedRange.isEmpty ? [self.string.nsRange] : selectedRanges guard let editingInfo = self.string.deleteDuplicateLine(in: ranges) else { return } self.edit(with: editingInfo, actionName: "Delete Duplicate Lines".localized) } /// duplicate selected lines below @IBAction func duplicateLine(_ sender: Any?) { guard let selectedRanges = self.rangesForUserTextChange?.map(\.rangeValue) else { return } guard let editingInfo = self.string.duplicateLine(in: selectedRanges, lineEnding: self.lineEnding.rawValue) else { return } self.edit(with: editingInfo, actionName: "Duplicate Line".localized) } /// remove selected lines @IBAction func deleteLine(_ sender: Any?) { guard let selectedRanges = self.rangesForUserTextChange?.map(\.rangeValue) else { return } guard let editingInfo = self.string.deleteLine(in: selectedRanges) else { return } self.edit(with: editingInfo, actionName: "Delete Line".localized) } /// trim all trailing whitespace @IBAction func trimTrailingWhitespace(_ sender: Any?) { let trimsWhitespaceOnlyLines = UserDefaults.standard[.trimsWhitespaceOnlyLines] self.trimTrailingWhitespace(ignoresEmptyLines: !trimsWhitespaceOnlyLines) } /// show pattern sort sheet @IBAction func patternSort(_ sender: Any?) { guard self.isEditable else { return NSSound.beep() } let viewController = PatternSortViewController.instantiate(storyboard: "PatternSortView") // sample the first line let location = self.selectedRange.isEmpty ? self.string.startIndex : String.Index(utf16Offset: self.selectedRange.location, in: self.string) let lineRange = self.string.lineContentsRange(at: location) viewController.sampleLine = String(self.string[lineRange]) viewController.sampleFontName = self.font?.fontName viewController.completionHandler = { [weak self] (pattern, options) in self?.sortLines(pattern: pattern, options: options) } self.viewControllerForSheet?.presentAsSheet(viewController) } // MARK: Private Methods /// replace content according to EditingInfo private func edit(with info: String.EditingInfo, actionName: String) { self.replace(with: info.strings, ranges: info.ranges, selectedRanges: info.selectedRanges, actionName: actionName) } /// Sort lines in the text content. /// /// - Parameters: /// - pattern: The sort pattern. /// - options: The sort options. private func sortLines(pattern: SortPattern, options: SortOptions) { // process whole document if no text selected let range = self.selectedRange.isEmpty ? self.string.nsRange : self.selectedRange let string = self.string as NSString let lineRange = string.lineContentsRange(for: range) guard !lineRange.isEmpty else { return } let newString = pattern.sort(string.substring(with: lineRange), options: options) self.replace(with: newString, range: lineRange, selectedRange: lineRange, actionName: "Sort Lines".localized) } } // MARK: - extension String { typealias EditingInfo = (strings: [String], ranges: [NSRange], selectedRanges: [NSRange]?) /// move selected line up func moveLineUp(in ranges: [NSRange]) -> EditingInfo? { // get line ranges to process let lineRanges = (self as NSString).lineRanges(for: ranges, includingLastEmptyLine: true) // cannot perform Move Line Up if one of the selections is already in the first line guard !lineRanges.isEmpty, lineRanges.first!.lowerBound != 0 else { return nil } var string = self as NSString var replacementRange = NSRange() var selectedRanges: [NSRange] = [] // swap lines for lineRange in lineRanges { let upperLineRange = string.lineRange(at: lineRange.location - 1) var lineString = string.substring(with: lineRange) var upperLineString = string.substring(with: upperLineRange) // last line if lineString.last?.isNewline != true, let lineEnding = upperLineString.popLast() { lineString.append(lineEnding) } // swap let editRange = lineRange.union(upperLineRange) string = string.replacingCharacters(in: editRange, with: lineString + upperLineString) as NSString replacementRange.formUnion(editRange) // move selected ranges in the line to move for selectedRange in ranges { if let intersectionRange = selectedRange.intersection(editRange) { selectedRanges.append(intersectionRange.shifted(by: -upperLineRange.length)) } else if editRange.touches(selectedRange.location) { selectedRanges.append(selectedRange.shifted(by: -upperLineRange.length)) } } } selectedRanges = selectedRanges.unique.sorted(\.location) let replacementString = string.substring(with: replacementRange) return (strings: [replacementString], ranges: [replacementRange], selectedRanges: selectedRanges) } /// move selected line down func moveLineDown(in ranges: [NSRange]) -> EditingInfo? { // get line ranges to process let lineRanges = (self as NSString).lineRanges(for: ranges) // cannot perform Move Line Down if one of the selections is already in the last line guard !lineRanges.isEmpty, (lineRanges.last!.upperBound != self.length || self.last?.isNewline == true) else { return nil } var string = self as NSString var replacementRange = NSRange() var selectedRanges: [NSRange] = [] // swap lines for lineRange in lineRanges.reversed() { let lowerLineRange = string.lineRange(at: lineRange.upperBound) var lineString = string.substring(with: lineRange) var lowerLineString = string.substring(with: lowerLineRange) // last line if lowerLineString.last?.isNewline != true, let lineEnding = lineString.popLast() { lowerLineString.append(lineEnding) } // swap let editRange = lineRange.union(lowerLineRange) string = string.replacingCharacters(in: editRange, with: lowerLineString + lineString) as NSString replacementRange.formUnion(editRange) // move selected ranges in the line to move for selectedRange in ranges { if let intersectionRange = selectedRange.intersection(editRange) { let offset = (lineString.last?.isNewline == true) ? lowerLineRange.length : lowerLineRange.length + lowerLineString.last!.utf16.count selectedRanges.append(intersectionRange.shifted(by: offset)) } else if editRange.touches(selectedRange.location) { selectedRanges.append(selectedRange.shifted(by: lowerLineRange.length)) } } } selectedRanges = selectedRanges.unique.sorted(\.location) let replacementString = string.substring(with: replacementRange) return (strings: [replacementString], ranges: [replacementRange], selectedRanges: selectedRanges) } /// sort selected lines ascending func sortLinesAscending(in range: NSRange) -> EditingInfo? { let string = self as NSString let lineEndingRange = string.range(of: "\\R", options: .regularExpression, range: range) // do nothing with single line guard lineEndingRange != .notFound else { return nil } let lineEnding = string.substring(with: lineEndingRange) let lineRange = string.lineContentsRange(for: range) let newString = string .substring(with: lineRange) .components(separatedBy: .newlines) .sorted(options: [.localized, .caseInsensitive]) .joined(separator: lineEnding) return (strings: [newString], ranges: [lineRange], selectedRanges: [lineRange]) } /// reverse selected lines func reverseLines(in range: NSRange) -> EditingInfo? { let string = self as NSString let lineEndingRange = string.range(of: "\\R", options: .regularExpression, range: range) // do nothing with single line guard lineEndingRange != .notFound else { return nil } let lineEnding = string.substring(with: lineEndingRange) let lineRange = string.lineContentsRange(for: range) let newString = string .substring(with: lineRange) .components(separatedBy: .newlines) .reversed() .joined(separator: lineEnding) return (strings: [newString], ranges: [lineRange], selectedRanges: [lineRange]) } /// delete duplicate lines in selection func deleteDuplicateLine(in ranges: [NSRange]) -> EditingInfo? { let string = self as NSString let lineContentRanges = ranges .map { string.lineRange(for: $0) } .flatMap { self.lineContentsRanges(for: $0) } .unique .sorted(\.location) var replacementRanges: [NSRange] = [] var uniqueLines: [String] = [] for lineContentRange in lineContentRanges { let line = string.substring(with: lineContentRange) if uniqueLines.contains(line) { replacementRanges.append(string.lineRange(for: lineContentRange)) } else { uniqueLines.append(line) } } guard !replacementRanges.isEmpty else { return nil } let replacementStrings = [String](repeating: "", count: replacementRanges.count) return (strings: replacementStrings, ranges: replacementRanges, selectedRanges: nil) } /// duplicate selected lines below func duplicateLine(in ranges: [NSRange], lineEnding: Character) -> EditingInfo? { let string = self as NSString var replacementStrings: [String] = [] var replacementRanges: [NSRange] = [] var selectedRanges: [NSRange] = [] // group the ranges sharing the same lines let rangeGroups: [[NSRange]] = ranges.sorted(\.location) .reduce(into: []) { (groups, range) in if let last = groups.last?.last, string.lineRange(for: last).intersects(string.lineRange(for: range)) { groups[groups.count - 1].append(range) } else { groups.append([range]) } } var offset = 0 for group in rangeGroups { let unionRange = group.reduce(into: group[0]) { $0.formUnion($1) } let lineRange = string.lineRange(for: unionRange) let replacementRange = NSRange(location: lineRange.location, length: 0) var lineString = string.substring(with: lineRange) // add line break if it's the last line if lineString.last?.isNewline != true { lineString.append(lineEnding) } replacementStrings.append(lineString) replacementRanges.append(replacementRange) offset += lineString.length for range in group { selectedRanges.append(range.shifted(by: offset)) } } return (strings: replacementStrings, ranges: replacementRanges, selectedRanges: selectedRanges) } /// remove selected lines func deleteLine(in ranges: [NSRange]) -> EditingInfo? { guard !ranges.isEmpty else { return nil } let lineRanges = (self as NSString).lineRanges(for: ranges) let replacementStrings = [String](repeating: "", count: lineRanges.count) var selectedRanges: [NSRange] = [] var offset = 0 for range in lineRanges { selectedRanges.append(NSRange(location: range.location + offset, length: 0)) offset -= range.length } selectedRanges = selectedRanges.unique.sorted(\.location) return (strings: replacementStrings, ranges: lineRanges, selectedRanges: selectedRanges) } }
apache-2.0
68725eef2105da283ef33d3a28431a7a
36.801887
131
0.603756
5.137179
false
false
false
false
nathawes/swift
stdlib/public/core/ArrayBuffer.swift
6
21914
//===--- ArrayBuffer.swift - Dynamic storage for Swift Array --------------===// // // 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 // //===----------------------------------------------------------------------===// // // This is the class that implements the storage and object management for // Swift Array. // //===----------------------------------------------------------------------===// #if _runtime(_ObjC) import SwiftShims @usableFromInline internal typealias _ArrayBridgeStorage = _BridgeStorage<__ContiguousArrayStorageBase> @usableFromInline @frozen internal struct _ArrayBuffer<Element>: _ArrayBufferProtocol { /// Create an empty buffer. @inlinable internal init() { _storage = _ArrayBridgeStorage(native: _emptyArrayStorage) } @inlinable internal init(nsArray: AnyObject) { _internalInvariant(_isClassOrObjCExistential(Element.self)) _storage = _ArrayBridgeStorage(objC: nsArray) } /// Returns an `_ArrayBuffer<U>` containing the same elements. /// /// - Precondition: The elements actually have dynamic type `U`, and `U` /// is a class or `@objc` existential. @inlinable __consuming internal func cast<U>(toBufferOf _: U.Type) -> _ArrayBuffer<U> { _internalInvariant(_isClassOrObjCExistential(Element.self)) _internalInvariant(_isClassOrObjCExistential(U.self)) return _ArrayBuffer<U>(storage: _storage) } /// Returns an `_ArrayBuffer<U>` containing the same elements, /// deferring checking each element's `U`-ness until it is accessed. /// /// - Precondition: `U` is a class or `@objc` existential derived from /// `Element`. @inlinable __consuming internal func downcast<U>( toBufferWithDeferredTypeCheckOf _: U.Type ) -> _ArrayBuffer<U> { _internalInvariant(_isClassOrObjCExistential(Element.self)) _internalInvariant(_isClassOrObjCExistential(U.self)) // FIXME: can't check that U is derived from Element pending // <rdar://problem/20028320> generic metatype casting doesn't work // _internalInvariant(U.self is Element.Type) return _ArrayBuffer<U>( storage: _ArrayBridgeStorage(native: _native._storage, isFlagged: true)) } @inlinable internal var needsElementTypeCheck: Bool { // NSArray's need an element typecheck when the element type isn't AnyObject return !_isNativeTypeChecked && !(AnyObject.self is Element.Type) } //===--- private --------------------------------------------------------===// @inlinable internal init(storage: _ArrayBridgeStorage) { _storage = storage } @usableFromInline internal var _storage: _ArrayBridgeStorage } extension _ArrayBuffer { /// Adopt the storage of `source`. @inlinable internal init(_buffer source: NativeBuffer, shiftedToStartIndex: Int) { _internalInvariant(shiftedToStartIndex == 0, "shiftedToStartIndex must be 0") _storage = _ArrayBridgeStorage(native: source._storage) } /// `true`, if the array is native and does not need a deferred type check. @inlinable internal var arrayPropertyIsNativeTypeChecked: Bool { return _isNativeTypeChecked } /// Returns `true` iff this buffer's storage is uniquely-referenced. /// /// This function should only be used for internal sanity checks. /// To guard a buffer mutation, use `beginCOWMutation`. @inlinable internal mutating func isUniquelyReferenced() -> Bool { if !_isClassOrObjCExistential(Element.self) { return _storage.isUniquelyReferencedUnflaggedNative() } return _storage.isUniquelyReferencedNative() && _isNative } /// Returns `true` and puts the buffer in a mutable state iff the buffer's /// storage is uniquely-referenced. /// /// - Precondition: The buffer must be immutable. /// /// - Warning: It's a requirement to call `beginCOWMutation` before the buffer /// is mutated. @_alwaysEmitIntoClient internal mutating func beginCOWMutation() -> Bool { let isUnique: Bool if !_isClassOrObjCExistential(Element.self) { isUnique = _storage.beginCOWMutationUnflaggedNative() } else if !_storage.beginCOWMutationNative() { return false } else { isUnique = _isNative } #if INTERNAL_CHECKS_ENABLED if isUnique { _native.isImmutable = false } #endif return isUnique } /// Puts the buffer in an immutable state. /// /// - Precondition: The buffer must be mutable. /// /// - Warning: After a call to `endCOWMutation` the buffer must not be mutated /// until the next call of `beginCOWMutation`. @_alwaysEmitIntoClient @inline(__always) internal mutating func endCOWMutation() { #if INTERNAL_CHECKS_ENABLED _native.isImmutable = true #endif _storage.endCOWMutation() } /// Convert to an NSArray. /// /// O(1) if the element type is bridged verbatim, O(*n*) otherwise. @inlinable internal func _asCocoaArray() -> AnyObject { return _fastPath(_isNative) ? _native._asCocoaArray() : _nonNative.buffer } /// Creates and returns a new uniquely referenced buffer which is a copy of /// this buffer. /// /// This buffer is consumed, i.e. it's released. @_alwaysEmitIntoClient @inline(never) @_semantics("optimize.sil.specialize.owned2guarantee.never") internal __consuming func _consumeAndCreateNew() -> _ArrayBuffer { return _consumeAndCreateNew(bufferIsUnique: false, minimumCapacity: count, growForAppend: false) } /// Creates and returns a new uniquely referenced buffer which is a copy of /// this buffer. /// /// If `bufferIsUnique` is true, the buffer is assumed to be uniquely /// referenced and the elements are moved - instead of copied - to the new /// buffer. /// The `minimumCapacity` is the lower bound for the new capacity. /// If `growForAppend` is true, the new capacity is calculated using /// `_growArrayCapacity`, but at least kept at `minimumCapacity`. /// /// This buffer is consumed, i.e. it's released. @_alwaysEmitIntoClient @inline(never) @_semantics("optimize.sil.specialize.owned2guarantee.never") internal __consuming func _consumeAndCreateNew( bufferIsUnique: Bool, minimumCapacity: Int, growForAppend: Bool ) -> _ArrayBuffer { let newCapacity = _growArrayCapacity(oldCapacity: capacity, minimumCapacity: minimumCapacity, growForAppend: growForAppend) let c = count _internalInvariant(newCapacity >= c) let newBuffer = _ContiguousArrayBuffer<Element>( _uninitializedCount: c, minimumCapacity: newCapacity) if bufferIsUnique { // As an optimization, if the original buffer is unique, we can just move // the elements instead of copying. let dest = newBuffer.firstElementAddress dest.moveInitialize(from: mutableFirstElementAddress, count: c) _native.mutableCount = 0 } else { _copyContents( subRange: 0..<c, initializing: newBuffer.mutableFirstElementAddress) } return _ArrayBuffer(_buffer: newBuffer, shiftedToStartIndex: 0) } /// If this buffer is backed by a uniquely-referenced mutable /// `_ContiguousArrayBuffer` that can be grown in-place to allow the self /// buffer store minimumCapacity elements, returns that buffer. /// Otherwise, returns `nil`. @inlinable internal mutating func requestUniqueMutableBackingBuffer(minimumCapacity: Int) -> NativeBuffer? { if _fastPath(isUniquelyReferenced()) { let b = _native if _fastPath(b.mutableCapacity >= minimumCapacity) { return b } } return nil } @inlinable internal mutating func isMutableAndUniquelyReferenced() -> Bool { return isUniquelyReferenced() } /// If this buffer is backed by a `_ContiguousArrayBuffer` /// containing the same number of elements as `self`, return it. /// Otherwise, return `nil`. @inlinable internal func requestNativeBuffer() -> NativeBuffer? { if !_isClassOrObjCExistential(Element.self) { return _native } return _fastPath(_storage.isNative) ? _native : nil } // We have two versions of type check: one that takes a range and the other // checks one element. The reason for this is that the ARC optimizer does not // handle loops atm. and so can get blocked by the presence of a loop (over // the range). This loop is not necessary for a single element access. @inline(never) @usableFromInline internal func _typeCheckSlowPath(_ index: Int) { if _fastPath(_isNative) { let element: AnyObject = cast(toBufferOf: AnyObject.self)._native[index] precondition( element is Element, """ Down-casted Array element failed to match the target type Expected \(Element.self) but found \(type(of: element)) """ ) } else { let element = _nonNative[index] precondition( element is Element, """ NSArray element failed to match the Swift Array Element type Expected \(Element.self) but found \(type(of: element)) """ ) } } @inlinable internal func _typeCheck(_ subRange: Range<Int>) { if !_isClassOrObjCExistential(Element.self) { return } if _slowPath(needsElementTypeCheck) { // Could be sped up, e.g. by using // enumerateObjectsAtIndexes:options:usingBlock: in the // non-native case. for i in subRange.lowerBound ..< subRange.upperBound { _typeCheckSlowPath(i) } } } /// Copy the elements in `bounds` from this buffer into uninitialized /// memory starting at `target`. Return a pointer "past the end" of the /// just-initialized memory. @inlinable @discardableResult __consuming internal func _copyContents( subRange bounds: Range<Int>, initializing target: UnsafeMutablePointer<Element> ) -> UnsafeMutablePointer<Element> { _typeCheck(bounds) if _fastPath(_isNative) { return _native._copyContents(subRange: bounds, initializing: target) } let buffer = UnsafeMutableRawPointer(target) .assumingMemoryBound(to: AnyObject.self) let result = _nonNative._copyContents( subRange: bounds, initializing: buffer) return UnsafeMutableRawPointer(result).assumingMemoryBound(to: Element.self) } public __consuming func _copyContents( initializing buffer: UnsafeMutableBufferPointer<Element> ) -> (Iterator,UnsafeMutableBufferPointer<Element>.Index) { // This customization point is not implemented for internal types. // Accidentally calling it would be a catastrophic performance bug. fatalError("unsupported") } /// Returns a `_SliceBuffer` containing the given sub-range of elements in /// `bounds` from this buffer. @inlinable internal subscript(bounds: Range<Int>) -> _SliceBuffer<Element> { get { _typeCheck(bounds) if _fastPath(_isNative) { return _native[bounds] } return _nonNative[bounds].unsafeCastElements(to: Element.self) } set { fatalError("not implemented") } } /// A pointer to the first element. /// /// - Precondition: The elements are known to be stored contiguously. @inlinable internal var firstElementAddress: UnsafeMutablePointer<Element> { _internalInvariant(_isNative, "must be a native buffer") return _native.firstElementAddress } /// A mutable pointer to the first element. /// /// - Precondition: the buffer must be mutable. @_alwaysEmitIntoClient internal var mutableFirstElementAddress: UnsafeMutablePointer<Element> { _internalInvariant(_isNative, "must be a native buffer") return _native.mutableFirstElementAddress } @inlinable internal var firstElementAddressIfContiguous: UnsafeMutablePointer<Element>? { return _fastPath(_isNative) ? firstElementAddress : nil } /// The number of elements the buffer stores. /// /// This property is obsolete. It's only used for the ArrayBufferProtocol and /// to keep backward compatibility. /// Use `immutableCount` or `mutableCount` instead. @inlinable internal var count: Int { @inline(__always) get { return _fastPath(_isNative) ? _native.count : _nonNative.endIndex } set { _internalInvariant(_isNative, "attempting to update count of Cocoa array") _native.count = newValue } } /// The number of elements of the buffer. /// /// - Precondition: The buffer must be immutable. @_alwaysEmitIntoClient internal var immutableCount: Int { return _fastPath(_isNative) ? _native.immutableCount : _nonNative.endIndex } /// The number of elements of the buffer. /// /// - Precondition: The buffer must be mutable. @_alwaysEmitIntoClient internal var mutableCount: Int { @inline(__always) get { _internalInvariant( _isNative, "attempting to get mutating-count of non-native buffer") return _native.mutableCount } @inline(__always) set { _internalInvariant(_isNative, "attempting to update count of Cocoa array") _native.mutableCount = newValue } } /// Traps if an inout violation is detected or if the buffer is /// native and the subscript is out of range. /// /// wasNative == _isNative in the absence of inout violations. /// Because the optimizer can hoist the original check it might have /// been invalidated by illegal user code. @inlinable internal func _checkInoutAndNativeBounds(_ index: Int, wasNative: Bool) { _precondition( _isNative == wasNative, "inout rules were violated: the array was overwritten") if _fastPath(wasNative) { _native._checkValidSubscript(index) } } /// Traps if an inout violation is detected or if the buffer is /// native and typechecked and the subscript is out of range. /// /// wasNativeTypeChecked == _isNativeTypeChecked in the absence of /// inout violations. Because the optimizer can hoist the original /// check it might have been invalidated by illegal user code. @inlinable internal func _checkInoutAndNativeTypeCheckedBounds( _ index: Int, wasNativeTypeChecked: Bool ) { _precondition( _isNativeTypeChecked == wasNativeTypeChecked, "inout rules were violated: the array was overwritten") if _fastPath(wasNativeTypeChecked) { _native._checkValidSubscript(index) } } /// Traps unless the given `index` is valid for subscripting, i.e. /// `0 ≤ index < count`. /// /// - Precondition: The buffer must be mutable. @_alwaysEmitIntoClient internal func _checkValidSubscriptMutating(_ index: Int) { _native._checkValidSubscriptMutating(index) } /// The number of elements the buffer can store without reallocation. /// /// This property is obsolete. It's only used for the ArrayBufferProtocol and /// to keep backward compatibility. /// Use `immutableCapacity` or `mutableCapacity` instead. @inlinable internal var capacity: Int { return _fastPath(_isNative) ? _native.capacity : _nonNative.endIndex } /// The number of elements the buffer can store without reallocation. /// /// - Precondition: The buffer must be immutable. @_alwaysEmitIntoClient internal var immutableCapacity: Int { return _fastPath(_isNative) ? _native.immutableCapacity : _nonNative.count } /// The number of elements the buffer can store without reallocation. /// /// - Precondition: The buffer must be mutable. @_alwaysEmitIntoClient internal var mutableCapacity: Int { _internalInvariant(_isNative, "attempting to get mutating-capacity of non-native buffer") return _native.mutableCapacity } @inlinable @inline(__always) internal func getElement(_ i: Int, wasNativeTypeChecked: Bool) -> Element { if _fastPath(wasNativeTypeChecked) { return _nativeTypeChecked[i] } return unsafeBitCast(_getElementSlowPath(i), to: Element.self) } @inline(never) @inlinable // @specializable internal func _getElementSlowPath(_ i: Int) -> AnyObject { _internalInvariant( _isClassOrObjCExistential(Element.self), "Only single reference elements can be indexed here.") let element: AnyObject if _isNative { // _checkInoutAndNativeTypeCheckedBounds does no subscript // checking for the native un-typechecked case. Therefore we // have to do it here. _native._checkValidSubscript(i) element = cast(toBufferOf: AnyObject.self)._native[i] precondition( element is Element, """ Down-casted Array element failed to match the target type Expected \(Element.self) but found \(type(of: element)) """ ) } else { // ObjC arrays do their own subscript checking. element = _nonNative[i] precondition( element is Element, """ NSArray element failed to match the Swift Array Element type Expected \(Element.self) but found \(type(of: element)) """ ) } return element } /// Get or set the value of the ith element. @inlinable internal subscript(i: Int) -> Element { get { return getElement(i, wasNativeTypeChecked: _isNativeTypeChecked) } nonmutating set { if _fastPath(_isNative) { _native[i] = newValue } else { var refCopy = self refCopy.replaceSubrange( i..<(i + 1), with: 1, elementsOf: CollectionOfOne(newValue)) } } } /// Call `body(p)`, where `p` is an `UnsafeBufferPointer` over the /// underlying contiguous storage. If no such storage exists, it is /// created on-demand. @inlinable internal func withUnsafeBufferPointer<R>( _ body: (UnsafeBufferPointer<Element>) throws -> R ) rethrows -> R { if _fastPath(_isNative) { defer { _fixLifetime(self) } return try body( UnsafeBufferPointer(start: firstElementAddress, count: count)) } return try ContiguousArray(self).withUnsafeBufferPointer(body) } /// Call `body(p)`, where `p` is an `UnsafeMutableBufferPointer` /// over the underlying contiguous storage. /// /// - Precondition: Such contiguous storage exists or the buffer is empty. @inlinable internal mutating func withUnsafeMutableBufferPointer<R>( _ body: (UnsafeMutableBufferPointer<Element>) throws -> R ) rethrows -> R { _internalInvariant( _isNative || count == 0, "Array is bridging an opaque NSArray; can't get a pointer to the elements" ) defer { _fixLifetime(self) } return try body(UnsafeMutableBufferPointer( start: firstElementAddressIfContiguous, count: count)) } /// An object that keeps the elements stored in this buffer alive. @inlinable internal var owner: AnyObject { return _fastPath(_isNative) ? _native._storage : _nonNative.buffer } /// An object that keeps the elements stored in this buffer alive. /// /// - Precondition: This buffer is backed by a `_ContiguousArrayBuffer`. @inlinable internal var nativeOwner: AnyObject { _internalInvariant(_isNative, "Expect a native array") return _native._storage } /// A value that identifies the storage used by the buffer. Two /// buffers address the same elements when they have the same /// identity and count. @inlinable internal var identity: UnsafeRawPointer { if _isNative { return _native.identity } else { return UnsafeRawPointer( Unmanaged.passUnretained(_nonNative.buffer).toOpaque()) } } //===--- Collection conformance -------------------------------------===// /// The position of the first element in a non-empty collection. /// /// In an empty collection, `startIndex == endIndex`. @inlinable internal var startIndex: Int { return 0 } /// The collection's "past the end" position. /// /// `endIndex` is not a valid argument to `subscript`, and is always /// reachable from `startIndex` by zero or more applications of /// `index(after:)`. @inlinable internal var endIndex: Int { return count } @usableFromInline internal typealias Indices = Range<Int> //===--- private --------------------------------------------------------===// internal typealias Storage = _ContiguousArrayStorage<Element> @usableFromInline internal typealias NativeBuffer = _ContiguousArrayBuffer<Element> @inlinable internal var _isNative: Bool { if !_isClassOrObjCExistential(Element.self) { return true } else { return _storage.isNative } } /// `true`, if the array is native and does not need a deferred type check. @inlinable internal var _isNativeTypeChecked: Bool { if !_isClassOrObjCExistential(Element.self) { return true } else { return _storage.isUnflaggedNative } } /// Our native representation. /// /// - Precondition: `_isNative`. @inlinable internal var _native: NativeBuffer { return NativeBuffer( _isClassOrObjCExistential(Element.self) ? _storage.nativeInstance : _storage.unflaggedNativeInstance) } /// Fast access to the native representation. /// /// - Precondition: `_isNativeTypeChecked`. @inlinable internal var _nativeTypeChecked: NativeBuffer { return NativeBuffer(_storage.unflaggedNativeInstance) } @inlinable internal var _nonNative: _CocoaArrayWrapper { get { _internalInvariant(_isClassOrObjCExistential(Element.self)) return _CocoaArrayWrapper(_storage.objCInstance) } } } #endif
apache-2.0
6ffbc27753fc4a1990080919064ba012
31.462222
93
0.669542
4.820062
false
false
false
false
roambotics/swift
test/Parse/self_rebinding.swift
3
4746
// RUN: %target-typecheck-verify-swift class Writer { private var articleWritten = 47 func stop() { let rest: () -> Void = { [weak self] in let articleWritten = self?.articleWritten ?? 0 guard let `self` = self else { return } self.articleWritten = articleWritten } fatalError("I'm running out of time") rest() } func nonStop() { let write: () -> Void = { [weak self] in self?.articleWritten += 1 if let self = self { self.articleWritten += 1 } if let `self` = self { self.articleWritten += 1 } guard let self = self else { return } self.articleWritten += 1 } write() } } struct T { var mutable: Int = 0 func f() { // expected-error @+2 {{keyword 'self' cannot be used as an identifier here}} // expected-note @+1 {{if this name is unavoidable, use backticks to escape it}} let self = self } } class MyCls { func something() {} func test() { // expected-warning @+1 {{initialization of immutable value 'self' was never used}} let `self` = Writer() // Even if `self` is shadowed, something() // this should still refer `MyCls.something`. } } // https://github.com/apple/swift/issues/47136 // Method called 'self' can be confused with regular 'self' func funcThatReturnsSomething(_ any: Any) -> Any { any } struct TypeWithSelfMethod { let property = self // expected-warning {{'self' refers to the method 'TypeWithSelfMethod.self', which may be unexpected}} expected-note{{use 'TypeWithSelfMethod.self' to silence this warning}} {{20-20=TypeWithSelfMethod.}} // Existing warning expected, not confusable let property2 = self() // expected-error {{cannot use instance member 'self' within property initializer; property initializers run before 'self' is available}} let propertyFromClosure: () = { print(self) // expected-warning {{'self' refers to the method 'TypeWithSelfMethod.self', which may be unexpected}} expected-note{{use 'TypeWithSelfMethod.self' to silence this warning}} {{15-15=TypeWithSelfMethod.}} }() let propertyFromFunc = funcThatReturnsSomething(self) // expected-warning {{'self' refers to the method 'TypeWithSelfMethod.self', which may be unexpected}} expected-note{{use 'TypeWithSelfMethod.self' to silence this warning}} {{53-53=TypeWithSelfMethod.}} let propertyFromFunc2 = funcThatReturnsSomething(TypeWithSelfMethod.self) // OK func `self`() { } } /// Test fix_unqualified_access_member_named_self doesn't appear for computed var called `self` /// it can't currently be referenced as a static member -- unlike a method with the same name struct TypeWithSelfComputedVar { let property = self // expected-error {{cannot use instance member 'self' within property initializer; property initializers run before 'self' is available}} let propertyFromClosure: () = { print(self) // expected-error {{cannot use instance member 'self' within property initializer; property initializers run before 'self' is available}} }() let propertyFromFunc = funcThatReturnsSomething(self) // expected-error {{cannot use instance member 'self' within property initializer; property initializers run before 'self' is available}} var `self`: () { () } } /// Test fix_unqualified_access_member_named_self doesn't appear for property called `self` /// it can't currently be referenced as a static member -- unlike a method with the same name struct TypeWithSelfProperty { let property = self // expected-error {{cannot use instance member 'self' within property initializer; property initializers run before 'self' is available}} let propertyFromClosure: () = { print(self) // expected-error {{cannot use instance member 'self' within property initializer; property initializers run before 'self' is available}} }() let propertyFromFunc = funcThatReturnsSomething(self) // expected-error {{cannot use instance member 'self' within property initializer; property initializers run before 'self' is available}} let `self`: () = () } enum EnumCaseNamedSelf { case `self` init() { self = .self // OK self = .`self` // OK self = EnumCaseNamedSelf.`self` // OK } } // rdar://90624344 - warning about `self` which cannot be fixed because it's located in implicitly generated code. struct TestImplicitSelfUse : Codable { let `self`: Int // Ok }
apache-2.0
68951fab63a4bc201359ee791710db82
34.41791
261
0.644332
4.468927
false
false
false
false
huonw/swift
test/ClangImporter/sdk-bridging-header.swift
28
1402
// RUN: %target-swift-frontend -typecheck -verify %s -import-objc-header %S/Inputs/sdk-bridging-header.h // RUN: not %target-swift-frontend -typecheck %s -import-objc-header %S/Inputs/bad-bridging-header.h 2>&1 | %FileCheck -check-prefix=CHECK-FATAL %s // RUN: %target-swift-frontend -typecheck -verify %s -Xcc -include -Xcc %S/Inputs/sdk-bridging-header.h -import-objc-header %S/../Inputs/empty.swift // RUN: not %target-swift-frontend -typecheck %s -Xcc -include -Xcc %S/Inputs/bad-bridging-header.h 2>&1 | %FileCheck -check-prefix=CHECK-INCLUDE %s // RUN: not %target-swift-frontend -typecheck %s -Xcc -include -Xcc %S/Inputs/bad-bridging-header.h -import-objc-header %S/../Inputs/empty.swift 2>&1 | %FileCheck -check-prefix=CHECK-INCLUDE %s // RUN: not %target-swift-frontend -typecheck %s -Xcc -include -Xcc %S/Inputs/bad-bridging-header.h -import-objc-header %S/Inputs/sdk-bridging-header.h 2>&1 | %FileCheck -check-prefix=CHECK-INCLUDE %s // CHECK-FATAL: failed to import bridging header // CHECK-INCLUDE: error: 'this-header-does-not-exist.h' file not found // CHECK-INCLUDE: error: use of unresolved identifier 'MyPredicate' // REQUIRES: objc_interop import Foundation let `true` = MyPredicate.`true`() let not = MyPredicate.not() let and = MyPredicate.and([]) let or = MyPredicate.or([not, and]) _ = MyPredicate.foobar() // expected-error{{type 'MyPredicate' has no member 'foobar'}}
apache-2.0
45b1f073b3d9a57aad9e2e81abf71899
57.416667
200
0.728245
3.115556
false
false
false
false
huonw/swift
test/Interpreter/layout_reabstraction.swift
70
2394
// RUN: %target-run-simple-swift | %FileCheck %s // REQUIRES: executable_test struct S {} struct Q {} func printMetatype<T>(_ x: Any, _: T.Type) { debugPrint(x as! T.Type) } func printMetatypeConditional<T>(_ x: Any, _: T.Type) { if let y = x as? T.Type { debugPrint(y) } else { print("nope") } } var any: Any = S.self // CHECK: downcast in substituted context: print("downcast in substituted context:") // CHECK-NEXT: main.S debugPrint(any as! S.Type) // CHECK-NEXT: nope if let q = any as? Q.Type { print(q) } else { print("nope") } // CHECK-NEXT: downcast in generic context: print("downcast in generic context:") // CHECK-NEXT: main.S printMetatype(any, S.self) // CHECK-NEXT: main.S printMetatypeConditional(any, S.self) // CHECK-NEXT: nope printMetatypeConditional(any, Q.self) // Unspecialized wrapper around sizeof(T) to force us to get the runtime's idea // of the size of a type. @inline(never) func unspecializedSizeOf<T>(_ t: T.Type) -> Int { return MemoryLayout<T>.size } struct ContainsTrivialMetatype<T> { var x: T var meta: S.Type } struct ContainsTupleOfTrivialMetatype<T> { var x: (T, S.Type) } // CHECK-NEXT: 8 print(MemoryLayout<ContainsTrivialMetatype<Int64>>.size) // CHECK-NEXT: 8 print(unspecializedSizeOf(ContainsTrivialMetatype<Int64>.self)) // CHECK-NEXT: 8 print(MemoryLayout<ContainsTupleOfTrivialMetatype<Int64>>.size) // CHECK-NEXT: 8 print(unspecializedSizeOf(ContainsTupleOfTrivialMetatype<Int64>.self)) struct ContainsTupleOfFunctions<T> { var x: (T, (T) -> T) func apply() -> T { return x.1(x.0) } } // CHECK-NEXT: 2 print(MemoryLayout<ContainsTupleOfFunctions<()>>.size / MemoryLayout<Int>.size) // CHECK-NEXT: 2 print(unspecializedSizeOf(ContainsTupleOfFunctions<()>.self) / MemoryLayout<Int>.size) // CHECK-NEXT: 3 print(MemoryLayout<ContainsTupleOfFunctions<Int>>.size / MemoryLayout<Int>.size) // CHECK-NEXT: 3 print(unspecializedSizeOf(ContainsTupleOfFunctions<Int>.self) / MemoryLayout<Int>.size) let x = ContainsTupleOfFunctions(x: (1, { $0 + 1 })) let y = ContainsTupleOfFunctions(x: ("foo", { $0 + "bar" })) // CHECK-NEXT: 2 print(x.apply()) // CHECK-NEXT: foobar print(y.apply()) func callAny<T>(_ f: Any, _ x: T) -> T { return (f as! (T) -> T)(x) } any = {(x: Int) -> Int in x + x} // CHECK-NEXT: 24 print((any as! (Int) -> Int)(12)) // CHECK-NEXT: 24 let ca = callAny(any, 12) print(ca)
apache-2.0
c1856698d6674cdcdf1db855885c90e8
22.94
87
0.685464
3.101036
false
false
false
false
faimin/ZDOpenSourceDemo
ZDOpenSourceSwiftDemo/Pods/lottie-ios/lottie-swift/src/Private/NodeRenderSystem/Nodes/RenderNodes/StrokeNode.swift
1
3890
// // StrokeNode.swift // lottie-swift // // Created by Brandon Withrow on 1/22/19. // import Foundation import QuartzCore // MARK: - Properties final class StrokeNodeProperties: NodePropertyMap, KeypathSearchable { init(stroke: Stroke) { self.keypathName = stroke.name self.color = NodeProperty(provider: KeyframeInterpolator(keyframes: stroke.color.keyframes)) self.opacity = NodeProperty(provider: KeyframeInterpolator(keyframes: stroke.opacity.keyframes)) self.width = NodeProperty(provider: KeyframeInterpolator(keyframes: stroke.width.keyframes)) self.miterLimit = CGFloat(stroke.miterLimit) self.lineCap = stroke.lineCap self.lineJoin = stroke.lineJoin if let dashes = stroke.dashPattern { var dashPatterns = [[Keyframe<Vector1D>]]() var dashPhase = [Keyframe<Vector1D>]() for dash in dashes { if dash.type == .offset { dashPhase = dash.value.keyframes } else { dashPatterns.append(dash.value.keyframes) } } self.dashPattern = NodeProperty(provider: GroupInterpolator(keyframeGroups: dashPatterns)) if dashPhase.count == 0 { self.dashPhase = NodeProperty(provider: SingleValueProvider(Vector1D(0))) } else { self.dashPhase = NodeProperty(provider: KeyframeInterpolator(keyframes: dashPhase)) } } else { self.dashPattern = NodeProperty(provider: SingleValueProvider([Vector1D]())) self.dashPhase = NodeProperty(provider: SingleValueProvider(Vector1D(0))) } self.keypathProperties = [ "Opacity" : opacity, "Color" : color, "Stroke Width" : width, "Dashes" : dashPattern, "Dash Phase" : dashPhase ] self.properties = Array(keypathProperties.values) } let keypathName: String let keypathProperties: [String : AnyNodeProperty] let properties: [AnyNodeProperty] let opacity: NodeProperty<Vector1D> let color: NodeProperty<Color> let width: NodeProperty<Vector1D> let dashPattern: NodeProperty<[Vector1D]> let dashPhase: NodeProperty<Vector1D> let lineCap: LineCap let lineJoin: LineJoin let miterLimit: CGFloat } // MARK: - Node /// Node that manages stroking a path final class StrokeNode: AnimatorNode, RenderNode { let strokeRender: StrokeRenderer var renderer: NodeOutput & Renderable { return strokeRender } let strokeProperties: StrokeNodeProperties init(parentNode: AnimatorNode?, stroke: Stroke) { self.strokeRender = StrokeRenderer(parent: parentNode?.outputNode) self.strokeProperties = StrokeNodeProperties(stroke: stroke) self.parentNode = parentNode } // MARK: Animator Node Protocol var propertyMap: NodePropertyMap & KeypathSearchable { return strokeProperties } let parentNode: AnimatorNode? var hasLocalUpdates: Bool = false var hasUpstreamUpdates: Bool = false var lastUpdateFrame: CGFloat? = nil var isEnabled: Bool = true { didSet { strokeRender.isEnabled = isEnabled } } func localUpdatesPermeateDownstream() -> Bool { return false } func rebuildOutputs(frame: CGFloat) { strokeRender.color = strokeProperties.color.value.cgColorValue strokeRender.opacity = strokeProperties.opacity.value.cgFloatValue * 0.01 strokeRender.width = strokeProperties.width.value.cgFloatValue strokeRender.miterLimit = strokeProperties.miterLimit strokeRender.lineCap = strokeProperties.lineCap strokeRender.lineJoin = strokeProperties.lineJoin /// Get dash lengths let dashLengths = strokeProperties.dashPattern.value.map { $0.cgFloatValue } if dashLengths.count > 0 { strokeRender.dashPhase = strokeProperties.dashPhase.value.cgFloatValue strokeRender.dashLengths = dashLengths } else { strokeRender.dashLengths = nil strokeRender.dashPhase = nil } } }
mit
60e3fa09a65a92555cd5adbbfcf7faa2
29.629921
100
0.709254
4.73236
false
false
false
false
IvanVorobei/ParallaxTableView
ParallaxTableView - project/ParallaxTableView/Sparrow/UI/Views/CollectionViews/CollectionViews/SPPageItemsScalingCollectionView.swift
1
1094
// // dsa.swift // createBageCollectionView // // Created by Ivan Vorobei on 9/6/16. // Copyright © 2016 Ivan Vorobei. All rights reserved. // import UIKit class SPPageItemsScalingCollectionView: UICollectionView { var layout = SPPageItemsScalingCollectionLayout() required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) commonInit() } init(frame: CGRect) { super.init(frame: frame, collectionViewLayout: self.layout) commonInit() } init() { super.init(frame: CGRect.zero, collectionViewLayout: self.layout) commonInit() } } // MARK: create extension SPPageItemsScalingCollectionView { fileprivate func commonInit() { self.backgroundColor = UIColor.clear self.collectionViewLayout = self.layout self.decelerationRate = UIScrollViewDecelerationRateFast self.delaysContentTouches = false self.isPagingEnabled = false self.showsHorizontalScrollIndicator = false self.showsVerticalScrollIndicator = false } }
mit
552888c82dabfb3ba457319850088719
23.288889
73
0.671546
4.945701
false
false
false
false
MinMao-Hub/MMActionSheet
Sources/MMActionSheet/MMTitleItem.swift
1
1076
// // MMTitleItem.swift // swiftui // // Created by JefferDevs on 2021/9/13. // Copyright © 2021 keeponrunning. All rights reserved. // import UIKit public struct MMTitleItem { /// text public var text: String? /// text color public var textColor: UIColor? /// textFont public var textFont: UIFont? = .systemFont(ofSize: 14.0) /// textAlignment public var textAlignment: NSTextAlignment? = .center /// backgroundColor public var backgroundColor: MMButtonTitleColor? = .custom(UIColor.clear) public init(title: String?, titleColor: UIColor? = MMButtonTitleColor.default.rawValue, titleFont: UIFont? = .systemFont(ofSize: 14.0), textAlignment: NSTextAlignment? = .center, backgroundColor: MMButtonTitleColor? = .custom(UIColor.clear) ) { self.text = title self.textColor = titleColor self.textFont = titleFont self.textAlignment = textAlignment self.backgroundColor = backgroundColor ?? .custom(UIColor.clear) } }
mit
5ddaccdd8df1e5e3aa57837e1212b5a9
29.714286
77
0.646512
4.535865
false
false
false
false
fellipecaetano/Democracy-iOS
Pods/RandomKit/Sources/RandomKit/Types/RandomInClosedRange.swift
3
6306
// // RandomInClosedRange.swift // RandomKit // // The MIT License (MIT) // // Copyright (c) 2015-2017 Nikolai Vazquez // // 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. // /// A type that can generate an random value in a closed range. public protocol RandomInClosedRange: Comparable { /// Returns a random value of `Self` inside of the closed range using `randomGenerator`. static func random<R: RandomGenerator>(in closedRange: ClosedRange<Self>, using randomGenerator: inout R) -> Self } extension RandomInClosedRange where Self: Strideable & Comparable, Self.Stride : SignedInteger { /// Returns a random value of `Self` inside of the closed range. public static func random<R: RandomGenerator>(in closedRange: CountableClosedRange<Self>, using randomGenerator: inout R) -> Self { return random(in: ClosedRange(closedRange), using: &randomGenerator) } } extension RandomInClosedRange { #if swift(>=3.2) /// Returns a sequence of random values in `closedRange` using `randomGenerator`. public static func randoms<R>(in closedRange: ClosedRange<Self>, using randomGenerator: inout R) -> RandomsWithinClosedRange<Self, R> { return RandomsWithinClosedRange(closedRange: closedRange, randomGenerator: &randomGenerator) } /// Returns a sequence of random values limited by `limit` in `closedRange` using `randomGenerator`. public static func randoms<R>(limitedBy limit: Int, in closedRange: ClosedRange<Self>, using randomGenerator: inout R) -> LimitedRandomsWithinClosedRange<Self, R> { return LimitedRandomsWithinClosedRange(limit: limit, closedRange: closedRange, randomGenerator: &randomGenerator) } #else /// Returns a sequence of random values in `closedRange` using `randomGenerator`. public static func randoms<R: RandomGenerator>(in closedRange: ClosedRange<Self>, using randomGenerator: inout R) -> RandomsWithinClosedRange<Self, R> { return RandomsWithinClosedRange(closedRange: closedRange, randomGenerator: &randomGenerator) } /// Returns a sequence of random values limited by `limit` in `closedRange` using `randomGenerator`. public static func randoms<R: RandomGenerator>(limitedBy limit: Int, in closedRange: ClosedRange<Self>, using randomGenerator: inout R) -> LimitedRandomsWithinClosedRange<Self, R> { return LimitedRandomsWithinClosedRange(limit: limit, closedRange: closedRange, randomGenerator: &randomGenerator) } #endif } /// A sequence of random values of a `RandomInClosedRange` type, generated by a `RandomGenerator`. /// /// - warning: An instance *should not* outlive its `RandomGenerator`. /// /// - seealso: `LimitedRandomsWithinClosedRange` public struct RandomsWithinClosedRange<Element: RandomInClosedRange, RG: RandomGenerator>: IteratorProtocol, Sequence { /// A pointer to the `RandomGenerator` private let _randomGenerator: UnsafeMutablePointer<RG> /// The closed range to generate in. public var closedRange: ClosedRange<Element> /// Creates an instance with `closedRange` and `randomGenerator`. public init(closedRange: ClosedRange<Element>, randomGenerator: inout RG) { _randomGenerator = UnsafeMutablePointer(&randomGenerator) self.closedRange = closedRange } /// Advances to the next element and returns it, or `nil` if no next element /// exists. Once `nil` has been returned, all subsequent calls return `nil`. public mutating func next() -> Element? { return Element.random(in: closedRange, using: &_randomGenerator.pointee) } } /// A limited sequence of random values of a `RandomInClosedRange` type, generated by a `RandomGenerator`. /// /// - warning: An instance *should not* outlive its `RandomGenerator`. /// /// - seealso: `RandomsWithinClosedRange` public struct LimitedRandomsWithinClosedRange<Element: RandomInClosedRange, RG: RandomGenerator>: IteratorProtocol, Sequence { /// A pointer to the `RandomGenerator` private let _randomGenerator: UnsafeMutablePointer<RG> /// The iteration for the random value generation. private var _iteration: Int = 0 /// The limit value. public var limit: Int /// The closed range to generate in. public var closedRange: ClosedRange<Element> /// A value less than or equal to the number of elements in /// the sequence, calculated nondestructively. /// /// - Complexity: O(1) public var underestimatedCount: Int { return limit &- _iteration } /// Creates an instance with `limit`, `closedRange`, and `randomGenerator`. public init(limit: Int, closedRange: ClosedRange<Element>, randomGenerator: inout RG) { _randomGenerator = UnsafeMutablePointer(&randomGenerator) self.limit = limit self.closedRange = closedRange } /// Advances to the next element and returns it, or `nil` if no next element /// exists. Once `nil` has been returned, all subsequent calls return `nil`. public mutating func next() -> Element? { guard _iteration < limit else { return nil } _iteration = _iteration &+ 1 return Element.random(in: closedRange, using: &_randomGenerator.pointee) } }
mit
0c3c91df03c8c86622ea7e3279450ee5
42.489655
185
0.720425
4.727136
false
false
false
false
sora0077/QiitaKit
QiitaKit/src/Endpoint/Project/ListProjects.swift
1
2382
// // ListProjects.swift // QiitaKit // // Created on 2015/06/08. // Copyright (c) 2015年 林達也. All rights reserved. // import Foundation import APIKit import Result /** * チーム内に存在するプロジェクト一覧をプロジェクト作成日時の降順で返します。 */ public struct ListProjects { /// ページ番号 (1から100まで) /// example: 1 /// ^[0-9]+$ public let page: Int /// 1ページあたりに含まれる要素数 (1から100まで) /// example: 20 /// ^[0-9]+$ public let per_page: Int public init(page: Int, per_page: Int = 20) { self.page = page self.per_page = per_page } } extension ListProjects: QiitaRequestToken { public typealias Response = ([Project], LinkMeta<ListProjects>) public typealias SerializedObject = [[String: AnyObject]] public var method: HTTPMethod { return .GET } public var path: String { return "/api/v2/projects" } public var parameters: [String: AnyObject]? { return [ "page": page, "per_page": per_page ] } } extension ListProjects: LinkProtocol { public init(url: NSURL!) { let comps = NSURLComponents(URL: url, resolvingAgainstBaseURL: false) self.page = Int(find(comps?.queryItems ?? [], name: "page")!.value!)! if let value = find(comps?.queryItems ?? [], name: "per_page")?.value, let per_page = Int(value) { self.per_page = per_page } else { self.per_page = 20 } } } public extension ListProjects { func transform(request: NSURLRequest?, response: NSHTTPURLResponse?, object: SerializedObject) throws -> Response { let projects = object.map { object in return Project( rendered_body: object["rendered_body"] as! String, archived: object["archived"] as! Bool, body: object["body"] as! String, created_at: object["created_at"] as! String, id: object["id"] as! Int, name: object["name"] as! String, updated_at: object["updated_at"] as! String ) } return (projects, LinkMeta<ListProjects>(dict: response!.allHeaderFields)) } }
mit
c608b525192fddb15037aa2c516873eb
24.235955
119
0.559216
3.93345
false
false
false
false
dduan/cURLLook
cURLLook/NSURLRequestCURLRepresentation.swift
1
3935
// // NSURLRequestCURLRepresentation.swift // cURLLook // // Created by Daniel Duan on 9/5/15. // // import Foundation extension NSURLRequest { /** Convenience property, the value of calling `cURLRepresentation()` with no arguments. */ public var cURLString: String { get { return cURLRepresentation() } } /** cURL (http://http://curl.haxx.se) is a commandline tool that makes network requests. This method serializes a `NSURLRequest` to a cURL command that performs the same HTTP request. - Parameter session: *optional* the `NSURLSession` this NSURLRequest is being used with. Extra information from the session such as cookies and credentials may be included in the result. - Parameter credential: *optional* the credential to include in the result. The value of `session?.configuration.URLCredentialStorage`, when present, would override this argument. - Returns: a string whose value is a cURL command that would perform the same HTTP request this object represents. */ public func cURLRepresentation(withURLSession session: NSURLSession? = nil, credential: NSURLCredential? = nil) -> String { var components = ["curl -i"] let URL = self.URL if let HTTPMethod = self.HTTPMethod where HTTPMethod != "GET" { components.append("-X \(HTTPMethod)") } if let credentialStorage = session?.configuration.URLCredentialStorage { let protectionSpace = NSURLProtectionSpace( host: URL!.host!, port: URL!.port?.integerValue ?? 0, protocol: URL!.scheme, realm: URL!.host!, authenticationMethod: NSURLAuthenticationMethodHTTPBasic ) if let credentials = credentialStorage.credentialsForProtectionSpace(protectionSpace)?.values { for credential in credentials { components.append("-u \(credential.user!):\(credential.password!)") } } else { if credential != nil { components.append("-u \(credential!.user!):\(credential!.password!)") } } } if session != nil && session!.configuration.HTTPShouldSetCookies { if let cookieStorage = session!.configuration.HTTPCookieStorage, cookies = cookieStorage.cookiesForURL(URL!) where !cookies.isEmpty { let string = cookies.reduce("") { $0 + "\($1.name)=\($1.value ?? String());" } components.append("-b \"\(string.substringToIndex(string.endIndex.predecessor()))\"") } } if let headerFields = self.allHTTPHeaderFields { for (field, value) in headerFields { switch field { case "Cookie": continue default: components.append("-H \"\(field): \(value)\"") } } } if let additionalHeaders = session?.configuration.HTTPAdditionalHeaders { for (field, value) in additionalHeaders { switch field { case "Cookie": continue default: components.append("-H \"\(field): \(value)\"") } } } if let HTTPBodyData = self.HTTPBody, HTTPBody = NSString(data: HTTPBodyData, encoding: NSUTF8StringEncoding) { let escapedBody = HTTPBody.stringByReplacingOccurrencesOfString("\"", withString: "\\\"") components.append("-d \"\(escapedBody)\"") } components.append("\"\(URL!.absoluteString)\"") return components.joinWithSeparator(" \\\n\t") } }
mit
fc36796f269e88ba919e9e6e7505b7e4
36.122642
139
0.561626
5.744526
false
false
false
false
dbart01/Spyder
Spyder Tests/JWT/Extensions/Data+Base64Tests.swift
1
692
// // Data+Base64Tests.swift // Spyder Tests // // Created by Dima Bart on 2018-02-06. // Copyright © 2018 Dima Bart. All rights reserved. // import XCTest class Data_Base64Tests: XCTestCase { // ---------------------------------- // MARK: - Base64 - // func testStandardBenchmark() { let content = "j_}u~?M~|\\/.><~9" let encoded = content.data(using: .utf8)?.base64EncodedString() XCTAssertEqual(encoded, "al99dX4/TX58XC8uPjx+OQ==") } func testURLEncoding() { let content = "j_}u~?M~|\\/.><~9" let encoded = content.data(using: .utf8)?.base64URL XCTAssertEqual(encoded, "al99dX4_TX58XC8uPjx-OQ") } }
bsd-2-clause
5c95593ae5cb50f6e8f56b5abde59cfe
24.592593
71
0.564399
3.244131
false
true
false
false
OatmealCode/Oatmeal
Pod/Classes/Cache/MemoryCache.swift
1
2083
// // Cache.swift // Pods // // Created by Michael Kantor on 8/21/15. // // import Foundation import Carlos import SwiftyJSON public class MemoryCache : NSObject,Cacheable{ var log : FileLog? public static var entityName : String? = "MemoryCache" public var linkToDisk = true public required override init() { super.init() } /** - parameter key: The Cache Key - returns: the resolved cached object **/ public func get(key: String,completion:(response: ResponseHandler) -> Void) { let cache = MemoryCacheLevel<String,NSData>() let request = cache.get(key) var handler = ResponseHandler() request.onSuccess { value in let json = JSON(data :value) handler.response = json handler.responseString = json.rawString() handler.success = true completion(response: handler) } request.onFailure { error in if let fileCache : FileCache = ~Oats() where self.linkToDisk { fileCache.get(key, completion: completion) } else { handler.success = false handler.error = error completion(response: handler) } } } /** - parameter key: The Cache Key - parameter value : The object being cached **/ public func set<T: Resolveable>(key:String,value:T) { let json = value.toJSON() let memoryCache = MemoryCacheLevel<String, NSData>() if let asString = json.rawString(), encoded = asString.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false) { print("Setting \(asString)") memoryCache.set(encoded, forKey: key) if let fileCache : FileCache = ~Oats() where linkToDisk { fileCache.set(key, value: value) } } } }
mit
79b53f0d51753651daa8f5c0f4869e83
25.05
131
0.536726
4.959524
false
false
false
false
dvlproad/CJUIKit
CJBaseUIKit-Swift/UIButton/UIButton+CJMoreProperty.swift
1
4472
// // UIButton+CJMoreProperty.m // CJUIKitDemo // // Created by ciyouzen on 7/9/15. // Copyright (c) 2015 dvlproad. All rights reserved. // typealias CJButtonTouchBlock = (_ button: UIButton) -> () private var cjNormalBGColorKey: String = "cjNormalBGColorKey" private var cjHighlightedBGColorKey: String = "cjHighlightedBGColorKey" private var cjDisabledBGColorKey: String = "cjDisabledBGColorKey" private var cjSelectedBGColorKey: String = "cjSelectedBGColorKey" private var cjTouchUpInsideBlockKey: String = "cjTouchUpInsideBlockKey" private var cjDataModelKey: String = "cjDataModelKey" extension UIButton { // MARK: - runtime 颜色相关 /// 设置按钮默认时候的背景颜色 var cjNormalBGColor: UIColor { get { return objc_getAssociatedObject(self, &cjNormalBGColorKey) as! UIColor } set { objc_setAssociatedObject(self, &cjNormalBGColorKey, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) let normalBGImage: UIImage = UIButton.cj_buttonBGImage(bgColor: newValue) self.setBackgroundImage(normalBGImage, for: .normal) } } /// 设置按钮高亮时候的背景颜色 var cjHighlightedBGColor: UIColor { get { return objc_getAssociatedObject(self, &cjHighlightedBGColorKey) as! UIColor } set { objc_setAssociatedObject(self, &cjHighlightedBGColorKey, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) let highlightedBGImage: UIImage = UIButton.cj_buttonBGImage(bgColor: newValue) self.setBackgroundImage(highlightedBGImage, for: .highlighted) } } /// 设置按钮失效时候的背景颜色 var cjDisabledBGColor: UIColor { get { return objc_getAssociatedObject(self, &cjDisabledBGColorKey) as! UIColor } set { objc_setAssociatedObject(self, &cjDisabledBGColorKey, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) let disabledBGImage: UIImage = UIButton.cj_buttonBGImage(bgColor: newValue) self.setBackgroundImage(disabledBGImage, for: .disabled) } } /// 设置按钮失效时候的背景颜色 var cjSelectedBGColor: UIColor { get { return objc_getAssociatedObject(self, &cjSelectedBGColorKey) as! UIColor } set { objc_setAssociatedObject(self, &cjSelectedBGColorKey, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) let selectedBGImage: UIImage = UIButton.cj_buttonBGImage(bgColor: newValue) self.setBackgroundImage(selectedBGImage, for: .selected) } } /// 使用颜色构建的背景图片 class func cj_buttonBGImage(bgColor: UIColor) -> UIImage { let rect: CGRect = CGRect(x: 0, y: 0, width: 1, height: 1) UIGraphicsBeginImageContext(rect.size) let context: CGContext = UIGraphicsGetCurrentContext()! context.setFillColor(bgColor.cgColor) context.fill(rect) let bgImage: UIImage = UIGraphicsGetImageFromCurrentImageContext()! UIGraphicsEndImageContext() return bgImage } // MARK: - runtime 数据相关 /// 设置按钮持有的数据对象 var cjDataModel: Any { get { return objc_getAssociatedObject(self, &cjDataModelKey) as! UIColor } set { objc_setAssociatedObject(self, &cjDataModelKey, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } // MARK: - runtime 事件点击相关 /// 设置按钮操作的事件 var cjTouchUpInsideBlock: CJButtonTouchBlock { get { return objc_getAssociatedObject(self, &cjTouchUpInsideBlockKey) as! CJButtonTouchBlock } set { objc_setAssociatedObject(self, &cjTouchUpInsideBlockKey, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_COPY_NONATOMIC) //设置的时候,就给他添加方法,省得再多个接口处理 self.addTarget(self, action: #selector(cjTouchUpInsideAction(button:)), for: .touchUpInside) } } /// 按钮点击事件 @objc func cjTouchUpInsideAction(button: UIButton) { self.cjTouchUpInsideBlock(button) } }
mit
9d0ddd6cedd8d0915b42f7c129e35ef5
33.590164
136
0.653791
4.386694
false
false
false
false
apple/swift-docc-symbolkit
Sources/dump-unified-graph/DumpUnifiedGraph.swift
1
4506
/* This source file is part of the Swift.org open source project Copyright (c) 2022 Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See https://swift.org/LICENSE.txt for license information See https://swift.org/CONTRIBUTORS.txt for Swift project authors */ import Foundation import ArgumentParser import SymbolKit @main struct DumpUnifiedGraph: ParsableCommand { static let configuration = CommandConfiguration( commandName: "dump-unified-graph", abstract: "Collects a unified symbol graph from given inputs and renders it to JSON") @Option( help: ArgumentHelp( "module's symbol graph to output", discussion: "will infer a single module, but will fail if multiple modules are being loaded", valueName: "name")) var moduleName: String? @Flag(inversion: .prefixedNo, help: "whether to pretty-print the output JSON") var prettyPrint: Bool = true @Option( name: .shortAndLong, help: ArgumentHelp( "output file to write to (default: standard out)", valueName: "file")) var output: String? @Option( help: ArgumentHelp( "directory to recursively load symbol graphs from", valueName: "dir"), completion: .directory) var symbolGraphDir: String? @Argument( help: ArgumentHelp( "individual symbol graphs to load", valueName: "file"), completion: .file(extensions: ["json"])) var files: [String] = [] mutating func validate() throws { guard !files.isEmpty || symbolGraphDir != nil else { throw ValidationError("Please provide files or a symbol graph directory") } if let symbolGraphDir = symbolGraphDir { if !FileManager.default.fileExists(atPath: symbolGraphDir) { throw ValidationError("Given symbol graph directory does not exist") } if !symbolGraphDir.hasSuffix("/") { self.symbolGraphDir = symbolGraphDir.appending("/") } } } func run() throws { var symbolGraphs = files if let symbolGraphDir = symbolGraphDir { symbolGraphs.append(contentsOf: loadSymbolGraphsFromDir(symbolGraphDir)) } if symbolGraphs.isEmpty { print("error: No symbol graphs were available") throw ExitCode.failure } let decoder = JSONDecoder() let collector = GraphCollector() for symbolGraph in symbolGraphs { let graphUrl = URL(fileURLWithPath: symbolGraph) let decodedGraph = try decoder.decode(SymbolGraph.self, from: Data(contentsOf: graphUrl)) collector.mergeSymbolGraph(decodedGraph, at: graphUrl) } let (unifiedGraphs, _) = collector.finishLoading() let outputGraph: UnifiedSymbolGraph if let moduleName = moduleName { if let graph = unifiedGraphs[moduleName] { outputGraph = graph } else { print("error: The given module was not represented in the symbol graphs") throw ExitCode.failure } } else { if unifiedGraphs.count > 1 { print("error: No module was given, but more than one module was represented in the symbol graphs") throw ExitCode.failure } else { outputGraph = unifiedGraphs.values.first! } } let encoder = JSONEncoder() if #available(macOS 10.13, *) { encoder.outputFormatting.insert(.sortedKeys) } if prettyPrint { encoder.outputFormatting.insert(.prettyPrinted) } let encoded = try encoder.encode(outputGraph) if let output = output, output != "-" { FileManager.default.createFile(atPath: output, contents: encoded) } else { let outString = String(data: encoded, encoding: .utf8) print(outString!) } } } func loadSymbolGraphsFromDir(_ dir: String) -> [String] { let enumerator = FileManager.default.enumerator(atPath: dir) var symbolGraphs: [String] = [] while let filename = enumerator?.nextObject() as? String { if filename.hasSuffix(".symbols.json") { symbolGraphs.append(dir.appending(filename)) } } return symbolGraphs }
apache-2.0
a26110f176ff853ea7d33ef393e260d7
31.890511
114
0.612295
4.968026
false
false
false
false
CodeMozart/MHzSinaWeibo-Swift-
SinaWeibo(stroyboard)/SinaWeibo/Classes/NewFeatureViewController.swift
1
5949
// // NewFeatureViewController.swift // SinaWeibo // // Created by Minghe on 11/12/15. // Copyright © 2015 Stanford swift. All rights reserved. // import UIKit import SnapKit class NewFeatureViewController: UIViewController,UICollectionViewDataSource,UICollectionViewDelegate { /// let maxImageCount = 4 override func viewDidLoad() { super.viewDidLoad() } // MARK: - UICollectionView DataSource ------------------------------ /// func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return maxImageCount } // 告诉系统当前行现实什么内容 func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCellWithReuseIdentifier("NewFeatureCell", forIndexPath: indexPath) as! MHzCollectionViewCell cell.index = indexPath.item // 以下代码,主要为了避免重用问题 cell.startButton.hidden = true return cell } // MARK: - UICollectionView Delegate ------------------------------ /** Tells the delegate that the specified cell was removed from the collection view. 当一个cell显示完了之后(离开屏幕)会调用 - parameter collectionView: 当前的collectionView - parameter cell: 上一页的那个cell - parameter indexPath: 上一页的索引 */ func collectionView(collectionView: UICollectionView, didEndDisplayingCell cell: UICollectionViewCell, forItemAtIndexPath indexPath: NSIndexPath) { // 1.获取当前展现在眼前的cell对应的索引 let path = collectionView.indexPathsForVisibleItems().last! // 2.根据索引取出当前展现在眼前的cell let cell = collectionView.cellForItemAtIndexPath(path) as! MHzCollectionViewCell // 3.判断是不是最后一页 if path.item == maxImageCount - 1 { cell.startButton.hidden = false // 实现按钮出现的动画: // 1.动画时禁用按钮交互 cell.startButton.userInteractionEnabled = false // 2.动画的具体代码 // usingSpringWithDamping 的范围为 0.0f 到 1.0f ,数值越小「弹簧」的振动效果越明显。 // initialSpringVelocity 则表示初始的速度,数值越大一开始移动越快, 值得注意的是,初始速度取值较高而时间较短时,也会出现反弹情况 cell.startButton.transform = CGAffineTransformMakeScale(0.0, 0.0) UIView.animateWithDuration(2.0, delay: 0.0, usingSpringWithDamping: 0.5, initialSpringVelocity: 7.0, options: UIViewAnimationOptions(rawValue: 0), animations: { () -> Void in cell.startButton.transform = CGAffineTransformIdentity }, completion: { (_) -> Void in cell.startButton.userInteractionEnabled = true }) } } } class MHzCollectionViewCell: UICollectionViewCell { // MARK: - 懒加载 ------------------------------ /// 大图容器 private lazy var iconView = UIImageView() /// 开始按钮 private lazy var startButton: UIButton = { let btn = UIButton(backgroundImage: "new_feature_button") btn.addTarget(self, action: Selector("startBtnClick"), forControlEvents: .TouchUpInside) btn.sizeToFit() return btn }() /// var index: Int = 0 { didSet{ iconView.image = UIImage(named: "new_feature_\(index + 1)") } } override init(frame: CGRect) { super.init(frame: frame) setupUI() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setupUI() } // MARK: - 内部控制方法 ------------------------------ /// private func setupUI() { // contentView.addSubview(iconView) contentView.addSubview(startButton) /* iconView.translatesAutoresizingMaskIntoConstraints = false var cons = NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[iconView]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["iconView": iconView]) cons += NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[iconView]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["iconView": iconView]) contentView.addConstraints(cons) */ iconView.snp_makeConstraints { (make) -> Void in make.edges.equalTo(0) } startButton.snp_makeConstraints { (make) -> Void in make.centerX.equalTo(contentView) make.bottom.equalTo(contentView.snp_bottom).offset(-150) } } /// 点击开始按钮 @objc private func startBtnClick() { // 发送通知,通知AppDelegate切换控制器 NSNotificationCenter.defaultCenter().postNotificationName(MHzRootViewControllerChanged, object: self, userInfo: nil) } } // 注意:Swift文件中一个文件中可以定义多个类 class MHzFlowLayout: UICollectionViewFlowLayout { // 流水布局 override func prepareLayout() { super.prepareLayout() itemSize = collectionView!.bounds.size minimumInteritemSpacing = 0 minimumLineSpacing = 0 scrollDirection = UICollectionViewScrollDirection.Horizontal collectionView?.bounces = false collectionView?.showsHorizontalScrollIndicator = false collectionView?.showsVerticalScrollIndicator = false collectionView?.pagingEnabled = true } }
mit
1ddffc270a0a1c074bf9a5f308f1deee
28.090909
186
0.613787
5.230769
false
false
false
false
hollance/swift-algorithm-club
Z-Algorithm/ZAlgorithm.swift
3
1477
/* Z-Algorithm for pattern/string pre-processing The code is based on the book: "Algorithms on String, Trees and Sequences: Computer Science and Computational Biology" by Dan Gusfield Cambridge University Press, 1997 */ import Foundation func ZetaAlgorithm(ptrn: String) -> [Int]? { let pattern = Array(ptrn) let patternLength = pattern.count guard patternLength > 0 else { return nil } var zeta = [Int](repeating: 0, count: patternLength) var left = 0 var right = 0 var k_1 = 0 var betaLength = 0 var textIndex = 0 var patternIndex = 0 for k in 1 ..< patternLength { if k > right { patternIndex = 0 while k + patternIndex < patternLength && pattern[k + patternIndex] == pattern[patternIndex] { patternIndex = patternIndex + 1 } zeta[k] = patternIndex if zeta[k] > 0 { left = k right = k + zeta[k] - 1 } } else { k_1 = k - left + 1 betaLength = right - k + 1 if zeta[k_1 - 1] < betaLength { zeta[k] = zeta[k_1 - 1] } else if zeta[k_1 - 1] >= betaLength { textIndex = betaLength patternIndex = right + 1 while patternIndex < patternLength && pattern[textIndex] == pattern[patternIndex] { textIndex = textIndex + 1 patternIndex = patternIndex + 1 } zeta[k] = patternIndex - k left = k right = patternIndex - 1 } } } return zeta }
mit
4223f55d2716286b64fbd265024855bb
21.723077
91
0.584292
3.683292
false
false
false
false
everald/JetPack
Build/PluralRulesGenerator/Sources/PluralRulesParser.swift
2
6265
import AEXML import Foundation // http://unicode.org/reports/tr35/tr35-numbers.html#Language_Plural_Rules // http://cldr.unicode.org/index/downloads internal struct PluralRulesParser { public func parse(xml data: Data) throws -> [PluralRuleSet] { let xml = try AEXMLDocument(xml: data) return try xml["supplementalData"]["plurals"].all? .filter { $0.attributes["type"] == "cardinal" } .flatMap { $0["pluralRules"].all ?? [] } .map(parseRuleSet) ?? [] } private func parseRule(xml: AEXMLElement) throws -> PluralRule { guard let category = xml.attributes["count"] else { throw Error(message: "Plural rule node is missing attribute 'count'.") } let tokens = try xml.string .components(separatedBy: "@")[0] .trimmingCharacters(in: .whitespaces) .components(separatedBy: .whitespaces) .map(parseRuleToken) var expressionParser = ExpressionParser(tokens: tokens) let expression = try expressionParser.parse() return PluralRule(category: category, expression: expression) } private func parseRuleSet(xml: AEXMLElement) throws -> PluralRuleSet { guard let locales = xml.attributes["locales"]?.components(separatedBy: .whitespaces), !locales.isEmpty else { throw Error(message: "Plural rule set node is missing attribute 'locales'.") } let rules = try xml["pluralRule"].all? .filter { $0.attributes["count"] != "other" } .map(parseRule) ?? [] return PluralRuleSet(locales: Set(locales), rules: rules) } private func parseRuleToken(_ string: String) throws -> RuleToken { switch string { case "f", "i", "n", "t", "v": return .variable(string) case "%": return .modulus case "=": return .equal case "!=": return .notEqual case "and": return .and case "or": return .or default: if string.contains(",") { let values = try string.components(separatedBy: ",").map { (component: String) -> PluralRule.Value in guard let value = try parseRuleValue(component) else { throw Error(message: "Invalid plural rule value '\(component)' in value list '\(string)' in expression.") } return value } return .multipleConstants(values) } else if let value = try parseRuleValue(string) { return .constant(value) } throw Error(message: "Unknown token '\(string)' in rule.") } } private func parseRuleValue(_ string: String) throws -> PluralRule.Value? { if !string.isEmpty && string.rangeOfCharacter(from: CharacterSet.decimalDigits.inverted) == nil { guard let number = Int(string) else { throw Error(message: "Invalid plural rule value '\(string)' in expression.") } return .number(number) } else if string.contains("..") { let components = string.components(separatedBy: "..") guard components.count == 2 else { throw Error(message: "Invalid plural rule value range '\(string)' in expression.") } guard let start = Int(components[0]) else { throw Error(message: "Invalid plural rule start value '\(components[0])' in range '\(string)' in expression.") } guard let end = Int(components[1]) else { throw Error(message: "Invalid plural rule end value '\(components[1])' in range '\(string)' in expression.") } return .numberRange(start ... end) } return nil } internal struct Error: Swift.Error { internal var message: String internal init(message: String) { self.message = message } } private struct ExpressionParser { private var index = 0 private let tokens: [RuleToken] fileprivate init(tokens: [RuleToken]) { self.tokens = tokens } private mutating func consumeCurrentToken() -> RuleToken { let token = tokens[index] index += 1 return token } private var currentToken: RuleToken? { guard index < tokens.count else { return nil } return tokens[index] } private func operatorForToken(_ token: RuleToken) -> PluralRule.BinaryOperator? { switch token { case .and: return .and case .equal: return .equal case .modulus: return .modulus case .notEqual: return .notEqual case .or: return .or default: return nil } } fileprivate mutating func parse() throws -> PluralRule.Expression { return try parseExpression() } private mutating func parseExpression() throws -> PluralRule.Expression { return try parseOperation(left: try parseValueOrVariable()) } private mutating func parseOperation(left: PluralRule.Expression, precedenceOfPreviousOperator: Int = 0) throws -> PluralRule.Expression { var left = left while let currentToken = currentToken { guard let op = operatorForToken(currentToken) else { throw Error(message: "Unexpected token '\(currentToken)' in rule.") } let tokenPrecedence = precedenceForOperator(op) if tokenPrecedence < precedenceOfPreviousOperator { return left } consumeCurrentToken() var right = try parseValueOrVariable() if let nextToken = self.currentToken, let nextOp = operatorForToken(nextToken), tokenPrecedence < precedenceForOperator(nextOp) { right = try parseOperation(left: right, precedenceOfPreviousOperator: tokenPrecedence + 1) } left = .binaryOperation(left: left, op: op, right: right) } return left } private mutating func parseValueOrVariable() throws -> PluralRule.Expression { let token = consumeCurrentToken() switch token { case let .constant(value): return .constant(value) case let .multipleConstants(values): return .multipleConstants(values) case let .variable(name): return .variable(name) default: throw Error(message: "Unexpected token '\(token)' in expression. Expected a variable or a value.") } } private func precedenceForOperator(_ op: PluralRule.BinaryOperator) -> Int { switch op { case .and: return 60 case .or: return 40 case .equal: return 80 case .modulus: return 100 case .notEqual: return 80 } } } private enum RuleToken { case and case constant(PluralRule.Value) case equal case modulus case multipleConstants([PluralRule.Value]) case notEqual case or case variable(String) } }
mit
c612684e4bd9813fd145e7bbdbead903
26.00431
140
0.671987
3.785498
false
false
false
false
weibo3721/WBLayout
WBLayout/Class/UIView_WBLayout.swift
1
2539
// // UIView_WBLayout.swift // WBLayout // // Created by weibo on 2017/3/6. // Copyright © 2017年 weibo. All rights reserved. // import UIKit import Foundation import PureLayout //WBLayout extension UIView { var wbLayoutKey:UnsafeMutableRawPointer { get { return UnsafeMutableRawPointer(Unmanaged.passUnretained(self).toOpaque()) } } var wbLayout:WBLayout { get { if let obj = objc_getAssociatedObject(self, wbLayoutKey) as? WBLayout { return obj } return WBLayout(view: self) } set { objc_setAssociatedObject(self, wbLayoutKey, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN) } } var wbLayouts:[WBLayoutEnum] { get { return wbLayout.getLayouts } } var wbLayoutviews:[UIView] { get { return wbLayout.getLayoutviews } } //MARK: 视图操作方法 func wbAddLayoutView(newView:UIView) { wbLayout.addLayoutView(newView: newView) } func wbGoneView(thisView:UIView) { wbLayout.goneView(thisView: thisView) } func wbSetLayoutViews(arr:[UIView]) { wbLayout.setLayoutViews(arr: arr) } func wbClearlayout() { wbLayout.clearlayout() } func wbDeleteBottomEdge() { wbLayout.deleteBottomEdge() } func wbSetMode(newMode: WBLayoutModeEnum) { wbLayout.setMode(newMode: newMode) } func wbAddlayoutConstraint(constraint: NSLayoutConstraint) { wbLayout.addlayoutConstraint(constraint: constraint) } //MARK: 自动布局方法 func wbHeight(size:CGFloat,_ relation:NSLayoutRelation = .equal) -> UIView { return wbLayout.wbHeight(size:size, relation) } func wbWidth(size:CGFloat,_ relation:NSLayoutRelation = .equal) -> UIView { return wbLayout.wbWidth(size:size, relation) } func wbPinEdge(edge:ALEdge,_ size:CGFloat = 0,_ relation:NSLayoutRelation = .equal) -> UIView { return wbLayout.wbPinEdge(edge: edge, size, relation) } func wbAxis(axis:ALAxis) ->UIView { return wbLayout.wbAxis(axis: axis) } func wbVertical() ->UIView { return self.wbAxis(axis: ALAxis.vertical) } func wbHorizontal() -> UIView { return self.wbAxis(axis: ALAxis.horizontal) } func wbLayoutSubviews() { wbLayout.wbLayoutSubviews() } }
mit
870cd8b8119d47d4f561a586f7416370
23.627451
113
0.60629
4.186667
false
false
false
false
apple/swift
test/IRGen/objc_object_getClass.swift
4
610
// RUN: %target-swift-frontend -emit-ir -primary-file %s -module-name A | %FileCheck %s // REQUIRES: CPU=armv7k // REQUIRES: OS=watchos import Foundation func getAClass(managedObjectClass : AnyClass) -> AnyClass{ let metaClass: AnyClass = object_getClass(managedObjectClass)! return metaClass } public class ObjCSubclass : NSObject { public final var field: Int32 = 0 } func test(_ o: ObjCSubclass) { o.field = 10 } // CHECK-DAG: declare i8* @object_getClass(i8*{{.*}}) // CHECK-DAG: call %objc_class* bitcast (i8* (i8*)* @object_getClass to %objc_class* (%objc_object*)*)(%objc_object* %{{.*}})
apache-2.0
3ea554189453d6fc0b4614260dcde8dd
26.727273
125
0.688525
3.262032
false
false
false
false
mariohahn/StatusProvider
StatusProvider/StatusProvider/DefaultStatusView.swift
1
4584
// // EmptyStatusView // // Created by MarioHahn on 25/08/16. // import Foundation import UIKit open class DefaultStatusView: UIView, StatusView { public var view: UIView { return self } public var status: StatusModel? { didSet { guard let status = status else { return } imageView.image = status.image titleLabel.text = status.title descriptionLabel.text = status.description #if swift(>=4.2) actionButton.setTitle(status.actionTitle, for: UIControl.State()) #else actionButton.setTitle(status.actionTitle, for: UIControlState()) #endif if status.isLoading { activityIndicatorView.startAnimating() } else { activityIndicatorView.stopAnimating() } imageView.isHidden = imageView.image == nil titleLabel.isHidden = titleLabel.text == nil descriptionLabel.isHidden = descriptionLabel.text == nil actionButton.isHidden = status.action == nil verticalStackView.isHidden = imageView.isHidden && descriptionLabel.isHidden && actionButton.isHidden } } public let titleLabel: UILabel = { $0.font = UIFont.preferredFont(forTextStyle: .headline) $0.textColor = UIColor.black $0.textAlignment = .center return $0 }(UILabel()) public let descriptionLabel: UILabel = { $0.font = UIFont.preferredFont(forTextStyle: .caption2) $0.textColor = UIColor.black $0.textAlignment = .center $0.numberOfLines = 0 return $0 }(UILabel()) #if swift(>=4.2) public let activityIndicatorView: UIActivityIndicatorView = { $0.isHidden = true $0.hidesWhenStopped = true #if os(tvOS) $0.style = .whiteLarge #endif #if os(iOS) $0.style = .gray #endif return $0 }(UIActivityIndicatorView(style: .whiteLarge)) #else public let activityIndicatorView: UIActivityIndicatorView = { $0.isHidden = true $0.hidesWhenStopped = true #if os(tvOS) $0.activityIndicatorViewStyle = .whiteLarge #endif #if os(iOS) $0.activityIndicatorViewStyle = .gray #endif return $0 }(UIActivityIndicatorView(activityIndicatorStyle: .whiteLarge)) #endif public let imageView: UIImageView = { $0.contentMode = .center return $0 }(UIImageView()) public let actionButton: UIButton = { return $0 }(UIButton(type: .system)) public let verticalStackView: UIStackView = { $0.axis = .vertical $0.spacing = 10 $0.alignment = .center return $0 }(UIStackView()) public let horizontalStackView: UIStackView = { $0.translatesAutoresizingMaskIntoConstraints = false $0.axis = .horizontal $0.spacing = 10 $0.alignment = .center return $0 }(UIStackView()) public override init(frame: CGRect) { super.init(frame: frame) actionButton.addTarget(self, action: #selector(DefaultStatusView.actionButtonAction), for: .touchUpInside) addSubview(horizontalStackView) horizontalStackView.addArrangedSubview(activityIndicatorView) horizontalStackView.addArrangedSubview(verticalStackView) verticalStackView.addArrangedSubview(imageView) verticalStackView.addArrangedSubview(titleLabel) verticalStackView.addArrangedSubview(descriptionLabel) verticalStackView.addArrangedSubview(actionButton) NSLayoutConstraint.activate([ horizontalStackView.leadingAnchor.constraint(equalTo: leadingAnchor), horizontalStackView.trailingAnchor.constraint(equalTo: trailingAnchor), horizontalStackView.topAnchor.constraint(equalTo: topAnchor), horizontalStackView.bottomAnchor.constraint(equalTo: bottomAnchor) ]) } #if os(tvOS) override open var preferredFocusEnvironments: [UIFocusEnvironment] { return [actionButton] } #endif @objc func actionButtonAction() { status?.action?() } open override var tintColor: UIColor! { didSet { titleLabel.textColor = tintColor descriptionLabel.textColor = tintColor } } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
mit
1117d115a43b08b397080490bd4d039c
27.47205
114
0.622164
5.065193
false
false
false
false
Esri/arcgis-runtime-samples-ios
arcgis-ios-sdk-samples/Display information/Show legend/MILLegendTableViewController.swift
1
3954
// Copyright 2016 Esri. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import UIKit import ArcGIS class MILLegendTableViewController: UITableViewController { var operationalLayers: NSMutableArray! var legendInfosDict = [String: [AGSLegendInfo]]() private var orderArray = [AGSLayerContent]() override func viewDidLoad() { super.viewDidLoad() self.populateLegends(with: self.operationalLayers as! [AGSLayerContent]) } func populateLegends(with layers: [AGSLayerContent]) { for layer in layers { if !layer.subLayerContents.isEmpty { self.populateLegends(with: layer.subLayerContents) } else { // else if no sublayers fetch legend info self.orderArray.append(layer) layer.fetchLegendInfos { [weak self] (legendInfos, error) in if let error = error { print(error) } else { if let legendInfos = legendInfos { self?.legendInfosDict[self!.hashString(for: layer)] = legendInfos self?.tableView.reloadData() } } } } } } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { // Return the number of sections. return orderArray.count } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // Return the number of rows in the section. let layer = self.orderArray[section] let legendInfos = self.legendInfosDict[self.hashString(for: layer)] return legendInfos?.count ?? 0 } override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { let layerContent = self.orderArray[section] return self.nameForLayerContent(layerContent) } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "MILLegendCell", for: indexPath) let layer = self.orderArray[indexPath.section] let legendInfos = self.legendInfosDict[self.hashString(for: layer)]! let legendInfo = legendInfos[indexPath.row] cell.textLabel?.text = legendInfo.name legendInfo.symbol?.createSwatch { (image, _) in if let updateCell = tableView.cellForRow(at: indexPath) { updateCell.imageView?.image = image updateCell.setNeedsLayout() } } return cell } func geometryTypeForSymbol(_ symbol: AGSSymbol) -> AGSGeometryType { if symbol is AGSFillSymbol { return AGSGeometryType.polygon } else if symbol is AGSLineSymbol { return .polyline } else { return .point } } // MARK: - Helper functions func hashString (for obj: AnyObject) -> String { return String(UInt(bitPattern: ObjectIdentifier(obj))) } func nameForLayerContent(_ layerContent: AGSLayerContent) -> String { if let layer = layerContent as? AGSLayer { return layer.name } else { return (layerContent as! AGSArcGISSublayer).name } } }
apache-2.0
2555bf54ebed53357c9c582f0faf4262
34.945455
109
0.62089
4.91791
false
false
false
false
hweetty/EasyTransitioning
Example/EasyTransitioning/Example 3/Example3ViewController.swift
1
1801
// // Example3ViewController.swift // EasyTransitioning // // Created by Jerry Yu on 2017-03-28. // Copyright © 2017 Jerry Yu. All rights reserved. // import UIKit import EasyTransitioning class Example3ViewController: UIViewController { let cardView = UIView() let transitionController = ETTransitionController() override func viewDidLoad() { super.viewDidLoad() cardView.backgroundColor = UIColor.orange.withAlphaComponent(0.8) view.addSubview(cardView) cardView.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate([ cardView.centerXAnchor.constraint(equalTo: view.centerXAnchor), cardView.centerYAnchor.constraint(equalTo: view.centerYAnchor), cardView.widthAnchor.constraint(equalTo: view.widthAnchor, multiplier: 0.75), cardView.heightAnchor.constraint(equalTo: view.heightAnchor, multiplier: 0.75), ]) let gest = UITapGestureRecognizer(target: self, action: #selector(showDetails)) view.addGestureRecognizer(gest) } func showDetails() { let vc = Presented3ViewController() let whiteBackgroundView = UIView(frame: view.bounds) whiteBackgroundView.backgroundColor = .white transitionController.elements = [ whiteBackgroundView.easyTransition([], shouldSnapshot: false), vc.view.easyTransition([ ETFadeAction(toAlpha: 1, fromAlpha: 0), ETTransformAction(to: CGAffineTransform.identity, from: CGAffineTransform(scaleX: 0.75, y: 0.75)) ], shouldSnapshot: false), cardView.easyTransition([ ETFrameAction(toFrame: view.bounds, fromFrameOfView: cardView), ETFadeAction(toAlpha: 0, fromAlpha: 1), ]) ] vc.transitioningDelegate = transitionController self.present(vc, animated: true, completion: nil) } }
mit
ce76e7286a68de0b0dfa093b0c3ce137
31.142857
105
0.73
4.556962
false
false
false
false
karivalkama/Agricola-Scripture-Editor
Pods/SCrypto/Source/SCrypto.swift
1
29093
// // SCrypto.swift // SCrypto // // Created by Maksym Shcheglov on 21/01/16. // Copyright © 2016 Maksym Shcheglov. All rights reserved. // import CommonCrypto public extension Data { func bytesArray<T: ExpressibleByIntegerLiteral>() -> [T] { var bytes = Array<T>(repeating: 0, count: self.count) (self as NSData).getBytes(&bytes, length:self.count * MemoryLayout<T>.size) return bytes } func hexString() -> String { let hexString = NSMutableString() let bytes: [UInt8] = self.bytesArray() for byte in bytes { hexString.appendFormat("%02x", UInt(byte)) } return hexString as String } } internal protocol RawConvertible { associatedtype RawValue var rawValue: RawValue { get } } /** The error values for SCrypto operations - ParamError: Illegal parameter value. - BufferTooSmall: Insufficent buffer provided for specified operation. - MemoryFailure: Memory allocation failure. - AlignmentError: Input size was not aligned properly. - DecodeError: Input data did not decode or decrypt properly. - Unimplemented: Function not implemented for the current algorithm. - Overflow: Overflow error. - RNGFailure: Random Number Generator Error. */ public enum SCryptoError: Error, RawRepresentable, CustomStringConvertible { case paramError, bufferTooSmall, memoryFailure, alignmentError, decodeError, unimplemented, overflow, rngFailure public typealias RawValue = CCCryptorStatus public init?(rawValue: RawValue) { switch Int(rawValue) { case kCCParamError : self = .paramError case kCCBufferTooSmall : self = .bufferTooSmall case kCCMemoryFailure : self = .memoryFailure case kCCAlignmentError: self = .alignmentError case kCCDecodeError: self = .decodeError case kCCUnimplemented : self = .unimplemented case kCCOverflow: self = .overflow case kCCRNGFailure: self = .rngFailure default: return nil } } public var rawValue: RawValue { switch self { case .paramError : return CCCryptorStatus(kCCParamError) case .bufferTooSmall : return CCCryptorStatus(kCCBufferTooSmall) case .memoryFailure : return CCCryptorStatus(kCCMemoryFailure) case .alignmentError: return CCCryptorStatus(kCCAlignmentError) case .decodeError: return CCCryptorStatus(kCCDecodeError) case .unimplemented : return CCCryptorStatus(kCCUnimplemented) case .overflow: return CCCryptorStatus(kCCOverflow) case .rngFailure: return CCCryptorStatus(kCCRNGFailure) } } /// The error's textual representation public var description: String { let descriptions = [SCryptoError.paramError: "ParamError", SCryptoError.bufferTooSmall: "BufferTooSmall", SCryptoError.memoryFailure: "MemoryFailure", SCryptoError.alignmentError: "AlignmentError", SCryptoError.decodeError: "DecodeError", SCryptoError.unimplemented: "Unimplemented", SCryptoError.overflow: "Overflow", SCryptoError.rngFailure: "RNGFailure"] return descriptions[self] ?? "" } } // MARK: Message Digest /// The `MessageDigest` class provides applications functionality of a message digest algorithms, such as MD5 or SHA. public final class MessageDigest { /** The cryptographic algorithm types to evaluate message digest. MD2, MD4, and MD5 are recommended only for compatibility with existing applications. In new applications, SHA-256(or greater) should be preferred. */ public enum Algorithm { case md2, md4, md5, sha1, sha224, sha256, sha384, sha512 typealias Function = (_ data: UnsafeRawPointer, _ len: CC_LONG, _ md: UnsafeMutablePointer<UInt8>) -> UnsafeMutablePointer<UInt8>? internal var digest: (length: Int32, function: Function) { switch self { case .md2: return (CC_MD2_DIGEST_LENGTH, CC_MD2) case .md4: return (CC_MD4_DIGEST_LENGTH, CC_MD4) case .md5: return (CC_MD5_DIGEST_LENGTH, CC_MD5) case .sha1: return (CC_SHA1_DIGEST_LENGTH, CC_SHA1) case .sha224: return (CC_SHA224_DIGEST_LENGTH, CC_SHA224) case .sha256: return (CC_SHA256_DIGEST_LENGTH, CC_SHA256) case .sha384: return (CC_SHA384_DIGEST_LENGTH, CC_SHA384) case .sha512: return (CC_SHA512_DIGEST_LENGTH, CC_SHA512) } } } fileprivate let algorithm: Algorithm fileprivate let data = NSMutableData() /** Initializes a new digest object with the specified cryptographic algorithm. - parameter algorithm: The cryptographic algorithm to use. - Returns: A newly created object to compute the message digest. */ init(_ algorithm: Algorithm) { self.algorithm = algorithm } /** Updates the digest using the specified array of bytes. Can be called repeatedly with chunks of the message to be hashed. - parameter bytes: The array of bytes to append. */ public func update(_ bytes: [UInt8]) { self.data.append(bytes, length: bytes.count) } /** Evaluates the message digest. - returns: the message digest. */ public func final() -> [UInt8] { var digest = [UInt8](repeating: UInt8(0), count: Int(self.algorithm.digest.length)) // the one-shot routine returns the pointer passed in via the md parameter _ = self.algorithm.digest.function(self.data.bytes, CC_LONG(self.data.length), &digest) return digest } } /// The `MessageDigestProducible` protocol defines methods to compute the message digest. public protocol MessageDigestProducible { /** Produces the message digest. - parameter algorithm: The cryptographic algorithm to use. - returns: the message digest. */ func digest(_ algorithm: MessageDigest.Algorithm) -> Self } public extension MessageDigestProducible { /** Evaluates the MD2 message digest at data and returns the result. Recommended only for compatibility with existing applications. In new applications, SHA-256(or greater) should be preferred. - returns: the MD2 message digest. */ func MD2() -> Self { return digest(.md2) } /** Evaluates the MD4 message digest at data and returns the result. Recommended only for compatibility with existing applications. In new applications, SHA-256(or greater) should be preferred. - returns: the MD4 message digest. */ func MD4() -> Self { return digest(.md4) } /** Evaluates the MD5 message digest at data and returns the result. Recommended only for compatibility with existing applications. In new applications, SHA-256(or greater) should be preferred. - returns: the MD5 message digest. */ func MD5() -> Self { return digest(.md5) } /** Evaluates the SHA-1 message digest at data and returns the result. - returns: the SHA-1 message digest. */ func SHA1() -> Self { return digest(.sha1) } /** Evaluates the SHA224 message digest at data and returns the result. - returns: the SHA224 message digest. */ func SHA224() -> Self { return digest(.sha224) } /** Evaluates the SHA256 message digest at data and returns the result. - returns: the SHA256 message digest. */ func SHA256() -> Self { return digest(.sha256) } /** Evaluates the SHA384 message digest at data and returns the result. - returns: the SHA384 message digest. */ func SHA384() -> Self { return digest(.sha384) } /** Evaluates the SHA512 message digest at data and returns the result. - returns: the SHA512 message digest. */ func SHA512() -> Self { return digest(.sha512) } } /// The `Data` extension defines methods to compute the message digest. extension Data: MessageDigestProducible { /** Produces the message digest. - parameter algorithm: The cryptographic algorithm to use. - returns: the message digest. */ public func digest(_ algorithm: MessageDigest.Algorithm) -> Data { let digest = MessageDigest(algorithm) digest.update(self.bytesArray()) let messageDigest = digest.final() return type(of: self).init(Data(bytes: UnsafePointer<UInt8>(messageDigest), count: messageDigest.count)) } } /// The `String` extension defines methods to compute the message digest. extension String: MessageDigestProducible { /** Produces the message digest. - parameter algorithm: The cryptographic algorithm to use. - returns: the message digest (string of hexadecimal digits). */ public func digest(_ algorithm: MessageDigest.Algorithm) -> String { let digest = MessageDigest(algorithm) digest.update(self.data(using: String.Encoding.utf8)!.bytesArray()) let messageDigest = digest.final() return Data(bytes: UnsafePointer<UInt8>(messageDigest), count: messageDigest.count).hexString() } } // MARK: Random /// The Random class defines a method for random bytes generation. public final class Random { /** Returns random bytes in a buffer allocated by the caller. - parameter length: Number of random bytes to return. - returns: An array populated with randomly generated bytes. - throws: `SCryptoError` instance in case of eny errors. */ public static func generateBytes(_ length : Int) throws -> [UInt8] { var bytes = [UInt8](repeating: UInt8(0), count: length) let statusCode = CCRandomGenerateBytes(&bytes, bytes.count) if statusCode != CCRNGStatus(kCCSuccess) { throw SCryptoError(rawValue: statusCode)! } return bytes } } /// The Data extension defines a method for random bytes generation. public extension Data { /** Creates Data object of the specified length and populates it with randomly generated bytes. The created object has cryptographically strong random bits suitable for use as cryptographic keys, IVs, nonces etc. - parameter length: Number of random bytes to return. - returns: newly created Data object populated with randomly generated bytes. */ static func random(_ length : Int) throws -> Data { let bytes = try Random.generateBytes(length) let data = Data(bytes: UnsafePointer<UInt8>(bytes), count: bytes.count) return data } } // MARK: HMAC /// The HMAC class public final class HMAC { public typealias Message = [UInt8] public typealias SecretKey = [UInt8] /** Cryptographic hash functions, that may be used in the calculation of an HMAC. */ public enum Algorithm: RawConvertible { case sha1, md5, sha256, sha384, sha512, sha224 internal var digestLength : Int32 { switch self { case .md5: return CC_MD5_DIGEST_LENGTH case .sha1: return CC_SHA1_DIGEST_LENGTH case .sha224: return CC_SHA224_DIGEST_LENGTH case .sha256: return CC_SHA256_DIGEST_LENGTH case .sha384: return CC_SHA384_DIGEST_LENGTH case .sha512: return CC_SHA512_DIGEST_LENGTH } } typealias RawValue = CCHmacAlgorithm internal var rawValue: RawValue { switch self { case .sha1 : return CCHmacAlgorithm(kCCHmacAlgSHA1) case .md5 : return CCHmacAlgorithm(kCCHmacAlgMD5) case .sha256 : return CCHmacAlgorithm(kCCHmacAlgSHA256) case .sha384 : return CCHmacAlgorithm(kCCHmacAlgSHA384) case .sha512: return CCHmacAlgorithm(kCCHmacAlgSHA512) case .sha224: return CCHmacAlgorithm(kCCHmacAlgSHA224) } } } fileprivate let algorithm: Algorithm fileprivate let message = NSMutableData() fileprivate let key: SecretKey /** Initializes a new HMAC object with the provided cryptographic algorithm and raw key bytes. - parameter algorithm: The cryptographic hash algorithm to use. - parameter key: The secret cryptographic key. The key should be randomly generated bytes and is recommended to be equal in length to the digest size of the hash function chosen. - Returns: A newly created object to compute the HMAC. */ init(_ algorithm: Algorithm, key: SecretKey) { self.algorithm = algorithm self.key = key } /** Appends specified bytes to the internal buffer. Can be called repeatedly with chunks of the message. - parameter message: The message to be authenticated. */ public func update(_ message: Message) { self.message.append(message, length: message.count) } /** Evaluates the HMAC. - returns: the message authentication code. */ public func final() -> [UInt8] { var hmac = [UInt8](repeating: UInt8(0), count: Int(self.algorithm.digestLength)) CCHmac(self.algorithm.rawValue, key, key.count, self.message.bytes, self.message.length, &hmac) return hmac } } /// The Data extension defines methods to compute the HMAC. public extension Data { /** Produces the keyed-hash message authentication code (HMAC). - parameter algorithm: The cryptographic hash algorithm to use. - parameter key: The secret cryptographic key. The key should be randomly generated bytes and is recommended to be equal in length to the digest size of the hash function chosen. - returns: the message authentication code. */ func hmac(_ algorithm: HMAC.Algorithm, key: Data) -> Data { let hmac = HMAC(algorithm, key: key.bytesArray()) hmac.update(self.bytesArray()) let result = hmac.final() return Data(bytes: UnsafePointer<UInt8>(result), count: result.count) } } /// The String extension defines methods to compute the HMAC. public extension String { /** Produces the keyed-hash message authentication code (HMAC). The key and message string and key are interpreted as UTF8. - parameter algorithm: The cryptographic hash algorithm to use. - parameter key: The secret cryptographic key. - returns: the message authentication code (string of hexadecimal digits). */ func hmac(_ algorithm: HMAC.Algorithm, key: String) -> String { let key = key.data(using: String.Encoding.utf8)! let message = self.data(using: String.Encoding.utf8)! return message.hmac(algorithm, key: key).hexString() } } // MARK: Cipher /// The Cipher provides the functionality of a cryptographic cipher for encryption and decryption (stream and block algorithms). public final class Cipher { public typealias Data = [UInt8] public typealias Key = [UInt8] public typealias IV = [UInt8] /** The encryption algorithms that are supported by the Cipher. - AES: Advanced Encryption Standard is a block cipher standardized by NIST. AES is both fast, and cryptographically strong. It is a good default choice for encryption. The secret key must be either 128, 192, or 256 bits long. - DES: A block cipher. The key should be either 64 bits long. - TripleDES: A block cipher standardized by NIST and not recommended for new applications because it is incredibly slow. The key should be 192 bits long. - CAST: A block cipher approved for use in the Canadian government by the Communications Security Establishment. It is a variable key length cipher and supports keys from 40-128 bits in length in increments of 8 bits. - RC2: A block cipher with variable key length from 8 to 1024 bits, in steps of 8 bits. - RC4: A stream cipher with serious weaknesses in its initial stream output. Its use is strongly discouraged. The secret key must be either 40, 56, 64, 80, 128, 192, or 256 bits in length. - Blowfish: A block cipher with variable key length from 32 to 448 bits in increments of 8 bits. Known to be susceptible to attacks when using weak keys. */ public enum Algorithm: RawConvertible { case aes, des, tripleDES, cast, rc2, rc4, blowfish typealias RawValue = CCAlgorithm internal var rawValue: RawValue { switch self { case .aes : return CCAlgorithm(kCCAlgorithmAES) case .des : return CCAlgorithm(kCCAlgorithmDES) case .tripleDES : return CCAlgorithm(kCCAlgorithm3DES) case .cast : return CCAlgorithm(kCCAlgorithmCAST) case .rc2: return CCAlgorithm(kCCAlgorithmRC2) case .rc4: return CCAlgorithm(kCCAlgorithmRC4) case .blowfish : return CCAlgorithm(kCCAlgorithmBlowfish) } } /// Block sizes, in bytes, for supported algorithms. public var blockSize: Int { switch self { case .aes : return kCCBlockSizeAES128 case .des : return kCCBlockSizeDES case .tripleDES : return kCCBlockSize3DES case .cast : return kCCBlockSizeCAST case .rc2: return kCCBlockSizeRC2 case .rc4: return 0 case .blowfish : return kCCBlockSizeBlowfish } } } fileprivate enum Operation: RawConvertible { case encrypt, decrypt typealias RawValue = CCOperation var rawValue: RawValue { switch self { case .encrypt : return CCOperation(kCCEncrypt) case .decrypt : return CCOperation(kCCDecrypt) } } } /** * Options for block ciphers */ public struct Options : OptionSet { public typealias RawValue = CCOptions public let rawValue: RawValue public init(rawValue: RawValue) { self.rawValue = rawValue } /// Perform the PKCS7 padding. public static let PKCS7Padding = Options(rawValue: RawValue(kCCOptionPKCS7Padding)) /// Electronic Code Book Mode. This block cipher mode is not recommended for use. Default mode is CBC. public static let ECBMode = Options(rawValue: RawValue(kCCOptionECBMode)) } fileprivate let algorithm: Algorithm fileprivate let options: Options fileprivate let iv: IV? /** Initializes a new cipher with the provided algorithm and options. - parameter algorithm: The symmetric algorithm to use for encryption - parameter options: The encryption options. - parameter iv: Initialization vector, optional. Used by block ciphers when Cipher Block Chaining (CBC) mode is enabled. If present, must be the same length as the selected algorithm's block size. This parameter is ignored if ECB mode is used or if a stream cipher algorithm is selected. nil by default. - returns: A newly created and initialized cipher object. */ init(algorithm: Algorithm, options: Options, iv: IV? = nil) { self.algorithm = algorithm self.options = options self.iv = iv } /** Encrypts the plaintext. - parameter data: The data to encrypt. - parameter key: The shared secret key. - throws: `SCryptoError` instance in case of eny errors. - returns: Encrypted data. */ public func encrypt(_ data: Data, key: Key) throws -> [UInt8] { return try cryptoOperation(data, key: key, operation: .encrypt) } /** Decrypts the ciphertext. - parameter data: The encrypted data. - parameter key: The shared secret key. - throws: `SCryptoError` instance in case of eny errors. - returns: Decrypted data. */ public func decrypt(_ data: Data, key: Key) throws -> [UInt8] { return try cryptoOperation(data, key: key, operation: .decrypt) } fileprivate func cryptoOperation(_ data: Data, key: Key, operation: Operation) throws -> [UInt8] { var dataOutMoved = 0 var outData = [UInt8](repeating: UInt8(0), count: Int(data.count + self.algorithm.blockSize)) let ivData = self.iv == nil ? nil : UnsafeRawPointer(self.iv!) let status = CCCrypt(operation.rawValue, // operation self.algorithm.rawValue, // algorithm self.options.rawValue, // options key, // key key.count, // keylength ivData, // iv data, // input data data.count, // input length &outData, // output buffer outData.count, // output buffer length &dataOutMoved) // output bytes real length if status == CCCryptorStatus(kCCSuccess) { return Array(outData[0..<dataOutMoved]) } else { throw SCryptoError(rawValue: status)! } } } /// The Data extension defines methods for symmetric encryption algorithms. public extension Data { /** Encrypts the plaintext. - parameter algorithm: The symmetric algorithm to use for encryption - parameter options: The encryption options. - parameter key: The shared secret key. - parameter iv: Initialization vector, optional. Used by block ciphers when Cipher Block Chaining (CBC) mode is enabled. If present, must be the same length as the selected algorithm's block size. This parameter is ignored if ECB mode is used or if a stream cipher algorithm is selected. nil by default. - throws: `SCryptoError` instance in case of eny errors. - returns: Encrypted data. */ func encrypt(_ algorithm: Cipher.Algorithm, options: Cipher.Options, key: Data, iv: Data? = nil) throws -> Data { let cipher = Cipher(algorithm: algorithm, options: options, iv: iv?.bytesArray()) let encryptedBytes = try cipher.encrypt(self.bytesArray(), key: key.bytesArray()) return Data(bytes: UnsafePointer<UInt8>(encryptedBytes), count: encryptedBytes.count) } /** Decrypts the ciphertext. - parameter algorithm: The symmetric algorithm to use for encryption - parameter options: The encryption options. - parameter key: The shared secret key. - parameter iv: Initialization vector, optional. Used by block ciphers when Cipher Block Chaining (CBC) mode is enabled. If present, must be the same length as the selected algorithm's block size. This parameter is ignored if ECB mode is used or if a stream cipher algorithm is selected. nil by default. - throws: `SCryptoError` instance in case of eny errors. - returns: Decrypted data. */ func decrypt(_ algorithm: Cipher.Algorithm, options: Cipher.Options, key: Data, iv: Data? = nil) throws -> Data { let cipher = Cipher(algorithm: algorithm, options: options, iv: iv?.bytesArray()) let decryptedBytes = try cipher.decrypt(self.bytesArray(), key: key.bytesArray()) return Data(bytes: UnsafePointer<UInt8>(decryptedBytes), count: decryptedBytes.count) } } // MARK: PBKDF /// The `PBKDF` class defines methods to derive a key from a text password/passphrase. public final class PBKDF { public typealias Password = [Int8] public typealias Salt = [UInt8] public typealias DerivedKey = [UInt8] fileprivate static let algorithm = CCPBKDFAlgorithm(kCCPBKDF2) // Currently only PBKDF2 is available via kCCPBKDF2 /** The Pseudo Random Algorithm to use for the derivation iterations. */ public enum PseudoRandomAlgorithm: RawConvertible { case sha1, sha224, sha256, sha384, sha512 typealias RawValue = CCPseudoRandomAlgorithm internal var rawValue: RawValue { switch self { case .sha1 : return CCPseudoRandomAlgorithm(kCCPRFHmacAlgSHA1) case .sha224 : return CCPseudoRandomAlgorithm(kCCPRFHmacAlgSHA224) case .sha256 : return CCPseudoRandomAlgorithm(kCCPRFHmacAlgSHA256) case .sha384 : return CCPseudoRandomAlgorithm(kCCPRFHmacAlgSHA384) case .sha512: return CCPseudoRandomAlgorithm(kCCPRFHmacAlgSHA512) } } } /** Derive a key from a text password/passphrase. - parameter length: The expected length of the derived key in bytes. - parameter password: The text password used as input to the derivation function. - parameter salt: The salt byte values used as input to the derivation function. Recommended to use 128-bits salt or longer. - parameter pseudoRandomAlgorithm: The Pseudo Random Algorithm to use for the derivation iterations. - parameter rounds: The number of rounds of the Pseudo Random Algorithm to use. This can be used to control the length of time the operation takes. Higher numbers help mitigate brute force attacks against derived keys. - throws: `SCryptoError` instance in case of eny errors. - returns: The resulting derived key. */ public static func derivedKey(withLength length: Int, password: Password, salt: Salt, pseudoRandomAlgorithm: PseudoRandomAlgorithm, rounds: UInt32) throws -> DerivedKey { var derivedKey = DerivedKey(repeating: UInt8(0), count: length) let statusCode = CCKeyDerivationPBKDF(self.algorithm, password, password.count, salt, salt.count, pseudoRandomAlgorithm.rawValue, rounds, &derivedKey, derivedKey.count) if statusCode != CCRNGStatus(kCCSuccess) { throw SCryptoError(rawValue: statusCode)! } return derivedKey } /** Determine the approximate number of PRF rounds to use for a specific delay on the current platform. - parameter passwordLength: The length of the text password in bytes. - parameter saltLength: The length of the salt in bytes. - parameter pseudoRandomAlgorithm: The Pseudo Random Algorithm to use for the derivation iterations. - parameter derivedKeyLength: The expected length of the derived key in bytes. - parameter msec: The targetted duration we want to achieve for a key derivation with these parameters. - returns: the number of iterations to use for the desired processing time. */ public static func calibrate(_ passwordLength: Int, saltLength: Int, pseudoRandomAlgorithm: PseudoRandomAlgorithm, derivedKeyLength: Int, msec : UInt32) -> UInt { return UInt(CCCalibratePBKDF(CCPBKDFAlgorithm(kCCPBKDF2), passwordLength, saltLength, pseudoRandomAlgorithm.rawValue, derivedKeyLength, msec)) } } /// The Data extension defines methods for deriving a key from a text password/passphrase. public extension Data { /** Derive a key from a text password/passphrase. - parameter salt: The salt byte values used as input to the derivation function. Recommended to use 128-bits salt or longer. - parameter pseudoRandomAlgorithm: The Pseudo Random Algorithm to use for the derivation iterations. - parameter rounds: The number of rounds of the Pseudo Random Algorithm to use. This can be used to control the length of time the operation takes. Higher numbers help mitigate brute force attacks against derived keys. - parameter derivedKeyLength: The expected length of the derived key in bytes. - throws: `SCryptoError` instance in case of eny errors. - returns: The resulting derived key. */ func derivedKey(_ salt: Data, pseudoRandomAlgorithm: PBKDF.PseudoRandomAlgorithm, rounds: UInt32, derivedKeyLength: Int) throws -> Data { let key = try PBKDF.derivedKey(withLength: derivedKeyLength, password: self.bytesArray(), salt: salt.bytesArray(), pseudoRandomAlgorithm: pseudoRandomAlgorithm, rounds: rounds) return Data(bytes: UnsafePointer<UInt8>(key), count: key.count) } /** Determine the approximate number of PRF rounds to use for a specific delay on the current platform. - parameter saltLength: The length of the salt in bytes. - parameter pseudoRandomAlgorithm: The Pseudo Random Algorithm to use for the derivation iterations. - parameter derivedKeyLength: The expected length of the derived key in bytes. - parameter msec: The targetted duration we want to achieve for a key derivation with these parameters. - returns: the number of iterations to use for the desired processing time. */ func calibrate(_ saltLength: Int, pseudoRandomAlgorithm: PBKDF.PseudoRandomAlgorithm, derivedKeyLength: Int, msec : UInt32) -> UInt { return PBKDF.calibrate(self.count, saltLength: saltLength, pseudoRandomAlgorithm: pseudoRandomAlgorithm, derivedKeyLength: derivedKeyLength, msec: msec) } }
mit
43603f49de5eaad79aaa654e3961d9ed
37.278947
315
0.667744
4.62218
false
false
false
false
belatrix/BelatrixEventsIOS
Hackatrix/Model/Event.swift
1
1698
// // Event.swift // Hackatrix // // Created by Erik Fernando Flores Quispe on 11/05/17. // Copyright © 2017 Belatrix. All rights reserved. // import Foundation import SwiftyJSON class Event: NSObject { var id:Int? var title:String? var image:String? var datetime:String? var address:String? var details:String? var registerLink:String? var sharingText:String? var hasInteractions:Bool? var interactionText:String? var interactionConfirmationText:String? var isFeatured:Bool? var isUpcoming:Bool? var isInteractionActive:Bool? var isActive:Bool? var location:Location? var city:[City]? init(data:JSON) { self.id = data["id"].int self.title = data["title"].string self.image = data["image"].string self.datetime = data["datetime"].string self.address = data["address"].string self.details = data["details"].string self.registerLink = data["register_link"].string self.sharingText = data["sharing_text"].string self.hasInteractions = data["has_interactions"].bool self.interactionText = data["interaction_text"].string self.interactionConfirmationText = data["interaction_confirmation_text"].string self.isFeatured = data["is_featured"].bool self.isUpcoming = data["is_upcoming"].bool self.isInteractionActive = data["is_interaction_active"].bool self.isActive = data["is_active"].bool self.location = Location(data: data["location"]) } }
apache-2.0
07ad165ffbaac471f74529b47471157d
31.018868
87
0.605775
4.285354
false
false
false
false
AleManni/LightOperations
LightOperations/LightOperation.swift
1
4141
// // GAOperation.swift // GeoApp // // Created by Alessandro Manni on 06/08/2017. // Copyright © 2017 Alessandro Manni. All rights reserved. // import Foundation public enum OperationState: String { case ready, executing, finished, cancelled var keyPath: String { return "is" + (self.rawValue).capitalized } } public enum OperationError: Error { case networkError(Error) case unexpectedInputType(Any) case inputDataMissing case genericError(Error) } public enum OperationFinalResult<T> { case success(T) case failure(OperationError) } /** This class is a basic subclass of Operation, providing its sublcasses with: - KVOs for all operation states - An initialData and operationFinalResult properties that are used by the Coupler class, but can also be set/read manually - An initializer, allowing to set an optional completionBlock for the operation Subclasses will need to override, at minimum, the main() function */ open class LightOperation : Operation { public var operationFinalResult: OperationFinalResult<Any>? public var initialData: Any? public var operationCompletion: ((OperationFinalResult<Any>) -> Void) override open var isAsynchronous: Bool { return true } public var state = OperationState.ready { willSet { willChangeValue(forKey: state.keyPath) willChangeValue(forKey: newValue.keyPath) } didSet { didChangeValue(forKey: state.keyPath) didChangeValue(forKey: oldValue.keyPath) } } override open var isExecuting: Bool { return state == .executing } override open var isFinished: Bool { return state == .finished } override open var isCancelled: Bool { return state == .cancelled } /** This initializer provides the opportunity to pass a completion block handling a OperationFinalResult type. The block can be executed at any point, e.g. at the end of the main() block of at any entry point provided by the state observer. */ public init(operationCompletion: @escaping ((OperationFinalResult<Any>) -> Void) = { _ in }) { self.operationCompletion = operationCompletion super.init() self.name = String(describing: self) } override open func start() { addObserver(self, forKeyPath: OperationState.executing.keyPath, options: .new, context: nil) addObserver(self, forKeyPath: OperationState.finished.keyPath, options: .new, context: nil) addObserver(self, forKeyPath: OperationState.cancelled.keyPath, options: .new, context: nil) if self.isCancelled { state = .finished } else { state = .ready main() } } override open func main() { if self.isCancelled { state = .finished return } else { state = .executing } } /** By default, this function prints the name of the operation and its state to the consolle. Sublcasses are encouraged to override it if needed. */ override open func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { guard let keyPath = keyPath else { return } switch keyPath { case OperationState.executing.keyPath: print("\(self.name ?? "un-named operation") is executing") case OperationState.finished.keyPath: print("\(self.name ?? "un-named operation") finished with result: \(String(describing: self.operationFinalResult))") case OperationState.cancelled.keyPath: print("\(self.name ?? "un-named operation") CANCELLED with result: \(String(describing: self.operationFinalResult))") default: return } } deinit { removeObserver(self, forKeyPath: OperationState.executing.keyPath) removeObserver(self, forKeyPath: OperationState.finished.keyPath) removeObserver(self, forKeyPath: OperationState.cancelled.keyPath) } }
mit
ed4c4246b3cb4684555bdb42b9928a87
32.387097
241
0.663043
4.813953
false
false
false
false
niunaruto/DeDaoAppSwift
testSwift/Pods/Kingfisher/Sources/General/KingfisherManager.swift
3
20363
// // KingfisherManager.swift // Kingfisher // // Created by Wei Wang on 15/4/6. // // Copyright (c) 2019 Wei Wang <[email protected]> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation /// The downloading progress block type. /// The parameter value is the `receivedSize` of current response. /// The second parameter is the total expected data length from response's "Content-Length" header. /// If the expected length is not available, this block will not be called. public typealias DownloadProgressBlock = ((_ receivedSize: Int64, _ totalSize: Int64) -> Void) /// Represents the result of a Kingfisher retrieving image task. public struct RetrieveImageResult { /// Gets the image object of this result. public let image: Image /// Gets the cache source of the image. It indicates from which layer of cache this image is retrieved. /// If the image is just downloaded from network, `.none` will be returned. public let cacheType: CacheType /// The `Source` from which the retrieve task begins. public let source: Source } /// Main manager class of Kingfisher. It connects Kingfisher downloader and cache, /// to provide a set of convenience methods to use Kingfisher for tasks. /// You can use this class to retrieve an image via a specified URL from web or cache. public class KingfisherManager { /// Represents a shared manager used across Kingfisher. /// Use this instance for getting or storing images with Kingfisher. public static let shared = KingfisherManager() // Mark: Public Properties /// The `ImageCache` used by this manager. It is `ImageCache.default` by default. /// If a cache is specified in `KingfisherManager.defaultOptions`, the value in `defaultOptions` will be /// used instead. public var cache: ImageCache /// The `ImageDownloader` used by this manager. It is `ImageDownloader.default` by default. /// If a downloader is specified in `KingfisherManager.defaultOptions`, the value in `defaultOptions` will be /// used instead. public var downloader: ImageDownloader /// Default options used by the manager. This option will be used in /// Kingfisher manager related methods, as well as all view extension methods. /// You can also passing other options for each image task by sending an `options` parameter /// to Kingfisher's APIs. The per image options will overwrite the default ones, /// if the option exists in both. public var defaultOptions = KingfisherOptionsInfo.empty // Use `defaultOptions` to overwrite the `downloader` and `cache`. private var currentDefaultOptions: KingfisherOptionsInfo { return [.downloader(downloader), .targetCache(cache)] + defaultOptions } private let processingQueue: CallbackQueue private convenience init() { self.init(downloader: .default, cache: .default) } init(downloader: ImageDownloader, cache: ImageCache) { self.downloader = downloader self.cache = cache let processQueueName = "com.onevcat.Kingfisher.KingfisherManager.processQueue.\(UUID().uuidString)" processingQueue = .dispatch(DispatchQueue(label: processQueueName)) } // Mark: Getting Images /// Gets an image from a given resource. /// /// - Parameters: /// - resource: The `Resource` object defines data information like key or URL. /// - options: Options to use when creating the animated image. /// - progressBlock: Called when the image downloading progress gets updated. If the response does not contain an /// `expectedContentLength`, this block will not be called. `progressBlock` is always called in /// main queue. /// - completionHandler: Called when the image retrieved and set finished. This completion handler will be invoked /// from the `options.callbackQueue`. If not specified, the main queue will be used. /// - Returns: A task represents the image downloading. If there is a download task starts for `.network` resource, /// the started `DownloadTask` is returned. Otherwise, `nil` is returned. /// /// - Note: /// This method will first check whether the requested `resource` is already in cache or not. If cached, /// it returns `nil` and invoke the `completionHandler` after the cached image retrieved. Otherwise, it /// will download the `resource`, store it in cache, then call `completionHandler`. /// @discardableResult public func retrieveImage( with resource: Resource, options: KingfisherOptionsInfo? = nil, progressBlock: DownloadProgressBlock? = nil, completionHandler: ((Result<RetrieveImageResult, KingfisherError>) -> Void)?) -> DownloadTask? { let source = Source.network(resource) return retrieveImage( with: source, options: options, progressBlock: progressBlock, completionHandler: completionHandler ) } /// Gets an image from a given resource. /// /// - Parameters: /// - source: The `Source` object defines data information from network or a data provider. /// - options: Options to use when creating the animated image. /// - progressBlock: Called when the image downloading progress gets updated. If the response does not contain an /// `expectedContentLength`, this block will not be called. `progressBlock` is always called in /// main queue. /// - completionHandler: Called when the image retrieved and set finished. This completion handler will be invoked /// from the `options.callbackQueue`. If not specified, the main queue will be used. /// - Returns: A task represents the image downloading. If there is a download task starts for `.network` resource, /// the started `DownloadTask` is returned. Otherwise, `nil` is returned. /// /// - Note: /// This method will first check whether the requested `source` is already in cache or not. If cached, /// it returns `nil` and invoke the `completionHandler` after the cached image retrieved. Otherwise, it /// will try to load the `source`, store it in cache, then call `completionHandler`. /// public func retrieveImage( with source: Source, options: KingfisherOptionsInfo? = nil, progressBlock: DownloadProgressBlock? = nil, completionHandler: ((Result<RetrieveImageResult, KingfisherError>) -> Void)?) -> DownloadTask? { let options = currentDefaultOptions + (options ?? .empty) return retrieveImage( with: source, options: KingfisherParsedOptionsInfo(options), progressBlock: progressBlock, completionHandler: completionHandler) } func retrieveImage( with source: Source, options: KingfisherParsedOptionsInfo, progressBlock: DownloadProgressBlock? = nil, completionHandler: ((Result<RetrieveImageResult, KingfisherError>) -> Void)?) -> DownloadTask? { if options.forceRefresh { return loadAndCacheImage( source: source, options: options, progressBlock: progressBlock, completionHandler: completionHandler)?.value } else { let loadedFromCache = retrieveImageFromCache( source: source, options: options, completionHandler: completionHandler) if loadedFromCache { return nil } if options.onlyFromCache { let error = KingfisherError.cacheError(reason: .imageNotExisting(key: source.cacheKey)) completionHandler?(.failure(error)) return nil } return loadAndCacheImage( source: source, options: options, progressBlock: progressBlock, completionHandler: completionHandler)?.value } } func provideImage( provider: ImageDataProvider, options: KingfisherParsedOptionsInfo, completionHandler: ((Result<ImageLoadingResult, KingfisherError>) -> Void)?) { guard let completionHandler = completionHandler else { return } provider.data { result in switch result { case .success(let data): (options.processingQueue ?? self.processingQueue).execute { let processor = options.processor let processingItem = ImageProcessItem.data(data) guard let image = processor.process(item: processingItem, options: options) else { options.callbackQueue.execute { let error = KingfisherError.processorError( reason: .processingFailed(processor: processor, item: processingItem)) completionHandler(.failure(error)) } return } options.callbackQueue.execute { let result = ImageLoadingResult(image: image, url: nil, originalData: data) completionHandler(.success(result)) } } case .failure(let error): options.callbackQueue.execute { let error = KingfisherError.imageSettingError( reason: .dataProviderError(provider: provider, error: error)) completionHandler(.failure(error)) } } } } @discardableResult func loadAndCacheImage( source: Source, options: KingfisherParsedOptionsInfo, progressBlock: DownloadProgressBlock? = nil, completionHandler: ((Result<RetrieveImageResult, KingfisherError>) -> Void)?) -> DownloadTask.WrappedTask? { func cacheImage(_ result: Result<ImageLoadingResult, KingfisherError>) { switch result { case .success(let value): // Add image to cache. let targetCache = options.targetCache ?? self.cache targetCache.store( value.image, original: value.originalData, forKey: source.cacheKey, options: options, toDisk: !options.cacheMemoryOnly) { _ in if options.waitForCache { let result = RetrieveImageResult(image: value.image, cacheType: .none, source: source) completionHandler?(.success(result)) } } // Add original image to cache if necessary. let needToCacheOriginalImage = options.cacheOriginalImage && options.processor != DefaultImageProcessor.default if needToCacheOriginalImage { let originalCache = options.originalCache ?? targetCache originalCache.storeToDisk( value.originalData, forKey: source.cacheKey, processorIdentifier: DefaultImageProcessor.default.identifier, expiration: options.diskCacheExpiration) } if !options.waitForCache { let result = RetrieveImageResult(image: value.image, cacheType: .none, source: source) completionHandler?(.success(result)) } case .failure(let error): completionHandler?(.failure(error)) } } switch source { case .network(let resource): let downloader = options.downloader ?? self.downloader guard let task = downloader.downloadImage( with: resource.downloadURL, options: options, progressBlock: progressBlock, completionHandler: cacheImage) else { return nil } return .download(task) case .provider(let provider): provideImage(provider: provider, options: options, completionHandler: cacheImage) return .dataProviding } } /// Retrieves image from memory or disk cache. /// /// - Parameters: /// - source: The target source from which to get image. /// - key: The key to use when caching the image. /// - url: Image request URL. This is not used when retrieving image from cache. It is just used for /// `RetrieveImageResult` callback compatibility. /// - options: Options on how to get the image from image cache. /// - completionHandler: Called when the image retrieving finishes, either with succeeded /// `RetrieveImageResult` or an error. /// - Returns: `true` if the requested image or the original image before being processed is existing in cache. /// Otherwise, this method returns `false`. /// /// - Note: /// The image retrieving could happen in either memory cache or disk cache. The `.processor` option in /// `options` will be considered when searching in the cache. If no processed image is found, Kingfisher /// will try to check whether an original version of that image is existing or not. If there is already an /// original, Kingfisher retrieves it from cache and processes it. Then, the processed image will be store /// back to cache for later use. func retrieveImageFromCache( source: Source, options: KingfisherParsedOptionsInfo, completionHandler: ((Result<RetrieveImageResult, KingfisherError>) -> Void)?) -> Bool { // 1. Check whether the image was already in target cache. If so, just get it. let targetCache = options.targetCache ?? cache let key = source.cacheKey let targetImageCached = targetCache.imageCachedType( forKey: key, processorIdentifier: options.processor.identifier) let validCache = targetImageCached.cached && (options.fromMemoryCacheOrRefresh == false || targetImageCached == .memory) if validCache { targetCache.retrieveImage(forKey: key, options: options) { result in guard let completionHandler = completionHandler else { return } options.callbackQueue.execute { result.match( onSuccess: { cacheResult in let value: Result<RetrieveImageResult, KingfisherError> if let image = cacheResult.image { value = result.map { RetrieveImageResult(image: image, cacheType: $0.cacheType, source: source) } } else { value = .failure(KingfisherError.cacheError(reason: .imageNotExisting(key: key))) } completionHandler(value) }, onFailure: { _ in completionHandler(.failure(KingfisherError.cacheError(reason: .imageNotExisting(key: key)))) } ) } } return true } // 2. Check whether the original image exists. If so, get it, process it, save to storage and return. let originalCache = options.originalCache ?? targetCache // No need to store the same file in the same cache again. if originalCache === targetCache && options.processor == DefaultImageProcessor.default { return false } // Check whether the unprocessed image existing or not. let originalImageCached = originalCache.imageCachedType( forKey: key, processorIdentifier: DefaultImageProcessor.default.identifier).cached if originalImageCached { // Now we are ready to get found the original image from cache. We need the unprocessed image, so remove // any processor from options first. var optionsWithoutProcessor = options optionsWithoutProcessor.processor = DefaultImageProcessor.default originalCache.retrieveImage(forKey: key, options: optionsWithoutProcessor) { result in result.match( onSuccess: { cacheResult in guard let image = cacheResult.image else { return } let processor = options.processor (options.processingQueue ?? self.processingQueue).execute { let item = ImageProcessItem.image(image) guard let processedImage = processor.process(item: item, options: options) else { let error = KingfisherError.processorError( reason: .processingFailed(processor: processor, item: item)) options.callbackQueue.execute { completionHandler?(.failure(error)) } return } var cacheOptions = options cacheOptions.callbackQueue = .untouch targetCache.store( processedImage, forKey: key, options: cacheOptions, toDisk: !options.cacheMemoryOnly) { _ in if options.waitForCache { let value = RetrieveImageResult(image: processedImage, cacheType: .none, source: source) options.callbackQueue.execute { completionHandler?(.success(value)) } } } if !options.waitForCache { let value = RetrieveImageResult(image: processedImage, cacheType: .none, source: source) options.callbackQueue.execute { completionHandler?(.success(value)) } } } }, onFailure: { _ in // This should not happen actually, since we already confirmed `originalImageCached` is `true`. // Just in case... options.callbackQueue.execute { completionHandler?(.failure(KingfisherError.cacheError(reason: .imageNotExisting(key: key)))) } } ) } return true } return false } }
mit
c27f9830f97702b3e5bd95d3b06a2c60
46.800469
124
0.592938
5.83969
false
false
false
false
fernandomarins/food-drivr-pt
hackathon-for-hunger/Modules/Driver/Dashboards/Views/DonationsContainerViewController.swift
1
5247
// // DonationsOverviewViewController.swift // hackathon-for-hunger // // Created by Ian Gristock on 4/17/16. // Copyright © 2016 Hacksmiths. All rights reserved. // import UIKit class DonationsContainerViewController: UIViewController, PendingDashboardControllerDelegate { enum ActiveBoard : Int { case List case Map } @IBOutlet weak var toggleButton: UIButton! @IBOutlet weak var dashboardContainerView: UIView! weak var currentViewController: UIViewController? var donationListView: PendingDonationsDashboard? var donationOverviewMap: DonationMapOverviewVC? var currentActiveView: ActiveBoard = .List override func viewDidLoad() { self.setupView() super.viewDidLoad() } private func setupView() { self.donationListView = self.storyboard?.instantiateViewControllerWithIdentifier("DonationLIstView") as? PendingDonationsDashboard self.donationListView?.delegate = self self.currentViewController = self.donationListView self.toggleButton.layer.cornerRadius = 0.5 * self.toggleButton.bounds.width self.toggleButton.layer.shadowColor = UIColor.blackColor().CGColor self.toggleButton.layer.shadowOffset = CGSizeMake(2, 2) self.toggleButton.layer.shadowRadius = 2 self.toggleButton.layer.shadowOpacity = 0.5 self.currentViewController!.view.translatesAutoresizingMaskIntoConstraints = false self.addChildViewController(self.currentViewController!) self.addSubview(self.currentViewController!.view, toView: self.dashboardContainerView) } @IBAction func containerButtonToggled(sender: AnyObject) { switch currentActiveView { case .Map: self.currentActiveView = .List let newViewController = self.donationListView newViewController!.view.translatesAutoresizingMaskIntoConstraints = false self.toggleButton.setImage(UIImage(named: "map-icon"), forState: .Normal) self.cycleFromViewController(self.currentViewController!, toViewController: newViewController!) self.currentViewController = newViewController case .List: self.currentActiveView = .Map if let newViewController = self.donationOverviewMap { newViewController.view.translatesAutoresizingMaskIntoConstraints = false self.toggleButton.setImage(UIImage(named: "list-icon"), forState: .Normal) self.cycleFromViewController(self.currentViewController!, toViewController: newViewController) } else { self.toggleButton.setImage(UIImage(named: "list-icon"), forState: .Normal) self.donationOverviewMap = self.storyboard?.instantiateViewControllerWithIdentifier("DonationOverviewMap") as? DonationMapOverviewVC let newViewController = self.donationOverviewMap newViewController!.view.translatesAutoresizingMaskIntoConstraints = false self.cycleFromViewController(self.currentViewController!, toViewController: newViewController!) } } } func addSubview(subView:UIView, toView parentView:UIView) { parentView.addSubview(subView) var viewBindingsDict = [String: AnyObject]() viewBindingsDict["subView"] = subView parentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[subView]|", options: [], metrics: nil, views: viewBindingsDict)) parentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[subView]|", options: [], metrics: nil, views: viewBindingsDict)) } func cycleFromViewController(oldViewController: UIViewController, toViewController newViewController: UIViewController) { self.currentViewController = newViewController oldViewController.willMoveToParentViewController(nil) self.addChildViewController(newViewController) self.addSubview(newViewController.view, toView:self.dashboardContainerView!) // TODO: Set the starting state of your constraints here newViewController.view.layoutIfNeeded() // TODO: Set the ending state of your constraints here UIView.animateWithDuration(0.5, animations: { // only need to call layoutIfNeeded here newViewController.view.layoutIfNeeded() }, completion: { finished in oldViewController.view.removeFromSuperview() oldViewController.removeFromParentViewController() newViewController.didMoveToParentViewController(self) }) } @IBAction func unwindToMenu(segue: UIStoryboardSegue) { guard let delegate = UIApplication.sharedApplication().delegate as? AppDelegate else { return } delegate.runLoginFlow() } func showToggleButton() { self.toggleButton.hidden = false } func hideToggleButton() { self.toggleButton.hidden = true } }
mit
5b912cd5e12c5bbfccaba64b9c70b692
42.363636
148
0.676897
6.022962
false
false
false
false
tobevoid/TBVPullView
TBVPullView/Classes/UIImage+GifExtension.swift
1
966
// // UIImage+GifExtension.swift // TBVAnimatePullView // // Created by tripleCC on 16/5/20. // Copyright © 2016年 tripleCC. All rights reserved. // import UIKit import ImageIO import MobileCoreServices extension UIImage { static func imagesWithGifData(data: NSData) -> [UIImage]? { let mutableOptions = NSMutableDictionary() mutableOptions[String(kCGImageSourceShouldCache)] = true mutableOptions[String(kCGImageSourceTypeIdentifierHint)] = String(kUTTypeGIF) guard let imageSource = CGImageSourceCreateWithData(data, mutableOptions) else { return nil } let numberOfFrames = CGImageSourceGetCount(imageSource) var mutableImages = [UIImage]() for idx in 0..<numberOfFrames { if let imageRef = CGImageSourceCreateImageAtIndex(imageSource, idx, mutableOptions) { mutableImages.append(UIImage(CGImage: imageRef)) } } return mutableImages } }
mit
49cf096c3f8ad2b1292b21cd8d332d94
33.428571
101
0.695742
4.863636
false
false
false
false
GrandCentralBoard/GrandCentralBoard
Pods/SlackKit/SlackKit/Sources/Team.swift
2
3007
// // Team.swift // // Copyright © 2016 Peter Zignego. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. public struct Team { public let id: String internal(set) public var name: String? internal(set) public var domain: String? internal(set) public var emailDomain: String? internal(set) public var messageEditWindowMinutes: Int? internal(set) public var overStorageLimit: Bool? internal(set) public var prefs: [String: AnyObject]? internal(set) public var plan: String? internal(set) public var icon: TeamIcon? internal init?(team: [String: AnyObject]?) { id = team?["id"] as! String name = team?["name"] as? String domain = team?["domain"] as? String emailDomain = team?["email_domain"] as? String messageEditWindowMinutes = team?["msg_edit_window_mins"] as? Int overStorageLimit = team?["over_storage_limit"] as? Bool prefs = team?["prefs"] as? [String: AnyObject] plan = team?["plan"] as? String icon = TeamIcon(icon: team?["icon"] as? [String: AnyObject]) } } public struct TeamIcon { internal(set) public var image34: String? internal(set) public var image44: String? internal(set) public var image68: String? internal(set) public var image88: String? internal(set) public var image102: String? internal(set) public var image132: String? internal(set) public var imageOriginal: String? internal(set) public var imageDefault: Bool? internal init?(icon: [String: AnyObject]?) { image34 = icon?["image_34"] as? String image44 = icon?["image_44"] as? String image68 = icon?["image_68"] as? String image88 = icon?["image_88"] as? String image102 = icon?["image_102"] as? String image132 = icon?["image_132"] as? String imageOriginal = icon?["image_original"] as? String imageDefault = icon?["image_default"] as? Bool } }
gpl-3.0
89eb0ffcddf3a5513c5847fd76bdc9f3
41.942857
80
0.686959
4.18663
false
false
false
false
Keanyuan/SwiftContact
SwiftContent/SwiftContent/Classes/PhotoBrower/LLPhotoBrowser/LLBrowserLoadingImageView.swift
1
1069
// // LLBrowserLoadingImageView.swift // LLPhotoBrowser // // Created by LvJianfeng on 2017/4/14. // Copyright © 2017年 LvJianfeng. All rights reserved. // import UIKit class LLBrowserLoadingImageView: UIImageView { let rotationAnimation: CABasicAnimation? = { let tempAnimation = CABasicAnimation.init(keyPath: "transform.rotation.z") tempAnimation.toValue = CGFloat(2 * Double.pi) tempAnimation.duration = 0.6 tempAnimation.repeatCount = .greatestFiniteMagnitude return tempAnimation }() override init(frame: CGRect) { super.init(frame: frame) image = LLAssetManager.image("ll_browserLoading") } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func startAnimating() { isHidden = false layer.add(rotationAnimation!, forKey: "rotateAnimation") } override func stopAnimating() { isHidden = true layer.removeAnimation(forKey: "rotateAnimation") } }
mit
1a1c729dba733fffa22ca894c7371080
26.333333
82
0.660413
4.655022
false
false
false
false
lorentey/swift
test/Interpreter/Inputs/dynamic_replacement_module.swift
8
5801
#if MODULE public dynamic var public_global_var = "public_global_var" public dynamic func public_global_func() -> String { return "public_global_func" } public dynamic func public_global_generic_func<T>(_ t: T.Type) -> String { return "public_global_generic_func" } public class PublicClass { public var str : String = "" public init() {} public dynamic init(x: Int) { str = "public_class_init" } public dynamic func function() -> String { return "public_class_func" } public dynamic final func finalFunction() -> String { return "public_class_final_func" } public dynamic func genericFunction<T>(_ t: T.Type) -> String { return "public_class_generic_func" } } public struct PublicStruct { public var str = "" public init() {} public dynamic init(x: Int) { str = "public_struct_init" } public dynamic func function() -> String { return "public_struct_func" } public dynamic func genericFunction<T>(_ t: T.Type) -> String { return "public_struct_generic_func" } public dynamic var public_stored_property : String = "public_stored_property" public dynamic subscript(_ x: Int) -> String { get { return "public_subscript_get" } set { str = newValue } } public dynamic subscript(y x: Int) -> String { _read { yield "public_subscript_get_modify_read" } _modify { yield &str } } } public enum PublicEnumeration<Q> { case A case B public dynamic func function() -> String { return "public_enum_func" } public dynamic func genericFunction<T>(_ t: T.Type) -> String { return "public_enum_generic_func" } } #elseif MODULENODYNAMIC public dynamic var public_global_var = "public_global_var" public func public_global_func() -> String { return "public_global_func" } public func public_global_generic_func<T>(_ t: T.Type) -> String { return "public_global_generic_func" } public class PublicClass { public var str : String = "" public init() {} public init(x: Int) { str = "public_class_init" } public func function() -> String { return "public_class_func" } public final func finalFunction() -> String { return "public_class_final_func" } public func genericFunction<T>(_ t: T.Type) -> String { return "public_class_generic_func" } } public struct PublicStruct { public var str = "" public init() {} public init(x: Int) { str = "public_struct_init" } public func function() -> String { return "public_struct_func" } public func genericFunction<T>(_ t: T.Type) -> String { return "public_struct_generic_func" } dynamic public var public_stored_property : String = "public_stored_property" public subscript(_ x: Int) -> String { get { return "public_subscript_get" } set { str = newValue } } public subscript(y x: Int) -> String { _read { yield "public_subscript_get_modify_read" } _modify { yield &str } } } public enum PublicEnumeration<Q> { case A case B public func function() -> String { return "public_enum_func" } public func genericFunction<T>(_ t: T.Type) -> String { return "public_enum_generic_func" } } #elseif MODULE2 import Module1 /// Public global functions, struct, class, and enum. @_dynamicReplacement(for: public_global_var) public var replacement_for_public_global_var : String { return "replacement of public_global_var" } @_dynamicReplacement(for: public_global_func()) public func replacement_for_public_global_func() -> String { return "replacement of " + public_global_func() } @_dynamicReplacement(for: public_global_generic_func(_:)) public func replacement_for_public_global_generic_func<T>(_ t: T.Type) -> String { return "replacement of " + public_global_generic_func(t) } extension PublicClass { @_dynamicReplacement(for: init(x:)) public init(y: Int) { str = "replacement of public_class_init" } @_dynamicReplacement(for: function()) public func replacement_function() -> String { return "replacement of " + function() } @_dynamicReplacement(for: finalFunction()) public func replacement_finalFunction() -> String { return "replacement of " + finalFunction() } @_dynamicReplacement(for: genericFunction(_:)) public func replacement_genericFunction<T>(_ t: T.Type) -> String { return "replacement of " + genericFunction(t) } } extension PublicStruct { @_dynamicReplacement(for: init(x:)) public init(y: Int) { self.init(x: y) str = "replacement of public_struct_init" } @_dynamicReplacement(for: function()) public func replacement_function() -> String { return "replacement of " + function() } @_dynamicReplacement(for: genericFunction(_:)) public func replacement_genericFunction<T>(_ t: T.Type) -> String { return "replacement of " + genericFunction(t) } @_dynamicReplacement(for: public_stored_property) var replacement_public_stored_property : String { return "replacement of " + public_stored_property } @_dynamicReplacement(for: subscript(_:)) subscript(x x: Int) -> String { get { return "replacement of " + self[x] } set { str = "replacement of " + newValue } } @_dynamicReplacement(for: subscript(y:)) public subscript(z x: Int) -> String { _read { yield "replacement of " + self[y: x] } _modify { yield &str str = "replacement of " + str } } } extension PublicEnumeration { @_dynamicReplacement(for: function()) public func replacement_function() -> String { return "replacement of " + function() } @_dynamicReplacement(for: genericFunction(_:)) public func replacement_genericFunction<T>(_ t: T.Type) -> String { return "replacement of " + genericFunction(t) } } #endif
apache-2.0
b7c3718b2299b84d5a2b7231b6ccb239
23.685106
82
0.657473
3.725755
false
false
false
false
gregomni/swift
test/SILGen/default_constructor.swift
5
6694
// RUN: %target-swift-emit-silgen -Xllvm -sil-full-demangle -primary-file %s | %FileCheck %s struct B { var i : Int, j : Float var c : C } struct C { var x : Int init() { x = 17 } } struct D { var (i, j) : (Int, Double) = (2, 3.5) } // CHECK-LABEL: sil hidden [transparent] [ossa] @$s19default_constructor1DV1iSivpfi : $@convention(thin) () -> (Int, Double) // CHECK: [[VALUE:%.*]] = integer_literal $Builtin.IntLiteral, 2 // CHECK-NEXT: [[METATYPE:%.*]] = metatype $@thin Int.Type // CHECK: [[FN:%.*]] = function_ref @$sSi22_builtinIntegerLiteralSiBI_tcfC : $@convention(method) (Builtin.IntLiteral, @thin Int.Type) -> Int // CHECK-NEXT: [[LEFT:%.*]] = apply [[FN]]([[VALUE]], [[METATYPE]]) : $@convention(method) (Builtin.IntLiteral, @thin Int.Type) -> Int // CHECK-NEXT: [[VALUE:%.*]] = float_literal $Builtin.FPIEEE{{64|80}}, {{0x400C000000000000|0x4000E000000000000000}} // CHECK-NEXT: [[METATYPE:%.*]] = metatype $@thin Double.Type // CHECK: [[FN:%.*]] = function_ref @$sSd20_builtinFloatLiteralSdBf{{64|80}}__tcfC : $@convention(method) (Builtin.FPIEEE{{64|80}}, @thin Double.Type) -> Double // CHECK-NEXT: [[RIGHT:%.*]] = apply [[FN]]([[VALUE]], [[METATYPE]]) : $@convention(method) (Builtin.FPIEEE{{64|80}}, @thin Double.Type) -> Double // CHECK-NEXT: [[RESULT:%.*]] = tuple ([[LEFT]] : $Int, [[RIGHT]] : $Double) // CHECK-NEXT: return [[RESULT]] : $(Int, Double) // CHECK-LABEL: sil hidden [ossa] @$s19default_constructor1DV{{[_0-9a-zA-Z]*}}fC : $@convention(method) (@thin D.Type) -> D // CHECK: [[THISBOX:%[0-9]+]] = alloc_box ${ var D } // CHECK: [[THIS:%[0-9]+]] = mark_uninit // CHECK: [[THISLIFE:%[^,]+]] = begin_borrow [lexical] [[THIS]] // CHECK: [[PB_THIS:%.*]] = project_box [[THISLIFE]] // CHECK: [[IADDR:%[0-9]+]] = struct_element_addr [[PB_THIS]] : $*D, #D.i // CHECK: [[JADDR:%[0-9]+]] = struct_element_addr [[PB_THIS]] : $*D, #D.j // CHECK: [[INIT:%[0-9]+]] = function_ref @$s19default_constructor1DV1iSivpfi // CHECK: [[RESULT:%[0-9]+]] = apply [[INIT]]() // CHECK: ([[INTVAL:%[0-9]+]], [[FLOATVAL:%[0-9]+]]) = destructure_tuple [[RESULT]] // CHECK: store [[INTVAL]] to [trivial] [[IADDR]] // CHECK: store [[FLOATVAL]] to [trivial] [[JADDR]] class E { var i = Int64() } // CHECK-LABEL: sil hidden [transparent] [ossa] @$s19default_constructor1EC1is5Int64Vvpfi : $@convention(thin) () -> Int64 // CHECK: [[IADDR:%[0-9]+]] = alloc_stack $Int64 // CHECK: [[INTTYPE:%[0-9]+]] = metatype $@thick Int64.Type // CHECK: [[INIT:%[0-9]+]] = function_ref @$sSzsExycfC : $@convention(method) // CHECK-NEXT: apply [[INIT]]<Int64>([[IADDR]], [[INTTYPE]]) // CHECK-NEXT: [[VALUE:%[0-9]+]] = load [trivial] [[IADDR]] // CHECK-NEXT: dealloc_stack [[IADDR]] // CHECK-NEXT: return [[VALUE]] : $Int64 // CHECK-LABEL: sil hidden [ossa] @$s19default_constructor1EC{{[_0-9a-zA-Z]*}}fc : $@convention(method) (@owned E) -> @owned E // CHECK: bb0([[SELFIN:%[0-9]+]] : @owned $E) // CHECK: [[SELF:%[0-9]+]] = mark_uninitialized // CHECK-NEXT: [[BORROWED_SELF:%.*]] = begin_borrow [[SELF]] // CHECK-NEXT: [[IREF:%[0-9]+]] = ref_element_addr [[BORROWED_SELF]] : $E, #E.i // CHECK: [[INIT:%[0-9]+]] = function_ref @$s19default_constructor1EC1is5Int64Vvpfi : $@convention(thin) () -> Int64 // CHECK-NEXT: [[VALUE:%[0-9]+]] = apply [[INIT]]() : $@convention(thin) () -> Int64 // CHECK-NEXT: store [[VALUE]] to [trivial] [[IREF]] : $*Int64 // CHECK-NEXT: end_borrow [[BORROWED_SELF]] // CHECK-NEXT: [[SELF_COPY:%.*]] = copy_value [[SELF]] // CHECK-NEXT: destroy_value [[SELF]] // CHECK-NEXT: return [[SELF_COPY]] : $E class F : E { } // CHECK-LABEL: sil hidden [ossa] @$s19default_constructor1FCACycfc : $@convention(method) (@owned F) -> @owned F // CHECK: bb0([[ORIGSELF:%[0-9]+]] : @owned $F) // CHECK-NEXT: [[SELF_BOX:%[0-9]+]] = alloc_box ${ var F } // CHECK-NEXT: [[SELF:%[0-9]+]] = mark_uninitialized [derivedself] [[SELF_BOX]] // CHECK-NEXT: [[SELFLIFE:%[^,]+]] = begin_borrow [lexical] [[SELF]] // CHECK-NEXT: [[PB:%.*]] = project_box [[SELFLIFE]] // CHECK-NEXT: store [[ORIGSELF]] to [init] [[PB]] : $*F // CHECK-NEXT: [[SELFP:%[0-9]+]] = load [take] [[PB]] : $*F // CHECK-NEXT: [[E:%[0-9]]] = upcast [[SELFP]] : $F to $E // CHECK: [[E_CTOR:%[0-9]+]] = function_ref @$s19default_constructor1ECACycfc : $@convention(method) (@owned E) -> @owned E // CHECK-NEXT: [[ESELF:%[0-9]]] = apply [[E_CTOR]]([[E]]) : $@convention(method) (@owned E) -> @owned E // CHECK-NEXT: [[ESELFW:%[0-9]+]] = unchecked_ref_cast [[ESELF]] : $E to $F // CHECK-NEXT: store [[ESELFW]] to [init] [[PB]] : $*F // CHECK-NEXT: [[SELFP:%[0-9]+]] = load [copy] [[PB]] : $*F // CHECK-NEXT: end_borrow [[SELFLIFE]] // CHECK-NEXT: destroy_value [[SELF]] : ${ var F } // CHECK-NEXT: return [[SELFP]] : $F // <rdar://problem/19780343> Default constructor for a struct with optional doesn't compile // This shouldn't get a default init, since it would be pointless (bar can never // be reassigned). It should get a memberwise init though. struct G { let bar: Int32? } // CHECK-NOT: default_constructor.G.init() // CHECK-LABEL: default_constructor.G.init(bar: Swift.Optional<Swift.Int32>) // CHECK-NEXT: sil hidden [ossa] @$s19default_constructor1GV{{[_0-9a-zA-Z]*}}fC // CHECK-NOT: default_constructor.G.init() struct H<T> { var opt: T? // CHECK-LABEL: sil hidden [ossa] @$s19default_constructor1HVyACyxGqd__clufC : $@convention(method) <T><U> (@in U, @thin H<T>.Type) -> @out H<T> { // CHECK: [[OPT_T:%[0-9]+]] = struct_element_addr {{%.*}} : $*H<T>, #H.opt // CHECK: [[INIT_FN:%[0-9]+]] = function_ref @$s19default_constructor1HV3optxSgvpfi : $@convention(thin) <τ_0_0> () -> @out Optional<τ_0_0> // CHECK-NEXT: apply [[INIT_FN]]<T>([[OPT_T]]) : $@convention(thin) <τ_0_0> () -> @out Optional<τ_0_0> init<U>(_: U) { } } // <rdar://problem/29605388> Member initializer for non-generic type with generic constructor doesn't compile struct I { var x: Int = 0 // CHECK-LABEL: sil hidden [ossa] @$s19default_constructor1IVyACxclufC : $@convention(method) <T> (@in T, @thin I.Type) -> I { // CHECK: [[X_ADDR:%[0-9]+]] = struct_element_addr {{.*}} : $*I, #I.x // CHECK: [[INIT_FN:%[0-9]+]] = function_ref @$s19default_constructor1IV1xSivpfi : $@convention(thin) () -> Int // CHECK: [[RESULT:%[0-9]+]] = apply [[INIT_FN]]() : $@convention(thin) () -> Int // CHECK: store [[RESULT]] to [trivial] [[X_ADDR]] : $*Int init<T>(_: T) {} } // https://bugs.swift.org/browse/SR-10075 func defaultValue<T>() -> T { fatalError() } struct S<T> { let value1: T = defaultValue() let value2: Int // CHECK-LABEL: sil hidden [ossa] @$s19default_constructor1SV6value2ACyxGSi_tcfC : $@convention(method) <T> (Int, @thin S<T>.Type) -> @out S<T> }
apache-2.0
cf2d943f0cd485b80689ee974ba21fb7
48.191176
165
0.602392
2.947137
false
false
false
false
mozilla-mobile/firefox-ios
Client/Telemetry/TelemetryWrapper.swift
1
71192
// 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 Glean import Shared import Telemetry import Account import Sync protocol TelemetryWrapperProtocol { func recordEvent(category: TelemetryWrapper.EventCategory, method: TelemetryWrapper.EventMethod, object: TelemetryWrapper.EventObject, value: TelemetryWrapper.EventValue?, extras: [String: Any]?) } extension TelemetryWrapperProtocol { func recordEvent(category: TelemetryWrapper.EventCategory, method: TelemetryWrapper.EventMethod, object: TelemetryWrapper.EventObject, value: TelemetryWrapper.EventValue? = nil, extras: [String: Any]? = nil) { recordEvent(category: category, method: method, object: object, value: value, extras: extras) } } class TelemetryWrapper: TelemetryWrapperProtocol { static let shared = TelemetryWrapper() let legacyTelemetry = Telemetry.default let glean = Glean.shared // Boolean flag to temporarily remember if we crashed during the // last run of the app. We cannot simply use `Sentry.crashedLastLaunch` // because we want to clear this flag after we've already reported it // to avoid re-reporting the same crash multiple times. private var crashedLastLaunch: Bool private var profile: Profile? init() { crashedLastLaunch = SentryIntegration.shared.crashedLastLaunch } private func migratePathComponentInDocumentsDirectory(_ pathComponent: String, to destinationSearchPath: FileManager.SearchPathDirectory) { guard let oldPath = try? FileManager.default.url( for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false).appendingPathComponent(pathComponent).path, FileManager.default.fileExists(atPath: oldPath) else { return } print("Migrating \(pathComponent) from ~/Documents to \(destinationSearchPath)") guard let newPath = try? FileManager.default.url( for: destinationSearchPath, in: .userDomainMask, appropriateFor: nil, create: true).appendingPathComponent(pathComponent).path else { print("Unable to get destination path \(destinationSearchPath) to move \(pathComponent)") return } do { try FileManager.default.moveItem(atPath: oldPath, toPath: newPath) print("Migrated \(pathComponent) to \(destinationSearchPath) successfully") } catch let error as NSError { print("Unable to move \(pathComponent) to \(destinationSearchPath): \(error.localizedDescription)") } } func setup(profile: Profile) { migratePathComponentInDocumentsDirectory("MozTelemetry-Default-core", to: .cachesDirectory) migratePathComponentInDocumentsDirectory("MozTelemetry-Default-mobile-event", to: .cachesDirectory) migratePathComponentInDocumentsDirectory("eventArray-MozTelemetry-Default-mobile-event.json", to: .cachesDirectory) NotificationCenter.default.addObserver(self, selector: #selector(uploadError), name: Telemetry.notificationReportError, object: nil) let telemetryConfig = legacyTelemetry.configuration telemetryConfig.appName = "Fennec" telemetryConfig.userDefaultsSuiteName = AppInfo.sharedContainerIdentifier telemetryConfig.dataDirectory = .cachesDirectory telemetryConfig.updateChannel = AppConstants.BuildChannel.rawValue let sendUsageData = profile.prefs.boolForKey(AppConstants.PrefSendUsageData) ?? true telemetryConfig.isCollectionEnabled = sendUsageData telemetryConfig.isUploadEnabled = sendUsageData telemetryConfig.measureUserDefaultsSetting(forKey: "profile.saveLogins", withDefaultValue: true) telemetryConfig.measureUserDefaultsSetting(forKey: "profile.showClipboardBar", withDefaultValue: false) telemetryConfig.measureUserDefaultsSetting(forKey: "profile.settings.closePrivateTabs", withDefaultValue: false) telemetryConfig.measureUserDefaultsSetting(forKey: "profile.ASPocketStoriesVisible", withDefaultValue: true) telemetryConfig.measureUserDefaultsSetting(forKey: "profile.ASBookmarkHighlightsVisible", withDefaultValue: true) telemetryConfig.measureUserDefaultsSetting(forKey: "profile.prefkey.trackingprotection.normalbrowsing", withDefaultValue: true) telemetryConfig.measureUserDefaultsSetting(forKey: "profile.prefkey.trackingprotection.privatebrowsing", withDefaultValue: true) telemetryConfig.measureUserDefaultsSetting(forKey: "profile.prefkey.trackingprotection.strength", withDefaultValue: "basic") telemetryConfig.measureUserDefaultsSetting(forKey: LegacyThemeManagerPrefs.systemThemeIsOn.rawValue, withDefaultValue: true) let prefs = profile.prefs legacyTelemetry.beforeSerializePing(pingType: CorePingBuilder.PingType) { (inputDict) -> [String: Any?] in var outputDict = inputDict // make a mutable copy var settings: [String: Any?] = inputDict["settings"] as? [String: Any?] ?? [:] if let newTabChoice = prefs.stringForKey(NewTabAccessors.HomePrefKey) { outputDict["defaultNewTabExperience"] = newTabChoice as AnyObject? } // Report this flag as a `1` or `0` integer to allow it // to be counted easily when reporting. Then, clear the // flag to avoid it getting reported multiple times. settings["crashedLastLaunch"] = self.crashedLastLaunch ? 1 : 0 self.crashedLastLaunch = false outputDict["settings"] = settings let delegate = UIApplication.shared.delegate as? AppDelegate outputDict["openTabCount"] = delegate?.tabManager.count ?? 0 outputDict["systemTheme"] = UITraitCollection.current.userInterfaceStyle == .dark ? "dark" : "light" return outputDict } legacyTelemetry.beforeSerializePing(pingType: MobileEventPingBuilder.PingType) { (inputDict) -> [String: Any?] in var outputDict = inputDict var settings: [String: String?] = inputDict["settings"] as? [String: String?] ?? [:] let searchEngines = SearchEngines(prefs: profile.prefs, files: profile.files) settings["defaultSearchEngine"] = searchEngines.defaultEngine.engineID ?? "custom" if let windowBounds = UIWindow.keyWindow?.bounds { settings["windowWidth"] = String(describing: windowBounds.width) settings["windowHeight"] = String(describing: windowBounds.height) } outputDict["settings"] = settings // App Extension telemetry requires reading events stored in prefs, then clearing them from prefs. if let extensionEvents = profile.prefs.arrayForKey(PrefsKeys.AppExtensionTelemetryEventArray) as? [[String: String]], var pingEvents = outputDict["events"] as? [[Any?]] { profile.prefs.removeObjectForKey(PrefsKeys.AppExtensionTelemetryEventArray) extensionEvents.forEach { extensionEvent in let category = TelemetryWrapper.EventCategory.appExtensionAction.rawValue let newEvent = TelemetryEvent(category: category, method: extensionEvent["method"] ?? "", object: extensionEvent["object"] ?? "") pingEvents.append(newEvent.toArray()) } outputDict["events"] = pingEvents } return outputDict } legacyTelemetry.add(pingBuilderType: CorePingBuilder.self) legacyTelemetry.add(pingBuilderType: MobileEventPingBuilder.self) // Initialize Glean initGlean(profile, sendUsageData: sendUsageData) } func initGlean(_ profile: Profile, sendUsageData: Bool) { // Get the legacy telemetry ID and record it in Glean for the deletion-request ping if let uuidString = UserDefaults.standard.string(forKey: "telemetry-key-prefix-clientId"), let uuid = UUID(uuidString: uuidString) { GleanMetrics.LegacyIds.clientId.set(uuid) } // Initialize Glean telemetry glean.initialize(uploadEnabled: sendUsageData, configuration: Configuration(channel: AppConstants.BuildChannel.rawValue), buildInfo: GleanMetrics.GleanBuild.info) // Save the profile so we can record settings from it when the notification below fires. self.profile = profile setSyncDeviceId() SponsoredTileTelemetry.setupContextId() // Register an observer to record settings and other metrics that are more appropriate to // record on going to background rather than during initialization. NotificationCenter.default.addObserver( self, selector: #selector(recordEnteredBackgroundPreferenceMetrics(notification:)), name: UIApplication.didEnterBackgroundNotification, object: nil ) NotificationCenter.default.addObserver( self, selector: #selector(recordFinishedLaunchingPreferenceMetrics(notification:)), name: UIApplication.didFinishLaunchingNotification, object: nil ) } // Sets hashed fxa sync device id for glean deletion ping func setSyncDeviceId() { guard let prefs = profile?.prefs else { return } // Grab our token so we can use the hashed_fxa_uid and clientGUID from our scratchpad for deletion-request ping RustFirefoxAccounts.shared.syncAuthState.token(Date.now(), canBeExpired: true) >>== { (token, kSync) in let scratchpadPrefs = prefs.branch("sync.scratchpad") guard let scratchpad = Scratchpad.restoreFromPrefs(scratchpadPrefs, syncKeyBundle: KeyBundle.fromKSync(kSync)) else { return } let deviceId = (scratchpad.clientGUID + token.hashedFxAUID).sha256.hexEncodedString GleanMetrics.Deletion.syncDeviceId.set(deviceId) } } @objc func recordFinishedLaunchingPreferenceMetrics(notification: NSNotification) { guard let profile = self.profile else { return } // Pocket stories visible if let pocketStoriesVisible = profile.prefs.boolForKey(PrefsKeys.FeatureFlags.ASPocketStories) { GleanMetrics.FirefoxHomePage.pocketStoriesVisible.set(pocketStoriesVisible) } else { GleanMetrics.FirefoxHomePage.pocketStoriesVisible.set(true) } } // Function for recording metrics that are better recorded when going to background due // to the particular measurement, or availability of the information. @objc func recordEnteredBackgroundPreferenceMetrics(notification: NSNotification) { guard let profile = self.profile else { assert(false); return; } // Record default search engine setting let searchEngines = SearchEngines(prefs: profile.prefs, files: profile.files) GleanMetrics.Search.defaultEngine.set(searchEngines.defaultEngine.engineID ?? "custom") // Record the open tab count let delegate = UIApplication.shared.delegate as? AppDelegate if let count = delegate?.tabManager.count { GleanMetrics.Tabs.cumulativeCount.add(Int32(count)) } // Record other preference settings. // If the setting exists at the key location, use that value. Otherwise record the default // value for that preference to ensure it makes it into the metrics ping. let prefs = profile.prefs // Record New Tab setting if let newTabChoice = prefs.stringForKey(NewTabAccessors.HomePrefKey) { GleanMetrics.Preferences.newTabExperience.set(newTabChoice) } else { GleanMetrics.Preferences.newTabExperience.set(NewTabAccessors.Default.rawValue) } // Record `Home` setting, where Firefox Home is "Home", a custom URL is "other" and blank is "Blank". let homePageSetting = NewTabAccessors.getHomePage(prefs) switch homePageSetting { case .topSites: let firefoxHome = "Home" GleanMetrics.Preferences.homePageSetting.set(firefoxHome) case .homePage: let customUrl = "other" GleanMetrics.Preferences.homePageSetting.set(customUrl) default: GleanMetrics.Preferences.homePageSetting.set(homePageSetting.rawValue) } // Save logins if let saveLogins = prefs.boolForKey(PrefsKeys.LoginsSaveEnabled) { GleanMetrics.Preferences.saveLogins.set(saveLogins) } else { GleanMetrics.Preferences.saveLogins.set(true) } // Show clipboard bar if let showClipboardBar = prefs.boolForKey("showClipboardBar") { GleanMetrics.Preferences.showClipboardBar.set(showClipboardBar) } else { GleanMetrics.Preferences.showClipboardBar.set(false) } // Close private tabs if let closePrivateTabs = prefs.boolForKey("settings.closePrivateTabs") { GleanMetrics.Preferences.closePrivateTabs.set(closePrivateTabs) } else { GleanMetrics.Preferences.closePrivateTabs.set(false) } // Tracking protection - enabled if let tpEnabled = prefs.boolForKey(ContentBlockingConfig.Prefs.EnabledKey) { GleanMetrics.TrackingProtection.enabled.set(tpEnabled) } else { GleanMetrics.TrackingProtection.enabled.set(true) } // Tracking protection - strength if let tpStrength = prefs.stringForKey(ContentBlockingConfig.Prefs.StrengthKey) { GleanMetrics.TrackingProtection.strength.set(tpStrength) } else { GleanMetrics.TrackingProtection.strength.set("basic") } // System theme enabled GleanMetrics.Theme.useSystemTheme.set(LegacyThemeManager.instance.systemThemeIsOn) // Installed Mozilla applications GleanMetrics.InstalledMozillaProducts.focus.set(UIApplication.shared.canOpenURL(URL(string: "firefox-focus://")!)) GleanMetrics.InstalledMozillaProducts.klar.set(UIApplication.shared.canOpenURL(URL(string: "firefox-klar://")!)) // Device Authentication GleanMetrics.Device.authentication.set(AppAuthenticator.canAuthenticateDeviceOwner()) // Wallpapers let currentWallpaper = WallpaperManager().currentWallpaper if case .other = currentWallpaper.type { // Need to lowercase the name for labeled counter. Ref: // https://mozilla.github.io/glean/book/reference/metrics/index.html#label-format) GleanMetrics.WallpaperAnalytics.themedWallpaper[currentWallpaper.id.lowercased()].add() } } @objc func uploadError(notification: NSNotification) { guard !DeviceInfo.isSimulator(), let error = notification.userInfo?["error"] as? NSError else { return } SentryIntegration.shared.send(message: "Upload Error", tag: SentryTag.unifiedTelemetry, severity: .info, description: error.debugDescription) } } // Enums for Event telemetry. extension TelemetryWrapper { public enum EventCategory: String { case action = "action" case appExtensionAction = "app-extension-action" case prompt = "prompt" case enrollment = "enrollment" case firefoxAccount = "firefox_account" case information = "information" } public enum EventMethod: String { case add = "add" case background = "background" case cancel = "cancel" case change = "change" case close = "close" case closeAll = "close-all" case delete = "delete" case deleteAll = "deleteAll" case drag = "drag" case drop = "drop" case foreground = "foreground" case swipe = "swipe" case navigate = "navigate" case open = "open" case press = "press" case pull = "pull" case scan = "scan" case share = "share" case tap = "tap" case translate = "translate" case view = "view" case applicationOpenUrl = "application-open-url" case emailLogin = "email" case qrPairing = "pairing" case settings = "settings" case application = "application" case voiceOver = "voice-over" case reduceTransparency = "reduce-transparency" case reduceMotion = "reduce-motion" case invertColors = "invert-colors" case switchControl = "switch-control" case dynamicTextSize = "dynamic-text-size" } public enum EventObject: String { case app = "app" case bookmark = "bookmark" case awesomebarResults = "awesomebar-results" case bookmarksPanel = "bookmarks-panel" case download = "download" case downloadLinkButton = "download-link-button" case downloadNowButton = "download-now-button" case downloadsPanel = "downloads-panel" case keyCommand = "key-command" case locationBar = "location-bar" case qrCodeText = "qr-code-text" case qrCodeURL = "qr-code-url" case readerModeCloseButton = "reader-mode-close-button" case readerModeOpenButton = "reader-mode-open-button" case readingListItem = "reading-list-item" case setting = "setting" case tab = "tab" case tabTray = "tab-tray" case tabNormalQuantity = "normal-tab-quantity" case tabPrivateQuantity = "private-tab-quantity" case groupedTab = "grouped-tab" case groupedTabPerformSearch = "grouped-tab-perform-search" case trackingProtectionStatistics = "tracking-protection-statistics" case trackingProtectionSafelist = "tracking-protection-safelist" case trackingProtectionMenu = "tracking-protection-menu" case url = "url" case searchText = "searchText" case whatsNew = "whats-new" case dismissUpdateCoverSheetAndStartBrowsing = "dismissed-update-cover_sheet_and_start_browsing" case dismissedUpdateCoverSheet = "dismissed-update-cover-sheet" case dismissedETPCoverSheet = "dismissed-etp-sheet" case dismissETPCoverSheetAndStartBrowsing = "dismissed-etp-cover-sheet-and-start-browsing" case dismissETPCoverSheetAndGoToSettings = "dismissed-update-cover-sheet-and-go-to-settings" case privateBrowsingButton = "private-browsing-button" case startSearchButton = "start-search-button" case addNewTabButton = "add-new-tab-button" case removeUnVerifiedAccountButton = "remove-unverified-account-button" case tabSearch = "tab-search" case tabToolbar = "tab-toolbar" case chinaServerSwitch = "china-server-switch" case accountConnected = "connected" case accountDisconnected = "disconnected" case appMenu = "app_menu" case settings = "settings" case settingsMenuSetAsDefaultBrowser = "set-as-default-browser-menu-go-to-settings" case settingsMenuShowTour = "show-tour" // MARK: New Onboarding case onboardingClose = "onboarding-close" case onboardingCardView = "onboarding-card-view" case onboardingPrimaryButton = "onboarding-card-primary-button" case onboardingSecondaryButton = "onboarding-card-secondary-button" case onboardingSelectWallpaper = "onboarding-select-wallpaper" case onboarding = "onboarding" case onboardingWallpaperSelector = "onboarding-wallpaper-selector" // MARK: New Upgrade screen case upgradeOnboardingClose = "upgrade-onboarding-close" case upgradeOnboardingCardView = "upgrade-onboarding-card-view" case upgradeOnboardingPrimaryButton = "upgrade-onboarding-card-primary-button" case upgradeOnboardingSecondaryButton = "upgrade-onboarding-card-secondary-button" case upgradeOnboarding = "upgrade-onboarding" case dismissDefaultBrowserCard = "default-browser-card" case goToSettingsDefaultBrowserCard = "default-browser-card-go-to-settings" case dismissDefaultBrowserOnboarding = "default-browser-onboarding" case goToSettingsDefaultBrowserOnboarding = "default-browser-onboarding-go-to-settings" case homeTabBannerEvergreen = "home-tab-banner-evergreen" case asDefaultBrowser = "as-default-browser" case mediumTabsOpenUrl = "medium-tabs-widget-url" case largeTabsOpenUrl = "large-tabs-widget-url" case smallQuickActionSearch = "small-quick-action-search" case mediumQuickActionSearch = "medium-quick-action-search" case mediumQuickActionPrivateSearch = "medium-quick-action-private-search" case mediumQuickActionCopiedLink = "medium-quick-action-copied-link" case mediumQuickActionClosePrivate = "medium-quick-action-close-private" case mediumTopSitesWidget = "medium-top-sites-widget" case topSiteTile = "top-site-tile" case topSiteContextualMenu = "top-site-contextual-menu" case historyHighlightContextualMenu = "history-highlights-contextual-menu" case pocketStory = "pocket-story" case pocketSectionImpression = "pocket-section-impression" case library = "library" case home = "home-page" case homeTabBanner = "home-tab-banner" case blockImagesEnabled = "block-images-enabled" case blockImagesDisabled = "block-images-disabled" case navigateTabHistoryBack = "navigate-tab-history-back" case navigateTabHistoryBackSwipe = "navigate-tab-history-back-swipe" case navigateTabHistoryForward = "navigate-tab-history-forward" case nightModeEnabled = "night-mode-enabled" case nightModeDisabled = "night-mode-disabled" case logins = "logins-and-passwords" case signIntoSync = "sign-into-sync" case syncTab = "sync-tab" case syncSignIn = "sync-sign-in" case syncCreateAccount = "sync-create-account" case libraryPanel = "library-panel" case navigateToGroupHistory = "navigate-to-group-history" case selectedHistoryItem = "selected-history-item" case searchHistory = "search-history" case deleteHistory = "delete-history" case sharePageWith = "share-page-with" case sendToDevice = "send-to-device" case copyAddress = "copy-address" case reportSiteIssue = "report-site-issue" case findInPage = "find-in-page" case requestDesktopSite = "request-desktop-site" case requestMobileSite = "request-mobile-site" case pinToTopSites = "pin-to-top-sites" case removePinnedSite = "remove-pinned-site" case firefoxHomepage = "firefox-homepage" case wallpaperSettings = "wallpaper-settings" case contextualHint = "contextual-hint" case jumpBackInTileImpressions = "jump-back-in-tile-impressions" case syncedTabTileImpressions = "synced-tab-tile-impressions" case historyImpressions = "history-highlights-impressions" case recentlySavedBookmarkImpressions = "recently-saved-bookmark-impressions" case recentlySavedReadingItemImpressions = "recently-saved-reading-items-impressions" case inactiveTabTray = "inactiveTabTray" case reload = "reload" case reloadFromUrlBar = "reload-from-url-bar" case fxaLoginWebpage = "fxa-login-webpage" case fxaLoginCompleteWebpage = "fxa-login-complete-webpage" case fxaRegistrationWebpage = "fxa-registration-webpage" case fxaRegistrationCompletedWebpage = "fxa-registration-completed-webpage" case fxaConfirmSignUpCode = "fxa-confirm-signup-code" case fxaConfirmSignInToken = "fxa-confirm-signin-token" case awesomebarLocation = "awesomebar-position" case searchHighlights = "search-highlights" case viewDownloadsPanel = "view-downloads-panel" case viewHistoryPanel = "view-history-panel" case createNewTab = "create-new-tab" } public enum EventValue: String { case activityStream = "activity-stream" case appMenu = "app-menu" case browser = "browser" case contextMenu = "context-menu" case downloadCompleteToast = "download-complete-toast" case homePanel = "home-panel" case markAsRead = "mark-as-read" case markAsUnread = "mark-as-unread" case pageActionMenu = "page-action-menu" case readerModeToolbar = "reader-mode-toolbar" case readingListPanel = "reading-list-panel" case shareExtension = "share-extension" case shareMenu = "share-menu" case tabTray = "tab-tray" case topTabs = "top-tabs" case systemThemeSwitch = "system-theme-switch" case themeModeManually = "theme-manually" case themeModeAutomatically = "theme-automatically" case themeLight = "theme-light" case themeDark = "theme-dark" case privateTab = "private-tab" case normalTab = "normal-tab" case tabView = "tab-view" case bookmarksPanel = "bookmarks-panel" case historyPanel = "history-panel" case historyPanelNonGroupItem = "history-panel-non-grouped-item" case historyPanelGroupedItem = "history-panel-grouped-item" case readingPanel = "reading-panel" case downloadsPanel = "downloads-panel" case syncPanel = "sync-panel" case yourLibrarySection = "your-library-section" case jumpBackInSectionShowAll = "jump-back-in-section-show-all" case jumpBackInSectionTabOpened = "jump-back-in-section-tab-opened" case jumpBackInSectionGroupOpened = "jump-back-in-section-group-opened" case jumpBackInSectionSyncedTabShowAll = "jump-back-in-section-synced-tab-show-all" case jumpBackInSectionSyncedTabOpened = "jump-back-in-section-synced-tab-opened" case recentlySavedSectionShowAll = "recently-saved-section-show-all" case recentlySavedBookmarkItemAction = "recently-saved-bookmark-item-action" case recentlySavedBookmarkItemView = "recently-saved-bookmark-item-view" case recentlySavedReadingListView = "recently-saved-reading-list-view" case recentlySavedReadingListAction = "recently-saved-reading-list-action" case historyHighlightsShowAll = "history-highlights-show-all" case historyHighlightsItemOpened = "history-highlights-item-opened" case historyHighlightsGroupOpen = "history-highlights-group-open" case customizeHomepageButton = "customize-homepage-button" case wallpaperSelected = "wallpaper-selected" case dismissCFRFromButton = "dismiss-cfr-from-button" case dismissCFRFromOutsideTap = "dismiss-cfr-from-outside-tap" case pressCFRActionButton = "press-cfr-action-button" case fxHomepageOrigin = "firefox-homepage-origin" case fxHomepageOriginZeroSearch = "zero-search" case fxHomepageOriginOther = "origin-other" case addBookmarkToast = "add-bookmark-toast" case openHomeFromAwesomebar = "open-home-from-awesomebar" case openHomeFromPhotonMenuButton = "open-home-from-photon-menu-button" case openInactiveTab = "openInactiveTab" case inactiveTabShown = "inactive-Tab-Shown" case inactiveTabExpand = "inactivetab-expand" case inactiveTabCollapse = "inactivetab-collapse" case inactiveTabCloseAllButton = "inactive-tab-close-all-button" case inactiveTabSwipeClose = "inactive-tab-swipe-close" case openRecentlyClosedTab = "openRecentlyClosedTab" case tabGroupWithExtras = "tabGroupWithExtras" case closeGroupedTab = "recordCloseGroupedTab" case messageImpression = "message-impression" case messageDismissed = "message-dismissed" case messageInteracted = "message-interacted" case messageExpired = "message-expired" case messageMalformed = "message-malformed" case historyItem = "history-item" case remoteTab = "remote-tab" case openedTab = "opened-tab" case bookmarkItem = "bookmark-item" case searchSuggestion = "search-suggestion" case searchHighlights = "search-highlights" } public enum EventExtraKey: String, CustomStringConvertible { case topSitePosition = "tilePosition" case topSiteTileType = "tileType" case contextualMenuType = "contextualMenuType" case pocketTilePosition = "pocketTilePosition" case fxHomepageOrigin = "fxHomepageOrigin" case tabsQuantity = "tabsQuantity" case awesomebarSearchTapType = "awesomebarSearchTapType" case preference = "pref" case preferenceChanged = "to" case isPrivate = "is-private" case action = "action" case wallpaperName = "wallpaperName" case wallpaperType = "wallpaperType" case cfrType = "hintType" // Grouped Tab case groupsWithTwoTabsOnly = "groupsWithTwoTabsOnly" case groupsWithTwoMoreTab = "groupsWithTwoMoreTab" case totalNumberOfGroups = "totalNumOfGroups" case averageTabsInAllGroups = "averageTabsInAllGroups" case totalTabsInAllGroups = "totalTabsInAllGroups" var description: String { return self.rawValue } // Inactive Tab case inactiveTabsCollapsed = "collapsed" case inactiveTabsExpanded = "expanded" // GleanPlumb case messageKey = "message-key" case actionUUID = "action-uuid" // Accessibility case isVoiceOverRunning = "is-voice-over-running" case isSwitchControlRunning = "is-switch-control-running" case isReduceTransparencyEnabled = "is-reduce-transparency-enabled" case isReduceMotionEnabled = "is-reduce-motion-enabled" case isInvertColorsEnabled = "is-invert-colors-enabled" case isAccessibilitySizeEnabled = "is-accessibility-size-enabled" case preferredContentSizeCategory = "preferred-content-size-category" // Onboarding case cardType = "card-type" } func recordEvent(category: EventCategory, method: EventMethod, object: EventObject, value: EventValue? = nil, extras: [String: Any]? = nil ) { TelemetryWrapper.recordEvent(category: category, method: method, object: object, value: value, extras: extras) } public static func recordEvent(category: EventCategory, method: EventMethod, object: EventObject, value: EventValue? = nil, extras: [String: Any]? = nil) { Telemetry.default.recordEvent(category: category.rawValue, method: method.rawValue, object: object.rawValue, value: value?.rawValue ?? "", extras: extras) gleanRecordEvent(category: category, method: method, object: object, value: value, extras: extras) } static func gleanRecordEvent(category: EventCategory, method: EventMethod, object: EventObject, value: EventValue? = nil, extras: [String: Any]? = nil) { switch (category, method, object, value, extras) { // MARK: Bookmarks case (.action, .view, .bookmarksPanel, let from?, _): GleanMetrics.Bookmarks.viewList[from.rawValue].add() case (.action, .add, .bookmark, let from?, _): GleanMetrics.Bookmarks.add[from.rawValue].add() case (.action, .delete, .bookmark, let from?, _): GleanMetrics.Bookmarks.delete[from.rawValue].add() case (.action, .open, .bookmark, let from?, _): GleanMetrics.Bookmarks.open[from.rawValue].add() case (.action, .change, .bookmark, let from?, _): GleanMetrics.Bookmarks.edit[from.rawValue].add() // MARK: Reader Mode case (.action, .tap, .readerModeOpenButton, _, _): GleanMetrics.ReaderMode.open.add() case (.action, .tap, .readerModeCloseButton, _, _): GleanMetrics.ReaderMode.close.add() // MARK: Reading List case (.action, .add, .readingListItem, let from?, _): GleanMetrics.ReadingList.add[from.rawValue].add() case (.action, .delete, .readingListItem, let from?, _): GleanMetrics.ReadingList.delete[from.rawValue].add() case (.action, .open, .readingListItem, _, _): GleanMetrics.ReadingList.open.add() // MARK: Top Site case (.action, .tap, .topSiteTile, _, let extras): if let homePageOrigin = extras?[EventExtraKey.fxHomepageOrigin.rawValue] as? String { GleanMetrics.TopSites.pressedTileOrigin[homePageOrigin].add() } if let position = extras?[EventExtraKey.topSitePosition.rawValue] as? String, let tileType = extras?[EventExtraKey.topSiteTileType.rawValue] as? String { GleanMetrics.TopSites.tilePressed.record(GleanMetrics.TopSites.TilePressedExtra(position: position, tileType: tileType)) } else { recordUninstrumentedMetrics(category: category, method: method, object: object, value: value, extras: extras) } case (.action, .view, .topSiteContextualMenu, _, let extras): if let type = extras?[EventExtraKey.contextualMenuType.rawValue] as? String { GleanMetrics.TopSites.contextualMenu.record(GleanMetrics.TopSites.ContextualMenuExtra(type: type)) } else { recordUninstrumentedMetrics(category: category, method: method, object: object, value: value, extras: extras) } // MARK: Preferences case (.action, .change, .setting, _, let extras): if let preference = extras?[EventExtraKey.preference.rawValue] as? String, let to = ((extras?[EventExtraKey.preferenceChanged.rawValue]) ?? "undefined") as? String { GleanMetrics.Preferences.changed.record(GleanMetrics.Preferences.ChangedExtra(changedTo: to, preference: preference)) } else if let preference = extras?[EventExtraKey.preference.rawValue] as? String, let to = ((extras?[EventExtraKey.preferenceChanged.rawValue]) ?? "undefined") as? Bool { GleanMetrics.Preferences.changed.record(GleanMetrics.Preferences.ChangedExtra(changedTo: to.description, preference: preference)) } else { recordUninstrumentedMetrics(category: category, method: method, object: object, value: value, extras: extras) } case (.action, .tap, .privateBrowsingButton, _, let extras): if let isPrivate = extras?[EventExtraKey.isPrivate.rawValue] as? String { let isPrivateExtra = GleanMetrics.Preferences.PrivateBrowsingButtonTappedExtra(isPrivate: isPrivate) GleanMetrics.Preferences.privateBrowsingButtonTapped.record(isPrivateExtra) } else { recordUninstrumentedMetrics( category: category, method: method, object: object, value: value, extras: extras) } // MARK: - QR Codes case (.action, .scan, .qrCodeText, _, _), (.action, .scan, .qrCodeURL, _, _): GleanMetrics.QrCode.scanned.add() // MARK: Tabs case (.action, .add, .tab, let privateOrNormal?, _): GleanMetrics.Tabs.open[privateOrNormal.rawValue].add() case (.action, .close, .tab, let privateOrNormal?, _): GleanMetrics.Tabs.close[privateOrNormal.rawValue].add() case (.action, .closeAll, .tab, let privateOrNormal?, _): GleanMetrics.Tabs.closeAll[privateOrNormal.rawValue].add() case (.action, .tap, .addNewTabButton, _, _): GleanMetrics.Tabs.newTabPressed.add() case (.action, .tap, .tab, _, _): GleanMetrics.Tabs.clickTab.record() case (.action, .open, .tabTray, _, _): GleanMetrics.Tabs.openTabTray.record() case (.action, .close, .tabTray, _, _): GleanMetrics.Tabs.closeTabTray.record() case (.action, .press, .tabToolbar, .tabView, _): GleanMetrics.Tabs.pressTabToolbar.record() case (.action, .press, .tab, _, _): GleanMetrics.Tabs.pressTopTab.record() case(.action, .pull, .reload, _, _): GleanMetrics.Tabs.pullToRefresh.add() case(.action, .navigate, .tab, _, _): GleanMetrics.Tabs.normalAndPrivateUriCount.add() case(.action, .tap, .navigateTabHistoryBack, _, _), (.action, .press, .navigateTabHistoryBack, _, _): GleanMetrics.Tabs.navigateTabHistoryBack.add() case(.action, .tap, .navigateTabHistoryForward, _, _), (.action, .press, .navigateTabHistoryForward, _, _): GleanMetrics.Tabs.navigateTabHistoryForward.add() case(.action, .swipe, .navigateTabHistoryBackSwipe, _, _): GleanMetrics.Tabs.navigateTabBackSwipe.add() case(.action, .tap, .reloadFromUrlBar, _, _): GleanMetrics.Tabs.reloadFromUrlBar.add() case(.information, .background, .tabNormalQuantity, _, let extras): if let quantity = extras?[EventExtraKey.tabsQuantity.rawValue] as? Int64 { GleanMetrics.Tabs.normalTabsQuantity.set(quantity) } else { recordUninstrumentedMetrics(category: category, method: method, object: object, value: value, extras: extras) } case(.information, .background, .tabPrivateQuantity, _, let extras): if let quantity = extras?[EventExtraKey.tabsQuantity.rawValue] as? Int64 { GleanMetrics.Tabs.privateTabsQuantity.set(quantity) } else { recordUninstrumentedMetrics(category: category, method: method, object: object, value: value, extras: extras) } // MARK: Settings Menu case (.action, .open, .settingsMenuSetAsDefaultBrowser, _, _): GleanMetrics.SettingsMenu.setAsDefaultBrowserPressed.add() case(.action, .tap, .settingsMenuShowTour, _, _): GleanMetrics.SettingsMenu.showTourPressed.record() // MARK: Start Search Button case (.action, .tap, .startSearchButton, _, _): GleanMetrics.Search.startSearchPressed.add() // MARK: Awesomebar Search Results case (.action, .tap, .awesomebarResults, _, let extras): if let tapValue = extras?[EventExtraKey.awesomebarSearchTapType.rawValue] as? String { let awesomebarExtraValue = GleanMetrics.Awesomebar.SearchResultTapExtra(type: tapValue) GleanMetrics.Awesomebar.searchResultTap.record(awesomebarExtraValue) } else { recordUninstrumentedMetrics( category: category, method: method, object: object, value: value, extras: extras) } // MARK: Default Browser case (.action, .tap, .dismissDefaultBrowserCard, _, _): GleanMetrics.DefaultBrowserCard.dismissPressed.add() case (.action, .tap, .goToSettingsDefaultBrowserCard, _, _): GleanMetrics.DefaultBrowserCard.goToSettingsPressed.add() case (.action, .open, .asDefaultBrowser, _, _): GleanMetrics.App.openedAsDefaultBrowser.add() case (.action, .tap, .dismissDefaultBrowserOnboarding, _, _): GleanMetrics.DefaultBrowserOnboarding.dismissPressed.add() case (.action, .tap, .goToSettingsDefaultBrowserOnboarding, _, _): GleanMetrics.DefaultBrowserOnboarding.goToSettingsPressed.add() case (.information, .view, .homeTabBannerEvergreen, _, _): GleanMetrics.DefaultBrowserCard.evergreenImpression.record() // MARK: Downloads case(.action, .tap, .downloadNowButton, _, _): GleanMetrics.Downloads.downloadNowButtonTapped.record() case(.action, .tap, .download, .downloadsPanel, _): GleanMetrics.Downloads.downloadsPanelRowTapped.record() case(.action, .view, .downloadsPanel, .downloadCompleteToast, _): GleanMetrics.Downloads.viewDownloadCompleteToast.record() // MARK: Key Commands case(.action, .press, .keyCommand, _, let extras): if let action = extras?[EventExtraKey.action.rawValue] as? String { let actionExtra = GleanMetrics.KeyCommands.PressKeyCommandActionExtra(action: action) GleanMetrics.KeyCommands.pressKeyCommandAction.record(actionExtra) } else { recordUninstrumentedMetrics(category: category, method: method, object: object, value: value, extras: extras) } // MARK: Onboarding case (.action, .view, .onboardingCardView, _, let extras): if let type = extras?[TelemetryWrapper.EventExtraKey.cardType.rawValue] as? String { let cardTypeExtra = GleanMetrics.Onboarding.CardViewExtra(cardType: type) GleanMetrics.Onboarding.cardView.record(cardTypeExtra) } else { recordUninstrumentedMetrics(category: category, method: method, object: object, value: value, extras: extras) } case (.action, .tap, .onboardingPrimaryButton, _, let extras): if let type = extras?[TelemetryWrapper.EventExtraKey.cardType.rawValue] as? String { let cardTypeExtra = GleanMetrics.Onboarding.PrimaryButtonTapExtra(cardType: type) GleanMetrics.Onboarding.primaryButtonTap.record(cardTypeExtra) } else { recordUninstrumentedMetrics(category: category, method: method, object: object, value: value, extras: extras) } case (.action, .tap, .onboardingSecondaryButton, _, let extras): if let type = extras?[TelemetryWrapper.EventExtraKey.cardType.rawValue] as? String { let cardTypeExtra = GleanMetrics.Onboarding.SecondaryButtonTapExtra(cardType: type) GleanMetrics.Onboarding.secondaryButtonTap.record(cardTypeExtra) } else { recordUninstrumentedMetrics(category: category, method: method, object: object, value: value, extras: extras) } case (.action, .tap, .onboardingSelectWallpaper, .wallpaperSelected, let extras): if let name = extras?[EventExtraKey.wallpaperName.rawValue] as? String, let type = extras?[EventExtraKey.wallpaperType.rawValue] as? String { let wallpaperExtra = GleanMetrics.Onboarding.WallpaperSelectedExtra(wallpaperName: name, wallpaperType: type) GleanMetrics.Onboarding.wallpaperSelected.record(wallpaperExtra) } else { recordUninstrumentedMetrics(category: category, method: method, object: object, value: value, extras: extras) } case (.action, .tap, .onboardingClose, _, let extras): if let type = extras?[TelemetryWrapper.EventExtraKey.cardType.rawValue] as? String { GleanMetrics.Onboarding.closeTap.record(GleanMetrics.Onboarding.CloseTapExtra(cardType: type)) } else { recordUninstrumentedMetrics(category: category, method: method, object: object, value: value, extras: extras) } case (.action, .tap, .onboardingWallpaperSelector, .wallpaperSelected, let extras): if let name = extras?[EventExtraKey.wallpaperName.rawValue] as? String, let type = extras?[EventExtraKey.wallpaperType.rawValue] as? String { let wallpaperExtra = GleanMetrics.Onboarding.WallpaperSelectorSelectedExtra(wallpaperName: name, wallpaperType: type) GleanMetrics.Onboarding.wallpaperSelectorSelected.record(wallpaperExtra) } else { recordUninstrumentedMetrics(category: category, method: method, object: object, value: value, extras: extras) } case (.action, .view, .onboardingWallpaperSelector, _, _): GleanMetrics.Onboarding.wallpaperSelectorView.record() case (.action, .close, .onboardingWallpaperSelector, _, _): GleanMetrics.Onboarding.wallpaperSelectorClose.record() // MARK: Upgrade onboarding case (.action, .view, .upgradeOnboardingCardView, _, let extras): if let type = extras?[TelemetryWrapper.EventExtraKey.cardType.rawValue] as? String { let cardTypeExtra = GleanMetrics.Upgrade.CardViewExtra(cardType: type) GleanMetrics.Upgrade.cardView.record(cardTypeExtra) } else { recordUninstrumentedMetrics(category: category, method: method, object: object, value: value, extras: extras) } case (.action, .tap, .upgradeOnboardingPrimaryButton, _, let extras): if let type = extras?[TelemetryWrapper.EventExtraKey.cardType.rawValue] as? String { let cardTypeExtra = GleanMetrics.Upgrade.PrimaryButtonTapExtra(cardType: type) GleanMetrics.Upgrade.primaryButtonTap.record(cardTypeExtra) } else { recordUninstrumentedMetrics(category: category, method: method, object: object, value: value, extras: extras) } case (.action, .tap, .upgradeOnboardingSecondaryButton, _, let extras): if let type = extras?[TelemetryWrapper.EventExtraKey.cardType.rawValue] as? String { let cardTypeExtra = GleanMetrics.Upgrade.SecondaryButtonTapExtra(cardType: type) GleanMetrics.Upgrade.secondaryButtonTap.record(cardTypeExtra) } else { recordUninstrumentedMetrics(category: category, method: method, object: object, value: value, extras: extras) } case (.action, .tap, .upgradeOnboardingClose, _, let extras): if let type = extras?[TelemetryWrapper.EventExtraKey.cardType.rawValue] as? String { GleanMetrics.Upgrade.closeTap.record(GleanMetrics.Upgrade.CloseTapExtra(cardType: type)) } else { recordUninstrumentedMetrics(category: category, method: method, object: object, value: value, extras: extras) } // MARK: Widget case (.action, .open, .mediumTabsOpenUrl, _, _): GleanMetrics.Widget.mTabsOpenUrl.add() case (.action, .open, .largeTabsOpenUrl, _, _): GleanMetrics.Widget.lTabsOpenUrl.add() case (.action, .open, .smallQuickActionSearch, _, _): GleanMetrics.Widget.sQuickActionSearch.add() case (.action, .open, .mediumQuickActionSearch, _, _): GleanMetrics.Widget.mQuickActionSearch.add() case (.action, .open, .mediumQuickActionPrivateSearch, _, _): GleanMetrics.Widget.mQuickActionPrivateSearch.add() case (.action, .open, .mediumQuickActionCopiedLink, _, _): GleanMetrics.Widget.mQuickActionCopiedLink.add() case (.action, .open, .mediumQuickActionClosePrivate, _, _): GleanMetrics.Widget.mQuickActionClosePrivate.add() case (.action, .open, .mediumTopSitesWidget, _, _): GleanMetrics.Widget.mTopSitesWidget.add() // MARK: Pocket case (.action, .tap, .pocketStory, _, let extras): if let homePageOrigin = extras?[EventExtraKey.fxHomepageOrigin.rawValue] as? String { GleanMetrics.Pocket.openStoryOrigin[homePageOrigin].add() } if let position = extras?[EventExtraKey.pocketTilePosition.rawValue] as? String { GleanMetrics.Pocket.openStoryPosition["position-"+position].add() } else { recordUninstrumentedMetrics(category: category, method: method, object: object, value: value, extras: extras) } case (.action, .view, .pocketSectionImpression, _, _): GleanMetrics.Pocket.sectionImpressions.add() // MARK: Library Panel case (.action, .tap, .libraryPanel, let type?, _): GleanMetrics.Library.panelPressed[type.rawValue].add() // History Panel related case (.action, .navigate, .navigateToGroupHistory, _, _): GleanMetrics.History.groupList.add() case (.action, .tap, .selectedHistoryItem, let type?, _): GleanMetrics.History.selectedItem[type.rawValue].add() case (.action, .tap, .searchHistory, _, _): GleanMetrics.History.searchTap.record() case (.action, .tap, .deleteHistory, _, _): GleanMetrics.History.deleteTap.record() // MARK: Sync case (.action, .open, .syncTab, _, _): GleanMetrics.Sync.openTab.add() case (.action, .tap, .syncSignIn, _, _): GleanMetrics.Sync.signInSyncPressed.add() case (.action, .tap, .syncCreateAccount, _, _): GleanMetrics.Sync.createAccountPressed.add() case (.firefoxAccount, .view, .fxaRegistrationWebpage, _, _): GleanMetrics.Sync.registrationView.record() case (.firefoxAccount, .view, .fxaRegistrationCompletedWebpage, _, _): GleanMetrics.Sync.registrationCompletedView.record() case (.firefoxAccount, .view, .fxaLoginWebpage, _, _): GleanMetrics.Sync.loginView.record() case (.firefoxAccount, .view, .fxaLoginCompleteWebpage, _, _): GleanMetrics.Sync.loginCompletedView.record() case (.firefoxAccount, .view, .fxaConfirmSignUpCode, _, _): GleanMetrics.Sync.registrationCodeView.record() case (.firefoxAccount, .view, .fxaConfirmSignInToken, _, _): GleanMetrics.Sync.loginTokenView.record() // MARK: App cycle case(.action, .foreground, .app, _, _): GleanMetrics.AppCycle.foreground.record() case(.action, .background, .app, _, _): GleanMetrics.AppCycle.background.record() // MARK: Accessibility case(.action, .voiceOver, .app, _, let extras): if let isRunning = extras?[EventExtraKey.isVoiceOverRunning.rawValue] as? String { let isRunningExtra = GleanMetrics.Accessibility.VoiceOverExtra(isRunning: isRunning) GleanMetrics.Accessibility.voiceOver.record(isRunningExtra) } else { recordUninstrumentedMetrics( category: category, method: method, object: object, value: value, extras: extras) } case(.action, .switchControl, .app, _, let extras): if let isRunning = extras?[EventExtraKey.isSwitchControlRunning.rawValue] as? String { let isRunningExtra = GleanMetrics.Accessibility.SwitchControlExtra(isRunning: isRunning) GleanMetrics.Accessibility.switchControl.record(isRunningExtra) } else { recordUninstrumentedMetrics( category: category, method: method, object: object, value: value, extras: extras) } case(.action, .reduceTransparency, .app, _, let extras): if let isEnabled = extras?[EventExtraKey.isReduceTransparencyEnabled.rawValue] as? String { let isEnabledExtra = GleanMetrics.Accessibility.ReduceTransparencyExtra(isEnabled: isEnabled) GleanMetrics.Accessibility.reduceTransparency.record(isEnabledExtra) } else { recordUninstrumentedMetrics( category: category, method: method, object: object, value: value, extras: extras) } case(.action, .reduceMotion, .app, _, let extras): if let isEnabled = extras?[EventExtraKey.isReduceMotionEnabled.rawValue] as? String { let isEnabledExtra = GleanMetrics.Accessibility.ReduceMotionExtra(isEnabled: isEnabled) GleanMetrics.Accessibility.reduceMotion.record(isEnabledExtra) } else { recordUninstrumentedMetrics( category: category, method: method, object: object, value: value, extras: extras) } case(.action, .invertColors, .app, _, let extras): if let isEnabled = extras?[EventExtraKey.isInvertColorsEnabled.rawValue] as? String { let isEnabledExtra = GleanMetrics.Accessibility.InvertColorsExtra(isEnabled: isEnabled) GleanMetrics.Accessibility.invertColors.record(isEnabledExtra) } else { recordUninstrumentedMetrics( category: category, method: method, object: object, value: value, extras: extras) } case(.action, .dynamicTextSize, .app, _, let extras): if let isAccessibilitySizeEnabled = extras?[EventExtraKey.isAccessibilitySizeEnabled.rawValue] as? String, let preferredSize = extras?[EventExtraKey.preferredContentSizeCategory.rawValue] as? String { let dynamicTextExtra = GleanMetrics.Accessibility.DynamicTextExtra( isAccessibilitySizeEnabled: isAccessibilitySizeEnabled, preferredSize: preferredSize) GleanMetrics.Accessibility.dynamicText.record(dynamicTextExtra) } else { recordUninstrumentedMetrics( category: category, method: method, object: object, value: value, extras: extras) } // MARK: App menu case (.action, .tap, .logins, _, _): GleanMetrics.AppMenu.logins.add() case (.action, .tap, .signIntoSync, _, _): GleanMetrics.AppMenu.signIntoSync.add() case (.action, .tap, .home, _, _): GleanMetrics.AppMenu.home.add() case (.action, .tap, .library, _, _): GleanMetrics.AppMenu.library.add() case (.action, .tap, .blockImagesEnabled, _, _): GleanMetrics.AppMenu.blockImagesEnabled.add() case (.action, .tap, .blockImagesDisabled, _, _): GleanMetrics.AppMenu.blockImagesDisabled.add() case (.action, .tap, .nightModeEnabled, _, _): GleanMetrics.AppMenu.nightModeEnabled.add() case (.action, .tap, .nightModeDisabled, _, _): GleanMetrics.AppMenu.nightModeDisabled.add() case (.action, .open, .whatsNew, _, _): GleanMetrics.AppMenu.whatsNew.add() case (.action, .open, .settings, _, _): GleanMetrics.AppMenu.settings.add() // MARK: Page Menu case (.action, .tap, .sharePageWith, _, _): GleanMetrics.PageActionMenu.sharePageWith.add() case (.action, .tap, .sendToDevice, _, _): GleanMetrics.PageActionMenu.sendToDevice.add() case (.action, .tap, .copyAddress, _, _): GleanMetrics.PageActionMenu.copyAddress.add() case (.action, .tap, .reportSiteIssue, _, _): GleanMetrics.PageActionMenu.reportSiteIssue.add() case (.action, .tap, .findInPage, _, _): GleanMetrics.PageActionMenu.findInPage.add() case (.action, .tap, .pinToTopSites, _, _): GleanMetrics.PageActionMenu.pinToTopSites.add() case (.action, .tap, .removePinnedSite, _, _): GleanMetrics.PageActionMenu.removePinnedSite.add() case (.action, .tap, .requestDesktopSite, _, _): GleanMetrics.PageActionMenu.requestDesktopSite.add() case (.action, .tap, .requestMobileSite, _, _): GleanMetrics.PageActionMenu.requestMobileSite.add() case (.action, .tap, .viewDownloadsPanel, _, _): GleanMetrics.PageActionMenu.viewDownloadsPanel.add() case (.action, .tap, .viewHistoryPanel, _, _): GleanMetrics.PageActionMenu.viewHistoryPanel.add() case (.action, .tap, .createNewTab, _, _): GleanMetrics.PageActionMenu.createNewTab.add() // MARK: Inactive Tab Tray case (.action, .tap, .inactiveTabTray, .openInactiveTab, _): GleanMetrics.InactiveTabsTray.openInactiveTab.add() case (.action, .tap, .inactiveTabTray, .inactiveTabExpand, _): let expandedExtras = GleanMetrics.InactiveTabsTray.ToggleInactiveTabTrayExtra(toggleType: EventExtraKey.inactiveTabsExpanded.rawValue) GleanMetrics.InactiveTabsTray.toggleInactiveTabTray.record(expandedExtras) case (.action, .tap, .inactiveTabTray, .inactiveTabCollapse, _): let collapsedExtras = GleanMetrics.InactiveTabsTray.ToggleInactiveTabTrayExtra(toggleType: EventExtraKey.inactiveTabsCollapsed.rawValue) GleanMetrics.InactiveTabsTray.toggleInactiveTabTray.record(collapsedExtras) case (.action, .tap, .inactiveTabTray, .inactiveTabSwipeClose, _): GleanMetrics.InactiveTabsTray.inactiveTabSwipeClose.add() case (.action, .tap, .inactiveTabTray, .inactiveTabCloseAllButton, _): GleanMetrics.InactiveTabsTray.inactiveTabsCloseAllBtn.add() case (.action, .tap, .inactiveTabTray, .inactiveTabShown, _): GleanMetrics.InactiveTabsTray.inactiveTabShown.add() // MARK: Tab Groups case (.action, .view, .tabTray, .tabGroupWithExtras, let extras): let groupedTabExtras = GleanMetrics.Tabs.GroupedTabExtra.init( averageTabsInAllGroups: extras?["\(EventExtraKey.averageTabsInAllGroups)"] as? Int32, groupsTwoTabsOnly: extras?["\(EventExtraKey.groupsWithTwoTabsOnly)"] as? Int32, groupsWithMoreThanTwoTab: extras?["\(EventExtraKey.groupsWithTwoMoreTab)"] as? Int32, totalNumOfGroups: extras?["\(EventExtraKey.totalNumberOfGroups)"] as? Int32, totalTabsInAllGroups: extras?["\(EventExtraKey.totalTabsInAllGroups)"] as? Int32) GleanMetrics.Tabs.groupedTab.record(groupedTabExtras) case (.action, .tap, .groupedTab, .closeGroupedTab, _): GleanMetrics.Tabs.groupedTabClosed.add() case (.action, .tap, .groupedTabPerformSearch, _, _): GleanMetrics.Tabs.groupedTabSearch.add() // MARK: Firefox Homepage case (.action, .view, .firefoxHomepage, .fxHomepageOrigin, let extras): if let homePageOrigin = extras?[EventExtraKey.fxHomepageOrigin.rawValue] as? String { GleanMetrics.FirefoxHomePage.firefoxHomepageOrigin[homePageOrigin].add() } case (.action, .open, .firefoxHomepage, .openHomeFromAwesomebar, _): GleanMetrics.FirefoxHomePage.openFromAwesomebar.add() case (.action, .open, .firefoxHomepage, .openHomeFromPhotonMenuButton, _): GleanMetrics.FirefoxHomePage.openFromMenuHomeButton.add() case (.action, .view, .firefoxHomepage, .recentlySavedBookmarkItemView, let extras): if let bookmarksCount = extras?[EventObject.recentlySavedBookmarkImpressions.rawValue] as? String { GleanMetrics.FirefoxHomePage.recentlySavedBookmarkView.record(GleanMetrics.FirefoxHomePage.RecentlySavedBookmarkViewExtra(bookmarkCount: bookmarksCount)) } case (.action, .view, .firefoxHomepage, .recentlySavedReadingListView, let extras): if let readingListItemsCount = extras?[EventObject.recentlySavedReadingItemImpressions.rawValue] as? String { GleanMetrics.FirefoxHomePage.readingListView.record(GleanMetrics.FirefoxHomePage.ReadingListViewExtra(readingListCount: readingListItemsCount)) } case (.action, .tap, .firefoxHomepage, .recentlySavedSectionShowAll, let extras): GleanMetrics.FirefoxHomePage.recentlySavedShowAll.add() if let homePageOrigin = extras?[EventExtraKey.fxHomepageOrigin.rawValue] as? String { GleanMetrics.FirefoxHomePage.recentlySavedShowAllOrigin[homePageOrigin].add() } case (.action, .tap, .firefoxHomepage, .recentlySavedBookmarkItemAction, let extras): GleanMetrics.FirefoxHomePage.recentlySavedBookmarkItem.add() if let homePageOrigin = extras?[EventExtraKey.fxHomepageOrigin.rawValue] as? String { GleanMetrics.FirefoxHomePage.recentlySavedBookmarkOrigin[homePageOrigin].add() } case (.action, .tap, .firefoxHomepage, .recentlySavedReadingListAction, let extras): GleanMetrics.FirefoxHomePage.recentlySavedReadingItem.add() if let homePageOrigin = extras?[EventExtraKey.fxHomepageOrigin.rawValue] as? String { GleanMetrics.FirefoxHomePage.recentlySavedReadOrigin[homePageOrigin].add() } case (.action, .tap, .firefoxHomepage, .jumpBackInSectionShowAll, let extras): GleanMetrics.FirefoxHomePage.jumpBackInShowAll.add() if let homePageOrigin = extras?[EventExtraKey.fxHomepageOrigin.rawValue] as? String { GleanMetrics.FirefoxHomePage.jumpBackInShowAllOrigin[homePageOrigin].add() } case (.action, .view, .jumpBackInTileImpressions, _, _): GleanMetrics.FirefoxHomePage.jumpBackInTileView.add() case (.action, .tap, .firefoxHomepage, .jumpBackInSectionTabOpened, let extras): GleanMetrics.FirefoxHomePage.jumpBackInTabOpened.add() if let homePageOrigin = extras?[EventExtraKey.fxHomepageOrigin.rawValue] as? String { GleanMetrics.FirefoxHomePage.jumpBackInTabOpenedOrigin[homePageOrigin].add() } case (.action, .tap, .firefoxHomepage, .jumpBackInSectionGroupOpened, let extras): GleanMetrics.FirefoxHomePage.jumpBackInGroupOpened.add() if let homePageOrigin = extras?[EventExtraKey.fxHomepageOrigin.rawValue] as? String { GleanMetrics.FirefoxHomePage.jumpBackInGroupOpenOrigin[homePageOrigin].add() } case (.action, .tap, .firefoxHomepage, .jumpBackInSectionSyncedTabShowAll, let extras): GleanMetrics.FirefoxHomePage.syncedTabShowAll.add() if let homePageOrigin = extras?[EventExtraKey.fxHomepageOrigin.rawValue] as? String { GleanMetrics.FirefoxHomePage.syncedTabShowAllOrigin[homePageOrigin].add() } case (.action, .tap, .firefoxHomepage, .jumpBackInSectionSyncedTabOpened, let extras): GleanMetrics.FirefoxHomePage.syncedTabOpened.add() if let homePageOrigin = extras?[EventExtraKey.fxHomepageOrigin.rawValue] as? String { GleanMetrics.FirefoxHomePage.syncedTabOpenedOrigin[homePageOrigin].add() } case (.action, .view, .syncedTabTileImpressions, _, _): GleanMetrics.FirefoxHomePage.syncedTabTileView.add() case (.action, .tap, .firefoxHomepage, .customizeHomepageButton, _): GleanMetrics.FirefoxHomePage.customizeHomepageButton.add() // MARK: - History Highlights case (.action, .tap, .firefoxHomepage, .historyHighlightsShowAll, _): GleanMetrics.FirefoxHomePage.customizeHomepageButton.add() case (.action, .tap, .firefoxHomepage, .historyHighlightsItemOpened, _): GleanMetrics.FirefoxHomePage.historyHighlightsItemOpened.record() case (.action, .tap, .firefoxHomepage, .historyHighlightsGroupOpen, _): GleanMetrics.FirefoxHomePage.historyHighlightsGroupOpen.record() case (.action, .view, .historyImpressions, _, _): GleanMetrics.FirefoxHomePage.customizeHomepageButton.add() case (.action, .view, .historyHighlightContextualMenu, _, let extras): if let type = extras?[EventExtraKey.contextualMenuType.rawValue] as? String { let contextExtra = GleanMetrics.FirefoxHomePage.HistoryHighlightsContextExtra(type: type) GleanMetrics.FirefoxHomePage.historyHighlightsContext.record(contextExtra) } else { recordUninstrumentedMetrics(category: category, method: method, object: object, value: value, extras: extras) } // MARK: - Wallpaper related case (.action, .tap, .wallpaperSettings, .wallpaperSelected, let extras): if let name = extras?[EventExtraKey.wallpaperName.rawValue] as? String, let type = extras?[EventExtraKey.wallpaperType.rawValue] as? String { GleanMetrics.WallpaperAnalytics.wallpaperSelected.record( GleanMetrics.WallpaperAnalytics.WallpaperSelectedExtra( wallpaperName: name, wallpaperType: type ) ) } else { recordUninstrumentedMetrics(category: category, method: method, object: object, value: value, extras: extras) } // MARK: - Contextual Hints case (.action, .tap, .contextualHint, .dismissCFRFromButton, let extras): if let hintType = extras?[EventExtraKey.cfrType.rawValue] as? String { GleanMetrics.CfrAnalytics.dismissCfrFromButton.record( GleanMetrics.CfrAnalytics.DismissCfrFromButtonExtra(hintType: hintType)) } else { recordUninstrumentedMetrics(category: category, method: method, object: object, value: value, extras: extras) } case (.action, .tap, .contextualHint, .dismissCFRFromOutsideTap, let extras): if let hintType = extras?[EventExtraKey.cfrType.rawValue] as? String { GleanMetrics.CfrAnalytics.dismissCfrFromOutsideTap.record( GleanMetrics.CfrAnalytics.DismissCfrFromOutsideTapExtra(hintType: hintType)) } else { recordUninstrumentedMetrics(category: category, method: method, object: object, value: value, extras: extras) } case (.action, .tap, .contextualHint, .pressCFRActionButton, let extras): if let hintType = extras?[EventExtraKey.cfrType.rawValue] as? String { GleanMetrics.CfrAnalytics.pressCfrActionButton.record( GleanMetrics.CfrAnalytics.PressCfrActionButtonExtra(hintType: hintType)) } else { recordUninstrumentedMetrics(category: category, method: method, object: object, value: value, extras: extras) } // MARK: - Awesomebar case (.information, .view, .awesomebarLocation, _, let extras): if let location = extras?[EventExtraKey.preference.rawValue] as? String { let locationExtra = GleanMetrics.Awesomebar.LocationExtra(location: location) GleanMetrics.Awesomebar.location.record(locationExtra) } else { recordUninstrumentedMetrics( category: category, method: method, object: object, value: value, extras: extras) } case (.action, .drag, .locationBar, _, _): GleanMetrics.Awesomebar.dragLocationBar.record() // MARK: - GleanPlumb Messaging case (.information, .view, .homeTabBanner, .messageImpression, let extras): if let messageId = extras?[EventExtraKey.messageKey.rawValue] as? String { GleanMetrics.Messaging.shown.record( GleanMetrics.Messaging.ShownExtra(messageKey: messageId) ) } case(.action, .tap, .homeTabBanner, .messageDismissed, let extras): if let messageId = extras?[EventExtraKey.messageKey.rawValue] as? String { GleanMetrics.Messaging.dismissed.record( GleanMetrics.Messaging.DismissedExtra(messageKey: messageId) ) } case(.action, .tap, .homeTabBanner, .messageInteracted, let extras): if let messageId = extras?[EventExtraKey.messageKey.rawValue] as? String, let actionUUID = extras?[EventExtraKey.actionUUID.rawValue] as? String { GleanMetrics.Messaging.clicked.record( GleanMetrics.Messaging.ClickedExtra(actionUuid: actionUUID, messageKey: messageId) ) } else if let messageId = extras?[EventExtraKey.messageKey.rawValue] as? String { GleanMetrics.Messaging.clicked.record( GleanMetrics.Messaging.ClickedExtra(messageKey: messageId) ) } case(.information, .view, .homeTabBanner, .messageExpired, let extras): if let messageId = extras?[EventExtraKey.messageKey.rawValue] as? String { GleanMetrics.Messaging.expired.record( GleanMetrics.Messaging.ExpiredExtra(messageKey: messageId) ) } case(.information, .application, .homeTabBanner, .messageMalformed, let extras): if let messageId = extras?[EventExtraKey.messageKey.rawValue] as? String { GleanMetrics.Messaging.malformed.record( GleanMetrics.Messaging.MalformedExtra(messageKey: messageId) ) } default: recordUninstrumentedMetrics(category: category, method: method, object: object, value: value, extras: extras) } } private static func recordUninstrumentedMetrics( category: EventCategory, method: EventMethod, object: EventObject, value: EventValue?, extras: [String: Any]? ) { let msg = "Uninstrumented metric recorded: \(category), \(method), \(object), \(String(describing: value)), \(String(describing: extras))" SentryIntegration.shared.send(message: msg, severity: .info) } } // MARK: - Firefox Home Page extension TelemetryWrapper { /// Bundle the extras dictionary for the home page origin static func getOriginExtras(isZeroSearch: Bool) -> [String: String] { let origin = isZeroSearch ? TelemetryWrapper.EventValue.fxHomepageOriginZeroSearch : TelemetryWrapper.EventValue.fxHomepageOriginOther return [TelemetryWrapper.EventExtraKey.fxHomepageOrigin.rawValue: origin.rawValue] } }
mpl-2.0
0dd39501d89e4c081398b540227f6c7e
53.345038
170
0.653051
4.928487
false
false
false
false
TheDarkCode/Example-Swift-Apps
Exercises and Basic Principles/neighborhood-app-exercise/neighborhood-app-exercise/AddPostVC.swift
1
2383
// // AddPostVC.swift // neighborhood-app-exercise // // Created by Mark Hamilton on 2/29/16. // Copyright © 2016 dryverless. All rights reserved. // import UIKit class AddPostVC: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate { @IBOutlet weak var newPostImg: UIImageView! @IBOutlet weak var postTitleField: UITextField! @IBOutlet weak var postDescriptionField: UITextField! var imagePicker: UIImagePickerController! override func viewDidLoad() { super.viewDidLoad() newPostImg.layer.cornerRadius = newPostImg.frame.size.width / 2 newPostImg.clipsToBounds = true imagePicker = UIImagePickerController() imagePicker.delegate = self } @IBAction func cancelButtonPressed(sender: AnyObject) { // Return to past screen dismissViewControllerAnimated(true, completion: nil) } @IBAction func addPicButtonPressed(sender: UIButton!) { // Remove Button Label "+ Add Pic" sender.setTitle("", forState: .Normal) // Present Image Picker View presentViewController(imagePicker, animated: true, completion: nil) } @IBAction func submitPostButtonPressed(sender: AnyObject) { // Validation, check for image and all text fields being populated if let postTitle: String = postTitleField.text, let postDescription: String = postDescriptionField.text, let postImage = newPostImg.image { // Save Image let imagePath = DataService.instance.saveImageAndCreatePath(postImage) // Create Post let newPost = Post(imagePath: imagePath, title: postTitle, postDetails: postDescription) // Add to Data Service DataService.instance.addPost(newPost) dismissViewControllerAnimated(true, completion: nil) } } func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) { // Dismiss Image Picker View imagePicker.dismissViewControllerAnimated(true, completion: nil) // Set chosen image to view newPostImg.image = image } }
mit
09fbb7fea467890e913e5e89226bc8a4
29.935065
147
0.638959
5.64455
false
false
false
false
coolshubh4/iOS-Demos
TextFieldChallenge/TextFieldChallenge/CurrencyDelegate.swift
1
2042
// // CurrencyDelegate.swift // TextFieldChallenge // // Created by Shubham Tripathi on 19/07/15. // Copyright (c) 2015 Shubham Tripathi. All rights reserved. // import Foundation import UIKit class CurrencyDelegate: NSObject, UITextFieldDelegate { func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool { var oldText = textField.text as NSString; println("oldText: \(oldText)"); var newText = oldText.stringByReplacingCharactersInRange(range, withString: string); println("newText: \(newText)"); var newTextString = String(newText); println("newTextString: \(newTextString)"); let digits = NSCharacterSet.decimalDigitCharacterSet(); println("digits: \(digits)"); var digitText = "" for c in newTextString.unicodeScalars { if digits.longCharacterIsMember(c.value) { digitText.append(c) } } println("digitText: \(digitText)") // Format the new string if let numOfPennies = digitText.toInt() { newText = "$" + self.dollarStringFromInt(numOfPennies) + "." + self.centsStringFromInt(numOfPennies) } else { newText = "$0.00" } textField.text = newText return false } func textFieldDidBeginEditing(textField: UITextField) { if textField.text.isEmpty { textField.text = "$0.00" } } func textFieldShouldReturn(textField: UITextField) -> Bool { textField.resignFirstResponder() return true; } func dollarStringFromInt(value: Int) -> String { return String(value / 100) } func centsStringFromInt(value: Int) -> String { let cents = value % 100 var centsString = String(cents) if cents < 10 { centsString = "0" + centsString } return centsString } }
mit
dc44232c88b199b18234ba23e6303212
29.044118
132
0.598433
4.932367
false
false
false
false
davefoxy/SwiftBomb
Example/SwiftBomb/DataProviders/ObjectResourcePaginator.swift
1
2972
// // ObjectResourcePaginator.swift // GBAPI // // Created by David Fox on 30/04/2016. // Copyright © 2016 David Fox. All rights reserved. // import Foundation import UIKit import SwiftBomb class ObjectResourcePaginator: ResourcePaginator { var searchTerm: String? var pagination: PaginationDefinition var sort: SortDefinition var isLoading = false var hasMore: Bool = true var resourceType = ResourceType.object var objects = [ObjectResource]() init(searchTerm: String? = nil, pagination: PaginationDefinition = PaginationDefinition(offset: 0, limit: 30), sort: SortDefinition = SortDefinition(field: "name", direction: .ascending)) { self.searchTerm = searchTerm self.pagination = pagination self.sort = sort } func loadMore(completion: @escaping (_ cellPresenters: [ResourceItemCellPresenter]?, _ error: SwiftBombRequestError?) -> Void) { if isLoading { return } isLoading = true SwiftBomb.fetchObjects(searchTerm, pagination: pagination, sort: sort) { results, error in self.isLoading = false if error == nil { if let objects = results?.resources { self.objects.append(contentsOf: objects) let cellPresenters = self.cellPresentersForResources(objects) self.pagination = PaginationDefinition(self.pagination.offset + objects.count, self.pagination.limit) self.hasMore = (results?.hasMoreResults)! completion(cellPresenters, nil) } } else { completion(nil, error) } } } func cellPresentersForResources(_ objects: [ObjectResource]) -> [ResourceItemCellPresenter] { var cellPresenters = [ResourceItemCellPresenter]() for object in objects { var subtitle = "" if let deck = object.deck { subtitle = deck } let cellPresenter = ResourceItemCellPresenter(imageURL: object.image?.small, title: object.name, subtitle: subtitle) cellPresenters.append(cellPresenter) } return cellPresenters } func resetPagination() { self.objects.removeAll() self.pagination = PaginationDefinition(0, self.pagination.limit) self.hasMore = true } func detailViewControllerForResourceAtIndexPath(indexPath: IndexPath) -> UIViewController { let viewController = ObjectViewController(style: .grouped) viewController.object = objects[(indexPath as NSIndexPath).row] return viewController } }
mit
f55d8650e180f7280244d0f97e7ac2ed
30.273684
193
0.573544
5.56367
false
false
false
false
overtake/TelegramSwift
Telegram-Mac/LottiePlayer.swift
1
68715
import SwiftSignalKit import Postbox import RLottie import TGUIKit import Metal import TelegramCore import GZIP import libwebp import Accelerate import QuartzCore final class RenderAtomic<T> { private var lock: pthread_mutex_t private var value: T public init(value: T) { self.lock = pthread_mutex_t() self.value = value pthread_mutex_init(&self.lock, nil) } deinit { pthread_mutex_destroy(&self.lock) } public func with<R>(_ f: (T) -> R) -> R { pthread_mutex_lock(&self.lock) let result = f(self.value) pthread_mutex_unlock(&self.lock) return result } public func modify(_ f: (T) -> T) -> T { pthread_mutex_lock(&self.lock) let result = f(self.value) self.value = result pthread_mutex_unlock(&self.lock) return result } public func swap(_ value: T) -> T { pthread_mutex_lock(&self.lock) let previous = self.value self.value = value pthread_mutex_unlock(&self.lock) return previous } } let lottieThreadPool: ThreadPool = ThreadPool(threadCount: 5, threadPriority: 1.0) private let stateQueue = Queue() enum LottiePlayerState : Equatable { case initializing case failed case playing case stoped case finished } protocol RenderedFrame { var duration: TimeInterval { get } var data: Data? { get } var image: CGImage? { get } var backingScale: Int { get } var size: NSSize { get } var key: LottieAnimationEntryKey { get } var frame: Int32 { get } var mirror: Bool { get } var bytesPerRow: Int { get } } final class RenderedWebpFrame : RenderedFrame, Equatable { let frame: Int32 let size: NSSize let backingScale: Int let key: LottieAnimationEntryKey private let webpData: WebPImageFrame init(key: LottieAnimationEntryKey, frame: Int32, size: NSSize, webpData: WebPImageFrame, backingScale: Int) { self.key = key self.backingScale = backingScale self.size = size self.frame = frame self.webpData = webpData } var bytesPerRow: Int { let s:(w: Int, h: Int) = (w: Int(size.width) * backingScale, h: Int(size.height) * backingScale) return DeviceGraphicsContextSettings.shared.bytesPerRow(forWidth: s.w) } var image: CGImage? { return webpData.image?._cgImage } var duration: TimeInterval { return webpData.duration } var data: Data? { return nil } var mirror: Bool { return key.mirror } static func == (lhs: RenderedWebpFrame, rhs: RenderedWebpFrame) -> Bool { return lhs.key == rhs.key } } private let loops = RenderFpsLoops() private struct RenderFpsToken : Hashable { struct LoopToken : Hashable { let duration: Double let queue: Queue static func ==(lhs: LoopToken, rhs: LoopToken) -> Bool { return lhs.duration == rhs.duration && lhs.queue === rhs.queue } func hash(into hasher: inout Hasher) { hasher.combine(duration) } } func deinstall() { loops.remove(token: self) } func install(_ callback:@escaping()->Void) { loops.add(token: self, callback: callback) } private let index: Int let value: LoopToken init(duration: Double, queue: Queue, index: Int) { self.value = .init(duration: duration, queue: queue) self.index = index } func hash(into hasher: inout Hasher) { hasher.combine(self.value) hasher.combine(self.index) } } private final class RenderFpsLoops { private let loops:Atomic<[RenderFpsToken.LoopToken: RenderFpsLoop]> = Atomic(value: [:]) private var index: Int = 0 init() { } func getIndex() -> Int { self.index += 1 return index } func add(token: RenderFpsToken, callback:@escaping()->Void) { let current: RenderFpsLoop if let value = self.loops.with({ $0[token.value] }) { current = value } else { current = RenderFpsLoop(duration: token.value.duration, queue: token.value.queue) _ = self.loops.modify { value in var value = value value[token.value] = current return value } } current.add(token, callback: callback) } func remove(token: RenderFpsToken) { _ = self.loops.modify { loops in var loops = loops let loop = loops[token.value] if let loop = loop { let isEmpty = loop.remove(token) if isEmpty { loops.removeValue(forKey: token.value) } } return loops } } } private struct RenderFpsCallback { let callback:()->Void init(callback: @escaping()->Void) { self.callback = callback } } private final class RenderFpsLoop { private class Values { var values: [RenderFpsToken: RenderFpsCallback] = [:] } private let duration: Double private var timer: SwiftSignalKit.Timer? private let values:QueueLocalObject<Values> private let queue: Queue init(duration: Double, queue: Queue) { self.duration = duration self.queue = queue self.values = .init(queue: queue, generate: { return .init() }) self.timer = .init(timeout: duration, repeat: true, completion: { [weak self] in self?.loop() }, queue: queue) self.timer?.start() } private func loop() { self.values.with { current in let values = current.values for (_, c) in values { c.callback() } } } func remove(_ token: RenderFpsToken) -> Bool { return self.values.syncWith { current in current.values.removeValue(forKey: token) return current.values.isEmpty } } func add(_ token: RenderFpsToken, callback: @escaping()->Void) { self.values.with { current in current.values[token] = .init(callback: callback) } } } final class RenderedWebmFrame : RenderedFrame, Equatable { let frame: Int32 let size: NSSize let backingScale: Int let key: LottieAnimationEntryKey private let _data: Data private let fps: Int init(key: LottieAnimationEntryKey, frame: Int32, fps: Int, size: NSSize, data: Data, backingScale: Int) { self.key = key self.backingScale = backingScale self.size = size self.frame = frame self._data = data self.fps = fps } var bytesPerRow: Int { let s:(w: Int, h: Int) = (w: Int(size.width) * backingScale, h: Int(size.height) * backingScale) return DeviceGraphicsContextSettings.shared.bytesPerRow(forWidth: s.w) } var image: CGImage? { if let data = data { let s:(w: Int, h: Int) = (w: Int(size.width) * backingScale, h: Int(size.height) * backingScale) return data.withUnsafeBytes { pointer in let bytes = pointer.baseAddress!.assumingMemoryBound(to: UInt8.self) let mutableBytes = UnsafeMutableRawPointer(mutating: bytes) var buffer = vImage_Buffer(data: mutableBytes, height: vImagePixelCount(s.h), width: vImagePixelCount(s.w), rowBytes: bytesPerRow) if self.key.mirror { vImageHorizontalReflect_ARGB8888(&buffer, &buffer, vImage_Flags(kvImageDoNotTile)) } return generateImagePixel(size, scale: CGFloat(backingScale), pixelGenerator: { (_, pixelData, bytesPerRow) in memcpy(pixelData, mutableBytes, bufferSize) }) } } return nil } var duration: TimeInterval { return 1.0 / Double(self.fps) } var bufferSize: Int { let s:(w: Int, h: Int) = (w: Int(size.width) * backingScale, h: Int(size.height) * backingScale) let bytesPerRow = DeviceGraphicsContextSettings.shared.bytesPerRow(forWidth: s.w) return s.h * bytesPerRow } var data: Data? { return _data } var mirror: Bool { return key.mirror } static func == (lhs: RenderedWebmFrame, rhs: RenderedWebmFrame) -> Bool { return lhs.key == rhs.key } deinit { } } final class RenderedLottieFrame : RenderedFrame, Equatable { let frame: Int32 let data: Data? let size: NSSize let backingScale: Int let key: LottieAnimationEntryKey let fps: Int let initedOnMain: Bool init(key: LottieAnimationEntryKey, fps: Int, frame: Int32, size: NSSize, data: Data, backingScale: Int) { self.key = key self.frame = frame self.size = size self.data = data self.backingScale = backingScale self.fps = fps self.initedOnMain = Thread.isMainThread } static func ==(lhs: RenderedLottieFrame, rhs: RenderedLottieFrame) -> Bool { return lhs.frame == rhs.frame } var bufferSize: Int { let s:(w: Int, h: Int) = (w: Int(size.width) * backingScale, h: Int(size.height) * backingScale) return s.h * bytesPerRow } var bytesPerRow: Int { let s:(w: Int, h: Int) = (w: Int(size.width) * backingScale, h: Int(size.height) * backingScale) let bytesPerRow = DeviceGraphicsContextSettings.shared.bytesPerRow(forWidth: s.w) return bytesPerRow } var mirror: Bool { return key.mirror } var duration: TimeInterval { return 1.0 / Double(self.fps) } var image: CGImage? { if let data = data { return data.withUnsafeBytes({ pointer in let bytes = pointer.baseAddress!.assumingMemoryBound(to: UInt8.self) return generateImagePixel(size, scale: CGFloat(backingScale), pixelGenerator: { (_, pixelData, bytesPerRow) in let s:(w: Int, h: Int) = (w: Int(size.width) * backingScale, h: Int(size.height) * backingScale) let mutableBytes = UnsafeMutableRawPointer(mutating: bytes) var buffer = vImage_Buffer(data: mutableBytes, height: vImagePixelCount(s.h), width: vImagePixelCount(s.w), rowBytes: bytesPerRow) if self.key.mirror { vImageHorizontalReflect_ARGB8888(&buffer, &buffer, vImage_Flags(kvImageDoNotTile)) } memcpy(pixelData, mutableBytes, bufferSize) }) }) } return nil } deinit { } } private final class RendererState { fileprivate let animation: LottieAnimation private(set) var frames: [RenderedFrame] private(set) var previousFrame:RenderedFrame? private(set) var cachedFrames:[Int32 : RenderedFrame] private(set) var currentFrame: Int32 private(set) var startFrame:Int32 private(set) var _endFrame: Int32 private(set) var cancelled: Bool private(set) weak var container: RenderContainer? private(set) var renderIndex: Int32? init(cancelled: Bool, animation: LottieAnimation, container: RenderContainer?, frames: [RenderedLottieFrame], cachedFrames: [Int32 : RenderedLottieFrame], currentFrame: Int32, startFrame: Int32, endFrame: Int32) { self.animation = animation self.cancelled = cancelled self.container = container self.frames = frames self.cachedFrames = cachedFrames self.currentFrame = currentFrame self.startFrame = startFrame self._endFrame = endFrame } var endFrame: Int32 { return container?.endFrame ?? _endFrame } func withUpdatedFrames(_ frames: [RenderedFrame]) { self.frames = frames } func addFrame(_ frame: RenderedFrame) { let prev = frame.frame == 0 ? nil : self.frames.last ?? previousFrame self.container?.cacheFrame(prev, frame) self.frames = self.frames + [frame] } func loopComplete() { self.container?.markFinished() } func updateCurrentFrame(_ currentFrame: Int32) { self.currentFrame = currentFrame } func takeFirst() -> RenderedFrame { var frames = self.frames if frames.first?.frame == endFrame { self.previousFrame = nil } else { self.previousFrame = frames.last } let prev = frames.removeFirst() self.renderIndex = prev.frame self.frames = frames return prev } func renderFrame(at frame: Int32) -> RenderedFrame? { let rendered = container?.render(at: frame, frames: frames, previousFrame: previousFrame) return rendered } deinit { } func cancel() -> RendererState { self.cancelled = true return self } } final class LottieSoundEffect { private let player: MediaPlayer let triggerOn: Int32? private(set) var isPlayable: Bool = false init(file: TelegramMediaFile, postbox: Postbox, triggerOn: Int32?) { self.player = MediaPlayer(postbox: postbox, reference: MediaResourceReference.standalone(resource: file.resource), streamable: false, video: false, preferSoftwareDecoding: false, enableSound: true, baseRate: 1.0, fetchAutomatically: true) self.triggerOn = triggerOn } func play() { if isPlayable { self.player.play() isPlayable = false } } func markAsPlayable() -> Void { isPlayable = true } } protocol Renderer { func render(at frame: Int32) -> RenderedFrame } private let maximum_rendered_frames: Int = 4 private final class PlayerRenderer { private var soundEffect: LottieSoundEffect? private(set) var finished: Bool = false private var animation: LottieAnimation private var layer: Atomic<RenderContainer?> = Atomic(value: nil) private let updateState:(LottiePlayerState)->Void private let displayFrame: (RenderedFrame, LottieRunLoop)->Void private var renderToken: RenderFpsToken? private let release:()->Void private var maxRefreshRate: Int = 60 init(animation: LottieAnimation, displayFrame: @escaping(RenderedFrame, LottieRunLoop)->Void, release:@escaping()->Void, updateState:@escaping(LottiePlayerState)->Void) { self.animation = animation self.displayFrame = displayFrame self.updateState = updateState self.release = release self.soundEffect = animation.soundEffect } private var onDispose: (()->Void)? deinit { self.renderToken?.deinstall() self.onDispose?() _ = self.layer.swap(nil) self.release() self.updateState(.stoped) } func initializeAndPlay(maxRefreshRate: Int) { self.maxRefreshRate = maxRefreshRate self.updateState(.initializing) assert(animation.runOnQueue.isCurrent()) let container = self.animation.initialize() if let container = container { self.play(self.layer.modify({_ in container })!) } else { self.updateState(.failed) } } func playAgain() { self.layer.with { container -> Void in if let container = container { self.play(container) } } } func playSoundEffect() { self.soundEffect?.markAsPlayable() } func updateSize(_ size: NSSize) { self.animation = self.animation.withUpdatedSize(size) } func setColors(_ colors: [LottieColor]) { self.layer.with { container -> Void in for color in colors { container?.setColor(color.color, keyPath: color.keyPath) } } } private var getCurrentFrame:()->Int32? = { return nil } var currentFrame: Int32? { return self.getCurrentFrame() } private var getTotalFrames:()->Int32? = { return nil } var totalFrames: Int32? { return self.getTotalFrames() } private var jumpTo:(Int32)->Void = { _ in } func jump(to frame: Int32) -> Void { self.jumpTo(frame) } private func play(_ player: RenderContainer) { self.finished = false let runOnQueue = animation.runOnQueue let maximum_renderer_frames: Int = Thread.isMainThread ? 2 : maximum_rendered_frames let fps: Int = max(1, min(player.fps, max(30, maxRefreshRate))) let mainFps: Int = player.mainFps let maxFrames:Int32 = 180 var currentFrame: Int32 = 0 var startFrame: Int32 = min(min(player.startFrame, maxFrames), min(player.endFrame, maxFrames)) var endFrame: Int32 = min(player.endFrame, maxFrames) switch self.animation.playPolicy { case let .loopAt(firstStart, range): startFrame = range.lowerBound endFrame = range.upperBound if let firstStart = firstStart { currentFrame = firstStart } case let .toEnd(from): startFrame = max(min(from, endFrame - 1), startFrame) currentFrame = max(min(from, endFrame - 1), startFrame) case let .toStart(from): startFrame = 1 currentFrame = max(min(from, endFrame - 1), startFrame) default: break } let initialState = RendererState(cancelled: false, animation: self.animation, container: player, frames: [], cachedFrames: [:], currentFrame: currentFrame, startFrame: startFrame, endFrame: endFrame) let stateValue:RenderAtomic<RendererState?> = RenderAtomic(value: initialState) let updateState:(_ f:(RendererState?)->RendererState?)->Void = { f in _ = stateValue.modify(f) } self.getCurrentFrame = { [weak stateValue] in return stateValue?.with { $0?.renderIndex } } self.getTotalFrames = { [weak stateValue] in return stateValue?.with { $0?.endFrame } } self.jumpTo = { [weak stateValue] frame in _ = stateValue?.with { state in state?.updateCurrentFrame(frame) } } var framesTask: ThreadPoolTask? = nil let isRendering: Atomic<Bool> = Atomic(value: false) self.onDispose = { updateState { $0?.cancel() } framesTask?.cancel() framesTask = nil _ = stateValue.swap(nil) } let currentState:(_ state: RenderAtomic<RendererState?>) -> RendererState? = { state in return state.with { $0 } } var renderNext:(()->Void)? = nil var add_frames_impl:(()->Void)? = nil var askedRender: Bool = false var playedCount: Int32 = 0 var loopCount: Int32 = 0 var previousFrame: Int32 = 0 let render:()->Void = { [weak self] in var hungry: Bool = false var cancelled: Bool = false if let renderer = self { var current: RenderedFrame? updateState { stateValue in guard let state = stateValue, !state.frames.isEmpty else { return stateValue } current = state.takeFirst() hungry = state.frames.count < maximum_renderer_frames - 1 cancelled = state.cancelled return state } if !cancelled { if let current = current { let displayFrame = renderer.displayFrame let updateState = renderer.updateState displayFrame(current, .init(fps: fps)) playedCount += 1 if current.frame > 0 { updateState(.playing) } if previousFrame > current.frame { loopCount += 1 } previousFrame = current.frame if let soundEffect = renderer.soundEffect { if let triggerOn = soundEffect.triggerOn { let triggers:[Int32] = [triggerOn - 1, triggerOn, triggerOn + 1] if triggers.contains(current.frame) { soundEffect.play() } } else { if current.frame == 0 { soundEffect.play() } } } if let triggerOn = renderer.animation.triggerOn { switch triggerOn.0 { case .first: if currentState(stateValue)?.startFrame == current.frame { DispatchQueue.main.async(execute: triggerOn.1) } case .last: if endFrame - 2 == current.frame { DispatchQueue.main.async(execute: triggerOn.1) } case let .custom(index): if index == current.frame { DispatchQueue.main.async(execute: triggerOn.1) } } } let finish:()->Void = { renderer.finished = true cancelled = true updateState(.finished) renderer.renderToken?.deinstall() framesTask?.cancel() let onFinish = renderer.animation.onFinish ?? {} DispatchQueue.main.async(execute: onFinish) } switch renderer.animation.playPolicy { case .loop, .loopAt: break case .once: if current.frame + 1 == currentState(stateValue)?.endFrame { finish() } case .onceEnd, .toEnd: let end = fps == 60 ? 1 : 2 if let state = currentState(stateValue), state.endFrame - current.frame <= end { finish() } case .toStart: if current.frame <= 1, playedCount > 1 { finish() } case let .framesCount(limit): if limit <= playedCount { finish() } case let .onceToFrame(frame): if frame <= current.frame { finish() } case let .playCount(count): if loopCount >= count { finish() } } } if !renderer.finished { let duration = current?.duration ?? (1.0 / TimeInterval(fps)) if duration > 0, (renderer.totalFrames ?? 0) > 1 { let token = RenderFpsToken(duration: duration, queue: runOnQueue, index: loops.getIndex()) if renderer.renderToken != token { renderer.renderToken?.deinstall() token.install { renderNext?() } renderer.renderToken = token } } } } let isRendering = isRendering.with { $0 } if hungry && !isRendering && !cancelled && !askedRender { askedRender = true add_frames_impl?() } } } renderNext = { render() } var firstTimeRendered: Bool = true let maximum = Int(initialState.endFrame - initialState.startFrame) framesTask = ThreadPoolTask { state in _ = isRendering.swap(true) _ = stateValue.with { stateValue -> RendererState? in while let stateValue = stateValue, stateValue.frames.count < min(maximum_renderer_frames, maximum) { let cancelled = state.cancelled.with({$0}) if cancelled { return stateValue } var currentFrame = stateValue.currentFrame let frame = stateValue.renderFrame(at: currentFrame) if mainFps >= fps { if currentFrame % Int32(round(Float(mainFps) / Float(fps))) != 0 { currentFrame += 1 } } if let frame = frame { stateValue.updateCurrentFrame(currentFrame + 1) stateValue.addFrame(frame) } else { if stateValue.startFrame != currentFrame { stateValue.updateCurrentFrame(stateValue.startFrame) stateValue.loopComplete() } else { break } } } return stateValue } _ = isRendering.swap(false) runOnQueue.async { askedRender = false if firstTimeRendered { firstTimeRendered = false render() } } } let add_frames:()->Void = { if let framesTask = framesTask { if Thread.isMainThread { framesTask.execute() } else { lottieThreadPool.addTask(framesTask) } } } add_frames_impl = { add_frames() } add_frames() } } final class AnimationPlayerContext { private let rendererRef: QueueLocalObject<PlayerRenderer> fileprivate let animation: LottieAnimation init(_ animation: LottieAnimation, maxRefreshRate: Int = 60, displayFrame: @escaping(RenderedFrame, LottieRunLoop)->Void, release:@escaping()->Void, updateState: @escaping(LottiePlayerState)->Void) { self.animation = animation self.rendererRef = QueueLocalObject(queue: animation.runOnQueue, generate: { return PlayerRenderer(animation: animation, displayFrame: displayFrame, release: release, updateState: { state in delay(0.032, closure: { updateState(state) }) }) }) self.rendererRef.with { renderer in renderer.initializeAndPlay(maxRefreshRate: maxRefreshRate) } } func playAgain() { self.rendererRef.with { renderer in if renderer.finished { renderer.playAgain() } } } func setColors(_ colors: [LottieColor]) { self.rendererRef.with { renderer in renderer.setColors(colors) } } func playSoundEffect() { self.rendererRef.with { renderer in renderer.playSoundEffect() } } func updateSize(_ size: NSSize) { self.rendererRef.syncWith { renderer in renderer.updateSize(size) } } var currentFrame:Int32? { var currentFrame:Int32? = nil self.rendererRef.syncWith { renderer in currentFrame = renderer.currentFrame } return currentFrame } var totalFrames:Int32? { var totalFrames:Int32? = nil self.rendererRef.syncWith { renderer in totalFrames = renderer.totalFrames } return totalFrames } func jump(to frame: Int32) -> Void { self.rendererRef.with { renderer in renderer.jump(to: frame) } } } enum ASLiveTime : Int { case chat = 3_600 case thumb = 259200 case effect = 241_920 // 7 days } enum ASCachePurpose { case none case temporaryLZ4(ASLiveTime) } struct LottieAnimationEntryKey : Hashable { let size: CGSize let backingScale: Int let key:LottieAnimationKey let fitzModifier: EmojiFitzModifier? let colors: [LottieColor] let mirror: Bool init(key: LottieAnimationKey, size: CGSize, backingScale: Int = Int(System.backingScale), fitzModifier: EmojiFitzModifier? = nil, colors: [LottieColor] = [], mirror: Bool = false) { self.key = key self.size = size self.backingScale = backingScale self.fitzModifier = fitzModifier self.colors = colors self.mirror = mirror } func withUpdatedColors(_ colors: [LottieColor]) -> LottieAnimationEntryKey { return LottieAnimationEntryKey(key: key, size: size, backingScale: backingScale, fitzModifier: fitzModifier, colors: colors, mirror: mirror) } func withUpdatedBackingScale(_ backingScale: Int) -> LottieAnimationEntryKey { return LottieAnimationEntryKey(key: key, size: size, backingScale: backingScale, fitzModifier: fitzModifier, colors: colors, mirror: mirror) } func withUpdatedSize(_ size: CGSize) -> LottieAnimationEntryKey { return LottieAnimationEntryKey(key: key, size: size, backingScale: backingScale, fitzModifier: fitzModifier, colors: colors, mirror: mirror) } func hash(into hasher: inout Hasher) { hasher.combine(size.width) hasher.combine(size.height) hasher.combine(backingScale) hasher.combine(key) if let fitzModifier = fitzModifier { hasher.combine(fitzModifier) } for color in colors { hasher.combine(color.keyPath) hasher.combine(color.color.argb) } hasher.combine(mirror) } } enum LottieAnimationKey : Hashable { case media(MediaId?) case bundle(String) func hash(into hasher: inout Hasher) { switch self { case let .bundle(value): hasher.combine("bundle") hasher.combine(value) case let .media(mediaId): hasher.combine("media") if let mediaId = mediaId { hasher.combine(mediaId) } } } } enum LottiePlayPolicy : Hashable { case loop case loopAt(firstStart:Int32?, range: ClosedRange<Int32>) case once case onceEnd case toEnd(from: Int32) case toStart(from: Int32) case framesCount(Int32) case onceToFrame(Int32) case playCount(Int32) static func ==(lhs: LottiePlayPolicy, rhs: LottiePlayPolicy) -> Bool { switch lhs { case .loop: if case .loop = rhs { return true } case let .loopAt(firstStart, range): if case .loopAt(firstStart, range) = rhs { return true } case .once: if case .once = rhs { return true } case .onceEnd: if case .onceEnd = rhs { return true } case .toEnd: if case .toEnd = rhs { return true } case .toStart: if case .toStart = rhs { return true } case let .framesCount(count): if case .framesCount(count) = rhs { return true } case let .onceToFrame(count): if case .onceToFrame(count) = rhs { return true } case .playCount: if case .playCount = rhs { return true } } return false } } struct LottieColor : Equatable { let keyPath: String let color: NSColor } enum LottiePlayerTriggerFrame : Equatable { case first case last case custom(Int32) } protocol RenderContainer : AnyObject { func render(at frame: Int32, frames: [RenderedFrame], previousFrame: RenderedFrame?) -> RenderedFrame? func cacheFrame(_ previous: RenderedFrame?, _ current: RenderedFrame) func markFinished() func setColor(_ color: NSColor, keyPath: String) var endFrame: Int32 { get } var startFrame: Int32 { get } var fps: Int { get } var mainFps: Int { get } } private final class WebPRenderer : RenderContainer { private let animation: LottieAnimation private let decoder: WebPImageDecoder init(animation: LottieAnimation, decoder: WebPImageDecoder) { self.animation = animation self.decoder = decoder } func render(at frame: Int32, frames: [RenderedFrame], previousFrame: RenderedFrame?) -> RenderedFrame? { if let webpFrame = self.decoder.frame(at: UInt(frame), decodeForDisplay: true) { return RenderedWebpFrame(key: animation.key, frame: frame, size: animation.size, webpData: webpFrame, backingScale: animation.backingScale) } else { return nil } } func cacheFrame(_ previous: RenderedFrame?, _ current: RenderedFrame) { } func markFinished() { } func setColor(_ color: NSColor, keyPath: String) { } var endFrame: Int32 { return Int32(decoder.frameCount) } var startFrame: Int32 { return 0 } var fps: Int { return 1 } var mainFps: Int { return 1 } } private final class WebmRenderer : RenderContainer { private let animation: LottieAnimation private let decoder: SoftwareVideoSource private var index: Int32 = 1 private let fileSupplyment: TRLotFileSupplyment? init(animation: LottieAnimation, decoder: SoftwareVideoSource, fileSupplyment: TRLotFileSupplyment?) { self.animation = animation self.decoder = decoder self.fileSupplyment = fileSupplyment } func render(at frameIndex: Int32, frames: [RenderedFrame], previousFrame: RenderedFrame?) -> RenderedFrame? { let s:(w: Int, h: Int) = (w: Int(animation.size.width) * animation.backingScale, h: Int(animation.size.height) * animation.backingScale) let bytesPerRow = DeviceGraphicsContextSettings.shared.bytesPerRow(forWidth: s.w) let bufferSize = s.h * bytesPerRow if let fileSupplyment = fileSupplyment { let previous = frameIndex == startFrame ? nil : frames.last ?? previousFrame if let data = fileSupplyment.readFrame(previous: previous?.data, frame: Int(frameIndex)) { return RenderedWebmFrame(key: animation.key, frame: frameIndex, fps: self.fps, size: animation.size, data: data, backingScale: animation.backingScale) } if fileSupplyment.isFinished { return nil } } let frameAndLoop = decoder.readFrame(maxPts: nil) if frameAndLoop.0 == nil { return nil } guard let frame = frameAndLoop.0 else { return nil } self.index += 1 let destBytesPerRow = bytesPerRow let memoryData = malloc(bufferSize)! let bytes = memoryData.assumingMemoryBound(to: UInt8.self) let imageBuffer = CMSampleBufferGetImageBuffer(frame.sampleBuffer) CVPixelBufferLockBaseAddress(imageBuffer!, CVPixelBufferLockFlags(rawValue: 0)) let sourceBytesPerRow = 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: sourceBytesPerRow) 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)) let data = Data(bytes: bytes, count: bufferSize) bytes.deallocate() return RenderedWebmFrame(key: animation.key, frame: frameIndex, fps: self.fps, size: animation.size, data: data, backingScale: animation.backingScale) } func cacheFrame(_ previous: RenderedFrame?, _ current: RenderedFrame) { if let fileSupplyment = fileSupplyment { fileSupplyment.addFrame(previous?.data, (current.data!, current.frame)) } } func markFinished() { fileSupplyment?.markFinished() } func setColor(_ color: NSColor, keyPath: String) { } var endFrame: Int32 { return Int32(60) } var startFrame: Int32 { return 0 } var fps: Int { return min(30, decoder.getFramerate()) } var mainFps: Int { return 1 } } private final class LottieRenderer : RenderContainer { private let animation: LottieAnimation private let bridge: RLottieBridge? private let fileSupplyment: TRLotFileSupplyment? init(animation: LottieAnimation, bridge: RLottieBridge?, fileSupplyment: TRLotFileSupplyment?) { self.animation = animation self.bridge = bridge self.fileSupplyment = fileSupplyment } var fps: Int { return max(min(Int(bridge?.fps() ?? fileSupplyment?.fps ?? 60), self.animation.maximumFps), 24) } var mainFps: Int { return Int(bridge?.fps() ?? fileSupplyment?.fps ?? 60) } var endFrame: Int32 { return bridge?.endFrame() ?? fileSupplyment?.endFrame ?? 0 } var startFrame: Int32 { return bridge?.startFrame() ?? fileSupplyment?.startFrame ?? 0 } func setColor(_ color: NSColor, keyPath: String) { self.bridge?.setColor(color, forKeyPath: keyPath) } func cacheFrame(_ previous: RenderedFrame?, _ current: RenderedFrame) { if let fileSupplyment = fileSupplyment { fileSupplyment.addFrame(previous?.data, (current.data!, current.frame)) } } func markFinished() { fileSupplyment?.markFinished() } func render(at frame: Int32, frames: [RenderedFrame], previousFrame: RenderedFrame?) -> RenderedFrame? { let s:(w: Int, h: Int) = (w: Int(animation.size.width) * animation.backingScale, h: Int(animation.size.height) * animation.backingScale) var data: Data? if let fileSupplyment = fileSupplyment { let previous = frame == startFrame ? nil : frames.last ?? previousFrame if let frame = fileSupplyment.readFrame(previous: previous?.data, frame: Int(frame)) { data = frame } } if frame > endFrame - 1 { return nil } if data == nil { let bytesPerRow = DeviceGraphicsContextSettings.shared.bytesPerRow(forWidth: s.w) let bufferSize = s.h * bytesPerRow let memoryData = malloc(bufferSize)! let frameData = memoryData.assumingMemoryBound(to: UInt8.self) bridge?.renderFrame(with: frame, into: frameData, width: Int32(s.w), height: Int32(s.h), bytesPerRow: Int32(bytesPerRow)) data = Data(bytes: frameData, count: bufferSize) frameData.deallocate() } if let data = data { return RenderedLottieFrame(key: animation.key, fps: fps, frame: frame, size: animation.size, data: data, backingScale: self.animation.backingScale) } return nil } deinit { var bp:Int = 0 bp += 1 } } enum LottieAnimationType { case lottie case webp case webm } final class LottieAnimation : Equatable { static func == (lhs: LottieAnimation, rhs: LottieAnimation) -> Bool { return lhs.key == rhs.key && lhs.playPolicy == rhs.playPolicy && lhs.colors == rhs.colors } let type: LottieAnimationType var liveTime: Int { switch cache { case .none: return 0 case let .temporaryLZ4(liveTime): return liveTime.rawValue } } var supportsMetal: Bool { switch type { case .lottie: return self.metalSupport case .webm: return false default: return false } } let compressed: Data let key: LottieAnimationEntryKey let cache: ASCachePurpose let maximumFps: Int let playPolicy: LottiePlayPolicy let colors:[LottieColor] let soundEffect: LottieSoundEffect? let metalSupport: Bool let postbox: Postbox? let runOnQueue: Queue var onFinish:(()->Void)? var triggerOn:(LottiePlayerTriggerFrame, ()->Void, ()->Void)? { didSet { var bp = 0 bp += 1 } } init(compressed: Data, key: LottieAnimationEntryKey, type: LottieAnimationType = .lottie, cachePurpose: ASCachePurpose = .temporaryLZ4(.thumb), playPolicy: LottiePlayPolicy = .loop, maximumFps: Int = 60, colors: [LottieColor] = [], soundEffect: LottieSoundEffect? = nil, postbox: Postbox? = nil, runOnQueue: Queue = stateQueue, metalSupport: Bool = false) { self.compressed = compressed self.key = key.withUpdatedColors(colors) self.cache = cachePurpose self.maximumFps = maximumFps self.playPolicy = playPolicy self.colors = colors self.postbox = postbox self.soundEffect = soundEffect self.runOnQueue = runOnQueue self.type = type self.metalSupport = metalSupport } var size: NSSize { let size = key.size return size } var viewSize: NSSize { return key.size } var backingScale: Int { return key.backingScale } func withUpdatedBackingScale(_ scale: Int) -> LottieAnimation { return LottieAnimation(compressed: self.compressed, key: self.key.withUpdatedBackingScale(scale), type: self.type, cachePurpose: self.cache, playPolicy: self.playPolicy, maximumFps: self.maximumFps, colors: self.colors, postbox: self.postbox, runOnQueue: self.runOnQueue, metalSupport: self.metalSupport) } func withUpdatedColors(_ colors: [LottieColor]) -> LottieAnimation { return LottieAnimation(compressed: self.compressed, key: self.key, type: self.type, cachePurpose: self.cache, playPolicy: self.playPolicy, maximumFps: self.maximumFps, colors: colors, postbox: self.postbox, runOnQueue: self.runOnQueue, metalSupport: self.metalSupport) } func withUpdatedPolicy(_ playPolicy: LottiePlayPolicy) -> LottieAnimation { return LottieAnimation(compressed: self.compressed, key: self.key, type: self.type, cachePurpose: self.cache, playPolicy: playPolicy, maximumFps: self.maximumFps, colors: colors, postbox: self.postbox, runOnQueue: self.runOnQueue, metalSupport: self.metalSupport) } func withUpdatedSize(_ size: CGSize) -> LottieAnimation { return LottieAnimation(compressed: self.compressed, key: self.key.withUpdatedSize(size), type: self.type, cachePurpose: self.cache, playPolicy: self.playPolicy, maximumFps: self.maximumFps, colors: colors, postbox: self.postbox, runOnQueue: self.runOnQueue, metalSupport: self.metalSupport) } var cacheKey: String { switch key.key { case let .media(id): if let id = id { if let fitzModifier = key.fitzModifier { return "animation-\(id.namespace)-\(id.id)-\(key.mirror)-fitz\(fitzModifier.rawValue)" + self.colors.map { $0.keyPath + $0.color.hexString }.joined(separator: " ") } else { return "animation-\(id.namespace)-\(id.id)-\(key.mirror)" + self.colors.map { $0.keyPath + $0.color.hexString }.joined(separator: " ") } } else { return "\(arc4random())" } case let .bundle(string): return string + self.colors.map { $0.keyPath + $0.color.hexString }.joined(separator: " ") } } var bufferSize: Int { let s:(w: Int, h: Int) = (w: Int(size.width) * backingScale, h: Int(size.height) * backingScale) let bytesPerRow = DeviceGraphicsContextSettings.shared.bytesPerRow(forWidth: s.w) return s.h * bytesPerRow } func initialize() -> RenderContainer? { switch type { case .lottie: let decompressed = TGGUnzipData(self.compressed, 8 * 1024 * 1024) let data: Data? if let decompressed = decompressed { data = decompressed } else { data = self.compressed } if let data = data, !data.isEmpty { let fileSupplyment: TRLotFileSupplyment? switch self.cache { case .temporaryLZ4: fileSupplyment = TRLotFileSupplyment(self, bufferSize: bufferSize, queue: Queue()) case .none: fileSupplyment = nil } if fileSupplyment?.isFinished == true { return LottieRenderer(animation: self, bridge: nil, fileSupplyment: fileSupplyment) } else { let modified: Data if let color = self.colors.first(where: { $0.keyPath == "" }) { modified = applyLottieColor(data: data, color: color.color) } else { modified = transformedWithFitzModifier(data: data, fitzModifier: self.key.fitzModifier) } if let json = String(data: modified, encoding: .utf8) { if let bridge = RLottieBridge(json: json, key: self.cacheKey) { for color in self.colors { bridge.setColor(color.color, forKeyPath: color.keyPath) } fileSupplyment?.initialize(fps: bridge.fps(), startFrame: bridge.startFrame(), endFrame: bridge.endFrame()) return LottieRenderer(animation: self, bridge: bridge, fileSupplyment: fileSupplyment) } } } } case .webp: let decompressed = TGGUnzipData(self.compressed, 8 * 1024 * 1024) let data: Data? if let decompressed = decompressed { data = decompressed } else { data = self.compressed } if let data = data, !data.isEmpty { if let decoder = WebPImageDecoder(data: data, scale: CGFloat(backingScale)) { return WebPRenderer(animation: self, decoder: decoder) } } case .webm: let path = String(data: self.compressed, encoding: .utf8) if let path = path { let premultiply = (DeviceGraphicsContextSettings.shared.opaqueBitmapInfo.rawValue & CGImageAlphaInfo.premultipliedFirst.rawValue) == 0 let decoder = SoftwareVideoSource(path: path, hintVP9: true, unpremultiplyAlpha: premultiply) let fileSupplyment: TRLotFileSupplyment? if size.width > 40 { switch self.cache { case .temporaryLZ4: fileSupplyment = TRLotFileSupplyment(self, bufferSize: bufferSize, queue: Queue()) case .none: fileSupplyment = nil } } else { fileSupplyment = nil } return WebmRenderer(animation: self, decoder: decoder, fileSupplyment: fileSupplyment) } } return nil } } private struct RenderLoopItem { weak private(set) var view: MetalRenderer? let frame: RenderedFrame func render(_ commandBuffer: MTLCommandBuffer) -> MTLDrawable? { return view?.draw(frame: frame, commandBuffer: commandBuffer) } } private class Loops { var data: [LottieRunLoop : Loop] = [:] func add(_ view: MetalRenderer, frame: RenderedFrame, runLoop: LottieRunLoop, commandQueue: MTLCommandQueue) { let loop = getLoop(runLoop, commandQueue: commandQueue) loop.append(.init(view: view, frame: frame)) } func clean() { data.removeAll() } private func getLoop(_ runLoop: LottieRunLoop, commandQueue: MTLCommandQueue) -> Loop { var loop: Loop if let c = data[runLoop] { loop = c } else { loop = Loop(runLoop, commandQueue: commandQueue) data[runLoop] = loop } return loop } } private final class Loop { var list:[RenderLoopItem] = [] private let commandQueue: MTLCommandQueue private var timer: SwiftSignalKit.Timer? init(_ runLoop: LottieRunLoop, commandQueue: MTLCommandQueue) { self.commandQueue = commandQueue self.timer = SwiftSignalKit.Timer(timeout: 1 / TimeInterval(runLoop.fps), repeat: true, completion: { [weak self] in self?.renderItems() }, queue: stateQueue) self.timer?.start() } private func renderItems() { let commandBuffer = self.commandQueue.makeCommandBuffer() if let commandBuffer = commandBuffer { var drawables: [MTLDrawable] = [] while !self.list.isEmpty { let item = self.list.removeLast() let drawable = item.render(commandBuffer) if let drawable = drawable { drawables.append(drawable) } } if drawables.isEmpty { return } commandBuffer.addScheduledHandler { _ in for drawable in drawables { drawable.present() } } commandBuffer.commit() } else { self.list.removeAll() } } func append(_ item: RenderLoopItem) { self.list.append(item) } } final class MetalContext { let device: MTLDevice let pipelineState: MTLRenderPipelineState let vertexBuffer: MTLBuffer let sampler: MTLSamplerState let commandQueue: MTLCommandQueue? let displayId: CGDirectDisplayID let refreshRate: Int private var loops: QueueLocalObject<Loops> init?() { self.loops = QueueLocalObject(queue: stateQueue, generate: { return Loops() }) self.displayId = CGMainDisplayID() self.refreshRate = 60 if let device = CGDirectDisplayCopyCurrentMetalDevice(displayId) { self.device = device self.commandQueue = device.makeCommandQueue() } else { return nil } do { let library = device.makeDefaultLibrary() let fragmentProgram = library?.makeFunction(name: "basic_fragment") let vertexProgram = library?.makeFunction(name: "basic_vertex") let pipelineStateDescriptor = MTLRenderPipelineDescriptor() pipelineStateDescriptor.vertexFunction = vertexProgram pipelineStateDescriptor.fragmentFunction = fragmentProgram pipelineStateDescriptor.colorAttachments[0].pixelFormat = .bgra8Unorm self.pipelineState = try device.makeRenderPipelineState(descriptor: pipelineStateDescriptor) let vertexData: [Float] = [ -1.0, -1.0, 0.0, 0.0, 1.0, -1.0, 1.0, 0.0, 0.0, 0.0, 1.0, -1.0, 0.0, 1.0, 1.0, 1.0, -1.0, 0.0, 1.0, 1.0, -1.0, 1.0, 0.0, 0.0, 0.0, 1.0, 1.0, 0.0, 1.0, 0.0 ] let dataSize = vertexData.count * MemoryLayout.size(ofValue: vertexData[0]) self.vertexBuffer = device.makeBuffer(bytes: vertexData, length: dataSize, options: [])! let sampler = MTLSamplerDescriptor() sampler.minFilter = MTLSamplerMinMagFilter.nearest sampler.magFilter = MTLSamplerMinMagFilter.nearest sampler.mipFilter = MTLSamplerMipFilter.nearest sampler.maxAnisotropy = 1 sampler.sAddressMode = MTLSamplerAddressMode.clampToZero sampler.tAddressMode = MTLSamplerAddressMode.clampToZero sampler.rAddressMode = MTLSamplerAddressMode.clampToZero sampler.normalizedCoordinates = true sampler.lodMinClamp = 0.0 sampler.lodMaxClamp = .greatestFiniteMagnitude self.sampler = device.makeSamplerState(descriptor: sampler)! } catch { return nil } } func cleanLoops() { self.loops.with { loops in loops.clean() } } fileprivate func add(_ view: MetalRenderer, frame: RenderedFrame, runLoop: LottieRunLoop, commandQueue: MTLCommandQueue) { self.loops.with { loops in loops.add(view, frame: frame, runLoop: runLoop, commandQueue: commandQueue) } } } private var metalContext: MetalContext? private final class ContextHolder { private var useCount: Int = 0 let context: MetalContext init?() { if metalContext == nil { metalContext = MetalContext() } else if metalContext?.displayId != CGMainDisplayID() { metalContext = MetalContext() } guard let context = metalContext else { return nil } self.context = context } func incrementUseCount() { assert(Queue.mainQueue().isCurrent()) useCount += 1 } func decrementUseCount() { assert(Queue.mainQueue().isCurrent()) useCount -= 1 assert(useCount >= 0) if shouldRelease() { holder = nil metalContext?.cleanLoops() } } func shouldRelease() -> Bool { return useCount == 0 } deinit { assert(Queue.mainQueue().isCurrent()) } } private var holder: ContextHolder? struct LottieRunLoop : Hashable { let fps: Int func hash(into hasher: inout Hasher) { hasher.combine(fps) } } private final class MetalRenderer: View { private let texture: MTLTexture private let metalLayer: CAMetalLayer = CAMetalLayer() private let context: MetalContext init(animation: LottieAnimation, context: MetalContext) { self.context = context let textureDesc: MTLTextureDescriptor = MTLTextureDescriptor.texture2DDescriptor(pixelFormat: .bgra8Unorm, width: Int(animation.size.width) * animation.backingScale, height: Int(animation.size.height) * animation.backingScale, mipmapped: false) textureDesc.sampleCount = 1 textureDesc.textureType = .type2D self.texture = context.device.makeTexture(descriptor: textureDesc)! super.init(frame: NSMakeRect(0, 0, animation.viewSize.width, animation.viewSize.height)) self.metalLayer.device = context.device self.metalLayer.framebufferOnly = true self.metalLayer.isOpaque = false self.metalLayer.contentsScale = backingScaleFactor self.wantsLayer = true self.layer?.addSublayer(metalLayer) metalLayer.frame = CGRect(origin: CGPoint(), size: animation.viewSize) holder?.incrementUseCount() } override func layout() { super.layout() metalLayer.frame = self.bounds } override func hitTest(_ point: NSPoint) -> NSView? { return nil } deinit { holder?.decrementUseCount() } override func viewDidChangeBackingProperties() { super.viewDidChangeBackingProperties() self.metalLayer.contentsScale = backingScaleFactor } override func removeFromSuperview() { super.removeFromSuperview() } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } required init(frame frameRect: NSRect) { fatalError("init(frame:) has not been implemented") } func draw(frame: RenderedFrame, commandBuffer: MTLCommandBuffer) -> MTLDrawable? { guard let drawable = metalLayer.nextDrawable(), let data = frame.data else { return nil } return data.withUnsafeBytes { pointer in let bytes = pointer.baseAddress!.assumingMemoryBound(to: UInt8.self) let size: NSSize = frame.size let backingScale: Int = frame.backingScale let region = MTLRegionMake2D(0, 0, Int(size.width) * backingScale, Int(size.height) * backingScale) self.texture.replace(region: region, mipmapLevel: 0, withBytes: bytes, bytesPerRow: Int(size.width) * backingScale * 4) let renderPassDescriptor = MTLRenderPassDescriptor() renderPassDescriptor.colorAttachments[0].texture = drawable.texture renderPassDescriptor.colorAttachments[0].loadAction = .clear renderPassDescriptor.colorAttachments[0].clearColor = MTLClearColor(red: 0.0, green: 0.0, blue: 0.0, alpha: 0.0) let renderEncoder = commandBuffer.makeRenderCommandEncoder(descriptor: renderPassDescriptor)! renderEncoder.setRenderPipelineState(self.context.pipelineState) renderEncoder.setVertexBuffer(self.context.vertexBuffer, offset: 0, index: 0) renderEncoder.setFragmentTexture(self.texture, index: 0) renderEncoder.setFragmentSamplerState(self.context.sampler, index: 0) var mirror = frame.mirror renderEncoder.setFragmentBytes(&mirror, length: MemoryLayout<Bool>.size, index: 0) renderEncoder.drawPrimitives(type: .triangle, vertexStart: 0, vertexCount: 6, instanceCount: 1) renderEncoder.endEncoding() return drawable } } func render(frame: RenderedFrame, runLoop: LottieRunLoop) { guard let commandQueue = self.context.commandQueue else { return } self.context.add(self, frame: frame, runLoop: runLoop, commandQueue: commandQueue) } } private final class LottieFallbackView: NSView { override func hitTest(_ point: NSPoint) -> NSView? { return nil } deinit { var bp = 0 bp += 1 } } class LottiePlayerView : View { private var context: AnimationPlayerContext? private var _ignoreCachedContext: Bool = false private let _currentState: Atomic<LottiePlayerState> = Atomic(value: .initializing) var currentState: LottiePlayerState { return _currentState.with { $0 } } private let stateValue: ValuePromise<LottiePlayerState> = ValuePromise(.initializing, ignoreRepeated: true) var state: Signal<LottiePlayerState, NoError> { return stateValue.get() } required init(frame frameRect: NSRect) { super.init(frame: frameRect) } required override init() { super.init() } private var temporary: LottieAnimation? func updateVisible() { if self.visibleRect == .zero { self.temporary = self.animation } else { if let temporary = temporary { self.set(temporary) } self.temporary = nil } } var animation: LottieAnimation? var contextAnimation: LottieAnimation? { return context?.animation } override var isFlipped: Bool { return true } override func setFrameSize(_ newSize: NSSize) { super.setFrameSize(newSize) update(size: newSize, transition: .immediate) } func update(size: NSSize, transition: ContainedViewLayoutTransition) { for subview in subviews { transition.updateFrame(view: subview, frame: size.bounds) } if let sublayers = layer?.sublayers { for sublayer in sublayers { transition.updateFrame(layer: sublayer, frame: size.bounds) } } } deinit { var bp:Int = 0 bp += 1 } required init?(coder decoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidChangeBackingProperties() { if let context = context { self.set(context.animation.withUpdatedBackingScale(Int(backingScaleFactor))) } } func playIfNeeded(_ playSound: Bool = false) { if let context = self.context, context.animation.playPolicy == .once { context.playAgain() if playSound { context.playSoundEffect() } } else { context?.playSoundEffect() } } func playAgain() { self.context?.playAgain() } var currentFrame: Int32? { if _ignoreCachedContext { return nil } if let context = self.context { return context.currentFrame } else { return nil } } func ignoreCachedContext() { _ignoreCachedContext = true } var totalFrames: Int32? { if _ignoreCachedContext { return nil } if let context = self.context { return context.totalFrames } else { return nil } } func setColors(_ colors: [LottieColor]) { context?.setColors(colors) } func set(_ animation: LottieAnimation?, reset: Bool = false, saveContext: Bool = false, animated: Bool = false) { assertOnMainThread() _ignoreCachedContext = false self.animation = animation if animation == nil { self.temporary = nil } var accept: Bool = true switch animation?.playPolicy { case let.framesCount(count): accept = count != 0 default: break } if let animation = animation, accept { self.stateValue.set(self._currentState.modify { _ in .initializing }) if self.context?.animation != animation || reset { if !animation.runOnQueue.isCurrent() && animation.supportsMetal { if holder == nil { holder = ContextHolder() } } else { holder = nil } if let holder = holder { let metal = MetalRenderer(animation: animation, context: holder.context) self.addSubview(metal) let layer = Unmanaged.passRetained(metal) var cachedContext:Unmanaged<AnimationPlayerContext>? if let context = self.context, saveContext { cachedContext = Unmanaged.passRetained(context) } else { cachedContext = nil } self.context = AnimationPlayerContext(animation, maxRefreshRate: holder.context.refreshRate, displayFrame: { frame, runLoop in layer.takeUnretainedValue().render(frame: frame, runLoop: runLoop) }, release: { delay(0.032, closure: { layer.takeRetainedValue().removeFromSuperview() _ = cachedContext?.takeRetainedValue() cachedContext = nil }) }, updateState: { [weak self] state in guard let `self` = self else { return } switch state { case .playing, .failed, .stoped: _ = cachedContext?.takeRetainedValue() cachedContext = nil default: break } self.stateValue.set(self._currentState.modify { _ in state } ) }) } else { let fallback = SimpleLayer() fallback.frame = CGRect(origin: CGPoint(), size: self.frame.size) fallback.contentsGravity = .resize self.layer?.addSublayer(fallback) if animated { fallback.animateAlpha(from: 0, to: 1, duration: 0.2) } let layer = Unmanaged.passRetained(fallback) self.context = AnimationPlayerContext(animation, displayFrame: { frame, _ in let image = frame.image Queue.mainQueue().async { layer.takeUnretainedValue().contents = image } }, release: { delay(0.032, closure: { let view = layer.takeRetainedValue() if animated { view.animateAlpha(from: 1, to: 0, duration: 0.2, removeOnCompletion: false, completion: { [weak view] _ in view?.removeFromSuperlayer() }) } else { view.removeFromSuperlayer() } }) }, updateState: { [weak self] state in guard let `self` = self else { return } self.stateValue.set(self._currentState.modify { _ in state } ) }) } } } else { self.context = nil self.stateValue.set(self._currentState.modify { _ in .stoped }) } } }
gpl-2.0
da178a69b32cbda3894c2bbf731965a1
33.000495
361
0.551161
4.957792
false
false
false
false
zwaldowski/Lustre
Lustre/EitherType+Result.swift
1
3066
// // EitherType+Result.swift // Lustre // // Created by Zachary Waldowski on 7/25/15. // Copyright © 2014-2015. Some rights reserved. // extension EitherType where LeftType == ErrorType { public var isSuccess: Bool { return isRight } public var isFailure: Bool { return isLeft } public var error: LeftType? { return left } public var value: RightType? { return right } } // MARK: Throws compatibility extension EitherType where LeftType == ErrorType { public init(@noescape _ fn: () throws -> RightType) { do { self.init(right: try fn()) } catch { self.init(left: error) } } public func extract() throws -> RightType { var error: LeftType! guard let value = analysis(ifLeft: { error = $0; return .None }, ifRight: { $0 }) as RightType? else { throw error } return value } } // MARK: Value recovery extension EitherType where LeftType == ErrorType { public init(_ value: RightType?, @autoclosure failWith: () -> LeftType) { if let value = value { self.init(right: value) } else { self.init(left: failWith()) } } public func recover(@autoclosure fallbackValue: () -> RightType) -> RightType { return analysis(ifLeft: { _ in fallbackValue() }, ifRight: { $0 }) } } public func ??<Either: EitherType where Either.LeftType == ErrorType>(lhs: Either, @autoclosure rhs: () -> Either.RightType) -> Either.RightType { return lhs.recover(rhs()) } // MARK: Result equatability extension ErrorType { public func matches(other: ErrorType) -> Bool { return (self as NSError) == (other as NSError) } } public func ==<LeftEither: EitherType, RightEither: EitherType where LeftEither.LeftType == ErrorType, RightEither.LeftType == ErrorType, LeftEither.RightType: Equatable, RightEither.RightType == LeftEither.RightType>(lhs: LeftEither, rhs: RightEither) -> Bool { return lhs.equals(rhs, leftEqual: { $0.matches($1) }, rightEqual: ==) } public func !=<LeftEither: EitherType, RightEither: EitherType where LeftEither.LeftType == ErrorType, RightEither.LeftType == ErrorType, LeftEither.RightType: Equatable, RightEither.RightType == LeftEither.RightType>(lhs: LeftEither, rhs: RightEither) -> Bool { return !(lhs == rhs) } public func ==<LeftEither: EitherType, RightEither: EitherType where LeftEither.LeftType == ErrorType, RightEither.LeftType == ErrorType, LeftEither.RightType == Void, RightEither.RightType == Void>(lhs: LeftEither, rhs: RightEither) -> Bool { return lhs.equals(rhs, leftEqual: { $0.matches($1) }, rightEqual: { _ in true }) } public func !=<LeftEither: EitherType, RightEither: EitherType where LeftEither.LeftType == ErrorType, RightEither.LeftType == ErrorType, LeftEither.RightType == Void, RightEither.RightType == Void>(lhs: LeftEither, rhs: RightEither) -> Bool { return !(lhs == rhs) }
mit
f828177f4808be38b1d5bc7b7111f06b
30.597938
262
0.641436
4.114094
false
false
false
false
Skyus/Oak
Oak/Defile.swift
1
5887
import Foundation public enum DefileModes { case read case write case append } public enum DefileError: Error { case modeMismatch case writeFailure case null } extension String { public func replacing(_ extensions: [String], with replacement: String) -> String { var components = self.components(separatedBy: ".") let last = components.count - 1 if extensions.contains(components[last]) { components.remove(at: last) } components.append(replacement) return components.joined(separator: ".") } } public class Defile { private var file: UnsafeMutablePointer<FILE> private var mode: DefileModes var endOfFile: Bool { return feof(file) == 0 } /* Initializes file. path: The give path (or filename) to open the file in. mode: .read, .write or .append. *.read opens file for reading. If the file does not exist, the initializer fails. *.write opens file for writing. If the file does not exist, it will be created. *.append opens the file for appending more information to the end of the file. If the file does not exist, it will be created. bufferSize: If you are going to be streaming particularly long strings (i.e. >1024 UTF8 characters), you might want to increase this value. Otherwise, the string will be truncated to a maximum length of 1024. */ public init?(_ path: String, mode: DefileModes) { var modeStr: String switch(mode) { case .read: modeStr = "r" case .write: modeStr = "w" case .append: modeStr = "a" } guard let file = fopen(path, modeStr) else { return nil } self.file = file self.mode = mode } deinit { fclose(file) } /* Loads the rest of the file into a string. Proceeds to remove entire file from stream. */ public func dumpString() throws -> String { if mode != .read { throw DefileError.modeMismatch } var string = "" var character = fgetc(file) while character != EOF { string += "\(UnicodeScalar(UInt32(character))!)" character = fgetc(file) } return string } /* Reads one line from file, removes it from stream. */ public func readLine() throws -> String? { if mode != .read { throw DefileError.modeMismatch } var string = "" var character = fgetc(file) while character != EOF && UInt8(character) != UInt8(ascii:"\n") { (UInt8(character) != UInt8(ascii:"\r")) ? string += "\(UnicodeScalar(UInt32(character))!)" : () character = fgetc(file) } if (string == "") { return nil } return string } /* Reads one string from file, removes it (and any preceding whitespace) from stream. */ public func readString() throws -> String? { if mode != .read { throw DefileError.modeMismatch } var string = "" var character = fgetc(file) while UInt8(character) == UInt8(ascii:"\n") || UInt8(character) == UInt8(ascii:"\r") || UInt8(character) == UInt8(ascii:" ") || UInt8(character) == UInt8(ascii:"\t") { character = fgetc(file) } while character != EOF && UInt8(character) != UInt8(ascii:"\n") && UInt8(character) != UInt8(ascii:"\r") && UInt8(character) != UInt8(ascii:" ") { string += "\(UnicodeScalar(UInt32(character))!)" character = fgetc(file) } if (string == "") { return nil } return string } /* Loads the rest of the file into a string. Proceeds to remove entire file from stream. */ public func dumpBytes() throws -> [UInt8] { if mode != .read { throw DefileError.modeMismatch } var bytes = [UInt8]() var character = fgetc(file) while character != EOF { bytes.append(UInt8(character)) character = fgetc(file) } return bytes } /* Reads binary data from file, removes it from stream. */ public func readBytes(count: Int) throws -> [UInt8]? { if mode != .read { throw DefileError.modeMismatch } var bytes = [UInt8]() var character: Int32 = 0 for _ in 0..<count { fread(&character, 1, 1, file); if character == EOF { return nil } bytes.append(UInt8(character & 0xFF)) } return bytes } /* Writes binary data to file. */ public func write(bytes: [UInt8]) throws { if mode != .write { throw DefileError.modeMismatch } for byte in bytes { if (fputc(Int32(byte), file) == EOF) { throw DefileError.writeFailure } } } /* Appends binary data to file. */ public func append(bytes: [UInt8]) throws { if mode != .append { throw DefileError.modeMismatch } for byte in bytes { if (fputc(Int32(byte), file) == EOF) { throw DefileError.writeFailure } } } }
mpl-2.0
f164a43ae9922444120b6cbdcd938c6a
22.454183
213
0.499915
4.524981
false
false
false
false
jpush/jchat-swift
JChat/Src/Utilites/3rdParty/InputBar/SAIInputAccessoryView.swift
1
25477
// // SAIInputAccessoryView.swift // SAIInputBar // // Created by SAGESSE on 7/23/16. // Copyright © 2016-2017 SAGESSE. All rights reserved. // import UIKit internal protocol SAIInputAccessoryViewDelegate: class { func inputAccessoryView(touchDown recordButton: UIButton) func inputAccessoryView(touchUpInside recordButton: UIButton) func inputAccessoryView(touchUpOutside recordButton: UIButton) func inputAccessoryView(dragOutside recordButton: UIButton) func inputAccessoryView(dragInside recordButton: UIButton) } internal class SAIInputAccessoryView: UIView { var isShowRecordButton: Bool { get { return _recordButton.isHidden } set { _recordButton.isHidden = !newValue _textField.isHidden = newValue } } var textField: SAIInputTextField { return _textField } weak var delegate: (UITextViewDelegate & SAIInputItemViewDelegate & SAIInputAccessoryViewDelegate)? override func layoutSubviews() { super.layoutSubviews() if _cacheBounds?.width != bounds.width { _cacheBounds = bounds _boundsDidChanged() } } override func becomeFirstResponder() -> Bool { return _textField.becomeFirstResponder() } override func resignFirstResponder() -> Bool { return _textField.resignFirstResponder() } override func invalidateIntrinsicContentSize() { _cacheContentSize = nil super.invalidateIntrinsicContentSize() } override var intrinsicContentSize: CGSize { if let size = _cacheContentSize, size.width == frame.width { return size } // Calculate intrinsicContentSize that will fit all the text let size = _contentSizeWithoutCache _cacheContentSize = size return size } func updateInputMode(_ newMode: SAIInputMode, oldMode: SAIInputMode, animated: Bool) { if !newMode.isEditing && textField.isFirstResponder { _ = resignFirstResponder() } if newMode.isEditing && !textField.isFirstResponder { _ = becomeFirstResponder() } } // MARK: Selection func barItems(atPosition position: SAIInputItemPosition) -> [SAIInputItem] { return _barItems(atPosition: position) } func setBarItems(_ barItems: [SAIInputItem], atPosition position: SAIInputItemPosition, animated: Bool) { _setBarItems(barItems, atPosition: position) // if _cacheBoundsSize is nil, the layout is not initialize if _cacheBounds != nil { _collectionViewLayout.invalidateLayoutIfNeeded(atPosition: position) _updateBarItemsLayout(animated) } } func canSelectBarItem(_ barItem: SAIInputItem) -> Bool { return !_selectedBarItems.contains(barItem) } func canDeselectBarItem(_ barItem: SAIInputItem) -> Bool { return _selectedBarItems.contains(barItem) } func selectBarItem(_ barItem: SAIInputItem, animated: Bool) { _selectedBarItems.insert(barItem) // need to be updated in the visible part of it _collectionView.visibleCells.forEach { guard let cell = ($0 as? SAIInputItemView), cell.item === barItem else { return } cell.setSelected(true, animated: animated) } } func deselectBarItem(_ barItem: SAIInputItem, animated: Bool) { _selectedBarItems.remove(barItem) // need to be updated in the visible part of it _collectionView.visibleCells.forEach { guard let cell = $0 as? SAIInputItemView, cell.item === barItem else { return } cell.setSelected(false, animated: animated) } } // MARK: Private Method fileprivate func _barItems(atPosition position: SAIInputItemPosition) -> [SAIInputItem] { return _barItems[position.rawValue] ?? [] } fileprivate func _setBarItems(_ barItems: [SAIInputItem], atPosition position: SAIInputItemPosition) { if position == .center { _centerBarItem = barItems.first ?? _textField.item _barItems[position.rawValue] = [_centerBarItem] } else { _barItems[position.rawValue] = barItems } } fileprivate func _barItem(atIndexPath indexPath: IndexPath) -> SAIInputItem { if let items = _barItems[(indexPath as NSIndexPath).section], (indexPath as NSIndexPath).item < items.count { return items[(indexPath as NSIndexPath).item] } fatalError("barItem not found at \(indexPath)") } fileprivate func _barItemAlginment(at indexPath: IndexPath) -> SAIInputItemAlignment { let item = _barItem(atIndexPath: indexPath) if item.alignment == .automatic { // in automatic mode, the section will have different performance switch (indexPath as NSIndexPath).section { case 0: return .bottom case 1: return .bottom case 2: return .bottom default: return .center } } return item.alignment } fileprivate func _boundsDidChanged() { _textField.item.invalidateCache() _updateBarItemsLayout(false) } fileprivate func _contentDidChange() { let center = NotificationCenter.default center.post(name: Notification.Name(rawValue: SAIAccessoryDidChangeFrameNotification), object: nil) } fileprivate func _updateContentInsetsIfNeeded() { let contentInsets = _contentInsetsWithoutCache guard contentInsets != _cacheContentInsets else { return } // update the constraints _textFieldTop.constant = contentInsets.top _textFieldLeft.constant = contentInsets.left _textFieldRight.constant = contentInsets.right _textFieldBottom.constant = contentInsets.bottom _cacheContentInsets = contentInsets } fileprivate func _updateContentSizeIfNeeded() { let contentSize = _contentSizeWithoutCache guard _cacheContentSize != contentSize else { return } invalidateIntrinsicContentSize() _cacheContentSize = contentSize _contentDidChange() } fileprivate func _updateContentSizeForTextChanged(_ animated: Bool) { guard _textField.item.needsUpdateContent else { return } if animated { UIView.beginAnimations("SAIB-ANI-AC", context: nil) UIView.setAnimationDuration(_SAInputDefaultAnimateDuration) UIView.setAnimationCurve(_SAInputDefaultAnimateCurve) } _updateContentSizeInCollectionView() _updateContentSizeIfNeeded() // reset the offset, because offset in the text before the update has been made changes _textField.setContentOffset(CGPoint.zero, animated: true) if animated { UIView.commitAnimations() } } fileprivate func _updateContentSizeInCollectionView() { _collectionView.reloadSections(IndexSet(integer: _SAInputAccessoryViewCenterSection)) } fileprivate func _updateBarItemsInCollectionView() { // add, remove, update (0 ..< numberOfSections(in: _collectionView)).forEach { section in let newItems = _barItems[section] ?? [] let oldItems = _cacheBarItems[section] ?? [] var addIdxs: Set<Int> = [] var removeIdxs: Set<Int> = [] var reloadIdxs: Set<Int> = [] _diff(oldItems, newItems).forEach { if $0.0 < 0 { let idx = max($0.1, 0) removeIdxs.insert(idx) } if $0.0 > 0 { let idx = max($0.1, 0) if removeIdxs.contains(idx) { removeIdxs.remove(idx) reloadIdxs.insert(idx) } else { addIdxs.insert($0.1 + addIdxs.count - removeIdxs.count + 1) } } } _collectionView.reloadItems(at: reloadIdxs.map({ IndexPath(item: $0, section: section) })) _collectionView.insertItems(at: addIdxs.map({ IndexPath(item: $0, section: section) })) _collectionView.deleteItems(at: removeIdxs.map({ IndexPath(item: $0, section: section) })) _cacheBarItems[section] = newItems } } fileprivate func _updateBarItemsLayout(_ animated: Bool) { if animated { UIView.beginAnimations("SAIB-ANI-AC", context: nil) UIView.setAnimationDuration(_SAInputDefaultAnimateDuration) UIView.setAnimationCurve(_SAInputDefaultAnimateCurve) } // step 0: update the boundary _updateContentInsetsIfNeeded() // step 1: update textField the size _textField.layoutIfNeeded() // step 2: update cell _updateBarItemsIfNeeded(animated) // step 3: update contentSize _updateContentSizeIfNeeded() // step 4: update other if _centerBarItem != _textField.item { _textField.alpha = 0 _textField.backgroundView.alpha = 0 } else { _textField.alpha = 1 _textField.backgroundView.alpha = 1 } if animated { UIView.commitAnimations() } } fileprivate func _updateBarItemsIfNeeded(_ animated: Bool) { guard !_collectionView.indexPathsForVisibleItems.isEmpty else { // initialization is not complete _cacheBarItems = _barItems return } _collectionView.performBatchUpdates(_updateBarItemsInCollectionView, completion: nil) } private func _init() { // configuration // _textField.isHidden = true _textField.font = UIFont.systemFont(ofSize: 15) _textField.layer.cornerRadius = 5 _textField.layer.borderWidth = 0.5 _textField.layer.borderColor = UIColor.gray.cgColor _textField.layer.masksToBounds = true _textField.delegate = self _textField.scrollsToTop = false _textField.returnKeyType = .send _textField.backgroundColor = .clear _textField.scrollIndicatorInsets = UIEdgeInsets.init(top: 2, left: 0, bottom: 2, right: 0) _textField.translatesAutoresizingMaskIntoConstraints = false _textField.backgroundView.translatesAutoresizingMaskIntoConstraints = false _textField.typingAttributes[NSAttributedString.Key.paragraphStyle] = { let style = NSMutableParagraphStyle() style.lineBreakMode = .byCharWrapping return style }() _recordButton.isHidden = true _recordButton.layer.cornerRadius = 5 _recordButton.layer.borderWidth = 0.5 _recordButton.layer.borderColor = UIColor.gray.cgColor _recordButton.layer.masksToBounds = true _recordButton.setTitleColor(UIColor(netHex: 0x5A5A5A), for: .normal) _recordButton.titleLabel?.font = UIFont.systemFont(ofSize: 15) _recordButton.translatesAutoresizingMaskIntoConstraints = false _recordButton.setTitle("按住 说话", for: .normal) _recordButton.setTitle("松开 发送", for: .highlighted) _recordButton.setTitleColor(.black, for: .normal) _recordButton.addTarget(self, action: #selector(_touchDown), for: .touchDown) _recordButton.addTarget(self, action: #selector(_touchUpInside), for: .touchUpInside) _recordButton.addTarget(self, action: #selector(_touchUpOutside), for: .touchUpOutside) _recordButton.addTarget(self, action: #selector(_dragOutside), for: .touchDragExit) _recordButton.addTarget(self, action: #selector(_dragInside), for: .touchDragEnter) _collectionViewLayout.minimumLineSpacing = 8 _collectionViewLayout.minimumInteritemSpacing = 8 _collectionView.bounces = false _collectionView.scrollsToTop = false _collectionView.isScrollEnabled = false _collectionView.allowsSelection = false _collectionView.isMultipleTouchEnabled = false _collectionView.showsHorizontalScrollIndicator = false _collectionView.showsVerticalScrollIndicator = false _collectionView.delaysContentTouches = false _collectionView.canCancelContentTouches = false _collectionView.backgroundColor = .clear _collectionView.dataSource = self _collectionView.delegate = self _collectionView.translatesAutoresizingMaskIntoConstraints = false _collectionView.setContentHuggingPriority(UILayoutPriority(rawValue: 700), for: .horizontal) _collectionView.setContentHuggingPriority(UILayoutPriority(rawValue: 700), for: .vertical) _collectionView.setContentCompressionResistancePriority(UILayoutPriority(rawValue: 200), for: .horizontal) _collectionView.setContentCompressionResistancePriority(UILayoutPriority(rawValue: 200), for: .vertical) // update center bar item _setBarItems([], atPosition: .center) // adds a child view addSubview(_collectionView) addSubview(_textField.backgroundView) addSubview(_textField) addSubview(_recordButton) // adding constraints addConstraints([ _SAInputLayoutConstraintMake(_collectionView, .top, .equal, self, .top), _SAInputLayoutConstraintMake(_collectionView, .left, .equal, self, .left), _SAInputLayoutConstraintMake(_collectionView, .right, .equal, self, .right), _SAInputLayoutConstraintMake(_collectionView, .bottom, .equal, self, .bottom), _SAInputLayoutConstraintMake(_textField.backgroundView, .top, .equal, _textField, .top), _SAInputLayoutConstraintMake(_textField.backgroundView, .left, .equal, _textField, .left), _SAInputLayoutConstraintMake(_textField.backgroundView, .right, .equal, _textField, .right), _SAInputLayoutConstraintMake(_textField.backgroundView, .bottom, .equal, _textField, .bottom), _textFieldTop, _textFieldLeft, _textFieldRight, _textFieldBottom, _SAInputLayoutConstraintMake(_recordButton, .top, .equal, _textField, .top), _SAInputLayoutConstraintMake(_recordButton, .left, .equal, _textField, .left), _SAInputLayoutConstraintMake(_recordButton, .right, .equal, _textField, .right), _SAInputLayoutConstraintMake(_recordButton, .bottom, .equal, _textField, .bottom), ]) // init collection view (0 ..< numberOfSections(in: _collectionView)).forEach { _collectionView.register(SAIInputItemView.self, forCellWithReuseIdentifier: "Cell-\($0)") } } // click event @objc open func _touchDown() { delegate?.inputAccessoryView(touchDown: _recordButton) } @objc open func _touchUpInside() { delegate?.inputAccessoryView(touchUpInside: _recordButton) } @objc open func _touchUpOutside() { delegate?.inputAccessoryView(touchUpOutside: _recordButton) } @objc open func _dragOutside() { delegate?.inputAccessoryView(dragOutside: _recordButton) } @objc open func _dragInside() { delegate?.inputAccessoryView(dragInside: _recordButton) } private var _contentSizeWithoutCache: CGSize { let centerBarItemSize = _centerBarItem.size let height = _textFieldTop.constant + centerBarItemSize.height + _textFieldBottom.constant return CGSize(width: frame.width, height: height) } private var _contentInsetsWithoutCache: UIEdgeInsets { var contentInsets = _collectionViewLayout.contentInsets // merge the top let topSize = _collectionViewLayout.sizeThatFits(bounds.size, atPosition: .top) if topSize.height != 0 { contentInsets.top += topSize.height + _collectionViewLayout.minimumLineSpacing } // merge the left let leftSize = _collectionViewLayout.sizeThatFits(bounds.size, atPosition: .left) if leftSize.width != 0 { contentInsets.left += leftSize.width + _collectionViewLayout.minimumInteritemSpacing } // merge the right let rightSize = _collectionViewLayout.sizeThatFits(bounds.size, atPosition: .right) if rightSize.width != 0 { contentInsets.right += rightSize.width + _collectionViewLayout.minimumInteritemSpacing } // merge the bottom let bottomSize = _collectionViewLayout.sizeThatFits(bounds.size, atPosition: .bottom) if bottomSize.height != 0 { contentInsets.bottom += bottomSize.height + _collectionViewLayout.minimumLineSpacing } return contentInsets } // MARK: Ivar fileprivate lazy var _centerBarItem: SAIInputItem = self.textField.item fileprivate lazy var _barItems: [Int: [SAIInputItem]] = [:] fileprivate lazy var _cacheBarItems: [Int: [SAIInputItem]] = [:] fileprivate lazy var _selectedBarItems: Set<SAIInputItem> = [] fileprivate lazy var _textField: SAIInputTextField = SAIInputTextField() fileprivate lazy var _recordButton: UIButton = UIButton() fileprivate lazy var _collectionViewLayout: SAIInputAccessoryViewLayout = SAIInputAccessoryViewLayout() fileprivate lazy var _collectionView: UICollectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: self._collectionViewLayout) fileprivate lazy var _textFieldTop: NSLayoutConstraint = { return _SAInputLayoutConstraintMake(self._textField, .top, .equal, self, .top) }() fileprivate lazy var _textFieldLeft: NSLayoutConstraint = { return _SAInputLayoutConstraintMake(self._textField, .left, .equal, self, .left) }() fileprivate lazy var _textFieldRight: NSLayoutConstraint = { return _SAInputLayoutConstraintMake(self, .right, .equal, self._textField, .right) }() fileprivate lazy var _textFieldBottom: NSLayoutConstraint = { return _SAInputLayoutConstraintMake(self, .bottom, .equal, self._textField, .bottom) }() fileprivate var _cacheBounds: CGRect? fileprivate var _cacheContentSize: CGSize? fileprivate var _cacheContentInsets: UIEdgeInsets? fileprivate var _cacheBarItemContainer: UICollectionViewCell? required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) _init() } override init(frame: CGRect) { super.init(frame: frame) _init() } } // MARK: - SAIInputItemDelegate(Forwarding) extension SAIInputAccessoryView: SAIInputItemViewDelegate { func barItem(shouldHighlightFor barItem: SAIInputItem) -> Bool { return delegate?.barItem(shouldHighlightFor: barItem) ?? true } func barItem(shouldDeselectFor barItem: SAIInputItem) -> Bool { return delegate?.barItem(shouldDeselectFor: barItem) ?? false } func barItem(shouldSelectFor barItem: SAIInputItem) -> Bool { return delegate?.barItem(shouldSelectFor: barItem) ?? false } func barItem(didHighlightFor barItem: SAIInputItem) { delegate?.barItem(didHighlightFor: barItem) } func barItem(didDeselectFor barItem: SAIInputItem) { _selectedBarItems.remove(barItem) delegate?.barItem(didDeselectFor: barItem) } func barItem(didSelectFor barItem: SAIInputItem) { _selectedBarItems.insert(barItem) delegate?.barItem(didSelectFor: barItem) } } // MARK: - UITextViewDelegate(Forwarding) extension SAIInputAccessoryView: UITextViewDelegate { func textViewShouldBeginEditing(_ textView: UITextView) -> Bool { return delegate?.textViewShouldBeginEditing?(textView) ?? true } func textViewShouldEndEditing(_ textView: UITextView) -> Bool { return delegate?.textViewShouldEndEditing?(textView) ?? true } func textViewDidBeginEditing(_ textView: UITextView) { delegate?.textViewDidBeginEditing?(textView) } func textViewDidEndEditing(_ textView: UITextView) { delegate?.textViewDidEndEditing?(textView) } func textViewDidChangeSelection(_ textView: UITextView) { delegate?.textViewDidChangeSelection?(textView) } func textViewDidChange(_ textView: UITextView) { delegate?.textViewDidChange?(textView) _updateContentSizeForTextChanged(true) } func textView(_ textView: UITextView, shouldInteractWith textAttachment: NSTextAttachment, in characterRange: NSRange) -> Bool { return delegate?.textView?(textView, shouldInteractWith: textAttachment, in: characterRange) ?? true } func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool { return delegate?.textView?(textView, shouldChangeTextIn: range, replacementText: text) ?? true } func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange) -> Bool { return delegate?.textView?(textView, shouldInteractWith: URL, in: characterRange) ?? true } } // MARK: - UICollectionViewDataSource & UICollectionViewDelegateFlowLayout extension SAIInputAccessoryView: UICollectionViewDataSource, UICollectionViewDelegateFlowLayout { func numberOfSections(in collectionView: UICollectionView) -> Int { return 5 } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { if section == _SAInputAccessoryViewCenterSection { return 1 } return _barItems[section]?.count ?? 0 } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { return collectionView.dequeueReusableCell(withReuseIdentifier: "Cell-\((indexPath as NSIndexPath).section)", for: indexPath) } func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) { guard let cell = cell as? SAIInputItemView else { return } let item = _barItem(atIndexPath: indexPath) cell.delegate = self cell.item = item cell.setSelected(_selectedBarItems.contains(item), animated: false) cell.isHidden = (item == _textField.item) } } /// /// 比较数组差异 /// (+1, src.index, dest.index) // add /// ( 0, src.index, dest.index) // equal /// (-1, src.index, dest.index) // remove /// private func _diff<T: Equatable>(_ src: Array<T>, _ dest: Array<T>) -> Array<(Int, Int, Int)> { let len1 = src.count let len2 = dest.count var c = [[Int]](repeating: [Int](repeating: 0, count: len2 + 1), count: len1 + 1) // lcs + 动态规划 for i in 1 ..< len1 + 1 { for j in 1 ..< len2 + 1 { if src[i - 1] == dest[j - 1] { c[i][j] = c[i - 1][j - 1] + 1 } else { c[i][j] = max(c[i - 1][j], c[i][j - 1]) } } } var r = [(Int, Int, Int)]() var i = len1 var j = len2 // create the optimal path repeat { guard i != 0 else { // the remaining is add while j > 0 { r.append((+1, i - 1, j - 1)) j -= 1 } break } guard j != 0 else { // the remaining is remove while i > 0 { r.append((-1, i - 1, j - 1)) i -= 1 } break } guard src[i - 1] != dest[j - 1] else { // no change r.append((0, i - 1, j - 1)) i -= 1 j -= 1 continue } // check the weight if c[i - 1][j] > c[i][j - 1] { // is remove r.append((-1, i - 1, j - 1)) i -= 1 } else { // is add r.append((+1, i - 1, j - 1)) j -= 1 } } while i > 0 || j > 0 return r.reversed() } private let _SAInputAccessoryViewCenterSection = SAIInputItemPosition.center.rawValue public let SAIAccessoryDidChangeFrameNotification = "SAIAccessoryDidChangeFrameNotification" // Helper function inserted by Swift 4.2 migrator. fileprivate func convertFromNSAttributedStringKeyDictionary(_ input: [NSAttributedString.Key: Any]) -> [String: Any] { return Dictionary(uniqueKeysWithValues: input.map {key, value in (key.rawValue, value)}) } // Helper function inserted by Swift 4.2 migrator. fileprivate func convertFromNSAttributedStringKey(_ input: NSAttributedString.Key) -> String { return input.rawValue }
mit
12c6cc50088ce9e2752a42f6d9e8d3b9
37.026906
147
0.628774
5.05866
false
false
false
false
PureSwift/Bluetooth
Tests/BluetoothTests/L2CAPSocket.swift
1
4794
// // L2CAPSocket.swift // BluetoothTests // // Created by Alsey Coleman Miller on 3/30/18. // Copyright © 2018 PureSwift. All rights reserved. // #if canImport(BluetoothGATT) import Foundation @testable import Bluetooth @testable import BluetoothGATT /// Test L2CAP socket internal actor TestL2CAPSocket: L2CAPSocket { private actor Cache { static let shared = Cache() private init() { } var pendingClients = [BluetoothAddress: [TestL2CAPSocket]]() func queue(client socket: TestL2CAPSocket, server: BluetoothAddress) { pendingClients[server, default: []].append(socket) } func dequeue(server: BluetoothAddress) -> TestL2CAPSocket? { guard let socket = pendingClients[server]?.first else { return nil } pendingClients[server]?.removeFirst() return socket } } static func lowEnergyClient( address: BluetoothAddress, destination: BluetoothAddress, isRandom: Bool ) async throws -> TestL2CAPSocket { let socket = TestL2CAPSocket( address: address, name: "Client" ) print("Client \(address) will connect to \(destination)") // append to pending clients await Cache.shared.queue(client: socket, server: destination) // wait until client has connected while await (Cache.shared.pendingClients[destination] ?? []).contains(where: { $0 === socket }) { try await Task.sleep(nanoseconds: 10_000_000) } return socket } static func lowEnergyServer( address: BluetoothAddress, isRandom: Bool, backlog: Int ) async throws -> TestL2CAPSocket { return TestL2CAPSocket( address: address, name: "Server" ) } // MARK: - Properties let name: String let address: BluetoothAddress public let event: L2CAPSocketEventStream private var eventContinuation: L2CAPSocketEventStream.Continuation! /// The socket's security level. private(set) var securityLevel: SecurityLevel = .sdp /// Attempts to change the socket's security level. func setSecurityLevel(_ securityLevel: SecurityLevel) async throws { self.securityLevel = securityLevel } /// Target socket. private weak var target: TestL2CAPSocket? fileprivate(set) var receivedData = [Data]() private(set) var cache = [Data]() // MARK: - Initialization private init( address: BluetoothAddress = .zero, name: String ) { self.address = address self.name = name var continuation: L2CAPSocketEventStream.Continuation! self.event = L2CAPSocketEventStream { continuation = $0 } self.eventContinuation = continuation } // MARK: - Methods func accept() async throws -> TestL2CAPSocket { // sleep until a client socket is created while (await Cache.shared.pendingClients[address] ?? []).isEmpty { try await Task.sleep(nanoseconds: 10_000_000) } let client = await Cache.shared.dequeue(server: address)! let newConnection = TestL2CAPSocket(address: client.address, name: "Server connection") // connect sockets await newConnection.connect(to: client) await client.connect(to: newConnection) return newConnection } /// Write to the socket. func send(_ data: Data) async throws { print("L2CAP Socket: \(name) will send \(data.count) bytes") guard let target = self.target else { throw POSIXError(.ECONNRESET) } await target.receive(data) eventContinuation.yield(.write(data.count)) } /// Reads from the socket. func recieve(_ bufferSize: Int) async throws -> Data { print("L2CAP Socket: \(name) will read \(bufferSize) bytes") while self.receivedData.isEmpty { guard self.target != nil else { throw POSIXError(.ECONNRESET) } try await Task.sleep(nanoseconds: 100_000_000) } let data = self.receivedData.removeFirst() cache.append(data) eventContinuation.yield(.read(data.count)) return data } fileprivate func receive(_ data: Data) { receivedData.append(data) print("L2CAP Socket: \(name) recieved \([UInt8](data))") eventContinuation.yield(.pendingRead) } internal func connect(to socket: TestL2CAPSocket) { self.target = socket } } #endif
mit
422fcfee1ed7e49b87d2a6192e53dfa1
28.58642
105
0.598999
4.689824
false
true
false
false
jjatie/Charts
Source/Charts/Renderers/Scatter/CircleShapeRenderer.swift
1
2106
// // CircleShapeRenderer.swift // Charts // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/Charts // import CoreGraphics import Foundation open class CircleShapeRenderer: ShapeRenderer { open func renderShape( context: CGContext, dataSet: ScatterChartDataSet, viewPortHandler _: ViewPortHandler, point: CGPoint, color: NSUIColor ) { let shapeSize = dataSet.scatterShapeSize let shapeHalf = shapeSize / 2.0 let shapeHoleSizeHalf = dataSet.scatterShapeHoleRadius let shapeHoleSize = shapeHoleSizeHalf * 2.0 let shapeHoleColor = dataSet.scatterShapeHoleColor let shapeStrokeSize = (shapeSize - shapeHoleSize) / 2.0 let shapeStrokeSizeHalf = shapeStrokeSize / 2.0 if shapeHoleSize > 0.0 { context.setStrokeColor(color.cgColor) context.setLineWidth(shapeStrokeSize) var rect = CGRect() rect.origin.x = point.x - shapeHoleSizeHalf - shapeStrokeSizeHalf rect.origin.y = point.y - shapeHoleSizeHalf - shapeStrokeSizeHalf rect.size.width = shapeHoleSize + shapeStrokeSize rect.size.height = shapeHoleSize + shapeStrokeSize context.strokeEllipse(in: rect) if let shapeHoleColor = shapeHoleColor { context.setFillColor(shapeHoleColor.cgColor) rect.origin.x = point.x - shapeHoleSizeHalf rect.origin.y = point.y - shapeHoleSizeHalf rect.size.width = shapeHoleSize rect.size.height = shapeHoleSize context.fillEllipse(in: rect) } } else { context.setFillColor(color.cgColor) var rect = CGRect() rect.origin.x = point.x - shapeHalf rect.origin.y = point.y - shapeHalf rect.size.width = shapeSize rect.size.height = shapeSize context.fillEllipse(in: rect) } } }
apache-2.0
7bbd3e6fdf84b6b65f58f673304fc58a
35.310345
77
0.625356
5.161765
false
false
false
false
Dhvl-Golakiya/DGSnackbar
Example/DGSnackbar/ViewController.swift
1
2877
// // ViewController.swift // DGSnackbar // // Created by Dhaval Golakiya on 11/18/2015. // Copyright (c) 2015 Dhaval Golakiya. All rights reserved. // import UIKit import DGSnackbar class ViewController: UIViewController , UITableViewDelegate, UITableViewDataSource { var fruitsArray = [String]() @IBOutlet weak var fruitListTableView: UITableView! override func viewDidLoad() { super.viewDidLoad() fruitsArray = ["Apple","Banana","Cherry","Grape","Guava","Mango","Orange","Pepper","Pineapple", "Strawberry"] fruitListTableView.reloadData() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func numberOfSectionsInTableView(tableView: UITableView) -> Int { // 1 return 1 } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // 2 return fruitsArray.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { // 3 let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as UITableViewCell cell.textLabel?.text = fruitsArray[indexPath.row] return cell } func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { let fruitName = fruitsArray[indexPath.row] self.fruitsArray.removeAtIndex(indexPath.row) self.fruitListTableView.reloadData() DGSnackbar().makeSnackbar(fruitName + " removed", actionButtonImage: UIImage(named: "ic_done_white"), interval: 3, actionButtonBlock: {action in self.fruitsArray.insert(fruitName, atIndex: indexPath.row) self.fruitListTableView.reloadData() }, dismisBlock: {acion in }) // DGSnackbar.makeSnackbar(fruitName + " removed", actionButtonImage: UIImage(named: "ic_done_white"), interval: 3, actionButtonBlock: {action in // self.fruitsArray.insert(fruitName, atIndex: indexPath.row) // self.fruitListTableView.reloadData() // }, dismisBlock: {acion in // }) // DGSnackbar().makeSnackbar(fruitName + " removed", actionButtonTitle: "Undo", interval: 3, actionButtonBlock: {action in // self.fruitsArray.insert(fruitName, atIndex: indexPath.row) // self.fruitListTableView.reloadData() // }, dismisBlock: {acion in // // }) } }
mit
2fef6ad5e12cbb5557dd939abfa1e08c
37.36
160
0.626694
4.994792
false
false
false
false
ifrins/Snappr
Snappr/Services/WallpaperChangerService.swift
1
12231
// // WallpaperChangerService.swift // Snappr // // Created by Francesc Bruguera on 8/7/16. // Copyright © 2016 Snappr. All rights reserved. // import Foundation @objc public class WallpaperChangerService : NSObject { private var timer: NSTimer? private var plannedFireDate: NSDate? static let sharedChanger = WallpaperChangerService() override private init() { super.init() let notificationCenter = NSWorkspace.sharedWorkspace().notificationCenter notificationCenter.addObserver(self, selector: #selector(willSleep), name: NSWorkspaceWillSleepNotification, object: nil) notificationCenter.addObserver(self, selector: #selector(willWake), name: NSWorkspaceDidWakeNotification, object: nil) notificationCenter.addObserver(self, selector: #selector(checkIfSpaceNeedsWallpaper), name: NSWorkspaceActiveSpaceDidChangeNotification, object: nil) scheduleInitialChange() } func nextWallpaper() { print("Next wallpaper…") SRStatistical.sharedStatitical.trackEvent(.WALLPAPER_CHANGE) let globalQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0) dispatch_async(globalQueue, { var attempts = 0 self.cleanOldFiles() while attempts < 5 { let changedImage = self.changeImage() if !changedImage { attempts += 1 } else { break } } }) } func changeTimerWithNewRepetition(seconds: NSTimeInterval) { if timer != nil && timer!.valid { let remaining = timer!.fireDate.timeIntervalSinceNow let newInterval = seconds - remaining timer = NSTimer.scheduledTimerWithTimeInterval(newInterval, target: self, selector: #selector(nextWallpaperFromTimer), userInfo: nil, repeats: false) } else { timer = NSTimer.scheduledTimerWithTimeInterval(seconds, target: self, selector: #selector(nextWallpaperFromTimer), userInfo: nil, repeats: false) } } private func cleanOldFiles() { let dirPath = SRSettings.imagesPath let pathURL = NSURL(fileURLWithPath: dirPath, isDirectory: true) let fileManager = NSFileManager.defaultManager() let dirFiles = try! fileManager.contentsOfDirectoryAtURL(pathURL, includingPropertiesForKeys: [NSURLContentModificationDateKey], options: .SkipsHiddenFiles) let deletionTarget = NSTimeInterval(5 * 24 * 3600) for file in dirFiles { var modificationDateRaw: AnyObject? try! file.getResourceValue(&modificationDateRaw, forKey: NSURLContentModificationDateKey) if file.pathExtension! == "plist" { continue } let modificationDate = modificationDateRaw as! NSDate! let timeInterval = NSDate().timeIntervalSinceDate(modificationDate) if timeInterval >= deletionTarget { try? NSFileManager.defaultManager().removeItemAtURL(file) } } } private func changeImage() -> Bool { let images: [RedditImage] = getAllImages() let minimumSize = getMinimumSize() var imageDataToUse: NSImage? = nil var imageToUse: RedditImage? = nil for refImage in images { let imageShown = hasImageBeenShown(refImage) var imageSizeSupported = true let inferredResolution = refImage.resolution if inferredResolution != nil { imageSizeSupported = sizeWillSupportScreenSize(inferredResolution!, screenResolution: minimumSize) } if imageShown || !imageSizeSupported { continue } let proveImage = refImage.getImage() if proveImage == nil { continue } let realSize = proveImage!.size let appropiateSize = sizeWillSupportScreenSize(realSize, screenResolution: minimumSize) if appropiateSize { imageToUse = refImage imageDataToUse = proveImage! break } } if imageDataToUse != nil && imageToUse != nil { setImageAsWallpaper(imageToUse!, imageData: imageDataToUse!) return true } return false } private func setImageAsWallpaper(refImage: RedditImage, imageData: NSImage) { let queue = dispatch_get_main_queue() let imagesPath = SRSettings.imagesPath let imgRep = imageData.representations[0] as! NSBitmapImageRep let imageData = imgRep.representationUsingType(.PNG, properties: [:]) let imageHash = refImage.getHash() let filePath = imagesPath.stringByAppendingString("/\(imageHash).png") let fileURL = NSURL(fileURLWithPath: filePath) imageData?.writeToURL(fileURL, atomically: true) dispatch_async(queue, { let screens = NSScreen.screens() for screen in screens! { try? NSWorkspace.sharedWorkspace().setDesktopImageURL(fileURL, forScreen: screen, options: [:]) SRSubredditDataStore.sharedDatastore().currentImage = refImage SRSettings.lastUpdated = NSDate() } self.sendNotificationForImage(refImage) self.scheduleNewChange() }) } private func sendNotificationForImage(image: RedditImage) { let imageUrl = image.redditURL if imageUrl != nil { let imageLink = imageUrl!.description let notification = NSUserNotification() notification.title = image.title notification.informativeText = NSLocalizedString("New Wallpaper", comment: "New wallpaper notification test") notification.userInfo = ["link" : imageLink] NSUserNotificationCenter.defaultUserNotificationCenter().deliverNotification(notification) } } private func sizeWillSupportScreenSize(realSize: NSSize, screenResolution: NSSize) -> Bool { return realSize.width >= screenResolution.width && realSize.height >= screenResolution.height } private func scheduleNewChange() { let timeInterval = SRSettings.refreshFrequency timer?.invalidate() timer = NSTimer.scheduledTimerWithTimeInterval(timeInterval, target: self, selector: #selector(nextWallpaperFromTimer), userInfo: nil, repeats: false) timer!.tolerance = 60 } private func scheduleInitialChange() { let lastUpdate = SRSettings.lastUpdated let lastUpdateDelta = lastUpdate.timeIntervalSinceNow let updateInterval = SRSettings.refreshFrequency if lastUpdateDelta > updateInterval { nextWallpaper() } else { let newTimeInterval = updateInterval - lastUpdateDelta timer?.invalidate() timer = NSTimer.scheduledTimerWithTimeInterval(newTimeInterval, target: self, selector: #selector(nextWallpaperFromTimer), userInfo: nil, repeats: false) } } private func hasImageBeenShown(image: RedditImage) -> Bool { let basePath = SRSettings.imagesPath let imageHash = image.getHash() let path = basePath.stringByAppendingString("/\(imageHash).png") return NSFileManager.defaultManager().fileExistsAtPath(path) } private func getAllImages() -> [RedditImage] { var allImages: [RedditImage] = [] let subreddits = SRSubredditDataStore.sharedDatastore().subredditArray as! [String] for subreddit in subreddits { let subredditImages = SRRedditParser.sharedParser().getImagesFor(subreddit) allImages.appendContentsOf(subredditImages) } allImages.shuffle() let immutableList = allImages return immutableList } private func getMinimumSize() -> NSSize { var maxWidth = CGFloat(0) var maxHeight = CGFloat(0) let screens = NSScreen.screens()! for screen in screens { let screenRect = screen.convertRectFromBacking(screen.frame) let screenSize = screenRect.size if screenSize.height > maxHeight { maxHeight = screenSize.height } if screenSize.width > maxWidth { maxWidth = screenSize.width } } return NSSize(width: maxWidth, height: maxHeight) } @objc public func willSleep(notification: NSNotification) { if timer != nil && timer!.valid { plannedFireDate = timer?.fireDate timer?.invalidate() } } @objc public func willWake(notification: NSNotification) { let timeInterval = plannedFireDate?.timeIntervalSinceNow if timeInterval == nil { return } if timeInterval <= 0 { nextWallpaperFromTimer() } else { timer = NSTimer.scheduledTimerWithTimeInterval(timeInterval!, target: self, selector: #selector(nextWallpaperFromTimer), userInfo: nil, repeats: false); } } @objc func checkIfSpaceNeedsWallpaper() { let currentImage = SRSubredditDataStore.sharedDatastore().currentImage if currentImage != nil && SRSettings.changeAllSpaces { let screens = NSScreen.screens()! let path = currentImage.getFilePath() let fileURL = NSURL(fileURLWithPath: path) let workspace = NSWorkspace.sharedWorkspace() for screen in screens { let screenImageURL = workspace.desktopImageURLForScreen(screen)! if screenImageURL != fileURL { try? workspace.setDesktopImageURL(fileURL, forScreen: screen, options: [:]) } } } } @objc private func nextWallpaperFromTimer() { nextWallpaper() } }
mit
8e79ee9a9e00a7058b657f9e66a38784
36.975155
164
0.518237
6.57773
false
false
false
false
itsaboutcode/WordPress-iOS
WordPress/Classes/ViewRelated/Post/PostListViewController.swift
1
35757
import Foundation import CocoaLumberjack import WordPressShared import Gridicons // FIXME: comparison operators with optionals were removed from the Swift Standard Libary. // Consider refactoring the code to use the non-optional operators. fileprivate func < <T: Comparable>(lhs: T?, rhs: T?) -> Bool { switch (lhs, rhs) { case let (l?, r?): return l < r case (nil, _?): return true default: return false } } // FIXME: comparison operators with optionals were removed from the Swift Standard Libary. // Consider refactoring the code to use the non-optional operators. fileprivate func > <T: Comparable>(lhs: T?, rhs: T?) -> Bool { switch (lhs, rhs) { case let (l?, r?): return l > r default: return rhs < lhs } } class PostListViewController: AbstractPostListViewController, UIViewControllerRestoration, InteractivePostViewDelegate { private let postCompactCellIdentifier = "PostCompactCellIdentifier" private let postCardTextCellIdentifier = "PostCardTextCellIdentifier" private let postCardRestoreCellIdentifier = "PostCardRestoreCellIdentifier" private let postCompactCellNibName = "PostCompactCell" private let postCardTextCellNibName = "PostCardCell" private let postCardRestoreCellNibName = "RestorePostTableViewCell" private let statsStoryboardName = "SiteStats" private let currentPostListStatusFilterKey = "CurrentPostListStatusFilterKey" private var postCellIdentifier: String { return isCompact || isSearching() ? postCompactCellIdentifier : postCardTextCellIdentifier } static private let postsViewControllerRestorationKey = "PostsViewControllerRestorationKey" private let statsCacheInterval = TimeInterval(300) // 5 minutes private let postCardEstimatedRowHeight = CGFloat(300.0) private let postListHeightForFooterView = CGFloat(50.0) @IBOutlet var searchWrapperView: UIView! @IBOutlet weak var filterTabBarTopConstraint: NSLayoutConstraint! @IBOutlet weak var filterTabBariOS10TopConstraint: NSLayoutConstraint! @IBOutlet weak var filterTabBarBottomConstraint: NSLayoutConstraint! @IBOutlet weak var tableViewTopConstraint: NSLayoutConstraint! private var database: KeyValueDatabase = UserDefaults.standard private lazy var _tableViewHandler: PostListTableViewHandler = { let tableViewHandler = PostListTableViewHandler(tableView: tableView) tableViewHandler.cacheRowHeights = false tableViewHandler.delegate = self tableViewHandler.updateRowAnimation = .none return tableViewHandler }() override var tableViewHandler: WPTableViewHandler { get { return _tableViewHandler } set { super.tableViewHandler = newValue } } private var postViewIcon: UIImage? { return isCompact ? UIImage(named: "icon-post-view-card") : .gridicon(.listUnordered) } private lazy var postActionSheet: PostActionSheet = { return PostActionSheet(viewController: self, interactivePostViewDelegate: self) }() private lazy var postsViewButtonItem: UIBarButtonItem = { return UIBarButtonItem(image: postViewIcon, style: .done, target: self, action: #selector(togglePostsView)) }() private var showingJustMyPosts: Bool { return filterSettings.currentPostAuthorFilter() == .mine } private var isCompact: Bool = false { didSet { database.set(isCompact, forKey: Constants.exhibitionModeKey) showCompactOrDefault() } } // MARK: - Convenience constructors @objc class func controllerWithBlog(_ blog: Blog) -> PostListViewController { let storyBoard = UIStoryboard(name: "Posts", bundle: Bundle.main) let controller = storyBoard.instantiateViewController(withIdentifier: "PostListViewController") as! PostListViewController controller.blog = blog controller.restorationClass = self return controller } // MARK: - UIViewControllerRestoration class func viewController(withRestorationIdentifierPath identifierComponents: [String], coder: NSCoder) -> UIViewController? { let context = ContextManager.sharedInstance().mainContext guard let blogID = coder.decodeObject(forKey: postsViewControllerRestorationKey) as? String, let objectURL = URL(string: blogID), let objectID = context.persistentStoreCoordinator?.managedObjectID(forURIRepresentation: objectURL), let restoredBlog = (try? context.existingObject(with: objectID)) as? Blog else { return nil } return self.controllerWithBlog(restoredBlog) } // MARK: - UIStateRestoring override func encodeRestorableState(with coder: NSCoder) { let objectString = blog?.objectID.uriRepresentation().absoluteString coder.encode(objectString, forKey: type(of: self).postsViewControllerRestorationKey) super.encodeRestorableState(with: coder) } // MARK: - UIViewController override func prepare(for segue: UIStoryboardSegue, sender: Any?) { precondition(segue.destination is UITableViewController) super.refreshNoResultsViewController = { [weak self] noResultsViewController in self?.handleRefreshNoResultsViewController(noResultsViewController) } super.tableViewController = (segue.destination as! UITableViewController) } override func viewDidLoad() { super.viewDidLoad() title = NSLocalizedString("Blog Posts", comment: "Title of the screen showing the list of posts for a blog.") configureFilterBarTopConstraint() updateGhostableTableViewOptions() configureNavigationButtons() createButtonCoordinator.add(to: view, trailingAnchor: view.safeAreaLayoutGuide.trailingAnchor, bottomAnchor: view.safeAreaLayoutGuide.bottomAnchor) } private lazy var createButtonCoordinator: CreateButtonCoordinator = { var actions: [ActionSheetItem] = [ PostAction(handler: { [weak self] in self?.dismiss(animated: false, completion: nil) self?.createPost() }, source: Constants.source) ] if blog.supports(.stories) { actions.insert(StoryAction(handler: { [weak self] in guard let self = self else { return } (self.tabBarController as? WPTabBarController)?.showStoryEditor(blog: self.blog, title: nil, content: nil) }, source: Constants.source), at: 0) } return CreateButtonCoordinator(self, actions: actions, source: Constants.source) }() override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) if traitCollection.horizontalSizeClass == .compact { createButtonCoordinator.showCreateButton(for: blog) } } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) configureCompactOrDefault() } override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) { super.traitCollectionDidChange(previousTraitCollection) if traitCollection.horizontalSizeClass == .compact { createButtonCoordinator.showCreateButton(for: blog) } else { createButtonCoordinator.hideCreateButton() } } func configureNavigationButtons() { navigationItem.rightBarButtonItems = [postsViewButtonItem] } @objc func togglePostsView() { isCompact.toggle() WPAppAnalytics.track(.postListToggleButtonPressed, withProperties: ["mode": isCompact ? Constants.compact: Constants.card]) } // MARK: - Configuration override func heightForFooterView() -> CGFloat { return postListHeightForFooterView } func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { guard _tableViewHandler.isSearching else { return 0.0 } return Constants.searchHeaderHeight } func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView! { guard _tableViewHandler.isSearching, let headerView = tableView.dequeueReusableHeaderFooterView(withIdentifier: ActivityListSectionHeaderView.identifier) as? ActivityListSectionHeaderView else { return UIView(frame: .zero) } let sectionInfo = _tableViewHandler.resultsController.sections?[section] if let sectionInfo = sectionInfo { headerView.titleLabel.text = PostSearchHeader.title(forStatus: sectionInfo.name) } return headerView } private func configureFilterBarTopConstraint() { filterTabBariOS10TopConstraint.isActive = false } override func selectedFilterDidChange(_ filterBar: FilterTabBar) { updateGhostableTableViewOptions() super.selectedFilterDidChange(filterBar) } override func refresh(_ sender: AnyObject) { updateGhostableTableViewOptions() super.refresh(sender) } /// Update the `GhostOptions` to correctly show compact or default cells private func updateGhostableTableViewOptions() { let ghostOptions = GhostOptions(displaysSectionHeader: false, reuseIdentifier: postCellIdentifier, rowsPerSection: [50]) let style = GhostStyle(beatDuration: GhostStyle.Defaults.beatDuration, beatStartColor: .placeholderElement, beatEndColor: .placeholderElementFaded) ghostableTableView.removeGhostContent() ghostableTableView.displayGhostContent(options: ghostOptions, style: style) } private func configureCompactOrDefault() { isCompact = database.object(forKey: Constants.exhibitionModeKey) as? Bool ?? false } override func configureTableView() { tableView.accessibilityIdentifier = "PostsTable" tableView.separatorStyle = .none tableView.estimatedRowHeight = postCardEstimatedRowHeight tableView.rowHeight = UITableView.automaticDimension tableView.separatorStyle = .none let bundle = Bundle.main // Register the cells let postCardTextCellNib = UINib(nibName: postCardTextCellNibName, bundle: bundle) tableView.register(postCardTextCellNib, forCellReuseIdentifier: postCardTextCellIdentifier) let postCompactCellNib = UINib(nibName: postCompactCellNibName, bundle: bundle) tableView.register(postCompactCellNib, forCellReuseIdentifier: postCompactCellIdentifier) let postCardRestoreCellNib = UINib(nibName: postCardRestoreCellNibName, bundle: bundle) tableView.register(postCardRestoreCellNib, forCellReuseIdentifier: postCardRestoreCellIdentifier) let headerNib = UINib(nibName: ActivityListSectionHeaderView.identifier, bundle: nil) tableView.register(headerNib, forHeaderFooterViewReuseIdentifier: ActivityListSectionHeaderView.identifier) WPStyleGuide.configureColors(view: view, tableView: tableView) } override func configureGhostableTableView() { super.configureGhostableTableView() ghostingEnabled = true // Register the cells let postCardTextCellNib = UINib(nibName: postCardTextCellNibName, bundle: Bundle.main) ghostableTableView.register(postCardTextCellNib, forCellReuseIdentifier: postCardTextCellIdentifier) let postCompactCellNib = UINib(nibName: postCompactCellNibName, bundle: Bundle.main) ghostableTableView.register(postCompactCellNib, forCellReuseIdentifier: postCompactCellIdentifier) } override func configureAuthorFilter() { guard filterSettings.canFilterByAuthor() else { return } let authorFilter = AuthorFilterButton() authorFilter.addTarget(self, action: #selector(showAuthorSelectionPopover(_:)), for: .touchUpInside) filterTabBar.accessoryView = authorFilter updateAuthorFilter() } override func configureSearchController() { super.configureSearchController() searchWrapperView.addSubview(searchController.searchBar) tableView.verticalScrollIndicatorInsets.top = searchController.searchBar.bounds.height updateTableHeaderSize() } fileprivate func updateTableHeaderSize() { if searchController.isActive { // Account for the search bar being moved to the top of the screen. searchWrapperView.frame.size.height = 0 } else { searchWrapperView.frame.size.height = searchController.searchBar.bounds.height } // Resetting the tableHeaderView is necessary to get the new height to take effect tableView.tableHeaderView = searchWrapperView } func showCompactOrDefault() { updateGhostableTableViewOptions() postsViewButtonItem.accessibilityLabel = NSLocalizedString("List style", comment: "The accessibility label for the list style button in the Post List.") postsViewButtonItem.accessibilityValue = isCompact ? NSLocalizedString("Compact", comment: "Accessibility indication that the current Post List style is currently Compact.") : NSLocalizedString("Expanded", comment: "Accessibility indication that the current Post List style is currently Expanded.") postsViewButtonItem.image = postViewIcon if isViewOnScreen() { tableView.reloadSections([0], with: .automatic) ghostableTableView.reloadSections([0], with: .automatic) } } // Mark - Layout Methods override func willTransition(to newCollection: UITraitCollection, with coordinator: UIViewControllerTransitionCoordinator) { // Need to reload the table alongside a traitCollection change. // This is mainly because we target Reg W and Any H vs all other size classes. // If we transition between the two, the tableView may not update the cell heights accordingly. // Brent C. Aug 3/2016 coordinator.animate(alongsideTransition: { context in if self.isViewLoaded { self.tableView.reloadData() } }) } // MARK: - Sync Methods override func postTypeToSync() -> PostServiceType { return .post } override func lastSyncDate() -> Date? { return blog?.lastPostsSync } // MARK: - Actions @objc private func showAuthorSelectionPopover(_ sender: UIView) { let filterController = AuthorFilterViewController(initialSelection: filterSettings.currentPostAuthorFilter(), gravatarEmail: blog.account?.email) { [weak self] filter in if filter != self?.filterSettings.currentPostAuthorFilter() { UIAccessibility.post(notification: UIAccessibility.Notification.screenChanged, argument: sender) } self?.filterSettings.setCurrentPostAuthorFilter(filter) self?.updateAuthorFilter() self?.refreshAndReload() self?.syncItemsWithUserInteraction(false) self?.dismiss(animated: true) } ForcePopoverPresenter.configurePresentationControllerForViewController(filterController, presentingFromView: sender) filterController.popoverPresentationController?.permittedArrowDirections = .up present(filterController, animated: true) } private func updateAuthorFilter() { guard let accessoryView = filterTabBar.accessoryView as? AuthorFilterButton else { return } if filterSettings.currentPostAuthorFilter() == .everyone { accessoryView.filterType = .everyone } else { accessoryView.filterType = .user(gravatarEmail: blog.account?.email) } } // MARK: - Data Model Interaction /// Retrieves the post object at the specified index path. /// /// - Parameter indexPath: the index path of the post object to retrieve. /// /// - Returns: the requested post. /// fileprivate func postAtIndexPath(_ indexPath: IndexPath) -> Post { guard let post = tableViewHandler.resultsController.object(at: indexPath) as? Post else { // Retrieving anything other than a post object means we have an App with an invalid // state. Ignoring this error would be counter productive as we have no idea how this // can affect the App. This controlled interruption is intentional. // // - Diego Rey Mendez, May 18 2016 // fatalError("Expected a post object.") } return post } // MARK: - TableViewHandler override func entityName() -> String { return String(describing: Post.self) } override func predicateForFetchRequest() -> NSPredicate { var predicates = [NSPredicate]() if let blog = blog { // Show all original posts without a revision & revision posts. let basePredicate = NSPredicate(format: "blog = %@ && revision = nil", blog) predicates.append(basePredicate) } let searchText = currentSearchTerm() ?? "" let filterPredicate = searchController.isActive ? NSPredicate(format: "postTitle CONTAINS[cd] %@", searchText) : filterSettings.currentPostListFilter().predicateForFetchRequest // If we have recently trashed posts, create an OR predicate to find posts matching the filter, // or posts that were recently deleted. if searchText.count == 0 && recentlyTrashedPostObjectIDs.count > 0 { let trashedPredicate = NSPredicate(format: "SELF IN %@", recentlyTrashedPostObjectIDs) predicates.append(NSCompoundPredicate(orPredicateWithSubpredicates: [filterPredicate, trashedPredicate])) } else { predicates.append(filterPredicate) } if filterSettings.shouldShowOnlyMyPosts() { let myAuthorID = blogUserID() ?? 0 // Brand new local drafts have an authorID of 0. let authorPredicate = NSPredicate(format: "authorID = %@ || authorID = 0", myAuthorID) predicates.append(authorPredicate) } if searchText.count > 0 { let searchPredicate = NSPredicate(format: "postTitle CONTAINS[cd] %@", searchText) predicates.append(searchPredicate) } let predicate = NSCompoundPredicate(andPredicateWithSubpredicates: predicates) return predicate } // MARK: - Table View Handling override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) let post = postAtIndexPath(indexPath) guard post.status != .trash else { // No editing posts that are trashed. return } editPost(apost: post) } @objc func tableView(_ tableView: UITableView, cellForRowAtIndexPath indexPath: IndexPath) -> UITableViewCell { if let windowlessCell = dequeCellForWindowlessLoadingIfNeeded(tableView) { return windowlessCell } let post = postAtIndexPath(indexPath) let identifier = cellIdentifierForPost(post) let cell = tableView.dequeueReusableCell(withIdentifier: identifier, for: indexPath) configureCell(cell, at: indexPath) return cell } override func configureCell(_ cell: UITableViewCell, at indexPath: IndexPath) { cell.accessoryType = .none let post = postAtIndexPath(indexPath) guard let interactivePostView = cell as? InteractivePostView, let configurablePostView = cell as? ConfigurablePostView else { fatalError("Cell does not implement the required protocols") } interactivePostView.setInteractionDelegate(self) interactivePostView.setActionSheetDelegate?(self) configurablePostView.configure(with: post) configurePostCell(cell) configureRestoreCell(cell) } fileprivate func cellIdentifierForPost(_ post: Post) -> String { var identifier: String if recentlyTrashedPostObjectIDs.contains(post.objectID) == true && filterSettings.currentPostListFilter().filterType != .trashed { identifier = postCardRestoreCellIdentifier } else { identifier = postCellIdentifier } return identifier } private func configurePostCell(_ cell: UITableViewCell) { guard let cell = cell as? PostCardCell else { return } cell.shouldHideAuthor = showingJustMyPosts } private func configureRestoreCell(_ cell: UITableViewCell) { guard let cell = cell as? RestorePostTableViewCell else { return } cell.isCompact = isCompact } // MARK: - Post Actions override func createPost() { let editor = EditPostViewController(blog: blog) editor.modalPresentationStyle = .fullScreen present(editor, animated: false, completion: nil) WPAppAnalytics.track(.editorCreatedPost, withProperties: [WPAppAnalyticsKeyTapSource: "posts_view", WPAppAnalyticsKeyPostType: "post"], with: blog) } private func editPost(apost: AbstractPost) { guard let post = apost as? Post else { return } guard !PostCoordinator.shared.isUploading(post: post) else { presentAlertForPostBeingUploaded() return } PostListEditorPresenter.handle(post: post, in: self) } private func editDuplicatePost(apost: AbstractPost) { guard let post = apost as? Post else { return } PostListEditorPresenter.handleCopy(post: post, in: self) } func presentAlertForPostBeingUploaded() { let message = NSLocalizedString("This post is currently uploading. It won't take long – try again soon and you'll be able to edit it.", comment: "Prompts the user that the post is being uploaded and cannot be edited while that process is ongoing.") let alertCancel = NSLocalizedString("OK", comment: "Title of an OK button. Pressing the button acknowledges and dismisses a prompt.") let alertController = UIAlertController(title: nil, message: message, preferredStyle: .alert) alertController.addCancelActionWithTitle(alertCancel, handler: nil) alertController.presentFromRootViewController() } override func promptThatPostRestoredToFilter(_ filter: PostListFilter) { var message = NSLocalizedString("Post Restored to Drafts", comment: "Prompts the user that a restored post was moved to the drafts list.") switch filter.filterType { case .published: message = NSLocalizedString("Post Restored to Published", comment: "Prompts the user that a restored post was moved to the published list.") break case .scheduled: message = NSLocalizedString("Post Restored to Scheduled", comment: "Prompts the user that a restored post was moved to the scheduled list.") break default: break } let alertCancel = NSLocalizedString("OK", comment: "Title of an OK button. Pressing the button acknowledges and dismisses a prompt.") let alertController = UIAlertController(title: nil, message: message, preferredStyle: .alert) alertController.addCancelActionWithTitle(alertCancel, handler: nil) alertController.presentFromRootViewController() } fileprivate func viewStatsForPost(_ apost: AbstractPost) { // Check the blog let blog = apost.blog guard blog.supports(.stats) else { // Needs Jetpack. return } WPAnalytics.track(.postListStatsAction, withProperties: propertiesForAnalytics()) // Push the Post Stats ViewController guard let postID = apost.postID as? Int else { return } SiteStatsInformation.sharedInstance.siteTimeZone = blog.timeZone SiteStatsInformation.sharedInstance.oauth2Token = blog.authToken SiteStatsInformation.sharedInstance.siteID = blog.dotComID let postURL = URL(string: apost.permaLink! as String) let postStatsTableViewController = PostStatsTableViewController.loadFromStoryboard() postStatsTableViewController.configure(postID: postID, postTitle: apost.titleForDisplay(), postURL: postURL) navigationController?.pushViewController(postStatsTableViewController, animated: true) } // MARK: - InteractivePostViewDelegate func edit(_ post: AbstractPost) { editPost(apost: post) } func view(_ post: AbstractPost) { viewPost(post) } func stats(for post: AbstractPost) { ReachabilityUtils.onAvailableInternetConnectionDo { viewStatsForPost(post) } } func duplicate(_ post: AbstractPost) { editDuplicatePost(apost: post) } func publish(_ post: AbstractPost) { publishPost(post) { BloggingRemindersFlow.present(from: self, for: post.blog, source: .publishFlow, alwaysShow: false) } } func trash(_ post: AbstractPost) { guard ReachabilityUtils.isInternetReachable() else { let offlineMessage = NSLocalizedString("Unable to trash posts while offline. Please try again later.", comment: "Message that appears when a user tries to trash a post while their device is offline.") ReachabilityUtils.showNoInternetConnectionNotice(message: offlineMessage) return } let cancelText: String let deleteText: String let messageText: String let titleText: String if post.status == .trash { cancelText = NSLocalizedString("Cancel", comment: "Cancels an Action") deleteText = NSLocalizedString("Delete Permanently", comment: "Delete option in the confirmation alert when deleting a post from the trash.") titleText = NSLocalizedString("Delete Permanently?", comment: "Title of the confirmation alert when deleting a post from the trash.") messageText = NSLocalizedString("Are you sure you want to permanently delete this post?", comment: "Message of the confirmation alert when deleting a post from the trash.") } else { cancelText = NSLocalizedString("Cancel", comment: "Cancels an Action") deleteText = NSLocalizedString("Move to Trash", comment: "Trash option in the trash confirmation alert.") titleText = NSLocalizedString("Trash this post?", comment: "Title of the trash confirmation alert.") messageText = NSLocalizedString("Are you sure you want to trash this post?", comment: "Message of the trash confirmation alert.") } let alertController = UIAlertController(title: titleText, message: messageText, preferredStyle: .alert) alertController.addCancelActionWithTitle(cancelText) alertController.addDestructiveActionWithTitle(deleteText) { [weak self] action in self?.deletePost(post) } alertController.presentFromRootViewController() } func restore(_ post: AbstractPost) { ReachabilityUtils.onAvailableInternetConnectionDo { restorePost(post) } } func draft(_ post: AbstractPost) { ReachabilityUtils.onAvailableInternetConnectionDo { moveToDraft(post) } } func retry(_ post: AbstractPost) { PostCoordinator.shared.save(post) } func cancelAutoUpload(_ post: AbstractPost) { PostCoordinator.shared.cancelAutoUploadOf(post) } func share(_ apost: AbstractPost, fromView view: UIView) { guard let post = apost as? Post else { return } let shareController = PostSharingController() shareController.sharePost(post, fromView: view, inViewController: self) } // MARK: - Searching override func updateForLocalPostsMatchingSearchText() { // If the user taps and starts to type right away, avoid doing the search // while the tableViewHandler is not ready yet if !_tableViewHandler.isSearching && currentSearchTerm()?.count > 0 { return } super.updateForLocalPostsMatchingSearchText() } override func willPresentSearchController(_ searchController: UISearchController) { super.willPresentSearchController(searchController) self.filterTabBar.alpha = WPAlphaZero } func didPresentSearchController(_ searchController: UISearchController) { updateTableHeaderSize() _tableViewHandler.isSearching = true tableView.verticalScrollIndicatorInsets.top = searchWrapperView.bounds.height tableView.contentInset.top = 0 } override func sortDescriptorsForFetchRequest() -> [NSSortDescriptor] { if !isSearching() { return super.sortDescriptorsForFetchRequest() } let descriptor = NSSortDescriptor(key: BasePost.statusKeyPath, ascending: true) return [descriptor] } override func willDismissSearchController(_ searchController: UISearchController) { _tableViewHandler.isSearching = false _tableViewHandler.refreshTableView() super.willDismissSearchController(searchController) } func didDismissSearchController(_ searchController: UISearchController) { updateTableHeaderSize() UIView.animate(withDuration: Animations.searchDismissDuration) { self.filterTabBar.alpha = WPAlphaFull } } enum Animations { static let searchDismissDuration: TimeInterval = 0.3 } // MARK: - NetworkAwareUI override func noConnectionMessage() -> String { return NSLocalizedString("No internet connection. Some posts may be unavailable while offline.", comment: "Error message shown when the user is browsing Site Posts without an internet connection.") } private enum Constants { static let exhibitionModeKey = "showCompactPosts" static let searchHeaderHeight: CGFloat = 40 static let card = "card" static let compact = "compact" static let source = "post_list" } } // MARK: - No Results Handling private extension PostListViewController { func handleRefreshNoResultsViewController(_ noResultsViewController: NoResultsViewController) { guard connectionAvailable() else { noResultsViewController.configure(title: "", noConnectionTitle: NoResultsText.noConnectionTitle, buttonTitle: NoResultsText.buttonTitle, subtitle: nil, noConnectionSubtitle: NoResultsText.noConnectionSubtitle, attributedSubtitle: nil, attributedSubtitleConfiguration: nil, image: nil, subtitleImage: nil, accessoryView: nil) return } if searchController.isActive { if currentSearchTerm()?.count == 0 { noResultsViewController.configureForNoSearchResults(title: NoResultsText.searchPosts) } else { noResultsViewController.configureForNoSearchResults(title: noResultsTitle()) } } else { let accessoryView = syncHelper.isSyncing ? NoResultsViewController.loadingAccessoryView() : nil noResultsViewController.configure(title: noResultsTitle(), buttonTitle: noResultsButtonTitle(), image: noResultsImageName, accessoryView: accessoryView) } } var noResultsImageName: String { return "posts-no-results" } func noResultsButtonTitle() -> String? { if syncHelper.isSyncing == true || isSearching() { return nil } let filterType = filterSettings.currentPostListFilter().filterType return filterType == .trashed ? nil : NoResultsText.buttonTitle } func noResultsTitle() -> String { if syncHelper.isSyncing == true { return NoResultsText.fetchingTitle } if isSearching() { return NoResultsText.noMatchesTitle } return noResultsFilteredTitle() } func noResultsFilteredTitle() -> String { let filterType = filterSettings.currentPostListFilter().filterType switch filterType { case .draft: return NoResultsText.noDraftsTitle case .scheduled: return NoResultsText.noScheduledTitle case .trashed: return NoResultsText.noTrashedTitle case .published: return NoResultsText.noPublishedTitle } } struct NoResultsText { static let buttonTitle = NSLocalizedString("Create Post", comment: "Button title, encourages users to create post on their blog.") static let fetchingTitle = NSLocalizedString("Fetching posts...", comment: "A brief prompt shown when the reader is empty, letting the user know the app is currently fetching new posts.") static let noMatchesTitle = NSLocalizedString("No posts matching your search", comment: "Displayed when the user is searching the posts list and there are no matching posts") static let noDraftsTitle = NSLocalizedString("You don't have any draft posts", comment: "Displayed when the user views drafts in the posts list and there are no posts") static let noScheduledTitle = NSLocalizedString("You don't have any scheduled posts", comment: "Displayed when the user views scheduled posts in the posts list and there are no posts") static let noTrashedTitle = NSLocalizedString("You don't have any trashed posts", comment: "Displayed when the user views trashed in the posts list and there are no posts") static let noPublishedTitle = NSLocalizedString("You haven't published any posts yet", comment: "Displayed when the user views published posts in the posts list and there are no posts") static let noConnectionTitle: String = NSLocalizedString("Unable to load posts right now.", comment: "Title for No results full page screen displayedfrom post list when there is no connection") static let noConnectionSubtitle: String = NSLocalizedString("Check your network connection and try again. Or draft a post.", comment: "Subtitle for No results full page screen displayed from post list when there is no connection") static let searchPosts = NSLocalizedString("Search posts", comment: "Text displayed when the search controller will be presented") } } extension PostListViewController: PostActionSheetDelegate { func showActionSheet(_ postCardStatusViewModel: PostCardStatusViewModel, from view: UIView) { let isCompactOrSearching = isCompact || searchController.isActive postActionSheet.show(for: postCardStatusViewModel, from: view, isCompactOrSearching: isCompactOrSearching) } }
gpl-2.0
0f11d634da1810f7fc4538a7075c5afd
39.039194
336
0.676297
5.564115
false
false
false
false
pjchavarria/Swift-Gif
Swift-Gif/Gif.swift
1
1525
// // Gif.swift // Swift-Gif // // Created by Paul Chavarria Podoliako on 9/11/14. // Copyright (c) 2014 AnyTap. All rights reserved. // import Foundation class Gif { var id: String = "" var source: String? var fixedWidthUrl: String? var originalUrl: String? var width: Int = 0 var height: Int = 0 var rating: String? } extension Gif { class func translateFromJSON(data: AnyObject?) -> [Gif] { if let data = data as? NSDictionary { let json = JSONValue(data) if let jsonGifs = json["data"].array { //JSONValue it self confirm to Protocol "LogicValue", with JSONValue.JInvalid produce false and others produce true var gifs = [Gif]() for jsonGif in jsonGifs { let gif = Gif() gif.id = jsonGif["id"].string! gif.source = jsonGif["source"].string gif.rating = jsonGif["rating"].string gif.originalUrl = jsonGif["images"]["original"]["url"].string gif.fixedWidthUrl = jsonGif["images"]["fixed_width"]["url"].string gif.width = jsonGif["images"]["original"]["width"].integer! gif.height = jsonGif["images"]["original"]["height"].integer! gifs.append(gif) } return gifs }else{ println(json) } } return [Gif]() } }
mit
d50b788f1cf7b60e7b9f02e641cd82e6
30.142857
131
0.513443
4.42029
false
false
false
false
Pluto-Y/SwiftyEcharts
SwiftyEcharts/Models/Graphic/SectorGraphic.swift
1
4785
// // SectorGraphic.swift // SwiftyEcharts // // Created by Pluto Y on 12/02/2017. // Copyright © 2017 com.pluto-y. All rights reserved. // /// 扇形类型的 `Graphic` public final class SectorGraphic: Graphic { /// 扇形的大小和位置 public final class Shape { public var cx: Float? public var cy: Float? public var r: Float? public var r0: Float? public var startAngle: Float? public var endAngle: Float? public var clockwise: Bool? public init() {} } /// MARK: Graphic public var type: GraphicType { return .sector } public var id: String? public var action: GraphicAction? public var left: Position? public var right: Position? public var top: Position? public var bottom: Position? public var bounding: GraphicBounding? public var z: Float? public var zlevel: Float? public var silent: Bool? public var invisible: Bool? public var cursor: String? public var draggable: Bool? public var progressive: Bool? /// 扇形的大小和位置 public var shape: Shape? /// 扇形的样式 public var style: CommonGraphicStyle? public init() {} } extension SectorGraphic.Shape: Enumable { public enum Enums { case cx(Float), cy(Float), r(Float), r0(Float), startAngle(Float), endAngle(Float), clockwise(Bool) } public typealias ContentEnum = Enums public convenience init(_ elements: Enums...) { self.init() for ele in elements { switch ele { case let .cx(cx): self.cx = cx case let .cy(cy): self.cy = cy case let .r(r): self.r = r case let .r0(r0): self.r0 = r0 case let .startAngle(startAngle): self.startAngle = startAngle case let .endAngle(endAngle): self.endAngle = endAngle case let .clockwise(clockwise): self.clockwise = clockwise } } } } extension SectorGraphic.Shape: Mappable { public func mapping(_ map: Mapper) { map["cx"] = cx map["cy"] = cy map["r"] = r map["r0"] = r0 map["startAngle"] = startAngle map["endAngle"] = endAngle map["clockwise"] = clockwise } } extension SectorGraphic: Enumable { public enum Enums { case id(String), action(GraphicAction), left(Position), right(Position), top(Position), bottom(Position), bounding(GraphicBounding), z(Float), zlevel(Float), silent(Bool), invisible(Bool), cursor(String), draggable(Bool), progressive(Bool), shape(Shape), style(CommonGraphicStyle) } public typealias ContentEnum = Enums public convenience init(_ elements: Enums...) { self.init() for ele in elements { switch ele { case let .id(id): self.id = id case let .action(action): self.action = action case let .left(left): self.left = left case let .right(right): self.right = right case let .top(top): self.top = top case let .bottom(bottom): self.bottom = bottom case let .bounding(bounding): self.bounding = bounding case let .z(z): self.z = z case let .zlevel(zlevel): self.zlevel = zlevel case let .silent(silent): self.silent = silent case let .invisible(invisible): self.invisible = invisible case let .cursor(cursor): self.cursor = cursor case let .draggable(draggable): self.draggable = draggable case let .progressive(progressive): self.progressive = progressive case let .shape(shape): self.shape = shape case let .style(style): self.style = style } } } } extension SectorGraphic: Mappable { public func mapping(_ map: Mapper) { map["type"] = type map["id"] = id map["$action"] = action map["left"] = left map["right"] = right map["top"] = top map["bottom"] = bottom map["bounding"] = bounding map["z"] = z map["zlevel"] = zlevel map["silent"] = silent map["invisible"] = invisible map["cursor"] = cursor map["draggable"] = draggable map["progressive"] = progressive map["shape"] = shape map["style"] = style } }
mit
b71fc742ff7b008274a879fdba03e5b7
28.209877
288
0.533812
4.498099
false
false
false
false
pushuhengyang/dyzb
DYZB/DYZB/Classes/Tools工具/UINaviBarItem.swift
1
921
// // UINaviBarItem.swift // DYZB // // Created by xuwenhao on 16/11/12. // Copyright © 2016年 xuwenhao. All rights reserved. // import UIKit extension UIBarButtonItem { convenience init(imageName : String, heightImageName: String = "", size :CGSize = CGSize.zero , target : AnyObject? = nil ,action : Selector? = nil){ let btn = UIButton.init(type: UIButtonType.custom); btn.setImage(UIImage.init(named: imageName), for: UIControlState.normal); if (heightImageName != "") { btn.setImage(UIImage.init(named: heightImageName), for: .highlighted ); } if (size != CGSize.zero) { btn.frame = CGRect.init(origin: CGPoint.zero, size: size); } btn.addTarget(target, action: action!, for: .touchUpInside); self.init(customView: btn); } }
mit
777afab2dc203df0826be70f93d1648e
24.5
153
0.571895
4.230415
false
false
false
false
apple/swift
test/Frontend/module-alias-emit-sil.swift
4
3516
/// Test emit sil with module aliasing. /// /// Module 'Lib' imports module 'XLogging', and 'XLogging' is aliased 'AppleLogging'. // RUN: %empty-directory(%t) // RUN: %{python} %utils/split_file.py -o %t %s /// Create AppleLogging.swiftmodule by aliasing XLogging // RUN: %target-swift-frontend -module-name AppleLogging -module-alias XLogging=AppleLogging %t/FileLogging.swift -emit-module -emit-module-path %t/AppleLogging.swiftmodule // RUN: test -f %t/AppleLogging.swiftmodule /// Verify generated SIL only contains AppleLogging // RUN: %target-swift-frontend -emit-sil %t/FileLib.swift -module-alias XLogging=AppleLogging -I %t > %t/result-sil.output // RUN: %FileCheck %s -input-file %t/result-sil.output // RUN: not %FileCheck %s -input-file %t/result-sil.output -check-prefix CHECK-NOT-FOUND // CHECK-NOT-FOUND: XLogging // CHECK: sil_stage canonical // CHECK: import Builtin // CHECK: import Swift // CHECK: import SwiftShims // CHECK: import AppleLogging // CHECK: public struct MyLib : Loggable { // CHECK: public var verbosity: Int { get } // CHECK: init() // CHECK: } // CHECK: public func start() -> (any Loggable)? // CHECK: public func end(_ arg: Logger) // CHECK: // protocol witness for Loggable.verbosity.getter in conformance MyLib // CHECK: sil shared [transparent] [thunk] @$s7FileLib02MyB0V12AppleLogging8LoggableAadEP9verbositySivgTW : $@convention(witness_method: Loggable) (@in_guaranteed MyLib) -> Int { // CHECK: // %0 // user: %1 // CHECK: bb0(%0 : $*MyLib): // CHECK: %1 = load %0 : $*MyLib // user: %3 // CHECK: // function_ref MyLib.verbosity.getter // CHECK: %2 = function_ref @$s7FileLib02MyB0V9verbositySivg : $@convention(method) (MyLib) -> Int // user: %3 // CHECK: %3 = apply %2(%1) : $@convention(method) (MyLib) -> Int // user: %4 // CHECK: return %3 : $Int // id: %4 // CHECK: } // end sil function '$s7FileLib02MyB0V12AppleLogging8LoggableAadEP9verbositySivgTW' // CHECK: // start() // CHECK: sil @$s7FileLib5start12AppleLogging8Loggable_pSgyF : $@convention(thin) () -> @out Optional<any Loggable> { // CHECK: // %0 "$return_value" // user: %2 // CHECK: bb0(%0 : $*Optional<any Loggable>): // CHECK: // function_ref setup() // CHECK: %1 = function_ref @$s12AppleLogging5setupAA8Loggable_pSgyF : $@convention(thin) () -> @out Optional<any Loggable> // user: %2 // CHECK: %2 = apply %1(%0) : $@convention(thin) () -> @out Optional<any Loggable> // CHECK: %3 = tuple () // user: %4 // CHECK: return %3 : $() // id: %4 // CHECK: } // end sil function '$s7FileLib5start12AppleLogging8Loggable_pSgyF' // CHECK: // setup() // CHECK: sil @$s12AppleLogging5setupAA8Loggable_pSgyF : $@convention(thin) () -> @out Optional<any Loggable> // CHECK: // end(_:) // CHECK: sil @$s7FileLib3endyy12AppleLogging6LoggerVF : $@convention(thin) (Logger) -> () { // CHECK: } // end sil function '$s7FileLib3endyy12AppleLogging6LoggerVF' // BEGIN FileLogging.swift public protocol Loggable { var verbosity: Int { get } } public struct Logger { public init() {} } public func setup() -> XLogging.Loggable? { return nil } // BEGIN FileLib.swift import XLogging public struct MyLib: Loggable { public var verbosity: Int { return 3 } } public func start() -> XLogging.Loggable? { return XLogging.setup() } public func end(_ arg: XLogging.Logger) { }
apache-2.0
3d6a223c0a2f497531e9db594edf9996
38.066667
178
0.644482
3.342205
false
false
false
false
roroque/Compiladores
Lexico/Lexico/Scanner.swift
1
7862
// // Scanner.swift // Lexico // // Created by Gabriel Neves Ferreira on 9/8/16. // Copyright © 2016 Gabriel Neves Ferreira. All rights reserved. // import Cocoa class Scanner { var urlArquivo :String? init(){ } func setUrl(_ url : String){ urlArquivo = url } func readFile() -> String? { var fileContent : String = "" do{ fileContent = try String(contentsOfFile: urlArquivo!) return fileContent }catch _ as NSError{ print("arquivo invalido") return nil } } func removeCommentsAndBlankSpaces(_ text : String) -> String? { var modifiedText = text var firstIndex = 0 var secondIndex = 0 //put code to check if doesnt make any modifications break while true { firstIndex = 0 secondIndex = 0 //contains first piece and contains this type of commentary if modifiedText.contains("{") { //contais second go and find if modifiedText.contains("}"){ //find first piece for character in modifiedText.characters { if character == "{"{ break } firstIndex = firstIndex + 1 } //find second piece for character in modifiedText.characters { if character == "}"{ break } secondIndex = secondIndex + 1 } if secondIndex < firstIndex{ //error de chave ErrorThrower().showError(errorNumber: "error\n erro de comentario {} ") return nil } let desiredRange = modifiedText.characters.index(modifiedText.startIndex, offsetBy: firstIndex)...modifiedText.characters.index(modifiedText.startIndex, offsetBy: secondIndex) modifiedText.removeSubrange(desiredRange) }else{ //error de chave ErrorThrower().showError(errorNumber: "error\n erro de comentario {} ") return nil } }else{ //contains one but doenst contain the other if modifiedText.contains("}") { //error de fecha chave ErrorThrower().showError(errorNumber: "error\n erro de comentario {} ") return nil }else{ print("dont modify {}") break } } } //put code to check if doesnt make any modifications break while true { firstIndex = 0 secondIndex = 0 //check second type of commentary //contains first piece if modifiedText.contains("/*"){ //contains second piece if modifiedText.contains("*/") { //find first piece for character in modifiedText.characters { if character == "/"{ //check if next is * let selectedString = modifiedText[modifiedText.characters.index(modifiedText.startIndex, offsetBy: firstIndex + 1)] if selectedString == "*"{ break }else{ ErrorThrower().showError(errorNumber: "error\n erro de comentario /**/ ") return nil } //else crash } firstIndex = firstIndex + 1 } //find second piece for character in modifiedText.characters { if secondIndex != 0 { if character == "/"{ //check if before * //check if next is * let selectedString = modifiedText[modifiedText.characters.index(modifiedText.startIndex, offsetBy: secondIndex - 1)] if selectedString == "*"{ break } } } secondIndex = secondIndex + 1 } if secondIndex < firstIndex{ //error de chave ErrorThrower().showError(errorNumber: "error\n erro de comentario /**/ ") return nil } let desiredRange = modifiedText.characters.index(modifiedText.startIndex, offsetBy: firstIndex)...modifiedText.characters.index(modifiedText.startIndex, offsetBy: secondIndex) modifiedText.removeSubrange(desiredRange) }else{ //doenst contains one of them //error de comentario ErrorThrower().showError(errorNumber: "error\n erro de comentario /**/ ") return nil } }else{ //doenst contain //contains one of them if modifiedText.contains("*/") { //error de comentario ErrorThrower().showError(errorNumber: "error\n erro de comentario /**/ ") return nil }else{ print("dont modify /*") break } } } //errors on programa //modifiedText = modifiedText.stringByReplacingOccurrencesOfString(" ", withString: "") modifiedText = modifiedText.replacingOccurrences(of: "\t", with: " ") modifiedText = modifiedText.replacingOccurrences(of: "\n", with: " ") modifiedText = modifiedText.replacingOccurrences(of: "\r", with: " ") return modifiedText } }
apache-2.0
47ee90737d1bb6ae10b785aae186c189
31.618257
195
0.362804
7.508118
false
false
false
false
menlatin/jalapeno
digeocache/mobile/iOS/diGeo/diGeo/DrawerController/ExampleRightSideDrawerViewController.swift
3
4034
// Copyright (c) 2014 evolved.io (http://evolved.io) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import UIKit class ExampleRightSideDrawerViewController: ExampleSideDrawerViewController { override init() { super.init() self.restorationIdentifier = "ExampleRightSideDrawerController" } override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) self.restorationIdentifier = "ExampleRightSideDrawerController" } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) println("Right will appear") } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) println("Right did appear") } override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) println("Right will disappear") } override func viewDidDisappear(animated: Bool) { super.viewDidDisappear(animated) println("Right did disappear") } override func viewDidLoad() { super.viewDidLoad() self.title = "Right Drawer" } override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { if section == DrawerSection.DrawerWidth.rawValue { return "Right Drawer Width" } else { return super.tableView(tableView, titleForHeaderInSection: section) } } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = super.tableView(tableView, cellForRowAtIndexPath: indexPath) if indexPath.section == DrawerSection.DrawerWidth.rawValue { let width = self.drawerWidths[indexPath.row] let drawerWidth = self.evo_drawerController?.maximumRightDrawerWidth if drawerWidth == width { cell.accessoryType = .Checkmark } else { cell.accessoryType = .None } cell.textLabel?.text = "Width \(self.drawerWidths[indexPath.row])" } return cell } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { if indexPath.section == DrawerSection.DrawerWidth.rawValue { self.evo_drawerController?.setMaximumRightDrawerWidth(self.drawerWidths[indexPath.row], animated: true, completion: { (finished) -> Void in tableView.reloadSections(NSIndexSet(index: indexPath.section), withRowAnimation: .None) tableView.selectRowAtIndexPath(indexPath, animated: false, scrollPosition: .None) tableView.deselectRowAtIndexPath(indexPath, animated: true) }) } else { super.tableView(tableView, didSelectRowAtIndexPath: indexPath) } } }
mit
b1899d9fad5d29779ab1b5d6e0101b98
40.587629
151
0.681953
5.335979
false
false
false
false
cwwise/CWWeChat
CWWeChat/MainClass/Contacts/GroupChatController/CWGroupChatController.swift
2
1714
// // CWGroupChatController.swift // CWWeChat // // Created by chenwei on 2017/4/8. // Copyright © 2017年 cwcoder. All rights reserved. // import UIKit class CWGroupChatController: CWBaseConversationController { override func viewDidLoad() { super.viewDidLoad() self.title = "群聊" fetchGroupChat() let barButtonItem = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(createGroupChat)) self.navigationItem.rightBarButtonItem = barButtonItem } @objc func createGroupChat() { let groupManager = CWChatClient.share.groupManager let setting = CWChatGroupOptions() groupManager.createGroup(title: "测试聊天", invitees: [], message: "", setting: setting, completion: nil) //let chatroomManager = CWChatClient.share.chatroomManager // chatroomManager.createChatroom(title: "测试", invitees: [], message: "") } // TODO: 应该只显示本地保存的群聊,后期修改 func fetchGroupChat() { let groupManager = CWChatClient.share.groupManager groupManager.fetchJoinGroups() // let chatroomManager = CWChatClient.share.chatroomManager //chatroomManager.fetchChatrooms() /* let jid = "[email protected]" let conversation = self.chatManager.fecthConversation(chatType: .group, targetId: jid) conversationList.append(CWChatConversationModel(conversation: conversation)) */ } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
f8a1bcf78db03726e63cc3112a6afe5f
30.339623
120
0.662854
4.453083
false
false
false
false
tjw/swift
test/Parse/enum.swift
1
19406
// RUN: %target-typecheck-verify-swift // FIXME: this test only passes on platforms which have Float80. // <rdar://problem/19508460> Floating point enum raw values are not portable // REQUIRES: CPU=i386 || CPU=x86_64 enum Empty {} enum Boolish { case falsy case truthy init() { self = .falsy } } var b = Boolish.falsy b = .truthy enum Optionable<T> { case Nought case Mere(T) } var o = Optionable<Int>.Nought o = .Mere(0) enum Color { case Red, Green, Grayscale(Int), Blue } var c = Color.Red c = .Green c = .Grayscale(255) c = .Blue let partialApplication = Color.Grayscale // Cases are excluded from non-enums. case FloatingCase // expected-error{{enum 'case' is not allowed outside of an enum}} struct SomeStruct { case StructCase // expected-error{{enum 'case' is not allowed outside of an enum}} } class SomeClass { case ClassCase // expected-error{{enum 'case' is not allowed outside of an enum}} } enum EnumWithExtension1 { case A1 } extension EnumWithExtension1 { case A2 // expected-error{{enum 'case' is not allowed outside of an enum}} } // Attributes for enum cases. enum EnumCaseAttributes { @xyz case EmptyAttributes // expected-error {{unknown attribute 'xyz'}} } // Recover when a switch 'case' label is spelled inside an enum (or outside). enum SwitchEnvy { case X: // expected-error{{'case' label can only appear inside a 'switch' statement}} case X(Y): // expected-error{{'case' label can only appear inside a 'switch' statement}} case X, Y: // expected-error{{'case' label can only appear inside a 'switch' statement}} case X where true: // expected-error{{'case' label can only appear inside a 'switch' statement}} case X(Y), Z(W): // expected-error{{'case' label can only appear inside a 'switch' statement}} case X(Y) where true: // expected-error{{'case' label can only appear inside a 'switch' statement}} case 0: // expected-error{{'case' label can only appear inside a 'switch' statement}} case _: // expected-error{{'case' label can only appear inside a 'switch' statement}} case (_, var x, 0): // expected-error{{'case' label can only appear inside a 'switch' statement}} } enum HasMethodsPropertiesAndCtors { case TweedleDee case TweedleDum func method() {} func staticMethod() {} init() {} subscript(x:Int) -> Int { return 0 } var property : Int { return 0 } } enum ImproperlyHasIVars { case Flopsy case Mopsy var ivar : Int // expected-error{{enums must not contain stored properties}} } // We used to crash on this. rdar://14678675 enum rdar14678675 { case U1, case U2 // expected-error{{expected identifier after comma in enum 'case' declaration}} case U3 } enum Recovery1 { case: // expected-error {{'case' label can only appear inside a 'switch' statement}} expected-error {{expected pattern}} } enum Recovery2 { case UE1: // expected-error {{'case' label can only appear inside a 'switch' statement}} } enum Recovery3 { case UE2(): // expected-error {{'case' label can only appear inside a 'switch' statement}} } enum Recovery4 { // expected-note {{in declaration of 'Recovery4'}} case Self Self // expected-error {{keyword 'Self' cannot be used as an identifier here}} expected-note {{if this name is unavoidable, use backticks to escape it}} {{8-12=`Self`}} expected-error {{consecutive declarations on a line must be separated by ';'}} {{12-12=;}} expected-error {{expected declaration}} } enum Recovery5 { case .UE3 // expected-error {{extraneous '.' in enum 'case' declaration}} {{8-9=}} case .UE4, .UE5 // expected-error@-1{{extraneous '.' in enum 'case' declaration}} {{8-9=}} // expected-error@-2{{extraneous '.' in enum 'case' declaration}} {{14-15=}} } enum Recovery6 { case Snout, _; // expected-error {{expected identifier after comma in enum 'case' declaration}} case _; // expected-error {{keyword '_' cannot be used as an identifier here}} expected-note {{if this name is unavoidable, use backticks to escape it}} {{8-9=`_`}} case Tusk, // expected-error {{expected pattern}} } // expected-error {{expected identifier after comma in enum 'case' declaration}} enum RawTypeEmpty : Int {} // expected-error {{an enum with no cases cannot declare a raw type}} // expected-error@-1{{'RawTypeEmpty' declares raw type 'Int', but does not conform to RawRepresentable and conformance could not be synthesized}} enum Raw : Int { case Ankeny, Burnside } enum MultiRawType : Int64, Int32 { // expected-error {{multiple enum raw types 'Int64' and 'Int32'}} case Couch, Davis } protocol RawTypeNotFirstProtocol {} enum RawTypeNotFirst : RawTypeNotFirstProtocol, Int { // expected-error {{raw type 'Int' must appear first in the enum inheritance clause}} {{24-24=Int, }} {{47-52=}} case E } enum ExpressibleByRawTypeNotLiteral : Array<Int> { // expected-error {{raw type 'Array<Int>' is not expressible by any literal}} // expected-error@-1{{'ExpressibleByRawTypeNotLiteral' declares raw type 'Array<Int>', but does not conform to RawRepresentable and conformance could not be synthesized}} case Ladd, Elliott, Sixteenth, Harrison } enum RawTypeCircularityA : RawTypeCircularityB, ExpressibleByIntegerLiteral { // expected-error {{circular enum raw types 'RawTypeCircularityA' -> 'RawTypeCircularityB' -> 'RawTypeCircularityA'}} FIXME: expected-error{{RawRepresentable}} case Morrison, Belmont, Madison, Hawthorne init(integerLiteral value: Int) { self = .Morrison } } enum RawTypeCircularityB : RawTypeCircularityA, ExpressibleByIntegerLiteral { // expected-note {{enum 'RawTypeCircularityB' declared here}} case Willamette, Columbia, Sandy, Multnomah init(integerLiteral value: Int) { self = .Willamette } } struct ExpressibleByFloatLiteralOnly : ExpressibleByFloatLiteral { init(floatLiteral: Double) {} } enum ExpressibleByRawTypeNotIntegerLiteral : ExpressibleByFloatLiteralOnly { // expected-error {{'ExpressibleByRawTypeNotIntegerLiteral' declares raw type 'ExpressibleByFloatLiteralOnly', but does not conform to RawRepresentable and conformance could not be synthesized}} expected-error {{RawRepresentable conformance cannot be synthesized because raw type 'ExpressibleByFloatLiteralOnly' is not Equatable}} case Everett // expected-error {{enum cases require explicit raw values when the raw type is not expressible by integer or string literal}} case Flanders } enum RawTypeWithIntValues : Int { case Glisan = 17, Hoyt = 219, Irving, Johnson = 97209 } enum RawTypeWithNegativeValues : Int { case Glisan = -17, Hoyt = -219, Irving, Johnson = -97209 case AutoIncAcrossZero = -1, Zero, One } enum RawTypeWithUnicodeScalarValues : UnicodeScalar { // expected-error {{'RawTypeWithUnicodeScalarValues' declares raw type 'UnicodeScalar' (aka 'Unicode.Scalar'), but does not conform to RawRepresentable and conformance could not be synthesized}} case Kearney = "K" case Lovejoy // expected-error {{enum cases require explicit raw values when the raw type is not expressible by integer or string literal}} case Marshall = "M" } enum RawTypeWithCharacterValues : Character { // expected-error {{'RawTypeWithCharacterValues' declares raw type 'Character', but does not conform to RawRepresentable and conformance could not be synthesized}} case First = "い" case Second // expected-error {{enum cases require explicit raw values when the raw type is not expressible by integer or string literal}} case Third = "は" } enum RawTypeWithCharacterValues_Correct : Character { case First = "😅" // ok case Second = "👩‍👩‍👧‍👦" // ok case Third = "👋🏽" // ok } enum RawTypeWithCharacterValues_Error1 : Character { // expected-error {{'RawTypeWithCharacterValues_Error1' declares raw type 'Character', but does not conform to RawRepresentable and conformance could not be synthesized}} case First = "abc" // expected-error {{cannot convert value of type 'String' to raw type 'Character'}} } enum RawTypeWithFloatValues : Float { // expected-error {{'RawTypeWithFloatValues' declares raw type 'Float', but does not conform to RawRepresentable and conformance could not be synthesized}} case Northrup = 1.5 case Overton // expected-error {{enum case must declare a raw value when the preceding raw value is not an integer}} case Pettygrove = 2.25 } enum RawTypeWithStringValues : String { case Primrose // okay case Quimby = "Lucky Lab" case Raleigh // okay case Savier = "McMenamin's", Thurman = "Kenny and Zuke's" } enum RawValuesWithoutRawType { case Upshur = 22 // expected-error {{enum case cannot have a raw value if the enum does not have a raw type}} } enum RawTypeWithRepeatValues : Int { case Vaughn = 22 // expected-note {{raw value previously used here}} case Wilson = 22 // expected-error {{raw value for enum case is not unique}} } enum RawTypeWithRepeatValues2 : Double { case Vaughn = 22 // expected-note {{raw value previously used here}} case Wilson = 22.0 // expected-error {{raw value for enum case is not unique}} } enum RawTypeWithRepeatValues3 : Double { // 2^63-1 case Vaughn = 9223372036854775807 // expected-note {{raw value previously used here}} case Wilson = 9223372036854775807.0 // expected-error {{raw value for enum case is not unique}} } enum RawTypeWithRepeatValues4 : Double { // 2^64-1 case Vaughn = 18446744073709551615 // expected-note {{raw value previously used here}} case Wilson = 18446744073709551615.0 // expected-error {{raw value for enum case is not unique}} } enum RawTypeWithRepeatValues5 : Double { // FIXME: should reject. // 2^65-1 case Vaughn = 36893488147419103231 case Wilson = 36893488147419103231.0 } enum RawTypeWithRepeatValues6 : Double { // FIXME: should reject. // 2^127-1 case Vaughn = 170141183460469231731687303715884105727 case Wilson = 170141183460469231731687303715884105727.0 } enum RawTypeWithRepeatValues7 : Double { // FIXME: should reject. // 2^128-1 case Vaughn = 340282366920938463463374607431768211455 case Wilson = 340282366920938463463374607431768211455.0 } enum RawTypeWithRepeatValues8 : String { case Vaughn = "XYZ" // expected-note {{raw value previously used here}} case Wilson = "XYZ" // expected-error {{raw value for enum case is not unique}} } enum RawTypeWithNonRepeatValues : Double { case SantaClara = 3.7 case SanFernando = 7.4 case SanAntonio = -3.7 case SanCarlos = -7.4 } enum RawTypeWithRepeatValuesAutoInc : Double { case Vaughn = 22 // expected-note {{raw value auto-incremented from here}} case Wilson // expected-note {{raw value previously used here}} case Yeon = 23 // expected-error {{raw value for enum case is not unique}} } enum RawTypeWithRepeatValuesAutoInc2 : Double { case Vaughn = 23 // expected-note {{raw value previously used here}} case Wilson = 22 // expected-note {{raw value auto-incremented from here}} case Yeon // expected-error {{raw value for enum case is not unique}} } enum RawTypeWithRepeatValuesAutoInc3 : Double { case Vaughn // expected-note {{raw value implicitly auto-incremented from zero}} case Wilson // expected-note {{raw value previously used here}} case Yeon = 1 // expected-error {{raw value for enum case is not unique}} } enum RawTypeWithRepeatValuesAutoInc4 : String { case A = "B" // expected-note {{raw value previously used here}} case B // expected-error {{raw value for enum case is not unique}} } enum RawTypeWithRepeatValuesAutoInc5 : String { case A // expected-note {{raw value previously used here}} case B = "A" // expected-error {{raw value for enum case is not unique}} } enum RawTypeWithRepeatValuesAutoInc6 : String { case A case B // expected-note {{raw value previously used here}} case C = "B" // expected-error {{raw value for enum case is not unique}} } enum NonliteralRawValue : Int { case Yeon = 100 + 20 + 3 // expected-error {{raw value for enum case must be a literal}} } enum RawTypeWithPayload : Int { // expected-error {{'RawTypeWithPayload' declares raw type 'Int', but does not conform to RawRepresentable and conformance could not be synthesized}} expected-note {{declared raw type 'Int' here}} expected-note {{declared raw type 'Int' here}} case Powell(Int) // expected-error {{enum with raw type cannot have cases with arguments}} case Terwilliger(Int) = 17 // expected-error {{enum with raw type cannot have cases with arguments}} } enum RawTypeMismatch : Int { // expected-error {{'RawTypeMismatch' declares raw type 'Int', but does not conform to RawRepresentable and conformance could not be synthesized}} case Barbur = "foo" // expected-error {{}} } enum DuplicateMembers1 { case Foo // expected-note {{'Foo' previously declared here}} case Foo // expected-error {{invalid redeclaration of 'Foo'}} } enum DuplicateMembers2 { case Foo, Bar // expected-note {{'Foo' previously declared here}} expected-note {{'Bar' previously declared here}} case Foo // expected-error {{invalid redeclaration of 'Foo'}} case Bar // expected-error {{invalid redeclaration of 'Bar'}} } enum DuplicateMembers3 { case Foo // expected-note {{'Foo' previously declared here}} case Foo(Int) // expected-error {{invalid redeclaration of 'Foo'}} } enum DuplicateMembers4 : Int { // expected-error {{'DuplicateMembers4' declares raw type 'Int', but does not conform to RawRepresentable and conformance could not be synthesized}} case Foo = 1 // expected-note {{'Foo' previously declared here}} case Foo = 2 // expected-error {{invalid redeclaration of 'Foo'}} } enum DuplicateMembers5 : Int { // expected-error {{'DuplicateMembers5' declares raw type 'Int', but does not conform to RawRepresentable and conformance could not be synthesized}} case Foo = 1 // expected-note {{'Foo' previously declared here}} case Foo = 1 + 1 // expected-error {{invalid redeclaration of 'Foo'}} expected-error {{raw value for enum case must be a literal}} } enum DuplicateMembers6 { case Foo // expected-note 2{{'Foo' previously declared here}} case Foo // expected-error {{invalid redeclaration of 'Foo'}} case Foo // expected-error {{invalid redeclaration of 'Foo'}} } enum DuplicateMembers7 : String { // expected-error {{'DuplicateMembers7' declares raw type 'String', but does not conform to RawRepresentable and conformance could not be synthesized}} case Foo // expected-note {{'Foo' previously declared here}} case Foo = "Bar" // expected-error {{invalid redeclaration of 'Foo'}} } // Refs to duplicated enum cases shouldn't crash the compiler. // rdar://problem/20922401 func check20922401() -> String { let x: DuplicateMembers1 = .Foo switch x { case .Foo: return "Foo" } } enum PlaygroundRepresentation : UInt8 { case Class = 1 case Struct = 2 case Tuple = 3 case Enum = 4 case Aggregate = 5 case Container = 6 case IDERepr = 7 case Gap = 8 case ScopeEntry = 9 case ScopeExit = 10 case Error = 11 case IndexContainer = 12 case KeyContainer = 13 case MembershipContainer = 14 case Unknown = 0xFF static func fromByte(byte : UInt8) -> PlaygroundRepresentation { let repr = PlaygroundRepresentation(rawValue: byte) if repr == .none { return .Unknown } else { return repr! } } } struct ManyLiteralable : ExpressibleByIntegerLiteral, ExpressibleByStringLiteral, Equatable { init(stringLiteral: String) {} init(integerLiteral: Int) {} init(unicodeScalarLiteral: String) {} init(extendedGraphemeClusterLiteral: String) {} } func ==(lhs: ManyLiteralable, rhs: ManyLiteralable) -> Bool { return true } enum ManyLiteralA : ManyLiteralable { case A // expected-note {{raw value previously used here}} expected-note {{raw value implicitly auto-incremented from zero}} case B = 0 // expected-error {{raw value for enum case is not unique}} } enum ManyLiteralB : ManyLiteralable { // expected-error {{'ManyLiteralB' declares raw type 'ManyLiteralable', but does not conform to RawRepresentable and conformance could not be synthesized}} case A = "abc" case B // expected-error {{enum case must declare a raw value when the preceding raw value is not an integer}} } enum ManyLiteralC : ManyLiteralable { case A case B = "0" } // rdar://problem/22476643 public protocol RawValueA: RawRepresentable { var rawValue: Double { get } } enum RawValueATest: Double, RawValueA { case A, B } public protocol RawValueB { var rawValue: Double { get } } enum RawValueBTest: Double, RawValueB { case A, B } enum foo : String { // expected-error {{'foo' declares raw type 'String', but does not conform to RawRepresentable and conformance could not be synthesized}} case bar = nil // expected-error {{cannot convert nil to raw type 'String'}} } // Static member lookup from instance methods struct EmptyStruct {} enum EnumWithStaticMember { static let staticVar = EmptyStruct() func foo() { let _ = staticVar // expected-error {{static member 'staticVar' cannot be used on instance of type 'EnumWithStaticMember'}} } } // SE-0036: struct SE0036_Auxiliary {} enum SE0036 { case A case B(SE0036_Auxiliary) case C(SE0036_Auxiliary) static func staticReference() { _ = A _ = self.A _ = SE0036.A } func staticReferenceInInstanceMethod() { _ = A // expected-error {{enum element 'A' cannot be referenced as an instance member}} {{9-9=SE0036.}} _ = self.A // expected-error {{enum element 'A' cannot be referenced as an instance member}} {{none}} _ = SE0036.A } static func staticReferenceInSwitchInStaticMethod() { switch SE0036.A { case A: break case B(_): break case C(let x): _ = x; break } } func staticReferenceInSwitchInInstanceMethod() { switch self { case A: break // expected-error {{enum element 'A' cannot be referenced as an instance member}} {{10-10=.}} case B(_): break // expected-error {{enum element 'B' cannot be referenced as an instance member}} {{10-10=.}} case C(let x): _ = x; break // expected-error {{enum element 'C' cannot be referenced as an instance member}} {{10-10=.}} } } func explicitReferenceInSwitch() { switch SE0036.A { case SE0036.A: break case SE0036.B(_): break case SE0036.C(let x): _ = x; break } } func dotReferenceInSwitchInInstanceMethod() { switch self { case .A: break case .B(_): break case .C(let x): _ = x; break } } static func dotReferenceInSwitchInStaticMethod() { switch SE0036.A { case .A: break case .B(_): break case .C(let x): _ = x; break } } init() { self = .A self = A // expected-error {{enum element 'A' cannot be referenced as an instance member}} {{12-12=.}} self = SE0036.A self = .B(SE0036_Auxiliary()) self = B(SE0036_Auxiliary()) // expected-error {{enum element 'B' cannot be referenced as an instance member}} {{12-12=.}} self = SE0036.B(SE0036_Auxiliary()) } } enum SE0036_Generic<T> { case A(x: T) func foo() { switch self { case A(_): break // expected-error {{enum element 'A' cannot be referenced as an instance member}} {{10-10=.}} } switch self { case .A(let a): print(a) } switch self { case SE0036_Generic.A(let a): print(a) } } } enum switch {} // expected-error {{keyword 'switch' cannot be used as an identifier here}} expected-note {{if this name is unavoidable, use backticks to escape it}} {{6-12=`switch`}}
apache-2.0
df6e357104c9107e6af680504babefc5
34.615809
407
0.711123
3.845772
false
false
false
false
lanjing99/RxSwiftDemo
12-beginning-rxcocoa/starter/Wundercast/ViewController.swift
1
4364
/* * Copyright (c) 2014-2016 Razeware LLC * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ import UIKit import RxSwift import RxCocoa class ViewController: UIViewController { @IBOutlet weak var searchCityName: UITextField! @IBOutlet weak var tempLabel: UILabel! @IBOutlet weak var humidityLabel: UILabel! @IBOutlet weak var iconLabel: UILabel! @IBOutlet weak var cityNameLabel: UILabel! let bag = DisposeBag() override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. style() ApiController.shared.currentWeather(city: "RxSwift") .observeOn(MainScheduler.instance) .subscribe(onNext: { weather in self.tempLabel.text = "\(weather.temperature) C" self.iconLabel.text = "\(weather.icon)" self.humidityLabel.text = "\(weather.humidity)%" self.cityNameLabel.text = weather.cityName }) .addDisposableTo(bag) // Bind To // let search = searchCityName.rx.text // .filter{ ($0 ?? "").isEmpty == false } // .flatMap{ text in // return ApiController.shared.currentWeather(city: text ?? "Error") // .catchErrorJustReturn(ApiController.Weather.empty) // } // .observeOn(MainScheduler.instance) // // search.map{ "\($0.temperature) C" } // .bind(to: tempLabel.rx.text) // .addDisposableTo(bag) // // search.map{ "\($0.icon)" } // .bind(to: iconLabel.rx.text) // .addDisposableTo(bag) // // search.map{ "\($0.humidity)%" } // .bind(to: humidityLabel.rx.text) // .addDisposableTo(bag) // search.map{ "\($0.cityName)%" } // .bind(to: cityNameLabel.rx.text) // .addDisposableTo(bag) let search = searchCityName.rx.controlEvent(.editingDidEndOnExit).asObservable() .map{ self.searchCityName.text } .flatMap{ text in return ApiController.shared.currentWeather(city: text ?? "Error") .catchErrorJustReturn(ApiController.Weather.empty) } .asDriver(onErrorJustReturn: ApiController.Weather.empty) search.map{ "\($0.temperature) C" } .drive(tempLabel.rx.text) .addDisposableTo(bag) search.map{ "\($0.icon)" } .drive(iconLabel.rx.text) .addDisposableTo(bag) search.map{ "\($0.humidity)%" } .drive(humidityLabel.rx.text) .addDisposableTo(bag) search.map{ "\($0.cityName)%" } .drive(cityNameLabel.rx.text) .addDisposableTo(bag) } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() Appearance.applyBottomLine(to: searchCityName) } override var preferredStatusBarStyle: UIStatusBarStyle { return .lightContent } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Style private func style() { view.backgroundColor = UIColor.aztec searchCityName.textColor = UIColor.ufoGreen tempLabel.textColor = UIColor.cream humidityLabel.textColor = UIColor.cream iconLabel.textColor = UIColor.cream cityNameLabel.textColor = UIColor.cream } }
mit
484ce9afbd7c3e924abac3d02650d6a5
32.060606
84
0.673006
4.320792
false
false
false
false
tguidon/SwiftySports
ArenaKit/SoccerFieldView.swift
1
13752
// // SoccerFieldView.swift // SwiftySports // // Created by Taylor Guidon on 1/17/17. // Copyright © 2017 Taylor Guidon. All rights reserved. // import UIKit import SnapKit class SoccerFieldView: UIView { let soccerField = SoccerField() // UI // soccerFieldView holds the rink's UI elements // dataView holds potential data overlays private let soccerFieldView = UIView() private let dataView = UIView() // all the lines private let centerCircleView = UIView() private let centerCircleDotView = UIView() private let midFieldLineView = UIView() private let homeGoalView = UIView() private let awayGoalView = UIView() private let homeGoalAreaView = UIView() private let awayGoalAreaView = UIView() private let homePenaltyDotView = UIView() private let awayPenaltyDotView = UIView() private let homePenaltyAreaView = UIView() private let awayPenaltyAreaView = UIView() private let homeAreaCurveView = UIView() private let awayAreaCurveView = UIView() private let topLeftCornerView = UIView() private let bottomLeftCornerView = UIView() private let topRightCornerView = UIView() private let bottomRightCornerView = UIView() // Array of all lines private var fieldLines: [UIView] = [] private var fieldDots: [UIView] = [] private var cornerViews: [UIView] = [] private var curveViews: [UIView] = [] // Colors with a redraw on set tp update view var fieldColor: UIColor = UIColor(red:0.55, green:0.84, blue:0.57, alpha:1.00) { didSet { self.backgroundColor = fieldColor draw() } } var lineColor: UIColor = .white { didSet { draw() } } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) // build array of lines fieldLines = [centerCircleView, midFieldLineView, homeGoalView, awayGoalView, homeGoalAreaView, awayGoalAreaView, homePenaltyAreaView, awayPenaltyAreaView] fieldDots = [centerCircleDotView, homePenaltyDotView, awayPenaltyDotView] cornerViews = [topLeftCornerView, bottomLeftCornerView, topRightCornerView, bottomRightCornerView] curveViews = [homeAreaCurveView, awayAreaCurveView] self.backgroundColor = fieldColor self.clipsToBounds = true } func setup() { // Setup the views soccerFieldView.translatesAutoresizingMaskIntoConstraints = false self.addSubview(soccerFieldView) fieldLines.forEach({$0.translatesAutoresizingMaskIntoConstraints = false }) fieldLines.forEach({ soccerFieldView.addSubview($0) }) fieldDots.forEach({ $0.translatesAutoresizingMaskIntoConstraints = false }) fieldDots.forEach({ soccerFieldView.addSubview($0) }) } override func layoutSubviews() { super.layoutSubviews() soccerField.initWithWidth(self.frame.width) draw() } func draw() { // Draw field soccerFieldView.backgroundColor = fieldColor soccerFieldView.layer.borderColor = lineColor.cgColor // must be set for the goals soccerFieldView.layer.borderWidth = soccerField.lineWidth soccerFieldView.clipsToBounds = false soccerFieldView.snp.remakeConstraints { (make) in make.top.equalToSuperview() make.bottom.equalToSuperview() make.left.equalToSuperview().offset(soccerField.soccerFieldOffset) make.right.equalToSuperview().offset(-soccerField.soccerFieldOffset) } // Draw the lines and dots fieldLines.forEach({ $0.layer.borderWidth = soccerField.lineWidth }) fieldLines.forEach({ $0.layer.borderColor = lineColor.cgColor }) fieldLines.forEach({ $0.backgroundColor = .clear }) fieldDots.forEach({ $0.backgroundColor = lineColor }) // Draw the goals homeGoalView.snp.remakeConstraints { (make) in make.right.equalTo(soccerFieldView.snp.left).offset(soccerField.lineWidth) make.width.equalTo(soccerField.goalWidth) make.height.equalTo(soccerField.goalHeight) make.centerY.equalToSuperview() } awayGoalView.snp.remakeConstraints { (make) in make.left.equalTo(soccerFieldView.snp.right).offset(-soccerField.lineWidth) make.width.equalTo(soccerField.goalWidth) make.height.equalTo(soccerField.goalHeight) make.centerY.equalToSuperview() } homeGoalView.backgroundColor = fieldColor awayGoalView.backgroundColor = fieldColor // Draw midfield line midFieldLineView.snp.remakeConstraints { (make) in make.centerX.equalToSuperview() make.width.equalTo(soccerField.lineWidth) make.top.equalToSuperview() make.bottom.equalToSuperview() } // Draw the penalty area homePenaltyAreaView.snp.remakeConstraints { (make) in make.left.equalTo(soccerFieldView.snp.left) make.width.equalTo(soccerField.penaltyAreaWidth) make.height.equalTo(soccerField.penaltyAreaHeight) make.centerY.equalToSuperview() } awayPenaltyAreaView.snp.remakeConstraints { (make) in make.right.equalTo(soccerFieldView.snp.right) make.width.equalTo(soccerField.penaltyAreaWidth) make.height.equalTo(soccerField.penaltyAreaHeight) make.centerY.equalToSuperview() } // Draw the goal area homeGoalAreaView.snp.remakeConstraints { (make) in make.left.equalTo(soccerFieldView.snp.left) make.width.equalTo(soccerField.goalAreaWidth) make.height.equalTo(soccerField.goalAreaHeight) make.centerY.equalToSuperview() } awayGoalAreaView.snp.remakeConstraints { (make) in make.right.equalTo(soccerFieldView.snp.right) make.width.equalTo(soccerField.goalAreaWidth) make.height.equalTo(soccerField.goalAreaHeight) make.centerY.equalToSuperview() } // Draw the penalty dots homePenaltyDotView.snp.remakeConstraints { (make) in make.width.equalTo(soccerField.centerCircleDotWidth) make.height.equalTo(soccerField.centerCircleDotWidth) make.centerY.equalToSuperview() make.centerX.equalTo(soccerFieldView.snp.left).offset(soccerField.penaltyDotOffset) } awayPenaltyDotView.snp.remakeConstraints { (make) in make.width.equalTo(soccerField.centerCircleDotWidth) make.height.equalTo(soccerField.centerCircleDotWidth) make.centerY.equalToSuperview() make.centerX.equalTo(soccerFieldView.snp.right).offset(-soccerField.penaltyDotOffset) } homePenaltyDotView.layer.cornerRadius = soccerField.centerCircleDotWidth / 2 awayPenaltyDotView.layer.cornerRadius = soccerField.centerCircleDotWidth / 2 // add the center circle and dot centerCircleView.snp.remakeConstraints { (make) in make.width.equalTo(soccerField.centerCircleWidth) make.height.equalTo(soccerField.centerCircleWidth) make.center.equalToSuperview() } centerCircleDotView.snp.remakeConstraints { (make) in make.width.equalTo(soccerField.centerCircleDotWidth) make.height.equalTo(soccerField.centerCircleDotWidth) make.center.equalToSuperview() } centerCircleView.layer.cornerRadius = soccerField.centerCircleWidth / 2 centerCircleDotView.layer.cornerRadius = soccerField.centerCircleDotWidth / 2 // add the corners for corner in cornerViews { corner.backgroundColor = .clear corner.translatesAutoresizingMaskIntoConstraints = false soccerFieldView.addSubview(corner) } topLeftCornerView.snp.remakeConstraints { (make) in make.left.equalToSuperview().offset(soccerField.lineWidth / 2) make.top.equalToSuperview() make.width.equalTo(soccerField.cornerWidth) make.height.equalTo(soccerField.cornerWidth) } bottomLeftCornerView.snp.remakeConstraints { (make) in make.left.equalToSuperview().offset(soccerField.lineWidth / 2) make.bottom.equalToSuperview() make.width.equalTo(soccerField.cornerWidth) make.height.equalTo(soccerField.cornerWidth) } topRightCornerView.snp.remakeConstraints { (make) in make.right.equalToSuperview().offset(-soccerField.lineWidth / 2) make.top.equalToSuperview() make.width.equalTo(soccerField.cornerWidth) make.height.equalTo(soccerField.cornerWidth) } bottomRightCornerView.snp.remakeConstraints { (make) in make.right.equalToSuperview().offset(-soccerField.lineWidth / 2) make.bottom.equalToSuperview() make.width.equalTo(soccerField.cornerWidth) make.height.equalTo(soccerField.cornerWidth) } let topLeftShape = CAShapeLayer() let bottomLeftShape = CAShapeLayer() let topRightShape = CAShapeLayer() let bottomRightShape = CAShapeLayer() let cornerShapes = [topLeftShape, bottomLeftShape, topRightShape, bottomRightShape] for corner in cornerShapes { corner.path = returnCornerBezierPath().cgPath corner.strokeColor = lineColor.cgColor corner.fillColor = UIColor.clear.cgColor corner.position = CGPoint(x: 0, y: 0) corner.lineWidth = soccerField.lineWidth } topLeftCornerView.layer.sublayers?.forEach({ (layer) in layer.removeFromSuperlayer() }) topLeftCornerView.layer.addSublayer(topLeftShape) bottomLeftCornerView.layer.addSublayer(bottomLeftShape) topRightCornerView.layer.addSublayer(topRightShape) bottomRightCornerView.layer.addSublayer(bottomRightShape) topLeftCornerView.transform = CGAffineTransform(rotationAngle: .pi / 2) topRightCornerView.transform = CGAffineTransform(rotationAngle: .pi) bottomRightCornerView.transform = CGAffineTransform(rotationAngle: (.pi / 2) * 3) // add the curve right outside the penalty and goal for curve in curveViews { curve.backgroundColor = .clear curve.translatesAutoresizingMaskIntoConstraints = false soccerFieldView.addSubview(curve) } homeAreaCurveView.snp.remakeConstraints { (make) in make.width.equalTo(soccerField.areaCurveWidth) make.height.equalTo(soccerField.areaCurveHeight) make.left.equalTo(homePenaltyAreaView.snp.right).offset(-soccerField.lineWidth / 2) make.centerY.equalToSuperview() } awayAreaCurveView.snp.remakeConstraints { (make) in make.width.equalTo(soccerField.areaCurveWidth) make.height.equalTo(soccerField.areaCurveHeight) make.right.equalTo(awayPenaltyAreaView.snp.left).offset(soccerField.lineWidth / 2) make.centerY.equalToSuperview() } let homeCurveShape = CAShapeLayer() let awayCurveShape = CAShapeLayer() let curveShapes = [homeCurveShape, awayCurveShape] for curve in curveShapes { curve.path = returnGoalCurveBezierPath().cgPath curve.strokeColor = lineColor.cgColor curve.fillColor = UIColor.clear.cgColor curve.position = CGPoint(x: 0, y: 0) curve.lineWidth = soccerField.lineWidth } homeAreaCurveView.layer.sublayers?.forEach({ (layer) in layer.removeFromSuperlayer() }) homeAreaCurveView.layer.addSublayer(homeCurveShape) awayAreaCurveView.layer.sublayers?.forEach({ (layer) in layer.removeFromSuperlayer() }) awayAreaCurveView.layer.addSublayer(awayCurveShape) awayAreaCurveView.transform = CGAffineTransform(rotationAngle: .pi) } func returnCornerBezierPath() -> UIBezierPath { let cornerPath = UIBezierPath() let cornerWidth = soccerField.cornerWidth cornerPath.move(to: CGPoint(x: 1, y: 1)) cornerPath.addLine(to: CGPoint(x: 1, y: cornerWidth - 1)) cornerPath.addLine(to: CGPoint(x: cornerWidth - 1, y: cornerWidth - 1)) cornerPath.addCurve(to: CGPoint(x: 1, y: 1), controlPoint1: CGPoint(x: cornerWidth - 1, y: cornerWidth - 1), controlPoint2: CGPoint(x: cornerWidth - 1, y: 1)) cornerPath.close() return cornerPath } func returnGoalCurveBezierPath() -> UIBezierPath { let bezierPath = UIBezierPath() let areaCurveHeight = soccerField.areaCurveHeight let areaCurveWidth = soccerField.areaCurveWidth bezierPath.move(to: CGPoint(x: 0, y: 0)) bezierPath.addCurve(to: CGPoint(x: 0, y: areaCurveHeight), controlPoint1: CGPoint(x: 0, y: 0), controlPoint2: CGPoint(x: 0, y: areaCurveHeight)) bezierPath.addCurve(to: CGPoint(x: areaCurveWidth, y: areaCurveHeight / 2), controlPoint1: CGPoint(x: 0, y: areaCurveHeight), controlPoint2: CGPoint(x: areaCurveWidth, y: areaCurveHeight * (15/18))) bezierPath.addCurve(to: CGPoint(x: 0, y: 0), controlPoint1: CGPoint(x: areaCurveWidth, y: areaCurveHeight * (4/18)), controlPoint2: CGPoint(x: 0, y: 0)) bezierPath.close() return bezierPath } }
mit
0175d440d57f1fbae175b081150ec2f6
43.073718
206
0.662206
4.651894
false
false
false
false
alexwillrock/PocketRocketNews
PocketRocketNews/Classes/BusinessLayer/Helpers/Helpers.swift
1
1508
// // Helpers.swift // PocketRocketNews // // Created by Алексей on 19.03.17. // Copyright © 2017 Алексей. All rights reserved. // import Foundation extension String { static func validate(urlString: String) -> Bool{ let types: NSTextCheckingResult.CheckingType = .link let detector = try? NSDataDetector(types: types.rawValue) if (detector?.firstMatch(in: urlString, options: .reportCompletion, range: NSMakeRange(0, urlString.characters.count))) != nil{ return true } return false } func firstImage() -> URL? { let pattern = "<img.*?src=\"([^\"]*)\"" do { let regex = try NSRegularExpression(pattern: pattern, options: .caseInsensitive) guard let match = regex.firstMatch(in: self, options: .withoutAnchoringBounds, range: NSMakeRange(0, self.characters.count)) else { return nil } let imageStr = (self as NSString).substring(with: match.rangeAt(1)) return URL(string: imageStr) } catch { print("не удалось преобразовать строку \(self)") return nil } } func rssDate() -> Date{ let dateFormatter = DateFormatter() dateFormatter.dateFormat = "EEE, dd MMM yyyy HH:mm:ss zzz" if let date = dateFormatter.date(from: self){ return date } return Date() } }
mit
f4ae807d3f9591a448495ebbc966bfee
24.701754
143
0.577474
4.425982
false
false
false
false
iOSDevLog/iOSDevLog
201. UI Test/Swift/Common/ListItem.swift
1
5014
/* Copyright (C) 2015 Apple Inc. All Rights Reserved. See LICENSE.txt for this sample’s licensing information Abstract: The `ListItem` class represents the text and completion state of a single item in the list. */ import Foundation /** A `ListItem` object is composed of a text property, a completion status, and an underlying opaque identity that distinguishes one `ListItem` object from another. `ListItem` objects are copyable and archivable. To ensure that the `ListItem` class is unarchivable from an instance that was archived in the Objective-C version of Lister, the `ListItem` class declaration is annotated with @objc(AAPLListItem). This annotation ensures that the runtime name of the `ListItem` class is the same as the `AAPLListItem` class defined in the Objective-C version of the app. It also allows the Objective-C version of Lister to unarchive a `ListItem` instance that was archived in the Swift version. */ @objc(AAPLListItem) final public class ListItem: NSObject, NSCoding, NSCopying, CustomDebugStringConvertible { // MARK: Types /** String constants that are used to archive the stored properties of a `ListItem`. These constants are used to help implement `NSCoding`. */ private struct SerializationKeys { static let text = "text" static let uuid = "uuid" static let complete = "completed" } // MARK: Properties /// The text content for a `ListItem`. public var text: String /// Whether or not this `ListItem` is complete. public var isComplete: Bool /// An underlying identifier to distinguish one `ListItem` from another. private var UUID: NSUUID // MARK: Initializers /** Initializes a `ListItem` instance with the designated text, completion state, and UUID. This is the designated initializer for `ListItem`. All other initializers are convenience initializers. However, this is the only private initializer. - parameter text: The intended text content of the list item. - parameter complete: The item's initial completion state. - parameter UUID: The item's initial UUID. */ private init(text: String, complete: Bool, UUID: NSUUID) { self.text = text self.isComplete = complete self.UUID = UUID } /** Initializes a `ListItem` instance with the designated text and completion state. - parameter text: The text content of the list item. - parameter complete: The item's initial completion state. */ public convenience init(text: String, complete: Bool) { self.init(text: text, complete: complete, UUID: NSUUID()) } /** Initializes a `ListItem` instance with the designated text and a default value for `isComplete`. The default value for `isComplete` is false. - parameter text: The intended text content of the list item. */ public convenience init(text: String) { self.init(text: text, complete: false) } // MARK: NSCopying public func copyWithZone(zone: NSZone) -> AnyObject { return ListItem(text: text, complete: isComplete, UUID: UUID) } // MARK: NSCoding public required init(coder aDecoder: NSCoder) { text = aDecoder.decodeObjectForKey(SerializationKeys.text) as! String isComplete = aDecoder.decodeBoolForKey(SerializationKeys.complete) UUID = aDecoder.decodeObjectForKey(SerializationKeys.uuid) as! NSUUID } public func encodeWithCoder(encoder: NSCoder) { encoder.encodeObject(text, forKey: SerializationKeys.text) encoder.encodeBool(isComplete, forKey: SerializationKeys.complete) encoder.encodeObject(UUID, forKey: SerializationKeys.uuid) } /** Resets the underlying identity of the `ListItem`. If a copy of this item is made, and a call to refreshIdentity() is made afterward, the items will no longer be equal. */ public func refreshIdentity() { UUID = NSUUID() } // MARK: Overrides /** Overrides NSObject's isEqual(_:) instance method to return whether or not the list item is equal to another list item. A `ListItem` is considered to be equal to another `ListItem` if the underyling identities of the two list items are equal. - parameter object: Any object, or nil. - returns: `true` if the object is a `ListItem` and it has the same underlying identity as the receiving instance. `false` otherwise. */ override public func isEqual(object: AnyObject?) -> Bool { if let item = object as? ListItem { return UUID == item.UUID } return false } // MARK: DebugPrintable public override var debugDescription: String { return "\"\(text)\"" } }
mit
8c13f17bd421fa6099e6038fd5b282a9
36.125926
110
0.660415
4.952569
false
false
false
false
noppoMan/SwiftKnex
Sources/Mysql/Protocol/Packet/Field.swift
1
2870
// // Field.swift // SwiftKnex // // Created by Yuki Takei on 2017/01/10. // // struct Field { var tableName: String var name: String var flags: Flags var fieldType: FieldTypes var decimals: UInt8 var origName: String var charSetNr: UInt8 var collation: UInt8 } struct Flags { let flags: UInt16 init(flags: UInt16){ self.flags = flags } func isUnsigned() -> Bool { return self.flags & FieldFlag.unsigned.rawValue == FieldFlag.unsigned.rawValue } } enum FieldParserError: Error { case tooLongColumns(Int) } final class FieldParser { var columns: [Field] = [] let count: Int init(count: Int){ self.count = count } func parse(bytes: [UInt8]) throws -> [Field]? { //EOF Packet if (bytes[0] == 0xfe) && ((bytes.count == 5) || (bytes.count == 1)) { if self.count != columns.count { throw FieldParserError.tooLongColumns(columns.count) } return columns } //Catalog var pos = skipLenEncStr(bytes) // Database [len coded string] var n = skipLenEncStr(Array(bytes[pos..<bytes.count])) pos += n // Table [len coded string] var table: String? (table, n) = lenEncStr(Array(bytes[pos..<bytes.count])) pos += n // Original table [len coded string] n = skipLenEncStr(Array(bytes[pos..<bytes.count])) pos += n // Name [len coded string] var name :String? (name, n) = lenEncStr(Array(bytes[pos..<bytes.count])) pos += n // Original name [len coded string] var origName :String? (origName, n) = lenEncStr(Array(bytes[pos..<bytes.count])) pos += n // Filler [uint8] pos += 1 // Charset [charset, collation uint8] let charSetNr = bytes[pos] let collation = bytes[pos + 1] // Length [uint32] pos += 2 + 4 // Field type [uint8] let fieldType = bytes[pos] pos += 1 // Flags [uint16] let flags = bytes[pos...pos+1].uInt16() pos += 2 // Decimals [uint8] let decimals = bytes[pos] //print(flags, fieldType, FieldFlag(rawValue: flags), FieldTypes(rawValue: fieldType)) let f = Field( tableName: table ?? "", name: name ?? "", flags: Flags(flags: flags), fieldType: FieldTypes(rawValue: fieldType)!, decimals: decimals, origName: origName ?? "", charSetNr: charSetNr, collation: collation ) columns.append(f) return nil } }
mit
1a38be9e9f230ec817c7f8128f4e1f02
23.117647
94
0.509059
4.15942
false
false
false
false
SunLiner/Floral
Floral/Floral/Classes/Home/Home/Controller/HomeTableViewController.swift
1
9567
// // HomeTableViewController.swift // Floral // // Created by ALin on 16/4/25. // Copyright © 2016年 ALin. All rights reserved. // import UIKit import Alamofire private let HomeArticleReuseIdentifier = "HomeArticleReuseIdentifier" class HomeTableViewController: UITableViewController, BlurViewDelegate { // MARK: - 参数/变量 // 文章数组 var articles : [Article]? // 当前页 var currentPage : Int = 0 // 所有的主题分类 var categories : [Category]? // 选中的分类 var selectedCategry : Category? // MARK: - 生命周期方法 override func viewDidLoad() { super.viewDidLoad() setup() } // MARK: - 基本设置 // 设置导航栏和tableview相关 private func setup() { // 设置左右item navigationItem.leftBarButtonItem = UIBarButtonItem(customView: menuBtn) navigationItem.rightBarButtonItem = UIBarButtonItem(title: "TOP", style: .Plain, target: self, action: #selector(HomeTableViewController.toTop)) // 设置titleView navigationItem.titleView = titleBtn // 设置tableview相关 tableView.registerClass(HomeArticleCell.self, forCellReuseIdentifier: HomeArticleReuseIdentifier) tableView.rowHeight = 330; tableView.separatorStyle = .None tableView.tableFooterView = UIView() // 设置下拉刷新控件 refreshControl = RefreshControl(frame: CGRectZero) refreshControl?.addTarget(self, action: #selector(HomeTableViewController.getList), forControlEvents: .ValueChanged) refreshControl?.beginRefreshing() getList() getCategories() } /******* START *********/ // OC中的方法都是运行时加载, 是属于动态的, 用的时候才加载 // SWift中的方法都是编译时加载, 属于静态的. // 如果使用addTarget, 且是private修饰的, 就需要告诉编辑器, 我这个方法是objc的, 属于动态加载 @objc private func toTop() { navigationController?.pushViewController(TopViewController(), animated: true) } @objc private func selectedCategory(btn: UIButton) { btn.selected = !btn.selected // 如果是需要显示菜单, 先设置transform, 然后再动画取消, 就有一上一下的动画 if btn.selected { // 添加高斯视图 tableView.addSubview(blurView) // 添加约束 blurView.snp_makeConstraints(closure: { (make) in make.left.equalTo(tableView) // 这儿的约束必须是设置tableView.contentOffset.y, 而不是设置为和tableView的top相等或者0 // 因为添加到tableview上面的控件, 一滚动就没了... // 为什么+64呢? 因为默认的tableView.contentOffset是(0, -64) make.top.equalTo(tableView.contentOffset.y+64) make.size.equalTo(CGSize(width: ScreenWidth, height: ScreenHeight-49-64)) }) // 设置transform blurView.transform = CGAffineTransformMakeTranslation(0, -ScreenHeight) } UIView.animateWithDuration(0.5, animations: { if btn.selected { // 循转 btn.transform = CGAffineTransformMakeRotation(CGFloat(M_PI_2)) self.blurView.transform = CGAffineTransformIdentity self.tableView.bringSubviewToFront(self.blurView) self.tableView.scrollEnabled = false }else{ // 回去 btn.transform = CGAffineTransformIdentity self.blurView.transform = CGAffineTransformMakeTranslation(0, -ScreenHeight) self.tableView.scrollEnabled = true } }) { (_) in if !btn.selected{ // 如果是向上走, 回去, 需要removeFromSuperview self.blurView.removeFromSuperview() } } } // MARK: 数据获取 /** #1.获得专题的类型:(POST或者GET都行) http://m.htxq.net/servlet/SysCategoryServlet?action=getList */ func getList() { // 如果是刷新的话.重置currentPage if refreshControl!.refreshing { reSet() } // 参数设置 var paramters = [String : AnyObject]() paramters["currentPageIndex"] = "\(currentPage)" paramters["pageSize"] = "5" // 如果选择了分类就设置分类的请求ID if let categry = selectedCategry { paramters["cateId"] = categry.id } NetworkTool.sharedTools.getHomeList(paramters) { (articles, error, loadAll) in // 停止加载数据 if self.refreshControl!.refreshing{ self.refreshControl!.endRefreshing() } if loadAll{ self.showHint("已经到最后了", duration: 2, yOffset: 0) self.currentPage -= 1 return } // 显示数据 if error == nil { if var _ = self.articles{ self.toLoadMore = false self.articles! += articles! }else{ self.articles = articles! } self.tableView.reloadData() }else{ // 获取数据失败后 self.currentPage -= 1 if self.toLoadMore{ self.toLoadMore = false } self.showHint("网络异常", duration: 2, yOffset: 0) } } } private func getCategories() { // 1. 获取本地保存的 if let array = Category.loadLocalCategories() { self.categories = array } // 2. 获取网络数据 NetworkTool.sharedTools.getCategories { (categories, error) in if error == nil{ self.categories = categories // 3. 保存在本地(已在方法中实现了) }else{ ALinLog(error?.domain) } } } /******* END *********/ // MARK: - Table view data source override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return articles?.count ?? 0 } // 是否加载更多 private var toLoadMore = false override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier(HomeArticleReuseIdentifier) as! HomeArticleCell cell.selectionStyle = .None let count = articles?.count ?? 0 if count > 0 { let article = articles![indexPath.row] cell.article = article cell.clickHeadImage = {[weak self] article in let columnist = ColumnistViewController() columnist.author = article?.author self!.navigationController?.pushViewController(columnist, animated: true) } } // 为了增强用户体验, 我们可以学习新浪微博的做法, 当用户滚动到最后一个Cell的时候,自动加载下一页数据 // 每次要用户手动的去加载更多, 就仿佛在告诉用户, 你在我这个APP已经玩了很久了, 该休息了...源源不断的刷新, 就会让用户一直停留在APP上 if count > 0 && indexPath.row == count-1 && !toLoadMore{ toLoadMore = true // 这儿写自增, 竟然有警告, swift语言更新确实有点快, 我记得1.2的时候还是可以的 currentPage += 1 getList() } return cell } // MARK: - Table view data delegate override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { let article = articles![indexPath.row] let detail = DetailViewController() detail.article = article self.navigationController!.pushViewController(detail, animated: true) } // MARK: - 懒加载 private lazy var menuBtn : UIButton = { let btn = UIButton() btn.setImage(UIImage(named: "menu"), forState: .Normal) btn.frame.size = CGSize(width: 20, height: 20) btn.addTarget(self, action: #selector(HomeTableViewController.selectedCategory(_:)), forControlEvents: .TouchUpInside) return btn }() private lazy var blurView : BlurView = { let blur = BlurView(effect: UIBlurEffect(style: .Light)) blur.categories = self.categories blur.delegate = self return blur }() private lazy var titleBtn : TitleBtn = TitleBtn() // MARK: -BlurViewDelegate func blurView(blurView: BlurView, didSelectCategory category: AnyObject) { // 去掉高斯蒙版 selectedCategory(menuBtn) // 设置选中的类型 selectedCategry = category as? Category // 开始动画 refreshControl!.beginRefreshing() // 请求数据 getList() } // MARK: - 内部控制方法 /** 重置数据 */ private func reSet() { // 重置当前页 currentPage = 0 // 重置数组 articles?.removeAll() articles = [Article]() } }
mit
5752db169fdf7f14e23af0f2940bfdb3
30.806691
152
0.567438
4.690789
false
false
false
false
kckd/ClassicAppExporter
classicexp-mac/Pods/SQLite.swift/Sources/SQLite/Core/Statement.swift
10
9623
// // SQLite.swift // https://github.com/stephencelis/SQLite.swift // Copyright © 2014-2015 Stephen Celis. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // #if SQLITE_SWIFT_STANDALONE import sqlite3 #elseif SQLITE_SWIFT_SQLCIPHER import SQLCipher #else import CSQLite #endif /// A single SQL statement. public final class Statement { fileprivate var handle: OpaquePointer? = nil fileprivate let connection: Connection init(_ connection: Connection, _ SQL: String) throws { self.connection = connection try connection.check(sqlite3_prepare_v2(connection.handle, SQL, -1, &handle, nil)) } deinit { sqlite3_finalize(handle) } public lazy var columnCount: Int = Int(sqlite3_column_count(self.handle)) public lazy var columnNames: [String] = (0..<Int32(self.columnCount)).map { String(cString: sqlite3_column_name(self.handle, $0)) } /// A cursor pointing to the current row. public lazy var row: Cursor = Cursor(self) /// Binds a list of parameters to a statement. /// /// - Parameter values: A list of parameters to bind to the statement. /// /// - Returns: The statement object (useful for chaining). public func bind(_ values: Binding?...) -> Statement { return bind(values) } /// Binds a list of parameters to a statement. /// /// - Parameter values: A list of parameters to bind to the statement. /// /// - Returns: The statement object (useful for chaining). public func bind(_ values: [Binding?]) -> Statement { if values.isEmpty { return self } reset() guard values.count == Int(sqlite3_bind_parameter_count(handle)) else { fatalError("\(sqlite3_bind_parameter_count(handle)) values expected, \(values.count) passed") } for idx in 1...values.count { bind(values[idx - 1], atIndex: idx) } return self } /// Binds a dictionary of named parameters to a statement. /// /// - Parameter values: A dictionary of named parameters to bind to the /// statement. /// /// - Returns: The statement object (useful for chaining). public func bind(_ values: [String: Binding?]) -> Statement { reset() for (name, value) in values { let idx = sqlite3_bind_parameter_index(handle, name) guard idx > 0 else { fatalError("parameter not found: \(name)") } bind(value, atIndex: Int(idx)) } return self } fileprivate func bind(_ value: Binding?, atIndex idx: Int) { if value == nil { sqlite3_bind_null(handle, Int32(idx)) } else if let value = value as? Blob { sqlite3_bind_blob(handle, Int32(idx), value.bytes, Int32(value.bytes.count), SQLITE_TRANSIENT) } else if let value = value as? Double { sqlite3_bind_double(handle, Int32(idx), value) } else if let value = value as? Int64 { sqlite3_bind_int64(handle, Int32(idx), value) } else if let value = value as? String { sqlite3_bind_text(handle, Int32(idx), value, -1, SQLITE_TRANSIENT) } else if let value = value as? Int { self.bind(value.datatypeValue, atIndex: idx) } else if let value = value as? Bool { self.bind(value.datatypeValue, atIndex: idx) } else if let value = value { fatalError("tried to bind unexpected value \(value)") } } /// - Parameter bindings: A list of parameters to bind to the statement. /// /// - Throws: `Result.Error` if query execution fails. /// /// - Returns: The statement object (useful for chaining). @discardableResult public func run(_ bindings: Binding?...) throws -> Statement { guard bindings.isEmpty else { return try run(bindings) } reset(clearBindings: false) repeat {} while try step() return self } /// - Parameter bindings: A list of parameters to bind to the statement. /// /// - Throws: `Result.Error` if query execution fails. /// /// - Returns: The statement object (useful for chaining). @discardableResult public func run(_ bindings: [Binding?]) throws -> Statement { return try bind(bindings).run() } /// - Parameter bindings: A dictionary of named parameters to bind to the /// statement. /// /// - Throws: `Result.Error` if query execution fails. /// /// - Returns: The statement object (useful for chaining). @discardableResult public func run(_ bindings: [String: Binding?]) throws -> Statement { return try bind(bindings).run() } /// - Parameter bindings: A list of parameters to bind to the statement. /// /// - Returns: The first value of the first row returned. public func scalar(_ bindings: Binding?...) throws -> Binding? { guard bindings.isEmpty else { return try scalar(bindings) } reset(clearBindings: false) _ = try step() return row[0] } /// - Parameter bindings: A list of parameters to bind to the statement. /// /// - Returns: The first value of the first row returned. public func scalar(_ bindings: [Binding?]) throws -> Binding? { return try bind(bindings).scalar() } /// - Parameter bindings: A dictionary of named parameters to bind to the /// statement. /// /// - Returns: The first value of the first row returned. public func scalar(_ bindings: [String: Binding?]) throws -> Binding? { return try bind(bindings).scalar() } public func step() throws -> Bool { return try connection.sync { try self.connection.check(sqlite3_step(self.handle)) == SQLITE_ROW } } fileprivate func reset(clearBindings shouldClear: Bool = true) { sqlite3_reset(handle) if (shouldClear) { sqlite3_clear_bindings(handle) } } } extension Statement : Sequence { public func makeIterator() -> Statement { reset(clearBindings: false) return self } } extension Statement : IteratorProtocol { public func next() -> [Binding?]? { return try! step() ? Array(row) : nil } } extension Statement : CustomStringConvertible { public var description: String { return String(cString: sqlite3_sql(handle)) } } public struct Cursor { fileprivate let handle: OpaquePointer fileprivate let columnCount: Int fileprivate init(_ statement: Statement) { handle = statement.handle! columnCount = statement.columnCount } public subscript(idx: Int) -> Double { return sqlite3_column_double(handle, Int32(idx)) } public subscript(idx: Int) -> Int64 { return sqlite3_column_int64(handle, Int32(idx)) } public subscript(idx: Int) -> String { return String(cString: UnsafePointer(sqlite3_column_text(handle, Int32(idx)))) } public subscript(idx: Int) -> Blob { if let pointer = sqlite3_column_blob(handle, Int32(idx)) { let length = Int(sqlite3_column_bytes(handle, Int32(idx))) return Blob(bytes: pointer, length: length) } else { // The return value from sqlite3_column_blob() for a zero-length BLOB is a NULL pointer. // https://www.sqlite.org/c3ref/column_blob.html return Blob(bytes: []) } } // MARK: - public subscript(idx: Int) -> Bool { return Bool.fromDatatypeValue(self[idx]) } public subscript(idx: Int) -> Int { return Int.fromDatatypeValue(self[idx]) } } /// Cursors provide direct access to a statement’s current row. extension Cursor : Sequence { public subscript(idx: Int) -> Binding? { switch sqlite3_column_type(handle, Int32(idx)) { case SQLITE_BLOB: return self[idx] as Blob case SQLITE_FLOAT: return self[idx] as Double case SQLITE_INTEGER: return self[idx] as Int64 case SQLITE_NULL: return nil case SQLITE_TEXT: return self[idx] as String case let type: fatalError("unsupported column type: \(type)") } } public func makeIterator() -> AnyIterator<Binding?> { var idx = 0 return AnyIterator { if idx >= self.columnCount { return Optional<Binding?>.none } else { idx += 1 return self[idx - 1] } } } }
unlicense
a400e4f2b1c8f81b486419a30a110e8f
31.390572
106
0.62183
4.341155
false
false
false
false
Flinesoft/BartyCrouch
Sources/BartyCrouchTranslator/BartyCrouchTranslator.swift
1
3832
import Foundation import Microya import MungoHealer /// Translator service to translate texts from one language to another. /// /// NOTE: Currently only supports Microsoft Translator Text API using a subscription key. public final class BartyCrouchTranslator { public typealias Translation = (language: Language, translatedText: String) /// The supported translation services. public enum TranslationService { /// The Microsoft Translator Text API. /// Website: https://docs.microsoft.com/en-us/azure/cognitive-services/translator/translator-info-overview /// /// - Parameters: /// - subscriptionKey: The `Ocp-Apim-Subscription-Key`, also called "Azure secret key" in the docs. case microsoft(subscriptionKey: String) case deepL(apiKey: String) } private let microsoftProvider = ApiProvider<MicrosoftTranslatorApi>(baseUrl: MicrosoftTranslatorApi.baseUrl) private let deepLProvider: ApiProvider<DeepLApi> private let translationService: TranslationService /// Creates a new translator object configured to use the specified translation service. public init( translationService: TranslationService ) { self.translationService = translationService let deepLApiType: DeepLApi.ApiType if case let .deepL(apiKey) = translationService { deepLApiType = apiKey.hasSuffix(":fx") ? .free : .pro } else { deepLApiType = .pro } deepLProvider = ApiProvider<DeepLApi>(baseUrl: DeepLApi.baseUrl(for: deepLApiType)) } /// Translates the given text from a given language to one or multiple given other languages. /// /// - Parameters: /// - text: The text to be translated. /// - sourceLanguage: The source language the given text is in. /// - targetLanguages: An array of other languages to be translated to. /// - Returns: A `Result` wrapper containing an array of translations if the request was successful, else the related error. public func translate( text: String, from sourceLanguage: Language, to targetLanguages: [Language] ) -> Result<[Translation], MungoError> { switch translationService { case let .microsoft(subscriptionKey): let endpoint = MicrosoftTranslatorApi.translate( texts: [text], from: sourceLanguage, to: targetLanguages, microsoftSubscriptionKey: subscriptionKey ) switch microsoftProvider.performRequestAndWait(on: endpoint, decodeBodyTo: [TranslateResponse].self) { case let .success(translateResponses): if let translations: [Translation] = translateResponses.first?.translations .map({ (Language.with(locale: $0.to)!, $0.text) }) { return .success(translations) } else { return .failure( MungoError(source: .internalInconsistency, message: "Could not fetch translation(s) for '\(text)'.") ) } case let .failure(failure): return .failure(MungoError(source: .internalInconsistency, message: failure.localizedDescription)) } case let .deepL(apiKey): var allTranslations: [Translation] = [] for targetLanguage in targetLanguages { let endpoint = DeepLApi.translate(texts: [text], from: sourceLanguage, to: targetLanguage, apiKey: apiKey) switch deepLProvider.performRequestAndWait(on: endpoint, decodeBodyTo: DeepLTranslateResponse.self) { case let .success(translateResponse): let translations: [Translation] = translateResponse.translations.map({ (targetLanguage, $0.text) }) allTranslations.append(contentsOf: translations) case let .failure(failure): return .failure(MungoError(source: .internalInconsistency, message: failure.localizedDescription)) } } return .success(allTranslations) } } }
mit
142e550fe5241ff84eb5b128d8ba421d
37.707071
126
0.700157
4.502938
false
false
false
false
externl/ice
swift/test/Ice/objects/AllTests.swift
1
9633
// // Copyright (c) ZeroC, Inc. All rights reserved. // import Foundation import Ice import PromiseKit import TestCommon func breakRetainCycleB(_ b: B?) { if let b1 = b { if let b2 = b1.theA as? B { b2.theA = nil b2.theB?.theA = nil b2.theB?.theB = nil b2.theB?.theC = nil b2.theB = nil b2.theC = nil // b2 = nil } b1.theA = nil b1.theB = nil b1.theC = nil } } func breakRetainCycleC(_ c: C?) { if let c1 = c { breakRetainCycleB(c1.theB) c1.theB = nil } } func breakRetainCycleD(_ d: D?) { if let d1 = d { breakRetainCycleB(d1.theA as? B) breakRetainCycleB(d1.theB) } } func allTests(_ helper: TestHelper) throws -> InitialPrx { func test(_ value: Bool, file: String = #file, line: Int = #line) throws { try helper.test(value, file: file, line: line) } let output = helper.getWriter() let communicator = helper.communicator() output.write("testing stringToProxy... ") var ref = "initial:\(helper.getTestEndpoint(num: 0))" var base = try communicator.stringToProxy(ref)! output.writeLine("ok") output.write("testing checked cast... ") let initial = try checkedCast(prx: base, type: InitialPrx.self)! try test(initial == base) output.writeLine("ok") output.write("getting B1... ") var b1 = try initial.getB1()! output.writeLine("ok") output.write("getting B2... ") let b2 = try initial.getB2()! output.writeLine("ok") output.write("getting C... ") let c = try initial.getC()! output.writeLine("ok") output.write("getting D... ") let d = try initial.getD()! output.writeLine("ok") output.write("checking consistency... ") try test(b1 !== b2) //test(b1 != c) //test(b1 != d) //test(b2 != c) //test(b2 != d) //test(c != d) try test(b1.theB === b1) try test(b1.theC == nil) try test(b1.theA is B) try test((b1.theA as! B).theA === b1.theA) try test((b1.theA as! B).theB === b1) //test(((B)b1.theA).theC is C) // Redundant -- theC is always of type C try test((b1.theA as! B).theC!.theB === b1.theA) try test(b1.preMarshalInvoked) try test(b1.postUnmarshalInvoked) try test(b1.theA!.preMarshalInvoked) try test(b1.theA!.postUnmarshalInvoked) try test((b1.theA as! B).theC!.preMarshalInvoked) try test((b1.theA as! B).theC!.postUnmarshalInvoked) // More tests possible for b2 and d, but I think this is already // sufficient. try test(b2.theA === b2) try test(d.theC === nil) breakRetainCycleB(b1) breakRetainCycleB(b2) breakRetainCycleC(c) breakRetainCycleD(d) output.writeLine("ok") output.write("getting B1, B2, C, and D all at once... ") let (b1out, b2out, cout, dout) = try initial.getAll() try test(b1out !== nil) try test(b2out !== nil) try test(cout !== nil) try test(dout !== nil) output.writeLine("ok") output.write("checking consistency... ") try test(b1out !== b2out) try test(b1out!.theA === b2out) try test(b1out!.theB === b1out) try test(b1out!.theC === nil) try test(b2out!.theA === b2out) try test(b2out!.theB === b1out) try test(b2out!.theC === cout) try test(cout!.theB === b2out) try test(dout!.theA === b1out) try test(dout!.theB === b2out) try test(dout!.theC === nil) try test(dout!.preMarshalInvoked) try test(dout!.postUnmarshalInvoked) try test(dout!.theA!.preMarshalInvoked) try test(dout!.theA!.postUnmarshalInvoked) try test(dout!.theB!.preMarshalInvoked) try test(dout!.theB!.postUnmarshalInvoked) try test(dout!.theB!.theC!.preMarshalInvoked) try test(dout!.theB!.theC!.postUnmarshalInvoked) breakRetainCycleB(b1out) breakRetainCycleB(b2out) breakRetainCycleC(cout) breakRetainCycleD(dout) output.writeLine("ok") output.write("getting I, J and H... ") let i = try initial.getI() try test(i !== nil) let j = try initial.getJ() try test(j != nil) let h = try initial.getH() try test(h != nil) output.writeLine("ok") output.write("getting K... ") let k = try initial.getK()! let l = k.value as! L try test(l.data == "l") output.writeLine("ok") output.write("testing Value as parameter... ") do { let (v3, v2) = try initial.opValue(L(data: "l")) try test((v2 as! L).data == "l") try test((v3 as! L).data == "l") } do { let (v3, v2) = try initial.opValueSeq([L(data: "l")]) try test((v2[0] as! L).data == "l") try test((v3[0] as! L).data == "l") } do { let (v3, v2) = try initial.opValueMap(["l": L(data: "l")]) try test((v2["l"]! as! L).data == "l") try test((v3["l"]! as! L).data == "l") } output.writeLine("ok") output.write("getting D1... ") do { var d1 = D1(a1: A1(name: "a1"), a2: A1(name: "a2"), a3: A1(name: "a3"), a4: A1(name: "a4")) d1 = try initial.getD1(d1)! try test(d1.a1!.name == "a1") try test(d1.a2!.name == "a2") try test(d1.a3!.name == "a3") try test(d1.a4!.name == "a4") } output.writeLine("ok") output.write("throw EDerived... ") do { try initial.throwEDerived() try test(false) } catch let ederived as EDerived { try test(ederived.a1!.name == "a1") try test(ederived.a2!.name == "a2") try test(ederived.a3!.name == "a3") try test(ederived.a4!.name == "a4") } output.writeLine("ok") output.write("setting G... ") do { try initial.setG(G(theS: S(str: "hello"), str: "g")) } catch is Ice.OperationNotExistException {} output.writeLine("ok") output.write("setting I... ") try initial.setI(i) try initial.setI(j) try initial.setI(h) output.writeLine("ok") output.write("testing sequences...") do { var (retS, outS) = try initial.opBaseSeq([Base]()) (retS, outS) = try initial.opBaseSeq([Base(theS: S(), str: "")]) try test(retS.count == 1 && outS.count == 1) } catch is Ice.OperationNotExistException {} output.writeLine("ok") output.write("testing recursive type... ") let top = Recursive() var p = top do { for depth in 0 ..< 1000 { p.v = Recursive() p = p.v! if (depth < 10 && (depth % 10) == 0) || (depth < 1000 && (depth % 100) == 0) || (depth < 10000 && (depth % 1000) == 0) || (depth % 10000) == 0 { try initial.setRecursive(top) } } try test(!initial.supportsClassGraphDepthMax()) } catch is Ice.UnknownLocalException { // Expected marshal exception from the server(max class graph depth reached) } catch is Ice.UnknownException { // Expected stack overflow from the server(Java only) } try initial.setRecursive(Recursive()) output.writeLine("ok") output.write("testing compact ID...") do { try test(initial.getCompact() != nil) } catch is Ice.OperationNotExistException {} output.writeLine("ok") output.write("testing marshaled results...") b1 = try initial.getMB()! try test(b1.theB === b1) breakRetainCycleB(b1) b1 = try initial.getAMDMBAsync().wait()! try test(b1.theB === b1) breakRetainCycleB(b1) output.writeLine("ok") output.write("testing UnexpectedObjectException...") ref = "uoet:\(helper.getTestEndpoint(num: 0))" base = try communicator.stringToProxy(ref)! let uoet = uncheckedCast(prx: base, type: UnexpectedObjectExceptionTestPrx.self) do { _ = try uoet.op() try test(false) } catch let ex as Ice.UnexpectedObjectException { try test(ex.type == "::Test::AlsoEmpty") try test(ex.expectedType == "::Test::Empty") } catch { output.writeLine("\(error)") try test(false) } output.writeLine("ok") output.write("testing class containing complex dictionary... ") do { let k1 = StructKey(i: 1, s: "1") let k2 = StructKey(i: 2, s: "2") let (m2, m1) = try initial.opM(M(v: [k1: L(data: "one"), k2: L(data: "two")])) try test(m1!.v.count == 2) try test(m2!.v.count == 2) try test(m1!.v[k1]!!.data == "one") try test(m2!.v[k1]!!.data == "one") try test(m1!.v[k2]!!.data == "two") try test(m2!.v[k2]!!.data == "two") } output.writeLine("ok") output.write("testing forward declarations... ") do { let (f11, f12) = try initial.opF1(F1(name: "F11")) try test(f11!.name == "F11") try test(f12!.name == "F12") ref = "F21:\(helper.getTestEndpoint(num: 0))" let (f21, f22) = try initial.opF2(uncheckedCast(prx: communicator.stringToProxy(ref)!, type: F2Prx.self)) try test(f21!.ice_getIdentity().name == "F21") try f21!.op() try test(f22!.ice_getIdentity().name == "F22") if try initial.hasF3() { let (f31, f32) = try initial.opF3(F3(f1: f11, f2: f21)) try test(f31!.f1!.name == "F11") try test(f31!.f2!.ice_getIdentity().name == "F21") try test(f32!.f1!.name == "F12") try test(f32!.f2!.ice_getIdentity().name == "F22") } } output.writeLine("ok") return initial }
gpl-2.0
7689bd0c139322807bf79fb4b59b3698
29.388013
94
0.559535
3.214214
false
true
false
false
ppamorim/Player
Source/Player.swift
3
16648
// Player.swift // // Created by patrick piemonte on 11/26/14. // // The MIT License (MIT) // // Copyright (c) 2014-present patrick piemonte (http://patrickpiemonte.com/) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. import UIKit import Foundation import AVFoundation import CoreGraphics public enum PlaybackState: Int, Printable { case Stopped = 0 case Playing case Paused case Failed public var description: String { get { switch self { case Stopped: return "Stopped" case Playing: return "Playing" case Failed: return "Failed" case Paused: return "Paused" } } } } public enum BufferingState: Int, Printable { case Unknown = 0 case Ready case Delayed public var description: String { get { switch self { case Unknown: return "Unknown" case Ready: return "Ready" case Delayed: return "Delayed" } } } } public protocol PlayerDelegate { func playerReady(player: Player) func playerPlaybackStateDidChange(player: Player) func playerBufferingStateDidChange(player: Player) func playerPlaybackWillStartFromBeginning(player: Player) func playerPlaybackDidEnd(player: Player) } // KVO contexts private var PlayerObserverContext = 0 private var PlayerItemObserverContext = 0 private var PlayerLayerObserverContext = 0 // KVO player keys private let PlayerTracksKey = "tracks" private let PlayerPlayableKey = "playable" private let PlayerDurationKey = "duration" private let PlayerRateKey = "rate" // KVO player item keys private let PlayerStatusKey = "status" private let PlayerEmptyBufferKey = "playbackBufferEmpty" private let PlayerKeepUp = "playbackLikelyToKeepUp" // KVO player layer keys private let PlayerReadyForDisplay = "readyForDisplay" // MARK: - Player public class Player: UIViewController { public var delegate: PlayerDelegate! private var filepath: String! public var path: String! { get { return filepath } set { // Make sure everything is reset beforehand if(self.playbackState == .Playing){ self.pause() } self.setupPlayerItem(nil) filepath = newValue var remoteUrl: NSURL? = NSURL(string: newValue) if remoteUrl != nil && remoteUrl?.scheme != nil { if let asset = AVURLAsset(URL: remoteUrl, options: .None) { self.setupAsset(asset) } } else { var localURL: NSURL? = NSURL(fileURLWithPath: newValue) if let asset = AVURLAsset(URL: localURL, options: .None) { self.setupAsset(asset) } } } } public var muted: Bool! { get { return self.player.muted } set { self.player.muted = newValue } } public var fillMode: String! { get { return self.playerView.fillMode } set { self.playerView.fillMode = newValue } } public var playbackLoops: Bool! { get { return (self.player.actionAtItemEnd == .None) as Bool } set { if newValue.boolValue { self.player.actionAtItemEnd = .None } else { self.player.actionAtItemEnd = .Pause } } } public var playbackFreezesAtEnd: Bool! public var playbackState: PlaybackState! public var bufferingState: BufferingState! public var maximumDuration: NSTimeInterval! { get { if let playerItem = self.playerItem { return CMTimeGetSeconds(playerItem.duration) } else { return CMTimeGetSeconds(kCMTimeIndefinite) } } } private var asset: AVAsset! private var playerItem: AVPlayerItem? private var player: AVPlayer! private var playerView: PlayerView! // MARK: object lifecycle public convenience init() { self.init(nibName: nil, bundle: nil) self.player = AVPlayer() self.player.actionAtItemEnd = .Pause self.player.addObserver(self, forKeyPath: PlayerRateKey, options: (NSKeyValueObservingOptions.New | NSKeyValueObservingOptions.Old) , context: &PlayerObserverContext) self.playbackLoops = false self.playbackFreezesAtEnd = false self.playbackState = .Stopped self.bufferingState = .Unknown } public required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } public override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) } deinit { self.playerView?.player = nil self.delegate = nil NSNotificationCenter.defaultCenter().removeObserver(self) self.playerView?.layer.removeObserver(self, forKeyPath: PlayerReadyForDisplay, context: &PlayerLayerObserverContext) self.player.removeObserver(self, forKeyPath: PlayerRateKey, context: &PlayerObserverContext) self.player.pause() self.setupPlayerItem(nil) } // MARK: view lifecycle public override func loadView() { self.playerView = PlayerView(frame: CGRectZero) self.playerView.fillMode = AVLayerVideoGravityResizeAspect self.playerView.playerLayer.hidden = true self.view = self.playerView self.playerView.layer.addObserver(self, forKeyPath: PlayerReadyForDisplay, options: (NSKeyValueObservingOptions.New | NSKeyValueObservingOptions.Old), context: &PlayerLayerObserverContext) NSNotificationCenter.defaultCenter().addObserver(self, selector: "applicationWillResignActive:", name: UIApplicationWillResignActiveNotification, object: UIApplication.sharedApplication()) NSNotificationCenter.defaultCenter().addObserver(self, selector: "applicationDidEnterBackground:", name: UIApplicationDidEnterBackgroundNotification, object: UIApplication.sharedApplication()) } public override func viewDidDisappear(animated: Bool) { super.viewDidDisappear(animated) if self.playbackState == .Playing { self.pause() } } // MARK: methods public func playFromBeginning() { self.delegate?.playerPlaybackWillStartFromBeginning(self) self.player.seekToTime(kCMTimeZero) self.playFromCurrentTime() } public func playFromCurrentTime() { self.playbackState = .Playing self.delegate?.playerPlaybackStateDidChange(self) self.player.play() } public func pause() { if self.playbackState != .Playing { return } self.player.pause() self.playbackState = .Paused self.delegate?.playerPlaybackStateDidChange(self) } public func stop() { if self.playbackState == .Stopped { return } self.player.pause() self.playbackState = .Stopped self.delegate?.playerPlaybackStateDidChange(self) self.delegate?.playerPlaybackDidEnd(self) } // MARK: private setup private func setupAsset(asset: AVAsset) { if self.playbackState == .Playing { self.pause() } self.bufferingState = .Unknown self.delegate?.playerBufferingStateDidChange(self) self.asset = asset if let updatedAsset = self.asset { self.setupPlayerItem(nil) } let keys: [String] = [PlayerTracksKey, PlayerPlayableKey, PlayerDurationKey] self.asset.loadValuesAsynchronouslyForKeys(keys, completionHandler: { () -> Void in dispatch_sync(dispatch_get_main_queue(), { () -> Void in for key in keys { var error: NSError? let status = self.asset.statusOfValueForKey(key, error:&error) if status == .Failed { self.playbackState = .Failed self.delegate?.playerPlaybackStateDidChange(self) return } } if self.asset.playable.boolValue == false { self.playbackState = .Failed self.delegate?.playerPlaybackStateDidChange(self) return } let playerItem: AVPlayerItem = AVPlayerItem(asset:self.asset) self.setupPlayerItem(playerItem) }) }) } private func setupPlayerItem(playerItem: AVPlayerItem?) { if self.playerItem != nil { self.playerItem?.removeObserver(self, forKeyPath: PlayerEmptyBufferKey, context: &PlayerItemObserverContext) self.playerItem?.removeObserver(self, forKeyPath: PlayerKeepUp, context: &PlayerItemObserverContext) self.playerItem?.removeObserver(self, forKeyPath: PlayerStatusKey, context: &PlayerItemObserverContext) NSNotificationCenter.defaultCenter().removeObserver(self, name: AVPlayerItemDidPlayToEndTimeNotification, object: self.playerItem) NSNotificationCenter.defaultCenter().removeObserver(self, name: AVPlayerItemFailedToPlayToEndTimeNotification, object: self.playerItem) } self.playerItem = playerItem if self.playerItem != nil { self.playerItem?.addObserver(self, forKeyPath: PlayerEmptyBufferKey, options: (NSKeyValueObservingOptions.New | NSKeyValueObservingOptions.Old), context: &PlayerItemObserverContext) self.playerItem?.addObserver(self, forKeyPath: PlayerKeepUp, options: (NSKeyValueObservingOptions.New | NSKeyValueObservingOptions.Old), context: &PlayerItemObserverContext) self.playerItem?.addObserver(self, forKeyPath: PlayerStatusKey, options: (NSKeyValueObservingOptions.New | NSKeyValueObservingOptions.Old), context: &PlayerItemObserverContext) NSNotificationCenter.defaultCenter().addObserver(self, selector: "playerItemDidPlayToEndTime:", name: AVPlayerItemDidPlayToEndTimeNotification, object: self.playerItem) NSNotificationCenter.defaultCenter().addObserver(self, selector: "playerItemFailedToPlayToEndTime:", name: AVPlayerItemFailedToPlayToEndTimeNotification, object: self.playerItem) } self.player.replaceCurrentItemWithPlayerItem(self.playerItem) if self.playbackLoops.boolValue == true { self.player.actionAtItemEnd = .None } else { self.player.actionAtItemEnd = .Pause } } // MARK: NSNotifications public func playerItemDidPlayToEndTime(aNotification: NSNotification) { if self.playbackLoops.boolValue == true || self.playbackFreezesAtEnd.boolValue == true { self.player.seekToTime(kCMTimeZero) } if self.playbackLoops.boolValue == false { self.stop() } } public func playerItemFailedToPlayToEndTime(aNotification: NSNotification) { self.playbackState = .Failed self.delegate?.playerPlaybackStateDidChange(self) } public func applicationWillResignActive(aNotification: NSNotification) { if self.playbackState == .Playing { self.pause() } } public func applicationDidEnterBackground(aNotification: NSNotification) { if self.playbackState == .Playing { self.pause() } } // MARK: KVO public override func observeValueForKeyPath(keyPath: String, ofObject object: AnyObject, change: [NSObject : AnyObject], context: UnsafeMutablePointer<Void>) { switch (keyPath, context) { case (PlayerRateKey, &PlayerObserverContext): true case (PlayerStatusKey, &PlayerItemObserverContext): true case (PlayerKeepUp, &PlayerItemObserverContext): if let item = self.playerItem { self.bufferingState = .Ready self.delegate?.playerBufferingStateDidChange(self) if item.playbackLikelyToKeepUp && self.playbackState == .Playing { self.playFromCurrentTime() } } let status = (change[NSKeyValueChangeNewKey] as! NSNumber).integerValue as AVPlayerStatus.RawValue switch (status) { case AVPlayerStatus.ReadyToPlay.rawValue: self.playerView.playerLayer.player = self.player self.playerView.playerLayer.hidden = false case AVPlayerStatus.Failed.rawValue: self.playbackState = PlaybackState.Failed self.delegate?.playerPlaybackStateDidChange(self) default: true } case (PlayerEmptyBufferKey, &PlayerItemObserverContext): if let item = self.playerItem { if item.playbackBufferEmpty { self.bufferingState = .Delayed self.delegate?.playerBufferingStateDidChange(self) } } let status = (change[NSKeyValueChangeNewKey] as! NSNumber).integerValue as AVPlayerStatus.RawValue switch (status) { case AVPlayerStatus.ReadyToPlay.rawValue: self.playerView.playerLayer.player = self.player self.playerView.playerLayer.hidden = false case AVPlayerStatus.Failed.rawValue: self.playbackState = PlaybackState.Failed self.delegate?.playerPlaybackStateDidChange(self) default: true } case (PlayerReadyForDisplay, &PlayerLayerObserverContext): if self.playerView.playerLayer.readyForDisplay { self.delegate?.playerReady(self) } default: super.observeValueForKeyPath(keyPath, ofObject: object, change: change, context: context) } } } extension Player { public func reset() { } } // MARK: - PlayerView internal class PlayerView: UIView { var player: AVPlayer! { get { return (self.layer as! AVPlayerLayer).player } set { (self.layer as! AVPlayerLayer).player = newValue } } var playerLayer: AVPlayerLayer! { get { return self.layer as! AVPlayerLayer } } var fillMode: String! { get { return (self.layer as! AVPlayerLayer).videoGravity } set { (self.layer as! AVPlayerLayer).videoGravity = newValue } } override class func layerClass() -> AnyClass { return AVPlayerLayer.self } // MARK: object lifecycle convenience init() { self.init(frame: CGRectZero) self.playerLayer.backgroundColor = UIColor.blackColor().CGColor! } override init(frame: CGRect) { super.init(frame: frame) self.playerLayer.backgroundColor = UIColor.blackColor().CGColor! } required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } }
mit
145b337fae5192f442d70197bfec6012
32.097416
200
0.624339
5.276704
false
false
false
false
OEA/Prayer-Time
build/Prayer Time/Classes/Delegates/AppDelegate.swift
1
1379
// // AppDelegate.swift // Prayer Time // // Created by Omer Emre Aslan on 10/06/2017. // Copyright © 2017 Omer Emre Aslan. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { setupWindow() setupViewController() return true } private func setupWindow() { let screenBounds = UIScreen.main.bounds self.window = UIWindow(frame: screenBounds) self.window!.backgroundColor = UIColor.white self.window!.makeKeyAndVisible() } private func setupViewController() { let userDefaults = UserDefaults.standard // let city = userDefaults.string(forKey: "city") let county = userDefaults.string(forKey: "county") // let country = userDefaults.string(forKey: "country") if county != nil { let viewController = ViewController() self.window!.rootViewController = viewController } else { let locationPickerViewController = LocationPickerViewController() self.window!.rootViewController = locationPickerViewController } } }
mit
55e65df7d66337d5cfda2caa4811e086
27.122449
144
0.644412
5.403922
false
false
false
false
IvanVorobei/Sparrow
sparrow/constraints/SPConstraintsAssistent.swift
1
2845
// The MIT License (MIT) // Copyright © 2017 Ivan Vorobei ([email protected]) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. import UIKit public struct SPConstraintsAssistent { static func setEqualSizeConstraint(_ subView: UIView, superVuew: UIView) { subView.translatesAutoresizingMaskIntoConstraints = false; let topMarginConstraint = NSLayoutConstraint( item: subView, attribute: NSLayoutAttribute.topMargin, relatedBy: NSLayoutRelation.equal, toItem: superVuew, attribute: NSLayoutAttribute.top, multiplier: 1, constant: 0) let bottomMarginConstraint = NSLayoutConstraint( item: subView, attribute: NSLayoutAttribute.bottomMargin, relatedBy: NSLayoutRelation.equal, toItem: superVuew, attribute: NSLayoutAttribute.bottom, multiplier: 1, constant: 0) let leadingMarginConstraint = NSLayoutConstraint( item: subView, attribute: NSLayoutAttribute.leadingMargin, relatedBy: NSLayoutRelation.equal, toItem: superVuew, attribute: NSLayoutAttribute.leading, multiplier: 1, constant: 0) let trailingMarginConstraint = NSLayoutConstraint( item: subView, attribute: NSLayoutAttribute.trailingMargin, relatedBy: NSLayoutRelation.equal, toItem: superVuew, attribute: NSLayoutAttribute.trailing, multiplier: 1, constant: 0) superVuew.addConstraints([ topMarginConstraint, bottomMarginConstraint, leadingMarginConstraint, trailingMarginConstraint ]) } }
mit
1af4bf7a995c36a12491ea7996715fad
39.056338
106
0.671238
5.448276
false
false
false
false
sharath-cliqz/browser-ios
Client/Cliqz/Frontend/Browser/ControlCenter/OrientationUtil.swift
2
2614
// // OrientationUtil.swift // Client // // Created by Tim Palade on 2/20/17. // Copyright © 2017 Mozilla. All rights reserved. // import UIKit enum ScreenSizeClass{ case compactWidthCompactHeight case compactWidthRegularHeight case regularWidthCompactHeight case regularWidthRegularHeight case unspecified } enum ControlPanelLayout{ case portrait case landscapeRegularSize case landscapeCompactSize } protocol ControlCenterPanelDelegate: class { func closeControlCenter() func reloadCurrentPage() } class OrientationUtil: NSObject { class func isPortrait() -> Bool { if UIScreen.main.bounds.size.height > UIScreen.main.bounds.size.width { return true } return false } class func screenHeight() -> CGFloat { return UIScreen.main.bounds.size.height } class func screenSizeClass() -> ScreenSizeClass { let traitCollection = UIScreen.main.traitCollection if (traitCollection.horizontalSizeClass == UIUserInterfaceSizeClass.compact){ if (traitCollection.verticalSizeClass == UIUserInterfaceSizeClass.compact) { return .compactWidthCompactHeight } else if (traitCollection.verticalSizeClass == UIUserInterfaceSizeClass.regular){ return .compactWidthRegularHeight } } else if (traitCollection.horizontalSizeClass == UIUserInterfaceSizeClass.regular){ if (traitCollection.verticalSizeClass == UIUserInterfaceSizeClass.compact) { return .regularWidthCompactHeight } else if (traitCollection.verticalSizeClass == UIUserInterfaceSizeClass.regular){ return .regularWidthRegularHeight } } return .unspecified } class func controlPanelLayout() -> ControlPanelLayout { let screenSizeClass = self.screenSizeClass() let screenHeight = self.screenHeight() let iPhone6_landscape_height = CGFloat(375.0) //let iPhone6_landscape_width = CGFloat(667.0) if self.isPortrait(){ return .portrait } else if screenSizeClass != .unspecified { if screenSizeClass != .compactWidthCompactHeight || screenHeight >= iPhone6_landscape_height{ return .landscapeRegularSize } else{ return .landscapeCompactSize } } return .landscapeCompactSize } }
mpl-2.0
e65ce8889e46e18d5d3361a686433528
27.714286
105
0.627248
5.607296
false
false
false
false
JadenGeller/Generational
Sources/Iterate.swift
1
1254
// // Subsequence.swift // Generational // // Created by Jaden Geller on 12/28/15. // Copyright © 2015 Jaden Geller. All rights reserved. // public struct IteratingSequence<Element>: SequenceType { private let initialValue: Element private let transform: Element -> Element public init(initialValue: Element, transform: Element -> Element) { self.initialValue = initialValue self.transform = transform } public func generate() -> IteratingGenerator<Element> { return IteratingGenerator(initialValue: initialValue, transform: transform) } } public struct IteratingGenerator<Element>: GeneratorType { private var value: Element private let transform: Element -> Element public init(initialValue: Element, transform: Element -> Element) { self.value = initialValue self.transform = transform } public mutating func next() -> Element? { let returnValue = value value = transform(value) return returnValue } } public func iterate<Element>(initialValue initialValue: Element, transform: Element -> Element) -> IteratingSequence<Element> { return IteratingSequence(initialValue: initialValue, transform: transform) }
mit
92c26c66a809e2b18ea6e64b3fe6eb68
29.560976
127
0.693536
4.972222
false
false
false
false
j-chao/venture
source/venture/BudgetVC.swift
1
4314
// // BudgetVC.swift // venture // // Created by Justin Chao on 4/18/17. // Copyright © 2017 Group1. All rights reserved. // import UIKit import Firebase class BudgetVC: UIViewController { let userID = FIRAuth.auth()?.currentUser!.uid let myRequest = DispatchGroup() var food:String? var transportation:String? var lodging:String? var attractions:String? var misc:String? var total:String? @IBOutlet weak var foodField: UITextField! @IBOutlet weak var transportationField: UITextField! @IBOutlet weak var lodgingField: UITextField! @IBOutlet weak var attractionsField: UITextField! @IBOutlet weak var miscField: UITextField! @IBOutlet weak var totalField: UILabel! override func viewDidLoad() { myRequest.enter() self.setBackground() super.viewDidLoad() self.observeDataFromFirebase() myRequest.notify(queue: DispatchQueue.main, execute: { self.foodField.text = self.food! self.transportationField.text = self.transportation! self.lodgingField.text = self.lodging! self.attractionsField.text = self.attractions! self.miscField.text = self.misc! self.totalField.text = "$" + String(Int(self.food!)! + Int(self.transportation!)! + Int(self.lodging!)! + Int(self.attractions!)! + Int(self.misc!)!) }) } override func viewWillDisappear(_ animated: Bool) { self.saveDataToFirebase() } func saveDataToFirebase() { if (foodField.text?.isEmpty)! || (transportationField.text?.isEmpty)! || (lodgingField.text?.isEmpty)! || (attractionsField.text?.isEmpty)! || (miscField.text?.isEmpty)! || (totalField.text?.isEmpty)! { self.presentAllFieldsAlert() } else { let ref = FIRDatabase.database().reference().child("users/\(userID!)/budgets/\(passedTrip)") ref.child("food").setValue(foodField.text) ref.child("transportation").setValue(transportationField.text) ref.child("lodging").setValue(lodgingField.text) ref.child("attractions").setValue(attractionsField.text) ref.child("misc").setValue(miscField.text) ref.child("total").setValue(totalField.text) } } func observeDataFromFirebase() { let ref = FIRDatabase.database().reference().child("users/\(userID!)/budgets/\(passedTrip)") ref.observeSingleEvent(of:.value, with: { snapshot in if snapshot.exists() { self.food = (snapshot.value as! NSDictionary) ["food"] as? String self.transportation = (snapshot.value as! NSDictionary) ["transportation"] as? String self.lodging = (snapshot.value as! NSDictionary) ["lodging"] as? String self.attractions = (snapshot.value as! NSDictionary) ["attractions"] as? String self.misc = (snapshot.value as! NSDictionary) ["misc"] as? String self.total = (snapshot.value as! NSDictionary) ["total"] as? String self.myRequest.leave() } }) } @IBAction func percentagesBtn(_ sender: Any) { let foodAmt = Int(self.foodField.text!)! let transportAmt = Int(self.transportationField.text!)! let lodgingAmt = Int(self.lodgingField.text!)! let attractionsAmt = Int(self.attractionsField.text!)! let miscAmt = Int(self.miscField.text!)! let totalAmt = foodAmt + transportAmt + lodgingAmt + attractionsAmt + miscAmt self.totalField.text = "$" + "\(totalAmt)" } func presentAllFieldsAlert() { let alert = UIAlertController(title: "Error", message: "Please fill out all fields." , preferredStyle: .alert) let OKAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default) { (action:UIAlertAction) in } alert.addAction(OKAction) self.present(alert, animated: true, completion:nil) return } func textFieldShouldReturn(_ textField: UITextField) -> Bool { textField.resignFirstResponder() return true } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { self.view.endEditing(true) } }
mit
68f0b26d0ab8eeee5b681aecfec3d140
38.935185
210
0.629956
4.3001
false
false
false
false
Stiivi/ParserCombinator
Tests/ParserCombinatorTests/ParserCombinatorTests.swift
1
5395
// // ParserCombinatorTests.swift // ParserCombinatorTests // // Created by Stefan Urbanek on 01/01/16. // Copyright © 2016 Stefan Urbanek. All rights reserved. // import XCTest @testable import ParserCombinator class ParserCombinatorTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func parse<R>(_ source: [String], parser:Parser<String,R>, onFailure: ((String) -> Void)? = nil) -> R? { let stream = source.stream() let result = parser.parse(stream) switch result { case .OK(let value): let (head, _) = value return head default: if let f = onFailure { f(result.description) } return nil } } func testSucceed() { let parser: Parser<String, String> = succeed("hello") var source = ["something"] var result = self.parse(source, parser:parser) XCTAssertEqual(result, "hello") source = [] result = self.parse(source, parser: parser) XCTAssertEqual(result, "hello") } func testFail() { let parser: Parser<String, String> = fail("parser error") let source = ["hello"] let result = self.parse(source, parser:parser) XCTAssertNil(result) } func testSatisfy() { let parser = satisfy("'hello'") { $0 == "hello" } let validSource = ["hello"] let failedSource = ["good bye"] var result: String? result = self.parse(validSource, parser: parser) XCTAssertEqual(result, "hello") result = self.parse(failedSource, parser: parser) XCTAssertNil(result) } func testExpect() { let parser = expect("hello") let validSource = ["hello"] let failedSource = ["good bye"] var result: String? result = self.parse(validSource, parser: parser) XCTAssertEqual(result, "hello") result = self.parse(failedSource, parser: parser) XCTAssertNil(result) } func testAlternate() { let parser = alternate(expect("left"), expect("right")) var source = ["left"] var result = self.parse(source, parser:parser) XCTAssertEqual(result, "left") source = ["right"] result = self.parse(source, parser:parser) XCTAssertEqual(result, "right") source = ["up"] result = self.parse(source, parser:parser) XCTAssertNil(result) } func testThen() { let parser = then(expect("left"), expect("right")) let source = ["left", "right"] let result = self.parse(source, parser: parser) XCTAssertEqual(result!.0, "left") XCTAssertEqual(result!.1, "right") } func testThenDifferent() { // expect(1) => { Int($0)! } + expect("thing") // Result: (1, "thing") let number = using(expect("1")) { return Int($0)! } let string = expect("thing") let parser = then(number, string) let source = ["1", "right"] let result = self.parse(source, parser: parser) XCTAssertNil(result) } func testMany() { let parser = many(expect("la")) var source = ["la", "la", "la"] var result = self.parse(source, parser: parser) result = self.parse(source, parser: parser) XCTAssertEqual(result!, ["la", "la", "la"]) source = ["la", "la", "bum"] result = self.parse(source, parser: parser) XCTAssertEqual(result!, ["la", "la"]) source = ["bum"] result = self.parse(source, parser: parser) XCTAssertEqual(result!, []) } func testThenDifferentMany() { let manya = many(expect("a")) let parser = then(expect("left"), manya) let source = ["left", "right"] let result = self.parse(source, parser: parser) XCTAssertEqual(result!.0, "left") XCTAssertEqual(result!.1, []) } func testSome() { let parser = some(expect("la")) var source = ["la", "la", "la"] var result = self.parse(source, parser: parser) XCTAssertEqual(result!, ["la", "la", "la"]) source = ["la", "la", "bum"] result = self.parse(source, parser: parser) XCTAssertEqual(result!, ["la", "la"]) source = ["bum"] result = self.parse(source, parser: parser) XCTAssertNil(result) } func testSimpleGrammar() { let parser = §"SAY" *> item("greeting") … §"TO" *> item("name") let source = ["SAY", "Good Night", "TO", "Moon"] let result = self.parse(source, parser: parser) XCTAssertEqual(result!.0, "Good Night") XCTAssertEqual(result!.1, "Moon") } func testSeparated() { let parser = separated(item("item"), expect(",")) var source = ["a", ",", "b", ",", "c"] var result = self.parse(source, parser: parser) XCTAssertEqual(result!, ["a", "b", "c"]) source = ["a", ",", "b", "=", "c"] result = self.parse(source, parser: parser) XCTAssertEqual(result!, ["a", "b"]) } }
mit
f1190e11334796f4890f2cb054d641a1
26.222222
111
0.561224
4.049587
false
true
false
false
jpavley/Emoji-Tac-Toe2
television/EmojiTacToeViewController.swift
1
1456
// // EmojiTacToeViewController.swift // Emoji Tac Toe // television // // Created by John Pavley on 8/14/16. // Copyright © 2016 Epic Loot. All rights reserved. // import UIKit class EmojiTacToeViewController: UIViewController { @IBOutlet weak var buttonOne: UIButton! @IBOutlet weak var buttonTwo: UIButton! override func didUpdateFocusInContext(context: UIFocusUpdateContext, withAnimationCoordinator coordinator: UIFocusAnimationCoordinator) { super.didUpdateFocusInContext(context, withAnimationCoordinator: coordinator) if let nextFocusedView = context.nextFocusedView { if 1...9 ~= nextFocusedView.tag { let button = view.viewWithTag(nextFocusedView.tag) as! UIButton button.backgroundColor = UIColor.yellowColor() } } if let previouslyFocusedView = context.previouslyFocusedView { if 1...9 ~= previouslyFocusedView.tag { let button = view.viewWithTag(previouslyFocusedView.tag) as! UIButton button.backgroundColor = UIColor.whiteColor() } } } 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. } }
mit
4d6ffd07211988cf27af814ae6cdeac0
29.957447
141
0.64811
5.349265
false
false
false
false
MichaelSelsky/TheBeatingAtTheGates
BeatingGatesCommon/WallEntity.swift
1
4351
// // WallEntity.swift // The Beating at the Gates // // Created by Grant Butler on 1/31/16. // Copyright © 2016 Grant J. Butler. All rights reserved. // import GameplayKit import SpriteKit public class WallEntity: GKEntity { private lazy var minorDamageSmokeNode: SKEmitterNode = { [unowned self] in guard let smokePath = NSBundle(forClass: self.dynamicType).pathForResource("CastleDamagedParticle", ofType: "sks") else { fatalError("Missing CastleDamagedParticle") } let node = NSKeyedUnarchiver.unarchiveObjectWithFile(smokePath) as! SKEmitterNode node.hidden = true node.paused = true node.zPosition = 30 return node }() private lazy var majorDamageSmokeNode: SKEmitterNode = { [unowned self] in guard let smokePath = NSBundle(forClass: self.dynamicType).pathForResource("CastleDamagedParticle", ofType: "sks") else { fatalError("Missing CastleDamagedParticle") } let node = NSKeyedUnarchiver.unarchiveObjectWithFile(smokePath) as! SKEmitterNode node.hidden = true node.paused = true node.zPosition = 30 return node }() private lazy var explosionNode: SKEmitterNode = { [unowned self] in guard let smokePath = NSBundle(forClass: self.dynamicType).pathForResource("CastleExplosionParticle", ofType: "sks") else { fatalError("Missing CastleExplosionParticle") } let node = NSKeyedUnarchiver.unarchiveObjectWithFile(smokePath) as! SKEmitterNode node.hidden = true node.paused = true node.zPosition = 30 return node }() var renderComponent: RenderComponent { guard let renderComponent = componentForClass(RenderComponent.self) else { fatalError("A WallEntity must have a RenderComponent.") } return renderComponent } var teamComponent: TeamComponent { guard let teamComponent = componentForClass(TeamComponent.self) else { fatalError("A WallEntity must have a TeamComponent.") } return teamComponent } public init(team: Team) { super.init() let teamComponent = TeamComponent(team: team) addComponent(teamComponent) let healthComponent = HealthComponent(health: 10) addComponent(healthComponent) let renderComponent = RenderComponent(entity: self) addComponent(renderComponent) let orientationComponent = OrientationComponent(node: renderComponent.node) orientationComponent.direction = team.direction addComponent(orientationComponent) let spriteNode = SKSpriteNode(imageNamed: "CastleWall") spriteNode.name = "CastleWall" renderComponent.node.addChild(spriteNode) } override public func updateWithDeltaTime(seconds: NSTimeInterval) { if let health = self.componentForClass(HealthComponent.self) { // Dead. Do some particle effects or something? if health.isDead() { if explosionNode.parent == nil { minorDamageSmokeNode.hidden = true minorDamageSmokeNode.paused = true minorDamageSmokeNode.removeFromParent() majorDamageSmokeNode.hidden = true majorDamageSmokeNode.paused = true majorDamageSmokeNode.removeFromParent() renderComponent.node.addChild(explosionNode) explosionNode.hidden = false explosionNode.paused = false let delay = SKAction.waitForDuration(0.25) let remove = SKAction.removeFromParent() renderComponent.node.runAction(SKAction.sequence([delay, remove])) } } else { switch health.health { case 4...7 where minorDamageSmokeNode.hidden: let castleWall = renderComponent.node.childNodeWithName("CastleWall")! let frame = castleWall.calculateAccumulatedFrame() let initialOffset = frame.width / 4.0 minorDamageSmokeNode.position = CGPoint(x: initialOffset , y: frame.height / 4.0) renderComponent.node.addChild(minorDamageSmokeNode) minorDamageSmokeNode.hidden = false minorDamageSmokeNode.paused = false case 0...3 where majorDamageSmokeNode.hidden: let castleWall = renderComponent.node.childNodeWithName("CastleWall")! let frame = castleWall.calculateAccumulatedFrame() let initialOffset = frame.width / 4.0 majorDamageSmokeNode.position = CGPoint(x: initialOffset , y: -frame.height / 4.0) renderComponent.node.addChild(majorDamageSmokeNode) majorDamageSmokeNode.hidden = false majorDamageSmokeNode.paused = false default: break } } } } }
mit
531306b8b408ede2a2160c7cc10b77e0
33.8
173
0.735862
4.076851
false
false
false
false
eggswift/ESTabBarController
ESTabBarControllerExample/ESTabBarControllerExample/Me/WebViewController.swift
1
1343
// // WebViewController.swift // ESPullToRefreshExample // // Created by lihao on 16/5/6. // Copyright © 2018年 egg swift. All rights reserved. // import UIKit public class WebViewController: UIViewController, UIWebViewDelegate { @IBOutlet weak var dismissButton: UIButton! public class func instanceFromStoryBoard() -> WebViewController { return UIStoryboard(name: "WebView", bundle: nil).instantiateInitialViewController() as! WebViewController } @IBOutlet weak var webView: UIWebView! override public func viewDidLoad() { super.viewDidLoad() self.title = "https://github.com/eggswift" self.webView.delegate = self self.webView.loadRequest(URLRequest(url: URL(string: "https://github.com/eggswift")!)) self.webView.scrollView.bounces = true self.webView.scrollView.alwaysBounceVertical = true self.dismissButton.layer.borderWidth = 2 self.dismissButton.layer.borderColor = UIColor.lightGray.cgColor self.dismissButton.layer.cornerRadius = 12 } @IBAction func dismissAction(_ sender: Any) { if let navigationController = self.navigationController { navigationController.popViewController(animated: true) } else { self.dismiss(animated: true, completion: nil) } } }
mit
228d55cbdf8268c1ef4c2e00fed50264
32.5
108
0.690299
4.802867
false
false
false
false
kelvin13/maxpng
examples/metadata/main.swift
1
774
import PNG let path:String = "examples/metadata/example" guard var image:PNG.Data.Rectangular = try .decompress(path: "\(path).png") else { fatalError("failed to open file '\(path).png'") } if let time:PNG.TimeModified = image.metadata.time { print(time) } if let gamma:PNG.Gamma = image.metadata.gamma { print(gamma) } if let physicalDimensions:PNG.PhysicalDimensions = image.metadata.physicalDimensions { print(physicalDimensions) } //print(image.metadata) image.metadata.time = .init(year: 1992, month: 8, day: 3, hour: 0, minute: 0, second: 0) try image.compress(path: "\(path)-newtime.png") if let time:PNG.TimeModified = (try PNG.Data.Rectangular.decompress(path: "\(path)-newtime.png")).map(\.metadata.time) ?? nil { print(time) }
gpl-3.0
9d267ffe1aca96910cdfe5c23fa4fef6
21.764706
98
0.698966
3.108434
false
false
false
false
MediaBrowser/Emby.ApiClient.Swift
Emby.ApiClient/model/apiclient/ServerDiscoveryInfo.swift
1
1267
// // ServerDiscoveryInfo.swift // EmbyApiClient // import Foundation public class ServerDiscoveryInfo: JSONSerializable { let address: String let id: String let name: String public required init(jSON: JSON_Object) { // {"Address":"http://192.168.1.68:8096","Id":"942bef179117406d852072d207a74a23","Name":"Vedrans-Mini.lan"} guard let address = jSON["Address"] as? String, let id = jSON["Id"] as? String, let name = jSON["Name"] as? String else { preconditionFailure("ServerDiscoveryInfo missing required field") } self.address = address self.id = id self.name = name } public func toJsonString() -> String { let dict = ["Address" : address, "Id": id, "Name": name] let jsonData = try! JSONSerialization.data(withJSONObject: dict, options: JSONSerialization.WritingOptions.prettyPrinted) return String(data: jsonData, encoding: String.Encoding.ascii)! } } extension ServerDiscoveryInfo: Hashable { public var hashValue: Int { return id.hashValue } } public func ==(lhs: ServerDiscoveryInfo, rhs: ServerDiscoveryInfo) -> Bool { return lhs.id == rhs.id }
mit
f9e0fa37cb04fda07a5c713f3162f1f9
27.795455
129
0.621152
4.280405
false
false
false
false
leejw51/BumblebeeNet
TwitterMessenger/TwitterMessenger/TwitterManager.swift
1
94074
// // TwitterManager.swift // TwitterMessenger // // Created by Jongwhan Lee on 26/07/2017. // Copyright © 2017 Jongwhan Lee. All rights reserved. // import Foundation import Dispatch import Accounts import Social import UIKit import SafariServices extension Data { var rawBytes: [UInt8] { return [UInt8](self) } init(bytes: [UInt8]) { self.init(bytes: UnsafePointer<UInt8>(bytes), count: bytes.count) } mutating func append(_ bytes: [UInt8]) { self.append(UnsafePointer<UInt8>(bytes), count: bytes.count) } } extension Dictionary { func filter(_ predicate: (Element) -> Bool) -> Dictionary { var filteredDictionary = Dictionary() for element in self where predicate(element) { filteredDictionary[element.key] = element.value } return filteredDictionary } var queryString: String { var parts = [String]() for (key, value) in self { let query: String = "\(key)=\(value)" parts.append(query) } return parts.joined(separator: "&") } func urlEncodedQueryString(using encoding: String.Encoding) -> String { var parts = [String]() for (key, value) in self { let keyString = "\(key)".urlEncodedString() let valueString = "\(value)".urlEncodedString(keyString == "status") let query: String = "\(keyString)=\(valueString)" parts.append(query) } return parts.joined(separator: "&") } func stringifiedDictionary() -> Dictionary<String, String> { var dict = [String: String]() for (key, value) in self { dict[String(describing: key)] = String(describing: value) } return dict } } infix operator +| func +| <K,V>(left: Dictionary<K,V>, right: Dictionary<K,V>) -> Dictionary<K,V> { var map = Dictionary<K,V>() for (k, v) in left { map[k] = v } for (k, v) in right { map[k] = v } return map } public struct HMAC { internal static func sha1(key: Data, message: Data) -> Data? { var key = key.rawBytes let message = message.rawBytes // key if key.count > 64 { key = SHA1(message: Data(bytes: key)).calculate().rawBytes } if (key.count < 64) { key = key + [UInt8](repeating: 0, count: 64 - key.count) } // var opad = [UInt8](repeating: 0x5c, count: 64) for (idx, _) in key.enumerated() { opad[idx] = key[idx] ^ opad[idx] } var ipad = [UInt8](repeating: 0x36, count: 64) for (idx, _) in key.enumerated() { ipad[idx] = key[idx] ^ ipad[idx] } let ipadAndMessageHash = SHA1(message: Data(bytes: (ipad + message))).calculate().rawBytes let finalHash = SHA1(message: Data(bytes: opad + ipadAndMessageHash)).calculate().rawBytes let mac = finalHash return Data(bytes: UnsafePointer<UInt8>(mac), count: mac.count) } } public enum JSON : Equatable, CustomStringConvertible { case string(String) case number(Double) case object(Dictionary<String, JSON>) case array(Array<JSON>) case bool(Bool) case null case invalid public init(_ rawValue: Any) { switch rawValue { case let json as JSON: self = json case let array as [JSON]: self = .array(array) case let dict as [String: JSON]: self = .object(dict) case let data as Data: do { let object = try JSONSerialization.jsonObject(with: data, options: []) self = JSON(object) } catch { self = .invalid } case let array as [Any]: let newArray = array.map { JSON($0) } self = .array(newArray) case let dict as [String: Any]: var newDict = [String: JSON]() for (key, value) in dict { newDict[key] = JSON(value) } self = .object(newDict) case let string as String: self = .string(string) case let number as NSNumber: self = number.isBoolean ? .bool(number.boolValue) : .number(number.doubleValue) case _ as Optional<Any>: self = .null default: assert(true, "This location should never be reached") self = .invalid } } public var string : String? { guard case .string(let value) = self else { return nil } return value } public var integer : Int? { guard case .number(let value) = self else { return nil } return Int(value) } public var double : Double? { guard case .number(let value) = self else { return nil } return value } public var object : [String: JSON]? { guard case .object(let value) = self else { return nil } return value } public var array : [JSON]? { guard case .array(let value) = self else { return nil } return value } public var bool : Bool? { guard case .bool(let value) = self else { return nil } return value } public subscript(key: String) -> JSON { guard case .object(let dict) = self, let value = dict[key] else { return .invalid } return value } public subscript(index: Int) -> JSON { guard case .array(let array) = self, array.count > index else { return .invalid } return array[index] } static func parse(jsonData: Data) throws -> JSON { do { let object = try JSONSerialization.jsonObject(with: jsonData, options: .mutableContainers) return JSON(object) } catch { throw SwifterError(message: "\(error)", kind: .jsonParseError) } } static func parse(string : String) throws -> JSON { do { guard let data = string.data(using: .utf8, allowLossyConversion: false) else { throw SwifterError(message: "Cannot parse invalid string", kind: .jsonParseError) } return try parse(jsonData: data) } catch { throw SwifterError(message: "\(error)", kind: .jsonParseError) } } func stringify(_ indent: String = " ") -> String? { guard self != .invalid else { assert(true, "The JSON value is invalid") return nil } return prettyPrint(indent, 0) } public var description: String { guard let string = stringify() else { return "<INVALID JSON>" } return string } private func prettyPrint(_ indent: String, _ level: Int) -> String { let currentIndent = (0...level).map({ _ in "" }).joined(separator: indent) let nextIndent = currentIndent + " " switch self { case .bool(let bool): return bool ? "true" : "false" case .number(let number): return "\(number)" case .string(let string): return "\"\(string)\"" case .array(let array): return "[\n" + array.map { "\(nextIndent)\($0.prettyPrint(indent, level + 1))" }.joined(separator: ",\n") + "\n\(currentIndent)]" case .object(let dict): return "{\n" + dict.map { "\(nextIndent)\"\($0)\" : \($1.prettyPrint(indent, level + 1))"}.joined(separator: ",\n") + "\n\(currentIndent)}" case .null: return "null" case .invalid: assert(true, "This should never be reached") return "" } } } public func ==(lhs: JSON, rhs: JSON) -> Bool { switch (lhs, rhs) { case (.null, .null): return true case (.bool(let lhsValue), .bool(let rhsValue)): return lhsValue == rhsValue case (.string(let lhsValue), .string(let rhsValue)): return lhsValue == rhsValue case (.number(let lhsValue), .number(let rhsValue)): return lhsValue == rhsValue case (.array(let lhsValue), .array(let rhsValue)): return lhsValue == rhsValue case (.object(let lhsValue), .object(let rhsValue)): return lhsValue == rhsValue default: return false } } extension JSON: ExpressibleByStringLiteral, ExpressibleByIntegerLiteral, ExpressibleByBooleanLiteral, ExpressibleByFloatLiteral, ExpressibleByArrayLiteral, ExpressibleByDictionaryLiteral, ExpressibleByNilLiteral { public init(stringLiteral value: StringLiteralType) { self.init(value) } public init(extendedGraphemeClusterLiteral value: StringLiteralType) { self.init(value) } public init(unicodeScalarLiteral value: StringLiteralType) { self.init(value) } public init(integerLiteral value: IntegerLiteralType) { self.init(value) } public init(booleanLiteral value: BooleanLiteralType) { self.init(value) } public init(floatLiteral value: FloatLiteralType) { self.init(value) } public init(dictionaryLiteral elements: (String, Any)...) { let object = elements.reduce([String: Any]()) { $0 + [$1.0: $1.1] } self.init(object) } public init(arrayLiteral elements: AnyObject...) { self.init(elements) } public init(nilLiteral: ()) { self.init(NSNull()) } } private func +(lhs: [String: Any], rhs: [String: Any]) -> [String: Any] { var lhs = lhs for element in rhs { lhs[element.key] = element.value } return lhs } private extension NSNumber { var isBoolean: Bool { return NSNumber(value: true).objCType == self.objCType } } /// If `rhs` is not `nil`, assign it to `lhs`. infix operator ??= : AssignmentPrecedence // { associativity right precedence 90 assignment } // matches other assignment operators /// If `rhs` is not `nil`, assign it to `lhs`. func ??=<T>(lhs: inout T?, rhs: T?) { guard let rhs = rhs else { return } lhs = rhs } extension Scanner { #if os(macOS) || os(iOS) func scanString(string: String) -> String? { var buffer: NSString? scanString(string, into: &buffer) return buffer as String? } func scanUpToString(_ string: String) -> String? { var buffer: NSString? scanUpTo(string, into: &buffer) return buffer as String? } #endif #if os(Linux) var isAtEnd: Bool { // This is the same check being done inside NSScanner.swift to // determine if the scanner is at the end. return scanLocation == string.utf16.count } #endif } struct SHA1 { var message: Data /** Common part for hash calculation. Prepare header data. */ func prepare(_ len:Int = 64) -> Data { var tmpMessage: Data = self.message // Step 1. Append Padding Bits tmpMessage.append([0x80]) // append one bit (Byte with one bit) to message // append "0" bit until message length in bits ≡ 448 (mod 512) while tmpMessage.count % len != (len - 8) { tmpMessage.append([0x00]) } return tmpMessage } func calculate() -> Data { //var tmpMessage = self.prepare() let len = 64 let h: [UInt32] = [0x67452301, 0xEFCDAB89, 0x98BADCFE, 0x10325476, 0xC3D2E1F0] var tmpMessage: Data = self.message // Step 1. Append Padding Bits tmpMessage.append([0x80]) // append one bit (Byte with one bit) to message // append "0" bit until message length in bits ≡ 448 (mod 512) while tmpMessage.count % len != (len - 8) { tmpMessage.append([0x00]) } // hash values var hh = h // append message length, in a 64-bit big-endian integer. So now the message length is a multiple of 512 bits. tmpMessage.append((self.message.count * 8).bytes(64 / 8)) // Process the message in successive 512-bit chunks: let chunkSizeBytes = 512 / 8 // 64 var leftMessageBytes = tmpMessage.count var i = 0; while i < tmpMessage.count { let chunk = tmpMessage.subdata(in: i..<i+min(chunkSizeBytes, leftMessageBytes)) // break chunk into sixteen 32-bit words M[j], 0 ≤ j ≤ 15, big-endian // Extend the sixteen 32-bit words into eighty 32-bit words: var M = [UInt32](repeating: 0, count: 80) for x in 0..<M.count { switch (x) { case 0...15: let le: UInt32 = chunk.withUnsafeBytes { $0[x] } M[x] = le.bigEndian break default: M[x] = rotateLeft(M[x-3] ^ M[x-8] ^ M[x-14] ^ M[x-16], n: 1) break } } var A = hh[0], B = hh[1], C = hh[2], D = hh[3], E = hh[4] // Main loop for j in 0...79 { var f: UInt32 = 0 var k: UInt32 = 0 switch j { case 0...19: f = (B & C) | ((~B) & D) k = 0x5A827999 break case 20...39: f = B ^ C ^ D k = 0x6ED9EBA1 break case 40...59: f = (B & C) | (B & D) | (C & D) k = 0x8F1BBCDC break case 60...79: f = B ^ C ^ D k = 0xCA62C1D6 break default: break } let temp = (rotateLeft(A,n: 5) &+ f &+ E &+ M[j] &+ k) & 0xffffffff E = D D = C C = rotateLeft(B, n: 30) B = A A = temp } hh[0] = (hh[0] &+ A) & 0xffffffff hh[1] = (hh[1] &+ B) & 0xffffffff hh[2] = (hh[2] &+ C) & 0xffffffff hh[3] = (hh[3] &+ D) & 0xffffffff hh[4] = (hh[4] &+ E) & 0xffffffff i = i + chunkSizeBytes leftMessageBytes -= chunkSizeBytes } // Produce the final hash value (big-endian) as a 160 bit number: var mutableBuff = Data() hh.forEach { var i = $0.bigEndian let numBytes = MemoryLayout.size(ofValue: i) / MemoryLayout<UInt8>.size withUnsafePointer(to: &i) { ptr in ptr.withMemoryRebound(to: UInt8.self, capacity: numBytes) { ptr in let buffer = UnsafeBufferPointer(start: ptr, count: numBytes) mutableBuff.append(buffer) } } } return mutableBuff } } extension String { internal func indexOf(_ sub: String) -> Int? { guard let range = self.range(of: sub), !range.isEmpty else { return nil } return self.characters.distance(from: self.startIndex, to: range.lowerBound) } internal subscript (r: Range<Int>) -> String { get { let startIndex = self.characters.index(self.startIndex, offsetBy: r.lowerBound) let endIndex = self.characters.index(startIndex, offsetBy: r.upperBound - r.lowerBound) return self[startIndex..<endIndex] } } func urlEncodedString(_ encodeAll: Bool = false) -> String { var allowedCharacterSet: CharacterSet = .urlQueryAllowed allowedCharacterSet.remove(charactersIn: "\n:#/?@!$&'()*+,;=") if !encodeAll { allowedCharacterSet.insert(charactersIn: "[]") } return self.addingPercentEncoding(withAllowedCharacters: allowedCharacterSet)! } var queryStringParameters: Dictionary<String, String> { var parameters = Dictionary<String, String>() let scanner = Scanner(string: self) var key: String? var value: String? while !scanner.isAtEnd { key = scanner.scanUpToString("=") _ = scanner.scanString(string: "=") value = scanner.scanUpToString("&") _ = scanner.scanString(string: "&") if let key = key, let value = value { parameters.updateValue(value, forKey: key) } } return parameters } } extension Notification.Name { static let SwifterCallbackNotification: Notification.Name = Notification.Name(rawValue: "SwifterCallbackNotificationName") } // MARK: - Twitter URL public enum TwitterURL { case api case upload case stream case userStream case siteStream case oauth var url: URL { switch self { case .api: return URL(string: "https://api.twitter.com/1.1/")! case .upload: return URL(string: "https://upload.twitter.com/1.1/")! case .stream: return URL(string: "https://stream.twitter.com/1.1/")! case .userStream: return URL(string: "https://userstream.twitter.com/1.1/")! case .siteStream: return URL(string: "https://sitestream.twitter.com/1.1/")! case .oauth: return URL(string: "https://api.twitter.com/")! } } } public class Swifter { // MARK: - Types public typealias SuccessHandler = (JSON) -> Void public typealias CursorSuccessHandler = (JSON, _ previousCursor: String?, _ nextCursor: String?) -> Void public typealias JSONSuccessHandler = (JSON, _ response: HTTPURLResponse) -> Void public typealias FailureHandler = (_ error: Error) -> Void internal struct CallbackNotification { static let optionsURLKey = "SwifterCallbackNotificationOptionsURLKey" } internal struct DataParameters { static let dataKey = "SwifterDataParameterKey" static let fileNameKey = "SwifterDataParameterFilename" } // MARK: - Properties public var client: SwifterClientProtocol // MARK: - Initializers public init(consumerKey: String, consumerSecret: String, appOnly: Bool = false) { self.client = appOnly ? AppOnlyClient(consumerKey: consumerKey, consumerSecret: consumerSecret) : OAuthClient(consumerKey: consumerKey, consumerSecret: consumerSecret) } public init(consumerKey: String, consumerSecret: String, oauthToken: String, oauthTokenSecret: String) { self.client = OAuthClient(consumerKey: consumerKey, consumerSecret: consumerSecret , accessToken: oauthToken, accessTokenSecret: oauthTokenSecret) } #if os(macOS) || os(iOS) public init(account: ACAccount) { self.client = AccountsClient(account: account) } #endif deinit { NotificationCenter.default.removeObserver(self) } // MARK: - JSON Requests @discardableResult internal func jsonRequest(path: String, baseURL: TwitterURL, method: HTTPMethodType, parameters: Dictionary<String, Any>, uploadProgress: HTTPRequest.UploadProgressHandler? = nil, downloadProgress: JSONSuccessHandler? = nil, success: JSONSuccessHandler? = nil, failure: HTTPRequest.FailureHandler? = nil) -> HTTPRequest { let jsonDownloadProgressHandler: HTTPRequest.DownloadProgressHandler = { data, _, _, response in guard let _ = downloadProgress else { return } guard let jsonResult = try? JSON.parse(jsonData: data) else { let jsonString = String(data: data, encoding: .utf8) let jsonChunks = jsonString!.components(separatedBy: "\r\n") for chunk in jsonChunks where !chunk.utf16.isEmpty { guard let chunkData = chunk.data(using: .utf8), let jsonResult = try? JSON.parse(jsonData: chunkData) else { continue } downloadProgress?(jsonResult, response) } return } downloadProgress?(jsonResult, response) } let jsonSuccessHandler: HTTPRequest.SuccessHandler = { data, response in DispatchQueue.global(qos: .utility).async { do { let jsonResult = try JSON.parse(jsonData: data) DispatchQueue.main.async { success?(jsonResult, response) } } catch { DispatchQueue.main.async { failure?(error) } } } } if method == .GET { return self.client.get(path, baseURL: baseURL, parameters: parameters, uploadProgress: uploadProgress, downloadProgress: jsonDownloadProgressHandler, success: jsonSuccessHandler, failure: failure) } else { return self.client.post(path, baseURL: baseURL, parameters: parameters, uploadProgress: uploadProgress, downloadProgress: jsonDownloadProgressHandler, success: jsonSuccessHandler, failure: failure) } } @discardableResult internal func getJSON(path: String, baseURL: TwitterURL, parameters: Dictionary<String, Any>, uploadProgress: HTTPRequest.UploadProgressHandler? = nil, downloadProgress: JSONSuccessHandler? = nil, success: JSONSuccessHandler?, failure: HTTPRequest.FailureHandler?) -> HTTPRequest { return self.jsonRequest(path: path, baseURL: baseURL, method: .GET, parameters: parameters, uploadProgress: uploadProgress, downloadProgress: downloadProgress, success: success, failure: failure) } @discardableResult internal func postJSON(path: String, baseURL: TwitterURL, parameters: Dictionary<String, Any>, uploadProgress: HTTPRequest.UploadProgressHandler? = nil, downloadProgress: JSONSuccessHandler? = nil, success: JSONSuccessHandler?, failure: HTTPRequest.FailureHandler?) -> HTTPRequest { return self.jsonRequest(path: path, baseURL: baseURL, method: .POST, parameters: parameters, uploadProgress: uploadProgress, downloadProgress: downloadProgress, success: success, failure: failure) } } internal class AccountsClient: SwifterClientProtocol { var credential: Credential? init(account: ACAccount) { self.credential = Credential(account: account) } func get(_ path: String, baseURL: TwitterURL, parameters: Dictionary<String, Any>, uploadProgress: HTTPRequest.UploadProgressHandler?, downloadProgress: HTTPRequest.DownloadProgressHandler?, success: HTTPRequest.SuccessHandler?, failure: HTTPRequest.FailureHandler?) -> HTTPRequest { let url = URL(string: path, relativeTo: baseURL.url) let stringifiedParameters = parameters.stringifiedDictionary() let socialRequest = SLRequest(forServiceType: SLServiceTypeTwitter, requestMethod: .GET, url: url, parameters: stringifiedParameters)! socialRequest.account = self.credential!.account! let request = HTTPRequest(request: socialRequest.preparedURLRequest()) request.parameters = parameters request.downloadProgressHandler = downloadProgress request.successHandler = success request.failureHandler = failure request.start() return request } func post(_ path: String, baseURL: TwitterURL, parameters: Dictionary<String, Any>, uploadProgress: HTTPRequest.UploadProgressHandler?, downloadProgress: HTTPRequest.DownloadProgressHandler?, success: HTTPRequest.SuccessHandler?, failure: HTTPRequest.FailureHandler?) -> HTTPRequest { let url = URL(string: path, relativeTo: baseURL.url) var params = parameters var postData: Data? var postDataKey: String? if let keyString = params[Swifter.DataParameters.dataKey] as? String { postDataKey = keyString postData = params[postDataKey!] as? Data params.removeValue(forKey: Swifter.DataParameters.dataKey) params.removeValue(forKey: postDataKey!) } var postDataFileName: String? if let fileName = params[Swifter.DataParameters.fileNameKey] as? String { postDataFileName = fileName params.removeValue(forKey: fileName) } let stringifiedParameters = params.stringifiedDictionary() let socialRequest = SLRequest(forServiceType: SLServiceTypeTwitter, requestMethod: .POST, url: url, parameters: stringifiedParameters)! socialRequest.account = self.credential!.account! if let data = postData { let fileName = postDataFileName ?? "media.jpg" socialRequest.addMultipartData(data, withName: postDataKey!, type: "application/octet-stream", filename: fileName) } let request = HTTPRequest(request: socialRequest.preparedURLRequest()) request.parameters = parameters request.downloadProgressHandler = downloadProgress request.successHandler = success request.failureHandler = failure request.start() return request } } internal class AppOnlyClient: SwifterClientProtocol { var consumerKey: String var consumerSecret: String var credential: Credential? let dataEncoding: String.Encoding = .utf8 init(consumerKey: String, consumerSecret: String) { self.consumerKey = consumerKey self.consumerSecret = consumerSecret } func get(_ path: String, baseURL: TwitterURL, parameters: Dictionary<String, Any>, uploadProgress: HTTPRequest.UploadProgressHandler?, downloadProgress: HTTPRequest.DownloadProgressHandler?, success: HTTPRequest.SuccessHandler?, failure: HTTPRequest.FailureHandler?) -> HTTPRequest { let url = URL(string: path, relativeTo: baseURL.url) let request = HTTPRequest(url: url!, method: .GET, parameters: parameters) request.downloadProgressHandler = downloadProgress request.successHandler = success request.failureHandler = failure request.dataEncoding = self.dataEncoding if let bearerToken = self.credential?.accessToken?.key { request.headers = ["Authorization": "Bearer \(bearerToken)"]; } request.start() return request } func post(_ path: String, baseURL: TwitterURL, parameters: Dictionary<String, Any>, uploadProgress: HTTPRequest.UploadProgressHandler?, downloadProgress: HTTPRequest.DownloadProgressHandler?, success: HTTPRequest.SuccessHandler?, failure: HTTPRequest.FailureHandler?) -> HTTPRequest { let url = URL(string: path, relativeTo: baseURL.url) let request = HTTPRequest(url: url!, method: .POST, parameters: parameters) request.downloadProgressHandler = downloadProgress request.successHandler = success request.failureHandler = failure request.dataEncoding = self.dataEncoding if let bearerToken = self.credential?.accessToken?.key { request.headers = ["Authorization": "Bearer \(bearerToken)"]; } else { let basicCredentials = AppOnlyClient.base64EncodedCredentials(withKey: self.consumerKey, secret: self.consumerSecret) request.headers = ["Authorization": "Basic \(basicCredentials)"]; request.encodeParameters = true } request.start() return request } class func base64EncodedCredentials(withKey key: String, secret: String) -> String { let encodedKey = key.urlEncodedString() let encodedSecret = secret.urlEncodedString() let bearerTokenCredentials = "\(encodedKey):\(encodedSecret)" guard let data = bearerTokenCredentials.data(using: .utf8) else { return "" } return data.base64EncodedString(options: []) } } public extension Swifter { public typealias TokenSuccessHandler = (Credential.OAuthAccessToken?, URLResponse) -> Void /** Begin Authorization with a Callback URL. - OS X only */ #if os(macOS) public func authorize(with callbackURL: URL, success: TokenSuccessHandler?, failure: FailureHandler? = nil) { self.postOAuthRequestToken(with: callbackURL, success: { token, response in var requestToken = token! NotificationCenter.default.addObserver(forName: .SwifterCallbackNotification, object: nil, queue: .main) { notification in NotificationCenter.default.removeObserver(self) let url = notification.userInfo![CallbackNotification.optionsURLKey] as! URL let parameters = url.query!.queryStringParameters requestToken.verifier = parameters["oauth_verifier"] self.postOAuthAccessToken(with: requestToken, success: { accessToken, response in self.client.credential = Credential(accessToken: accessToken!) success?(accessToken!, response) }, failure: failure) } let authorizeURL = URL(string: "oauth/authorize", relativeTo: TwitterURL.oauth.url) let queryURL = URL(string: authorizeURL!.absoluteString + "?oauth_token=\(token!.key)")! NSWorkspace.shared().open(queryURL) }, failure: failure) } #endif /** Begin Authorization with a Callback URL - Parameter presentFromViewController: The viewController used to present the SFSafariViewController. The UIViewController must inherit SFSafariViewControllerDelegate */ #if os(iOS) public func authorize(with callbackURL: URL, presentFrom presentingViewController: UIViewController? , success: TokenSuccessHandler?, failure: FailureHandler? = nil) { self.postOAuthRequestToken(with: callbackURL, success: { token, response in var requestToken = token! NotificationCenter.default.addObserver(forName: .SwifterCallbackNotification, object: nil, queue: .main) { notification in NotificationCenter.default.removeObserver(self) presentingViewController?.presentedViewController?.dismiss(animated: true, completion: nil) let url = notification.userInfo![CallbackNotification.optionsURLKey] as! URL let parameters = url.query!.queryStringParameters requestToken.verifier = parameters["oauth_verifier"] self.postOAuthAccessToken(with: requestToken, success: { accessToken, response in self.client.credential = Credential(accessToken: accessToken!) success?(accessToken!, response) }, failure: failure) } let authorizeURL = URL(string: "oauth/authorize", relativeTo: TwitterURL.oauth.url) let queryURL = URL(string: authorizeURL!.absoluteString + "?oauth_token=\(token!.key)")! if #available(iOS 9.0, *) , let delegate = presentingViewController as? SFSafariViewControllerDelegate { let safariView = SFSafariViewController(url: queryURL) safariView.delegate = delegate presentingViewController?.present(safariView, animated: true, completion: nil) } else { UIApplication.shared.openURL(queryURL) } }, failure: failure) } #endif public class func handleOpenURL(_ url: URL) { let notification = Notification(name: .SwifterCallbackNotification, object: nil, userInfo: [CallbackNotification.optionsURLKey: url]) NotificationCenter.default.post(notification) } public func authorizeAppOnly(success: TokenSuccessHandler?, failure: FailureHandler?) { self.postOAuth2BearerToken(success: { json, response in if let tokenType = json["token_type"].string { if tokenType == "bearer" { let accessToken = json["access_token"].string let credentialToken = Credential.OAuthAccessToken(key: accessToken!, secret: "") self.client.credential = Credential(accessToken: credentialToken) success?(credentialToken, response) } else { let error = SwifterError(message: "Cannot find bearer token in server response", kind: .invalidAppOnlyBearerToken) failure?(error) } } else if case .object = json["errors"] { let error = SwifterError(message: json["errors"]["message"].string!, kind: .responseError(code: json["errors"]["code"].integer!)) failure?(error) } else { let error = SwifterError(message: "Cannot find JSON dictionary in response", kind: .invalidJSONResponse) failure?(error) } }, failure: failure) } public func postOAuth2BearerToken(success: JSONSuccessHandler?, failure: FailureHandler?) { let path = "oauth2/token" var parameters = Dictionary<String, Any>() parameters["grant_type"] = "client_credentials" self.jsonRequest(path: path, baseURL: .oauth, method: .POST, parameters: parameters, success: success, failure: failure) } public func invalidateOAuth2BearerToken(success: TokenSuccessHandler?, failure: FailureHandler?) { let path = "oauth2/invalidate_token" self.jsonRequest(path: path, baseURL: .oauth, method: .POST, parameters: [:], success: { json, response in if let accessToken = json["access_token"].string { self.client.credential = nil let credentialToken = Credential.OAuthAccessToken(key: accessToken, secret: "") success?(credentialToken, response) } else { success?(nil, response) } }, failure: failure) } public func postOAuthRequestToken(with callbackURL: URL, success: @escaping TokenSuccessHandler, failure: FailureHandler?) { let path = "oauth/request_token" let parameters: [String: Any] = ["oauth_callback": callbackURL.absoluteString] self.client.post(path, baseURL: .oauth, parameters: parameters, uploadProgress: nil, downloadProgress: nil, success: { data, response in let responseString = String(data: data, encoding: .utf8)! let accessToken = Credential.OAuthAccessToken(queryString: responseString) success(accessToken, response) }, failure: failure) } public func postOAuthAccessToken(with requestToken: Credential.OAuthAccessToken, success: @escaping TokenSuccessHandler, failure: FailureHandler?) { if let verifier = requestToken.verifier { let path = "oauth/access_token" let parameters: [String: Any] = ["oauth_token": requestToken.key, "oauth_verifier": verifier] self.client.post(path, baseURL: .oauth, parameters: parameters, uploadProgress: nil, downloadProgress: nil, success: { data, response in let responseString = String(data: data, encoding: .utf8)! let accessToken = Credential.OAuthAccessToken(queryString: responseString) success(accessToken, response) }, failure: failure) } else { let error = SwifterError(message: "Bad OAuth response received from server", kind: .badOAuthResponse) failure?(error) } } } public protocol SwifterClientProtocol { var credential: Credential? { get set } @discardableResult func get(_ path: String, baseURL: TwitterURL, parameters: Dictionary<String, Any>, uploadProgress: HTTPRequest.UploadProgressHandler?, downloadProgress: HTTPRequest.DownloadProgressHandler?, success: HTTPRequest.SuccessHandler?, failure: HTTPRequest.FailureHandler?) -> HTTPRequest @discardableResult func post(_ path: String, baseURL: TwitterURL, parameters: Dictionary<String, Any>, uploadProgress: HTTPRequest.UploadProgressHandler?, downloadProgress: HTTPRequest.DownloadProgressHandler?, success: HTTPRequest.SuccessHandler?, failure: HTTPRequest.FailureHandler?) -> HTTPRequest } public class Credential { public struct OAuthAccessToken { public internal(set) var key: String public internal(set) var secret: String public internal(set) var verifier: String? public internal(set) var screenName: String? public internal(set) var userID: String? public init(key: String, secret: String) { self.key = key self.secret = secret } public init(queryString: String) { var attributes = queryString.queryStringParameters self.key = attributes["oauth_token"]! self.secret = attributes["oauth_token_secret"]! self.screenName = attributes["screen_name"] self.userID = attributes["user_id"] } } public internal(set) var accessToken: OAuthAccessToken? #if os(macOS) || os(iOS) public internal(set) var account: ACAccount? public init(account: ACAccount) { self.account = account } #endif public init(accessToken: OAuthAccessToken) { self.accessToken = accessToken } } public struct SwifterError: Error { public enum ErrorKind: CustomStringConvertible { case invalidAppOnlyBearerToken case responseError(code: Int) case invalidJSONResponse case badOAuthResponse case urlResponseError(status: Int, headers: [AnyHashable: Any], errorCode: Int) case jsonParseError public var description: String { switch self { case .invalidAppOnlyBearerToken: return "invalidAppOnlyBearerToken" case .invalidJSONResponse: return "invalidJSONResponse" case .responseError(let code): return "responseError(code: \(code))" case .badOAuthResponse: return "badOAuthResponse" case .urlResponseError(let code, let headers, let errorCode): return "urlResponseError(status: \(code), headers: \(headers), errorCode: \(errorCode)" case .jsonParseError: return "jsonParseError" } } } public var message: String public var kind: ErrorKind public var localizedDescription: String { return "[\(kind.description)] - \(message)" } } public extension Swifter { /** GET friendships/no_retweets/ids Returns a collection of user_ids that the currently authenticated user does not want to receive retweets from. Use POST friendships/update to set the "no retweets" status for a given user account on behalf of the current user. */ public func listOfNoRetweetsFriends(stringifyIDs: Bool = true, success: SuccessHandler? = nil, failure: FailureHandler? = nil) { let path = "friendships/no_retweets/ids.json" var parameters = Dictionary<String, Any>() parameters["stringify_ids"] = stringifyIDs self.getJSON(path: path, baseURL: .api, parameters: parameters, success: { json, _ in success?(json) }, failure: failure) } /** GET friends/ids Returns Users (*: user IDs for followees) Returns a cursored collection of user IDs for every user the specified user is following (otherwise known as their "friends"). At this time, results are ordered with the most recent following first — however, this ordering is subject to unannounced change and eventual consistency issues. Results are given in groups of 5,000 user IDs and multiple "pages" of results can be navigated through using the next_cursor value in subsequent requests. See Using cursors to navigate collections for more information. This method is especially powerful when used in conjunction with GET users/lookup, a method that allows you to convert user IDs into full user objects in bulk. */ public func getUserFollowingIDs(for userTag: UserTag, cursor: String? = nil, stringifyIDs: Bool? = nil, count: Int? = nil, success: CursorSuccessHandler? = nil, failure: FailureHandler? = nil) { let path = "friends/ids.json" var parameters = Dictionary<String, Any>() parameters[userTag.key] = userTag.value parameters["cursor"] ??= cursor parameters["stringify_ids"] ??= stringifyIDs parameters["count"] ??= count self.getJSON(path: path, baseURL: .api, parameters: parameters, success: { json, _ in success?(json["ids"], json["previous_cursor_str"].string, json["next_cursor_str"].string) }, failure: failure) } /** GET followers/ids Returns a cursored collection of user IDs for every user following the specified user. At this time, results are ordered with the most recent following first — however, this ordering is subject to unannounced change and eventual consistency issues. Results are given in groups of 5,000 user IDs and multiple "pages" of results can be navigated through using the next_cursor value in subsequent requests. See Using cursors to navigate collections for more information. This method is especially powerful when used in conjunction with GET users/lookup, a method that allows you to convert user IDs into full user objects in bulk. */ public func getUserFollowersIDs(for userTag: UserTag, cursor: String? = nil, stringifyIDs: Bool? = nil, count: Int? = nil, success: CursorSuccessHandler? = nil, failure: FailureHandler? = nil) { let path = "followers/ids.json" var parameters = Dictionary<String, Any>() parameters[userTag.key] = userTag.value parameters["cursor"] ??= cursor parameters["stringify_ids"] ??= stringifyIDs parameters["count"] ??= count self.getJSON(path: path, baseURL: .api, parameters: parameters, success: { json, _ in success?(json["ids"], json["previous_cursor_str"].string, json["next_cursor_str"].string) }, failure: failure) } /** GET friendships/incoming Returns a collection of numeric IDs for every user who has a pending request to follow the authenticating user. */ public func getIncomingPendingFollowRequests(cursor: String? = nil, stringifyIDs: String? = nil, success: CursorSuccessHandler? = nil, failure: FailureHandler? = nil) { let path = "friendships/incoming.json" var parameters = Dictionary<String, Any>() parameters["cursor"] ??= cursor parameters["stringify_ids"] ??= stringifyIDs self.getJSON(path: path, baseURL: .api, parameters: parameters, success: { json, _ in success?(json["ids"], json["previous_cursor_str"].string, json["next_cursor_str"].string) }, failure: failure) } /** GET friendships/outgoing Returns a collection of numeric IDs for every protected user for whom the authenticating user has a pending follow request. */ public func getOutgoingPendingFollowRequests(cursor: String? = nil, stringifyIDs: String? = nil, success: CursorSuccessHandler? = nil, failure: FailureHandler? = nil) { let path = "friendships/outgoing.json" var parameters = Dictionary<String, Any>() parameters["cursor"] ??= cursor parameters["stringify_ids"] ??= stringifyIDs self.getJSON(path: path, baseURL: .api, parameters: parameters, success: { json, _ in success?(json["ids"], json["previous_cursor_str"].string, json["next_cursor_str"].string) }, failure: failure) } /** POST friendships/create Allows the authenticating users to follow the user specified in the ID parameter. Returns the befriended user in the requested format when successful. Returns a string describing the failure condition when unsuccessful. If you are already friends with the user a HTTP 403 may be returned, though for performance reasons you may get a 200 OK message even if the friendship already exists. Actions taken in this method are asynchronous and changes will be eventually consistent. */ public func followUser(for userTag: UserTag, follow: Bool? = nil, success: SuccessHandler? = nil, failure: FailureHandler? = nil) { let path = "friendships/create.json" var parameters = Dictionary<String, Any>() parameters[userTag.key] = userTag.value parameters["follow"] ??= follow self.postJSON(path: path, baseURL: .api, parameters: parameters, success: { json, _ in success?(json) }, failure: failure) } /** POST friendships/destroy Allows the authenticating user to unfollow the user specified in the ID parameter. Returns the unfollowed user in the requested format when successful. Returns a string describing the failure condition when unsuccessful. Actions taken in this method are asynchronous and changes will be eventually consistent. */ public func unfollowUser(for userTag: UserTag, success: SuccessHandler? = nil, failure: FailureHandler? = nil) { let path = "friendships/destroy.json" var parameters = Dictionary<String, Any>() parameters[userTag.key] = userTag.value self.postJSON(path: path, baseURL: .api, parameters: parameters, success: { json, _ in success?(json) }, failure: failure) } /** POST friendships/update Allows one to enable or disable retweets and device notifications from the specified user. */ public func updateFriendship(with userTag: UserTag, device: Bool? = nil, retweets: Bool? = nil, success: SuccessHandler? = nil, failure: FailureHandler? = nil) { let path = "friendships/update.json" var parameters = Dictionary<String, Any>() parameters[userTag.key] = userTag.value parameters["device"] ??= device parameters["retweets"] ??= retweets self.postJSON(path: path, baseURL: .api, parameters: parameters, success: { json, _ in success?(json) }, failure: failure) } /** GET friendships/show Returns detailed information about the relationship between two arbitrary users. */ public func showFriendship(between sourceTag: UserTag, and targetTag: UserTag, success: SuccessHandler? = nil, failure: FailureHandler? = nil) { let path = "friendships/show.json" var parameters = Dictionary<String, Any>() switch sourceTag { case .id: parameters["source_id"] = sourceTag.value case .screenName: parameters["source_screen_name"] = sourceTag.value } switch targetTag { case .id: parameters["target_id"] = targetTag.value case .screenName: parameters["target_screen_name"] = targetTag.value } self.getJSON(path: path, baseURL: .api, parameters: parameters, success: { json, _ in success?(json) }, failure: failure) } /** GET friends/list Returns a cursored collection of user objects for every user the specified user is following (otherwise known as their "friends"). At this time, results are ordered with the most recent following first — however, this ordering is subject to unannounced change and eventual consistency issues. Results are given in groups of 20 users and multiple "pages" of results can be navigated through using the next_cursor value in subsequent requests. See Using cursors to navigate collections for more information. */ public func getUserFollowing(for userTag: UserTag, cursor: String? = nil, count: Int? = nil, skipStatus: Bool? = nil, includeUserEntities: Bool? = nil, success: CursorSuccessHandler? = nil, failure: FailureHandler? = nil) { let path = "friends/list.json" var parameters = Dictionary<String, Any>() parameters[userTag.key] = userTag.value parameters["cursor"] ??= cursor parameters["count"] ??= count parameters["skip_status"] ??= skipStatus parameters["include_user_entities"] ??= includeUserEntities self.getJSON(path: path, baseURL: .api, parameters: parameters, success: { json, _ in success?(json["users"], json["previous_cursor_str"].string, json["next_cursor_str"].string) }, failure: failure) } /** GET followers/list Returns a cursored collection of user objects for users following the specified user. At this time, results are ordered with the most recent following first — however, this ordering is subject to unannounced change and eventual consistency issues. Results are given in groups of 20 users and multiple "pages" of results can be navigated through using the next_cursor value in subsequent requests. See Using cursors to navigate collections for more information. */ public func getUserFollowers(for userTag: UserTag, cursor: String? = nil, count: Int? = nil, skipStatus: Bool? = nil, includeUserEntities: Bool? = nil, success: CursorSuccessHandler? = nil, failure: FailureHandler? = nil) { let path = "followers/list.json" var parameters = Dictionary<String, Any>() parameters[userTag.key] = userTag.value parameters["cursor"] ??= cursor parameters["count"] ??= count parameters["skip_status"] ??= skipStatus parameters["include_user_entities"] ??= includeUserEntities self.getJSON(path: path, baseURL: .api, parameters: parameters, success: { json, _ in success?(json["users"], json["previous_cursor_str"].string, json["next_cursor_str"].string) }, failure: failure) } /** GET friendships/lookup Returns the relationships of the authenticating user to the comma-separated list of up to 100 screen_names or user_ids provided. Values for connections can be: following, following_requested, followed_by, none. */ public func lookupFriendship(with usersTag: UsersTag, success: SuccessHandler? = nil, failure: FailureHandler?) { let path = "friendships/lookup.json" var parameters = Dictionary<String, Any>() parameters[usersTag.key] = usersTag.value self.getJSON(path: path, baseURL: .api, parameters: parameters, success: { json, _ in success?(json) }, failure: failure) } } public enum HTTPMethodType: String { case OPTIONS case GET case HEAD case POST case PUT case DELETE case TRACE case CONNECT } public class HTTPRequest: NSObject, URLSessionDataDelegate { public typealias UploadProgressHandler = (_ bytesWritten: Int, _ totalBytesWritten: Int, _ totalBytesExpectedToWrite: Int) -> Void public typealias DownloadProgressHandler = (Data, _ totalBytesReceived: Int, _ totalBytesExpectedToReceive: Int, HTTPURLResponse) -> Void public typealias SuccessHandler = (Data, HTTPURLResponse) -> Void public typealias FailureHandler = (Error) -> Void internal struct DataUpload { var data: Data var parameterName: String var mimeType: String? var fileName: String? } let url: URL let HTTPMethod: HTTPMethodType var request: URLRequest? var dataTask: URLSessionDataTask! var headers: Dictionary<String, String> = [:] var parameters: Dictionary<String, Any> var encodeParameters: Bool var uploadData: [DataUpload] = [] var dataEncoding: String.Encoding = .utf8 var timeoutInterval: TimeInterval = 60 var HTTPShouldHandleCookies: Bool = false var response: HTTPURLResponse! var responseData: Data = Data() var uploadProgressHandler: UploadProgressHandler? var downloadProgressHandler: DownloadProgressHandler? var successHandler: SuccessHandler? var failureHandler: FailureHandler? public init(url: URL, method: HTTPMethodType = .GET, parameters: Dictionary<String, Any> = [:]) { self.url = url self.HTTPMethod = method self.parameters = parameters self.encodeParameters = false } public init(request: URLRequest) { self.request = request self.url = request.url! self.HTTPMethod = HTTPMethodType(rawValue: request.httpMethod!)! self.parameters = [:] self.encodeParameters = true } public func start() { if request == nil { self.request = URLRequest(url: self.url) self.request!.httpMethod = self.HTTPMethod.rawValue self.request!.timeoutInterval = self.timeoutInterval self.request!.httpShouldHandleCookies = self.HTTPShouldHandleCookies for (key, value) in headers { self.request!.setValue(value, forHTTPHeaderField: key) } let charset = CFStringConvertEncodingToIANACharSetName(CFStringConvertNSStringEncodingToEncoding(self.dataEncoding.rawValue)) let nonOAuthParameters = self.parameters.filter { key, _ in !key.hasPrefix("oauth_") } if !self.uploadData.isEmpty { let boundary = "----------HTTPRequestBoUnDaRy" let contentType = "multipart/form-data; boundary=\(boundary)" self.request!.setValue(contentType, forHTTPHeaderField:"Content-Type") var body = Data() for dataUpload: DataUpload in self.uploadData { let multipartData = HTTPRequest.mulipartContent(with: boundary, data: dataUpload.data, fileName: dataUpload.fileName, parameterName: dataUpload.parameterName, mimeType: dataUpload.mimeType) body.append(multipartData) } for (key, value): (String, Any) in nonOAuthParameters { body.append("\r\n--\(boundary)\r\n".data(using: .utf8)!) body.append("Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n".data(using: .utf8)!) body.append("\(value)".data(using: .utf8)!) } body.append("\r\n--\(boundary)--\r\n".data(using: .utf8)!) self.request!.setValue("\(body.count)", forHTTPHeaderField: "Content-Length") self.request!.httpBody = body } else if !nonOAuthParameters.isEmpty { if self.HTTPMethod == .GET || self.HTTPMethod == .HEAD || self.HTTPMethod == .DELETE { let queryString = nonOAuthParameters.urlEncodedQueryString(using: self.dataEncoding) self.request!.url = self.url.append(queryString: queryString) self.request!.setValue("application/x-www-form-urlencoded; charset=\(String(describing: charset))", forHTTPHeaderField: "Content-Type") } else { var queryString = "" if self.encodeParameters { queryString = nonOAuthParameters.urlEncodedQueryString(using: self.dataEncoding) self.request!.setValue("application/x-www-form-urlencoded; charset=\(String(describing: charset))", forHTTPHeaderField: "Content-Type") } else { queryString = nonOAuthParameters.queryString } if let data = queryString.data(using: self.dataEncoding) { self.request!.setValue(String(data.count), forHTTPHeaderField: "Content-Length") self.request!.httpBody = data } } } } DispatchQueue.main.async { let session = URLSession(configuration: .default, delegate: self, delegateQueue: .main) self.dataTask = session.dataTask(with: self.request!) self.dataTask.resume() #if os(iOS) UIApplication.shared.isNetworkActivityIndicatorVisible = true #endif } } public func stop() { self.dataTask.cancel() } public func add(multipartData data: Data, parameterName: String, mimeType: String?, fileName: String?) -> Void { let dataUpload = DataUpload(data: data, parameterName: parameterName, mimeType: mimeType, fileName: fileName) self.uploadData.append(dataUpload) } private class func mulipartContent(with boundary: String, data: Data, fileName: String?, parameterName: String, mimeType mimeTypeOrNil: String?) -> Data { let mimeType = mimeTypeOrNil ?? "application/octet-stream" let fileNameContentDisposition = fileName != nil ? "filename=\"\(String(describing: fileName))\"" : "" let contentDisposition = "Content-Disposition: form-data; name=\"\(parameterName)\"; \(fileNameContentDisposition)\r\n" var tempData = Data() tempData.append("--\(boundary)\r\n".data(using: .utf8)!) tempData.append(contentDisposition.data(using: .utf8)!) tempData.append("Content-Type: \(mimeType)\r\n\r\n".data(using: .utf8)!) tempData.append(data) tempData.append("\r\n".data(using: .utf8)!) return tempData } // MARK: - URLSessionDataDelegate public func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) { #if os(iOS) UIApplication.shared.isNetworkActivityIndicatorVisible = false #endif defer { session.finishTasksAndInvalidate() } if let error = error { self.failureHandler?(error) return } guard self.response.statusCode >= 400 else { self.successHandler?(self.responseData, self.response) return } let responseString = String(data: responseData, encoding: dataEncoding)! let errorCode = HTTPRequest.responseErrorCode(for: responseData) ?? 0 let localizedDescription = HTTPRequest.description(for: response.statusCode, response: responseString) let error = SwifterError(message: localizedDescription, kind: .urlResponseError(status: response.statusCode, headers: response.allHeaderFields, errorCode: errorCode)) self.failureHandler?(error) } public func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) { self.responseData.append(data) let expectedContentLength = Int(self.response!.expectedContentLength) let totalBytesReceived = self.responseData.count guard !data.isEmpty else { return } self.downloadProgressHandler?(data, totalBytesReceived, expectedContentLength, self.response) } public func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive response: URLResponse, completionHandler: @escaping (URLSession.ResponseDisposition) -> Void) { self.response = response as? HTTPURLResponse self.responseData.count = 0 completionHandler(.allow) } public func urlSession(_ session: URLSession, task: URLSessionTask, didSendBodyData bytesSent: Int64, totalBytesSent: Int64, totalBytesExpectedToSend: Int64) { self.uploadProgressHandler?(Int(bytesSent), Int(totalBytesSent), Int(totalBytesExpectedToSend)) } // MARK: - Error Responses class func responseErrorCode(for data: Data) -> Int? { guard let code = JSON(data)["errors"].array?.first?["code"].integer else { return nil } return code } class func description(for status: Int, response string: String) -> String { var s = "HTTP Status \(status)" let description: String // http://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml // https://dev.twitter.com/overview/api/response-codes switch(status) { case 400: description = "Bad Request" case 401: description = "Unauthorized" case 402: description = "Payment Required" case 403: description = "Forbidden" case 404: description = "Not Found" case 405: description = "Method Not Allowed" case 406: description = "Not Acceptable" case 407: description = "Proxy Authentication Required" case 408: description = "Request Timeout" case 409: description = "Conflict" case 410: description = "Gone" case 411: description = "Length Required" case 412: description = "Precondition Failed" case 413: description = "Payload Too Large" case 414: description = "URI Too Long" case 415: description = "Unsupported Media Type" case 416: description = "Requested Range Not Satisfiable" case 417: description = "Expectation Failed" case 420: description = "Enhance Your Calm" case 422: description = "Unprocessable Entity" case 423: description = "Locked" case 424: description = "Failed Dependency" case 425: description = "Unassigned" case 426: description = "Upgrade Required" case 427: description = "Unassigned" case 428: description = "Precondition Required" case 429: description = "Too Many Requests" case 430: description = "Unassigned" case 431: description = "Request Header Fields Too Large" case 432: description = "Unassigned" case 500: description = "Internal Server Error" case 501: description = "Not Implemented" case 502: description = "Bad Gateway" case 503: description = "Service Unavailable" case 504: description = "Gateway Timeout" case 505: description = "HTTP Version Not Supported" case 506: description = "Variant Also Negotiates" case 507: description = "Insufficient Storage" case 508: description = "Loop Detected" case 509: description = "Unassigned" case 510: description = "Not Extended" case 511: description = "Network Authentication Required" default: description = "" } if !description.isEmpty { s = s + ": " + description + ", Response: " + string } return s } } internal class OAuthClient: SwifterClientProtocol { struct OAuth { static let version = "1.0" static let signatureMethod = "HMAC-SHA1" } var consumerKey: String var consumerSecret: String var credential: Credential? let dataEncoding: String.Encoding = .utf8 init(consumerKey: String, consumerSecret: String) { self.consumerKey = consumerKey self.consumerSecret = consumerSecret } init(consumerKey: String, consumerSecret: String, accessToken: String, accessTokenSecret: String) { self.consumerKey = consumerKey self.consumerSecret = consumerSecret let credentialAccessToken = Credential.OAuthAccessToken(key: accessToken, secret: accessTokenSecret) self.credential = Credential(accessToken: credentialAccessToken) } func get(_ path: String, baseURL: TwitterURL, parameters: Dictionary<String, Any>, uploadProgress: HTTPRequest.UploadProgressHandler?, downloadProgress: HTTPRequest.DownloadProgressHandler?, success: HTTPRequest.SuccessHandler?, failure: HTTPRequest.FailureHandler?) -> HTTPRequest { let url = URL(string: path, relativeTo: baseURL.url)! let request = HTTPRequest(url: url, method: .GET, parameters: parameters) request.headers = ["Authorization": self.authorizationHeader(for: .GET, url: url, parameters: parameters, isMediaUpload: false)] request.downloadProgressHandler = downloadProgress request.successHandler = success request.failureHandler = failure request.dataEncoding = self.dataEncoding request.start() return request } func post(_ path: String, baseURL: TwitterURL, parameters: Dictionary<String, Any>, uploadProgress: HTTPRequest.UploadProgressHandler?, downloadProgress: HTTPRequest.DownloadProgressHandler?, success: HTTPRequest.SuccessHandler?, failure: HTTPRequest.FailureHandler?) -> HTTPRequest { let url = URL(string: path, relativeTo: baseURL.url)! var parameters = parameters var postData: Data? var postDataKey: String? if let key: Any = parameters[Swifter.DataParameters.dataKey] { if let keyString = key as? String { postDataKey = keyString postData = parameters[postDataKey!] as? Data parameters.removeValue(forKey: Swifter.DataParameters.dataKey) parameters.removeValue(forKey: postDataKey!) } } var postDataFileName: String? if let fileName: Any = parameters[Swifter.DataParameters.fileNameKey] { if let fileNameString = fileName as? String { postDataFileName = fileNameString parameters.removeValue(forKey: fileNameString) } } let request = HTTPRequest(url: url, method: .POST, parameters: parameters) request.headers = ["Authorization": self.authorizationHeader(for: .POST, url: url, parameters: parameters, isMediaUpload: postData != nil)] request.downloadProgressHandler = downloadProgress request.successHandler = success request.failureHandler = failure request.dataEncoding = self.dataEncoding request.encodeParameters = postData == nil if let postData = postData { let fileName = postDataFileName ?? "media.jpg" request.add(multipartData: postData, parameterName: postDataKey!, mimeType: "application/octet-stream", fileName: fileName) } request.start() return request } func authorizationHeader(for method: HTTPMethodType, url: URL, parameters: Dictionary<String, Any>, isMediaUpload: Bool) -> String { var authorizationParameters = Dictionary<String, Any>() authorizationParameters["oauth_version"] = OAuth.version authorizationParameters["oauth_signature_method"] = OAuth.signatureMethod authorizationParameters["oauth_consumer_key"] = self.consumerKey authorizationParameters["oauth_timestamp"] = String(Int(Date().timeIntervalSince1970)) authorizationParameters["oauth_nonce"] = UUID().uuidString authorizationParameters["oauth_token"] ??= self.credential?.accessToken?.key for (key, value) in parameters where key.hasPrefix("oauth_") { authorizationParameters.updateValue(value, forKey: key) } let combinedParameters = authorizationParameters +| parameters let finalParameters = isMediaUpload ? authorizationParameters : combinedParameters authorizationParameters["oauth_signature"] = self.oauthSignature(for: method, url: url, parameters: finalParameters, accessToken: self.credential?.accessToken) let authorizationParameterComponents = authorizationParameters.urlEncodedQueryString(using: self.dataEncoding).components(separatedBy: "&").sorted() var headerComponents = [String]() for component in authorizationParameterComponents { let subcomponent = component.components(separatedBy: "=") if subcomponent.count == 2 { headerComponents.append("\(subcomponent[0])=\"\(subcomponent[1])\"") } } return "OAuth " + headerComponents.joined(separator: ", ") } func oauthSignature(for method: HTTPMethodType, url: URL, parameters: Dictionary<String, Any>, accessToken token: Credential.OAuthAccessToken?) -> String { let tokenSecret = token?.secret.urlEncodedString() ?? "" let encodedConsumerSecret = self.consumerSecret.urlEncodedString() let signingKey = "\(encodedConsumerSecret)&\(tokenSecret)" let parameterComponents = parameters.urlEncodedQueryString(using: dataEncoding).components(separatedBy: "&").sorted() let parameterString = parameterComponents.joined(separator: "&") let encodedParameterString = parameterString.urlEncodedString() let encodedURL = url.absoluteString.urlEncodedString() let signatureBaseString = "\(method)&\(encodedURL)&\(encodedParameterString)" let key = signingKey.data(using: .utf8)! let msg = signatureBaseString.data(using: .utf8)! let sha1 = HMAC.sha1(key: key, message: msg)! return sha1.base64EncodedString(options: []) } } public enum UserTag { case id(String) case screenName(String) var key: String { switch self { case .id: return "user_id" case .screenName: return "screen_name" } } var value: String { switch self { case .id(let id): return id case .screenName(let user): return user } } } public enum UsersTag { case id([String]) case screenName([String]) var key: String { switch self { case .id: return "user_id" case .screenName: return "screen_name" } } var value: String { switch self { case .id(let id): return id.joined(separator: ",") case .screenName(let user): return user.joined(separator: ",") } } } public enum ListTag { case id(String) case slug(String, owner: UserTag) var key: String { switch self { case .id: return "list_id" case .slug: return "slug" } } var value: String { switch self { case .id(let id): return id case .slug(let slug, _): return slug } } } public extension Swifter { /** GET account/settings Returns settings (including current trend, geo and sleep time information) for the authenticating user. */ public func getAccountSettings(success: SuccessHandler? = nil, failure: FailureHandler? = nil) { let path = "account/settings.json" self.getJSON(path: path, baseURL: .api, parameters: [:], success: { json, _ in success?(json) }, failure: failure) } /** GET account/verify_credentials Returns an HTTP 200 OK response code and a representation of the requesting user if authentication was successful; returns a 401 status code and an error message if not. Use this method to test if supplied user credentials are valid. */ public func verifyAccountCredentials(includeEntities: Bool? = nil, skipStatus: Bool? = nil, success: SuccessHandler? = nil, failure: FailureHandler? = nil) { let path = "account/verify_credentials.json" var parameters = Dictionary<String, Any>() parameters["include_entities"] ??= includeEntities parameters["skip_status"] ??= skipStatus self.getJSON(path: path, baseURL: .api, parameters: parameters, success: { json, _ in success?(json) }, failure: failure) } /** POST account/settings Updates the authenticating user's settings. */ public func updateAccountSettings(trendLocationWOEID: String? = nil, sleepTimeEnabled: Bool? = nil, startSleepTime: Int? = nil, endSleepTime: Int? = nil, timeZone: String? = nil, lang: String? = nil, success: SuccessHandler? = nil, failure: FailureHandler? = nil) { assert(trendLocationWOEID != nil || sleepTimeEnabled != nil || startSleepTime != nil || endSleepTime != nil || timeZone != nil || lang != nil, "At least one or more should be provided when executing this request") let path = "account/settings.json" var parameters = Dictionary<String, Any>() parameters["trend_location_woeid"] ??= trendLocationWOEID parameters["sleep_time_enabled"] ??= sleepTimeEnabled parameters["start_sleep_time"] ??= startSleepTime parameters["end_sleep_time"] ??= endSleepTime parameters["time_zone"] ??= timeZone parameters["lang"] ??= lang self.postJSON(path: path, baseURL: .api, parameters: parameters, success: { json, _ in success?(json) }, failure: failure) } /** POST account/update_profile Sets values that users are able to set under the "Account" tab of their settings page. Only the parameters specified will be updated. */ public func updateUserProfile(name: String? = nil, url: String? = nil, location: String? = nil, description: String? = nil, includeEntities: Bool? = nil, skipStatus: Bool? = nil, success: SuccessHandler? = nil, failure: FailureHandler? = nil) { assert(name != nil || url != nil || location != nil || description != nil || includeEntities != nil || skipStatus != nil) let path = "account/update_profile.json" var parameters = Dictionary<String, Any>() parameters["name"] ??= name parameters["url"] ??= url parameters["location"] ??= location parameters["description"] ??= description parameters["include_entities"] ??= includeEntities parameters["skip_status"] ??= skipStatus self.postJSON(path: path, baseURL: .api, parameters: parameters, success: { json, _ in success?(json) }, failure: failure) } /** POST account/update_profile_background_image Updates the authenticating user's profile background image. This method can also be used to enable or disable the profile background image. Although each parameter is marked as optional, at least one of image, tile or use must be provided when making this request. */ public func updateProfileBackground(using imageData: Data, title: String? = nil, includeEntities: Bool? = nil, use: Bool? = nil, success: SuccessHandler? = nil, failure: FailureHandler? = nil) { assert(title != nil || use != nil, "At least one of image, tile or use must be provided when making this request") let path = "account/update_profile_background_image.json" var parameters = Dictionary<String, Any>() parameters["image"] = imageData.base64EncodedString(options: []) parameters["title"] ??= title parameters["include_entities"] ??= includeEntities parameters["use"] ??= use self.postJSON(path: path, baseURL: .api, parameters: parameters, success: { json, _ in success?(json) }, failure: failure) } /** POST account/update_profile_colors Sets one or more hex values that control the color scheme of the authenticating user's profile page on twitter.com. Each parameter's value must be a valid hexidecimal value, and may be either three or six characters (ex: #fff or #ffffff). */ public func updateProfileColors(backgroundColor: String? = nil, linkColor: String? = nil, sidebarBorderColor: String? = nil, sidebarFillColor: String? = nil, textColor: String? = nil, includeEntities: Bool? = nil, skipStatus: Bool? = nil, success: SuccessHandler? = nil, failure: @escaping FailureHandler) { let path = "account/update_profile_colors.json" var parameters = Dictionary<String, Any>() parameters["profile_background_color"] ??= backgroundColor parameters["profile_link_color"] ??= linkColor parameters["profile_sidebar_link_color"] ??= sidebarBorderColor parameters["profile_sidebar_fill_color"] ??= sidebarFillColor parameters["profile_text_color"] ??= textColor parameters["include_entities"] ??= includeEntities parameters["skip_status"] ??= skipStatus self.postJSON(path: path, baseURL: .api, parameters: parameters, success: { json, _ in success?(json) }, failure: failure) } /** POST account/update_profile_image Updates the authenticating user's profile image. Note that this method expects raw multipart data, not a URL to an image. This method asynchronously processes the uploaded file before updating the user's profile image URL. You can either update your local cache the next time you request the user's information, or, at least 5 seconds after uploading the image, ask for the updated URL using GET users/show. */ public func updateProfileImage(using imageData: Data, includeEntities: Bool? = nil, skipStatus: Bool? = nil, success: SuccessHandler? = nil, failure: FailureHandler? = nil) { let path = "account/update_profile_image.json" var parameters = Dictionary<String, Any>() parameters["image"] = imageData.base64EncodedString(options: []) parameters["include_entities"] ??= includeEntities parameters["skip_status"] ??= skipStatus self.postJSON(path: path, baseURL: .api, parameters: parameters, success: { json, _ in success?(json) }, failure: failure) } /** GET blocks/list Returns a collection of user objects that the authenticating user is blocking. */ public func getBlockedUsers(includeEntities: Bool? = nil, skipStatus: Bool? = nil, cursor: String? = nil, success: CursorSuccessHandler? = nil, failure: FailureHandler? = nil) { let path = "blocks/list.json" var parameters = Dictionary<String, Any>() parameters["include_entities"] ??= includeEntities parameters["skip_status"] ??= skipStatus parameters["cursor"] ??= cursor self.getJSON(path: path, baseURL: .api, parameters: parameters, success: { json, _ in success?(json["users"], json["previous_cursor_str"].string, json["next_cursor_str"].string) }, failure: failure) } /** GET blocks/ids Returns an array of numeric user ids the authenticating user is blocking. */ public func getBlockedUsersIDs(stringifyIDs: String? = nil, cursor: String? = nil, success: CursorSuccessHandler? = nil, failure: @escaping FailureHandler) { let path = "blocks/ids.json" var parameters = Dictionary<String, Any>() parameters["stringify_ids"] ??= stringifyIDs parameters["cursor"] ??= cursor self.getJSON(path: path, baseURL: .api, parameters: parameters, success: { json, _ in success?(json["ids"], json["previous_cursor_str"].string, json["next_cursor_str"].string) }, failure: failure) } /** POST blocks/create Blocks the specified user from following the authenticating user. In addition the blocked user will not show in the authenticating users mentions or timeline (unless retweeted by another user). If a follow or friend relationship exists it is destroyed. */ public func blockUser(for userTag: UserTag, includeEntities: Bool? = nil, skipStatus: Bool? = nil, success: SuccessHandler? = nil, failure: @escaping FailureHandler) { let path = "blocks/create.json" var parameters = Dictionary<String, Any>() parameters[userTag.key] = userTag.value parameters["include_entities"] ??= includeEntities parameters["skip_status"] ??= skipStatus self.postJSON(path: path, baseURL: .api, parameters: parameters, success: { json, _ in success?(json) }, failure: failure) } /** POST blocks/destroy Un-blocks the user specified in the ID parameter for the authenticating user. Returns the un-blocked user in the requested format when successful. If relationships existed before the block was instated, they will not be restored. */ public func unblockUser(for userTag: UserTag, includeEntities: Bool? = nil, skipStatus: Bool? = nil, success: SuccessHandler? = nil, failure: @escaping FailureHandler) { let path = "blocks/destroy.json" var parameters = Dictionary<String, Any>() parameters[userTag.key] = userTag.value parameters["include_entities"] ??= includeEntities parameters["skip_status"] ??= skipStatus self.postJSON(path: path, baseURL: .api, parameters: parameters, success: { json, _ in success?(json) }, failure: failure) } /** GET users/lookup Returns fully-hydrated user objects for up to 100 users per request, as specified by comma-separated values passed to the user_id and/or screen_name parameters. This method is especially useful when used in conjunction with collections of user IDs returned from GET friends/ids and GET followers/ids. GET users/show is used to retrieve a single user object. There are a few things to note when using this method. - You must be following a protected user to be able to see their most recent status update. If you don't follow a protected user their status will be removed. - The order of user IDs or screen names may not match the order of users in the returned array. - If a requested user is unknown, suspended, or deleted, then that user will not be returned in the results list. - If none of your lookup criteria can be satisfied by returning a user object, a HTTP 404 will be thrown. - You are strongly encouraged to use a POST for larger requests. */ public func lookupUsers(for usersTag: UsersTag, includeEntities: Bool? = nil, success: SuccessHandler? = nil, failure: @escaping FailureHandler) { let path = "users/lookup.json" var parameters = Dictionary<String, Any>() parameters[usersTag.key] = usersTag.value parameters["include_entities"] ??= includeEntities self.getJSON(path: path, baseURL: .api, parameters: parameters, success: { json, _ in success?(json) }, failure: failure) } /** GET users/show Returns a variety of information about the user specified by the required user_id or screen_name parameter. The author's most recent Tweet will be returned inline when possible. GET users/lookup is used to retrieve a bulk collection of user objects. You must be following a protected user to be able to see their most recent Tweet. If you don't follow a protected user, the users Tweet will be removed. A Tweet will not always be returned in the current_status field. */ public func showUser(for userTag: UserTag, includeEntities: Bool? = nil, success: SuccessHandler? = nil, failure: @escaping FailureHandler) { let path = "users/show.json" var parameters = Dictionary<String, Any>() parameters[userTag.key] = userTag.value parameters["include_entities"] ??= includeEntities self.getJSON(path: path, baseURL: .api, parameters: parameters, success: { json, _ in success?(json) }, failure: failure) } /** GET users/search Provides a simple, relevance-based search interface to public user accounts on Twitter. Try querying by topical interest, full name, company name, location, or other criteria. Exact match searches are not supported. Only the first 1,000 matching results are available. */ public func searchUsers(using query: String, page: Int?, count: Int?, includeEntities: Bool?, success: SuccessHandler? = nil, failure: @escaping FailureHandler) { let path = "users/search.json" var parameters = Dictionary<String, Any>() parameters["q"] = query parameters["page"] ??= page parameters["count"] ??= count parameters["include_entities"] ??= includeEntities self.getJSON(path: path, baseURL: .api, parameters: parameters, success: { json, _ in success?(json) }, failure: failure) } /** POST account/remove_profile_banner Removes the uploaded profile banner for the authenticating user. Returns HTTP 200 upon success. */ public func removeProfileBanner(success: SuccessHandler? = nil, failure: FailureHandler? = nil) { let path = "account/remove_profile_banner.json" self.postJSON(path: path, baseURL: .api, parameters: [:], success: { json, _ in success?(json) }, failure: failure) } /** POST account/update_profile_banner Uploads a profile banner on behalf of the authenticating user. For best results, upload an <5MB image that is exactly 1252px by 626px. Images will be resized for a number of display options. Users with an uploaded profile banner will have a profile_banner_url node in their Users objects. More information about sizing variations can be found in User Profile Images and Banners and GET users/profile_banner. Profile banner images are processed asynchronously. The profile_banner_url and its variant sizes will not necessary be available directly after upload. If providing any one of the height, width, offset_left, or offset_top parameters, you must provide all of the sizing parameters. HTTP Response Codes 200, 201, 202 Profile banner image succesfully uploaded 400 Either an image was not provided or the image data could not be processed 422 The image could not be resized or is too large. */ public func updateProfileBanner(using imageData: Data, width: Int? = nil, height: Int? = nil, offsetLeft: Int? = nil, offsetTop: Int? = nil, success: SuccessHandler? = nil, failure: FailureHandler? = nil) { let path = "account/update_profile_banner.json" var parameters = Dictionary<String, Any>() parameters["banner"] = imageData.base64EncodedString parameters["width"] ??= width parameters["height"] ??= height parameters["offset_left"] ??= offsetLeft parameters["offset_top"] ??= offsetTop self.postJSON(path: path, baseURL: .api, parameters: parameters, success: { json, _ in success?(json) }, failure: failure) } /** GET users/profile_banner Returns a map of the available size variations of the specified user's profile banner. If the user has not uploaded a profile banner, a HTTP 404 will be served instead. This method can be used instead of string manipulation on the profile_banner_url returned in user objects as described in User Profile Images and Banners. */ public func getProfileBanner(for userTag: UserTag, success: SuccessHandler? = nil, failure: FailureHandler? = nil) { let path = "users/profile_banner.json" let parameters: [String: Any] = [userTag.key: userTag.value] self.postJSON(path: path, baseURL: .api, parameters: parameters, success: { json, _ in success?(json) }, failure: failure) } /** POST mutes/users/create Mutes the user specified in the ID parameter for the authenticating user. Returns the muted user in the requested format when successful. Returns a string describing the failure condition when unsuccessful. Actions taken in this method are asynchronous and changes will be eventually consistent. */ public func muteUser(for userTag: UserTag, success: SuccessHandler? = nil, failure: FailureHandler? = nil) { let path = "mutes/users/create.json" let parameters: [String: Any] = [userTag.key: userTag.value] self.postJSON(path: path, baseURL: .api, parameters: parameters, success: { json, _ in success?(json) }, failure: failure) } /** POST mutes/users/destroy Un-mutes the user specified in the ID parameter for the authenticating user. Returns the unmuted user in the requested format when successful. Returns a string describing the failure condition when unsuccessful. Actions taken in this method are asynchronous and changes will be eventually consistent. */ public func unmuteUser(for userTag: UserTag, success: SuccessHandler? = nil, failure: FailureHandler? = nil) { let path = "mutes/users/destroy.json" var parameters = Dictionary<String, Any>() parameters[userTag.key] = userTag.value self.postJSON(path: path, baseURL: .api, parameters: parameters, success: { json, _ in success?(json) }, failure: failure) } /** GET mutes/users/ids Returns an array of numeric user ids the authenticating user has muted. */ public func getMuteUsersIDs(cursor: String? = nil, success: CursorSuccessHandler? = nil, failure: FailureHandler? = nil) { let path = "mutes/users/ids.json" var parameters = Dictionary<String, Any>() parameters["cursor"] ??= cursor self.getJSON(path: path, baseURL: .api, parameters: parameters, success: { json, _ in success?(json["ids"], json["previous_cursor_str"].string, json["next_cursor_str"].string) }, failure: failure) } /** GET mutes/users/list Returns an array of user objects the authenticating user has muted. */ public func getMuteUsers(cursor: String? = nil, includeEntities: Bool? = nil, skipStatus: Bool? = nil, success: CursorSuccessHandler? = nil, failure: FailureHandler? = nil) { let path = "mutes/users/list.json" var parameters = Dictionary<String, Any>() parameters["include_entities"] ??= includeEntities parameters["skip_status"] ??= skipStatus parameters["cursor"] ??= cursor self.getJSON(path: path, baseURL: .api, parameters: parameters, success: { json, _ in success?(json["users"], json["previous_cursor_str"].string, json["next_cursor_str"].string) }, failure: failure) } } extension URL { func append(queryString: String) -> URL { guard !queryString.utf16.isEmpty else { return self } var absoluteURLString = self.absoluteString if absoluteURLString.hasSuffix("?") { absoluteURLString = absoluteURLString[0..<absoluteURLString.utf16.count] } let urlString = absoluteURLString + (absoluteURLString.range(of: "?") != nil ? "&" : "?") + queryString return URL(string: urlString)! } } func rotateLeft(_ v:UInt16, n:UInt16) -> UInt16 { return ((v << n) & 0xFFFF) | (v >> (16 - n)) } func rotateLeft(_ v:UInt32, n:UInt32) -> UInt32 { return ((v << n) & 0xFFFFFFFF) | (v >> (32 - n)) } func rotateLeft(_ x:UInt64, n:UInt64) -> UInt64 { return (x << n) | (x >> (64 - n)) } func rotateRight(_ x:UInt16, n:UInt16) -> UInt16 { return (x >> n) | (x << (16 - n)) } func rotateRight(_ x:UInt32, n:UInt32) -> UInt32 { return (x >> n) | (x << (32 - n)) } func rotateRight(_ x:UInt64, n:UInt64) -> UInt64 { return ((x >> n) | (x << (64 - n))) } func reverseBytes(_ value: UInt32) -> UInt32 { let tmp1 = ((value & 0x000000FF) << 24) | ((value & 0x0000FF00) << 8) let tmp2 = ((value & 0x00FF0000) >> 8) | ((value & 0xFF000000) >> 24) return tmp1 | tmp2 } extension Int { public func bytes(_ totalBytes: Int = MemoryLayout<Int>.size) -> [UInt8] { return arrayOfBytes(self, length: totalBytes) } } func arrayOfBytes<T>(_ value:T, length: Int? = nil) -> [UInt8] { let totalBytes = length ?? (MemoryLayout<T>.size * 8) let valuePointer = UnsafeMutablePointer<T>.allocate(capacity: 1) valuePointer.pointee = value let bytesPointer = valuePointer.withMemoryRebound(to: UInt8.self, capacity: 1) { $0 } var bytes = [UInt8](repeating: 0, count: totalBytes) for j in 0..<min(MemoryLayout<T>.size,totalBytes) { bytes[totalBytes - 1 - j] = (bytesPointer + j).pointee } valuePointer.deinitialize() valuePointer.deallocate(capacity: 1) return bytes } class TwiterManager { }
mit
2ebe5166639abead87c4b099f2a7f477
39.717316
412
0.621453
4.879487
false
false
false
false
OscarSwanros/swift
test/expr/closure/closures.swift
14
13791
// RUN: %target-typecheck-verify-swift var func6 : (_ fn : (Int,Int) -> Int) -> () var func6a : ((Int, Int) -> Int) -> () var func6b : (Int, (Int, Int) -> Int) -> () func func6c(_ f: (Int, Int) -> Int, _ n: Int = 0) {} // Expressions can be auto-closurified, so that they can be evaluated separately // from their definition. var closure1 : () -> Int = {4} // Function producing 4 whenever it is called. var closure2 : (Int,Int) -> Int = { 4 } // expected-error{{contextual type for closure argument list expects 2 arguments, which cannot be implicitly ignored}} {{36-36= _,_ in}} var closure3a : () -> () -> (Int,Int) = {{ (4, 2) }} // multi-level closing. var closure3b : (Int,Int) -> (Int) -> (Int,Int) = {{ (4, 2) }} // expected-error{{contextual type for closure argument list expects 2 arguments, which cannot be implicitly ignored}} {{52-52=_,_ in }} var closure4 : (Int,Int) -> Int = { $0 + $1 } var closure5 : (Double) -> Int = { $0 + 1.0 // expected-error@+1 {{cannot convert value of type 'Double' to closure result type 'Int'}} } var closure6 = $0 // expected-error {{anonymous closure argument not contained in a closure}} var closure7 : Int = { 4 } // expected-error {{function produces expected type 'Int'; did you mean to call it with '()'?}} {{9-9=()}} var capturedVariable = 1 var closure8 = { [capturedVariable] in capturedVariable += 1 // expected-error {{left side of mutating operator isn't mutable: 'capturedVariable' is an immutable capture}} } func funcdecl1(_ a: Int, _ y: Int) {} func funcdecl3() -> Int {} func funcdecl4(_ a: ((Int) -> Int), _ b: Int) {} func funcdecl5(_ a: Int, _ y: Int) { // Pass in a closure containing the call to funcdecl3. funcdecl4({ funcdecl3() }, 12) // expected-error {{contextual type for closure argument list expects 1 argument, which cannot be implicitly ignored}} {{14-14= _ in}} func6({$0 + $1}) // Closure with two named anonymous arguments func6({($0) + $1}) // Closure with sequence expr inferred type func6({($0) + $0}) // // expected-error {{contextual closure type '(Int, Int) -> Int' expects 2 arguments, but 1 was used in closure body}} var testfunc : ((), Int) -> Int // expected-note {{'testfunc' declared here}} testfunc({$0+1}) // expected-error {{missing argument for parameter #2 in call}} funcdecl5(1, 2) // recursion. // Element access from a tuple. var a : (Int, f : Int, Int) var b = a.1+a.f // Tuple expressions with named elements. var i : (y : Int, x : Int) = (x : 42, y : 11) funcdecl1(123, 444) // Calls. 4() // expected-error {{cannot call value of non-function type 'Int'}}{{4-6=}} // rdar://12017658 - Infer some argument types from func6. func6({ a, b -> Int in a+b}) // Return type inference. func6({ a,b in a+b }) // Infer incompatible type. func6({a,b -> Float in 4.0 }) // expected-error {{declared closure result 'Float' is incompatible with contextual type 'Int'}} {{17-22=Int}} // Pattern doesn't need to name arguments. func6({ _,_ in 4 }) func6({a,b in 4.0 }) // expected-error {{cannot convert value of type 'Double' to closure result type 'Int'}} // TODO: This diagnostic can be improved: rdar://22128205 func6({(a : Float, b) in 4 }) // expected-error {{cannot convert value of type '(Float, _) -> Int' to expected argument type '(Int, Int) -> Int'}} var fn = {} var fn2 = { 4 } var c : Int = { a,b -> Int in a+b} // expected-error{{cannot convert value of type '(Int, Int) -> Int' to specified type 'Int'}} } func unlabeledClosureArgument() { func add(_ x: Int, y: Int) -> Int { return x + y } func6a({$0 + $1}) // single closure argument func6a(add) func6b(1, {$0 + $1}) // second arg is closure func6b(1, add) func6c({$0 + $1}) // second arg is default int func6c(add) } // rdar://11935352 - closure with no body. func closure_no_body(_ p: () -> ()) { return closure_no_body({}) } // rdar://12019415 func t() { let u8 : UInt8 = 1 let x : Bool = true if 0xA0..<0xBF ~= Int(u8) && x { } } // <rdar://problem/11927184> func f0(_ a: Any) -> Int { return 1 } assert(f0(1) == 1) var selfRef = { selfRef() } // expected-error {{variable used within its own initial value}} var nestedSelfRef = { var recursive = { nestedSelfRef() } // expected-error {{variable used within its own initial value}} recursive() } var shadowed = { (shadowed: Int) -> Int in let x = shadowed return x } // no-warning var shadowedShort = { (shadowedShort: Int) -> Int in shadowedShort+1 } // no-warning func anonymousClosureArgsInClosureWithArgs() { func f(_: String) {} var a1 = { () in $0 } // expected-error {{anonymous closure arguments cannot be used inside a closure that has explicit arguments}} var a2 = { () -> Int in $0 } // expected-error {{anonymous closure arguments cannot be used inside a closure that has explicit arguments}} var a3 = { (z: Int) in $0 } // expected-error {{anonymous closure arguments cannot be used inside a closure that has explicit arguments; did you mean 'z'?}} {{26-28=z}} var a4 = { (z: [Int], w: [Int]) in f($0.count) // expected-error {{anonymous closure arguments cannot be used inside a closure that has explicit arguments; did you mean 'z'?}} {{7-9=z}} expected-error {{cannot convert value of type 'Int' to expected argument type 'String'}} f($1.count) // expected-error {{anonymous closure arguments cannot be used inside a closure that has explicit arguments; did you mean 'w'?}} {{7-9=w}} expected-error {{cannot convert value of type 'Int' to expected argument type 'String'}} } var a5 = { (_: [Int], w: [Int]) in f($0.count) // expected-error {{anonymous closure arguments cannot be used inside a closure that has explicit arguments}} f($1.count) // expected-error {{anonymous closure arguments cannot be used inside a closure that has explicit arguments; did you mean 'w'?}} {{7-9=w}} expected-error {{cannot convert value of type 'Int' to expected argument type 'String'}} } } func doStuff(_ fn : @escaping () -> Int) {} func doVoidStuff(_ fn : @escaping () -> ()) {} // <rdar://problem/16193162> Require specifying self for locations in code where strong reference cycles are likely class ExplicitSelfRequiredTest { var x = 42 func method() -> Int { // explicit closure requires an explicit "self." base. doVoidStuff({ self.x += 1 }) doStuff({ x+1 }) // expected-error {{reference to property 'x' in closure requires explicit 'self.' to make capture semantics explicit}} {{15-15=self.}} doVoidStuff({ x += 1 }) // expected-error {{reference to property 'x' in closure requires explicit 'self.' to make capture semantics explicit}} {{19-19=self.}} // Methods follow the same rules as properties, uses of 'self' must be marked with "self." doStuff { method() } // expected-error {{call to method 'method' in closure requires explicit 'self.' to make capture semantics explicit}} {{15-15=self.}} doVoidStuff { _ = method() } // expected-error {{call to method 'method' in closure requires explicit 'self.' to make capture semantics explicit}} {{23-23=self.}} doStuff { self.method() } // <rdar://problem/18877391> "self." shouldn't be required in the initializer expression in a capture list // This should not produce an error, "x" isn't being captured by the closure. doStuff({ [myX = x] in myX }) // This should produce an error, since x is used within the inner closure. doStuff({ [myX = {x}] in 4 }) // expected-error {{reference to property 'x' in closure requires explicit 'self.' to make capture semantics explicit}} {{23-23=self.}} // expected-warning @-1 {{capture 'myX' was never used}} return 42 } } class SomeClass { var field : SomeClass? func foo() -> Int {} } func testCaptureBehavior(_ ptr : SomeClass) { // Test normal captures. weak var wv : SomeClass? = ptr unowned let uv : SomeClass = ptr unowned(unsafe) let uv1 : SomeClass = ptr unowned(safe) let uv2 : SomeClass = ptr doStuff { wv!.foo() } doStuff { uv.foo() } doStuff { uv1.foo() } doStuff { uv2.foo() } // Capture list tests let v1 : SomeClass? = ptr let v2 : SomeClass = ptr doStuff { [weak v1] in v1!.foo() } // expected-warning @+2 {{variable 'v1' was written to, but never read}} doStuff { [weak v1, // expected-note {{previous}} weak v1] in v1!.foo() } // expected-error {{definition conflicts with previous value}} doStuff { [unowned v2] in v2.foo() } doStuff { [unowned(unsafe) v2] in v2.foo() } doStuff { [unowned(safe) v2] in v2.foo() } doStuff { [weak v1, weak v2] in v1!.foo() + v2!.foo() } let i = 42 // expected-warning @+1 {{variable 'i' was never mutated}} {{19-20=let}} doStuff { [weak i] in i! } // expected-error {{'weak' may only be applied to class and class-bound protocol types, not 'Int'}} } extension SomeClass { func bar() { doStuff { [unowned self] in self.foo() } doStuff { [unowned xyz = self.field!] in xyz.foo() } doStuff { [weak xyz = self.field] in xyz!.foo() } // rdar://16889886 - Assert when trying to weak capture a property of self in a lazy closure doStuff { [weak self.field] in field!.foo() } // expected-error {{fields may only be captured by assigning to a specific name}} expected-error {{reference to property 'field' in closure requires explicit 'self.' to make capture semantics explicit}} {{36-36=self.}} // expected-warning @+1 {{variable 'self' was written to, but never read}} doStuff { [weak self&field] in 42 } // expected-error {{expected ']' at end of capture list}} } func strong_in_capture_list() { // <rdar://problem/18819742> QOI: "[strong self]" in capture list generates unhelpful error message _ = {[strong self] () -> () in return } // expected-error {{expected 'weak', 'unowned', or no specifier in capture list}} } } // <rdar://problem/16955318> Observed variable in a closure triggers an assertion var closureWithObservedProperty: () -> () = { var a: Int = 42 { willSet { _ = "Will set a to \(newValue)" } didSet { _ = "Did set a with old value of \(oldValue)" } } } ; {}() // expected-error{{top-level statement cannot begin with a closure expression}} // rdar://19179412 - Crash on valid code. func rdar19179412() -> (Int) -> Int { return { x in class A { let d : Int = 0 } } } // Test coercion of single-expression closure return types to void. func takesVoidFunc(_ f: () -> ()) {} var i: Int = 1 // expected-warning @+1 {{expression of type 'Int' is unused}} takesVoidFunc({i}) // expected-warning @+1 {{expression of type 'Int' is unused}} var f1: () -> () = {i} var x = {return $0}(1) func returnsInt() -> Int { return 0 } takesVoidFunc(returnsInt) // expected-error {{cannot convert value of type '() -> Int' to expected argument type '() -> ()'}} takesVoidFunc({() -> Int in 0}) // expected-error {{declared closure result 'Int' is incompatible with contextual type '()'}} {{22-25=()}} // These used to crash the compiler, but were fixed to support the implementation of rdar://problem/17228969 Void(0) // expected-error{{argument passed to call that takes no arguments}} _ = {0} // <rdar://problem/22086634> "multi-statement closures require an explicit return type" should be an error not a note let samples = { // expected-error {{unable to infer complex closure return type; add explicit type to disambiguate}} {{16-16= () -> Bool in }} if (i > 10) { return true } else { return false } }() // <rdar://problem/19756953> Swift error: cannot capture '$0' before it is declared func f(_ fp : (Bool, Bool) -> Bool) {} f { $0 && !$1 } // <rdar://problem/18123596> unexpected error on self. capture inside class method func TakesIntReturnsVoid(_ fp : ((Int) -> ())) {} struct TestStructWithStaticMethod { static func myClassMethod(_ count: Int) { // Shouldn't require "self." TakesIntReturnsVoid { _ in myClassMethod(0) } } } class TestClassWithStaticMethod { class func myClassMethod(_ count: Int) { // Shouldn't require "self." TakesIntReturnsVoid { _ in myClassMethod(0) } } } // Test that we can infer () as the result type of these closures. func genericOne<T>(_ a: () -> T) {} func genericTwo<T>(_ a: () -> T, _ b: () -> T) {} genericOne {} genericTwo({}, {}) // <rdar://problem/22344208> QoI: Warning for unused capture list variable should be customized class r22344208 { func f() { let q = 42 let _: () -> Int = { [unowned self, // expected-warning {{capture 'self' was never used}} q] in // expected-warning {{capture 'q' was never used}} 1 } } } var f = { (s: Undeclared) -> Int in 0 } // expected-error {{use of undeclared type 'Undeclared'}} // <rdar://problem/21375863> Swift compiler crashes when using closure, declared to return illegal type. func r21375863() { var width = 0 var height = 0 var bufs: [[UInt8]] = (0..<4).map { _ -> [asdf] in // expected-error {{use of undeclared type 'asdf'}} [UInt8](repeating: 0, count: width*height) } } // <rdar://problem/25993258> // Don't crash if we infer a closure argument to have a tuple type containing inouts. func r25993258_helper(_ fn: (inout Int, Int) -> ()) {} func r25993258a() { r25993258_helper { x in () } // expected-error {{named parameter has type '(inout Int, Int)' which includes nested inout parameters}} } func r25993258b() { r25993258_helper { _ in () } } // We have to map the captured var type into the right generic environment. class GenericClass<T> {} func lvalueCapture<T>(c: GenericClass<T>) { var cc = c weak var wc = c func innerGeneric<U>(_: U) { _ = cc _ = wc cc = wc! } }
apache-2.0
fd674b062dabcc9d8f7fb8d660bf660f
37.738764
270
0.640563
3.555298
false
false
false
false
wangwugang1314/weiBoSwift
weiBoSwift/weiBoSwift/Classes/Home/View/YBHomeCellBottomView.swift
1
2084
// // YBHomeCellBottomView.swift // weiBoSwift // // Created by MAC on 15/12/4. // Copyright © 2015年 MAC. All rights reserved. // import UIKit class YBHomeCellBottomView: UIView { // MARK: - 属性 // MARK: - 构造函数 override init(frame: CGRect) { super.init(frame: frame) // 准备UI prepareUI() backgroundColor = UIColor.lightGrayColor() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - 准备UI private func prepareUI(){ addSubview(retweetView) addSubview(commentView) addSubview(unlikeView) self.ff_HorizontalTile([retweetView, commentView, unlikeView], insets: UIEdgeInsets(top: 1, left: 1, bottom: 1, right: 1)) } // MARK: - 懒加载 /// 转发 private lazy var retweetView: UIButton = { let but = UIButton() but.setImage(UIImage(named: "timeline_icon_unlike"), forState: UIControlState.Normal) but.setTitle("转发", forState: UIControlState.Normal) but.setTitleColor(UIColor.grayColor(), forState: UIControlState.Normal) but.backgroundColor = UIColor.whiteColor() return but }() /// 评论 private lazy var commentView: UIButton = { let but = UIButton() but.setImage(UIImage(named: "timeline_icon_comment"), forState: UIControlState.Normal) but.setTitle("评论", forState: UIControlState.Normal) but.setTitleColor(UIColor.grayColor(), forState: UIControlState.Normal) but.backgroundColor = UIColor.whiteColor() return but }() /// 赞 private lazy var unlikeView: UIButton = { let but = UIButton() but.setImage(UIImage(named: "timeline_icon_unlike"), forState: UIControlState.Normal) but.setTitle("赞", forState: UIControlState.Normal) but.setTitleColor(UIColor.grayColor(), forState: UIControlState.Normal) but.backgroundColor = UIColor.whiteColor() return but }() }
apache-2.0
fe74290c229e85e8b65357eb634e1050
29.833333
130
0.630467
4.522222
false
false
false
false
sfurlani/addsumfun
Add Sum Fun/Add Sum Fun/NumbersViewController.swift
1
2816
// // NumbersViewController.swift // Add Sum Fun // // Created by SFurlani on 8/26/15. // Copyright © 2015 Dig-It! Games. All rights reserved. // import UIKit class NumbersViewController: UIViewController { @IBOutlet var numberRow: UIStackView! private(set) var panStart: CGPoint? private(set) var panView: NumberView? override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. let numberViews = (0...9).map { (index: UInt) in NumberView.newWithNumber(index) } for case let numberView? in numberViews { numberView.userInteractionEnabled = true numberRow.addArrangedSubview(numberView) } numberRow.setNeedsLayout() } private func numberViewForGesture(gesture: UIPanGestureRecognizer) -> NumberView? { let location = gesture.locationInView(view) return view.hitTest(location, withEvent: nil) as? NumberView } // MARK: - Gesture Actions func beginDraggingView(gesture: UIPanGestureRecognizer) -> Bool{ guard let numberView = numberViewForGesture(gesture) else { panStart = nil panView = nil return false } panStart = gesture.locationInView(view) panView = numberView return true } func updateDraggingView(gesture: UIPanGestureRecognizer) { guard let panView = panView, panStart = panStart else { return } let location = gesture.locationInView(view) panView.transform = transform(panStart, to: location) } func endDraggingView(switchViews: Bool, gesture: UIPanGestureRecognizer) { guard let panView = panView else { return } if switchViews { UIView.animateWithDuration(0.1, delay: 0, options: [], animations: { () -> Void in panView.alpha = 0.0 }, completion: { (finished: Bool) -> Void in panView.transform = CGAffineTransformIdentity UIView.animateWithDuration(0.1, animations: { () -> Void in panView.alpha = 1.0 }) }) } else { UIView.animateWithDuration(0.2, animations: { () -> Void in panView.transform = CGAffineTransformIdentity }) } self.panView = nil self.panStart = nil } private func transform(start: CGPoint, to: CGPoint) -> CGAffineTransform { let dX = to.x - start.x let dY = to.y - start.y return CGAffineTransformMakeTranslation(dX, dY) } }
mit
eff105a90594ce11d30d1db346a62eff
28.631579
94
0.568739
4.991135
false
false
false
false
Fenrikur/ef-app_ios
Eurofurence/Modules/Dealers/View/UIKit/DealersSearchTableViewController.swift
1
2063
import UIKit class DealersSearchTableViewController: UITableViewController { // MARK: Functions var onDidSelectSearchResultAtIndexPath: ((IndexPath) -> Void)? private var numberOfDealersPerSection: [Int] = [] private var sectionIndexTitles: [String]? private var binder: DealersSearchResultsBinder? func bindSearchResults(numberOfDealersPerSection: [Int], sectionIndexTitles: [String], using binder: DealersSearchResultsBinder) { self.numberOfDealersPerSection = numberOfDealersPerSection self.sectionIndexTitles = sectionIndexTitles self.binder = binder tableView.reloadData() } // MARK: Overrides override func viewDidLoad() { super.viewDidLoad() tableView.register(DealerComponentTableViewCell.self) tableView.registerConventionBrandedHeader() } override func numberOfSections(in tableView: UITableView) -> Int { return numberOfDealersPerSection.count } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return numberOfDealersPerSection[section] } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeue(DealerComponentTableViewCell.self) binder?.bind(cell, toDealerSearchResultAt: indexPath) return cell } override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let header = tableView.dequeueConventionBrandedHeader() binder?.bind(header, toDealerSearchResultGroupAt: section) return header } override func sectionIndexTitles(for tableView: UITableView) -> [String]? { return sectionIndexTitles } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) onDidSelectSearchResultAtIndexPath?(indexPath) } }
mit
7b33c65491f731e6282f85691c8aaca2
33.383333
109
0.705284
5.575676
false
false
false
false
marius-/GraphTheory
GraphTheory/Algorithms/PriorityQueue.swift
1
2863
/* Copyright (C) 2014 Bouke Haarsma Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ import Foundation public class PriorityQueue<PrioType: Comparable, ValueType>: GeneratorType { private final var heap = [(PrioType, ValueType)]() public init() { } public func push(priority: PrioType, item: ValueType) { heap.append((priority, item)) if heap.count == 1 { return } var current = heap.count - 1 while current > 0 { let parent = (current - 1) >> 1 if heap[parent].0 <= heap[current].0 { break } (heap[parent], heap[current]) = (heap[current], heap[parent]) current = parent } } public func next() -> ValueType? { return pop()?.1 } public func pop() -> (PrioType, ValueType)? { if heap.count == 0 { return nil } if heap.endIndex - 1 != 0 { swap(&heap[0], &heap[heap.endIndex - 1]) } let pop = heap.removeLast() heapify(0) return pop } public func removeAll() { heap = [] } private func heapify(index: Int) { let left = index * 2 + 1 let right = index * 2 + 2 var smallest = index let count = heap.count if left < count && heap[left].0 < heap[smallest].0 { smallest = left } if right < count && heap[right].0 < heap[smallest].0 { smallest = right } if smallest != index { swap(&heap[index], &heap[smallest]) heapify(smallest) } } public var count: Int { return heap.count } } extension PriorityQueue: SequenceType { public func generate() -> PriorityQueue { return self } }
mit
4fa904f19fa8ace4770ffe9626a7065b
28.515464
79
0.602864
4.544444
false
false
false
false