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
realDogbert/myScore
myScore/CourseManager.swift
1
1228
// // CourseManager.swift // myScore // // Created by Frank on 21.07.14. // Copyright (c) 2014 Frank von Eitzen. All rights reserved. // import UIKit import CoreData var manager = CourseManager() struct CourseManager { var context:NSManagedObjectContext! init() { var appDel = (UIApplication.sharedApplication().delegate as! AppDelegate) //self.context = appDel.managedObjectContext } func getCourseByName(name: String) -> Course { // Ebersberg Sepp Maier var holes = [ Hole(number: 1, par: 3, length: 128, average:4), Hole(number: 2, par: 4, length: 237, average:5), Hole(number: 3, par: 3, length: 152, average:4), Hole(number: 4, par: 4, length: 329, average:8), Hole(number: 5, par: 3, length: 104, average:3), Hole(number: 6, par: 3, length: 165, average:4), Hole(number: 7, par: 4, length: 280, average:5), Hole(number: 8, par: 3, length: 113, average:4), Hole(number: 9, par: 3, length: 91, average:4) ] var current = Course(name: "Ebersberg Sepp Maier", holes: holes) return current } }
mit
f45434646a4d136f45201eef5ddd1889
28.238095
81
0.570847
3.676647
false
false
false
false
BlurredSoftware/BSWInterfaceKit
Sources/BSWInterfaceKit/SwiftUI/AsyncStateView.swift
1
2729
#if canImport(SwiftUI) import SwiftUI @available(iOS 14, *) public protocol ViewDataInitiable { associatedtype Data init(data: Data) } /* Use this view like this: ``` AsyncStateView<ProductDetailsView>( model: AsyncStateModel( generator: Current.productDetailFactory(productID) ) ) ``` */ @available(iOS 14, *) public struct AsyncStateView<HostedView: View & ViewDataInitiable>: View { @StateObject public var model: AsyncStateModel<HostedView.Data> public var body: some View { switch model.state { case .loading: ProgressView() case .loaded(let data): HostedView(data: data) case .error(let error): ErrorView(error: error, onRetry: { self.model.fetchData() }) } } } import Combine @available(iOS 14, *) private extension AsyncStateView { struct ErrorView: View { let error: Swift.Error let onRetry: () -> () var body: some View { VStack(spacing: 16) { Text(error.localizedDescription) .multilineTextAlignment(.center) Button("Retry") { self.onRetry() } } .padding() } } } @available(iOS 14, *) public class AsyncStateModel<T>: ObservableObject { public typealias Generator = () -> Combine.AnyPublisher<T, Swift.Error> @Published public var state: State<T> public let generator: Generator public init(generator: @escaping Generator) { self.generator = generator self.state = .loading fetchData() } init(state: State<T>) { self.state = state self.generator = { Future.never().eraseToAnyPublisher() } fetchData() } deinit { cancellable?.cancel() } private var cancellable: AnyCancellable! func fetchData() { self.state = .loading let fetch = self.generator() cancellable = fetch.receive(on: DispatchQueue.main).sink(receiveCompletion: { (completion) in switch completion { case .failure(let error): self.state = .error(error) case .finished: break } self.cancellable.cancel() self.cancellable = nil }, receiveValue: { self.state = .loaded($0) }) } public enum State<T> { case loading case loaded(T) case error(Swift.Error) } } @available(iOS 14, *) private extension Future { static func never() -> Future<Output, Failure> { return .init { (_) in } } } #endif
mit
ad32276a889e7d838ab925ae35965d64
21.553719
101
0.55808
4.518212
false
false
false
false
gaurav1981/SwiftStructures
Source/Factories/Trie.swift
1
3345
// // Trie.swift // SwiftStructures // // Created by Wayne Bishop on 10/14/14. // Copyright (c) 2014 Arbutus Software Inc. All rights reserved. // import Foundation public class Trie { private var root: TrieNode! init(){ root = TrieNode() } //builds a tree hierarchy of dictionary content func append(word keyword: String) { //trivial case guard keyword.length > 0 else { return } var current: TrieNode = root while keyword.length != current.level { var childToUse: TrieNode! let searchKey = keyword.substring(to: current.level + 1) //print("current has \(current.children.count) children..") //iterate through child nodes for child in current.children { if (child.key == searchKey) { childToUse = child break } } //new node if childToUse == nil { childToUse = TrieNode() childToUse.key = searchKey childToUse.level = current.level + 1 current.children.append(childToUse) } current = childToUse } //end while //final end of word check if (keyword.length == current.level) { current.isFinal = true print("end of word reached!") return } } //end function //find words based on the prefix func search(forWord keyword: String) -> Array<String>! { //trivial case guard keyword.length > 0 else { return nil } var current: TrieNode = root var wordList = Array<String>() while keyword.length != current.level { var childToUse: TrieNode! let searchKey = keyword.substring(to: current.level + 1) //print("looking for prefix: \(searchKey)..") //iterate through any child nodes for child in current.children { if (child.key == searchKey) { childToUse = child current = childToUse break } } if childToUse == nil { return nil } } //end while //retrieve the keyword and any descendants if ((current.key == keyword) && (current.isFinal)) { wordList.append(current.key) } //include only children that are words for child in current.children { if (child.isFinal == true) { wordList.append(child.key) } } return wordList } //end function }
mit
2b519f2e294eb55014138cd94ef0ed39
21.006579
71
0.418834
6.275797
false
false
false
false
ngageoint/mage-ios
Mage/Extensions/UIApplicationTopController.swift
1
884
// // UIApplicationTopController.swift // MAGE // // Created by Daniel Barela on 11/19/20. // Copyright © 2020 National Geospatial Intelligence Agency. All rights reserved. // import Foundation extension UIApplication { @objc class func getTopViewController(base: UIViewController? = UIApplication.shared.windows.filter {$0.isKeyWindow}.first?.rootViewController) -> UIViewController? { if let nav = base as? UINavigationController { return getTopViewController(base: nav.visibleViewController) } else if let tab = base as? UITabBarController, let selected = tab.selectedViewController { return getTopViewController(base: selected) } else if let presented = base?.presentedViewController { return getTopViewController(base: presented) } return base } }
apache-2.0
47fb2952f0f52830079347ae76cfe89b
32.961538
170
0.677237
5.450617
false
false
false
false
leeaken/LTMap
LTMap/LTLocationMap/LocationManager/LTGeocodeManager.swift
1
3204
// // LTGeocodeManager.swift // LTMap // // POI地理位置搜索 // 国内调用高德poi,国外使用谷歌webservice // Created by aken on 2017/6/2. // Copyright © 2017年 LTMap. All rights reserved. // import UIKit class LTGeocodeManager { fileprivate var dataCompletion:SearchCompletion? fileprivate var searchManager:LTGeocodeProtocol? private var location:CLLocationCoordinate2D? /// 默认构造是用国内高德poi init(){ searchManager = createSearchCountry(type: .LTCN) } /// 通过构造参数经纬度来初始化poi搜索,国内使用高德,国外使用谷歌 /// /// - Parameter coordinate: 经纬度 init(coordinate:CLLocationCoordinate2D) { location = coordinate if isInChina() { searchManager = createSearchCountry(type: .LTCN) } else { searchManager = createSearchCountry(type: .LTAbroad) } } /// MARK: -- 私有方法 private func isInChina() ->Bool { // 默认为中国 if !CLLocationCoordinate2DIsValid(location!) { return true } return AMapLocationDataAvailableForCoordinate(location!) } private func createSearchCountry(type:LTGeocodeType) -> LTGeocodeProtocol? { switch type { case .LTCN: return LTGaodeGeocode() case.LTAbroad: return LTGoogleGeocode() } } func switchSearchCountry(type:LTGeocodeType) { // 如果当前type已经创建了,则直接返回 if searchManager?.type != type { searchManager = createSearchCountry(type:type) } } /// MARK: -- 公共方法 func searchReGeocodeWithCoordinate(coordinate: CLLocationCoordinate2D,completion:@escaping(SearchCompletion)) { if !CLLocationCoordinate2DIsValid(coordinate) { print("输入的经纬度不合法") return } searchManager?.searchReGeocodeWithCoordinate(coordinate: coordinate, completion: completion) } func searchNearbyWithCoordinate(param:LTPOISearchAroundArg,completion:@escaping(SearchCompletion)) { guard let coordinate = param.location,CLLocationCoordinate2DIsValid(coordinate) else { print("输入的经纬度不合法") return } searchManager?.searchNearbyWithCoordinate(param: param, completion: completion) } func searchInputTipsAutoCompletionWithKeyword(param:LTPOISearchAroundArg,completion:@escaping(SearchCompletion)) { searchManager?.searchInputTipsAutoCompletionWithKeyword(param: param, completion: completion) } func searchPlaceWithKeyWord(param:LTPOISearchAroundArg,completion:@escaping(SearchCompletion)) { searchManager?.searchPlaceWithKeyWord(param: param, completion: completion) } }
mit
8322546f6fd03a62dabe4a3c58f0bf5d
23.104839
118
0.592506
5.066102
false
false
false
false
prometheon/MLNimbleNinja
Nimble Ninja/MLCloudGenerator.swift
2
1431
// // MLCloudGenerator.swift // Nimble Ninja // // Created by Michael Leech on 1/30/15. // Copyright (c) 2015 CrashCourseCode. All rights reserved. // import Foundation import SpriteKit class MLCloudGenerator: SKSpriteNode { let CLOUD_WIDTH: CGFloat = 125.0 let CLOUD_HEIGHT: CGFloat = 55.0 var generationTimer: NSTimer! func populate(num: Int) { for var i = 0; i < num; i++ { let cloud = MLCloud(size: CGSizeMake(CLOUD_WIDTH, CLOUD_HEIGHT)) let x = CGFloat(arc4random_uniform(UInt32(size.width))) - size.width/2 let y = CGFloat(arc4random_uniform(UInt32(size.height))) - size.height/2 cloud.position = CGPointMake(x, y) cloud.zPosition = -1 addChild(cloud) } } func startGeneratingWithSpawnTime(seconds: NSTimeInterval) { generationTimer = NSTimer.scheduledTimerWithTimeInterval(seconds, target: self, selector: "generateCloud", userInfo: nil, repeats: true) } func stopGenerating() { generationTimer.invalidate() } func generateCloud() { let x = size.width/2 + CLOUD_WIDTH/2 let y = CGFloat(arc4random_uniform(UInt32(size.height))) - size.height/2 let cloud = MLCloud(size: CGSizeMake(CLOUD_WIDTH, CLOUD_HEIGHT)) cloud.position = CGPointMake(x, y) cloud.zPosition = -1 addChild(cloud) } }
mit
ec7d4fcf94923b8ff18383b990946cfe
29.468085
144
0.625437
3.942149
false
false
false
false
ps12138/dribbbleAPI
Model/Comment.swift
1
1376
// // Comment.swift // DribbbleModuleFramework // // Created by PSL on 12/7/16. // Copyright © 2016 PSL. All rights reserved. // import Foundation open class Comment { open let id: Int open var body: String open let likes_count: Int open let likes_url: String open let created_at: String open let updated_at: String open let user: User open var commentBody: CommentBody? init?(dict: Dictionary<String, AnyObject>?) { guard let id = dict?[CommentKey.id] as? Int, let body = dict?[CommentKey.body] as? String, let likes_count = dict?[CommentKey.likes_count] as? Int, let likes_url = dict?[CommentKey.likes_url] as? String, let created_at = dict?[CommentKey.created_at] as? String, let updated_at = dict?[CommentKey.updated_at] as? String, let user = User(dict: dict?[ShotKey.user] as? Dictionary<String, AnyObject>) else { return nil } self.id = id self.body = body self.likes_count = likes_count self.likes_url = likes_url self.created_at = created_at self.updated_at = updated_at self.user = user } public func translateBody(dict: Dictionary<String, AnyObject>?) { self.commentBody = CommentBody(dict: dict) } }
mit
3e862a9bbd2ac2d66e060a75ec85ea65
27.061224
88
0.595636
3.928571
false
false
false
false
YouareMylovelyGirl/Sina-Weibo
新浪微博/新浪微博/AppDelegate.swift
1
2703
// // AppDelegate.swift // 新浪微博 // // Created by 阳光 on 2017/6/5. // Copyright © 2017年 YG. All rights reserved. // import UIKit //iOS 10推出用户提醒 import UserNotifications import SVProgressHUD import AFNetworking @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { //应用程序额外设置 setupAdditions() //设置启动 window = UIWindow() window?.backgroundColor = UIColor.white window?.rootViewController = MainTabBarController() window?.makeKeyAndVisible() //异步加载网络数据 loadAppInfo() return true } } //MARK: - 设置应用程序额外信息 extension AppDelegate { fileprivate func setupAdditions() { //1. 设置 SVPregressHUD 最小接触时间 SVProgressHUD.setMinimumDismissTimeInterval(1.0) //2. 设置网络加载指示器 AFNetworkActivityIndicatorManager.shared().isEnabled = true //3. 设置用户授权显示通知 //最新用户提示 是检测设备版本, 如果是10.0 以上 if #available(iOS 10.0, *) { UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound, .carPlay]) { (success, error) in print("授权" + (success ? "成功" : "失败") )} } else { //取得用户授权显示通知"上方的提示条/ 声音/ BadgeNumber" 过期方法 10.0 一下 let notifySetting = UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil) //这是一个单利 UIApplication.shared.registerUserNotificationSettings(notifySetting) } } } //从服务器加载应用程序信息 extension AppDelegate { fileprivate func loadAppInfo() { //1. 模拟异步 DispatchQueue.global().async { //1> url let url = Bundle.main.url(forResource: "Main.json", withExtension: nil) //2> data let data = NSData(contentsOf: url!) //3> 写入磁盘 let docDir = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first! let jsonPath = (docDir as NSString).appendingPathComponent("Main.json") //直接保存在沙盒, 等待下一次程序启动 data?.write(toFile: jsonPath, atomically: true) print("应用程序加载完毕\(jsonPath)") } } }
apache-2.0
f7843697bf328188ec872c4243b42569
28.209877
144
0.615807
4.489564
false
false
false
false
johnno1962d/swift
stdlib/public/core/Builtin.swift
2
18659
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// import SwiftShims // Definitions that make elements of Builtin usable in real code // without gobs of boilerplate. /// Returns the contiguous memory footprint of `T`. /// /// Does not include any dynamically-allocated or "remote" storage. /// In particular, `sizeof(X.self)`, when `X` is a class type, is the /// same regardless of how many stored properties `X` has. @_transparent @warn_unused_result public func sizeof<T>(_:T.Type) -> Int { return Int(Builtin.sizeof(T.self)) } /// Returns the contiguous memory footprint of `T`. /// /// Does not include any dynamically-allocated or "remote" storage. /// In particular, `sizeof(a)`, when `a` is a class instance, is the /// same regardless of how many stored properties `a` has. @_transparent @warn_unused_result public func sizeofValue<T>(_:T) -> Int { return sizeof(T.self) } /// Returns the minimum memory alignment of `T`. @_transparent @warn_unused_result public func alignof<T>(_:T.Type) -> Int { return Int(Builtin.alignof(T.self)) } /// Returns the minimum memory alignment of `T`. @_transparent @warn_unused_result public func alignofValue<T>(_:T) -> Int { return alignof(T.self) } /// Returns the least possible interval between distinct instances of /// `T` in memory. The result is always positive. @_transparent @warn_unused_result public func strideof<T>(_:T.Type) -> Int { return Int(Builtin.strideof_nonzero(T.self)) } /// Returns the least possible interval between distinct instances of /// `T` in memory. The result is always positive. @_transparent @warn_unused_result public func strideofValue<T>(_:T) -> Int { return strideof(T.self) } @_versioned @warn_unused_result internal func _roundUp(_ offset: Int, toAlignment alignment: Int) -> Int { _sanityCheck(offset >= 0) _sanityCheck(alignment > 0) _sanityCheck(_isPowerOf2(alignment)) // Note, given that offset is >= 0, and alignment > 0, we don't // need to underflow check the -1, as it can never underflow. let x = (offset + alignment &- 1) // Note, as alignment is a power of 2, we'll use masking to efficiently // get the aligned value return x & ~(alignment &- 1) } /// Returns a tri-state of 0 = no, 1 = yes, 2 = maybe. @_transparent @warn_unused_result public // @testable func _canBeClass<T>(_: T.Type) -> Int8 { return Int8(Builtin.canBeClass(T.self)) } /// Returns the bits of `x`, interpreted as having type `U`. /// /// - Warning: Breaks the guarantees of Swift's type system; use /// with extreme care. There's almost always a better way to do /// anything. /// @_transparent @warn_unused_result public func unsafeBitCast<T, U>(_ x: T, to: U.Type) -> U { _precondition(sizeof(T.self) == sizeof(U.self), "can't unsafeBitCast between types of different sizes") return Builtin.reinterpretCast(x) } /// `unsafeBitCast` something to `AnyObject`. @_transparent @warn_unused_result public func _reinterpretCastToAnyObject<T>(_ x: T) -> AnyObject { return unsafeBitCast(x, to: AnyObject.self) } @_transparent @warn_unused_result func ==(lhs: Builtin.NativeObject, rhs: Builtin.NativeObject) -> Bool { return unsafeBitCast(lhs, to: Int.self) == unsafeBitCast(rhs, to: Int.self) } @_transparent @warn_unused_result func !=(lhs: Builtin.NativeObject, rhs: Builtin.NativeObject) -> Bool { return !(lhs == rhs) } @_transparent @warn_unused_result func ==(lhs: Builtin.RawPointer, rhs: Builtin.RawPointer) -> Bool { return unsafeBitCast(lhs, to: Int.self) == unsafeBitCast(rhs, to: Int.self) } @_transparent @warn_unused_result func !=(lhs: Builtin.RawPointer, rhs: Builtin.RawPointer) -> Bool { return !(lhs == rhs) } /// Returns `true` iff `t0` is identical to `t1`; i.e. if they are both /// `nil` or they both represent the same type. @warn_unused_result public func == (t0: Any.Type?, t1: Any.Type?) -> Bool { return unsafeBitCast(t0, to: Int.self) == unsafeBitCast(t1, to: Int.self) } /// Returns `false` iff `t0` is identical to `t1`; i.e. if they are both /// `nil` or they both represent the same type. @warn_unused_result public func != (t0: Any.Type?, t1: Any.Type?) -> Bool { return !(t0 == t1) } /// Tell the optimizer that this code is unreachable if condition is /// known at compile-time to be true. If condition is false, or true /// but not a compile-time constant, this call has no effect. @_transparent internal func _unreachable(_ condition: Bool = true) { if condition { // FIXME: use a parameterized version of Builtin.unreachable when // <rdar://problem/16806232> is closed. Builtin.unreachable() } } /// Tell the optimizer that this code is unreachable if this builtin is /// reachable after constant folding build configuration builtins. @_versioned @_transparent @noreturn internal func _conditionallyUnreachable() { Builtin.conditionallyUnreachable() } @_versioned @warn_unused_result @_silgen_name("swift_isClassOrObjCExistentialType") func _swift_isClassOrObjCExistentialType<T>(_ x: T.Type) -> Bool /// Returns `true` iff `T` is a class type or an `@objc` existential such as /// `AnyObject`. @_versioned @inline(__always) @warn_unused_result internal func _isClassOrObjCExistential<T>(_ x: T.Type) -> Bool { let tmp = _canBeClass(x) // Is not a class. if tmp == 0 { return false // Is a class. } else if tmp == 1 { return true } // Maybe a class. return _swift_isClassOrObjCExistentialType(x) } /// Returns an `UnsafePointer` to the storage used for `object`. There's /// not much you can do with this other than use it to identify the /// object. @_transparent @warn_unused_result public func unsafeAddress(of object: AnyObject) -> UnsafePointer<Void> { return UnsafePointer(Builtin.bridgeToRawPointer(object)) } @available(*, unavailable, renamed: "unsafeAddress(of:)") public func unsafeAddressOf(_ object: AnyObject) -> UnsafePointer<Void> { fatalError("unavailable function can't be called") } /// Converts a reference of type `T` to a reference of type `U` after /// unwrapping one level of Optional. /// /// Unwrapped `T` and `U` must be convertible to AnyObject. They may /// be either a class or a class protocol. Either T, U, or both may be /// optional references. @_transparent @warn_unused_result public func _unsafeReferenceCast<T, U>(_ x: T, to: U.Type) -> U { return Builtin.castReference(x) } /// - returns: `x as T`. /// /// - Precondition: `x is T`. In particular, in -O builds, no test is /// performed to ensure that `x` actually has dynamic type `T`. /// /// - Warning: Trades safety for performance. Use `unsafeDowncast` /// only when `x as T` has proven to be a performance problem and you /// are confident that, always, `x is T`. It is better than an /// `unsafeBitCast` because it's more restrictive, and because /// checking is still performed in debug builds. @_transparent @warn_unused_result public func unsafeDowncast<T : AnyObject>(_ x: AnyObject, to: T.Type) -> T { _debugPrecondition(x is T, "invalid unsafeDowncast") return Builtin.castReference(x) } @inline(__always) @warn_unused_result public func _getUnsafePointerToStoredProperties(_ x: AnyObject) -> UnsafeMutablePointer<UInt8> { let storedPropertyOffset = _roundUp( sizeof(_HeapObject.self), toAlignment: alignof(Optional<AnyObject>.self)) return UnsafeMutablePointer<UInt8>(Builtin.bridgeToRawPointer(x)) + storedPropertyOffset } //===----------------------------------------------------------------------===// // Branch hints //===----------------------------------------------------------------------===// // Use @_semantics to indicate that the optimizer recognizes the // semantics of these function calls. This won't be necessary with // mandatory generic inlining. @_versioned @_transparent @_semantics("branchhint") @warn_unused_result internal func _branchHint<C : Boolean>(_ actual: C, expected: Bool) -> Bool { return Bool(Builtin.int_expect_Int1(actual.boolValue._value, expected._value)) } /// Optimizer hint that `x` is expected to be `true`. @_transparent @_semantics("fastpath") @warn_unused_result public func _fastPath<C: Boolean>(_ x: C) -> Bool { return _branchHint(x.boolValue, expected: true) } /// Optimizer hint that `x` is expected to be `false`. @_transparent @_semantics("slowpath") @warn_unused_result public func _slowPath<C : Boolean>(_ x: C) -> Bool { return _branchHint(x.boolValue, expected: false) } /// Optimizer hint that the code where this function is called is on the fast /// path. @_transparent public func _onFastPath() { Builtin.onFastPath() } //===--- Runtime shim wrappers --------------------------------------------===// /// Returns `true` iff the class indicated by `theClass` uses native /// Swift reference-counting. @_versioned @inline(__always) @warn_unused_result internal func _usesNativeSwiftReferenceCounting(_ theClass: AnyClass) -> Bool { #if _runtime(_ObjC) return swift_objc_class_usesNativeSwiftReferenceCounting( unsafeAddress(of: theClass) ) #else return true #endif } @warn_unused_result @_silgen_name("swift_class_getInstanceExtents") func swift_class_getInstanceExtents(_ theClass: AnyClass) -> (negative: UInt, positive: UInt) @warn_unused_result @_silgen_name("swift_objc_class_unknownGetInstanceExtents") func swift_objc_class_unknownGetInstanceExtents(_ theClass: AnyClass) -> (negative: UInt, positive: UInt) /// - Returns: @inline(__always) @warn_unused_result internal func _class_getInstancePositiveExtentSize(_ theClass: AnyClass) -> Int { #if _runtime(_ObjC) return Int(swift_objc_class_unknownGetInstanceExtents(theClass).positive) #else return Int(swift_class_getInstanceExtents(theClass).positive) #endif } //===--- Builtin.BridgeObject ---------------------------------------------===// #if arch(i386) || arch(arm) @_versioned internal var _objectPointerSpareBits: UInt { @inline(__always) get { return 0x0000_0003 } } @_versioned internal var _objectPointerIsObjCBit: UInt { @inline(__always) get { return 0x0000_0002 } } @_versioned internal var _objectPointerLowSpareBitShift: UInt { @inline(__always) get { return 0 } } @_versioned internal var _objCTaggedPointerBits: UInt { @inline(__always) get { return 0 } } #elseif arch(x86_64) @_versioned internal var _objectPointerSpareBits: UInt { @inline(__always) get { return 0x7F00_0000_0000_0006 } } @_versioned internal var _objectPointerIsObjCBit: UInt { @inline(__always) get { return 0x4000_0000_0000_0000 } } @_versioned internal var _objectPointerLowSpareBitShift: UInt { @inline(__always) get { return 1 } } @_versioned internal var _objCTaggedPointerBits: UInt { @inline(__always) get { return 0x8000_0000_0000_0001 } } #elseif arch(arm64) @_versioned internal var _objectPointerSpareBits: UInt { @inline(__always) get { return 0x7F00_0000_0000_0007 } } @_versioned internal var _objectPointerIsObjCBit: UInt { @inline(__always) get { return 0x4000_0000_0000_0000 } } @_versioned internal var _objectPointerLowSpareBitShift: UInt { @inline(__always) get { return 0 } } @_versioned internal var _objCTaggedPointerBits: UInt { @inline(__always) get { return 0x8000_0000_0000_0000 } } #elseif arch(powerpc64) || arch(powerpc64le) @_versioned internal var _objectPointerSpareBits: UInt { @inline(__always) get { return 0x0000_0000_0000_0007 } } @_versioned internal var _objectPointerIsObjCBit: UInt { @inline(__always) get { return 0x0000_0000_0000_0002 } } @_versioned internal var _objectPointerLowSpareBitShift: UInt { @inline(__always) get { return 0 } } @_versioned internal var _objCTaggedPointerBits: UInt { @inline(__always) get { return 0 } } #endif /// Extract the raw bits of `x`. @_versioned @inline(__always) @warn_unused_result internal func _bitPattern(_ x: Builtin.BridgeObject) -> UInt { return UInt(Builtin.castBitPatternFromBridgeObject(x)) } /// Extract the raw spare bits of `x`. @_versioned @inline(__always) @warn_unused_result internal func _nonPointerBits(_ x: Builtin.BridgeObject) -> UInt { return _bitPattern(x) & _objectPointerSpareBits } @_versioned @inline(__always) @warn_unused_result internal func _isObjCTaggedPointer(_ x: AnyObject) -> Bool { return (Builtin.reinterpretCast(x) & _objCTaggedPointerBits) != 0 } /// Create a `BridgeObject` around the given `nativeObject` with the /// given spare bits. /// /// Reference-counting and other operations on this /// object will have access to the knowledge that it is native. /// /// - Precondition: `bits & _objectPointerIsObjCBit == 0`, /// `bits & _objectPointerSpareBits == bits`. @_versioned @inline(__always) @warn_unused_result internal func _makeNativeBridgeObject( _ nativeObject: AnyObject, _ bits: UInt ) -> Builtin.BridgeObject { _sanityCheck( (bits & _objectPointerIsObjCBit) == 0, "BridgeObject is treated as non-native when ObjC bit is set" ) return _makeBridgeObject(nativeObject, bits) } /// Create a `BridgeObject` around the given `objCObject`. @inline(__always) @warn_unused_result public // @testable func _makeObjCBridgeObject( _ objCObject: AnyObject ) -> Builtin.BridgeObject { return _makeBridgeObject( objCObject, _isObjCTaggedPointer(objCObject) ? 0 : _objectPointerIsObjCBit) } /// Create a `BridgeObject` around the given `object` with the /// given spare bits. /// /// - Precondition: /// /// 1. `bits & _objectPointerSpareBits == bits` /// 2. if `object` is a tagged pointer, `bits == 0`. Otherwise, /// `object` is either a native object, or `bits == /// _objectPointerIsObjCBit`. @_versioned @inline(__always) @warn_unused_result internal func _makeBridgeObject( _ object: AnyObject, _ bits: UInt ) -> Builtin.BridgeObject { _sanityCheck(!_isObjCTaggedPointer(object) || bits == 0, "Tagged pointers cannot be combined with bits") _sanityCheck( _isObjCTaggedPointer(object) || _usesNativeSwiftReferenceCounting(object.dynamicType) || bits == _objectPointerIsObjCBit, "All spare bits must be set in non-native, non-tagged bridge objects" ) _sanityCheck( bits & _objectPointerSpareBits == bits, "Can't store non-spare bits into Builtin.BridgeObject") return Builtin.castToBridgeObject( object, bits._builtinWordValue ) } /// Returns the superclass of `t`, if any. The result is `nil` if `t` is /// a root class or class protocol. @inline(__always) @warn_unused_result public // @testable func _getSuperclass(_ t: AnyClass) -> AnyClass? { return unsafeBitCast( swift_class_getSuperclass(unsafeBitCast(t, to: OpaquePointer.self)), to: AnyClass.self) } /// Returns the superclass of `t`, if any. The result is `nil` if `t` is /// not a class, is a root class, or is a class protocol. @inline(__always) @warn_unused_result public // @testable func _getSuperclass(_ t: Any.Type) -> AnyClass? { return (t as? AnyClass).flatMap { _getSuperclass($0) } } //===--- Builtin.IsUnique -------------------------------------------------===// // _isUnique functions must take an inout object because they rely on // Builtin.isUnique which requires an inout reference to preserve // source-level copies in the presence of ARC optimization. // // Taking an inout object makes sense for two additional reasons: // // 1. You should only call it when about to mutate the object. // Doing so otherwise implies a race condition if the buffer is // shared across threads. // // 2. When it is not an inout function, self is passed by // value... thus bumping the reference count and disturbing the // result we are trying to observe, Dr. Heisenberg! // // _isUnique and _isUniquePinned cannot be made public or the compiler // will attempt to generate generic code for the transparent function // and type checking will fail. /// Returns `true` if `object` is uniquely referenced. @_versioned @_transparent @warn_unused_result internal func _isUnique<T>(_ object: inout T) -> Bool { return Bool(Builtin.isUnique(&object)) } /// Returns `true` if `object` is uniquely referenced or pinned. @_versioned @_transparent @warn_unused_result internal func _isUniqueOrPinned<T>(_ object: inout T) -> Bool { return Bool(Builtin.isUniqueOrPinned(&object)) } /// Returns `true` if `object` is uniquely referenced. /// This provides sanity checks on top of the Builtin. @_transparent @warn_unused_result public // @testable func _isUnique_native<T>(_ object: inout T) -> Bool { // This could be a bridge object, single payload enum, or plain old // reference. Any case it's non pointer bits must be zero, so // force cast it to BridgeObject and check the spare bits. _sanityCheck( (_bitPattern(Builtin.reinterpretCast(object)) & _objectPointerSpareBits) == 0) _sanityCheck(_usesNativeSwiftReferenceCounting( (Builtin.reinterpretCast(object) as AnyObject).dynamicType)) return Bool(Builtin.isUnique_native(&object)) } /// Returns `true` if `object` is uniquely referenced or pinned. /// This provides sanity checks on top of the Builtin. @_transparent @warn_unused_result public // @testable func _isUniqueOrPinned_native<T>(_ object: inout T) -> Bool { // This could be a bridge object, single payload enum, or plain old // reference. Any case it's non pointer bits must be zero. _sanityCheck( (_bitPattern(Builtin.reinterpretCast(object)) & _objectPointerSpareBits) == 0) _sanityCheck(_usesNativeSwiftReferenceCounting( (Builtin.reinterpretCast(object) as AnyObject).dynamicType)) return Bool(Builtin.isUniqueOrPinned_native(&object)) } /// Returns `true` if type is a POD type. A POD type is a type that does not /// require any special handling on copying or destruction. @_transparent @warn_unused_result public // @testable func _isPOD<T>(_ type: T.Type) -> Bool { return Bool(Builtin.ispod(type)) } /// Returns `true` if type is nominally an Optional type. @_transparent @warn_unused_result public // @testable func _isOptional<T>(_ type: T.Type) -> Bool { return Bool(Builtin.isOptional(type)) } @available(*, unavailable, message: "Removed in Swift 3. Please use Optional.unsafelyUnwrapped instead.") public func unsafeUnwrap<T>(_ nonEmpty: T?) -> T { fatalError("unavailable function can't be called") }
apache-2.0
15a5c106b24743201743e3055f655694
30.202341
105
0.695696
3.915023
false
false
false
false
davidkobilnyk/BNRGuideSolutionsInSwift
11-Camera/HomePwner/HomePwner/BNRItemsViewController.swift
2
5485
// // BNRItemsViewController.swift // HomePwner // // Created by David Kobilnyk on 7/8/14. // Copyright (c) 2014 David Kobilnyk. All rights reserved. // import UIKit class BNRItemsViewController: UITableViewController { // Need to add this init in in Swift, or you get "fatal error: use of unimplemented initializer 'init(nibName:bundle:)' for class" override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) } override init() { super.init(style: UITableViewStyle.Plain) let navItem = self.navigationItem navItem.title = "Homepwner" // Create a new bar button item that will send // addNewItem: to BNRItemsViewController let bbi = UIBarButtonItem(barButtonSystemItem: .Add, target: self, action: "addNewItem:") // Set this bar button item as the right item in the navigationItem navItem.rightBarButtonItem = bbi navItem.leftBarButtonItem = self.editButtonItem() } override convenience init(style: UITableViewStyle) { self.init() } // Without this, get error: "Class ‘BNRItemsViewController’ does not implement its // superclass’s required members" required init(coder aDecoder: NSCoder) { fatalError("NSCoding not supported") } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) tableView.reloadData() } override func viewDidLoad() { super.viewDidLoad() // Use .self to get the class. It's equivalent to [UITableViewCell class] in Objective-C. tableView!.registerClass(UITableViewCell.self, forCellReuseIdentifier: "UITableViewCell") } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int)->Int { return BNRItemStore.sharedStore.allItems.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { // Get a new or recycled cell let cell: UITableViewCell = tableView.dequeueReusableCellWithIdentifier("UITableViewCell") as UITableViewCell // Set the text on the cell with the description of the item // that is at the nth index of items, where n = row this cell // will appear in on the tableview let item = BNRItemStore.sharedStore.allItems[indexPath.row] cell.textLabel?.text = item.description return cell } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { let detailViewController = BNRDetailViewController() let items = BNRItemStore.sharedStore.allItems let selectedItem = items[indexPath.row] // Give detail view controller a pointer to the item object in row detailViewController.item = selectedItem // Push it onto the top of the navigation controller's stack self.navigationController?.pushViewController(detailViewController, animated: true) } override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { // If the table view is asking to commit a delete command... if (editingStyle == .Delete) { var items = BNRItemStore.sharedStore.allItems var item = items[indexPath.row] BNRItemStore.sharedStore.removeItem(item) // Also remove that row from the table view with an animation tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } } override func tableView(tableView: UITableView, moveRowAtIndexPath sourceIndexPath: NSIndexPath, toIndexPath destinationIndexPath: NSIndexPath) { BNRItemStore.sharedStore.moveItemAtIndex(sourceIndexPath.row, toIndex: destinationIndexPath.row) } @IBAction func addNewItem(sender: UIButton) { // Create a new BNRItem and add it to the store var newItem = BNRItemStore.sharedStore.createItem() // Figure out where that item is in the array var lastRow: Int = 0 for i in 0..<BNRItemStore.sharedStore.allItems.count { if BNRItemStore.sharedStore.allItems[i] === newItem { lastRow = i break } } // I wonder why BNR does it like this -- searching through the array for the new // element instead of just using count-1 for lastRow var indexPath = NSIndexPath(forRow: lastRow, inSection: 0) // Insert this new row into the table. tableView.insertRowsAtIndexPaths([indexPath], withRowAnimation: .Top) } @IBAction func toggleEditingMode(sender: UIButton) { // If you are currently in editing mode... if editing { // Change text of button to inform user of state sender.setTitle("Edit", forState: .Normal) // Turn off editing mode setEditing(false, animated: true) } else { // Change tet of button to inform user of state sender.setTitle("Done", forState: .Normal) // Enter editing mode setEditing(true, animated: true) } } }
mit
a45c5190186f7325dfa7d2858e9d4e1c
38.135714
157
0.653221
5.468064
false
false
false
false
6ag/BaoKanIOS
BaoKanIOS/Classes/Utils/JFSQLiteManager.swift
1
3710
// // JFSQLiteManager.swift // LiuAGeIOS // // Created by zhoujianfeng on 16/6/12. // Copyright © 2016年 六阿哥. All rights reserved. // import UIKit import FMDB let NEWS_LIST_HOME_TOP = "jf_newslist_hometop" // 首页 列表页 的 幻灯片 数据表 let NEWS_LIST_HOME_LIST = "jf_newslist_homelist" // 首页 列表页 的 列表 数据表 let NEWS_LIST_OTHER_TOP = "jf_newslist_othertop" // 其他分类 列表页 的 幻灯片 数据表 let NEWS_LIST_OTHER_LIST = "jf_newslist_otherlist" // 其他分类 列表页 的 列表 数据表 let NEWS_CONTENT = "jf_news_content" // 资讯/图库 正文 数据表 let SEARCH_KEYBOARD = "jf_search_keyboard" // 搜索关键词数据表 class JFSQLiteManager: NSObject { /// FMDB单例 static let shareManager = JFSQLiteManager() /// sqlite数据库名 fileprivate let newsDBName = "news.db" let dbQueue: FMDatabaseQueue override init() { let documentPath = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true).last! let dbPath = "\(documentPath)/\(newsDBName)" print(dbPath) // 根据路径创建并打开数据库,开启一个串行队列 dbQueue = FMDatabaseQueue(path: dbPath) super.init() // 创建数据表 createNewsListTable(NEWS_LIST_HOME_TOP) createNewsListTable(NEWS_LIST_HOME_LIST) createNewsListTable(NEWS_LIST_OTHER_TOP) createNewsListTable(NEWS_LIST_OTHER_LIST) createNewsContentTable() createSearchKeyboardTable() } /** 创建新闻列表的数据表 - parameter tbname: 表名 */ fileprivate func createNewsListTable(_ tbname: String) { let sql = "CREATE TABLE IF NOT EXISTS \(tbname) ( \n" + "id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, \n" + "classid INTEGER, \n" + "news TEXT, \n" + "createTime VARCHAR(30) DEFAULT (datetime('now', 'localtime')) \n" + ");" dbQueue.inDatabase { (db) in if (db?.executeStatements(sql))! { print("创建 \(tbname) 表成功") } else { print("创建 \(tbname) 表失败") } } } /** 创建资讯内容数据表 */ fileprivate func createNewsContentTable() { let sql = "CREATE TABLE IF NOT EXISTS \(NEWS_CONTENT) ( \n" + "id INTEGER, \n" + "classid INTEGER, \n" + "news TEXT, \n" + "createTime VARCHAR(30) DEFAULT (datetime('now', 'localtime')) \n" + ");" dbQueue.inDatabase { (db) in if (db?.executeStatements(sql))! { print("创建 \(NEWS_CONTENT) 表成功") } else { print("创建 \(NEWS_CONTENT) 表失败") } } } /** 创建搜索关键词数据表 */ fileprivate func createSearchKeyboardTable() { let sql = "CREATE TABLE IF NOT EXISTS \(SEARCH_KEYBOARD) ( \n" + "id INTEGER, \n" + "keyboard VARCHAR(30), \n" + "pinyin VARCHAR(30), \n" + "num INTEGER, \n" + "createTime VARCHAR(30) DEFAULT (datetime('now', 'localtime')) \n" + ");" dbQueue.inDatabase { (db) in if (db?.executeStatements(sql))! { print("创建 \(SEARCH_KEYBOARD) 表成功") } else { print("创建 \(SEARCH_KEYBOARD) 表失败") } } } }
apache-2.0
c00453af0a92f307bc7a4735fa834755
29.1875
174
0.540964
3.982332
false
false
false
false
griff/metaz
Framework/src/String-matches-mimetype-pattern.swift
1
975
// // String-matches-mimetype-pattern.swift // MetaZKit // // Created by Brian Olsen on 22/02/2020. // import Foundation extension String { public func matches(mimeTypePattern pattern: String) -> Bool { if pattern == "*" { return true } var pattern = pattern var range : Range<String.Index> = self.startIndex ..< self.endIndex var length = pattern.endIndex if pattern.hasSuffix("/*") { length = pattern.index(before: length) pattern = String(pattern.prefix(upTo: length)) if length < range.upperBound { range = self.startIndex ..< length } } else if range.upperBound != length { return false } return self.compare(pattern, options: [.caseInsensitive, .literal], range: range, locale: nil) == .orderedSame } }
mit
9e7ab16d7138c71c5bd26f7c02366ea9
28.545455
75
0.526154
4.850746
false
false
false
false
dklinzh/NodeExtension
NodeExtension/Classes/UIKit/String.swift
1
3198
// // String.swift // NodeExtension // // Created by Linzh on 8/20/17. // Copyright (c) 2017 Daniel Lin. All rights reserved. // /// Get localized string for the specified key from a custom table /// /// - Parameters: /// - key: The specified key /// - tableName: The custom table /// - Returns: Localized string from the specified strings table public func DLLocalizedString(_ key: String, tableName: String? = "Localizable") -> String { return NSLocalizedString(key, tableName: tableName, comment: "") } extension NSAttributedString { /// Create a NSAttributedString with some attributes /// /// - Parameters: /// - string: The string for the new attributed string /// - size: The font size of attributed string /// - color: The color of attributed string /// - Returns: A NSAttributedString instance public static func dl_attributedString(string: String, fontSize size: CGFloat, color: UIColor = .black) -> NSAttributedString { return NSAttributedString.dl_attributedString(string: string, fontSize: size, color: color, firstWordColor: nil) } /// Create a NSAttributedString with some attributes /// /// - Parameters: /// - string: The string for the new attributed string /// - size: The font size of attributed string /// - color: The color of attributed string /// - firstWordColor: The color of frist word /// - Returns: A NSAttributedString instance public static func dl_attributedString(string: String, fontSize size: CGFloat, color: UIColor = .black, firstWordColor: UIColor? = nil) -> NSAttributedString { let attributes = [NSAttributedString.Key.foregroundColor: color, NSAttributedString.Key.font: UIFont.systemFont(ofSize: size)] let attributedString = NSMutableAttributedString(string: string, attributes: attributes) if let firstWordColor = firstWordColor { let nsString = string as NSString let firstSpaceRange = nsString.rangeOfCharacter(from: NSCharacterSet.whitespaces) let firstWordRange = NSMakeRange(0, firstSpaceRange.location) attributedString.addAttribute(NSAttributedString.Key.foregroundColor, value: firstWordColor, range: firstWordRange) } return attributedString } /// Add attributs of font size and text color to the NSAttributedString /// /// - Parameters: /// - range: The range of characters to which the specified attributes apply /// - font: The font of text /// - color: The text color /// - Returns: A NSAttributedString instance public func dl_stringAddAttribute(range: NSRange, font: UIFont, color: UIColor) -> NSAttributedString { guard range.location != NSNotFound else { return self } let attributedString = self.mutableCopy() as! NSMutableAttributedString let attributes = [NSAttributedString.Key.foregroundColor: color, NSAttributedString.Key.font: font] attributedString.addAttributes(attributes, range: range) return attributedString } }
mit
c334b9a9f0248c6922ed188412effb7e
41.64
163
0.66823
5.141479
false
false
false
false
AppLovin/iOS-SDK-Demo
Swift Demo App/iOS-SDK-Demo/ALEventTrackingViewController.swift
1
8088
// // ALEventTrackingViewController.swift // iOS-SDK-Demo-Swift // // Created by Monica Ong on 6/5/17. // Copyright © 2017 AppLovin. All rights reserved. // import UIKit import StoreKit import AppLovinSDK struct ALDemoEvent { var name: String var purpose: String } class ALEventTrackingViewController : ALDemoBaseTableViewController { private let events = [ALDemoEvent(name: "Began Checkout Event", purpose: "Track when user begins checkout procedure"), ALDemoEvent(name: "Cart Event", purpose: "Track when user adds an item to cart"), ALDemoEvent(name: "Completed Achievement Event", purpose: "Track when user completed an achievement"), ALDemoEvent(name: "Completed Checkout Event", purpose: "Track when user completed checkout"), ALDemoEvent(name: "Completed Level Event", purpose: "Track when user completed level"), ALDemoEvent(name: "Created Reservation Event", purpose: "Track when user created a reservation"), ALDemoEvent(name: "In-App Purchase Event", purpose: "Track when user makes an in-app purchase"), ALDemoEvent(name: "Login Event", purpose: "Track when user logs in"), ALDemoEvent(name: "Payment Info Event", purpose: "Tracks when user inputs their payment information"), ALDemoEvent(name: "Registration Event", purpose: "Track when user registers"), ALDemoEvent(name: "Search Event", purpose: "Track when user makes a search"), ALDemoEvent(name: "Sent Invitation Event", purpose: "Track when user sends invitation"), ALDemoEvent(name: "Shared Link Event", purpose: "Track when user shares a link"), ALDemoEvent(name: "Spent Virtual Currency Event", purpose: "Track when users spends virtual currency"), ALDemoEvent(name: "Tutorial Event", purpose: "Track when users does a tutorial"), ALDemoEvent(name: "Viewed Content Event", purpose: "Track when user views content"), ALDemoEvent(name: "Viewed Product Event", purpose: "Track when user views product"), ALDemoEvent(name: "Wishlist Event", purpose: "Track when user adds an item to their wishlist")] // MARK: Table View Data Source override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return events.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "rootPrototype", for: indexPath) cell.textLabel!.text = events[indexPath.row].name cell.detailTextLabel!.text = events[indexPath.row].purpose return cell } // MARK: Table View Delegate override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) let eventService = ALSdk.shared()!.eventService switch indexPath.row { case 0: eventService.trackEvent(kALEventTypeUserBeganCheckOut, parameters: [kALEventParameterProductIdentifierKey : "PRODUCT SKU OR ID", kALEventParameterRevenueAmountKey : "PRICE OF ITEM", kALEventParameterRevenueCurrencyKey : "3-LETTER CURRENCY CODE"]) case 1: eventService.trackEvent(kALEventTypeUserAddedItemToCart, parameters: [kALEventParameterProductIdentifierKey : "PRODUCT SKU OR ID"]) case 2: eventService.trackEvent(kALEventTypeUserCompletedAchievement, parameters: [kALEventParameterCompletedAchievementKey : "ACHIEVEMENT NAME OR ID"]) case 3: eventService.trackEvent(kALEventTypeUserCompletedCheckOut, parameters: [kALEventParameterCheckoutTransactionIdentifierKey : "UNIQUE TRANSACTION ID", kALEventParameterProductIdentifierKey : "PRODUCT SKU OR ID", kALEventParameterRevenueAmountKey : "AMOUNT OF MONEY SPENT", kALEventParameterRevenueCurrencyKey : "3-LETTER CURRENCY CODE"]) case 4: eventService.trackEvent(kALEventTypeUserCompletedLevel, parameters: [kALEventParameterCompletedLevelKey : "LEVEL NAME OR NUMBER"]) case 5: eventService.trackEvent(kALEventTypeUserCreatedReservation, parameters: [kALEventParameterProductIdentifierKey : "PRODUCT SKU OR ID", kALEventParameterReservationStartDateKey : "START NSDATE", kALEventParameterReservationEndDateKey : "END NSDATE"]) case 6: //In-App Purchases // let transaction: SKPaymentTransaction = ... // from paymentQueue:updatedTransactions: //let product: SKProduct = ... // Appropriate product (matching productIdentifier property to SKPaymentTransaction) eventService.trackInAppPurchase(withTransactionIdentifier: "transaction.transactionIdentifier", parameters: [kALEventParameterRevenueAmountKey : "AMOUNT OF MONEY SPENT", kALEventParameterRevenueCurrencyKey : "3-LETTER CURRENCY CODE", kALEventParameterProductIdentifierKey : "product.productIdentifier"]) //product.productIdentifier case 7: eventService.trackEvent(kALEventTypeUserLoggedIn, parameters: [kALEventParameterUserAccountIdentifierKey : "USERNAME"]) case 8: eventService.trackEvent(kALEventTypeUserProvidedPaymentInformation) case 9: eventService.trackEvent(kALEventTypeUserCreatedAccount, parameters: [kALEventParameterUserAccountIdentifierKey : "USERNAME"]) case 10: eventService.trackEvent(kALEventTypeUserExecutedSearch, parameters: [kALEventParameterSearchQueryKey : "USER'S SEARCH STRING"]) case 11: eventService.trackEvent(kALEventTypeUserSentInvitation) case 12: eventService.trackEvent(kALEventTypeUserSharedLink) case 13: eventService.trackEvent(kALEventTypeUserSpentVirtualCurrency, parameters: [kALEventParameterVirtualCurrencyAmountKey : "NUMBER OF COINS SPENT", kALEventParameterVirtualCurrencyNameKey : "CURRENCY NAME"]) case 14: eventService.trackEvent(kALEventTypeUserCompletedTutorial) case 15: eventService.trackEvent(kALEventTypeUserViewedContent, parameters: [kALEventParameterContentIdentifierKey : "SOME ID DESCRIBING CONTENT"]) case 16: eventService.trackEvent(kALEventTypeUserViewedProduct, parameters: [kALEventParameterProductIdentifierKey : "PRODUCT SKU OR ID"]) case 17: eventService.trackEvent(kALEventTypeUserAddedItemToWishlist, parameters: [kALEventParameterProductIdentifierKey : "PRODUCT SKU OR ID"]) default: title = "Default event tracking initiated" } } }
mit
fa231c9e02958da4ff20446a6953f983
58.029197
154
0.596513
6.428458
false
false
false
false
omaralbeik/SwifterSwift
Tests/FoundationTests/FileManagerExtensionsTests.swift
1
3674
// // FileManagerExtensionsTests.swift // SwifterSwift // // Created by Jason Jon E. Carreos on 05/02/2018. // Copyright © 2018 SwifterSwift // import XCTest @testable import SwifterSwift #if canImport(Foundation) import Foundation final class FileManagerExtensionsTests: XCTestCase { func testJSONFromFileAtPath() { do { let bundle = Bundle(for: FileManagerExtensionsTests.self) let filePath = bundle.path(forResource: "test", ofType: "json") guard let path = filePath else { XCTFail("File path undefined.") return } let json = try FileManager.default.jsonFromFile(atPath: path) XCTAssertNotNil(json) // Check contents if let dict = json { if let string = dict["title"] as? String, let itemId = dict["id"] as? Int { XCTAssert(string == "Test") XCTAssert(itemId == 1) } else { XCTFail("Does not contain the correct content.") } } else { XCTFail("Opening of file returned nil.") } } catch { XCTFail("Error encountered during opening of file. \(error.localizedDescription)") } } func testJSONFromFileWithFilename() { do { var filename = "test.json" // With extension var json = try FileManager.default.jsonFromFile(withFilename: filename, at: FileManagerExtensionsTests.self) XCTAssertNotNil(json) filename = "test" // Without extension json = try FileManager.default.jsonFromFile(withFilename: filename, at: FileManagerExtensionsTests.self) XCTAssertNotNil(json) // Check contents if let dict = json { if let string = dict["title"] as? String, let itemId = dict["id"] as? Int { XCTAssert(string == "Test") XCTAssert(itemId == 1) } else { XCTFail("Does not contain the correct content.") } } else { XCTFail("Opening of file returned nil.") } } catch { XCTFail("Error encountered during opening of file. \(error.localizedDescription)") } } func testInvalidFile() { let filename = "another_test.not_json" do { let json = try FileManager.default.jsonFromFile(withFilename: filename, at: FileManagerExtensionsTests.self) XCTAssertNil(json) } catch {} } func testCreateTemporaryDirectory() { do { let fileManager = FileManager.default let tempDirectory = try fileManager.createTemporaryDirectory() XCTAssertFalse(tempDirectory.path.isEmpty) var isDirectory = ObjCBool(false) XCTAssert(fileManager.fileExists(atPath: tempDirectory.path, isDirectory: &isDirectory)) XCTAssertTrue(isDirectory.boolValue) XCTAssert(try fileManager.contentsOfDirectory(atPath: tempDirectory.path).isEmpty) let tempFile = tempDirectory.appendingPathComponent(ProcessInfo().globallyUniqueString) XCTAssert(fileManager.createFile(atPath: tempFile.path, contents: Data(), attributes: nil)) XCTAssertFalse(try fileManager.contentsOfDirectory(atPath: tempDirectory.path).isEmpty) XCTAssertNotNil(fileManager.contents(atPath: tempFile.path)) try fileManager.removeItem(at: tempDirectory) } catch { XCTFail("\(error)") } } } #endif
mit
2d9aeeb38fd41a5ad89fcb68626ceea5
33.327103
120
0.589709
5.401471
false
true
false
false
AttilaTheFun/SwaggerParser
Sources/SchemaType.swift
1
4732
/// The discrete type defined by the schema. /// This can be a primitive type (string, float, integer, etc.) or a complex type like a dictionay or array. public enum SchemaType { /// A structure represents a named or aliased type. indirect case structure(Structure<Schema>) /// Defines an anonymous object type with a set of named properties. indirect case object(ObjectSchema) /// Defines an array of heterogenous (but possibly polymorphic) objects. indirect case array(ArraySchema) /// Defines an object with the combined requirements of several subschema. indirect case allOf(AllOfSchema) /// A string type with optional format information (e.g. base64 encoding). case string(StringFormat?) /// A floating point number type with optional format information (e.g. single vs double precision). case number(NumberFormat?) /// An integer type with an optional format (32 vs 64 bit). case integer(IntegerFormat?) /// An enumeration type with explicit acceptable values defined in the metadata. case enumeration /// A boolean type. case boolean /// A file type. case file /// An 'any' type which matches any value. case any /// A void data type. (Void in Swift, None in Python) case null } enum SchemaTypeBuilder: Codable { indirect case pointer(Pointer<SchemaBuilder>) indirect case object(ObjectSchemaBuilder) indirect case array(ArraySchemaBuilder) indirect case allOf(AllOfSchemaBuilder) case string(StringFormat?) case number(NumberFormat?) case integer(IntegerFormat?) case enumeration case boolean case file case any case null enum CodingKeys: String, CodingKey { case format } init(from decoder: Decoder) throws { let dataType = try DataType(from: decoder) let values = try decoder.container(keyedBy: CodingKeys.self) switch dataType { case .pointer: self = .pointer(try Pointer<SchemaBuilder>(from: decoder)) case .object: self = .object(try ObjectSchemaBuilder(from: decoder)) case .array: self = .array(try ArraySchemaBuilder(from: decoder)) case .allOf: self = .allOf(try AllOfSchemaBuilder(from: decoder)) case .string: self = .string(try values.decodeIfPresent(StringFormat.self, forKey: .format)) case .number: self = .number(try values.decodeIfPresent(NumberFormat.self, forKey: .format)) case .integer: self = .integer(try values.decodeIfPresent(IntegerFormat.self, forKey: .format)) case .enumeration: self = .enumeration case .boolean: self = .boolean case .file: self = .file case .any: self = .any case .null: self = .null } } func encode(to encoder: Encoder) throws { switch self { case .pointer(let pointer): try pointer.encode(to: encoder) case .object(let object): try object.encode(to: encoder) case .array(let array): try array.encode(to: encoder) case .allOf(let allOf): try allOf.encode(to: encoder) case .string(let format): try format.encode(to: encoder) case .number(let format): try format.encode(to: encoder) case .integer(let format): try format.encode(to: encoder) case .enumeration, .boolean, .file, .any, .null: // Will be encoded by Schema -> Metadata -> DataType break } } } extension SchemaTypeBuilder: Builder { typealias Building = SchemaType func build(_ swagger: SwaggerBuilder) throws -> SchemaType { switch self { case .pointer(let pointer): let structure = try SchemaBuilder.resolver.resolve(swagger, pointer: pointer) return .structure(structure) case .object(let builder): return .object(try builder.build(swagger)) case .array(let builder): return .array(try builder.build(swagger)) case .allOf(let builder): return .allOf(try builder.build(swagger)) case .string(let format): return .string(format) case .number(let format): return .number(format) case .integer(let format): return .integer(format) case .enumeration: return .enumeration case .boolean: return .boolean case .file: return .file case .any: return .any case .null: return .null } } }
mit
fc993c466e52e27bb21d19f85c20612a
31.190476
108
0.614328
4.717846
false
false
false
false
peferron/algo
EPI/Binary Trees/Implement ab inorder traversal with O(1) space/swift/main.swift
1
1273
// swiftlint:disable conditional_binding_cascade public class Node<T> { public let value: T public let left: Node? public let right: Node? public var parent: Node? = nil public init(value: T, left: Node? = nil, right: Node? = nil) { self.value = value self.left = left self.right = right left?.parent = self right?.parent = self } public func inorder() -> [T] { var values = [T]() var current: Node? = self var previous: Node? = nil while let c = current { if let p = previous, let l = c.left, p === l { // Coming back up from the left child. values.append(c.value) current = c.right ?? c.parent } else if let p = previous, let r = c.right, p === r { // Coming back up from the right child. current = c.parent } else { // Coming down from the parent. if let l = c.left { current = l } else { values.append(c.value) current = c.right ?? c.parent } } previous = c } return values } }
mit
9c298b81a8260ea4843bfb67636cc39b
27.288889
66
0.463472
4.34471
false
false
false
false
ginppian/fif2016
ACTabScrollView/ContentViewController.swift
1
3953
// // ContentViewController.swift // ACTabScrollView // // Created by Azure Chen on 5/19/16. // Copyright © 2016 AzureChen. All rights reserved. // import UIKit class ContentViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { @IBOutlet weak var tableView: UITableView! var eventoFif = EventoFIF() var category: NewsCategory? { didSet { for news in MockData.newsArray { if (news.category == category) { newsArray.append(news) } } } } var newsArray: [News] = [] override func viewDidLoad() { super.viewDidLoad() tableView.rowHeight = UITableViewAutomaticDimension tableView.estimatedRowHeight = 44 tableView.delegate = self tableView.dataSource = self } func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return newsArray.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let news = newsArray[(indexPath as NSIndexPath).row] // set the cell let cell = tableView.dequeueReusableCell(withIdentifier: "Cell") as! ContentTableViewCell // cell.thumbnailImageView.image = UIImage(named: "thumbnail-\(news.id)") // cell.thumbnailImageView.layer.cornerRadius = 4 // cell.titleLabel.text = news.title // cell.categoryLabel.text = String(describing: news.category) // cell.categoryView.layer.backgroundColor = UIColor.white.cgColor // cell.categoryView.layer.cornerRadius = 4 // cell.categoryView.layer.borderWidth = 1 // cell.categoryView.layer.borderColor = UIColor(red: 32.0 / 255, green: 188.0 / 255, blue: 239.0 / 255, alpha: 1.0).cgColor cell.labelHour.text = news.horaIni cell.labelEvento.text = news.evento cell.labelPonente.text = news.ponente cell.tag = news.id cell.accessoryType = UITableViewCellAccessoryType.disclosureIndicator return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let new = newsArray[indexPath.row] self.eventoFif.id = new.id self.eventoFif.fecha = new.fecha self.eventoFif.horaIni = new.horaIni self.eventoFif.horaFin = new.horaFin self.eventoFif.sede = new.sede self.eventoFif.direccion = new.direccion self.eventoFif.evento = new.evento self.eventoFif.ponente = new.ponente self.eventoFif.pais = new.pais self.eventoFif.descripcion = new.descripcion performSegue(withIdentifier: "detailContentIdentifier", sender: self) } func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 3 } func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let view = UIView() // view.frame = CGRect(x: 0.0, y: 0.0, width: view.frame.width, height: view.frame.height*2.0) view.backgroundColor = UIColor(red: 31.0 / 255, green: 180.0 / 255, blue: 228.0 / 255, alpha: 1.0) return view } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if (segue.identifier) == "detailContentIdentifier" { let vc = segue.destination as! DetailContentViewController vc.eventoFif = self.eventoFif } } } class ContentTableViewCell: UITableViewCell { @IBOutlet weak var labelHour: UILabel! @IBOutlet weak var labelEvento: UILabel! @IBOutlet weak var labelPonente: UILabel! override func awakeFromNib() { self.selectionStyle = .none } }
mit
27a1678d9d970410f7f56b135372a219
32.491525
131
0.634868
4.649412
false
false
false
false
agrippa1994/iOS-PLC
Pods/Charts/Charts/Classes/Renderers/ChartLegendRenderer.swift
5
14927
// // ChartLegendRenderer.swift // Charts // // Created by Daniel Cohen Gindi on 4/3/15. // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/ios-charts // import Foundation import CoreGraphics import UIKit public class ChartLegendRenderer: ChartRendererBase { /// the legend object this renderer renders internal var _legend: ChartLegend! public init(viewPortHandler: ChartViewPortHandler, legend: ChartLegend?) { super.init(viewPortHandler: viewPortHandler) _legend = legend } /// Prepares the legend and calculates all needed forms, labels and colors. public func computeLegend(data: ChartData) { if (!_legend.isLegendCustom) { var labels = [String?]() var colors = [UIColor?]() // loop for building up the colors and labels used in the legend for (var i = 0, count = data.dataSetCount; i < count; i++) { let dataSet = data.getDataSetByIndex(i)! var clrs: [UIColor] = dataSet.colors let entryCount = dataSet.entryCount // if we have a barchart with stacked bars if (dataSet.isKindOfClass(BarChartDataSet) && (dataSet as! BarChartDataSet).isStacked) { let bds = dataSet as! BarChartDataSet var sLabels = bds.stackLabels for (var j = 0; j < clrs.count && j < bds.stackSize; j++) { labels.append(sLabels[j % sLabels.count]) colors.append(clrs[j]) } if (bds.label != nil) { // add the legend description label colors.append(nil) labels.append(bds.label) } } else if (dataSet.isKindOfClass(PieChartDataSet)) { var xVals = data.xVals let pds = dataSet as! PieChartDataSet for (var j = 0; j < clrs.count && j < entryCount && j < xVals.count; j++) { labels.append(xVals[j]) colors.append(clrs[j]) } if (pds.label != nil) { // add the legend description label colors.append(nil) labels.append(pds.label) } } else { // all others for (var j = 0; j < clrs.count && j < entryCount; j++) { // if multiple colors are set for a DataSet, group them if (j < clrs.count - 1 && j < entryCount - 1) { labels.append(nil) } else { // add label to the last entry labels.append(dataSet.label) } colors.append(clrs[j]) } } } _legend.colors = colors + _legend._extraColors _legend.labels = labels + _legend._extraLabels } // calculate all dimensions of the legend _legend.calculateDimensions(labelFont: _legend.font, viewPortHandler: viewPortHandler) } public func renderLegend(context context: CGContext?) { if (_legend === nil || !_legend.enabled) { return } let labelFont = _legend.font let labelTextColor = _legend.textColor let labelLineHeight = labelFont.lineHeight let formYOffset = labelLineHeight / 2.0 var labels = _legend.labels var colors = _legend.colors let formSize = _legend.formSize let formToTextSpace = _legend.formToTextSpace let xEntrySpace = _legend.xEntrySpace let direction = _legend.direction // space between the entries let stackSpace = _legend.stackSpace let yoffset = _legend.yOffset let xoffset = _legend.xOffset let legendPosition = _legend.position switch (legendPosition) { case .BelowChartLeft: fallthrough case .BelowChartRight: fallthrough case .BelowChartCenter: let contentWidth: CGFloat = viewPortHandler.contentWidth var originPosX: CGFloat if (legendPosition == .BelowChartLeft) { originPosX = viewPortHandler.contentLeft + xoffset if (direction == .RightToLeft) { originPosX += _legend.neededWidth } } else if (legendPosition == .BelowChartRight) { originPosX = viewPortHandler.contentRight - xoffset if (direction == .LeftToRight) { originPosX -= _legend.neededWidth } } else // if (legendPosition == .BelowChartCenter) { originPosX = viewPortHandler.contentLeft + contentWidth / 2.0 } var calculatedLineSizes = _legend.calculatedLineSizes var calculatedLabelSizes = _legend.calculatedLabelSizes var calculatedLabelBreakPoints = _legend.calculatedLabelBreakPoints var posX: CGFloat = originPosX var posY: CGFloat = viewPortHandler.chartHeight - yoffset - _legend.neededHeight var lineIndex: Int = 0 for (var i = 0, count = labels.count; i < count; i++) { if (calculatedLabelBreakPoints[i]) { posX = originPosX posY += labelLineHeight } if (posX == originPosX && legendPosition == .BelowChartCenter) { posX += (direction == .RightToLeft ? calculatedLineSizes[lineIndex].width : -calculatedLineSizes[lineIndex].width) / 2.0 lineIndex++ } let drawingForm = colors[i] != nil let isStacked = labels[i] == nil; // grouped forms have null labels if (drawingForm) { if (direction == .RightToLeft) { posX -= formSize } drawForm(context, x: posX, y: posY + formYOffset, colorIndex: i, legend: _legend) if (direction == .LeftToRight) { posX += formSize } } if (!isStacked) { if (drawingForm) { posX += direction == .RightToLeft ? -formToTextSpace : formToTextSpace } if (direction == .RightToLeft) { posX -= calculatedLabelSizes[i].width } drawLabel(context, x: posX, y: posY, label: labels[i]!, font: labelFont, textColor: labelTextColor) if (direction == .LeftToRight) { posX += calculatedLabelSizes[i].width } posX += direction == .RightToLeft ? -xEntrySpace : xEntrySpace } else { posX += direction == .RightToLeft ? -stackSpace : stackSpace } } break case .PiechartCenter: fallthrough case .RightOfChart: fallthrough case .RightOfChartCenter: fallthrough case .RightOfChartInside: fallthrough case .LeftOfChart: fallthrough case .LeftOfChartCenter: fallthrough case .LeftOfChartInside: // contains the stacked legend size in pixels var stack = CGFloat(0.0) var wasStacked = false var posX: CGFloat = 0.0, posY: CGFloat = 0.0 if (legendPosition == .PiechartCenter) { posX = viewPortHandler.chartWidth / 2.0 + (direction == .LeftToRight ? -_legend.textWidthMax / 2.0 : _legend.textWidthMax / 2.0) posY = viewPortHandler.chartHeight / 2.0 - _legend.neededHeight / 2.0 + _legend.yOffset } else { let isRightAligned = legendPosition == .RightOfChart || legendPosition == .RightOfChartCenter || legendPosition == .RightOfChartInside if (isRightAligned) { posX = viewPortHandler.chartWidth - xoffset if (direction == .LeftToRight) { posX -= _legend.textWidthMax } } else { posX = xoffset if (direction == .RightToLeft) { posX += _legend.textWidthMax } } if (legendPosition == .RightOfChart || legendPosition == .LeftOfChart) { posY = viewPortHandler.contentTop + yoffset } else if (legendPosition == .RightOfChartCenter || legendPosition == .LeftOfChartCenter) { posY = viewPortHandler.chartHeight / 2.0 - _legend.neededHeight / 2.0 } else /*if (legend.position == .RightOfChartInside || legend.position == .LeftOfChartInside)*/ { posY = viewPortHandler.contentTop + yoffset } } for (var i = 0; i < labels.count; i++) { let drawingForm = colors[i] != nil var x = posX if (drawingForm) { if (direction == .LeftToRight) { x += stack } else { x -= formSize - stack } drawForm(context, x: x, y: posY + formYOffset, colorIndex: i, legend: _legend) if (direction == .LeftToRight) { x += formSize } } if (labels[i] != nil) { if (drawingForm && !wasStacked) { x += direction == .LeftToRight ? formToTextSpace : -formToTextSpace } else if (wasStacked) { x = posX } if (direction == .RightToLeft) { x -= (labels[i] as NSString!).sizeWithAttributes([NSFontAttributeName: labelFont]).width } if (!wasStacked) { drawLabel(context, x: x, y: posY, label: labels[i]!, font: labelFont, textColor: labelTextColor) } else { posY += labelLineHeight drawLabel(context, x: x, y: posY, label: labels[i]!, font: labelFont, textColor: labelTextColor) } // make a step down posY += labelLineHeight stack = 0.0 } else { stack += formSize + stackSpace wasStacked = true } } break } } private var _formLineSegmentsBuffer = [CGPoint](count: 2, repeatedValue: CGPoint()) /// Draws the Legend-form at the given position with the color at the given index. internal func drawForm(context: CGContext?, x: CGFloat, y: CGFloat, colorIndex: Int, legend: ChartLegend) { let formColor = legend.colors[colorIndex] if (formColor === nil || formColor == UIColor.clearColor()) { return } let formsize = legend.formSize CGContextSaveGState(context) switch (legend.form) { case .Circle: CGContextSetFillColorWithColor(context, formColor!.CGColor) CGContextFillEllipseInRect(context, CGRect(x: x, y: y - formsize / 2.0, width: formsize, height: formsize)) break case .Square: CGContextSetFillColorWithColor(context, formColor!.CGColor) CGContextFillRect(context, CGRect(x: x, y: y - formsize / 2.0, width: formsize, height: formsize)) break case .Line: CGContextSetLineWidth(context, legend.formLineWidth) CGContextSetStrokeColorWithColor(context, formColor!.CGColor) _formLineSegmentsBuffer[0].x = x _formLineSegmentsBuffer[0].y = y _formLineSegmentsBuffer[1].x = x + formsize _formLineSegmentsBuffer[1].y = y CGContextStrokeLineSegments(context, _formLineSegmentsBuffer, 2) break } CGContextRestoreGState(context) } /// Draws the provided label at the given position. internal func drawLabel(context: CGContext?, x: CGFloat, y: CGFloat, label: String, font: UIFont, textColor: UIColor) { ChartUtils.drawText(context: context, text: label, point: CGPoint(x: x, y: y), align: .Left, attributes: [NSFontAttributeName: font, NSForegroundColorAttributeName: textColor]) } }
mit
12782eefdefd8c1974caca0b1069f00b
35.23301
184
0.449722
6.354619
false
false
false
false
bitjammer/swift
test/sil-func-extractor/load-serialized-sil.swift
1
1799
// RUN: %target-swift-frontend -primary-file %s -module-name Swift -g -sil-serialize-all -module-link-name swiftCore -O -parse-as-library -parse-stdlib -emit-module -emit-module-path - -o /dev/null | %target-sil-func-extractor -module-name="Swift" -func="_T0s1XV4testyyF" | %FileCheck %s // RUN: %target-swift-frontend -primary-file %s -module-name Swift -g -O -parse-as-library -parse-stdlib -emit-sib -o - | %target-sil-func-extractor -module-name="Swift" -func="_T0s1XV4testyyF" | %FileCheck %s -check-prefix=SIB-CHECK // CHECK: import Builtin // CHECK: import Swift // CHECK: func unknown() // CHECK: struct X { // CHECK-NEXT: func test() // CHECK-NEXT: init // CHECK-NEXT: } // CHECK: sil @unknown : $@convention(thin) () -> () // CHECK-LABEL: sil hidden [fragile] @_T0s1XV4testyyF : $@convention(method) (X) -> () // CHECK: bb0 // CHECK-NEXT: function_ref // CHECK-NEXT: function_ref @unknown : $@convention(thin) () -> () // CHECK-NEXT: apply // CHECK-NEXT: tuple // CHECK-NEXT: return // CHECK-NOT: sil {{.*}} @_T0s1XVABycfC : $@convention(thin) (@thin X.Type) -> X // SIB-CHECK: import Builtin // SIB-CHECK: import Swift // SIB-CHECK: func unknown() // SIB-CHECK: struct X { // SIB-CHECK-NEXT: func test() // SIB-CHECK-NEXT: init // SIB-CHECK-NEXT: } // SIB-CHECK: sil @unknown : $@convention(thin) () -> () // SIB-CHECK-LABEL: sil hidden @_T0s1XV4testyyF : $@convention(method) (X) -> () // SIB-CHECK: bb0 // SIB-CHECK-NEXT: function_ref // SIB-CHECK-NEXT: function_ref @unknown : $@convention(thin) () -> () // SIB-CHECK-NEXT: apply // SIB-CHECK-NEXT: tuple // SIB-CHECK-NEXT: return // SIB-CHECK-NOT: sil {{.*}} @_T0s1XVABycfC : $@convention(thin) (@thin X.Type) -> X @_silgen_name("unknown") public func unknown() -> () struct X { func test() { unknown() } }
apache-2.0
f83d15b4f7987efd9a131fff1cc55a0e
31.125
287
0.64925
2.9063
false
true
false
false
tiagomartinho/webhose-cocoa
webhose-cocoa/Pods/Quick/Sources/Quick/Example.swift
45
3588
import Foundation private var numberOfExamplesRun = 0 /** Examples, defined with the `it` function, use assertions to demonstrate how code should behave. These are like "tests" in XCTest. */ final public class Example: NSObject { /** A boolean indicating whether the example is a shared example; i.e.: whether it is an example defined with `itBehavesLike`. */ public var isSharedExample = false /** The site at which the example is defined. This must be set correctly in order for Xcode to highlight the correct line in red when reporting a failure. */ public var callsite: Callsite weak internal var group: ExampleGroup? private let internalDescription: String private let closure: () -> Void private let flags: FilterFlags internal init(description: String, callsite: Callsite, flags: FilterFlags, closure: @escaping () -> Void) { self.internalDescription = description self.closure = closure self.callsite = callsite self.flags = flags } public override var description: String { return internalDescription } /** The example name. A name is a concatenation of the name of the example group the example belongs to, followed by the description of the example itself. The example name is used to generate a test method selector to be displayed in Xcode's test navigator. */ public var name: String { guard let groupName = group?.name else { return description } return "\(groupName), \(description)" } /** Executes the example closure, as well as all before and after closures defined in the its surrounding example groups. */ public func run() { let world = World.sharedWorld if numberOfExamplesRun == 0 { world.suiteHooks.executeBefores() } let exampleMetadata = ExampleMetadata(example: self, exampleIndex: numberOfExamplesRun) world.currentExampleMetadata = exampleMetadata world.exampleHooks.executeBefores(exampleMetadata) group!.phase = .beforesExecuting for before in group!.befores { before(exampleMetadata) } group!.phase = .beforesFinished closure() group!.phase = .aftersExecuting for after in group!.afters { after(exampleMetadata) } group!.phase = .aftersFinished world.exampleHooks.executeAfters(exampleMetadata) numberOfExamplesRun += 1 if !world.isRunningAdditionalSuites && numberOfExamplesRun >= world.includedExampleCount { world.suiteHooks.executeAfters() } } /** Evaluates the filter flags set on this example and on the example groups this example belongs to. Flags set on the example are trumped by flags on the example group it belongs to. Flags on inner example groups are trumped by flags on outer example groups. */ internal var filterFlags: FilterFlags { var aggregateFlags = flags for (key, value) in group!.filterFlags { aggregateFlags[key] = value } return aggregateFlags } } extension Example { /** Returns a boolean indicating whether two Example objects are equal. If two examples are defined at the exact same callsite, they must be equal. */ @nonobjc public static func == (lhs: Example, rhs: Example) -> Bool { return lhs.callsite == rhs.callsite } }
mit
ce14886c0436aff6f61b4f1de14c2925
30.752212
111
0.651338
5.082153
false
false
false
false
bitjammer/swift
test/SILGen/cf.swift
1
4984
// RUN: %target-swift-frontend -import-cf-types -sdk %S/Inputs %s -emit-silgen -o - | %FileCheck %s // REQUIRES: objc_interop import CoreCooling // CHECK: sil hidden @_T02cf8useEmAllySo16CCMagnetismModelCF : // CHECK: bb0([[ARG:%.*]] : $CCMagnetismModel): func useEmAll(_ model: CCMagnetismModel) { // CHECK: function_ref @CCPowerSupplyGetDefault : $@convention(c) () -> @autoreleased Optional<CCPowerSupply> let power = CCPowerSupplyGetDefault() // CHECK: function_ref @CCRefrigeratorCreate : $@convention(c) (Optional<CCPowerSupply>) -> Optional<Unmanaged<CCRefrigerator>> let unmanagedFridge = CCRefrigeratorCreate(power) // CHECK: function_ref @CCRefrigeratorSpawn : $@convention(c) (Optional<CCPowerSupply>) -> @owned Optional<CCRefrigerator> let managedFridge = CCRefrigeratorSpawn(power) // CHECK: function_ref @CCRefrigeratorOpen : $@convention(c) (Optional<CCRefrigerator>) -> () CCRefrigeratorOpen(managedFridge) // CHECK: function_ref @CCRefrigeratorCopy : $@convention(c) (Optional<CCRefrigerator>) -> @owned Optional<CCRefrigerator> let copy = CCRefrigeratorCopy(managedFridge) // CHECK: function_ref @CCRefrigeratorClone : $@convention(c) (Optional<CCRefrigerator>) -> @autoreleased Optional<CCRefrigerator> let clone = CCRefrigeratorClone(managedFridge) // CHECK: function_ref @CCRefrigeratorDestroy : $@convention(c) (@owned Optional<CCRefrigerator>) -> () CCRefrigeratorDestroy(clone) // CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]] // CHECK: class_method [volatile] [[BORROWED_ARG]] : $CCMagnetismModel, #CCMagnetismModel.refrigerator!1.foreign : (CCMagnetismModel) -> () -> Unmanaged<CCRefrigerator>!, $@convention(objc_method) (CCMagnetismModel) -> Optional<Unmanaged<CCRefrigerator>> let f0 = model.refrigerator() // CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]] // CHECK: class_method [volatile] [[BORROWED_ARG]] : $CCMagnetismModel, #CCMagnetismModel.getRefrigerator!1.foreign : (CCMagnetismModel) -> () -> CCRefrigerator!, $@convention(objc_method) (CCMagnetismModel) -> @autoreleased Optional<CCRefrigerator> let f1 = model.getRefrigerator() // CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]] // CHECK: class_method [volatile] [[BORROWED_ARG]] : $CCMagnetismModel, #CCMagnetismModel.takeRefrigerator!1.foreign : (CCMagnetismModel) -> () -> CCRefrigerator!, $@convention(objc_method) (CCMagnetismModel) -> @owned Optional<CCRefrigerator> let f2 = model.takeRefrigerator() // CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]] // CHECK: class_method [volatile] [[BORROWED_ARG]] : $CCMagnetismModel, #CCMagnetismModel.borrowRefrigerator!1.foreign : (CCMagnetismModel) -> () -> CCRefrigerator!, $@convention(objc_method) (CCMagnetismModel) -> @autoreleased Optional<CCRefrigerator> let f3 = model.borrowRefrigerator() // CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]] // CHECK: class_method [volatile] [[BORROWED_ARG]] : $CCMagnetismModel, #CCMagnetismModel.setRefrigerator!1.foreign : (CCMagnetismModel) -> (CCRefrigerator!) -> (), $@convention(objc_method) (Optional<CCRefrigerator>, CCMagnetismModel) -> () model.setRefrigerator(copy) // CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]] // CHECK: class_method [volatile] [[BORROWED_ARG]] : $CCMagnetismModel, #CCMagnetismModel.giveRefrigerator!1.foreign : (CCMagnetismModel) -> (CCRefrigerator!) -> (), $@convention(objc_method) (@owned Optional<CCRefrigerator>, CCMagnetismModel) -> () model.giveRefrigerator(copy) // rdar://16846555 let prop: CCRefrigerator = model.fridgeProp } // Ensure that accessors are emitted for fields used as protocol witnesses. protocol Impedance { associatedtype Component var real: Component { get } var imag: Component { get } } extension CCImpedance: Impedance {} // CHECK-LABEL: sil hidden [transparent] [fragile] [thunk] @_T0SC11CCImpedanceV2cf9ImpedanceA2cDP4real9ComponentQzfgTW // CHECK-LABEL: sil shared [transparent] [fragile] @_T0SC11CCImpedanceV4realSdfg // CHECK-LABEL: sil hidden [transparent] [fragile] [thunk] @_T0SC11CCImpedanceV2cf9ImpedanceA2cDP4imag9ComponentQzfgTW // CHECK-LABEL: sil shared [transparent] [fragile] @_T0SC11CCImpedanceV4imagSdfg class MyMagnetism : CCMagnetismModel { // CHECK-LABEL: sil hidden [thunk] @_T02cf11MyMagnetismC15getRefrigerator{{[_0-9a-zA-Z]*}}FTo : $@convention(objc_method) (MyMagnetism) -> @autoreleased CCRefrigerator override func getRefrigerator() -> CCRefrigerator { return super.getRefrigerator() } // CHECK-LABEL: sil hidden [thunk] @_T02cf11MyMagnetismC16takeRefrigerator{{[_0-9a-zA-Z]*}}FTo : $@convention(objc_method) (MyMagnetism) -> @owned CCRefrigerator override func takeRefrigerator() -> CCRefrigerator { return super.takeRefrigerator() } // CHECK-LABEL: sil hidden [thunk] @_T02cf11MyMagnetismC18borrowRefrigerator{{[_0-9a-zA-Z]*}}FTo : $@convention(objc_method) (MyMagnetism) -> @autoreleased CCRefrigerator override func borrowRefrigerator() -> CCRefrigerator { return super.borrowRefrigerator() } }
apache-2.0
bb7c07461e4a16355f4cfa18c243e75a
55.636364
254
0.739767
4.016116
false
false
false
false
gregomni/swift
utils/parser-lib/profile-input.swift
9
108227
/* 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 Photos import UIKit import WebKit import Shared import Storage import SnapKit import XCGLogger import Alamofire import Account import MobileCoreServices import SDWebImage import SwiftyJSON import Telemetry import Sentry import Deferred private let KVOs: [KVOConstants] = [ .estimatedProgress, .loading, .canGoBack, .canGoForward, .URL, .title, ] private let ActionSheetTitleMaxLength = 120 private struct BrowserViewControllerUX { fileprivate static let ShowHeaderTapAreaHeight: CGFloat = 32 fileprivate static let BookmarkStarAnimationDuration: Double = 0.5 fileprivate static let BookmarkStarAnimationOffset: CGFloat = 80 } class BrowserViewController: UIViewController { var homePanelController: (UIViewController & Themeable)? var libraryPanelController: HomePanelViewController? var webViewContainer: UIView! var urlBar: URLBarView! var clipboardBarDisplayHandler: ClipboardBarDisplayHandler? var readerModeBar: ReaderModeBarView? var readerModeCache: ReaderModeCache var statusBarOverlay: UIView! fileprivate(set) var toolbar: TabToolbar? var searchController: SearchViewController? var screenshotHelper: ScreenshotHelper! fileprivate var homePanelIsInline = false fileprivate var searchLoader: SearchLoader? let alertStackView = UIStackView() // All content that appears above the footer should be added to this view. (Find In Page/SnackBars) var findInPageBar: FindInPageBar? lazy var mailtoLinkHandler: MailtoLinkHandler = MailtoLinkHandler() lazy fileprivate var customSearchEngineButton: UIButton = { let searchButton = UIButton() searchButton.setImage(UIImage(named: "AddSearch")?.withRenderingMode(.alwaysTemplate), for: []) searchButton.addTarget(self, action: #selector(addCustomSearchEngineForFocusedElement), for: .touchUpInside) searchButton.accessibilityIdentifier = "BrowserViewController.customSearchEngineButton" return searchButton }() fileprivate var customSearchBarButton: UIBarButtonItem? // popover rotation handling var displayedPopoverController: UIViewController? var updateDisplayedPopoverProperties: (() -> Void)? var openInHelper: OpenInHelper? // location label actions fileprivate var pasteGoAction: AccessibleAction! fileprivate var pasteAction: AccessibleAction! fileprivate var copyAddressAction: AccessibleAction! fileprivate weak var tabTrayController: TabTrayController? let profile: Profile let tabManager: TabManager // These views wrap the urlbar and toolbar to provide background effects on them var header: UIView! var footer: UIView! fileprivate var topTouchArea: UIButton! let urlBarTopTabsContainer = UIView(frame: CGRect.zero) var topTabsVisible: Bool { return topTabsViewController != nil } // Backdrop used for displaying greyed background for private tabs var webViewContainerBackdrop: UIView! var scrollController = TabScrollingController() fileprivate var keyboardState: KeyboardState? var pendingToast: Toast? // A toast that might be waiting for BVC to appear before displaying var downloadToast: DownloadToast? // A toast that is showing the combined download progress // Tracking navigation items to record history types. // TODO: weak references? var ignoredNavigation = Set<WKNavigation>() var typedNavigation = [WKNavigation: VisitType]() var navigationToolbar: TabToolbarProtocol { return toolbar ?? urlBar } var topTabsViewController: TopTabsViewController? let topTabsContainer = UIView() // Keep track of allowed `URLRequest`s from `webView(_:decidePolicyFor:decisionHandler:)` so // that we can obtain the originating `URLRequest` when a `URLResponse` is received. This will // allow us to re-trigger the `URLRequest` if the user requests a file to be downloaded. var pendingRequests = [String: URLRequest]() // This is set when the user taps "Download Link" from the context menu. We then force a // download of the next request through the `WKNavigationDelegate` that matches this web view. weak var pendingDownloadWebView: WKWebView? let downloadQueue = DownloadQueue() init(profile: Profile, tabManager: TabManager) { self.profile = profile self.tabManager = tabManager self.readerModeCache = DiskReaderModeCache.sharedInstance super.init(nibName: nil, bundle: nil) didInit() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override var supportedInterfaceOrientations: UIInterfaceOrientationMask { if UIDevice.current.userInterfaceIdiom == .phone { return .allButUpsideDown } else { return .all } } override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { super.viewWillTransition(to: size, with: coordinator) dismissVisibleMenus() coordinator.animate(alongsideTransition: { context in self.scrollController.updateMinimumZoom() self.topTabsViewController?.scrollToCurrentTab(false, centerCell: false) if let popover = self.displayedPopoverController { self.updateDisplayedPopoverProperties?() self.present(popover, animated: true, completion: nil) } }, completion: { _ in self.scrollController.setMinimumZoom() }) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } fileprivate func didInit() { screenshotHelper = ScreenshotHelper(controller: self) tabManager.addDelegate(self) tabManager.addNavigationDelegate(self) downloadQueue.delegate = self NotificationCenter.default.addObserver(self, selector: #selector(displayThemeChanged), name: .DisplayThemeChanged, object: nil) } override var preferredStatusBarStyle: UIStatusBarStyle { return ThemeManager.instance.statusBarStyle } @objc func displayThemeChanged(notification: Notification) { applyTheme() } func shouldShowFooterForTraitCollection(_ previousTraitCollection: UITraitCollection) -> Bool { return previousTraitCollection.verticalSizeClass != .compact && previousTraitCollection.horizontalSizeClass != .regular } func shouldShowTopTabsForTraitCollection(_ newTraitCollection: UITraitCollection) -> Bool { return newTraitCollection.verticalSizeClass == .regular && newTraitCollection.horizontalSizeClass == .regular } func toggleSnackBarVisibility(show: Bool) { if show { UIView.animate(withDuration: 0.1, animations: { self.alertStackView.isHidden = false }) } else { alertStackView.isHidden = true } } fileprivate func updateToolbarStateForTraitCollection(_ newCollection: UITraitCollection, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator? = nil) { let showToolbar = shouldShowFooterForTraitCollection(newCollection) let showTopTabs = shouldShowTopTabsForTraitCollection(newCollection) urlBar.topTabsIsShowing = showTopTabs urlBar.setShowToolbar(!showToolbar) toolbar?.removeFromSuperview() toolbar?.tabToolbarDelegate = nil toolbar = nil if showToolbar { toolbar = TabToolbar() footer.addSubview(toolbar!) toolbar?.tabToolbarDelegate = self toolbar?.applyUIMode(isPrivate: tabManager.selectedTab?.isPrivate ?? false) toolbar?.applyTheme() updateTabCountUsingTabManager(self.tabManager) } if showTopTabs { if topTabsViewController == nil { let topTabsViewController = TopTabsViewController(tabManager: tabManager) topTabsViewController.delegate = self addChildViewController(topTabsViewController) topTabsViewController.view.frame = topTabsContainer.frame topTabsContainer.addSubview(topTabsViewController.view) topTabsViewController.view.snp.makeConstraints { make in make.edges.equalTo(topTabsContainer) make.height.equalTo(TopTabsUX.TopTabsViewHeight) } self.topTabsViewController = topTabsViewController topTabsViewController.applyTheme() } topTabsContainer.snp.updateConstraints { make in make.height.equalTo(TopTabsUX.TopTabsViewHeight) } } else { topTabsContainer.snp.updateConstraints { make in make.height.equalTo(0) } topTabsViewController?.view.removeFromSuperview() topTabsViewController?.removeFromParentViewController() topTabsViewController = nil } view.setNeedsUpdateConstraints() if let home = homePanelController { home.view.setNeedsUpdateConstraints() } if let tab = tabManager.selectedTab, let webView = tab.webView { updateURLBarDisplayURL(tab) navigationToolbar.updateBackStatus(webView.canGoBack) navigationToolbar.updateForwardStatus(webView.canGoForward) navigationToolbar.updateReloadStatus(tab.loading) } } override func willTransition(to newCollection: UITraitCollection, with coordinator: UIViewControllerTransitionCoordinator) { super.willTransition(to: newCollection, with: coordinator) // During split screen launching on iPad, this callback gets fired before viewDidLoad gets a chance to // set things up. Make sure to only update the toolbar state if the view is ready for it. if isViewLoaded { updateToolbarStateForTraitCollection(newCollection, withTransitionCoordinator: coordinator) } displayedPopoverController?.dismiss(animated: true, completion: nil) coordinator.animate(alongsideTransition: { context in self.scrollController.showToolbars(animated: false) if self.isViewLoaded { self.statusBarOverlay.backgroundColor = self.shouldShowTopTabsForTraitCollection(self.traitCollection) ? UIColor.Photon.Grey80 : self.urlBar.backgroundColor self.setNeedsStatusBarAppearanceUpdate() } }, completion: nil) } func dismissVisibleMenus() { displayedPopoverController?.dismiss(animated: true) if let _ = self.presentedViewController as? PhotonActionSheet { self.presentedViewController?.dismiss(animated: true, completion: nil) } } @objc func appDidEnterBackgroundNotification() { displayedPopoverController?.dismiss(animated: false) { self.displayedPopoverController = nil } } @objc func tappedTopArea() { scrollController.showToolbars(animated: true) } @objc func appWillResignActiveNotification() { // Dismiss any popovers that might be visible displayedPopoverController?.dismiss(animated: false) { self.displayedPopoverController = nil } // If we are displying a private tab, hide any elements in the tab that we wouldn't want shown // when the app is in the home switcher guard let privateTab = tabManager.selectedTab, privateTab.isPrivate else { return } webViewContainerBackdrop.alpha = 1 webViewContainer.alpha = 0 urlBar.locationContainer.alpha = 0 topTabsViewController?.switchForegroundStatus(isInForeground: false) presentedViewController?.popoverPresentationController?.containerView?.alpha = 0 presentedViewController?.view.alpha = 0 } @objc func appDidBecomeActiveNotification() { // Re-show any components that might have been hidden because they were being displayed // as part of a private mode tab UIView.animate(withDuration: 0.2, delay: 0, options: UIViewAnimationOptions(), animations: { self.webViewContainer.alpha = 1 self.urlBar.locationContainer.alpha = 1 self.topTabsViewController?.switchForegroundStatus(isInForeground: true) self.presentedViewController?.popoverPresentationController?.containerView?.alpha = 1 self.presentedViewController?.view.alpha = 1 self.view.backgroundColor = UIColor.clear }, completion: { _ in self.webViewContainerBackdrop.alpha = 0 }) // Re-show toolbar which might have been hidden during scrolling (prior to app moving into the background) scrollController.showToolbars(animated: false) } override func viewDidLoad() { super.viewDidLoad() NotificationCenter.default.addObserver(self, selector: #selector(appWillResignActiveNotification), name: .UIApplicationWillResignActive, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(appDidBecomeActiveNotification), name: .UIApplicationDidBecomeActive, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(appDidEnterBackgroundNotification), name: .UIApplicationDidEnterBackground, object: nil) KeyboardHelper.defaultHelper.addDelegate(self) webViewContainerBackdrop = UIView() webViewContainerBackdrop.backgroundColor = UIColor.Photon.Grey50 webViewContainerBackdrop.alpha = 0 view.addSubview(webViewContainerBackdrop) webViewContainer = UIView() view.addSubview(webViewContainer) // Temporary work around for covering the non-clipped web view content statusBarOverlay = UIView() view.addSubview(statusBarOverlay) topTouchArea = UIButton() topTouchArea.isAccessibilityElement = false topTouchArea.addTarget(self, action: #selector(tappedTopArea), for: .touchUpInside) view.addSubview(topTouchArea) // Setup the URL bar, wrapped in a view to get transparency effect urlBar = URLBarView() urlBar.translatesAutoresizingMaskIntoConstraints = false urlBar.delegate = self urlBar.tabToolbarDelegate = self header = urlBarTopTabsContainer urlBarTopTabsContainer.addSubview(urlBar) urlBarTopTabsContainer.addSubview(topTabsContainer) view.addSubview(header) // UIAccessibilityCustomAction subclass holding an AccessibleAction instance does not work, thus unable to generate AccessibleActions and UIAccessibilityCustomActions "on-demand" and need to make them "persistent" e.g. by being stored in BVC pasteGoAction = AccessibleAction(name: Strings.PasteAndGoTitle, handler: { () -> Bool in if let pasteboardContents = UIPasteboard.general.string { self.urlBar(self.urlBar, didSubmitText: pasteboardContents) return true } return false }) pasteAction = AccessibleAction(name: Strings.PasteTitle, handler: { () -> Bool in if let pasteboardContents = UIPasteboard.general.string { // Enter overlay mode and make the search controller appear. self.urlBar.enterOverlayMode(pasteboardContents, pasted: true, search: true) return true } return false }) copyAddressAction = AccessibleAction(name: Strings.CopyAddressTitle, handler: { () -> Bool in if let url = self.tabManager.selectedTab?.canonicalURL?.displayURL ?? self.urlBar.currentURL { UIPasteboard.general.url = url } return true }) view.addSubview(alertStackView) footer = UIView() view.addSubview(footer) alertStackView.axis = .vertical alertStackView.alignment = .center clipboardBarDisplayHandler = ClipboardBarDisplayHandler(prefs: profile.prefs, tabManager: tabManager) clipboardBarDisplayHandler?.delegate = self scrollController.urlBar = urlBar scrollController.readerModeBar = readerModeBar scrollController.header = header scrollController.footer = footer scrollController.snackBars = alertStackView self.updateToolbarStateForTraitCollection(self.traitCollection) setupConstraints() // Setup UIDropInteraction to handle dragging and dropping // links into the view from other apps. let dropInteraction = UIDropInteraction(delegate: self) view.addInteraction(dropInteraction) } fileprivate func setupConstraints() { topTabsContainer.snp.makeConstraints { make in make.leading.trailing.equalTo(self.header) make.top.equalTo(urlBarTopTabsContainer) } urlBar.snp.makeConstraints { make in make.leading.trailing.bottom.equalTo(urlBarTopTabsContainer) make.height.equalTo(UIConstants.TopToolbarHeight) make.top.equalTo(topTabsContainer.snp.bottom) } header.snp.makeConstraints { make in scrollController.headerTopConstraint = make.top.equalTo(self.topLayoutGuide.snp.bottom).constraint make.left.right.equalTo(self.view) } webViewContainerBackdrop.snp.makeConstraints { make in make.edges.equalTo(webViewContainer) } } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() statusBarOverlay.snp.remakeConstraints { make in make.top.left.right.equalTo(self.view) make.height.equalTo(self.topLayoutGuide.length) } } override var canBecomeFirstResponder: Bool { return true } override func becomeFirstResponder() -> Bool { // Make the web view the first responder so that it can show the selection menu. return tabManager.selectedTab?.webView?.becomeFirstResponder() ?? false } func loadQueuedTabs(receivedURLs: [URL]? = nil) { // Chain off of a trivial deferred in order to run on the background queue. succeed().upon() { res in self.dequeueQueuedTabs(receivedURLs: receivedURLs ?? []) } } fileprivate func dequeueQueuedTabs(receivedURLs: [URL]) { assert(!Thread.current.isMainThread, "This must be called in the background.") self.profile.queue.getQueuedTabs() >>== { cursor in // This assumes that the DB returns rows in some kind of sane order. // It does in practice, so WFM. if cursor.count > 0 { // Filter out any tabs received by a push notification to prevent dupes. let urls = cursor.compactMap { $0?.url.asURL }.filter { !receivedURLs.contains($0) } if !urls.isEmpty { DispatchQueue.main.async { self.tabManager.addTabsForURLs(urls, zombie: false) } } // Clear *after* making an attempt to open. We're making a bet that // it's better to run the risk of perhaps opening twice on a crash, // rather than losing data. self.profile.queue.clearQueuedTabs() } // Then, open any received URLs from push notifications. if !receivedURLs.isEmpty { DispatchQueue.main.async { self.tabManager.addTabsForURLs(receivedURLs, zombie: false) if let lastURL = receivedURLs.last, let tab = self.tabManager.getTabForURL(lastURL) { self.tabManager.selectTab(tab) } } } } } // Because crashedLastLaunch is sticky, it does not get reset, we need to remember its // value so that we do not keep asking the user to restore their tabs. var displayedRestoreTabsAlert = false override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) // On iPhone, if we are about to show the On-Boarding, blank out the tab so that it does // not flash before we present. This change of alpha also participates in the animation when // the intro view is dismissed. if UIDevice.current.userInterfaceIdiom == .phone { self.view.alpha = (profile.prefs.intForKey(PrefsKeys.IntroSeen) != nil) ? 1.0 : 0.0 } if !displayedRestoreTabsAlert && !cleanlyBackgrounded() && crashedLastLaunch() { displayedRestoreTabsAlert = true showRestoreTabsAlert() } else { tabManager.restoreTabs() } updateTabCountUsingTabManager(tabManager, animated: false) clipboardBarDisplayHandler?.checkIfShouldDisplayBar() } fileprivate func crashedLastLaunch() -> Bool { return Sentry.crashedLastLaunch } fileprivate func cleanlyBackgrounded() -> Bool { guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { return false } return appDelegate.applicationCleanlyBackgrounded } fileprivate func showRestoreTabsAlert() { guard tabManager.hasTabsToRestoreAtStartup() else { tabManager.selectTab(tabManager.addTab()) return } let alert = UIAlertController.restoreTabsAlert( okayCallback: { _ in self.tabManager.restoreTabs() }, noCallback: { _ in self.tabManager.selectTab(self.tabManager.addTab()) } ) self.present(alert, animated: true, completion: nil) } override func viewDidAppear(_ animated: Bool) { presentIntroViewController() screenshotHelper.viewIsVisible = true screenshotHelper.takePendingScreenshots(tabManager.tabs) super.viewDidAppear(animated) if shouldShowWhatsNewTab() { // Only display if the SUMO topic has been configured in the Info.plist (present and not empty) if let whatsNewTopic = AppInfo.whatsNewTopic, whatsNewTopic != "" { if let whatsNewURL = SupportUtils.URLForTopic(whatsNewTopic) { self.openURLInNewTab(whatsNewURL, isPrivileged: false) profile.prefs.setString(AppInfo.appVersion, forKey: LatestAppVersionProfileKey) } } } if let toast = self.pendingToast { self.pendingToast = nil show(toast: toast, afterWaiting: ButtonToastUX.ToastDelay) } showQueuedAlertIfAvailable() } // THe logic for shouldShowWhatsNewTab is as follows: If we do not have the LatestAppVersionProfileKey in // the profile, that means that this is a fresh install and we do not show the What's New. If we do have // that value, we compare it to the major version of the running app. If it is different then this is an // upgrade, downgrades are not possible, so we can show the What's New page. fileprivate func shouldShowWhatsNewTab() -> Bool { guard let latestMajorAppVersion = profile.prefs.stringForKey(LatestAppVersionProfileKey)?.components(separatedBy: ".").first else { return false // Clean install, never show What's New } return latestMajorAppVersion != AppInfo.majorAppVersion && DeviceInfo.hasConnectivity() } fileprivate func showQueuedAlertIfAvailable() { if let queuedAlertInfo = tabManager.selectedTab?.dequeueJavascriptAlertPrompt() { let alertController = queuedAlertInfo.alertController() alertController.delegate = self present(alertController, animated: true, completion: nil) } } override func viewWillDisappear(_ animated: Bool) { screenshotHelper.viewIsVisible = false super.viewWillDisappear(animated) } override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) } func resetBrowserChrome() { // animate and reset transform for tab chrome urlBar.updateAlphaForSubviews(1) footer.alpha = 1 [header, footer, readerModeBar].forEach { view in view?.transform = .identity } statusBarOverlay.isHidden = false } override func updateViewConstraints() { super.updateViewConstraints() topTouchArea.snp.remakeConstraints { make in make.top.left.right.equalTo(self.view) make.height.equalTo(BrowserViewControllerUX.ShowHeaderTapAreaHeight) } readerModeBar?.snp.remakeConstraints { make in make.top.equalTo(self.header.snp.bottom) make.height.equalTo(UIConstants.ToolbarHeight) make.leading.trailing.equalTo(self.view) } webViewContainer.snp.remakeConstraints { make in make.left.right.equalTo(self.view) if let readerModeBarBottom = readerModeBar?.snp.bottom { make.top.equalTo(readerModeBarBottom) } else { make.top.equalTo(self.header.snp.bottom) } let findInPageHeight = (findInPageBar == nil) ? 0 : UIConstants.ToolbarHeight if let toolbar = self.toolbar { make.bottom.equalTo(toolbar.snp.top).offset(-findInPageHeight) } else { make.bottom.equalTo(self.view).offset(-findInPageHeight) } } // Setup the bottom toolbar toolbar?.snp.remakeConstraints { make in make.edges.equalTo(self.footer) make.height.equalTo(UIConstants.BottomToolbarHeight) } footer.snp.remakeConstraints { make in scrollController.footerBottomConstraint = make.bottom.equalTo(self.view.snp.bottom).constraint make.leading.trailing.equalTo(self.view) } urlBar.setNeedsUpdateConstraints() // Remake constraints even if we're already showing the home controller. // The home controller may change sizes if we tap the URL bar while on about:home. homePanelController?.view.snp.remakeConstraints { make in make.top.equalTo(self.urlBar.snp.bottom) make.left.right.equalTo(self.view) if self.homePanelIsInline { make.bottom.equalTo(self.toolbar?.snp.top ?? self.view.snp.bottom) } else { make.bottom.equalTo(self.view.snp.bottom) } } alertStackView.snp.remakeConstraints { make in make.centerX.equalTo(self.view) make.width.equalTo(self.view.safeArea.width) if let keyboardHeight = keyboardState?.intersectionHeightForView(self.view), keyboardHeight > 0 { make.bottom.equalTo(self.view).offset(-keyboardHeight) } else if let toolbar = self.toolbar { make.bottom.equalTo(toolbar.snp.top) make.bottom.lessThanOrEqualTo(self.view.safeArea.bottom) } else { make.bottom.equalTo(self.view) } } } fileprivate func showHomePanelController(inline: Bool) { homePanelIsInline = inline if homePanelController == nil { var homePanelVC: (UIViewController & HomePanel)? let currentChoice = NewTabAccessors.getNewTabPage(self.profile.prefs) switch currentChoice { case .topSites: homePanelVC = ActivityStreamPanel(profile: profile) case .bookmarks: homePanelVC = BookmarksPanel(profile: profile) case .history: homePanelVC = HistoryPanel(profile: profile) case .readingList: homePanelVC = ReadingListPanel(profile: profile) default: break } if let vc = homePanelVC { let navController = ThemedNavigationController(rootViewController: vc) navController.setNavigationBarHidden(true, animated: false) navController.interactivePopGestureRecognizer?.delegate = nil navController.view.alpha = 0 self.homePanelController = navController vc.homePanelDelegate = self addChildViewController(navController) view.addSubview(navController.view) vc.didMove(toParentViewController: self) } } guard let homePanelController = self.homePanelController else { return } homePanelController.applyTheme() // We have to run this animation, even if the view is already showing because there may be a hide animation running // and we want to be sure to override its results. UIView.animate(withDuration: 0.2, animations: { () -> Void in homePanelController.view.alpha = 1 }, completion: { finished in if finished { self.webViewContainer.accessibilityElementsHidden = true UIAccessibilityPostNotification(UIAccessibilityScreenChangedNotification, nil) } }) view.setNeedsUpdateConstraints() } fileprivate func hideHomePanelController() { if let controller = homePanelController { self.homePanelController = nil UIView.animate(withDuration: 0.2, delay: 0, options: .beginFromCurrentState, animations: { () -> Void in controller.view.alpha = 0 }, completion: { _ in controller.willMove(toParentViewController: nil) controller.view.removeFromSuperview() controller.removeFromParentViewController() self.webViewContainer.accessibilityElementsHidden = false UIAccessibilityPostNotification(UIAccessibilityScreenChangedNotification, nil) // Refresh the reading view toolbar since the article record may have changed if let readerMode = self.tabManager.selectedTab?.getContentScript(name: ReaderMode.name()) as? ReaderMode, readerMode.state == .active { self.showReaderModeBar(animated: false) } }) } } fileprivate func updateInContentHomePanel(_ url: URL?) { if !urlBar.inOverlayMode { guard let url = url else { hideHomePanelController() return } if url.isAboutHomeURL { showHomePanelController(inline: true) } else if url.isErrorPageURL || !url.isLocalUtility || url.isReaderModeURL { hideHomePanelController() } } else if url?.isAboutHomeURL ?? false { showHomePanelController(inline: false) } } fileprivate func showSearchController() { if searchController != nil { return } let isPrivate = tabManager.selectedTab?.isPrivate ?? false searchController = SearchViewController(profile: profile, isPrivate: isPrivate) searchController!.searchEngines = profile.searchEngines searchController!.searchDelegate = self searchLoader = SearchLoader(profile: profile, urlBar: urlBar) searchLoader?.addListener(searchController!) addChildViewController(searchController!) view.addSubview(searchController!.view) searchController!.view.snp.makeConstraints { make in make.top.equalTo(self.urlBar.snp.bottom) make.left.right.bottom.equalTo(self.view) return } homePanelController?.view?.isHidden = true searchController!.didMove(toParentViewController: self) } fileprivate func hideSearchController() { if let searchController = searchController { searchController.willMove(toParentViewController: nil) searchController.view.removeFromSuperview() searchController.removeFromParentViewController() self.searchController = nil homePanelController?.view?.isHidden = false searchLoader = nil } } func finishEditingAndSubmit(_ url: URL, visitType: VisitType, forTab tab: Tab) { urlBar.currentURL = url urlBar.leaveOverlayMode() if let webView = tab.webView { resetSpoofedUserAgentIfRequired(webView, newURL: url) } if let nav = tab.loadRequest(PrivilegedRequest(url: url) as URLRequest) { self.recordNavigationInTab(tab, navigation: nav, visitType: visitType) } } func addBookmark(_ tabState: TabState) { guard let url = tabState.url else { return } let absoluteString = url.absoluteString let shareItem = ShareItem(url: absoluteString, title: tabState.title, favicon: tabState.favicon) _ = profile.bookmarks.shareItem(shareItem) var userData = [QuickActions.TabURLKey: shareItem.url] if let title = shareItem.title { userData[QuickActions.TabTitleKey] = title } QuickActions.sharedInstance.addDynamicApplicationShortcutItemOfType(.openLastBookmark, withUserData: userData, toApplication: UIApplication.shared) } override func accessibilityPerformEscape() -> Bool { if urlBar.inOverlayMode { urlBar.didClickCancel() return true } else if let selectedTab = tabManager.selectedTab, selectedTab.canGoBack { selectedTab.goBack() return true } return false } override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey: Any]?, context: UnsafeMutableRawPointer?) { guard let webView = object as? WKWebView else { assert(false) return } guard let kp = keyPath, let path = KVOConstants(rawValue: kp) else { assertionFailure("Unhandled KVO key: \(keyPath ?? "nil")") return } switch path { case .estimatedProgress: guard webView == tabManager.selectedTab?.webView else { break } if !(webView.url?.isLocalUtility ?? false) { urlBar.updateProgressBar(Float(webView.estimatedProgress)) // Profiler.end triggers a screenshot, and a delay is needed here to capture the correct screen // (otherwise the screen prior to this step completing is captured). if webView.estimatedProgress > 0.9 { Profiler.shared?.end(bookend: .load_url, delay: 0.200) } } else { urlBar.hideProgressBar() } case .loading: guard let loading = change?[.newKey] as? Bool else { break } if webView == tabManager.selectedTab?.webView { navigationToolbar.updateReloadStatus(loading) } if !loading { runScriptsOnWebView(webView) } case .URL: guard let tab = tabManager[webView] else { break } // To prevent spoofing, only change the URL immediately if the new URL is on // the same origin as the current URL. Otherwise, do nothing and wait for // didCommitNavigation to confirm the page load. if tab.url?.origin == webView.url?.origin { tab.url = webView.url if tab === tabManager.selectedTab && !tab.restoring { updateUIForReaderHomeStateForTab(tab) } } case .title: guard let tab = tabManager[webView] else { break } // Ensure that the tab title *actually* changed to prevent repeated calls // to navigateInTab(tab:). guard let title = tab.title else { break } if !title.isEmpty && title != tab.lastTitle { navigateInTab(tab: tab) } case .canGoBack: guard webView == tabManager.selectedTab?.webView, let canGoBack = change?[.newKey] as? Bool else { break } navigationToolbar.updateBackStatus(canGoBack) case .canGoForward: guard webView == tabManager.selectedTab?.webView, let canGoForward = change?[.newKey] as? Bool else { break } navigationToolbar.updateForwardStatus(canGoForward) default: assertionFailure("Unhandled KVO key: \(keyPath ?? "nil")") } } fileprivate func runScriptsOnWebView(_ webView: WKWebView) { guard let url = webView.url, url.isWebPage(), !url.isLocal else { return } if NoImageModeHelper.isActivated(profile.prefs) { webView.evaluateJavaScript("__firefox__.NoImageMode.setEnabled(true)", completionHandler: nil) } } func updateUIForReaderHomeStateForTab(_ tab: Tab) { updateURLBarDisplayURL(tab) scrollController.showToolbars(animated: false) if let url = tab.url { if url.isReaderModeURL { showReaderModeBar(animated: false) NotificationCenter.default.addObserver(self, selector: #selector(dynamicFontChanged), name: .DynamicFontChanged, object: nil) } else { hideReaderModeBar(animated: false) NotificationCenter.default.removeObserver(self, name: .DynamicFontChanged, object: nil) } updateInContentHomePanel(url as URL) } } /// Updates the URL bar text and button states. /// Call this whenever the page URL changes. fileprivate func updateURLBarDisplayURL(_ tab: Tab) { urlBar.currentURL = tab.url?.displayURL let isPage = tab.url?.displayURL?.isWebPage() ?? false navigationToolbar.updatePageStatus(isPage) } // MARK: Opening New Tabs func switchToPrivacyMode(isPrivate: Bool) { if let tabTrayController = self.tabTrayController, tabTrayController.tabDisplayManager.isPrivate != isPrivate { tabTrayController.changePrivacyMode(isPrivate) } topTabsViewController?.applyUIMode(isPrivate: isPrivate) } func switchToTabForURLOrOpen(_ url: URL, isPrivate: Bool = false, isPrivileged: Bool) { popToBVC() if let tab = tabManager.getTabForURL(url) { tabManager.selectTab(tab) } else { openURLInNewTab(url, isPrivate: isPrivate, isPrivileged: isPrivileged) } } func openURLInNewTab(_ url: URL?, isPrivate: Bool = false, isPrivileged: Bool) { if let selectedTab = tabManager.selectedTab { screenshotHelper.takeScreenshot(selectedTab) } let request: URLRequest? if let url = url { request = isPrivileged ? PrivilegedRequest(url: url) as URLRequest : URLRequest(url: url) } else { request = nil } switchToPrivacyMode(isPrivate: isPrivate) tabManager.selectTab(tabManager.addTab(request, isPrivate: isPrivate)) } func focusLocationTextField(forTab tab: Tab?, setSearchText searchText: String? = nil) { DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(300)) { // Without a delay, the text field fails to become first responder // Check that the newly created tab is still selected. // This let's the user spam the Cmd+T button without lots of responder changes. guard tab == self.tabManager.selectedTab else { return } self.urlBar.tabLocationViewDidTapLocation(self.urlBar.locationView) if let text = searchText { self.urlBar.setLocation(text, search: true) } } } func openBlankNewTab(focusLocationField: Bool, isPrivate: Bool = false, searchFor searchText: String? = nil) { popToBVC() openURLInNewTab(nil, isPrivate: isPrivate, isPrivileged: true) let freshTab = tabManager.selectedTab if focusLocationField { focusLocationTextField(forTab: freshTab, setSearchText: searchText) } } func openSearchNewTab(isPrivate: Bool = false, _ text: String) { popToBVC() let engine = profile.searchEngines.defaultEngine if let searchURL = engine.searchURLForQuery(text) { openURLInNewTab(searchURL, isPrivate: isPrivate, isPrivileged: true) } else { // We still don't have a valid URL, so something is broken. Give up. print("Error handling URL entry: \"\(text)\".") assertionFailure("Couldn't generate search URL: \(text)") } } fileprivate func popToBVC() { guard let currentViewController = navigationController?.topViewController else { return } currentViewController.dismiss(animated: true, completion: nil) if currentViewController != self { _ = self.navigationController?.popViewController(animated: true) } else if urlBar.inOverlayMode { urlBar.didClickCancel() } } // MARK: User Agent Spoofing func resetSpoofedUserAgentIfRequired(_ webView: WKWebView, newURL: URL) { // Reset the UA when a different domain is being loaded if webView.url?.host != newURL.host { webView.customUserAgent = nil } } func restoreSpoofedUserAgentIfRequired(_ webView: WKWebView, newRequest: URLRequest) { // Restore any non-default UA from the request's header let ua = newRequest.value(forHTTPHeaderField: "User-Agent") webView.customUserAgent = ua != UserAgent.defaultUserAgent() ? ua : nil } fileprivate func presentActivityViewController(_ url: URL, tab: Tab? = nil, sourceView: UIView?, sourceRect: CGRect, arrowDirection: UIPopoverArrowDirection) { let helper = ShareExtensionHelper(url: url, tab: tab) let controller = helper.createActivityViewController({ [unowned self] completed, _ in // After dismissing, check to see if there were any prompts we queued up self.showQueuedAlertIfAvailable() // Usually the popover delegate would handle nil'ing out the references we have to it // on the BVC when displaying as a popover but the delegate method doesn't seem to be // invoked on iOS 10. See Bug 1297768 for additional details. self.displayedPopoverController = nil self.updateDisplayedPopoverProperties = nil }) if let popoverPresentationController = controller.popoverPresentationController { popoverPresentationController.sourceView = sourceView popoverPresentationController.sourceRect = sourceRect popoverPresentationController.permittedArrowDirections = arrowDirection popoverPresentationController.delegate = self } present(controller, animated: true, completion: nil) LeanPlumClient.shared.track(event: .userSharedWebpage) } @objc fileprivate func openSettings() { assert(Thread.isMainThread, "Opening settings requires being invoked on the main thread") let settingsTableViewController = AppSettingsTableViewController() settingsTableViewController.profile = profile settingsTableViewController.tabManager = tabManager settingsTableViewController.settingsDelegate = self let controller = ThemedNavigationController(rootViewController: settingsTableViewController) controller.popoverDelegate = self controller.modalPresentationStyle = .formSheet self.present(controller, animated: true, completion: nil) } fileprivate func postLocationChangeNotificationForTab(_ tab: Tab, navigation: WKNavigation?) { let notificationCenter = NotificationCenter.default var info = [AnyHashable: Any]() info["url"] = tab.url?.displayURL info["title"] = tab.title if let visitType = self.getVisitTypeForTab(tab, navigation: navigation)?.rawValue { info["visitType"] = visitType } info["isPrivate"] = tab.isPrivate notificationCenter.post(name: .OnLocationChange, object: self, userInfo: info) } func navigateInTab(tab: Tab, to navigation: WKNavigation? = nil) { tabManager.expireSnackbars() guard let webView = tab.webView else { print("Cannot navigate in tab without a webView") return } if let url = webView.url { if !url.isErrorPageURL, !url.isAboutHomeURL, !url.isFileURL { postLocationChangeNotificationForTab(tab, navigation: navigation) // Fire the readability check. This is here and not in the pageShow event handler in ReaderMode.js anymore // because that event wil not always fire due to unreliable page caching. This will either let us know that // the currently loaded page can be turned into reading mode or if the page already is in reading mode. We // ignore the result because we are being called back asynchronous when the readermode status changes. webView.evaluateJavaScript("\(ReaderModeNamespace).checkReadability()", completionHandler: nil) // Re-run additional scripts in webView to extract updated favicons and metadata. runScriptsOnWebView(webView) } TabEvent.post(.didChangeURL(url), for: tab) } if tab === tabManager.selectedTab { UIAccessibilityPostNotification(UIAccessibilityScreenChangedNotification, nil) // must be followed by LayoutChanged, as ScreenChanged will make VoiceOver // cursor land on the correct initial element, but if not followed by LayoutChanged, // VoiceOver will sometimes be stuck on the element, not allowing user to move // forward/backward. Strange, but LayoutChanged fixes that. UIAccessibilityPostNotification(UIAccessibilityLayoutChangedNotification, nil) } else if let webView = tab.webView { // To Screenshot a tab that is hidden we must add the webView, // then wait enough time for the webview to render. view.insertSubview(webView, at: 0) // This is kind of a hacky fix for Bug 1476637 to prevent webpages from focusing the // touch-screen keyboard from the background even though they shouldn't be able to. webView.resignFirstResponder() DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(500)) { self.screenshotHelper.takeScreenshot(tab) if webView.superview == self.view { webView.removeFromSuperview() } } } // Remember whether or not a desktop site was requested tab.desktopSite = webView.customUserAgent?.isEmpty == false } } extension BrowserViewController: ClipboardBarDisplayHandlerDelegate { func shouldDisplay(clipboardBar bar: ButtonToast) { show(toast: bar, duration: ClipboardBarToastUX.ToastDelay) } } extension BrowserViewController: QRCodeViewControllerDelegate { func didScanQRCodeWithURL(_ url: URL) { guard let tab = tabManager.selectedTab else { return } openBlankNewTab(focusLocationField: false) finishEditingAndSubmit(url, visitType: VisitType.typed, forTab: tab) UnifiedTelemetry.recordEvent(category: .action, method: .scan, object: .qrCodeURL) } func didScanQRCodeWithText(_ text: String) { guard let tab = tabManager.selectedTab else { return } openBlankNewTab(focusLocationField: false) submitSearchText(text, forTab: tab) UnifiedTelemetry.recordEvent(category: .action, method: .scan, object: .qrCodeText) } } extension BrowserViewController: SettingsDelegate { func settingsOpenURLInNewTab(_ url: URL) { self.openURLInNewTab(url, isPrivileged: false) } } extension BrowserViewController: PresentingModalViewControllerDelegate { func dismissPresentedModalViewController(_ modalViewController: UIViewController, animated: Bool) { self.dismiss(animated: animated, completion: nil) } } /** * History visit management. * TODO: this should be expanded to track various visit types; see Bug 1166084. */ extension BrowserViewController { func ignoreNavigationInTab(_ tab: Tab, navigation: WKNavigation) { self.ignoredNavigation.insert(navigation) } func recordNavigationInTab(_ tab: Tab, navigation: WKNavigation, visitType: VisitType) { self.typedNavigation[navigation] = visitType } /** * Untrack and do the right thing. */ func getVisitTypeForTab(_ tab: Tab, navigation: WKNavigation?) -> VisitType? { guard let navigation = navigation else { // See https://github.com/WebKit/webkit/blob/master/Source/WebKit2/UIProcess/Cocoa/NavigationState.mm#L390 return VisitType.link } if let _ = self.ignoredNavigation.remove(navigation) { return nil } return self.typedNavigation.removeValue(forKey: navigation) ?? VisitType.link } } extension BrowserViewController: URLBarDelegate { func showTabTray() { Sentry.shared.clearBreadcrumbs() updateFindInPageVisibility(visible: false) let tabTrayController = TabTrayController(tabManager: tabManager, profile: profile, tabTrayDelegate: self) if let tab = tabManager.selectedTab { screenshotHelper.takeScreenshot(tab) } navigationController?.pushViewController(tabTrayController, animated: true) self.tabTrayController = tabTrayController } func urlBarDidPressReload(_ urlBar: URLBarView) { tabManager.selectedTab?.reload() } func urlBarDidPressQRButton(_ urlBar: URLBarView) { let qrCodeViewController = QRCodeViewController() qrCodeViewController.qrCodeDelegate = self let controller = QRCodeNavigationController(rootViewController: qrCodeViewController) self.present(controller, animated: true, completion: nil) } func urlBarDidPressPageOptions(_ urlBar: URLBarView, from button: UIButton) { guard let tab = tabManager.selectedTab, let urlString = tab.url?.absoluteString, !urlBar.inOverlayMode else { return } let actionMenuPresenter: (URL, Tab, UIView, UIPopoverArrowDirection) -> Void = { (url, tab, view, _) in self.presentActivityViewController(url, tab: tab, sourceView: view, sourceRect: view.bounds, arrowDirection: .up) } let findInPageAction = { self.updateFindInPageVisibility(visible: true) } let successCallback: (String) -> Void = { (successMessage) in SimpleToast().showAlertWithText(successMessage, bottomContainer: self.webViewContainer) } let deferredBookmarkStatus: Deferred<Maybe<Bool>> = fetchBookmarkStatus(for: urlString) let deferredPinnedTopSiteStatus: Deferred<Maybe<Bool>> = fetchPinnedTopSiteStatus(for: urlString) // Wait for both the bookmark status and the pinned status deferredBookmarkStatus.both(deferredPinnedTopSiteStatus).uponQueue(.main) { let isBookmarked = $0.successValue ?? false let isPinned = $1.successValue ?? false let pageActions = self.getTabActions(tab: tab, buttonView: button, presentShareMenu: actionMenuPresenter, findInPage: findInPageAction, presentableVC: self, isBookmarked: isBookmarked, isPinned: isPinned, success: successCallback) self.presentSheetWith(title: Strings.PageActionMenuTitle, actions: pageActions, on: self, from: button) } } func urlBarDidLongPressPageOptions(_ urlBar: URLBarView, from button: UIButton) { guard let tab = tabManager.selectedTab else { return } guard let url = tab.canonicalURL?.displayURL, self.presentedViewController == nil else { return } let generator = UIImpactFeedbackGenerator(style: .heavy) generator.impactOccurred() presentActivityViewController(url, tab: tab, sourceView: button, sourceRect: button.bounds, arrowDirection: .up) } func urlBarDidTapShield(_ urlBar: URLBarView, from button: UIButton) { if let tab = self.tabManager.selectedTab { let trackingProtectionMenu = self.getTrackingSubMenu(for: tab) guard !trackingProtectionMenu.isEmpty else { return } self.presentSheetWith(actions: trackingProtectionMenu, on: self, from: urlBar) } } func urlBarDidPressStop(_ urlBar: URLBarView) { tabManager.selectedTab?.stop() } func urlBarDidPressTabs(_ urlBar: URLBarView) { showTabTray() } func urlBarDidPressReaderMode(_ urlBar: URLBarView) { if let tab = tabManager.selectedTab { if let readerMode = tab.getContentScript(name: "ReaderMode") as? ReaderMode { switch readerMode.state { case .available: enableReaderMode() UnifiedTelemetry.recordEvent(category: .action, method: .tap, object: .readerModeOpenButton) LeanPlumClient.shared.track(event: .useReaderView) case .active: disableReaderMode() UnifiedTelemetry.recordEvent(category: .action, method: .tap, object: .readerModeCloseButton) case .unavailable: break } } } } func urlBarDidLongPressReaderMode(_ urlBar: URLBarView) -> Bool { guard let tab = tabManager.selectedTab, let url = tab.url?.displayURL else { UIAccessibilityPostNotification(UIAccessibilityAnnouncementNotification, NSLocalizedString("Could not add page to Reading list", comment: "Accessibility message e.g. spoken by VoiceOver after adding current webpage to the Reading List failed.")) return false } let result = profile.readingList.createRecordWithURL(url.absoluteString, title: tab.title ?? "", addedBy: UIDevice.current.name) switch result.value { case .success: UIAccessibilityPostNotification(UIAccessibilityAnnouncementNotification, NSLocalizedString("Added page to Reading List", comment: "Accessibility message e.g. spoken by VoiceOver after the current page gets added to the Reading List using the Reader View button, e.g. by long-pressing it or by its accessibility custom action.")) // TODO: https://bugzilla.mozilla.org/show_bug.cgi?id=1158503 provide some form of 'this has been added' visual feedback? case .failure(let error): UIAccessibilityPostNotification(UIAccessibilityAnnouncementNotification, NSLocalizedString("Could not add page to Reading List. Maybe it’s already there?", comment: "Accessibility message e.g. spoken by VoiceOver after the user wanted to add current page to the Reading List and this was not done, likely because it already was in the Reading List, but perhaps also because of real failures.")) print("readingList.createRecordWithURL(url: \"\(url.absoluteString)\", ...) failed with error: \(error)") } return true } func locationActionsForURLBar(_ urlBar: URLBarView) -> [AccessibleAction] { if UIPasteboard.general.string != nil { return [pasteGoAction, pasteAction, copyAddressAction] } else { return [copyAddressAction] } } func urlBarDisplayTextForURL(_ url: URL?) -> (String?, Bool) { // use the initial value for the URL so we can do proper pattern matching with search URLs var searchURL = self.tabManager.selectedTab?.currentInitialURL if searchURL?.isErrorPageURL ?? true { searchURL = url } if let query = profile.searchEngines.queryForSearchURL(searchURL as URL?) { return (query, true) } else { return (url?.absoluteString, false) } } func urlBarDidLongPressLocation(_ urlBar: URLBarView) { let urlActions = self.getLongPressLocationBarActions(with: urlBar) let generator = UIImpactFeedbackGenerator(style: .heavy) generator.impactOccurred() if let tab = self.tabManager.selectedTab { let trackingProtectionMenu = self.getTrackingMenu(for: tab, presentingOn: urlBar) self.presentSheetWith(actions: [urlActions, trackingProtectionMenu], on: self, from: urlBar) } else { self.presentSheetWith(actions: [urlActions], on: self, from: urlBar) } } func urlBarDidPressScrollToTop(_ urlBar: URLBarView) { if let selectedTab = tabManager.selectedTab, homePanelController == nil { // Only scroll to top if we are not showing the home view controller selectedTab.webView?.scrollView.setContentOffset(CGPoint.zero, animated: true) } } func urlBarLocationAccessibilityActions(_ urlBar: URLBarView) -> [UIAccessibilityCustomAction]? { return locationActionsForURLBar(urlBar).map { $0.accessibilityCustomAction } } func urlBar(_ urlBar: URLBarView, didEnterText text: String) { if text.isEmpty { hideSearchController() } else { showSearchController() searchController?.searchQuery = text searchLoader?.query = text } } func urlBar(_ urlBar: URLBarView, didSubmitText text: String) { guard let currentTab = tabManager.selectedTab else { return } if let fixupURL = URIFixup.getURL(text) { // The user entered a URL, so use it. finishEditingAndSubmit(fixupURL, visitType: VisitType.typed, forTab: currentTab) return } // We couldn't build a URL, so check for a matching search keyword. let trimmedText = text.trimmingCharacters(in: .whitespaces) guard let possibleKeywordQuerySeparatorSpace = trimmedText.index(of: " ") else { submitSearchText(text, forTab: currentTab) return } let possibleKeyword = String(trimmedText[..<possibleKeywordQuerySeparatorSpace]) let possibleQuery = String(trimmedText[trimmedText.index(after: possibleKeywordQuerySeparatorSpace)...]) profile.bookmarks.getURLForKeywordSearch(possibleKeyword).uponQueue(.main) { result in if var urlString = result.successValue, let escapedQuery = possibleQuery.addingPercentEncoding(withAllowedCharacters: NSCharacterSet.urlQueryAllowed), let range = urlString.range(of: "%s") { urlString.replaceSubrange(range, with: escapedQuery) if let url = URL(string: urlString) { self.finishEditingAndSubmit(url, visitType: VisitType.typed, forTab: currentTab) return } } self.submitSearchText(text, forTab: currentTab) } } fileprivate func submitSearchText(_ text: String, forTab tab: Tab) { let engine = profile.searchEngines.defaultEngine if let searchURL = engine.searchURLForQuery(text) { // We couldn't find a matching search keyword, so do a search query. Telemetry.default.recordSearch(location: .actionBar, searchEngine: engine.engineID ?? "other") finishEditingAndSubmit(searchURL, visitType: VisitType.typed, forTab: tab) } else { // We still don't have a valid URL, so something is broken. Give up. print("Error handling URL entry: \"\(text)\".") assertionFailure("Couldn't generate search URL: \(text)") } } func urlBarDidEnterOverlayMode(_ urlBar: URLBarView) { guard let profile = profile as? BrowserProfile else { return } if .blankPage == NewTabAccessors.getNewTabPage(profile.prefs) { UIAccessibilityPostNotification(UIAccessibilityScreenChangedNotification, nil) } else { if let toast = clipboardBarDisplayHandler?.clipboardToast { toast.removeFromSuperview() } showHomePanelController(inline: false) } LeanPlumClient.shared.track(event: .interactWithURLBar) } func urlBarDidLeaveOverlayMode(_ urlBar: URLBarView) { hideSearchController() updateInContentHomePanel(tabManager.selectedTab?.url as URL?) } func urlBarDidBeginDragInteraction(_ urlBar: URLBarView) { dismissVisibleMenus() } } extension BrowserViewController: TabToolbarDelegate, PhotonActionSheetProtocol { func tabToolbarDidPressBack(_ tabToolbar: TabToolbarProtocol, button: UIButton) { tabManager.selectedTab?.goBack() } func tabToolbarDidLongPressBack(_ tabToolbar: TabToolbarProtocol, button: UIButton) { let generator = UIImpactFeedbackGenerator(style: .heavy) generator.impactOccurred() showBackForwardList() } func tabToolbarDidPressReload(_ tabToolbar: TabToolbarProtocol, button: UIButton) { tabManager.selectedTab?.reload() } func tabToolbarDidLongPressReload(_ tabToolbar: TabToolbarProtocol, button: UIButton) { guard let tab = tabManager.selectedTab else { return } let urlActions = self.getRefreshLongPressMenu(for: tab) guard !urlActions.isEmpty else { return } let generator = UIImpactFeedbackGenerator(style: .heavy) generator.impactOccurred() let shouldSuppress = !topTabsVisible && UIDevice.current.userInterfaceIdiom == .pad presentSheetWith(actions: [urlActions], on: self, from: button, suppressPopover: shouldSuppress) } func tabToolbarDidPressStop(_ tabToolbar: TabToolbarProtocol, button: UIButton) { tabManager.selectedTab?.stop() } func tabToolbarDidPressForward(_ tabToolbar: TabToolbarProtocol, button: UIButton) { tabManager.selectedTab?.goForward() } func tabToolbarDidLongPressForward(_ tabToolbar: TabToolbarProtocol, button: UIButton) { let generator = UIImpactFeedbackGenerator(style: .heavy) generator.impactOccurred() showBackForwardList() } func tabToolbarDidPressMenu(_ tabToolbar: TabToolbarProtocol, button: UIButton) { // ensure that any keyboards or spinners are dismissed before presenting the menu UIApplication.shared.sendAction(#selector(UIResponder.resignFirstResponder), to: nil, from: nil, for: nil) var actions: [[PhotonActionSheetItem]] = [] if let syncAction = syncMenuButton(showFxA: presentSignInViewController) { actions.append(syncAction) } actions.append(getLibraryActions(vcDelegate: self)) actions.append(getOtherPanelActions(vcDelegate: self)) // force a modal if the menu is being displayed in compact split screen let shouldSuppress = !topTabsVisible && UIDevice.current.userInterfaceIdiom == .pad presentSheetWith(actions: actions, on: self, from: button, suppressPopover: shouldSuppress) } func tabToolbarDidPressTabs(_ tabToolbar: TabToolbarProtocol, button: UIButton) { showTabTray() } func getTabToolbarLongPressActionsForModeSwitching() -> [PhotonActionSheetItem] { guard let selectedTab = tabManager.selectedTab else { return [] } let count = selectedTab.isPrivate ? tabManager.normalTabs.count : tabManager.privateTabs.count let infinity = "\u{221E}" let tabCount = (count < 100) ? count.description : infinity func action() { let result = tabManager.switchPrivacyMode() if result == .createdNewTab, NewTabAccessors.getNewTabPage(self.profile.prefs) == .blankPage { focusLocationTextField(forTab: tabManager.selectedTab) } } let privateBrowsingMode = PhotonActionSheetItem(title: Strings.privateBrowsingModeTitle, iconString: "nav-tabcounter", iconType: .TabsButton, tabCount: tabCount) { _ in action() } let normalBrowsingMode = PhotonActionSheetItem(title: Strings.normalBrowsingModeTitle, iconString: "nav-tabcounter", iconType: .TabsButton, tabCount: tabCount) { _ in action() } if let tab = self.tabManager.selectedTab { return tab.isPrivate ? [normalBrowsingMode] : [privateBrowsingMode] } return [privateBrowsingMode] } func getMoreTabToolbarLongPressActions() -> [PhotonActionSheetItem] { let newTab = PhotonActionSheetItem(title: Strings.NewTabTitle, iconString: "quick_action_new_tab", iconType: .Image) { action in let shouldFocusLocationField = NewTabAccessors.getNewTabPage(self.profile.prefs) == .blankPage self.openBlankNewTab(focusLocationField: shouldFocusLocationField, isPrivate: false)} let newPrivateTab = PhotonActionSheetItem(title: Strings.NewPrivateTabTitle, iconString: "quick_action_new_tab", iconType: .Image) { action in let shouldFocusLocationField = NewTabAccessors.getNewTabPage(self.profile.prefs) == .blankPage self.openBlankNewTab(focusLocationField: shouldFocusLocationField, isPrivate: true)} let closeTab = PhotonActionSheetItem(title: Strings.CloseTabTitle, iconString: "tab_close", iconType: .Image) { action in if let tab = self.tabManager.selectedTab { self.tabManager.removeTabAndUpdateSelectedIndex(tab) self.updateTabCountUsingTabManager(self.tabManager) }} if let tab = self.tabManager.selectedTab { return tab.isPrivate ? [newPrivateTab, closeTab] : [newTab, closeTab] } return [newTab, closeTab] } func tabToolbarDidLongPressTabs(_ tabToolbar: TabToolbarProtocol, button: UIButton) { guard self.presentedViewController == nil else { return } var actions: [[PhotonActionSheetItem]] = [] actions.append(getTabToolbarLongPressActionsForModeSwitching()) actions.append(getMoreTabToolbarLongPressActions()) // Force a modal if the menu is being displayed in compact split screen. let shouldSuppress = !topTabsVisible && UIDevice.current.userInterfaceIdiom == .pad let generator = UIImpactFeedbackGenerator(style: .heavy) generator.impactOccurred() presentSheetWith(actions: actions, on: self, from: button, suppressPopover: shouldSuppress) } func showBackForwardList() { if let backForwardList = tabManager.selectedTab?.webView?.backForwardList { let backForwardViewController = BackForwardListViewController(profile: profile, backForwardList: backForwardList) backForwardViewController.tabManager = tabManager backForwardViewController.bvc = self backForwardViewController.modalPresentationStyle = .overCurrentContext backForwardViewController.backForwardTransitionDelegate = BackForwardListAnimator() self.present(backForwardViewController, animated: true, completion: nil) } } } extension BrowserViewController: TabDelegate { func tab(_ tab: Tab, didCreateWebView webView: WKWebView) { webView.frame = webViewContainer.frame // Observers that live as long as the tab. Make sure these are all cleared in willDeleteWebView below! KVOs.forEach { webView.addObserver(self, forKeyPath: $0.rawValue, options: .new, context: nil) } webView.scrollView.addObserver(self.scrollController, forKeyPath: KVOConstants.contentSize.rawValue, options: .new, context: nil) webView.uiDelegate = self let formPostHelper = FormPostHelper(tab: tab) tab.addContentScript(formPostHelper, name: FormPostHelper.name()) let readerMode = ReaderMode(tab: tab) readerMode.delegate = self tab.addContentScript(readerMode, name: ReaderMode.name()) // only add the logins helper if the tab is not a private browsing tab if !tab.isPrivate { let logins = LoginsHelper(tab: tab, profile: profile) tab.addContentScript(logins, name: LoginsHelper.name()) } let contextMenuHelper = ContextMenuHelper(tab: tab) contextMenuHelper.delegate = self tab.addContentScript(contextMenuHelper, name: ContextMenuHelper.name()) let errorHelper = ErrorPageHelper() tab.addContentScript(errorHelper, name: ErrorPageHelper.name()) let sessionRestoreHelper = SessionRestoreHelper(tab: tab) sessionRestoreHelper.delegate = self tab.addContentScript(sessionRestoreHelper, name: SessionRestoreHelper.name()) let findInPageHelper = FindInPageHelper(tab: tab) findInPageHelper.delegate = self tab.addContentScript(findInPageHelper, name: FindInPageHelper.name()) let noImageModeHelper = NoImageModeHelper(tab: tab) tab.addContentScript(noImageModeHelper, name: NoImageModeHelper.name()) let downloadContentScript = DownloadContentScript(tab: tab) tab.addContentScript(downloadContentScript, name: DownloadContentScript.name()) let printHelper = PrintHelper(tab: tab) tab.addContentScript(printHelper, name: PrintHelper.name()) let customSearchHelper = CustomSearchHelper(tab: tab) tab.addContentScript(customSearchHelper, name: CustomSearchHelper.name()) let nightModeHelper = NightModeHelper(tab: tab) tab.addContentScript(nightModeHelper, name: NightModeHelper.name()) // XXX: Bug 1390200 - Disable NSUserActivity/CoreSpotlight temporarily // let spotlightHelper = SpotlightHelper(tab: tab) // tab.addHelper(spotlightHelper, name: SpotlightHelper.name()) tab.addContentScript(LocalRequestHelper(), name: LocalRequestHelper.name()) let historyStateHelper = HistoryStateHelper(tab: tab) historyStateHelper.delegate = self tab.addContentScript(historyStateHelper, name: HistoryStateHelper.name()) let blocker = FirefoxTabContentBlocker(tab: tab, prefs: profile.prefs) tab.contentBlocker = blocker tab.addContentScript(blocker, name: FirefoxTabContentBlocker.name()) tab.addContentScript(FocusHelper(tab: tab), name: FocusHelper.name()) } func tab(_ tab: Tab, willDeleteWebView webView: WKWebView) { tab.cancelQueuedAlerts() KVOs.forEach { webView.removeObserver(self, forKeyPath: $0.rawValue) } webView.scrollView.removeObserver(self.scrollController, forKeyPath: KVOConstants.contentSize.rawValue) webView.uiDelegate = nil webView.scrollView.delegate = nil webView.removeFromSuperview() } fileprivate func findSnackbar(_ barToFind: SnackBar) -> Int? { let bars = alertStackView.arrangedSubviews for (index, bar) in bars.enumerated() where bar === barToFind { return index } return nil } func showBar(_ bar: SnackBar, animated: Bool) { view.layoutIfNeeded() UIView.animate(withDuration: animated ? 0.25 : 0, animations: { self.alertStackView.insertArrangedSubview(bar, at: 0) self.view.layoutIfNeeded() }) } func removeBar(_ bar: SnackBar, animated: Bool) { UIView.animate(withDuration: animated ? 0.25 : 0, animations: { bar.removeFromSuperview() }) } func removeAllBars() { alertStackView.arrangedSubviews.forEach { $0.removeFromSuperview() } } func tab(_ tab: Tab, didAddSnackbar bar: SnackBar) { showBar(bar, animated: true) } func tab(_ tab: Tab, didRemoveSnackbar bar: SnackBar) { removeBar(bar, animated: true) } func tab(_ tab: Tab, didSelectFindInPageForSelection selection: String) { updateFindInPageVisibility(visible: true) findInPageBar?.text = selection } func tab(_ tab: Tab, didSelectSearchWithFirefoxForSelection selection: String) { openSearchNewTab(isPrivate: tab.isPrivate, selection) } } extension BrowserViewController: HomePanelDelegate { func homePanelDidRequestToSignIn() { let fxaParams = FxALaunchParams(query: ["entrypoint": "homepanel"]) presentSignInViewController(fxaParams) // TODO UX Right now the flow for sign in and create account is the same } func homePanelDidRequestToCreateAccount() { let fxaParams = FxALaunchParams(query: ["entrypoint": "homepanel"]) presentSignInViewController(fxaParams) // TODO UX Right now the flow for sign in and create account is the same } func homePanel(didSelectURL url: URL, visitType: VisitType) { guard let tab = tabManager.selectedTab else { return } finishEditingAndSubmit(url, visitType: visitType, forTab: tab) } func homePanel(didSelectURLString url: String, visitType: VisitType) { guard let url = URIFixup.getURL(url) ?? profile.searchEngines.defaultEngine.searchURLForQuery(url) else { Logger.browserLogger.warning("Invalid URL, and couldn't generate a search URL for it.") return } return self.homePanel(didSelectURL: url, visitType: visitType) } func homePanelDidRequestToOpenInNewTab(_ url: URL, isPrivate: Bool) { let tab = self.tabManager.addTab(PrivilegedRequest(url: url) as URLRequest, afterTab: self.tabManager.selectedTab, isPrivate: isPrivate) // If we are showing toptabs a user can just use the top tab bar // If in overlay mode switching doesnt correctly dismiss the homepanels guard !topTabsVisible, !self.urlBar.inOverlayMode else { return } // We're not showing the top tabs; show a toast to quick switch to the fresh new tab. let toast = ButtonToast(labelText: Strings.ContextMenuButtonToastNewTabOpenedLabelText, buttonText: Strings.ContextMenuButtonToastNewTabOpenedButtonText, completion: { buttonPressed in if buttonPressed { self.tabManager.selectTab(tab) } }) self.show(toast: toast) } } extension BrowserViewController: SearchViewControllerDelegate { func searchViewController(_ searchViewController: SearchViewController, didSelectURL url: URL) { guard let tab = tabManager.selectedTab else { return } finishEditingAndSubmit(url, visitType: VisitType.typed, forTab: tab) } func searchViewController(_ searchViewController: SearchViewController, didLongPressSuggestion suggestion: String) { self.urlBar.setLocation(suggestion, search: true) } func presentSearchSettingsController() { let ThemedNavigationController = SearchSettingsTableViewController() ThemedNavigationController.model = self.profile.searchEngines ThemedNavigationController.profile = self.profile let navController = ModalSettingsNavigationController(rootViewController: ThemedNavigationController) self.present(navController, animated: true, completion: nil) } func searchViewController(_ searchViewController: SearchViewController, didHighlightText text: String, search: Bool) { self.urlBar.setLocation(text, search: search) } } extension BrowserViewController: TabManagerDelegate { func tabManager(_ tabManager: TabManager, didSelectedTabChange selected: Tab?, previous: Tab?, isRestoring: Bool) { // Remove the old accessibilityLabel. Since this webview shouldn't be visible, it doesn't need it // and having multiple views with the same label confuses tests. if let wv = previous?.webView { wv.endEditing(true) wv.accessibilityLabel = nil wv.accessibilityElementsHidden = true wv.accessibilityIdentifier = nil wv.removeFromSuperview() } if let tab = selected, let webView = tab.webView { updateURLBarDisplayURL(tab) if previous == nil || tab.isPrivate != previous?.isPrivate { applyTheme() let ui: [PrivateModeUI?] = [toolbar, topTabsViewController, urlBar] ui.forEach { $0?.applyUIMode(isPrivate: tab.isPrivate) } } readerModeCache = tab.isPrivate ? MemoryReaderModeCache.sharedInstance : DiskReaderModeCache.sharedInstance if let privateModeButton = topTabsViewController?.privateModeButton, previous != nil && previous?.isPrivate != tab.isPrivate { privateModeButton.setSelected(tab.isPrivate, animated: true) } ReaderModeHandlers.readerModeCache = readerModeCache scrollController.tab = selected webViewContainer.addSubview(webView) webView.snp.makeConstraints { make in make.left.right.top.bottom.equalTo(self.webViewContainer) } webView.accessibilityLabel = NSLocalizedString("Web content", comment: "Accessibility label for the main web content view") webView.accessibilityIdentifier = "contentView" webView.accessibilityElementsHidden = false if webView.url == nil { // The web view can go gray if it was zombified due to memory pressure. // When this happens, the URL is nil, so try restoring the page upon selection. tab.reload() } } updateTabCountUsingTabManager(tabManager) removeAllBars() if let bars = selected?.bars { for bar in bars { showBar(bar, animated: true) } } updateFindInPageVisibility(visible: false, tab: previous) navigationToolbar.updateReloadStatus(selected?.loading ?? false) navigationToolbar.updateBackStatus(selected?.canGoBack ?? false) navigationToolbar.updateForwardStatus(selected?.canGoForward ?? false) if !(selected?.webView?.url?.isLocalUtility ?? false) { self.urlBar.updateProgressBar(Float(selected?.estimatedProgress ?? 0)) } if let readerMode = selected?.getContentScript(name: ReaderMode.name()) as? ReaderMode { urlBar.updateReaderModeState(readerMode.state) if readerMode.state == .active { showReaderModeBar(animated: false) } else { hideReaderModeBar(animated: false) } } else { urlBar.updateReaderModeState(ReaderModeState.unavailable) } if topTabsVisible { topTabsDidChangeTab() } updateInContentHomePanel(selected?.url as URL?) if let tab = selected, tab.url == nil, !tab.restoring, NewTabAccessors.getNewTabPage(self.profile.prefs) == .blankPage { self.urlBar.tabLocationViewDidTapLocation(self.urlBar.locationView) } } func tabManager(_ tabManager: TabManager, willAddTab tab: Tab) { } func tabManager(_ tabManager: TabManager, didAddTab tab: Tab, isRestoring: Bool) { // If we are restoring tabs then we update the count once at the end if !isRestoring { updateTabCountUsingTabManager(tabManager) } tab.tabDelegate = self } func tabManager(_ tabManager: TabManager, willRemoveTab tab: Tab) { if let url = tab.url, !url.isAboutURL && !tab.isPrivate { profile.recentlyClosedTabs.addTab(url as URL, title: tab.title, faviconURL: tab.displayFavicon?.url) } } func tabManager(_ tabManager: TabManager, didRemoveTab tab: Tab, isRestoring: Bool) { updateTabCountUsingTabManager(tabManager) } func tabManagerDidAddTabs(_ tabManager: TabManager) { updateTabCountUsingTabManager(tabManager) } func tabManagerDidRestoreTabs(_ tabManager: TabManager) { updateTabCountUsingTabManager(tabManager) } func show(toast: Toast, afterWaiting delay: DispatchTimeInterval = SimpleToastUX.ToastDelayBefore, duration: DispatchTimeInterval? = SimpleToastUX.ToastDismissAfter) { if let downloadToast = toast as? DownloadToast { self.downloadToast = downloadToast } // If BVC isnt visible hold on to this toast until viewDidAppear if self.view.window == nil { self.pendingToast = toast return } toast.showToast(viewController: self, delay: delay, duration: duration, makeConstraints: { make in make.left.right.equalTo(self.view) make.bottom.equalTo(self.webViewContainer?.safeArea.bottom ?? 0) }) } func tabManagerDidRemoveAllTabs(_ tabManager: TabManager, toast: ButtonToast?) { guard let toast = toast, !(tabTrayController?.tabDisplayManager.isPrivate ?? false) else { return } show(toast: toast, afterWaiting: ButtonToastUX.ToastDelay) } fileprivate func updateTabCountUsingTabManager(_ tabManager: TabManager, animated: Bool = true) { if let selectedTab = tabManager.selectedTab { let count = selectedTab.isPrivate ? tabManager.privateTabs.count : tabManager.normalTabs.count toolbar?.updateTabCount(count, animated: animated) urlBar.updateTabCount(count, animated: !urlBar.inOverlayMode) topTabsViewController?.updateTabCount(count, animated: animated) } } } // MARK: - UIPopoverPresentationControllerDelegate extension BrowserViewController: UIPopoverPresentationControllerDelegate { func popoverPresentationControllerDidDismissPopover(_ popoverPresentationController: UIPopoverPresentationController) { displayedPopoverController = nil updateDisplayedPopoverProperties = nil } } extension BrowserViewController: UIAdaptivePresentationControllerDelegate { // Returning None here makes sure that the Popover is actually presented as a Popover and // not as a full-screen modal, which is the default on compact device classes. func adaptivePresentationStyle(for controller: UIPresentationController, traitCollection: UITraitCollection) -> UIModalPresentationStyle { return .none } } extension BrowserViewController: IntroViewControllerDelegate { @discardableResult func presentIntroViewController(_ force: Bool = false, animated: Bool = true) -> Bool { if let deeplink = self.profile.prefs.stringForKey("AdjustDeeplinkKey"), let url = URL(string: deeplink) { self.launchFxAFromDeeplinkURL(url) return true } if force || profile.prefs.intForKey(PrefsKeys.IntroSeen) == nil { let introViewController = IntroViewController() introViewController.delegate = self // On iPad we present it modally in a controller if topTabsVisible { introViewController.preferredContentSize = CGSize(width: IntroUX.Width, height: IntroUX.Height) introViewController.modalPresentationStyle = .formSheet } present(introViewController, animated: animated) { // On first run (and forced) open up the homepage in the background. if let homePageURL = HomePageAccessors.getHomePage(self.profile.prefs), let tab = self.tabManager.selectedTab, DeviceInfo.hasConnectivity() { tab.loadRequest(URLRequest(url: homePageURL)) } } return true } return false } func launchFxAFromDeeplinkURL(_ url: URL) { self.profile.prefs.removeObjectForKey("AdjustDeeplinkKey") var query = url.getQuery() query["entrypoint"] = "adjust_deepklink_ios" let fxaParams: FxALaunchParams fxaParams = FxALaunchParams(query: query) self.presentSignInViewController(fxaParams) } func introViewControllerDidFinish(_ introViewController: IntroViewController, requestToLogin: Bool) { self.profile.prefs.setInt(1, forKey: PrefsKeys.IntroSeen) introViewController.dismiss(animated: true) { if self.navigationController?.viewControllers.count ?? 0 > 1 { _ = self.navigationController?.popToRootViewController(animated: true) } if requestToLogin { let fxaParams = FxALaunchParams(query: ["entrypoint": "firstrun"]) self.presentSignInViewController(fxaParams) } } } func presentSignInViewController(_ fxaOptions: FxALaunchParams? = nil) { // Show the settings page if we have already signed in. If we haven't then show the signin page let vcToPresent: UIViewController if profile.hasAccount(), let status = profile.getAccount()?.actionNeeded, status == .none { let settingsTableViewController = SyncContentSettingsViewController() settingsTableViewController.profile = profile vcToPresent = settingsTableViewController } else { let signInVC = FxAContentViewController(profile: profile, fxaOptions: fxaOptions) signInVC.delegate = self vcToPresent = signInVC } vcToPresent.navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(dismissSignInViewController)) let themedNavigationController = ThemedNavigationController(rootViewController: vcToPresent) themedNavigationController.modalPresentationStyle = .formSheet themedNavigationController.navigationBar.isTranslucent = false self.present(themedNavigationController, animated: true, completion: nil) } @objc func dismissSignInViewController() { self.dismiss(animated: true, completion: nil) } } extension BrowserViewController: FxAContentViewControllerDelegate { func contentViewControllerDidSignIn(_ viewController: FxAContentViewController, withFlags flags: FxALoginFlags) { if flags.verified { self.dismiss(animated: true, completion: nil) } } func contentViewControllerDidCancel(_ viewController: FxAContentViewController) { self.dismiss(animated: true, completion: nil) } } extension BrowserViewController: ContextMenuHelperDelegate { func contextMenuHelper(_ contextMenuHelper: ContextMenuHelper, didLongPressElements elements: ContextMenuHelper.Elements, gestureRecognizer: UIGestureRecognizer) { // locationInView can return (0, 0) when the long press is triggered in an invalid page // state (e.g., long pressing a link before the document changes, then releasing after a // different page loads). let touchPoint = gestureRecognizer.location(in: view) guard touchPoint != CGPoint.zero else { return } let touchSize = CGSize(width: 0, height: 16) let actionSheetController = AlertController(title: nil, message: nil, preferredStyle: .actionSheet) var dialogTitle: String? if let url = elements.link, let currentTab = tabManager.selectedTab { dialogTitle = url.absoluteString let isPrivate = currentTab.isPrivate let addTab = { (rURL: URL, isPrivate: Bool) in let tab = self.tabManager.addTab(URLRequest(url: rURL as URL), afterTab: currentTab, isPrivate: isPrivate) LeanPlumClient.shared.track(event: .openedNewTab, withParameters: ["Source": "Long Press Context Menu"]) guard !self.topTabsVisible else { return } // We're not showing the top tabs; show a toast to quick switch to the fresh new tab. let toast = ButtonToast(labelText: Strings.ContextMenuButtonToastNewTabOpenedLabelText, buttonText: Strings.ContextMenuButtonToastNewTabOpenedButtonText, completion: { buttonPressed in if buttonPressed { self.tabManager.selectTab(tab) } }) self.show(toast: toast) } if !isPrivate { let newTabTitle = NSLocalizedString("Open in New Tab", comment: "Context menu item for opening a link in a new tab") let openNewTabAction = UIAlertAction(title: newTabTitle, style: .default) { _ in addTab(url, false) } actionSheetController.addAction(openNewTabAction, accessibilityIdentifier: "linkContextMenu.openInNewTab") } let openNewPrivateTabTitle = NSLocalizedString("Open in New Private Tab", tableName: "PrivateBrowsing", comment: "Context menu option for opening a link in a new private tab") let openNewPrivateTabAction = UIAlertAction(title: openNewPrivateTabTitle, style: .default) { _ in addTab(url, true) } actionSheetController.addAction(openNewPrivateTabAction, accessibilityIdentifier: "linkContextMenu.openInNewPrivateTab") let downloadTitle = NSLocalizedString("Download Link", comment: "Context menu item for downloading a link URL") let downloadAction = UIAlertAction(title: downloadTitle, style: .default) { _ in self.pendingDownloadWebView = currentTab.webView currentTab.webView?.evaluateJavaScript("window.__firefox__.download('\(url.absoluteString)', '\(UserScriptManager.securityToken)')") UnifiedTelemetry.recordEvent(category: .action, method: .tap, object: .downloadLinkButton) } actionSheetController.addAction(downloadAction, accessibilityIdentifier: "linkContextMenu.download") let copyTitle = NSLocalizedString("Copy Link", comment: "Context menu item for copying a link URL to the clipboard") let copyAction = UIAlertAction(title: copyTitle, style: .default) { _ in UIPasteboard.general.url = url as URL } actionSheetController.addAction(copyAction, accessibilityIdentifier: "linkContextMenu.copyLink") let shareTitle = NSLocalizedString("Share Link", comment: "Context menu item for sharing a link URL") let shareAction = UIAlertAction(title: shareTitle, style: .default) { _ in self.presentActivityViewController(url as URL, sourceView: self.view, sourceRect: CGRect(origin: touchPoint, size: touchSize), arrowDirection: .any) } actionSheetController.addAction(shareAction, accessibilityIdentifier: "linkContextMenu.share") } if let url = elements.image { if dialogTitle == nil { dialogTitle = url.absoluteString } let photoAuthorizeStatus = PHPhotoLibrary.authorizationStatus() let saveImageTitle = NSLocalizedString("Save Image", comment: "Context menu item for saving an image") let saveImageAction = UIAlertAction(title: saveImageTitle, style: .default) { _ in if photoAuthorizeStatus == .authorized || photoAuthorizeStatus == .notDetermined { self.getImageData(url as URL) { data in PHPhotoLibrary.shared().performChanges({ PHAssetCreationRequest.forAsset().addResource(with: .photo, data: data, options: nil) }) } } else { let accessDenied = UIAlertController(title: NSLocalizedString("Firefox would like to access your Photos", comment: "See http://mzl.la/1G7uHo7"), message: NSLocalizedString("This allows you to save the image to your Camera Roll.", comment: "See http://mzl.la/1G7uHo7"), preferredStyle: .alert) let dismissAction = UIAlertAction(title: Strings.CancelString, style: .default, handler: nil) accessDenied.addAction(dismissAction) let settingsAction = UIAlertAction(title: NSLocalizedString("Open Settings", comment: "See http://mzl.la/1G7uHo7"), style: .default ) { _ in UIApplication.shared.open(URL(string: UIApplicationOpenSettingsURLString)!, options: [:]) } accessDenied.addAction(settingsAction) self.present(accessDenied, animated: true, completion: nil) } } actionSheetController.addAction(saveImageAction, accessibilityIdentifier: "linkContextMenu.saveImage") let copyImageTitle = NSLocalizedString("Copy Image", comment: "Context menu item for copying an image to the clipboard") let copyAction = UIAlertAction(title: copyImageTitle, style: .default) { _ in // put the actual image on the clipboard // do this asynchronously just in case we're in a low bandwidth situation let pasteboard = UIPasteboard.general pasteboard.url = url as URL let changeCount = pasteboard.changeCount let application = UIApplication.shared var taskId: UIBackgroundTaskIdentifier = 0 taskId = application.beginBackgroundTask (expirationHandler: { application.endBackgroundTask(taskId) }) Alamofire.request(url).validate(statusCode: 200..<300).response { response in // Only set the image onto the pasteboard if the pasteboard hasn't changed since // fetching the image; otherwise, in low-bandwidth situations, // we might be overwriting something that the user has subsequently added. if changeCount == pasteboard.changeCount, let imageData = response.data, response.error == nil { pasteboard.addImageWithData(imageData, forURL: url) } application.endBackgroundTask(taskId) } } actionSheetController.addAction(copyAction, accessibilityIdentifier: "linkContextMenu.copyImage") } // If we're showing an arrow popup, set the anchor to the long press location. if let popoverPresentationController = actionSheetController.popoverPresentationController { popoverPresentationController.sourceView = view popoverPresentationController.sourceRect = CGRect(origin: touchPoint, size: touchSize) popoverPresentationController.permittedArrowDirections = .any popoverPresentationController.delegate = self } if actionSheetController.popoverPresentationController != nil { displayedPopoverController = actionSheetController } actionSheetController.title = dialogTitle?.ellipsize(maxLength: ActionSheetTitleMaxLength) let cancelAction = UIAlertAction(title: Strings.CancelString, style: UIAlertActionStyle.cancel, handler: nil) actionSheetController.addAction(cancelAction) self.present(actionSheetController, animated: true, completion: nil) } fileprivate func getImageData(_ url: URL, success: @escaping (Data) -> Void) { Alamofire.request(url).validate(statusCode: 200..<300).response { response in if let data = response.data { success(data) } } } func contextMenuHelper(_ contextMenuHelper: ContextMenuHelper, didCancelGestureRecognizer: UIGestureRecognizer) { displayedPopoverController?.dismiss(animated: true) { self.displayedPopoverController = nil } } } extension BrowserViewController { @objc func image(_ image: UIImage, didFinishSavingWithError error: NSError?, contextInfo: UnsafeRawPointer) { if error == nil { LeanPlumClient.shared.track(event: .saveImage) } } } extension BrowserViewController: HistoryStateHelperDelegate { func historyStateHelper(_ historyStateHelper: HistoryStateHelper, didPushOrReplaceStateInTab tab: Tab) { navigateInTab(tab: tab) tabManager.storeChanges() } } /** A third party search engine Browser extension **/ extension BrowserViewController { func addCustomSearchButtonToWebView(_ webView: WKWebView) { //check if the search engine has already been added. let domain = webView.url?.domainURL.host let matches = self.profile.searchEngines.orderedEngines.filter {$0.shortName == domain} if !matches.isEmpty { self.customSearchEngineButton.tintColor = UIColor.Photon.Grey50 self.customSearchEngineButton.isUserInteractionEnabled = false } else { self.customSearchEngineButton.tintColor = UIConstants.SystemBlueColor self.customSearchEngineButton.isUserInteractionEnabled = true } /* This is how we access hidden views in the WKContentView Using the public headers we can find the keyboard accessoryView which is not usually available. Specific values here are from the WKContentView headers. https://github.com/JaviSoto/iOS9-Runtime-Headers/blob/master/Frameworks/WebKit.framework/WKContentView.h */ guard let webContentView = UIView.findSubViewWithFirstResponder(webView) else { /* In some cases the URL bar can trigger the keyboard notification. In that case the webview isnt the first responder and a search button should not be added. */ return } guard let input = webContentView.perform(#selector(getter: UIResponder.inputAccessoryView)), let inputView = input.takeUnretainedValue() as? UIInputView, let nextButton = inputView.value(forKey: "_nextItem") as? UIBarButtonItem, let nextButtonView = nextButton.value(forKey: "view") as? UIView else { //failed to find the inputView instead lets use the inputAssistant addCustomSearchButtonToInputAssistant(webContentView) return } inputView.addSubview(self.customSearchEngineButton) self.customSearchEngineButton.snp.remakeConstraints { make in make.leading.equalTo(nextButtonView.snp.trailing).offset(20) make.width.equalTo(inputView.snp.height) make.top.equalTo(nextButtonView.snp.top) make.height.equalTo(inputView.snp.height) } } /** This adds the customSearchButton to the inputAssistant for cases where the inputAccessoryView could not be found for example on the iPad where it does not exist. However this only works on iOS9 **/ func addCustomSearchButtonToInputAssistant(_ webContentView: UIView) { guard customSearchBarButton == nil else { return //The searchButton is already on the keyboard } let inputAssistant = webContentView.inputAssistantItem let item = UIBarButtonItem(customView: customSearchEngineButton) customSearchBarButton = item _ = Try(withTry: { inputAssistant.trailingBarButtonGroups.last?.barButtonItems.append(item) }) { (exception) in Sentry.shared.send(message: "Failed adding custom search button to input assistant", tag: .general, severity: .error, description: "\(exception ??? "nil")") } } @objc func addCustomSearchEngineForFocusedElement() { guard let webView = tabManager.selectedTab?.webView else { return } webView.evaluateJavaScript("__firefox__.searchQueryForField()") { (result, _) in guard let searchQuery = result as? String, let favicon = self.tabManager.selectedTab!.displayFavicon else { //Javascript responded with an incorrectly formatted message. Show an error. let alert = ThirdPartySearchAlerts.failedToAddThirdPartySearch() self.present(alert, animated: true, completion: nil) return } self.addSearchEngine(searchQuery, favicon: favicon) self.customSearchEngineButton.tintColor = UIColor.Photon.Grey50 self.customSearchEngineButton.isUserInteractionEnabled = false } } func addSearchEngine(_ searchQuery: String, favicon: Favicon) { guard searchQuery != "", let iconURL = URL(string: favicon.url), let url = URL(string: searchQuery.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlFragmentAllowed)!), let shortName = url.domainURL.host else { let alert = ThirdPartySearchAlerts.failedToAddThirdPartySearch() self.present(alert, animated: true, completion: nil) return } let alert = ThirdPartySearchAlerts.addThirdPartySearchEngine { alert in self.customSearchEngineButton.tintColor = UIColor.Photon.Grey50 self.customSearchEngineButton.isUserInteractionEnabled = false SDWebImageManager.shared().loadImage(with: iconURL, options: .continueInBackground, progress: nil) { (image, _, _, _, _, _) in guard let image = image else { let alert = ThirdPartySearchAlerts.failedToAddThirdPartySearch() self.present(alert, animated: true, completion: nil) return } self.profile.searchEngines.addSearchEngine(OpenSearchEngine(engineID: nil, shortName: shortName, image: image, searchTemplate: searchQuery, suggestTemplate: nil, isCustomEngine: true)) let Toast = SimpleToast() Toast.showAlertWithText(Strings.ThirdPartySearchEngineAdded, bottomContainer: self.webViewContainer) } } self.present(alert, animated: true, completion: {}) } } extension BrowserViewController: KeyboardHelperDelegate { func keyboardHelper(_ keyboardHelper: KeyboardHelper, keyboardWillShowWithState state: KeyboardState) { keyboardState = state updateViewConstraints() UIView.animate(withDuration: state.animationDuration) { UIView.setAnimationCurve(state.animationCurve) self.alertStackView.layoutIfNeeded() } guard let webView = tabManager.selectedTab?.webView else { return } webView.evaluateJavaScript("__firefox__.searchQueryForField()") { (result, _) in guard let _ = result as? String else { return } self.addCustomSearchButtonToWebView(webView) } } func keyboardHelper(_ keyboardHelper: KeyboardHelper, keyboardDidShowWithState state: KeyboardState) { } func keyboardHelper(_ keyboardHelper: KeyboardHelper, keyboardWillHideWithState state: KeyboardState) { keyboardState = nil updateViewConstraints() //If the searchEngineButton exists remove it form the keyboard if let buttonGroup = customSearchBarButton?.buttonGroup { buttonGroup.barButtonItems = buttonGroup.barButtonItems.filter { $0 != customSearchBarButton } customSearchBarButton = nil } if self.customSearchEngineButton.superview != nil { self.customSearchEngineButton.removeFromSuperview() } UIView.animate(withDuration: state.animationDuration) { UIView.setAnimationCurve(state.animationCurve) self.alertStackView.layoutIfNeeded() } } } extension BrowserViewController: SessionRestoreHelperDelegate { func sessionRestoreHelper(_ helper: SessionRestoreHelper, didRestoreSessionForTab tab: Tab) { tab.restoring = false if let tab = tabManager.selectedTab, tab.webView === tab.webView { updateUIForReaderHomeStateForTab(tab) } } } extension BrowserViewController: TabTrayDelegate { // This function animates and resets the tab chrome transforms when // the tab tray dismisses. func tabTrayDidDismiss(_ tabTray: TabTrayController) { resetBrowserChrome() } func tabTrayDidAddTab(_ tabTray: TabTrayController, tab: Tab) {} func tabTrayDidAddBookmark(_ tab: Tab) { guard let url = tab.url?.absoluteString, !url.isEmpty else { return } self.addBookmark(tab.tabState) } func tabTrayDidAddToReadingList(_ tab: Tab) -> ReadingListItem? { guard let url = tab.url?.absoluteString, !url.isEmpty else { return nil } return profile.readingList.createRecordWithURL(url, title: tab.title ?? url, addedBy: UIDevice.current.name).value.successValue } func tabTrayRequestsPresentationOf(_ viewController: UIViewController) { self.present(viewController, animated: false, completion: nil) } } // MARK: Browser Chrome Theming extension BrowserViewController: Themeable { func applyTheme() { let ui: [Themeable?] = [urlBar, toolbar, readerModeBar, topTabsViewController, homePanelController, searchController] ui.forEach { $0?.applyTheme() } statusBarOverlay.backgroundColor = shouldShowTopTabsForTraitCollection(traitCollection) ? UIColor.Photon.Grey80 : urlBar.backgroundColor setNeedsStatusBarAppearanceUpdate() (presentedViewController as? Themeable)?.applyTheme() } } extension BrowserViewController: JSPromptAlertControllerDelegate { func promptAlertControllerDidDismiss(_ alertController: JSPromptAlertController) { showQueuedAlertIfAvailable() } } extension BrowserViewController: TopTabsDelegate { func topTabsDidPressTabs() { urlBar.leaveOverlayMode(didCancel: true) self.urlBarDidPressTabs(urlBar) } func topTabsDidPressNewTab(_ isPrivate: Bool) { openBlankNewTab(focusLocationField: false, isPrivate: isPrivate) } func topTabsDidTogglePrivateMode() { guard let _ = tabManager.selectedTab else { return } urlBar.leaveOverlayMode() } func topTabsDidChangeTab() { urlBar.leaveOverlayMode(didCancel: true) } } extension BrowserViewController: ClientPickerViewControllerDelegate, InstructionsViewControllerDelegate { func instructionsViewControllerDidClose(_ instructionsViewController: InstructionsViewController) { self.popToBVC() } func clientPickerViewControllerDidCancel(_ clientPickerViewController: ClientPickerViewController) { self.popToBVC() } func clientPickerViewController(_ clientPickerViewController: ClientPickerViewController, didPickClients clients: [RemoteClient]) { guard let tab = tabManager.selectedTab, let url = tab.canonicalURL?.displayURL?.absoluteString else { return } let shareItem = ShareItem(url: url, title: tab.title, favicon: tab.displayFavicon) guard shareItem.isShareable else { let alert = UIAlertController(title: Strings.SendToErrorTitle, message: Strings.SendToErrorMessage, preferredStyle: .alert) alert.addAction(UIAlertAction(title: Strings.SendToErrorOKButton, style: .default) { _ in self.popToBVC()}) present(alert, animated: true, completion: nil) return } profile.sendItem(shareItem, toClients: clients).uponQueue(.main) { _ in self.popToBVC() } } }
apache-2.0
415c9a167ff23e16f15a5d6cddf8de5b
42.976026
406
0.666131
5.77693
false
false
false
false
ZackKingS/Tasks
task/Classes/Others/Lib/TakePhoto/PhotoPickerController.swift
2
2624
// // PhotoPickerController.swift // PhotoPicker // // Created by liangqi on 16/3/5. // Copyright © 2016年 dailyios. All rights reserved. // import UIKit import Photos enum PageType{ case List case RecentAlbum case AllAlbum } protocol PhotoPickerControllerDelegate: class{ func onImageSelectFinished(images: [PHAsset]) } class PhotoPickerController: UINavigationController { // the select image max number static var imageMaxSelectedNum = 4 // already select total static var alreadySelectedImageNum = 0 weak var imageSelectDelegate: PhotoPickerControllerDelegate? override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) } init(type:PageType){ let rootViewController = PhotoAlbumsTableViewController(style:.plain) // clear cache PhotoImage.instance.selectedImage.removeAll() super.init(rootViewController: rootViewController) if type == .RecentAlbum || type == .AllAlbum { let currentType = type == .RecentAlbum ? PHAssetCollectionSubtype.smartAlbumRecentlyAdded : PHAssetCollectionSubtype.smartAlbumUserLibrary let results = PHAssetCollection.fetchAssetCollections(with: .smartAlbum, subtype:currentType, options: nil) if results.count > 0 { if let model = self.getModel(collection: results[0]) { if model.count > 0 { let layout = PhotoCollectionViewController.configCustomCollectionLayout() let controller = PhotoCollectionViewController(collectionViewLayout: layout) controller.fetchResult = model as? PHFetchResult<PHObject>; self.pushViewController(controller, animated: false) } } } } } private func getModel(collection: PHAssetCollection) -> PHFetchResult<PHAsset>?{ let fetchResult = PHAsset.fetchAssets(in: collection, options: PhotoFetchOptions.shareInstance) if fetchResult.count > 0 { return fetchResult } return nil } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } func imageSelectFinish(){ if self.imageSelectDelegate != nil { self.dismiss(animated: true, completion: nil) self.imageSelectDelegate?.onImageSelectFinished(images: PhotoImage.instance.selectedImage) } } }
apache-2.0
3e288a41c7dfa94a42c75975fb43530c
30.202381
150
0.642884
5.471816
false
false
false
false
bizz84/ReviewTime
ReviewTime/Own/NHView.swift
3
689
// // NHView.swift // ReviewTime // // Created by Nathan Hegedus on 25/05/15. // Copyright (c) 2015 Nathan Hegedus. All rights reserved. // import UIKit class NHView: UIView { @IBInspectable var isCircle: Bool = false { didSet { if isCircle { self.layer.cornerRadius = self.frame.size.width/2 } } } @IBInspectable var borderWidth: CGFloat = 0 { didSet { self.layer.borderWidth = borderWidth } } @IBInspectable var borderColorHexa: String = "" { didSet { self.layer.borderColor = UIColor(hexa: borderColorHexa, alpha: 1.0).CGColor } } }
mit
d7dd521c4297258e4f9aaa0d33c419e0
19.878788
87
0.561684
4.052941
false
false
false
false
kickstarter/Kickstarter-Prelude
Prelude-UIKit/lenses/UITextInputTraitsLenses.swift
1
1846
import Prelude import UIKit public protocol UITextInputTraitsProtocol: NSObjectProtocol { var autocapitalizationType: UITextAutocapitalizationType { get set } var autocorrectionType: UITextAutocorrectionType { get set } var keyboardAppearance: UIKeyboardAppearance { get set } var keyboardType: UIKeyboardType { get set } var returnKeyType: UIReturnKeyType { get set } var isSecureTextEntry: Bool { get set } var spellCheckingType: UITextSpellCheckingType { get set } } public extension LensHolder where Object: UITextInputTraitsProtocol { public var autocapitalizationType: Lens<Object, UITextAutocapitalizationType> { return Lens( view: { $0.autocapitalizationType }, set: { $1.autocapitalizationType = $0; return $1 } ) } public var autocorrectionType: Lens<Object, UITextAutocorrectionType> { return Lens( view: { $0.autocorrectionType }, set: { $1.autocorrectionType = $0; return $1 } ) } public var keyboardAppearance: Lens<Object, UIKeyboardAppearance> { return Lens( view: { $0.keyboardAppearance }, set: { $1.keyboardAppearance = $0; return $1 } ) } public var keyboardType: Lens<Object, UIKeyboardType> { return Lens( view: { $0.keyboardType }, set: { $1.keyboardType = $0; return $1 } ) } public var returnKeyType: Lens<Object, UIReturnKeyType> { return Lens( view: { $0.returnKeyType }, set: { $1.returnKeyType = $0; return $1 } ) } public var secureTextEntry: Lens<Object, Bool> { return Lens( view: { $0.isSecureTextEntry }, set: { $1.isSecureTextEntry = $0; return $1 } ) } public var spellCheckingType: Lens<Object, UITextSpellCheckingType> { return Lens( view: { $0.spellCheckingType }, set: { $1.spellCheckingType = $0; return $1 } ) } }
apache-2.0
988a4b3d29cf976d7823e9a891f9739a
28.301587
81
0.675515
4.513447
false
false
false
false
BeezleLabs/HackerTracker-iOS
hackertracker/HTSpeakerViewController.swift
1
6991
// // HTSpeakerViewController.swift // hackertracker // // Created by Seth Law on 8/6/18. // Copyright © 2018 Beezle Labs. All rights reserved. // import SafariServices import UIKit class HTSpeakerViewController: UIViewController, UIViewControllerTransitioningDelegate, UITableViewDataSource, UITableViewDelegate, EventCellDelegate { @IBOutlet private var twitterButton: UIButton! @IBOutlet private var talkButton: UIButton! @IBOutlet private var nameLabel: UILabel! @IBOutlet private var bioLabel: UILabel! @IBOutlet private var vertStackView: UIStackView! @IBOutlet private var eventTableView: UITableView! @IBOutlet private var eventTableHeightConstraint: NSLayoutConstraint! var eventTokens: [UpdateToken] = [] var events: [UserEventModel] = [] var speaker: HTSpeaker? override func viewDidLoad() { super.viewDidLoad() if let speaker = speaker { nameLabel.text = speaker.name bioLabel.text = speaker.description bioLabel.sizeToFit() eventTableView.register(UINib(nibName: "EventCell", bundle: nil), forCellReuseIdentifier: "EventCell") eventTableView.register(UINib(nibName: "UpdateCell", bundle: nil), forCellReuseIdentifier: "UpdateCell") eventTableView.delegate = self eventTableView.dataSource = self eventTableView.backgroundColor = UIColor.clear eventTableView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0) addEventList() twitterButton.isHidden = true if !speaker.twitter.isEmpty { twitterButton.setTitle(speaker.twitter, for: .normal) twitterButton.isHidden = false } self.eventTableView.reloadData() self.vertStackView.layoutSubviews() } } func addEventList() { var idx = 0 for eventModel in speaker?.events ?? [] { if eventTokens.indices.contains(idx) { // NSLog("Already an eventtoken for event \(e.title)") } else { let eToken = FSConferenceDataController.shared.requestEvents(forConference: AnonymousSession.shared.currentConference, eventId: eventModel.id) { result in switch result { case .success(let event): if self.events.contains(event), let idx = self.events.firstIndex(of: event) { self.events.remove(at: idx) self.events.insert(event, at: idx) } else { self.events.append(event) } self.eventTableView.reloadData() self.vertStackView.layoutSubviews() case .failure: // TODO: Properly log failure break } } eventTokens.append(eToken) } idx += 1 } if let speaker = speaker { if !speaker.events.isEmpty { eventTableHeightConstraint.constant = CGFloat(speaker.events.count * 200) } else { eventTableHeightConstraint.constant = 100 } } } @IBAction private func twitterTapped(_ sender: Any) { if let twit = speaker?.twitter { if let url = URL(string: "https://mobile.twitter.com/\(twit.replacingOccurrences(of: "@", with: ""))") { let controller = SFSafariViewController(url: url) controller.preferredBarTintColor = .backgroundGray controller.preferredControlTintColor = .white present(controller, animated: true) } } } override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { super.viewWillTransition(to: size, with: coordinator) } // MARK: - Navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "eventSegue" { let destController: HTEventDetailViewController if let destinationNav = segue.destination as? UINavigationController, let controller = destinationNav.viewControllers.first as? HTEventDetailViewController { destController = controller } else { destController = segue.destination as! HTEventDetailViewController } if let speaker = speaker { let events = speaker.events if !events.isEmpty { destController.event = events[0] } } destController.transitioningDelegate = self } } // Table Functions func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if !events.isEmpty { return events.count } else { return 1 } } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { if !events.isEmpty { let cell = tableView.dequeueReusableCell(withIdentifier: "EventCell", for: indexPath) as! EventCell let event = events[indexPath.row] cell.bind(userEvent: event) cell.eventCellDelegate = self return cell } else { let cell = tableView.dequeueReusableCell(withIdentifier: "UpdateCell") as! UpdateCell cell.bind(title: "404 - Not Found", desc: "No events found for this speaker, check with the #hackertracker team") return cell } } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if let speaker = speaker, !speaker.events.isEmpty { let event: UserEventModel = events[indexPath.row] if let storyboard = self.storyboard, let eventController = storyboard.instantiateViewController(withIdentifier: "HTEventDetailViewController") as? HTEventDetailViewController { eventController.event = event.event eventController.bookmark = event.bookmark self.navigationItem.backBarButtonItem = UIBarButtonItem(title: " ", style: .plain, target: nil, action: nil) self.navigationController?.pushViewController(eventController, animated: true) } } } func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat { return 75 } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return UITableView.automaticDimension } func numberOfSections(in tableView: UITableView) -> Int { return 1 } // Event Cell Delegate func updatedEvents() { // self.addEventList() self.eventTableView.reloadData() } }
gpl-2.0
fc166314d9dc5c5605a58bb5dd610b66
37.833333
188
0.608155
5.556439
false
false
false
false
lakesoft/LKUserDefaultOption
Pod/Classes/LKUserDefaultOptionSingleSelectionViewController.swift
1
1842
// // LKUserDefaultModelSelectionViewController.swift // VideoEver // // Created by Hiroshi Hashiguchi on 2015/07/19. // Copyright (c) 2015年 lakesoft. All rights reserved. // import UIKit public class LKUserDefaultOptionSingleSelectionViewController: UITableViewController { var model:LKUserDefaultOptionModel! var selection: LKUserDefaultOptionSingleSelection! public override func viewDidLoad() { super.viewDidLoad() title = model.titleLabel() tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "LKUserDefaultModelSingleSelectionViewControllerCell") self.tableView.reloadData() } // MARK: - Table view data source public override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return selection.numberOfRows(section) } public override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("LKUserDefaultModelSingleSelectionViewControllerCell", forIndexPath: indexPath) cell.textLabel!.text = selection.label(indexPath) cell.accessoryType = selection.isSelected(indexPath) ? .Checkmark : .None return cell } public override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { let indexPaths:[NSIndexPath] = [indexPath, selection.selectedIndexPath] selection.selectedIndexPath = indexPath model.save() tableView.reloadRowsAtIndexPaths(indexPaths, withRowAnimation: UITableViewRowAnimation.None) if selection.closeWhenSelected() { self.navigationController?.popViewControllerAnimated(true) } } }
mit
3565dc011cb0d3d376046b13f40b57e1
35.078431
142
0.722826
5.84127
false
false
false
false
chicio/Exploring-SceneKit
ExploringSceneKit/Model/Scenes/Collada/ColladaScene.swift
1
2860
// // ColladaScene.swift // ExploringSceneKit // // Created by Fabrizio Duroni on 28.08.17. // import SceneKit class ColladaScene: SCNScene, Scene { var colladaFileContents: SCNScene! var camera: Camera! var home: SCNNode! var light: SCNNode! override init() { super.init() colladaFileContents = ColladaLoader.loadFromSCNAssetsAColladaFileWith(name: "house") createCamera() createLights() createObjects() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } //MARK: Camera func createCamera() { camera = Camera(cameraNode: colladaFileContents.rootNode.childNode(withName: "Camera", recursively: true)!) rootNode.addChildNode(camera.node) } //MARK: Light func createLights() { colladaFileContents.rootNode.enumerateChildNodes { node, stop in if node.name?.contains("Light") == true { rootNode.addChildNode(node) } } } //MARK: Objects private func createObjects() { addHome() addFloor() addBackground() pointCameraToHome() } private func addHome() { home = colladaFileContents.rootNode.childNode(withName: "home", recursively: true)! rootNode.addChildNode(colladaFileContents.rootNode.childNode(withName: "home", recursively: true)!) } private func addFloor() { rootNode.addChildNode( OpaqueFloor( material: BlinnPhongMaterial( ambient: 0.0, diffuse: BlinnPhongDiffuseMaterialComponent( value: UIColor(red: 67.0/255.0, green: 100.0/255.0, blue: 31.0/255.0, alpha: 1.0) ), specular: 0.0 ), position: SCNVector3(0.0, 0.0, 0.0), rotation: SCNVector4(0.0, 0.0, 0.0, 0.0) ).node ) } private func addBackground() { background.contents = ["right.png", "left.png", "up.png", "down.png", "back.png", "front.png"] } private func pointCameraToHome() { camera.node.constraints = [SCNLookAtConstraint(target: home)] } //MARK: Gestures func actionForOnefingerGesture(withLocation location: CGPoint, andHitResult hitResult: [Any]!) { let moveInFrontAnimation = MoveAnimationFactory.makeMoveTo(position: SCNVector3(0.0, 0.5, 15.0), time: 5) let moveLeftAnimation = MoveAnimationFactory.makeMoveTo(position: SCNVector3(-6.0, 0.5, 15.0), time: 5) self.camera.node.addAnimation( AnimationGroupFactory.makeGroupWith(animations: [moveInFrontAnimation, moveLeftAnimation], time: 10.0), forKey: nil ) } }
mit
6bc2eea55e87ac2836f2acb22b074e2c
29.752688
115
0.591958
4.313725
false
false
false
false
ashfurrow/pragma-2015-rx-workshop
Session 4/Entities Demo/Entities Demo/AppDelegate.swift
2
3330
// // AppDelegate.swift // Entities Demo // // Created by Ash Furrow on 2015-10-08. // Copyright © 2015 Artsy. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate, UISplitViewControllerDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. let splitViewController = self.window!.rootViewController as! UISplitViewController let navigationController = splitViewController.viewControllers[splitViewController.viewControllers.count-1] as! UINavigationController navigationController.topViewController!.navigationItem.leftBarButtonItem = splitViewController.displayModeButtonItem() splitViewController.delegate = self return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } // MARK: - Split view func splitViewController(splitViewController: UISplitViewController, collapseSecondaryViewController secondaryViewController:UIViewController, ontoPrimaryViewController primaryViewController:UIViewController) -> Bool { guard let secondaryAsNavController = secondaryViewController as? UINavigationController else { return false } guard let topAsDetailController = secondaryAsNavController.topViewController as? DetailViewController else { return false } if topAsDetailController.detailItem == nil { // Return true to indicate that we have handled the collapse by doing nothing; the secondary controller will be discarded. return true } return false } }
mit
9e68f5f843946fa9992020aa6530a39f
53.57377
285
0.764794
6.199255
false
false
false
false
mlgoogle/wp
wp/General/Base/BaseTableViewController.swift
1
5426
// // BaseTableViewController.swift // viossvc // // Created by yaowang on 2016/10/27. // Copyright © 2016年 ywwlcom.yundian. All rights reserved. // import Foundation import SVProgressHUD class BaseTableViewController: UITableViewController , TableViewHelperProtocol { var tableViewHelper:TableViewHelper = TableViewHelper(); override func viewDidLoad() { super.viewDidLoad(); if tableView.tableFooterView == nil { tableView.tableFooterView = UIView(frame:CGRect(x: 0,y: 0,width: 0,height: 0.5)); } } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) AppDataHelper.instance().userCash() } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) checkUpdateVC() SVProgressHUD.dismiss() } //MARK:TableViewHelperProtocol func isCacheCellHeight() -> Bool { return false; } func isCalculateCellHeight() ->Bool { return isCacheCellHeight(); } func isSections() ->Bool { return false; } func tableView(_ tableView:UITableView ,cellIdentifierForRowAtIndexPath indexPath: IndexPath) -> String? { return tableViewHelper.tableView(tableView, cellIdentifierForRowAtIndexPath: indexPath, controller: self); } func tableView(_ tableView:UITableView ,cellDataForRowAtIndexPath indexPath: IndexPath) -> AnyObject? { return nil; } //MARK: -UITableViewDelegate override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { var cell:UITableViewCell? = super.tableView(tableView,cellForRowAt:indexPath); if cell == nil { cell = tableViewHelper.tableView(tableView, cellForRowAtIndexPath: indexPath, controller: self); } return cell!; } override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) { tableViewHelper.tableView(tableView, willDisplayCell: cell, forRowAtIndexPath: indexPath, controller: self); } override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { if( isCalculateCellHeight() ) { let cellHeight:CGFloat = tableViewHelper.tableView(tableView, heightForRowAtIndexPath: indexPath, controller: self); if( cellHeight != CGFloat.greatestFiniteMagnitude ) { return cellHeight; } } return super.tableView(tableView, heightForRowAt: indexPath); } } class BaseRefreshTableViewController :BaseTableViewController { override func viewDidLoad() { super.viewDidLoad(); self.setupRefreshControl(); } internal func completeBlockFunc()->CompleteBlock { return { [weak self] (obj) in self?.didRequestComplete(obj) } } internal func didRequestComplete(_ data:AnyObject?) { endRefreshing() self.tableView.reloadData() } override func didRequestError(_ error:NSError) { self.endRefreshing() super.didRequestError(error) } deinit { performSelectorRemoveRefreshControl(); } } class BaseListTableViewController :BaseRefreshTableViewController { internal var dataSource:Array<AnyObject>?; override func didRequestComplete(_ data: AnyObject?) { dataSource = data as? Array<AnyObject>; super.didRequestComplete(dataSource as AnyObject?); } //MARK: -UITableViewDelegate override func numberOfSections(in tableView: UITableView) -> Int { var count:Int = dataSource != nil ? 1 : 0; if isSections() && count != 0 { count = dataSource!.count; } return count; } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { var datas:Array<AnyObject>? = dataSource; if dataSource != nil && isSections() { datas = dataSource![section] as? Array<AnyObject>; } return datas == nil ? 0 : datas!.count; } //MARK:TableViewHelperProtocol override func tableView(_ tableView:UITableView ,cellDataForRowAtIndexPath indexPath: IndexPath) -> AnyObject? { var datas:Array<AnyObject>? = dataSource; if dataSource != nil && isSections() { datas = dataSource![indexPath.section] as? Array<AnyObject>; } return (datas != nil && datas!.count > indexPath.row ) ? datas![indexPath.row] : nil; } } class BasePageListTableViewController :BaseListTableViewController { override func viewDidLoad() { super.viewDidLoad(); setupLoadMore(); } override func didRequestComplete(_ data: AnyObject?) { tableViewHelper.didRequestComplete(&self.dataSource, pageDatas: data as? Array<AnyObject>, controller: self); super.didRequestComplete(self.dataSource as AnyObject?); } override func didRequestError(_ error:NSError) { if (!(self.pageIndex == 1) ) { self.errorLoadMore() } self.setIsLoadData(true) super.didRequestError(error) } deinit { removeLoadMore(); } }
apache-2.0
e81911e4bf1d7e5772ec61227b0b0af7
30.346821
128
0.638392
5.353406
false
false
false
false
swojtyna/starsview
StarsView/StarsViewTests/ImageDataImporterTests.swift
1
2996
// // ImageDataImporterTests.swift // StarsView // // Created by Sebastian Wojtyna on 30/08/16. // Copyright © 2016 Sebastian Wojtyna. All rights reserved. // import XCTest @testable import StarsView class ImageDataImporterTests: XCTestCase, LoadableTestStringFile { override class func setUp() { super.setUp() LSNocilla.sharedInstance().start() } override class func tearDown() { super.tearDown() LSNocilla.sharedInstance().stop() } override func tearDown() { LSNocilla.sharedInstance().clearStubs() } func testImportImageDataSuccess() { let expectation = self.expectationWithDescription("Success import all image data") let fakeRequest = ImagesListRequest() let fakeRequestURL = fakeRequest.buildRequest()!.URL!.absoluteString let filenameJSON = "imageList_success.json" let contentJSON = stringContentOfFile(filenameJSON, bundle: NSBundle(forClass: self.dynamicType)) stubRequest(fakeRequest.method, fakeRequestURL).withHeaders(fakeRequest.headers).andReturn(200).withBody(contentJSON) ImagesDataImporter().importDataList( success: { result in XCTAssertNotNil(result) expectation.fulfill() }, failure: { error in XCTAssertNil(error) }) waitForExpectationsWithTimeout(0.1, handler: nil) } func testImportImageDataJSONParseFailure() { let expectation = self.expectationWithDescription("JSON parse error during import all image data") let fakeRequest = ImagesListRequest() let fakeRequestURL = fakeRequest.buildRequest()!.URL!.absoluteString let filenameJSON = "imageList_jsonparse_failure.json" let contentJSON = stringContentOfFile(filenameJSON, bundle: NSBundle(forClass: self.dynamicType)) stubRequest(fakeRequest.method, fakeRequestURL).withHeaders(fakeRequest.headers).andReturn(200).withBody(contentJSON) ImagesDataImporter().importDataList( success: { result in XCTAssertNil(result) }, failure: { error in XCTAssertNotNil(error) expectation.fulfill() }) waitForExpectationsWithTimeout(0.1, handler: nil) } func testImportImageDataNotFoundFailure() { let expectation = self.expectationWithDescription("Not found 404 code during import all image data") let fakeRequest = ImagesListRequest() let fakeRequestURL = fakeRequest.buildRequest()!.URL!.absoluteString stubRequest(fakeRequest.method, fakeRequestURL).withHeaders(fakeRequest.headers).andReturn(404) ImagesDataImporter().importDataList( success: { result in XCTAssertNil(result) }, failure: { error in XCTAssertNotNil(error) expectation.fulfill() }) waitForExpectationsWithTimeout(0.1, handler: nil) } }
agpl-3.0
49f0bfeddccd5fe62a133b3c10121654
32.651685
125
0.667446
5.47532
false
true
false
false
renzifeng/ZFZhiHuDaily
ZFZhiHuDaily/NewsDatail/Controller/ZFNewsDetailViewController.swift
1
15226
// // ZFNewsDetailViewController.swift // ZFZhiHuDaily // // Created by 任子丰 on 16/1/12. // Copyright © 2016年 任子丰. All rights reserved. // import UIKit import NVActivityIndicatorView import Kingfisher import SKPhotoBrowser class ZFNewsDetailViewController: ZFBaseViewController { /// 容器view @IBOutlet weak var containerView: UIView! @IBOutlet weak var webView: UIWebView! @IBOutlet weak var zanBtn: ZanButton! @IBOutlet weak var commentBtn: UIButton! @IBOutlet weak var commentNumLabel: UILabel! @IBOutlet weak var zanNumLabel: UILabel! @IBOutlet weak var nextNewsBtn: UIButton! @IBOutlet weak var bottomView: UIView! /// 存放内容id的数组 var newsIdArray : [String]! /// 新闻id var newsId : String! var viewModel = ZFNewsDetailViewModel() var backgroundImg : UIImageView! /// top图片上的title var titleLabel : UILabel! /// 新闻额外信息 var newsExtra : ZFNewsExtra! /// loading var activityIndicatorView : NVActivityIndicatorView! /// 判断是否有图 var hasPic : Bool = false /// 是否正在加载 var isLoading : Bool = false /// headerView var headerView : ZFHeaderView! /// footerView var footerView : ZFFooterView! /// 是否为夜间模式 var isNight : Bool = false var tapGesture : UITapGestureRecognizer! // MARK: - life sycle override func viewDidLoad() { super.viewDidLoad() let mode = NSUserDefaults.standardUserDefaults().objectForKey("NightOrLightMode") as! String if mode == "light"{ //白天模式 isNight = false }else if mode == "night" { //夜间模式 isNight = true } setupUI() //赞 setupZan() viewModel.newsIdArray = self.newsIdArray getNewsWithId(self.newsId) bottomView.dk_backgroundColorPicker = BG_COLOR webView.dk_backgroundColorPicker = BG_COLOR view.dk_backgroundColorPicker = BG_COLOR tapGesture = UITapGestureRecognizer() tapGesture.addTarget(self, action: #selector(ZFNewsDetailViewController.tapAction(_:))) webView.addGestureRecognizer(tapGesture) tapGesture.delegate = self } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) navigationController?.navigationBarHidden = true navView.hidden = true closeTheDrawerGesture() } // MARK: - SetupUI func setupUI() { statusView.backgroundColor = UIColor.clearColor() navView.hidden = true backgroundImg = UIImageView() backgroundImg.contentMode = .ScaleAspectFill backgroundImg.clipsToBounds = true backgroundImg.frame = CGRectMake(0, -60, ScreenWidth, CGFloat(265)) webView.scrollView.addSubview(backgroundImg) webView.scrollView.delegate = self titleLabel = UILabel() titleLabel.numberOfLines = 0 titleLabel.textColor = UIColor.whiteColor() titleLabel.font = UIFont.boldSystemFontOfSize(20.0) backgroundImg.addSubview(titleLabel) titleLabel.snp_makeConstraints { (make) -> Void in make.left.equalTo(10) make.right.equalTo(-10) make.bottom.equalTo(-10) } let x = view.center.x let y = view.center.y let width = CGFloat(50.0) let height = CGFloat(50.0) // loading activityIndicatorView = NVActivityIndicatorView(frame: CGRectMake(x, y, width, height), type: .BallClipRotatePulse , color: UIColor.lightGrayColor(), padding: 5) activityIndicatorView.center = self.view.center self.view.addSubview(activityIndicatorView) // 上一篇header headerView = ZFHeaderView(frame: CGRectMake(0, -60, ScreenWidth, 60)) //先隐藏,待web加载完毕后显示 headerView.hidden = true self.webView.scrollView.addSubview(headerView) // 下一篇footer footerView = ZFFooterView(frame: CGRectMake(0, 0, ScreenWidth, 60)) // 先隐藏,待web加载完毕后显示 footerView.hidden = true self.webView.scrollView.addSubview(footerView) } func setupZan() { zanBtn.zanImage = UIImage(named: "News_Navigation_Vote") zanBtn.zanedImage = UIImage(named: "News_Navigation_Voted") // 赞 zanBtn.zanAction = { [weak self](number) -> Void in guard let strongSelf = self else { return } strongSelf.zanNumLabel.text = "\(number)" strongSelf.zanNumLabel.textColor = ThemeColor strongSelf.zanNumLabel.text = "\(number)" } // 取消赞 zanBtn.unzanAction = { [weak self](number)->Void in guard let strongSelf = self else { return } strongSelf.zanNumLabel.text = "\(number)" strongSelf.zanNumLabel.textColor = UIColor.lightGrayColor() strongSelf.zanNumLabel.text = "\(number)" } zanBtn.dk_backgroundColorPicker = BG_COLOR } // MARK: - 配置header 和 footerview func configHederAndFooterView() { // 配置header headerView.configTintColor(hasPic) if viewModel.hasPrevious { headerView.hasHeaderData() }else { headerView.notiNoHeaderData() } if viewModel.hasNext { footerView.hasMoreData() nextNewsBtn.enabled = true }else { footerView.notiNoMoreData() nextNewsBtn.enabled = false } } // MARK: - Networking func getNewsWithId(newsId : String!) { activityIndicatorView.startAnimation() self.isLoading = true //获取新闻详情 viewModel.loadNewsDetail(newsId, complate: { [weak self](newsDetail) -> Void in guard let strongSelf = self else { return } if let img = newsDetail.image { strongSelf.hasPic = true strongSelf.backgroundImg.hidden = false strongSelf.titleLabel.text = newsDetail.title! LightStatusBar() strongSelf.backgroundImg.kf_setImageWithURL(NSURL(string: img)!, placeholderImage: UIImage(named: "avatar")) strongSelf.webView.scrollView.contentInset = UIEdgeInsetsMake(-30, 0, 0, 0) }else { strongSelf.hasPic = false strongSelf.backgroundImg.hidden = true BlackStatusBar() strongSelf.webView.scrollView.contentInset = UIEdgeInsetsMake(0, 0, 0, 0) } //配置header和footer strongSelf.configHederAndFooterView() if var body = newsDetail.body { if let css = newsDetail.css { if !strongSelf.isNight { //白天模式 body = "<html><head><link rel='stylesheet' href='\(css[0])'></head><body>\(body)</body></html>" }else { //夜间模式 body = "<html><head><link rel='stylesheet' href='\(css[0])'></head><body><div class='night'>\(body)</div></body></html>" } } //print("\(body)") strongSelf.webView.loadHTMLString(body, baseURL: nil) } }) { (error) -> Void in } /// 获取新闻额外信息 viewModel.loadNewsExra(newsId, complate: { [weak self](newsExtra) -> Void in guard let strongSelf = self else { return } strongSelf.newsExtra = newsExtra strongSelf.commentNumLabel.text = "\(newsExtra.comments!)" strongSelf.zanBtn.initNumber = newsExtra.popularity! strongSelf.zanNumLabel.text = "\(newsExtra.popularity!)" }) { (error) -> Void in } } // MARK: - Action // 返回 @IBAction func didClickLeft(sender: UIButton) { navigationController?.popViewControllerAnimated(true) } // 下一条新闻 @IBAction func didClickNext() { getNextNews() } // 分享 @IBAction func didClickShare(sender: UIButton) { print("分享") } // webView tap事件 func tapAction(gesture : UITapGestureRecognizer) { let touchPoint = gesture.locationInView(self.webView) getImage(touchPoint) } // 获取webView图片 func getImage(point : CGPoint) { let js = String(format: "document.elementFromPoint(%f, %f).tagName", arguments: [point.x,point.y]) let tagName = webView.stringByEvaluatingJavaScriptFromString(js) if tagName == "IMG" { let imgURL = String(format: "document.elementFromPoint(%f, %f).src", arguments: [point.x,point.y]) let urlToShow = webView.stringByEvaluatingJavaScriptFromString(imgURL) if let url = urlToShow { var images = [SKPhoto]() let photo = SKPhoto.photoWithImageURL(url) photo.shouldCachePhotoURLImage = true images.append(photo) let browser = SKPhotoBrowser(photos: images) presentViewController(browser, animated: true, completion: {}) } } } // 下一条新闻 func getNextNews() { // 取消赞 zanBtn.isZan = true zanBtn.zanAnimationPlay() UIView.animateWithDuration(0.3, delay: 0.0, options: .CurveLinear, animations: { () -> Void in self.containerView.frame = CGRectMake(0, -ScreenHeight, ScreenWidth, ScreenHeight); self.getNewsWithId(self.viewModel.nextId) }) { (finished) -> Void in if !self.hasPic { if self.isNight { LightStatusBar() }else { BlackStatusBar() } } let delay = dispatch_time(DISPATCH_TIME_NOW, Int64(0.3 * Double(NSEC_PER_SEC))) dispatch_after(delay, dispatch_get_main_queue()) { self.containerView.frame = CGRectMake(0, 0, ScreenWidth, ScreenHeight); } } } // 上一条新闻 func getPreviousNews() { // 取消赞 zanBtn.isZan = true zanBtn.zanAnimationPlay() UIView.animateWithDuration(0.3, delay: 0.0, options: .CurveLinear, animations: { () -> Void in self.containerView.frame = CGRectMake(0, ScreenHeight, ScreenWidth, ScreenHeight); self.getNewsWithId(self.viewModel.previousId) }) { (finished) -> Void in } } // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. let commentVC = segue.destinationViewController as! ZFNewsCommentViewController commentVC.commentNum = String(self.newsExtra.comments!) commentVC.newsId = self.newsId } } // MARK: - UIWebViewDelegate extension ZFNewsDetailViewController: UIWebViewDelegate { func webViewDidFinishLoad(webView: UIWebView) { //显示header和footer footerView.hidden = false headerView.hidden = false activityIndicatorView.stopAnimation() self.isLoading = false footerView.y = webView.scrollView.contentSize.height } } // MARK: - UIScrollViewDelegate extension ZFNewsDetailViewController: UIScrollViewDelegate { func scrollViewDidScroll(scrollView: UIScrollView) { let offSetY = scrollView.contentOffset.y //有图模式 if hasPic { if (Float)(offSetY) >= 170 { if !isNight { //白天模式 BlackStatusBar() }else { //夜间模式 LightStatusBar() } statusView.dk_backgroundColorPicker = BG_COLOR }else { LightStatusBar() statusView.backgroundColor = UIColor.clearColor() } }else { //无图模式 statusView.dk_backgroundColorPicker = BG_COLOR if !isNight { //白天模式 BlackStatusBar() }else { //夜间模式 LightStatusBar() } } //到-80 让webview不再能被拉动 if (-offSetY > 60) { webView.scrollView.contentOffset = CGPointMake(0, -60); } //改变header下拉箭头的方向 if (-offSetY >= 40 ) { UIView.animateWithDuration(0.3, animations: { () -> Void in self.headerView.arrowImageView.transform = CGAffineTransformMakeRotation((CGFloat)(M_PI)) }) }else if -offSetY < 40 { UIView.animateWithDuration(0.3, animations: { () -> Void in self.headerView.arrowImageView.transform = CGAffineTransformIdentity }) } //改变footer下拉箭头的方向 if offSetY + ScreenHeight - 100 > scrollView.contentSize.height { UIView.animateWithDuration(0.3, animations: { () -> Void in self.footerView.arrowImageView.transform = CGAffineTransformMakeRotation((CGFloat)(M_PI)) }) }else { UIView.animateWithDuration(0.3, animations: { () -> Void in self.footerView.arrowImageView.transform = CGAffineTransformIdentity }) } } func scrollViewDidEndDragging(scrollView: UIScrollView, willDecelerate decelerate: Bool) { let offSetY = scrollView.contentOffset.y if (-offSetY <= 60 && -offSetY >= 40 ) { if !viewModel.hasPrevious { return } if isLoading { return } isLoading = true //上一条新闻 getPreviousNews() }else if (-offSetY > 60) {//到-80 让webview不再能被拉动 self.webView.scrollView.contentOffset = CGPointMake(0, -60); } if (offSetY + ScreenHeight - 100 > scrollView.contentSize.height) { if !viewModel.hasNext { return } if isLoading { return } isLoading = true getNextNews() } } } // MARK: - UIGestureRecognizerDelegate extension ZFNewsDetailViewController: UIGestureRecognizerDelegate { func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWithGestureRecognizer otherGestureRecognizer: UIGestureRecognizer) -> Bool { if gestureRecognizer == tapGesture { return true } return false } }
apache-2.0
f165b59993b88d15abfda379cca77e31
33.947991
172
0.581817
5.062671
false
false
false
false
ahoppen/swift
test/stdlib/NSDictionary.swift
41
739
// RUN: %target-run-simple-swift // REQUIRES: executable_test // REQUIRES: objc_interop import StdlibUnittest import Foundation var tests = TestSuite("NSDictionary") tests.test("copy construction") { let expected = ["A":1, "B":2, "C":3, "D":4] let x = NSDictionary(dictionary: expected as NSDictionary) expectEqual(expected, x as! Dictionary) let y = NSMutableDictionary(dictionary: expected as NSDictionary) expectEqual(expected, y as NSDictionary as! Dictionary) } // rdar://problem/27875914 tests.test("subscript with Any") { let d = NSMutableDictionary() d["k"] = "@this is how the world ends" expectEqual((d["k"]! as AnyObject).character(at: 0), 0x40) d["k"] = nil expectTrue(d["k"] == nil) } runAllTests()
apache-2.0
42ff19e42dd445e35ce135f0d546f919
24.482759
67
0.696888
3.535885
false
true
false
false
formbound/Plume
Sources/Plume/Result/RowSequence.swift
1
1530
/// A RowSequence is a sequence of database rows over multiple results public class RowSequence<T: Sequence> : Sequence where T.Element : ResultProtocol { internal var resultSequence: T internal init(_ resultSequence: T) { self.resultSequence = resultSequence } /// Returns an iterator over the rows in this sequence. public func makeIterator() -> AnyIterator<T.Element.Element> { var resultIterator = resultSequence.makeIterator() var result = resultIterator.next() guard let firstResult = result else { return AnyIterator<T.Element.Element> { return nil } } var rowIndex: T.Element.Index = firstResult.startIndex return AnyIterator<T.Element.Element> { var nonNilResult: T.Iterator.Element if let existingResult = result { nonNilResult = existingResult } else { if let next = resultIterator.next() { rowIndex = next.startIndex result = next nonNilResult = next } else { return nil } } if rowIndex < nonNilResult.endIndex { let row = nonNilResult[rowIndex] rowIndex = nonNilResult.index(after: rowIndex) if rowIndex > nonNilResult.endIndex { result = nil } return row } return nil } } }
mit
197e9ad4ace84ddfbb67ca49adadba6b
27.867925
83
0.548366
5.730337
false
false
false
false
HassanEskandari/HEDatePicker
HEDatePicker/Classes/HEDatePickerComponents.swift
1
381
// // HEDatePickerComponents.swift // HEDatePicker // // Created by Hassan on 8/11/17. // Copyright © 2017 hassaneskandari. All rights reserved. // enum HEDatePickerComponents : Character { case invalid = "!", year = "y", month = "M", day = "d", hour = "h", minute = "m", space = "W" }
mit
6ff677ecc4585ad4818d9ceaa7fe22cd
20.111111
58
0.486842
3.486239
false
false
false
false
AboutObjectsTraining/swift-comp-reston-2017-01
examples/Shopping/ShoppingTests/Cart.swift
2
1724
// // Copyright (C) 2016 About Objects, Inc. All Rights Reserved. // See LICENSE.txt for this example's licensing information. // import Foundation extension Double { var dollarAmount: String { return String(format: "$%.2f", self) } } class Cart: CustomStringConvertible { var items: [Item] = [] init() { } init(items: [Item]) { self.items = items } func add(item: Item) { items.append(item) } var description: String { return items.description } var amount: Double { var total = 0.0 for item in items { total += item.amount } return total } var discountAmount: Double { var total = 0.0 for item in items { total += item.discountAmount } return total } class Item: CustomStringConvertible { let name: String let price: Double var quantity: Int var onSale = false init(name: String, price: Double, quantity: Int, onSale: Bool = false) { self.name = name self.price = price self.quantity = quantity self.onSale = onSale } var amount: Double { return price * Double(quantity) } var discount: Double { return amount < 100 ? 5 : fmin(amount/20, 30) } var discountAmount: Double { return onSale ? amount * (discount/100) : 0 } var description: String { let discountedAmount = (amount - discountAmount).dollarAmount return "\(quantity) \(name) @ $\(price) = \(discountedAmount)" } } }
mit
214edeb8911036f4881ebaf2f93711fe
21.986667
80
0.529582
4.585106
false
false
false
false
Tarovk/Mundus_Client
Pods/Aldo/Aldo/AldoEncoding.swift
2
1473
// // AldoEncoding.swift // Pods // // Created by Team Aldo on 11/01/2017. // // import Foundation import Alamofire /** Encoding the information that is passed in the body when a request is send to the server runinng the Aldo Framework. This struct is a fix for a problem that occurs when using the **JSONEncoding** struct of **Alamofire**. **The code in this struct is a combination of JSONEncoding.default and URLEncoding implemented by Alamofire.** For more information about these structs, see [Alamofire](https://github.com/Alamofire/Alamofire). */ public struct AldoEncoding: ParameterEncoding { public func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest { var urlRequest = try urlRequest.asURLRequest() if urlRequest.httpMethod != HTTPMethod.get.rawValue { guard let parameters = parameters else { return urlRequest } do { let data = try JSONSerialization.data(withJSONObject: parameters, options: []) if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil { urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type") } urlRequest.httpBody = data } catch { throw AFError.parameterEncodingFailed(reason: .jsonEncodingFailed(error: error)) } } return urlRequest } }
mit
f9f7e7e91deb758588b6de6092a2c0b7
32.477273
112
0.655126
5.18662
false
false
false
false
tannernelson/ActivityBar
Pod/Classes/ActivityBar.swift
2
6759
import UIKit public class ActivityBar: UIView { //MARK: Properties private var bar = UIView() private var barLeft: NSLayoutConstraint! private var barRight: NSLayoutConstraint! private var animationTimer: NSTimer? //MARK: Constants private let duration: NSTimeInterval = 1 private let waitTime: NSTimeInterval = 0.5 //MARK: Lifecycle private func initializeBar() { super.awakeFromNib() self.bar.backgroundColor = self.color self.bar.translatesAutoresizingMaskIntoConstraints = false self.addSubview(self.bar) //Left and right margins from bar to container self.barLeft = NSLayoutConstraint(item: self.bar, attribute: .Left, relatedBy: .Equal, toItem: self, attribute: .Left, multiplier: 1, constant: 0) self.addConstraint(self.barLeft) self.barRight = NSLayoutConstraint(item: self, attribute: .Right, relatedBy: .Equal, toItem: self.bar, attribute: .Right, multiplier: 1, constant: 1) self.addConstraint(self.barRight!) //Align top and bottom of bar to container self.addConstraint( NSLayoutConstraint(item: self.bar, attribute: .Top, relatedBy: .Equal, toItem: self, attribute: .Top, multiplier: 1, constant: 0) ) self.addConstraint( NSLayoutConstraint(item: self.bar, attribute: .Bottom, relatedBy: .Equal, toItem: self, attribute: .Bottom, multiplier: 1, constant: 0) ) } func animate() { let toZero: NSLayoutConstraint let toWidth: NSLayoutConstraint if self.barRight.constant == 0 { toZero = self.barLeft toWidth = self.barRight self.barRight.constant = 0 self.barLeft.constant = self.frame.size.width } else { toZero = self.barRight toWidth = self.barLeft self.barRight.constant = self.frame.size.width self.barLeft.constant = 0 } self.layoutIfNeeded() UIView.animateWithDuration(self.duration, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 0, options: [], animations: { toZero.constant = 0 self.layoutIfNeeded() }, completion: nil) UIView.animateWithDuration(self.duration * 0.7, delay: self.duration * 0.3, usingSpringWithDamping: 1, initialSpringVelocity: 0, options: [], animations: { toWidth.constant = self.frame.size.width self.layoutIfNeeded() }, completion:nil) } //MARK: Public /** Set the ActivityBar to a fixed progress. Valid values are between 0.0 and 1.0. The progress will be `nil` if the bar is currently animating. */ public var progress: Float? { didSet { if self.progress != nil { self.stop() self.hidden = false } else { self.hidden = true } if self.progress > 1.0 { self.progress = 1.0 } else if self.progress < 0 { self.progress = 0 } if let progress = self.progress { UIView.animateWithDuration(self.duration, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 0, options: [], animations: { self.barLeft.constant = 0 self.barRight.constant = self.frame.size.width - (CGFloat(progress) * self.frame.size.width) self.layoutIfNeeded() }, completion: nil) } } } /** The tint color of the ActivityBar. Defaults to the parent UIView's tint color. */ public var color = UIColor.blackColor() { didSet { self.bar.backgroundColor = self.color } } /** Starts animating the ActivityBar. Call `.stop()` to stop. */ public func start() { self.stop() self.barRight.constant = self.frame.size.width - 1 self.layoutIfNeeded() self.hidden = false self.animationTimer = NSTimer.scheduledTimerWithTimeInterval(self.duration + self.waitTime, target: self, selector: "animate", userInfo: nil, repeats: true) self.animate() } /** Stops animating the ActivityBar. Call `.start()` to start. */ public func stop() { self.animationTimer?.invalidate() self.animationTimer = nil } //MARK: Class /** Adds an ActivityBar to the supplied view controller. The added ActivityBar is returned. */ public class func addTo(viewController: UIViewController) -> ActivityBar { let activityBar = ActivityBar() activityBar.alpha = 0.8 var topOffset: CGFloat = 20 let view: UIView let xLayout: NSLayoutConstraint if let navigationBar = viewController.navigationController?.navigationBar { topOffset += navigationBar.frame.size.height view = navigationBar xLayout = NSLayoutConstraint(item: activityBar, attribute: .Top, relatedBy: .Equal, toItem: view, attribute: .Bottom, multiplier: 1, constant: -2) } else { view = viewController.view xLayout = NSLayoutConstraint(item: activityBar, attribute: .Top, relatedBy: .Equal, toItem: view, attribute: .Top, multiplier: 1, constant: topOffset) } activityBar.translatesAutoresizingMaskIntoConstraints = false activityBar.hidden = true view.addSubview(activityBar) //Height = 2 activityBar.addConstraint( NSLayoutConstraint(item: activityBar, attribute: .Height, relatedBy: .Equal, toItem: nil, attribute: .Height, multiplier: 1, constant: 2) ) //Insert view at top with top offset view.addConstraint( xLayout ) //Left and right align view to superview view.addConstraint( NSLayoutConstraint(item: activityBar, attribute: .Right, relatedBy: .Equal, toItem: view, attribute: .Right, multiplier: 1, constant: 0) ) view.addConstraint( NSLayoutConstraint(item: activityBar, attribute: .Left, relatedBy: .Equal, toItem: view, attribute: .Left, multiplier: 1, constant: 0) ) activityBar.initializeBar() activityBar.color = viewController.view.tintColor return activityBar } }
mit
3b93cf599a20385cb14d05e9b6ded904
32.964824
164
0.581891
5.136018
false
false
false
false
ben-ng/swift
stdlib/private/SwiftPrivatePthreadExtras/PthreadBarriers.swift
1
3657
//===--- PthreadBarriers.swift --------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// #if os(OSX) || os(iOS) || os(watchOS) || os(tvOS) import Darwin #elseif os(Linux) || os(FreeBSD) || os(PS4) || os(Android) import Glibc #endif // // Implement pthread barriers. // // (OS X does not implement them.) // public struct _stdlib_pthread_barrierattr_t { public init() {} } public func _stdlib_pthread_barrierattr_init( _ attr: UnsafeMutablePointer<_stdlib_pthread_barrierattr_t> ) -> CInt { return 0 } public func _stdlib_pthread_barrierattr_destroy( _ attr: UnsafeMutablePointer<_stdlib_pthread_barrierattr_t> ) -> CInt { return 0 } public var _stdlib_PTHREAD_BARRIER_SERIAL_THREAD: CInt { return 1 } public struct _stdlib_pthread_barrier_t { var mutex: UnsafeMutablePointer<pthread_mutex_t>? var cond: UnsafeMutablePointer<pthread_cond_t>? /// The number of threads to synchronize. var count: CUnsignedInt = 0 /// The number of threads already waiting on the barrier. /// /// This shared variable is protected by `mutex`. var numThreadsWaiting: CUnsignedInt = 0 public init() {} } public func _stdlib_pthread_barrier_init( _ barrier: UnsafeMutablePointer<_stdlib_pthread_barrier_t>, _ attr: UnsafeMutablePointer<_stdlib_pthread_barrierattr_t>?, _ count: CUnsignedInt ) -> CInt { barrier.pointee = _stdlib_pthread_barrier_t() if count == 0 { errno = EINVAL return -1 } barrier.pointee.mutex = UnsafeMutablePointer.allocate(capacity: 1) if pthread_mutex_init(barrier.pointee.mutex!, nil) != 0 { // FIXME: leaking memory. return -1 } barrier.pointee.cond = UnsafeMutablePointer.allocate(capacity: 1) if pthread_cond_init(barrier.pointee.cond!, nil) != 0 { // FIXME: leaking memory, leaking a mutex. return -1 } barrier.pointee.count = count return 0 } public func _stdlib_pthread_barrier_destroy( _ barrier: UnsafeMutablePointer<_stdlib_pthread_barrier_t> ) -> CInt { if pthread_cond_destroy(barrier.pointee.cond!) != 0 { // FIXME: leaking memory, leaking a mutex. return -1 } if pthread_mutex_destroy(barrier.pointee.mutex!) != 0 { // FIXME: leaking memory. return -1 } barrier.pointee.cond!.deinitialize() barrier.pointee.cond!.deallocate(capacity: 1) barrier.pointee.mutex!.deinitialize() barrier.pointee.mutex!.deallocate(capacity: 1) return 0 } public func _stdlib_pthread_barrier_wait( _ barrier: UnsafeMutablePointer<_stdlib_pthread_barrier_t> ) -> CInt { if pthread_mutex_lock(barrier.pointee.mutex!) != 0 { return -1 } barrier.pointee.numThreadsWaiting += 1 if barrier.pointee.numThreadsWaiting < barrier.pointee.count { // Put the thread to sleep. if pthread_cond_wait(barrier.pointee.cond!, barrier.pointee.mutex!) != 0 { return -1 } if pthread_mutex_unlock(barrier.pointee.mutex!) != 0 { return -1 } return 0 } else { // Reset thread count. barrier.pointee.numThreadsWaiting = 0 // Wake up all threads. if pthread_cond_broadcast(barrier.pointee.cond!) != 0 { return -1 } if pthread_mutex_unlock(barrier.pointee.mutex!) != 0 { return -1 } return _stdlib_PTHREAD_BARRIER_SERIAL_THREAD } }
apache-2.0
9210ecb71f3d77b54f572544591a41e7
26.916031
80
0.665573
3.849474
false
false
false
false
typelift/Basis
Basis/Search.swift
2
1708
// // Search.swift // Basis // // Created by Robert Widmann on 9/7/14. // Copyright (c) 2014 TypeLift. All rights reserved. // Released under the MIT license. // /// Returns whether an element is a member of an array. public func elem<A : Equatable>(e : A) -> [A] -> Bool { return { l in any({ $0 == e })(l) } } /// Returns whether an element is not a member of an array. public func notElem<A : Equatable>(e : A) -> [A] -> Bool { return { l in all({ $0 != e })(l) } } /// Returns whether an element is a member of a list. public func elem<A : Equatable>(e : A) -> List<A> -> Bool { return { l in any({ $0 == e })(l) } } /// Returns whether an element is not a member of a list. public func notElem<A : Equatable>(e : A) -> List<A> -> Bool { return { l in all({ $0 != e })(l) } } /// Looks up a key in a dictionary. public func lookup<A : Equatable, B>(e : A) -> [A:B] -> Optional<B> { return { d in switch destructure(d) { case .Empty: return .None case .Destructure(let (x, y), let xys): if e == x { return .Some(y) } return lookup(e)(xys) } } } /// Looks up a key in an array of key-value pairs. public func lookup<A : Equatable, B>(e : A) -> [(A, B)] -> Optional<B> { return { d in switch match(d) { case .Nil: return .None case .Cons(let (x, y), let xys): if e == x { return .Some(y) } return lookup(e)(xys) } } } /// Looks up a key in a list of key-value pairs. public func lookup<A : Equatable, B>(e : A) -> List<(A, B)> -> Optional<B> { return { d in switch d.match() { case .Nil: return .None case .Cons(let (x, y), let xys): if e == x { return .Some(y) } return lookup(e)(xys) } } }
mit
775d9496e3faf128a18c22497fb14bbe
22.39726
76
0.566745
2.750403
false
false
false
false
eselkin/DirectionFieldiOS
Pods/GRDB.swift/GRDB/Foundation/DatabaseDateComponents.swift
1
9629
import Foundation /// DatabaseDateComponents reads and stores NSDateComponents in the database. public struct DatabaseDateComponents : DatabaseValueConvertible { /// The available formats for reading and storing date components. public enum Format : String { /// The format "yyyy-MM-dd". case YMD = "yyyy-MM-dd" /// The format "yyyy-MM-dd HH:mm". /// /// This format is lexically comparable with SQLite's CURRENT_TIMESTAMP. case YMD_HM = "yyyy-MM-dd HH:mm" /// The format "yyyy-MM-dd HH:mm:ss". /// /// This format is lexically comparable with SQLite's CURRENT_TIMESTAMP. case YMD_HMS = "yyyy-MM-dd HH:mm:ss" /// The format "yyyy-MM-dd HH:mm:ss.SSS". /// /// This format is lexically comparable with SQLite's CURRENT_TIMESTAMP. case YMD_HMSS = "yyyy-MM-dd HH:mm:ss.SSS" /// The format "HH:mm". case HM = "HH:mm" /// The format "HH:mm:ss". case HMS = "HH:mm:ss" /// The format "HH:mm:ss.SSS". case HMSS = "HH:mm:ss.SSS" } // MARK: - NSDateComponents conversion /// The date components public let dateComponents: NSDateComponents /// The database format public let format: Format /// Creates a DatabaseDateComponents from an NSDateComponents and a format. /// /// The result is nil if and only if *dateComponents* is nil. /// /// - parameter dateComponents: An optional NSDateComponents. /// - parameter format: The format used for storing the date components in /// the database. /// - returns: An optional DatabaseDateComponents. public init?(_ dateComponents: NSDateComponents?, format: Format) { guard let dateComponents = dateComponents else { return nil } self.format = format self.dateComponents = dateComponents } // MARK: - DatabaseValueConvertible adoption /// Returns a value that can be stored in the database. public var databaseValue: DatabaseValue { let dateString: String? switch format { case .YMD_HM, .YMD_HMS, .YMD_HMSS, .YMD: let year = (dateComponents.year == NSDateComponentUndefined) ? 0 : dateComponents.year let month = (dateComponents.month == NSDateComponentUndefined) ? 1 : dateComponents.month let day = (dateComponents.day == NSDateComponentUndefined) ? 1 : dateComponents.day dateString = NSString(format: "%04d-%02d-%02d", year, month, day) as String default: dateString = nil } let timeString: String? switch format { case .YMD_HM, .HM: let hour = (dateComponents.hour == NSDateComponentUndefined) ? 0 : dateComponents.hour let minute = (dateComponents.minute == NSDateComponentUndefined) ? 0 : dateComponents.minute timeString = NSString(format: "%02d:%02d", hour, minute) as String case .YMD_HMS, .HMS: let hour = (dateComponents.hour == NSDateComponentUndefined) ? 0 : dateComponents.hour let minute = (dateComponents.minute == NSDateComponentUndefined) ? 0 : dateComponents.minute let second = (dateComponents.second == NSDateComponentUndefined) ? 0 : dateComponents.second timeString = NSString(format: "%02d:%02d:%02d", hour, minute, second) as String case .YMD_HMSS, .HMSS: let hour = (dateComponents.hour == NSDateComponentUndefined) ? 0 : dateComponents.hour let minute = (dateComponents.minute == NSDateComponentUndefined) ? 0 : dateComponents.minute let second = (dateComponents.second == NSDateComponentUndefined) ? 0 : dateComponents.second let nanosecond = (dateComponents.nanosecond == NSDateComponentUndefined) ? 0 : dateComponents.nanosecond timeString = NSString(format: "%02d:%02d:%02d.%03d", hour, minute, second, Int(round(Double(nanosecond) / 1_000_000.0))) as String default: timeString = nil } return DatabaseValue([dateString, timeString].flatMap { $0 }.joinWithSeparator(" ")) } /// Returns a DatabaseDateComponents if *databaseValue* contains a /// valid date. /// /// - parameter databaseValue: A DatabaseValue. /// - returns: An optional DatabaseDateComponents. public static func fromDatabaseValue(databaseValue: DatabaseValue) -> DatabaseDateComponents? { // https://www.sqlite.org/lang_datefunc.html // // Supported formats are: // // - YYYY-MM-DD // - YYYY-MM-DD HH:MM // - YYYY-MM-DD HH:MM:SS // - YYYY-MM-DD HH:MM:SS.SSS // - YYYY-MM-DDTHH:MM // - YYYY-MM-DDTHH:MM:SS // - YYYY-MM-DDTHH:MM:SS.SSS // - HH:MM // - HH:MM:SS // - HH:MM:SS.SSS // We need a String guard let string = String.fromDatabaseValue(databaseValue) else { return nil } let dateComponents = NSDateComponents() let scanner = NSScanner(string: string) scanner.charactersToBeSkipped = NSCharacterSet() let hasDate: Bool // YYYY or HH var initialNumber: Int = 0 if !scanner.scanInteger(&initialNumber) { return nil } switch scanner.scanLocation { case 2: // HH hasDate = false let hour = initialNumber if hour >= 0 && hour <= 23 { dateComponents.hour = hour } else { return nil } case 4: // YYYY hasDate = true let year = initialNumber if year >= 0 && year <= 9999 { dateComponents.year = year } else { return nil } // - if !scanner.scanString("-", intoString: nil) { return nil } // MM var month: Int = 0 if scanner.scanInteger(&month) && month >= 1 && month <= 12 { dateComponents.month = month } else { return nil } // - if !scanner.scanString("-", intoString: nil) { return nil } // DD var day: Int = 0 if scanner.scanInteger(&day) && day >= 1 && day <= 31 { dateComponents.day = day } else { return nil } // YYYY-MM-DD if scanner.atEnd { return DatabaseDateComponents(dateComponents, format: .YMD) } // T/space if !scanner.scanString("T", intoString: nil) && !scanner.scanString(" ", intoString: nil) { return nil } // HH var hour: Int = 0 if scanner.scanInteger(&hour) && hour >= 0 && hour <= 23 { dateComponents.hour = hour } else { return nil } default: return nil } // : if !scanner.scanString(":", intoString: nil) { return nil } // MM var minute: Int = 0 if scanner.scanInteger(&minute) && minute >= 0 && minute <= 59 { dateComponents.minute = minute } else { return nil } // [YYYY-MM-DD] HH:MM if scanner.atEnd { if hasDate { return DatabaseDateComponents(dateComponents, format: .YMD_HM) } else { return DatabaseDateComponents(dateComponents, format: .HM) } } // : if !scanner.scanString(":", intoString: nil) { return nil } // SS var second: Int = 0 if scanner.scanInteger(&second) && second >= 0 && second <= 59 { dateComponents.second = second } else { return nil } // [YYYY-MM-DD] HH:MM:SS if scanner.atEnd { if hasDate { return DatabaseDateComponents(dateComponents, format: .YMD_HMS) } else { return DatabaseDateComponents(dateComponents, format: .HMS) } } // . if !scanner.scanString(".", intoString: nil) { return nil } // SSS var millisecondDigits: NSString? = nil if scanner.scanCharactersFromSet(NSCharacterSet.decimalDigitCharacterSet(), intoString: &millisecondDigits), var millisecondDigits = millisecondDigits { if millisecondDigits.length > 3 { millisecondDigits = millisecondDigits.substringToIndex(3) } dateComponents.nanosecond = millisecondDigits.integerValue * 1_000_000 } else { return nil } // [YYYY-MM-DD] HH:MM:SS.SSS if scanner.atEnd { if hasDate { return DatabaseDateComponents(dateComponents, format: .YMD_HMSS) } else { return DatabaseDateComponents(dateComponents, format: .HMSS) } } // Unknown format return nil } }
gpl-3.0
83dbf2b7c4d602b3294eb962a12fd3f8
33.266904
160
0.527885
5.185245
false
false
false
false
Mobilette/AniMee
Pods/p2.OAuth2/Sources/Base/OAuth2CodeGrant.swift
2
4928
// // OAuth2CodeGrant.swift // OAuth2 // // Created by Pascal Pfiffner on 6/16/14. // Copyright 2014 Pascal Pfiffner // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import Foundation /** A class to handle authorization for confidential clients via the authorization code grant method. This auth flow is designed for clients that are capable of protecting their client secret but can be used from installed apps. During code exchange and token refresh flows, **if** the client has a secret, a "Basic key:secret" Authorization header will be used. If not the client key will be embedded into the request body. */ public class OAuth2CodeGrant: OAuth2 { public override class var grantType: String { return "authorization_code" } override public class var responseType: String? { return "code" } // MARK: - Token Request /** Generate the URL to be used for the token request from known instance variables and supplied parameters. This will set "grant_type" to "authorization_code", add the "code" provided and forward to `authorizeURLWithBase()` to fill the remaining parameters. The "client_id" is only added if there is no secret (public client) or if the request body is used for id and secret. - parameter code: The code you want to exchange for an access token - parameter params: Optional additional params to add as URL parameters - returns: The URL you can use to exchange the code for an access token */ func tokenURLWithCode(code: String, params: OAuth2StringDict? = nil) throws -> NSURL { guard let redirect = context.redirectURL else { throw OAuth2Error.NoRedirectURL } var urlParams = params ?? OAuth2StringDict() urlParams["code"] = code urlParams["grant_type"] = self.dynamicType.grantType urlParams["redirect_uri"] = redirect if let secret = clientConfig.clientSecret { if authConfig.secretInBody { urlParams["client_secret"] = secret urlParams["client_id"] = clientConfig.clientId } } else { urlParams["client_id"] = clientConfig.clientId } return try authorizeURLWithParams(urlParams, asTokenURL: true) } /** Create a request for token exchange. */ func tokenRequestWithCode(code: String) throws -> NSMutableURLRequest { let url = try tokenURLWithCode(code) return try tokenRequestWithURL(url) } /** Extracts the code from the redirect URL and exchanges it for a token. */ override public func handleRedirectURL(redirect: NSURL) { logIfVerbose("Handling redirect URL \(redirect.description)") do { let code = try validateRedirectURL(redirect) exchangeCodeForToken(code) } catch let error { didFail(error) } } /** Takes the received code and exchanges it for a token. */ public func exchangeCodeForToken(code: String) { do { guard !code.isEmpty else { throw OAuth2Error.PrerequisiteFailed("I don't have a code to exchange, let the user authorize first") } let post = try tokenRequestWithCode(code) logIfVerbose("Exchanging code \(code) for access token at \(post.URL!)") performRequest(post) { data, status, error in do { guard let data = data else { throw error ?? OAuth2Error.NoDataInResponse } let params = try self.parseAccessTokenResponse(data) if status < 400 { self.logIfVerbose("Did exchange code for access [\(nil != self.clientConfig.accessToken)] and refresh [\(nil != self.clientConfig.refreshToken)] tokens") self.didAuthorize(params) } else { throw OAuth2Error.Generic("\(status)") } } catch let error { self.didFail(error) } } } catch let error { didFail(error) } } // MARK: - Utilities /** Validates the redirect URI: returns a tuple with the code and nil on success, nil and an error on failure. */ func validateRedirectURL(redirect: NSURL) throws -> String { let comp = NSURLComponents(URL: redirect, resolvingAgainstBaseURL: true) if let compQuery = comp?.query where compQuery.characters.count > 0 { let query = OAuth2CodeGrant.paramsFromQuery(comp!.percentEncodedQuery!) if let cd = query["code"] { // we got a code, use it if state is correct (and reset state) try assureMatchesState(query) return cd } throw OAuth2Error.ResponseError("No “code” received") } throw OAuth2Error.PrerequisiteFailed("The redirect URL contains no query fragment") } }
mit
6c9a1044c04bf297b19e2d3856c2b129
30.767742
159
0.713038
3.89249
false
false
false
false
changjiashuai/AudioKit
Tests/Tests/AKMoogVCF.swift
14
1537
// // main.swift // AudioKit // // Created by Nick Arner and Aurelius Prochazka on 12/19/14. // Copyright (c) 2014 Aurelius Prochazka. All rights reserved. // import Foundation let testDuration: NSTimeInterval = 10.0 class Instrument : AKInstrument { var auxilliaryOutput = AKAudio() override init() { super.init() let filename = "AKSoundFiles.bundle/Sounds/PianoBassDrumLoop.wav" let audio = AKFileInput(filename: filename) let mono = AKMix(monoAudioFromStereoInput: audio) auxilliaryOutput = AKAudio.globalParameter() assignOutput(auxilliaryOutput, to:mono) } } class Processor : AKInstrument { init(audioSource: AKAudio) { super.init() let cutoffFrequency = AKLine( firstPoint: 200.ak, secondPoint: 6000.ak, durationBetweenPoints: testDuration.ak ) let moogVCF = AKMoogVCF(input: audioSource) moogVCF.cutoffFrequency = cutoffFrequency setAudioOutput(moogVCF) enableParameterLog( "Cutoff Frequency = ", parameter: moogVCF.cutoffFrequency, timeInterval:0.1 ) resetParameter(audioSource) } } AKOrchestra.testForDuration(testDuration) let instrument = Instrument() let processor = Processor(audioSource: instrument.auxilliaryOutput) AKOrchestra.addInstrument(instrument) AKOrchestra.addInstrument(processor) processor.play() instrument.play() NSThread.sleepForTimeInterval(NSTimeInterval(testDuration))
mit
1d2b11499f101496a732ffe7a28ac863
22.287879
73
0.681197
4.773292
false
true
false
false
hwsyy/ruby-china-ios
RubyChina/Controllers/TopicsController.swift
4
9575
// // NodesController.swift // RubyChina // // Created by Jianqiu Xiao on 5/22/15. // Copyright (c) 2015 Jianqiu Xiao. All rights reserved. // import AFNetworking import CCBottomRefreshControl import SwiftyJSON import TPKeyboardAvoiding import UINavigationBar_Addition import UIKit class TopicsController: UIViewController, UISearchBarDelegate, UITableViewDataSource, UITableViewDelegate, UIToolbarDelegate { var emptyView = EmptyView() var failureView = FailureView() var loadingView = LoadingView() var parameters: JSON = [:] var refreshing = false var segmentedControl = UISegmentedControl(items: ["默认", "最新", "热门", "精华"]) var tableView = TPKeyboardAvoidingTableView() var toolbar = UIToolbar() var topRefreshControl = UIRefreshControl() var topics: JSON = [] override func viewDidLoad() { automaticallyAdjustsScrollViewInsets = false navigationItem.rightBarButtonItem = UIBarButtonItem(title: "账号", style: .Plain, target: self, action: Selector("user")) navigationItem.title = JSON(NSBundle.mainBundle().localizedInfoDictionary!)["CFBundleDisplayName"].string view.backgroundColor = Helper.backgroundColor tableView.allowsMultipleSelection = false tableView.autoresizingMask = .FlexibleWidth | .FlexibleHeight tableView.backgroundColor = .clearColor() tableView.dataSource = self tableView.delegate = self tableView.frame = view.bounds tableView.registerClass(TopicCell.self, forCellReuseIdentifier: "Cell") tableView.tableFooterView = UIView() view.addSubview(tableView) let searchBar = UISearchBar() searchBar.autocapitalizationType = .None searchBar.autocorrectionType = .No searchBar.delegate = self searchBar.placeholder = "搜索" searchBar.sizeToFit() tableView.tableHeaderView = searchBar topRefreshControl.addTarget(self, action: Selector("topRefresh"), forControlEvents: .ValueChanged) tableView.addSubview(topRefreshControl) let bottomRefreshControl = UIRefreshControl() bottomRefreshControl.addTarget(self, action: Selector("bottomRefresh"), forControlEvents: .ValueChanged) tableView.bottomRefreshControl = bottomRefreshControl toolbar.autoresizingMask = .FlexibleWidth toolbar.delegate = self toolbar.frame.size.width = view.bounds.width view.addSubview(toolbar) segmentedControl.addTarget(self, action: Selector("segmentedControlValueChanged:"), forControlEvents: .ValueChanged) segmentedControl.autoresizingMask = .FlexibleLeftMargin | .FlexibleRightMargin | .FlexibleTopMargin | .FlexibleBottomMargin segmentedControl.frame.size.height = 28 segmentedControl.selectedSegmentIndex = max(0, segmentedControl.selectedSegmentIndex) toolbar.addSubview(segmentedControl) failureView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: Selector("autoRefresh"))) view.addSubview(failureView) view.addSubview(loadingView) emptyView.text = "没有帖子" view.addSubview(emptyView) } override func viewWillAppear(animated: Bool) { navigationController?.navigationBar.hideBottomHairline() if tableView.indexPathForSelectedRow() != nil { tableView.deselectRowAtIndexPath(tableView.indexPathForSelectedRow()!, animated: true) } traitCollectionDidChange(nil) if topics.count == 0 { autoRefresh() } Helper.trackView(self) } override func viewWillDisappear(animated: Bool) { navigationController?.navigationBar.showBottomHairline() } func autoRefresh() { if refreshing { return } loadingView.show() loadData() } func topRefresh() { if refreshing { topRefreshControl.endRefreshing(); return } topics = [] loadData() } func bottomRefresh() { if refreshing { tableView.bottomRefreshControl.endRefreshing(); tableView.bottomRefreshControl.hidden = true; return } loadData() } func stopRefresh() { refreshing = false loadingView.hide() topRefreshControl.endRefreshing() tableView.bottomRefreshControl.endRefreshing() tableView.bottomRefreshControl.hidden = true } func loadData() { if refreshing { return } refreshing = true failureView.hide() emptyView.hide() let selectedSegmentIndex = segmentedControl.selectedSegmentIndex parameters["limit"].object = 30 parameters["offset"].object = topics.count parameters["type"].object = ["last_actived", "recent", "popular", "excellent"][selectedSegmentIndex] AFHTTPRequestOperationManager(baseURL: Helper.baseURL).GET("/topics.json", parameters: parameters.object, success: { (operation, responseObject) in self.stopRefresh() if JSON(responseObject)["topics"].count == 0 { if self.topics.count == 0 { self.emptyView.show() } else { return } } if self.topics.count == 0 { self.tableView.scrollRectToVisible(CGRect(x: 0, y: self.tableView.tableHeaderView?.frame.height ?? 0, width: 1, height: 1), animated: false) } self.topics = JSON(self.topics.arrayValue + JSON(responseObject)["topics"].arrayValue) self.tableView.reloadData() self.segmentedControl.selectedSegmentIndex = selectedSegmentIndex }) { (operation, error) in self.stopRefresh() self.failureView.show() } } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return topics.count } func tableView(tableView: UITableView, estimatedHeightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return 61 } func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { let cell = TopicCell() cell.accessoryType = .DisclosureIndicator cell.detailTextLabel?.text = " " cell.frame.size.width = tableView.frame.width cell.textLabel?.text = topics[indexPath.row]["title"].string cell.topic = topics[indexPath.row] cell.layoutSubviews() let textLabelHeight = cell.textLabel!.textRectForBounds(cell.textLabel!.frame, limitedToNumberOfLines: cell.textLabel!.numberOfLines).height return 10 + textLabelHeight + 4 + cell.detailTextLabel!.frame.height + 10 } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! TopicCell cell.topic = topics[indexPath.row] return cell } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { let topicController = TopicController() topicController.topic = topics[indexPath.row] splitViewController?.showDetailViewController(UINavigationController(rootViewController: topicController), sender: self) } func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) { if (indexPath.row + 1) % 30 == 0 && indexPath.row + 1 == topics.count { autoRefresh() } } func positionForBar(bar: UIBarPositioning) -> UIBarPosition { return .Top } override func traitCollectionDidChange(previousTraitCollection: UITraitCollection?) { super.traitCollectionDidChange(previousTraitCollection) toolbar.frame.origin.y = min(UIApplication.sharedApplication().statusBarFrame.width, UIApplication.sharedApplication().statusBarFrame.height) + navigationController!.navigationBar.frame.height toolbar.frame.size.height = navigationController!.navigationBar.frame.height tableView.contentInset.top = toolbar.frame.origin.y + toolbar.frame.height tableView.scrollIndicatorInsets.top = toolbar.frame.origin.y + toolbar.frame.height segmentedControl.frame.size.width = min(320, view.bounds.width, view.bounds.height) - 16 segmentedControl.frame.origin.x = (view.bounds.width - segmentedControl.frame.width) / 2 } func segmentedControlValueChanged(segmentedControl: UISegmentedControl) { topics = [] autoRefresh() } func searchBarTextDidBeginEditing(searchBar: UISearchBar) { searchBar.setShowsCancelButton(true, animated: true) } func searchBarTextDidEndEditing(searchBar: UISearchBar) { searchBar.setShowsCancelButton(false, animated: true) } func searchBarSearchButtonClicked(searchBar: UISearchBar) { searchBar.resignFirstResponder() parameters["query"].string = searchBar.text != "" ? searchBar.text : nil topics = [] tableView.reloadData() autoRefresh() } func searchBarCancelButtonClicked(searchBar: UISearchBar) { searchBar.resignFirstResponder() searchBar.setShowsCancelButton(false, animated: true) searchBar.text = "" searchBarSearchButtonClicked(searchBar) } func user() { navigationController?.pushViewController(UserController(), animated: true) } func selectNode(node: JSON) { parameters["node_id"].object = node["id"].object title = node["name"].string topics = [] tableView.reloadData() navigationController?.popToViewController(self, animated: true) } }
mit
dd12c3681e6e83ecf8622fef5c057646
40.672489
200
0.69999
5.459382
false
false
false
false
Enziferum/iosBoss
iosBoss/Extensions.swift
1
3366
// // Extensions.swift // IosHelper // // Created by AlexRaag on 30/08/2017. // Copyright © 2017 AlexRaag. All rights reserved. // import UIKit /**TODO Block extension UIImageView need struct for printing exception */ extension String:URLable{ public func asURL() throws -> URL { guard let url = URL(string:self) else { throw urlError.NoAsURL } return url } public func Decode(_ data:Data)->String{ return String(data: data, encoding: .utf8)! } //MARK:allows Cut substring from given String /** NOTE: from Swift 3 in String Must be Range<String.Index> - Parameter lowerChar: lower Bound - Parameter upChar: up Bound - Returns:String */ public func getSubStr(Str:String,lowerChar:Character,upChar:Character)->String { var symbolIndex:Int=0 var lower:String.Index? var up:String.Index? for symbol in Str.characters { if symbol == lowerChar { lower = Str.index(Str.startIndex, offsetBy: symbolIndex+1) } if symbol == upChar { up = Str.index(Str.startIndex, offsetBy: symbolIndex) } symbolIndex += 1 } return String(Str[lower!..<up!]) } //Subscript for Giving index// // public subscript } extension UIView{ /** Allow to use Custom Constraints - Parameter Arg: Constraint Value as String - Parameter Views: Try to set Constraints to all Views */ func AddConstraints(use Arg:String,forViews Views:UIView...){ var ViewDict = [String:UIView]() for (index,view) in Views.enumerated(){ let Key = "v\(Views[index])" ViewDict[Key] = view } addConstraints(NSLayoutConstraint.constraints(withVisualFormat: Arg, options: NSLayoutFormatOptions(), metrics: nil, views: ViewDict)) } } extension UIColor { //MARK:Color /** By default UIColor - return not standard rgba color In this way need make Retranslation -Return UIColor */ func Color(red:CGFloat, green: CGFloat, blue: CGFloat, alpha: CGFloat)->UIColor{ return UIColor(red: red/255, green:green/255, blue: blue/255, alpha: alpha) } //MARK: Color Randomize public func Randomize(red:Int?=255,green:Int?=255,blue:Int?=255)->UIColor{ let Red = Int(arc4random_uniform(UInt32(red!))) let Green = Int(arc4random_uniform(UInt32(green!))) let Blue = Int(arc4random_uniform(UInt32(blue!))) return UIColor().Color(red: CGFloat(Red), green: CGFloat(Green), blue:CGFloat(Blue), alpha: 1) } } extension UIImageView{ public enum ErrorLoad:Error{ case NoData //print("No Data was given for loading Image") } /** Allow to LoadAsync Image using URL */ open func LoadAsync(fromURl url:String)throws{ let request=Request() request.accompishData(withUrl: url, handler: { (data) in guard let data = data else { //throw ErrorLoad.NoData return } DispatchQueue.main.async { self.image=UIImage(data: data) } }) } }
mit
e8f511f999dcad7d521df4c7cdae8288
26.137097
142
0.581872
4.308579
false
false
false
false
tkremenek/swift
test/IRGen/prespecialized-metadata/enum-inmodule-1argument-within-struct-1argument-1distinct_use.swift
14
3030
// RUN: %swift -prespecialize-generic-metadata -target %module-target-future -emit-ir %s | %FileCheck %s -DINT=i%target-ptrsize -DALIGNMENT=%target-alignment // REQUIRES: VENDOR=apple || OS=linux-gnu // UNSUPPORTED: CPU=i386 && OS=ios // UNSUPPORTED: CPU=armv7 && OS=ios // UNSUPPORTED: CPU=armv7s && OS=ios // CHECK: @"$s4main9NamespaceV5ValueOySS_SiGMf" = linkonce_odr hidden constant <{ // CHECK-SAME: i8**, // CHECK-SAME: [[INT]], // CHECK-SAME: %swift.type_descriptor*, // CHECK-SAME: %swift.type*, // CHECK-SAME: %swift.type*, // CHECK-SAME: i64 // CHECK-SAME: }> <{ // i8** getelementptr inbounds (%swift.enum_vwtable, %swift.enum_vwtable* @"$s4main9NamespaceV5ValueOySS_SiGWV", i32 0, i32 0), // CHECK-SAME: [[INT]] 513, // CHECK-SAME: %swift.type_descriptor* bitcast ( // CHECK-SAME: {{.*}}$s4main9NamespaceV5ValueOMn{{.*}} to %swift.type_descriptor* // CHECK-SAME: ), // CHECK-SAME: %swift.type* @"$sSSN", // CHECK-SAME: %swift.type* @"$sSiN", // CHECK-SAME: i64 3 // CHECK-SAME: }>, align [[ALIGNMENT]] struct Namespace<Arg> { enum Value<First> { case first(First) } } @inline(never) func consume<T>(_ t: T) { withExtendedLifetime(t) { t in } } // CHECK: define hidden swiftcc void @"$s4main4doityyF"() #{{[0-9]+}} { // CHECK: call swiftcc void @"$s4main7consumeyyxlF"( // CHECK-SAME: %swift.opaque* noalias nocapture %{{[0-9]+}}, // CHECK-SAME: %swift.type* getelementptr inbounds ( // CHECK-SAME: %swift.full_type, // CHECK-SAME: %swift.full_type* bitcast ( // CHECK-SAME: <{ // CHECK-SAME: i8**, // CHECK-SAME: [[INT]], // CHECK-SAME: %swift.type_descriptor*, // CHECK-SAME: %swift.type*, // CHECK-SAME: %swift.type*, // CHECK-SAME: i64 // CHECK-SAME: }>* @"$s4main9NamespaceV5ValueOySS_SiGMf" // CHECK-SAME: to %swift.full_type* // CHECK-SAME: ), // CHECK-SAME: i32 0, // CHECK-SAME: i32 1 // CHECK-SAME: ) // CHECK-SAME: ) // CHECK: } func doit() { consume( Namespace<String>.Value.first(13) ) } doit() // CHECK: ; Function Attrs: noinline nounwind readnone // CHECK: define hidden swiftcc %swift.metadata_response @"$s4main9NamespaceV5ValueOMa"([[INT]] %0, %swift.type* %1, %swift.type* %2) #{{[0-9]+}} { // CHECK: entry: // CHECK: [[ERASED_TYPE_1:%[0-9]+]] = bitcast %swift.type* %1 to i8* // CHECK: [[ERASED_TYPE_2:%[0-9]+]] = bitcast %swift.type* %2 to i8* // CHECK: {{%[0-9]+}} = call swiftcc %swift.metadata_response @__swift_instantiateCanonicalPrespecializedGenericMetadata( // CHECK-SAME: [[INT]] %0, // CHECK-SAME: i8* [[ERASED_TYPE_1]], // CHECK-SAME: i8* [[ERASED_TYPE_2]], // CHECK-SAME: i8* undef, // CHECK-SAME: %swift.type_descriptor* bitcast ( // CHECK-SAME: {{.*}}$s4main9NamespaceV5ValueOMn{{.*}} to %swift.type_descriptor* // CHECK-SAME: ) // CHECK-SAME: ) #{{[0-9]+}} // CHECK: ret %swift.metadata_response {{%[0-9]+}} // CHECK: }
apache-2.0
2ab53b042abf92a2c2ea64dd5867a52f
37.35443
157
0.59538
3.03
false
false
false
false
joerocca/GitHawk
Pods/Pageboy/Sources/Pageboy/Extensions/PageboyViewController+ScrollDetection.swift
1
15999
// // PageboyScrollDetection.swift // Pageboy // // Created by Merrick Sapsford on 13/02/2017. // Copyright © 2017 Merrick Sapsford. All rights reserved. // import UIKit // MARK: - UIPageViewControllerDelegate, UIScrollViewDelegate extension PageboyViewController: UIPageViewControllerDelegate, UIScrollViewDelegate { // MARK: UIPageViewControllerDelegate public func pageViewController(_ pageViewController: UIPageViewController, willTransitionTo pendingViewControllers: [UIViewController]) { guard pageViewControllerIsActual(pageViewController) else { return } self.pageViewController(pageViewController, willTransitionTo: pendingViewControllers, animated: false) } internal func pageViewController(_ pageViewController: UIPageViewController, willTransitionTo pendingViewControllers: [UIViewController], animated: Bool) { guard pageViewControllerIsActual(pageViewController) else { return } guard let viewController = pendingViewControllers.first, let index = viewControllerMap.index(forObjectAfter: { return $0.object === viewController }) else { return } self.expectedTransitionIndex = index let direction = NavigationDirection.forPage(index, previousPage: self.currentIndex ?? index) self.delegate?.pageboyViewController(self, willScrollToPageAt: index, direction: direction, animated: animated) } public func pageViewController(_ pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [UIViewController], transitionCompleted completed: Bool) { guard pageViewControllerIsActual(pageViewController) else { return } guard completed == true else { return } if let viewController = pageViewController.viewControllers?.first, let index = viewControllerMap.index(forObjectAfter: { return $0.object === viewController }) { guard index == self.expectedTransitionIndex else { return } self.updateCurrentPageIndexIfNeeded(index) } } public func presentationCount(for pageViewController: UIPageViewController) -> Int { guard showsPageControl else { return -1 } return pageCount ?? 0 } public func presentationIndex(for pageViewController: UIPageViewController) -> Int { guard showsPageControl else { return -1 } return targetIndex ?? 0 } // MARK: UIScrollViewDelegate public func scrollViewDidScroll(_ scrollView: UIScrollView) { guard scrollViewIsActual(scrollView) else { return } guard self.updateContentOffsetForBounceIfNeeded(scrollView: scrollView) == false else { return } guard let currentIndex = self.currentIndex else { return } let previousPagePosition = self.previousPagePosition ?? 0.0 // calculate offset / page size for relative orientation var pageSize: CGFloat! var contentOffset: CGFloat! switch navigationOrientation { case .horizontal: pageSize = scrollView.frame.size.width if scrollView.layoutIsRightToLeft { contentOffset = pageSize + (pageSize - scrollView.contentOffset.x) } else { contentOffset = scrollView.contentOffset.x } case .vertical: pageSize = scrollView.frame.size.height contentOffset = scrollView.contentOffset.y } guard let scrollIndexDiff = self.pageScrollIndexDiff(forCurrentIndex: currentIndex, expectedIndex: self.expectedTransitionIndex, currentContentOffset: contentOffset, pageSize: pageSize) else { return } guard var pagePosition = self.pagePosition(forContentOffset: contentOffset, pageSize: pageSize, indexDiff: scrollIndexDiff) else { return } // do not continue if a page change is detected guard !self.detectCurrentPageIndexIfNeeded(pagePosition: pagePosition, scrollView: scrollView) else { return } // do not continue if previous position equals current if previousPagePosition == pagePosition { return } // update relative page position for infinite overscroll if required self.detectInfiniteOverscrollIfNeeded(pagePosition: &pagePosition) // provide scroll updates var positionPoint: CGPoint! let direction = NavigationDirection.forPosition(pagePosition, previous: previousPagePosition) if self.navigationOrientation == .horizontal { positionPoint = CGPoint(x: pagePosition, y: scrollView.contentOffset.y) } else { positionPoint = CGPoint(x: scrollView.contentOffset.x, y: pagePosition) } // ignore duplicate updates guard self.currentPosition != positionPoint else { return } self.currentPosition = positionPoint self.delegate?.pageboyViewController(self, didScrollTo: positionPoint, direction: direction, animated: self.isScrollingAnimated) self.previousPagePosition = pagePosition } public func scrollViewWillBeginDragging(_ scrollView: UIScrollView) { guard scrollViewIsActual(scrollView) else { return } if self.autoScroller.cancelsOnScroll { self.autoScroller.cancel() } } public func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) { guard scrollViewIsActual(scrollView) else { return } self.scrollView(didEndScrolling: scrollView) } public func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { guard scrollViewIsActual(scrollView) else { return } self.scrollView(didEndScrolling: scrollView) } public func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) { guard scrollViewIsActual(scrollView) else { return } self.updateContentOffsetForBounceIfNeeded(scrollView: scrollView) } private func scrollView(didEndScrolling scrollView: UIScrollView) { guard scrollViewIsActual(scrollView) else { return } if self.autoScroller.restartsOnScrollEnd { self.autoScroller.restart() } } // MARK: Calculations /// Detect whether the scroll view is overscrolling while infinite scroll is enabled /// Adjusts pagePosition if required. /// /// - Parameter pagePosition: the relative page position. private func detectInfiniteOverscrollIfNeeded(pagePosition: inout CGFloat) { guard self.isInfinitelyScrolling(forPosition: pagePosition) else { return } let maxPagePosition = CGFloat((self.viewControllerCount ?? 1) - 1) var integral: Double = 0.0 var progress = CGFloat(modf(fabs(Double(pagePosition)), &integral)) var maxInfinitePosition: CGFloat! if pagePosition > 0.0 { progress = 1.0 - progress maxInfinitePosition = 0.0 } else { maxInfinitePosition = maxPagePosition } var infinitePagePosition = maxPagePosition * progress if fmod(progress, 1.0) == 0.0 { infinitePagePosition = maxInfinitePosition } pagePosition = infinitePagePosition } /// Whether a position is infinitely scrolling between end ranges /// /// - Parameter pagePosition: The position. /// - Returns: Whether the position is infinitely scrolling. private func isInfinitelyScrolling(forPosition pagePosition: CGFloat) -> Bool { let maxPagePosition = CGFloat((self.viewControllerCount ?? 1) - 1) let overscrolling = pagePosition < 0.0 || pagePosition > maxPagePosition guard self.isInfiniteScrollEnabled && overscrolling else { return false } return true } /// Detects whether a page boundary has been passed. /// As pageViewController:didFinishAnimating is not reliable. /// /// - Parameters: /// - pageOffset: The current page scroll offset /// - scrollView: The scroll view that is being scrolled. /// - Returns: Whether a page transition has been detected. private func detectCurrentPageIndexIfNeeded(pagePosition: CGFloat, scrollView: UIScrollView) -> Bool { guard let currentIndex = self.currentIndex else { return false } guard scrollView.isDecelerating == false else { return false } let isPagingForward = pagePosition > self.previousPagePosition ?? 0.0 if scrollView.isTracking { if isPagingForward && pagePosition >= CGFloat(currentIndex + 1) { self.updateCurrentPageIndexIfNeeded(currentIndex + 1) return true } else if !isPagingForward && pagePosition <= CGFloat(currentIndex - 1) { self.updateCurrentPageIndexIfNeeded(currentIndex - 1) return true } } let isOnPage = pagePosition.truncatingRemainder(dividingBy: 1) == 0 if isOnPage { guard currentIndex != self.currentIndex else { return false} self.currentIndex = currentIndex } return false } /// Safely update the current page index. /// /// - Parameter index: the proposed index. private func updateCurrentPageIndexIfNeeded(_ index: Int) { guard self.currentIndex != index, index >= 0 && index < self.viewControllerCount ?? 0 else { return } self.currentIndex = index } /// Calculate the expected index diff for a page scroll. /// /// - Parameters: /// - index: The current index. /// - expectedIndex: The target page index. /// - currentContentOffset: The current content offset. /// - pageSize: The size of each page. /// - Returns: The expected index diff. private func pageScrollIndexDiff(forCurrentIndex index: Int?, expectedIndex: Int?, currentContentOffset: CGFloat, pageSize: CGFloat) -> CGFloat? { guard let index = index else { return nil } let expectedIndex = expectedIndex ?? index let expectedDiff = CGFloat(max(1, abs(expectedIndex - index))) let expectedPosition = self.pagePosition(forContentOffset: currentContentOffset, pageSize: pageSize, indexDiff: expectedDiff) ?? CGFloat(index) guard self.isInfinitelyScrolling(forPosition: expectedPosition) == false else { return 1 } return expectedDiff } /// Calculate the relative page position. /// /// - Parameters: /// - contentOffset: The current contentOffset. /// - pageSize: The current page size. /// - indexDiff: The expected difference between current / target page indexes. /// - Returns: The relative page position. private func pagePosition(forContentOffset contentOffset: CGFloat, pageSize: CGFloat, indexDiff: CGFloat) -> CGFloat? { guard let currentIndex = self.currentIndex else { return nil } let scrollOffset = contentOffset - pageSize let pageOffset = (CGFloat(currentIndex) * pageSize) + (scrollOffset * indexDiff) let position = pageOffset / pageSize return position.isFinite ? position : 0 } /// Update the scroll view contentOffset for bouncing preference if required. /// /// - Parameter scrollView: The scroll view. /// - Returns: Whether the contentOffset was manipulated to achieve bouncing preference. @discardableResult private func updateContentOffsetForBounceIfNeeded(scrollView: UIScrollView) -> Bool { guard self.bounces == false else { return false } let previousContentOffset = scrollView.contentOffset if self.currentIndex == 0 && scrollView.contentOffset.x < scrollView.bounds.size.width { scrollView.contentOffset = CGPoint(x: scrollView.bounds.size.width, y: 0.0) } if self.currentIndex == (self.viewControllerCount ?? 1) - 1 && scrollView.contentOffset.x > scrollView.bounds.size.width { scrollView.contentOffset = CGPoint(x: scrollView.bounds.size.width, y: 0.0) } return previousContentOffset != scrollView.contentOffset } // MARK: Utilities /// Check that a scroll view is the actual page view controller managed instance. /// /// - Parameter scrollView: The scroll view to check. /// - Returns: Whether it is the actual managed instance. private func scrollViewIsActual(_ scrollView: UIScrollView) -> Bool { return scrollView === pageViewController?.scrollView } /// Check that a UIPageViewController is the actual managed instance. /// /// - Parameter pageViewController: The page view controller to check. /// - Returns: Whether it is the actual managed instance. private func pageViewControllerIsActual(_ pageViewController: UIPageViewController) -> Bool { return pageViewController === self.pageViewController } } // MARK: - NavigationDirection detection internal extension PageboyViewController.NavigationDirection { var pageViewControllerNavDirection: UIPageViewControllerNavigationDirection { get { switch self { case .reverse: return .reverse default: return .forward } } } static func forPage(_ page: Int, previousPage: Int) -> PageboyViewController.NavigationDirection { return self.forPosition(CGFloat(page), previous: CGFloat(previousPage)) } static func forPosition(_ position: CGFloat, previous previousPosition: CGFloat) -> PageboyViewController.NavigationDirection { if position == previousPosition { return .neutral } return position > previousPosition ? .forward : .reverse } } internal extension UIScrollView { /// Whether the scroll view can be assumed to be interactively scrolling var isProbablyActiveInScroll: Bool { return self.isTracking || self.isDragging || self.isDecelerating } }
mit
2d55c82e95c92b886ef725c81ea4cfd3
39.604061
130
0.599262
6.298425
false
false
false
false
xBrux/Pensieve
Source/Core/Value.swift
1
3525
// // 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. // /// - Warning: `Binding` is a protocol that SQLite.swift uses internally to /// directly map SQLite types to Swift types. /// /// Do not conform custom types to the Binding protocol. See the `Value` /// protocol, instead. /*public*/ protocol Binding {} /*public*/ protocol Number : Binding {} /*public*/ protocol Value : Expressible { // extensions cannot have inheritance clauses typealias ValueType = Self typealias Datatype : Binding static var declaredDatatype: String { get } static func fromDatatypeValue(datatypeValue: Datatype) -> ValueType var datatypeValue: Datatype { get } } extension Double : Number, Value { /*public*/ static let declaredDatatype = "REAL" /*public*/ static func fromDatatypeValue(datatypeValue: Double) -> Double { return datatypeValue } /*public*/ var datatypeValue: Double { return self } } extension Int64 : Number, Value { /*public*/ static let declaredDatatype = "INTEGER" /*public*/ static func fromDatatypeValue(datatypeValue: Int64) -> Int64 { return datatypeValue } /*public*/ var datatypeValue: Int64 { return self } } extension String : Binding, Value { /*public*/ static let declaredDatatype = "TEXT" /*public*/ static func fromDatatypeValue(datatypeValue: String) -> String { return datatypeValue } /*public*/ var datatypeValue: String { return self } } extension Blob : Binding, Value { /*public*/ static let declaredDatatype = "BLOB" /*public*/ static func fromDatatypeValue(datatypeValue: Blob) -> Blob { return datatypeValue } /*public*/ var datatypeValue: Blob { return self } } // MARK: - extension Bool : Binding, Value { /*public*/ static var declaredDatatype = Int64.declaredDatatype /*public*/ static func fromDatatypeValue(datatypeValue: Int64) -> Bool { return datatypeValue != 0 } /*public*/ var datatypeValue: Int64 { return self ? 1 : 0 } } extension Int : Number, Value { /*public*/ static var declaredDatatype = Int64.declaredDatatype /*public*/ static func fromDatatypeValue(datatypeValue: Int64) -> Int { return Int(datatypeValue) } /*public*/ var datatypeValue: Int64 { return Int64(self) } }
mit
c947e28dd4dd2c4695f1c6e4ad10b1ba
25.69697
87
0.688706
4.618611
false
false
false
false
ProjectDent/ARKit-CoreLocation
Sources/ARKit-CoreLocation/Nodes/ScalingScheme.swift
1
3742
// // ScalingScheme.swift // ARCL // // Created by Eric Internicola on 5/17/19. // import Foundation /// A set of schemes that can be used to scale a LocationNode. /// /// Values: /// - normal: The default way of scaling, Hardcoded value out to 3000 meters, and then 0.75 that factor beyond 3000 m. /// - tiered (threshold, scale): Return 1.0 at distance up to `threshold` meters, or `scale` beyond. /// - doubleTiered (firstThreshold, firstCale, secondThreshold, secondScale): A way of scaling everything /// beyond 2 specific distances at two specific scales. /// - linear (threshold): linearly scales an object based on its distance. /// - linearBuffer (threshold, buffer): linearly scales an object based on its distance as long as it is /// further than the buffer distance, otherwise it just returns 100% scale. public enum ScalingScheme { case normal case tiered(threshold: Double, scale: Float) case doubleTiered(firstThreshold: Double, firstScale: Float, secondThreshold: Double, secondScale: Float) case linear(threshold: Double) case linearBuffer(threshold: Double, buffer: Double) /// Returns a closure to compute appropriate scale factor based on the current value of `self` (a `ScalingSchee`). /// The closure accepts two parameters and returns the scale factor to apply to an `AnnotationNode`. public func getScheme() -> ( (_ distance: Double, _ adjustedDistance: Double) -> Float) { switch self { case .tiered(let threshold, let scale): return { (distance, adjustedDistance) in if adjustedDistance > threshold { return scale } else { return 1.0 } } case .doubleTiered(let firstThreshold, let firstScale, let secondThreshold, let secondScale): return { (distance, adjustedDistance) in if adjustedDistance > secondThreshold { return secondScale } else if adjustedDistance > firstThreshold { return firstScale } else { return 1.0 } } case .linear(let threshold): return { (distance, adjustedDistance) in let maxSize = 1.0 let absThreshold = abs(threshold) let absAdjDist = abs(adjustedDistance) let scaleToReturn = Float( max(maxSize - (absAdjDist / absThreshold), 0.0)) // print("threshold: \(absThreshold) adjDist: \(absAdjDist) scaleToReturn: \(scaleToReturn)") return scaleToReturn } case .linearBuffer(let threshold, let buffer): return { (distance, adjustedDistance) in let maxSize = 1.0 let absThreshold = abs(threshold) let absAdjDist = abs(adjustedDistance) if absAdjDist < buffer { // print("threshold: \(absThreshold) adjDist: \(absAdjDist)") return Float(maxSize) } else { let scaleToReturn = Float( max( maxSize - (absAdjDist / absThreshold), 0.0 )) // print("threshold: \(absThreshold) adjDist: \(absAdjDist) scaleToReturn: \(scaleToReturn)") return scaleToReturn } } case .normal: return { (distance, adjustedDistance) in // Scale it to be an appropriate size so that it can be seen var scale = Float(adjustedDistance) * 0.181 if distance > 3000 { scale *= 0.75 } return scale } } } }
mit
d9c12368c1cf15db49d51328394b1c75
40.120879
118
0.582843
4.936675
false
false
false
false
VladimirMilichenko/CountAnimationLabelSwift
Examples/Pods/CountAnimationLabel/CountAnimationLabel/UILabel+CountAnimation.swift
2
5659
// // UILabel+CountAnimation.swift // // Created by Vladimir Milichenko on 12/2/15. // Copyright © 2016 Vladimir Milichenko. All rights reserved. //import UIKit private struct AssociatedKeys { static var isAnimated = "isAnimated" } public extension UILabel { var isAnimated : Bool { get { guard let number = objc_getAssociatedObject(self, &AssociatedKeys.isAnimated) as? NSNumber else { return false } return number.boolValue } set(value) { objc_setAssociatedObject(self, &AssociatedKeys.isAnimated, NSNumber(bool: value), objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } func countAnimationWithDuration(duration: NSTimeInterval, numberFormatter: NSNumberFormatter?) { if !self.isAnimated { self.isAnimated = true let lastNumberSymbol = self.text!.substringFromIndex(self.text!.endIndex.predecessor()) let textWidth = self.text!.sizeWithAttributes([NSFontAttributeName: self.font]).width let halfWidthsDiff = (self.frame.size.width - textWidth) / 2.0 let lastNumberSymbolWidth = lastNumberSymbol.sizeWithAttributes([NSFontAttributeName: self.font]).width let textStorage = NSTextStorage(attributedString: self.attributedText!) let layoutManager = NSLayoutManager() textStorage.addLayoutManager(layoutManager) let textContainer = NSTextContainer(size: self.bounds.size) textContainer.lineFragmentPadding = 0 layoutManager.addTextContainer(textContainer) let lastCharacterRange = NSRange(location: self.text!.characters.count - 1, length: 1) layoutManager.characterRangeForGlyphRange(lastCharacterRange, actualGlyphRange: nil) let lastNumberViewFrame = layoutManager.boundingRectForGlyphRange(lastCharacterRange, inTextContainer: textContainer) let lastNumberView = UIView( frame:CGRect( x: lastNumberViewFrame.origin.x + self.frame.origin.x, y: self.frame.origin.y, width: lastNumberSymbolWidth + halfWidthsDiff, height: self.frame.size.height ) ) lastNumberView.backgroundColor = UIColor.clearColor() lastNumberView.clipsToBounds = true let lastNumberUpperLabel = UILabel( frame: CGRect( x: 0.0, y: 0.0, width: lastNumberView.frame.size.width, height: lastNumberView.frame.size.height ) ) lastNumberUpperLabel.textAlignment = .Left; lastNumberUpperLabel.font = self.font; lastNumberUpperLabel.textColor = self.textColor; lastNumberUpperLabel.text = lastNumberSymbol; lastNumberView.addSubview(lastNumberUpperLabel) var lastNumber = Int(lastNumberSymbol)! lastNumber = lastNumber == 9 ? 0 : lastNumber + 1 let lastNumberBottomLabel = UILabel( frame: CGRect( x: lastNumberUpperLabel.frame.origin.x, y: (lastNumberUpperLabel.frame.origin.y + lastNumberUpperLabel.frame.size.height) - (lastNumberUpperLabel.frame.size.height) / 4.0, width: lastNumberUpperLabel.frame.size.width, height: lastNumberUpperLabel.frame.size.height ) ) lastNumberBottomLabel.textAlignment = .Left; lastNumberBottomLabel.font = self.font; lastNumberBottomLabel.textColor = self.textColor; lastNumberBottomLabel.text = "\(lastNumber)" lastNumberView.addSubview(lastNumberBottomLabel) self.superview!.insertSubview(lastNumberView, belowSubview: self.superview!) let attributedText = NSMutableAttributedString(string: self.text!) attributedText.addAttribute( NSForegroundColorAttributeName, value: UIColor.clearColor(), range: lastCharacterRange ) self.attributedText! = attributedText UIView.animateWithDuration(duration, animations: { var lastNumberBottomLabelFrame = lastNumberBottomLabel.frame lastNumberBottomLabelFrame.origin.y = lastNumberUpperLabel.frame.origin.y lastNumberBottomLabel.frame = lastNumberBottomLabelFrame var lastNumberUpperLabelFrame = lastNumberUpperLabel.frame lastNumberUpperLabelFrame.origin.y = lastNumberUpperLabel.frame.origin.y - lastNumberUpperLabel.frame.size.height; lastNumberUpperLabel.frame = lastNumberUpperLabelFrame }, completion: { [unowned self] finished in var likesCount = numberFormatter != nil ? Int(numberFormatter!.numberFromString(self.text!)!) : Int(self.text!) likesCount!++ self.text = numberFormatter != nil ? numberFormatter!.stringFromNumber(likesCount!) : "\(likesCount!)" lastNumberView.removeFromSuperview() self.isAnimated = false } ) } } }
mit
20de1ec9a91e7720a2cefbd531c38ca8
43.559055
151
0.591552
6.307692
false
false
false
false
SeptAi/Cooperate
Cooperate/Cooperate/Class/View/Main/base/BaseViewController.swift
1
7019
// // BaseViewController.swift // Cooperation // // Created by J on 2016/12/26. // Copyright © 2016年 J. All rights reserved. // import UIKit /* frame:x,y当前控件相对父控件的位置 bounds:x,y内部子控件相对(自己的坐标系统)原点的位置 ,就是scrollView的contentOffset 修改bounds会影响 其子视图的位置,而自身位置不会移动 */ /// 1.NavigationController的设置。2.TableView的设置 class BaseViewController: UIViewController { // MARK: - 属性 // 属性不能定义到分类 // 登陆标示 let userLogin = true // 导航栏 - 自定义导航条 lazy var navigationBar = UINavigationBar(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 64)) // 导航项 lazy var nvItem = UINavigationItem() // 访客视图信息字典 var visitorInfoDictionary: [String: String]? // 表格视图:未登录时不创建 var tableview:UITableView? // 刷新控件 var refreshControl:JRefreshControl? var isPullup = false override var title: String?{ didSet{ nvItem.title = title } } // MARK: - 方法 // 加载数据 func loadData(){ // 如果子类不实现方法,默认关闭控件 refreshControl?.endRefreshing() } // MARK: - 方法 // MARK: - 系统 override func viewDidLoad() { super.viewDidLoad() // 背景颜色 - 白色 view.backgroundColor = UIColor.white setupUI() NetworkManager.sharedInstance.userLogon ? loadData() : () // 注册通知 NotificationCenter.default.addObserver(self, selector: #selector(loginSuccess(n:)), name: NSNotification.Name(rawValue: NoticeName.UserLoginSuccessedNotification), object: nil) // Do any additional setup after loading the view. } } /* 1.属性不能定义到分类 2.分类不能重写父类本类的方法{父类方法和子类方法位置一致、}可能导致不执行 */ extension BaseViewController{ /// 设置界面 func setupUI() { view.backgroundColor = UIColor.lightGray // 取消自动缩进 - 如果隐藏导航栏会缩进20 automaticallyAdjustsScrollViewInsets = false setupNav() if userLogin{ setuptableview() }else{ setupVisitorView() } } /// 设置表格 func setuptableview() { // 1.添加表格视图 tableview = UITableView(frame: view.bounds, style: .plain) // 将tableView添加到nav下方。仅层次 view.insertSubview(tableview!, belowSubview: navigationBar) // 2.设置代理&数据源 tableview?.delegate = self tableview?.dataSource = self // 3.实现协议方法 // 4.1设置内容缩进 - 那么你的contentview就是从scrollview的*开始显示 tableview?.contentInset = UIEdgeInsets(top: navigationBar.bounds.height, left: 0, bottom: tabBarController?.tabBar.bounds.height ?? 49, right: 0) // 4.2设置指示器的缩进 tableview?.scrollIndicatorInsets = tableview!.contentInset // 5.刷新控件 refreshControl = JRefreshControl() tableview?.addSubview(refreshControl!) // 6.添加监听事件 refreshControl?.addTarget(self, action: #selector(loadData), for: .valueChanged) } /// 设置访客视图 func setupVisitorView(){ let visitorView = VisitorView(frame: view.bounds) view.insertSubview(visitorView, belowSubview: navigationBar) // 1.设置访客信息 visitorView.visitorInfo = visitorInfoDictionary // 2. 添加访客视图按钮的监听方法 visitorView.loginButton.addTarget(self, action: #selector(login), for: .touchUpInside) visitorView.registerButton.addTarget(self, action: #selector(register), for: .touchUpInside) // 3. 设置导航条按钮 nvItem.leftBarButtonItem = UIBarButtonItem(title: "注册", style: .plain, target: self, action: #selector(register)) nvItem.rightBarButtonItem = UIBarButtonItem(title: "登录", style: .plain, target: self, action: #selector(login)) } /// 设置Nav字体样式 func setupNav() { view.addSubview(navigationBar) navigationBar.items = [nvItem] // navigationBar.barTintColor = UIColor.white // FIXME: - 系统设置透明度过高 // 设置navBar的字体颜色 navigationBar.titleTextAttributes = [NSForegroundColorAttributeName:UIColor.darkGray] // 设置按钮字体颜色 navigationBar.tintColor = UIColor.orange } } extension BaseViewController{ func loginSuccess(n:NSNotification){ print("登录成功 \(n)") // 登录前左边是注册,右边是登录 nvItem.leftBarButtonItem = nil nvItem.rightBarButtonItem = nil // 更新 UI => 将访客视图替换为表格视图 // 需要重新设置 view // 在访问 view 的 getter 时,如果 view == nil 会调用 loadView -> viewDidLoad view = nil // 注销通知 -> 重新执行 viewDidLoad 会再次注册!避免通知被重复注册 NotificationCenter.default.removeObserver(self) } func login() { NotificationCenter.default.post(name: NSNotification.Name(rawValue: NoticeName.UserShouldLoginNotification), object: nil) } func register(){ print("用户注册") } } extension BaseViewController:UITableViewDelegate,UITableViewDataSource{ // 基类准备方法,子类进行实现;子类不需要super func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 0 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = UITableViewCell() return cell } // 实现上拉刷新 func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) { // 判断最后一行 let row = indexPath.row let section = ((tableview?.numberOfSections)! - 1) if row<0 || section<0{ return } let count = tableview?.numberOfRows(inSection: section) if (row == (count! - 1) && !isPullup) { isPullup = true // 开始刷新 // FIXME: - 上拉刷新判断 // loadData() } } // 为了子类能重写此方法,这样子类方法才能被调用 func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 10 } }
mit
866b8c573ef9d49560d87b486b6854d7
28.607843
184
0.601325
4.60717
false
false
false
false
debugsquad/Hyperborea
Hyperborea/Model/Search/MSearchOrigins.swift
1
4805
import UIKit class MSearchOrigins { let attributedString:NSAttributedString private let kBreak:String = "\n" private let kKeyResults:String = "results" private let kKeyWord:String = "word" private let kKeyLexicalEntries:String = "lexicalEntries" private let kKeyEntries:String = "entries" private let kKeyEtymologies:String = "etymologies" private let kWordFontSize:CGFloat = 40 private let kFontSize:CGFloat = 18 private let kNotFoundFontSize:CGFloat = 18 init(json:Any) { let mutableString:NSMutableAttributedString = NSMutableAttributedString() guard let jsonMap:[String:Any] = json as? [String:Any], let jsonResults:[Any] = jsonMap[kKeyResults] as? [Any] else { attributedString = mutableString return } let attributes:[String:AnyObject] = [ NSFontAttributeName:UIFont.regular(size:kFontSize), NSForegroundColorAttributeName:UIColor.black] let stringBreak:NSAttributedString = NSAttributedString( string:kBreak, attributes:attributes) var wordString:NSAttributedString? for jsonResult:Any in jsonResults { guard let jsonResultMap:[String:Any] = jsonResult as? [String:Any], let jsonLexicalEntries:[Any] = jsonResultMap[kKeyLexicalEntries] as? [Any] else { continue } if wordString == nil { if let word:String = jsonResultMap[kKeyWord] as? String { let wordCapitalized:String = word.capitalizedFirstLetter() let attributesWord:[String:AnyObject] = [ NSFontAttributeName:UIFont.medium(size:kWordFontSize), NSForegroundColorAttributeName:UIColor.black] wordString = NSAttributedString( string:wordCapitalized, attributes:attributesWord) } } for jsonLexicalEntry:Any in jsonLexicalEntries { guard let jsonLexicalEntryMap:[String:Any] = jsonLexicalEntry as? [String:Any], let jsonEntries:[Any] = jsonLexicalEntryMap[kKeyEntries] as? [Any] else { continue } for jsonEntry:Any in jsonEntries { guard let jsonEntryMap:[String:Any] = jsonEntry as? [String:Any], let jsonEtymologies:[Any] = jsonEntryMap[kKeyEtymologies] as? [Any] else { continue } for jsonEtymology:Any in jsonEtymologies { guard let titleEtymology:String = jsonEtymology as? String else { continue } let stringEtymology:NSAttributedString = NSAttributedString( string:titleEtymology, attributes:attributes) if !mutableString.string.isEmpty { mutableString.append(stringBreak) } mutableString.append(stringEtymology) } } } } if let wordString:NSAttributedString = wordString { if !mutableString.string.isEmpty { mutableString.insert(stringBreak, at:0) mutableString.insert(stringBreak, at:0) } mutableString.insert(wordString, at:0) } attributedString = mutableString } init() { let string:String = NSLocalizedString("MSearchOrigins_notFound", comment:"") let attributes:[String:AnyObject] = [ NSFontAttributeName:UIFont.regular(size:kNotFoundFontSize), NSForegroundColorAttributeName:UIColor(white:0.4, alpha:1)] attributedString = NSAttributedString( string:string, attributes:attributes) } }
mit
3de06b32a53d075ec30bb69e78410aff
33.078014
93
0.479709
6.600275
false
false
false
false
teamheisenberg/GeoFire-Image-Demo
Photo Drop/ViewController.swift
1
7810
// // ViewController.swift // Photo Drop // // Created by Bob Warwick on 2015-05-05. // Copyright (c) 2015 Whole Punk Creators. All rights reserved. // import UIKit import CoreLocation import MapKit class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate, UIAlertViewDelegate { // MARK: - Setup let locationManager = CLLocationManager() let imagePicker = UIImagePickerController() var firebase: Firebase? var geofire: GeoFire? var regionQuery: GFRegionQuery? var foundQuery: GFCircleQuery? var annotations: Dictionary<String, Pin> = Dictionary(minimumCapacity: 8) var lastExchangeKeyFound: String? var lastExchangeLocationFound: CLLocation? var inExchange = false @IBOutlet weak var mapView: MKMapView! @IBOutlet weak var foundImage: UIImageView! override func viewDidLoad() { super.viewDidLoad() imagePicker.sourceType = .PhotoLibrary imagePicker.delegate = self firebase = Firebase(url: "https://vivid-fire-6294.firebaseio.com/") geofire = GeoFire(firebaseRef: firebase!.childByAppendingPath("geo")) let gestureRecongnizer = UITapGestureRecognizer(target: self, action: Selector("hideImageView:")) foundImage.addGestureRecognizer(gestureRecongnizer) } // MARK: - Map Tracking override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) locationManager.requestWhenInUseAuthorization() self.mapView.userLocation.addObserver(self, forKeyPath: "location", options: NSKeyValueObservingOptions(), context: nil) } override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) { if (self.mapView.showsUserLocation && self.mapView.userLocation.location != nil) { let span = MKCoordinateSpanMake(0.0125, 0.0125) let region = MKCoordinateRegion(center: self.mapView.userLocation.location!.coordinate, span: span) self.mapView.setRegion(region, animated: true) if regionQuery == nil { regionQuery = geofire?.queryWithRegion(region) regionQuery!.observeEventType(GFEventTypeKeyEntered, withBlock: { (key: String!, location: CLLocation!) in let annotation = Pin(key: key) annotation.coordinate = location.coordinate self.mapView.addAnnotation(annotation) self.annotations[key] = annotation }) regionQuery!.observeEventType(GFEventTypeKeyExited, withBlock: { (key: String!, location: CLLocation!) -> Void in self.mapView.removeAnnotation(self.annotations[key]!) self.annotations[key] = nil }) } // We also want a query with an extremely limited span. When a photo enters that region, we want to notify the user they can exchange. if foundQuery == nil { foundQuery = geofire?.queryAtLocation(self.mapView.userLocation.location, withRadius: 0.05) foundQuery!.observeEventType(GFEventTypeKeyEntered, withBlock: { (key: String!, location: CLLocation!) -> Void in self.lastExchangeKeyFound = key self.lastExchangeLocationFound = location let foundAPhoto = UIAlertView(title: "You Found a Drop!", message: "You can view the photo by tapping exchange and providing a new photo.", delegate: self, cancelButtonTitle: "Not Here", otherButtonTitles: "Exchange") foundAPhoto.show() }) } else { foundQuery?.center = self.mapView.userLocation.location } } } // MARK: - Drop a Photo @IBAction func dropPhoto(sender: AnyObject) { self.presentViewController(imagePicker, animated: true, completion: nil) } func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage!, editingInfo: [NSObject : AnyObject]!) { self.dismissViewControllerAnimated(true, completion: nil) // Save the photo to Firebase let thumbnail = image.resizedImageWithContentMode(UIViewContentMode.ScaleAspectFit, bounds: CGSizeMake(400, 400), interpolationQuality:CGInterpolationQuality.High) let imgData = UIImagePNGRepresentation(thumbnail) let base64EncodedImage = imgData!.base64EncodedStringWithOptions(NSDataBase64EncodingOptions()) if inExchange { // Download the existing photo and show it firebase?.childByAppendingPath(lastExchangeKeyFound).observeEventType(.Value, withBlock: { (snapshot) -> Void in self.firebase?.childByAppendingPath(self.lastExchangeKeyFound).removeAllObservers() let existingImageInBase64 = snapshot.value as! String let existingImageData = NSData(base64EncodedString: existingImageInBase64, options: NSDataBase64DecodingOptions()) let image = UIImage(data: existingImageData!) self.foundImage.image = image self.foundImage.hidden = false UIView.animateWithDuration(0.5, animations: { () -> Void in self.foundImage.alpha = 1.0 var layer = self.foundImage.layer layer.shadowColor = UIColor.blackColor().CGColor layer.shadowRadius = 10.0 layer.shadowOffset = CGSizeMake(10.0, 5.0) layer.shadowOpacity = 0.8 }) // Overwrite the existing photo let existingReference = self.firebase?.childByAppendingPath(self.lastExchangeKeyFound) existingReference?.setValue(base64EncodedImage) // Go back to the non-exchange flow self.inExchange = false }) } else { let uniqueReference = firebase?.childByAutoId() uniqueReference!.setValue(base64EncodedImage) let key = uniqueReference?.key let location = mapView.userLocation.location geofire!.setLocation(mapView.userLocation.location, forKey: key) } } func imagePickerControllerDidCancel(picker: UIImagePickerController) { self.dismissViewControllerAnimated(true, completion: nil) inExchange = false } func hideImageView(sender: AnyObject?) { UIView.animateWithDuration(0.5, animations: { () -> Void in self.foundImage.alpha = 0.0 let layer = self.foundImage.layer layer.shadowColor = UIColor.blackColor().CGColor layer.shadowRadius = 0.0 layer.shadowOffset = CGSizeMake(0.0, 0.0) layer.shadowOpacity = 0.0 }) { (bool) -> Void in self.foundImage.image = nil self.foundImage.hidden = true } } // MARK: - Exchange Dialog Delegate func alertView(alertView: UIAlertView, didDismissWithButtonIndex buttonIndex: Int) { if buttonIndex == 1 { inExchange = true self.dropPhoto(self) } } }
mit
6c04ca7a9a9289db22ccf1606934897f
38.444444
237
0.601536
5.780903
false
false
false
false
abdullasulaiman/RaeesIOSProject
SwiftOpenCV/SwiftOCR.swift
1
5852
// // SwiftOCR.swift // SwiftOpenCV // // Created by Lee Whitney on 10/28/14. // Copyright (c) 2014 WhitneyLand. All rights reserved. // import Foundation import UIKit class SwiftOCR { var _image: UIImage var _tesseract: Tesseract var _characterBoxes : Array<CharBox> var _groupedImage : UIImage var _recognizedText: String //Get grouped image after executing recognize method var groupedImage : UIImage { get { return _groupedImage; } } //Get Recognized Text after executing recognize method var recognizedText: String { get { return _recognizedText; } } var characterBoxes :Array<CharBox> { get { return _characterBoxes; } } /*init(fromImagePath path:String) { _image = UIImage(contentsOfFile: path)! _tesseract = Tesseract(language: "eng") _tesseract.setVariableValue("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ", forKey: "tessedit_char_whitelist") _tesseract.image = _image _characterBoxes = Array<CharBox>() _groupedImage = _image _recognizedText = "" }*/ init(fromImage image:UIImage) { _image = image; _tesseract = Tesseract(language: "eng") _tesseract.setVariableValue("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ()@+.-,!#$%&*?''", forKey: "tessedit_char_whitelist") println(image) _tesseract.image = image _characterBoxes = Array<CharBox>() _groupedImage = image _recognizedText = "" NSLog("%d",image.imageOrientation.rawValue); } //Recognize function func recognize() { _characterBoxes = Array<CharBox>() var uImage = CImage(image: _image); var channels = uImage.channels; let classifier1 = NSBundle.mainBundle().pathForResource("trained_classifierNM1", ofType: "xml") let classifier2 = NSBundle.mainBundle().pathForResource("trained_classifierNM2", ofType: "xml") var erFilter1 = ExtremeRegionFilter.createERFilterNM1(classifier1, c: 8, x: 0.00015, y: 0.13, f: 0.2, a: true, scale: 0.1); var erFilter2 = ExtremeRegionFilter.createERFilterNM2(classifier2, andX: 0.5); var regions = Array<ExtremeRegionStat>(); var index : Int; for index = 0; index < channels.count; index++ { var region = ExtremeRegionStat() region = erFilter1.run(channels[index] as UIImage); regions.append(region); } _groupedImage = ExtremeRegionStat.groupImage(uImage, withRegions: regions); _tesseract.recognize(); /* @property (nonatomic, readonly) NSArray *getConfidenceByWord; @property (nonatomic, readonly) NSArray *getConfidenceBySymbol; @property (nonatomic, readonly) NSArray *getConfidenceByTextline; @property (nonatomic, readonly) NSArray *getConfidenceByParagraph; @property (nonatomic, readonly) NSArray *getConfidenceByBlock; */ var words = _tesseract.getConfidenceByWord; var paragraphs = _tesseract.getConfidenceByTextline var texts = Array<String>(); var windex: Int /*for windex = 0; windex < words.count; windex++ { let dict = words[windex] as Dictionary<String, AnyObject> let text = dict["text"]! as String //println(text) let confidence = dict["confidence"]! as Float let box = dict["boundingbox"] as NSValue if((text.utf16Count < 2 || confidence < 51) || (text.utf16Count < 4 && confidence < 60)){ continue } let rect = box.CGRectValue() _characterBoxes.append(CharBox(text: text, rect: rect)) texts.append(text) }*/ windex = 0 texts = Array<String>(); for windex = 0; windex < paragraphs.count; windex++ { let dict = paragraphs[windex] as Dictionary<String, AnyObject> let text = dict["text"]! as String println("paragraphs of \(windex) is \(text)") liguistingTagger(text) let confidence = dict["confidence"]! as Float let box = dict["boundingbox"] as NSValue if((text.utf16Count < 2 || confidence < 51) || (text.utf16Count < 4 && confidence < 60)){ continue } let rect = box.CGRectValue() _characterBoxes.append(CharBox(text: text, rect: rect)) texts.append(text) } var str : String = "" for (idx, item) in enumerate(texts) { str += item if idx < texts.count-1 { str += " " } } _recognizedText = str } func liguistingTagger(input:String) -> Array<String> { let options: NSLinguisticTaggerOptions = .OmitWhitespace | .OmitPunctuation | .JoinNames let schemes = NSLinguisticTagger.availableTagSchemesForLanguage("en") let tagger = NSLinguisticTagger(tagSchemes: schemes, options: Int(options.rawValue)) tagger.string = input var results = Array<String>(); tagger.enumerateTagsInRange(NSMakeRange(0, (input as NSString).length), scheme: NSLinguisticTagSchemeNameTypeOrLexicalClass, options: options) { (tag, tokenRange, sentenceRange, _) in let token = (input as NSString).substringWithRange(tokenRange) results.append(token) } println("liguistingTagger \(results)") return results; } }
mit
ec1d493fab2651590ee2631047f1272c
33.633136
191
0.583561
4.83237
false
false
false
false
mparrish91/gifRecipes
framework/Network/Session+messages.swift
1
11069
// // Session+messages.swift // reddift // // Created by sonson on 2015/05/19. // Copyright (c) 2015年 sonson. All rights reserved. // import Foundation extension Session { // MARK: Update message status /** Mark messages as "unread" - parameter id: A comma-separated list of thing fullnames - parameter modhash: A modhash, default is blank string not nil. - returns: Data task which requests search to reddit.com. */ @discardableResult public func markMessagesAsUnread(_ fullnames: [String], modhash: String = "", completion: @escaping (Result<JSONAny>) -> Void) throws -> URLSessionDataTask { let commaSeparatedFullameString = fullnames.joined(separator: ",") let parameter = ["id": commaSeparatedFullameString] guard let request = URLRequest.requestForOAuth(with: baseURL, path:"/api/unread_message", parameter:parameter, method:"POST", token:token) else { throw ReddiftError.canNotCreateURLRequest as NSError } let closure = {(data: Data?, response: URLResponse?, error: NSError?) -> Result<JSONAny> in return Result(from: Response(data: data, urlResponse: response), optional:error) .flatMap(response2Data) .flatMap(data2Json) } return executeTask(request, handleResponse: closure, completion: completion) } /** Mark messages as "read" - parameter id: A comma-separated list of thing fullnames - parameter modhash: A modhash, default is blank string not nil. - returns: Data task which requests search to reddit.com. */ @discardableResult public func markMessagesAsRead(_ fullnames: [String], modhash: String = "", completion: @escaping (Result<JSONAny>) -> Void) throws -> URLSessionDataTask { let commaSeparatedFullameString = fullnames.joined(separator: ",") let parameter = ["id": commaSeparatedFullameString] guard let request = URLRequest.requestForOAuth(with: baseURL, path:"/api/read_message", parameter:parameter, method:"POST", token:token) else { throw ReddiftError.canNotCreateURLRequest as NSError } let closure = {(data: Data?, response: URLResponse?, error: NSError?) -> Result<JSONAny> in return Result(from: Response(data: data, urlResponse: response), optional:error) .flatMap(response2Data) .flatMap(data2Json) } return executeTask(request, handleResponse: closure, completion: completion) } /** Mark all messages as "read" Queue up marking all messages for a user as read. This may take some time, and returns 202 to acknowledge acceptance of the request. - parameter modhash: A modhash, default is blank string not nil. - returns: Data task which requests search to reddit.com. */ @discardableResult public func markAllMessagesAsRead(_ modhash: String = "", completion: @escaping (Result<JSONAny>) -> Void) throws -> URLSessionDataTask { guard let request = URLRequest.requestForOAuth(with: baseURL, path:"/api/read_all_messages", parameter:nil, method:"POST", token:token) else { throw ReddiftError.canNotCreateURLRequest as NSError } let closure = {(data: Data?, response: URLResponse?, error: NSError?) -> Result<JSONAny> in return Result(from: Response(data: data, urlResponse: response), optional:error) .flatMap(response2Data) .flatMap(data2Json) } return executeTask(request, handleResponse: closure, completion: completion) } /** Collapse messages - parameter id: A comma-separated list of thing fullnames - parameter modhash: A modhash, default is blank string not nil. - returns: Data task which requests search to reddit.com. */ @discardableResult public func collapseMessages(_ fullnames: [String], modhash: String = "", completion: @escaping (Result<JSONAny>) -> Void) throws -> URLSessionDataTask { let commaSeparatedFullameString = fullnames.joined(separator: ",") let parameter = ["id": commaSeparatedFullameString] guard let request = URLRequest.requestForOAuth(with: baseURL, path:"/api/collapse_message", parameter:parameter, method:"POST", token:token) else { throw ReddiftError.canNotCreateURLRequest as NSError } let closure = {(data: Data?, response: URLResponse?, error: NSError?) -> Result<JSONAny> in return Result(from: Response(data: data, urlResponse: response), optional:error) .flatMap(response2Data) .flatMap(data2Json) } return executeTask(request, handleResponse: closure, completion: completion) } /** Uncollapse messages - parameter id: A comma-separated list of thing fullnames - parameter modhash: A modhash, default is blank string not nil. - returns: Data task which requests search to reddit.com. */ @discardableResult public func uncollapseMessages(_ fullnames: [String], modhash: String = "", completion: @escaping (Result<JSONAny>) -> Void) throws -> URLSessionDataTask { let commaSeparatedFullameString = fullnames.joined(separator: ",") let parameter = ["id": commaSeparatedFullameString] guard let request = URLRequest.requestForOAuth(with: baseURL, path:"/api/uncollapse_message", parameter:parameter, method:"POST", token:token) else { throw ReddiftError.canNotCreateURLRequest as NSError } let closure = {(data: Data?, response: URLResponse?, error: NSError?) -> Result<JSONAny> in return Result(from: Response(data: data, urlResponse: response), optional:error) .flatMap(response2Data) .flatMap(data2Json) } return executeTask(request, handleResponse: closure, completion: completion) } /** For blocking via inbox. - parameter id: fullname of a thing - parameter modhash: A modhash, default is blank string not nil. - returns: Data task which requests search to reddit.com. */ @discardableResult public func blockViaInbox(_ fullname: String, modhash: String = "", completion: @escaping (Result<JSONAny>) -> Void) throws -> URLSessionDataTask { let parameter = ["id": fullname] guard let request = URLRequest.requestForOAuth(with: Session.OAuthEndpointURL, path:"/api/block", parameter:parameter, method:"POST", token:token) else { throw ReddiftError.canNotCreateURLRequest as NSError } let closure = {(data: Data?, response: URLResponse?, error: NSError?) -> Result<JSONAny> in return Result(from: Response(data: data, urlResponse: response), optional:error) .flatMap(response2Data) .flatMap(data2Json) } return executeTask(request, handleResponse: closure, completion: completion) } /** For unblocking via inbox. - parameter id: fullname of a thing - parameter modhash: A modhash, default is blank string not nil. - returns: Data task which requests search to reddit.com. */ @discardableResult public func unblockViaInbox(_ fullname: String, modhash: String = "", completion: @escaping (Result<JSONAny>) -> Void) throws -> URLSessionDataTask { let parameter = ["id": fullname] guard let request = URLRequest.requestForOAuth(with: baseURL, path:"/api/unblock_subreddit", parameter:parameter, method:"POST", token:token) else { throw ReddiftError.canNotCreateURLRequest as NSError } let closure = {(data: Data?, response: URLResponse?, error: NSError?) -> Result<JSONAny> in return Result(from: Response(data: data, urlResponse: response), optional:error) .flatMap(response2Data) .flatMap(data2Json) } return executeTask(request, handleResponse: closure, completion: completion) } // MARK: Get messages /** Get the message from the specified box. - parameter messageWhere: The box from which you want to get your messages. - parameter limit: The maximum number of comments to return. Default is 100. - parameter completion: The completion handler to call when the load request is complete. - returns: Data task which requests search to reddit.com. */ @discardableResult public func getMessage(_ messageWhere: MessageWhere, limit: Int = 100, completion: @escaping (Result<Listing>) -> Void) throws -> URLSessionDataTask { guard let request = URLRequest.requestForOAuth(with: baseURL, path:"/message" + messageWhere.path, method:"GET", token:token) else { throw ReddiftError.canNotCreateURLRequest as NSError } let closure = {(data: Data?, response: URLResponse?, error: NSError?) -> Result<Listing> in return Result(from: Response(data: data, urlResponse: response), optional:error) .flatMap(response2Data) .flatMap(data2Json) .flatMap(json2RedditAny) .flatMap(redditAny2Object) } return executeTask(request, handleResponse: closure, completion: completion) } // MARK: Compose a message /** Compose new message to specified user. - parameter to: Account object of user to who you want to send a message. - parameter subject: A string no longer than 100 characters - parameter text: Raw markdown text - parameter fromSubreddit: Subreddit name? - parameter captcha: The user's response to the CAPTCHA challenge - parameter captchaIden: The identifier of the CAPTCHA challenge - parameter completion: The completion handler to call when the load request is complete. - returns: Data task which requests search to reddit.com. */ @discardableResult public func composeMessage(_ to: Account, subject: String, text: String, fromSubreddit: Subreddit, captcha: String, captchaIden: String, completion: @escaping (Result<JSONAny>) -> Void) throws -> URLSessionDataTask { let parameter = [ "api_type": "json", "captcha": captcha, "iden": captchaIden, "from_sr": fromSubreddit.displayName, "text": text, "subject": subject, "to": to.id ] guard let request = URLRequest.requestForOAuth(with: baseURL, path:"/api/submit", parameter:parameter, method:"POST", token:token) else { throw ReddiftError.canNotCreateURLRequest as NSError } let closure = {(data: Data?, response: URLResponse?, error: NSError?) -> Result<JSONAny> in return Result(from: Response(data: data, urlResponse: response), optional:error) .flatMap(response2Data) .flatMap(data2Json) .flatMap(json2RedditAny) .flatMap(redditAny2Object) } return executeTask(request, handleResponse: closure, completion: completion) } }
mit
514163ad7d6addc6a477c09137e9be77
51.20283
220
0.664679
4.940625
false
false
false
false
jhaigler94/cs4720-iOS
Pensieve/Pods/SwiftyDropbox/Source/FilesRoutes.swift
1
32905
/// Routes for the files namespace public class FilesRoutes { public let client : BabelClient init(client: BabelClient) { self.client = client } /** Returns the metadata for a file or folder. - parameter path: The path of a file or folder on Dropbox - parameter includeMediaInfo: If true, :field:'FileMetadata.media_info' is set for photo and video. - returns: Through the response callback, the caller will receive a `Files.Metadata` object on success or a `Files.GetMetadataError` object on failure. */ public func getMetadata(path path: String, includeMediaInfo: Bool = false) -> BabelRpcRequest<Files.MetadataSerializer, Files.GetMetadataErrorSerializer> { let request = Files.GetMetadataArg(path: path, includeMediaInfo: includeMediaInfo) return BabelRpcRequest(client: self.client, host: "meta", route: "/files/get_metadata", params: Files.GetMetadataArgSerializer().serialize(request), responseSerializer: Files.MetadataSerializer(), errorSerializer: Files.GetMetadataErrorSerializer()) } /** A longpoll endpoint to wait for changes on an account. In conjunction with listFolder, this call gives you a low-latency way to monitor an account for file changes. The connection will block until there are changes available or a timeout occurs. - parameter cursor: A cursor as returned by listFolder or listFolderContinue - parameter timeout: A timeout in seconds. The request will block for at most this length of time, plus up to 90 seconds of random jitter added to avoid the thundering herd problem. Care should be taken when using this parameter, as some network infrastructure does not support long timeouts. - returns: Through the response callback, the caller will receive a `Files.ListFolderLongpollResult` object on success or a `Files.ListFolderLongpollError` object on failure. */ public func listFolderLongpoll(cursor cursor: String, timeout: UInt64 = 30) -> BabelRpcRequest<Files.ListFolderLongpollResultSerializer, Files.ListFolderLongpollErrorSerializer> { let request = Files.ListFolderLongpollArg(cursor: cursor, timeout: timeout) return BabelRpcRequest(client: self.client, host: "notify", route: "/files/list_folder/longpoll", params: Files.ListFolderLongpollArgSerializer().serialize(request), responseSerializer: Files.ListFolderLongpollResultSerializer(), errorSerializer: Files.ListFolderLongpollErrorSerializer()) } /** Returns the contents of a folder. - parameter path: The path to the folder you want to see the contents of. - parameter recursive: If true, the list folder operation will be applied recursively to all subfolders and the response will contain contents of all subfolders. - parameter includeMediaInfo: If true, :field:'FileMetadata.media_info' is set for photo and video. - returns: Through the response callback, the caller will receive a `Files.ListFolderResult` object on success or a `Files.ListFolderError` object on failure. */ public func listFolder(path path: String, recursive: Bool = false, includeMediaInfo: Bool = false) -> BabelRpcRequest<Files.ListFolderResultSerializer, Files.ListFolderErrorSerializer> { let request = Files.ListFolderArg(path: path, recursive: recursive, includeMediaInfo: includeMediaInfo) return BabelRpcRequest(client: self.client, host: "meta", route: "/files/list_folder", params: Files.ListFolderArgSerializer().serialize(request), responseSerializer: Files.ListFolderResultSerializer(), errorSerializer: Files.ListFolderErrorSerializer()) } /** Once a cursor has been retrieved from listFolder, use this to paginate through all files and retrieve updates to the folder. - parameter cursor: The cursor returned by your last call to listFolder or listFolderContinue. - returns: Through the response callback, the caller will receive a `Files.ListFolderResult` object on success or a `Files.ListFolderContinueError` object on failure. */ public func listFolderContinue(cursor cursor: String) -> BabelRpcRequest<Files.ListFolderResultSerializer, Files.ListFolderContinueErrorSerializer> { let request = Files.ListFolderContinueArg(cursor: cursor) return BabelRpcRequest(client: self.client, host: "meta", route: "/files/list_folder/continue", params: Files.ListFolderContinueArgSerializer().serialize(request), responseSerializer: Files.ListFolderResultSerializer(), errorSerializer: Files.ListFolderContinueErrorSerializer()) } /** A way to quickly get a cursor for the folder's state. Unlike listFolder, listFolderGetLatestCursor doesn't return any entries. This endpoint is for app which only needs to know about new files and modifications and doesn't need to know about files that already exist in Dropbox. - parameter path: The path to the folder you want to see the contents of. - parameter recursive: If true, the list folder operation will be applied recursively to all subfolders and the response will contain contents of all subfolders. - parameter includeMediaInfo: If true, :field:'FileMetadata.media_info' is set for photo and video. - returns: Through the response callback, the caller will receive a `Files.ListFolderGetLatestCursorResult` object on success or a `Files.ListFolderError` object on failure. */ public func listFolderGetLatestCursor(path path: String, recursive: Bool = false, includeMediaInfo: Bool = false) -> BabelRpcRequest<Files.ListFolderGetLatestCursorResultSerializer, Files.ListFolderErrorSerializer> { let request = Files.ListFolderArg(path: path, recursive: recursive, includeMediaInfo: includeMediaInfo) return BabelRpcRequest(client: self.client, host: "meta", route: "/files/list_folder/get_latest_cursor", params: Files.ListFolderArgSerializer().serialize(request), responseSerializer: Files.ListFolderGetLatestCursorResultSerializer(), errorSerializer: Files.ListFolderErrorSerializer()) } /** Download a file from a user's Dropbox. - parameter path: The path of the file to download. - parameter rev: Deprecated. Please specify revision in :field:'path' instead - parameter destination: A closure used to compute the destination, given the temporary file location and the response - returns: Through the response callback, the caller will receive a `Files.FileMetadata` object on success or a `Files.DownloadError` object on failure. */ public func download(path path: String, rev: String? = nil, destination: (NSURL, NSHTTPURLResponse) -> NSURL) -> BabelDownloadRequest<Files.FileMetadataSerializer, Files.DownloadErrorSerializer> { let request = Files.DownloadArg(path: path, rev: rev) return BabelDownloadRequest(client: self.client, host: "content", route: "/files/download", params: Files.DownloadArgSerializer().serialize(request), responseSerializer: Files.FileMetadataSerializer(), errorSerializer: Files.DownloadErrorSerializer(), destination: destination) } /** Upload sessions allow you to upload a single file using multiple requests. This call starts a new upload session with the given data. You can then use uploadSessionAppend to add more data and uploadSessionFinish to save all the data to a file in Dropbox. - parameter body: The file to upload, as an NSData object - returns: Through the response callback, the caller will receive a `Files.UploadSessionStartResult` object on success or a `Void` object on failure. */ public func uploadSessionStart(body body: NSData) -> BabelUploadRequest<Files.UploadSessionStartResultSerializer, VoidSerializer> { return BabelUploadRequest(client: self.client, host: "content", route: "/files/upload_session/start", params: Serialization._VoidSerializer.serialize(), responseSerializer: Files.UploadSessionStartResultSerializer(), errorSerializer: Serialization._VoidSerializer, body: .Data(body)) } /** Upload sessions allow you to upload a single file using multiple requests. This call starts a new upload session with the given data. You can then use uploadSessionAppend to add more data and uploadSessionFinish to save all the data to a file in Dropbox. - parameter body: The file to upload, as an NSURL object - returns: Through the response callback, the caller will receive a `Files.UploadSessionStartResult` object on success or a `Void` object on failure. */ public func uploadSessionStart(body body: NSURL) -> BabelUploadRequest<Files.UploadSessionStartResultSerializer, VoidSerializer> { return BabelUploadRequest(client: self.client, host: "content", route: "/files/upload_session/start", params: Serialization._VoidSerializer.serialize(), responseSerializer: Files.UploadSessionStartResultSerializer(), errorSerializer: Serialization._VoidSerializer, body: .File(body)) } /** Upload sessions allow you to upload a single file using multiple requests. This call starts a new upload session with the given data. You can then use uploadSessionAppend to add more data and uploadSessionFinish to save all the data to a file in Dropbox. - parameter body: The file to upload, as an NSInputStream object - returns: Through the response callback, the caller will receive a `Files.UploadSessionStartResult` object on success or a `Void` object on failure. */ public func uploadSessionStart(body body: NSInputStream) -> BabelUploadRequest<Files.UploadSessionStartResultSerializer, VoidSerializer> { return BabelUploadRequest(client: self.client, host: "content", route: "/files/upload_session/start", params: Serialization._VoidSerializer.serialize(), responseSerializer: Files.UploadSessionStartResultSerializer(), errorSerializer: Serialization._VoidSerializer, body: .Stream(body)) } /** Append more data to an upload session. - parameter sessionId: The upload session ID (returned by uploadSessionStart). - parameter offset: The amount of data that has been uploaded so far. We use this to make sure upload data isn't lost or duplicated in the event of a network error. - parameter body: The file to upload, as an NSData object - returns: Through the response callback, the caller will receive a `Void` object on success or a `Files.UploadSessionLookupError` object on failure. */ public func uploadSessionAppend(sessionId sessionId: String, offset: UInt64, body: NSData) -> BabelUploadRequest<VoidSerializer, Files.UploadSessionLookupErrorSerializer> { let request = Files.UploadSessionCursor(sessionId: sessionId, offset: offset) return BabelUploadRequest(client: self.client, host: "content", route: "/files/upload_session/append", params: Files.UploadSessionCursorSerializer().serialize(request), responseSerializer: Serialization._VoidSerializer, errorSerializer: Files.UploadSessionLookupErrorSerializer(), body: .Data(body)) } /** Append more data to an upload session. - parameter sessionId: The upload session ID (returned by uploadSessionStart). - parameter offset: The amount of data that has been uploaded so far. We use this to make sure upload data isn't lost or duplicated in the event of a network error. - parameter body: The file to upload, as an NSURL object - returns: Through the response callback, the caller will receive a `Void` object on success or a `Files.UploadSessionLookupError` object on failure. */ public func uploadSessionAppend(sessionId sessionId: String, offset: UInt64, body: NSURL) -> BabelUploadRequest<VoidSerializer, Files.UploadSessionLookupErrorSerializer> { let request = Files.UploadSessionCursor(sessionId: sessionId, offset: offset) return BabelUploadRequest(client: self.client, host: "content", route: "/files/upload_session/append", params: Files.UploadSessionCursorSerializer().serialize(request), responseSerializer: Serialization._VoidSerializer, errorSerializer: Files.UploadSessionLookupErrorSerializer(), body: .File(body)) } /** Append more data to an upload session. - parameter sessionId: The upload session ID (returned by uploadSessionStart). - parameter offset: The amount of data that has been uploaded so far. We use this to make sure upload data isn't lost or duplicated in the event of a network error. - parameter body: The file to upload, as an NSInputStream object - returns: Through the response callback, the caller will receive a `Void` object on success or a `Files.UploadSessionLookupError` object on failure. */ public func uploadSessionAppend(sessionId sessionId: String, offset: UInt64, body: NSInputStream) -> BabelUploadRequest<VoidSerializer, Files.UploadSessionLookupErrorSerializer> { let request = Files.UploadSessionCursor(sessionId: sessionId, offset: offset) return BabelUploadRequest(client: self.client, host: "content", route: "/files/upload_session/append", params: Files.UploadSessionCursorSerializer().serialize(request), responseSerializer: Serialization._VoidSerializer, errorSerializer: Files.UploadSessionLookupErrorSerializer(), body: .Stream(body)) } /** Finish an upload session and save the uploaded data to the given file path. - parameter cursor: Contains the upload session ID and the offset. - parameter commit: Contains the path and other optional modifiers for the commit. - parameter body: The file to upload, as an NSData object - returns: Through the response callback, the caller will receive a `Files.FileMetadata` object on success or a `Files.UploadSessionFinishError` object on failure. */ public func uploadSessionFinish(cursor cursor: Files.UploadSessionCursor, commit: Files.CommitInfo, body: NSData) -> BabelUploadRequest<Files.FileMetadataSerializer, Files.UploadSessionFinishErrorSerializer> { let request = Files.UploadSessionFinishArg(cursor: cursor, commit: commit) return BabelUploadRequest(client: self.client, host: "content", route: "/files/upload_session/finish", params: Files.UploadSessionFinishArgSerializer().serialize(request), responseSerializer: Files.FileMetadataSerializer(), errorSerializer: Files.UploadSessionFinishErrorSerializer(), body: .Data(body)) } /** Finish an upload session and save the uploaded data to the given file path. - parameter cursor: Contains the upload session ID and the offset. - parameter commit: Contains the path and other optional modifiers for the commit. - parameter body: The file to upload, as an NSURL object - returns: Through the response callback, the caller will receive a `Files.FileMetadata` object on success or a `Files.UploadSessionFinishError` object on failure. */ public func uploadSessionFinish(cursor cursor: Files.UploadSessionCursor, commit: Files.CommitInfo, body: NSURL) -> BabelUploadRequest<Files.FileMetadataSerializer, Files.UploadSessionFinishErrorSerializer> { let request = Files.UploadSessionFinishArg(cursor: cursor, commit: commit) return BabelUploadRequest(client: self.client, host: "content", route: "/files/upload_session/finish", params: Files.UploadSessionFinishArgSerializer().serialize(request), responseSerializer: Files.FileMetadataSerializer(), errorSerializer: Files.UploadSessionFinishErrorSerializer(), body: .File(body)) } /** Finish an upload session and save the uploaded data to the given file path. - parameter cursor: Contains the upload session ID and the offset. - parameter commit: Contains the path and other optional modifiers for the commit. - parameter body: The file to upload, as an NSInputStream object - returns: Through the response callback, the caller will receive a `Files.FileMetadata` object on success or a `Files.UploadSessionFinishError` object on failure. */ public func uploadSessionFinish(cursor cursor: Files.UploadSessionCursor, commit: Files.CommitInfo, body: NSInputStream) -> BabelUploadRequest<Files.FileMetadataSerializer, Files.UploadSessionFinishErrorSerializer> { let request = Files.UploadSessionFinishArg(cursor: cursor, commit: commit) return BabelUploadRequest(client: self.client, host: "content", route: "/files/upload_session/finish", params: Files.UploadSessionFinishArgSerializer().serialize(request), responseSerializer: Files.FileMetadataSerializer(), errorSerializer: Files.UploadSessionFinishErrorSerializer(), body: .Stream(body)) } /** Create a new file with the contents provided in the request. - parameter path: Path in the user's Dropbox to save the file. - parameter mode: Selects what to do if the file already exists. - parameter autorename: If there's a conflict, as determined by mode, have the Dropbox server try to autorename the file to avoid conflict. - parameter clientModified: The value to store as the clientModified timestamp. Dropbox automatically records the time at which the file was written to the Dropbox servers. It can also record an additional timestamp, provided by Dropbox desktop clients, mobile clients, and API apps of when the file was actually created or modified. - parameter mute: Normally, users are made aware of any file modifications in their Dropbox account via notifications in the client software. If true, this tells the clients that this modification shouldn't result in a user notification. - parameter body: The file to upload, as an NSData object - returns: Through the response callback, the caller will receive a `Files.FileMetadata` object on success or a `Files.UploadError` object on failure. */ public func upload(path path: String, mode: Files.WriteMode = .Add, autorename: Bool = false, clientModified: NSDate? = nil, mute: Bool = false, body: NSData) -> BabelUploadRequest<Files.FileMetadataSerializer, Files.UploadErrorSerializer> { let request = Files.CommitInfo(path: path, mode: mode, autorename: autorename, clientModified: clientModified, mute: mute) return BabelUploadRequest(client: self.client, host: "content", route: "/files/upload", params: Files.CommitInfoSerializer().serialize(request), responseSerializer: Files.FileMetadataSerializer(), errorSerializer: Files.UploadErrorSerializer(), body: .Data(body)) } /** Create a new file with the contents provided in the request. - parameter path: Path in the user's Dropbox to save the file. - parameter mode: Selects what to do if the file already exists. - parameter autorename: If there's a conflict, as determined by mode, have the Dropbox server try to autorename the file to avoid conflict. - parameter clientModified: The value to store as the clientModified timestamp. Dropbox automatically records the time at which the file was written to the Dropbox servers. It can also record an additional timestamp, provided by Dropbox desktop clients, mobile clients, and API apps of when the file was actually created or modified. - parameter mute: Normally, users are made aware of any file modifications in their Dropbox account via notifications in the client software. If true, this tells the clients that this modification shouldn't result in a user notification. - parameter body: The file to upload, as an NSURL object - returns: Through the response callback, the caller will receive a `Files.FileMetadata` object on success or a `Files.UploadError` object on failure. */ public func upload(path path: String, mode: Files.WriteMode = .Add, autorename: Bool = false, clientModified: NSDate? = nil, mute: Bool = false, body: NSURL) -> BabelUploadRequest<Files.FileMetadataSerializer, Files.UploadErrorSerializer> { let request = Files.CommitInfo(path: path, mode: mode, autorename: autorename, clientModified: clientModified, mute: mute) return BabelUploadRequest(client: self.client, host: "content", route: "/files/upload", params: Files.CommitInfoSerializer().serialize(request), responseSerializer: Files.FileMetadataSerializer(), errorSerializer: Files.UploadErrorSerializer(), body: .File(body)) } /** Create a new file with the contents provided in the request. - parameter path: Path in the user's Dropbox to save the file. - parameter mode: Selects what to do if the file already exists. - parameter autorename: If there's a conflict, as determined by mode, have the Dropbox server try to autorename the file to avoid conflict. - parameter clientModified: The value to store as the clientModified timestamp. Dropbox automatically records the time at which the file was written to the Dropbox servers. It can also record an additional timestamp, provided by Dropbox desktop clients, mobile clients, and API apps of when the file was actually created or modified. - parameter mute: Normally, users are made aware of any file modifications in their Dropbox account via notifications in the client software. If true, this tells the clients that this modification shouldn't result in a user notification. - parameter body: The file to upload, as an NSInputStream object - returns: Through the response callback, the caller will receive a `Files.FileMetadata` object on success or a `Files.UploadError` object on failure. */ public func upload(path path: String, mode: Files.WriteMode = .Add, autorename: Bool = false, clientModified: NSDate? = nil, mute: Bool = false, body: NSInputStream) -> BabelUploadRequest<Files.FileMetadataSerializer, Files.UploadErrorSerializer> { let request = Files.CommitInfo(path: path, mode: mode, autorename: autorename, clientModified: clientModified, mute: mute) return BabelUploadRequest(client: self.client, host: "content", route: "/files/upload", params: Files.CommitInfoSerializer().serialize(request), responseSerializer: Files.FileMetadataSerializer(), errorSerializer: Files.UploadErrorSerializer(), body: .Stream(body)) } /** Searches for files and folders. - parameter path: The path in the user's Dropbox to search. Should probably be a folder. - parameter query: The string to search for. The search string is split on spaces into multiple tokens. For file name searching, the last token is used for prefix matching (i.e. "bat c" matches "bat cave" but not "batman car"). - parameter start: The starting index within the search results (used for paging). - parameter maxResults: The maximum number of search results to return. - parameter mode: The search mode (filename, filename_and_content, or deleted_filename). - returns: Through the response callback, the caller will receive a `Files.SearchResult` object on success or a `Files.SearchError` object on failure. */ public func search(path path: String, query: String, start: UInt64 = 0, maxResults: UInt64 = 100, mode: Files.SearchMode = .Filename) -> BabelRpcRequest<Files.SearchResultSerializer, Files.SearchErrorSerializer> { let request = Files.SearchArg(path: path, query: query, start: start, maxResults: maxResults, mode: mode) return BabelRpcRequest(client: self.client, host: "meta", route: "/files/search", params: Files.SearchArgSerializer().serialize(request), responseSerializer: Files.SearchResultSerializer(), errorSerializer: Files.SearchErrorSerializer()) } /** Create a folder at a given path. - parameter path: Path in the user's Dropbox to create. - returns: Through the response callback, the caller will receive a `Files.FolderMetadata` object on success or a `Files.CreateFolderError` object on failure. */ public func createFolder(path path: String) -> BabelRpcRequest<Files.FolderMetadataSerializer, Files.CreateFolderErrorSerializer> { let request = Files.CreateFolderArg(path: path) return BabelRpcRequest(client: self.client, host: "meta", route: "/files/create_folder", params: Files.CreateFolderArgSerializer().serialize(request), responseSerializer: Files.FolderMetadataSerializer(), errorSerializer: Files.CreateFolderErrorSerializer()) } /** Delete the file or folder at a given path. If the path is a folder, all its contents will be deleted too. - parameter path: Path in the user's Dropbox to delete. - returns: Through the response callback, the caller will receive a `Files.Metadata` object on success or a `Files.DeleteError` object on failure. */ public func delete(path path: String) -> BabelRpcRequest<Files.MetadataSerializer, Files.DeleteErrorSerializer> { let request = Files.DeleteArg(path: path) return BabelRpcRequest(client: self.client, host: "meta", route: "/files/delete", params: Files.DeleteArgSerializer().serialize(request), responseSerializer: Files.MetadataSerializer(), errorSerializer: Files.DeleteErrorSerializer()) } /** Permanently delete the file or folder at a given path (see https://www.dropbox.com/en/help/40). - parameter path: Path in the user's Dropbox to delete. - returns: Through the response callback, the caller will receive a `Void` object on success or a `Files.DeleteError` object on failure. */ public func permanentlyDelete(path path: String) -> BabelRpcRequest<VoidSerializer, Files.DeleteErrorSerializer> { let request = Files.DeleteArg(path: path) return BabelRpcRequest(client: self.client, host: "meta", route: "/files/permanently_delete", params: Files.DeleteArgSerializer().serialize(request), responseSerializer: Serialization._VoidSerializer, errorSerializer: Files.DeleteErrorSerializer()) } /** Copy a file or folder to a different location in the user's Dropbox. If the source path is a folder all its contents will be copied. - parameter fromPath: Path in the user's Dropbox to be copied or moved. - parameter toPath: Path in the user's Dropbox that is the destination. - returns: Through the response callback, the caller will receive a `Files.Metadata` object on success or a `Files.RelocationError` object on failure. */ public func copy(fromPath fromPath: String, toPath: String) -> BabelRpcRequest<Files.MetadataSerializer, Files.RelocationErrorSerializer> { let request = Files.RelocationArg(fromPath: fromPath, toPath: toPath) return BabelRpcRequest(client: self.client, host: "meta", route: "/files/copy", params: Files.RelocationArgSerializer().serialize(request), responseSerializer: Files.MetadataSerializer(), errorSerializer: Files.RelocationErrorSerializer()) } /** Move a file or folder to a different location in the user's Dropbox. If the source path is a folder all its contents will be moved. - parameter fromPath: Path in the user's Dropbox to be copied or moved. - parameter toPath: Path in the user's Dropbox that is the destination. - returns: Through the response callback, the caller will receive a `Files.Metadata` object on success or a `Files.RelocationError` object on failure. */ public func move(fromPath fromPath: String, toPath: String) -> BabelRpcRequest<Files.MetadataSerializer, Files.RelocationErrorSerializer> { let request = Files.RelocationArg(fromPath: fromPath, toPath: toPath) return BabelRpcRequest(client: self.client, host: "meta", route: "/files/move", params: Files.RelocationArgSerializer().serialize(request), responseSerializer: Files.MetadataSerializer(), errorSerializer: Files.RelocationErrorSerializer()) } /** Get a thumbnail for an image. This method currently supports files with the following file extensions: jpg, jpeg, png, tiff, tif, gif and bmp. Photos that are larger than 20MB in size won't be converted to a thumbnail. - parameter path: The path to the image file you want to thumbnail. - parameter format: The format for the thumbnail image, jpeg (default) or png. For images that are photos, jpeg should be preferred, while png is better for screenshots and digital arts. - parameter size: The size for the thumbnail image. - parameter destination: A closure used to compute the destination, given the temporary file location and the response - returns: Through the response callback, the caller will receive a `Files.FileMetadata` object on success or a `Files.ThumbnailError` object on failure. */ public func getThumbnail(path path: String, format: Files.ThumbnailFormat = .Jpeg, size: Files.ThumbnailSize = .W64h64, destination: (NSURL, NSHTTPURLResponse) -> NSURL) -> BabelDownloadRequest<Files.FileMetadataSerializer, Files.ThumbnailErrorSerializer> { let request = Files.ThumbnailArg(path: path, format: format, size: size) return BabelDownloadRequest(client: self.client, host: "content", route: "/files/get_thumbnail", params: Files.ThumbnailArgSerializer().serialize(request), responseSerializer: Files.FileMetadataSerializer(), errorSerializer: Files.ThumbnailErrorSerializer(), destination: destination) } /** Get a preview for a file. Currently previews are only generated for the files with the following extensions: .doc, .docx, .docm, .ppt, .pps, .ppsx, .ppsm, .pptx, .pptm, .xls, .xlsx, .xlsm, .rtf - parameter path: The path of the file to preview. - parameter rev: Deprecated. Please specify revision in :field:'path' instead - parameter destination: A closure used to compute the destination, given the temporary file location and the response - returns: Through the response callback, the caller will receive a `Files.FileMetadata` object on success or a `Files.PreviewError` object on failure. */ public func getPreview(path path: String, rev: String? = nil, destination: (NSURL, NSHTTPURLResponse) -> NSURL) -> BabelDownloadRequest<Files.FileMetadataSerializer, Files.PreviewErrorSerializer> { let request = Files.PreviewArg(path: path, rev: rev) return BabelDownloadRequest(client: self.client, host: "content", route: "/files/get_preview", params: Files.PreviewArgSerializer().serialize(request), responseSerializer: Files.FileMetadataSerializer(), errorSerializer: Files.PreviewErrorSerializer(), destination: destination) } /** Return revisions of a file - parameter path: The path to the file you want to see the revisions of. - parameter limit: The maximum number of revision entries returned. - returns: Through the response callback, the caller will receive a `Files.ListRevisionsResult` object on success or a `Files.ListRevisionsError` object on failure. */ public func listRevisions(path path: String, limit: UInt64 = 10) -> BabelRpcRequest<Files.ListRevisionsResultSerializer, Files.ListRevisionsErrorSerializer> { let request = Files.ListRevisionsArg(path: path, limit: limit) return BabelRpcRequest(client: self.client, host: "meta", route: "/files/list_revisions", params: Files.ListRevisionsArgSerializer().serialize(request), responseSerializer: Files.ListRevisionsResultSerializer(), errorSerializer: Files.ListRevisionsErrorSerializer()) } /** Restore a file to a specific revision - parameter path: The path to the file you want to restore. - parameter rev: The revision to restore for the file. - returns: Through the response callback, the caller will receive a `Files.FileMetadata` object on success or a `Files.RestoreError` object on failure. */ public func restore(path path: String, rev: String) -> BabelRpcRequest<Files.FileMetadataSerializer, Files.RestoreErrorSerializer> { let request = Files.RestoreArg(path: path, rev: rev) return BabelRpcRequest(client: self.client, host: "meta", route: "/files/restore", params: Files.RestoreArgSerializer().serialize(request), responseSerializer: Files.FileMetadataSerializer(), errorSerializer: Files.RestoreErrorSerializer()) } }
apache-2.0
1850426c82b89f7a512c6e69245cce56
74.817972
313
0.73539
5.171303
false
false
false
false
XCEssentials/ProjectGenerator
Sources/Manager.swift
1
934
// // Manager.swift // MKHProjGen // // Created by Maxim Khatskevich on 3/16/17. // Copyright © 2017 Maxim Khatskevich. All rights reserved. // public enum Manager { public static func prepareSpec( _ format: Spec.Format, for project: Project ) -> String { let rawSpec: RawSpec //=== switch format { case .v1_2_1: rawSpec = Spec_1_2_1.generate(for: project) case .v1_3_0: rawSpec = Spec_1_3_0.generate(for: project) case .v2_0_0: rawSpec = Spec_2_0_0.generate(for: project) case .v2_1_0: rawSpec = Spec_2_1_0.generate(for: project) } //=== return rawSpec .map { "\(Spec.ident($0))\($1)" } .joined(separator: "\n") } }
mit
07bbfa93ec49af713ec2d023b13830e1
20.204545
60
0.444802
3.920168
false
false
false
false
timd/ProiOSTableCollectionViews
Ch09/InCellCV/InCellCV/ViewController.swift
1
3372
// // ViewController.swift // InCellCV // // Created by Tim on 07/11/15. // Copyright © 2015 Tim Duckett. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet var collectionView: UICollectionView! var cvData = [Int]() override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. setupData() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } extension ViewController { func setupData() { for index in 0...100 { cvData.append(index) } } func addButtonToCell(cell: UICollectionViewCell) { guard cell.contentView.viewWithTag(1000) != nil else { return } let button = UIButton(type: UIButtonType.RoundedRect) button.tag = 1000 button.setTitle("Tap me!", forState: UIControlState.Normal) button.sizeToFit() button.translatesAutoresizingMaskIntoConstraints = false button.addTarget(self, action: "didTapButtonInCell:", forControlEvents: UIControlEvents.TouchUpInside) let vConstraint = NSLayoutConstraint(item: button, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: cell.contentView, attribute: NSLayoutAttribute.CenterX, multiplier: 1.0, constant: 0) let hConstraint = NSLayoutConstraint(item: button, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: cell.contentView, attribute: NSLayoutAttribute.Bottom, multiplier: 1.0, constant: -10) cell.contentView.addSubview(button) cell.contentView.addConstraints([vConstraint, hConstraint]) } func didTapButtonInCell(sender: UIButton) { let cell = sender.superview!.superview as! UICollectionViewCell let indexPathAtTap = collectionView.indexPathForCell(cell) let alert = UIAlertController(title: "Something happened!", message: "A button was tapped in item \(indexPathAtTap!.row)", preferredStyle: .Alert) let action = UIAlertAction(title: "OK", style: .Default, handler: nil) alert.addAction(action) self.presentViewController(alert, animated: true, completion: nil) } } extension ViewController: UICollectionViewDataSource { func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int { return 1 } func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return cvData.count } func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCellWithReuseIdentifier("CellIdentifier", forIndexPath: indexPath) if let label = cell.contentView.viewWithTag(1000) as? UILabel { label.text = "Item \(cvData[indexPath.row])" } addButtonToCell(cell) cell.layer.borderColor = UIColor.blackColor().CGColor cell.layer.borderWidth = 1.0 return cell } }
mit
1e8218624845b39cf84595a86d002362
31.413462
225
0.661821
5.410915
false
false
false
false
omochi/numsw
Playgrounds/LineGraphRenderer.swift
1
2562
// // LineGraphRenderer.swift // sandbox // // Created by omochimetaru on 2017/03/04. // Copyright © 2017年 sonson. All rights reserved. // import UIKit import CoreGraphics public class LineGraphRenderer: Renderer { public init(viewport: CGRect, line: LineGraph) { self.viewport = viewport self.line = line } public let viewport: CGRect public let line: LineGraph public func render(context: CGContext, windowSize: CGSize) { viewportTransform = RendererUtil.computeViewportTransform(viewport: viewport, windowSize: windowSize) drawLine(context: context, points: line.points) } // public func drawPoints(context ctx: CGContext) { // ctx.setStrokeColor(UIColor.white.cgColor) // // if lines.count >= 1 { // drawLine(context: ctx, points: lines[0].points) // } // if lines.count >= 2 { // drawSanpuzu(context: ctx, line: lines[1]) // } // } public func drawSanpuzu(context ctx: CGContext, line: LineGraph) { ctx.setStrokeColor(UIColor.green.cgColor) let t = viewportTransform! for point in line.points { let p = point.applying(t) RendererUtil.drawLine(context: ctx, points: [ CGPoint(x: p.x - 10, y: p.y - 10), CGPoint(x: p.x + 10, y: p.y + 10) ]) RendererUtil.drawLine(context: ctx, points: [ CGPoint(x: p.x - 10, y: p.y + 10), CGPoint(x: p.x + 10, y: p.y - 10) ]) } } public func drawDebugX(context ctx: CGContext, point0: CGPoint, point1: CGPoint) { ctx.setStrokeColor(UIColor.red.cgColor) drawLine(context: ctx, points: [ CGPoint(x: point0.x, y: point0.y), CGPoint(x: point1.x, y: point1.y) ]) ctx.setStrokeColor(UIColor.green.cgColor) drawLine(context: ctx, points: [ CGPoint(x: point1.x, y: point0.y), CGPoint(x: point0.x, y: point1.y) ]) } public func drawLine(context: CGContext, points: [CGPoint]) { context.setStrokeColor(UIColor.white.cgColor) let t = viewportTransform! let points = points.map { $0.applying(t) } RendererUtil.drawLine(context: context, points: points) } private var viewportTransform: CGAffineTransform? }
mit
579f2409033a49fd7449d2e4011010dc
29.464286
109
0.550215
4.08134
false
false
false
false
SpencerCurtis/GYI
GYI/MenuPopoverViewController.swift
1
19754
// MenuPopoverViewController.swift // GYI // // Created by Spencer Curtis on 1/12/17. // Copyright © 2017 Spencer Curtis. All rights reserved. // import Cocoa class MenuPopoverViewController: NSViewController, NSPopoverDelegate, AccountCreationDelegate, AccountDeletionDelegate, ExecutableUpdateDelegate, VideoPasswordSubmissionDelegate { // MARK: - Properties @IBOutlet weak var inputTextField: NSTextField! @IBOutlet weak var outputPathControl: NSPathControl! @IBOutlet weak var accountSelectionPopUpButton: NSPopUpButtonCell! @IBOutlet weak var submitButton: NSButton! @IBOutlet weak var videoIsPasswordProtectedCheckboxButtton: NSButton! @IBOutlet weak var defaultOutputFolderCheckboxButton: NSButton! @IBOutlet weak var downloadProgressIndicator: NSProgressIndicator! @IBOutlet weak var playlistCountProgressIndicator: NSProgressIndicator! @IBOutlet weak var timeLeftLabel: NSTextField! @IBOutlet weak var videoCountLabel: NSTextField! @IBOutlet weak var downloadSpeedLabel: NSTextField! @IBOutlet weak var automaticallyUpdateYoutubeDLCheckboxButton: NSButton! let downloadController = DownloadController.shared var downloadProgressIndicatorIsAnimating = false var playlistCountProgressIndicatorIsAnimating = false var applicationIsDownloadingVideo = false var currentVideo = 1 var numberOfVideosInPlaylist = 1 var videoNeedsAudio = false private let defaultOutputFolderKey = "defaultOutputFolder" var executableUpdatingView: NSView! var userDidCancelDownload = false var appearance: String! // MARK: - View Controller Lifecycle override func viewDidLoad() { super.viewDidLoad() self.view.layer?.backgroundColor = CGColor.white NotificationCenter.default.addObserver(self, selector: #selector(processDidEnd), name: processDidEndNotification, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(presentPasswordProtectedVideoAlert), name: downloadController.videoIsPasswordProtectedNotification, object: nil) downloadController.downloadDelegate = self downloadSpeedLabel.stringValue = "0KiB/s" videoCountLabel.stringValue = "No video downloading" timeLeftLabel.stringValue = "Add a video above" downloadProgressIndicator.doubleValue = 0.0 playlistCountProgressIndicator.doubleValue = 0.0 let userWantsAutoUpdate = UserDefaults.standard.bool(forKey: downloadController.autoUpdateYoutubeDLKey) automaticallyUpdateYoutubeDLCheckboxButton.state = userWantsAutoUpdate ? .on : .off outputPathControl.doubleAction = #selector(openOutputFolderPanel) if let defaultPath = UserDefaults.standard.url(forKey: defaultOutputFolderKey) { outputPathControl.url = defaultPath print(outputPathControl.url!) } else { outputPathControl.url = URL(string: "file:///Users/\(NSUserName)/Downloads") } defaultOutputFolderCheckboxButton.state = NSControl.StateValue(rawValue: 1) guard let popover = downloadController.popover else { return } popover.delegate = self } override func viewWillAppear() { setupAccountSelectionPopUpButton() } @objc func processDidEnd() { submitButton.title = "Submit" if !userDidCancelDownload { inputTextField.stringValue = "" } downloadProgressIndicatorIsAnimating = false guard timeLeftLabel.stringValue != "Video already downloaded" else { return } playlistCountProgressIndicator.doubleValue = 100.0 if downloadProgressIndicator.doubleValue == 100.0 { playlistCountProgressIndicator.doubleValue = 100.0 timeLeftLabel.stringValue = "Download Complete" } else if downloadController.userDidCancelDownload { timeLeftLabel.stringValue = "Download canceled" } else if downloadProgressIndicator.doubleValue != 100.0 { timeLeftLabel.stringValue = "Error downloading video" } downloadSpeedLabel.stringValue = "0KiB/s" downloadSpeedLabel.isHidden = true applicationIsDownloadingVideo = false downloadProgressIndicator.stopAnimation(self) playlistCountProgressIndicator.stopAnimation(self) } func presentVideoPasswordSubmissionSheet() { let storyboard = NSStoryboard(name: NSStoryboard.Name(rawValue: "Main"), bundle: nil) guard let accountModificationWC = (storyboard.instantiateController(withIdentifier: NSStoryboard.SceneIdentifier(rawValue: "VideoPasswordSubmissionWC")) as? NSWindowController), let window = accountModificationWC.window, let videoPasswordSubmissionVC = window.contentViewController as? VideoPasswordSubmissionViewController else { return } videoPasswordSubmissionVC.delegate = self self.view.window?.beginSheet(window, completionHandler: nil) } @IBAction func manageAccountsButtonClicked(_ sender: NSMenuItem) { manageAccountsSheet() } // MARK: - Account Creation/Deletion Delegates func newAccountWasCreated() { setupAccountSelectionPopUpButton() } func accountWasDeletedWith(title: String) { accountSelectionPopUpButton.removeItem(withTitle: title) } func manageAccountsSheet() { let storyboard = NSStoryboard(name: NSStoryboard.Name(rawValue: "Main"), bundle: nil) guard let accountModificationWC = (storyboard.instantiateController(withIdentifier: NSStoryboard.SceneIdentifier(rawValue: "AccountModificationWC")) as? NSWindowController), let window = accountModificationWC.window, let accountModificationVC = window.contentViewController as? AccountModificationViewController else { return } accountModificationVC.delegate = self self.view.window?.beginSheet(window, completionHandler: { (response) in self.setupAccountSelectionPopUpButton() }) } func setupAccountSelectionPopUpButton() { for account in AccountController.accounts.reversed() { guard let title = account.title else { return } accountSelectionPopUpButton.insertItem(withTitle: title, at: 0) } } // MARK: - Output folder selection @IBAction func chooseOutputFolderButtonTapped(_ sender: NSButton) { openOutputFolderPanel() } @IBAction func defaultOutputFolderButtonClicked(_ sender: NSButton) { if sender.state.rawValue == 1 { let path = outputPathControl.url UserDefaults.standard.set(path, forKey: defaultOutputFolderKey) } } @objc func openOutputFolderPanel() { let openPanel = NSOpenPanel() openPanel.allowsMultipleSelection = false openPanel.canChooseFiles = false openPanel.canChooseDirectories = true openPanel.begin { (result) in guard let path = openPanel.url, result.rawValue == NSFileHandlingPanelOKButton else { return } if self.outputPathControl.url != path { self.defaultOutputFolderCheckboxButton.state = NSControl.StateValue(rawValue: 0) } self.outputPathControl.url = path if self.appearance == "Dark" { self.outputPathControl.pathComponentCells().forEach({$0.textColor = NSColor.white}) } } } // MARK: - ExecutableUpdateDelegate func executableDidBeginUpdateWith(dataString: String) { self.view.addSubview(self.executableUpdatingView, positioned: .above, relativeTo: nil) } func executableDidFinishUpdatingWith(dataString: String) { } func setupExecutableUpdatingView() { let executableUpdatingView = NSView(frame: self.view.frame) executableUpdatingView.wantsLayer = true executableUpdatingView.layer?.backgroundColor = appearance == "Dark" ? .white : .black self.executableUpdatingView = executableUpdatingView // WARNING: - Remove this. This is only for testing. self.view.addSubview(self.executableUpdatingView, positioned: .above, relativeTo: nil) } // MARK: - Password Protected Videos @objc func presentPasswordProtectedVideoAlert() { let storyboard = NSStoryboard(name: NSStoryboard.Name(rawValue: "Main"), bundle: nil) guard let accountModificationWC = (storyboard.instantiateController(withIdentifier: NSStoryboard.SceneIdentifier(rawValue: "VideoPasswordSubmissionWC")) as? NSWindowController), let window = accountModificationWC.window, let videoPasswordSubmissionVC = window.contentViewController as? VideoPasswordSubmissionViewController else { return } videoPasswordSubmissionVC.delegate = self self.view.window?.beginSheet(window, completionHandler: { (response) in }) } // MARK: - Appearance func changeAppearanceForMenuStyle() { if appearance == "Dark" { outputPathControl.pathComponentCells().forEach({$0.textColor = NSColor.white}) inputTextField.focusRingType = .none } else { outputPathControl.pathComponentCells().forEach({$0.textColor = NSColor.black}) inputTextField.focusRingType = .default inputTextField.backgroundColor = .clear } } func popoverWillShow(_ notification: Notification) { appearance = UserDefaults.standard.string(forKey: "AppleInterfaceStyle") ?? "Light" changeAppearanceForMenuStyle() guard let executableUpdatingView = executableUpdatingView else { return } executableUpdatingView.layer?.backgroundColor = appearance == "Dark" ? .white : .black } // MARK: - Other override func cancelOperation(_ sender: Any?) { NotificationCenter.default.post(name: closePopoverNotification, object: self) } @IBAction func quitButtonClicked(_ sender: Any) { if applicationIsDownloadingVideo { let alert: NSAlert = NSAlert() alert.messageText = "You are currently downloading a video." alert.informativeText = "Do you stil want to quit GYI?" alert.alertStyle = NSAlert.Style.informational alert.addButton(withTitle: "OK") alert.addButton(withTitle: "Cancel") guard let window = self.view.window else { return } alert.beginSheetModal(for: window, completionHandler: { (response) in if response == NSApplication.ModalResponse.alertFirstButtonReturn { NSApplication.shared.terminate(self) } }) } else { downloadController.popover?.performClose(nil) Timer.scheduledTimer(timeInterval: 0.5, target: self, selector: #selector(terminateApp), userInfo: nil, repeats: false) } } } // MARK: - Download Delegate/ General Downloading extension MenuPopoverViewController: DownloadDelegate { @IBAction func submitButtonTapped(_ sender: NSButton) { guard inputTextField.stringValue != "" else { return } guard videoIsPasswordProtectedCheckboxButtton.state.rawValue == 0 else { presentVideoPasswordSubmissionSheet(); return } if downloadController.applicationIsDownloading { downloadController.terminateCurrentTask() submitButton.title = "Submit" downloadController.userDidCancelDownload = true } else { beginDownloadOfVideoWith(url: inputTextField.stringValue) } } func beginDownloadOfVideoWith(url: String) { submitButton.title = "Stop Download" downloadController.applicationIsDownloading = true self.processDidBegin() guard let outputFolder = outputPathControl.url?.absoluteString else { return } let outputWithoutPrefix = outputFolder.replacingOccurrences(of: "file://", with: "") let output = outputWithoutPrefix + "%(title)s.%(ext)s" guard let selectedAccountItem = accountSelectionPopUpButton.selectedItem else { return } let account = AccountController.accounts.filter({$0.title == selectedAccountItem.title}).first downloadController.downloadVideoAt(videoURL: url, outputFolder: output, account: account) } func beginDownloadOfVideoWith(additionalArguments: [String]) { let url = inputTextField.stringValue submitButton.title = "Stop Download" downloadController.applicationIsDownloading = true self.processDidBegin() guard let outputFolder = outputPathControl.url?.absoluteString else { return } let outputWithoutPrefix = outputFolder.replacingOccurrences(of: "file://", with: "") let output = outputWithoutPrefix + "%(title)s.%(ext)s" guard let selectedAccountItem = accountSelectionPopUpButton.selectedItem else { return } let account = AccountController.accounts.filter({$0.title == selectedAccountItem.title}).first downloadController.downloadVideoAt(videoURL: url, outputFolder: output, account: account, additionalArguments: additionalArguments) } func processDidBegin() { videoCountLabel.stringValue = "Video 1 of 1" timeLeftLabel.stringValue = "Getting video..." playlistCountProgressIndicator.doubleValue = 0.0 downloadProgressIndicator.doubleValue = 0.0 downloadProgressIndicator.isIndeterminate = true downloadProgressIndicator.startAnimation(self) downloadSpeedLabel.isHidden = false applicationIsDownloadingVideo = true } func updateProgressBarWith(percentString: String?) { let numbersOnly = percentString?.trimmingCharacters(in: NSCharacterSet.decimalDigits.inverted) guard let numbersOnlyUnwrapped = numbersOnly, let progressPercentage = Double(numbersOnlyUnwrapped) else { return } if downloadProgressIndicator.isIndeterminate { downloadProgressIndicator.isIndeterminate = false } if progressPercentage > downloadProgressIndicator.doubleValue { downloadProgressIndicator.doubleValue = progressPercentage } if progressPercentage == 100.0 && (currentVideo + 1) <= numberOfVideosInPlaylist { currentVideo += 1 videoCountLabel.stringValue = "Video \(currentVideo) of \(numberOfVideosInPlaylist)" playlistCountProgressIndicator.doubleValue = Double(currentVideo) / Double(numberOfVideosInPlaylist) } if currentVideo == 1 && numberOfVideosInPlaylist == 1 && progressPercentage == 100.0 { videoNeedsAudio = true if !downloadProgressIndicator.isIndeterminate { downloadProgressIndicator.isIndeterminate = true } } } func updatePlaylistProgressBarWith(downloadString: String) { if downloadString.contains("Downloading video") { let downloadStringWords = downloadString.components(separatedBy: " ") var secondNumber = 1.0 var secondNumberInt = 1 if let secondNum = downloadStringWords.last { var secondNumb = secondNum if secondNumb.contains("\n") { secondNumb.removeLast() guard let secondNum = Double(secondNumb), let secondNumInt = Int(secondNumb) else { return } secondNumber = secondNum secondNumberInt = secondNumInt } else { guard let secondNum = Double(secondNumb), let secondNumInt = Int(secondNumb) else { return } secondNumber = secondNum secondNumberInt = secondNumInt } } playlistCountProgressIndicator.minValue = 0.0 playlistCountProgressIndicator.maxValue = 1.0 playlistCountProgressIndicator.startAnimation(self) let percentage = Double(currentVideo) / secondNumber numberOfVideosInPlaylist = Int(secondNumber) videoCountLabel.stringValue = "Video \(currentVideo) of \(secondNumberInt)" playlistCountProgressIndicator.doubleValue = percentage } } func updateDownloadSpeedLabelWith(downloadString: String) { let downloadStringWords = downloadString.components(separatedBy: " ") guard let atStringIndex = downloadStringWords.index(of: "at") else { return } var speed = downloadStringWords[(atStringIndex + 1)] if speed == "" { speed = downloadStringWords[(atStringIndex + 2)] } downloadSpeedLabel.stringValue = speed } func parseResponseStringForETA(responseString: String) { let words = responseString.components(separatedBy: " ") guard let timeLeft = words.last else { return } var timeLeftString = timeLeft if (timeLeftString.contains("00:")) { timeLeftString.removeFirst() } if videoNeedsAudio { timeLeftLabel.stringValue = "Getting audio. Almost done." } else { timeLeftLabel.stringValue = "Getting video. Time remaining: \(timeLeft)" } // timeLeftLabel.stringValue = "Time remaining: \(timeLeft)" } func userHasAlreadyDownloadedVideo() { timeLeftLabel.stringValue = "Video already downloaded" let alert: NSAlert = NSAlert() alert.messageText = "You have already downloaded this video." alert.informativeText = "Please check your output directory." alert.alertStyle = NSAlert.Style.informational alert.addButton(withTitle: "OK") alert.addButton(withTitle: "Cancel") guard let window = self.view.window else { return } alert.beginSheetModal(for: window, completionHandler: nil) } @objc func terminateApp() { NSApplication.shared.terminate(_:self) } @IBAction func automaticallyUpdateYoutubeDLCheckboxButtonClicked(_ sender: NSButton) { switch sender.state { case .off: UserDefaults.standard.set(false, forKey: downloadController.autoUpdateYoutubeDLKey) case .on: UserDefaults.standard.set(true, forKey: downloadController.autoUpdateYoutubeDLKey) default: break } } } // MARK: - Resizing (may not be needed) extension NSWindow { func change(height: CGFloat) { var frame = self.frame frame.size.height += height frame.origin.y -= height self.setFrame(frame, display: true) } } var processDidBeginNotification = Notification.Name("processDidBegin") var processDidEndNotification = Notification.Name("processDidEnd")
mit
2d4737bc898ecfdd3694815991c47249
37.504873
228
0.652863
6.005777
false
false
false
false
radvansky-tomas/NutriFacts
nutri-facts/nutri-facts/Libraries/iOSCharts/Classes/Animation/ChartAnimationEasing.swift
7
13883
// // ChartAnimationUtils.swift // Charts // // Created by Daniel Cohen Gindi on 23/2/15. // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/ios-charts // import Foundation import CoreGraphics.CGBase @objc public enum ChartEasingOption: Int { case Linear case EaseInQuad case EaseOutQuad case EaseInOutQuad case EaseInCubic case EaseOutCubic case EaseInOutCubic case EaseInQuart case EaseOutQuart case EaseInOutQuart case EaseInQuint case EaseOutQuint case EaseInOutQuint case EaseInSine case EaseOutSine case EaseInOutSine case EaseInExpo case EaseOutExpo case EaseInOutExpo case EaseInCirc case EaseOutCirc case EaseInOutCirc case EaseInElastic case EaseOutElastic case EaseInOutElastic case EaseInBack case EaseOutBack case EaseInOutBack case EaseInBounce case EaseOutBounce case EaseInOutBounce } public typealias ChartEasingFunctionBlock = ((elapsed: NSTimeInterval, duration: NSTimeInterval) -> CGFloat); internal func easingFunctionFromOption(easing: ChartEasingOption) -> ChartEasingFunctionBlock { switch easing { case .Linear: return EasingFunctions.Linear; case .EaseInQuad: return EasingFunctions.EaseInQuad; case .EaseOutQuad: return EasingFunctions.EaseOutQuad; case .EaseInOutQuad: return EasingFunctions.EaseInOutQuad; case .EaseInCubic: return EasingFunctions.EaseInCubic; case .EaseOutCubic: return EasingFunctions.EaseOutCubic; case .EaseInOutCubic: return EasingFunctions.EaseInOutCubic; case .EaseInQuart: return EasingFunctions.EaseInQuart; case .EaseOutQuart: return EasingFunctions.EaseOutQuart; case .EaseInOutQuart: return EasingFunctions.EaseInOutQuart; case .EaseInQuint: return EasingFunctions.EaseInQuint; case .EaseOutQuint: return EasingFunctions.EaseOutQuint; case .EaseInOutQuint: return EasingFunctions.EaseInOutQuint; case .EaseInSine: return EasingFunctions.EaseInSine; case .EaseOutSine: return EasingFunctions.EaseOutSine; case .EaseInOutSine: return EasingFunctions.EaseInOutSine; case .EaseInExpo: return EasingFunctions.EaseInExpo; case .EaseOutExpo: return EasingFunctions.EaseOutExpo; case .EaseInOutExpo: return EasingFunctions.EaseInOutExpo; case .EaseInCirc: return EasingFunctions.EaseInCirc; case .EaseOutCirc: return EasingFunctions.EaseOutCirc; case .EaseInOutCirc: return EasingFunctions.EaseInOutCirc; case .EaseInElastic: return EasingFunctions.EaseInElastic; case .EaseOutElastic: return EasingFunctions.EaseOutElastic; case .EaseInOutElastic: return EasingFunctions.EaseInOutElastic; case .EaseInBack: return EasingFunctions.EaseInBack; case .EaseOutBack: return EasingFunctions.EaseOutBack; case .EaseInOutBack: return EasingFunctions.EaseInOutBack; case .EaseInBounce: return EasingFunctions.EaseInBounce; case .EaseOutBounce: return EasingFunctions.EaseOutBounce; case .EaseInOutBounce: return EasingFunctions.EaseInOutBounce; } } internal struct EasingFunctions { internal static let Linear = { (elapsed: NSTimeInterval, duration: NSTimeInterval) -> CGFloat in return CGFloat(elapsed / duration); }; internal static let EaseInQuad = { (elapsed: NSTimeInterval, duration: NSTimeInterval) -> CGFloat in var position = CGFloat(elapsed / duration); return position * position; }; internal static let EaseOutQuad = { (elapsed: NSTimeInterval, duration: NSTimeInterval) -> CGFloat in var position = CGFloat(elapsed / duration); return -position * (position - 2.0); }; internal static let EaseInOutQuad = { (elapsed: NSTimeInterval, duration: NSTimeInterval) -> CGFloat in var position = CGFloat(elapsed / (duration / 2.0)); if (position < 1.0) { return 0.5 * position * position; } return -0.5 * ((--position) * (position - 2.0) - 1.0); }; internal static let EaseInCubic = { (elapsed: NSTimeInterval, duration: NSTimeInterval) -> CGFloat in var position = CGFloat(elapsed / duration); return position * position * position; }; internal static let EaseOutCubic = { (elapsed: NSTimeInterval, duration: NSTimeInterval) -> CGFloat in var position = CGFloat(elapsed / duration); position--; return (position * position * position + 1.0); }; internal static let EaseInOutCubic = { (elapsed: NSTimeInterval, duration: NSTimeInterval) -> CGFloat in var position = CGFloat(elapsed / (duration / 2.0)); if (position < 1.0) { return 0.5 * position * position * position; } position -= 2.0; return 0.5 * (position * position * position + 2.0); }; internal static let EaseInQuart = { (elapsed: NSTimeInterval, duration: NSTimeInterval) -> CGFloat in var position = CGFloat(elapsed / duration); return position * position * position * position; }; internal static let EaseOutQuart = { (elapsed: NSTimeInterval, duration: NSTimeInterval) -> CGFloat in var position = CGFloat(elapsed / duration); position--; return -(position * position * position * position - 1.0); }; internal static let EaseInOutQuart = { (elapsed: NSTimeInterval, duration: NSTimeInterval) -> CGFloat in var position = CGFloat(elapsed / (duration / 2.0)); if (position < 1.0) { return 0.5 * position * position * position * position; } position -= 2.0; return -0.5 * (position * position * position * position - 2.0); }; internal static let EaseInQuint = { (elapsed: NSTimeInterval, duration: NSTimeInterval) -> CGFloat in var position = CGFloat(elapsed / duration); return position * position * position * position * position; }; internal static let EaseOutQuint = { (elapsed: NSTimeInterval, duration: NSTimeInterval) -> CGFloat in var position = CGFloat(elapsed / duration); position--; return (position * position * position * position * position + 1.0); }; internal static let EaseInOutQuint = { (elapsed: NSTimeInterval, duration: NSTimeInterval) -> CGFloat in var position = CGFloat(elapsed / (duration / 2.0)); if (position < 1.0) { return 0.5 * position * position * position * position * position; } else { position -= 2.0; return 0.5 * (position * position * position * position * position + 2.0); } }; internal static let EaseInSine = { (elapsed: NSTimeInterval, duration: NSTimeInterval) -> CGFloat in var position: NSTimeInterval = elapsed / duration; return CGFloat( -cos(position * M_PI_2) + 1.0 ); }; internal static let EaseOutSine = { (elapsed: NSTimeInterval, duration: NSTimeInterval) -> CGFloat in var position: NSTimeInterval = elapsed / duration; return CGFloat( sin(position * M_PI_2) ); }; internal static let EaseInOutSine = { (elapsed: NSTimeInterval, duration: NSTimeInterval) -> CGFloat in var position: NSTimeInterval = elapsed / duration; return CGFloat( -0.5 * (cos(M_PI * position) - 1.0) ); }; internal static let EaseInExpo = { (elapsed: NSTimeInterval, duration: NSTimeInterval) -> CGFloat in return (elapsed == 0) ? 0.0 : CGFloat(pow(2.0, 10.0 * (elapsed / duration - 1.0))); }; internal static let EaseOutExpo = { (elapsed: NSTimeInterval, duration: NSTimeInterval) -> CGFloat in return (elapsed == duration) ? 1.0 : (-CGFloat(pow(2.0, -10.0 * elapsed / duration)) + 1.0); }; internal static let EaseInOutExpo = { (elapsed: NSTimeInterval, duration: NSTimeInterval) -> CGFloat in if (elapsed == 0) { return 0.0; } if (elapsed == duration) { return 1.0; } var position: NSTimeInterval = elapsed / (duration / 2.0); if (position < 1.0) { return CGFloat( 0.5 * pow(2.0, 10.0 * (position - 1.0)) ); } return CGFloat( 0.5 * (-pow(2.0, -10.0 * --position) + 2.0) ); }; internal static let EaseInCirc = { (elapsed: NSTimeInterval, duration: NSTimeInterval) -> CGFloat in var position = CGFloat(elapsed / duration); return -(CGFloat(sqrt(1.0 - position * position)) - 1.0); }; internal static let EaseOutCirc = { (elapsed: NSTimeInterval, duration: NSTimeInterval) -> CGFloat in var position = CGFloat(elapsed / duration); position--; return CGFloat( sqrt(1 - position * position) ); }; internal static let EaseInOutCirc = { (elapsed: NSTimeInterval, duration: NSTimeInterval) -> CGFloat in var position: NSTimeInterval = elapsed / (duration / 2.0); if (position < 1.0) { return CGFloat( -0.5 * (sqrt(1.0 - position * position) - 1.0) ); } position -= 2.0; return CGFloat( 0.5 * (sqrt(1.0 - position * position) + 1.0) ); }; internal static let EaseInElastic = { (elapsed: NSTimeInterval, duration: NSTimeInterval) -> CGFloat in if (elapsed == 0.0) { return 0.0; } var position: NSTimeInterval = elapsed / duration; if (position == 1.0) { return 1.0; } var p = duration * 0.3; var s = p / (2.0 * M_PI) * asin(1.0); position -= 1.0; return CGFloat( -(pow(2.0, 10.0 * position) * sin((position * duration - s) * (2.0 * M_PI) / p)) ); }; internal static let EaseOutElastic = { (elapsed: NSTimeInterval, duration: NSTimeInterval) -> CGFloat in if (elapsed == 0.0) { return 0.0; } var position: NSTimeInterval = elapsed / duration; if (position == 1.0) { return 1.0; } var p = duration * 0.3; var s = p / (2.0 * M_PI) * asin(1.0); return CGFloat( pow(2.0, -10.0 * position) * sin((position * duration - s) * (2.0 * M_PI) / p) + 1.0 ); }; internal static let EaseInOutElastic = { (elapsed: NSTimeInterval, duration: NSTimeInterval) -> CGFloat in if (elapsed == 0.0) { return 0.0; } var position: NSTimeInterval = elapsed / (duration / 2.0); if (position == 2.0) { return 1.0; } var p = duration * (0.3 * 1.5); var s = p / (2.0 * M_PI) * asin(1.0); if (position < 1.0) { position -= 1.0; return CGFloat( -0.5 * (pow(2.0, 10.0 * position) * sin((position * duration - s) * (2.0 * M_PI) / p)) ); } position -= 1.0; return CGFloat( pow(2.0, -10.0 * position) * sin((position * duration - s) * (2.0 * M_PI) / p) * 0.5 + 1.0 ); }; internal static let EaseInBack = { (elapsed: NSTimeInterval, duration: NSTimeInterval) -> CGFloat in let s: NSTimeInterval = 1.70158; var position: NSTimeInterval = elapsed / duration; return CGFloat( position * position * ((s + 1.0) * position - s) ); }; internal static let EaseOutBack = { (elapsed: NSTimeInterval, duration: NSTimeInterval) -> CGFloat in let s: NSTimeInterval = 1.70158; var position: NSTimeInterval = elapsed / duration; position--; return CGFloat( (position * position * ((s + 1.0) * position + s) + 1.0) ); }; internal static let EaseInOutBack = { (elapsed: NSTimeInterval, duration: NSTimeInterval) -> CGFloat in var s: NSTimeInterval = 1.70158; var position: NSTimeInterval = elapsed / (duration / 2.0); if (position < 1.0) { s *= 1.525; return CGFloat( 0.5 * (position * position * ((s + 1.0) * position - s)) ); } s *= 1.525; position -= 2.0; return CGFloat( 0.5 * (position * position * ((s + 1.0) * position + s) + 2.0) ); }; internal static let EaseInBounce = { (elapsed: NSTimeInterval, duration: NSTimeInterval) -> CGFloat in return 1.0 - EaseOutBounce(duration - elapsed, duration); }; internal static let EaseOutBounce = { (elapsed: NSTimeInterval, duration: NSTimeInterval) -> CGFloat in var position: NSTimeInterval = elapsed / duration; if (position < (1.0 / 2.75)) { return CGFloat( 7.5625 * position * position ); } else if (position < (2.0 / 2.75)) { position -= (1.5 / 2.75); return CGFloat( 7.5625 * position * position + 0.75 ); } else if (position < (2.5 / 2.75)) { position -= (2.25 / 2.75); return CGFloat( 7.5625 * position * position + 0.9375 ); } else { position -= (2.625 / 2.75); return CGFloat( 7.5625 * position * position + 0.984375 ); } }; internal static let EaseInOutBounce = { (elapsed: NSTimeInterval, duration: NSTimeInterval) -> CGFloat in if (elapsed < (duration / 2.0)) { return EaseInBounce(elapsed * 2.0, duration) * 0.5; } return EaseOutBounce(elapsed * 2.0 - duration, duration) * 0.5 + 0.5; }; };
gpl-2.0
9cb474679ae9b4b83ab0a3276e1be59c
34.238579
139
0.599366
4.410102
false
false
false
false
nickdex/cosmos
code/graph_algorithms/src/breadth_first_search/breadth_first_search.swift
17
496
func breadthFirstSearch(_ graph: Graph, source: Node) -> [String] { var queue = Queue<Node>() queue.enqueue(source) var nodesExplored = [source.label] source.visited = true while let current = queue.dequeue() { for edge in current.neighbors { let neighborNode = edge.neighbor if !neighborNode.visited { queue.enqueue(neighborNode) neighborNode.visited = true nodesExplored.append(neighborNode.label) } } } return nodesExplored }
gpl-3.0
14b4d30412d100e1601636c264bf147a
23.8
67
0.663306
4.389381
false
false
false
false
SettlePad/client-iOS
SettlePad/keychain.swift
1
1999
// // keychain.swift // SettlePad // // Created by Rob Everhardt on 06/01/15. // Copyright (c) 2015 SettlePad. All rights reserved. // import UIKit import Security class Keychain { class func save(key: String, data: NSData) -> Bool { let query = [ kSecClass as String : kSecClassGenericPassword as String, kSecAttrAccount as String : key, kSecValueData as String : data ] SecItemDelete(query as CFDictionaryRef) let status: OSStatus = SecItemAdd(query as CFDictionaryRef, nil) return status == noErr } class func load(key: String) -> NSData? { let query = [ kSecClass as String : kSecClassGenericPassword, kSecAttrAccount as String : key, kSecReturnData as String : kCFBooleanTrue, kSecMatchLimit as String : kSecMatchLimitOne ] var extractedData: AnyObject? let status = SecItemCopyMatching(query, &extractedData) if status == noErr { return extractedData as? NSData } else { return nil } } class func delete(key: String) -> Bool { let query = [ kSecClass as String : kSecClassGenericPassword, kSecAttrAccount as String : key ] let status: OSStatus = SecItemDelete(query as CFDictionaryRef) return status == noErr } class func clear() -> Bool { let query = [ kSecClass as String : kSecClassGenericPassword ] let status: OSStatus = SecItemDelete(query as CFDictionaryRef) return status == noErr } } extension String { public var dataValue: NSData { return dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)! } } extension NSData { public var stringValue: String { return NSString(data: self, encoding: NSUTF8StringEncoding)! as String } }
mit
74fbc326130d78ffecf85018ae754747
25.302632
84
0.596798
5.302387
false
false
false
false
SusanDoggie/Doggie
Sources/DoggieGraphics/SVGContext/SVGEffect/SVGConvolveMatrixEffect.swift
1
4890
// // SVGConvolveMatrixEffect.swift // // The MIT License // Copyright (c) 2015 - 2022 Susan Cheng. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // public struct SVGConvolveMatrixEffect: SVGEffectElement { public var region: Rect = .null public var regionUnit: SVGEffect.RegionUnit = .objectBoundingBox public var source: SVGEffect.Source public var matrix: [Double] public var divisor: Double public var bias: Double public var orderX: Int public var orderY: Int public var targetX: Int public var targetY: Int public var edgeMode: EdgeMode public var preserveAlpha: Bool public var sources: [SVGEffect.Source] { return [source] } public init(source: SVGEffect.Source = .source, matrix: [Double], divisor: Double = 1, bias: Double = 0, orderX: Int, orderY: Int, edgeMode: EdgeMode = .duplicate, preserveAlpha: Bool = false) { precondition(orderX > 0, "nonpositive width is not allowed.") precondition(orderY > 0, "nonpositive height is not allowed.") precondition(orderX * orderY == matrix.count, "mismatch matrix count.") self.source = source self.matrix = matrix self.divisor = divisor self.bias = bias self.orderX = orderX self.orderY = orderY self.targetX = orderX / 2 self.targetY = orderY / 2 self.edgeMode = edgeMode self.preserveAlpha = preserveAlpha } public enum EdgeMode { case duplicate case wrap case none } public func visibleBound(_ sources: [SVGEffect.Source: Rect]) -> Rect? { guard let source = sources[source] else { return nil } guard !preserveAlpha else { return source } let minX = source.minX - Double(orderX - targetX - 1) let minY = source.minY - Double(orderY - targetY - 1) let width = source.width + Double(orderX - 1) let height = source.height + Double(orderY - 1) return Rect(x: minX, y: minY, width: width, height: height) } } extension SVGConvolveMatrixEffect { public init() { self.init(matrix: [0, 0, 0, 0, 0, 0, 0, 0, 0], orderX: 3, orderY: 3) } } extension SVGConvolveMatrixEffect { public var xml_element: SDXMLElement { let matrix = self.matrix.map { "\(Decimal($0).rounded(scale: 9))" } var filter = SDXMLElement(name: "feConvolveMatrix", attributes: ["kernelMatrix": matrix.joined(separator: " "), "order": orderX == orderY ? "\(orderX)" : "\(orderX) \(orderY)"]) let sum = self.matrix.reduce(0, +) if divisor != (sum == 0 ? 1 : sum) { filter.setAttribute(for: "divisor", value: "\(Decimal(divisor).rounded(scale: 9))") } if bias != 0 { filter.setAttribute(for: "bias", value: "\(Decimal(bias).rounded(scale: 9))") } if targetX != orderX / 2 { filter.setAttribute(for: "targetX", value: "\(targetX)") } if targetY != orderY / 2 { filter.setAttribute(for: "targetY", value: "\(targetY)") } filter.setAttribute(for: "preserveAlpha", value: "\(preserveAlpha)") switch edgeMode { case .duplicate: filter.setAttribute(for: "edgeMode", value: "duplicate") case .wrap: filter.setAttribute(for: "edgeMode", value: "wrap") case .none: filter.setAttribute(for: "edgeMode", value: "none") } switch self.source { case .source: filter.setAttribute(for: "in", value: "SourceGraphic") case .sourceAlpha: filter.setAttribute(for: "in", value: "SourceAlpha") case let .reference(uuid): filter.setAttribute(for: "in", value: uuid.uuidString) } return filter } }
mit
1aa1e9c2edcd732237082628c6123297
38.12
198
0.635992
4.270742
false
false
false
false
royratcliffe/ManagedObject
Sources/ObjectsDidChangeObserver.swift
1
5407
// ManagedObject ObjectsDidChangeObserver.swift // // Copyright © 2016, Roy Ratcliffe, Pioneering Software, United Kingdom // // 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, EITHER // EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. 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 CoreData /// Observes managed-object changes, collates those changes and notifies change /// controllers; automatically instantiates such change controllers if required. /// /// Set up the observer by adding it to the notification centre. Then add change /// controllers, one for each entity that might change. The observer invokes the /// controllers when one or more objects of interest change: either inserted, /// updated or deleted. When inserting objects, a change controller receives a /// `insertedObjects(objects: [NSManagedObject])` method invocation where the /// argument is an array of managed objects for insertion. Similarly for updated /// and deleted. public class ObjectsDidChangeObserver: NSObject { /// True if you want the observer to use the Objective-C run-time to /// automatically instantiate change controllers based on entity name. Looks /// for entity name plus `ChangeController` as an Objective-C class name. This /// is not the default behaviour because change controllers will typically /// require additional set-up beyond just simple instantiation before they /// are ready to begin observing changes. public var automaticallyInstantiatesChangeControllers = false /// Handles a managed-object change notification. Instantiates change /// controllers automatically if the Objective-C run-time environment has a /// controller class matching the entity name plus `ChangeController`. @objc private func objectsDidChange(_ notification: Notification) { guard NSNotification.Name.NSManagedObjectContextObjectsDidChange == notification.name else { return } guard let objectsDidChange = ObjectsDidChange(notification: notification) else { return } // Iterate change keys and entity names. The change key becomes part of the // selector. The entity name becomes part of the controller class name. for (changeKey, objectsByEntityName) in objectsDidChange.managedObjectsByEntityNameByChangeKey { let selector = Selector("\(changeKey)Objects:") for (entityName, objects) in objectsByEntityName { var changeController = changeControllersByEntityName[entityName] if automaticallyInstantiatesChangeControllers && changeController == nil { let changeControllerClassName = "\(entityName)ChangeController" if let changeControllerClass = NSClassFromString(changeControllerClassName) as? NSObject.Type { changeController = changeControllerClass.init() changeControllersByEntityName[entityName] = changeController } } if let controller = changeController { if controller.responds(to: selector) { controller.perform(selector, with: objects) } } } } } //---------------------------------------------------------------------------- // MARK: - Change Controllers var changeControllersByEntityName = [String: NSObject]() /// Adds a change controller for the given entity name. There can be only one /// controller for each entity. If your application requires more than one /// controller, use more than one observer. public func add(changeController: NSObject, forEntityName entityName: String) { changeControllersByEntityName[entityName] = changeController } /// Removes a change controller. public func removeChangeController(forEntityName entityName: String) { changeControllersByEntityName.removeValue(forKey: entityName) } //---------------------------------------------------------------------------- // MARK: - Notification Centre /// Adds this observer to the given notification centre. public func add(to center: NotificationCenter, context: NSManagedObjectContext? = nil) { center.addObserver(self, selector: #selector(ObjectsDidChangeObserver.objectsDidChange(_:)), name: NSNotification.Name.NSManagedObjectContextObjectsDidChange, object: context) } /// Removes this observer from the given notification centre. public func remove(from center: NotificationCenter) { center.removeObserver(self) } }
mit
ebec5dc81e125c35d5ebd6eda4599df1
48.522936
105
0.720082
5.508163
false
false
false
false
gregttn/GTToast
Pod/Classes/GTToastView.swift
1
7779
// // GTToastView.swift // Pods // // Created by Grzegorz Tatarzyn on 03/10/2015. // // open class GTToastView: UIView, GTAnimatable { fileprivate let animationOffset: CGFloat = 20 fileprivate let margin: CGFloat = 5 fileprivate let config: GTToastConfig fileprivate let image: UIImage? fileprivate let message: String fileprivate var messageLabel: UILabel! fileprivate var imageView: UIImageView! fileprivate lazy var contentSize: CGSize = { [unowned self] in return CGSize(width: self.frame.size.width - self.config.contentInsets.leftAndRight, height: self.frame.size.height - self.config.contentInsets.topAndBottom) }() fileprivate lazy var imageSize: CGSize = { [unowned self] in guard let image = self.image else { return CGSize.zero } return CGSize( width: min(image.size.width, self.config.maxImageSize.width), height: min(image.size.height, self.config.maxImageSize.height) ) }() override open var frame: CGRect { didSet { guard let _ = messageLabel else { return } messageLabel.frame = createLabelFrame() guard let _ = image else { return } imageView.frame = createImageViewFrame() } } open var displayed: Bool { return superview != nil } init() { fatalError("init() has not been implemented") } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } public init(message: String, config: GTToastConfig, image: UIImage? = .none) { self.config = config self.message = message self.image = image super.init(frame: CGRect.zero) self.autoresizingMask = [.flexibleTopMargin, .flexibleLeftMargin, .flexibleRightMargin] self.backgroundColor = config.backgroundColor self.layer.cornerRadius = config.cornerRadius messageLabel = createLabel() addSubview(messageLabel) if let image = image { imageView = createImageView() imageView.image = image addSubview(imageView) } } // MARK: creating views fileprivate func createLabel() -> UILabel { let label = UILabel() label.backgroundColor = UIColor.clear label.textAlignment = config.textAlignment label.textColor = config.textColor label.font = config.font label.numberOfLines = 0 label.text = message label.autoresizingMask = [.flexibleTopMargin, .flexibleLeftMargin, .flexibleRightMargin] return label } fileprivate func createImageView() -> UIImageView { let imageView = UIImageView() imageView.contentMode = UIViewContentMode.scaleAspectFit return imageView } fileprivate func createLabelFrame() -> CGRect { var x: CGFloat = config.contentInsets.left var y: CGFloat = config.contentInsets.top var width: CGFloat = contentSize.width var height: CGFloat = contentSize.height switch config.imageAlignment { case .left: x += imageWithMarginsSize().width fallthrough case .right: width -= imageWithMarginsSize().width case .top: y += config.imageMargins.topAndBottom + imageSize.height fallthrough case .bottom: height = height - config.imageMargins.topAndBottom - imageSize.height } return CGRect(x: x, y: y, width: width, height: height) } fileprivate func createImageViewFrame() -> CGRect { let allInsets = config.contentInsets + config.imageMargins var x: CGFloat = allInsets.left var y: CGFloat = allInsets.top var width: CGFloat = imageSize.width var height: CGFloat = imageSize.height switch config.imageAlignment { case .right: x = frame.width - allInsets.right - imageSize.width fallthrough case .left: height = contentSize.height - config.imageMargins.topAndBottom case .bottom: y += calculateLabelSize().height fallthrough case .top: width = frame.size.width - allInsets.leftAndRight } return CGRect(x: x, y: y, width: width, height: height) } // MARK: size and frame calculation open override func sizeThatFits(_ size: CGSize) -> CGSize { let imageLocationAdjustment = imageLocationSizeAdjustment() let labelSize = calculateLabelSize() let height = labelSize.height + config.contentInsets.topAndBottom + imageLocationAdjustment.height let width = labelSize.width + config.contentInsets.leftAndRight + imageLocationAdjustment.width return CGSize(width: width, height: height) } fileprivate func calculateLabelSize() -> CGSize { let imageLocationAdjustment = imageLocationSizeAdjustment() let screenSize = UIScreen.main.bounds let maxLabelWidth = screenSize.width - 2 * margin - config.contentInsets.leftAndRight - imageLocationAdjustment.width let size = config.font.sizeFor(message, constrain: CGSize(width: maxLabelWidth, height: 0)) return CGSize(width: ceil(size.width), height: ceil(size.height)) } fileprivate func imageLocationSizeAdjustment() -> CGSize { switch config.imageAlignment { case .left, .right: return CGSize(width: imageWithMarginsSize().width, height: 0) case .top, .bottom: return CGSize(width: 0, height: imageWithMarginsSize().height) } } fileprivate func imageWithMarginsSize() -> CGSize { guard let _ = image else { return CGSize.zero } return CGSize( width: imageSize.width + config.imageMargins.leftAndRight, height: imageSize.height + config.imageMargins.topAndBottom ) } open func show() { guard let window = UIApplication.shared.windows.first else { return } if !displayed { window.addSubview(self) animateAll(self, interval: config.displayInterval, animations: config.animation) } } open func dismiss() { self.config.animation.show(self) layer.removeAllAnimations() animate(0, animations: { self.config.animation.hide(self) }) { _ in self.removeFromSuperview() } } } internal protocol GTAnimatable {} internal extension GTAnimatable { func animateAll(_ view: UIView, interval: TimeInterval, animations: GTAnimation) { animations.before(view) animate(0, animations: { animations.show(view) }, completion: { _ in self.animate(interval, animations: { animations.hide(view) }) { finished in if finished { view.removeFromSuperview() } } } ) } fileprivate func animate(_ interval: TimeInterval, animations: @escaping () -> Void, completion: ((Bool) -> Void)?) { UIView.animate(withDuration: 0.6, delay: interval, usingSpringWithDamping: 0.8, initialSpringVelocity: 0, options: .allowUserInteraction, animations: animations, completion: completion) } }
mit
4f8aa3cd3e77f4f50927f6c0ce25f83a
31.822785
165
0.598149
5.302658
false
true
false
false
zhaoxin151/SpeechTranslate
SpeechTranslate/Controller/SpeechController.swift
1
11294
// // SpeechController.swift // SpeechTranslate // // Created by NATON on 2017/6/1. // Copyright © 2017年 NATON. All rights reserved. // import UIKit import Speech import AVFoundation class SpeechController: UIViewController, SFSpeechRecognizerDelegate, AVSpeechSynthesizerDelegate{ @IBOutlet weak var microphoneButton: UIButton! @IBOutlet weak var speechButton: UIButton! @IBOutlet weak var translateButton: UIButton! @IBOutlet weak var speechLanguageTextView: UITextView! @IBOutlet weak var translateLanguageTextview: UITextView! //录音 private var speechRecognizer = SFSpeechRecognizer(locale: Locale.init(identifier: "zh-cn"))! private var recognitionRequest: SFSpeechAudioBufferRecognitionRequest? private var recognitionTask: SFSpeechRecognitionTask? private let audioEngine = AVAudioEngine() private let av = AVSpeechSynthesizer() var language = Language() override func viewDidLoad() { super.viewDidLoad() microphoneButton.isEnabled = false speechRecognizer.delegate = self av.delegate = self // Do any additional setup after loading the view. SFSpeechRecognizer.requestAuthorization { (authStatus) in var isButtonEnabled = false switch authStatus { case .authorized: isButtonEnabled = true case .denied: isButtonEnabled = false print("User denied access to speech recognition") case .restricted: isButtonEnabled = false print("Speech recognition restricted on this device") case .notDetermined: isButtonEnabled = false print("Speech recognition not yet authorized") } OperationQueue.main.addOperation() { self.microphoneButton.isEnabled = isButtonEnabled } } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ //说话语言被按下 @IBAction func speechLangugateClick(_ sender: UIButton) { self.speechLanguageTextView.text = "" let sb = UIStoryboard(name: "Main", bundle:nil) let vc = sb.instantiateViewController(withIdentifier: "LanguageListController") as! LanguageListController //VC为该界面storyboardID,Main.storyboard中选中该界面View,Identifier inspector中修改 vc.languageStr = sender.currentTitle! vc.selectBlock = {(titleStr) in sender.setTitle(titleStr, for: .normal) let codeStr = self.language.languageCodeByTitle(titleStr: titleStr) self.speechRecognizer = SFSpeechRecognizer(locale: Locale.init(identifier: codeStr))! self.speechRecognizer.delegate = self } self.present(vc, animated: true, completion: nil) } //翻译语言被按下 @IBAction func tranlatorLanguageClick(_ sender: UIButton) { let sb = UIStoryboard(name: "Main", bundle:nil) let vc = sb.instantiateViewController(withIdentifier: "LanguageListController") as! LanguageListController vc.languageStr = sender.currentTitle! //VC为该界面storyboardID,Main.storyboard中选中该界面View,Identifier inspector中修改 vc.selectBlock = {(titleStr) in sender.setTitle(titleStr, for: .normal) } self.present(vc, animated: true, completion: nil) } //翻译按钮被按下 @IBAction func translateButtonClick(_ sender: UIButton) { let transelateStr = speechLanguageTextView.text! let appid = "20170522000048682" let salt = "858585858" let sercet = "QFaDv625Kk7ocCnT8xlv" let baseUrl = "http://api.fanyi.baidu.com/api/trans/vip/translate" let sign = appid+transelateStr+salt+sercet let speechCode = language.baiduLanguageCodeByTitle(titleStr: speechButton.currentTitle!) let tranlateCode = language.baiduLanguageCodeByTitle(titleStr: translateButton.currentTitle!) let signMd5 = MD5(sign) let params = ["q":transelateStr, "from":speechCode, "to":tranlateCode, "appid":appid, "salt":salt, "sign":signMd5] HttpRequest.instanceRequst.request(method: .Get, usrString: baseUrl, params: params as AnyObject, resultBlock: { (responseObject, error) in if error != nil { print(error) return } guard (responseObject as [String : AnyObject]?) != nil else{ return } let re = responseObject?["trans_result"] as! Array<Dictionary<String,AnyObject>> let dst = re[0] self.translateLanguageTextview.text = dst["dst"] as! String }) } //播放按钮被按下 @IBAction func playButtonClick(_ sender: UIButton) { if(sender.isSelected == false) { if(av.isPaused) { //如果暂停则恢复,会从暂停的地方继续 av.continueSpeaking() sender.isSelected = !sender.isSelected; }else{ //AVSpeechUtterance*utterance = [[AVSpeechUtterance alloc]initWithString:"];//需要转换的文字 let str: String = self.translateLanguageTextview.text //let utterance = AVSpeechUtterance(string: str) let utterance = AVSpeechUtterance.init(string: "Hello") utterance.rate=0.4;// 设置语速,范围0-1,注意0最慢,1最快;AVSpeechUtteranceMinimumSpeechRate最慢,AVSpeechUtteranceMaximumSpeechRate最快 //AVSpeechSynthesisVoice*voice = [AVSpeechSynthesisVoice voiceWithLanguage:@"en-us"];//设置发音,这是中文普通话 //let voice = AVSpeechSynthesisVoice(language: "en-us") let voice = AVSpeechSynthesisVoice(language: language.languageCodeByTitle(titleStr: translateButton.currentTitle!)) utterance.voice = voice //[_av speakUtteran ce:utterance];//开始 av.speak(utterance) sender.isSelected = !sender.isSelected } }else{ //[av stopSpeakingAtBoundary:AVSpeechBoundaryWord];//感觉效果一样,对应代理>>>取消 //[_av pauseSpeakingAtBoundary:AVSpeechBoundaryWord];//暂停 av.pauseSpeaking(at: .word) sender.isSelected = !sender.isSelected; } } //录音按钮被按下 @IBAction func recodeButtonClick(_ sender: UIButton) { if audioEngine.isRunning { audioEngine.stop() recognitionRequest?.endAudio() sender.isEnabled = false sender.setTitle("开始录音", for: .normal) } else { startRecording() sender.setTitle("结束录音", for: .normal) } } func startRecording() { if recognitionTask != nil { //1 recognitionTask?.cancel() recognitionTask = nil } let audioSession = AVAudioSession.sharedInstance() //2 do { try audioSession.setCategory(AVAudioSessionCategoryRecord) try audioSession.setMode(AVAudioSessionModeMeasurement) try audioSession.setActive(true, with: .notifyOthersOnDeactivation) } catch { print("audioSession properties weren't set because of an error.") } recognitionRequest = SFSpeechAudioBufferRecognitionRequest() //3 guard let inputNode = audioEngine.inputNode else { fatalError("Audio engine has no input node") } //4 guard let recognitionRequest = recognitionRequest else { fatalError("Unable to create an SFSpeechAudioBufferRecognitionRequest object") } //5 recognitionRequest.shouldReportPartialResults = true //6 recognitionTask = speechRecognizer.recognitionTask(with: recognitionRequest, resultHandler: { (result, error) in //7 var isFinal = false //8 if result != nil { self.speechLanguageTextView.text = result?.bestTranscription.formattedString //9 isFinal = (result?.isFinal)! } if error != nil || isFinal { //10 self.audioEngine.stop() inputNode.removeTap(onBus: 0) self.recognitionRequest = nil self.recognitionTask = nil self.microphoneButton.isEnabled = true } }) let recordingFormat = inputNode.outputFormat(forBus: 0) //11 inputNode.installTap(onBus: 0, bufferSize: 1024, format: recordingFormat) { (buffer, when) in self.recognitionRequest?.append(buffer) } audioEngine.prepare() //12 do { try audioEngine.start() } catch { print("audioEngine couldn't start because of an error.") } speechLanguageTextView.text = "Say something, I'm listening!" } func speechRecognizer(_ speechRecognizer: SFSpeechRecognizer, availabilityDidChange available: Bool) { if available { microphoneButton.isEnabled = true } else { microphoneButton.isEnabled = false } } func MD5(_ string: String) -> String? { let length = Int(CC_MD5_DIGEST_LENGTH) var digest = [UInt8](repeating: 0, count: length) if let d = string.data(using: String.Encoding.utf8) { _ = d.withUnsafeBytes { (body: UnsafePointer<UInt8>) in CC_MD5(body, CC_LONG(d.count), &digest) } } return (0..<length).reduce("") { $0 + String(format: "%02x", digest[$1]) } } func speechSynthesizer(_ synthesizer: AVSpeechSynthesizer, didStart utterance: AVSpeechUtterance) { print("Speaker class started") } func speechSynthesizer(_ synthesizer: AVSpeechSynthesizer, didFinish utterance: AVSpeechUtterance) { print("Speaker class finished") } }
mit
6d6d8c90d60325e42369380ac7c8db3d
34.924837
147
0.582825
5.391368
false
false
false
false
reeseugolf/EffectsModalSegue
EffectsModalSegue/EffectsModalSegue.swift
2
4194
// // EffectsModalSegue.swift // EffectsModalSegue // // Created by UGolf_Reese on 15/7/17. // Copyright (c) 2015年 reese. All rights reserved. // import UIKit enum EffectsModalSegueType: Int { case Blur case Draken } enum EffectsModalSegueTransitionStyle: Int { case Fade = 0 case FromTop = 1 case FromBottom = 2 case FromLeft = 3 case FromRight = 4 } class EffectsModalSegue: UIStoryboardSegue { var type: EffectsModalSegueType = .Draken var transitionStyle: EffectsModalSegueTransitionStyle = .Fade var backgroundOpacity: CGFloat = 0.4 var backgroundBlurRadius: CGFloat = 8 var backgroundSaturationDeltaFactor: CGFloat = 1 var backgroundTintColor = UIColor.clearColor() private var backgroundImageView: UIImageView! private var maskView: UIView! private var backgroundView: UIView! private var contentView: UIView! override init!(identifier: String?, source: UIViewController, destination: UIViewController) { super.init(identifier: identifier, source: source, destination: destination) } override func perform() { let source = self.sourceViewController as! UIViewController let destination = self.destinationViewController as! UIViewController contentView = destination.view contentView.backgroundColor = UIColor.clearColor() contentView.autoresizingMask = .FlexibleHeight | .FlexibleWidth backgroundImageView = UIImageView(frame: destination.view.frame) backgroundImageView.autoresizingMask = .FlexibleHeight | .FlexibleWidth maskView = UIView(frame: destination.view.frame) maskView.autoresizingMask = .FlexibleHeight | .FlexibleWidth maskView.backgroundColor = UIColor.blackColor() maskView.alpha = 0.0 backgroundView = UIView(frame: destination.view.frame) destination.view = backgroundView destination.view.insertSubview(backgroundImageView, atIndex: 0) destination.view.insertSubview(maskView, atIndex: 1) destination.view.addSubview(contentView) var beginFrame = destination.view.frame switch self.transitionStyle { case .FromTop: beginFrame.origin.y = -1 * beginFrame.size.height case .FromBottom : beginFrame.origin.y = 1 * beginFrame.size.height case .FromLeft : beginFrame.origin.x = -1 * beginFrame.size.width case .FromRight : beginFrame.origin.x = 1 * beginFrame.size.width default: beginFrame = destination.view.frame } self.contentView.frame = beginFrame let windowBounds = source.view.window!.bounds UIGraphicsBeginImageContextWithOptions(windowBounds.size, true, 0.0) source.view.window!.drawViewHierarchyInRect(windowBounds, afterScreenUpdates: true) var snaphost = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() if self.type == .Blur { snaphost = snaphost.applyBlurWithRadius(backgroundBlurRadius, tintColor: backgroundTintColor, saturationDeltaFactor: backgroundSaturationDeltaFactor, maskImage: nil) } backgroundImageView.image = snaphost destination.modalTransitionStyle = UIModalTransitionStyle.CrossDissolve source.presentViewController(destination, animated: true, completion: nil) destination.transitionCoordinator()?.animateAlongsideTransition({ [weak self] (context) -> Void in if self!.type == .Draken { self!.maskView.alpha = self!.backgroundOpacity } self!.contentView.frame = self!.backgroundView.frame }, completion: nil) } }
mit
673fbb70bfbd306c21af6e78d6b78233
27.517007
111
0.619752
5.946099
false
false
false
false
edwin123chen/NSData-GZIP
Sources/NSData+GZIP.swift
2
4432
// // NSData+GZIP.swift // // Version 1.1.0 /* The MIT License (MIT) © 2014-2015 1024jp <wolfrosch.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 Foundation private let CHUNK_SIZE : Int = 2 ^ 14 private let STREAM_SIZE : Int32 = Int32(sizeof(z_stream)) public extension NSData { /// Return gzip-compressed data object or nil. public func gzippedData() -> NSData? { if self.length == 0 { return NSData() } var stream = self.createZStream() var status : Int32 status = deflateInit2_(&stream, Z_DEFAULT_COMPRESSION, Z_DEFLATED, 31, 8, Z_DEFAULT_STRATEGY, ZLIB_VERSION, STREAM_SIZE) if status != Z_OK { if let errorMessage = String.fromCString(stream.msg) { println(String(format: "Compression failed: %@", errorMessage)) } return nil } var data = NSMutableData(length: CHUNK_SIZE)! while stream.avail_out == 0 { if Int(stream.total_out) >= data.length { data.length += CHUNK_SIZE } stream.next_out = UnsafeMutablePointer<Bytef>(data.mutableBytes).advancedBy(Int(stream.total_out)) stream.avail_out = uInt(data.length) - uInt(stream.total_out) deflate(&stream, Z_FINISH) } deflateEnd(&stream) data.length = Int(stream.total_out) return data } /// Return gzip-decompressed data object or nil. public func gunzippedData() -> NSData? { if self.length == 0 { return NSData() } var stream = self.createZStream() var status : Int32 status = inflateInit2_(&stream, 47, ZLIB_VERSION, STREAM_SIZE) if status != Z_OK { if let errorMessage = String.fromCString(stream.msg) { println(String(format: "Decompression failed: %@", errorMessage)) } return nil } var data = NSMutableData(length: self.length * 2)! do { if Int(stream.total_out) >= data.length { data.length += self.length / 2; } stream.next_out = UnsafeMutablePointer<Bytef>(data.mutableBytes).advancedBy(Int(stream.total_out)) stream.avail_out = uInt(data.length) - uInt(stream.total_out) status = inflate(&stream, Z_SYNC_FLUSH) } while status == Z_OK if inflateEnd(&stream) != Z_OK || status != Z_STREAM_END { if let errorMessage = String.fromCString(stream.msg) { println(String(format: "Decompression failed: %@", errorMessage)) } return nil } data.length = Int(stream.total_out) return data } private func createZStream() -> z_stream { return z_stream( next_in: UnsafeMutablePointer<Bytef>(self.bytes), avail_in: uint(self.length), total_in: 0, next_out: nil, avail_out: 0, total_out: 0, msg: nil, state: nil, zalloc: nil, zfree: nil, opaque: nil, data_type: 0, adler: 0, reserved: 0 ) } }
mit
aee51fca8b434cbd796acfb36546670f
30.65
128
0.578199
4.462236
false
false
false
false
superk589/DereGuide
DereGuide/Common/BaseRequest.swift
2
5819
// // BaseRequest.swift // DereGuide // // Created by zzk on 2017/1/25. // Copyright © 2017 zzk. All rights reserved. // import Foundation import SwiftyJSON class BaseRequest { static let `default` = BaseRequest() var session = BaseSession.shared.session func getWith(urlStr:String, params:[String:String]?, callback:@escaping (_ data:Data?, _ response: HTTPURLResponse?, _ error: Error?) -> Void) { var newStr = urlStr if params != nil { newStr.append(encodeUnicode(string: paramsToString(params: params!))) } var request = URLRequest.init(url: URL.init(string: newStr)!) request.httpMethod = "GET" dataTask(with: request, completionHandler: callback) } func postWith(urlStr:String, params:[String:String]?, callback:@escaping (_ data:Data?, _ response: HTTPURLResponse?, _ error: Error?) -> Void) { var newStr = "" if params != nil { newStr.append(encodeUnicode(string: paramsToString(params: params!))) } var request = URLRequest.init(url: URL.init(string: urlStr)!) request.httpMethod = "POST" request.httpBody = newStr.data(using: .utf8) dataTask(with: request, completionHandler: callback) } func postWith(request:inout URLRequest, params:[String:String]?, callback:@escaping (_ data:Data?, _ response: HTTPURLResponse?, _ error: Error?) -> Void) { var newStr = "" if params != nil { newStr.append(encodeUnicode(string: paramsToString(params: params!))) } request.httpMethod = "POST" request.httpBody = newStr.data(using: .utf8) dataTask(with: request, completionHandler: callback) } func getWith(request:inout URLRequest, params: [String :String]? = nil, callback:@escaping (_ data:Data?, _ response: HTTPURLResponse?, _ error: Error?) -> Void) { var newStr = "" if params != nil { newStr.append(encodeUnicode(string: paramsToString(params: params!))) } request.httpMethod = "GET" request.httpBody = newStr.data(using: .utf8) dataTask(with: request, completionHandler: callback) } func getWith(urlString:String, params: [String :String]? = nil, callback:@escaping (_ data:Data?, _ response: HTTPURLResponse?, _ error: Error?) -> Void) { var newStr = "" if params != nil { newStr.append("?") newStr.append(encodeUnicode(string: paramsToString(params: params!))) } var request = URLRequest.init(url: URL.init(string: urlString + newStr)!) request.httpMethod = "GET" dataTask(with: request, completionHandler: callback) } fileprivate func paramsToString(params:[String:String]) -> String { if params.count == 0 { return "" } var paraStr = "" var paraArr = [String]() for (key, value) in params { paraArr.append("\(key)=\(value)") } paraStr.append(paraArr.joined(separator: "&")) return String(paraStr) } /// construct multipart url request /// /// - Parameters: /// - urlStr: string of remote api /// - params: params of the multipart form /// - fileNames: file names of params with file data /// - Returns: the constructed request fileprivate func constructMultipartRequest(urlStr:String, params:[String:Any?], fileNames: [String:String]?) -> URLRequest { var request = URLRequest.init(url: URL.init(string: urlStr)!) let boundary = "Boundary+BFFF11CB6FF1E452" request.addValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type") var data = Data() for (k, v) in params { data.append("--\(boundary)\r\n".data(using: .utf8)!) if v is UIImage { data.append("Content-Disposition: form-data; name=\"\(k)\"; filename=\"\(fileNames?[k] ?? "")\"\r\n".data(using: .utf8)!) data.append("Content-Type: image/png\r\n\r\n".data(using: .utf8)!) let imageData = (v as? UIImage ?? UIImage()).pngData() ?? Data() data.append(imageData) data.append("\r\n".data(using: .utf8)!) } else if v is String { data.append("Content-Disposition: form-data; name=\"\(k)\"\r\n\r\n".data(using: .utf8)!) data.append("\(v!)\r\n".data(using: .utf8, allowLossyConversion: true)!) } } data.append("--\(boundary)--\r\n".data(using: .utf8)!) request.httpBody = data return request } func dataTask(with request:URLRequest, completionHandler: @escaping (Data?, HTTPURLResponse?, Error?) -> Void) { #if DEBUG print("request the url: ", request.url?.absoluteString ?? "") #endif let task = session?.dataTask(with: request) { (data, response, error) in DispatchQueue.main.async { UIApplication.shared.isNetworkActivityIndicatorVisible = false } if error != nil { } else { #if DEBUG print("response code is ", (response as? HTTPURLResponse)?.statusCode ?? 0) #endif } completionHandler(data, response as? HTTPURLResponse, error) } UIApplication.shared.isNetworkActivityIndicatorVisible = true task?.resume() } func encodeUnicode(string:String) -> String { var cs = CharacterSet.urlQueryAllowed cs.remove(UnicodeScalar.init("+")) let newStr = (string as NSString).addingPercentEncoding(withAllowedCharacters: cs) return newStr ?? "" } }
mit
e121cc67b4ba7c1a62327e9d4b190e09
39.402778
167
0.586456
4.510078
false
false
false
false
apple/swift-tools-support-core
Tests/TSCBasicTests/JSONMapperTests.swift
1
4491
/* 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 http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for Swift project authors */ import XCTest import TSCBasic fileprivate struct Bar: JSONMappable, JSONSerializable, Equatable { let str: String let bool: Bool init(json: JSON) throws { self.str = try json.get("str") self.bool = try json.get("bool") } func toJSON() -> JSON { return .dictionary([ "str": .string(str), "bool": .bool(bool), ]) } init(str: String, bool: Bool) { self.str = str self.bool = bool } public static func ==(lhs: Bar, rhs: Bar) -> Bool { return lhs.str == rhs.str && lhs.bool == rhs.bool } } fileprivate struct Foo: JSONMappable, JSONSerializable { let str: String let int: Int let optStr: String? let bar: Bar let barOp: Bar? let barArray: [Bar] let dict: [String: Double] init(json: JSON) throws { self.str = try json.get("str") self.int = try json.get("int") self.optStr = json.get("optStr") self.bar = try json.get("bar") self.barOp = json.get("barOp") self.barArray = try json.get("barArray") self.dict = try json.get("dict") } func toJSON() -> JSON { return .dictionary([ "str": .string(str), "int": .int(int), "optStr": optStr.flatMap(JSON.string) ?? .null, "bar": bar.toJSON(), "barOp": barOp.flatMap{$0.toJSON()} ?? .null, "barArray": .array(barArray.map{$0.toJSON()}), "dict": .dictionary(Dictionary(uniqueKeysWithValues: dict.map{($0.0, .double($0.1))})), ]) } init(str: String, int: Int, optStr: String?, bar: Bar, barArray: [Bar], dict: [String: Double]) { self.str = str self.int = int self.optStr = optStr self.bar = bar self.barOp = nil self.barArray = barArray self.dict = dict } } class JSONMapperTests: XCTestCase { func testBasics() throws { let bar = Bar(str: "bar", bool: false) let bar1 = Bar(str: "bar1", bool: true) let dict = ["a": 1.0, "b": 2.923] let foo = Foo( str: "foo", int: 1, optStr: "k", bar: bar, barArray: [bar, bar1], dict: dict) let foo1 = try Foo(json: foo.toJSON()) XCTAssertEqual(foo.str, foo1.str) XCTAssertEqual(foo.int, foo1.int) XCTAssertEqual(foo.optStr, foo1.optStr) XCTAssertEqual(foo.bar, bar) XCTAssertNil(foo.barOp) XCTAssertEqual(foo.barArray, [bar, bar1]) XCTAssertEqual(foo.dict, dict) } func testErrors() throws { let foo = JSON.dictionary(["foo": JSON.string("Hello")]) do { let string: String = try foo.get("bar") XCTFail("unexpected string: \(string)") } catch JSON.MapError.missingKey(let key) { XCTAssertEqual(key, "bar") } do { let int: Int = try foo.get("foo") XCTFail("unexpected int: \(int)") } catch JSON.MapError.custom(let key, let msg) { XCTAssertNil(key) XCTAssertEqual(msg, "expected int, got \"Hello\"") } do { let bool: Bool = try foo.get("foo") XCTFail("unexpected bool: \(bool)") } catch JSON.MapError.custom(let key, let msg) { XCTAssertNil(key) XCTAssertEqual(msg, "expected bool, got \"Hello\"") } do { let foo = JSON.string("Hello") let string: String = try foo.get("bar") XCTFail("unexpected string: \(string)") } catch JSON.MapError.typeMismatch(let key, let expected, let json) { XCTAssertEqual(key, "bar") XCTAssert(expected == Dictionary<String, JSON>.self) XCTAssertEqual(json, .string("Hello")) } do { let string: [String] = try foo.get("foo") XCTFail("unexpected string: \(string)") } catch JSON.MapError.typeMismatch(let key, let expected, let json) { XCTAssertEqual(key, "foo") XCTAssert(expected == Array<JSON>.self) XCTAssertEqual(json, .string("Hello")) } } }
apache-2.0
3f8fedc7f1ac0b43b4292383fa47223d
30.1875
101
0.555556
3.963813
false
false
false
false
icanzilb/EventBlankApp
EventBlank/EventBlank/ViewControllers/Speakers/SpeakersDetailsViewController+TableView.swift
2
8327
// // SpeakersDetailsViewController+TableView.swift // EventBlank // // Created by Marin Todorov on 9/22/15. // Copyright (c) 2015 Underplot ltd. All rights reserved. // import UIKit import SQLite //MARK: table view methods extension SpeakerDetailsViewController { func numberOfSectionsInTableView(tableView: UITableView) -> Int { if let twitterHandle = speaker[Speaker.twitter] where count(twitterHandle) > 0 { return 2 } return 1 } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { switch section { case 0: return 1; case 1 where tweets == nil: return 1 case 1 where tweets != nil && tweets!.count == 0: return 0 case 1 where tweets != nil && tweets!.count > 0: return tweets!.count default: return 0 } } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { if indexPath.section == 0 { //speaker details let cell = tableView.dequeueReusableCellWithIdentifier("SpeakerDetailsCell") as! SpeakerDetailsCell //configure cell.isFavoriteSpeaker = speakers.isFavorite(speakerId: speaker[Speaker.idColumn]) cell.indexPath = indexPath //populate cell.populateFromSpeaker(speaker, twitter: twitter) //tap handlers if let twitterHandle = speaker[Speaker.twitter] where count(twitterHandle) > 0 { cell.didTapTwitter = { let twitterUrl = NSURL(string: "https://twitter.com/" + twitterHandle)! let webVC = self.storyboard?.instantiateViewControllerWithIdentifier("WebViewController") as! WebViewController webVC.initialURL = twitterUrl self.navigationController!.pushViewController(webVC, animated: true) } cell.didTapFollow = { self.twitter.authorize({success in if success { cell.btnIsFollowing.followState = .SendingRequest self.twitter.followUser(twitterHandle, completion: {following in cell.btnIsFollowing.followState = following ? .Following : .Follow cell.btnIsFollowing.animateSelect(scale: 0.8, completion: nil) }) } else { cell.btnIsFollowing.hidden = true } }) } } cell.didSetIsFavoriteTo = {setIsFavorite, indexPath in //TODO: update all this to Swift 2.0 let id = self.speaker[Speaker.idColumn] let isInFavorites = self.speakers.isFavorite(speakerId: id) if setIsFavorite && !isInFavorites { self.speakers.addFavorite(speakerId: id) } else if !setIsFavorite && isInFavorites { self.speakers.removeFavorite(speakerId: id) } delay(seconds: 0.1, { self.notification(kFavoritesChangedNotification, object: self.speakers) }) } cell.didTapURL = {tappedUrl in let webVC = self.storyboard?.instantiateViewControllerWithIdentifier("WebViewController") as! WebViewController webVC.initialURL = tappedUrl self.navigationController!.pushViewController(webVC, animated: true) } //work on the user photo backgroundQueue({ if self.speaker[Speaker.photo]?.imageValue == nil { self.userCtr.lookupUserImage(self.speaker, completion: {userImage in userImage?.asyncToSize(.FillSize(cell.userImage.bounds.size), cornerRadius: 5, completion: {result in cell.userImage.image = result }) if let userImage = userImage { cell.didTapPhoto = { PhotoPopupView.showImage(userImage, inView: self.view) } } }) } else { cell.didTapPhoto = { PhotoPopupView.showImage(self.speaker[Speaker.photo]!.imageValue!, inView: self.view) } } }) return cell } if indexPath.section == 1, let tweets = tweets where tweets.count > 0 { let cell = self.tableView.dequeueReusableCellWithIdentifier("TweetCell") as! TweetCell let row = indexPath.row let tweet = tweets[indexPath.row] cell.message.text = tweet.text cell.timeLabel.text = tweet.created.relativeTimeToString() cell.message.selectedRange = NSRange(location: 0, length: 0) if let attachmentUrl = tweet.imageUrl { cell.attachmentImage.hnk_setImageFromURL(attachmentUrl, placeholder: nil, format: nil, failure: nil, success: {image in image.asyncToSize(.Fill(cell.attachmentImage.bounds.width, 150), cornerRadius: 5.0, completion: {result in cell.attachmentImage.image = result }) }) cell.didTapAttachment = { PhotoPopupView.showImageWithUrl(attachmentUrl, inView: self.view) } cell.attachmentHeight.constant = 148.0 } cell.nameLabel.text = speaker[Speaker.name] if user == nil { let usersTable = database[UserConfig.tableName] user = usersTable.filter(User.idColumn == tweet.userId).first } if let userImage = user?[User.photo]?.imageValue { userImage.asyncToSize(.FillSize(cell.userImage.bounds.size), cornerRadius: 5, completion: {result in cell.userImage.image = result }) } else { if !fetchingUserImage { fetchUserImage() } cell.userImage.image = UIImage(named: "empty") } cell.didTapURL = {tappedUrl in let webVC = self.storyboard?.instantiateViewControllerWithIdentifier("WebViewController") as! WebViewController webVC.initialURL = tappedUrl self.navigationController!.pushViewController(webVC, animated: true) } return cell } if indexPath.section == 1 && tweets == nil { return tableView.dequeueReusableCellWithIdentifier("LoadingCell") as! UITableViewCell } return tableView.dequeueReusableCellWithIdentifier("") as! UITableViewCell } func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { switch section { case 0: return "Speaker Details" case 1: return (tweets?.count < 1) ? "No tweets available" : "Latest tweets" default: return nil } } func tableView(tableView: UITableView, titleForFooterInSection section: Int) -> String? { if section == 1, let tweets = tweets where tweets.count == 0 { return "We couldn't load any tweets" } else { return nil } } //add some space at the end of the tweet list func tableView(tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { switch section { case 1: return 50 default: return 0 } } func tableView(tableView: UITableView, viewForFooterInSection section: Int) -> UIView? { switch section { case 1: return UIView(frame: CGRect(x: 0, y: 0, width: 100, height: 50)) default: return nil } } }
mit
a062c1ed0fde7c60ee05693fbad50806
39.818627
135
0.541371
5.668482
false
false
false
false
razvn/swiftserver-vapordemo
Sources/App/Models/User.swift
1
1025
import Foundation import Vapor struct User: Model { var exists: Bool = false var id: Node? let name: String let beer: Int? init(name: String, beer: Int?) { self.name = name self.beer = beer } //Intializable from a Node init(node: Node, in context: Context) throws { id = try node.extract("id") name = try node.extract("name") beer = try node.extract("beer") } //Node represantable func makeNode(context: Context) throws -> Node { return try Node(node: ["id": id, "name": name, "beer": beer]) } //Database preparation static func prepare(_ database: Database) throws { try database.create("users") {users in users.id() users.string("name") users.int("beer", optional: true) } } static func revert(_ database: Database) throws { try database.delete("users") } }
mit
ff22bbfc7fb94a62736d018d219e7175
24
54
0.523902
4.361702
false
false
false
false
Lweek/Formulary
Formulary/Input/Validation.swift
1
2383
// // Validation.swift // Formulary // // Created by Fabian Canas on 1/21/15. // Copyright (c) 2015 Fabian Canas. All rights reserved. // import Foundation public typealias Validation = (String?) -> (valid: Bool, reason: String) public let PermissiveValidation: Validation = { _ in (true, "")} public let RequiredString: (String) -> Validation = { name in { value in if value == nil { return (false, "\(name) can't be empty") } if let text = value { if text.isEmpty { return (false, "\(name) can't be empty") } return (true, "") } return (false, "\(name) must be a String") } } private extension String { func toDouble() -> Double? { let trimmedValue = (self as NSString).stringByTrimmingCharactersInSet(NSCharacterSet.decimalDigitCharacterSet().invertedSet) return self == trimmedValue ? (self as NSString).doubleValue : nil } } public let MinimumNumber: (String, Int) -> Validation = { name, min in { value in if let value = value { if let number = value.toDouble() { if number < Double(min) { return (false, "\(name) must be at least \(min)") } return (true, "") } } else { return (false, "\(name) must be at least \(min)") } return (false, "\(name) must be a number") } } public let MaximumNumber: (String, Int) -> Validation = { name, max in { value in if let value = value { if let number = value.toDouble() { if number > Double(max) { return (false, "\(name) must be at most \(max)") } return (true, "") } } else { return (false, "\(name) must be at most \(max)") } return (false, "\(name) must be a number") } } public func && (lhs: Validation, rhs: Validation) -> Validation { return { value in let lhsr = lhs(value) if !lhsr.valid { return lhsr } let rhsr = rhs(value) if !rhsr.valid { return rhsr } return (true, "") } }
mit
bb2cc9ad49915818416bbee41d4795ef
24.902174
132
0.485522
4.462547
false
false
false
false
Authman2/Pix
Pix/ProfilePage.swift
1
12696
// // ProfilePage.swift // Pix // // Created by Adeola Uthman on 12/23/16. // Copyright © 2016 Adeola Uthman. All rights reserved. // import UIKit import Foundation import SnapKit import Firebase import PullToRefreshSwift import OneSignal import IGListKit class ProfilePage: ProfileDisplayPage, IGListAdapterDataSource, UIImagePickerControllerDelegate, UINavigationControllerDelegate { /******************************** * * VARIABLES * ********************************/ /* The adapter. */ lazy var adapter: IGListAdapter = { return IGListAdapter(updater: IGListAdapterUpdater(), viewController: self, workingRangeSize: 1); }(); /* The collection view. */ let collectionView: IGListCollectionView = { let layout = IGListGridCollectionViewLayout(); let view = IGListCollectionView(frame: CGRect.zero, collectionViewLayout: layout); view.alwaysBounceVertical = true; return view; }(); /* The image view that displays the profile picture. */ let profilePicture: CircleImageView = { let i = CircleImageView(); i.translatesAutoresizingMaskIntoConstraints = false; i.isUserInteractionEnabled = true; i.backgroundColor = UIColor.gray; return i; }(); /* A label to display whether or not this user is private. */ let privateLabel: UILabel = { let a = UILabel(); a.translatesAutoresizingMaskIntoConstraints = false; a.isUserInteractionEnabled = false; a.font = UIFont(name: a.font.fontName, size: 15); a.numberOfLines = 0; a.textColor = UIColor(red: 21/255, green: 180/255, blue: 133/255, alpha: 1).lighter(); a.textAlignment = .center; a.isHidden = true; return a; }(); /* Label that shows the user's name. */ let nameLabel: UILabel = { let n = UILabel(); n.translatesAutoresizingMaskIntoConstraints = false; n.isUserInteractionEnabled = false; n.font = UIFont(name: n.font.fontName, size: 20); n.textColor = UIColor.black; n.textAlignment = .center; return n; }(); /* Label that shows the number of followers this user has. */ let followersLabel: UILabel = { let n = UILabel(); n.translatesAutoresizingMaskIntoConstraints = false; n.isUserInteractionEnabled = false; n.font = UIFont(name: n.font.fontName, size: 15); n.textColor = UIColor.black; n.textAlignment = .center; return n; }(); /* Label that shows the number of people this user is following. */ let followingLabel: UILabel = { let n = UILabel(); n.translatesAutoresizingMaskIntoConstraints = false; n.isUserInteractionEnabled = false; n.font = UIFont(name: n.font.fontName, size: 15); n.textColor = UIColor.black; n.textAlignment = .center; return n; }(); /* The button used for editing the profile. */ var editProfileButton: UIBarButtonItem!; /* Image picker */ let imgPicker = UIImagePickerController(); var canChangeProfilePic = false; var tap: UITapGestureRecognizer!; /* Firebase reference. */ let fireRef: FIRDatabaseReference = FIRDatabase.database().reference(); /******************************** * * METHODS * ********************************/ override func viewDidLoad() { super.viewDidLoad(); view.backgroundColor = UIColor(red: 239/255, green: 255/255, blue:245/255, alpha: 1); navigationController?.navigationBar.isHidden = false; navigationItem.hidesBackButton = true; navigationItem.title = "Profile"; viewcontrollerName = "Profile"; setupCollectionView(); view.addSubview(collectionView) /* Setup/Layout the view. */ view.addSubview(privateLabel); view.addSubview(profilePicture); view.addSubview(nameLabel); view.addSubview(followersLabel); view.addSubview(followingLabel); profilePicture.snp.makeConstraints { (maker: ConstraintMaker) in maker.centerX.equalTo(view.snp.centerX); maker.bottom.equalTo(view.snp.centerY).offset(-100); maker.width.equalTo(90); maker.height.equalTo(90); } privateLabel.snp.makeConstraints { (maker: ConstraintMaker) in maker.centerX.equalTo(view.snp.centerX); maker.bottom.equalTo(profilePicture.snp.top).offset(-10); maker.width.equalTo(view.width); maker.height.equalTo(50); } nameLabel.snp.makeConstraints { (maker: ConstraintMaker) in maker.centerX.equalTo(view.snp.centerX); maker.width.equalTo(view.width); maker.height.equalTo(25); maker.top.equalTo(profilePicture.snp.bottom).offset(20); } followersLabel.snp.makeConstraints { (maker: ConstraintMaker) in maker.centerX.equalTo(view.snp.centerX); maker.width.equalTo(view.width); maker.height.equalTo(20); maker.top.equalTo(nameLabel.snp.bottom).offset(10); } followingLabel.snp.makeConstraints { (maker: ConstraintMaker) in maker.centerX.equalTo(view.snp.centerX); maker.width.equalTo(view.width); maker.height.equalTo(20); maker.top.equalTo(followersLabel.snp.bottom).offset(5); } collectionView.snp.makeConstraints({ (maker: ConstraintMaker) in maker.width.equalTo(view.frame.width); maker.centerX.equalTo(view); maker.top.equalTo(followingLabel.snp.bottom).offset(10); maker.bottom.equalTo(view.snp.bottom); }) /* Add the pull to refresh function. */ var options = PullToRefreshOption(); options.fixedSectionHeader = false; collectionView.addPullRefresh(options: options, refreshCompletion: { (Void) in //self.adapter.performUpdates(animated: true, completion: nil); self.adapter.reloadData(completion: { (b: Bool) in self.reloadLabels(); self.collectionView.stopPullRefreshEver(); }) }); /* Bar button item. */ editProfileButton = UIBarButtonItem(title: "Edit", style: .plain, target: self, action: #selector(editProfile)); editProfileButton.tintColor = .white; navigationItem.rightBarButtonItem = editProfileButton; /* Profile pic image picker. */ imgPicker.delegate = self; imgPicker.sourceType = .photoLibrary; tap = UITapGestureRecognizer(target: self, action: #selector(uploadProfilePic)); profilePicture.addGestureRecognizer(tap); } // End of viewDidLoad(). override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated); lastProfile = self; self.adapter.reloadData(completion: nil); editProfileButton.isEnabled = true; editProfileButton.tintColor = .white; self.reloadLabels(); profilePicture.addGestureRecognizer(tap); } // End of viewDidAppear(). func reloadLabels() { if let cUser = Networking.currentUser { nameLabel.text = "\(cUser.firstName) \(cUser.lastName)"; followersLabel.text = "Followers: \(cUser.followers.count)"; followingLabel.text = "Following: \(cUser.following.count)"; profilePicture.image = cUser.profilepic; privateLabel.text = "\(cUser.username) is private. Send a follow request to see their photos."; privateLabel.isHidden = true; collectionView.isHidden = false; profilePicture.image = cUser.profilepic; } } @objc func logout() { do { try FIRAuth.auth()?.signOut(); Networking.currentUser = nil; feedPage.followingUsers.removeAll(); feedPage.postFeed.removeAll(); explorePage.listOfUsers.removeAll(); explorePage.listOfUsers_fb.removeAllObjects(); let _ = navigationController?.popToRootViewController(animated: true); self.debug(message: "Signed out!"); self.debug(message: "Logged out!"); } catch { self.debug(message: "There was a problem signing out."); } } @objc func editProfile() { navigationController?.pushViewController(EditProfilePage(), animated: true); } /******************************** * * IMAGE PICKER * ********************************/ @objc func uploadProfilePic() { show(imgPicker, sender: self); } func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) { if let photo = info[UIImagePickerControllerOriginalImage] as? UIImage { // Set the picture on the image view and also on the actual user object. profilePicture.image = photo; let id = Networking.currentUser!.profilePicName; Networking.currentUser!.profilepic = photo; // Delete the old picture from firebase, and replace it with the new one, but keep the same id. let storageRef = FIRStorageReference().child("\(Networking.currentUser!.uid)/\(id!).jpg"); storageRef.delete { error in // If there's an error. if let error = error { self.debug(message: "There was an error deleting the image: \(error)"); } else { // Save the new image. let data = UIImageJPEGRepresentation(photo, 100) as NSData?; let _ = storageRef.put(data! as Data, metadata: nil) { (metaData, error) in if (error == nil) { let post = Post(photo: photo, caption: "", Uploader: Networking.currentUser!, ID: id!); post.isProfilePicture = true; let postObj = post.toDictionary(); Networking.saveObject(object: postObj, path: "Photos/\(Networking.currentUser!.uid)/\(id!)", success: { }, failure: { (err: Error) in }); // self.fireRef.child("Photos").child("\(Networking.currentUser!.uid)").child("\(id!)").setValue(postObj); self.debug(message: "Old profile picture was removed; replace with new one."); } else { print(error.debugDescription); } } } } // Dismiss view controller. imgPicker.dismiss(animated: true, completion: nil); } } /******************************** * * COLLECTION VIEW * ********************************/ func setupCollectionView() { collectionView.register(ProfilePageCell.self, forCellWithReuseIdentifier: "Cell"); collectionView.backgroundColor = view.backgroundColor; adapter.collectionView = collectionView; adapter.dataSource = self; } func objects(for listAdapter: IGListAdapter) -> [IGListDiffable] { if let cUser = Networking.currentUser { return cUser.posts; } else { return []; } } func listAdapter(_ listAdapter: IGListAdapter, sectionControllerFor object: Any) -> IGListSectionController { return ProfileSectionController(vc: self); } func emptyView(for listAdapter: IGListAdapter) -> UIView? { return EmptyPhotoView(place: .top); } }
gpl-3.0
101c46d6bb716e603e60ad8774779c74
31.551282
133
0.549508
5.521966
false
false
false
false
faimin/ZDOpenSourceDemo
ZDOpenSourceSwiftDemo/Pods/lottie-ios/lottie-swift/src/Private/LayerContainers/AnimationContainer.swift
1
6066
// // AnimationContainer.swift // lottie-swift // // Created by Brandon Withrow on 1/24/19. // import Foundation import QuartzCore /** The base animation container. This layer holds a single composition container and allows for animation of the currentFrame property. */ final class AnimationContainer: CALayer { /// The animatable Current Frame Property @NSManaged var currentFrame: CGFloat var imageProvider: AnimationImageProvider { get { return layerImageProvider.imageProvider } set { layerImageProvider.imageProvider = newValue } } func reloadImages() { layerImageProvider.reloadImages() } var renderScale: CGFloat = 1 { didSet { animationLayers.forEach({ $0.renderScale = renderScale }) } } public var respectAnimationFrameRate: Bool = false /// Forces the view to update its drawing. func forceDisplayUpdate() { animationLayers.forEach( { $0.displayWithFrame(frame: currentFrame, forceUpdates: true) }) } func logHierarchyKeypaths() { print("Lottie: Logging Animation Keypaths") animationLayers.forEach({ $0.logKeypaths(for: nil) }) } func setValueProvider(_ valueProvider: AnyValueProvider, keypath: AnimationKeypath) { for layer in animationLayers { if let foundProperties = layer.nodeProperties(for: keypath) { for property in foundProperties { property.setProvider(provider: valueProvider) } layer.displayWithFrame(frame: presentation()?.currentFrame ?? currentFrame, forceUpdates: true) } } } func getValue(for keypath: AnimationKeypath, atFrame: CGFloat?) -> Any? { for layer in animationLayers { if let foundProperties = layer.nodeProperties(for: keypath), let first = foundProperties.first { return first.valueProvider.value(frame: atFrame ?? currentFrame) } } return nil } func layer(for keypath: AnimationKeypath) -> CALayer? { for layer in animationLayers { if let foundLayer = layer.layer(for: keypath) { return foundLayer } } return nil } func animatorNodes(for keypath: AnimationKeypath) -> [AnimatorNode]? { var results = [AnimatorNode]() for layer in animationLayers { if let nodes = layer.animatorNodes(for: keypath) { results.append(contentsOf: nodes) } } if results.count == 0 { return nil } return results } var textProvider: AnimationTextProvider { get { return layerTextProvider.textProvider } set { layerTextProvider.textProvider = newValue } } var animationLayers: ContiguousArray<CompositionLayer> fileprivate let layerImageProvider: LayerImageProvider fileprivate let layerTextProvider: LayerTextProvider init(animation: Animation, imageProvider: AnimationImageProvider, textProvider: AnimationTextProvider) { self.layerImageProvider = LayerImageProvider(imageProvider: imageProvider, assets: animation.assetLibrary?.imageAssets) self.layerTextProvider = LayerTextProvider(textProvider: textProvider) self.animationLayers = [] super.init() bounds = animation.bounds let layers = animation.layers.initializeCompositionLayers(assetLibrary: animation.assetLibrary, layerImageProvider: layerImageProvider, textProvider: textProvider, frameRate: CGFloat(animation.framerate)) var imageLayers = [ImageCompositionLayer]() var textLayers = [TextCompositionLayer]() var mattedLayer: CompositionLayer? = nil for layer in layers.reversed() { layer.bounds = bounds animationLayers.append(layer) if let imageLayer = layer as? ImageCompositionLayer { imageLayers.append(imageLayer) } if let textLayer = layer as? TextCompositionLayer { textLayers.append(textLayer) } if let matte = mattedLayer { /// The previous layer requires this layer to be its matte matte.matteLayer = layer mattedLayer = nil continue } if let matte = layer.matteType, (matte == .add || matte == .invert) { /// We have a layer that requires a matte. mattedLayer = layer } addSublayer(layer) } layerImageProvider.addImageLayers(imageLayers) layerImageProvider.reloadImages() layerTextProvider.addTextLayers(textLayers) layerTextProvider.reloadTexts() setNeedsDisplay() } /// For CAAnimation Use public override init(layer: Any) { self.animationLayers = [] self.layerImageProvider = LayerImageProvider(imageProvider: BlankImageProvider(), assets: nil) self.layerTextProvider = LayerTextProvider(textProvider: DefaultTextProvider()) super.init(layer: layer) guard let animationLayer = layer as? AnimationContainer else { return } currentFrame = animationLayer.currentFrame } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: CALayer Animations override public class func needsDisplay(forKey key: String) -> Bool { if key == "currentFrame" { return true } return super.needsDisplay(forKey: key) } override public func action(forKey event: String) -> CAAction? { if event == "currentFrame" { let animation = CABasicAnimation(keyPath: event) animation.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.linear) animation.fromValue = self.presentation()?.currentFrame return animation } return super.action(forKey: event) } public override func display() { guard Thread.isMainThread else { return } var newFrame: CGFloat = self.presentation()?.currentFrame ?? self.currentFrame if respectAnimationFrameRate { newFrame = floor(newFrame) } animationLayers.forEach( { $0.displayWithFrame(frame: newFrame, forceUpdates: false) }) } } fileprivate class BlankImageProvider: AnimationImageProvider { func imageForAsset(asset: ImageAsset) -> CGImage? { return nil } }
mit
4da5a4ed262566e4c112e8aa9473767b
29.482412
208
0.695846
4.9038
false
false
false
false
zmian/xcore.swift
Sources/Xcore/Cocoa/Animations/TransitionAnimator.swift
1
2729
// // Xcore // Copyright © 2016 Xcore // MIT license, see LICENSE file for details // import UIKit public enum AnimationDirection { case `in` case out } public enum AnimationState { case began case cancelled case ended } open class TransitionContext { public let context: UIViewControllerContextTransitioning public let to: UIViewController public let from: UIViewController public let containerView: UIView public init?(transitionContext: UIViewControllerContextTransitioning) { guard let to = transitionContext.viewController(forKey: .to), let from = transitionContext.viewController(forKey: .from) else { return nil } self.context = transitionContext self.to = to self.from = from self.containerView = transitionContext.containerView } open func completeTransition() { context.completeTransition(!context.transitionWasCancelled) } } open class TransitionAnimator: NSObject, UIViewControllerTransitioningDelegate, UIViewControllerAnimatedTransitioning { open var direction: AnimationDirection = .in // MARK: - UIViewControllerTransitioningDelegate open func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? { direction = .in return self } open func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? { direction = .out return self } // MARK: - UIViewControllerAnimatedTransitioning open func animateTransition(using transitionContext: UIViewControllerContextTransitioning) { guard let context = TransitionContext(transitionContext: transitionContext) else { return transitionContext.completeTransition(!transitionContext.transitionWasCancelled) } // Orientation bug fix // SeeAlso: http://stackoverflow.com/a/20061872/351305 context.from.view.frame = context.containerView.bounds context.to.view.frame = context.containerView.bounds if direction == .in { // Add destination view to container context.containerView.addSubview(context.to.view) } transition(context: context, direction: direction) } open func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval { fatalError(because: .subclassMustImplement) } open func transition(context: TransitionContext, direction: AnimationDirection) { fatalError(because: .subclassMustImplement) } }
mit
53a597fb9fbb3f53932f8a5086e41817
30.356322
175
0.71261
6.008811
false
false
false
false
moosichu/hac-website
Sources/HaCWebsiteLib/Views/Workshops/WorkshopsIndexPage/WorkshopsIndexArchive.swift
2
684
import HaCTML /// Above-the-fold for the WorkshopsIndexPage struct WorkshopsIndexArchive: Nodeable { let workshops: [Workshop] var node: Node { return El.Div[Attr.className => "WorkshopsIndexPage__archive"].containing( El.H2[Attr.className => "Text--sectionHeading"].containing("Browse Workshops"), El.Ul[Attr.className => "WorkshopsIndexPage__archive__list"].containing( workshops.map { workshop in El.Li.containing( El.A[Attr.href => "/workshops/\(workshop.workshopId)", Attr.className => "WorkshopsIndexPage__archive__list__item"].containing( workshop.title ) ) } ) ) } }
mit
613ec40f46e2b9c255e2caef3d259138
31.571429
140
0.631579
4.301887
false
false
false
false
rafalwojcik/WRUserSettings
WRUserSettings/WRUserSettings.swift
1
6512
// // Copyright (c) 2019 Chilli Coder - Rafał Wójcik // // 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 protocol SharedInstanceType: class { init(classType: AnyClass) func clearInstances() } private var userSettingsSingletons = [String: SharedInstanceType]() extension SharedInstanceType { public static var shared: Self { let className = String(describing: self) guard let singleton = userSettingsSingletons[className] as? Self else { let singleton = Self.init(classType: self) userSettingsSingletons[className] = singleton return singleton } return singleton } public func clearInstances() { userSettingsSingletons = [:] } } @objcMembers open class WRUserSettings: NSObject, SharedInstanceType { typealias Property = String private var migrationUserDefaultKey: String { return "MigrationKey-\(uniqueIdentifierKey)" } private let childClassName: String private var uniqueIdentifierKey: String { return "\(childClassName)-WRUserSettingsIdentifier" } private var userDefaults = UserDefaults.standard private var defaultValues: [String: Data] = [:] required public init(classType: AnyClass) { childClassName = String(describing: classType) super.init() if let suiteName = suiteName(), let newUserDefaults = UserDefaults(suiteName: suiteName) { migrateIfNeeded(from: userDefaults, to: newUserDefaults) userDefaults = newUserDefaults } let mirror = Mirror(reflecting: self) for attr in mirror.children { guard let property = attr.label else { continue } saveDefaultValue(property) fillProperty(property) observe(property: property) } } deinit { let mirror = Mirror(reflecting: self) for attr in mirror.children { guard let property = attr.label else { continue } self.removeObserver(self, forKeyPath: property) } } private func userDefaultsKey(forProperty property: Property) -> String { return "\(uniqueIdentifierKey).\(property)" } private func saveDefaultValue(_ property: Property) { guard let object = self.value(forKeyPath: property) else { return } let archivedObject = try? NSKeyedArchiver.data(object: object) defaultValues[property] = archivedObject } private func fillProperty(_ property: Property) { if let data = userDefaults.object(forKey: userDefaultsKey(forProperty: property)) as? Data { let value = NSKeyedUnarchiver.object(data: data) self.setValue(value, forKey: property) } } private func observe(property: Property) { self.addObserver(self, forKeyPath: property, options: [.new], context: nil) } open func suiteName() -> String? { return nil } private func migrateIfNeeded(from: UserDefaults, to: UserDefaults) { guard !from.bool(forKey: migrationUserDefaultKey) else { return } for (key, value) in from.dictionaryRepresentation() where key.hasPrefix(uniqueIdentifierKey) { to.set(value, forKey: key) from.removeObject(forKey: key) } guard to.synchronize() else { return } from.set(true, forKey: migrationUserDefaultKey) from.synchronize() } } // MARK: Public methods extension WRUserSettings { public func reset() { for (property, defaultValue) in defaultValues { let value = NSKeyedUnarchiver.object(data: defaultValue) self.setValue(value, forKey: property) } } } // MARK: Description extension WRUserSettings { override open var description: String { var settings = [String: Any]() for (key, value) in userDefaults.dictionaryRepresentation() where key.hasPrefix(uniqueIdentifierKey) { guard let data = value as? Data else { continue } let newKey = key.replacingOccurrences(of: "\(uniqueIdentifierKey).", with: "") let object = NSKeyedUnarchiver.object(data: data) settings[newKey] = object } return settings.description } } // MARK: KVO extension WRUserSettings { override open func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { guard let keyPath = keyPath else { return } let usKey = userDefaultsKey(forProperty: keyPath) guard let object = self.value(forKeyPath: keyPath) else { userDefaults.removeObject(forKey: usKey) return } let archivedObject = try? NSKeyedArchiver.data(object: object) userDefaults.set(archivedObject, forKey: usKey) userDefaults.synchronize() } } private extension NSKeyedUnarchiver { class func object(data: Data) -> Any? { if #available(iOS 11.0, macOS 10.12, *) { return (try? self.unarchiveTopLevelObjectWithData(data)) ?? nil } else { return self.unarchiveObject(with: data) } } } private extension NSKeyedArchiver { class func data(object: Any) throws -> Data { if #available(iOS 11.0, macOS 10.12, *) { return try self.archivedData(withRootObject: object, requiringSecureCoding: false) } else { return self.archivedData(withRootObject: object) } } }
mit
d52f9734fcf5445e159fd6792c98350d
36.630058
156
0.67235
4.88006
false
false
false
false
ozgur/AutoLayoutAnimation
UserDataSource.swift
1
2156
// // UserDataSource.swift // AutoLayoutAnimation // // Created by Ozgur Vatansever on 10/25/15. // Copyright © 2015 Techshed. All rights reserved. // import UIKit import AddressBook class UserDataSource { fileprivate var users = [User]() var count: Int { return users.count } subscript(index: Int) -> User { return users[index] } func addUser(_ user: User) -> Bool { if users.contains(user) { return false } users.append(user) return true } func removeUser(_ user: User) -> Bool { guard let index = users.index(of: user) else { return false } users.remove(at: index) return true } func loadUsersFromPlist(named: String) -> [User]? { let mainBundle = Bundle.main guard let path = mainBundle.path(forResource: named, ofType: "plist"), content = NSArray(contentsOfFile: path) as? [[String: String]] else { return nil } users = content.map { (dict) -> User in return User(data: dict) } return users } } class User: NSObject { var firstName: String var lastName: String var userId: Int var city: String var fullName: String { let record = ABPersonCreate().takeRetainedValue() as ABRecordRef ABRecordSetValue(record, kABPersonFirstNameProperty, firstName, nil) ABRecordSetValue(record, kABPersonLastNameProperty, lastName, nil) guard let name = ABRecordCopyCompositeName(record)?.takeRetainedValue() else { return "" } return name as String } override var description: String { return "<User: \(fullName)>" } init(firstName: String, lastName: String, userId: Int, city: String) { self.firstName = firstName self.lastName = lastName self.userId = userId self.city = city } convenience init(data: [String: String]) { let firstName = data["firstname"]! let lastName = data["lastname"]! let userId = Int(data["id"]!)! let city = data["city"]! self.init(firstName: firstName, lastName: lastName, userId: userId, city: city) } } func ==(lhs: User, rhs: User) -> Bool { return lhs.userId == rhs.userId }
mit
f032ee58df89001219296f4b25f29ac0
21.925532
83
0.642691
4.028037
false
false
false
false
chrisjmendez/swift-exercises
Walkthroughs/MyPresentation/Carthage/Checkouts/Presentation/Source/PresentationController.swift
1
5229
import UIKit import Pages @objc public protocol PresentationControllerDelegate { func presentationController( presentationController: PresentationController, didSetViewController viewController: UIViewController, atPage page: Int) } public class PresentationController: PagesController { public weak var presentationDelegate: PresentationControllerDelegate? public var maxAnimationDelay: Double = 3 private var backgroundContents = [Content]() private var slides = [SlideController]() private var animationsForPages = [Int : [Animatable]]() private var animationIndex = 0 private weak var scrollView: UIScrollView? var animationTimer: NSTimer? public convenience init(pages: [UIViewController]) { self.init( transitionStyle: .Scroll, navigationOrientation: .Horizontal, options: nil) add(pages) } // MARK: - View lifecycle public override func viewDidLoad() { pagesDelegate = self super.viewDidLoad() } public override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) for subview in view.subviews{ if subview.isKindOfClass(UIScrollView) { scrollView = subview as? UIScrollView scrollView?.delegate = self } } animateAtIndex(0, perform: { animation in animation.play() }) } // MARK: - Public methods public override func goTo(index: Int) { startAnimationTimer() super.goTo(index) if index >= 0 && index < pagesCount { let reverse = index < animationIndex if !reverse { animationIndex = index } for slide in slides { if reverse { slide.goToLeft() } else { slide.goToRight() } } scrollView?.delegate = nil animateAtIndex(animationIndex, perform: { animation in if reverse { animation.playBack() } else { animation.play() } }) } } // MARK: - Animation Timer func startAnimationTimer() { stopAnimationTimer() scrollView?.userInteractionEnabled = false if animationTimer == nil { dispatch_async(dispatch_get_main_queue()) { self.animationTimer = NSTimer.scheduledTimerWithTimeInterval(self.maxAnimationDelay, target: self, selector: "updateAnimationTimer:", userInfo: nil, repeats: false) NSRunLoop.currentRunLoop().addTimer(self.animationTimer!, forMode: NSRunLoopCommonModes) } } } func stopAnimationTimer() { animationTimer?.invalidate() animationTimer = nil } func updateAnimationTimer(timer: NSTimer) { stopAnimationTimer() scrollView?.userInteractionEnabled = true } } // MARK: - Content extension PresentationController { public override func add(viewControllers: [UIViewController]) { for controller in viewControllers { if controller is SlideController { slides.append((controller as! SlideController)) } } super.add(viewControllers) } public func addToBackground(elements: [Content]) { for content in elements { backgroundContents.append(content) view.addSubview(content.view) view.sendSubviewToBack(content.view) content.layout() } } } // MARK: - Animations extension PresentationController { public func addAnimations(animations: [Animatable], forPage page: Int) { for animation in animations { addAnimation(animation, forPage: page) } } public func addAnimation(animation: Animatable, forPage page: Int) { if animationsForPages[page] == nil { animationsForPages[page] = [] } animationsForPages[page]?.append(animation) } private func animateAtIndex(index: Int, perform: (animation: Animatable) -> Void) { if let animations = animationsForPages[index] { for animation in animations { perform(animation: animation) } } } } // MARK: - PagesControllerDelegate extension PresentationController: PagesControllerDelegate { public func pageViewController(pageViewController: UIPageViewController, setViewController viewController: UIViewController, atPage page: Int) { animationIndex = page scrollView?.delegate = self presentationDelegate?.presentationController(self, didSetViewController: viewController, atPage: page) } } // MARK: - UIScrollViewDelegate extension PresentationController: UIScrollViewDelegate { public func scrollViewDidScroll(scrollView: UIScrollView) { let offset = scrollView.contentOffset.x - CGRectGetWidth(view.frame) let offsetRatio = offset / CGRectGetWidth(view.frame) var index = animationIndex if offsetRatio > 0.0 || index == 0 { index++ } let canMove = offsetRatio != 0.0 && !(animationIndex == 0 && offsetRatio < 0.0) && !(index == pagesCount) if canMove { animateAtIndex(index, perform: { animation in animation.moveWith(offsetRatio) }) for slide in slides { if index <= animationIndex { slide.goToLeft() } else { slide.goToRight() } } } scrollView.layoutIfNeeded() view.layoutIfNeeded() } }
mit
35c6e28338a0f17fb0992c0cb46b18d3
23.32093
96
0.66724
5.04243
false
false
false
false
LearningSwift2/LearningApps
SimpleSegue/SimpleSegue/ViewController.swift
1
1108
// // ColorViewController.swift // SimpleSegue // // Created by Phil Wright on 3/1/16. // Copyright © 2016 The Iron Yard. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var label: UILabel! @IBAction func redButtonTapped(sender: AnyObject) { label.text = "Red" performSegueWithIdentifier("ShowColor", sender: UIColor.redColor()) } @IBAction func greenButtonTapped(sender: AnyObject) { label.text = "Green" performSegueWithIdentifier("ShowColor", sender: UIColor.greenColor()) } @IBAction func blueButtonTapped(sender: AnyObject) { label.text = "Blue" performSegueWithIdentifier("ShowColor", sender: UIColor.blueColor()) } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "ShowColor" { if let destinationController = segue.destinationViewController as? ColorViewController { destinationController.color = sender as? UIColor } } } }
apache-2.0
3042741260c39d527150ab4910b930fa
26
100
0.65131
4.941964
false
false
false
false
trujillo138/MyExpenses
MyExpenses/MyExpenses/Common/UI/Controls/AddExpenseButton.swift
1
3873
// // AddExpenseButton.swift // MyExpenses // // Created by Tomas Trujillo on 10/18/17. // Copyright © 2017 TOMApps. All rights reserved. // import UIKit protocol AddExpenseButtonDelegate { func buttonWasTapped() } class AddExpenseButton: UIView { //MARK: Properties var delegate: AddExpenseButtonDelegate? private var buttonPath: CAShapeLayer? private var plusHorizontalPath: CAShapeLayer? private var plusVerticalPath: CAShapeLayer? private var strokeColor: UIColor { return UIColor.ME_ButtonColor } //MARK Drawing override func draw(_ rect: CGRect) { buttonPath = CAShapeLayer() plusHorizontalPath = CAShapeLayer() plusVerticalPath = CAShapeLayer() var buttonRect = self.bounds buttonRect = buttonRect.insetBy(dx: 0.95, dy: 0.95) let path = UIBezierPath(ovalIn: buttonRect) let center = CGPoint(x: bounds.midX, y: bounds.midY) let length = bounds.width * 2 / 3 let horizontalPath = UIBezierPath() horizontalPath.move(to: CGPoint(x: center.x - length / 2, y: center.y)) horizontalPath.addLine(to: CGPoint(x: center.x + length / 2, y: center.y)) let verticalPath = UIBezierPath() verticalPath.move(to: CGPoint(x: center.x, y: center.y - length / 2)) verticalPath.addLine(to: CGPoint(x: center.x, y: center.y + length / 2)) path.addClip() buttonPath?.path = path.cgPath plusHorizontalPath?.path = horizontalPath.cgPath plusVerticalPath?.path = verticalPath.cgPath buttonPath?.strokeColor = strokeColor.cgColor buttonPath?.fillColor = UIColor.white.cgColor buttonPath?.lineWidth = 5.0 buttonPath?.lineCap = kCALineCapRound plusHorizontalPath?.strokeColor = strokeColor.cgColor plusHorizontalPath?.fillColor = UIColor.clear.cgColor plusHorizontalPath?.lineWidth = 5.0 plusHorizontalPath?.lineCap = kCALineCapRound plusVerticalPath?.strokeColor = strokeColor.cgColor plusVerticalPath?.fillColor = UIColor.clear.cgColor plusVerticalPath?.lineWidth = 5.0 plusVerticalPath?.lineCap = kCALineCapRound self.layer.addSublayer(buttonPath!) self.layer.addSublayer(plusHorizontalPath!) self.layer.addSublayer(plusVerticalPath!) } private func animateButton(){ // guard let button = buttonPath, let horizontalPath = plusHorizontalPath, // let verticalPath = plusVerticalPath else { return } // let scaleAnimation = CABasicAnimation(keyPath: "transform.scale") // scaleAnimation.fromValue = 1.0 // scaleAnimation.toValue = 1.25 // scaleAnimation.isRemovedOnCompletion = true // scaleAnimation.duration = 0.4 // button.add(scaleAnimation, forKey: "scale animation") // horizontalPath.add(scaleAnimation, forKey: "scale animation") // verticalPath.add(scaleAnimation, forKey: "scale animation") } func show() { UIView.animate(withDuration: 0.4) { self.alpha = 1.0 } } func hide() { UIView.animate(withDuration: 0.4) { self.alpha = 0.0 } } //MARK: Intialization private func setup() { backgroundColor = UIColor.clear isOpaque = false contentMode = .redraw addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(tappedButton))) } @objc func tappedButton(tapGesture: UITapGestureRecognizer) { animateButton() delegate?.buttonWasTapped() } override init(frame: CGRect) { super.init(frame: frame) setup() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setup() } }
apache-2.0
3ad7569284c30390bd848be4668601b4
31.537815
99
0.641012
4.913706
false
false
false
false
carabina/TapGestureGenerater
TapGestureGeneraterExample/TapGestureGenerater/ViewController.swift
1
7850
// // ViewController.swift // TapGestureGenerater // // Created by ikemai on 08/21/2015. // Copyright (c) 2015 ikemai. All rights reserved. // import UIKit import TapGestureGenerater class ViewController: UIViewController { @IBOutlet weak var labelView: UILabel! @IBOutlet weak var summaryLabelView: UILabel! @IBOutlet weak var tapButton: UIButton! @IBOutlet weak var touchButton: UIButton! @IBOutlet weak var pinchingButton: UIButton! @IBOutlet weak var pinchInOutButton: UIButton! @IBOutlet weak var SwipButton: UIButton! private var tapGestureView: TapGestureGenerater! private let tapColor = UIColor.greenColor() private let touchColor = UIColor.magentaColor() private let pinchColor = UIColor.blueColor() private let swipColor = UIColor.orangeColor() override func viewDidLoad() { super.viewDidLoad() tapGestureView = TapGestureGenerater(frame: view.frame) tapGestureView.backgroundColor = UIColor.whiteColor() view.addSubview(tapGestureView) view.sendSubviewToBack(tapGestureView) labelView.text = "" summaryLabelView.text = "" setButton(tapButton, color: tapColor) setButton(touchButton, color: touchColor) setButton(pinchingButton, color: pinchColor) setButton(pinchInOutButton, color: pinchColor) setButton(SwipButton, color: swipColor) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func tapButtonDidDown(sender: AnyObject) { tapGestureView.reset() setTapGestures() } @IBAction func touchButtonDidDown(sender: AnyObject) { tapGestureView.reset() setTouchesAndDrag() } @IBAction func pinchingButtonDidDown(sender: AnyObject) { tapGestureView.reset() setPinchingGesture() } @IBAction func pinchInOutButtonDidDown(sender: AnyObject) { tapGestureView.reset() setPinchInOutGesture() } @IBAction func SwipButtonDidDown(sender: AnyObject) { tapGestureView.reset() setSwipGesture() } private func setButton(button: UIButton, color: UIColor) { button.backgroundColor = color button.layer.cornerRadius = tapButton.bounds.width / 2 button.layer.masksToBounds = true button.layer.borderWidth = 1.0 button.layer.borderColor = UIColor.whiteColor().CGColor } } // // MARK:- Set tap gestures // extension ViewController { private func setTapGestures() { // Tap tapGestureView.setTapGesture({[weak self] tapGestureView in if let me = self { me.tapGestureView.backgroundColor = me.tapColor me.labelView.text = "Tap Gesture" me.summaryLabelView.text = "" } }) // Double tap tapGestureView.setDoubleTapGesture({[weak self] tapGestureView in if let me = self { me.tapGestureView.backgroundColor = me.tapColor me.labelView.text = "Double Tap Gesture" me.summaryLabelView.text = "" } }) // Triple tap tapGestureView.setTripleTapGesture({[weak self] tapGestureView in if let me = self { me.tapGestureView.backgroundColor = me.tapColor me.labelView.text = "Triple Tap Gesture" me.summaryLabelView.text = "" } }) } } // // MARK:- Set touches and dragging // extension ViewController { private func setTouchesAndDrag() { // Touches began tapGestureView.setTouchesBegan({[weak self] tapGestureView, point in if let me = self { me.tapGestureView.backgroundColor = me.touchColor me.labelView.text = "Touches Began" me.summaryLabelView.text = "point = \(point)" } }) // Touches cancelled tapGestureView.setTouchesCancelled({[weak self] tapGestureView, point in if let me = self { me.tapGestureView.backgroundColor = me.touchColor me.labelView.text = "Touches Cancelled" me.summaryLabelView.text = "point = \(point)" } }) // Touches ended tapGestureView.setTouchesEnded({[weak self] tapGestureView, point in if let me = self { me.tapGestureView.backgroundColor = me.touchColor me.labelView.text = "Touches Ended" me.summaryLabelView.text = "point = \(point)" } }) // Dragging tapGestureView.setDraggingGesture({[weak self] tapGestureView, deltaPoint in if let me = self { me.tapGestureView.backgroundColor = me.touchColor me.labelView.text = "Dragging" me.summaryLabelView.text = "deltaPoint = \(deltaPoint)" } }) } } // // MARK:- Set pinch gestures // extension ViewController { private func setPinchingGesture() { // Pinching tapGestureView.setPinchingGesture({[weak self] tapGestureView, sender in if let me = self { me.tapGestureView.backgroundColor = me.pinchColor me.labelView.text = "Pinching Gesture" me.summaryLabelView.text = "sender = \(sender)" } }) } private func setPinchInOutGesture() { // Pinch in tapGestureView.setPinchInGesture({[weak self] tapGestureView, sender in if let me = self { me.tapGestureView.backgroundColor = me.pinchColor me.labelView.text = "Pinch In Gesture" me.summaryLabelView.text = "sender = \(sender)" } }) // Pinch out tapGestureView.setPinchOutGesture({[weak self] tapGestureView, sender in if let me = self { me.tapGestureView.backgroundColor = me.pinchColor me.labelView.text = "Pinch Out Gesture" me.summaryLabelView.text = "sender = \(sender)" } }) } } // // MARK:- Set swip gestures // extension ViewController { private func setSwipGesture() { // Swip to left tapGestureView.setSwipToLeftGesture({[weak self] tapGestureView, gesture in if let me = self { me.tapGestureView.backgroundColor = me.swipColor me.labelView.text = "Swip To Left" me.summaryLabelView.text = "gesture = \(gesture)" } }) // Swip to right tapGestureView.setSwipToRightGesture({[weak self] tapGestureView, gesture in if let me = self { me.tapGestureView.backgroundColor = me.swipColor me.labelView.text = "Swip To Right" me.summaryLabelView.text = "gesture = \(gesture)" } }) // Swip to top tapGestureView.setSwipToUpGesture({[weak self] tapGestureView, gesture in if let me = self { me.tapGestureView.backgroundColor = me.swipColor me.labelView.text = "Swip To Up" me.summaryLabelView.text = "gesture = \(gesture)" } }) // Swip to down tapGestureView.setSwipToDownGesture({[weak self] tapGestureView, gesture in if let me = self { me.tapGestureView.backgroundColor = me.swipColor me.labelView.text = "Swip To Down" me.summaryLabelView.text = "gesture = \(gesture)" } }) } }
mit
d20748b7d76f5bb1ee4334b6cac4c262
32.836207
84
0.587261
5.110677
false
false
false
false
NoryCao/zhuishushenqi
zhuishushenqi/NewVersion/Comment/ZSPostReviewBook.swift
1
505
// // Book.swift // // Create by 农运 on 7/8/2019 // Copyright © 2019. All rights reserved. // 模型生成器(小波汉化)JSONExport: https://github.com/Ahmed-Ali/JSONExport import Foundation import HandyJSON struct ZSPostReviewBook :HandyJSON{ var id : String = "" var allowFree : Bool = false var apptype : [Int] = [] var author : String = "" var cover : String = "" var latelyFollower : AnyObject? var retentionRatio : AnyObject? var safelevel : Int = 0 var title : String = "" }
mit
c81a702bcc01ac83a6c0edf6efb17f76
19.782609
65
0.682008
3.025316
false
false
false
false
lstanii-magnet/ChatKitSample-iOS
ChatMessenger/Pods/ChatKit/ChatKit/source/src/Helpers/Utils/Utils.swift
1
13147
/* * Copyright (c) 2016 Magnet Systems, Inc. * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you * may not use this file except in compliance with the License. You * may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. */ import UIKit import MagnetMax extension UIImage { convenience init(view: UIView) { UIGraphicsBeginImageContext(view.frame.size) view.layer.renderInContext(UIGraphicsGetCurrentContext()!) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() self.init(CGImage: image.CGImage!) } } class UtilsImageOperation : MMAsyncBlockOperation { //Mark: Public variables var url : NSURL? weak var imageView : UIImageView? } public class UtilsImageCache : UtilsCache { //Mark: Public variables public var maxImageCacheSize : Int = 4194304 //2^22 = 4mb public static var sharedCache : UtilsImageCache = { let cache = UtilsImageCache() return cache }() public func setImage(image : UIImage, forURL : NSURL) { let data = UIImagePNGRepresentation(image) var size = 0 if let len = data?.length { size = len } self.setObject(image, forURL: forURL, cost:size) } public func imageForUrl(url : NSURL) -> UIImage? { return self.objectForURL(url) as? UIImage } } public class Utils: NSObject { //MARK: Private Properties private static var queue : NSOperationQueue = { let queue = NSOperationQueue() queue.underlyingQueue = dispatch_queue_create("operation - images", nil) queue.maxConcurrentOperationCount = 10 return queue }() //MARK: Image Loading public static func loadImageWithUrl(url : NSURL?, toImageView: UIImageView, placeholderImage:UIImage?) { loadImageWithUrl(url, toImageView: toImageView, placeholderImage: placeholderImage, completion: nil) } public static func loadImageWithUrl(url : NSURL?, toImageView: UIImageView, placeholderImage:UIImage?, onlyShowAfterDownload:Bool) { loadImageWithUrl(url, toImageView: toImageView, placeholderImage: placeholderImage, onlyShowAfterDownload:onlyShowAfterDownload, completion: nil) } public static func loadImageWithUrl(url : NSURL?, toImageView: UIImageView, placeholderImage:UIImage?, completion : ((image : UIImage?)->Void)?) { loadImageWithUrl(url, toImageView: toImageView, placeholderImage: placeholderImage, onlyShowAfterDownload: placeholderImage == nil, completion: completion) } public static func loadImageWithUrl(url : NSURL?, toImageView: UIImageView, placeholderImage:UIImage?, onlyShowAfterDownload:Bool, completion : ((image : UIImage?)->Void)?) { imageWithUrl(url, toImageView: toImageView, placeholderImage: placeholderImage, onlyShowAfterDownload: onlyShowAfterDownload, completion: completion) } public static func loadUserAvatar(user : MMUser, toImageView: UIImageView, placeholderImage:UIImage?) { loadImageWithUrl(user.avatarURL(), toImageView: toImageView, placeholderImage: placeholderImage) } public static func loadUserAvatarByUserID(userID : String, toImageView: UIImageView, placeholderImage:UIImage?) { toImageView.image = placeholderImage MMUser.usersWithUserIDs([userID], success: { (users) -> Void in let user = users.first if (user != nil) { Utils.loadUserAvatar(user!, toImageView: toImageView, placeholderImage: placeholderImage) } }) { (error) -> Void in //print("error getting users \(error)") } } //MARK: User Avatar Generation public static func firstCharacterInString(s: String) -> String { if s == "" { return "" } return s.substringWithRange(Range<String.Index>(start: s.startIndex, end: s.endIndex.advancedBy(-(s.characters.count - 1)))) } public class func name(name: AnyClass) -> String { let ident:String = NSStringFromClass(name).componentsSeparatedByString(".").last! return ident } public static func noAvatarImageForUser(user : MMUser) -> UIImage { return Utils.noAvatarImageForUser(user.firstName, lastName: user.lastName ?? "") } public static func noAvatarImageForUser(firstName : String?, lastName:String?) -> UIImage { var fName = "" var lName = "" if let firstName = firstName{ fName = firstName } if let lastName = lastName { lName = lastName } let diameter : CGFloat = 30.0 * 3 let view : UIView = UIView(frame: CGRect(x: 0, y: 0, width: diameter, height: diameter)) let lbl : UILabel = UILabel(frame: CGRect(x: 0, y: 0, width: diameter, height: diameter)) lbl.backgroundColor = MagnetControllerAppearance.tintColor let f = firstCharacterInString(fName).uppercaseString let l = firstCharacterInString(lName).uppercaseString lbl.font = UIFont.systemFontOfSize(diameter * 0.5) lbl.text = "\(f)\(l)" lbl.textAlignment = NSTextAlignment.Center lbl.textColor = UIColor.whiteColor() view.addSubview(lbl) let image:UIImage = UIImage.init(view: view) return image } public class func resizeImage(image:UIImage, toSize:CGSize) -> UIImage { UIGraphicsBeginImageContextWithOptions(toSize, false, 0.0); image.drawInRect(CGRect(x: 0, y: 0, width: toSize.width, height: toSize.height)) let newImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return newImage; } //MARK: User Naming public class func displayNameForUser(user : MMUser) -> String { //create username var name : String = "" if user.firstName != nil { name = "\(user.firstName)" } if user.lastName != nil { name += (name.characters.count > 0 ? " " : "") + user.lastName } if name.characters.count == 0 { name = user.userName } return name } public class func nameForUser(user : MMUser) -> String { //create username var name = user.userName if user.lastName != nil { name = user.lastName } else if user.firstName != nil { name = user.firstName } return name } //MARK: Private Methods private static func imageWithUrl(url : NSURL?, toImageView: UIImageView, placeholderImage:UIImage?, onlyShowAfterDownload:Bool, completion : ((image : UIImage?)->Void)?) { for operation in queue.operations { if let imageOperation = operation as? UtilsImageOperation { if imageOperation.imageView === toImageView { imageOperation.cancel() } } } guard let imageUrl = url else { //print("no url content data") if !onlyShowAfterDownload { toImageView.image = placeholderImage } completion?(image: nil) return } if let image = UtilsImageCache.sharedCache.imageForUrl(imageUrl) { toImageView.image = image return } if !onlyShowAfterDownload { toImageView.image = placeholderImage } let imageOperation = UtilsImageOperation(with: { operation in if let imageOperation = operation as? UtilsImageOperation { if let image = UtilsImageCache.sharedCache.imageForUrl(imageUrl) { toImageView.image = image return } var image : UIImage? if let imageData = NSData(contentsOfURL: imageUrl) { image = UIImage(data: imageData) } dispatch_async(dispatch_get_main_queue(), { let image = imageForImageView(imageOperation, image: image, placeholderImage: placeholderImage) completion?(image: image) }) imageOperation.finish() } }) imageOperation.imageView = toImageView imageOperation.url = url self.queue.addOperation(imageOperation) } static func imageForImageView(operation : UtilsImageOperation, image : UIImage?, placeholderImage : UIImage? ) -> UIImage? { if let url = operation.url, let img = image { UtilsImageCache.sharedCache.setImage(img, forURL: url) } if !operation.cancelled { if let img = image { operation.imageView?.image = img } else { operation.imageView?.image = placeholderImage } } return operation.imageView?.image } } extension Array { func findInsertionIndexForSortedArray<T : Comparable>(mappedObject : ((obj : Generator.Element) -> T), object : T) -> Int { return self.findInsertionIndexForSortedArrayWithBlock() { (haystack) -> Bool in return mappedObject(obj: haystack) > object } } func findInsertionIndexForSortedArrayWithBlock(greaterThan GR_TH : (Generator.Element) -> Bool) -> Int { return Array.findInsertionIndex(self) { (haystack) -> Bool in return GR_TH(haystack) } } func searchrSortedArrayWithBlock(greaterThan GR_TH : (Generator.Element) -> Bool?) -> Int? { return Array.find(self) { (haystack) -> Bool? in return GR_TH(haystack) } } func searchrSortedArray<T : Comparable>(mappedObject : ((obj : Generator.Element) -> T), object : T) -> Int? { return self.searchrSortedArrayWithBlock() { (haystack) -> Bool? in let mapped = mappedObject(obj: haystack) if mapped == object { return nil } return mapped > object } } static private func find(haystack : Array<Element>, greaterThan : (haystack : Generator.Element) -> Bool?) -> Int? { //search for index of user group based on letter if haystack.count == 0 { return nil } let index = haystack.count >> 0x1 let compare = haystack[index] let isGreater = greaterThan(haystack: compare) if isGreater == nil {//if equal return index } else if let greater = isGreater where greater == true { //if greater return find(Array(haystack[0..<index]), greaterThan : greaterThan) } if let rightIndex = find(Array(haystack[index + 1..<haystack.count]), greaterThan : greaterThan) { return rightIndex + index + 1 } return nil } static private func findInsertionIndex(haystack : Array<Element>, greaterThan : ((haystack : Generator.Element) -> Bool)) -> Int { if haystack.count == 0 { return 0 } let index = haystack.count >> 0x1 let compare = haystack[index] if greaterThan(haystack: compare) { return findInsertionIndex(Array(haystack[0..<index]), greaterThan : greaterThan) } return findInsertionIndex(Array(haystack[index + 1..<haystack.count]), greaterThan : greaterThan) + 1 + index } } extension Array where Element : Comparable { func findInsertionIndexForSortedArray(obj : Generator.Element) -> Int { return self.findInsertionIndexForSortedArrayWithBlock() { (haystack) -> Bool in return haystack > obj } } func searchrSortedArray(obj : Generator.Element) -> Int? { return self.searchrSortedArrayWithBlock() { (haystack) -> Bool? in if haystack == obj { return nil } return haystack > obj } } } public class MagnetControllerAppearance { public static var tintColor : UIColor = UIColor(hue: 210.0 / 360.0, saturation: 0.94, brightness: 1.0, alpha: 1.0) public var tintColor : UIColor { set { self.dynamicType.tintColor = newValue } get { return self.dynamicType.tintColor } } }
apache-2.0
0b7a33c612852442b19e49b0d1fa341f
32.796915
179
0.599072
5.242026
false
false
false
false
MoralAlberto/SlackWebAPIKit
Example/Tests/Integration/Groups/FindGroupAndSendMessageSpec.swift
1
2503
import Quick import Nimble import Alamofire import RxSwift @testable import SlackWebAPIKit class FindGroupAndSendMessageSpec: QuickSpec { class MockGroupAPIClient: APIClientProtocol { func execute(withURL url: URL?) -> Observable<[String: Any]> { let json = readJSON(name: "apiclient.list.groups.succeed") as? [String: Any] return Observable.from(optional: json) } } class MockChatAPIClient: APIClientProtocol { func execute(withURL url: URL?) -> Observable<[String: Any]> { let json = readJSON(name: "apiclient.postmessage.group.succeed") as? [String: Any] return Observable.from(optional: json) } } override func spec() { describe("\(String(describing: FindGroupAndPostMessageUseCase.self)) Spec") { context("list user use case") { var sut: FindGroupAndPostMessageUseCaseProtocol! let mockGroupAPIClient = MockGroupAPIClient() let mockChatAPIClient = MockChatAPIClient() let groupRemoteDatasource = GroupDatasource(apiClient: mockGroupAPIClient) let chatRemoteDatasource = ChatDatasource(apiClient: mockChatAPIClient) let groupRepository = GroupRepository(remoteDatasource: groupRemoteDatasource) let chatRepository = ChatRepository(remoteDatasource: chatRemoteDatasource) let disposeBag = DisposeBag() beforeEach { let findGroupUseCase = FindGroupUseCase(repository: groupRepository) let postMessageUseCase = PostMessageUseCase(repository: chatRepository) sut = FindGroupAndPostMessageUseCase(findGroupUseCase: findGroupUseCase, postMessageUseCase: postMessageUseCase) } it("send message") { sut.execute(text: "Hello", group: "secret").subscribe(onNext: { isSent in expect(isSent).to(equal(true)) }).addDisposableTo(disposeBag) } it("group NOT found") { sut.execute(text: "Hello", group: "channel-five").subscribe(onError: { error in expect(error as? GroupDatasourceError).to(equal(GroupDatasourceError.groupNotFound)) }).addDisposableTo(disposeBag) } } } } }
mit
5f55bb8ebf358696eeadd122220b0ef6
43.696429
132
0.597283
5.441304
false
false
false
false
ifeherva/HSTracker
HSTracker/Importers/Handlers/HearthstoneTopDeck.swift
1
2202
// // HearthstoneTopDeck.swift // HSTracker // // Created by Benjamin Michotte on 11/10/16. // Copyright © 2016 Benjamin Michotte. All rights reserved. // import Foundation import Kanna import RegexUtil struct HearthstoneTopDeck: HttpImporter { var siteName: String { return "Hearthstonetopdeck" } var handleUrl: RegexPattern { return "hearthstonetopdeck\\.com\\/deck" } var preferHttps: Bool { return false } func loadDeck(doc: HTMLDocument, url: String) -> (Deck, [Card])? { guard let nameNode = doc.at_xpath("//h1[contains(@class, 'panel-title')]"), let deckName = nameNode.text?.replace("\\s+", with: " ").trim() else { logger.error("Deck name not found") return nil } logger.verbose("Got deck name \(deckName)") let xpath = "//div[contains(@class, 'deck_banner_description')]" + "//span[contains(@class, 'midlarge')]/span" let nodeInfos = doc.xpath(xpath) guard let className = nodeInfos[1].text?.trim(), let playerClass = CardClass(rawValue: className.lowercased()) else { logger.error("Class not found") return nil } logger.verbose("Got class \(playerClass)") let deck = Deck() deck.playerClass = playerClass deck.name = deckName var cards: [Card] = [] let cardNodes = doc.xpath("//div[contains(@class, 'cardname')]/span") for cardNode in cardNodes { guard let nameStr = cardNode.text else { continue } let matches = nameStr.matches("^\\s*(\\d+)\\s+(.*)\\s*$") logger.verbose("\(nameStr) \(matches)") if let countStr = matches.first?.value, let count = Int(countStr), let cardName = matches.last?.value, let card = Cards.by(englishNameCaseInsensitive: cardName) { card.count = count logger.verbose("Got card \(card)") cards.append(card) } } logger.verbose("is valid : \(deck.isValid()) \(deck.countCards())") return (deck, cards) } }
mit
789fd2114fc8969c2556ea0ca8de7df3
32.348485
83
0.562926
4.249035
false
false
false
false
material-components/material-components-ios
catalog/MDCCatalog/MDCDebugSafeAreaInsetsView.swift
2
2161
// Copyright 2017-present the Material Components for iOS authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import UIKit class MDCDebugSafeAreaInsetsView: UIView { fileprivate var edgeViews = [UIView]() override init(frame: CGRect) { super.init(frame: frame) isUserInteractionEnabled = false backgroundColor = .clear for _ in 0...3 { let view = UIView() view.backgroundColor = UIColor.red.withAlphaComponent(0.15) view.isUserInteractionEnabled = false edgeViews.append(view) addSubview(view) } } @available(*, unavailable) required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override open func safeAreaInsetsDidChange() { setNeedsLayout() layoutIfNeeded() } override func layoutSubviews() { var safeAreaInsets = UIEdgeInsets.zero safeAreaInsets = self.safeAreaInsets let width = frame.width let height = frame.height let insetHeight = height - safeAreaInsets.top - safeAreaInsets.bottom // top edgeViews[0].frame = CGRect(x: 0, y: 0, width: width, height: safeAreaInsets.top) // left edgeViews[1].frame = CGRect( x: 0, y: safeAreaInsets.top, width: safeAreaInsets.left, height: insetHeight) // bottom edgeViews[2].frame = CGRect( x: 0, y: height - safeAreaInsets.bottom, width: width, height: safeAreaInsets.bottom) // right edgeViews[3].frame = CGRect( x: width - safeAreaInsets.right, y: safeAreaInsets.top, width: safeAreaInsets.right, height: insetHeight) } }
apache-2.0
ca7dcc41f69ccd2e3ebd4b2b27ad3154
27.064935
87
0.686719
4.437372
false
false
false
false
zambelz48/swift-sample-dependency-injection
SampleDI/App/User/ViewModels/LoginViewModel.swift
1
2361
// // LoginViewModel.swift // SampleDI // // Created by Nanda Julianda Akbar on 8/23/17. // Copyright © 2017 Nanda Julianda Akbar. All rights reserved. // import Foundation import RxSwift final class LoginViewModel { // MARK: Dependencies private var userService: UserServiceProtocol private var userModel: UserModelProtocol // MARK: Private properties private let minUsernameLength: Int = 5 private let minPasswordLength: Int = 8 private let loginSuccessSubject = PublishSubject<Void>() private let loginFailedSubject = PublishSubject<NSError>() private let disposeBag = DisposeBag() // MARK: Public properties var username = Variable<String>("") var password = Variable<String>("") var loginSuccessObservable: Observable<Void> { return loginSuccessSubject.asObservable() } var loginFailedObservable: Observable<NSError> { return loginFailedSubject.asObservable() } init(userService: UserServiceProtocol, userModel: UserModelProtocol) { self.userService = userService self.userModel = userModel configureUserDataChangesObservable() } // MARK: Private methods private func configureUserDataChangesObservable() { userModel.userDataSuccessfullyChangedObservable .bind(to: loginSuccessSubject) .disposed(by: disposeBag) userModel.userDataFailChangedObservable .bind(to: loginFailedSubject) .disposed(by: disposeBag) } // MARK: Public methods func isUsernameValid() -> Observable<Bool> { return username.asObservable() .map { $0.count >= self.minUsernameLength } } func isPasswordValid() -> Observable<Bool> { return password.asObservable() .map { $0.count >= self.minPasswordLength } } func isUsernameAndPasswordValid() -> Observable<Bool> { return Observable .combineLatest(isUsernameValid(), isPasswordValid()) { $0 && $1 } .distinctUntilChanged() } func performLogin() { userService.performLogin( username: username.value, password: password.value ) .subscribe( onNext: { [weak self] user in self?.userModel.storeUserData(with: user) }, onError: { [weak self] error in let nsError = error as NSError self?.loginFailedSubject.onNext(nsError) } ) .disposed(by: disposeBag) } deinit { loginSuccessSubject.onCompleted() loginFailedSubject.onCompleted() } }
mit
043bb413c92426b9687a9b7a233bc254
21.264151
63
0.717797
3.986486
false
false
false
false
dunkelstern/unchained
Unchained/router.swift
1
9781
// // router.swift // unchained // // Created by Johannes Schriewer on 30/11/15. // Copyright © 2015 Johannes Schriewer. All rights reserved. // import TwoHundred import UnchainedString import UnchainedLogger import SwiftyRegex /// Unchained route entry public struct Route { /// Router errors public enum Error: ErrorType { /// No route with that name exists case NoRouteWithThatName(name: String) /// Route contains mix of numbered and named parameters case MixedNumberedAndNamedParameters /// Missing parameter of `name` to call that route case MissingParameterForRoute(name: String) /// Wrong parameter count for a route with unnamed parameters case WrongParameterCountForRoute } /// A route request handler, takes `request`, numbered `parameters` and `namedParameters`, returns `HTTPResponseBase` public typealias RequestHandler = ((request: HTTPRequest, parameters: [String], namedParameters: [String:String]) -> HTTPResponseBase) /// Name of the route (used for route reversing) public var name: String private var re: RegEx? private var handler:RequestHandler /// Initialize a route /// /// - parameter regex: Regex to match /// - parameter handler: handler callback to run if route matches /// - parameter name: (optional) name of this route to `reverse` public init(_ regex: String, handler:RequestHandler, name: String? = nil) { do { self.re = try RegEx(pattern: regex) } catch RegEx.Error.InvalidPattern(let offset, let message) { Log.error("Route: Pattern parse error for pattern \(regex) at character \(offset): \(message)") } catch { // unused } self.handler = handler if let name = name { self.name = name } else { self.name = "r'\(regex)'" } } /// execute a route on a request /// /// - parameter request: the request on which to execute this route /// - returns: response to the request or nil if the route does not match public func execute(request: HTTPRequest) -> HTTPResponseBase? { guard let re = self.re else { return nil } let matches = re.match(request.header.url) if matches.numberedParams.count > 0 { return self.handler(request: request, parameters: matches.numberedParams, namedParameters: matches.namedParams) } return nil } // MARK: - Internal enum RouteComponentType { case Text(String) case NamedPattern(String) case NumberedPattern(Int) } /// split a route regex into components for route reversal /// /// - returns: Array of route components func splitIntoComponents() -> [RouteComponentType]? { guard let pattern = self.re?.pattern else { return nil } var patternNum = 0 var openBrackets = 0 var components = [RouteComponentType]() var currentComponent = "" currentComponent.reserveCapacity(pattern.characters.count) var gen = pattern.characters.generate() while let c = gen.next() { switch c { case "(": if openBrackets == 0 { // split point if currentComponent.characters.count > 0 { patternNum += 1 components.append(.Text(currentComponent)) currentComponent.removeAll() } } break case ")": if openBrackets == 0 { // split point if currentComponent.characters.count > 0 { var found = false for (name, idx) in self.re!.namedCaptureGroups { if idx == patternNum { components.append(.NamedPattern(name)) currentComponent.removeAll() found = true break } } if !found { components.append(.NumberedPattern(patternNum)) } } } case "[": openBrackets += 1 case "]": openBrackets -= 1 case "\\": // skip next char gen.next() default: currentComponent.append(c) } } if currentComponent.characters.count > 0 { components.append(.Text(currentComponent)) } // strip ^ on start if case .Text(let text) = components.first! { if text.characters.first! == "^" { components[0] = .Text(text.subString(fromIndex: text.startIndex.advancedBy(1))) } } // strip $ on end if case .Text(let text) = components.last! { if text.characters.last! == "$" { components.removeLast() if text.characters.count > 1 { components.append(.Text(text.subString(toIndex: text.startIndex.advancedBy(text.characters.count - 2)))) } } } return components } } /// Route reversion public extension UnchainedResponseHandler { /// reverse a route with named parameters /// /// - parameter name: the name of the route URL to produce /// - parameter parameters: the parameters to substitute /// - parameter absolute: (optional) return relative path (from root, default) or absolute URL with hostname /// - returns: URL of route with parameters /// /// - throws: Throws errors if route could not be reversed public func reverseRoute(name: String, parameters:[String:String], absolute: Bool = false) throws -> String { guard let route = self.fetchRoute(name) else { throw Route.Error.NoRouteWithThatName(name: name) } var result = "" if absolute { result.appendContentsOf(self.request.config.externalServerURL) } // Build route string for item in route { switch item { case .NumberedPattern: throw Route.Error.MixedNumberedAndNamedParameters case .NamedPattern(let name): if let param = parameters[name] { result.appendContentsOf(param) } else { throw Route.Error.MissingParameterForRoute(name: name) } case .Text(let text): result.appendContentsOf(text) } } return result } /// reverse a route with numbered parameters /// /// - parameter name: the name of the route URL to produce /// - parameter parameters: the parameters to substitute /// - parameter absolute: (optional) return relative path (from root, default) or absolute URL with hostname /// - returns: URL of route with parameters /// /// - throws: Throws errors if route could not be reversed public func reverseRoute(name: String, parameters:[String], absolute: Bool = false) throws -> String { guard let route = self.fetchRoute(name) else { throw Route.Error.NoRouteWithThatName(name: name) } var result = "" if absolute { result.appendContentsOf(self.request.config.externalServerURL) } // Build route string for item in route { switch item { case .NumberedPattern(let num): if parameters.count > num - 1 { result.appendContentsOf(parameters[num - 1]) } else { throw Route.Error.WrongParameterCountForRoute } case .NamedPattern: throw Route.Error.MixedNumberedAndNamedParameters case .Text(let text): result.appendContentsOf(text) } } return result } /// reverse a route without parameters /// /// - parameter name: the name of the route URL to produce /// - parameter absolute: (optional) return relative path (from root, default) or absolute URL with hostname /// - returns: URL of route with parameters /// /// - throws: Throws errors if route could not be reversed public func reverseRoute(name: String, absolute: Bool = false) throws -> String { guard let route = self.fetchRoute(name) else { throw Route.Error.NoRouteWithThatName(name: name) } var result = "" if absolute { result.appendContentsOf(self.request.config.externalServerURL) } // Build route string for item in route { switch item { case .NumberedPattern: throw Route.Error.WrongParameterCountForRoute case .NamedPattern(let name): throw Route.Error.MissingParameterForRoute(name: name) case .Text(let text): result.appendContentsOf(text) } } return result } /// Fetch a route by name /// /// - parameter name: Name to search /// - returns: Route instance or nil if not found private func fetchRoute(name: String) -> [Route.RouteComponentType]? { for route in self.request.config.routes { if route.name == name { return route.splitIntoComponents() } } return nil } }
bsd-3-clause
6451e300d99497dc30943dc5fd38284d
32.608247
138
0.557362
5.158228
false
false
false
false
SuPair/firefox-ios
Client/Frontend/Browser/ScreenshotHelper.swift
16
2146
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation /** * Handles screenshots for a given tab, including pages with non-webview content. */ class ScreenshotHelper { var viewIsVisible = false fileprivate weak var controller: BrowserViewController? init(controller: BrowserViewController) { self.controller = controller } func takeScreenshot(_ tab: Tab) { var screenshot: UIImage? if let url = tab.url { if url.isAboutHomeURL { if let homePanel = controller?.homePanelController { screenshot = homePanel.view.screenshot(quality: UIConstants.ActiveScreenshotQuality) } } else { let offset = CGPoint(x: 0, y: -(tab.webView?.scrollView.contentInset.top ?? 0)) screenshot = tab.webView?.screenshot(offset: offset, quality: UIConstants.ActiveScreenshotQuality) } } tab.setScreenshot(screenshot) } /// Takes a screenshot after a small delay. /// Trying to take a screenshot immediately after didFinishNavigation results in a screenshot /// of the previous page, presumably due to an iOS bug. Adding a brief delay fixes this. func takeDelayedScreenshot(_ tab: Tab) { let time = DispatchTime.now() + Double(Int64(100 * NSEC_PER_MSEC)) / Double(NSEC_PER_SEC) DispatchQueue.main.asyncAfter(deadline: time) { // If the view controller isn't visible, the screenshot will be blank. // Wait until the view controller is visible again to take the screenshot. guard self.viewIsVisible else { tab.pendingScreenshot = true return } self.takeScreenshot(tab) } } func takePendingScreenshots(_ tabs: [Tab]) { for tab in tabs where tab.pendingScreenshot { tab.pendingScreenshot = false takeDelayedScreenshot(tab) } } }
mpl-2.0
bb032ea35c582abd5d42a721b4f924c4
35.372881
114
0.631873
4.877273
false
false
false
false
kzaher/RxSwift
RxExample/RxExample/Examples/UIPickerViewExample/CustomPickerViewAdapterExampleViewController.swift
2
2050
// // CustomPickerViewAdapterExampleViewController.swift // RxExample // // Created by Sergey Shulga on 12/07/2017. // Copyright © 2017 Krunoslav Zaher. All rights reserved. // import UIKit import RxSwift import RxCocoa final class CustomPickerViewAdapterExampleViewController: ViewController { @IBOutlet weak var pickerView: UIPickerView! override func viewDidLoad() { super.viewDidLoad() Observable.just([[1, 2, 3], [5, 8, 13], [21, 34]]) .bind(to: pickerView.rx.items(adapter: PickerViewViewAdapter())) .disposed(by: disposeBag) pickerView.rx.modelSelected(Int.self) .subscribe(onNext: { models in print(models) }) .disposed(by: disposeBag) } } final class PickerViewViewAdapter : NSObject , UIPickerViewDataSource , UIPickerViewDelegate , RxPickerViewDataSourceType , SectionedViewDataSourceType { typealias Element = [[CustomStringConvertible]] private var items: [[CustomStringConvertible]] = [] func model(at indexPath: IndexPath) throws -> Any { items[indexPath.section][indexPath.row] } func numberOfComponents(in pickerView: UIPickerView) -> Int { items.count } func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { items[component].count } func pickerView(_ pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusing view: UIView?) -> UIView { let label = UILabel() label.text = items[component][row].description label.textColor = UIColor.orange label.font = UIFont.preferredFont(forTextStyle: .headline) label.textAlignment = .center return label } func pickerView(_ pickerView: UIPickerView, observedEvent: Event<Element>) { Binder(self) { (adapter, items) in adapter.items = items pickerView.reloadAllComponents() }.on(observedEvent) } }
mit
72f525df8c956bda196ca33304ec7d2c
28.695652
132
0.652513
4.985401
false
false
false
false
cdmx/MiniMancera
miniMancera/View/Store/VStoreHeader.swift
1
4399
import UIKit class VStoreHeader:UICollectionReusableView { private weak var imageView:UIImageView! private weak var label:UILabel! private weak var layoutLabelHeight:NSLayoutConstraint! private let attrTitle:[String:Any] private let attrDescr:[String:Any] private let labelMargin2:CGFloat private let kImageHeight:CGFloat = 150 private let kLabelMargin:CGFloat = 10 private let kBorderHeight:CGFloat = 1 override init(frame:CGRect) { attrTitle = [ NSFontAttributeName:UIFont.bold(size:17), NSForegroundColorAttributeName:UIColor.white] attrDescr = [ NSFontAttributeName:UIFont.regular(size:14), NSForegroundColorAttributeName:UIColor.white] labelMargin2 = kLabelMargin + kLabelMargin super.init(frame:frame) clipsToBounds = true backgroundColor = UIColor.clear isUserInteractionEnabled = false let imageView:UIImageView = UIImageView() imageView.isUserInteractionEnabled = false imageView.contentMode = UIViewContentMode.center imageView.clipsToBounds = true imageView.translatesAutoresizingMaskIntoConstraints = false self.imageView = imageView let label:UILabel = UILabel() label.isUserInteractionEnabled = false label.backgroundColor = UIColor.clear label.translatesAutoresizingMaskIntoConstraints = false label.numberOfLines = 0 self.label = label let border:VBorder = VBorder(color:UIColor(white:1, alpha:0.3)) addSubview(label) addSubview(border) addSubview(imageView) NSLayoutConstraint.topToTop( view:imageView, toView:self) NSLayoutConstraint.height( view:imageView, constant:kImageHeight) NSLayoutConstraint.equalsHorizontal( view:imageView, toView:self) NSLayoutConstraint.topToBottom( view:label, toView:imageView) layoutLabelHeight = NSLayoutConstraint.height( view:label) NSLayoutConstraint.equalsHorizontal( view:label, toView:self, margin:kLabelMargin) NSLayoutConstraint.bottomToBottom( view:border, toView:self) NSLayoutConstraint.height( view:border, constant:kBorderHeight) NSLayoutConstraint.equalsHorizontal( view:border, toView:self) } required init?(coder:NSCoder) { return nil } override func layoutSubviews() { guard let attributedText:NSAttributedString = label.attributedText else { return } let width:CGFloat = bounds.maxX let height:CGFloat = bounds.maxY let usableWidth:CGFloat = width - labelMargin2 let usableSize:CGSize = CGSize(width:usableWidth, height:height) let boundingRect:CGRect = attributedText.boundingRect( with:usableSize, options:NSStringDrawingOptions([ NSStringDrawingOptions.usesLineFragmentOrigin, NSStringDrawingOptions.usesFontLeading]), context:nil) layoutLabelHeight.constant = ceil(boundingRect.size.height) super.layoutSubviews() } //MARK: public func config(model:MStoreItem) { imageView.image = model.option.thumbnail guard let title:String = model.option.title, let descr:String = model.option.descr else { label.attributedText = nil return } let mutableString:NSMutableAttributedString = NSMutableAttributedString() let stringTitle:NSAttributedString = NSAttributedString( string:title, attributes:attrTitle) let stringDescr:NSAttributedString = NSAttributedString( string:descr, attributes:attrDescr) mutableString.append(stringTitle) mutableString.append(stringDescr) label.attributedText = mutableString setNeedsLayout() } }
mit
9f8cd7c017964ca235b09c72b37a7f2e
29.337931
81
0.607183
6.126741
false
false
false
false
adelang/DoomKit
Sources/Texture.swift
1
3579
// // Texture.swift // DoomKit // // Created by Arjan de Lang on 04-01-15. // Copyright (c) 2015 Blue Depths Media. All rights reserved. // import Cocoa open class Texture { class PatchDescriptor { var patchName: String var xOffset: Int16 = 0 var yOffset: Int16 = 0 init(data: Data, dataOffset: inout Int, patchNames: [String]) { (data as NSData).getBytes(&xOffset, range: NSMakeRange(dataOffset, MemoryLayout<Int16>.size)) dataOffset += MemoryLayout<Int16>.size (data as NSData).getBytes(&yOffset, range: NSMakeRange(dataOffset, MemoryLayout<Int16>.size)) dataOffset += MemoryLayout<Int16>.size var patchNumber: Int16 = 0 (data as NSData).getBytes(&patchNumber, range: NSMakeRange(dataOffset, MemoryLayout<Int16>.size)) patchName = patchNames[Int(patchNumber)] dataOffset += MemoryLayout<Int16>.size // Ignore next two shorts dataOffset += 2 * MemoryLayout<Int16>.size } } var _name: String open var name: String { get { return _name } } var _width: Int16 = 0 open var width: Int16 { get { return _width } } var _height: Int16 = 0 open var height: Int16 { get { return _height } } var patchDescriptors = [PatchDescriptor]() var _cachedImage: NSImage? init(data: Data, dataOffset: inout Int, patchNames: [String]) { _name = String(data: data.subdata(in: (dataOffset ..< dataOffset + 8)), encoding: .ascii)!.trimmingCharacters(in: CharacterSet(charactersIn: "\0")) dataOffset += 8 // Ignore next two shorts dataOffset += 2 * MemoryLayout<Int16>.size (data as NSData).getBytes(&_width, range: NSMakeRange(dataOffset, MemoryLayout<Int16>.size)) dataOffset += MemoryLayout<Int16>.size (data as NSData).getBytes(&_height, range: NSMakeRange(dataOffset, MemoryLayout<Int16>.size)) dataOffset += MemoryLayout<Int16>.size // Ignore next two shorts dataOffset += 2 * MemoryLayout<Int16>.size var numberOfPatchDescriptors: Int16 = 0 (data as NSData).getBytes(&numberOfPatchDescriptors, range: NSMakeRange(dataOffset, MemoryLayout<Int16>.size)) dataOffset += MemoryLayout<Int16>.size for _ in (0 ..< Int(numberOfPatchDescriptors)) { let patchDescriptor = PatchDescriptor(data: data, dataOffset: &dataOffset, patchNames: patchNames) patchDescriptors.append(patchDescriptor) } } open func imageWithPalette(_ palette: Palette, usingPatchesFromWad wad: Wad) -> NSImage { if let image = _cachedImage { return image } let bitmap = NSBitmapImageRep(bitmapDataPlanes: nil, pixelsWide: Int(_width), pixelsHigh: Int(_height), bitsPerSample: 8, samplesPerPixel: 4, hasAlpha: true, isPlanar: false, colorSpaceName: NSCalibratedRGBColorSpace, bytesPerRow: Int(4 * width), bitsPerPixel: 32) NSGraphicsContext.setCurrent(NSGraphicsContext(bitmapImageRep: bitmap!)) // Flip coordinate system var transform = AffineTransform.identity transform.translate(x: 0, y: CGFloat(_height)) transform.scale(x: 1, y: -1) (transform as NSAffineTransform).concat() let image = NSImage() image.addRepresentation(bitmap!) for patchDescriptor in patchDescriptors { if let patchGraphic = Graphic.graphicWithLumpName(patchDescriptor.patchName, inWad: wad) { let patchImage = patchGraphic.imageWithPalette(palette) let patchBitmap = patchImage.representations.first as! NSBitmapImageRep patchBitmap.draw(at: NSMakePoint(CGFloat(patchDescriptor.xOffset), CGFloat(patchDescriptor.yOffset))) } else { print("Unable to find path with name '\(patchDescriptor.patchName)' for texture '\(_name)'") } } _cachedImage = image return image } }
mit
1f41f9f5c46407a6803fd07512913519
34.79
266
0.724225
3.795334
false
false
false
false
zakkhoyt/ColorPicKit
ColorPicKit/Classes/SpectrumView.swift
1
3860
// // SpectrumView.swift // ColorPicKitExample // // Created by Zakk Hoyt on 10/25/16. // Copyright © 2016 Zakk Hoyt. All rights reserved. // import UIKit class SpectrumView: UIView { // MARK: Variables private var _borderColor: UIColor = .lightGray @IBInspectable public var borderColor: UIColor{ get { return _borderColor } set { if _borderColor != newValue { _borderColor = newValue self.layer.borderColor = newValue.cgColor } } } private var _borderWidth: CGFloat = 0.5 @IBInspectable public var borderWidth: CGFloat{ get { return _borderWidth } set { if _borderWidth != newValue { _borderWidth = newValue self.layer.borderWidth = newValue } } } fileprivate var imageData: [GradientData] = [GradientData]() fileprivate var imageDataLength: Int = 0 fileprivate var radialImage: CGImage? = nil // MARK: Private methods override open func layoutSubviews() { super.layoutSubviews() updateGradient() } override open func draw(_ rect: CGRect) { guard let context = UIGraphicsGetCurrentContext() else { print("no context") return } context.saveGState() let borderFrame = bounds.insetBy(dx: -borderWidth / 2.0, dy: -borderWidth / 2.0) if borderWidth > 0 { context.setLineWidth(borderWidth) context.setStrokeColor(borderColor.cgColor) context.addRect(borderFrame) context.strokePath() } context.addRect(bounds) context.clip() if let radialImage = radialImage { // CGContextDrawImage(context, wheelFrame, radialImage) context.draw(radialImage, in: bounds) } context.restoreGState() } fileprivate func updateGradient() { if bounds.width == 0 || bounds.height == 0 { return } radialImage = nil let width = Int(bounds.width) let height = Int(bounds.height) let dataLength = MemoryLayout<GradientData>.size * width * height imageData.removeAll() self.imageDataLength = dataLength for y in 0 ..< height { for x in 0 ..< width { let point = CGPoint(x: CGFloat(x), y: CGFloat(y)) let rgb = rgbaFor(point: point) let gradientData = GradientData(red: UInt8(rgb.red * CGFloat(255)), green: UInt8(rgb.green * CGFloat(255)), blue: UInt8(rgb.blue * CGFloat(255))) imageData.append(gradientData) } } let bitmapInfo: CGBitmapInfo = [] let callback: CGDataProviderReleaseDataCallback = { _,_,_ in } if let dataProvider = CGDataProvider(dataInfo: nil, data: &imageData, size: dataLength, releaseData: callback) { let colorSpace = CGColorSpaceCreateDeviceRGB() let renderingIntent = CGColorRenderingIntent.defaultIntent radialImage = CGImage(width: width, height: height, bitsPerComponent: 8, bitsPerPixel: 24, bytesPerRow: width * 3, space: colorSpace, bitmapInfo: bitmapInfo, provider: dataProvider, decode: nil, shouldInterpolate: true, intent: renderingIntent) } setNeedsDisplay() } // MARK: Public methods func rgbaFor(point: CGPoint) -> RGBA { print("child class must implement") return UIColor.clear.rgba() } }
mit
c3d2e294464757cbf4e6d2c6208cac2d
29.148438
256
0.548069
5.293553
false
false
false
false
bigscreen/mangindo-ios
Mangindo/Modules/Contents/ContentsViewController.swift
1
2250
// // ContentsViewController.swift // Mangindo // // Created by Gallant Pratama on 8/30/17. // Copyright © 2017 Gallant Pratama. All rights reserved. // import UIKit import iCarousel class ContentsViewController: UIViewController { @IBOutlet weak var carousel: iCarousel! @IBOutlet weak var loadingIndicator: UIActivityIndicatorView! var pageTitle = "Manga Content" var presenter: IContentsPresenter! override func viewDidLoad() { super.viewDidLoad() self.navigationItem.title = presenter.getDisplayedNavTitle(pageTitle) carousel.delegate = self carousel.dataSource = self carousel.isPagingEnabled = true carousel.bounces = false carousel.isScrollEnabled = true presenter.fetchContents() } } extension ContentsViewController: IContentsView { func startLoading() { loadingIndicator.startAnimating() } func stopLoading() { loadingIndicator.stopAnimating() } func showData() { carousel.reloadData() } func showAlert(message: String) { let alert = UIAlertController(title: "Oops!", message: message, preferredStyle: UIAlertControllerStyle.alert) alert.addAction(UIAlertAction(title: "Back", style: UIAlertActionStyle.default, handler: { _ in if let navController = self.navigationController { navController.popViewController(animated: true) } })) alert.addAction(UIAlertAction(title: "Reload", style: UIAlertActionStyle.default, handler: { _ in self.presenter.fetchContents() })) self.present(alert, animated: true, completion: nil) } } extension ContentsViewController: iCarouselDelegate, iCarouselDataSource { func numberOfItems(in carousel: iCarousel) -> Int { return presenter.contents.count } func carousel(_ carousel: iCarousel, viewForItemAt index: Int, reusing view: UIView?) -> UIView { let pageView = ContentZoomableView(frame: CGRect(x: 0, y: 0, width: carousel.frame.width, height: carousel.frame.height)) pageView.imageUrl = presenter.contents[index].imageUrl return pageView } }
mit
32e2c636148f7fb1199656d2d70158c9
29.391892
129
0.666074
4.986696
false
false
false
false
wordpress-mobile/WordPress-iOS
WordPress/Classes/Models/BloggingPromptSettingsReminderDays+CoreDataClass.swift
1
1056
import Foundation import CoreData import WordPressKit public class BloggingPromptSettingsReminderDays: NSManagedObject { func configure(with remoteReminderDays: RemoteBloggingPromptsSettings.ReminderDays) { self.monday = remoteReminderDays.monday self.tuesday = remoteReminderDays.tuesday self.wednesday = remoteReminderDays.wednesday self.thursday = remoteReminderDays.thursday self.friday = remoteReminderDays.friday self.saturday = remoteReminderDays.saturday self.sunday = remoteReminderDays.sunday } func getActiveWeekdays() -> [BloggingRemindersScheduler.Weekday] { return [ sunday, monday, tuesday, wednesday, thursday, friday, saturday ].enumerated().compactMap { (index: Int, isReminderActive: Bool) in guard isReminderActive else { return nil } return BloggingRemindersScheduler.Weekday(rawValue: index) } } }
gpl-2.0
0956fc0e2e989b868b6c027a4044d595
30.058824
89
0.647727
5.834254
false
false
false
false
gffny/rgbycch
ios/coachapp/coachapp/coachapp/views/FieldView.swift
1
1798
// // FieldView.swift // coachapp // // Created by John D. Gaffney on 7/8/15. // Copyright (c) 2015 gffny.com. All rights reserved. // import UIKit @IBDesignable class FieldView: UIView { // Our custom view from the XIB file weak var view: UIView! @IBOutlet weak var actionLabel: UILabel! override init(frame: CGRect) { // 1. setup any properties here // 2. call super.init(frame:) super.init(frame: frame) // 3. Setup view from .xib file xibSetup() } required init(coder aDecoder: NSCoder) { // 1. setup any properties here // 2. call super.init(coder:) super.init(coder: aDecoder) // 3. Setup view from .xib file xibSetup() } func xibSetup() { view = loadViewFromNib() // use bounds not frame or it'll be offset view.frame = bounds // Make the view stretch with containing view view.autoresizingMask = UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleHeight renderKickOffDisplay() // Adding custom subview on top of our view (over any custom drawing > see note below) addSubview(view) } func loadViewFromNib() -> UIView { let bundle = NSBundle(forClass: self.dynamicType) let nib = UINib(nibName: "FieldRepresentation", bundle: bundle) // Assumes UIView is top level and only object in CustomView.xib file let view = nib.instantiateWithOwner(self, options: nil)[0] as UIView return view } func renderKickOffDisplay() { // hide any none used controls actionLabel.hidden = false actionLabel.text = "Tap for Kick Off" } func clearDisplay() { actionLabel.hidden = true } }
mit
22812f55ff302de739a740d996a44151
24.685714
100
0.615684
4.461538
false
false
false
false