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
jabez1314/ImagePickerSheetController
ImagePickerSheetController/ImagePickerSheetController/PreviewSupplementaryView.swift
6
2578
// // PreviewSupplementaryView.swift // ImagePickerSheet // // Created by Laurin Brandner on 06/09/14. // Copyright (c) 2014 Laurin Brandner. All rights reserved. // import UIKit class PreviewSupplementaryView : UICollectionReusableView { private let button: UIButton = { let button = UIButton() button.tintColor = .whiteColor() button.userInteractionEnabled = false button.setImage(PreviewSupplementaryView.checkmarkImage, forState: .Normal) button.setImage(PreviewSupplementaryView.selectedCheckmarkImage, forState: .Selected) return button }() var buttonInset = UIEdgeInsetsZero var selected: Bool = false { didSet { button.selected = selected reloadButtonBackgroundColor() } } class var checkmarkImage: UIImage? { let bundle = NSBundle(forClass: ImagePickerSheetController.self) let image = UIImage(named: "PreviewSupplementaryView-Checkmark", inBundle: bundle, compatibleWithTraitCollection: nil) return image?.imageWithRenderingMode(.AlwaysTemplate) } class var selectedCheckmarkImage: UIImage? { let bundle = NSBundle(forClass: ImagePickerSheetController.self) let image = UIImage(named: "PreviewSupplementaryView-Checkmark-Selected", inBundle: bundle, compatibleWithTraitCollection: nil) return image?.imageWithRenderingMode(.AlwaysTemplate) } // MARK: - Initialization override init(frame: CGRect) { super.init(frame: frame) initialize() } required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) initialize() } private func initialize() { addSubview(button) } // MARK: - Other Methods override func prepareForReuse() { super.prepareForReuse() selected = false } override func tintColorDidChange() { super.tintColorDidChange() reloadButtonBackgroundColor() } private func reloadButtonBackgroundColor() { button.backgroundColor = (selected) ? tintColor : nil } // MARK: - Layout override func layoutSubviews() { super.layoutSubviews() button.sizeToFit() button.frame.origin = CGPointMake(buttonInset.left, CGRectGetHeight(bounds)-CGRectGetHeight(button.frame)-buttonInset.bottom) button.layer.cornerRadius = CGRectGetHeight(button.frame) / 2.0 } }
mit
c8580f8b5d2cf474e05f2cb53a46e9af
27.021739
135
0.641195
5.508547
false
false
false
false
bykoianko/omim
iphone/Maps/Bookmarks/Categories/Sharing/Tags/TagCollectionViewCell.swift
1
676
final class TagCollectionViewCell: UICollectionViewCell { @IBOutlet private weak var title: UILabel! @IBOutlet weak var containerView: UIView! var color: UIColor? { didSet { title.textColor = color containerView.layer.borderColor = color?.cgColor } } override var isSelected: Bool{ didSet { containerView.backgroundColor = isSelected ? color : .white() title.textColor = isSelected ? .whitePrimaryText() : color } } func update(with tag: MWMTag) { title.text = tag.name color = tag.color } override func prepareForReuse() { super.prepareForReuse() title.text = nil color = nil } }
apache-2.0
6ea6b6ffc084ea42102445c67a42daf3
21.533333
67
0.655325
4.567568
false
false
false
false
ReactiveX/RxSwift
RxCocoa/iOS/UIBarButtonItem+Rx.swift
6
1817
// // UIBarButtonItem+Rx.swift // RxCocoa // // Created by Daniel Tartaglia on 5/31/15. // Copyright ยฉ 2015 Krunoslav Zaher. All rights reserved. // #if os(iOS) || os(tvOS) import UIKit import RxSwift private var rx_tap_key: UInt8 = 0 extension Reactive where Base: UIBarButtonItem { /// Reactive wrapper for target action pattern on `self`. public var tap: ControlEvent<()> { let source = lazyInstanceObservable(&rx_tap_key) { () -> Observable<()> in Observable.create { [weak control = self.base] observer in guard let control = control else { observer.on(.completed) return Disposables.create() } let target = BarButtonItemTarget(barButtonItem: control) { observer.on(.next(())) } return target } .take(until: self.deallocated) .share() } return ControlEvent(events: source) } } @objc final class BarButtonItemTarget: RxTarget { typealias Callback = () -> Void weak var barButtonItem: UIBarButtonItem? var callback: Callback! init(barButtonItem: UIBarButtonItem, callback: @escaping () -> Void) { self.barButtonItem = barButtonItem self.callback = callback super.init() barButtonItem.target = self barButtonItem.action = #selector(BarButtonItemTarget.action(_:)) } override func dispose() { super.dispose() #if DEBUG MainScheduler.ensureRunningOnMainThread() #endif barButtonItem?.target = nil barButtonItem?.action = nil callback = nil } @objc func action(_ sender: AnyObject) { callback() } } #endif
mit
0d7e8694d6b6ae3b0f7de059fc18bb44
24.222222
82
0.578194
4.88172
false
false
false
false
leizh007/HiPDA
HiPDA/HiPDA/Sections/Search/SearchTitleTableViewCell.swift
1
2202
// // SearchTitleTableViewCell.swift // HiPDA // // Created by leizh007 on 2017/7/5. // Copyright ยฉ 2017ๅนด HiPDA. All rights reserved. // import Foundation import SDWebImage class SearchTitleTableViewCell: UITableViewCell { @IBOutlet fileprivate weak var avatarImageView: UIImageView! @IBOutlet fileprivate weak var usernameLabel: UILabel! @IBOutlet fileprivate weak var forumNameLabel: UILabel! @IBOutlet fileprivate weak var titleLabel: UILabel! @IBOutlet fileprivate weak var timeLabel: UILabel! @IBOutlet fileprivate weak var readCountLabel: UILabel! @IBOutlet fileprivate weak var replyCountLabel: UILabel! override func awakeFromNib() { super.awakeFromNib() titleLabel.preferredMaxLayoutWidth = C.UI.screenWidth - 16.0 } var model: SearchTitleModelForUI! { didSet { let url = model.user.avatarImageURL.absoluteString avatarImageView.sd_setImage(with: model.user.avatarImageURL, placeholderImage: Avatar.placeholder, options: [.avoidAutoSetImage]) { [weak self] (image, _, _, _) in guard let `self` = self, let image = image else { return } DispatchQueue.global().async { let corneredImage = image.image(roundCornerRadius: Avatar.cornerRadius, borderWidth: 1.0 / C.UI.screenScale, borderColor: .lightGray, size: CGSize(width: Avatar.width, height: Avatar.height)) DispatchQueue.main.async { guard url == self.model.user.avatarImageURL.absoluteString else { return } self.avatarImageView.image = corneredImage } } } usernameLabel.text = model.user.name forumNameLabel.text = model.forumName titleLabel.attributedText = model.title timeLabel.text = "ๅ‘่กจๆ—ถ้—ด: \(model.time)" readCountLabel.text = "ๆŸฅ็œ‹: \(model.readCount)" replyCountLabel.text = "ๅ›žๅค: \(model.replyCount)" } } override func prepareForReuse() { super.prepareForReuse() avatarImageView.sd_cancelCurrentImageLoad() } }
mit
cc60314297624ad40a5cc677040f4d1a
39.425926
211
0.641319
4.961364
false
false
false
false
kousun12/RxSwift
RxTests/Tests/PerformanceTools.swift
4
5413
// // PerformanceTools.swift // RxTests // // Created by Krunoslav Zaher on 9/27/15. // // import Foundation var mallocFunctions: [(@convention(c) (UnsafeMutablePointer<_malloc_zone_t>, Int) -> UnsafeMutablePointer<Void>)] = [] var allocCalls: Int64 = 0 var bytesAllocated: Int64 = 0 func call0(p: UnsafeMutablePointer<_malloc_zone_t>, size: Int) -> UnsafeMutablePointer<Void> { OSAtomicIncrement64(&allocCalls) OSAtomicAdd64(Int64(size), &bytesAllocated) #if ALLOC_HOOK allocation() #endif return mallocFunctions[0](p, size) } func call1(p: UnsafeMutablePointer<_malloc_zone_t>, size: Int) -> UnsafeMutablePointer<Void> { OSAtomicIncrement64(&allocCalls) OSAtomicAdd64(Int64(size), &bytesAllocated) #if ALLOC_HOOK allocation() #endif return mallocFunctions[1](p, size) } func call2(p: UnsafeMutablePointer<_malloc_zone_t>, size: Int) -> UnsafeMutablePointer<Void> { OSAtomicIncrement64(&allocCalls) OSAtomicAdd64(Int64(size), &bytesAllocated) #if ALLOC_HOOK allocation() #endif return mallocFunctions[2](p, size) } var proxies: [(@convention(c) (UnsafeMutablePointer<_malloc_zone_t>, Int) -> UnsafeMutablePointer<Void>)] = [call0, call1, call2] func getMemoryInfo() -> (bytes: Int64, allocations: Int64) { return (bytesAllocated, allocCalls) } var registeredMallocHooks = false func registerMallocHooks() { if registeredMallocHooks { return } registeredMallocHooks = true var _zones: UnsafeMutablePointer<vm_address_t> = UnsafeMutablePointer(nil) var count: UInt32 = 0 // malloc_zone_print(nil, 1) let res = malloc_get_all_zones(mach_task_self_, nil, &_zones, &count) assert(res == 0) let zones = UnsafeMutablePointer<UnsafeMutablePointer<malloc_zone_t>>(_zones) assert(Int(count) <= proxies.count) for i in 0 ..< Int(count) { let zoneArray = zones.advancedBy(i) let name = malloc_get_zone_name(zoneArray.memory) var zone = zoneArray.memory.memory //print(String.fromCString(name)) assert(name != nil) mallocFunctions.append(zone.malloc) zone.malloc = proxies[i] let protectSize = vm_size_t(sizeof(malloc_zone_t)) * vm_size_t(count) if true { let addressPointer = UnsafeMutablePointer<vm_address_t>(zoneArray) let res = vm_protect(mach_task_self_, addressPointer.memory, protectSize, 0, PROT_READ | PROT_WRITE) assert(res == 0) } zoneArray.memory.memory = zone if true { let res = vm_protect(mach_task_self_, _zones.memory, protectSize, 0, PROT_READ) assert(res == 0) } } } // MARK: Benchmark tools let NumberOfIterations = 10000 class A { let _0 = 0 let _1 = 0 let _2 = 0 let _3 = 0 let _4 = 0 let _5 = 0 let _6 = 0 } class B { var a = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29] } let numberOfObjects = 1000000 let aliveAtTheEnd = numberOfObjects / 10 var objects: [AnyObject] = [] func fragmentMemory() { objects = [AnyObject](count: aliveAtTheEnd, repeatedValue: A()) for _ in 0 ..< numberOfObjects { objects[Int(arc4random_uniform(UInt32(aliveAtTheEnd)))] = arc4random_uniform(2) == 0 ? A() : B() } } func approxValuePerIteration(total: Int) -> UInt64 { return UInt64(round(Double(total) / Double(NumberOfIterations))) } func approxValuePerIteration(total: UInt64) -> UInt64 { return UInt64(round(Double(total) / Double(NumberOfIterations))) } func measureTime(@noescape work: () -> ()) -> UInt64 { var timebaseInfo: mach_timebase_info = mach_timebase_info() let res = mach_timebase_info(&timebaseInfo) assert(res == 0) let start = mach_absolute_time() for _ in 0 ..< NumberOfIterations { work() } let timeInNano = (mach_absolute_time() - start) * UInt64(timebaseInfo.numer) / UInt64(timebaseInfo.denom) return approxValuePerIteration(timeInNano) / 1000 } func measureMemoryUsage(@noescape work: () -> ()) -> (bytesAllocated: UInt64, allocations: UInt64) { let (bytes, allocations) = getMemoryInfo() for _ in 0 ..< NumberOfIterations { work() } let (bytesAfter, allocationsAfter) = getMemoryInfo() return (approxValuePerIteration(bytesAfter - bytes), approxValuePerIteration(allocationsAfter - allocations)) } func compareTwoImplementations(benchmarkTime benchmarkTime: Bool, @noescape first: () -> (), @noescape second: () -> ()) { print("Fragmenting memory ...") fragmentMemory() print("Benchmarking ...") // first warm up to keep it fair let time1: UInt64 let time2: UInt64 if benchmarkTime { first() second() time1 = measureTime(first) time2 = measureTime(second) } else { time1 = 0 time2 = 0 } registerMallocHooks() first() second() let memory1 = measureMemoryUsage(first) let memory2 = measureMemoryUsage(second) // this is good enough print(String(format: "#1 implementation %8d bytes %4d allocations %5d useconds", arguments: [ memory1.bytesAllocated, memory1.allocations, time1 ])) print(String(format: "#2 implementation %8d bytes %4d allocations %5d useconds", arguments: [ memory2.bytesAllocated, memory2.allocations, time2 ])) }
mit
56a94210a6dffce5ba3964d8c1d219f7
25.930348
129
0.652503
3.67232
false
false
false
false
cocoaheadsru/server
Sources/App/Controllers/Event/Registration/RegistrationController.swift
1
2218
import HTTP import Vapor import Fluent final class RegistrationController { let autoapprove = try? AutoapproveController() let drop: Droplet init(drop: Droplet) { self.drop = drop } func store(_ request: Request) throws -> ResponseRepresentable { let user = try request.user() guard let userId = user.id else { throw Abort(.internalServerError, reason: "Can't get user.id") } guard let json = request.json, let regFormIdInt = json[Keys.regFormId]?.int else { throw Abort(.internalServerError, reason: "Can't get 'reg_form_Id' from request") } let regFormId = Identifier(.int(regFormIdInt)) guard try EventReg.duplicationCheck(regFormId: regFormId, userId: userId) else { throw Abort( .internalServerError, reason: "User with token '\(user.token ?? "")' has alredy registered to this event") } guard let event = try RegForm.find(regFormId)?.event, let grandApprove = try autoapprove?.grandApprove(to: user, on: event) else { throw Abort(.internalServerError, reason: "Can't check autoapprove status") } let eventReg = EventReg( regFormId: regFormId, userId: userId, status: grandApprove ? EventReg.RegistrationStatus.approved : EventReg.RegistrationStatus.waiting) try drop.mysql().transaction { (connection) in try eventReg.makeQuery(connection).save() try storeEventRegAnswers(request, eventReg: eventReg, connection: connection) } return eventReg } func cancel(_ request: Request, eventReg: EventReg) throws -> ResponseRepresentable { let user = try request.user() guard let userId = user.id, eventReg.status == EventReg.RegistrationStatus.approved, eventReg.userId == userId else { throw Abort(.internalServerError, reason: "Can't find approved User's registraion for cancel") } try eventReg.delete() return try Response( .ok, message: "Registration is canceled") } } extension RegistrationController: ResourceRepresentable { func makeResource() -> Resource<EventReg> { return Resource( store: store, destroy: cancel ) } }
mit
533f48c4b906cefdddd5dd9cffec15cd
26.04878
104
0.669973
4.323587
false
false
false
false
evgenyneu/walk-to-circle-ios
walk to circle/Screens/Map/YiiButtons.swift
1
2019
import UIKit class YiiButtons: NSObject { @IBOutlet weak var startButton: UIButton! @IBOutlet weak var rewindButton: RewindButton! weak var delegate: YiiButtonsDelegate? private var lastTapped = NSDate().dateByAddingTimeInterval(NSTimeInterval(-100)) @IBAction func onStartTapped(sender: AnyObject) { if !canTap { return } tapped() start() } @IBAction func onRewindTapped(sender: AnyObject) { if !canTap { return } tapped() rewind() } func viewDidLoad() { YiiButtons.initButton(startButton) YiiButtons.initButton(rewindButton) } private class func initButton(button: UIButton) { button.backgroundColor = nil button.setTitle("", forState: UIControlState.Normal) button.hidden = true } func showStartButton() { if !startButton.hidden { return } startButton.hidden = false iiSounds.shared.play(iiSoundType.blop, atVolume: 0.2) iiAnimator.bounce(startButton) } private func showRewindButton() { if !rewindButton.hidden { return } rewindButton.hidden = false } private func disableButtonsInteraction() { startButton.userInteractionEnabled = false rewindButton.userInteractionEnabled = false } private func rewind() { delegate?.yiiButtonsDelegate_start() iiAnimator.rotate3d360(rewindButton) } private func start() { delegate?.yiiButtonsDelegate_start() showRewindButton() // Rotate start button startButton.layer.zPosition = 1000 iiAnimator.rotate3dOut(startButton) iiAnimator.fadeOut(startButton, duration: 0.1) // Rotate rewind button rewindButton.layer.zPosition = 999 iiAnimator.rotate3dIn(rewindButton) iiAnimator.fadeIn(rewindButton, duration: 0.1) } // We can not allow to tap very fast, as it may not save current coordinate private var canTap: Bool { let intervalSinceLastTap = NSDate().timeIntervalSinceDate(lastTapped) return intervalSinceLastTap > 0.2 } private func tapped() { lastTapped = NSDate() } }
mit
9c05288e59bcd116f2b77154c32eee67
23.621951
82
0.712729
4.232704
false
false
false
false
Snail93/iOSDemos
SnailSwiftDemos/Pods/ObjectMapper/Sources/ImmutableMappable.swift
7
13984
// // ImmutableMappble.swift // ObjectMapper // // Created by Suyeol Jeon on 23/09/2016. // // The MIT License (MIT) // // Copyright (c) 2014-2016 Hearst // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. public protocol ImmutableMappable: BaseMappable { init(map: Map) throws } public extension ImmutableMappable { /// Implement this method to support object -> JSON transform. public func mapping(map: Map) {} /// Initializes object from a JSON String public init(JSONString: String, context: MapContext? = nil) throws { self = try Mapper(context: context).map(JSONString: JSONString) } /// Initializes object from a JSON Dictionary public init(JSON: [String: Any], context: MapContext? = nil) throws { self = try Mapper(context: context).map(JSON: JSON) } /// Initializes object from a JSONObject public init(JSONObject: Any, context: MapContext? = nil) throws { self = try Mapper(context: context).map(JSONObject: JSONObject) } } public extension Map { fileprivate func currentValue(for key: String, nested: Bool? = nil, delimiter: String = ".") -> Any? { let isNested = nested ?? key.contains(delimiter) return self[key, nested: isNested, delimiter: delimiter].currentValue } // MARK: Basic /// Returns a value or throws an error. public func value<T>(_ key: String, nested: Bool? = nil, delimiter: String = ".", file: StaticString = #file, function: StaticString = #function, line: UInt = #line) throws -> T { let currentValue = self.currentValue(for: key, nested: nested, delimiter: delimiter) guard let value = currentValue as? T else { throw MapError(key: key, currentValue: currentValue, reason: "Cannot cast to '\(T.self)'", file: file, function: function, line: line) } return value } /// Returns a transformed value or throws an error. public func value<Transform: TransformType>(_ key: String, nested: Bool? = nil, delimiter: String = ".", using transform: Transform, file: StaticString = #file, function: StaticString = #function, line: UInt = #line) throws -> Transform.Object { let currentValue = self.currentValue(for: key, nested: nested, delimiter: delimiter) guard let value = transform.transformFromJSON(currentValue) else { throw MapError(key: key, currentValue: currentValue, reason: "Cannot transform to '\(Transform.Object.self)' using \(transform)", file: file, function: function, line: line) } return value } /// Returns a RawRepresentable type or throws an error. public func value<T: RawRepresentable>(_ key: String, nested: Bool? = nil, delimiter: String = ".", file: StaticString = #file, function: StaticString = #function, line: UInt = #line) throws -> T { return try self.value(key, nested: nested, delimiter: delimiter, using: EnumTransform(), file: file, function: function, line: line) } /// Returns a `[RawRepresentable]` type or throws an error. public func value<T: RawRepresentable>(_ key: String, nested: Bool? = nil, delimiter: String = ".", file: StaticString = #file, function: StaticString = #function, line: UInt = #line) throws -> [T] { return try self.value(key, nested: nested, delimiter: delimiter, using: EnumTransform(), file: file, function: function, line: line) } // MARK: BaseMappable /// Returns a `BaseMappable` object or throws an error. public func value<T: BaseMappable>(_ key: String, nested: Bool? = nil, delimiter: String = ".", file: StaticString = #file, function: StaticString = #function, line: UInt = #line) throws -> T { let currentValue = self.currentValue(for: key, nested: nested, delimiter: delimiter) guard let JSONObject = currentValue else { throw MapError(key: key, currentValue: currentValue, reason: "Found unexpected nil value", file: file, function: function, line: line) } return try Mapper<T>(context: context).mapOrFail(JSONObject: JSONObject) } // MARK: [BaseMappable] /// Returns a `[BaseMappable]` or throws an error. public func value<T: BaseMappable>(_ key: String, nested: Bool? = nil, delimiter: String = ".", file: StaticString = #file, function: StaticString = #function, line: UInt = #line) throws -> [T] { let currentValue = self.currentValue(for: key, nested: nested, delimiter: delimiter) guard let jsonArray = currentValue as? [Any] else { throw MapError(key: key, currentValue: currentValue, reason: "Cannot cast to '[Any]'", file: file, function: function, line: line) } return try jsonArray.enumerated().map { i, JSONObject -> T in return try Mapper<T>(context: context).mapOrFail(JSONObject: JSONObject) } } /// Returns a `[BaseMappable]` using transform or throws an error. public func value<Transform: TransformType>(_ key: String, nested: Bool? = nil, delimiter: String = ".", using transform: Transform, file: StaticString = #file, function: StaticString = #function, line: UInt = #line) throws -> [Transform.Object] { let currentValue = self.currentValue(for: key, nested: nested, delimiter: delimiter) guard let jsonArray = currentValue as? [Any] else { throw MapError(key: key, currentValue: currentValue, reason: "Cannot cast to '[Any]'", file: file, function: function, line: line) } return try jsonArray.enumerated().map { i, json -> Transform.Object in guard let object = transform.transformFromJSON(json) else { throw MapError(key: "\(key)[\(i)]", currentValue: json, reason: "Cannot transform to '\(Transform.Object.self)' using \(transform)", file: file, function: function, line: line) } return object } } // MARK: [String: BaseMappable] /// Returns a `[String: BaseMappable]` or throws an error. public func value<T: BaseMappable>(_ key: String, nested: Bool? = nil, delimiter: String = ".", file: StaticString = #file, function: StaticString = #function, line: UInt = #line) throws -> [String: T] { let currentValue = self.currentValue(for: key, nested: nested, delimiter: delimiter) guard let jsonDictionary = currentValue as? [String: Any] else { throw MapError(key: key, currentValue: currentValue, reason: "Cannot cast to '[String: Any]'", file: file, function: function, line: line) } var value: [String: T] = [:] for (key, json) in jsonDictionary { value[key] = try Mapper<T>(context: context).mapOrFail(JSONObject: json) } return value } /// Returns a `[String: BaseMappable]` using transform or throws an error. public func value<Transform: TransformType>(_ key: String, nested: Bool? = nil, delimiter: String = ".", using transform: Transform, file: StaticString = #file, function: StaticString = #function, line: UInt = #line) throws -> [String: Transform.Object] { let currentValue = self.currentValue(for: key, nested: nested, delimiter: delimiter) guard let jsonDictionary = currentValue as? [String: Any] else { throw MapError(key: key, currentValue: currentValue, reason: "Cannot cast to '[String: Any]'", file: file, function: function, line: line) } var value: [String: Transform.Object] = [:] for (key, json) in jsonDictionary { guard let object = transform.transformFromJSON(json) else { throw MapError(key: key, currentValue: json, reason: "Cannot transform to '\(Transform.Object.self)' using \(transform)", file: file, function: function, line: line) } value[key] = object } return value } // MARK: [[BaseMappable]] /// Returns a `[[BaseMappable]]` or throws an error. public func value<T: BaseMappable>(_ key: String, nested: Bool? = nil, delimiter: String = ".", file: StaticString = #file, function: StaticString = #function, line: UInt = #line) throws -> [[T]] { let currentValue = self.currentValue(for: key, nested: nested, delimiter: delimiter) guard let json2DArray = currentValue as? [[Any]] else { throw MapError(key: key, currentValue: currentValue, reason: "Cannot cast to '[[Any]]'", file: file, function: function, line: line) } return try json2DArray.map { jsonArray in try jsonArray.map { jsonObject -> T in return try Mapper<T>(context: context).mapOrFail(JSONObject: jsonObject) } } } /// Returns a `[[BaseMappable]]` using transform or throws an error. public func value<Transform: TransformType>(_ key: String, nested: Bool? = nil, delimiter: String = ".", using transform: Transform, file: StaticString = #file, function: StaticString = #function, line: UInt = #line) throws -> [[Transform.Object]] { let currentValue = self.currentValue(for: key, nested: nested, delimiter: delimiter) guard let json2DArray = currentValue as? [[Any]] else { throw MapError(key: key, currentValue: currentValue, reason: "Cannot cast to '[[Any]]'", file: file, function: function, line: line) } return try json2DArray.enumerated().map { i, jsonArray in try jsonArray.enumerated().map { j, json -> Transform.Object in guard let object = transform.transformFromJSON(json) else { throw MapError(key: "\(key)[\(i)][\(j)]", currentValue: json, reason: "Cannot transform to '\(Transform.Object.self)' using \(transform)", file: file, function: function, line: line) } return object } } } } public extension Mapper where N: ImmutableMappable { public func map(JSON: [String: Any]) throws -> N { return try self.mapOrFail(JSON: JSON) } public func map(JSONString: String) throws -> N { return try mapOrFail(JSONString: JSONString) } public func map(JSONObject: Any) throws -> N { return try mapOrFail(JSONObject: JSONObject) } // MARK: Array mapping functions public func mapArray(JSONArray: [[String: Any]]) throws -> [N] { return try JSONArray.flatMap(mapOrFail) } public func mapArray(JSONString: String) throws -> [N] { guard let JSONObject = Mapper.parseJSONString(JSONString: JSONString) else { throw MapError(key: nil, currentValue: JSONString, reason: "Cannot convert string into Any'") } return try mapArray(JSONObject: JSONObject) } public func mapArray(JSONObject: Any) throws -> [N] { guard let JSONArray = JSONObject as? [[String: Any]] else { throw MapError(key: nil, currentValue: JSONObject, reason: "Cannot cast to '[[String: Any]]'") } return try mapArray(JSONArray: JSONArray) } // MARK: Dictionary mapping functions public func mapDictionary(JSONString: String) throws -> [String: N] { guard let JSONObject = Mapper.parseJSONString(JSONString: JSONString) else { throw MapError(key: nil, currentValue: JSONString, reason: "Cannot convert string into Any'") } return try mapDictionary(JSONObject: JSONObject) } public func mapDictionary(JSONObject: Any?) throws -> [String: N] { guard let JSON = JSONObject as? [String: [String: Any]] else { throw MapError(key: nil, currentValue: JSONObject, reason: "Cannot cast to '[String: [String: Any]]''") } return try mapDictionary(JSON: JSON) } public func mapDictionary(JSON: [String: [String: Any]]) throws -> [String: N] { return try JSON.filterMap(mapOrFail) } // MARK: Dictinoary of arrays mapping functions public func mapDictionaryOfArrays(JSONObject: Any?) throws -> [String: [N]] { guard let JSON = JSONObject as? [String: [[String: Any]]] else { throw MapError(key: nil, currentValue: JSONObject, reason: "Cannot cast to '[String: [String: Any]]''") } return try mapDictionaryOfArrays(JSON: JSON) } public func mapDictionaryOfArrays(JSON: [String: [[String: Any]]]) throws -> [String: [N]] { return try JSON.filterMap { array -> [N] in try mapArray(JSONArray: array) } } // MARK: 2 dimentional array mapping functions public func mapArrayOfArrays(JSONObject: Any?) throws -> [[N]] { guard let JSONArray = JSONObject as? [[[String: Any]]] else { throw MapError(key: nil, currentValue: JSONObject, reason: "Cannot cast to '[[[String: Any]]]''") } return try JSONArray.map(mapArray) } } internal extension Mapper { internal func mapOrFail(JSON: [String: Any]) throws -> N { let map = Map(mappingType: .fromJSON, JSON: JSON, context: context, shouldIncludeNilValues: shouldIncludeNilValues) // Check if object is ImmutableMappable, if so use ImmutableMappable protocol for mapping if let klass = N.self as? ImmutableMappable.Type, var object = try klass.init(map: map) as? N { object.mapping(map: map) return object } // If not, map the object the standard way guard let value = self.map(JSON: JSON) else { throw MapError(key: nil, currentValue: JSON, reason: "Cannot map to '\(N.self)'") } return value } internal func mapOrFail(JSONString: String) throws -> N { guard let JSON = Mapper.parseJSONStringIntoDictionary(JSONString: JSONString) else { throw MapError(key: nil, currentValue: JSONString, reason: "Cannot parse into '[String: Any]'") } return try mapOrFail(JSON: JSON) } internal func mapOrFail(JSONObject: Any) throws -> N { guard let JSON = JSONObject as? [String: Any] else { throw MapError(key: nil, currentValue: JSONObject, reason: "Cannot cast to '[String: Any]'") } return try mapOrFail(JSON: JSON) } }
apache-2.0
330c6269362bcb7a603d0d2266ef385a
43.393651
256
0.704233
3.813472
false
false
false
false
criticalmaps/criticalmaps-ios
CriticalMapsKit/Sources/NextRideFeature/CriticalMassAnnotationView.swift
2
2238
import L10n import MapKit import Styleguide /// Map annotation view that displays the CM logo and offers a menu on long press. public final class CMMarkerAnnotationView: MKMarkerAnnotationView { public typealias EventClosure = () -> Void public var shareEventClosure: EventClosure? public var routeEventClosure: EventClosure? override public func prepareForDisplay() { super.prepareForDisplay() commonInit() } private func commonInit() { animatesWhenAdded = true markerTintColor = .backgroundPrimary glyphImage = Asset.cmLogoM.image glyphTintColor = .textPrimary canShowCallout = false isAccessibilityElement = false let interaction = UIContextMenuInteraction(delegate: self) addInteraction(interaction) } } extension CMMarkerAnnotationView: UIContextMenuInteractionDelegate { public func contextMenuInteraction( _: UIContextMenuInteraction, configurationForMenuAtLocation _: CGPoint ) -> UIContextMenuConfiguration? { UIContextMenuConfiguration( identifier: nil, previewProvider: { MapSnapshotViewController() }, actionProvider: { _ in self.makeContextMenu() } ) } private func makeContextMenu() -> UIMenu { let share = UIAction( title: L10n.Map.Menu.share, image: UIImage(systemName: "square.and.arrow.up") ) { _ in self.shareEventClosure?() } let route = UIAction( title: L10n.Map.Menu.route, image: UIImage(systemName: "arrow.turn.up.right") ) { _ in self.routeEventClosure?() } return UIMenu( title: L10n.Map.Menu.title, children: [share, route] ) } class MapSnapshotViewController: UIViewController { private let imageView = UIImageView() override func loadView() { view = imageView } init() { super.init(nibName: nil, bundle: nil) imageView.backgroundColor = .clear imageView.clipsToBounds = true imageView.contentMode = .scaleAspectFit imageView.image = Asset.cmLogoC.image preferredContentSize = CGSize(width: 200, height: 150) } @available(*, unavailable) required init?(coder _: NSCoder) { fatalError("init(coder:) has not been implemented") } } }
mit
0fa5964d7eeaf6562141bb0bbd186e73
27.692308
82
0.690349
4.63354
false
false
false
false
SKrotkih/YTLiveStreaming
YTLiveStreaming/LiveStreamingAPI.swift
1
6070
// // LiveStreamingAPI.swift // YTLiveStreaming // // Created by Serhii Krotkykh on 10/28/16. // Copyright ยฉ 2016 Serhii Krotkykh. All rights reserved. // import Foundation import Moya private func JSONResponseDataFormatter(_ data: Data) -> Data { do { let dataAsJSON = try JSONSerialization.jsonObject(with: data, options: []) let prettyData = try JSONSerialization.data(withJSONObject: dataAsJSON, options: .prettyPrinted) return prettyData } catch { return data // fallback to original data if it cant be serialized } } let requestClosure = { (endpoint: Moya.Endpoint, done: @escaping MoyaProvider<LiveStreamingAPI>.RequestResultClosure) in GoogleOAuth2.sharedInstance.requestToken { token in if let token = token { do { var request = try endpoint.urlRequest() as URLRequest request.addValue("Bearer \(token)", forHTTPHeaderField: "Authorization") request.addValue("application/json", forHTTPHeaderField: "Accept") request.addValue(Bundle.main.bundleIdentifier!, forHTTPHeaderField: "X-Ios-Bundle-Identifier") done(.success(request)) } catch { var nserror: NSError! = NSError( domain: "LiveStreamingAPIHttp", code: 4000, userInfo: ["NSLocalizedDescriptionKey": "Failed Google OAuth2 request token"] ) let error = MoyaError.underlying(nserror, nil) done(.failure(error)) } } else { var nserror: NSError! = NSError( domain: "LiveStreamingAPIHttp", code: 4000, userInfo: ["NSLocalizedDescriptionKey": "Failed Google OAuth2 request token"] ) let error = MoyaError.underlying(nserror, nil) done(.failure(error)) } } } let youTubeLiveVideoProvider = MoyaProvider<LiveStreamingAPI>( requestClosure: requestClosure, plugins: [NetworkLoggerPlugin()] ) enum LiveStreamingAPI { case listBroadcasts([String: AnyObject]) case liveBroadcast([String: AnyObject]) case transitionLiveBroadcast([String: AnyObject]) case deleteLiveBroadcast([String: AnyObject]) case bindLiveBroadcast([String: AnyObject]) case liveStream([String: AnyObject]) case deleteLiveStream([String: AnyObject]) } extension LiveStreamingAPI: TargetType { public var baseURL: URL { return URL(string: LiveAPI.BaseURL)! } public var path: String { switch self { case .listBroadcasts: return "/liveBroadcasts" case .liveBroadcast: return "/liveBroadcasts" case .transitionLiveBroadcast: return "/liveBroadcasts/transition" case .deleteLiveBroadcast: return "/liveBroadcasts" case .bindLiveBroadcast: return "/liveBroadcasts/bind" case .liveStream: return "/liveStreams" case .deleteLiveStream: return "/liveStreams" } } public var method: Moya.Method { switch self { case .listBroadcasts: return .get case .liveBroadcast: return .get case .transitionLiveBroadcast: return .post case .deleteLiveBroadcast: return .delete case .bindLiveBroadcast: return .post case .liveStream: return .get case .deleteLiveStream: return .delete } } public var task: Task { switch self { case .listBroadcasts(let parameters): return .requestParameters(parameters: parameters, encoding: URLEncoding.queryString) case .liveBroadcast(let parameters): return .requestParameters(parameters: parameters, encoding: URLEncoding.queryString) case .transitionLiveBroadcast(let parameters): return .requestParameters(parameters: parameters, encoding: URLEncoding.queryString) case .deleteLiveBroadcast(let parameters): return .requestParameters(parameters: parameters, encoding: URLEncoding.queryString) case .bindLiveBroadcast(let parameters): return .requestParameters(parameters: parameters, encoding: URLEncoding.queryString) case .liveStream(let parameters): return .requestParameters(parameters: parameters, encoding: URLEncoding.queryString) case .deleteLiveStream(let parameters): return .requestParameters(parameters: parameters, encoding: URLEncoding.queryString) } } public var parameters: [String: Any]? { switch self { case .listBroadcasts(let parameters): return parameters case .liveBroadcast(let parameters): return parameters case .transitionLiveBroadcast(let parameters): return parameters case .deleteLiveBroadcast(let parameters): return parameters case .bindLiveBroadcast(let parameters): return parameters case .liveStream(let parameters): return parameters case .deleteLiveStream(let parameters): return parameters } } public var sampleData: Data { switch self { case .listBroadcasts: return Data() case .liveBroadcast: return Data() case .transitionLiveBroadcast: return Data() case .deleteLiveBroadcast: return Data() case .bindLiveBroadcast: return Data() case .liveStream: return Data() case .deleteLiveStream: return Data() } } public var multipartBody: [MultipartFormData]? { return [] } var headers: [String: String]? { return ["Content-type": "application/json"] } } public func url(_ route: TargetType) -> String { return route.baseURL.appendingPathComponent(route.path).absoluteString }
mit
e3e2c8a9b42869eb8195df4f5b2c05b6
33.68
120
0.622343
5.147583
false
false
false
false
borglab/SwiftFusion
Sources/SwiftFusion/Inference/PenguinExtensions.swift
1
29886
// TODO: Move all these to Penguin. import _Differentiation import PenguinStructures /// A suitable `Index` type for a flattened view of a collection-of-collections having `OuterIndex` /// and `InnerIndex` as the `Index` types of the outer and inner collections, respectively. public struct FlattenedIndex<OuterIndex: Comparable, InnerIndex: Comparable> : Comparable { /// The position of `self` in the outer collection public var outer: OuterIndex /// The position of `self` in the inner collection public var inner: InnerIndex? /// Returns `true` iff `lhs` precedes `rhs`. public static func <(lhs: Self, rhs: Self) -> Bool { if lhs.outer < rhs.outer { return true } if lhs.outer != rhs.outer { return false } guard let l1 = lhs.inner else { return false } guard let r1 = rhs.inner else { return true } return l1 < r1 } /// Creates an instance with the given stored properties. private init(outer: OuterIndex, inner: InnerIndex?) { self.outer = outer self.inner = inner } /// Returns an instance that represents the first position in the flattened view of `c`, where the /// inner collection for each element `e` of `c` is `innerCollection(e)`. internal init<OuterCollection: Collection, InnerCollection: Collection>( firstValidIn c: OuterCollection, innerCollection: (OuterCollection.Element)->InnerCollection ) where OuterCollection.Index == OuterIndex, InnerCollection.Index == InnerIndex { if let i = c.firstIndex(where: { !innerCollection($0).isEmpty }) { self.init(outer: i, inner: innerCollection(c[i]).startIndex) } else { self.init(endIn: c) } } /// Replaces `self` with the next position in the flattened view of `c`, where the inner /// collection for each element `e` of `c` is `innerCollection(e)`. internal mutating func formNextValid<OuterCollection: Collection, InnerCollection: Collection>( in c: OuterCollection, innerCollection: (OuterCollection.Element)->InnerCollection ) where OuterCollection.Index == OuterIndex, InnerCollection.Index == InnerIndex { let c1 = innerCollection(c[outer]) var i = inner! c1.formIndex(after: &i) inner = i if i != c1.endIndex { return } self = .init(firstValidIn: c[outer...].dropFirst(), innerCollection: innerCollection) } /// Replaces `self` with the next position in the flattened view of `c`, where the inner /// collection for each element `e` of `c` is `e` itself. internal mutating func formNextValid<OuterCollection: Collection>(in c: OuterCollection) where OuterCollection.Index == OuterIndex, OuterCollection.Element: Collection, OuterCollection.Element.Index == InnerIndex { formNextValid(in: c) { $0 } } /// Creates an instance that represents the first position in the flattened view of `c`, where the /// inner collection for each element `e` of `c` is `e` itself. internal init<C: Collection>(firstValidIn c: C) where C.Index == OuterIndex, C.Element: Collection, C.Element.Index == InnerIndex { self.init(firstValidIn: c) { $0 } } /// Creates an instance that represents the `endIndex` in a flattened view of `c`. internal init<C: Collection>(endIn c: C) where C.Index == OuterIndex { self.init(outer: c.endIndex, inner: nil) } /// Creates an instance that represents the next position after `i` in a flattened view of `c`, /// where the inner collection for each element `e` of `c` is `innerCollection(e)`. init<OuterCollection: Collection, InnerCollection: Collection>( nextAfter i: Self, in c: OuterCollection, innerCollection: (OuterCollection.Element)->InnerCollection ) where OuterCollection.Index == OuterIndex, InnerCollection.Index == InnerIndex { let c1 = innerCollection(c[i.outer]) let nextInner = c1.index(after: i.inner!) if nextInner != c1.endIndex { self.init(outer: i.outer, inner: nextInner) return } let nextOuter = c.index(after: i.outer) self.init(firstValidIn: c[nextOuter...], innerCollection: innerCollection) } /// Creates an instance that represents the next position after `i` in a flattened view of `c`, /// where the inner collection for each element `e` of `c` is `e` itself. init<OuterCollection: Collection>(nextAfter i: Self, in c: OuterCollection) where OuterCollection.Index == OuterIndex, OuterCollection.Element: Collection, OuterCollection.Element.Index == InnerIndex { self.init(nextAfter: i, in: c) { $0 } } } extension AnyArrayBuffer { /// `true` iff `self` contains no elements. var isEmpty: Bool { count == 0 } // TODO: retire in favor of subscript downcast + append? /// Appends `x`, returning the index of the appended element. /// /// - Requires: `self.elementType == T.self`. mutating func unsafelyAppend<T>(_ x: T) -> Int { self[unsafelyAssumingElementType: Type<T>()].append(x) } /// Accesses `self` as an `AnyArrayBuffer` with no exposed capabilities /// (i.e. `AnyArrayBuffer<AnyObject>`). var upcast: AnyArrayBuffer<AnyObject> { get { .init(self) } _modify { var x = AnyArrayBuffer<AnyObject>(unsafelyCasting: self) self.storage = nil defer { self.storage = x.storage } yield &x } } } extension ArrayStorage: CustomDebugStringConvertible { public var debugDescription: String { "ArrayStorage(\(Array(self)))" } } extension ArrayBuffer: CustomDebugStringConvertible { public var debugDescription: String { "ArrayBuffer(\(Array(self)))" } } import PenguinParallelWithFoundation // // Storage for โ€œvtablesโ€ implementing operations on type-erased values. // // Large tables of Swift functions are expensive if stored inline, and incur ARC and allocation // costs if stored in classes. We want to allocate them once, keep them alive forever, and // reference them with cheap unsafe pointers. // // We therefore need a vtable cache. For thread-safety, we could share a table and use a lock, but // the easiest answer for now is use a thread-local cache per thread. typealias TLS = PosixConcurrencyPlatform.ThreadLocalStorage /// Holds the lookup table for vtables. TLS facilities require that this be a class type. fileprivate class VTableCache { /// A map from a pair of types (`Wrapper`, `Wrapped`) to the address of a VTable containing the /// implementation of `Wrapper` operations in terms of `Wrapped` operations. var tables: [Array2<TypeID>: UnsafeRawPointer] = [:] init() {} } /// Lookup key for the thread-local vtable cache. fileprivate let vTableCacheKey = TLS.makeKey(for: Type<VTableCache>()) /// Constructs a vtable cache instance for the current thread. @inline(never) fileprivate func makeVTableCache() -> VTableCache { let r = VTableCache() TLS.set(r, for: vTableCacheKey) return r } /// Returns a pointer to the table corresponding to `tableID`, creating it by invoking `create` if it /// is not already available. fileprivate func demandVTable<Table>(_ tableID: Array2<TypeID>, create: ()->Table) -> UnsafePointer<Table> { /// Returns a pointer to a globally-allocated copy of the result of `create`, registering it /// in `tableCache`. @inline(never) func makeAndCacheTable(in cache: VTableCache) -> UnsafePointer<Table> { let r = UnsafeMutablePointer<Table>.allocate(capacity: 1) r.initialize(to: create()) cache.tables[tableID] = .init(r) return .init(r) } let slowPathCache: VTableCache if let cache = TLS.get(vTableCacheKey) { if let r = cache.tables[tableID] { return r.assumingMemoryBound(to: Table.self) } slowPathCache = cache } else { slowPathCache = makeVTableCache() } return makeAndCacheTable(in: slowPathCache) } // ================================================================================================= /// โ€œExistential VTableโ€ for requirements that can't be threaded through closures (see /// https://forums.swift.org/t/pitch-rethrows-unchecked/10078/9). fileprivate protocol AnyMutableCollectionExistentialDispatchProtocol { static func withContiguousStorageIfAvailable( _ self_: AnyValue, _ body: (UnsafeRawPointer?, Int) throws -> Void ) rethrows static func withUnsafeMutableBufferPointerIfSupported( _ self_: inout AnyValue, _ body: (UnsafeMutableRawPointer?, Int) throws -> Void ) rethrows static func withContiguousMutableStorageIfAvailable( _ self_: inout AnyValue, _ body: (UnsafeMutableRawPointer?, Int) throws -> Void ) rethrows static func partition( _ self_: inout AnyValue, _ resultIndex: UnsafeMutableRawPointer, _ belongsInSecondPartition: (UnsafeRawPointer) throws -> Bool ) rethrows } /// Instance of `AnyMutableCollectionExistentialDispatchProtocol` for an AnyMutableCollection /// wrapping `C`. enum AnyMutableCollectionExistentialDispatch<C: MutableCollection> : AnyMutableCollectionExistentialDispatchProtocol { static func withContiguousStorageIfAvailable( _ self_: AnyValue, _ body: (UnsafeRawPointer?, Int) throws -> Void ) rethrows { try self_[unsafelyAssuming: Type<C>()] .withContiguousStorageIfAvailable { try body($0.baseAddress, $0.count) } } static func withUnsafeMutableBufferPointerIfSupported( _ self_: inout AnyValue, _ body: (UnsafeMutableRawPointer?, Int) throws -> Void ) rethrows { try self_[unsafelyAssuming: Type<C>()] ._withUnsafeMutableBufferPointerIfSupported { try body($0.baseAddress, $0.count) } } static func withContiguousMutableStorageIfAvailable( _ self_: inout AnyValue, _ body: (UnsafeMutableRawPointer?, Int) throws -> Void ) rethrows { try self_[unsafelyAssuming: Type<C>()] .withContiguousMutableStorageIfAvailable { try body($0.baseAddress, $0.count) } } static func partition( _ self_: inout AnyValue, _ resultIndex: UnsafeMutableRawPointer, _ belongsInSecondPartition: (UnsafeRawPointer) throws -> Bool ) rethrows { let r = try self_[unsafelyAssuming: Type<C>()] .partition { try withUnsafePointer(to: $0) { try belongsInSecondPartition($0) } } resultIndex.assumingMemoryBound(to: AnyMutableCollection<C.Element>.Index?.self) .pointee = .init(r) } } /// A type-erased mutable collection similar to the standard library's `AnyCollection`. public struct AnyMutableCollection<Element> { typealias Storage = AnyValue private var storage: Storage private var vtable: UnsafePointer<VTable> typealias Self_ = Self fileprivate struct VTable { // Sequence requirements. let makeIterator: (Self_) -> Iterator let existentialDispatch: AnyMutableCollectionExistentialDispatchProtocol.Type // Hidden Sequence requirements let customContainsEquatableElement: (Self_, Element) -> Bool? let copyToContiguousArray: (Self_) -> ContiguousArray<Element> let copyContents: ( Self_, _ uninitializedTarget: UnsafeMutableBufferPointer<Element>) -> (Iterator, UnsafeMutableBufferPointer<Element>.Index) // Collection requirements. let startIndex: (Self_) -> Index let endIndex: (Self_) -> Index let indexAfter: (Self_, Index) -> Index let formIndexAfter: (Self_, inout Index) -> Void let subscript_get: (Self_, Index) -> Element let subscript_set: (inout Self_, Index, Element) -> Void let isEmpty: (Self_) -> Bool let count: (Self_) -> Int let indexOffsetBy: (Self_, Index, Int) -> Index let indexOffsetByLimitedBy: (Self_, Index, Int, _ limit: Index) -> Index? let distance: (Self_, _ start: Index, _ end: Index) -> Int // let subscriptRange_get: (Self_, Range<Index>) -> SubSequence // let subscriptRange_set: (inout Self_, Range<Index>, SubSequence) -> Void // We'd need an efficient AnyCollection in order to implement this better. // let indices: (Self_) -> Indices // Hidden collection requirements let customIndexOfEquatableElement: (Self_, _ element: Element) -> Index?? let customLastIndexOfEquatableElement: (Self_, _ element: Element) -> Index?? // MutableCollection requirements let swapAt: (inout Self_, Index, Index) -> Void } init<C: MutableCollection>(_ x: C) where C.Element == Element { storage = Storage(x) vtable = demandVTable(.init(Type<Self>.id, Type<C>.id)) { VTable( makeIterator: { Iterator($0.storage[unsafelyAssuming: Type<C>()].makeIterator()) }, existentialDispatch: AnyMutableCollectionExistentialDispatch<C>.self, customContainsEquatableElement: { self_, e in self_.storage[unsafelyAssuming: Type<C>()]._customContainsEquatableElement(e) }, copyToContiguousArray: { $0.storage[unsafelyAssuming: Type<C>()]._copyToContiguousArray() }, copyContents: { self_, target in let (i, j) = self_.storage[unsafelyAssuming: Type<C>()] ._copyContents(initializing: target) return (Iterator(i), j) }, startIndex: { Index($0.storage[unsafelyAssuming: Type<C>()].startIndex) }, endIndex: { Index($0.storage[unsafelyAssuming: Type<C>()].endIndex) }, indexAfter: { self_, index_ in Index( self_.storage[unsafelyAssuming: Type<C>()] .index(after: index_.storage[Type<C.Index>()])) }, formIndexAfter: { self_, index in self_.storage[unsafelyAssuming: Type<C>()] .formIndex(after: &index.storage[Type<C.Index>()]) }, subscript_get: { self_, index in self_.storage[unsafelyAssuming: Type<C>()][index.storage[Type<C.Index>()]] }, subscript_set: { self_, index, newValue in self_.storage[unsafelyAssuming: Type<C>()][index.storage[Type<C.Index>()]] = newValue }, isEmpty: { $0.storage[unsafelyAssuming: Type<C>()].isEmpty }, count: { $0.storage[unsafelyAssuming: Type<C>()].count }, indexOffsetBy: { self_, i, offset in Index( self_.storage[unsafelyAssuming: Type<C>()] .index(i.storage[Type<C.Index>()], offsetBy: offset)) }, indexOffsetByLimitedBy: { self_, i, offset, limit in self_.storage[unsafelyAssuming: Type<C>()].index( i.storage[Type<C.Index>()], offsetBy: offset, limitedBy: limit.storage[Type<C.Index>()] ).map(Index.init) }, distance: { self_, start, end in self_.storage[unsafelyAssuming: Type<C>()].distance( from: start.storage[Type<C.Index>()], to: end.storage[Type<C.Index>()]) }, // Hidden collection requirements customIndexOfEquatableElement: { self_, e in self_.storage[unsafelyAssuming: Type<C>()] ._customIndexOfEquatableElement(e).map { $0.map(Index.init) } }, customLastIndexOfEquatableElement: { self_, e in self_.storage[unsafelyAssuming: Type<C>()]._customLastIndexOfEquatableElement(e) .map { $0.map(Index.init) } }, // MutableCollection requirements. swapAt: { self_, i, j in self_.storage[unsafelyAssuming: Type<C>()] .swapAt(i.storage[Type<C.Index>()], j.storage[Type<C.Index>()]) } ) } } public var asAny: Any { storage.asAny } } extension AnyMutableCollection: Sequence { public struct Iterator: IteratorProtocol { var storage: Storage // There's only one operation, so probably no point bothering with a vtable. var next_: (inout Self) -> Element? init<T: IteratorProtocol>(_ x: T) where T.Element == Element { storage = .init(x) next_ = { $0.storage[unsafelyAssuming: Type<T>()].next() } } public mutating func next() -> Element? { next_(&self) } } public func makeIterator() -> Iterator { vtable[0].makeIterator(self) } /// If `self` supports a contiguous storage representation, assumes that representation and /// returns the result of passing the storage to `body`; returns `nil` otherwise. /// /// - Note: this documentation might be wrong: https://bugs.swift.org/browse/SR-13486 public func withContiguousStorageIfAvailable<R>( _ body: (UnsafeBufferPointer<Element>) throws -> R ) rethrows -> R? { var result: R? = nil try vtable[0].existentialDispatch.withContiguousStorageIfAvailable(storage) { try result = body( UnsafeBufferPointer(start: $0?.assumingMemoryBound(to: Element.self), count: $1)) } return result } public func _customContainsEquatableElement(_ e: Element) -> Bool? { vtable[0].customContainsEquatableElement(self, e) } public __consuming func _copyToContiguousArray() -> ContiguousArray<Element> { vtable[0].copyToContiguousArray(self) } public __consuming func _copyContents( initializing target: UnsafeMutableBufferPointer<Element> ) -> (Iterator,UnsafeMutableBufferPointer<Element>.Index) { vtable[0].copyContents(self, target) } } extension AnyMutableCollection: MutableCollection { public struct Index: Comparable { fileprivate var storage: Storage // Note: using a vtable here actually made benchmarks slower. We might want to try again if we // expand what the benchmarks are doing. My hunch is that the cost of copying an Index is less // important than the cost of checking for equality. fileprivate let less: (Index, Index) -> Bool fileprivate let equal: (Index, Index) -> Bool fileprivate init<T: Comparable>(_ x: T) { storage = .init(x) less = {l, r in l.storage[unsafelyAssuming: Type<T>()] < r.storage[Type<T>()]} equal = {l, r in l.storage[unsafelyAssuming: Type<T>()] == r.storage[Type<T>()]} } public static func == (lhs: Index, rhs: Index) -> Bool { lhs.equal(lhs, rhs) } public static func < (lhs: Index, rhs: Index) -> Bool { lhs.less(lhs, rhs) } } public var startIndex: Index { vtable[0].startIndex(self) } public var endIndex: Index { vtable[0].endIndex(self) } public func index(after x: Index) -> Index { vtable[0].indexAfter(self, x) } public func formIndex(after x: inout Index) { vtable[0].formIndexAfter(self, &x) } public subscript(i: Index) -> Element { get { vtable[0].subscript_get(self, i) } set { vtable[0].subscript_set(&self, i, newValue) } } public var isEmpty: Bool { vtable[0].isEmpty(self) } public var count: Int { vtable[0].count(self) } public func _customIndexOfEquatableElement(_ element: Element) -> Index?? { vtable[0].customIndexOfEquatableElement(self, element) } public func _customLastIndexOfEquatableElement(_ element: Element) -> Index?? { vtable[0].customLastIndexOfEquatableElement(self, element) } /// Returns an index that is the specified distance from the given index. public func index(_ i: Index, offsetBy distance: Int) -> Index { vtable[0].indexOffsetBy(self, i, distance) } /// Returns an index that is the specified distance from the given index, /// unless that distance is beyond a given limiting index. public func index( _ i: Index, offsetBy distance: Int, limitedBy limit: Index ) -> Index? { vtable[0].indexOffsetByLimitedBy(self, i, distance, limit) } /// Returns the distance between two indices. public func distance(from start: Index, to end: Index) -> Int { vtable[0].distance(self, start, end) } public mutating func _withUnsafeMutableBufferPointerIfSupported<R>( _ body: (inout UnsafeMutableBufferPointer<Element>) throws -> R ) rethrows -> R? { var result: R? = nil try vtable[0].existentialDispatch.withUnsafeMutableBufferPointerIfSupported(&storage) { var buf = UnsafeMutableBufferPointer( start: $0?.assumingMemoryBound(to: Element.self), count: $1) try result = body(&buf) } return result } public mutating func withContiguousMutableStorageIfAvailable<R>( _ body: (inout UnsafeMutableBufferPointer<Element>) throws -> R ) rethrows -> R? { var result: R? = nil try vtable[0].existentialDispatch.withContiguousMutableStorageIfAvailable(&storage) { var buf = UnsafeMutableBufferPointer( start: $0?.assumingMemoryBound(to: Element.self), count: $1) try result = body(&buf) } return result } /// Reorders the elements of the collection such that all the elements /// that match the given predicate are after all the elements that don't /// match. /// /// - Complexity: O(*n*), where *n* is the length of the collection. public mutating func partition( by belongsInSecondPartition: (Element) throws -> Bool ) rethrows -> Index { var r: Index? = nil try vtable[0].existentialDispatch.partition(&storage, &r) { p in try belongsInSecondPartition(p.assumingMemoryBound(to: Element.self).pointee) } return r.unsafelyUnwrapped } /// Exchanges the values at the specified indices of the collection. public mutating func swapAt(_ i: Index, _ j: Index) { vtable[0].swapAt(&self, i, j) } } // ================================================================================================= public struct FlattenedMutableCollection<Base: MutableCollection> where Base.Element: MutableCollection { var base: Base init(_ base: Base) { self.base = base } } /* extension Sequence { func reduceUntil<R>( _ initialValue: R, combine: (R, Element) throws -> (R, done: Bool) ) rethrows -> R { var r = initialValue var i = makeIterator() while let e = i.next() { let (r1, done) = try combine(r, i.next()) r = r1 if done { break } } return r } } */ extension FlattenedMutableCollection: Sequence { public typealias Element = Base.Element.Element public struct Iterator: IteratorProtocol { var outer: Base.Iterator var inner: Base.Element.Iterator? init(outer: Base.Iterator, inner: Base.Element.Iterator? = nil) { self.outer = outer self.inner = inner } public mutating func next() -> Element? { while true { if let r = inner?.next() { return r } guard let o = outer.next() else { return nil } inner = o.makeIterator() } } } public func makeIterator() -> Iterator { Iterator(outer: base.makeIterator()) } // https://bugs.swift.org/browse/SR-13486 points out that the withContiguousStorageIfAvailable // method is dangerously underspecified, so we don't implement it here. public func _customContainsEquatableElement(_ e: Element) -> Bool? { let m = base.lazy.map({ $0._customContainsEquatableElement(e) }) if let x = m.first(where: { $0 != false }) { return x } return false } public __consuming func _copyContents( initializing t: UnsafeMutableBufferPointer<Element> ) -> (Iterator, UnsafeMutableBufferPointer<Element>.Index) { var r = 0 var outer = base.makeIterator() while r < t.count, let e = outer.next() { var (inner, r1) = e._copyContents( initializing: .init(start: t.baseAddress.map { $0 + r }, count: t.count - r)) r += r1 // See if we ran out of target space before reaching the end of the inner collection. I think // this will be rare, so instead of using an O(N) `e.count` and comparing with `r1` in all // passes of the outer loop, spend `inner` seeing if we reached the end and reconstitute it in // O(N) if not. if inner.next() != nil { @inline(never) func earlyExit() -> (Iterator, UnsafeMutableBufferPointer<Element>.Index) { var i = e.makeIterator() for _ in 0..<r1 { _ = i.next() } return (.init(outer: outer, inner: i), r) } return earlyExit() } } return (.init(outer: outer, inner: nil), r) } } extension FlattenedMutableCollection: MutableCollection { public typealias Index = FlattenedIndex<Base.Index, Base.Element.Index> public var startIndex: Index { .init(firstValidIn: base) } public var endIndex: Index { .init(endIn: base) } public func index(after x: Index) -> Index { .init(nextAfter: x, in: base) } public func formIndex(after x: inout Index) { x.formNextValid(in: base) } public subscript(i: Index) -> Element { get { base[i.outer][i.inner!] } set { base[i.outer][i.inner!] = newValue } _modify { yield &base[i.outer][i.inner!] } } public var isEmpty: Bool { base.allSatisfy { $0.isEmpty } } public var count: Int { base.lazy.map(\.count).reduce(0, +) } /* TODO: implement or discard func _customIndexOfEquatableElement(_ element: Element) -> Index?? { } func _customLastIndexOfEquatableElement(_ element: Element) -> Index?? { } /// Returns an index that is the specified distance from the given index. func index(_ i: Index, offsetBy distance: Int) -> Index { } /// Returns an index that is the specified distance from the given index, /// unless that distance is beyond a given limiting index. func index( _ i: Index, offsetBy distance: Int, limitedBy limit: Index ) -> Index? { vtable[0].indexOffsetByLimitedBy(self, i, distance, limit) } /// Returns the distance between two indices. func distance(from start: Index, to end: Index) -> Int { vtable[0].distance(self, start, end) } // https://bugs.swift.org/browse/SR-13486 points out that these two // methods are dangerously underspecified, so we don't implement them here. public mutating func _withUnsafeMutableBufferPointerIfSupported<R>( _ body: (inout UnsafeMutableBufferPointer<Element>) throws -> R ) rethrows -> R? { } public mutating func withContiguousMutableStorageIfAvailable<R>( _ body: (inout UnsafeMutableBufferPointer<Element>) throws -> R ) rethrows -> R? { } /// Reorders the elements of the collection such that all the elements /// that match the given predicate are after all the elements that don't /// match. /// /// - Complexity: O(*n*), where *n* is the length of the collection. public mutating func partition( by belongsInSecondPartition: (Element) throws -> Bool ) rethrows -> Index { } /// Exchanges the values at the specified indices of the collection. public mutating func swapAt(_ i: Index, _ j: Index) { } */ } // ================================================================================================= // Standard library extensions extension UnsafeRawPointer { /// Returns the `T` to which `self` points. internal subscript<T>(as _: Type<T>) -> T { self.assumingMemoryBound(to: T.self).pointee } } extension UnsafeMutableRawPointer { /// Returns the `T` to which `self` points. internal subscript<T>(as _: Type<T>) -> T { get { self.assumingMemoryBound(to: T.self).pointee } _modify { yield &self.assumingMemoryBound(to: T.self).pointee } } } extension Dictionary { /// Accesses the value associated with a key that is known to exist in `self`. /// /// - Precondition: self[k] != `nil`. subscript(existingKey k: Key) -> Value { get { self[k]! } _modify { yield &values[index(forKey: k)!] } } /// Invokes `update` to mutate each stored `Value`, passing its corresponding `Key` and the /// `Index` in `self` where that `(Key, Value)` pair is stored. mutating func updateValues(_ update: (Key, inout Value, Index) throws -> Void) rethrows { var i = startIndex while i != endIndex { try update(self[i].key, &values[i], i) formIndex(after: &i) } } } extension InsertionOrderedDictionary { /// Accesses the value associated with a key that is known to exist in `self`. /// /// - Precondition: self[k] != `nil`. subscript(existingKey k: Key) -> Value { get { self[k]! } _modify { yield &values[index(forKey: k)!] } } /// Invokes `update` to mutate each stored `Value`, passing its corresponding `Key` and the /// `Index` in `self` where that `(Key, Value)` pair is stored. mutating func updateValues(_ update: (Key, inout Value, Index) throws -> Void) rethrows { var i = startIndex while i != endIndex { try update(self[i].key, &values[i], i) formIndex(after: &i) } } } /// The consecutive `SubSequence`s of a `Base` collection having a given maximum size. struct Batched<Base: Collection>: Collection { public let base: Base public let maxBatchSize: Int init(_ base: Base, maxBatchSize: Int) { precondition(maxBatchSize > 0) self.base = base self.maxBatchSize = maxBatchSize } struct Iterator: IteratorProtocol { let slices: Batched let position: Index mutating func next() -> Base.SubSequence? { position.sliceStart == position.sliceEnd ? nil : slices[position] } } func makeIterator() -> Iterator { .init(slices: self, position: startIndex) } struct Index: Comparable { var sliceStart, sliceEnd: Base.Index static func < (lhs: Self, rhs: Self) -> Bool { lhs.sliceStart < rhs.sliceStart } } private func next(after i: Base.Index) -> Base.Index { let limit = base.endIndex return base.index(i, offsetBy: maxBatchSize, limitedBy: limit) ?? limit } var startIndex: Index { .init(sliceStart: base.startIndex, sliceEnd: next(after: base.startIndex)) } var endIndex: Index { .init(sliceStart: base.endIndex, sliceEnd: base.endIndex) } func index(after i: Index) -> Index { .init(sliceStart: i.sliceEnd, sliceEnd: next(after: i.sliceEnd)) } func formIndex(after i: inout Index) { (i.sliceStart, i.sliceEnd) = (i.sliceEnd, next(after: i.sliceEnd)) } subscript(i: Index) -> Base.SubSequence { base[i.sliceStart..<i.sliceEnd] } } extension Collection { func sliced(intoBatchesOfAtMost maxBatchSize: Int) -> Batched<Self> { .init(self, maxBatchSize: maxBatchSize) } }
apache-2.0
3cfa61a5a53c3b45ed3bdbf3b058c051
34.696535
101
0.662427
4.134219
false
false
false
false
Draveness/RbSwift
RbSwiftTests/String/String+TransformSpec.swift
1
8756
// // Conversions.swift // RbSwift // // Created by draveness on 19/03/2017. // Copyright ยฉ 2017 draveness. All rights reserved. // import Quick import Nimble import RbSwift class StringTransformSpec: BaseSpec { override func spec() { describe(".concat") { it("concats two strings together") { expect("Hello".concat(" World")).to(equal("Hello World")) } } describe(".chomp(chars:)") { it("returns a new string without whitespace in the end") { expect("1Hello\r1\n".chomp).to(equal("1Hello\r1")) expect("Hello\r\n\r\n".chomp).to(equal("Hello")) expect("Hello\n".chomp).to(equal("Hello")) expect("Hello ".chomp).to(equal("Hello")) expect("Hello \r".chomp).to(equal("Hello")) expect(" Hello \r".chomp).to(equal(" Hello")) expect("".chomp).to(beEmpty()) } it("returns a new string without the passing chars in the end") { expect("Hello\r\n".chomp("o\r\n")).to(equal("Hell")) expect("Hello".chomp("o\r\n")).to(equal("Hello")) } it("returns a new string without newline") { expect("Hello\r\n\r\n".chomp("")).to(equal("Hello")) expect("Hello\r\n\r\r\n".chomp("")).to(equal("Hello\r\n\r")) } } describe(".chop") { it("returns a new string without the last character") { expect("Hello\r\n\r\n".chop).to(equal("Hello\r\n")) expect("Hello\r\n".chop).to(equal("Hello")) expect("Hello\n\r".chop).to(equal("Hello\n")) expect("Hello\n".chop).to(equal("Hello")) expect("x".chop).to(beEmpty()) expect("".chop.chop).to(beEmpty()) } } describe(".clear") { it("makes the string empty") { var s = "xyz" expect(s.cleared()).to(beEmpty()) expect(s).to(beEmpty()) } } describe(".count(str:)") { it("returns the count of specific chars inside the receiver string") { let a = "hello world" expect(a.count("lo")).to(equal(5)) expect(a.count("lo", "o")).to(equal(2)) expect(a.count("hello", "^l")).to(equal(4)) expect(a.count("ej-m")).to(equal(4)) expect("hello^world".count("\\^aeiou")).to(equal(4)) expect("hello-world".count("a-eo")).to(equal(4)) let c = "hello world\\r\\n" expect(c.count("\\A")).to(equal(0)) expect(c.count("X\\-\\\\w")).to(equal(3)) } } describe(".delete(str:)") { it("returns the string with specific chars deleted inside the receiver string") { let a = "hello world" expect(a.delete("lo")).to(equal("he wrd")) expect(a.delete("lo", "o")).to(equal("hell wrld")) expect(a.delete("hello", "^l")).to(equal("ll wrld")) expect(a.delete("ej-m")).to(equal("ho word")) expect("hello^world".delete("\\^aeiou")).to(equal("hllwrld")) expect("hello-world".delete("a-eo")).to(equal("hll-wrl")) expect("hello-world".delete("a\\-eo")).to(equal("hllwrld")) let c = "hello world\\r\\n" expect(c.delete("\\A")).to(equal("hello world\\r\\n")) expect(c.delete("X\\-\\\\w")).to(equal("hello orldrn")) } } describe(".reverse") { it("returns a new string with reverse order") { expect("Hello".reverse).to(equal("olleH")) } } describe(".split") { it("splits string into array") { expect(" now's the time".split).to(equal(["now's", "the", "time"])) expect(" now's\nthe time\n\t".split).to(equal(["now's", "the", "time"])) expect("hello".split("")).to(equal(["h", "e", "l", "l", "o"])) expect("hello".split("l+")).to(equal(["he", "o"])) expect(" now's the time".split(" ")).to(equal(["now's", "the", "time"])) expect("mellow yellow".split("ello")).to(equal(["m", "w y", "w"])) expect("1,2,,3,4,,".split(",")).to(equal(["1", "2", "", "3", "4"])) expect("red yellow and blue".split("[ae ]")).to(equal(["r", "d", "y", "llow", "", "nd", "blu"])) } } describe(".ljust") { context("when integer is greater than the length of str") { it("returns a new String of length integer with str left justified and padded with padstr") { expect("hello".ljust(20)).to(equal("hello" + 15 * " ")) expect("hello".ljust(20, "1234")).to(equal("hello123412341234123")) } } context("otherwise") { it("returns the string") { expect("hello".ljust(4)).to(equal("hello")) } } } describe(".rjust") { context("when integer is greater than the length of str") { it("returns a new String of length integer with str right justified and padded with padstr") { expect("hello".rjust(20)).to(equal(15 * " " + "hello")) expect("hello".rjust(20, "1234")).to(equal("123412341234123hello")) } } context("otherwise") { it("returns the string") { expect("hello".rjust(4)).to(equal("hello")) } } } describe(".center") { context("when integer is greater than the length of str") { it("returns a new String of length integer with str centered and padded with padstr") { expect("hello".center(20)).to(equal(" hello ")) expect("hello".center(20).length).to(equal(20)) expect("hello".center(20, "123")).to(equal("1231231hello12312312")) } } context("otherwise") { it("returns the string") { expect("hello".center(4)).to(equal("hello")) } } } describe(".strip") { it("removes both sides whitespace from str") { expect("\t \nhello ".strip).to(equal("hello")) expect("\t hello ".strip).to(equal("hello")) expect("hello ".strip).to(equal("hello")) } } describe(".lstrip") { it("removes leading whitespace from str") { expect("\t \nhello".lstrip).to(equal("hello")) expect("\t hello ".lstrip).to(equal("hello ")) } } describe(".rstrip") { it("removes trailing whitespace from str") { expect("\t \nhello ".rstrip).to(equal("\t \nhello")) expect("\t hello ".rstrip).to(equal("\t hello")) } } describe(".prepend(other:)") { it("prepends the given string to str") { var str = "yz" expect(str.prepend("x")).to(equal("xyz")) expect(str).to(equal("xyz")) } } describe(".replace(other:)") { it("replaces the contents and taintedness of str with the corresponding values in other str") { var str = "yz" expect(str.replace("x")).to(equal("x")) expect(str).to(equal("x")) } } describe(".partition") { it("searches sep or pattern (regexp) in the string and returns the part before it, the match, and the part after it") { expect("hello".partition("l")).to(equal(["he", "l", "lo"])) expect("hello".partition("le")).to(equal(["hello", "", ""])) } } describe(".rpartition") { it("searches sep or pattern (regexp) in the string from the end of it and returns the part before it, the match, and the part after it") { expect("hello".rpartition("l")).to(equal(["hel", "l", "o"])) expect("hello".rpartition("le")).to(equal(["", "", "hello"])) } } } }
mit
7733dedeadf70f9864efb7536010217e
39.72093
150
0.45414
4.175012
false
false
false
false
cookpad/puree-ios
Example/Tests/PURLoggerStandardPluginTest.swift
1
9592
import XCTest class PURLoggerStandardPluginTest: XCTestCase { class TestLoggerConfiguration: PURLoggerConfiguration { let logStorage = TestLogStorage() let logStoreOperationDispatchQueue = DispatchQueue(label: "Puree logger test") } var loggerConfiguration: TestLoggerConfiguration! var logger: PURLogger! var testLogStorage: TestLogStorage { return loggerConfiguration.logStorage } override func setUp() { let configuration = TestLoggerConfiguration() let logStoreDBPath = NSTemporaryDirectory() + "/PureeLoggerTest-\(UUID().uuidString).db" let logStore = PURLogStore(databasePath: logStoreDBPath) let logStorage = configuration.logStorage configuration.logStore = logStore configuration.filterSettings = [ PURFilterSetting(filter: PURTestChangeTagFilter.self, tagPattern: "filter.test", settings: ["tagSuffix": "XXX"]), PURFilterSetting(filter: PURTestAppendParamFilter.self, tagPattern: "filter.append.**"), ] configuration.outputSettings = [ PUROutputSetting(output: PURTestOutput.self, tagPattern: "filter.testXXX", settings: ["logStorage": logStorage]), PUROutputSetting(output: PURTestOutput.self, tagPattern: "filter.append.**", settings: ["logStorage": logStorage]), PUROutputSetting(output: PURTestOutput.self, tagPattern: "test.*", settings: ["logStorage": logStorage]), PUROutputSetting(output: PURTestOutput.self, tagPattern: "unbuffered", settings: ["logStorage": logStorage]), PUROutputSetting(output: PURTestBufferedOutput.self, tagPattern: "buffered.*", settings: ["logStorage": logStorage, PURBufferedOutputSettingsFlushIntervalKey: 2]), PUROutputSetting(output: PURTestFailureOutput.self, tagPattern: "failure", settings: ["logStorage": logStorage]), ] loggerConfiguration = configuration logger = PURLogger(configuration: configuration) } override func tearDown() { logger.logStore().clearAll() logger.shutdown() } func testChangeTagFilterPlugin() { XCTAssertEqual(String(describing: testLogStorage), "") logger.post(["aaa": "123"], tag: "filter.test") logger.post(["bbb": "456", "ccc": "789"], tag: "filter.test") logger.post(["ddd": "12345"], tag: "debug") logger.post(["eee": "not filtered"], tag: "filter.testXXX") XCTAssertEqual(String(describing: testLogStorage), "[filter.testXXX|aaa:123][filter.testXXX|bbb:456,ccc:789][filter.testXXX|eee:not filtered]") } func testAppendParamFilterPlugin() { XCTAssertEqual(String(describing: testLogStorage), "") logger.post(["aaa": "123"], tag: "filter.append") logger.post(["bbb": "456"], tag: "filter.append.xxx") logger.post(["ddd": "12345"], tag: "debug") logger.post(["ccc": "789"], tag: "filter.append.yyy") XCTAssertEqual(String(describing: testLogStorage), "[filter.append|aaa:123,ext:][filter.append.xxx|bbb:456,ext:xxx][filter.append.yyy|ccc:789,ext:yyy]") } func testUnbufferedOutputPlugin() { XCTAssertEqual(String(describing: testLogStorage), "") logger.post(["aaa": "123"], tag: "test.hoge") logger.post(["bbb": "456", "ccc": "789"], tag: "test.fuga") logger.post(["ddd": "12345"], tag: "debug") XCTAssertEqual(String(describing: testLogStorage), "[test.hoge|aaa:123][test.fuga|bbb:456,ccc:789]") } func testBufferedOutputPlugin_writeLog() { expectation(forNotification: Notification.Name.PURBufferedOutputDidStart.rawValue, object: nil, handler: nil) waitForExpectations(timeout: 1.0, handler: nil) XCTAssertEqual(String(describing: testLogStorage), "") expectation(forNotification: Notification.Name.PURBufferedOutputDidSuccessWriteChunk.rawValue, object: nil, handler: nil) logger.post(["aaa": "1"], tag: "buffered.a") logger.post(["aaa": "2"], tag: "buffered.a") logger.post(["aaa": "3"], tag: "buffered.b") XCTAssertEqual(String(describing: testLogStorage), "") logger.post(["aaa": "4"], tag: "buffered.b") logger.post(["zzz": "###"], tag: "unbuffered") logger.post(["aaa": "5"], tag: "buffered.a") // <- flush! // stay in buffer logger.post(["aaa": "6"], tag: "buffered.a") waitForExpectations(timeout: 1.0, handler: nil) let logStorageContent = String(describing: testLogStorage) XCTAssertTrue(logStorageContent.contains("[unbuffered|zzz:###]")) XCTAssertTrue(logStorageContent.contains("{buffered.a|aaa:1}")) XCTAssertTrue(logStorageContent.contains("{buffered.a|aaa:2}")) XCTAssertTrue(logStorageContent.contains("{buffered.b|aaa:3}")) XCTAssertTrue(logStorageContent.contains("{buffered.b|aaa:4}")) XCTAssertTrue(logStorageContent.contains("{buffered.a|aaa:5}")) XCTAssertFalse(logStorageContent.contains("{buffered.a|aaa:6}")) } func testBufferedOutputPlugin_resumeStoredLogs() { expectation(forNotification: Notification.Name.PURBufferedOutputDidStart.rawValue, object: nil, handler: nil) waitForExpectations(timeout: 1.0, handler: nil) XCTAssertEqual(String(describing: testLogStorage), "") expectation(forNotification: Notification.Name.PURBufferedOutputDidSuccessWriteChunk.rawValue, object: nil, handler: nil) logger.post(["aaa": "1"], tag: "buffered.c") logger.post(["aaa": "2"], tag: "buffered.c") logger.post(["aaa": "3"], tag: "buffered.d") XCTAssertEqual(String(describing: testLogStorage), "") logger.shutdown() expectation(forNotification: Notification.Name.PURBufferedOutputDidStart.rawValue, object: nil, handler: nil) // renewal logger! logger = PURLogger(configuration: loggerConfiguration) // <- flush! waitForExpectations(timeout: 1.0, handler: nil) logger.post(["aaa": "4"], tag: "buffered.d") // stay in buffer logger.post(["zzz": "###"], tag: "unbuffered") logger.post(["aaa": "5"], tag: "buffered.c") // stay in buffer logger.post(["aaa": "6"], tag: "buffered.c") // stay in buffer let logStorageContent = String(describing: testLogStorage) XCTAssertTrue(logStorageContent.contains("[unbuffered|zzz:###]")) XCTAssertTrue(logStorageContent.contains("{buffered.c|aaa:1}")) XCTAssertTrue(logStorageContent.contains("{buffered.c|aaa:2}")) XCTAssertTrue(logStorageContent.contains("{buffered.d|aaa:3}")) XCTAssertFalse(logStorageContent.contains("{buffered.d|aaa:4}")) XCTAssertFalse(logStorageContent.contains("{buffered.c|aaa:5}")) XCTAssertFalse(logStorageContent.contains("{buffered.c|aaa:6}")) } func testBufferedOutputPlugin_periodicalFlushing() { expectation(forNotification: Notification.Name.PURBufferedOutputDidStart.rawValue, object: nil, handler: nil) waitForExpectations(timeout: 1.0, handler: nil) XCTAssertEqual(String(describing: testLogStorage), "") expectation(forNotification: Notification.Name.PURBufferedOutputDidSuccessWriteChunk.rawValue, object: nil, handler: nil) logger.post(["aaa": "1"], tag: "buffered.e") logger.post(["aaa": "2"], tag: "buffered.e") logger.post(["aaa": "3"], tag: "buffered.f") XCTAssertEqual(String(describing: testLogStorage), "") // wait flush interval(2sec) ... waitForExpectations(timeout: 3.0, handler: nil) let logStorageContent = String(describing: testLogStorage) XCTAssertTrue(logStorageContent.contains("{buffered.e|aaa:1}")) XCTAssertTrue(logStorageContent.contains("{buffered.e|aaa:2}")) XCTAssertTrue(logStorageContent.contains("{buffered.f|aaa:3}")) } func testBufferedOutputPlugin_retry() { expectation(forNotification: Notification.Name.PURBufferedOutputDidStart.rawValue, object: nil, handler: nil) waitForExpectations(timeout: 1.0, handler: nil) XCTAssertEqual(String(describing: testLogStorage), "") expectation(forNotification: Notification.Name.PURBufferedOutputDidTryWriteChunk.rawValue, object: nil, handler: nil) logger.post(["aaa": "1"], tag: "failure") logger.post(["aaa": "2"], tag: "failure") logger.post(["aaa": "3"], tag: "failure") logger.post(["aaa": "4"], tag: "failure") logger.post(["aaa": "5"], tag: "failure") waitForExpectations(timeout: 1.0, handler: nil) XCTAssertEqual(String(describing: testLogStorage), "[error]") expectation(forNotification: Notification.Name.PURBufferedOutputDidTryWriteChunk.rawValue, object: nil, handler: nil) // scheduled after 2sec waitForExpectations(timeout: 3.0, handler: nil) XCTAssertEqual(String(describing: testLogStorage), "[error][error]") expectation(forNotification: Notification.Name.PURBufferedOutputDidTryWriteChunk.rawValue, object: nil, handler: nil) // scheduled after 4sec waitForExpectations(timeout: 5.0, handler: nil) XCTAssertEqual(String(describing: testLogStorage), "[error][error][error]") expectation(forNotification: Notification.Name.PURBufferedOutputDidTryWriteChunk.rawValue, object: nil, handler: nil) // scheduled after 8sec waitForExpectations(timeout: 9.0, handler: nil) XCTAssertEqual(String(describing: testLogStorage), "[error][error][error][error]") } }
mit
bb152df9c38f818e8d877b8b82d00634
46.251232
175
0.67254
4.278323
false
true
false
false
AlexEdunov/Timecode
Timecode/Timecode.swift
1
4322
// // Timecode.swift // Timecode // // Created by Alex Edunov on 29/02/16. // Copyright ยฉ 2016 AlexEdunov. All rights reserved. // import UIKit enum Framerate: Double { case _23_976 = 23.976 case _23_98 = 23.98 case _24 = 24.0 case _29_97 = 29.97 case _30 = 30.0 } class Timecode: NSObject { var hour: Int = 0 var minute: Int = 0 var second: Int = 0 var frame: Int = 0 var framerate: Framerate = ._24 var miliseconds: Int { get { return Int(Double(self.absoluteFrame) / round(self.framerate.rawValue) * 1000); } } var absoluteFrame: Int { get { let framerate = round(self.framerate.rawValue); let frame = framerate * (Double(self.hour) * 3600 + Double(self.minute) * 60 + Double(self.second)) + Double(self.frame); if (self.isDropframe) { let totalMinutes = 60 * self.hour + self.minute; return Int(frame - 2 * (Double(totalMinutes) - floor(Double(totalMinutes) / 10))); } else { return Int(frame) } } set { self.frame = newValue } } var isDropframe: Bool { get { return (framerate == ._29_97) } } var string: String { get { let hourString = "\(self.hour.format("02"))" let minuteString = "\(self.minute.format("02"))" let secondString = "\(self.second.format("02"))" let framerateDelimeter = self.isDropframe ? ";" : ":" let frameString = "\(self.frame.format("02"))" return "\(hourString):\(minuteString):\(secondString)\(framerateDelimeter)\(frameString)" } } // MARK - func convertToFramerate(framerate outputFrame: Framerate!) -> Timecode { let inputFramerate = self.framerate if ((round(inputFramerate.rawValue) == 30 && (outputFrame.rawValue == round(outputFrame.rawValue)) && (outputFrame.rawValue == 24))) { return Timecode(absoluteFrame: threeTwoPullUp(self.absoluteFrame), framerate: outputFrame); } else if ((round(inputFramerate.rawValue) == 24 && (outputFrame.rawValue == round(outputFrame.rawValue)) && (outputFrame.rawValue == 30))) { return Timecode(absoluteFrame: threeTwoPullDown(self.absoluteFrame), framerate: outputFrame); } else { return Timecode(absoluteFrame: self.absoluteFrame, framerate: outputFrame); } } // MARK - required init(hour: Int, minute: Int, second: Int, frame: Int, framerate: Framerate) { super.init() self.hour = hour self.minute = minute self.second = second self.frame = frame self.framerate = (framerate == ._23_98) ? ._23_976 : framerate } convenience init(var absoluteFrame: Int, framerate: Framerate) { let roundFramerate = round(framerate.rawValue) if (framerate.rawValue == 29.97) { // The number of 10 minute inteverals let D = floor(Double(absoluteFrame) / ((600 * roundFramerate) - 18)); // The remaining minutes let M = Double(absoluteFrame) % ((600 * roundFramerate) - 18); // Add 18 frames for every 10 minutes, and 2 frames for every remaining minute absoluteFrame += Int(18.0 * D + 2.0 * floor((M - 2.0) / (60.0 * roundFramerate - 2.0))); } self.init( hour: Int(floor(floor(floor(Double(absoluteFrame) / roundFramerate) / 60) / 60) % 24), minute: Int(floor(floor(Double(absoluteFrame) / roundFramerate) / 60) % 60), second: Int(floor(Double(absoluteFrame) / roundFramerate) % 60), frame: Int(Double(absoluteFrame) % roundFramerate), framerate: framerate) } // MARK - Private private func threeTwoPullDown(frames: Int) -> Int { return Int(round(Double(frames) * 5/4)); } private func threeTwoPullUp(frames: Int) -> Int { return Int(round(Double(frames) * 4/5)); } }
mit
05b0b08af787e35669f0acf27815eb2b
31.488722
109
0.544781
3.924614
false
false
false
false
huangboju/Moots
Examples/UIScrollViewDemo/UIScrollViewDemo/Controllers/EmbedScrollView/ScrollingDecelerator.swift
1
6661
// // ScrollingDecelerator.swift // UIScrollViewDemo // // Created by ้ป„ๆธŠ on 2022/9/23. // Copyright ยฉ 2022 ไผฏ้ฉน ้ป„. All rights reserved. // import Foundation final class ScrollingDecelerator { weak var scrollView: UIScrollView? var scrollingAnimation: TimerAnimationProtocol? let threshold: CGFloat init(scrollView: UIScrollView) { self.scrollView = scrollView threshold = 0.1 } } // MARK: - ScrollingDeceleratorProtocol extension ScrollingDecelerator: ScrollingDeceleratorProtocol { func decelerate(by deceleration: ScrollingDeceleration) { guard let scrollView = scrollView else { return } let velocity = CGPoint(x: deceleration.velocity.x, y: deceleration.velocity.y * 1000 * threshold) scrollingAnimation = beginScrollAnimation(initialContentOffset: scrollView.contentOffset, initialVelocity: velocity, decelerationRate: deceleration.decelerationRate.rawValue) { [weak scrollView] point in guard let scrollView = scrollView else { return } if deceleration.velocity.y < 0 { scrollView.contentOffset.y = max(point.y, 0) } else { scrollView.contentOffset.y = max(0, min(point.y, scrollView.contentSize.height - scrollView.frame.height)) } } } func invalidateIfNeeded() { guard scrollView?.isUserInteracted == true else { return } scrollingAnimation?.invalidate() scrollingAnimation = nil } } // MARK: - Privates extension ScrollingDecelerator { private func beginScrollAnimation(initialContentOffset: CGPoint, initialVelocity: CGPoint, decelerationRate: CGFloat, animations: @escaping (CGPoint) -> Void) -> TimerAnimationProtocol { let timingParameters = ScrollTimingParameters(initialContentOffset: initialContentOffset, initialVelocity: initialVelocity, decelerationRate: decelerationRate, threshold: threshold) return TimerAnimation(duration: timingParameters.duration, animations: { progress in let point = timingParameters.point(at: progress * timingParameters.duration) animations(point) }) } } // MARK: - ScrollTimingParameters extension ScrollingDecelerator { struct ScrollTimingParameters { let initialContentOffset: CGPoint let initialVelocity: CGPoint let decelerationRate: CGFloat let threshold: CGFloat } } extension ScrollingDecelerator.ScrollTimingParameters { var duration: TimeInterval { guard decelerationRate < 1 && decelerationRate > 0 && initialVelocity.length != 0 else { return 0 } let dCoeff = 1000 * log(decelerationRate) return TimeInterval(log(-dCoeff * threshold / initialVelocity.length) / dCoeff) } func point(at time: TimeInterval) -> CGPoint { guard decelerationRate < 1 && decelerationRate > 0 && initialVelocity != .zero else { return .zero } let dCoeff = 1000 * log(decelerationRate) return initialContentOffset + (pow(decelerationRate, CGFloat(1000 * time)) - 1) / dCoeff * initialVelocity } } // MARK: - TimerAnimation extension ScrollingDecelerator { final class TimerAnimation { typealias Animations = (_ progress: Double) -> Void typealias Completion = (_ isFinished: Bool) -> Void weak var displayLink: CADisplayLink? private(set) var isRunning: Bool private let duration: TimeInterval private let animations: Animations private let completion: Completion? private let firstFrameTimestamp: CFTimeInterval init(duration: TimeInterval, animations: @escaping Animations, completion: Completion? = nil) { self.duration = duration self.animations = animations self.completion = completion firstFrameTimestamp = CACurrentMediaTime() isRunning = true let displayLink = CADisplayLink(target: self, selector: #selector(step)) displayLink.add(to: .main, forMode: .common) self.displayLink = displayLink } } } // MARK: - TimerAnimationProtocol extension ScrollingDecelerator.TimerAnimation: TimerAnimationProtocol { func invalidate() { guard isRunning else { return } isRunning = false stopDisplayLink() completion?(false) } } // MARK: - Privates extension ScrollingDecelerator.TimerAnimation { @objc private func step(displayLink: CADisplayLink) { guard isRunning else { return } let elapsed = CACurrentMediaTime() - firstFrameTimestamp if elapsed >= duration || duration == 0 { animations(1) isRunning = false stopDisplayLink() completion?(true) } else { animations(elapsed / duration) } } private func stopDisplayLink() { displayLink?.isPaused = true displayLink?.invalidate() displayLink = nil } } // MARK: - CGPoint private extension CGPoint { var length: CGFloat { return sqrt(x * x + y * y) } static func + (lhs: CGPoint, rhs: CGPoint) -> CGPoint { return CGPoint(x: lhs.x + rhs.x, y: lhs.y + rhs.y) } static func * (lhs: CGFloat, rhs: CGPoint) -> CGPoint { return CGPoint(x: lhs * rhs.x, y: lhs * rhs.y) } } final class ScrollingDeceleration { let velocity: CGPoint let decelerationRate: UIScrollView.DecelerationRate init(velocity: CGPoint, decelerationRate: UIScrollView.DecelerationRate) { self.velocity = velocity self.decelerationRate = decelerationRate } } // MARK: - Equatable extension ScrollingDeceleration: Equatable { static func == (lhs: ScrollingDeceleration, rhs: ScrollingDeceleration) -> Bool { return lhs.velocity == rhs.velocity && lhs.decelerationRate == rhs.decelerationRate } } // MARK: - ScrollingDeceleratorProtocol protocol ScrollingDeceleratorProtocol { func decelerate(by deceleration: ScrollingDeceleration) func invalidateIfNeeded() } // MARK: - TimerAnimationProtocol protocol TimerAnimationProtocol { func invalidate() } // MARK: - UIScrollView extension UIScrollView { // Indicates that the scrolling is caused by user. var isUserInteracted: Bool { return isTracking || isDragging || isDecelerating } }
mit
6651e6b45897180bfae2df671f4f4bfa
32.417085
211
0.645263
5.227987
false
false
false
false
dxdp/Stage
Stage/PropertyBindings/UISwitchBindings.swift
1
3669
// // UISwitchBindings.swift // Stage // // Copyright ยฉ 2016 David Parton // // 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 extension StageRegister { public class func Switch(_ registration: StagePropertyRegistration) { tap(registration) { $0.registerBool("on") .apply { (view: UISwitch, value) in view.isOn = value } // Images $0.register("onImage") { scanner in scanner.string.trimmed() } .apply { (view: UISwitch, value) in guard let url = URL(string: value) else { view.onImage = UIImage(named: value) return } let task = URLSession.shared.dataTask(with: URLRequest(url: url), completionHandler: { [weak view] data, _, _ in if let data = data { view?.onImage = UIImage(data: data, scale: 0) } }) task.resume() view.onDeallocation { [weak task] in if let state = task?.state , state == .suspended || state == .running { task?.cancel() } } } $0.register("offImage") { scanner in scanner.string.trimmed() } .apply { (view: UISwitch, value) in guard let url = URL(string: value) else { view.offImage = UIImage(named: value) return } let task = URLSession.shared.dataTask(with: URLRequest(url: url), completionHandler: { [weak view] data, response, error in if let data = data { view?.offImage = UIImage(data: data, scale: 0) } }) task.resume() view.onDeallocation { [weak task] in if let state = task?.state , state == .suspended || state == .running { task?.cancel() } } } // Tint Colors $0.registerColor("tintColor") .apply { (view: UISwitch, value) in view.tintColor = value } $0.registerColor("onTintColor") .apply { (view: UISwitch, value) in view.onTintColor = value } $0.registerColor("thumbTintColor") .apply { (view: UISwitch, value) in view.thumbTintColor = value } } } }
mit
10e0b218c409bf9ae5fa4132dc3f2205
46.636364
143
0.54253
4.976934
false
false
false
false
KiranJasvanee/OnlyPictures
Local_images_Example/OnlyPictures/ViewController.swift
1
5943
// // ViewController.swift // OnlyPictures // // Created by Kiran Jasvanee on 10/02/2017. // Copyright (c) 2017 Kiran Jasvanee. All rights reserved. // import UIKit import OnlyPictures class ViewController: UIViewController { @IBOutlet weak var onlyPictures: OnlyHorizontalPictures! //var pictures: [UIImage] = [#imageLiteral(resourceName: "p1"),#imageLiteral(resourceName: "p2"),#imageLiteral(resourceName: "p3"),#imageLiteral(resourceName: "p4"),#imageLiteral(resourceName: "p5"), UIImage(),#imageLiteral(resourceName: "p6"),#imageLiteral(resourceName: "p7"),#imageLiteral(resourceName: "p8"),#imageLiteral(resourceName: "p9"),#imageLiteral(resourceName: "p10"),#imageLiteral(resourceName: "p11"),#imageLiteral(resourceName: "p12"),#imageLiteral(resourceName: "p13"),#imageLiteral(resourceName: "p14"),#imageLiteral(resourceName: "p15")] var pictures: [UIImage] = [#imageLiteral(resourceName: "p1"),#imageLiteral(resourceName: "p2"),#imageLiteral(resourceName: "p3"),#imageLiteral(resourceName: "p4"),#imageLiteral(resourceName: "p5"),#imageLiteral(resourceName: "p6"),#imageLiteral(resourceName: "p7"),#imageLiteral(resourceName: "p8"),#imageLiteral(resourceName: "p9"),#imageLiteral(resourceName: "p10"),#imageLiteral(resourceName: "p11"),#imageLiteral(resourceName: "p12"),#imageLiteral(resourceName: "p13"),#imageLiteral(resourceName: "p14"),#imageLiteral(resourceName: "p15")] override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. onlyPictures.layer.cornerRadius = 20.0 onlyPictures.layer.masksToBounds = true onlyPictures.dataSource = self onlyPictures.delegate = self onlyPictures.order = .descending onlyPictures.alignment = .center onlyPictures.countPosition = .right onlyPictures.recentAt = .left onlyPictures.spacingColor = UIColor.white onlyPictures.backgroundColorForCount = .red onlyPictures.defaultPicture = #imageLiteral(resourceName: "defaultProfilePicture") onlyPictures.backgroundColorForCount = UIColor.init(red: 230/255, green: 230/255, blue: 230/255, alpha: 1.0) onlyPictures.textColorForCount = .red onlyPictures.fontForCount = UIFont(name: "HelveticaNeue", size: 18)! } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func addMoreWithReloadActionListener(_ sender: Any) { pictures.append(#imageLiteral(resourceName: "p7")) pictures.append(#imageLiteral(resourceName: "p8")) pictures.append(#imageLiteral(resourceName: "p9")) pictures.append(#imageLiteral(resourceName: "p10")) pictures.append(#imageLiteral(resourceName: "p11")) pictures.append(#imageLiteral(resourceName: "p12")) pictures.append(#imageLiteral(resourceName: "p13")) pictures.append(#imageLiteral(resourceName: "p14")) self.onlyPictures.reloadData() } @IBAction func insertAtFirstActionListener(_ sender: Any) { onlyPictures.insertFirst(image: #imageLiteral(resourceName: "p11"), withAnimation: .popup) pictures.append(#imageLiteral(resourceName: "p12")) } @IBAction func insertLastActionListener(_ sender: Any) { pictures.append(#imageLiteral(resourceName: "p12")) onlyPictures.insertLast(image: #imageLiteral(resourceName: "p12"), withAnimation: .popup) } @IBAction func insertAt2ndPositionActionListener(_ sender: Any) { pictures.insert(#imageLiteral(resourceName: "p13"), at: 2) onlyPictures.insertPicture(#imageLiteral(resourceName: "p13"), atIndex: 2, withAnimation: .popup) } @IBAction func removeFirstActionListener(_ sender: Any) { onlyPictures.removeFirst(withAnimation: .popdown) pictures.removeFirst() // Please do remove operations after does similar operations inside onlyPictures. } @IBAction func removeLastActionListener(_ sender: Any) { onlyPictures.removeLast(withAnimation: .popdown) pictures.removeLast() // Please do remove operations after does similar operations inside onlyPictures. } @IBAction func removeAt2ndPositionActionListener(_ sender: Any) { onlyPictures.removePicture(atIndex: 2, withAnimation: .popdown) pictures.remove(at: 2) // Please do remove operations after does similar operations inside onlyPictures. } } extension ViewController: OnlyPicturesDataSource { func numberOfPictures() -> Int { return self.pictures.count } func visiblePictures() -> Int { return 6 } func pictureViews(index: Int) -> UIImage { return self.pictures[index] } } extension ViewController: OnlyPicturesDelegate { // --------------------------------------------------- // receive an action of selected picture tap index func pictureView(_ imageView: UIImageView, didSelectAt index: Int) { print("Selected index: \(index)") } // --------------------------------------------------- // receive an action of tap upon count func pictureViewCountDidSelect() { print("Tap on count") } // --------------------------------------------------- // receive a count, incase you want to do additionally things with it. // even if your requirement is to hide count and handle it externally with below fuction, you can hide it using property `isVisibleCount = true`. func pictureViewCount(value: Int) { print("count value: \(value)") } // --------------------------------------------------- // receive an action, whem tap occures anywhere in OnlyPicture view. func pictureViewDidSelect() { print("tap on picture view") } }
mit
d7761f25c9ee9a3d09bef93ffba417ed
44.366412
561
0.664816
4.606977
false
false
false
false
sjtu-meow/iOS
Meow/LoginUtils.swift
1
1291
// // LoginUtils.swift // Meow // // Copyright ยฉ 2017ๅนด ๅ–ตๅ–ตๅ–ต็š„ไผ™ไผด. All rights reserved. // import RxSwift import PKHUD class UserManager { open static var shared = UserManager() let disposeBag = DisposeBag() var currentUser: Profile? @discardableResult func login(phone: String, password: String, cont: (()->())? = nil) -> Observable<Profile> { let observable = MeowAPIProvider.shared .request(.login(phone: phone, password: password)) .mapTo(type: Token.self) .flatMap { token -> Observable<Any> in token.save() MeowAPIProvider.refresh() return MeowAPIProvider.shared.request(.myProfile) } .mapTo(type: Profile.self) observable.subscribe(onNext: { profile in UserManager.shared.currentUser = profile ChatManager.didLoginSuccess(withClientId: "\(profile.userId!)") if let cont = cont { cont() } }, onError: { e in HUD.flash(.labeledError(title: "็”จๆˆทๅๆˆ–ๅฏ†็ ้”™่ฏฏ", subtitle: nil), delay: 1) }).addDisposableTo(disposeBag) return observable } }
apache-2.0
fad4b9250c9658ea47c3fcf0ed3ab125
26.391304
95
0.550794
4.736842
false
false
false
false
bitomule/ReactiveSwiftRealm
Carthage/Checkouts/realm-cocoa/RealmSwift/Tests/ObjectCreationTests.swift
1
26896
//////////////////////////////////////////////////////////////////////////// // // Copyright 2015 Realm Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////// import XCTest import Realm.Private import RealmSwift import Foundation class ObjectCreationTests: TestCase { // MARK: Init tests func testInitWithDefaults() { // test all properties are defaults let object = SwiftObject() XCTAssertNil(object.realm) // test defaults values verifySwiftObjectWithDictionaryLiteral(object, dictionary: SwiftObject.defaultValues(), boolObjectValue: false, boolObjectListValues: []) // test realm properties are nil for standalone XCTAssertNil(object.realm) XCTAssertNil(object.objectCol!.realm) XCTAssertNil(object.arrayCol.realm) } func testInitWithOptionalWithoutDefaults() { let object = SwiftOptionalObject() for prop in object.objectSchema.properties { let value = object[prop.name] if let value = value as? RLMOptionalBase { XCTAssertNil(value.underlyingValue) } else { XCTAssertNil(value) } } } func testInitWithOptionalDefaults() { let object = SwiftOptionalDefaultValuesObject() verifySwiftOptionalObjectWithDictionaryLiteral(object, dictionary: SwiftOptionalDefaultValuesObject.defaultValues(), boolObjectValue: true) } func testInitWithDictionary() { // dictionary with all values specified let baselineValues: [String: Any] = ["boolCol": true, "intCol": 1, "floatCol": 1.1 as Float, "doubleCol": 11.1, "stringCol": "b", "binaryCol": "b".data(using: String.Encoding.utf8)!, "dateCol": Date(timeIntervalSince1970: 2), "objectCol": SwiftBoolObject(value: [true]), "arrayCol": [SwiftBoolObject(value: [true]), SwiftBoolObject()] ] // test with valid dictionary literals let props = try! Realm().schema["SwiftObject"]!.properties for propNum in 0..<props.count { for validValue in validValuesForSwiftObjectType(props[propNum].type) { // update dict with valid value and init var values = baselineValues values[props[propNum].name] = validValue let object = SwiftObject(value: values) verifySwiftObjectWithDictionaryLiteral(object, dictionary: values, boolObjectValue: true, boolObjectListValues: [true, false]) } } // test with invalid dictionary literals for propNum in 0..<props.count { for invalidValue in invalidValuesForSwiftObjectType(props[propNum].type) { // update dict with invalid value and init var values = baselineValues values[props[propNum].name] = invalidValue assertThrows(SwiftObject(value: values), "Invalid property value") } } } func testInitWithDefaultsAndDictionary() { // test with dictionary with mix of default and one specified value let object = SwiftObject(value: ["intCol": 200]) let valueDict = defaultSwiftObjectValuesWithReplacements(["intCol": 200]) verifySwiftObjectWithDictionaryLiteral(object, dictionary: valueDict, boolObjectValue: false, boolObjectListValues: []) } func testInitWithArray() { // array with all values specified let baselineValues: [Any] = [true, 1, 1.1 as Float, 11.1, "b", "b".data(using: String.Encoding.utf8)!, Date(timeIntervalSince1970: 2), ["boolCol": true], [[true], [false]]] // test with valid dictionary literals let props = try! Realm().schema["SwiftObject"]!.properties for propNum in 0..<props.count { for validValue in validValuesForSwiftObjectType(props[propNum].type) { // update dict with valid value and init var values = baselineValues values[propNum] = validValue let object = SwiftObject(value: values) verifySwiftObjectWithArrayLiteral(object, array: values, boolObjectValue: true, boolObjectListValues: [true, false]) } } // test with invalid dictionary literals for propNum in 0..<props.count { for invalidValue in invalidValuesForSwiftObjectType(props[propNum].type) { // update dict with invalid value and init var values = baselineValues values[propNum] = invalidValue assertThrows(SwiftObject(value: values), "Invalid property value") } } } func testInitWithKVCObject() { // test with kvc object let objectWithInt = SwiftObject(value: ["intCol": 200]) let objectWithKVCObject = SwiftObject(value: objectWithInt) let valueDict = defaultSwiftObjectValuesWithReplacements(["intCol": 200]) verifySwiftObjectWithDictionaryLiteral(objectWithKVCObject, dictionary: valueDict, boolObjectValue: false, boolObjectListValues: []) } func testGenericInit() { func createObject<T: Object>() -> T { return T() } let obj1: SwiftBoolObject = createObject() let obj2 = SwiftBoolObject() XCTAssertEqual(obj1.boolCol, obj2.boolCol, "object created via generic initializer should equal object created by calling initializer directly") } // MARK: Creation tests func testCreateWithDefaults() { let realm = try! Realm() assertThrows(realm.create(SwiftObject.self), "Must be in write transaction") var object: SwiftObject! let objects = realm.objects(SwiftObject.self) XCTAssertEqual(0, objects.count) try! realm.write { // test create with all defaults object = realm.create(SwiftObject.self) return } verifySwiftObjectWithDictionaryLiteral(object, dictionary: SwiftObject.defaultValues(), boolObjectValue: false, boolObjectListValues: []) // test realm properties are populated correctly XCTAssertEqual(object.realm!, realm) XCTAssertEqual(object.objectCol!.realm!, realm) XCTAssertEqual(object.arrayCol.realm!, realm) } func testCreateWithOptionalWithoutDefaults() { let realm = try! Realm() try! realm.write { let object = realm.create(SwiftOptionalObject.self) for prop in object.objectSchema.properties { XCTAssertNil(object[prop.name]) } } } func testCreateWithOptionalDefaults() { let realm = try! Realm() try! realm.write { let object = realm.create(SwiftOptionalDefaultValuesObject.self) self.verifySwiftOptionalObjectWithDictionaryLiteral(object, dictionary: SwiftOptionalDefaultValuesObject.defaultValues(), boolObjectValue: true) } } func testCreateWithOptionalIgnoredProperties() { let realm = try! Realm() try! realm.write { let object = realm.create(SwiftOptionalIgnoredPropertiesObject.self) let properties = object.objectSchema.properties XCTAssertEqual(properties.count, 1) XCTAssertEqual(properties[0].name, "id") } } func testCreateWithDictionary() { // dictionary with all values specified let baselineValues: [String: Any] = [ "boolCol": true, "intCol": 1, "floatCol": 1.1 as Float, "doubleCol": 11.1, "stringCol": "b", "binaryCol": "b".data(using: String.Encoding.utf8)!, "dateCol": Date(timeIntervalSince1970: 2), "objectCol": SwiftBoolObject(value: [true]), "arrayCol": [SwiftBoolObject(value: [true]), SwiftBoolObject()] ] // test with valid dictionary literals let props = try! Realm().schema["SwiftObject"]!.properties for propNum in 0..<props.count { for validValue in validValuesForSwiftObjectType(props[propNum].type) { // update dict with valid value and init var values = baselineValues values[props[propNum].name] = validValue try! Realm().beginWrite() let object = try! Realm().create(SwiftObject.self, value: values) verifySwiftObjectWithDictionaryLiteral(object, dictionary: values, boolObjectValue: true, boolObjectListValues: [true, false]) try! Realm().commitWrite() verifySwiftObjectWithDictionaryLiteral(object, dictionary: values, boolObjectValue: true, boolObjectListValues: [true, false]) } } // test with invalid dictionary literals for propNum in 0..<props.count { for invalidValue in invalidValuesForSwiftObjectType(props[propNum].type) { // update dict with invalid value and init var values = baselineValues values[props[propNum].name] = invalidValue try! Realm().beginWrite() assertThrows(try! Realm().create(SwiftObject.self, value: values), "Invalid property value") try! Realm().cancelWrite() } } } func testCreateWithDefaultsAndDictionary() { // test with dictionary with mix of default and one specified value let realm = try! Realm() realm.beginWrite() let objectWithInt = realm.create(SwiftObject.self, value: ["intCol": 200]) try! realm.commitWrite() let valueDict = defaultSwiftObjectValuesWithReplacements(["intCol": 200]) verifySwiftObjectWithDictionaryLiteral(objectWithInt, dictionary: valueDict, boolObjectValue: false, boolObjectListValues: []) } func testCreateWithArray() { // array with all values specified let baselineValues: [Any] = [true, 1, 1.1 as Float, 11.1, "b", "b".data(using: String.Encoding.utf8)!, Date(timeIntervalSince1970: 2), ["boolCol": true], [[true], [false]]] // test with valid dictionary literals let props = try! Realm().schema["SwiftObject"]!.properties for propNum in 0..<props.count { for validValue in validValuesForSwiftObjectType(props[propNum].type) { // update dict with valid value and init var values = baselineValues values[propNum] = validValue try! Realm().beginWrite() let object = try! Realm().create(SwiftObject.self, value: values) verifySwiftObjectWithArrayLiteral(object, array: values, boolObjectValue: true, boolObjectListValues: [true, false]) try! Realm().commitWrite() verifySwiftObjectWithArrayLiteral(object, array: values, boolObjectValue: true, boolObjectListValues: [true, false]) } } // test with invalid array literals for propNum in 0..<props.count { for invalidValue in invalidValuesForSwiftObjectType(props[propNum].type) { // update dict with invalid value and init var values = baselineValues values[propNum] = invalidValue try! Realm().beginWrite() assertThrows(try! Realm().create(SwiftObject.self, value: values), "Invalid property value '\(invalidValue)' for property number \(propNum)") try! Realm().cancelWrite() } } } func testCreateWithKVCObject() { // test with kvc object try! Realm().beginWrite() let objectWithInt = try! Realm().create(SwiftObject.self, value: ["intCol": 200]) let objectWithKVCObject = try! Realm().create(SwiftObject.self, value: objectWithInt) let valueDict = defaultSwiftObjectValuesWithReplacements(["intCol": 200]) try! Realm().commitWrite() verifySwiftObjectWithDictionaryLiteral(objectWithKVCObject, dictionary: valueDict, boolObjectValue: false, boolObjectListValues: []) XCTAssertEqual(try! Realm().objects(SwiftObject.self).count, 2, "Object should have been copied") } func testCreateWithNestedObjects() { let standalone = SwiftPrimaryStringObject(value: ["p0", 11]) try! Realm().beginWrite() let objectWithNestedObjects = try! Realm().create(SwiftLinkToPrimaryStringObject.self, value: ["p1", ["p1", 11], [standalone]]) try! Realm().commitWrite() let stringObjects = try! Realm().objects(SwiftPrimaryStringObject.self) XCTAssertEqual(stringObjects.count, 2) let persistedObject = stringObjects.first! // standalone object should be copied into the realm, not added directly XCTAssertNotEqual(standalone, persistedObject) XCTAssertEqual(objectWithNestedObjects.object!, persistedObject) XCTAssertEqual(objectWithNestedObjects.objects.first!, stringObjects.last!) let standalone1 = SwiftPrimaryStringObject(value: ["p3", 11]) try! Realm().beginWrite() assertThrows(try! Realm().create(SwiftLinkToPrimaryStringObject.self, value: ["p3", ["p3", 11], [standalone1]]), "Should throw with duplicate primary key") try! Realm().commitWrite() } func testUpdateWithNestedObjects() { let standalone = SwiftPrimaryStringObject(value: ["primary", 11]) try! Realm().beginWrite() let object = try! Realm().create(SwiftLinkToPrimaryStringObject.self, value: ["otherPrimary", ["primary", 12], [["primary", 12]]], update: true) try! Realm().commitWrite() let stringObjects = try! Realm().objects(SwiftPrimaryStringObject.self) XCTAssertEqual(stringObjects.count, 1) let persistedObject = object.object! XCTAssertEqual(persistedObject.intCol, 12) XCTAssertNil(standalone.realm) // the standalone object should be copied, rather than added, to the realm XCTAssertEqual(object.object!, persistedObject) XCTAssertEqual(object.objects.first!, persistedObject) } func testCreateWithObjectsFromAnotherRealm() { let values: [String: Any] = [ "boolCol": true, "intCol": 1, "floatCol": 1.1 as Float, "doubleCol": 11.1, "stringCol": "b", "binaryCol": "b".data(using: String.Encoding.utf8)!, "dateCol": Date(timeIntervalSince1970: 2), "objectCol": SwiftBoolObject(value: [true]), "arrayCol": [SwiftBoolObject(value: [true]), SwiftBoolObject()] ] realmWithTestPath().beginWrite() let otherRealmObject = realmWithTestPath().create(SwiftObject.self, value: values) try! realmWithTestPath().commitWrite() try! Realm().beginWrite() let object = try! Realm().create(SwiftObject.self, value: otherRealmObject) try! Realm().commitWrite() XCTAssertNotEqual(otherRealmObject, object) verifySwiftObjectWithDictionaryLiteral(object, dictionary: values, boolObjectValue: true, boolObjectListValues: [true, false]) } func testCreateWithDeeplyNestedObjectsFromAnotherRealm() { let values: [String: Any] = [ "boolCol": true, "intCol": 1, "floatCol": 1.1 as Float, "doubleCol": 11.1, "stringCol": "b", "binaryCol": "b".data(using: String.Encoding.utf8)!, "dateCol": Date(timeIntervalSince1970: 2), "objectCol": SwiftBoolObject(value: [true]), "arrayCol": [SwiftBoolObject(value: [true]), SwiftBoolObject()] ] let realmA = realmWithTestPath() let realmB = try! Realm() var realmAObject: SwiftListOfSwiftObject! try! realmA.write { let array = [SwiftObject(value: values), SwiftObject(value: values)] realmAObject = realmA.create(SwiftListOfSwiftObject.self, value: ["array": array]) } var realmBObject: SwiftListOfSwiftObject! try! realmB.write { realmBObject = realmB.create(SwiftListOfSwiftObject.self, value: realmAObject) } XCTAssertNotEqual(realmAObject, realmBObject) XCTAssertEqual(realmBObject.array.count, 2) for swiftObject in realmBObject.array { verifySwiftObjectWithDictionaryLiteral(swiftObject, dictionary: values, boolObjectValue: true, boolObjectListValues: [true, false]) } } func testUpdateWithObjectsFromAnotherRealm() { realmWithTestPath().beginWrite() let otherRealmObject = realmWithTestPath().create(SwiftLinkToPrimaryStringObject.self, value: ["primary", NSNull(), [["2", 2], ["4", 4]]]) try! realmWithTestPath().commitWrite() try! Realm().beginWrite() try! Realm().create(SwiftLinkToPrimaryStringObject.self, value: ["primary", ["10", 10], [["11", 11]]]) let object = try! Realm().create(SwiftLinkToPrimaryStringObject.self, value: otherRealmObject, update: true) try! Realm().commitWrite() XCTAssertNotEqual(otherRealmObject, object) // the object from the other realm should be copied into this realm XCTAssertEqual(try! Realm().objects(SwiftLinkToPrimaryStringObject.self).count, 1) XCTAssertEqual(try! Realm().objects(SwiftPrimaryStringObject.self).count, 4) } func testCreateWithNSNullLinks() { let values: [String: Any] = [ "boolCol": true, "intCol": 1, "floatCol": 1.1, "doubleCol": 11.1, "stringCol": "b", "binaryCol": "b".data(using: String.Encoding.utf8)!, "dateCol": Date(timeIntervalSince1970: 2), "objectCol": NSNull(), "arrayCol": NSNull() ] realmWithTestPath().beginWrite() let object = realmWithTestPath().create(SwiftObject.self, value: values) try! realmWithTestPath().commitWrite() XCTAssert(object.objectCol == nil) // XCTAssertNil caused a NULL deref inside _swift_getClass XCTAssertEqual(object.arrayCol.count, 0) } // test null object // test null list // MARK: Add tests func testAddWithExisingNestedObjects() { try! Realm().beginWrite() let existingObject = try! Realm().create(SwiftBoolObject.self) try! Realm().commitWrite() try! Realm().beginWrite() let object = SwiftObject(value: ["objectCol": existingObject]) try! Realm().add(object) try! Realm().commitWrite() XCTAssertNotNil(object.realm) XCTAssertEqual(object.objectCol, existingObject) } func testAddAndUpdateWithExisingNestedObjects() { try! Realm().beginWrite() let existingObject = try! Realm().create(SwiftPrimaryStringObject.self, value: ["primary", 1]) try! Realm().commitWrite() try! Realm().beginWrite() let object = SwiftLinkToPrimaryStringObject(value: ["primary", ["primary", 2], []]) try! Realm().add(object, update: true) try! Realm().commitWrite() XCTAssertNotNil(object.realm) XCTAssertEqual(object.object!, existingObject) // the existing object should be updated XCTAssertEqual(existingObject.intCol, 2) } // MARK: Private utilities private func verifySwiftObjectWithArrayLiteral(_ object: SwiftObject, array: [Any], boolObjectValue: Bool, boolObjectListValues: [Bool]) { XCTAssertEqual(object.boolCol, (array[0] as! Bool)) XCTAssertEqual(object.intCol, (array[1] as! Int)) XCTAssertEqual(object.floatCol, (array[2] as! Float)) XCTAssertEqual(object.doubleCol, (array[3] as! Double)) XCTAssertEqual(object.stringCol, (array[4] as! String)) XCTAssertEqual(object.binaryCol, (array[5] as! Data)) XCTAssertEqual(object.dateCol, (array[6] as! Date)) XCTAssertEqual(object.objectCol!.boolCol, boolObjectValue) XCTAssertEqual(object.arrayCol.count, boolObjectListValues.count) for i in 0..<boolObjectListValues.count { XCTAssertEqual(object.arrayCol[i].boolCol, boolObjectListValues[i]) } } private func verifySwiftObjectWithDictionaryLiteral(_ object: SwiftObject, dictionary: [String: Any], boolObjectValue: Bool, boolObjectListValues: [Bool]) { XCTAssertEqual(object.boolCol, (dictionary["boolCol"] as! Bool)) XCTAssertEqual(object.intCol, (dictionary["intCol"] as! Int)) XCTAssertEqual(object.floatCol, (dictionary["floatCol"] as! Float)) XCTAssertEqual(object.doubleCol, (dictionary["doubleCol"] as! Double)) XCTAssertEqual(object.stringCol, (dictionary["stringCol"] as! String)) XCTAssertEqual(object.binaryCol, (dictionary["binaryCol"] as! Data)) XCTAssertEqual(object.dateCol, (dictionary["dateCol"] as! Date)) XCTAssertEqual(object.objectCol!.boolCol, boolObjectValue) XCTAssertEqual(object.arrayCol.count, boolObjectListValues.count) for i in 0..<boolObjectListValues.count { XCTAssertEqual(object.arrayCol[i].boolCol, boolObjectListValues[i]) } } private func verifySwiftOptionalObjectWithDictionaryLiteral(_ object: SwiftOptionalDefaultValuesObject, dictionary: [String: Any], boolObjectValue: Bool?) { XCTAssertEqual(object.optBoolCol.value, (dictionary["optBoolCol"] as! Bool?)) XCTAssertEqual(object.optIntCol.value, (dictionary["optIntCol"] as! Int?)) XCTAssertEqual(object.optInt8Col.value, ((dictionary["optInt8Col"] as! NSNumber?)?.int8Value).map({Int8($0)})) XCTAssertEqual(object.optInt16Col.value, ((dictionary["optInt16Col"] as! NSNumber?)?.int16Value).map({Int16($0)})) XCTAssertEqual(object.optInt32Col.value, ((dictionary["optInt32Col"] as! NSNumber?)?.int32Value).map({Int32($0)})) XCTAssertEqual(object.optInt64Col.value, (dictionary["optInt64Col"] as! NSNumber?)?.int64Value) XCTAssertEqual(object.optFloatCol.value, (dictionary["optFloatCol"] as! Float?)) XCTAssertEqual(object.optDoubleCol.value, (dictionary["optDoubleCol"] as! Double?)) XCTAssertEqual(object.optStringCol, (dictionary["optStringCol"] as! String?)) XCTAssertEqual(object.optNSStringCol, (dictionary["optNSStringCol"] as! NSString)) XCTAssertEqual(object.optBinaryCol, (dictionary["optBinaryCol"] as! Data?)) XCTAssertEqual(object.optDateCol, (dictionary["optDateCol"] as! Date?)) XCTAssertEqual(object.optObjectCol?.boolCol, boolObjectValue) } private func defaultSwiftObjectValuesWithReplacements(_ replace: [String: Any]) -> [String: Any] { var valueDict = SwiftObject.defaultValues() for (key, value) in replace { valueDict[key] = value } return valueDict } // return an array of valid values that can be used to initialize each type // swiftlint:disable:next cyclomatic_complexity private func validValuesForSwiftObjectType(_ type: PropertyType) -> [Any] { try! Realm().beginWrite() let persistedObject = try! Realm().create(SwiftBoolObject.self, value: [true]) try! Realm().commitWrite() switch type { case .bool: return [true, NSNumber(value: 0 as Int), NSNumber(value: 1 as Int)] case .int: return [NSNumber(value: 1 as Int)] case .float: return [NSNumber(value: 1 as Int), NSNumber(value: 1.1 as Float), NSNumber(value: 11.1 as Double)] case .double: return [NSNumber(value: 1 as Int), NSNumber(value: 1.1 as Float), NSNumber(value: 11.1 as Double)] case .string: return ["b"] case .data: return ["b".data(using: String.Encoding.utf8, allowLossyConversion: false)!] case .date: return [Date(timeIntervalSince1970: 2)] case .object: return [[true], ["boolCol": true], SwiftBoolObject(value: [true]), persistedObject] case .array: return [ [[true], [false]], [["boolCol": true], ["boolCol": false]], [SwiftBoolObject(value: [true]), SwiftBoolObject(value: [false])], [persistedObject, [false]] ] case .any: XCTFail("not supported") case .linkingObjects: XCTFail("not supported") } return [] } // swiftlint:disable:next cyclomatic_complexity private func invalidValuesForSwiftObjectType(_ type: PropertyType) -> [Any] { try! Realm().beginWrite() let persistedObject = try! Realm().create(SwiftIntObject.self) try! Realm().commitWrite() switch type { case .bool: return ["invalid", NSNumber(value: 2 as Int), NSNumber(value: 1.1 as Float), NSNumber(value: 11.1 as Double)] case .int: return ["invalid", NSNumber(value: 1.1 as Float), NSNumber(value: 11.1 as Double)] case .float: return ["invalid", true, false] case .double: return ["invalid", true, false] case .string: return [0x197A71D, true, false] case .data: return ["invalid"] case .date: return ["invalid"] case .object: return ["invalid", ["a"], ["boolCol": "a"], SwiftIntObject()] case .array: return ["invalid", [["a"]], [["boolCol": "a"]], [[SwiftIntObject()]], [[persistedObject]]] case .any: XCTFail("not supported") case .linkingObjects: XCTFail("not supported") } return [] } }
mit
24af042507606c10467952671014d958
44.203361
137
0.619386
5.355635
false
true
false
false
yaobanglin/viossvc
viossvc/General/Extension/UIViewController+Extension.swift
1
7422
// // UIViewController+Extension.swift // viossvc // // Created by yaowang on 2016/10/31. // Copyright ยฉ 2016ๅนด ywwlcom.yundian. All rights reserved. // import Foundation import XCGLogger import SVProgressHUD import Qiniu extension UIViewController { static func storyboardViewController<T:UIViewController>(storyboard:UIStoryboard) ->T { return storyboard.instantiateViewControllerWithIdentifier(T.className()) as! T; } func storyboardViewController<T:UIViewController>() ->T { return storyboard!.instantiateViewControllerWithIdentifier(T.className()) as! T; } func errorBlockFunc()->ErrorBlock { return { [weak self] (error) in XCGLogger.error("\(error) \(self)") self?.didRequestError(error) } } func didRequestError(error:NSError) { self.showErrorWithStatus(error.localizedDescription) } func showErrorWithStatus(status: String!) { SVProgressHUD.showErrorWithStatus(status) } func showWithStatus(status: String!) { SVProgressHUD.showWithStatus(status) } //MARK: -Common function func checkTextFieldEmpty(array:[UITextField]) -> Bool { for textField in array { if NSString.isEmpty(textField.text) { showErrorWithStatus(textField.placeholder); return false } } return true } func dismissController() { view.endEditing(true) dismissViewControllerAnimated(true, completion: nil) } //ๆŸฅ่ฏข็”จๆˆทไฝ™้ข func requestUserCash(complete: CompleteBlock) { AppAPIHelper.userAPI().userCash(CurrentUserHelper.shared.userInfo.uid, complete: { (result) in if result == nil{ return } let resultDic = result as? Dictionary<String, AnyObject> if let hasPassword = resultDic!["has_passwd_"] as? Int{ CurrentUserHelper.shared.userInfo.has_passwd_ = hasPassword } if let userCash = resultDic!["user_cash_"] as? Int{ CurrentUserHelper.shared.userInfo.user_cash_ = userCash complete(userCash) } }, error: errorBlockFunc()) } /** ๆŸฅ่ฏข่ฎค่ฏ็Šถๆ€ */ func checkAuthStatus() { AppAPIHelper.userAPI().anthStatus(CurrentUserHelper.shared.userInfo.uid, complete: { (result) in if let errorReason = result?.valueForKey("failed_reason_") as? String { if errorReason.characters.count != 0 { SVProgressHUD.showErrorMessage(ErrorMessage: errorReason, ForDuration: 1, completion: nil) } } if let status = result?.valueForKey("review_status_") as? Int { CurrentUserHelper.shared.userInfo.auth_status_ = status } }, error: errorBlockFunc()) } /** ไธƒ็‰›ไธŠไผ ๅ›พ็‰‡ - parameter image: ๅ›พ็‰‡ - parameter imageName: ๅ›พ็‰‡ๅ - parameter complete: ๅ›พ็‰‡ๅฎŒๆˆBlock */ func qiniuUploadImage(image: UIImage, imageName: String, complete:CompleteBlock) { //0,ๅฐ†ๅ›พ็‰‡ๅญ˜ๅˆฐๆฒ™็›’ไธญ let filePath = cacheImage(image, imageName: imageName) //1,่ฏทๆฑ‚token AppAPIHelper.commenAPI().imageToken({ (result) in let token = result?.valueForKey("img_token_") as! String //2,ไธŠไผ ๅ›พ็‰‡ let timestamp = NSDate().timeIntervalSince1970 let key = "\(imageName)\(timestamp).png" let qiniuManager = QNUploadManager() qiniuManager.putFile(filePath, key: key, token: token, complete: { (info, key, resp) in if resp == nil{ complete(nil) return } //3,่ฟ”ๅ›žURL let respDic: NSDictionary? = resp let value:String? = respDic!.valueForKey("key") as? String let imageUrl = AppConst.Network.qiniuHost+value! complete(imageUrl) }, option: nil) }, error: errorBlockFunc()) } /** ไธƒ็‰›ไธŠไผ ๅ›พ็‰‡ - parameter image: ๅ›พ็‰‡ - parameter imagePath: ๅ›พ็‰‡ๆœๅŠกๅ™จ่ทฏๅพ„ - parameter imageName: ๅ›พ็‰‡ๅ - parameter tags: ๅ›พ็‰‡ๆ ‡่ฎฐ - parameter complete: ๅ›พ็‰‡ๅฎŒๆˆBlock */ func qiniuUploadImage(image: UIImage, imagePath: String, imageName:String, tags:[String: AnyObject], complete:CompleteBlock) { let timestemp = NSDate().timeIntervalSince1970 let timeStr = String.init(timestemp).stringByReplacingOccurrencesOfString(".", withString: "") //0,ๅฐ†ๅ›พ็‰‡ๅญ˜ๅˆฐๆฒ™็›’ไธญ let filePath = cacheImage(image, imageName: "/tmp_" + timeStr) //1,่ฏทๆฑ‚token AppAPIHelper.commenAPI().imageToken({ (result) in let token = result?.valueForKey("img_token_") as! String //2,ไธŠไผ ๅ›พ็‰‡ let qiniuManager = QNUploadManager() qiniuManager.putFile(filePath, key: imagePath + imageName + "_\(timeStr)", token: token, complete: { (info, key, resp) in try! NSFileManager.defaultManager().removeItemAtPath(filePath) if resp == nil{ NSLog(info.debugDescription) complete([tags, "failed"]) return } //3,่ฟ”ๅ›žURL let respDic: NSDictionary? = resp let value:String? = respDic!.valueForKey("key") as? String let imageUrl = AppConst.Network.qiniuHost+value! complete([tags, imageUrl]) }, option: nil) }, error: errorBlockFunc()) } /** ็ผ“ๅญ˜ๅ›พ็‰‡ - parameter image: ๅ›พ็‰‡ - parameter imageName: ๅ›พ็‰‡ๅ - returns: ๅ›พ็‰‡ๆฒ™็›’่ทฏๅพ„ */ func cacheImage(image: UIImage ,imageName: String) -> String { let data = UIImageJPEGRepresentation(image, 0.5) let homeDirectory = NSHomeDirectory() let documentPath = homeDirectory + "/Documents/" let fileManager: NSFileManager = NSFileManager.defaultManager() do { try fileManager.createDirectoryAtPath(documentPath, withIntermediateDirectories: true, attributes: nil) } catch _ { } let key = "\(imageName).png" fileManager.createFileAtPath(documentPath.stringByAppendingString(key), contents: data, attributes: nil) //ๅพ—ๅˆฐ้€‰ๆ‹ฉๅŽๆฒ™็›’ไธญๅ›พ็‰‡็š„ๅฎŒๆ•ด่ทฏๅพ„ let filePath: String = String(format: "%@%@", documentPath, key) return filePath } func didActionTel(telPhone:String) { let alert = UIAlertController.init(title: "ๅ‘ผๅซ", message: telPhone, preferredStyle: .Alert) let ensure = UIAlertAction.init(title: "็กฎๅฎš", style: .Default, handler: { (action: UIAlertAction) in UIApplication.sharedApplication().openURL(NSURL(string: "tel://\(telPhone)")!) }) let cancel = UIAlertAction.init(title: "ๅ–ๆถˆ", style: .Cancel, handler: { (action: UIAlertAction) in }) alert.addAction(ensure) alert.addAction(cancel) presentViewController(alert, animated: true, completion: nil) } }
apache-2.0
239cca8b794b2125bc6341cc6ac21f09
34.89
133
0.586735
4.956492
false
false
false
false
fuku2014/spritekit-original-game
src/scenes/tittle/TitleScene.swift
1
3349
// // FirstScene.swift // ใ‚ใ‚‹ใใ‚นใƒžใƒ› // // Created by admin on 2015/05/09. // Copyright (c) 2015ๅนด m.fukuzawa. All rights reserved. // import UIKit import SpriteKit import NCMB class TitleScene: SKScene, SignUpViewDelegate { override func didMoveToView(view: SKView) { // ่ƒŒๆ™ฏใฎใ‚ปใƒƒใƒˆ let back = SKSpriteNode(imageNamed:"title_back") back.xScale = self.size.width/back.size.width back.yScale = self.size.height/back.size.height back.position = CGPointMake(CGRectGetMidX(self.frame),CGRectGetMidY(self.frame)); back.zPosition = 0 self.addChild(back) let userName : String! = UserData.getUserName() // ๅˆๅ›ž่ตทๅ‹•ๆ™‚ใซใƒฆใƒผใ‚ถใƒผๅๅ…ฅๅŠ›ใƒ€ใ‚คใ‚ขใƒญใ‚ฐ่กจ็คบ if (userName == nil) { let dialog = SignUpView(scene: self, frame:CGRectMake(0, 0, self.view!.bounds.maxX - 50, 300)) dialog.delegate = self self.view!.addSubview(dialog) } } override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { let uuid : String! = UserData.getUserId() var error: NSError? do { // ใƒญใ‚ฐใ‚คใƒณ try NCMBUser.logInWithUsername(uuid, password: uuid) } catch let error1 as NSError { error = error1 } if let actualError = error { let alert: UIAlertController = UIAlertController(title:"้€šไฟกใ‚จใƒฉใƒผ", message: actualError.localizedDescription, preferredStyle: UIAlertControllerStyle.Alert) self.view?.window?.rootViewController?.presentViewController(alert, animated: true, completion: nil) return } // ใƒ›ใƒผใƒ ็”ป้ขใธ้ท็งป let homeScene = HomeScene(size: self.view!.bounds.size) homeScene.scaleMode = SKSceneScaleMode.AspectFill; self.view!.presentScene(homeScene) let sound = SKAction.playSoundFileNamed("button.mp3", waitForCompletion: false) homeScene.runAction(sound) // BGMใฎๅ†็”Ÿ let vc = UIApplication.sharedApplication().keyWindow?.rootViewController! as! ViewController vc.changeBGM(homeScene) } func signUp(userName : String) { let uuid : String = NSUUID().UUIDString let user : NCMBUser = NCMBUser() let acl : NCMBACL = NCMBACL() var error: NSError? user.userName = uuid as String user.password = uuid as String user.setObject(userName, forKey: "myName") acl.setPublicReadAccess(true) acl.setPublicWriteAccess(true) user.ACL = acl // ใƒฆใƒผใ‚ถใƒผ็™ป้Œฒ user.signUp(&error) if let actualError = error { let alert: UIAlertController = UIAlertController(title:"้€šไฟกใ‚จใƒฉใƒผ", message: actualError.localizedDescription, preferredStyle: UIAlertControllerStyle.Alert) self.view?.window?.rootViewController?.presentViewController(alert, animated: true, completion: nil) return } UserData.setUserId(uuid) UserData.setUserName(userName) let img : UIImage = UIImage(named: "manAvatar.png")! let data : NSData = UIImagePNGRepresentation(img)! UserData.setImageData(data) } }
apache-2.0
53bc539291602ad897952d2e3cdb7590
35.602273
112
0.622477
4.498603
false
false
false
false
edagarli/Swift
TestSwift/APIController.swift
1
2383
// // APIController.swift // TestSwift // // Created by Jameson Quave on 6/3/14. // Copyright (c) 2014 JQ Software LLC. All rights reserved. // import UIKit protocol APIControllerProtocol { func didRecieveAPIResults(results: NSDictionary) } class APIController: NSObject { var data: NSMutableData = NSMutableData() var delegate: APIControllerProtocol? func searchItunesFor(searchTerm: String) { // The iTunes API wants multiple terms separated by + symbols, so replace spaces with + signs var itunesSearchTerm = searchTerm.stringByReplacingOccurrencesOfString(" ", withString: "+", options: NSStringCompareOptions.CaseInsensitiveSearch, range: nil) // Now escape anything else that isn't URL-friendly var escapedSearchTerm = itunesSearchTerm.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding) var urlPath = "https://itunes.apple.com/search?term=\(escapedSearchTerm)&media=software" var url: NSURL = NSURL(string: urlPath) var request: NSURLRequest = NSURLRequest(URL: url) var connection: NSURLConnection = NSURLConnection(request: request, delegate: self, startImmediately: false) connection.start() } func connection(connection: NSURLConnection!, didFailWithError error: NSError!) { println("Connection failed.\(error.localizedDescription)") } func connection(didReceiveResponse: NSURLConnection!, didReceiveResponse response: NSURLResponse!) { // Recieved a new request, clear out the data object self.data = NSMutableData() } func connection(connection: NSURLConnection!, didReceiveData data: NSData!) { // Append the recieved chunk of data to our data object self.data.appendData(data) } func connectionDidFinishLoading(connection: NSURLConnection!) { // Request complete, self.data should now hold the resulting info // Convert the retrieved data in to an object through JSON deserialization var err: NSError var jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary // Now send the JSON result to our delegate object delegate?.didRecieveAPIResults(jsonResult) } }
mit
84b979aa5cac5fc2825c35a3a7bc61b1
37.435484
167
0.701637
5.490783
false
false
false
false
luckytianyiyan/TySimulator
TySimulator/MainMenuController.swift
1
2813
// // MainMenuController.swift // TySimulator // // Created by ty0x2333 on 2016/11/13. // Copyright ยฉ 2016ๅนด ty0x2333. All rights reserved. // import Cocoa class MainMenuController: NSObject { let statusItem = NSStatusBar.system.statusItem(withLength: NSStatusItem.squareLength) let popover: NSPopover = NSPopover() let quitMenuItem: NSMenuItem = NSMenuItem(title: NSLocalizedString("menu.quit", comment: "menu"), action: #selector(NSApplication.terminate(_:)), keyEquivalent: "q") let aboutItem: NSMenuItem = NSMenuItem(title: NSLocalizedString("menu.about", comment: "menu"), action: #selector(NSApplication.showAboutWindow), keyEquivalent: "") let preferenceItem: NSMenuItem = NSMenuItem(title: NSLocalizedString("menu.preference", comment: "menu"), action: #selector(NSApplication.showPreferencesWindow), keyEquivalent: ",") lazy var menu: NSMenu = { let menu = NSMenu() menu.autoenablesItems = false menu.addItem(preferenceItem) menu.addItem(aboutItem) menu.addItem(NSMenuItem.separator()) menu.addItem(quitMenuItem) return menu }() var monitor: Any? override func awakeFromNib() { super.awakeFromNib() popover.contentViewController = MainViewController(nibName: "MainViewController", bundle: nil) if let button = statusItem.button { button.image = NSImage(named: "MenuIcon") button.target = self button.action = #selector(MainMenuController.togglePopver(_:)) } } // MARK: Actions @IBAction func onClickMenuPreferences(_ sender: Any) { NSApplication.shared.showPreferencesWindow() } @objc func togglePopver(_ sender: Any?) { if popover.isShown { closePopover(sender: sender) } else { showPopover(sender: sender) } } // MARK: Private private func showPopover(sender: Any?) { guard let button = statusItem.button else { return } log.info("show Popover") popover.show(relativeTo: button.bounds, of: button, preferredEdge: NSRectEdge.minY) guard monitor == nil else { return } monitor = NSEvent.addGlobalMonitorForEvents(matching: [.leftMouseDown, .rightMouseDown]) { [weak self] event in guard let weakSelf = self, weakSelf.popover.isShown else { return } weakSelf.closePopover(sender: event) } } func closePopover(sender: Any?) { log.info("close Popover") popover.performClose(sender) if let monitor = self.monitor { NSEvent.removeMonitor(monitor) self.monitor = nil } } }
mit
1df95db339905e41e6fdcf9ae9c94ab6
33.268293
185
0.623843
4.844828
false
false
false
false
apple/swift
test/Constraints/enum_cases.swift
4
5690
// RUN: %target-typecheck-verify-swift -swift-version 4 // See test/Compatibility/enum_cases.swift for Swift 3 behavior enum E { case foo(bar: String) case bar(_: String) case two(x: Int, y: Int) case tuple((x: Int, y: Int)) } enum G_E<T> { case foo(bar: T) case bar(_: T) case two(x: T, y: T) case tuple((x: T, y: T)) } let arr: [String] = [] let _ = arr.map(E.foo) // Ok let _ = arr.map(E.bar) // Ok let _ = arr.map(E.two) // expected-error {{cannot convert value of type '(Int, Int) -> E' to expected argument type '(String) throws -> E'}} let _ = arr.map(E.tuple) // expected-error {{cannot convert value of type '((x: Int, y: Int)) -> E' to expected argument type '(String) throws -> E'}} let _ = arr.map(G_E<String>.foo) // Ok let _ = arr.map(G_E<String>.bar) // Ok let _ = arr.map(G_E<String>.two) // expected-error {{cannot convert value of type '(String, String) -> G_E<String>' to expected argument type '(String) throws -> G_E<String>'}} let _ = arr.map(G_E<Int>.tuple) // expected-error {{cannot convert value of type '((x: Int, y: Int)) -> G_E<Int>' to expected argument type '(String) throws -> G_E<Int>'}} let _ = E.foo("hello") // expected-error {{missing argument label 'bar:' in call}} let _ = E.bar("hello") // Ok let _ = G_E<String>.foo("hello") // expected-error {{missing argument label 'bar:' in call}} let _ = G_E<String>.bar("hello") // Ok // Passing enum case as an argument to generic function func bar_1<T>(_: (T) -> E) {} func bar_2<T>(_: (T) -> G_E<T>) {} func bar_3<T, U>(_: (T) -> G_E<U>) {} bar_1(E.foo) // Ok bar_1(E.bar) // Ok // SE-0110: We reverted to allowing this for the time being, but this // test is valuable in case we end up disallowing it again in the // future. bar_1(E.two) // Ok since we backed off on this aspect of SE-0110 for the moment. bar_1(E.tuple) // Ok - it's going to be ((x: Int, y: Int)) bar_2(G_E<String>.foo) // Ok bar_2(G_E<Int>.bar) // Ok bar_2(G_E<Int>.two) // expected-error {{cannot convert value of type '(Int, Int) -> G_E<Int>' to expected argument type '(Int) -> G_E<Int>'}} bar_2(G_E<Int>.tuple) // expected-error {{cannot convert value of type '((x: Int, y: Int)) -> G_E<Int>' to expected argument type '(Int) -> G_E<Int>'}} bar_3(G_E<Int>.tuple) // Ok // Regular enum case assigned as a value let foo: (String) -> E = E.foo // Ok let _ = foo("hello") // Ok let bar: (String) -> E = E.bar // Ok let _ = bar("hello") // Ok let two: (Int, Int) -> E = E.two // Ok let _ = two(0, 42) // Ok let tuple: ((x: Int, y: Int)) -> E = E.tuple // Ok let _ = tuple((x: 0, y: 42)) // Ok // Generic enum case assigned as a value let g_foo: (String) -> G_E<String> = G_E<String>.foo // Ok let _ = g_foo("hello") // Ok let g_bar: (String) -> G_E<String> = G_E<String>.bar // Ok let _ = g_bar("hello") // Ok let g_two: (Int, Int) -> G_E<Int> = G_E<Int>.two // Ok let _ = g_two(0, 42) // Ok let g_tuple: ((x: Int, y: Int)) -> G_E<Int> = G_E<Int>.tuple // Ok let _ = g_tuple((x: 0, y: 42)) // Ok enum Foo { case a(x: Int) case b(y: Int) } func foo<T>(_: T, _: T) {} foo(Foo.a, Foo.b) // Ok in Swift 4 because we strip labels from the arguments // rdar://problem/32551313 - Useless SE-0110 diagnostic enum E_32551313<L, R> { case Left(L) case Right(R) } struct Foo_32551313 { static func bar() -> E_32551313<(String, Foo_32551313?), (String, String)>? { return E_32551313.Left("", Foo_32551313()) // expected-error@-1 {{cannot convert value of type 'String' to expected argument type '(String, Foo_32551313?)'}} // expected-error@-2 {{extra argument in call}} } } func rdar34583132() { enum E { case timeOut } struct S { func foo(_ x: Int) -> E { return .timeOut } } func bar(_ s: S) { guard s.foo(1 + 2) == .timeout else { // expected-error@-1 {{enum type 'E' has no case 'timeout'; did you mean 'timeOut'?}} fatalError() } } } func rdar_49159472() { struct A {} struct B {} struct C {} enum E { case foo(a: A, b: B?) var foo: C? { return nil } } class Test { var e: E init(_ e: E) { self.e = e } func bar() { e = .foo(a: A(), b: nil) // Ok e = E.foo(a: A(), b: nil) // Ok baz(e: .foo(a: A(), b: nil)) // Ok baz(e: E.foo(a: A(), b: nil)) // Ok } func baz(e: E) {} } } struct EnumElementPatternFromContextualType<T> { enum E { case plain case payload(T) } func foo(x: Any) where T == EnumElementPatternFromContextualType<Bool>.E { switch x { case T.plain: // Ok break case T.payload(true): // Ok break default: break } } } // https://github.com/apple/swift/issues/56765 enum CompassPoint { case North(Int) case South case East case West } func isNorth(c : CompassPoint) -> Bool { // expected-error@+1{{member 'North' expects argument of type 'Int'}} return c == .North // expected-error {{binary operator '==' cannot be applied to two 'CompassPoint' operands}} // expected-note@-1 {{binary operator '==' cannot be synthesized for enums with associated values}} } func isNorth2(c : CompassPoint) -> Bool { // expected-error@+1{{member 'North' expects argument of type 'Int'}} return .North == c // expected-error {{binary operator '==' cannot be applied to two 'CompassPoint' operands}} // expected-note@-1 {{binary operator '==' cannot be synthesized for enums with associated values}} } func isSouth(c : CompassPoint) -> Bool { return c == .South // expected-error {{binary operator '==' cannot be applied to two 'CompassPoint' operands}} // expected-note@-1 {{binary operator '==' cannot be synthesized for enums with associated values}} }
apache-2.0
fbc54cec5fc979674fa79f3c201e7e04
27.592965
176
0.597364
2.93905
false
false
false
false
GuitarPlayer-Ma/Swiftweibo
weibo/weibo/Classes/Home/View/Cell/HomeStatusTopView.swift
1
3770
// // HomeStatusTopView.swift // weibo // // Created by mada on 15/10/12. // Copyright ยฉ 2015ๅนด MD. All rights reserved. // import UIKit class HomeStatusTopView: UIView { var status: Status? { didSet { // ๅคดๅƒ iconView.sd_setImageWithURL(status?.user?.profile_URL) // ่ฎพ็ฝฎๆ˜ต็งฐ nameLabel.text = status?.user?.name // ่ฎค่ฏๅ›พๆ ‡ verifiedView.image = status?.user?.verified_image // ไผšๅ‘˜ๅ›พๆ ‡ if let image = status?.user?.vipImage { vipView.image = image nameLabel.textColor = UIColor.orangeColor() } else { vipView.image = nil nameLabel.textColor = UIColor.blackColor() } // ๅพฎๅšๆฅๆบ sourceLabel.text = status?.source // ่ฎพ็ฝฎๆ—ถ้—ด timeLabel.text = status?.created_at; } } override init(frame: CGRect) { super.init(frame: frame) setupUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func setupUI() { addSubview(iconView) iconView.addSubview(verifiedView) addSubview(nameLabel) addSubview(vipView) addSubview(timeLabel) addSubview(sourceLabel) // ๅธƒๅฑ€ๅคดๅƒ iconView.snp_makeConstraints { (make) -> Void in make.top.equalTo(10) make.left.equalTo(10) make.width.equalTo(50) make.height.equalTo(50) make.bottom.equalTo(self.snp_bottom).offset(-10) } // ๅธƒๅฑ€่ฎค่ฏ verifiedView.snp_makeConstraints { (make) -> Void in make.right.equalTo(iconView).offset(8) make.bottom.equalTo(iconView).offset(8) } // ๅธƒๅฑ€ๆ˜ต็งฐ nameLabel.snp_makeConstraints { (make) -> Void in make.top.equalTo(iconView).offset(5) make.left.equalTo(iconView.snp_right).offset(10) } // ๅธƒๅฑ€ไผšๅ‘˜ๅ›พๆ ‡ vipView.snp_makeConstraints { (make) -> Void in make.top.equalTo(nameLabel) make.left.equalTo(nameLabel.snp_right).offset(10) make.size.equalTo(CGSize(width: 17, height: 17)) } // ๅธƒๅฑ€ๅ‘ๅธƒๆ—ถ้—ด timeLabel.snp_makeConstraints { (make) -> Void in make.left.equalTo(nameLabel.snp_left) make.top.equalTo(nameLabel.snp_bottom).offset(5) } // ๅธƒๅฑ€ๅพฎๅšๆฅๆบ sourceLabel.snp_makeConstraints { (make) -> Void in make.left.equalTo(timeLabel.snp_right).offset(5) make.top.equalTo(timeLabel) } } // MARK: - ๆ‡’ๅŠ ่ฝฝ // ๅคดๅƒ private lazy var iconView: UIImageView = UIImageView(image: UIImage(named: "avatar_default_big")) // ่ฎค่ฏๅ›พ็‰‡ private lazy var verifiedView: UIImageView = UIImageView(image: UIImage(named: "avatar_enterprise_vip")) // ๆ˜ต็งฐ private lazy var nameLabel: UILabel = { let nameLabel = UILabel() nameLabel.text = "ๅŠ ๆ–ฏๅŠ ็š„็Œฟ" return nameLabel }() // ไผšๅ‘˜ๅ›พๆ ‡ private lazy var vipView: UIImageView = UIImageView(image: UIImage(named: "common_icon_membership_expired")) // ๆ—ถ้—ด private lazy var timeLabel: UILabel = { let label = UILabel(color: UIColor.orangeColor(), size: 13) label.text = "ๅˆšๅˆš" return label }() // ๆฅๆบ private lazy var sourceLabel: UILabel = { let label = UILabel(color: UIColor.lightGrayColor(), size: 13) label.text = "ๆฅ่‡ช:ๅฎ‡ๅฎ™่ฎก็ฎ—ๆœบ" return label }() }
mit
4b4b67214accd707e8211ba5f662a490
29.483051
112
0.557965
4.307784
false
false
false
false
padawan/smartphone-app
MT_iOS/MT_iOS/Classes/ViewController/BlogSettingsTableViewController.swift
1
8134
// // BlogSettingsTableViewController.swift // MT_iOS // // Created by CHEEBOW on 2015/05/26. // Copyright (c) 2015ๅนด Six Apart, Ltd. All rights reserved. // import UIKit class BlogSettingsTableViewController: BaseTableViewController, BlogImageSizeDelegate, BlogImageQualityDelegate, BlogUploadDirDelegate { enum Item:Int { case UploadDir = 0, Size, Quality, _Num } var blog: Blog! var uploadDir = "/" var imageSize = Blog.ImageSize.M var imageQuality = Blog.ImageQuality.Normal override func viewDidLoad() { super.viewDidLoad() // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Uncomment the following line to display an Edit button in the navigation bar for this view controller. // self.navigationItem.rightBarButtonItem = self.editButtonItem() self.title = NSLocalizedString("Settings", comment: "Settings") self.tableView.backgroundColor = Color.tableBg self.navigationItem.leftBarButtonItem = UIBarButtonItem(image: UIImage(named: "btn_close"), left: true, target: self, action: "closeButtonPushed:") self.navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Save, target: self, action: "saveButtonPushed:") uploadDir = blog.uploadDir imageSize = blog.imageSize imageQuality = blog.imageQuality } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { // #warning Potentially incomplete method implementation. // Return the number of sections. return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete method implementation. // Return the number of rows in the section. return Item._Num.rawValue } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("ItemCell", forIndexPath: indexPath) as! UITableViewCell self.adjustCellLayoutMargins(cell) cell.accessoryType = UITableViewCellAccessoryType.DisclosureIndicator cell.textLabel?.textColor = Color.cellText cell.textLabel?.font = UIFont.systemFontOfSize(17.0) cell.detailTextLabel?.textColor = Color.black cell.detailTextLabel?.font = UIFont.systemFontOfSize(15.0) switch indexPath.row { case Item.UploadDir.rawValue: cell.textLabel?.text = NSLocalizedString("Upload Dir", comment: "Upload Dir") cell.imageView?.image = UIImage(named: "ico_upload") cell.detailTextLabel?.text = uploadDir case Item.Size.rawValue: cell.textLabel?.text = NSLocalizedString("Image Size", comment: "Image Size") cell.imageView?.image = UIImage(named: "ico_size") cell.detailTextLabel?.text = imageSize.label() + "(" + imageSize.pix() + ")" case Item.Quality.rawValue: cell.textLabel?.text = NSLocalizedString("Image Quality", comment: "Image Quality") cell.imageView?.image = UIImage(named: "ico_quality") cell.detailTextLabel?.text = imageQuality.label() default: cell.textLabel?.text = "" } // Configure the cell... return cell } override func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 21.0 } override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return 58.0 } /* // Override to support conditional editing of the table view. override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return NO if you do not want the specified item to be editable. return true } */ /* // Override to support editing the table view. override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { // Delete the row from the data source tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } else if editingStyle == .Insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } */ /* // Override to support rearranging the table view. override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return NO if you do not want the item to be re-orderable. return true } */ // MARK: - Table view delegte override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { switch indexPath.row { case Item.UploadDir.rawValue: let storyboard: UIStoryboard = UIStoryboard(name: "BlogUploadDir", bundle: nil) let vc = storyboard.instantiateInitialViewController() as! BlogUploadDirTableViewController vc.directory = uploadDir vc.delegate = self self.navigationController?.pushViewController(vc, animated: true) case Item.Size.rawValue: let storyboard: UIStoryboard = UIStoryboard(name: "BlogImageSize", bundle: nil) let vc = storyboard.instantiateInitialViewController() as! BlogImageSizeTableViewController vc.selected = imageSize.rawValue vc.delegate = self self.navigationController?.pushViewController(vc, animated: true) case Item.Quality.rawValue: let storyboard: UIStoryboard = UIStoryboard(name: "BlogImageQuality", bundle: nil) let vc = storyboard.instantiateInitialViewController() as! BlogImageQualityTableViewController vc.selected = imageQuality.rawValue vc.delegate = self self.navigationController?.pushViewController(vc, animated: true) default: break } } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using [segue destinationViewController]. // Pass the selected object to the new view controller. } */ @IBAction func closeButtonPushed(sender: AnyObject) { self.dismissViewControllerAnimated(true, completion: nil) } @IBAction func saveButtonPushed(sender: AnyObject) { blog.uploadDir = uploadDir blog.imageSize = imageSize blog.imageQuality = imageQuality blog.saveSettings() self.dismissViewControllerAnimated(true, completion: nil) } func blogImageSizeDone(controller: BlogImageSizeTableViewController, selected: Int) { imageSize = Blog.ImageSize(rawValue: selected)! self.tableView.reloadData() } func blogImageQualityDone(controller: BlogImageQualityTableViewController, selected: Int) { imageQuality = Blog.ImageQuality(rawValue: selected)! self.tableView.reloadData() } func blogUploadDirDone(controller: BlogUploadDirTableViewController, directory: String) { uploadDir = directory self.tableView.reloadData() } }
mit
0f0e5d994f3e1515876b37e5464ec9a4
38.668293
157
0.673266
5.417722
false
false
false
false
Kofktu/KofktuSDK
KofktuSDK/Classes/Components/KUIAlertController.swift
1
1951
// // KUIAlertManager.swift // KofktuSDK // // Created by Kofktu on 2016. 9. 7.. // Copyright ยฉ 2016๋…„ Kofktu. All rights reserved. // import Foundation import UIKit public protocol KUIAlertControllerDefaultProtocol { var okTitle: String { get } var cancelTitle: String { get } } public struct KUIAlertControllerDefault: KUIAlertControllerDefaultProtocol { public var okTitle: String { return "ํ™•์ธ" } public var cancelTitle: String { return "์ทจ์†Œ" } } public class KUIAlertController { public static var defaultValue = KUIAlertControllerDefault() public class func showAlert(title: String?, message: String?, okTitle: String? = nil, onOk: (() -> Void)? = nil) { let alertController = UIAlertController(title: title ?? "", message: message, preferredStyle: .alert) alertController.addAction(UIAlertAction(title: okTitle ?? defaultValue.okTitle, style: .`default`, handler: { (action) in onOk?() })) UIApplication.shared.delegate?.window!?.rootViewController?.topMostViewController.present(alertController, animated: true, completion: nil) } public class func showOkCancelAlert(title: String?, message: String?, okTitle: String? = nil, onOk: (() -> Void)? = nil, cancelTitle: String? = nil, onCancel: (() -> Void)? = nil) { let alertController = UIAlertController(title: title ?? "", message: message, preferredStyle: .alert) alertController.addAction(UIAlertAction(title: okTitle ?? defaultValue.okTitle, style: .`default`, handler: { (action) in onOk?() })) alertController.addAction(UIAlertAction(title: cancelTitle ?? defaultValue.cancelTitle, style: .cancel, handler: { (action) in onCancel?() })) UIApplication.shared.delegate?.window!?.rootViewController?.topMostViewController.present(alertController, animated: true, completion: nil) } }
mit
cdcea8e3c5848c20f8d8997920dac267
39.416667
185
0.677835
4.575472
false
false
false
false
peterxhu/ARGoal
ARGoal/Virtual Goal/VirtualGoalViewController.swift
1
47192
// // VirtualGoalViewController.swift // ARGoal // // Created by Peter Hu on 6/17/17. // Copyright ยฉ 2017 App Doctor Hu. All rights reserved. // import ARKit import Foundation import SceneKit import UIKit import Photos import ReplayKit enum PhysicsBodyType: Int { case projectile = 10 // ball case goalFrame = 11 // goal frame (cross bar) case plane = 12 // ground case goalPlane = 13 // goal scoring plane (detect goal) } enum VirtualGoalTutorialStep: Int { case addObject1 = 1 case launchObject2 = 2 case longPressObject3 = 3 case zoomOnGoal4 = 4 case holdToDrag5 = 5 case goToSettings6 = 6 case endOfTutorial7 = 7 } class VirtualGoalViewController: UIViewController, ARSCNViewDelegate, UIPopoverPresentationControllerDelegate, SCNPhysicsContactDelegate, VirtualObjectSelectionViewControllerDelegate, RPScreenRecorderDelegate, RPPreviewViewControllerDelegate, EasyTipViewDelegate { let cheerView = CheerView() var timer: Timer = Timer() override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() cheerView.frame = view.bounds } // MARK: - Main Setup & View Controller methods override func viewDidLoad() { super.viewDidLoad() cheerView.config.particle = .confetti view.addSubview(cheerView) circlePowerMeter.isHidden = true let tapGesture = UITapGestureRecognizer(target: self, action: #selector(triggerNormalTap(_:))) let longGesture = TimedLongPressGesture(target: self, action: #selector(triggerLongTap(_:))) tapGesture.numberOfTapsRequired = 1 triggerButton.addGestureRecognizer(tapGesture) triggerButton.addGestureRecognizer(longGesture) let swipeUpGestureRecognizer = UISwipeGestureRecognizer(target: self, action: #selector(triggerNormalTap(_:))) swipeUpGestureRecognizer.direction = UISwipeGestureRecognizerDirection.up self.sceneView.addGestureRecognizer(swipeUpGestureRecognizer) Setting.registerDefaults() setupScene() setupDebug() setupUIControls() setupFocusSquare() updateSettings() resetVirtualObject() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) // Prevent the screen from being dimmed after a while. UIApplication.shared.isIdleTimerDisabled = true // Start the ARSession. restartPlaneDetection() } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) session.pause() } // MARK: - Tooltip func easyTipViewDidDismissOnTap(_ tipView: EasyTipView) { if (UserDefaults.standard.bool(for: .endOfTutorial7TutorialFulfilled)) { NSLog("End of tutorial") } else if (UserDefaults.standard.bool(for: .goToSettings6TutorialFulfilled)) { showToolTipFor(step: .endOfTutorial7) UserDefaults.standard.set(true, for: .endOfTutorial7TutorialFulfilled) } else if (UserDefaults.standard.bool(for: .holdToDrag5TutorialFulfilled)) { showToolTipFor(step: .goToSettings6) UserDefaults.standard.set(true, for: .goToSettings6TutorialFulfilled) } else if (UserDefaults.standard.bool(for: .zoomOnGoal4TutorialFulfilled)) { showToolTipFor(step: .holdToDrag5) UserDefaults.standard.set(true, for: .holdToDrag5TutorialFulfilled) } else if (UserDefaults.standard.bool(for: .longPressObject3TutorialFulfilled)) { showToolTipFor(step: .zoomOnGoal4) UserDefaults.standard.set(true, for: .zoomOnGoal4TutorialFulfilled) } else if (UserDefaults.standard.bool(for: .launchObject2TutorialFulfilled)) { showToolTipFor(step: .longPressObject3) UserDefaults.standard.set(true, for: .longPressObject3TutorialFulfilled) } else if (UserDefaults.standard.bool(for: .addObject1TutorialFulfilled)) { showToolTipFor(step: .launchObject2) UserDefaults.standard.set(true, for: .launchObject2TutorialFulfilled) } } func showToolTipFor(step: VirtualGoalTutorialStep) { switch step { case .addObject1: let newTooltip = UtilityMethods.showToolTip(for: addObjectButton, superview: view, text: "(1/7) Welcome to the tutorial. Start here! Add a goal! (Tap the bubble to move along)", position: .bottom) newTooltip?.delegate = self case .launchObject2: let newTooltip = UtilityMethods.showToolTip(for: triggerButton, superview: view, text: "(2/7) Swipe up on the screen OR single click the trigger button to launch a virtual ball!", position: .bottom) newTooltip?.delegate = self case .longPressObject3: let anchorView = UIView(frame: CGRect(x: view.center.x, y: view.center.y, width: 1, height: 1)) view.addSubview(anchorView) let newTooltip = UtilityMethods.showToolTip(for: anchorView, superview: view, text: "(3/7) Tap and hold the trigger button to launch the ball harder!", position: .bottom) newTooltip?.delegate = self case .zoomOnGoal4: let newTooltip = UtilityMethods.showToolTip(for: addObjectButton, superview: view, text: "(4/7) Pinch and zoom on the goal to increase or decrease the size.", position: .bottom) newTooltip?.delegate = self case .holdToDrag5: let anchorView = UIView(frame: CGRect(x: view.center.x, y: view.center.y, width: 1, height: 1)) view.addSubview(anchorView) let newTooltip = UtilityMethods.showToolTip(for: anchorView, superview: view, text: "(5/7) To move the object, either single tap on a surface in the scene or tap and hold the object, then drag the goal to move it around.", position: .bottom) newTooltip?.delegate = self case .goToSettings6: let newTooltip = UtilityMethods.showToolTip(for: settingsButton, superview: view, text: "(6/7) Go to settings to enable surface planes, enable goal detection, view how-tos, and change other configurations", position: .right) newTooltip?.delegate = self case .endOfTutorial7: let anchorView = UIView(frame: CGRect(x: view.center.x, y: view.center.y, width: 1, height: 1)) view.addSubview(anchorView) let newTooltip = UtilityMethods.showToolTip(for: addObjectButton, superview: view, text: "(7/7) Congrats! You have all you need to know. Cheers!", position: .bottom) newTooltip?.delegate = self } } // MARK: - ARKit / ARSCNView let session = ARSession() var sessionConfig: ARConfiguration = ARWorldTrackingConfiguration() var use3DOFTracking = false { didSet { if use3DOFTracking { sessionConfig = AROrientationTrackingConfiguration() } sessionConfig.isLightEstimationEnabled = true session.run(sessionConfig) } } var use3DOFTrackingFallback = false @IBOutlet var sceneView: ARSCNView! var screenCenter: CGPoint? func setupScene() { // set up sceneView sceneView.delegate = self sceneView.session = session sceneView.antialiasingMode = .multisampling4X sceneView.automaticallyUpdatesLighting = true self.sceneView.autoenablesDefaultLighting = true self.sceneView.scene.physicsWorld.contactDelegate = self sceneView.preferredFramesPerSecond = 60 sceneView.contentScaleFactor = 1.3 enableEnvironmentMapWithIntensity(25.0) DispatchQueue.main.async { self.screenCenter = self.sceneView.bounds.mid } if let camera = sceneView.pointOfView?.camera { camera.wantsHDR = true camera.wantsExposureAdaptation = true camera.exposureOffset = -1 camera.minimumExposure = -1 } } func enableEnvironmentMapWithIntensity(_ intensity: CGFloat) { let estimate: ARLightEstimate? = self.session.currentFrame?.lightEstimate if estimate == nil { return } // A value of 1000 is considered neutral, lighting environment intensity normalizes // 1.0 to neutral so we need to scale the ambientIntensity value let intensity: CGFloat? = (estimate?.ambientIntensity)! / 1000.0 sceneView.scene.lightingEnvironment.intensity = intensity! } // MARK: - ARSCNViewDelegate func renderer(_ renderer: SCNSceneRenderer, updateAtTime time: TimeInterval) { refreshFeaturePoints() DispatchQueue.main.async { self.updateFocusSquare() self.enableEnvironmentMapWithIntensity(1000) } } func renderer(_ renderer: SCNSceneRenderer, didAdd node: SCNNode, for anchor: ARAnchor) { DispatchQueue.main.async { if let planeAnchor = anchor as? ARPlaneAnchor { self.addPlane(node: node, anchor: planeAnchor) self.checkIfObjectShouldMoveOntoPlane(anchor: planeAnchor) } } } func renderer(_ renderer: SCNSceneRenderer, didUpdate node: SCNNode, for anchor: ARAnchor) { DispatchQueue.main.async { if let planeAnchor = anchor as? ARPlaneAnchor { self.updatePlane(anchor: planeAnchor) self.checkIfObjectShouldMoveOntoPlane(anchor: planeAnchor) } } } func renderer(_ renderer: SCNSceneRenderer, didRemove node: SCNNode, for anchor: ARAnchor) { DispatchQueue.main.async { if let planeAnchor = anchor as? ARPlaneAnchor { self.removePlane(anchor: planeAnchor) } } } var trackingFallbackTimer: Timer? func session(_ session: ARSession, cameraDidChangeTrackingState camera: ARCamera) { textManager.showTrackingQualityInfo(for: camera.trackingState, autoHide: !self.showDetailedMessages) switch camera.trackingState { case .notAvailable: textManager.escalateFeedback(for: camera.trackingState, inSeconds: 5.0) case .limited: if use3DOFTrackingFallback { // After 10 seconds of limited quality, fall back to 3DOF mode. // 3DOF tracking maintains an AR illusion when the the device pivots // but not when the device's position moves trackingFallbackTimer = Timer.scheduledTimer(withTimeInterval: 10.0, repeats: false, block: { _ in self.use3DOFTracking = true self.trackingFallbackTimer?.invalidate() self.trackingFallbackTimer = nil }) } else { textManager.escalateFeedback(for: camera.trackingState, inSeconds: 10.0) } case .normal: textManager.cancelScheduledMessage(forType: .trackingStateEscalation) if use3DOFTrackingFallback && trackingFallbackTimer != nil { trackingFallbackTimer!.invalidate() trackingFallbackTimer = nil } } } func session(_ session: ARSession, didFailWithError error: Error) { guard let arError = error as? ARError else { return } let nsError = error as NSError var sessionErrorMsg = "\(nsError.localizedDescription) \(nsError.localizedFailureReason ?? "")" if let recoveryOptions = nsError.localizedRecoveryOptions { for option in recoveryOptions { sessionErrorMsg.append("\(option).") } } let isRecoverable = (arError.code == .worldTrackingFailed) if isRecoverable { sessionErrorMsg += "\nYou can try resetting the session or quit the application." } else { sessionErrorMsg += "\nThis is an unrecoverable error that requires to quit the application." } displayErrorMessage(title: "We're sorry!", message: sessionErrorMsg, allowRestart: isRecoverable) } func sessionWasInterrupted(_ session: ARSession) { textManager.blurBackground() textManager.showAlert(title: "Session Interrupted", message: "The session will be reset after the interruption has ended. If issues still persist, please use the \"X\" button to close and reopen the session.") restartExperience(self) } func sessionInterruptionEnded(_ session: ARSession) { textManager.unblurBackground() session.run(sessionConfig, options: [.resetTracking, .removeExistingAnchors]) restartExperience(self) textManager.showMessage("RESETTING SESSION") } // MARK: - Ambient Light Estimation func toggleAmbientLightEstimation(_ enabled: Bool) { if enabled { if !sessionConfig.isLightEstimationEnabled { // turn on light estimation sessionConfig.isLightEstimationEnabled = true session.run(sessionConfig) } } else { if sessionConfig.isLightEstimationEnabled { // turn off light estimation sessionConfig.isLightEstimationEnabled = false session.run(sessionConfig) } } } // MARK: - Gesture Recognizers var currentGesture: Gesture? override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { guard let object = virtualObject else { return } if currentGesture == nil { currentGesture = Gesture.startGestureFromTouches(touches, self.sceneView, object) } else { currentGesture = currentGesture!.updateGestureFromTouches(touches, .touchBegan) } displayVirtualObjectTransform() } override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) { if virtualObject == nil { return } currentGesture = currentGesture?.updateGestureFromTouches(touches, .touchMoved) displayVirtualObjectTransform() } override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { if virtualObject == nil { chooseObject(addObjectButton) return } currentGesture = currentGesture?.updateGestureFromTouches(touches, .touchEnded) } override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) { if virtualObject == nil { return } currentGesture = currentGesture?.updateGestureFromTouches(touches, .touchCancelled) } // MARK: - Virtual Object Manipulation func displayVirtualObjectTransform() { guard let object = virtualObject, let cameraTransform = session.currentFrame?.camera.transform else { return } // Output the current translation, rotation & scale of the virtual object as text. let cameraPos = SCNVector3.positionFromTransform(cameraTransform) let vectorToCamera = cameraPos - object.position let distanceToUser = vectorToCamera.length() var angleDegrees = Int(((object.eulerAngles.y) * 180) / Float.pi) % 360 if angleDegrees < 0 { angleDegrees += 360 } let distance = String(format: "%.2f", distanceToUser) let scale = String(format: "%.2f", object.scale.x) textManager.showDebugMessage("Distance: \(distance) m\nRotation: \(angleDegrees)ยฐ\nScale: \(scale)x") } func moveVirtualObjectToPosition(_ pos: SCNVector3?, _ instantly: Bool, _ filterPosition: Bool) { guard let newPosition = pos else { textManager.showMessage("CANNOT PLACE OBJECT\nTry moving left or right.") // Reset the content selection in the menu only if the content has not yet been initially placed. if virtualObject == nil { resetVirtualObject() } return } if instantly { setNewVirtualObjectPosition(newPosition) } else { updateVirtualObjectPosition(newPosition, filterPosition) } } var dragOnInfinitePlanesEnabled = false func worldPositionFromScreenPosition(_ position: CGPoint, objectPos: SCNVector3?, infinitePlane: Bool = false) -> (position: SCNVector3?, planeAnchor: ARPlaneAnchor?, hitAPlane: Bool) { // ------------------------------------------------------------------------------- // 1. Always do a hit test against exisiting plane anchors first. // (If any such anchors exist & only within their extents.) let planeHitTestResults = sceneView.hitTest(position, types: .existingPlaneUsingExtent) if let result = planeHitTestResults.first { let planeHitTestPosition = SCNVector3.positionFromTransform(result.worldTransform) let planeAnchor = result.anchor // Return immediately - this is the best possible outcome. return (planeHitTestPosition, planeAnchor as? ARPlaneAnchor, true) } // ------------------------------------------------------------------------------- // 2. Collect more information about the environment by hit testing against // the feature point cloud, but do not return the result yet. var featureHitTestPosition: SCNVector3? var highQualityFeatureHitTestResult = false let highQualityfeatureHitTestResults = sceneView.hitTestWithFeatures(position, coneOpeningAngleInDegrees: 18, minDistance: 0.2, maxDistance: 2.0) if !highQualityfeatureHitTestResults.isEmpty { let result = highQualityfeatureHitTestResults[0] featureHitTestPosition = result.position highQualityFeatureHitTestResult = true } // ------------------------------------------------------------------------------- // 3. If desired or necessary (no good feature hit test result): Hit test // against an infinite, horizontal plane (ignoring the real world). if (infinitePlane && dragOnInfinitePlanesEnabled) || !highQualityFeatureHitTestResult { let pointOnPlane = objectPos ?? SCNVector3Zero let pointOnInfinitePlane = sceneView.hitTestWithInfiniteHorizontalPlane(position, pointOnPlane) if pointOnInfinitePlane != nil { return (pointOnInfinitePlane, nil, true) } } // ------------------------------------------------------------------------------- // 4. If available, return the result of the hit test against high quality // features if the hit tests against infinite planes were skipped or no // infinite plane was hit. if highQualityFeatureHitTestResult { return (featureHitTestPosition, nil, false) } // ------------------------------------------------------------------------------- // 5. As a last resort, perform a second, unfiltered hit test against features. // If there are no features in the scene, the result returned here will be nil. let unfilteredFeatureHitTestResults = sceneView.hitTestWithFeatures(position) if !unfilteredFeatureHitTestResults.isEmpty { let result = unfilteredFeatureHitTestResults[0] return (result.position, nil, false) } return (nil, nil, false) } // Use average of recent virtual object distances to avoid rapid changes in object scale. var recentVirtualObjectDistances = [CGFloat]() func setNewVirtualObjectPosition(_ pos: SCNVector3) { guard let object = virtualObject, let cameraTransform = session.currentFrame?.camera.transform else { return } recentVirtualObjectDistances.removeAll() let cameraWorldPos = SCNVector3.positionFromTransform(cameraTransform) var cameraToPosition = pos - cameraWorldPos // Limit the distance of the object from the camera to a maximum of 10 meters. cameraToPosition.setMaximumLength(10) object.position = cameraWorldPos + cameraToPosition if object.parent == nil { if let goalPlane = object.childNode(withName: "goalPlane", recursively: true) { if enableGoalDetection { goalPlane.opacity = 0.5 } else { goalPlane.removeFromParentNode() } goalPlane.physicsBody = SCNPhysicsBody(type: .kinematic, shape: SCNPhysicsShape(node: goalPlane, options: nil)) goalPlane.physicsBody?.categoryBitMask = PhysicsBodyType.goalPlane.rawValue } sceneView.scene.rootNode.addChildNode(object) // This is the tutorial access point if (!UserDefaults.standard.bool(for: .addObject1TutorialFulfilled)) { let launchTutorialAction = UIAlertAction(title: "Yes", style: .default) { _ in self.showToolTipFor(step: .addObject1) UserDefaults.standard.set(true, for: .addObject1TutorialFulfilled) } let dismissAction = UIAlertAction(title: "Dismiss", style: .cancel) { _ in UserDefaults.standard.set(true, for: .addObject1TutorialFulfilled) } textManager.showAlert(title: "Welcome!", message: "It looks like this is your first time! Would you like a quick tutorial to show you how to make the most of ARGoal: \"Virtual Goal\"?", actions: [launchTutorialAction, dismissAction]) } } } func resetVirtualObject() { virtualObject?.unloadModel() virtualObject?.removeFromParentNode() virtualObject = nil DispatchQueue.main.async { self.triggerButton.isHidden = true self.triggerIconImageView.isHidden = true } addObjectButton.setImage(#imageLiteral(resourceName: "add"), for: []) addObjectButton.setImage(#imageLiteral(resourceName: "addPressed"), for: [.highlighted]) // Reset selected object id for row highlighting in object selection view controller. UserDefaults.standard.set(-1, for: .selectedObjectID) } func updateVirtualObjectPosition(_ pos: SCNVector3, _ filterPosition: Bool) { guard let object = virtualObject else { return } guard let cameraTransform = session.currentFrame?.camera.transform else { return } let cameraWorldPos = SCNVector3.positionFromTransform(cameraTransform) var cameraToPosition = pos - cameraWorldPos // Limit the distance of the object from the camera to a maximum of 10 meters. cameraToPosition.setMaximumLength(10) // Compute the average distance of the object from the camera over the last ten // updates. If filterPosition is true, compute a new position for the object // with this average. Notice that the distance is applied to the vector from // the camera to the content, so it only affects the percieved distance of the // object - the averaging does _not_ make the content "lag". let hitTestResultDistance = CGFloat(cameraToPosition.length()) recentVirtualObjectDistances.append(hitTestResultDistance) recentVirtualObjectDistances.keepLast(10) if filterPosition { let averageDistance = recentVirtualObjectDistances.average! cameraToPosition.setLength(Float(averageDistance)) let averagedDistancePos = cameraWorldPos + cameraToPosition object.position = averagedDistancePos } else { object.position = cameraWorldPos + cameraToPosition } } func checkIfObjectShouldMoveOntoPlane(anchor: ARPlaneAnchor) { guard let object = virtualObject, let planeAnchorNode = sceneView.node(for: anchor) else { return } // Get the object's position in the plane's coordinate system. let objectPos = planeAnchorNode.convertPosition(object.position, from: object.parent) if objectPos.y == 0 { return; // The object is already on the plane - nothing to do here. } // Add 10% tolerance to the corners of the plane. let tolerance: Float = 0.1 let minX: Float = anchor.center.x - anchor.extent.x / 2 - anchor.extent.x * tolerance let maxX: Float = anchor.center.x + anchor.extent.x / 2 + anchor.extent.x * tolerance let minZ: Float = anchor.center.z - anchor.extent.z / 2 - anchor.extent.z * tolerance let maxZ: Float = anchor.center.z + anchor.extent.z / 2 + anchor.extent.z * tolerance if objectPos.x < minX || objectPos.x > maxX || objectPos.z < minZ || objectPos.z > maxZ { return } // Drop the object onto the plane if it is near it. let verticalAllowance: Float = 0.03 if objectPos.y > -verticalAllowance && objectPos.y < verticalAllowance { textManager.showDebugMessage("OBJECT MOVED\nSurface detected nearby") SCNTransaction.begin() SCNTransaction.animationDuration = 0.5 SCNTransaction.animationTimingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut) object.position.y = anchor.transform.columns.3.y SCNTransaction.commit() } } // MARK: - Virtual Object Loading var virtualObject: VirtualObject? var isLoadingObject: Bool = false { didSet { DispatchQueue.main.async { self.settingsButton.isEnabled = !self.isLoadingObject self.addObjectButton.isEnabled = !self.isLoadingObject self.screenshotButton.isEnabled = !self.isLoadingObject self.restartExperienceButton.isEnabled = !self.isLoadingObject } } } // MARK: - Projectile Launching @IBOutlet weak var triggerButton: UIButton! @IBOutlet weak var triggerIconImageView: UIImageView! var lastContactNode: SCNNode! @IBOutlet weak var circlePowerMeter: CircleProgressView! @IBOutlet weak var powerMeterLabel: UILabel! @objc func triggerNormalTap(_ sender: UIGestureRecognizer) { shootObject(longPressMultiplier: 0.5) } @objc func triggerLongTap(_ gesture: TimedLongPressGesture) { if gesture.state == .ended { shootObject(longPressMultiplier: Float(circlePowerMeter.progress)) circlePowerMeter.isHidden = true timer.invalidate() } else if gesture.state == .began { gesture.startTime = NSDate() circlePowerMeter.progress = 0 powerMeterLabel.text = "0" circlePowerMeter.isHidden = false timer = Timer.scheduledTimer(timeInterval: 0.01, target: self, selector: #selector(increaseProgressBar), userInfo: nil, repeats: true) } } @objc func increaseProgressBar() { if circlePowerMeter.progress < 1 { let newProgress = circlePowerMeter.progress + 0.01 circlePowerMeter.progress = newProgress powerMeterLabel.text = String(format: "%.2f", newProgress) } } func shootObject(longPressMultiplier: Float = 1) { guard let currentFrame = self.sceneView.session.currentFrame else { return } var translation = matrix_identity_float4x4 translation.columns.3.z = -0.3 if let footballObjectScene = SCNScene(named: "football.scn", inDirectory: "Models.scnassets/football"), self.virtualObject is FieldGoal { guard let footballNode = footballObjectScene.rootNode.childNode(withName: "football", recursively: true) else { fatalError("Node not found!") } let projectileNode: SCNNode = SCNNode() projectileNode.addChildNode(footballNode) projectileNode.name = "Projectile" projectileNode.physicsBody = SCNPhysicsBody(type: .dynamic, shape: SCNPhysicsShape(node: projectileNode, options: nil)) projectileNode.physicsBody?.isAffectedByGravity = true projectileNode.physicsBody?.categoryBitMask = PhysicsBodyType.projectile.rawValue projectileNode.physicsBody?.contactTestBitMask = PhysicsBodyType.goalFrame.rawValue projectileNode.physicsBody?.contactTestBitMask = PhysicsBodyType.goalPlane.rawValue projectileNode.physicsBody?.contactTestBitMask = PhysicsBodyType.plane.rawValue projectileNode.simdTransform = matrix_multiply(currentFrame.camera.transform, translation) let forceVector = SCNVector3(projectileNode.worldFront.x * 1,10 * longPressMultiplier, projectileNode.worldFront.z) projectileNode.physicsBody?.applyForce(forceVector, asImpulse: true) self.sceneView.scene.rootNode.addChildNode(projectileNode) } else if let soccerObjectScene = SCNScene(named: "soccerBall.scn", inDirectory: "Models.scnassets/soccerBall"), self.virtualObject is SoccerGoal { guard let soccerNode = soccerObjectScene.rootNode.childNode(withName: "ball", recursively: true) else { fatalError("Node not found!") } let projectileNode: SCNNode = SCNNode() projectileNode.addChildNode(soccerNode) projectileNode.name = "Projectile" projectileNode.physicsBody = SCNPhysicsBody(type: .dynamic, shape: SCNPhysicsShape(node: projectileNode, options: nil)) projectileNode.physicsBody?.isAffectedByGravity = false projectileNode.physicsBody?.categoryBitMask = PhysicsBodyType.projectile.rawValue projectileNode.physicsBody?.contactTestBitMask = PhysicsBodyType.goalFrame.rawValue projectileNode.physicsBody?.contactTestBitMask = PhysicsBodyType.goalPlane.rawValue projectileNode.physicsBody?.contactTestBitMask = PhysicsBodyType.plane.rawValue projectileNode.simdTransform = matrix_multiply(currentFrame.camera.transform, translation) let forceMultiplier = 10 * longPressMultiplier let forceVector = SCNVector3(projectileNode.worldFront.x * forceMultiplier, projectileNode.worldFront.y * forceMultiplier, projectileNode.worldFront.z * forceMultiplier) projectileNode.physicsBody?.applyForce(forceVector, asImpulse: true) self.sceneView.scene.rootNode.addChildNode(projectileNode) } } func physicsWorld(_ world: SCNPhysicsWorld, didBegin contact: SCNPhysicsContact) { let contactNode: SCNNode! // Make sure we set the contact node to what we suspect to be the projectile if contact.nodeA.name == "Projectile" { contactNode = contact.nodeB } else { contactNode = contact.nodeA } // Validate that that the collision is what we wanted if let hitObjectCategory = contactNode.physicsBody?.categoryBitMask { if hitObjectCategory == PhysicsBodyType.goalFrame.rawValue { textManager.showDebugMessage("HIT THE FRAME! SO CLOSE!!!") } else if hitObjectCategory == PhysicsBodyType.goalPlane.rawValue { // Collision has occurred, hit the confetti textManager.showDebugMessage("NICE SHOT!!!") if (showGoalConfetti) { launchConfetti() } } } } // MARK: - Cheerview func launchConfetti() { DispatchQueue.main.async { self.cheerView.start() } DispatchQueue.main.asyncAfter(deadline: .now() + 2) { self.cheerView.stop() } } @IBOutlet weak var addObjectButton: UIButton! func loadVirtualObject(at index: Int) { resetVirtualObject() // Show progress indicator let spinner = UIActivityIndicatorView() spinner.center = addObjectButton.center spinner.bounds.size = CGSize(width: addObjectButton.bounds.width - 5, height: addObjectButton.bounds.height - 5) addObjectButton.setImage(#imageLiteral(resourceName: "buttonring"), for: []) sceneView.addSubview(spinner) spinner.startAnimating() // Load the content asynchronously. DispatchQueue.global().async { self.isLoadingObject = true let object = VirtualObject.availableObjects[index] object.viewController = self self.virtualObject = object DispatchQueue.main.async { self.triggerButton.isHidden = false self.triggerIconImageView.isHidden = false if self.virtualObject is FieldGoal { self.triggerIconImageView.image = #imageLiteral(resourceName: "footballLaunch") } else if self.virtualObject is SoccerGoal { self.triggerIconImageView.image = #imageLiteral(resourceName: "soccerBallLaunch") } } object.loadModel() DispatchQueue.main.async { // Immediately place the object in 3D space. if let lastFocusSquarePos = self.focusSquare?.lastPosition { self.setNewVirtualObjectPosition(lastFocusSquarePos) } else { self.setNewVirtualObjectPosition(SCNVector3Zero) } // Remove progress indicator spinner.removeFromSuperview() // Update the icon of the add object button let buttonImage = UIImage.composeButtonImage(from: object.thumbImage) let pressedButtonImage = UIImage.composeButtonImage(from: object.thumbImage, alpha: 0.3) self.addObjectButton.setImage(buttonImage, for: []) self.addObjectButton.setImage(pressedButtonImage, for: [.highlighted]) self.isLoadingObject = false } } } @IBAction func chooseObject(_ button: UIButton) { // Abort if we are about to load another object to avoid concurrent modifications of the scene. if isLoadingObject { return } textManager.cancelScheduledMessage(forType: .contentPlacement) let rowHeight = 45 let popoverSize = CGSize(width: 250, height: rowHeight * VirtualObject.availableObjects.count) let objectViewController = VirtualObjectSelectionViewController(size: popoverSize) objectViewController.delegate = self objectViewController.modalPresentationStyle = .popover objectViewController.popoverPresentationController?.delegate = self self.present(objectViewController, animated: true, completion: nil) objectViewController.popoverPresentationController?.sourceView = button objectViewController.popoverPresentationController?.sourceRect = button.bounds } // MARK: - VirtualObjectSelectionViewControllerDelegate func virtualObjectSelectionViewController(_: VirtualObjectSelectionViewController, didSelectObjectAt index: Int) { loadVirtualObject(at: index) } func virtualObjectSelectionViewControllerDidDeselectObject(_: VirtualObjectSelectionViewController) { resetVirtualObject() } // MARK: - Planes var planes = [ARPlaneAnchor: Plane]() func addPlane(node: SCNNode, anchor: ARPlaneAnchor) { let pos = SCNVector3.positionFromTransform(anchor.transform) textManager.showDebugMessage("NEW SURFACE DETECTED AT \(pos.friendlyString())") let plane = Plane(anchor, showARPlanes, true, false) planes[anchor] = plane node.addChildNode(plane) textManager.cancelScheduledMessage(forType: .planeEstimation) textManager.showMessage("SURFACE DETECTED") if virtualObject == nil { textManager.scheduleMessage("TAP + TO PLACE AN OBJECT", inSeconds: 7.5, messageType: .contentPlacement) } } func updatePlane(anchor: ARPlaneAnchor) { if let plane = planes[anchor] { plane.update(anchor) } } func removePlane(anchor: ARPlaneAnchor) { if let plane = planes.removeValue(forKey: anchor) { plane.removeFromParentNode() } } func restartPlaneDetection() { // configure session if let worldSessionConfig = sessionConfig as? ARWorldTrackingConfiguration { worldSessionConfig.planeDetection = .horizontal session.run(worldSessionConfig, options: [.resetTracking, .removeExistingAnchors]) } // reset timer if trackingFallbackTimer != nil { trackingFallbackTimer!.invalidate() trackingFallbackTimer = nil } textManager.scheduleMessage("FIND A SURFACE TO PLACE AN OBJECT", inSeconds: 7.5, messageType: .planeEstimation) } // MARK: - Focus Square var focusSquare: FocusSquare? func setupFocusSquare() { focusSquare?.isHidden = true focusSquare?.removeFromParentNode() focusSquare = FocusSquare() sceneView.scene.rootNode.addChildNode(focusSquare!) textManager.scheduleMessage("TRY MOVING LEFT OR RIGHT", inSeconds: 5.0, messageType: .focusSquare) } func updateFocusSquare() { guard let screenCenter = screenCenter else { return } if virtualObject != nil && sceneView.isNode(virtualObject!, insideFrustumOf: sceneView.pointOfView!) { focusSquare?.hide() } else { focusSquare?.unhide() } let (worldPos, planeAnchor, _) = worldPositionFromScreenPosition(screenCenter, objectPos: focusSquare?.position) if let worldPos = worldPos { focusSquare?.update(for: worldPos, planeAnchor: planeAnchor, camera: self.session.currentFrame?.camera) textManager.cancelScheduledMessage(forType: .focusSquare) } } // MARK: - Debug Visualizations @IBOutlet var featurePointCountLabel: UILabel! func refreshFeaturePoints() { guard showARFeaturePoints else { return } // retrieve cloud guard let cloud = session.currentFrame?.rawFeaturePoints else { return } DispatchQueue.main.async { self.featurePointCountLabel.text = "Features: \(cloud.__count)".uppercased() } } var showDetailedMessages: Bool = UserDefaults.standard.bool(for: .showDetailedMessages) { didSet { // Message Panel featurePointCountLabel.isHidden = !showDetailedMessages debugMessageLabel.isHidden = !showDetailedMessages messagePanel.isHidden = !showDetailedMessages // save pref UserDefaults.standard.set(showDetailedMessages, for: .showDetailedMessages) } } var showARPlanes: Bool = UserDefaults.standard.bool(for: .showGrassARPlanes) { didSet { // Update Plane Visuals planes.values.forEach { $0.showARPlaneVisualizations(showARPlanes, true, false) } // save pref UserDefaults.standard.set(showARPlanes, for: .showGrassARPlanes) } } var showARFeaturePoints: Bool = UserDefaults.standard.bool(for: .showARFeaturePoints) { didSet { // SceneView Visuals if showARFeaturePoints { sceneView.debugOptions = [ARSCNDebugOptions.showFeaturePoints] } else { sceneView.debugOptions = [] } // save pref UserDefaults.standard.set(showARFeaturePoints, for: .showARFeaturePoints) } } var enableGoalDetection: Bool = UserDefaults.standard.bool(for: .enableGoalDetection) { didSet { self.restartExperience(self) // save pref UserDefaults.standard.set(enableGoalDetection, for: .enableGoalDetection) } } var showGoalConfetti: Bool = UserDefaults.standard.bool(for: .showGoalConfetti) { didSet { // save pref UserDefaults.standard.set(showGoalConfetti, for: .showGoalConfetti) } } func setupDebug() { // Set appearance of debug output panel messagePanel.layer.cornerRadius = 3.0 messagePanel.clipsToBounds = true } // MARK: - UI Elements and Actions @IBOutlet weak var messagePanel: UIView! @IBOutlet weak var messageLabel: UILabel! @IBOutlet weak var debugMessageLabel: UILabel! var textManager: VirtualGoalTextManager! func setupUIControls() { textManager = VirtualGoalTextManager(viewController: self) // hide debug message view debugMessageLabel.isHidden = true featurePointCountLabel.text = "" debugMessageLabel.text = "" messageLabel.text = "" } @IBOutlet weak var closeExperienceButton: UIButton! @IBAction func closeExperience(_ sender: UIButton) { self.dismiss(animated: true, completion: nil) } @IBOutlet weak var restartExperienceButton: UIButton! var restartExperienceButtonIsEnabled = true @IBAction func restartExperience(_ sender: Any) { guard restartExperienceButtonIsEnabled, !isLoadingObject else { return } DispatchQueue.main.async { self.restartExperienceButtonIsEnabled = false self.textManager.cancelAllScheduledMessages() self.textManager.dismissPresentedAlert() self.textManager.showMessage("STARTING A NEW SESSION") self.use3DOFTracking = false self.setupFocusSquare() self.resetVirtualObject() self.restartPlaneDetection() self.restartExperienceButton.setImage(#imageLiteral(resourceName: "restart"), for: []) self.textManager.unblurBackground() // Disable Restart button for five seconds in order to give the session enough time to restart. DispatchQueue.main.asyncAfter(deadline: .now() + 5.0, execute: { self.restartExperienceButtonIsEnabled = true }) } } @IBOutlet weak var screenshotButton: UIButton! @IBAction func takeScreenshot() { guard screenshotButton.isEnabled else { return } let takeScreenshotBlock = { UIImageWriteToSavedPhotosAlbum(self.sceneView.snapshot(), nil, nil, nil) DispatchQueue.main.async { // Briefly flash the screen. let flashOverlay = UIView(frame: self.sceneView.frame) flashOverlay.backgroundColor = UIColor.white self.sceneView.addSubview(flashOverlay) UIView.animate(withDuration: 0.25, animations: { flashOverlay.alpha = 0.0 }, completion: { _ in flashOverlay.removeFromSuperview() }) } } switch PHPhotoLibrary.authorizationStatus() { case .authorized: takeScreenshotBlock() case .restricted, .denied: let title = "Photos access denied" let message = "Please enable Photos access for this application in Settings > Privacy to allow saving screenshots." textManager.showAlert(title: title, message: message) case .notDetermined: PHPhotoLibrary.requestAuthorization({ (authorizationStatus) in if authorizationStatus == .authorized { takeScreenshotBlock() } }) } } // MARK: - Screen Recording (Not implemented yet) fileprivate let recorder = RPScreenRecorder.shared() @IBOutlet weak var screenRecordingLabel: UILabel! @IBOutlet weak var screenRecordButton: UIButton! @IBOutlet weak var stopRecordButton: UIButton! @IBAction func screenRecordButtonPressed(_ sender: UIButton) { // start recording recorder.startRecording(handler: { [unowned self] error in if let error = error { NSLog("Failed start recording: \(error.localizedDescription)") return } DispatchQueue.main.async { [unowned self] in self.screenRecordButton.isHidden = true self.stopRecordButton.isHidden = false self.screenRecordingLabel.isHidden = false } NSLog("Start recording") }) } @IBAction func stopRecordButtonPressed(_ sender: Any) { // end recording recorder.stopRecording(handler: { [unowned self] (previewViewController, error) in if let error = error { NSLog("Failed stop recording: \(error.localizedDescription)") return } DispatchQueue.main.async { self.screenRecordButton.isHidden = false self.stopRecordButton.isHidden = true self.screenRecordingLabel.isHidden = true } NSLog("Stop recording") previewViewController?.previewControllerDelegate = self DispatchQueue.main.async { [unowned self] in // show preview window self.present(previewViewController!, animated: true, completion: nil) } }) } // ========================================================================= // MARK: - RPScreenRecorderDelegate // called after stopping the recording func screenRecorder(_ screenRecorder: RPScreenRecorder, didStopRecordingWithError error: Error, previewViewController: RPPreviewViewController?) { DispatchQueue.main.async { [unowned self] in self.screenRecordButton.setImage(UIImage(named: "startRecord"), for: .normal) } NSLog("Stop recording") } // called when the recorder availability has changed func screenRecorderDidChangeAvailability(_ screenRecorder: RPScreenRecorder) { let availability = screenRecorder.isAvailable NSLog("Availablility: \(availability)") } // ========================================================================= // MARK: - RPPreviewViewControllerDelegate // called when preview is finished func previewControllerDidFinish(_ previewController: RPPreviewViewController) { NSLog("Preview finish") DispatchQueue.main.async { [unowned previewController] in // close preview window previewController.dismiss(animated: true, completion: nil) } } // MARK: - Settings @IBOutlet weak var settingsButton: UIButton! @IBAction func showSettings(_ button: UIButton) { let storyboard = UIStoryboard(name: "Main", bundle: nil) guard let settingsViewController = storyboard.instantiateViewController(withIdentifier: "settingsViewController") as? VirtualGoalSettingsViewController else { return } let barButtonItem = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(dismissSettings)) settingsViewController.navigationItem.rightBarButtonItem = barButtonItem settingsViewController.title = "Options" let navigationController = UINavigationController(rootViewController: settingsViewController) navigationController.modalPresentationStyle = .popover navigationController.popoverPresentationController?.delegate = self navigationController.preferredContentSize = CGSize(width: sceneView.bounds.size.width - 20, height: sceneView.bounds.size.height - 50) self.present(navigationController, animated: true, completion: nil) navigationController.popoverPresentationController?.sourceView = settingsButton navigationController.popoverPresentationController?.sourceRect = settingsButton.bounds } @objc func dismissSettings() { self.dismiss(animated: true, completion: nil) updateSettings() } private func updateSettings() { let defaults = UserDefaults.standard showDetailedMessages = defaults.bool(for: .showDetailedMessages) showARPlanes = defaults.bool(for: .showGrassARPlanes) showARFeaturePoints = defaults.bool(for: .showARFeaturePoints) enableGoalDetection = defaults.bool(for: .enableGoalDetection) showGoalConfetti = defaults.bool(for: .showGoalConfetti) dragOnInfinitePlanesEnabled = defaults.bool(for: .dragOnInfinitePlanes) use3DOFTrackingFallback = defaults.bool(for: .use3DOFFallback) } // MARK: - Error handling func displayErrorMessage(title: String, message: String, allowRestart: Bool = false) { // Blur the background. textManager.blurBackground() if allowRestart { // Present an alert informing about the error that has occurred. let restartAction = UIAlertAction(title: "Reset", style: .default) { _ in self.textManager.unblurBackground() self.restartExperience(self) } textManager.showAlert(title: title, message: message, actions: [restartAction]) } else { textManager.showAlert(title: title, message: message, actions: []) } } // MARK: - UIPopoverPresentationControllerDelegate func adaptivePresentationStyle(for controller: UIPresentationController) -> UIModalPresentationStyle { return .none } func popoverPresentationControllerDidDismissPopover(_ popoverPresentationController: UIPopoverPresentationController) { updateSettings() } } class TimedLongPressGesture: UILongPressGestureRecognizer { var startTime: NSDate? }
apache-2.0
ae7fd26f284b2157279a59b85ec7e6be
37.680328
265
0.683174
4.643314
false
false
false
false
WhisperSystems/Signal-iOS
Signal/src/ViewControllers/MediaGallery/Transitions/MediaDismissAnimationController.swift
1
12051
// // Copyright (c) 2019 Open Whisper Systems. All rights reserved. // import Foundation import PromiseKit class MediaDismissAnimationController: NSObject { private let galleryItem: MediaGalleryItem public let interactionController: MediaInteractiveDismiss? var transitionView: UIView? var fromMediaFrame: CGRect? var pendingCompletion: (() -> Promise<Void>)? init(galleryItem: MediaGalleryItem, interactionController: MediaInteractiveDismiss? = nil) { self.galleryItem = galleryItem self.interactionController = interactionController } } extension MediaDismissAnimationController: UIViewControllerAnimatedTransitioning { func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval { return kIsDebuggingMediaPresentationAnimations ? 1.5 : 0.15 } func animateTransition(using transitionContext: UIViewControllerContextTransitioning) { let containerView = transitionContext.containerView guard let fromVC = transitionContext.viewController(forKey: .from) else { owsFailDebug("fromVC was unexpectedly nil") transitionContext.completeTransition(false) return } let fromContextProvider: MediaPresentationContextProvider switch fromVC { case let contextProvider as MediaPresentationContextProvider: fromContextProvider = contextProvider case let navController as UINavigationController: guard let contextProvider = navController.topViewController as? MediaPresentationContextProvider else { owsFailDebug("unexpected context: \(String(describing: navController.topViewController))") transitionContext.completeTransition(false) return } fromContextProvider = contextProvider default: owsFailDebug("unexpected fromVC: \(fromVC)") transitionContext.completeTransition(false) return } guard let fromMediaContext = fromContextProvider.mediaPresentationContext(galleryItem: galleryItem, in: containerView) else { owsFailDebug("fromPresentationContext was unexpectedly nil") transitionContext.completeTransition(false) return } self.fromMediaFrame = fromMediaContext.presentationFrame guard let toVC = transitionContext.viewController(forKey: .to) else { owsFailDebug("toVC was unexpectedly nil") transitionContext.completeTransition(false) return } // toView will be nil if doing a modal dismiss, in which case we don't want to add the view - // it's already in the view hierarchy, behind the VC we're dismissing. if let toView = transitionContext.view(forKey: .to) { containerView.insertSubview(toView, at: 0) } guard let fromView = transitionContext.view(forKey: .from) else { owsFailDebug("fromView was unexpectedly nil") transitionContext.completeTransition(false) return } let toContextProvider: MediaPresentationContextProvider switch toVC { case let contextProvider as MediaPresentationContextProvider: toContextProvider = contextProvider case let navController as UINavigationController: guard let contextProvider = navController.topViewController as? MediaPresentationContextProvider else { owsFailDebug("unexpected context: \(String(describing: navController.topViewController))") return } toContextProvider = contextProvider default: owsFailDebug("unexpected toVC: \(toVC)") transitionContext.completeTransition(false) return } let toMediaContext = toContextProvider.mediaPresentationContext(galleryItem: galleryItem, in: containerView) guard let presentationImage = galleryItem.attachmentStream.originalImage else { owsFailDebug("presentationImage was unexpectedly nil") // Complete transition immediately. fromContextProvider.mediaWillPresent(fromContext: fromMediaContext) if let toMediaContext = toMediaContext { toContextProvider.mediaWillPresent(toContext: toMediaContext) } DispatchQueue.main.async { fromContextProvider.mediaDidPresent(fromContext: fromMediaContext) if let toMediaContext = toMediaContext { toContextProvider.mediaDidPresent(toContext: toMediaContext) } transitionContext.completeTransition(true) } return } let transitionView = UIImageView(image: presentationImage) transitionView.contentMode = .scaleAspectFill transitionView.layer.masksToBounds = true transitionView.layer.cornerRadius = fromMediaContext.cornerRadius self.transitionView = transitionView containerView.addSubview(transitionView) transitionView.frame = fromMediaContext.presentationFrame let fromTransitionalOverlayView: UIView? if let (overlayView, overlayViewFrame) = fromContextProvider.snapshotOverlayView(in: containerView) { fromTransitionalOverlayView = overlayView containerView.addSubview(overlayView) overlayView.frame = overlayViewFrame } else { owsFailDebug("expected overlay while dismissing media view") fromTransitionalOverlayView = nil } assert(toContextProvider.snapshotOverlayView(in: containerView) == nil) // Because toggling `isHidden` causes UIStack view layouts to change, we instead toggle `alpha` fromTransitionalOverlayView?.alpha = 1.0 fromMediaContext.mediaView.alpha = 0.0 toMediaContext?.mediaView.alpha = 0.0 let duration = transitionDuration(using: transitionContext) let completion = { () -> Promise<Void> in let destinationFrame: CGRect let destinationCornerRadius: CGFloat if transitionContext.transitionWasCancelled { destinationFrame = fromMediaContext.presentationFrame destinationCornerRadius = fromMediaContext.cornerRadius } else if let toMediaContext = toMediaContext { destinationFrame = toMediaContext.presentationFrame destinationCornerRadius = toMediaContext.cornerRadius } else { // `toMediaContext` can be nil if the target item is scrolled off of the // contextProvider's screen, so we synthesize a context to dismiss the item // off screen let offscreenFrame = fromMediaContext.presentationFrame.offsetBy(dx: 0, dy: UIScreen.main.bounds.height) destinationFrame = offscreenFrame destinationCornerRadius = fromMediaContext.cornerRadius } return UIView.animate(.promise, duration: duration, delay: 0.0, options: [.beginFromCurrentState, .curveEaseInOut]) { transitionView.frame = destinationFrame transitionView.layer.cornerRadius = destinationCornerRadius }.done { _ in fromTransitionalOverlayView?.removeFromSuperview() transitionView.removeFromSuperview() fromMediaContext.mediaView.alpha = 1.0 toMediaContext?.mediaView.alpha = 1.0 if transitionContext.transitionWasCancelled { // the "to" view will be nil if we're doing a modal dismiss, in which case // we wouldn't want to remove the toView. transitionContext.view(forKey: .to)?.removeFromSuperview() } else { assert(transitionContext.view(forKey: .from) != nil) transitionContext.view(forKey: .from)?.removeFromSuperview() } transitionContext.completeTransition(!transitionContext.transitionWasCancelled) }.done { fromContextProvider.mediaDidDismiss(fromContext: fromMediaContext) if let toMediaContext = toMediaContext { toContextProvider.mediaDidDismiss(toContext: toMediaContext) } }.done { // HACK: First Responder Juggling // // First responder status is relinquished to the toVC upon the // *start* of the dismissal. This is surprisng for two reasons: // 1. I'd expect the input toolbar to be dismissed interactively, since we're in // an interactive transition. // 2. I'd expect cancelling the transition to restore first responder to the // fromVC. // // Scenario 1: Cancelled dismissal causes CVC input toolbar over the media view. // // Scenario 2: Cancelling dismissal, followed by an actual dismissal to CVC, // results in a non-visible input toolbar. // // A known bug with this approach is that the *first* time you start to dismiss // you'll see the input toolbar enter the screen. It will dismiss itself if you // cancel the transition. let firstResponderVC = transitionContext.transitionWasCancelled ? fromVC : toVC if !firstResponderVC.isFirstResponder { Logger.verbose("regaining first responder") firstResponderVC.becomeFirstResponder() } } } if transitionContext.isInteractive { self.pendingCompletion = completion } else { Logger.verbose("ran completion simultaneously for non-interactive transition") completion().retainUntilComplete() } fromContextProvider.mediaWillDismiss(fromContext: fromMediaContext) if let toMediaContext = toMediaContext { toContextProvider.mediaWillDismiss(toContext: toMediaContext) } UIView.animate(.promise, duration: duration, delay: 0.0, options: [.beginFromCurrentState, .curveEaseInOut]) { fromTransitionalOverlayView?.alpha = 0.0 fromView.alpha = 0.0 }.then { (_: Bool) -> Promise<Void> in guard let pendingCompletion = self.pendingCompletion else { Logger.verbose("pendingCompletion already ran by the time fadeout completed.") return Promise.value(()) } Logger.verbose("ran pendingCompletion after fadeout") self.pendingCompletion = nil return pendingCompletion() }.retainUntilComplete() } } extension MediaDismissAnimationController: InteractiveDismissDelegate { func interactiveDismiss(_ interactiveDismiss: MediaInteractiveDismiss, didChangeTouchOffset offset: CGPoint) { guard let transitionView = transitionView else { // transition hasn't started yet. return } guard let fromMediaFrame = fromMediaFrame else { owsFailDebug("fromMediaFrame was unexpectedly nil") return } transitionView.center = fromMediaFrame.offsetBy(dx: offset.x, dy: offset.y).center } func interactiveDismissDidFinish(_ interactiveDismiss: MediaInteractiveDismiss) { if let pendingCompletion = pendingCompletion { Logger.verbose("interactive gesture started pendingCompletion during fadeout") self.pendingCompletion = nil pendingCompletion().retainUntilComplete() } } }
gpl-3.0
c56a6001f48077654577b1438c22c430
44.475472
133
0.641607
6.117259
false
false
false
false
roambotics/swift
test/SILGen/objc_protocols.swift
1
16904
// RUN: %target-swift-emit-silgen -module-name objc_protocols -sdk %S/Inputs -I %S/Inputs -enable-source-import %s -disable-objc-attr-requires-foundation-module | %FileCheck %s // REQUIRES: objc_interop import gizmo import objc_protocols_Bas @objc protocol NSRuncing { func runce() -> NSObject func copyRuncing() -> NSObject func foo() static func mince() -> NSObject } @objc protocol NSFunging { func funge() func foo() } protocol Ansible { func anse() } // CHECK-LABEL: sil hidden [ossa] @$s14objc_protocols0A8_generic{{[_0-9a-zA-Z]*}}F // CHECK: bb0([[THIS:%.*]] : @guaranteed $T): // -- Result of runce is autoreleased according to default objc conv // CHECK: [[METHOD:%.*]] = objc_method [[THIS]] : {{\$.*}}, #NSRuncing.runce!foreign // CHECK: [[RESULT1:%.*]] = apply [[METHOD]]<T>([[THIS:%.*]]) : $@convention(objc_method) <ฯ„_0_0 where ฯ„_0_0 : NSRuncing> (ฯ„_0_0) -> @autoreleased NSObject // -- Result of copyRuncing is received copy_valued according to -copy family // CHECK: [[METHOD:%.*]] = objc_method [[THIS]] : {{\$.*}}, #NSRuncing.copyRuncing!foreign // CHECK: [[RESULT2:%.*]] = apply [[METHOD]]<T>([[THIS:%.*]]) : $@convention(objc_method) <ฯ„_0_0 where ฯ„_0_0 : NSRuncing> (ฯ„_0_0) -> @owned NSObject // -- Arguments are not consumed by objc calls // CHECK-NOT: destroy_value [[THIS]] func objc_generic<T : NSRuncing>(_ x: T) -> (NSObject, NSObject) { return (x.runce(), x.copyRuncing()) } // CHECK-LABEL: sil hidden [ossa] @$s14objc_protocols0A22_generic_partial_applyyyxAA9NSRuncingRzlF : $@convention(thin) <T where T : NSRuncing> (@guaranteed T) -> () { func objc_generic_partial_apply<T : NSRuncing>(_ x: T) { // CHECK: bb0([[ARG:%.*]] : @guaranteed $T): // CHECK: [[FN:%.*]] = function_ref @$s14objc_protocols0A22_generic_partial_applyyyxAA9NSRuncingRzlFSo8NSObjectCycxcfu_ _ = x.runce // CHECK: [[FN:%.*]] = function_ref @$s14objc_protocols0A22_generic_partial_applyyyxAA9NSRuncingRzlFSo8NSObjectCycxcfu1_ _ = T.runce // CHECK: [[FN:%.*]] = function_ref @$s14objc_protocols0A22_generic_partial_applyyyxAA9NSRuncingRzlFSo8NSObjectCycfu3_ _ = T.mince // CHECK-NOT: destroy_value [[ARG]] } // CHECK: } // end sil function '$s14objc_protocols0A22_generic_partial_applyyyxAA9NSRuncingRzlF' // CHECK: sil private [ossa] @$s14objc_protocols0A22_generic_partial_applyyyxAA9NSRuncingRzlFSo8NSObjectCycxcfu_ : $@convention(thin) <T where T : NSRuncing> (@guaranteed T) -> @owned @callee_guaranteed () -> @owned NSObject { // CHECK: function_ref @$s14objc_protocols0A22_generic_partial_applyyyxAA9NSRuncingRzlFSo8NSObjectCycxcfu_AEycfu0_ : $@convention(thin) <ฯ„_0_0 where ฯ„_0_0 : NSRuncing> (@guaranteed ฯ„_0_0) -> @owned NSObject // CHECK: } // end sil function '$s14objc_protocols0A22_generic_partial_applyyyxAA9NSRuncingRzlFSo8NSObjectCycxcfu_' // CHECK: sil private [ossa] @$s14objc_protocols0A22_generic_partial_applyyyxAA9NSRuncingRzlFSo8NSObjectCycxcfu_AEycfu0_ : $@convention(thin) <T where T : NSRuncing> (@guaranteed T) -> @owned NSObject { // CHECK: objc_method %0 : $T, #NSRuncing.runce!foreign : <Self where Self : NSRuncing> (Self) -> () -> NSObject, $@convention(objc_method) <ฯ„_0_0 where ฯ„_0_0 : NSRuncing> (ฯ„_0_0) -> @autoreleased NSObject // CHECK: } // end sil function '$s14objc_protocols0A22_generic_partial_applyyyxAA9NSRuncingRzlFSo8NSObjectCycxcfu_AEycfu0_' // CHECK: sil private [ossa] @$s14objc_protocols0A22_generic_partial_applyyyxAA9NSRuncingRzlFSo8NSObjectCycxcfu1_ : $@convention(thin) <T where T : NSRuncing> (@guaranteed T) -> @owned @callee_guaranteed () -> @owned NSObject // CHECK: function_ref @$s14objc_protocols0A22_generic_partial_applyyyxAA9NSRuncingRzlFSo8NSObjectCycxcfu1_AEycfu2_ : $@convention(thin) <ฯ„_0_0 where ฯ„_0_0 : NSRuncing> (@guaranteed ฯ„_0_0) -> @owned NSObject // CHECK: } // end sil function '$s14objc_protocols0A22_generic_partial_applyyyxAA9NSRuncingRzlFSo8NSObjectCycxcfu1_' // CHECK: sil private [ossa] @$s14objc_protocols0A22_generic_partial_applyyyxAA9NSRuncingRzlFSo8NSObjectCycxcfu1_AEycfu2_ : $@convention(thin) <T where T : NSRuncing> (@guaranteed T) -> @owned NSObject // CHECK: objc_method %0 : $T, #NSRuncing.runce!foreign : <Self where Self : NSRuncing> (Self) -> () -> NSObject, $@convention(objc_method) <ฯ„_0_0 where ฯ„_0_0 : NSRuncing> (ฯ„_0_0) -> @autoreleased NSObject // CHECK: } // end sil function '$s14objc_protocols0A22_generic_partial_applyyyxAA9NSRuncingRzlFSo8NSObjectCycxcfu1_AEycfu2_' // CHECK-LABEL: sil private [ossa] @$s14objc_protocols0A22_generic_partial_applyyyxAA9NSRuncingRzlFSo8NSObjectCycfu3_ : $@convention(thin) <T where T : NSRuncing> (@thick T.Type) -> @owned NSObject // CHECK: objc_method %2 : $@objc_metatype T.Type, #NSRuncing.mince!foreign : <Self where Self : NSRuncing> (Self.Type) -> () -> NSObject, $@convention(objc_method) <ฯ„_0_0 where ฯ„_0_0 : NSRuncing> (@objc_metatype ฯ„_0_0.Type) -> @autoreleased NSObject // CHECK: } // end sil function '$s14objc_protocols0A22_generic_partial_applyyyxAA9NSRuncingRzlFSo8NSObjectCycfu3_' // CHECK-LABEL: sil hidden [ossa] @$s14objc_protocols0A9_protocol{{[_0-9a-zA-Z]*}}F // CHECK: bb0([[THIS:%.*]] : @guaranteed $any NSRuncing): // -- Result of runce is autoreleased according to default objc conv // CHECK: [[THIS1:%.*]] = open_existential_ref [[THIS]] : $any NSRuncing to $[[OPENED:@opened\(.*, any NSRuncing\) Self]] // CHECK: [[METHOD:%.*]] = objc_method [[THIS1]] : $[[OPENED]], #NSRuncing.runce!foreign // CHECK: [[RESULT1:%.*]] = apply [[METHOD]]<[[OPENED]]>([[THIS1]]) // -- Result of copyRuncing is received copy_valued according to -copy family // CHECK: [[THIS2:%.*]] = open_existential_ref [[THIS]] : $any NSRuncing to $[[OPENED2:@opened\(.*, any NSRuncing\) Self]] // CHECK: [[METHOD:%.*]] = objc_method [[THIS2]] : $[[OPENED2]], #NSRuncing.copyRuncing!foreign // CHECK: [[RESULT2:%.*]] = apply [[METHOD]]<[[OPENED2]]>([[THIS2:%.*]]) // -- Arguments are not consumed by objc calls // CHECK-NOT: destroy_value [[THIS]] func objc_protocol(_ x: NSRuncing) -> (NSObject, NSObject) { return (x.runce(), x.copyRuncing()) } // CHECK-LABEL: sil hidden [ossa] @$s14objc_protocols0A23_protocol_partial_applyyyAA9NSRuncing_pF : $@convention(thin) (@guaranteed any NSRuncing) -> () { func objc_protocol_partial_apply(_ x: NSRuncing) { // CHECK: bb0([[ARG:%.*]] : @guaranteed $any NSRuncing): // CHECK: [[FN:%.*]] = function_ref @$s14objc_protocols0A23_protocol_partial_applyyyAA9NSRuncing_pFSo8NSObjectCycAaC_pcfu_ // CHECK: [[RESULT:%.*]] = apply [[FN]]([[ARG]]) _ = x.runce // rdar://21289579 _ = NSRuncing.runce } // CHECK: } // end sil function '$s14objc_protocols0A23_protocol_partial_applyyyAA9NSRuncing_pF' // CHECK-LABEL: sil hidden [ossa] @$s14objc_protocols0A21_protocol_composition{{[_0-9a-zA-Z]*}}F func objc_protocol_composition(_ x: NSRuncing & NSFunging) { // CHECK: [[THIS:%.*]] = open_existential_ref [[THIS_ORIG:%.*]] : $any NSFunging & NSRuncing to $[[OPENED:@opened\(.*, any NSFunging & NSRuncing\) Self]] // CHECK: [[METHOD:%.*]] = objc_method [[THIS]] : $[[OPENED]], #NSRuncing.runce!foreign // CHECK: apply [[METHOD]]<[[OPENED]]>([[THIS]]) x.runce() // CHECK: [[THIS:%.*]] = open_existential_ref [[THIS_ORIG:%.*]] : $any NSFunging & NSRuncing to $[[OPENED:@opened\(.*, any NSFunging & NSRuncing\) Self]] // CHECK: [[METHOD:%.*]] = objc_method [[THIS]] : $[[OPENED]], #NSFunging.funge!foreign // CHECK: apply [[METHOD]]<[[OPENED]]>([[THIS]]) x.funge() } // -- ObjC thunks get emitted for ObjC protocol conformances class Foo : NSRuncing, NSFunging, Ansible { // -- NSRuncing @objc func runce() -> NSObject { return NSObject() } @objc func copyRuncing() -> NSObject { return NSObject() } @objc static func mince() -> NSObject { return NSObject() } // -- NSFunging @objc func funge() {} // -- Both NSRuncing and NSFunging @objc func foo() {} // -- Ansible func anse() {} } // CHECK-LABEL: sil private [thunk] [ossa] @$s14objc_protocols3FooC5runce{{[_0-9a-zA-Z]*}}FTo // CHECK-LABEL: sil private [thunk] [ossa] @$s14objc_protocols3FooC11copyRuncing{{[_0-9a-zA-Z]*}}FTo // CHECK-LABEL: sil private [thunk] [ossa] @$s14objc_protocols3FooC5funge{{[_0-9a-zA-Z]*}}FTo // CHECK-LABEL: sil private [thunk] [ossa] @$s14objc_protocols3FooC3foo{{[_0-9a-zA-Z]*}}FTo // CHECK-NOT: sil hidden [ossa] @_TToF{{.*}}anse{{.*}} class Bar { } extension Bar : NSRuncing { @objc func runce() -> NSObject { return NSObject() } @objc func copyRuncing() -> NSObject { return NSObject() } @objc func foo() {} @objc static func mince() -> NSObject { return NSObject() } } // CHECK-LABEL: sil private [thunk] [ossa] @$s14objc_protocols3BarC5runce{{[_0-9a-zA-Z]*}}FTo // CHECK-LABEL: sil private [thunk] [ossa] @$s14objc_protocols3BarC11copyRuncing{{[_0-9a-zA-Z]*}}FTo // CHECK-LABEL: sil private [thunk] [ossa] @$s14objc_protocols3BarC3foo{{[_0-9a-zA-Z]*}}FTo // class Bas from objc_protocols_Bas module extension Bas : NSRuncing { // runce() implementation from the original definition of Bas @objc func copyRuncing() -> NSObject { return NSObject() } @objc func foo() {} @objc static func mince() -> NSObject { return NSObject() } } // CHECK-LABEL: sil private [thunk] [ossa] @$s18objc_protocols_Bas0C0C0a1_B0E11copyRuncing{{[_0-9a-zA-Z]*}}FTo // CHECK-LABEL: sil private [thunk] [ossa] @$s18objc_protocols_Bas0C0C0a1_B0E3foo{{[_0-9a-zA-Z]*}}FTo // -- Inherited objc protocols protocol Fungible : NSFunging { } class Zim : Fungible { @objc func funge() {} @objc func foo() {} } // CHECK-LABEL: sil private [thunk] [ossa] @$s14objc_protocols3ZimC5funge{{[_0-9a-zA-Z]*}}FTo // CHECK-LABEL: sil private [thunk] [ossa] @$s14objc_protocols3ZimC3foo{{[_0-9a-zA-Z]*}}FTo // class Zang from objc_protocols_Bas module extension Zang : Fungible { // funge() implementation from the original definition of Zim @objc func foo() {} } // CHECK-LABEL: sil private [thunk] [ossa] @$s18objc_protocols_Bas4ZangC0a1_B0E3foo{{[_0-9a-zA-Z]*}}FTo // -- objc protocols with property requirements in extensions // <rdar://problem/16284574> @objc protocol NSCounting { var count: Int {get} } class StoredPropertyCount { @objc let count = 0 } extension StoredPropertyCount: NSCounting {} // CHECK-LABEL: sil private [transparent] [thunk] [ossa] @$s14objc_protocols19StoredPropertyCountC5countSivgTo class ComputedPropertyCount { @objc var count: Int { return 0 } } extension ComputedPropertyCount: NSCounting {} // CHECK-LABEL: sil private [thunk] [ossa] @$s14objc_protocols21ComputedPropertyCountC5countSivgTo // -- adding @objc protocol conformances to native ObjC classes should not // emit thunks since the methods are already available to ObjC. // Gizmo declared in Inputs/usr/include/Gizmo.h extension Gizmo : NSFunging { } // CHECK-NOT: _TTo{{.*}}5Gizmo{{.*}} @objc class InformallyFunging { @objc func funge() {} @objc func foo() {} } extension InformallyFunging: NSFunging { } @objc protocol Initializable { init(int: Int) } // CHECK-LABEL: sil hidden [ossa] @$s14objc_protocols28testInitializableExistential_1iAA0D0_pAaD_pXp_SitF : $@convention(thin) (@thick any Initializable.Type, Int) -> @owned any Initializable { func testInitializableExistential(_ im: Initializable.Type, i: Int) -> Initializable { // CHECK: bb0([[META:%[0-9]+]] : $@thick any Initializable.Type, [[I:%[0-9]+]] : $Int): // CHECK: [[I2_BOX:%[0-9]+]] = alloc_box ${ var any Initializable } // CHECK: [[I2_LIFETIME:%[0-9]+]] = begin_borrow [lexical] [[I2_BOX]] // CHECK: [[PB:%.*]] = project_box [[I2_LIFETIME]] // CHECK: [[ARCHETYPE_META:%[0-9]+]] = open_existential_metatype [[META]] : $@thick any Initializable.Type to $@thick (@opened([[N:".*"]], any Initializable) Self).Type // CHECK: [[ARCHETYPE_META_OBJC:%[0-9]+]] = thick_to_objc_metatype [[ARCHETYPE_META]] : $@thick (@opened([[N]], any Initializable) Self).Type to $@objc_metatype (@opened([[N]], any Initializable) Self).Type // CHECK: [[I2_ALLOC:%[0-9]+]] = alloc_ref_dynamic [objc] [[ARCHETYPE_META_OBJC]] : $@objc_metatype (@opened([[N]], any Initializable) Self).Type, $@opened([[N]], any Initializable) Self // CHECK: [[INIT_WITNESS:%[0-9]+]] = objc_method [[I2_ALLOC]] : $@opened([[N]], any Initializable) Self, #Initializable.init!initializer.foreign : {{.*}} // CHECK: [[I2:%[0-9]+]] = apply [[INIT_WITNESS]]<@opened([[N]], any Initializable) Self>([[I]], [[I2_ALLOC]]) : $@convention(objc_method) <ฯ„_0_0 where ฯ„_0_0 : Initializable> (Int, @owned ฯ„_0_0) -> @owned ฯ„_0_0 // CHECK: [[I2_EXIST_CONTAINER:%[0-9]+]] = init_existential_ref [[I2]] : $@opened([[N]], any Initializable) Self : $@opened([[N]], any Initializable) Self, $any Initializable // CHECK: store [[I2_EXIST_CONTAINER]] to [init] [[PB]] : $*any Initializable // CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[PB]] : $*any Initializable // CHECK: [[I2:%[0-9]+]] = load [copy] [[READ]] : $*any Initializable // CHECK: end_borrow [[I2_LIFETIME]] // CHECK: destroy_value [[I2_BOX]] : ${ var any Initializable } // CHECK: return [[I2]] : $any Initializable var i2 = im.init(int: i) return i2 } // CHECK: } // end sil function '$s14objc_protocols28testInitializableExistential_1iAA0D0_pAaD_pXp_SitF' class InitializableConformer: Initializable { @objc required init(int: Int) {} } // CHECK-LABEL: sil private [thunk] [ossa] @$s14objc_protocols22InitializableConformerC{{[_0-9a-zA-Z]*}}fcTo final class InitializableConformerByExtension { init() {} } extension InitializableConformerByExtension: Initializable { @objc convenience init(int: Int) { self.init() } } // CHECK-LABEL: sil private [thunk] [ossa] @$s14objc_protocols33InitializableConformerByExtensionC{{[_0-9a-zA-Z]*}}fcTo // Make sure we're crashing from trying to use materializeForSet here. @objc protocol SelectionItem { var time: Double { get set } } func incrementTime(contents: SelectionItem) { contents.time += 1.0 } @objc public protocol DangerousEscaper { @objc func malicious(_ mayActuallyEscape: () -> ()) } // Make sure we emit an withoutActuallyEscaping sentinel. // CHECK-LABEL: sil [ossa] @$s14objc_protocols19couldActuallyEscapeyyyyc_AA16DangerousEscaper_ptF : $@convention(thin) (@guaranteed @callee_guaranteed () -> (), @guaranteed any DangerousEscaper) -> () { // CHECK: bb0([[CLOSURE_ARG:%.*]] : @guaranteed $@callee_guaranteed () -> (), [[SELF:%.*]] : @guaranteed $any DangerousEscaper): // CHECK: [[OE:%.*]] = open_existential_ref [[SELF]] // CHECK: [[CLOSURE_COPY1:%.*]] = copy_value [[CLOSURE_ARG]] // CHECK: [[NOESCAPE:%.*]] = convert_escape_to_noescape [not_guaranteed] [[CLOSURE_COPY1]] // CHECK: [[WITHOUT_ACTUALLY_ESCAPING_THUNK:%.*]] = function_ref @$sIg_Ieg_TR : $@convention(thin) (@noescape @callee_guaranteed () -> ()) -> () // CHECK: [[WITHOUT_ACTUALLY_ESCAPING_SENTINEL:%.*]] = partial_apply [callee_guaranteed] [[WITHOUT_ACTUALLY_ESCAPING_THUNK]]([[NOESCAPE]]) // CHECK: [[WITHOUT_ESCAPING:%.*]] = mark_dependence [[WITHOUT_ACTUALLY_ESCAPING_SENTINEL]] : $@callee_guaranteed () -> () on [[NOESCAPE]] // CHECK: [[WITHOUT_ESCAPING_COPY:%.*]] = copy_value [[WITHOUT_ESCAPING]] : $@callee_guaranteed () -> () // CHECK: [[BLOCK:%.*]] = alloc_stack $@block_storage @callee_guaranteed () -> () // CHECK: [[BLOCK_ADDR:%.*]] = project_block_storage [[BLOCK]] : $*@block_storage @callee_guaranteed () -> () // CHECK: store [[WITHOUT_ESCAPING_COPY]] to [init] [[BLOCK_ADDR]] : $*@callee_guaranteed () -> () // CHECK: [[BLOCK_INVOKE:%.*]] = function_ref @$sIeg_IyB_TR : $@convention(c) (@inout_aliasable @block_storage @callee_guaranteed () -> ()) -> () // CHECK: [[BLOCK_CLOSURE:%.*]] = init_block_storage_header [[BLOCK]] : $*@block_storage @callee_guaranteed () -> (), invoke [[BLOCK_INVOKE]] : $@convention(c) (@inout_aliasable @block_storage @callee_guaranteed () -> ()) -> (), type $@convention(block) @noescape () -> () // CHECK: [[BLOCK_CLOSURE_COPY:%.*]] = copy_block_without_escaping [[BLOCK_CLOSURE]] : $@convention(block) @noescape () -> () withoutEscaping [[WITHOUT_ESCAPING]] : $@callee_guaranteed () -> () // CHECK: destroy_addr [[BLOCK_ADDR]] : $*@callee_guaranteed () -> () // CHECK: dealloc_stack [[BLOCK]] : $*@block_storage @callee_guaranteed () -> () // CHECK: destroy_value [[CLOSURE_COPY1]] : $@callee_guaranteed () -> () // CHECK: [[METH:%.*]] = objc_method [[OE]] : $@opened("{{.*}}", any DangerousEscaper) Self, #DangerousEscaper.malicious!foreign // CHECK: apply [[METH]]<@opened("{{.*}}", any DangerousEscaper) Self>([[BLOCK_CLOSURE_COPY]], [[OE]]) : $@convention(objc_method) <ฯ„_0_0 where ฯ„_0_0 : DangerousEscaper> (@convention(block) @noescape () -> (), ฯ„_0_0) -> () // CHECK: destroy_value [[BLOCK_CLOSURE_COPY]] : $@convention(block) @noescape () -> () // CHECK: return {{.*}} : $() public func couldActuallyEscape(_ closure: @escaping () -> (), _ villian: DangerousEscaper) { villian.malicious(closure) }
apache-2.0
db30f1cfccde04e16b15e3c10333e0e7
52.745223
273
0.671782
3.385356
false
false
false
false
IngmarStein/swift
test/Sema/deprecation_osx.swift
4
6621
// RUN: %swift -parse -parse-as-library -target x86_64-apple-macosx10.51 %clang-importer-sdk -I %S/Inputs/custom-modules %s -verify // RUN: %swift -parse -parse-as-library -target x86_64-apple-macosx10.51 %clang-importer-sdk -I %S/Inputs/custom-modules %s 2>&1 | %FileCheck %s '--implicit-check-not=<unknown>:0' // // This test requires a target of OS X 10.51 or later to test deprecation // diagnostics because (1) we only emit deprecation warnings if a symbol is // deprecated on all deployment targets and (2) symbols deprecated on 10.9 and // earlier are imported as unavailable. // // We run this test with FileCheck, as well, because the DiagnosticVerifier // swallows diagnostics from buffers with unknown filenames, which is // how diagnostics with invalid source locations appear. The // --implicit-check-not checks to make sure we do not emit any such // diagnostics with invalid source locations. // REQUIRES: OS=macosx import Foundation func useClassThatTriggersImportOfDeprecatedEnum() { // Check to make sure that the bodies of enum methods that are synthesized // when importing deprecated enums do not themselves trigger deprecation // warnings in the synthesized code. _ = NSClassWithDeprecatedOptionsInMethodSignature.sharedInstance() _ = NSClassWithExplicitlyUnavailableOptionsInMethodSignature.sharedInstance() } func directUseShouldStillTriggerDeprecationWarning() { _ = NSDeprecatedOptions.first // expected-warning {{'NSDeprecatedOptions' was deprecated in OS X 10.51: Use a different API}} _ = NSDeprecatedEnum.first // expected-warning {{'NSDeprecatedEnum' was deprecated in OS X 10.51: Use a different API}} } func useInSignature(options: NSDeprecatedOptions) { // expected-warning {{'NSDeprecatedOptions' was deprecated in OS X 10.51: Use a different API}} } class Super { @available(OSX, introduced: 10.9, deprecated: 10.51) init() { } } class Sub : Super { // The synthesized call to super.init() calls a deprecated constructor, so we // really should emit a warning. We lost such a warning (with no source // location) as part of the quick fix for rdar://problem/20007266, // which involved spurious warnings in synthesized code. // rdar://problem/20024980 tracks adding a proper warning in this and similar /// cases. } @available(OSX, introduced: 10.9, deprecated: 10.51) func functionDeprecatedIn10_51() { _ = ClassDeprecatedIn10_51() } @available(OSX, introduced: 10.9, deprecated: 10.9) class ClassDeprecatedIn10_9 { } @available(OSX, introduced: 10.8, deprecated: 10.51) class ClassDeprecatedIn10_51 { var other10_51: ClassDeprecatedIn10_51 = ClassDeprecatedIn10_51() func usingDeprecatedIn10_9() { // Following clang, we don't warn here even though we are using a class // that was deprecated before the containing class was deprecated. The // policy is to not warn if the use is inside a declaration that // is deprecated on all deployment targets. We can revisit this policy // if needed. _ = ClassDeprecatedIn10_9() } } class ClassWithComputedPropertyDeprecatedIn10_51 { @available(OSX, introduced: 10.8, deprecated: 10.51) var annotatedPropertyDeprecatedIn10_51 : ClassDeprecatedIn10_51 { get { return ClassDeprecatedIn10_51() } set(newValue) { _ = ClassDeprecatedIn10_51() } } // We really shouldn't be emitting three warnings here. It looks like // we are emitting one for each of the setter and getter, as well. var unannotatedPropertyDeprecatedIn10_51 : ClassDeprecatedIn10_51 { // expected-warning 3{{ClassDeprecatedIn10_51' was deprecated in OS X 10.51}} get { return ClassDeprecatedIn10_51() // expected-warning {{ClassDeprecatedIn10_51' was deprecated in OS X 10.51}} } set(newValue) { _ = ClassDeprecatedIn10_51() // expected-warning {{ClassDeprecatedIn10_51' was deprecated in OS X 10.51}} } } var unannotatedStoredPropertyOfTypeDeprecatedIn10_51 : ClassDeprecatedIn10_51? = nil // expected-warning {{ClassDeprecatedIn10_51' was deprecated in OS X 10.51}} } func usesFunctionDeprecatedIn10_51() { _ = ClassDeprecatedIn10_51() // expected-warning {{ClassDeprecatedIn10_51' was deprecated in OS X 10.51}} } @available(OSX, introduced: 10.8, deprecated: 10.51) func annotatedUsesFunctionDeprecatedIn10_51() { _ = ClassDeprecatedIn10_51() } func hasParameterDeprecatedIn10_51(p: ClassDeprecatedIn10_51) { // expected-warning {{ClassDeprecatedIn10_51' was deprecated in OS X 10.51}} } @available(OSX, introduced: 10.8, deprecated: 10.51) func annotatedHasParameterDeprecatedIn10_51(p: ClassDeprecatedIn10_51) { } func hasReturnDeprecatedIn10_51() -> ClassDeprecatedIn10_51 { // expected-warning {{ClassDeprecatedIn10_51' was deprecated in OS X 10.51}} } @available(OSX, introduced: 10.8, deprecated: 10.51) func annotatedHasReturnDeprecatedIn10_51() -> ClassDeprecatedIn10_51 { } var globalWithDeprecatedType : ClassDeprecatedIn10_51? = nil // expected-warning {{ClassDeprecatedIn10_51' was deprecated in OS X 10.51}} @available(OSX, introduced: 10.8, deprecated: 10.51) var annotatedGlobalWithDeprecatedType : ClassDeprecatedIn10_51? enum EnumWithDeprecatedCasePayload { case WithDeprecatedPayload(p: ClassDeprecatedIn10_51) // expected-warning {{ClassDeprecatedIn10_51' was deprecated in OS X 10.51}} @available(OSX, introduced: 10.8, deprecated: 10.51) case AnnotatedWithDeprecatedPayload(p: ClassDeprecatedIn10_51) } extension ClassDeprecatedIn10_51 { // expected-warning {{'ClassDeprecatedIn10_51' was deprecated in OS X 10.51}} } @available(OSX, introduced: 10.8, deprecated: 10.51) extension ClassDeprecatedIn10_51 { func methodInExtensionOfClassDeprecatedIn10_51() { } } func callMethodInDeprecatedExtension() { let o = ClassDeprecatedIn10_51() // expected-warning {{'ClassDeprecatedIn10_51' was deprecated in OS X 10.51}} o.methodInExtensionOfClassDeprecatedIn10_51() // expected-warning {{'methodInExtensionOfClassDeprecatedIn10_51()' was deprecated in OS X 10.51}} } func functionWithDeprecatedMethodInDeadElseBranch() { if #available(iOS 8.0, *) { } else { // This branch is dead on OS X, so we shouldn't emit a deprecation warning in it. let _ = ClassDeprecatedIn10_9() // no-warning } if #available(OSX 10.9, *) { // no-warning } else { // This branch is dead because our minimum deployment target is 10.51. let _ = ClassDeprecatedIn10_9() // no-warning } guard #available(iOS 8.0, *) else { // This branch is dead because our platform is OS X, so the wildcard always matches. let _ = ClassDeprecatedIn10_9() // no-warning } }
apache-2.0
4f3c1863141471684725883ee3699e3e
38.177515
179
0.741278
3.711323
false
false
false
false
BjornRuud/HTTPSession
Pods/Swifter/Sources/HttpServer.swift
3
2528
// // HttpServer.swift // Swifter // // Copyright (c) 2014-2016 Damian Koล‚akowski. All rights reserved. // import Foundation public class HttpServer: HttpServerIO { public static let VERSION = "1.3.2" private let router = HttpRouter() public override init() { self.DELETE = MethodRoute(method: "DELETE", router: router) self.UPDATE = MethodRoute(method: "UPDATE", router: router) self.HEAD = MethodRoute(method: "HEAD", router: router) self.POST = MethodRoute(method: "POST", router: router) self.GET = MethodRoute(method: "GET", router: router) self.PUT = MethodRoute(method: "PUT", router: router) self.delete = MethodRoute(method: "DELETE", router: router) self.update = MethodRoute(method: "UPDATE", router: router) self.head = MethodRoute(method: "HEAD", router: router) self.post = MethodRoute(method: "POST", router: router) self.get = MethodRoute(method: "GET", router: router) self.put = MethodRoute(method: "PUT", router: router) } public var DELETE, UPDATE, HEAD, POST, GET, PUT : MethodRoute public var delete, update, head, post, get, put : MethodRoute public subscript(path: String) -> ((HttpRequest) -> HttpResponse)? { set { router.register(nil, path: path, handler: newValue) } get { return nil } } public var routes: [String] { return router.routes(); } public var notFoundHandler: ((HttpRequest) -> HttpResponse)? public var middleware = Array<(HttpRequest) -> HttpResponse?>() override public func dispatch(_ request: HttpRequest) -> ([String:String], (HttpRequest) -> HttpResponse) { for layer in middleware { if let response = layer(request) { return ([:], { _ in response }) } } if let result = router.route(request.method, path: request.path) { return result } if let notFoundHandler = self.notFoundHandler { return ([:], notFoundHandler) } return super.dispatch(request) } public struct MethodRoute { public let method: String public let router: HttpRouter public subscript(path: String) -> ((HttpRequest) -> HttpResponse)? { set { router.register(method, path: path, handler: newValue) } get { return nil } } } }
mit
4988d8fb592b69878ade04f2f45317a0
32.693333
111
0.586466
4.349398
false
false
false
false
ostatnicky/kancional-ios
Pods/BonMot/Sources/StylisticAlternates.swift
2
10088
// // StylisticAlternates.swift // BonMot // // Created by Zev Eisenberg on 11/4/16. // Copyright ยฉ 2016 Raizlabs. All rights reserved. // #if os(OSX) import AppKit #else import UIKit #endif // This is not supported on watchOS #if os(iOS) || os(tvOS) || os(OSX) /// Different stylistic alternates available for customizing a font. /// Typically, a font will support a small subset of these alternates, and /// what they mean in a particular font is up to the font's creator. For /// example, in Apple's San Francisco font, turn on alternate set "six" to /// enable high-legibility alternates for ambiguous characters like: 0lI164. public struct StylisticAlternates { var one: Bool? var two: Bool? var three: Bool? var four: Bool? var five: Bool? var six: Bool? var seven: Bool? var eight: Bool? var nine: Bool? var ten: Bool? var eleven: Bool? var twelve: Bool? var thirteen: Bool? var fourteen: Bool? var fifteen: Bool? var sixteen: Bool? var seventeen: Bool? var eighteen: Bool? var nineteen: Bool? var twenty: Bool? public init() { } } // Convenience constructors extension StylisticAlternates { public static func one(on isOn: Bool) -> StylisticAlternates { var alts = StylisticAlternates() alts.one = isOn return alts } public static func two(on isOn: Bool) -> StylisticAlternates { var alts = StylisticAlternates() alts.two = isOn return alts } public static func three(on isOn: Bool) -> StylisticAlternates { var alts = StylisticAlternates() alts.three = isOn return alts } public static func four(on isOn: Bool) -> StylisticAlternates { var alts = StylisticAlternates() alts.four = isOn return alts } public static func five(on isOn: Bool) -> StylisticAlternates { var alts = StylisticAlternates() alts.five = isOn return alts } public static func six(on isOn: Bool) -> StylisticAlternates { var alts = StylisticAlternates() alts.six = isOn return alts } public static func seven(on isOn: Bool) -> StylisticAlternates { var alts = StylisticAlternates() alts.seven = isOn return alts } public static func eight(on isOn: Bool) -> StylisticAlternates { var alts = StylisticAlternates() alts.eight = isOn return alts } public static func nine(on isOn: Bool) -> StylisticAlternates { var alts = StylisticAlternates() alts.nine = isOn return alts } public static func ten(on isOn: Bool) -> StylisticAlternates { var alts = StylisticAlternates() alts.ten = isOn return alts } public static func eleven(on isOn: Bool) -> StylisticAlternates { var alts = StylisticAlternates() alts.eleven = isOn return alts } public static func twelve(on isOn: Bool) -> StylisticAlternates { var alts = StylisticAlternates() alts.twelve = isOn return alts } public static func thirteen(on isOn: Bool) -> StylisticAlternates { var alts = StylisticAlternates() alts.thirteen = isOn return alts } public static func fourteen(on isOn: Bool) -> StylisticAlternates { var alts = StylisticAlternates() alts.fourteen = isOn return alts } public static func fifteen(on isOn: Bool) -> StylisticAlternates { var alts = StylisticAlternates() alts.fifteen = isOn return alts } public static func sixteen(on isOn: Bool) -> StylisticAlternates { var alts = StylisticAlternates() alts.sixteen = isOn return alts } public static func seventeen(on isOn: Bool) -> StylisticAlternates { var alts = StylisticAlternates() alts.seventeen = isOn return alts } public static func eighteen(on isOn: Bool) -> StylisticAlternates { var alts = StylisticAlternates() alts.eighteen = isOn return alts } public static func nineteen(on isOn: Bool) -> StylisticAlternates { var alts = StylisticAlternates() alts.nineteen = isOn return alts } public static func twenty(on isOn: Bool) -> StylisticAlternates { var alts = StylisticAlternates() alts.twenty = isOn return alts } } extension StylisticAlternates { mutating public func add(other theOther: StylisticAlternates) { // swiftlint:disable operator_usage_whitespace one = theOther.one ?? one two = theOther.two ?? two three = theOther.three ?? three four = theOther.four ?? four five = theOther.five ?? five six = theOther.six ?? six seven = theOther.seven ?? seven eight = theOther.eight ?? eight nine = theOther.nine ?? nine ten = theOther.ten ?? ten eleven = theOther.eleven ?? eleven twelve = theOther.twelve ?? twelve thirteen = theOther.thirteen ?? thirteen fourteen = theOther.fourteen ?? fourteen fifteen = theOther.fifteen ?? fifteen sixteen = theOther.sixteen ?? sixteen seventeen = theOther.seventeen ?? seventeen eighteen = theOther.eighteen ?? eighteen nineteen = theOther.nineteen ?? nineteen twenty = theOther.twenty ?? twenty // swiftlint:enable operator_usage_whitespace } public func byAdding(other theOther: StylisticAlternates) -> StylisticAlternates { var varSelf = self varSelf.add(other: theOther) return varSelf } } extension StylisticAlternates: FontFeatureProvider { //swiftlint:disable:next cyclomatic_complexity public func featureSettings() -> [(type: Int, selector: Int)] { var selectors = [Int]() if let one = one { selectors.append(one ? kStylisticAltOneOnSelector : kStylisticAltOneOffSelector) } if let two = two { selectors.append(two ? kStylisticAltTwoOnSelector : kStylisticAltTwoOffSelector) } if let three = three { selectors.append(three ? kStylisticAltThreeOnSelector : kStylisticAltThreeOffSelector) } if let four = four { selectors.append(four ? kStylisticAltFourOnSelector : kStylisticAltFourOffSelector) } if let five = five { selectors.append(five ? kStylisticAltFiveOnSelector : kStylisticAltFiveOffSelector) } if let six = six { selectors.append(six ? kStylisticAltSixOnSelector : kStylisticAltSixOffSelector) } if let seven = seven { selectors.append(seven ? kStylisticAltSevenOnSelector : kStylisticAltSevenOffSelector) } if let eight = eight { selectors.append(eight ? kStylisticAltEightOnSelector : kStylisticAltEightOffSelector) } if let nine = nine { selectors.append(nine ? kStylisticAltNineOnSelector : kStylisticAltNineOffSelector) } if let ten = ten { selectors.append(ten ? kStylisticAltTenOnSelector : kStylisticAltTenOffSelector) } if let eleven = eleven { selectors.append(eleven ? kStylisticAltElevenOnSelector : kStylisticAltElevenOffSelector) } if let twelve = twelve { selectors.append(twelve ? kStylisticAltTwelveOnSelector : kStylisticAltTwelveOffSelector) } if let thirteen = thirteen { selectors.append(thirteen ? kStylisticAltThirteenOnSelector : kStylisticAltThirteenOffSelector) } if let fourteen = fourteen { selectors.append(fourteen ? kStylisticAltFourteenOnSelector : kStylisticAltFourteenOffSelector) } if let fifteen = fifteen { selectors.append(fifteen ? kStylisticAltFifteenOnSelector : kStylisticAltFifteenOffSelector) } if let sixteen = sixteen { selectors.append(sixteen ? kStylisticAltSixteenOnSelector : kStylisticAltSixteenOffSelector) } if let seventeen = seventeen { selectors.append(seventeen ? kStylisticAltSeventeenOnSelector : kStylisticAltSeventeenOffSelector) } if let eighteen = eighteen { selectors.append(eighteen ? kStylisticAltEighteenOnSelector : kStylisticAltEighteenOffSelector) } if let nineteen = nineteen { selectors.append(nineteen ? kStylisticAltNineteenOnSelector : kStylisticAltNineteenOffSelector) } if let twenty = twenty { selectors.append(twenty ? kStylisticAltTwentyOnSelector : kStylisticAltTwentyOffSelector) } return selectors.map { (type: kStylisticAlternativesType, selector: $0) } } } public func + (lhs: StylisticAlternates, rhs: StylisticAlternates) -> StylisticAlternates { return lhs.byAdding(other: rhs) } #endif
mit
e9f9b92f857ccdd72616287b70d6fb62
34.392982
114
0.573808
5.178131
false
false
false
false
overtake/TelegramSwift
Telegram-Mac/AccountContext.swift
1
51914
// // AccountContext.swift // Telegram // // Created by Mikhail Filimonov on 25/02/2019. // Copyright ยฉ 2019 Telegram. All rights reserved. // import Foundation import SwiftSignalKit import Postbox import TelegramCore import ColorPalette import TGUIKit import InAppSettings import ThemeSettings import Reactions import FetchManager import InAppPurchaseManager import ApiCredentials protocol ChatLocationContextHolder: AnyObject { } enum ChatLocation: Equatable { case peer(PeerId) case thread(ChatReplyThreadMessage) } extension ChatLocation { var unreadMessageCountsItem: UnreadMessageCountsItem { switch self { case let .peer(peerId): return .peer(id: peerId, handleThreads: false) case let .thread(data): return .peer(id: data.messageId.peerId, handleThreads: false) } } var postboxViewKey: PostboxViewKey { switch self { case let .peer(peerId): return .peer(peerId: peerId, components: []) case let .thread(data): return .peer(peerId: data.messageId.peerId, components: []) } } var pinnedItemId: PinnedItemId { switch self { case let .peer(peerId): return .peer(peerId) case let .thread(data): return .peer(data.messageId.peerId) } } var peerId: PeerId { switch self { case let .peer(peerId): return peerId case let .thread(data): return data.messageId.peerId } } var threadId: Int64? { switch self { case .peer: return nil case let .thread(replyThreadMessage): return makeMessageThreadId(replyThreadMessage.messageId) //Int64(replyThreadMessage.messageId.id) } } var threadMsgId: MessageId? { switch self { case .peer: return nil case let .thread(replyThreadMessage): return replyThreadMessage.messageId } } } struct TemporaryPasswordContainer { let date: TimeInterval let password: String var isActive: Bool { return date + 15 * 60 > Date().timeIntervalSince1970 } } enum ApplyThemeUpdate { case local(ColorPalette) case cloud(TelegramTheme) } final class AccountContextBindings { #if !SHARE let rootNavigation: () -> MajorNavigationController let mainController: () -> MainViewController let showControllerToaster: (ControllerToaster, Bool) -> Void let globalSearch:(String)->Void let switchSplitLayout:(SplitViewState)->Void let entertainment:()->EntertainmentViewController let needFullsize:()->Void let displayUpgradeProgress:(CGFloat)->Void init(rootNavigation: @escaping() -> MajorNavigationController = { fatalError() }, mainController: @escaping() -> MainViewController = { fatalError() }, showControllerToaster: @escaping(ControllerToaster, Bool) -> Void = { _, _ in fatalError() }, globalSearch: @escaping(String) -> Void = { _ in fatalError() }, entertainment: @escaping()->EntertainmentViewController = { fatalError() }, switchSplitLayout: @escaping(SplitViewState)->Void = { _ in fatalError() }, needFullsize: @escaping() -> Void = { fatalError() }, displayUpgradeProgress: @escaping(CGFloat)->Void = { _ in fatalError() }) { self.rootNavigation = rootNavigation self.mainController = mainController self.showControllerToaster = showControllerToaster self.globalSearch = globalSearch self.entertainment = entertainment self.switchSplitLayout = switchSplitLayout self.needFullsize = needFullsize self.displayUpgradeProgress = displayUpgradeProgress } #endif } private var lastTimeFreeSpaceNotified: TimeInterval? final class AccountContext { let sharedContext: SharedAccountContext let account: Account let window: Window var bindings: AccountContextBindings = AccountContextBindings() #if !SHARE let fetchManager: FetchManager let diceCache: DiceCache let inlinePacksContext: InlineStickersContext let cachedGroupCallContexts: AccountGroupCallContextCacheImpl let networkStatusManager: NetworkStatusManager let inAppPurchaseManager: InAppPurchaseManager #endif private(set) var timeDifference:TimeInterval = 0 #if !SHARE var audioPlayer:APController? let peerChannelMemberCategoriesContextsManager: PeerChannelMemberCategoriesContextsManager let blockedPeersContext: BlockedPeersContext let cacheCleaner: AccountClearCache let activeSessionsContext: ActiveSessionsContext let webSessions: WebSessionsContext let reactions: Reactions private(set) var reactionSettings: ReactionSettings = ReactionSettings.default private let reactionSettingsDisposable = MetaDisposable() private var chatInterfaceTempState:[PeerId : ChatInterfaceTempState] = [:] private let _chatThemes: Promise<[(String, TelegramPresentationTheme)]> = Promise([]) var chatThemes: Signal<[(String, TelegramPresentationTheme)], NoError> { return _chatThemes.get() |> deliverOnMainQueue } private let _cloudThemes:Promise<CloudThemesCachedData> = Promise() var cloudThemes:Signal<CloudThemesCachedData, NoError> { return _cloudThemes.get() |> deliverOnMainQueue } #endif let cancelGlobalSearch:ValuePromise<Bool> = ValuePromise(ignoreRepeated: false) private(set) var isSupport: Bool = false var isCurrent: Bool = false { didSet { if !self.isCurrent { //self.callManager = nil } } } private(set) var isPremium: Bool = false { didSet { #if !SHARE self.reactions.isPremium = isPremium #endif } } #if !SHARE var premiumIsBlocked: Bool { return self.premiumLimits.premium_purchase_blocked } #endif private let premiumDisposable = MetaDisposable() let globalPeerHandler:Promise<ChatLocation?> = Promise() func updateGlobalPeer() { globalPeerHandler.set(globalPeerHandler.get() |> take(1)) } let hasPassportSettings: Promise<Bool> = Promise(false) private var _recentlyPeerUsed:[PeerId] = [] private let _recentlyUserPeerIds = ValuePromise<[PeerId]>([]) var recentlyUserPeerIds:Signal<[PeerId], NoError> { return _recentlyUserPeerIds.get() } private(set) var recentlyPeerUsed:[PeerId] { set { _recentlyPeerUsed = newValue _recentlyUserPeerIds.set(newValue) } get { return _recentlyPeerUsed } } var peerId: PeerId { return account.peerId } private let updateDifferenceDisposable = MetaDisposable() private let temporaryPwdDisposable = MetaDisposable() private let actualizeCloudTheme = MetaDisposable() private let applyThemeDisposable = MetaDisposable() private let cloudThemeObserver = MetaDisposable() private let freeSpaceDisposable = MetaDisposable() private let prefDisposable = DisposableSet() private let _limitConfiguration: Atomic<LimitsConfiguration> = Atomic(value: LimitsConfiguration.defaultValue) var limitConfiguration: LimitsConfiguration { return _limitConfiguration.with { $0 } } private let _appConfiguration: Atomic<AppConfiguration> = Atomic(value: AppConfiguration.defaultValue) var appConfiguration: AppConfiguration { return _appConfiguration.with { $0 } } private var _myPeer: Peer? var myPeer: Peer? { return _myPeer } private let isKeyWindowValue: ValuePromise<Bool> = ValuePromise(ignoreRepeated: true) var isKeyWindow: Signal<Bool, NoError> { return isKeyWindowValue.get() |> deliverOnMainQueue } private let _autoplayMedia: Atomic<AutoplayMediaPreferences> = Atomic(value: AutoplayMediaPreferences.defaultSettings) var autoplayMedia: AutoplayMediaPreferences { return _autoplayMedia.with { $0 } } var layout:SplitViewState = .none { didSet { self.layoutHandler.set(self.layout) } } private let layoutHandler:ValuePromise<SplitViewState> = ValuePromise(ignoreRepeated:true) var layoutValue: Signal<SplitViewState, NoError> { return layoutHandler.get() } var isInGlobalSearch: Bool = false private let _contentSettings: Atomic<ContentSettings> = Atomic(value: ContentSettings.default) var contentSettings: ContentSettings { return _contentSettings.with { $0 } } public var closeFolderFirst: Bool = false private let preloadGifsDisposable = MetaDisposable() let engine: TelegramEngine private let giftStickersValues:Promise<[TelegramMediaFile]> = Promise([]) var giftStickers: Signal<[TelegramMediaFile], NoError> { return giftStickersValues.get() } init(sharedContext: SharedAccountContext, window: Window, account: Account, isSupport: Bool = false) { self.sharedContext = sharedContext self.account = account self.window = window self.engine = TelegramEngine(account: account) self.isSupport = isSupport #if !SHARE self.inAppPurchaseManager = .init(premiumProductId: ApiEnvironment.premiumProductId) self.peerChannelMemberCategoriesContextsManager = PeerChannelMemberCategoriesContextsManager(self.engine, account: account) self.diceCache = DiceCache(postbox: account.postbox, engine: self.engine) self.inlinePacksContext = .init(postbox: account.postbox, engine: self.engine) self.fetchManager = FetchManagerImpl(postbox: account.postbox, storeManager: DownloadedMediaStoreManagerImpl(postbox: account.postbox, accountManager: sharedContext.accountManager)) self.blockedPeersContext = BlockedPeersContext(account: account) self.cacheCleaner = AccountClearCache(account: account) self.cachedGroupCallContexts = AccountGroupCallContextCacheImpl() self.activeSessionsContext = engine.privacy.activeSessions() self.webSessions = engine.privacy.webSessions() self.networkStatusManager = NetworkStatusManager(account: account, window: window, sharedContext: sharedContext) self.reactions = Reactions(engine) #endif giftStickersValues.set(engine.stickers.loadedStickerPack(reference: .premiumGifts, forceActualized: false) |> map { pack in switch pack { case let .result(_, items, _): return items.map { $0.file } default: return [] } }) let engine = self.engine repliesPeerId = account.testingEnvironment ? test_repliesPeerId : prod_repliesPeerId let limitConfiguration = _limitConfiguration prefDisposable.add(account.postbox.preferencesView(keys: [PreferencesKeys.limitsConfiguration]).start(next: { view in _ = limitConfiguration.swap(view.values[PreferencesKeys.limitsConfiguration]?.get(LimitsConfiguration.self) ?? LimitsConfiguration.defaultValue) })) let preloadGifsDisposable = self.preloadGifsDisposable let appConfiguration = _appConfiguration prefDisposable.add(account.postbox.preferencesView(keys: [PreferencesKeys.appConfiguration]).start(next: { view in let configuration = view.values[PreferencesKeys.appConfiguration]?.get(AppConfiguration.self) ?? AppConfiguration.defaultValue _ = appConfiguration.swap(configuration) })) prefDisposable.add((account.postbox.peerView(id: account.peerId) |> deliverOnMainQueue).start(next: { [weak self] peerView in self?._myPeer = peerView.peers[peerView.peerId] })) #if !SHARE let signal:Signal<Void, NoError> = Signal { subscriber in let signal: Signal<Never, NoError> = account.postbox.transaction { return $0.getPreferencesEntry(key: PreferencesKeys.appConfiguration)?.get(AppConfiguration.self) ?? AppConfiguration.defaultValue } |> mapToSignal { configuration in let value = GIFKeyboardConfiguration.with(appConfiguration: configuration) var signals = value.emojis.map { engine.stickers.searchGifs(query: $0) } signals.insert(engine.stickers.searchGifs(query: ""), at: 0) return combineLatest(signals) |> ignoreValues } let disposable = signal.start(completed: { subscriber.putCompletion() }) return ActionDisposable { disposable.dispose() } } let updated = (signal |> then(.complete() |> suspendAwareDelay(20.0 * 60.0, queue: .concurrentDefaultQueue()))) |> restart preloadGifsDisposable.set(updated.start()) let chatThemes: Signal<[(String, TelegramPresentationTheme)], NoError> = combineLatest(appearanceSignal, engine.themes.getChatThemes(accountManager: sharedContext.accountManager)) |> mapToSignal { appearance, themes in var signals:[Signal<(String, TelegramPresentationTheme), NoError>] = [] for theme in themes { let effective = theme.effectiveSettings(isDark: appearance.presentation.dark) if let settings = effective, let emoji = theme.emoticon?.fixed { let newTheme = appearance.presentation.withUpdatedColors(settings.palette) if let wallpaper = settings.wallpaper?.uiWallpaper { signals.append(moveWallpaperToCache(postbox: account.postbox, wallpaper: wallpaper) |> map { wallpaper in return (emoji, newTheme.withUpdatedWallpaper(.init(wallpaper: wallpaper, associated: nil))) }) } else { signals.append(.single((emoji, newTheme))) } } } let first = Signal<[(String, TelegramPresentationTheme)], NoError>.single([]) return first |> then(combineLatest(signals)) |> map { values in var dict: [(String, TelegramPresentationTheme)] = [] for value in values { dict.append((value.0, value.1)) } return dict } } self._chatThemes.set((chatThemes |> then(.complete() |> suspendAwareDelay(20.0 * 60.0, queue: .concurrentDefaultQueue()))) |> restart) let cloudThemes: Signal<[TelegramTheme], NoError> = telegramThemes(postbox: account.postbox, network: account.network, accountManager: sharedContext.accountManager) |> distinctUntilChanged(isEqual: { lhs, rhs in return lhs.count == rhs.count }) let themesList: Signal<([TelegramTheme], [CloudThemesCachedData.Key : [SmartThemeCachedData]]), NoError> = cloudThemes |> mapToSignal { themes in var signals:[Signal<(CloudThemesCachedData.Key, Int64, TelegramPresentationTheme), NoError>] = [] for key in CloudThemesCachedData.Key.all { for theme in themes { let effective = theme.effectiveSettings(for: key.colors) if let settings = effective, theme.isDefault, let _ = theme.emoticon { let newTheme = appAppearance.presentation.withUpdatedColors(settings.palette) if let wallpaper = settings.wallpaper?.uiWallpaper { signals.append(moveWallpaperToCache(postbox: account.postbox, wallpaper: wallpaper) |> map { wallpaper in return (key, theme.id, newTheme.withUpdatedWallpaper(.init(wallpaper: wallpaper, associated: nil))) }) } else { signals.append(.single((key, theme.id, newTheme))) } } } } return combineLatest(signals) |> mapToSignal { values in var signals: [Signal<(CloudThemesCachedData.Key, Int64, SmartThemeCachedData), NoError>] = [] for value in values { let bubbled = value.0.bubbled let theme = value.2 let themeId = value.1 let key = value.0 if let telegramTheme = themes.first(where: { $0.id == value.1 }) { signals.append(generateChatThemeThumb(palette: theme.colors, bubbled: bubbled, backgroundMode: bubbled ? theme.backgroundMode : .color(color: theme.colors.chatBackground)) |> map { (key, themeId, SmartThemeCachedData(source: .cloud(telegramTheme), data: .init(appTheme: theme, previewIcon: $0, emoticon: telegramTheme.emoticon ?? telegramTheme.title))) }) } } return combineLatest(signals) |> map { values in var data:[CloudThemesCachedData.Key: [SmartThemeCachedData]] = [:] for value in values { var array:[SmartThemeCachedData] = data[value.0] ?? [] array.append(value.2) data[value.0] = array } return (themes, data) } } } let defaultAndCustom: Signal<(SmartThemeCachedData, SmartThemeCachedData?), NoError> = combineLatest(appearanceSignal, themeSettingsView(accountManager: sharedContext.accountManager)) |> map { appearance, value -> (ThemePaletteSettings, TelegramPresentationTheme, ThemePaletteSettings?) in let `default` = value.withUpdatedToDefault(dark: appearance.presentation.dark) .withUpdatedCloudTheme(nil) .withUpdatedPalette(appearance.presentation.colors.parent.palette) .installDefaultWallpaper() let customData = value.withUpdatedCloudTheme(appearance.presentation.cloudTheme) .withUpdatedPalette(appearance.presentation.colors) .installDefaultWallpaper() var custom: ThemePaletteSettings? if let cloud = customData.cloudTheme, cloud.settings == nil { custom = customData } else if let cloud = customData.cloudTheme { if let settings = cloud.effectiveSettings(for: value.palette.parent.palette) { if customData.wallpaper.wallpaper != settings.wallpaper?.uiWallpaper { custom = customData } } } return (`default`, appearance.presentation, custom) } |> deliverOn(.concurrentBackgroundQueue()) |> mapToSignal { (value, theme, custom) in var signals:[Signal<SmartThemeCachedData, NoError>] = [] let values = [value, custom].compactMap { $0 } for (i, value) in values.enumerated() { let newTheme = theme.withUpdatedColors(value.palette).withUpdatedWallpaper(value.wallpaper) signals.append(moveWallpaperToCache(postbox: account.postbox, wallpaper: value.wallpaper.wallpaper) |> mapToSignal { _ in return generateChatThemeThumb(palette: newTheme.colors, bubbled: value.bubbled, backgroundMode: value.bubbled ? newTheme.backgroundMode : .color(color: newTheme.colors.chatBackground)) } |> map { previewIcon in return SmartThemeCachedData(source: .local(value.palette), data: .init(appTheme: newTheme, previewIcon: previewIcon, emoticon: i == 0 ? "๐Ÿ " : "๐ŸŽจ")) }) } return combineLatest(signals) |> map { ($0[0], $0.count == 2 ? $0[1] : nil) } } _cloudThemes.set(cloudThemes |> map { cloudThemes in return .init(themes: cloudThemes, list: [:], default: nil, custom: nil) }) // _cloudThemes.set(.single(.init(themes: [], list: [:], default: nil, custom: nil))) let settings = account.postbox.preferencesView(keys: [PreferencesKeys.reactionSettings]) |> map { preferencesView -> ReactionSettings in let reactionSettings: ReactionSettings if let entry = preferencesView.values[PreferencesKeys.reactionSettings], let value = entry.get(ReactionSettings.self) { reactionSettings = value } else { reactionSettings = .default } return reactionSettings } |> deliverOnMainQueue reactionSettingsDisposable.set(settings.start(next: { [weak self] settings in self?.reactionSettings = settings })) #endif let autoplayMedia = _autoplayMedia prefDisposable.add(account.postbox.preferencesView(keys: [ApplicationSpecificPreferencesKeys.autoplayMedia]).start(next: { view in _ = autoplayMedia.swap(view.values[ApplicationSpecificPreferencesKeys.autoplayMedia]?.get(AutoplayMediaPreferences.self) ?? AutoplayMediaPreferences.defaultSettings) })) let contentSettings = _contentSettings prefDisposable.add(getContentSettings(postbox: account.postbox).start(next: { settings in _ = contentSettings.swap(settings) })) globalPeerHandler.set(.single(nil)) if account.network.globalTime > 0 { timeDifference = floor(account.network.globalTime - Date().timeIntervalSince1970) } updateDifferenceDisposable.set((Signal<Void, NoError>.single(Void()) |> delay(5, queue: Queue.mainQueue()) |> restart).start(next: { [weak self, weak account] in if let account = account, account.network.globalTime > 0 { self?.timeDifference = floor(account.network.globalTime - Date().timeIntervalSince1970) } })) let passthrough: Atomic<Bool> = Atomic(value: false) let cloudSignal = appearanceSignal |> distinctUntilChanged(isEqual: { lhs, rhs -> Bool in return lhs.presentation.cloudTheme == rhs.presentation.cloudTheme }) |> take(until: { _ in return .init(passthrough: passthrough.swap(true), complete: false) }) |> map { value in return (value.presentation.cloudTheme, value.presentation.colors) } |> deliverOnMainQueue cloudThemeObserver.set(cloudSignal.start(next: { [weak self] (cloud, palette) in let update: ApplyThemeUpdate if let cloud = cloud { update = .cloud(cloud) } else { update = .local(palette) } self?.updateTheme(update) })) NotificationCenter.default.addObserver(self, selector: #selector(updateKeyWindow), name: NSWindow.didBecomeKeyNotification, object: window) NotificationCenter.default.addObserver(self, selector: #selector(updateKeyWindow), name: NSWindow.didResignKeyNotification, object: window) #if !SHARE var freeSpaceSignal:Signal<UInt64?, NoError> = Signal { subscriber in subscriber.putNext(freeSystemGigabytes()) subscriber.putCompletion() return ActionDisposable { } } |> runOn(.concurrentDefaultQueue()) freeSpaceSignal = (freeSpaceSignal |> then(.complete() |> suspendAwareDelay(60.0 * 30, queue: Queue.concurrentDefaultQueue()))) |> restart let isLocked = (NSApp.delegate as? AppDelegate)?.passlock ?? .single(false) freeSpaceDisposable.set(combineLatest(queue: .mainQueue(), freeSpaceSignal, isKeyWindow, isLocked).start(next: { [weak self] space, isKeyWindow, locked in let limit: UInt64 = 5 guard let `self` = self, isKeyWindow, !locked, let space = space, space < limit else { return } if lastTimeFreeSpaceNotified == nil || (lastTimeFreeSpaceNotified! + 60.0 * 60.0 * 3 < Date().timeIntervalSince1970) { lastTimeFreeSpaceNotified = Date().timeIntervalSince1970 showOutOfMemoryWarning(window, freeSpace: space, context: self) } })) account.callSessionManager.updateVersions(versions: OngoingCallContext.versions(includeExperimental: true, includeReference: true).map { version, supportsVideo -> CallSessionManagerImplementationVersion in CallSessionManagerImplementationVersion(version: version, supportsVideo: supportsVideo) }) // reactions.needsPremium = { [weak self] in // if let strongSelf = self { // showModal(with: PremiumReactionsModal(context: strongSelf), for: strongSelf.window) // } // } #endif let isPremium: Signal<Bool, NoError> = account.postbox.peerView(id: account.peerId) |> map { view in return (view.peers[view.peerId] as? TelegramUser)?.flags.contains(.isPremium) ?? false } |> deliverOnMainQueue self.premiumDisposable.set(isPremium.start(next: { [weak self] value in self?.isPremium = value })) } @objc private func updateKeyWindow() { self.isKeyWindowValue.set(window.isKeyWindow) } func focus() { window.makeKeyAndOrderFront(nil) } private func updateTheme(_ update: ApplyThemeUpdate) { switch update { case let .cloud(cloudTheme): _ = applyTheme(accountManager: self.sharedContext.accountManager, account: self.account, theme: cloudTheme).start() let signal = actualizedTheme(account: self.account, accountManager: self.sharedContext.accountManager, theme: cloudTheme) |> deliverOnMainQueue self.actualizeCloudTheme.set(signal.start(next: { [weak self] cloudTheme in if let `self` = self { self.applyThemeDisposable.set(downloadAndApplyCloudTheme(context: self, theme: cloudTheme, install: theme.cloudTheme?.id != cloudTheme.id).start()) } })) case let .local(palette): actualizeCloudTheme.set(applyTheme(accountManager: self.sharedContext.accountManager, account: self.account, theme: nil).start()) applyThemeDisposable.set(updateThemeInteractivetly(accountManager: self.sharedContext.accountManager, f: { return $0.withUpdatedPalette(palette).withUpdatedCloudTheme(nil) }).start()) } } var timestamp: Int32 { var time:TimeInterval = TimeInterval(Date().timeIntervalSince1970) time -= self.timeDifference return Int32(time) } private var _temporartPassword: String? var temporaryPassword: String? { return _temporartPassword } func resetTemporaryPwd() { _temporartPassword = nil temporaryPwdDisposable.set(nil) } #if !SHARE func setChatInterfaceTempState(_ state: ChatInterfaceTempState, for peerId: PeerId) { self.chatInterfaceTempState[peerId] = state } func getChatInterfaceTempState(_ peerId: PeerId?) -> ChatInterfaceTempState? { if let peerId = peerId { return self.chatInterfaceTempState[peerId] } else { return nil } } var premiumLimits: PremiumLimitConfig { return PremiumLimitConfig(appConfiguration: appConfiguration) } var premiumOrder:PremiumPromoOrder { return PremiumPromoOrder(appConfiguration: appConfiguration) } var premiumBuyConfig: PremiumBuyConfig { return PremiumBuyConfig(appConfiguration: appConfiguration) } #endif func setTemporaryPwd(_ password: String) -> Void { _temporartPassword = password let signal = Signal<Void, NoError>.single(Void()) |> delay(30 * 60, queue: Queue.mainQueue()) temporaryPwdDisposable.set(signal.start(next: { [weak self] in self?._temporartPassword = nil })) } deinit { cleanup() } func cleanup() { updateDifferenceDisposable.dispose() temporaryPwdDisposable.dispose() prefDisposable.dispose() actualizeCloudTheme.dispose() applyThemeDisposable.dispose() cloudThemeObserver.dispose() preloadGifsDisposable.dispose() freeSpaceDisposable.dispose() premiumDisposable.dispose() NotificationCenter.default.removeObserver(self) #if !SHARE // self.walletPasscodeTimeoutContext.clear() self.networkStatusManager.cleanup() self.audioPlayer?.cleanup() self.audioPlayer = nil self.diceCache.cleanup() _chatThemes.set(.single([])) _cloudThemes.set(.single(.init(themes: [], list: [:], default: nil, custom: nil))) reactionSettingsDisposable.dispose() #endif } func checkFirstRecentlyForDuplicate(peerId:PeerId) { if let index = recentlyPeerUsed.firstIndex(of: peerId), index == 0 { // recentlyPeerUsed.remove(at: index) } } func addRecentlyUsedPeer(peerId:PeerId) { if let index = recentlyPeerUsed.firstIndex(of: peerId) { recentlyPeerUsed.remove(at: index) } recentlyPeerUsed.insert(peerId, at: 0) } func chatLocationInput(for location: ChatLocation, contextHolder: Atomic<ChatLocationContextHolder?>) -> ChatLocationInput { switch location { case let .peer(peerId): return .peer(peerId: peerId, threadId: nil) case let .thread(data): if data.isForumPost { return .peer(peerId: data.messageId.peerId, threadId: makeMessageThreadId(data.messageId)) } else { let context = chatLocationContext(holder: contextHolder, account: self.account, data: data) return .thread(peerId: data.messageId.peerId, threadId: makeMessageThreadId(data.messageId), data: context.state) } } } func chatLocationOutgoingReadState(for location: ChatLocation, contextHolder: Atomic<ChatLocationContextHolder?>) -> Signal<MessageId?, NoError> { switch location { case .peer: return .single(nil) case let .thread(data): if data.isForumPost { let viewKey: PostboxViewKey = .messageHistoryThreadInfo(peerId: data.messageId.peerId, threadId: Int64(data.messageId.id)) return self.account.postbox.combinedView(keys: [viewKey]) |> map { views -> MessageId? in if let threadInfo = views.views[viewKey] as? MessageHistoryThreadInfoView, let data = threadInfo.info?.data.get(MessageHistoryThreadData.self) { return MessageId(peerId: location.peerId, namespace: Namespaces.Message.Cloud, id: data.maxOutgoingReadId) } else { return nil } } } else { let context = chatLocationContext(holder: contextHolder, account: self.account, data: data) return context.maxReadOutgoingMessageId } } } public func chatLocationUnreadCount(for location: ChatLocation, contextHolder: Atomic<ChatLocationContextHolder?>) -> Signal<Int, NoError> { switch location { case let .peer(peerId): let unreadCountsKey: PostboxViewKey = .unreadCounts(items: [.peer(id: peerId, handleThreads: false), .total(nil)]) return self.account.postbox.combinedView(keys: [unreadCountsKey]) |> map { views in var unreadCount: Int32 = 0 if let view = views.views[unreadCountsKey] as? UnreadMessageCountsView { if let count = view.count(for: .peer(id: peerId, handleThreads: false)) { unreadCount = count } } return Int(unreadCount) } case let .thread(data): if data.isForumPost { let viewKey: PostboxViewKey = .messageHistoryThreadInfo(peerId: data.messageId.peerId, threadId: Int64(data.messageId.id)) return self.account.postbox.combinedView(keys: [viewKey]) |> map { views -> Int in if let threadInfo = views.views[viewKey] as? MessageHistoryThreadInfoView, let data = threadInfo.info?.data.get(MessageHistoryThreadData.self) { return Int(data.incomingUnreadCount) } else { return 0 } } } else { let context = chatLocationContext(holder: contextHolder, account: self.account, data: data) return context.unreadCount } } } func applyMaxReadIndex(for location: ChatLocation, contextHolder: Atomic<ChatLocationContextHolder?>, messageIndex: MessageIndex) { switch location { case .peer: let _ = self.engine.messages.applyMaxReadIndexInteractively(index: messageIndex).start() case let .thread(data): let context = chatLocationContext(holder: contextHolder, account: self.account, data: data) context.applyMaxReadIndex(messageIndex: messageIndex) } } #if !SHARE func navigateToThread(_ threadId: MessageId, fromId: MessageId) { let signal:Signal<ThreadInfo, FetchChannelReplyThreadMessageError> = fetchAndPreloadReplyThreadInfo(context: self, subject: .channelPost(threadId)) _ = showModalProgress(signal: signal |> take(1), for: self.window).start(next: { [weak self] result in guard let context = self else { return } let chatLocation: ChatLocation = .thread(result.message) let updatedMode: ReplyThreadMode if result.isChannelPost { updatedMode = .comments(origin: fromId) } else { updatedMode = .replies(origin: fromId) } let controller = ChatController(context: context, chatLocation: chatLocation, mode: .thread(data: result.message, mode: updatedMode), messageId: fromId, initialAction: nil, chatLocationContextHolder: result.contextHolder) context.bindings.rootNavigation().push(controller) }, error: { error in }) } func composeCreateGroup(selectedPeers:Set<PeerId> = Set()) { createGroup(with: self, selectedPeers: selectedPeers) } func composeCreateChannel() { createChannel(with: self) } func composeCreateSecretChat() { let account = self.account let window = self.window let engine = self.engine let confirmationImpl:([PeerId])->Signal<Bool, NoError> = { peerIds in if let first = peerIds.first, peerIds.count == 1 { return account.postbox.loadedPeerWithId(first) |> deliverOnMainQueue |> mapToSignal { peer in return confirmSignal(for: window, information: strings().composeConfirmStartSecretChat(peer.displayTitle)) } } return confirmSignal(for: window, information: strings().peerInfoConfirmAddMembers1Countable(peerIds.count)) } let select = selectModalPeers(window: window, context: self, title: strings().composeSelectSecretChat, limit: 1, confirmation: confirmationImpl) let create = select |> map { $0.first! } |> mapToSignal { peerId in return engine.peers.createSecretChat(peerId: peerId) |> `catch` {_ in .complete()} } |> deliverOnMainQueue |> mapToSignal{ peerId -> Signal<PeerId, NoError> in return showModalProgress(signal: .single(peerId), for: window) } _ = create.start(next: { [weak self] peerId in guard let `self` = self else {return} self.bindings.rootNavigation().push(ChatController(context: self, chatLocation: .peer(peerId))) }) } #endif } func downloadAndApplyCloudTheme(context: AccountContext, theme cloudTheme: TelegramTheme, palette: ColorPalette? = nil, install: Bool = false) -> Signal<Never, Void> { if let cloudSettings = cloudTheme.effectiveSettings(for: palette ?? theme.colors) { return Signal { subscriber in #if !SHARE let wallpaperDisposable = DisposableSet() let palette = cloudSettings.palette var wallpaper: Signal<TelegramWallpaper?, GetWallpaperError>? = nil let associated = theme.wallpaper.associated?.wallpaper if let w = cloudSettings.wallpaper, theme.wallpaper.wallpaper == associated || install { wallpaper = .single(w) } else if install, let wrapper = palette.wallpaper.wallpaper.cloudWallpaper { wallpaper = .single(wrapper) } if let wallpaper = wallpaper { wallpaperDisposable.add(wallpaper.start(next: { cloud in if let cloud = cloud { let wp = Wallpaper(cloud) wallpaperDisposable.add(moveWallpaperToCache(postbox: context.account.postbox, wallpaper: wp).start(next: { wallpaper in _ = updateThemeInteractivetly(accountManager: context.sharedContext.accountManager, f: { settings in var settings = settings.withUpdatedPalette(palette).withUpdatedCloudTheme(cloudTheme) var updateDefault:DefaultTheme = palette.isDark ? settings.defaultDark : settings.defaultDay updateDefault = updateDefault.updateCloud { _ in return DefaultCloudTheme(cloud: cloudTheme, palette: palette, wallpaper: AssociatedWallpaper(cloud: cloud, wallpaper: wallpaper)) } settings = palette.isDark ? settings.withUpdatedDefaultDark(updateDefault) : settings.withUpdatedDefaultDay(updateDefault) settings = settings.withUpdatedDefaultIsDark(palette.isDark) return settings.updateWallpaper { value in return value.withUpdatedWallpaper(wallpaper) .withUpdatedAssociated(AssociatedWallpaper(cloud: cloud, wallpaper: wallpaper)) }.saveDefaultWallpaper().withSavedAssociatedTheme().saveDefaultAccent(color: cloudSettings.accent) }).start() subscriber.putCompletion() })) } else { _ = updateThemeInteractivetly(accountManager: context.sharedContext.accountManager, f: { settings in var settings = settings var updateDefault:DefaultTheme = palette.isDark ? settings.defaultDark : settings.defaultDay updateDefault = updateDefault.updateCloud { _ in return DefaultCloudTheme(cloud: cloudTheme, palette: palette, wallpaper: AssociatedWallpaper(cloud: cloud, wallpaper: .none)) } settings = palette.isDark ? settings.withUpdatedDefaultDark(updateDefault) : settings.withUpdatedDefaultDay(updateDefault) settings = settings.withUpdatedDefaultIsDark(palette.isDark) return settings.withUpdatedPalette(palette).withUpdatedCloudTheme(cloudTheme).updateWallpaper({ value in return value.withUpdatedWallpaper(.none) .withUpdatedAssociated(AssociatedWallpaper(cloud: cloud, wallpaper: .none)) }).saveDefaultWallpaper().withSavedAssociatedTheme().saveDefaultAccent(color: cloudSettings.accent) }).start() subscriber.putCompletion() } }, error: { _ in subscriber.putCompletion() })) } else { _ = updateThemeInteractivetly(accountManager: context.sharedContext.accountManager, f: { settings in var settings = settings.withUpdatedPalette(palette).withUpdatedCloudTheme(cloudTheme) var updateDefault:DefaultTheme = palette.isDark ? settings.defaultDark : settings.defaultDay updateDefault = updateDefault.updateCloud { current in let associated = current?.wallpaper ?? AssociatedWallpaper(cloud: nil, wallpaper: palette.wallpaper.wallpaper) return DefaultCloudTheme(cloud: cloudTheme, palette: palette, wallpaper: associated) } settings = palette.isDark ? settings.withUpdatedDefaultDark(updateDefault) : settings.withUpdatedDefaultDay(updateDefault) return settings.withSavedAssociatedTheme().saveDefaultAccent(color: cloudSettings.accent) }).start() subscriber.putCompletion() } #endif return ActionDisposable { #if !SHARE wallpaperDisposable.dispose() #endif } } |> runOn(.mainQueue()) |> deliverOnMainQueue } else if let file = cloudTheme.file { return Signal { subscriber in let fetchDisposable = fetchedMediaResource(mediaBox: context.account.postbox.mediaBox, reference: MediaResourceReference.standalone(resource: file.resource)).start() let wallpaperDisposable = DisposableSet() let resourceData = context.account.postbox.mediaBox.resourceData(file.resource) |> filter { $0.complete } |> take(1) let dataDisposable = resourceData.start(next: { data in if let palette = importPalette(data.path) { var wallpaper: Signal<TelegramWallpaper?, GetWallpaperError>? = nil var newSettings: WallpaperSettings = WallpaperSettings() #if !SHARE switch palette.wallpaper { case .none: if theme.wallpaper.wallpaper == theme.wallpaper.associated?.wallpaper || install { wallpaper = .single(nil) } case .builtin: if theme.wallpaper.wallpaper == theme.wallpaper.associated?.wallpaper || install { wallpaper = .single(.builtin(WallpaperSettings())) } case let .color(color): if theme.wallpaper.wallpaper == theme.wallpaper.associated?.wallpaper || install { wallpaper = .single(.color(color.argb)) } case let .url(string): let link = inApp(for: string as NSString, context: context) switch link { case let .wallpaper(values): switch values.preview { case let .slug(slug, settings): if theme.wallpaper.wallpaper == theme.wallpaper.associated?.wallpaper || install { if let associated = theme.wallpaper.associated, let cloud = associated.cloud { switch cloud { case let .file(values): if values.slug == values.slug && values.settings == settings { wallpaper = .single(cloud) } else { wallpaper = getWallpaper(network: context.account.network, slug: slug) |> map(Optional.init) } default: wallpaper = getWallpaper(network: context.account.network, slug: slug) |> map(Optional.init) } } else { wallpaper = getWallpaper(network: context.account.network, slug: slug) |> map(Optional.init) } } newSettings = settings default: break } default: break } } #endif if let wallpaper = wallpaper { #if !SHARE wallpaperDisposable.add(wallpaper.start(next: { cloud in if let cloud = cloud { let wp = Wallpaper(cloud).withUpdatedSettings(newSettings) wallpaperDisposable.add(moveWallpaperToCache(postbox: context.account.postbox, wallpaper: wp).start(next: { wallpaper in _ = updateThemeInteractivetly(accountManager: context.sharedContext.accountManager, f: { settings in var settings = settings.withUpdatedPalette(palette).withUpdatedCloudTheme(cloudTheme) var updateDefault:DefaultTheme = palette.isDark ? settings.defaultDark : settings.defaultDay updateDefault = updateDefault.updateCloud { _ in return DefaultCloudTheme(cloud: cloudTheme, palette: palette, wallpaper: AssociatedWallpaper(cloud: cloud, wallpaper: wp)) } settings = palette.isDark ? settings.withUpdatedDefaultDark(updateDefault) : settings.withUpdatedDefaultDay(updateDefault) settings = settings.withUpdatedDefaultIsDark(palette.isDark) return settings.updateWallpaper { value in return value.withUpdatedWallpaper(wallpaper) .withUpdatedAssociated(AssociatedWallpaper(cloud: cloud, wallpaper: wallpaper)) }.saveDefaultWallpaper() }).start() subscriber.putCompletion() })) } else { _ = updateThemeInteractivetly(accountManager: context.sharedContext.accountManager, f: { settings in var settings = settings var updateDefault:DefaultTheme = palette.isDark ? settings.defaultDark : settings.defaultDay updateDefault = updateDefault.updateCloud { _ in return DefaultCloudTheme(cloud: cloudTheme, palette: palette, wallpaper: AssociatedWallpaper(cloud: cloud, wallpaper: .none)) } settings = palette.isDark ? settings.withUpdatedDefaultDark(updateDefault) : settings.withUpdatedDefaultDay(updateDefault) settings = settings.withUpdatedDefaultIsDark(palette.isDark) return settings.withUpdatedPalette(palette).withUpdatedCloudTheme(cloudTheme).updateWallpaper({ value in return value.withUpdatedWallpaper(.none) .withUpdatedAssociated(AssociatedWallpaper(cloud: cloud, wallpaper: .none)) }).saveDefaultWallpaper() }).start() subscriber.putCompletion() } }, error: { _ in subscriber.putCompletion() })) #endif } else { _ = updateThemeInteractivetly(accountManager: context.sharedContext.accountManager, f: { settings in var settings = settings.withUpdatedPalette(palette).withUpdatedCloudTheme(cloudTheme) var updateDefault:DefaultTheme = palette.isDark ? settings.defaultDark : settings.defaultDay updateDefault = updateDefault.updateCloud { current in let associated = current?.wallpaper ?? AssociatedWallpaper(cloud: nil, wallpaper: palette.wallpaper.wallpaper) return DefaultCloudTheme(cloud: cloudTheme, palette: palette, wallpaper: associated) } settings = palette.isDark ? settings.withUpdatedDefaultDark(updateDefault) : settings.withUpdatedDefaultDay(updateDefault) return settings }).start() subscriber.putCompletion() } } }) return ActionDisposable { fetchDisposable.dispose() dataDisposable.dispose() wallpaperDisposable.dispose() } } |> runOn(.mainQueue()) |> deliverOnMainQueue } else { return .complete() } } private func chatLocationContext(holder: Atomic<ChatLocationContextHolder?>, account: Account, data: ChatReplyThreadMessage) -> ReplyThreadHistoryContext { let holder = holder.modify { current in if let current = current as? ChatLocationContextHolderImpl { return current } else { return ChatLocationContextHolderImpl(account: account, data: data) } } as! ChatLocationContextHolderImpl return holder.context } private final class ChatLocationContextHolderImpl: ChatLocationContextHolder { let context: ReplyThreadHistoryContext init(account: Account, data: ChatReplyThreadMessage) { self.context = ReplyThreadHistoryContext(account: account, peerId: data.messageId.peerId, data: data) } }
gpl-2.0
09a56a1904cfd383b83e3ad7ba6c8393
44.894783
596
0.591693
5.378964
false
false
false
false
Nefuln/LNAddressBook
LNAddressBook/LNAddressBook/LNAddressBookUI/AddContact/view/LNContactTableView.swift
1
7561
// // LNContactTableView.swift // LNAddressBook // // Created by ๆตชๆผซๆปกๅฑ‹ on 2017/8/2. // Copyright ยฉ 2017ๅนด com.man.www. All rights reserved. // import UIKit import Contacts class LNContactTableView: UITableView { var phoneArr = [(tag: String, phone: String)]() var emailArr = [(tag: String, eamil: String)]() var contact: CNContact? var mutaContact: CNMutableContact? { get { if _mutaContact == nil { _mutaContact = CNMutableContact() } _mutaContact?.familyName = headerView.familyName _mutaContact?.givenName = headerView.givenName _mutaContact?.organizationName = headerView.companyName getPhones() getEmails() return _mutaContact } } public func set(contact: CNContact?) { self.contact = contact _mutaContact = contact?.mutableCopy() as? CNMutableContact headerView.set(contact: contact) tableFooterView = self.contact == nil ? UIView() : footView self.phoneArr.removeAll() self.emailArr.removeAll() for dict in (contact?.mPhones)! { self.phoneArr.append(("ๆ‰‹ๆœบ", dict.values.first!)) } for dict in (contact?.mEmails)! { self.emailArr.append(("้‚ฎไปถ", dict.values.first!)) } reloadData() } public lazy var headerView: LNContactHeaderView = { let headerView = LNContactHeaderView(frame: CGRect(x: 0, y: 0, width: ScreenWidth, height: 150)) return headerView }() public var footView: LNContactFootView = { let footView = LNContactFootView(frame: CGRect(x: 0, y: 0, width: ScreenWidth, height: 150)) return footView }() override init(frame: CGRect, style: UITableViewStyle) { super.init(frame: frame, style: style) initUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK:- Private func private func initUI() { tableFooterView = self.contact == nil ? UIView() : footView tableHeaderView = headerView separatorStyle = .none register(LNContactCell.self, forCellReuseIdentifier: NSStringFromClass(LNContactCell.self)) dataSource = self delegate = self } fileprivate var _mutaContact: CNMutableContact? } extension LNContactTableView: UITableViewDelegate, UITableViewDataSource { func numberOfSections(in tableView: UITableView) -> Int { return 2 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 1 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: NSStringFromClass(LNContactCell.self), for: indexPath) as! LNContactCell switch indexPath.section { case 0: cell.tLabel.text = "ๆทปๅŠ ็”ต่ฏ" case 1: cell.tLabel.text = "ๆทปๅŠ ็”ตๅญ้‚ฎไปถ" default: break } return cell } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 40 } func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { switch section { case 0: return (self.phoneArr.count == 0 || self.phoneArr.count == 1) ? 60 : CGFloat((self.phoneArr.count - 1) * 40 + 60) default: return 60 } } func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { return 1 } func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let view = UIView() view.backgroundColor = UIColor.white view.tag = 1000 * (section + 1) switch section { case 0: for (idx, obj) in self.phoneArr.enumerated() { let subview = LNContactCommonAddView() subview.set(tagTitle: "\(obj.0)", placeholder: "", text: obj.phone) subview.editBlock = { (view) in view.isEditing(true) } subview.deleteBlock = { [weak self] (view) in if let weakSelf = self { } } view.addSubview(subview) subview.snp.makeConstraints({ (make) in make.left.right.equalTo(view) make.bottom.equalTo(-idx*40) make.height.equalTo(40) }) } case 1: for (idx, obj) in self.emailArr.enumerated() { let subview = LNContactCommonAddView() subview.set(tagTitle: "\(obj.0)", placeholder: "", text: obj.eamil) subview.editBlock = { (view) in view.isEditing(true) } subview.deleteBlock = { [weak self] (view) in if let weakSelf = self { } } view.addSubview(subview) subview.snp.makeConstraints({ (make) in make.left.right.equalTo(view) make.bottom.equalTo(-idx*40) make.height.equalTo(40) }) } default: break } return view } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) switch indexPath.section { case 0: self.getPhones() self.phoneArr.append(("ๆ‰‹ๆœบ", "")) case 1: getEmails() self.emailArr.append(("้‚ฎไปถ", "")) default: break } tableView.reloadSections(IndexSet(indexPath), with: .automatic) } } extension LNContactTableView { fileprivate func getPhones() { let headerView = self.viewWithTag(1000) _mutaContact?.phoneNumbers.removeAll() self.phoneArr.removeAll() if headerView?.subviews.count == 0 { return } for subview in (headerView?.subviews)! { self.phoneArr.append((tag: "ๆ‰‹ๆœบ", phone: (subview as! LNContactCommonAddView).inputText ?? "")) let phone = CNLabeledValue(label: CNLabelPhoneNumberiPhone, value: CNPhoneNumber(stringValue: (subview as! LNContactCommonAddView).inputText ?? "")) _mutaContact?.phoneNumbers.append(phone) } } fileprivate func getEmails() { let headerView = self.viewWithTag(2000) _mutaContact?.emailAddresses.removeAll() self.emailArr.removeAll() if headerView?.subviews.count == 0 { return } for subview in (headerView?.subviews)! { self.emailArr.append((tag: "้‚ฎไปถ", phone: (subview as! LNContactCommonAddView).inputText ?? "") as! (tag: String, eamil: String)) let email = CNLabeledValue(label: CNLabelHome, value: ((subview as! LNContactCommonAddView).inputText ?? "") as NSString) _mutaContact?.emailAddresses.append(email) } } }
mit
07066152a9a75d9fbbd8852781e1e512
31.777293
160
0.555955
4.783939
false
false
false
false
HTWDD/HTWDresden-iOS-Temp
HTWDresden/HTWDresden/Detail/MealDetailViewController.swift
1
822
import UIKit import Kingfisher class MealDetailViewController: UIViewController { var tableView = UITableView() override func viewDidLoad() { super.viewDidLoad() tableView.frame = view.bounds tableView.autoresizingMask = [.FlexibleWidth, .FlexibleHeight] tableView.delegate = self tableView.dataSource = self tableView.registerClass(MealDetailViewCell.self, forCellReuseIdentifier: "cell") view.addSubview(tableView) } } extension MealDetailViewController: UITableViewDelegate, UITableViewDataSource { func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 3 } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { return tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) } }
gpl-2.0
a0b17f823214fdf46ca9f4cb0705915b
27.37931
106
0.798054
4.922156
false
false
false
false
Mikelulu/BaiSiBuDeQiJie
LKBS/Pods/BMPlayer/Source/BMPlayerLayerView.swift
1
15387
// // BMPlayerLayerView.swift // Pods // // Created by BrikerMan on 16/4/28. // // import UIKit import AVFoundation /** Player status emun - notSetURL: not set url yet - readyToPlay: player ready to play - buffering: player buffering - bufferFinished: buffer finished - playedToTheEnd: played to the End - error: error with playing */ public enum BMPlayerState { case notSetURL case readyToPlay case buffering case bufferFinished case playedToTheEnd case error } /** video aspect ratio types - `default`: video default aspect - sixteen2NINE: 16:9 - four2THREE: 4:3 */ public enum BMPlayerAspectRatio : Int { case `default` = 0 case sixteen2NINE case four2THREE } public protocol BMPlayerLayerViewDelegate : class { func bmPlayer(player: BMPlayerLayerView ,playerStateDidChange state: BMPlayerState) func bmPlayer(player: BMPlayerLayerView ,loadedTimeDidChange loadedDuration: TimeInterval , totalDuration: TimeInterval) func bmPlayer(player: BMPlayerLayerView ,playTimeDidChange currentTime : TimeInterval , totalTime: TimeInterval) func bmPlayer(player: BMPlayerLayerView ,playerIsPlaying playing: Bool) } open class BMPlayerLayerView: UIView { open weak var delegate: BMPlayerLayerViewDelegate? /// ่ง†้ข‘่ทณ่ฝฌ็ง’ๆ•ฐ็ฝฎ0 open var seekTime = 0 /// ๆ’ญๆ”พๅฑžๆ€ง open var playerItem: AVPlayerItem? { didSet { onPlayerItemChange() } } /// ๆ’ญๆ”พๅฑžๆ€ง open lazy var player: AVPlayer? = { if let item = self.playerItem { let player = AVPlayer(playerItem: item) return player } return nil }() open var videoGravity = AVLayerVideoGravityResizeAspect { didSet { self.playerLayer?.videoGravity = videoGravity } } open var isPlaying: Bool = false { didSet { if oldValue != isPlaying { delegate?.bmPlayer(player: self, playerIsPlaying: isPlaying) } } } var aspectRatio:BMPlayerAspectRatio = .default { didSet { self.setNeedsLayout() } } /// ่ฎกๆ—ถๅ™จ var timer : Timer? fileprivate var urlAsset: AVURLAsset? fileprivate var lastPlayerItem: AVPlayerItem? /// playerLayer fileprivate var playerLayer: AVPlayerLayer? /// ้Ÿณ้‡ๆป‘ๆ† fileprivate var volumeViewSlider: UISlider! /// ๆ’ญๅ‘ๅ™จ็š„ๅ‡ ็ง็Šถๆ€ fileprivate var state = BMPlayerState.notSetURL { didSet { if state != oldValue { delegate?.bmPlayer(player: self, playerStateDidChange: state) } } } /// ๆ˜ฏๅฆไธบๅ…จๅฑ fileprivate var isFullScreen = false /// ๆ˜ฏๅฆ้”ๅฎšๅฑๅน•ๆ–นๅ‘ fileprivate var isLocked = false /// ๆ˜ฏๅฆๅœจ่ฐƒ่Š‚้Ÿณ้‡ fileprivate var isVolume = false /// ๆ˜ฏๅฆๆ’ญๆ”พๆœฌๅœฐๆ–‡ไปถ fileprivate var isLocalVideo = false /// sliderไธŠๆฌก็š„ๅ€ผ fileprivate var sliderLastValue:Float = 0 /// ๆ˜ฏๅฆ็‚นไบ†้‡ๆ’ญ fileprivate var repeatToPlay = false /// ๆ’ญๆ”พๅฎŒไบ† fileprivate var playDidEnd = false // playbackBufferEmptyไผšๅๅค่ฟ›ๅ…ฅ๏ผŒๅ› ๆญคๅœจbufferingOneSecondๅปถๆ—ถๆ’ญๆ”พๆ‰ง่กŒๅฎŒไน‹ๅ‰ๅ†่ฐƒ็”จbufferingSomeSecond้ƒฝๅฟฝ็•ฅ // ไป…ๅœจbufferingSomeSecond้‡Œ้ขไฝฟ็”จ fileprivate var isBuffering = false fileprivate var hasReadyToPlay = false fileprivate var shouldSeekTo: TimeInterval = 0 // MARK: - Actions open func playURL(url: URL) { let asset = AVURLAsset(url: url) playAsset(asset: asset) } open func playAsset(asset: AVURLAsset) { urlAsset = asset onSetVideoAsset() play() } open func play() { if let player = player { player.play() setupTimer() isPlaying = true } } open func pause() { player?.pause() isPlaying = false timer?.fireDate = Date.distantFuture } deinit { NotificationCenter.default.removeObserver(self) } // MARK: - layoutSubviews override open func layoutSubviews() { super.layoutSubviews() switch self.aspectRatio { case .default: self.playerLayer?.videoGravity = "AVLayerVideoGravityResizeAspect" self.playerLayer?.frame = self.bounds break case .sixteen2NINE: self.playerLayer?.videoGravity = "AVLayerVideoGravityResize" self.playerLayer?.frame = CGRect(x: 0, y: 0, width: self.bounds.width, height: self.bounds.width/(16/9)) break case .four2THREE: self.playerLayer?.videoGravity = "AVLayerVideoGravityResize" let _w = self.bounds.height * 4 / 3 self.playerLayer?.frame = CGRect(x: (self.bounds.width - _w )/2, y: 0, width: _w, height: self.bounds.height) break } } open func resetPlayer() { // ๅˆๅง‹ๅŒ–็Šถๆ€ๅ˜้‡ self.playDidEnd = false self.playerItem = nil self.seekTime = 0 self.timer?.invalidate() self.pause() // ็งป้™คๅŽŸๆฅ็š„layer self.playerLayer?.removeFromSuperlayer() // ๆ›ฟๆขPlayerItemไธบnil self.player?.replaceCurrentItem(with: nil) player?.removeObserver(self, forKeyPath: "rate") // ๆŠŠplayer็ฝฎไธบnil self.player = nil } open func prepareToDeinit() { self.resetPlayer() } open func onTimeSliderBegan() { if self.player?.currentItem?.status == AVPlayerItemStatus.readyToPlay { self.timer?.fireDate = Date.distantFuture } } open func seek(to secounds: TimeInterval, completion:(()->Void)?) { if secounds.isNaN { return } setupTimer() if self.player?.currentItem?.status == AVPlayerItemStatus.readyToPlay { let draggedTime = CMTimeMake(Int64(secounds), 1) self.player!.seek(to: draggedTime, toleranceBefore: kCMTimeZero, toleranceAfter: kCMTimeZero, completionHandler: { (finished) in completion?() }) } else { self.shouldSeekTo = secounds } } // MARK: - ่ฎพ็ฝฎ่ง†้ข‘URL fileprivate func onSetVideoAsset() { repeatToPlay = false playDidEnd = false configPlayer() } fileprivate func onPlayerItemChange() { if lastPlayerItem == playerItem { return } if let item = lastPlayerItem { NotificationCenter.default.removeObserver(self, name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: item) item.removeObserver(self, forKeyPath: "status") item.removeObserver(self, forKeyPath: "loadedTimeRanges") item.removeObserver(self, forKeyPath: "playbackBufferEmpty") item.removeObserver(self, forKeyPath: "playbackLikelyToKeepUp") } lastPlayerItem = playerItem if let item = playerItem { NotificationCenter.default.addObserver(self, selector: #selector(moviePlayDidEnd), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: playerItem) item.addObserver(self, forKeyPath: "status", options: NSKeyValueObservingOptions.new, context: nil) item.addObserver(self, forKeyPath: "loadedTimeRanges", options: NSKeyValueObservingOptions.new, context: nil) // ็ผ“ๅ†ฒๅŒบ็ฉบไบ†๏ผŒ้œ€่ฆ็ญ‰ๅพ…ๆ•ฐๆฎ item.addObserver(self, forKeyPath: "playbackBufferEmpty", options: NSKeyValueObservingOptions.new, context: nil) // ็ผ“ๅ†ฒๅŒบๆœ‰่ถณๅคŸๆ•ฐๆฎๅฏไปฅๆ’ญๆ”พไบ† item.addObserver(self, forKeyPath: "playbackLikelyToKeepUp", options: NSKeyValueObservingOptions.new, context: nil) } } fileprivate func configPlayer(){ player?.removeObserver(self, forKeyPath: "rate") playerItem = AVPlayerItem(asset: urlAsset!) player = AVPlayer(playerItem: playerItem!) player!.addObserver(self, forKeyPath: "rate", options: NSKeyValueObservingOptions.new, context: nil) playerLayer?.removeFromSuperlayer() playerLayer = AVPlayerLayer(player: player) playerLayer!.videoGravity = videoGravity layer.addSublayer(playerLayer!) setNeedsLayout() layoutIfNeeded() } func setupTimer() { timer?.invalidate() timer = Timer.scheduledTimer(timeInterval: 0.5, target: self, selector: #selector(playerTimerAction), userInfo: nil, repeats: true) timer?.fireDate = Date() } // MARK: - ่ฎกๆ—ถๅ™จไบ‹ไปถ @objc fileprivate func playerTimerAction() { if let playerItem = playerItem { if playerItem.duration.timescale != 0 { let currentTime = CMTimeGetSeconds(self.player!.currentTime()) let totalTime = TimeInterval(playerItem.duration.value) / TimeInterval(playerItem.duration.timescale) delegate?.bmPlayer(player: self, playTimeDidChange: currentTime, totalTime: totalTime) } updateStatus(inclodeLoading: true) } } fileprivate func updateStatus(inclodeLoading: Bool = false) { if let player = player { if let playerItem = playerItem { if inclodeLoading { if playerItem.isPlaybackLikelyToKeepUp || playerItem.isPlaybackBufferFull { self.state = .bufferFinished } else { self.state = .buffering } } } if player.rate == 0.0 { if player.error != nil { self.state = .error return } if let currentItem = player.currentItem { if player.currentTime() >= currentItem.duration { moviePlayDidEnd() return } if currentItem.isPlaybackLikelyToKeepUp || currentItem.isPlaybackBufferFull { } } } } } // MARK: - Notification Event @objc fileprivate func moviePlayDidEnd() { if state != .playedToTheEnd { if let playerItem = playerItem { delegate?.bmPlayer(player: self, playTimeDidChange: CMTimeGetSeconds(playerItem.duration), totalTime: CMTimeGetSeconds(playerItem.duration)) } self.state = .playedToTheEnd self.isPlaying = false self.playDidEnd = true self.timer?.invalidate() } } // MARK: - KVO override open func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { if let item = object as? AVPlayerItem, let keyPath = keyPath { if item == self.playerItem { switch keyPath { case "status": if player?.status == AVPlayerStatus.readyToPlay { self.state = .buffering if shouldSeekTo != 0 { print("BMPlayerLayer | Should seek to \(shouldSeekTo)") seek(to: shouldSeekTo, completion: { self.shouldSeekTo = 0 self.hasReadyToPlay = true self.state = .readyToPlay }) } else { self.hasReadyToPlay = true self.state = .readyToPlay } } else if player?.status == AVPlayerStatus.failed { self.state = .error } case "loadedTimeRanges": // ่ฎก็ฎ—็ผ“ๅ†ฒ่ฟ›ๅบฆ if let timeInterVarl = self.availableDuration() { let duration = item.duration let totalDuration = CMTimeGetSeconds(duration) delegate?.bmPlayer(player: self, loadedTimeDidChange: timeInterVarl, totalDuration: totalDuration) } case "playbackBufferEmpty": // ๅฝ“็ผ“ๅ†ฒๆ˜ฏ็ฉบ็š„ๆ—ถๅ€™ if self.playerItem!.isPlaybackBufferEmpty { self.state = .buffering self.bufferingSomeSecond() } case "playbackLikelyToKeepUp": if item.isPlaybackBufferEmpty { if state != .bufferFinished && hasReadyToPlay { self.state = .bufferFinished self.playDidEnd = true } } default: break } } } if keyPath == "rate" { updateStatus() } } /** ็ผ“ๅ†ฒ่ฟ›ๅบฆ - returns: ็ผ“ๅ†ฒ่ฟ›ๅบฆ */ fileprivate func availableDuration() -> TimeInterval? { if let loadedTimeRanges = player?.currentItem?.loadedTimeRanges, let first = loadedTimeRanges.first { let timeRange = first.timeRangeValue let startSeconds = CMTimeGetSeconds(timeRange.start) let durationSecound = CMTimeGetSeconds(timeRange.duration) let result = startSeconds + durationSecound return result } return nil } /** ็ผ“ๅ†ฒๆฏ”่พƒๅทฎ็š„ๆ—ถๅ€™ */ fileprivate func bufferingSomeSecond() { self.state = .buffering // playbackBufferEmptyไผšๅๅค่ฟ›ๅ…ฅ๏ผŒๅ› ๆญคๅœจbufferingOneSecondๅปถๆ—ถๆ’ญๆ”พๆ‰ง่กŒๅฎŒไน‹ๅ‰ๅ†่ฐƒ็”จbufferingSomeSecond้ƒฝๅฟฝ็•ฅ if isBuffering { return } isBuffering = true // ้œ€่ฆๅ…ˆๆš‚ๅœไธ€ๅฐไผšไน‹ๅŽๅ†ๆ’ญๆ”พ๏ผŒๅฆๅˆ™็ฝ‘็ปœ็Šถๅ†ตไธๅฅฝ็š„ๆ—ถๅ€™ๆ—ถ้—ดๅœจ่ตฐ๏ผŒๅฃฐ้Ÿณๆ’ญๆ”พไธๅ‡บๆฅ player?.pause() let popTime = DispatchTime.now() + Double(Int64( Double(NSEC_PER_SEC) * 1.0 )) / Double(NSEC_PER_SEC) DispatchQueue.main.asyncAfter(deadline: popTime) { // ๅฆ‚ๆžœๆ‰ง่กŒไบ†play่ฟ˜ๆ˜ฏๆฒกๆœ‰ๆ’ญๆ”พๅˆ™่ฏดๆ˜Ž่ฟ˜ๆฒกๆœ‰็ผ“ๅญ˜ๅฅฝ๏ผŒๅˆ™ๅ†ๆฌก็ผ“ๅญ˜ไธ€ๆฎตๆ—ถ้—ด self.isBuffering = false if let item = self.playerItem { if !item.isPlaybackLikelyToKeepUp { self.bufferingSomeSecond() } else { // ๅฆ‚ๆžœๆญคๆ—ถ็”จๆˆทๅทฒ็ปๆš‚ๅœไบ†๏ผŒๅˆ™ไธๅ†้œ€่ฆๅผ€ๅฏๆ’ญๆ”พไบ† self.state = BMPlayerState.bufferFinished } } } } }
mit
20dfb60f89025b3c97bbe2d2eec22c97
31.800443
156
0.554046
5.208803
false
false
false
false
jtbandes/swift
benchmark/single-source/Integrate.swift
11
1831
//===--- Integrate.swift --------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// import TestsUtils // A micro-benchmark for recursive divide and conquer problems. // The program performs integration via Gaussian Quadrature class Integrate { static let epsilon = 1.0e-9 let fun: (Double) -> Double init (f: @escaping (Double) -> Double) { fun = f } private func recEval(_ l: Double, fl: Double, r: Double, fr: Double, a: Double) -> Double { let h = (r - l) / 2 let hh = h / 2 let c = l + h let fc = fun(c) let al = (fl + fc) * hh let ar = (fr + fc) * hh let alr = al + ar let error = abs(alr-a) if (error < Integrate.epsilon) { return alr } else { let a1 = recEval(c, fl:fc, r:r, fr:fr, a:ar) let a2 = recEval(l, fl:fl, r:c, fr:fc, a:al) return a1 + a2 } } @inline(never) func computeArea(_ left: Double, right: Double) -> Double { return recEval(left, fl:fun(left), r:right, fr:fun(right), a:0) } } @inline(never) public func run_Integrate(_ N: Int) { let obj = Integrate(f: { x in (x*x + 1.0) * x}) let left = 0.0 let right = 10.0 let ref_result = 2550.0 let bound = 0.0001 var result = 0.0 for _ in 1...N { result = obj.computeArea(left, right:right) if abs(result - ref_result) > bound { break } } CheckResults(abs(result - ref_result) < bound) }
apache-2.0
bf21123aa1f5dabc8511c77dafb22780
26.328358
93
0.566903
3.378229
false
false
false
false
ViacomInc/Router
Tests/RouterSpecs.swift
1
9216
//////////////////////////////////////////////////////////////////////////// // Copyright 2015 Viacom Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //////////////////////////////////////////////////////////////////////////// import UIKit import Quick import Nimble @testable import Router class RouterSpecs: QuickSpec { override func spec() { describe("Route") { describe(".regex") { it("converts /video/:id to regex /video/([^/]+)/?") { let route = try! Route(aRoute: "/video/:id") expect(route.routePattern).to(equal("^/video/([^/]+)/?$")) } it("converts /shows/:showId/video/:id to regex /shows/([^/]+)/video/([^/]+)/?") { let route = try! Route(aRoute: "/shows/:showId/video/:id") expect(route.routePattern).to(equal("^/shows/([^/]+)/video/([^/]+)/?$")) } it("converts routes with many params to a regex pattern") { let route = try! Route(aRoute: "/a/:a/b/:b/c/:c/d/:d/e/:e/f/:f") expect(route.routePattern).to(equal("^/a/([^/]+)/b/([^/]+)/c/([^/]+)/d/([^/]+)/e/([^/]+)/f/([^/]+)/?$")) } it("converts routes with many variable length params to a regex pattern") { let route = try! Route(aRoute: "/a/:abc/b/:bcdef/third/:cx/d/:d123/efgh/:e987654/:lastOne") expect(route.routePattern).to(equal("^/a/([^/]+)/b/([^/]+)/third/([^/]+)/d/([^/]+)/efgh/([^/]+)/([^/]+)/?$")) } it("converts non parameterized routes to a regex pattern") { let route = try! Route(aRoute: "/shows") expect(route.routePattern).to(equal("^/shows/?$")) } it("raises exception with identical url params in route") { do { let _ = try Route(aRoute: "/shows/:id/:id") } catch Route.RegexResult.duplicateRouteParamError(let route, let param) { expect(route).to(equal("/shows/:id/:id")) expect(param).to(equal("id")) } catch { fail() } } } } describe("Router") { describe(".match") { let route = "/video/:id" var myRouter: Router? beforeEach() { myRouter = Router() } it("allows alpha numeric and _, - characters in params") { let example = URL(string: "/video/123-asdf_foo-bar?q=123-_-")! myRouter?.bind(route) { (req) in expect(req.param("id")!).to(equal("123-asdf_foo-bar")) expect(req.query("q")).to(equal("123-_-")) } let matched = myRouter!.match(example)! expect(matched.route).to(equal(route)) } it("returns 1234 as :id in /video/1234") { let example = URL(string: "/video/1234")! myRouter?.bind(route) { (req) in expect(req.param("id")!).to(equal("1234")) expect(req.query("id")).to(beNil()) } let matched = myRouter!.match(example)! expect(matched.route).to(equal(route)) } it("handles routes with many params") { let example = URL(string: "/a/1/b/22/third/333/d/4444/efgh/55/6?q=asdf&fq=-alias")! let aRoute = "/a/:abc/b/:bcdef/third/:cx/d/:d123/efgh/:e987654/:lastOne" myRouter?.bind(aRoute) { (req) in expect(req.param("abc")!).to(equal("1")) expect(req.param("bcdef")!).to(equal("22")) expect(req.param("cx")!).to(equal("333")) expect(req.param("d123")!).to(equal("4444")) expect(req.param("e987654")!).to(equal("55")) expect(req.param("lastOne")!).to(equal("6")) expect(req.query("q")!).to(equal("asdf")) expect(req.query("fq")!).to(equal("-alias")) } let matched = myRouter!.match(example)! expect(matched.route).to(equal(aRoute)) } it("does not match routes with malformed query strings") { let example = URL(string: "/video/123/&q=asdf")! myRouter?.bind(route) { (req) in expect(req.query("q")).to(beNil()) } expect(myRouter!.match(example)).to(beNil()) } it("accepts query strings with '?&' sequence") { myRouter?.bind(route) { (req) in expect(req.param("id")!).to(equal("1234")) expect(req.query("q")!).to(equal("asdf")) } var matched = myRouter!.match(URL(string: "/video/1234/?&q=asdf")!)! expect(matched.route).to(equal(route)) matched = myRouter!.match(URL(string: "/video/1234?&q=asdf")!)! expect(matched.route).to(equal(route)) } it("matches routes at the start of the string, not suffix") { myRouter?.bind(route) { (req) in expect(0).to(equal(1)) } let matched = myRouter!.match(URL(string: "/shows/1234/video/1234")!) expect(matched).to(beNil()) } it("doesn't mix url param id with query param id") { let example = URL(string: "/video/1234?id=asdf")! myRouter?.bind(route) { (req) in expect(req.param("id")!).to(equal("1234")) expect(req.query("id")).to(equal("asdf")) } let matched = myRouter!.match(example)! expect(matched.route).to(equal(route)) } it("matches specific routes before general when binded first") { myRouter?.bind("/video/jersey-shore") { (req) in expect(0).to(equal(0)) } myRouter?.bind("/video/:id") { (req) in expect(0).to(equal(1)) } if let myRoute = myRouter?.match(URL(string: "/video/jersey-shore")!) { expect(myRoute.route).to(equal("/video/jersey-shore")) } else { expect(0).to(equal(1)) } } it("matches general routes before specific when binded first") { myRouter?.bind("/video/:id") { (req) in expect(0).to(equal(0)) } myRouter?.bind("/video/jersey-shore") { (req) in expect(0).to(equal(1)) } if let myRoute = myRouter?.match(URL(string: "/video/jersey-shore")!) { expect(myRoute.route).to(equal("/video/:id")) } else { expect(0).to(equal(1)) } } it("returns nil when no route is matched") { myRouter?.bind(route) { (req) in expect(0).to(equal(1)) } if let _ = myRouter?.match(URL(string: "/shows/1234")!) { expect(0).to(equal(1)) } else { expect(0).to(equal(0)) } } } } } }
apache-2.0
8a9e41b711540ffe31e850cf82d7cc52
42.885714
129
0.399957
4.733436
false
false
false
false
0416354917/FeedMeIOS
SSRadioButtonsController.swift
3
3795
// // RadioButtonsController.swift // TestApp // // Created by Al Shamas Tufail on 24/03/2015. // Copyright (c) 2015 Al Shamas Tufail. All rights reserved. // // Modified by Jun Chen on 30/03/2016. // Copyright ยฉ 2016 FeedMe. All rights reserved. // import UIKit /// RadioButtonControllerDelegate. Delegate optionally implements didSelectButton that receives selected button. @objc protocol SSRadioButtonControllerDelegate { /** This function is called when a button is selected. If 'shouldLetDeSelect' is true, and a button is deselected, this function is called with a nil. */ optional func didSelectButton(aButton: UIButton?) } class SSRadioButtonsController : NSObject { private var buttonsArray = [UIButton]() private weak var currentSelectedButton:UIButton? = nil weak var delegate : SSRadioButtonControllerDelegate? = nil /** Set whether a selected radio button can be deselected or not. Default value is false. */ var shouldLetDeSelect = false /** Variadic parameter init that accepts UIButtons. - parameter buttons: Buttons that should behave as Radio Buttons */ init(buttons: UIButton...) { super.init() for aButton in buttons { aButton.addTarget(self, action: #selector(SSRadioButtonsController.pressed(_:)), forControlEvents: UIControlEvents.TouchUpInside) } self.buttonsArray = buttons } /** Add a UIButton to Controller - parameter button: Add the button to controller. */ func addButton(aButton: UIButton) { buttonsArray.append(aButton) aButton.addTarget(self, action: #selector(SSRadioButtonsController.pressed(_:)), forControlEvents: UIControlEvents.TouchUpInside) } /** Remove a UIButton from controller. - parameter button: Button to be removed from controller. */ func removeButton(aButton: UIButton) { var iteration = 0 var iteratingButton: UIButton? = nil for _ in 0..<buttonsArray.count { iteratingButton = buttonsArray[iteration] if(iteratingButton == aButton) { break } else { iteratingButton = nil } iteration += 1 } if(iteratingButton != nil) { buttonsArray.removeAtIndex(iteration) iteratingButton!.removeTarget(self, action: #selector(SSRadioButtonsController.pressed(_:)), forControlEvents: UIControlEvents.TouchUpInside) if currentSelectedButton == iteratingButton { currentSelectedButton = nil } } } /** Set an array of UIButons to behave as controller. - parameter buttonArray: Array of buttons */ func setButtonsArray(aButtonsArray: [UIButton]) { for aButton in aButtonsArray { aButton.addTarget(self, action: #selector(SSRadioButtonsController.pressed(_:)), forControlEvents: UIControlEvents.TouchUpInside) } buttonsArray = aButtonsArray } func pressed(sender: UIButton) { if(sender.selected) { if shouldLetDeSelect { sender.selected = false currentSelectedButton = nil } } else { for aButton in buttonsArray { aButton.selected = false } sender.selected = true currentSelectedButton = sender } delegate?.didSelectButton?(currentSelectedButton) } /** Get the currently selected button. - returns: Currenlty selected button. */ func selectedButton() -> UIButton? { return currentSelectedButton } }
bsd-3-clause
5fbfd28c69c9b3ad39f75720f87d9c74
30.890756
154
0.624143
5.43553
false
false
false
false
wireapp/wire-ios
Wire-iOS/Sources/UserInterface/Sketchpad/CanvasViewController.swift
1
16020
// // Wire // Copyright (C) 2016 Wire Swiss GmbH // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see http://www.gnu.org/licenses/. // import UIKit import WireCanvas import WireCommonComponents import WireSyncEngine protocol CanvasViewControllerDelegate: AnyObject { func canvasViewController(_ canvasViewController: CanvasViewController, didExportImage image: UIImage) } enum CanvasViewControllerEditMode: UInt { case draw case emoji } final class CanvasViewController: UIViewController, UINavigationControllerDelegate { weak var delegate: CanvasViewControllerDelegate? var canvas = Canvas() private lazy var toolbar: SketchToolbar = SketchToolbar(buttons: [photoButton, drawButton, emojiButton, sendButton]) let drawButton = NonLegacyIconButton() let emojiButton = NonLegacyIconButton() let sendButton = IconButton.sendButton() let photoButton = NonLegacyIconButton() let separatorLine = UIView() let hintLabel = UILabel() let hintImageView = UIImageView() var isEmojiKeyboardInTransition = false var sketchImage: UIImage? { didSet { if let image = sketchImage { canvas.referenceImage = image } } } let emojiKeyboardViewController = EmojiKeyboardViewController() let colorPickerController = SketchColorPickerController() override var shouldAutorotate: Bool { switch UIDevice.current.userInterfaceIdiom { case .pad: return true default: return false } } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() canvas.setNeedsDisplay() } override func viewDidLoad() { super.viewDidLoad() canvas.delegate = self canvas.backgroundColor = SemanticColors.View.backgroundDefaultWhite canvas.isAccessibilityElement = true canvas.accessibilityIdentifier = "canvas" emojiKeyboardViewController.delegate = self separatorLine.backgroundColor = SemanticColors.View.backgroundSeparatorCell hintImageView.setIcon(.brush, size: 132, color: SemanticColors.Label.textSettingsPasswordPlaceholder) hintImageView.tintColor = SemanticColors.Label.textSettingsPasswordPlaceholder hintLabel.text = L10n.Localizable.Sketchpad.initialHint.capitalized hintLabel.numberOfLines = 0 hintLabel.font = FontSpec.normalRegularFont.font hintLabel.textAlignment = .center hintLabel.textColor = SemanticColors.Label.textSettingsPasswordPlaceholder self.view.backgroundColor = SemanticColors.View.backgroundDefaultWhite [canvas, hintLabel, hintImageView, toolbar].forEach(view.addSubview) if sketchImage != nil { hideHint() } configureNavigationItems() configureColorPicker() configureButtons() updateButtonSelection() createConstraints() } func configureNavigationItems() { let undoImage = StyleKitIcon.undo.makeImage(size: .tiny, color: .black) let closeImage = StyleKitIcon.cross.makeImage(size: .tiny, color: .black) let closeButtonItem = UIBarButtonItem(image: closeImage, style: .plain, target: self, action: #selector(CanvasViewController.close)) closeButtonItem.accessibilityIdentifier = "closeButton" let undoButtonItem = UIBarButtonItem(image: undoImage, style: .plain, target: canvas, action: #selector(Canvas.undo)) undoButtonItem.isEnabled = false undoButtonItem.accessibilityIdentifier = "undoButton" navigationItem.leftBarButtonItem = undoButtonItem navigationItem.rightBarButtonItem = closeButtonItem } func configureButtons() { let hitAreaPadding = CGSize(width: 16, height: 16) sendButton.addTarget(self, action: #selector(exportImage), for: .touchUpInside) sendButton.isEnabled = false sendButton.hitAreaPadding = hitAreaPadding drawButton.setIcon(.brush, size: .tiny, for: .normal) drawButton.addTarget(self, action: #selector(toggleDrawTool), for: .touchUpInside) drawButton.hitAreaPadding = hitAreaPadding drawButton.accessibilityIdentifier = "drawButton" photoButton.setIcon(.photo, size: .tiny, for: .normal) photoButton.addTarget(self, action: #selector(pickImage), for: .touchUpInside) photoButton.hitAreaPadding = hitAreaPadding photoButton.accessibilityIdentifier = "photoButton" photoButton.isHidden = !MediaShareRestrictionManager(sessionRestriction: ZMUserSession.shared()).hasAccessToCameraRoll emojiButton.setIcon(.emoji, size: .tiny, for: .normal) emojiButton.addTarget(self, action: #selector(openEmojiKeyboard), for: .touchUpInside) emojiButton.hitAreaPadding = hitAreaPadding emojiButton.accessibilityIdentifier = "emojiButton" [photoButton, drawButton, emojiButton].forEach { iconButton in iconButton.layer.cornerRadius = 12 iconButton.clipsToBounds = true iconButton.applyStyle(.iconButtonStyle) } } func configureColorPicker() { colorPickerController.sketchColors = [.black, .white, SemanticColors.LegacyColors.strongBlue, SemanticColors.LegacyColors.strongLimeGreen, SemanticColors.LegacyColors.brightYellow, SemanticColors.LegacyColors.vividRed, SemanticColors.LegacyColors.brightOrange, SemanticColors.LegacyColors.softPink, SemanticColors.LegacyColors.violet, UIColor(red: 0.688, green: 0.342, blue: 0.002, alpha: 1), UIColor(red: 0.381, green: 0.192, blue: 0.006, alpha: 1), UIColor(red: 0.894, green: 0.735, blue: 0.274, alpha: 1), UIColor(red: 0.905, green: 0.317, blue: 0.466, alpha: 1), UIColor(red: 0.58, green: 0.088, blue: 0.318, alpha: 1), UIColor(red: 0.431, green: 0.65, blue: 0.749, alpha: 1), UIColor(red: 0.6, green: 0.588, blue: 0.278, alpha: 1), UIColor(red: 0.44, green: 0.44, blue: 0.44, alpha: 1)] colorPickerController.view.addSubview(separatorLine) colorPickerController.delegate = self colorPickerController.willMove(toParent: self) view.addSubview(colorPickerController.view) addChild(colorPickerController) colorPickerController.selectedColorIndex = colorPickerController.sketchColors.firstIndex(of: UIColor.accent()) ?? 0 } private func createConstraints() { guard let colorPicker = colorPickerController.view else { return } [canvas, colorPicker, toolbar, separatorLine, hintImageView, hintLabel].prepareForLayout() NSLayoutConstraint.activate([ colorPicker.topAnchor.constraint(equalTo: view.topAnchor), colorPicker.leftAnchor.constraint(equalTo: view.leftAnchor), colorPicker.rightAnchor.constraint(equalTo: view.rightAnchor), colorPicker.heightAnchor.constraint(equalToConstant: 48), separatorLine.topAnchor.constraint(equalTo: colorPicker.bottomAnchor), separatorLine.leftAnchor.constraint(equalTo: colorPicker.leftAnchor), separatorLine.rightAnchor.constraint(equalTo: colorPicker.rightAnchor), separatorLine.heightAnchor.constraint(equalToConstant: .hairline), canvas.topAnchor.constraint(equalTo: colorPicker.bottomAnchor), canvas.leftAnchor.constraint(equalTo: view.leftAnchor), canvas.rightAnchor.constraint(equalTo: view.rightAnchor), toolbar.topAnchor.constraint(equalTo: canvas.bottomAnchor), toolbar.bottomAnchor.constraint(equalTo: view.bottomAnchor), toolbar.leftAnchor.constraint(equalTo: view.leftAnchor), toolbar.rightAnchor.constraint(equalTo: view.rightAnchor), hintImageView.centerXAnchor.constraint(equalTo: view.centerXAnchor), hintImageView.centerYAnchor.constraint(equalTo: view.centerYAnchor), hintLabel.topAnchor.constraint(equalTo: colorPicker.bottomAnchor, constant: 16), hintLabel.layoutMarginsGuide.leftAnchor.constraint(equalTo: view.layoutMarginsGuide.leftAnchor), hintLabel.layoutMarginsGuide.rightAnchor.constraint(equalTo: view.layoutMarginsGuide.rightAnchor) ]) } func updateButtonSelection() { drawButton.isSelected = canvas.mode == .draw colorPickerController.view.isHidden = canvas.mode != .draw } func hideHint() { hintLabel.isHidden = true hintImageView.isHidden = true } // MARK: - Actions @objc func toggleDrawTool() { if canvas.mode == .edit { canvas.mode = .draw } else { canvas.mode = .edit } updateButtonSelection() } @objc func openEmojiKeyboard() { select(editMode: .emoji, animated: true) } @objc func exportImage() { if let image = canvas.trimmedImage { delegate?.canvasViewController(self, didExportImage: image) } } @objc func close() { self.dismiss(animated: true, completion: nil) } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { super.touchesBegan(touches, with: event) hideEmojiKeyboard(animated: true) } func select(editMode: CanvasViewControllerEditMode, animated: Bool) { switch editMode { case .draw: hideEmojiKeyboard(animated: animated) canvas.mode = .draw updateButtonSelection() case .emoji: canvas.mode = .edit updateButtonSelection() showEmojiKeyboard(animated: animated) } } } extension CanvasViewController: CanvasDelegate { func canvasDidChange(_ canvas: Canvas) { sendButton.isEnabled = canvas.hasChanges navigationItem.leftBarButtonItem?.isEnabled = canvas.hasChanges hideHint() } } extension CanvasViewController: EmojiKeyboardViewControllerDelegate { func showEmojiKeyboard(animated: Bool) { guard !isEmojiKeyboardInTransition, let emojiKeyboardView = emojiKeyboardViewController.view else { return } emojiKeyboardViewController.willMove(toParent: self) view.addSubview(emojiKeyboardViewController.view) emojiKeyboardView.translatesAutoresizingMaskIntoConstraints = false addChild(emojiKeyboardViewController) NSLayoutConstraint.activate([ emojiKeyboardView.heightAnchor.constraint(equalToConstant: KeyboardHeight.current), emojiKeyboardView.leftAnchor.constraint(equalTo: view.leftAnchor), emojiKeyboardView.rightAnchor.constraint(equalTo: view.rightAnchor), emojiKeyboardView.bottomAnchor.constraint(equalTo: view.bottomAnchor) ]) if animated { isEmojiKeyboardInTransition = true let offscreen = CGAffineTransform(translationX: 0, y: KeyboardHeight.current) emojiKeyboardViewController.view.transform = offscreen view.layoutIfNeeded() UIView.animate(withDuration: 0.25, delay: 0, options: UIView.AnimationOptions(rawValue: UInt(7)), animations: { self.emojiKeyboardViewController.view.transform = CGAffineTransform.identity }, completion: { _ in self.isEmojiKeyboardInTransition = false }) } } func hideEmojiKeyboard(animated: Bool) { guard children.contains(emojiKeyboardViewController), !isEmojiKeyboardInTransition else { return } emojiKeyboardViewController.willMove(toParent: nil) let removeEmojiKeyboardViewController = { self.emojiKeyboardViewController.view.removeFromSuperview() self.emojiKeyboardViewController.removeFromParent() } if animated { isEmojiKeyboardInTransition = true UIView.animate(withDuration: 0.25, delay: 0, options: UIView.AnimationOptions(rawValue: UInt(7)), animations: { let offscreen = CGAffineTransform(translationX: 0, y: self.emojiKeyboardViewController.view.bounds.size.height) self.emojiKeyboardViewController.view.transform = offscreen }, completion: { _ in self.isEmojiKeyboardInTransition = false removeEmojiKeyboardViewController() }) } else { removeEmojiKeyboardViewController() } } func emojiKeyboardViewControllerDeleteTapped(_ viewController: EmojiKeyboardViewController) { } func emojiKeyboardViewController(_ viewController: EmojiKeyboardViewController, didSelectEmoji emoji: String) { let attributes = [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 82)] if let image = emoji.image(renderedWithAttributes: attributes)?.imageWithAlphaTrimmed { canvas.insert(image: image, at: CGPoint(x: canvas.center.x - image.size.width / 2, y: canvas.center.y - image.size.height / 2)) } hideEmojiKeyboard(animated: true) } } extension CanvasViewController: UIImagePickerControllerDelegate { @objc func pickImage() { let imagePickerController = UIImagePickerController() imagePickerController.delegate = self present(imagePickerController, animated: true, completion: nil) } func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey: Any]) { defer { picker.dismiss(animated: true, completion: nil) } guard let image = info[.editedImage] as? UIImage ?? info[.originalImage] as? UIImage else { return } canvas.referenceImage = image canvas.mode = .draw updateButtonSelection() } func imagePickerControllerDidCancel(_ picker: UIImagePickerController) { picker.dismiss(animated: true, completion: nil) } } extension CanvasViewController: SketchColorPickerControllerDelegate { func sketchColorPickerController(_ controller: SketchColorPickerController, changedSelectedColor color: UIColor) { canvas.brush = Brush(size: Float(controller.brushWidth(for: color)), color: color) } }
gpl-3.0
fed323173a1f0bc58dbc90745a26b71c
38.073171
143
0.643196
5.574113
false
false
false
false
KiiPlatform/thing-if-iOSSample
SampleProject/TriggerCommandEditViewController.swift
1
7308
// // TriggerCommandEditViewController.swift // SampleProject // // Created by Yongping on 8/27/15. // Copyright ยฉ 2015 Kii Corporation. All rights reserved. // import UIKit import ThingIFSDK protocol TriggerCommandEditViewControllerDelegate { func saveCommands(schemaName: String, schemaVersion: Int, actions: [Dictionary<String, AnyObject>], targetID: String?, title: String?, commandDescription: String?, metadata: Dictionary<String, AnyObject>?) } class TriggerCommandEditViewController: CommandEditViewController { var delegate: TriggerCommandEditViewControllerDelegate? override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) var targetIdSection = SectionStruct(headerTitle: "Target thing ID", items: []) var titleSection = SectionStruct(headerTitle: "Title", items: []) var descriptionSection = SectionStruct(headerTitle: "Description", items: []) var metadataSection = SectionStruct(headerTitle: "Meta data", items: []) if let command = self.commandStruct { if let targetID = command.targetID { targetIdSection.items.append(targetID) } if let title = command.title { titleSection.items.append(title) } if let description = command.commandDescription { descriptionSection.items.append(description) } if let metadata = command.metadata { if let data = try? NSJSONSerialization.dataWithJSONObject( metadata, options: .PrettyPrinted) { metadataSection.items.append( String(data:data, encoding:NSUTF8StringEncoding)!) } } } sections += [targetIdSection, titleSection, descriptionSection, metadataSection] } override func tableView( tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { if sections[indexPath.section].headerTitle == "Target thing ID" { let cell = tableView.dequeueReusableCellWithIdentifier( "TargetIDCell", forIndexPath: indexPath) if let items = sections[indexPath.section].items where !items.isEmpty { let value = items[indexPath.row] as! String (cell.viewWithTag(202) as! UITextField).text = value } return cell } else if sections[indexPath.section].headerTitle == "Title" { let cell = tableView.dequeueReusableCellWithIdentifier( "CommandTitleCell", forIndexPath: indexPath) if let items = sections[indexPath.section].items where !items.isEmpty { let value = items[indexPath.row] as! String (cell.viewWithTag(203) as! UITextField).text = value } return cell } else if sections[indexPath.section].headerTitle == "Description" { let cell = tableView.dequeueReusableCellWithIdentifier( "CommandDescriptionCell", forIndexPath: indexPath) if let items = sections[indexPath.section].items where !items.isEmpty { let value = items[indexPath.row] as! String (cell.viewWithTag(204) as! UITextView).text = value } return cell } else if sections[indexPath.section].headerTitle == "Meta data" { let cell = tableView.dequeueReusableCellWithIdentifier( "CommandMetadataCell", forIndexPath: indexPath) if let items = sections[indexPath.section].items where !items.isEmpty { let value = items[indexPath.row] as! String (cell.viewWithTag(205) as! UITextView).text = value } return cell } else { return super.tableView(tableView, cellForRowAtIndexPath: indexPath) } } override func tableView( tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { if sections[indexPath.section].headerTitle == "Description" { return 130 } else if sections[indexPath.section].headerTitle == "Meta data" { return 130 } else { return super.tableView(tableView, heightForRowAtIndexPath: indexPath) } } @IBAction func tapSaveCommand(sender: AnyObject) { // generate actions array var actions = [Dictionary<String, AnyObject>]() if let actionsItems = sections[2].items { for actionItem in actionsItems { if let actionCellData = actionItem as? ActionStruct { // action should be like: ["actionName": ["requiredStatus": value] ], where value can be Bool, Int or Double actions.append(actionCellData.getActionDict()) } } } // the defaultd schema and schemaVersion from predefined schem dict let schema: String? = (self.view.viewWithTag(200) as? UITextField)?.text let schemaVersion: Int? if let schemaVersionTextFiled = self.view.viewWithTag(201) as? UITextField { schemaVersion = Int(schemaVersionTextFiled.text!)! } else { schemaVersion = nil } let targetID: String? if let text = (self.view.viewWithTag(202) as? UITextField)?.text where !text.isEmpty { targetID = text } else { targetID = nil } let title: String? if let text = (self.view.viewWithTag(203) as? UITextField)?.text where !text.isEmpty { title = text } else { title = nil } let description: String? if let text = (self.view.viewWithTag(204) as? UITextView)?.text where !text.isEmpty { description = text } else { description = nil } let metadata: Dictionary<String, AnyObject>? if let text = (self.view.viewWithTag(205) as? UITextView)?.text { metadata = try? NSJSONSerialization.JSONObjectWithData( text.dataUsingEncoding(NSUTF8StringEncoding)!, options: .MutableContainers) as! Dictionary<String, AnyObject> } else { metadata = nil } if self.delegate != nil { delegate?.saveCommands(schema!, schemaVersion: schemaVersion!, actions: actions, targetID: targetID, title: title, commandDescription: description, metadata: metadata) } self.navigationController?.popViewControllerAnimated(true) } }
mit
65a547ad159e0eefbced12021082c55c
38.284946
128
0.559327
5.646832
false
false
false
false
mlgoogle/wp
wp/Scenes/Share/RechageVC/RechargeDetailVC.swift
1
1133
// // WithDrawDetail.swift // wp // // Created by sum on 2017/1/9. // Copyright ยฉ 2017ๅนด com.yundian. All rights reserved. // import UIKit // ๆ็Žฐ่ฏฆๆƒ… class RechargeDetailVC: BaseTableViewController { // ้“ถ่กŒๅ็งฐ @IBOutlet weak var bankName: UILabel! // ๆ็Žฐๆ—ถ้—ด @IBOutlet weak var withDrawtime: UILabel! // ้ข„่ฎกๅˆฐ่ดฆๆ—ถ้—ด @IBOutlet weak var expectTime: UILabel! // ๅˆฐ่ดฆๆ—ถ้—ด @IBOutlet weak var ToAccountTime: UILabel! override func viewDidLoad() { super.viewDidLoad() title = "ๅ……ๅ€ผ่ฏฆๆƒ…" didRequest() } // ่ฏทๆฑ‚ๆŽฅๅฃ override func didRequest() { let param = RechargeDetailParam() param.rid = Int(ShareModel.share().shareData["wid"]!)! AppAPIHelper.user().creditdetail(param: param, complete: { [weak self](result) -> ()? in let model : WithdrawModel = result as! WithdrawModel self?.bankName.text = model.bank return nil }, error: errorBlockFunc()) } }
apache-2.0
c803f937a89ceae000ab4b3a66938285
21.765957
96
0.557009
4.297189
false
false
false
false
mirchow/HungerFreeCity
ios/Hunger Free City/Controllers/LoginViewController.swift
1
2700
// // LoginViewController.swift // Hunger Free City // // Created by Mirek Chowaniok on 6/26/15. // Copyright (c) 2015 Mobilesoft. All rights reserved. // import UIKit import FBSDKLoginKit class LoginViewController: UIViewController, FBSDKLoginButtonDelegate { @IBOutlet weak var fbLoginButton: FBSDKLoginButton! // @IBOutlet weak var googleLoginButton: GIDSignInButton! override func viewDidLoad() { super.viewDidLoad() fbLoginButton.readPermissions = ["public_profile", "email"] fbLoginButton.delegate = self } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: Facebook Delegate Methods func loginButton(loginButton: FBSDKLoginButton!, didCompleteWithResult result: FBSDKLoginManagerLoginResult!, error: NSError!) { print("User Logged In") if error != nil { print("process error") } else if result.isCancelled { print("handle cancellations") } else { // If you ask for multiple permissions at once, you // should check if specific permissions missing } } func loginButtonDidLogOut(loginButton: FBSDKLoginButton!) { print("User logged Out") } @IBOutlet weak var userDataLabel: UILabel! @IBAction func clickUserData() { returnUserData() } func returnUserData() { let graphRequest: FBSDKGraphRequest = FBSDKGraphRequest(graphPath: "me", parameters: nil) graphRequest.startWithCompletionHandler { (connection, result, error) -> Void in if error != nil { print("Error: \(error)") } else { print("fetched user: \(result)") let userName: NSString = result.valueForKey("name") as! NSString print("User Name is: \(userName)") let userEmail: NSString = result.valueForKey("email") as! NSString print("User Email is: \(userEmail)") dispatch_async(dispatch_get_main_queue(), { self.userDataLabel.text = "\(result)" }) } } } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
mit
0b13d7083e1b20bc0cd2ae74bceec58d
30.764706
132
0.606296
5.357143
false
false
false
false
misuqian/iOSDemoSwift
ZoomingPDFViewerSwift/ZoomingPDFViewerSwift/RootViewController.swift
1
6005
// // ViewController.swift // ZoomingPDFViewerSwift // // Created by ๅฝญ่ŠŠ on 16/4/24. // Copyright ยฉ 2016ๅนด ๅฝญ่ŠŠ. All rights reserved. // import UIKit // ๆ น่ง†ๅ›พ๏ผŒ็”จๆฅๅˆ›ๅปบPageControllerๅนถ็ฎก็†่ง†ๅ›พๅˆ‡ๆข class RootViewController: UIViewController,UIPageViewControllerDelegate,UIPageViewControllerDataSource{ //ๅ…จๅฑ€ๅฃฐๆ˜Žๅˆๅง‹ๅŒ–pageController.PageCurlๅฐ†ๅฑ•็คบ็ฟป้กตๆ•ˆๆžœ(page-turning),Scrollๅฑ•็คบๆปšๅŠจ้กต้ขๆ•ˆๆžœ(page-scrolling) private var pageController : UIPageViewController = UIPageViewController(transitionStyle: .PageCurl, navigationOrientation: .Horizontal, options: nil) private var pdf : CGPDFDocument? = nil private var numberPages : Int = 0 override func viewDidLoad() { super.viewDidLoad() readPDF() //่ฎพ็ฝฎpageController self.pageController.delegate = self self.pageController.dataSource = self //ๅฎ˜ๆ–นOC็‰ˆๆœฌๅฐ†่ฟ™้ƒจๅˆ†ๅฐ่ฃ…ๅˆฐไบ†modelControllerไธญ let startingViewController = viewControllerAtIndex(0, storyBoard: self.storyboard!) self.pageController.setViewControllers([startingViewController], direction: .Forward, animated: false, completion: nil) self.addChildViewController(self.pageController) self.view.addSubview(self.pageController.view) let pageViewRect = self.view.bounds self.pageController.view.frame = pageViewRect self.pageController.didMoveToParentViewController(self) self.view.gestureRecognizers = self.pageController.gestureRecognizers } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } /** UIPageViewControllerDataSource */ //่ฟ”ๅ›žๅฝ“ๅ‰้กต้ข็š„ๅ‰ไธ€้กตViewController internal func pageViewController(pageViewController: UIPageViewController, viewControllerBeforeViewController viewController: UIViewController) -> UIViewController?{ //่Žทๅ–ๅฝ“ๅ‰VC็š„index var index = self.indexOfViewController(viewController as! DataViewController) //NSNotFoundๆ˜ฏไธ€ไธชๅœจ32ไฝๅ’Œ64ไฝไธŠไธไธ€ๆ ท็š„int,ไธ€่ˆฌๅฃฐๆ˜ŽไธบUIntๆœ€ๅคงๅ€ผ,็”จๆฅ่กจ็คบๆฒกๆœ‰ๆ‰พๅˆฐ if index == 0 || index == NSNotFound{ return nil } index -= 1 return self.viewControllerAtIndex(index, storyBoard: self.storyboard!) } //่ฟ”ๅ›žๅฝ“ๅ‰้กต้ข็š„ๅŽไธ€้กตViewController internal func pageViewController(pageViewController: UIPageViewController, viewControllerAfterViewController viewController: UIViewController) -> UIViewController?{ var index = self.indexOfViewController(viewController as! DataViewController) //NSNotFoundๆ˜ฏไธ€ไธชๅœจ32ไฝๅ’Œ64ไฝไธŠไธไธ€ๆ ท็š„int,็”จๆฅ่กจ็คบๆฒกๆœ‰ๆ‰พๅˆฐ if index == NSNotFound{ return nil } index += 1 if index == self.numberPages{ return nil } return self.viewControllerAtIndex(index, storyBoard: self.storyboard!) } /** UIPageViewControllerDelegate */ //ๅฝ“ๅฑๅน•่ฝฌๅ‘ๅ˜ๅŒ–็š„ๆ—ถๅ€™่ฐƒ็”จ๏ผŒไป…ๅœจpageStyleไธบPageCurlๆ—ถ็”Ÿๆ•ˆ func pageViewController(pageViewController: UIPageViewController, spineLocationForInterfaceOrientation orientation: UIInterfaceOrientation) -> UIPageViewControllerSpineLocation { let currentVC = self.pageController.viewControllers![0] as! DataViewController var VCArray = [currentVC] //็ซ–ๅฑๆˆ–่€…iPhone,่ฟ”ๅ›žSpineLocation.Min(้กต้ขๅชๆœ‰ไธ€ไธชpage),doubleSidedๅŒ้กต่ฎพ็ฝฎflase,ๅนถ้‡็ฝฎpageController็š„VCๆ•ฐ็ป„ๅชๅซๅฝ“ๅ‰้กต้ข if orientation == UIInterfaceOrientation.Portrait || UIDevice.currentDevice().userInterfaceIdiom == UIUserInterfaceIdiom.Phone{ self.pageController.setViewControllers(VCArray, direction: .Forward, animated: true, completion: nil) self.pageController.doubleSided = false return UIPageViewControllerSpineLocation.Min } //ๆจชๅฑๆˆ–่€…iPad่ฎพๅค‡,่ฟ”ๅ›žSpineLocation.Mid(้กต้ขๆœ‰ไธคไธชpage),pageController็š„VCๆ•ฐ็ป„้œ€่ฆไธคไธชไปฅไธŠVC.ๅˆคๆ–ญๅฝ“ๅ‰้กตไฝ็ฝฎ,ๅถๆ•ฐๅŠ ่ฝฝๅฝ“ๅ‰ๅ’Œไน‹ๅŽVC,ๅฅ‡ๆ•ฐๅŠ ่ฝฝๅฝ“ๅ‰ๅ’Œไน‹ๅ‰็š„VC(ๅฝ“ๅ‰้กตไฝ็ฝฎไปŽ0ๅผ€ๅง‹) let VCIndex = self.indexOfViewController(currentVC) if VCIndex % 2 == 0 { let nextVC = self.pageViewController(self.pageController, viewControllerAfterViewController: currentVC) as! DataViewController VCArray.append(nextVC) }else{ let preVC = self.pageViewController(self.pageController, viewControllerBeforeViewController: currentVC) as! DataViewController VCArray.removeAll() VCArray.append(preVC) VCArray.append(currentVC) } self.pageController.setViewControllers(VCArray, direction: .Forward, animated: true, completion: nil) return UIPageViewControllerSpineLocation.Mid } /** ็›ธๅฝ“ไบŽๅฎ˜ๆ–นOC็‰ˆไธญ็š„ModelController */ //่ฏปๅ–PDF func readPDF(){ let url = NSBundle.mainBundle().URLForResource("input_pdf", withExtension: ".pdf") pdf = CGPDFDocumentCreateWithURL(url) numberPages = CGPDFDocumentGetNumberOfPages(pdf) if numberPages % 2 == 1 { numberPages += 1 } } func viewControllerAtIndex(index : Int,storyBoard : UIStoryboard) -> DataViewController{ //storyboardไธญVC็š„identify inspector่ฎพ็ฝฎStoryBoard IdไธบDataViewController let dataViewController = storyBoard.instantiateViewControllerWithIdentifier("DataViewController") as! DataViewController dataViewController.numberPages = index + 1 dataViewController.pdf = self.pdf! return dataViewController } func indexOfViewController(dataViewController : DataViewController) -> Int{ return dataViewController.numberPages - 1 } //้š่—้กถ้ƒจ็Šถๆ€ๆ  override func prefersStatusBarHidden() -> Bool { return true } }
mit
a48b1a0a933c31988a2f7f896d1a13a9
40.938931
182
0.710229
5.115456
false
false
false
false
richard92m/three.bar
ThreeBar/ThreeBar/Lock.swift
1
1471
// // Lock.swift // ThreeBar // // Created by Marquez, Richard A on 12/21/14. // Copyright (c) 2014 Richard Marquez. All rights reserved. // import Foundation import SpriteKit class Lock: SKSpriteNode { var open = false init(position: CGPoint) { let width = _magic.get("lockWidth") as CGFloat let height = _magic.get("lockHeight") as CGFloat let color = UIColor.purpleColor() super.init(texture: nil, color: color, size: CGSize(width: width, height: height)) self.position = position zRotation = DEGREES_TO_RADIANS(_magic.get("lockRotation") as CGFloat) zPosition = CGFloat(ZIndex.Lock.rawValue) setPhysics() } func setPhysics() { let tolerance = _magic.get("lockContactTolerance") as CGFloat physicsBody = SKPhysicsBody(rectangleOfSize: CGSize(width: size.width + tolerance, height: size.height + tolerance)) physicsBody?.categoryBitMask = PhysicsCategory.Lock physicsBody?.dynamic = true physicsBody?.allowsRotation = true physicsBody?.usesPreciseCollisionDetection = true physicsBody?.contactTestBitMask = PhysicsCategory.Laser physicsBody?.collisionBitMask = 0 } func unlock() { open = true color = UIColor.greenColor() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
gpl-3.0
e8ad081b99f531a07d34df5151740e6f
27.862745
124
0.636982
4.611285
false
false
false
false
cherrywoods/swift-meta-serialization
Examples/DynamicUnwrap/DecodingKeyedContainerMeta.swift
1
3118
// // DecodingKeyedContainerMeta.swift // MetaSerialization // // Copyright 2018 cherrywoods // // 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 @testable import MetaSerialization struct Example2DecodingKeyedContainerMeta: DecodingKeyedContainerMeta { let values: Dictionary<String, Example2Meta> /// Returns a new decoding container meta, if array can be seen a keyed container. init?(array: [Example2Meta]) { guard !array.isEmpty else { // if array is empty, it can always be a keyed container self.values = [:] return } guard array.count % 2 == 0 else { // if the number of elements isn't just, it can't be an array of key value pairs. return nil } var keys: [String] = [] var values: [Example2Meta] = [] for index in 0..<array.count { if index % 2 == 0 { // just elements are seen as keys guard case Example2Meta.string(let key) = array[index] else { // keys need to be Strings (and not Arrays of Strings) return nil } keys.append( key ) } else { // odds are values values.append( array[index] ) } } // check that there are no duplicate keys: // sort keys, so we don't need to compare all keys to all keys let sortedKeys = keys.sorted() // now we just need to go through all keys and compare with the key before var lastKey = sortedKeys.first! // since array isn't empty, there is at least one key for key in sortedKeys.suffix( keys.count-1 /* All keys, except the first one */ ) { guard key != lastKey else { // if keys aren't unique, array can't be seen as a keyed container return nil } lastKey = key } self.values = Dictionary(uniqueKeysWithValues: zip(keys, values)) } // MARK: keyed container furctionality var allKeys: [MetaCodingKey] { return values.keys.map { MetaCodingKey(stringValue: $0) } } func contains(key: MetaCodingKey) -> Bool { return values[key.stringValue] != nil } func getValue(for key: MetaCodingKey) -> Meta? { return values[key.stringValue] } }
apache-2.0
b2e0c6ff1f8d639fb734cc5459e9d837
31.479167
93
0.566389
4.789555
false
false
false
false
tokyovigilante/CesiumKit
CesiumKit/Renderer/Framebuffer.swift
1
3551
// // Framebuffer.swift // CesiumKit // // Created by Ryan Walklin on 15/06/14. // Copyright (c) 2014 Test Toast. All rights reserved. // import MetalKit /** * @private */ class Framebuffer { let maximumColorAttachments: Int fileprivate (set) var colorTextures: [Texture]? fileprivate (set) var depthTexture: Texture? fileprivate (set) var stencilTexture: Texture? var depthStencilTexture: Texture? { return depthTexture === stencilTexture ? depthTexture : nil } var renderPassDescriptor: MTLRenderPassDescriptor { return _rpd } fileprivate var _rpd = MTLRenderPassDescriptor() var numberOfColorAttachments: Int { return colorTextures?.count ?? 0 } /** * True if the framebuffer has a depth attachment. Depth attachments include * depth and depth-stencil textures, and depth and depth-stencil renderbuffers. When * rendering to a framebuffer, a depth attachment is required for the depth test to have effect. * @memberof Framebuffer.prototype * @type {Boolean} */ var hasDepthAttachment: Bool { return depthTexture != nil } init ( maximumColorAttachments: Int, colorTextures: [Texture]? = nil, depthTexture: Texture? = nil, stencilTexture: Texture? = nil) { self.maximumColorAttachments = maximumColorAttachments self.colorTextures = colorTextures self.depthTexture = depthTexture self.stencilTexture = stencilTexture assert(colorTextures == nil || colorTextures!.count <= Int(maximumColorAttachments), "The number of color attachments exceeds the number supported.") updateRenderPassDescriptor() } func updateFromDrawable (context: Context, drawable: CAMetalDrawable, depthStencil: MTLTexture?) { colorTextures = [Texture(context: context, metalTexture: drawable.texture)] depthTexture = depthStencil == nil ? nil : Texture(context: context, metalTexture: depthStencil!) stencilTexture = depthTexture updateRenderPassDescriptor() } func update (colorTextures: [Texture]?, depthTexture: Texture?, stencilTexture: Texture?) { self.colorTextures = colorTextures self.depthTexture = depthTexture self.stencilTexture = stencilTexture updateRenderPassDescriptor() } fileprivate func updateRenderPassDescriptor () { if let colorTextures = self.colorTextures { for (i, colorTexture) in colorTextures.enumerated() { _rpd.colorAttachments[i].texture = colorTexture.metalTexture _rpd.colorAttachments[i].storeAction = .store } } else { for i in 0..<maximumColorAttachments { _rpd.colorAttachments[i].texture = nil _rpd.colorAttachments[i].loadAction = .dontCare _rpd.colorAttachments[i].storeAction = .dontCare } } _rpd.depthAttachment.texture = self.depthTexture?.metalTexture _rpd.stencilAttachment.texture = self.stencilTexture?.metalTexture } func clearDrawable () { colorTextures = nil _rpd.colorAttachments[0].texture = nil _rpd.colorAttachments[0].loadAction = .load _rpd.colorAttachments[0].storeAction = .dontCare _rpd.depthAttachment.texture = nil _rpd.stencilAttachment.texture = nil } }
apache-2.0
0bc06de707d5a203babdb824112824c5
32.819048
161
0.640383
4.904696
false
false
false
false
GreatfeatServices/gf-mobile-app
olivin-esguerra/ios-exam/Pods/Moya/Sources/Moya/Moya+Alamofire.swift
43
3037
import Foundation import Alamofire public typealias Manager = Alamofire.SessionManager internal typealias Request = Alamofire.Request internal typealias DownloadRequest = Alamofire.DownloadRequest internal typealias UploadRequest = Alamofire.UploadRequest internal typealias DataRequest = Alamofire.DataRequest internal typealias URLRequestConvertible = Alamofire.URLRequestConvertible /// Represents an HTTP method. public typealias Method = Alamofire.HTTPMethod /// Choice of parameter encoding. public typealias ParameterEncoding = Alamofire.ParameterEncoding public typealias JSONEncoding = Alamofire.JSONEncoding public typealias URLEncoding = Alamofire.URLEncoding public typealias PropertyListEncoding = Alamofire.PropertyListEncoding /// Multipart form public typealias RequestMultipartFormData = Alamofire.MultipartFormData /// Multipart form data encoding result. public typealias MultipartFormDataEncodingResult = Manager.MultipartFormDataEncodingResult public typealias DownloadDestination = Alamofire.DownloadRequest.DownloadFileDestination /// Make the Alamofire Request type conform to our type, to prevent leaking Alamofire to plugins. extension Request: RequestType { } /// Internal token that can be used to cancel requests public final class CancellableToken: Cancellable, CustomDebugStringConvertible { let cancelAction: () -> Void let request: Request? public fileprivate(set) var isCancelled = false fileprivate var lock: DispatchSemaphore = DispatchSemaphore(value: 1) public func cancel() { _ = lock.wait(timeout: DispatchTime.distantFuture) defer { lock.signal() } guard !isCancelled else { return } isCancelled = true cancelAction() } public init(action: @escaping () -> Void) { self.cancelAction = action self.request = nil } init(request: Request) { self.request = request self.cancelAction = { request.cancel() } } public var debugDescription: String { guard let request = self.request else { return "Empty Request" } return request.debugDescription } } internal typealias RequestableCompletion = (HTTPURLResponse?, URLRequest?, Data?, Swift.Error?) -> Void internal protocol Requestable { func response(queue: DispatchQueue?, completionHandler: @escaping RequestableCompletion) -> Self } extension DataRequest: Requestable { internal func response(queue: DispatchQueue?, completionHandler: @escaping RequestableCompletion) -> Self { return response(queue: queue) { handler in completionHandler(handler.response, handler.request, handler.data, handler.error) } } } extension DownloadRequest: Requestable { internal func response(queue: DispatchQueue?, completionHandler: @escaping RequestableCompletion) -> Self { return response(queue: queue) { handler in completionHandler(handler.response, handler.request, nil, handler.error) } } }
apache-2.0
2089b26e7d08fa52d08c6ccaae928816
33.511364
111
0.74218
5.562271
false
false
false
false
PeteShearer/SwiftNinja
029-ActivityViewController/MasterDetail/MasterDetail/MasterViewController.swift
1
3204
// // MasterViewController.swift // MasterDetail // // Created by Peter Shearer on 12/12/16. // Copyright ยฉ 2016 Peter Shearer. All rights reserved. // import UIKit class MasterViewController: UITableViewController { var objects = [Episode]() var selectedEpisode = Episode( episodeTitle: "", writerName: "", doctorName: "", episodeNumber: "", synopsis: "") override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. objects = EpisodeRepository.getEpisodeList() } // MARK: - Segues override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "showDetail" { (segue.destination as! DetailViewController).detailItem = selectedEpisode } } // MARK: - Table View func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { // the cells you would like the actions to appear needs to be editable return true } func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { // You need to declare this method or else you can't swipe } override func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? { let episode = self.objects[indexPath.row] self.selectedEpisode = episode let delete = UITableViewRowAction(style: .destructive, title: "Delete") { (action, indexPath) in self.objects.remove(at: indexPath.row) self.tableView.reloadData() } let share = UITableViewRowAction(style: .normal, title: "Share") { (action, indexPath) in let activityViewController = UIActivityViewController( activityItems: [episode.episodeTitle, episode.episodeNumber, episode.doctorName], applicationActivities: nil) self.present(activityViewController, animated: true, completion: nil) } let selectToView = UITableViewRowAction(style: .normal, title: "Select") { (action, indexPath) in self.performSegue(withIdentifier: "showDetail", sender: nil) } selectToView.backgroundColor = UIColor.blue return [delete, share, selectToView] } override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return objects.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as UITableViewCell let episode = objects[indexPath.row] cell.textLabel?.text = episode.episodeTitle cell.detailTextLabel?.text = episode.episodeNumber return cell } }
bsd-2-clause
e29e376ea41db37d14be752cf9b2ca54
33.44086
148
0.640649
5.493997
false
false
false
false
pupboss/vfeng
vfeng/ShowTableViewController.swift
1
2903
// // ShowTableViewController.swift // vfeng // // Created by Li Jie on 10/25/15. // Copyright ยฉ 2015 PUPBOSS. All rights reserved. // import UIKit import Alamofire class ShowTableViewController: BaseTableViewController { var foodArr = [] override func viewDidLoad() { super.viewDidLoad() self.tableView.registerNib(UINib(nibName: "FoodTableViewCell", bundle: nil), forCellReuseIdentifier: "foodcell") self.tableView.rowHeight = 101 MBProgressHUD.showMessage(Constants.Notification.LOADING) Alamofire.request(.GET, Constants.ROOT_URL + "information/food").responseJSON { (response: Response<AnyObject, NSError>) -> Void in MBProgressHUD.hideHUD() if let arr = response.result.value as? Array<Array<String>> { self.foodArr = arr self.tableView.reloadData() } else { MBProgressHUD.showError(Constants.Notification.NET_ERROR) } } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { // #warning Incomplete implementation, return the number of sections return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows return self.foodArr.count } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { super.tableView(tableView, didSelectRowAtIndexPath: indexPath) self.performSegueWithIdentifier("show2detail", sender: self.foodArr[indexPath.row]) } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("foodcell") as! FoodTableViewCell let arr: Array<String> = self.foodArr[indexPath.row] as! Array<String> cell.imgView.image = UIImage.init(data: NSData.init(contentsOfURL: NSURL(string: arr[0])!)!) cell.nameLabel.text = arr[1] cell.rewardLabel.text = arr[3] return cell } // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { let con = segue.destinationViewController as! ShowDetailViewController con.detailArr = sender as! Array<String> } }
gpl-2.0
6f75b8f860cb4591f0425469049c8cba
31.606742
139
0.639214
5.305302
false
false
false
false
saturday06/FrameworkBenchmarks
frameworks/Swift/vapor/Sources/vapor-tfb-mongodb/Models/Fortune.swift
10
1785
import Vapor import FluentProvider final class Fortune: Model { static let entity = "fortune" var storage: Storage = Storage() var mongoId: Node? var id: Node? var message: String static var idKey = "_id" // For internal Vapor use var exists: Bool = false init(id: Int, message: String) { self.id = Node(id) self.message = message } init(node: Node, in context: Context) throws { id = try node.get("_id") mongoId = try node.get("id") message = try node.get("message") } /// Initializes the Fortune from the /// database row init(row: Row) throws { mongoId = try row.get("id") id = try row.get("_id") message = try row.get("message") } // Serializes the Fortune to the database func makeRow() throws -> Row { var row = Row() try row.set("id", mongoId!) try row.set("_id", id!) try row.set("message", message) return row } func makeNode(context: Context) throws -> Node { return try Node(node: [ "id": mongoId!, "_id": id!, "message": message ]) } func makeJSONNode() throws -> Node { return try Node(node: [ "id": id!.int!, "message": message ]) } func makeJSON() throws -> JSON { let node = try makeJSONNode() return JSON(node: node) } } // MARK: Fluent Preparation extension Fortune: Preparation { /// Prepares a table/collection in the database /// for storing Fortunes static func prepare(_ database: Database) throws { } /// Undoes what was done in `prepare` static func revert(_ database: Database) throws { } }
bsd-3-clause
826c9ccb5a0461d7b8b492dbc3de3340
20.768293
54
0.54902
4.056818
false
false
false
false
dreamsxin/swift
stdlib/public/SDK/XCTest/XCTest.swift
3
41099
//===----------------------------------------------------------------------===// // // 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 // //===----------------------------------------------------------------------===// @_exported import XCTest // Clang module import CoreGraphics /// Returns the current test case, so we can use free functions instead of methods for the overlay. @_silgen_name("_XCTCurrentTestCaseBridge") func _XCTCurrentTestCaseBridge() -> XCTestCase // --- Failure Formatting --- /// Register the failure, expected or unexpected, of the current test case. func _XCTRegisterFailure(_ expected: Bool, _ condition: String, _ message: @autoclosure () -> String, _ file: StaticString, _ line: UInt) -> Void { // Call the real _XCTFailureHandler. let test = _XCTCurrentTestCaseBridge() _XCTPreformattedFailureHandler(test, expected, file.description, line, condition, message()) } /// Produce a failure description for the given assertion type. func _XCTFailureDescription(_ assertionType: _XCTAssertionType, _ formatIndex: UInt, _ expressionStrings: CVarArg...) -> String { // In order to avoid revlock/submission issues between XCTest and the Swift XCTest overlay, // we are using the convention with _XCTFailureFormat that (formatIndex >= 100) should be // treated just like (formatIndex - 100), but WITHOUT the expression strings. (Swift can't // stringify the expressions, only their values.) This way we don't have to introduce a new // BOOL parameter to this semi-internal function and coordinate that across builds. // // Since there's a single bottleneck in the overlay where we invoke _XCTFailureFormat, just // add the formatIndex adjustment there rather than in all of the individual calls to this // function. return String(format: _XCTFailureFormat(assertionType, formatIndex + 100), arguments: expressionStrings) } // --- Exception Support --- @_silgen_name("_XCTRunThrowableBlockBridge") func _XCTRunThrowableBlockBridge(_: @noescape @convention(block) () -> Void) -> NSDictionary /// The Swift-style result of evaluating a block which may throw an exception. enum _XCTThrowableBlockResult { case success case failedWithError(error: ErrorProtocol) case failedWithException(className: String, name: String, reason: String) case failedWithUnknownException } /// Asks some Objective-C code to evaluate a block which may throw an exception or error, /// and if it does consume the exception and return information about it. func _XCTRunThrowableBlock(_ block: @noescape () throws -> Void) -> _XCTThrowableBlockResult { var blockErrorOptional: ErrorProtocol? let d = _XCTRunThrowableBlockBridge({ do { try block() } catch { blockErrorOptional = error } }) if let blockError = blockErrorOptional { return .failedWithError(error: blockError) } else if d.count > 0 { let t: String = d["type"] as! String if t == "objc" { return .failedWithException( className: d["className"] as! String, name: d["name"] as! String, reason: d["reason"] as! String) } else { return .failedWithUnknownException } } else { return .success } } // --- Supported Assertions --- public func XCTFail(_ message: String = "", file: StaticString = #file, line: UInt = #line) -> Void { let assertionType = _XCTAssertionType.fail _XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 0, "" as NSString), message, file, line) } public func XCTAssertNil(_ expression: @autoclosure () throws -> Any?, _ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line) -> Void { let assertionType = _XCTAssertionType.`nil` // evaluate the expression exactly once var expressionValueOptional: Any? let result = _XCTRunThrowableBlock { expressionValueOptional = try expression() } switch result { case .success: // test both Optional and value to treat .none and nil as synonymous var passed: Bool var expressionValueStr: String = "nil" if let expressionValueUnwrapped = expressionValueOptional { passed = false expressionValueStr = "\(expressionValueUnwrapped)" } else { passed = true } if !passed { // TODO: @auto_string expression _XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 0, expressionValueStr as NSString), message, file, line) } case .failedWithError(let error): _XCTRegisterFailure(false, "XCTAssertNil failed: threw error \"\(error)\"", message, file, line) case .failedWithException(_, _, let reason): _XCTRegisterFailure(false, _XCTFailureDescription(assertionType, 1, reason as NSString), message, file, line) case .failedWithUnknownException: _XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 2), message, file, line) } } public func XCTAssertNotNil(_ expression: @autoclosure () throws -> Any?, _ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line) -> Void { let assertionType = _XCTAssertionType.notNil // evaluate the expression exactly once var expressionValueOptional: Any? let result = _XCTRunThrowableBlock { expressionValueOptional = try expression() } switch result { case .success: // test both Optional and value to treat .none and nil as synonymous var passed: Bool var expressionValueStr: String = "nil" if let expressionValueUnwrapped = expressionValueOptional { passed = true expressionValueStr = "\(expressionValueUnwrapped)" } else { passed = false } if !passed { // TODO: @auto_string expression _XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 0, expressionValueStr as NSString), message, file, line) } case .failedWithError(let error): _XCTRegisterFailure(false, "XCTAssertNotNil failed: threw error \"\(error)\"", message, file, line) case .failedWithException(_, _, let reason): _XCTRegisterFailure(false, _XCTFailureDescription(assertionType, 1, reason as NSString), message, file, line) case .failedWithUnknownException: _XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 2), message, file, line) } } public func XCTAssert(_ expression: @autoclosure () throws -> Boolean, _ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line) -> Void { // XCTAssert is just a cover for XCTAssertTrue. XCTAssertTrue(expression, message, file: file, line: line) } public func XCTAssertTrue(_ expression: @autoclosure () throws -> Boolean, _ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line) -> Void { let assertionType = _XCTAssertionType.`true` // evaluate the expression exactly once var expressionValueOptional: Bool? let result = _XCTRunThrowableBlock { expressionValueOptional = try expression().boolValue } switch result { case .success: let expressionValue = expressionValueOptional! if !expressionValue { // TODO: @auto_string expression _XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 0), message, file, line) } case .failedWithError(let error): _XCTRegisterFailure(false, "XCTAssertTrue failed: threw error \"\(error)\"", message, file, line) case .failedWithException(_, _, let reason): _XCTRegisterFailure(false, _XCTFailureDescription(assertionType, 1, reason as NSString), message, file, line) case .failedWithUnknownException: _XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 2), message, file, line) } } public func XCTAssertFalse(_ expression: @autoclosure () throws -> Boolean, _ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line) -> Void { let assertionType = _XCTAssertionType.`false` // evaluate the expression exactly once var expressionValueOptional: Bool? let result = _XCTRunThrowableBlock { expressionValueOptional = try expression().boolValue } switch result { case .success: let expressionValue = expressionValueOptional! if expressionValue { // TODO: @auto_string expression _XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 0), message, file, line) } case .failedWithError(let error): _XCTRegisterFailure(false, "XCTAssertFalse failed: threw error \"\(error)\"", message, file, line) case .failedWithException(_, _, let reason): _XCTRegisterFailure(false, _XCTFailureDescription(assertionType, 1, reason as NSString), message, file, line) case .failedWithUnknownException: _XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 2), message, file, line) } } public func XCTAssertEqual<T : Equatable>(_ expression1: @autoclosure () throws -> T?, _ expression2: @autoclosure () throws -> T?, _ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line) -> Void { let assertionType = _XCTAssertionType.equal // evaluate each expression exactly once var expressionValue1Optional: T? var expressionValue2Optional: T? let result = _XCTRunThrowableBlock { expressionValue1Optional = try expression1() expressionValue2Optional = try expression2() } switch result { case .success: if expressionValue1Optional != expressionValue2Optional { // TODO: @auto_string expression1 // TODO: @auto_string expression2 let expressionValueStr1 = "\(expressionValue1Optional)" let expressionValueStr2 = "\(expressionValue2Optional)" _XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 0, expressionValueStr1 as NSString, expressionValueStr2 as NSString), message, file, line) } case .failedWithError(let error): _XCTRegisterFailure(false, "XCTAssertEqual failed: threw error \"\(error)\"", message, file, line) case .failedWithException(_, _, let reason): _XCTRegisterFailure(false, _XCTFailureDescription(assertionType, 1, reason as NSString), message, file, line) case .failedWithUnknownException: _XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 2), message, file, line) } } // FIXME: Due to <rdar://problem/16768059> we need overrides of XCTAssertEqual for: // ContiguousArray<T> // ArraySlice<T> // Array<T> // Dictionary<T, U> public func XCTAssertEqual<T : Equatable>(_ expression1: @autoclosure () throws -> ArraySlice<T>, _ expression2: @autoclosure () throws -> ArraySlice<T>, _ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line) -> Void { let assertionType = _XCTAssertionType.equal // evaluate each expression exactly once var expressionValue1Optional: ArraySlice<T>? var expressionValue2Optional: ArraySlice<T>? let result = _XCTRunThrowableBlock { expressionValue1Optional = try expression1() expressionValue2Optional = try expression2() } switch result { case .success: let expressionValue1: ArraySlice<T> = expressionValue1Optional! let expressionValue2: ArraySlice<T> = expressionValue2Optional! if expressionValue1 != expressionValue2 { // TODO: @auto_string expression1 // TODO: @auto_string expression2 let expressionValueStr1 = "\(expressionValue1)" let expressionValueStr2 = "\(expressionValue2)" _XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 0, expressionValueStr1 as NSString, expressionValueStr2 as NSString), message, file, line) } case .failedWithError(let error): _XCTRegisterFailure(false, "XCTAssertEqual failed: threw error \"\(error)\"", message, file, line) case .failedWithException(_, _, let reason): _XCTRegisterFailure(false, _XCTFailureDescription(assertionType, 1, reason as NSString), message, file, line) case .failedWithUnknownException: _XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 2), message, file, line) } } public func XCTAssertEqual<T : Equatable>(_ expression1: @autoclosure () throws -> ContiguousArray<T>, _ expression2: @autoclosure () throws -> ContiguousArray<T>, _ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line) -> Void { let assertionType = _XCTAssertionType.equal // evaluate each expression exactly once var expressionValue1Optional: ContiguousArray<T>? var expressionValue2Optional: ContiguousArray<T>? let result = _XCTRunThrowableBlock { expressionValue1Optional = try expression1() expressionValue2Optional = try expression2() } switch result { case .success: let expressionValue1: ContiguousArray<T> = expressionValue1Optional! let expressionValue2: ContiguousArray<T> = expressionValue2Optional! if expressionValue1 != expressionValue2 { // TODO: @auto_string expression1 // TODO: @auto_string expression2 let expressionValueStr1 = "\(expressionValue1)" let expressionValueStr2 = "\(expressionValue2)" _XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 0, expressionValueStr1 as NSString, expressionValueStr2 as NSString), message, file, line) } case .failedWithError(let error): _XCTRegisterFailure(false, "XCTAssertEqual failed: threw error \"\(error)\"", message, file, line) case .failedWithException(_, _, let reason): _XCTRegisterFailure(false, _XCTFailureDescription(assertionType, 1, reason as NSString), message, file, line) case .failedWithUnknownException: _XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 2), message, file, line) } } public func XCTAssertEqual<T : Equatable>(_ expression1: @autoclosure () throws -> [T], _ expression2: @autoclosure () throws -> [T], _ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line) -> Void { let assertionType = _XCTAssertionType.equal // evaluate each expression exactly once var expressionValue1Optional: [T]? var expressionValue2Optional: [T]? let result = _XCTRunThrowableBlock { expressionValue1Optional = try expression1() expressionValue2Optional = try expression2() } switch result { case .success: let expressionValue1: [T] = expressionValue1Optional! let expressionValue2: [T] = expressionValue2Optional! if expressionValue1 != expressionValue2 { // TODO: @auto_string expression1 // TODO: @auto_string expression2 let expressionValueStr1 = "\(expressionValue1)" let expressionValueStr2 = "\(expressionValue2)" _XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 0, expressionValueStr1 as NSString, expressionValueStr2 as NSString), message, file, line) } case .failedWithError(let error): _XCTRegisterFailure(false, "XCTAssertEqual failed: threw error \"\(error)\"", message, file, line) case .failedWithException(_, _, let reason): _XCTRegisterFailure(false, _XCTFailureDescription(assertionType, 1, reason as NSString), message, file, line) case .failedWithUnknownException: _XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 2), message, file, line) } } public func XCTAssertEqual<T, U : Equatable>(_ expression1: @autoclosure () throws -> [T: U], _ expression2: @autoclosure () throws -> [T: U], _ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line) -> Void { let assertionType = _XCTAssertionType.equal // evaluate each expression exactly once var expressionValue1Optional: [T: U]? var expressionValue2Optional: [T: U]? let result = _XCTRunThrowableBlock { expressionValue1Optional = try expression1() expressionValue2Optional = try expression2() } switch result { case .success: let expressionValue1: [T: U] = expressionValue1Optional! let expressionValue2: [T: U] = expressionValue2Optional! if expressionValue1 != expressionValue2 { // TODO: @auto_string expression1 // TODO: @auto_string expression2 let expressionValueStr1 = "\(expressionValue1)" let expressionValueStr2 = "\(expressionValue2)" _XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 0, expressionValueStr1 as NSString, expressionValueStr2 as NSString), message, file, line) } case .failedWithError(let error): _XCTRegisterFailure(false, "XCTAssertEqual failed: threw error \"\(error)\"", message, file, line) case .failedWithException(_, _, let reason): _XCTRegisterFailure(false, _XCTFailureDescription(assertionType, 1, reason as NSString), message, file, line) case .failedWithUnknownException: _XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 2), message, file, line) } } public func XCTAssertNotEqual<T : Equatable>(_ expression1: @autoclosure () throws -> T?, _ expression2: @autoclosure () throws -> T?, _ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line) -> Void { let assertionType = _XCTAssertionType.notEqual // evaluate each expression exactly once var expressionValue1Optional: T? var expressionValue2Optional: T? let result = _XCTRunThrowableBlock { expressionValue1Optional = try expression1() expressionValue2Optional = try expression2() } switch result { case .success: if expressionValue1Optional == expressionValue2Optional { // TODO: @auto_string expression1 // TODO: @auto_string expression2 let expressionValueStr1 = "\(expressionValue1Optional)" let expressionValueStr2 = "\(expressionValue2Optional)" _XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 0, expressionValueStr1 as NSString, expressionValueStr2 as NSString), message, file, line) } case .failedWithError(let error): _XCTRegisterFailure(false, "XCTAssertNotEqual failed: threw error \"\(error)\"", message, file, line) case .failedWithException(_, _, let reason): _XCTRegisterFailure(false, _XCTFailureDescription(assertionType, 1, reason as NSString), message, file, line) case .failedWithUnknownException: _XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 2), message, file, line) } } // FIXME: Due to <rdar://problem/16768059> we need overrides of XCTAssertNotEqual for: // ContiguousArray<T> // ArraySlice<T> // Array<T> // Dictionary<T, U> public func XCTAssertNotEqual<T : Equatable>(_ expression1: @autoclosure () throws -> ContiguousArray<T>, _ expression2: @autoclosure () throws -> ContiguousArray<T>, _ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line) -> Void { let assertionType = _XCTAssertionType.notEqual // evaluate each expression exactly once var expressionValue1Optional: ContiguousArray<T>? var expressionValue2Optional: ContiguousArray<T>? let result = _XCTRunThrowableBlock { expressionValue1Optional = try expression1() expressionValue2Optional = try expression2() } switch result { case .success: let expressionValue1: ContiguousArray<T> = expressionValue1Optional! let expressionValue2: ContiguousArray<T> = expressionValue2Optional! if expressionValue1 == expressionValue2 { // TODO: @auto_string expression1 // TODO: @auto_string expression2 let expressionValueStr1 = "\(expressionValue1)" let expressionValueStr2 = "\(expressionValue2)" _XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 0, expressionValueStr1 as NSString, expressionValueStr2 as NSString), message, file, line) } case .failedWithError(let error): _XCTRegisterFailure(false, "XCTAssertNotEqual failed: threw error \"\(error)\"", message, file, line) case .failedWithException(_, _, let reason): _XCTRegisterFailure(false, _XCTFailureDescription(assertionType, 1, reason as NSString), message, file, line) case .failedWithUnknownException: _XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 2), message, file, line) } } public func XCTAssertNotEqual<T : Equatable>(_ expression1: @autoclosure () throws -> ArraySlice<T>, _ expression2: @autoclosure () throws -> ArraySlice<T>, _ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line) -> Void { let assertionType = _XCTAssertionType.notEqual // evaluate each expression exactly once var expressionValue1Optional: ArraySlice<T>? var expressionValue2Optional: ArraySlice<T>? let result = _XCTRunThrowableBlock { expressionValue1Optional = try expression1() expressionValue2Optional = try expression2() } switch result { case .success: let expressionValue1: ArraySlice<T> = expressionValue1Optional! let expressionValue2: ArraySlice<T> = expressionValue2Optional! if expressionValue1 == expressionValue2 { // TODO: @auto_string expression1 // TODO: @auto_string expression2 let expressionValueStr1 = "\(expressionValue1)" let expressionValueStr2 = "\(expressionValue2)" _XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 0, expressionValueStr1 as NSString, expressionValueStr2 as NSString), message, file, line) } case .failedWithError(let error): _XCTRegisterFailure(false, "XCTAssertNotEqual failed: threw error \"\(error)\"", message, file, line) case .failedWithException(_, _, let reason): _XCTRegisterFailure(false, _XCTFailureDescription(assertionType, 1, reason as NSString), message, file, line) case .failedWithUnknownException: _XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 2), message, file, line) } } public func XCTAssertNotEqual<T : Equatable>(_ expression1: @autoclosure () throws -> [T], _ expression2: @autoclosure () throws -> [T], _ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line) -> Void { let assertionType = _XCTAssertionType.notEqual // evaluate each expression exactly once var expressionValue1Optional: [T]? var expressionValue2Optional: [T]? let result = _XCTRunThrowableBlock { expressionValue1Optional = try expression1() expressionValue2Optional = try expression2() } switch result { case .success: let expressionValue1: [T] = expressionValue1Optional! let expressionValue2: [T] = expressionValue2Optional! if expressionValue1 == expressionValue2 { // TODO: @auto_string expression1 // TODO: @auto_string expression2 let expressionValueStr1 = "\(expressionValue1)" let expressionValueStr2 = "\(expressionValue2)" _XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 0, expressionValueStr1 as NSString, expressionValueStr2 as NSString), message, file, line) } case .failedWithError(let error): _XCTRegisterFailure(false, "XCTAssertNotEqual failed: threw error \"\(error)\"", message, file, line) case .failedWithException(_, _, let reason): _XCTRegisterFailure(false, _XCTFailureDescription(assertionType, 1, reason as NSString), message, file, line) case .failedWithUnknownException: _XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 2), message, file, line) } } public func XCTAssertNotEqual<T, U : Equatable>(_ expression1: @autoclosure () throws -> [T: U], _ expression2: @autoclosure () throws -> [T: U], _ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line) -> Void { let assertionType = _XCTAssertionType.notEqual // evaluate each expression exactly once var expressionValue1Optional: [T: U]? var expressionValue2Optional: [T: U]? let result = _XCTRunThrowableBlock { expressionValue1Optional = try expression1() expressionValue2Optional = try expression2() } switch result { case .success: let expressionValue1: [T: U] = expressionValue1Optional! let expressionValue2: [T: U] = expressionValue2Optional! if expressionValue1 == expressionValue2 { // TODO: @auto_string expression1 // TODO: @auto_string expression2 let expressionValueStr1 = "\(expressionValue1)" let expressionValueStr2 = "\(expressionValue2)" _XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 0, expressionValueStr1 as NSString, expressionValueStr2 as NSString), message, file, line) } case .failedWithError(let error): _XCTRegisterFailure(false, "XCTAssertNotEqual failed: threw error \"\(error)\"", message, file, line) case .failedWithException(_, _, let reason): _XCTRegisterFailure(false, _XCTFailureDescription(assertionType, 1, reason as NSString), message, file, line) case .failedWithUnknownException: _XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 2), message, file, line) } } func _XCTCheckEqualWithAccuracy_Double(_ value1: Double, _ value2: Double, _ accuracy: Double) -> Bool { return (!value1.isNaN && !value2.isNaN) && (abs(value1 - value2) <= accuracy) } func _XCTCheckEqualWithAccuracy_Float(_ value1: Float, _ value2: Float, _ accuracy: Float) -> Bool { return (!value1.isNaN && !value2.isNaN) && (abs(value1 - value2) <= accuracy) } func _XCTCheckEqualWithAccuracy_CGFloat(_ value1: CGFloat, _ value2: CGFloat, _ accuracy: CGFloat) -> Bool { return (!value1.isNaN && !value2.isNaN) && (abs(value1 - value2) <= accuracy) } public func XCTAssertEqualWithAccuracy<T : FloatingPoint>(_ expression1: @autoclosure () throws -> T, _ expression2: @autoclosure () throws -> T, accuracy: T, _ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line) -> Void { let assertionType = _XCTAssertionType.equalWithAccuracy // evaluate each expression exactly once var expressionValue1Optional: T? var expressionValue2Optional: T? let result = _XCTRunThrowableBlock { expressionValue1Optional = try expression1() expressionValue2Optional = try expression2() } switch result { case .success: let expressionValue1 = expressionValue1Optional! let expressionValue2 = expressionValue2Optional! var equalWithAccuracy: Bool = false switch (expressionValue1, expressionValue2, accuracy) { case let (expressionValue1Double as Double, expressionValue2Double as Double, accuracyDouble as Double): equalWithAccuracy = _XCTCheckEqualWithAccuracy_Double(expressionValue1Double, expressionValue2Double, accuracyDouble) case let (expressionValue1Float as Float, expressionValue2Float as Float, accuracyFloat as Float): equalWithAccuracy = _XCTCheckEqualWithAccuracy_Float(expressionValue1Float, expressionValue2Float, accuracyFloat) case let (expressionValue1CGFloat as CGFloat, expressionValue2CGFloat as CGFloat, accuracyCGFloat as CGFloat): equalWithAccuracy = _XCTCheckEqualWithAccuracy_CGFloat(expressionValue1CGFloat, expressionValue2CGFloat, accuracyCGFloat) default: // unknown type, fail with prejudice _preconditionFailure("unsupported floating-point type passed to XCTAssertEqualWithAccuracy") } if !equalWithAccuracy { // TODO: @auto_string expression1 // TODO: @auto_string expression2 let expressionValueStr1 = "\(expressionValue1)" let expressionValueStr2 = "\(expressionValue2)" let accuracyStr = "\(accuracy)" _XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 0, expressionValueStr1 as NSString, expressionValueStr2 as NSString, accuracyStr as NSString), message, file, line) } case .failedWithError(let error): _XCTRegisterFailure(false, "XCTAssertEqualWithAccuracy failed: threw error \"\(error)\"", message, file, line) case .failedWithException(_, _, let reason): _XCTRegisterFailure(false, _XCTFailureDescription(assertionType, 1, reason as NSString), message, file, line) case .failedWithUnknownException: _XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 2), message, file, line) } } func _XCTCheckNotEqualWithAccuracy_Double(_ value1: Double, _ value2: Double, _ accuracy: Double) -> Bool { return (value1.isNaN || value2.isNaN) || (abs(value1 - value2) > accuracy) } func _XCTCheckNotEqualWithAccuracy_Float(_ value1: Float, _ value2: Float, _ accuracy: Float) -> Bool { return (value1.isNaN || value2.isNaN) || (abs(value1 - value2) > accuracy) } func _XCTCheckNotEqualWithAccuracy_CGFloat(_ value1: CGFloat, _ value2: CGFloat, _ accuracy: CGFloat) -> Bool { return (value1.isNaN || value2.isNaN) || (abs(value1 - value2) > accuracy) } public func XCTAssertNotEqualWithAccuracy<T : FloatingPoint>(_ expression1: @autoclosure () throws -> T, _ expression2: @autoclosure () throws -> T, _ accuracy: T, _ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line) -> Void { let assertionType = _XCTAssertionType.notEqualWithAccuracy // evaluate each expression exactly once var expressionValue1Optional: T? var expressionValue2Optional: T? let result = _XCTRunThrowableBlock { expressionValue1Optional = try expression1() expressionValue2Optional = try expression2() } switch result { case .success: let expressionValue1 = expressionValue1Optional! let expressionValue2 = expressionValue2Optional! var notEqualWithAccuracy: Bool = false switch (expressionValue1, expressionValue2, accuracy) { case let (expressionValue1Double as Double, expressionValue2Double as Double, accuracyDouble as Double): notEqualWithAccuracy = _XCTCheckNotEqualWithAccuracy_Double(expressionValue1Double, expressionValue2Double, accuracyDouble) case let (expressionValue1Float as Float, expressionValue2Float as Float, accuracyFloat as Float): notEqualWithAccuracy = _XCTCheckNotEqualWithAccuracy_Float(expressionValue1Float, expressionValue2Float, accuracyFloat) case let (expressionValue1CGFloat as CGFloat, expressionValue2CGFloat as CGFloat, accuracyCGFloat as CGFloat): notEqualWithAccuracy = _XCTCheckNotEqualWithAccuracy_CGFloat(expressionValue1CGFloat, expressionValue2CGFloat, accuracyCGFloat) default: // unknown type, fail with prejudice _preconditionFailure("unsupported floating-point type passed to XCTAssertNotEqualWithAccuracy") } if !notEqualWithAccuracy { // TODO: @auto_string expression1 // TODO: @auto_string expression2 let expressionValueStr1 = "\(expressionValue1)" let expressionValueStr2 = "\(expressionValue2)" let accuracyStr = "\(accuracy)" _XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 0, expressionValueStr1 as NSString, expressionValueStr2 as NSString, accuracyStr as NSString), message, file, line) } case .failedWithError(let error): _XCTRegisterFailure(false, "XCTAssertNotEqualWithAccuracy failed: threw error \"\(error)\"", message, file, line) case .failedWithException(_, _, let reason): _XCTRegisterFailure(false, _XCTFailureDescription(assertionType, 1, reason as NSString), message, file, line) case .failedWithUnknownException: _XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 2), message, file, line) } } public func XCTAssertGreaterThan<T : Comparable>(_ expression1: @autoclosure () throws -> T, _ expression2: @autoclosure () throws -> T, _ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line) -> Void { let assertionType = _XCTAssertionType.greaterThan // evaluate each expression exactly once var expressionValue1Optional: T? var expressionValue2Optional: T? let result = _XCTRunThrowableBlock { expressionValue1Optional = try expression1() expressionValue2Optional = try expression2() } switch result { case .success: let expressionValue1 = expressionValue1Optional! let expressionValue2 = expressionValue2Optional! if !(expressionValue1 > expressionValue2) { // TODO: @auto_string expression1 // TODO: @auto_string expression2 let expressionValueStr1 = "\(expressionValue1)" let expressionValueStr2 = "\(expressionValue2)" _XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 0, expressionValueStr1 as NSString, expressionValueStr2 as NSString), message, file, line) } case .failedWithError(let error): _XCTRegisterFailure(false, "XCTAssertGreaterThan failed: threw error \"\(error)\"", message, file, line) case .failedWithException(_, _, let reason): _XCTRegisterFailure(false, _XCTFailureDescription(assertionType, 1, reason as NSString), message, file, line) case .failedWithUnknownException: _XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 2), message, file, line) } } public func XCTAssertGreaterThanOrEqual<T : Comparable>(_ expression1: @autoclosure () throws -> T, _ expression2: @autoclosure () throws -> T, _ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line) { let assertionType = _XCTAssertionType.greaterThanOrEqual // evaluate each expression exactly once var expressionValue1Optional: T? var expressionValue2Optional: T? let result = _XCTRunThrowableBlock { expressionValue1Optional = try expression1() expressionValue2Optional = try expression2() } switch result { case .success: let expressionValue1 = expressionValue1Optional! let expressionValue2 = expressionValue2Optional! if !(expressionValue1 >= expressionValue2) { // TODO: @auto_string expression1 // TODO: @auto_string expression2 let expressionValueStr1 = "\(expressionValue1)" let expressionValueStr2 = "\(expressionValue2)" _XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 0, expressionValueStr1 as NSString, expressionValueStr2 as NSString), message, file, line) } case .failedWithError(let error): _XCTRegisterFailure(false, "XCTAssertGreaterThanOrEqual failed: threw error \"\(error)\"", message, file, line) case .failedWithException(_, _, let reason): _XCTRegisterFailure(false, _XCTFailureDescription(assertionType, 1, reason as NSString), message, file, line) case .failedWithUnknownException: _XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 2), message, file, line) } } public func XCTAssertLessThan<T : Comparable>(_ expression1: @autoclosure () throws -> T, _ expression2: @autoclosure () throws -> T, _ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line) -> Void { let assertionType = _XCTAssertionType.lessThan // evaluate each expression exactly once var expressionValue1Optional: T? var expressionValue2Optional: T? let result = _XCTRunThrowableBlock { expressionValue1Optional = try expression1() expressionValue2Optional = try expression2() } switch result { case .success: let expressionValue1 = expressionValue1Optional! let expressionValue2 = expressionValue2Optional! if !(expressionValue1 < expressionValue2) { // TODO: @auto_string expression1 // TODO: @auto_string expression2 let expressionValueStr1 = "\(expressionValue1)" let expressionValueStr2 = "\(expressionValue2)" _XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 0, expressionValueStr1 as NSString, expressionValueStr2 as NSString), message, file, line) } case .failedWithError(let error): _XCTRegisterFailure(false, "XCTAssertLessThan failed: threw error \"\(error)\"", message, file, line) case .failedWithException(_, _, let reason): _XCTRegisterFailure(false, _XCTFailureDescription(assertionType, 1, reason as NSString), message, file, line) case .failedWithUnknownException: _XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 2), message, file, line) } } public func XCTAssertLessThanOrEqual<T : Comparable>(_ expression1: @autoclosure () throws -> T, _ expression2: @autoclosure () throws -> T, _ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line) { let assertionType = _XCTAssertionType.lessThanOrEqual // evaluate each expression exactly once var expressionValue1Optional: T? var expressionValue2Optional: T? let result = _XCTRunThrowableBlock { expressionValue1Optional = try expression1() expressionValue2Optional = try expression2() } switch result { case .success: let expressionValue1 = expressionValue1Optional! let expressionValue2 = expressionValue2Optional! if !(expressionValue1 <= expressionValue2) { // TODO: @auto_string expression1 // TODO: @auto_string expression2 let expressionValueStr1 = "\(expressionValue1)" let expressionValueStr2 = "\(expressionValue2)" _XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 0, expressionValueStr1 as NSString, expressionValueStr2 as NSString), message, file, line) } case .failedWithError(let error): _XCTRegisterFailure(false, "XCTAssertLessThanOrEqual failed: threw error \"\(error)\"", message, file, line) case .failedWithException(_, _, let reason): _XCTRegisterFailure(false, _XCTFailureDescription(assertionType, 1, reason as NSString), message, file, line) case .failedWithUnknownException: _XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 2), message, file, line) } } public func XCTAssertThrowsError<T>(_ expression: @autoclosure () throws -> T, _ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line, _ errorHandler: (error: ErrorProtocol) -> Void = { _ in }) -> Void { // evaluate expression exactly once var caughtErrorOptional: ErrorProtocol? let result = _XCTRunThrowableBlock { do { _ = try expression() } catch { caughtErrorOptional = error } } switch result { case .success: if let caughtError = caughtErrorOptional { errorHandler(error: caughtError) } else { _XCTRegisterFailure(true, "XCTAssertThrowsError failed: did not throw an error", message, file, line) } case .failedWithError(let error): _XCTRegisterFailure(false, "XCTAssertLessThanOrEqual failed: threw error \"\(error)\"", message, file, line) case .failedWithException(_, _, let reason): _XCTRegisterFailure(true, "XCTAssertThrowsError failed: throwing \(reason)", message, file, line) case .failedWithUnknownException: _XCTRegisterFailure(true, "XCTAssertThrowsError failed: throwing an unknown exception", message, file, line) } } #if XCTEST_ENABLE_EXCEPTION_ASSERTIONS // --- Currently-Unsupported Assertions --- public func XCTAssertThrows(_ expression: @autoclosure () -> Any?, _ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line) -> Void { let assertionType = _XCTAssertionType.assertion_Throws // FIXME: Unsupported } public func XCTAssertThrowsSpecific(_ expression: @autoclosure () -> Any?, _ exception: Any, _ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line) -> Void { let assertionType = _XCTAssertionType.assertion_ThrowsSpecific // FIXME: Unsupported } public func XCTAssertThrowsSpecificNamed(_ expression: @autoclosure () -> Any?, _ exception: Any, _ name: String, _ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line) -> Void { let assertionType = _XCTAssertionType.assertion_ThrowsSpecificNamed // FIXME: Unsupported } public func XCTAssertNoThrow(_ expression: @autoclosure () -> Any?, _ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line) -> Void { let assertionType = _XCTAssertionType.assertion_NoThrow // FIXME: Unsupported } public func XCTAssertNoThrowSpecific(_ expression: @autoclosure () -> Any?, _ exception: Any, _ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line) -> Void { let assertionType = _XCTAssertionType.assertion_NoThrowSpecific // FIXME: Unsupported } public func XCTAssertNoThrowSpecificNamed(_ expression: @autoclosure () -> Any?, _ exception: Any, _ name: String, _ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line) -> Void { let assertionType = _XCTAssertionType.assertion_NoThrowSpecificNamed // FIXME: Unsupported } #endif
apache-2.0
a2aa4ab0edd11a1153c842bc0ec39134
40.430444
267
0.709579
4.338083
false
false
false
false
instacrate/Subber-api
Sources/App/TypeSafeOptionsParameter.swift
2
3088
// // TypeSafeOptionsParameter.swift // subber-api // // Created by Hakon Hanesand on 11/18/16. // // import Foundation import Vapor import HTTP import TypeSafeRouting import Node import Fluent import Vapor import HTTP extension QueryRepresentable { func apply(_ option: QueryModifiable) throws -> Query<T> { return try option.modify(self.makeQuery()) } func apply(_ option: QueryModifiable?) throws -> Query<T> { if let option = option { return try option.modify(self.makeQuery()) } return try self.makeQuery() } } protocol QueryModifiable { func modify<T: Entity>(_ query: Query<T>) throws -> Query<T> } protocol TypesafeOptionsParameter: StringInitializable, NodeConvertible, QueryModifiable { static var key: String { get } static var values: [String] { get } static var defaultValue: Self? { get } } extension TypesafeOptionsParameter { static var humanReadableValuesString: String { return "Valid values are : [\(Self.values.joined(separator: ", "))]" } func modify<T : Entity>(_ query: Query<T>) throws -> Query<T> { return query } } extension RawRepresentable where Self: TypesafeOptionsParameter, RawValue == String { init?(from string: String) throws { self.init(rawValue: string) } init?(from _string: String?) throws { guard let string = _string else { return nil } self.init(rawValue: string) } init(node: Node, in context: Context = EmptyNode) throws { if node.isNull { guard let defaultValue = Self.defaultValue else { throw Abort.custom(status: .badRequest, message: "Missing query parameter value \(Self.key). Acceptable values are : [\(Self.values.joined(separator: ", "))]") } self = defaultValue return } guard let string = node.string else { throw NodeError.unableToConvert(node: node, expected: "\(String.self)") } guard let value = Self.init(rawValue: string) else { throw Abort.custom(status: .badRequest, message: "Invalid value for enumerated type. \(Self.humanReadableValuesString)") } self = value } func makeNode(context: Context = EmptyNode) throws -> Node { return Node.string(self.rawValue) } } extension Request { func extract<T: TypesafeOptionsParameter>() throws -> T where T: RawRepresentable, T.RawValue == String { return try T.init(node: self.query?[T.key]) } func extract<T: TypesafeOptionsParameter>() throws -> [T] where T: RawRepresentable, T.RawValue == String { guard let optionsArray = self.query?[T.key]?.nodeArray else { throw Abort.custom(status: .badRequest, message: "Missing query option at key \(T.key). Acceptable values are \(T.values)") } return try optionsArray.map { try T.init(node: $0) } } }
mit
ad1f870f0357263ed84d0c26dbbee7ab
26.571429
175
0.612047
4.367751
false
false
false
false
mownier/Umalahokan
Umalahokan/Source/Util/KeyboardHandler.swift
1
3079
// // KeyboardHandler.swift // Umalahokan // // Created by Mounir Ybanez on 08/02/2017. // Copyright ยฉ 2017 Ner. All rights reserved. // import UIKit enum KeyboardDirection { case none case up case down } struct KeyboardFrameDelta { var height: CGFloat = 0 var y: CGFloat = 0 var direction: KeyboardDirection = .none } struct KeyboardHandler { var willMoveUp: ((KeyboardFrameDelta) -> Void)? var willMoveDown: ((KeyboardFrameDelta) -> Void)? var info: [AnyHashable: Any]? var willMoveUsedView: Bool = true func handle(using view: UIView, with animation: ((KeyboardFrameDelta) -> Void)? = nil) { guard let userInfo = info, let curve = userInfo[UIKeyboardAnimationCurveUserInfoKey] as? UInt, let duration = userInfo[UIKeyboardAnimationDurationUserInfoKey] as? Double, let frameEnd = userInfo[UIKeyboardFrameEndUserInfoKey] as? NSValue, let frameBegin = userInfo[UIKeyboardFrameBeginUserInfoKey] as? NSValue, let window = view.window, let superview = view.superview else { return } let rectEnd = frameEnd.cgRectValue let rectBegin = frameBegin.cgRectValue let options = UIViewAnimationOptions(rawValue: curve << 16) let rectWindow = view.convert(CGRect.zero, to: nil) var insetBottom = window.bounds.size.height - rectWindow.origin.y var delta = KeyboardFrameDelta() delta.direction = direction(end: frameEnd, begin: frameBegin) delta.height = rectEnd.size.height - rectBegin.size.height delta.y = rectEnd.origin.y - rectBegin.origin.y switch delta.direction { case .up: insetBottom -= view.bounds.size.height delta.y += insetBottom willMoveUp?(delta) case .down: insetBottom += view.frame.origin.y insetBottom -= superview.bounds.size.height delta.y -= insetBottom willMoveDown?(delta) default: break } UIView.animate( withDuration: duration, delay: 0, options: options, animations: { if self.willMoveUsedView { if delta.height == 0 { view.frame.origin.y += delta.y } else { view.frame.origin.y -= delta.height } } animation?(delta) }, completion: nil ) } private func direction(end frameEnd: NSValue, begin frameBegin: NSValue) -> KeyboardDirection { let rectEnd = frameEnd.cgRectValue let rectBegin = frameBegin.cgRectValue if rectEnd.origin.y < rectBegin.origin.y { return .up } else if rectEnd.origin.y > rectBegin.origin.y { return .down } else { return .none } } }
mit
183d5fd2cb031c4a5a0fdcbc7e13cfb8
29.475248
99
0.563678
4.862559
false
false
false
false
SwiftKit/Cuckoo
Generator/Source/CuckooGeneratorFramework/Tokens/Kinds.swift
1
761
// // Kinds.swift // CuckooGenerator // // Created by Filip Dolnik on 30.05.16. // Copyright ยฉ 2016 Brightify. All rights reserved. // public enum Kinds: String { case ProtocolDeclaration = "source.lang.swift.decl.protocol" case InstanceMethod = "source.lang.swift.decl.function.method.instance" case MethodParameter = "source.lang.swift.decl.var.parameter" case ClassDeclaration = "source.lang.swift.decl.class" case ExtensionDeclaration = "source.lang.swift.decl.extension" case InstanceVariable = "source.lang.swift.decl.var.instance" case GenericParameter = "source.lang.swift.decl.generic_type_param" case AssociatedType = "source.lang.swift.decl.associatedtype" case Optional = "source.decl.attribute.optional" }
mit
b1e5207dfe0227db6e7752580ff6d421
39
75
0.740789
3.781095
false
false
false
false
natestedman/PrettyOkayKit
PrettyOkayKit/APIClient.swift
1
4232
// Copyright (c) 2016, Nate Stedman <[email protected]> // // Permission to use, copy, modify, and/or distribute this software for any // purpose with or without fee is hereby granted, provided that the above // copyright notice and this permission notice appear in all copies. // // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY // AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM // LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR // OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR // PERFORMANCE OF THIS SOFTWARE. import Endpoint import ReactiveCocoa import Shirley import enum Result.NoError /// A client for the Very Goods API. public final class APIClient { // MARK: - Initialization /// Initializes an API client. /// /// - parameter authentication: The authentication to use for the client. public init(authentication: Authentication?) { self.authentication = authentication // session setup let dataSession = URLSession.HTTPSession().mapRequests({ (request: NSURLRequest) in let mutable = (request as? NSMutableURLRequest) ?? request.mutableCopy() as! NSMutableURLRequest authentication?.applyToMutableURLRequest(mutable) return mutable }) let loggingSession = Session { request in dataSession.producerForRequest(request) .on(started: { print("Sending \(request.logDescription)") }) .on(next: { print("Response \($0.response.statusCode) \(request.URL!.absoluteString)") }) }.raiseHTTPErrors { response, data in let str = NSString(data: data, encoding: NSUTF8StringEncoding) ?? "invalid" return ["Response String": str] } self.dataSession = loggingSession self.endpointSession = loggingSession.JSONSession().bodySession().mapRequests({ endpoint in endpoint.requestWithBaseURL(NSURL(string: "https://verygoods.co/site-api-0.1/")!)! }) // CSRF setup let CSRFSession = loggingSession.mapRequests({ (endpoint: AnyEndpoint) in endpoint.request! }) CSRFToken = AnyProperty( initialValue: nil, producer: authentication.map({ authentication in SignalProducer(value: ()) .concat(timer(3600, onScheduler: QueueScheduler.mainQueueScheduler).map({ _ in () })) // request a CSRF token .flatMap(.Latest, transform: { _ -> SignalProducer<String, NoError> in CSRFSession.outputProducerForRequest(CSRFEndpoint(purpose: .Authenticated(authentication))) .map({ $0.token }) .flatMapError({ _ in SignalProducer.empty }) }) .map({ $0 }) }) ?? SignalProducer.empty ) } // MARK: - Sessions /// The backing session for derived sessions. let URLSession = NSURLSession(configuration: NSURLSessionConfiguration.defaultSessionConfiguration()) /// A session for loading data. let dataSession: Session<NSURLRequest, Message<NSHTTPURLResponse, NSData>, NSError> /// A session for using endpoint values to load JSON objects. let endpointSession: Session<AnyBaseURLEndpoint, AnyObject, NSError> // MARK: - Authentication /// The authentication value for this API client. public let authentication: Authentication? // MARK: - CSRF /// Destructive actions against the Very Goods API require a CSRF token. If authenticated, the client will /// automatically obtain one periodically, and place it in this property. let CSRFToken: AnyProperty<String?> } extension NSURLRequest { private var logDescription: String { if let headers = allHTTPHeaderFields { return "\(HTTPMethod!) \(URL!.absoluteString) \(headers)" } else { return "\(HTTPMethod!) \(URL!.absoluteString)" } } }
isc
4e6997cebcd93df4ebab6ecca6e65fc2
37.825688
111
0.657609
5.0441
false
false
false
false
xwu/swift
test/Generics/unify_nested_types_1.swift
2
724
// RUN: %target-typecheck-verify-swift -requirement-machine=verify -dump-requirement-machine 2>&1 | %FileCheck %s protocol P1 { associatedtype T : P1 } protocol P2 { associatedtype T where T == Int } extension Int : P1 { public typealias T = Int } struct G<T : P1 & P2> {} // Since G.T.T == G.T.T.T == G.T.T.T.T = ... = Int, we tie off the // recursion by introducing a same-type requirement G.T.T => G.T. // CHECK-LABEL: Adding generic signature <ฯ„_0_0 where ฯ„_0_0 : P1, ฯ„_0_0 : P2> { // CHECK-LABEL: Rewrite system: { // CHECK: - ฯ„_0_0.[P1&P2:T].[concrete: Int] => ฯ„_0_0.[P1&P2:T] // CHECK: - [P1&P2:T].T => [P1&P2:T].[P1:T] // CHECK: - ฯ„_0_0.[P1&P2:T].[P1:T] => ฯ„_0_0.[P1&P2:T] // CHECK: } // CHECK: }
apache-2.0
c362a8777fd405c24cab598cc5ad10e2
26.576923
113
0.598326
2.312903
false
false
false
false
gyro-n/PaymentsIos
GyronPayments/Classes/Utils/Rest.swift
1
1660
// // Rest.swift // GyronPayments // // Created by Ye David on 10/25/16. // Copyright ยฉ 2016 gyron. All rights reserved. // import Foundation /*public func filterData(data: RequestData, keys: [String], excludeKeys: Bool) -> RequestData { var newData = data if (excludeKeys) { keys.forEach({ key in newData.removeValue(forKey: key) }) return newData } else { return getDataForKeys(data: data, keys: keys) } } public func getDataForKeys(data: RequestData, keys: [String]) -> RequestData { var result = RequestData() let filtered: [(String,AnyObject)] = data.filter({key, value in return keys.contains(key) }) for value in filtered { result[value.0] = value.1 } return result } public func convertToJson(data: RequestData) throws -> Data { do { return try JSONSerialization.data(withJSONObject: data, options: .prettyPrinted) } catch { throw error } } public func convertToRequestData(obj: AnyObject) -> RequestData { return Mirror(reflecting: obj).children.reduce(RequestData(), { prev, curr in var r: RequestData = prev if (curr.label != nil) { let a: AnyObject? = (curr.value as AnyObject) if let b = a { if !(b is NSNull) { r[curr.label!.stringFromCamelCase()] = b is RequestDataDelegate ? (b as! RequestDataDelegate).convertToMap() as AnyObject : b return r } return r } else { return r } } else { return r } }) }*/
mit
e47f652cc19d46c8a39099e42de75547
26.65
145
0.572031
4.286822
false
false
false
false
LYM-mg/MGDS_Swift
MGDS_Swift/MGDS_Swift/Class/Music/PlayMusic/Controller/MGMusicPlayViewController.swift
1
21732
// // MGMusicPlayViewController.swift // MGDS_Swift // // Created by i-Techsys.com on 17/3/2. // Copyright ยฉ 2017ๅนด i-Techsys. All rights reserved. // import UIKit import AVKit //enum MGPlayMode: Int { // case cicyleMode = 0, // randomMode, // singleModel //} //myContext็š„ไฝœ็”จ๏ผŒไธป่ฆๆ˜ฏๅŒบๅˆ†็›‘ๅฌๅฏน่ฑก๏ผŒๅ…ทไฝ“ไฝœ็”จ๏ผŒ็ง‘่‡ชๅทฑไธŠ็ฝ‘ๆŸฅ้˜…่ต„ๆ–™ private var currentMusicContext = 0 class MGMusicPlayViewController: UIViewController { // MARK: - ่„ฑ็บฟๅฑžๆ€ง /** ่ƒŒๆ™ฏๅ›พ็‰‡็š„ imageView */ @IBOutlet weak var backgroudImageView: UIImageView! // #pragma mark --- ้กถ้ƒจๅฑžๆ€ง ------- /** ๆญŒๆ›ฒๅ็งฐ */ @IBOutlet weak var songNameLabel: UILabel! /** ๆญŒๆ‰‹ */ @IBOutlet weak var singerLabel: UILabel! // #pragma mark --- ไธญ้ƒจๅฑžๆ€ง ------- /** ๆญŒ่ฏ */ @IBOutlet weak var lrcLabel: MGLrcLabel! /** ๆญŒ่ฏcrollViewๆปšๅŠจๆก */ @IBOutlet weak var lrcScrollView: UIScrollView! /** ๆญŒๆ‰‹ไธ“่พ‘ๅ›พ็‰‡ */ @IBOutlet weak var singerImageV: UIImageView! @IBOutlet weak var singerImageVHCon: NSLayoutConstraint! // #pragma mark --- ๅบ•้ƒจๅฑžๆ€ง ------- /** ๅฝ“ๅ‰ๆ’ญๆ”พๆ—ถ้—ด */ @IBOutlet weak var currentTimeLabel: UILabel! /** ๆญŒๆ›ฒๆ€ปๆ—ถ้•ฟ */ @IBOutlet weak var totalTimeLabel: UILabel! /** ๆŒ‰้’ฎ */ @IBOutlet weak var playOrStopBtn: UIButton! /** ๆปšๅŠจๆก */ @IBOutlet weak var progressSlide: UISlider! @IBOutlet weak var orderBtn: MGOrderButton! // MARK: - ่‡ชๅฎšไน‰ๅฑžๆ€ง fileprivate lazy var lrcTVC: MGLrcTableViewController = MGLrcTableViewController() lazy var musicArr = [SongDetail]() dynamic var currentMusic: MGMusicModel? var playingIndex: Int = 0 var playingItem: AVPlayerItem? // var playMode: MGPlayMode = MGPlayMode.cicyleMode var lrcTimer: CADisplayLink? // ๆญŒ่ฏ็š„ๅฎšๆ—ถๅ™จ var progressTimer: Timer? // ่ฟ›ๅบฆๆก็š„ๅฎšๆ—ถๅ™จ static let _indicator = MGMusicIndicator.share override func viewDidLoad() { super.viewDidLoad() setUpInit() } func setSongIdArray(musicArr: [SongDetail],currentIndex: NSInteger) { self.musicArr = musicArr self.playingIndex = currentIndex loadSongDetail() } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() // MARK: - โš ๏ธ ๅฟ…้กปๅŠ ไธŠ่ฟ™ๅฅไปฃ็  ่ฆไธ็„ถ่Žทๅ–็š„bounceไธๅ‡†็กฎๆ˜ฏ๏ผˆ0๏ผŒ0๏ผŒ1000๏ผŒ1000๏ผ‰ view.layoutIfNeeded() // ่ฎพ็ฝฎlrcView็š„ๆปšๅŠจๅŒบๅŸŸ self.lrcScrollView.contentSize = CGSize(width: backgroudImageView.mg_width * 2, height: 0) self.lrcTVC.tableView.frame = self.lrcScrollView.bounds self.lrcTVC.tableView.mg_y = MGGloabalMargin self.lrcTVC.tableView.mg_height = self.lrcScrollView.bounds.size.height - MGGloabalMargin self.lrcTVC.tableView.mg_x = self.backgroudImageView.mg_width self.singerImageV.layer.cornerRadius = self.singerImageV.mg_width*0.5; self.singerImageV.clipsToBounds = true self.singerImageV.layer.borderWidth = 1 self.singerImageV.layer.shadowOffset = CGSize(width: -1,height: -1) self.singerImageV.layer.shadowColor = UIColor.yellow.cgColor self.singerImageV.layer.shadowOpacity = 0.6 self.singerImageV.layer.borderColor = UIColor.red.cgColor } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) navigationController?.setNavigationBarHidden(true, animated: animated) } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) if playingItem?.status == AVPlayerItem.Status.readyToPlay{ // ๅชๆœ‰ๅœจ่ฟ™ไธช็Šถๆ€ไธ‹ๆ‰่ƒฝๆ’ญๆ”พ self.playingItem = MGPlayMusicTool.playMusicWithLink(link: currentMusic!.showLink) beginAnimation() } } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) navigationController?.setNavigationBarHidden(false, animated: animated) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } fileprivate func loadSongDetail() { let parameters: [String: Any] = ["songIds": self.musicArr[playingIndex].song_id] NetWorkTools.requestData(type: .get, urlString: "http://ting.baidu.com/data/music/links", parameters: parameters, succeed: { (result, err) in guard let resultDict = result as? [String : Any] else { return } // 2.ๆ นๆฎdata่ฏฅkey,่Žทๅ–ๆ•ฐ็ป„ guard let resultDictArray = resultDict["data"] as? [String : Any] else { return } guard let dataArray = resultDictArray["songList"] as? [[String : Any]] else { return } self.currentMusic = MGMusicModel(dict: dataArray.first!) self.setUpOnce() }) { (err) in self.showHint(hint: "ๆ’ญๆ”พๅคฑ่ดฅ") } } deinit { self.removeObserver(self, forKeyPath: "currentMusic") MGNotificationCenter.removeObserver(self) } } // MARK: - KVO extension MGMusicPlayViewController { fileprivate func setUpKVO() { self.addObserver(self, forKeyPath: "currentMusic", options: [.new,.old], context: &currentMusicContext) // ็›‘ๅฌ็ผ“ๅ†ฒ่ฟ›ๅบฆๆ”นๅ˜ // playingItem?.addObserver(self, forKeyPath: "loadedTimeRanges", options: .new, context: nil) // ็›‘ๅฌ็Šถๆ€ๆ”นๅ˜ // playingItem?.addObserver(self, forKeyPath: "status", options: .new, context: nil) // ๅฐ†่ง†้ข‘่ต„ๆบ่ต‹ๅ€ผ็ป™่ง†้ข‘ๆ’ญๆ”พๅฏน่ฑก // MGMusicPlayViewController._indicator.addObserver(self, forKeyPath: "state", options: .new, context: nil) } override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { if context == &currentMusicContext { let new: MGMusicModel = change![NSKeyValueChangeKey.newKey] as! MGMusicModel self.playingItem = MGPlayMusicTool.playMusicWithLink(link: new.songLink) MGNotificationCenter.addObserver(self, selector: #selector(MGMusicPlayViewController.playItemAction(item:)), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: self.playingItem) } // if keyPath == "loadedTimeRanges"{ // // ็ผ“ๅ†ฒ่ฟ›ๅบฆ ๅค„็† // let timeInterval = availableDuration() // ่ฎก็ฎ—็ผ“ๅ†ฒ่ฟ›ๅบฆ // debugPrint("็ผ“ๅ†ฒ่ฟ›ๅบฆ Time Interval:%f",timeInterval); // let duration: CMTime = (self.playingItem?.duration)!; // let totalDuration: Float = Float(CMTimeGetSeconds(duration)) // self.progressSlide.setValue(Float(timeInterval) / totalDuration, animated: true) // } else if keyPath == "status"{ // // ็›‘ๅฌ็Šถๆ€ๆ”นๅ˜ // if playingItem?.status == AVPlayerItemStatus.readyToPlay{ // // ๅชๆœ‰ๅœจ่ฟ™ไธช็Šถๆ€ไธ‹ๆ‰่ƒฝๆ’ญๆ”พ // self.playingItem = MGPlayMusicTool.playMusicWithLink(link: currentMusic!.showLink) // beginAnimation() // }else { // pauseAnimation() // MGPlayMusicTool.pauseMusicWithLink(link: currentMusic!.showLink) // debugPrint("ๆš‚ๅœๆˆ–่€…ๅผ‚ๅธธ") // } // } } fileprivate func availableDuration() -> TimeInterval { let loadedTimeRanges = self.playingItem?.loadedTimeRanges let timeRange = loadedTimeRanges?.first?.timeRangeValue // ่Žทๅ–็ผ“ๅ†ฒๅŒบๅŸŸ let startSeconds = CMTimeGetSeconds((timeRange?.start)!) let durationSeconds = CMTimeGetSeconds((timeRange?.duration)!) let result = startSeconds + durationSeconds // ่ฎก็ฎ—็ผ“ๅ†ฒๆ€ป่ฟ›ๅบฆ return result } // ๆ’ญๆ”พ้Ÿณไน - musicEnd @objc fileprivate func playItemAction(item: AVPlayerItem) { nextMusicBtnBlick() } func refreshIndicatorViewState() { } } // MARK: - Navigation extension MGMusicPlayViewController { /** * ๆŽงๅˆถๅ™จ็š„ๅˆๅง‹ๅŒ–ๆ–นๆณ•(ๅŠ ไธ€ไบ›่ง†ๅ›พๆŽงไปถ, ๆˆ–่€…, ไธ€ๆฌกๆ€ง็š„่ฎพ็ฝฎ) */ fileprivate func setUpInit() { self.addChild(lrcTVC) singerImageVHCon.constant = (MGScreenW == 320) ? 250 : 320 // ่ฎพ็ฝฎslideๆปšๅŠจๆก็š„ๆป‘ๅŠจๆŒ‰้’ฎๅ›พ็‰‡ progressSlide.setThumbImage(#imageLiteral(resourceName: "player_slider_playback_thumb"), for: .normal) // ๅœจlrcViewๆทปๅŠ ไธ€ไธชtableView self.lrcScrollView.addSubview(self.lrcTVC.tableView) // ่ฎพ็ฝฎๅˆ†้กต๏ผˆๅทฒๅœจstory้š่—ๆฐดๅนณๆปšๅŠจๆก๏ผ‰ lrcScrollView.isScrollEnabled = true; lrcScrollView.isUserInteractionEnabled = true; self.lrcScrollView.isPagingEnabled = true } // ่ฎพ็ฝฎไธ€ๆฌก็š„ๆ“ไฝœๅœจ่ฟ™้‡Œ func setUpOnce() { self.playOrStopBtn.isSelected = true self.songNameLabel.text = currentMusic?.songName self.singerLabel.text = currentMusic!.artistName + " " + currentMusic!.albumName self.singerImageV.setImageWithURLString(currentMusic?.songPicRadio!, placeholder: #imageLiteral(resourceName: "dzq")) // ่ฎพ็ฝฎ่ƒŒๆ™ฏๅ›พ็‰‡ // ๆทปๅŠ ไธ“่พ‘ๅ›พ็‰‡ๅŠจ็”ป self.backgroudImageView.setImageWithURLString(currentMusic?.songPicRadio!, placeholder: #imageLiteral(resourceName: "dzq")) beginAnimation() self.playingItem = MGPlayMusicTool.playMusicWithLink(link: currentMusic!.songLink) MGNotificationCenter.addObserver(self, selector: #selector(MGMusicPlayViewController.playItemAction(item:)), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: self.playingItem) setUpKVO() /** * ๅŠ ่ฝฝๆญŒๆ›ฒๅฏนๅบ”็š„ๆญŒ่ฏ่ต„ๆบ */ MGLrcLoadTool.getNetLrcModelsWithUrl(urlStr: currentMusic!.lrcLink!) { (lrcMs) in // ๆญŒ่ฏ็•Œ้ขๅŠ ่ฝฝๆ•ฐๆฎ (lrcArrayๆ˜ฏๆญŒ่ฏๆ•ฐ็ป„) self.lrcTVC.lrcMs = lrcMs self.addProgressTimer() self.addLrcTimer() } self.playOrStopBtn.isSelected = true } fileprivate func beginAnimation() { singerImageV.layer.removeAnimation(forKey: "rotation") /// 1.ๆ—‹่ฝฌๅŠจ็”ป let baseAnimation1 = CABasicAnimation(keyPath: "transform.rotation.z") baseAnimation1.fromValue = 0 baseAnimation1.toValue = (M_PI*2) baseAnimation1.autoreverses = false // ่ฎพ็ฝฎๅŠจ็”ป่‡ชๅŠจๅ่ฝฌ(ๆ€ŽไนˆๅŽป, ๆ€Žไนˆๅ›ž) /// 2.็ผฉๆ”พๅŠจ็”ป let baseAnimition2 = CABasicAnimation(keyPath: "transform.scale") baseAnimition2.fromValue = 1.2 baseAnimition2.toValue = 0.8 baseAnimition2.autoreverses = true // ่ฎพ็ฝฎๅŠจ็”ป่‡ชๅŠจๅ่ฝฌ(ๆ€ŽไนˆๅŽป, ๆ€Žไนˆๅ›ž) /// 3.ๅŠจ็”ป็ป„ let groupAnimition = CAAnimationGroup() groupAnimition.animations = [baseAnimation1,baseAnimition2] groupAnimition.duration = 20; groupAnimition.repeatCount = MAXFLOAT; groupAnimition.fillMode = CAMediaTimingFillMode.forwards; // ไฟๅญ˜ๅŠจ็”ปๆœ€ๅ‰้ข็š„ๆ•ˆๆžœ. groupAnimition.autoreverses = true // ่ฎพ็ฝฎๅŠจ็”ป่‡ชๅŠจๅ่ฝฌ(ๆ€ŽไนˆๅŽป, ๆ€Žไนˆๅ›ž) // ๆทปๅŠ ๅŠจ็”ป็ป„ self.singerImageV.layer.add(groupAnimition, forKey: "rotation") } // ๆš‚ๅœๅŠจ็”ป fileprivate func pauseAnimation() { self.singerImageV.layer.pauseAnimate() } // ็ปง็ปญๅŠจ็”ป fileprivate func resumeAnimation() { self.singerImageV.layer.resumeAnimate() } } // MARK: - Action extension MGMusicPlayViewController { // ไธŠไธ€้ฆ– @IBAction func preMusicBtnBlick() { changeMusic(variable: -1) } // ๆ’ญๆ”พORๆš‚ๅœ @IBAction func playOrStopBtnClick() { playOrStopBtn.isSelected = !playOrStopBtn.isSelected; if (playOrStopBtn.isSelected) { resumeAnimation(); addProgressTimer(); addLrcTimer() self.playingItem = MGPlayMusicTool.playMusicWithLink(link: currentMusic!.songLink) }else{ pauseAnimation(); removeProgressTimer(); removeLrcTimer() MGPlayMusicTool.pauseMusicWithLink(link: currentMusic!.songLink) } } // ไธ‹ไธ€้ฆ– @IBAction func nextMusicBtnBlick() { changeMusic(variable: 1) } // ๆ นๆฎๆจกๅผๆ’ญๆ”พ้Ÿณไน๐ŸŽต fileprivate func changeMusic(variable: NSInteger) { // if (playingItem != nil) { // playingItem?.removeObserver(self, forKeyPath: "loadedTimeRanges") // playingItem?.removeObserver(self, forKeyPath: "status") // } removeProgressTimer(); removeLrcTimer() MGPlayMusicTool.stopMusicWithLink(link: currentMusic!.songLink) switch(orderBtn.orderIndex){ case 1: //้กบๅบๆ’ญๆ”พ cicyleMusic(variable: variable) case 2: //้šๆœบๆ’ญๆ”พ randomMusic() case 3: //ๅ•ๆ›ฒๅพช็Žฏ break default: break } // switch (self.playMode) { // case .cicyleMode: // cicyleMusic(variable: variable) // case .randomMode: // randomMusic() // case .singleModel: // break // } loadSongDetail() addProgressTimer(); addLrcTimer() } fileprivate func cicyleMusic(variable: NSInteger) { if (self.playingIndex == self.musicArr.count - 1) { self.playingIndex = 0 } else if(self.playingIndex == 0){ self.playingIndex = self.musicArr.count - 1 } else{ self.playingIndex = variable + self.playingIndex } } fileprivate func randomMusic() { self.playingIndex = Int(arc4random_uniform(UInt32(musicArr.count))) - 1 // self.playingIndex = Int(arc4random())/ self.musicArr.count } // ้šๆœบๆ’ญๆ”พ @IBAction func randomPlayClick(_ btn: UIButton) { } // ๆ›ดๅคšๆŒ‰้’ฎ @IBAction func moreBtnClick(_ btn: UIButton) { self.showHint(hint: "็ญ‰ไฝ ๆฅๅฎŒๅ–„", mode: .determinateHorizontalBar) } @IBAction func backBtnClick(_ sender: UIButton) { let _ = navigationController?.popViewController(animated: true) } // MARK: - slideๆป‘ๅ—็›ธๅ…ณๆ–นๆณ• /// ๏ผˆๅฏ้šๆœบๆ‹–ๅˆฐslideไปปไฝ•ไฝ็ฝฎ๏ผ‰ @IBAction func slideValueChange(_ slider: UISlider) { if self.playingItem == nil { return } self.currentTimeLabel.text = MGTimeTool.getFormatTimeWithTimeInterval(timeInterval: Double(slider.value)) let dragCMtime = CMTimeMake(value: Int64(slider.value), timescale: 1) MGPlayMusicTool.setUpCurrentPlayingTime(time: dragCMtime, link: currentMusic!.songLink) } /// ๆทปๅŠ ็‚นๆŒ‰ๆ‰‹ๅŠฟ๏ผŒ้šๆœบๆ‹–ๆ‹ฝๆ’ญๆ”พ @IBAction func seekToTimeIntValue(_ tap: UITapGestureRecognizer) { } // ๆ‰‹ๆŒ‰ไธ‹ๅŽป็š„ๆ—ถๅ€™๏ผŒ่ฟ›่กŒ็š„ไธ€ไบ›ๆ“ไฝœ @IBAction func touchUp(_ sender: UISlider) { } // ๆ‰‹ๆŒ‰ไธ‹ๅŽป็š„ๆ—ถๅ€™๏ผŒๆธ…้™คupdateTimeๅฎšๆ—ถๅ™จ @IBAction func touchDown(_ sender: UISlider) { } } // MARK: - ๅฎšๆ—ถๅ™จ็›ธๅ…ณๆ–นๆณ• extension MGMusicPlayViewController { fileprivate func addProgressTimer() { self.progressTimer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(MGMusicPlayViewController.updateProgress), userInfo: nil, repeats: true) } fileprivate func addLrcTimer() { self.lrcTimer = CADisplayLink(target: self, selector: #selector(MGMusicPlayViewController.updateLrcLabel)) lrcTimer?.add(to: RunLoop.main, forMode: RunLoop.Mode.common) } fileprivate func removeProgressTimer() { progressTimer?.invalidate() progressTimer = nil } fileprivate func removeLrcTimer() { lrcTimer?.invalidate() lrcTimer = nil } // ๆ›ดๆ–ฐ @objc fileprivate func updateProgress() { self.currentTimeLabel.text = MGTimeTool.getFormatTimeWithTimeInterval(timeInterval: CMTimeGetSeconds(self.playingItem!.currentTime())) self.totalTimeLabel.text = MGTimeTool.getFormatTimeWithTimeInterval(timeInterval: CMTimeGetSeconds(self.playingItem!.asset.duration)) self.progressSlide.value = Float(CMTimeGetSeconds(self.playingItem!.currentTime())); // MARK: - โš ๏ธ้˜ฒๆญข่ฟ‡ๅฟซ็š„ๅˆ‡ๆขๆญŒๆ›ฒๅฏผ่‡ดduration == nan่€Œๅดฉๆบƒ BUG็›ดๆŽฅไฝฟ็”จself.playingItem!.duration่ฟ”ๅ›žnanๅฏผ่‡ดๅดฉๆบƒ if __inline_isnand(CMTimeGetSeconds(self.playingItem!.asset.duration)) == 1 { self.progressSlide.maximumValue = Float(CMTimeGetSeconds(self.playingItem!.currentTime())) + 1.00 } else { self.progressSlide.maximumValue = Float(CMTimeGetSeconds(self.playingItem!.asset.duration)) } } @objc fileprivate func updateLrcLabel() { // ่ฎก็ฎ—ๅฝ“ๅ‰ๆ’ญๆ”พๆ—ถ้—ด, ๅฏนๅบ”็š„ๆญŒ่ฏ่กŒๅท let row = MGLrcLoadTool.getRowWithCurrentTime(currentTime: CMTimeGetSeconds((self.playingItem?.currentTime())!), lrcMs: self.lrcTVC.lrcMs) self.lrcTVC.scrollRow = row // ๆ˜พ็คบๆญŒ่ฏlabel // ๅ–ๅ‡บๅฝ“ๅ‰ๆญฃๅœจๆ’ญๆ”พ็š„ๆญŒ่ฏๆ•ฐๆฎๆจกๅž‹ if self.lrcTVC.lrcMs.count == 0 { return } let lrcModel = self.lrcTVC.lrcMs[row]; // let ctime = playingItem!.currentTime() // let currentTimeSec: Float = Float(ctime.value) / Float(ctime.timescale) // let costTime = Double(currentTimeSec) - lrcModel.beginTime // let costTime = Double(CMTimeGetSeconds(playingItem!.currentTime()))-lrcModel.beginTime // let linetime = lrcModel.endTime - lrcModel.beginTime let currentTime = Double(CMTimeGetSeconds(MGPlayerQueue.share.currentTime())) /* ๆ€ปๆ’ญๆ”พๆ—ถ้—ด: ไฝฟ็”จๅฟ—ๆ„ฟ่ง‚ๅฏŸ็š„ไบ‹ไปถ AVQueuePlayer (็ฑปไผผไบŽๆญค)๏ผŒๅ’Œ่‡ชๅทฑ่ฎก็ฎ—ๆ‚จ็š„้˜Ÿๅˆ—็š„ๆ€ปๆ’ญๆ”พๆ—ถ้—ดใ€‚ ๅฏนไบŽๅฝ“ๅ‰ๆ’ญๆ”พ็š„ๆญŒๆ›ฒ็š„ๆ€ปๆ—ถ้—ด๏ผŒๆ‚จๅฏไปฅไฝฟ็”จ: */ // let value = playingItem!.currentTime().value // let timescale = playingItem!.currentTime().timescale.hashValue // let currentTimeSec = value/timescale let costTime = currentTime-lrcModel.beginTime let linetime = lrcModel.endTime - lrcModel.beginTime self.lrcLabel.progress = costTime/linetime self.lrcTVC.progress = self.lrcLabel.progress self.lrcLabel.text = lrcModel.lrcText; // ๆ›ดๆ–ฐ้”้ข‘ๆญŒ่ฏ updateLockInfo() } } // MARK: - ่ฎพ็ฝฎ้”ๅฑไฟกๆฏ๏ผๅŽๅฐ extension MGMusicPlayViewController { fileprivate func updateLockInfo() { //1.่Žทๅ–ๅฝ“ๅ‰ๆ’ญๆ”พไธญๅฟƒ let center = MPNowPlayingInfoCenter.default() var infos = [String: Any]() infos[MPMediaItemPropertyTitle] = currentMusic?.songName infos[MPMediaItemPropertyArtist] = currentMusic?.artistName infos[MPMediaItemPropertyPlaybackDuration] = Double(CMTimeGetSeconds(self.playingItem!.asset.duration)) // ๆญŒๆ›ฒๆ€ปๆ—ถ้•ฟ infos[MPNowPlayingInfoPropertyElapsedPlaybackTime] = Double(CMTimeGetSeconds(MGPlayerQueue.share.currentTime())) // ๆญŒๆ›ฒๅทฒ็ปๆ’ญๆ”พ็š„ๆ—ถ้•ฟ let row = MGLrcLoadTool.getRowWithCurrentTime(currentTime: CMTimeGetSeconds((self.playingItem?.currentTime())!), lrcMs: self.lrcTVC.lrcMs) let lrcModel = lrcTVC.lrcMs[row] let image = MGImageTool.creatImageWithText(text: lrcModel.lrcText, InImage: singerImageV.image!) if #available(iOS 10.0, *) { infos[MPMediaItemPropertyArtwork] = MPMediaItemArtwork(boundsSize: CGSize(width: 200,height: 200), requestHandler: { (size) -> UIImage in return image! }) } else { infos[MPMediaItemPropertyArtwork] = MPMediaItemArtwork(image: image!) } center.nowPlayingInfo = infos //่ฎพ็ฝฎ่ฟœ็จ‹ๆ“ๆŽง UIApplication.shared.beginReceivingRemoteControlEvents() // let _ = self.becomeFirstResponder() } // override func becomeFirstResponder() -> Bool { // return true // } // override func remoteControlReceived(with event: UIEvent?) { super.remoteControlReceived(with: event) switch (event!.subtype) { case UIEvent.EventSubtype.remoteControlPlay: playOrStopBtnClick() // self.playOrStopBtn.isSelected = false // playOrStopBtn.isSelected = !playOrStopBtn.isSelected; // resumeAnimation() // self.playingItem = MGPlayMusicTool.playMusicWithLink(link: currentMusic!.songLink) // break; case .remoteControlPause: playOrStopBtnClick() // self.playOrStopBtn.isSelected = true // MGPlayMusicTool.pauseMusicWithLink(link: currentMusic!.songLink) // pauseAnimation() // MGPlayerQueue.share.pause() // break; case .remoteControlStop: MGPlayMusicTool.stopMusicWithLink(link: currentMusic!.songLink) case .remoteControlNextTrack: nextMusicBtnBlick() setUpOnce() case .remoteControlPreviousTrack: preMusicBtnBlick() setUpOnce() default: break; } } } extension MGMusicPlayViewController: UIScrollViewDelegate { func scrollViewDidScroll(_ scrollView: UIScrollView) { let offsetX = scrollView.contentOffset.x let scale = offsetX/self.backgroudImageView.mg_width self.singerImageV.alpha = 1 - scale self.lrcLabel.alpha = 1 - scale } }
mit
3ae6fd006fd425add400420d3e28e739
38.055662
202
0.641341
4.334896
false
false
false
false
huangxiaoer/PhotoBrowser
PhotoBrowser/PhotoBrowser/Classes/Home/HomeViewController.swift
1
1354
// // HomeViewController.swift // PhotoBrowser // // Created by ๆŽๅ…ˆ็”Ÿ on 16/4/28. // Copyright ยฉ 2016ๅนด MaYuan. All rights reserved. // import UIKit private let reuseIdentifier = "Cell" class HomeViewController: UICollectionViewController { override func viewDidLoad() { super.viewDidLoad() let cols : CGFloat = 3 let margin : CGFloat = 10 let collectionViewFlowLayout = UICollectionViewFlowLayout() let itemWH = (UIScreen.mainScreen().bounds.width - (cols + 1)) / cols collectionViewFlowLayout.minimumInteritemSpacing = margin collectionViewFlowLayout.minimumLineSpacing = margin collectionViewFlowLayout.itemSize = CGSize(width: itemWH, height: itemWH) } } extension HomeViewController { override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return 20 } override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { //1.ๅˆ›ๅปบcell let cell = collectionView.dequeueReusableCellWithReuseIdentifier("HomeCell", forIndexPath: indexPath) //2.่ฎพ็ฝฎcell็š„่ƒŒๆ™ฏ่‰ฒ cell.backgroundColor = UIColor.redColor() return cell } }
apache-2.0
90498046d09c004465eb0ac1c0936ef2
26.142857
139
0.68322
5.560669
false
false
false
false
ewhitley/CDAKit
CDAKit/health-data-standards/lib/models/coded_result_value.swift
1
1150
// // result_value.swift // CDAKit // // Created by Eric Whitley on 11/30/15. // Copyright ยฉ 2015 Eric Whitley. All rights reserved. // import Foundation /** CDA Coded Result Value */ public class CDAKCodedResultValue: CDAKResultValue, CDAKThingWithCodes { // MARK: CDA properties ///CDA description public var item_description: String? ///Any codes associated with the result value public var codes: CDAKCodedEntries = CDAKCodedEntries() // MARK: Standard properties ///Debugging description override public var description: String { return "\(self.dynamicType) => attributes: \(attributes), time: \(time), start_time: \(start_time), end_time: \(end_time), item_description: \(item_description), codes: \(codes)" } } extension CDAKCodedResultValue { // MARK: - JSON Generation ///Dictionary for JSON data override public var jsonDict: [String: AnyObject] { var dict = super.jsonDict if let item_description = item_description { dict["description"] = item_description } if codes.count > 0 { dict["codes"] = codes.codes.map({$0.jsonDict}) } return dict } }
mit
3a73a23d2a09213d30bdb05074878c0c
22.9375
182
0.67624
4.074468
false
false
false
false
TCA-Team/iOS
TUM Campus App/DataSources/StudyRoomsDataSource.swift
1
3311
// // RoomFinderDataSource.swift // Campus // // This file is part of the TUM Campus App distribution https://github.com/TCA-Team/iOS // Copyright (c) 2018 TCA // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, version 3. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. // import UIKit class StudyRoomsDataSource: NSObject, TUMDataSource, TUMInteractiveDataSource { let parent: CardViewController var manager: StudyRoomsManager var cellType: AnyClass = StudyRoomsCollectionViewCell.self var isEmpty: Bool { return data.isEmpty } var cardKey: CardKey = .studyRooms var data: [StudyRoomGroup] = [] lazy var flowLayoutDelegate: ColumnsFlowLayoutDelegate = FixedColumnsVerticalItemsFlowLayoutDelegate(delegate: self) init(parent: CardViewController, manager: StudyRoomsManager) { self.parent = parent self.manager = manager super.init() } func refresh(group: DispatchGroup) { group.enter() manager.fetch().onSuccess(in: .main) { data in self.data = data group.leave() } } func onItemSelected(at indexPath: IndexPath) { let studyRoomGroup = data[indexPath.row] openStudyRooms(with: studyRoomGroup) } func onShowMore() { openStudyRooms() } private func openStudyRooms(with currentGroup: StudyRoomGroup? = nil) { let storyboard = UIStoryboard(name: "StudyRooms", bundle: nil) if let destination = storyboard.instantiateInitialViewController() as? StudyRoomsTableViewController { destination.delegate = parent destination.roomGroups = data destination.currentGroup = currentGroup ?? data.first parent.navigationController?.pushViewController(destination, animated: true) } } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return data.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell( withReuseIdentifier: cellReuseID, for: indexPath) as! StudyRoomsCollectionViewCell let roomGroup = data[indexPath.row] let availableRoomsCount = roomGroup.rooms.filter{$0.status == StudyRoomStatus.Free }.count cell.groupNameLabel.text = roomGroup.name cell.availableRoomsLabel.text = String(availableRoomsCount) switch availableRoomsCount { case 0: cell.availableRoomsLabel.backgroundColor = .red default: cell.availableRoomsLabel.backgroundColor = .green } return cell } }
gpl-3.0
f5fdc748d47b9e5c21ea3fbbc8f98ce8
34.602151
110
0.672908
4.890694
false
false
false
false
milseman/swift
test/expr/postfix/call/construction.swift
27
2402
// RUN: %target-typecheck-verify-swift struct S { init(i: Int) { } struct Inner { init(i: Int) { } } } enum E { case X case Y(Int) init(i: Int) { self = .Y(i) } enum Inner { case X case Y(Int) } } class C { init(i: Int) { } // expected-note{{selected non-required initializer 'init(i:)'}} required init(d: Double) { } class Inner { init(i: Int) { } } } final class D { init(i: Int) { } } // -------------------------------------------------------------------------- // Construction from Type values // -------------------------------------------------------------------------- func getMetatype<T>(_ m : T.Type) -> T.Type { return m } // Construction from a struct Type value func constructStructMetatypeValue() { _ = getMetatype(S.self).init(i: 5) _ = getMetatype(S.self)(i: 5) // expected-error{{initializing from a metatype value must reference 'init' explicitly}} {{26-26=.init}} _ = getMetatype(S.self) } // Construction from a struct Type value func constructEnumMetatypeValue() { _ = getMetatype(E.self).init(i: 5) } // Construction from a class Type value. func constructClassMetatypeValue() { // Only permitted with a @required constructor. _ = getMetatype(C.self).init(d: 1.5) // okay _ = getMetatype(C.self).init(i: 5) // expected-error{{constructing an object of class type 'C' with a metatype value must use a 'required' initializer}} _ = getMetatype(D.self).init(i: 5) } // -------------------------------------------------------------------------- // Construction via archetypes // -------------------------------------------------------------------------- protocol P { init() } func constructArchetypeValue<T: P>(_ t: T, tm: T.Type) { var t = t var t1 = T() t = t1 t1 = t var t2 = tm.init() t = t2 t2 = t } // -------------------------------------------------------------------------- // Construction via existentials. // -------------------------------------------------------------------------- protocol P2 { init(int: Int) } func constructExistentialValue(_ pm: P.Type) { _ = pm.init() _ = P() // expected-error{{protocol type 'P' cannot be instantiated}} } typealias P1_and_P2 = P & P2 func constructExistentialCompositionValue(_ pm: (P & P2).Type) { _ = pm.init(int: 5) _ = P1_and_P2(int: 5) // expected-error{{protocol type 'P1_and_P2' (aka 'P & P2') cannot be instantiated}} }
apache-2.0
e6fccbc80cd4817102e2bc1cf5f4a907
24.020833
154
0.511657
3.61203
false
false
false
false
SusanDoggie/Doggie
Sources/DoggieGraphics/ApplePlatform/ImageIO/CGImageRep.swift
1
5370
// // CGImageRep.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. // #if canImport(CoreGraphics) && canImport(ImageIO) protocol CGImageRepBase { var width: Int { get } var height: Int { get } var resolution: Resolution { get } var mediaType: MediaType? { get } var numberOfPages: Int { get } var general_properties: [CFString: Any] { get } var properties: [CFString: Any] { get } func page(_ index: Int) -> CGImageRepBase var cgImage: CGImage? { get } func auxiliaryDataInfo(_ type: String) -> [String: AnyObject]? func copy(to destination: CGImageDestination, properties: [CFString: Any]) var isAnimated: Bool { get } var repeats: Int { get } var duration: Double { get } } public struct CGImageRep { let base: CGImageRepBase private let cache = Cache() private init(base: CGImageRepBase) { self.base = base } } extension CGImageRep { @usableFromInline final class Cache { let lck = NSLock() var image: CGImage? var pages: [Int: CGImageRep] @usableFromInline init() { self.pages = [:] } } public func clearCaches() { cache.lck.synchronized { cache.image = nil cache.pages = [:] } } } extension CGImageRep { public static var supportedMediaTypes: [MediaType] { let types = CGImageSourceCopyTypeIdentifiers() as? [String] ?? [] return types.map { MediaType(rawValue: $0) } } public static var supportedDestinationMediaTypes: [MediaType] { let types = CGImageDestinationCopyTypeIdentifiers() as? [String] ?? [] return types.map { MediaType(rawValue: $0) } } } extension CGImageRep { public init?(url: URL) { guard let source = CGImageSourceCreateWithURL(url as CFURL, nil).flatMap(_CGImageSourceImageRepBase.init) else { return nil } self.base = source } public init?(data: Data) { guard let source = CGImageSourceCreateWithData(data as CFData, nil).flatMap(_CGImageSourceImageRepBase.init) else { return nil } self.base = source } public init?(provider: CGDataProvider) { guard let source = CGImageSourceCreateWithDataProvider(provider, nil).flatMap(_CGImageSourceImageRepBase.init) else { return nil } self.base = source } } extension CGImageRep { public init(cgImage: CGImage, resolution: Resolution = .default) { self.base = _CGImageRepBase(image: cgImage, resolution: resolution) } } extension CGImageRep { public var numberOfPages: Int { return base.numberOfPages } public func page(_ index: Int) -> CGImageRep { return cache.lck.synchronized { if cache.pages[index] == nil { cache.pages[index] = CGImageRep(base: base.page(index)) } return cache.pages[index]! } } public var cgImage: CGImage? { return cache.lck.synchronized { if cache.image == nil { cache.image = base.cgImage } return cache.image } } public func auxiliaryDataInfo(_ type: String) -> [String: AnyObject]? { return base.auxiliaryDataInfo(type) } } extension CGImageRep { public var width: Int { return base.width } public var height: Int { return base.height } public var resolution: Resolution { return base.resolution } } extension CGImageRep { public var isAnimated: Bool { return base.isAnimated } public var repeats: Int { return base.repeats } public var duration: Double { return base.duration } } extension CGImageRep { public var general_properties: [CFString: Any] { return base.general_properties } public var properties: [CFString: Any] { return base.properties } } extension CGImageRep { public var mediaType: MediaType? { return base.mediaType } } #endif
mit
df6f3ee6ee80b6dfff5d9083a3647489
24.69378
138
0.622905
4.609442
false
false
false
false
larryhou/swift
TexasHoldem/TexasHoldem/PatternTableViewController.swift
1
3661
// // PatternTableViewController.swift // TexasHoldem // // Created by larryhou on 12/3/2016. // Copyright ยฉ 2016 larryhou. All rights reserved. // import Foundation import UIKit class PatternTableViewController: UITableViewController, UISearchBarDelegate { private let background_queue = DispatchQueue(label: "TexasHoldem.background.search", attributes: DispatchQueueAttributes.concurrent) @IBOutlet weak var search: UISearchBar! var model: ViewModel! var id: Int = 0 var history: [UniqueRound]! override func viewDidLoad() { super.viewDidLoad() history = model.data } override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 80 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return history.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { if (indexPath as NSIndexPath).row < history.count { let cell = tableView.dequeueReusableCell(withIdentifier: "PatternCell") as! PatternTableViewCell let data = history[(indexPath as NSIndexPath).row].list[id] cell.renderView(data) return cell } else { let identifier = "LoadingCell" let cell: UITableViewCell if let reuseCell = tableView.dequeueReusableCell(withIdentifier: identifier) { cell = reuseCell } else { cell = UITableViewCell(style: .default, reuseIdentifier: identifier) cell.textLabel?.font = UIFont(name: "Menlo", size: 18) cell.textLabel?.text = "..." } return cell } } @IBAction func showPatternStats(_ sender: UIBarButtonItem) { let alert = PatternStatsPrompt(title: "็‰Œๅž‹ๅˆ†ๅธƒ", message: nil, preferredStyle: .actionSheet) alert.setPromptSheet(model.stats[id]!) present(alert, animated: true, completion: nil) } // MARK: search func searchBarSearchButtonClicked(_ searchBar: UISearchBar) { searchBar.resignFirstResponder() } func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) { searchByInput(searchText) } func searchByInput(_ searchText: String?) { if let text = searchText { var integer = NSString(string: text).integerValue integer = min(max(0, integer), 255) if let pattern = HandPattern(rawValue: UInt8(integer)) { background_queue.async { self.history = [] DispatchQueue.main.async { self.tableView.reloadData() } for i in 0..<self.model.data.count { let hand = self.model.data[i].list[self.id] if hand.data.0 == pattern.rawValue { self.history.append(self.model.data[i]) if self.history.count < 10 { DispatchQueue.main.async { self.tableView.reloadData() } } } } DispatchQueue.main.async { self.tableView.reloadData() } } } else { history = model.data } } else { history = model.data } tableView.reloadData() } }
mit
f17bd4ddca36a8035923ab8e7effc112
31.900901
136
0.560241
5.30814
false
false
false
false
wangyuxianglove/TestKitchen1607
Testkitchen1607/Testkitchen1607/classes/ingredient(้ฃŸๆ)/main(ไธป่ฆๆจกๅ—)/view/IngreRecommendView.swift
1
7745
// // IngreRecommendView.swift // Testkitchen1607 // // Created by qianfeng on 16/10/25. // Copyright ยฉ 2016ๅนด zhb. All rights reserved. // import UIKit public enum IngreWidgetType:Int{ case GuessYouLike = 1//็Œœไฝ ๅ–œๆฌข case RedPacket = 2//็บขๅŒ…ๅ…ฅๅฃ case TodayNew=5//ไปŠๆ—ฅๆ–ฐๅ“ case Scene=3//ๆ—ฉ้ค case SceneList=9//ๅ…จ้ƒจๅœบๆ™ฏ } class IngreRecommendView: UIView { //ๆ•ฐๆฎ var jumpClosure:IngreJumpClourse? var model:IngreRcommend?{ didSet{ //setๆ–นๆณ•่ฐƒ็”จไน‹ๅŽไผš่ฐƒ็”จ่ฟ™้‡Œๆ–นๆณ• tableView?.reloadData() } } //่กจๆ ผ private var tableView:UITableView? //้‡ๆ–ฐๅฎž็Žฐๅˆๅง‹ๅŒ–ๆ–นๆณ• override init(frame: CGRect) { super.init(frame: frame) //ๅˆ›ๅปบ่กจๆ ผ่ง†ๅ›พ tableView=UITableView(frame: CGRectZero, style: .Plain) tableView?.dataSource=self tableView?.delegate=self addSubview(tableView!) //็บฆๆŸ tableView?.snp_makeConstraints(closure: { (make) in make.edges.equalToSuperview() }) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } //MARK:UITableViewไปฃ็†ๆ–นๆณ• extension IngreRecommendView:UITableViewDelegate,UITableViewDataSource{ func numberOfSectionsInTableView(tableView: UITableView) -> Int { //bannerๅนฟๅ‘Š้ƒจๅˆ†ๆ˜พ็คบไธ€ไธชๅˆ†็ป„ var section=1 if model?.data?.widgetList?.count>0{ section+=(model?.data?.widgetList?.count)! } return section } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { //bannerๅนฟๅ‘ŠSectionๆ˜พ็คบไธ€่กŒ var row=0 if section==0{ //ๅนฟๅ‘Š row=1 }else{ //่Žทๅ–listๅฏน่ฑก let listModel = model?.data?.widgetList![section-1] if (listModel?.widget_type?.integerValue)! == IngreWidgetType.GuessYouLike.rawValue||(listModel?.widget_type?.integerValue)! == IngreWidgetType.RedPacket.rawValue||(listModel?.widget_type?.integerValue)! == IngreWidgetType.TodayNew.rawValue||(listModel?.widget_type?.integerValue)! == IngreWidgetType.Scene.rawValue||(listModel?.widget_type?.integerValue)! == IngreWidgetType.SceneList.rawValue{ //็Œœไฝ ๅ–œๆฌข //็บขๅŒ…ๅ…ฅๅฃ //ไปŠๆ—ฅๆ–ฐๅ“ //ๆ—ฉ้คๆ—ฅ่ฎฐ //ๅ…จ้ƒจๅœบๆ™ฏ row=1 } } return row } func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { var height:CGFloat=0 if indexPath.section==0{ height=140 }else{ let listModel=model?.data?.widgetList![indexPath.section-1] if listModel?.widget_type?.integerValue==IngreWidgetType.GuessYouLike.rawValue{ //็Œœไฝ ๅ–œๆฌข height=70 }else if listModel?.widget_type?.integerValue==IngreWidgetType.RedPacket.rawValue{ //็บขๅŒ…ๅ…ฅๅฃ height=75 }else if listModel?.widget_type?.integerValue==IngreWidgetType.TodayNew.rawValue{ //ไปŠๆ—ฅๆ–ฐๅ“ height=280 }else if listModel?.widget_type?.integerValue==IngreWidgetType.Scene.rawValue{ //ๆ—ฉ้คๆ—ฅ่ฎฐ height=200 }else if listModel?.widget_type?.integerValue==IngreWidgetType.SceneList.rawValue{ //ๅ…จ้ƒจๅœบๆ™ฏ height=70 } } return height } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { if indexPath.section==0{ let cell=IngreBannerCell.creatBannerCellFor(tableView, atIndexPath: indexPath, bannerArray: model?.data?.bannerArray) //็‚นๅ‡ปไบ‹ไปถ cell.jumpClosure=jumpClosure return cell }else{ let listModel=model?.data?.widgetList![indexPath.section-1] if listModel?.widget_type?.integerValue==IngreWidgetType.GuessYouLike.rawValue{ //็Œœไฝ ๅ–œๆฌข let cell = IngreLikeCell.creatLikeCellFor(tableView, atIndexPath: indexPath, listModel: listModel) //็‚นๅ‡ปไบ‹ไปถ cell.jumpClosure=jumpClosure return cell }else if listModel?.widget_type?.integerValue==IngreWidgetType.RedPacket.rawValue{ //็บขๅŒ…ๅ…ฅๅฃ let cell = IngreRedPacketCell.creatRedPackCellFor(tableView, atIndexPath: indexPath, listModel: listModel!) //็‚นๅ‡ปไบ‹ไปถ cell.jumpClosure=jumpClosure return cell }else if listModel?.widget_type?.integerValue==IngreWidgetType.TodayNew.rawValue{ //ไปŠๆ—ฅๆ–ฐๅ“ let cell = IngreTodayCell.creatRedTodayCellFor(tableView, atIndexPath: indexPath, listModel: listModel) //็‚นๅ‡ปไบ‹ไปถ cell.jumpClosure=jumpClosure return cell }else if listModel?.widget_type?.integerValue==IngreWidgetType.Scene.rawValue{ //ๆ—ฉ้ค let cell = IngrescenCell.creatSceneCellFor(tableView, atIndexPath: indexPath, listModel: listModel) //็‚นๅ‡ปไบ‹ไปถ cell.jumpClosure=jumpClosure return cell }else if listModel?.widget_type?.integerValue==IngreWidgetType.SceneList.rawValue{ //ๅ…จ้ƒจ let cell = IngreSceneListCell.creatSceneListCellFor(tableView, atIndexPath: indexPath, listModel: listModel) //็‚นๅ‡ปไบ‹ไปถ cell.jumpClosure=jumpClosure return cell } } return UITableViewCell() } func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { if section>0{ let listModel=model?.data?.widgetList![section-1] if listModel?.widget_type?.integerValue==IngreWidgetType.GuessYouLike.rawValue{ //็Œœไฝ ๅ–œๆฌขๅˆ†็ป„็š„header let likeHeaderView=IngreLikeHeaderView(frame: CGRect(x: 0, y: 0, width: bounds.size.width, height: 44)) return likeHeaderView }else if listModel?.widget_type?.integerValue==IngreWidgetType.TodayNew.rawValue||listModel?.widget_type?.integerValue==IngreWidgetType.Scene.rawValue{ //ไปŠๆ—ฅๆ–ฐๅ“ let headerView=IngreHeaderView(frame: CGRect(x: 0, y: 0, width:kScreenWidth , height: 54)) //headerView.configText((listModel?.title)!) headerView.jumpClosure=jumpClosure headerView.listModel=listModel return headerView } } return nil } //่ฎพ็ฝฎheader็š„้ซ˜ๅบฆ func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { var height:CGFloat=0 if section > 0{ let listModel=model?.data?.widgetList![section-1] if listModel?.widget_type?.integerValue==IngreWidgetType.GuessYouLike.rawValue{ height=44 }else if listModel?.widget_type?.integerValue==IngreWidgetType.TodayNew.rawValue||listModel?.widget_type?.integerValue==IngreWidgetType.Scene.rawValue{ // height=54 } } return height } }
mit
f1c2a23aa22aaec988a65e50f67f9526
34.209524
412
0.585204
5.127601
false
false
false
false
trungung/UIKitExtension
Pod/Classes/UIViewExtensions.swift
1
4550
// // UIViewExtensions.swift // UIKitExtension // // Created by TrungUng on 06/23/2015. // Copyright (c) 06/23/2015 TrungUng. All rights reserved. // import Foundation import UIKit import CGRectExtensions extension UIView { // *************************************************************************** // MARK: - UIView with Animations /** Fade In Animation :param: duration - Animation duration (default 0.7) */ public func fadeIn(duration: CFTimeInterval = 0.7) { UIView.animateWithDuration(duration, delay: 0.0, options: UIViewAnimationOptions.CurveEaseIn, animations: { self.alpha = 1.0 }, completion: nil) } /** Fade Out Animation :param: duration - Animation duration (default 0.7) */ public func fadeOut(duration: CFTimeInterval = 0.7) { UIView.animateWithDuration(duration, delay: 0.0, options: UIViewAnimationOptions.CurveEaseOut, animations: { self.alpha = 0.0 }, completion: nil) } /** Rotate 360 degrees Animation :param: duration - Animation duration (default 0.7) :param: completionDelegate */ public func rotate360Degrees(duration: CFTimeInterval = 0.7, completionDelegate: AnyObject? = nil) { // Create a CATransition animation let rotateAnimation = CABasicAnimation(keyPath: "transform.rotation") rotateAnimation.fromValue = 0.0 rotateAnimation.toValue = CGFloat(M_PI * 2.0) rotateAnimation.duration = duration if let delegate: AnyObject = completionDelegate { rotateAnimation.delegate = delegate } self.layer.addAnimation(rotateAnimation, forKey: nil) } /** SlideIn View from left :param: duration - Animation duration (default 0.7) :param: completionDelegate */ public func slideInFromLeft(duration: NSTimeInterval = 0.7, completionDelegate: AnyObject? = nil) { // Create a CATransition animation let slideInFromLeftTransition = CATransition() if let delegate: AnyObject = completionDelegate { slideInFromLeftTransition.delegate = delegate } // Customize the animation's properties slideInFromLeftTransition.type = kCATransitionPush slideInFromLeftTransition.subtype = kCATransitionFromLeft slideInFromLeftTransition.duration = duration slideInFromLeftTransition.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut) slideInFromLeftTransition.fillMode = kCAFillModeRemoved // Add the animation to the View's layer self.layer.addAnimation(slideInFromLeftTransition, forKey: "slideInFromLeftTransition") } // *************************************************************************** // MARK: - UIView with Animations // The top coordinate of the UIView. public var top: CGFloat { get { return frame.left } set(value) { var frame = self.frame frame.top = value self.frame = frame } } // The left coordinate of the UIView. public var left: CGFloat { get { return frame.left } set(value) { var frame = self.frame frame.left = value self.frame = frame } } // The bottom coordinate of the UIView. public var bottom: CGFloat { get { return frame.bottom } set(value) { var frame = self.frame frame.bottom = value self.frame = frame } } // The right coordinate of the UIView. public var right: CGFloat { get { return frame.right } set(value) { var frame = self.frame frame.right = value self.frame = frame } } // The width of the UIView. public var width: CGFloat { get { return frame.width } set(value) { var frame = self.frame frame.size.width = value self.frame = frame } } // The height of the UIView. public var height: CGFloat { get { return frame.height } set(value) { var frame = self.frame frame.size.width = value self.frame = frame } } // The horizontal center coordinate of the UIView. public var centerX: CGFloat { get { return frame.centerX } set(value) { var frame = self.frame frame.centerX = value self.frame = frame } } // The vertical center coordinate of the UIView. public var centerY: CGFloat { get { return frame.centerY } set(value) { var frame = self.frame frame.centerY = value self.frame = frame } } }
mit
90d6dcc1be284adaa0436aec60a66ad6
23.467742
112
0.622857
4.531873
false
false
false
false
AutomationStation/BouncerBuddy
BouncerBuddy(version1.2)/BouncerBuddy/CAGradientLayer.convience.swift
1
832
// // CAGradientLayer+convience.swift // BouncerBuddy // // Created by Jiaxi Liu on 3/8/16. // Copyright ยฉ 2016 Sheryl Hong. All rights reserved. // import UIKit extension CAGradientLayer { func turquoiseColor() -> CAGradientLayer { let topColor = UIColor(red: (150/255.0), green: (222/255.0), blue: (218/255.0), alpha: 1) let bottomColor = UIColor(red: (80/255.0), green: (201/255.0), blue: (195/255.0), alpha: 1) let gradientColors: [CGColor] = [topColor.CGColor, bottomColor.CGColor] let gradientLocations: [Float] = [0.0, 1.0] let gradientLayer: CAGradientLayer = CAGradientLayer() gradientLayer.colors = gradientColors gradientLayer.locations = gradientLocations return gradientLayer } }
apache-2.0
21f9e6c85adc22b855e8079d014bb8b0
26.7
99
0.614922
4.073529
false
false
false
false
ivanbruel/snapist
SnapIST/Classes/View Controllers/Extensions/ChatViewController+SnapIST.swift
1
731
// // ChatViewController+SnapIST.swift // SnapIST // // Created by Ivan Bruel on 25/02/15. // Copyright (c) 2015 SINFO 22. All rights reserved. // import UIKit extension ChatViewController { func calculateHeightForIndexPath(indexPath: NSIndexPath) -> CGFloat { let message = messages[indexPath.row] let size = CGSize(width: CGRectGetWidth(tableView.bounds) - 40, height: CGFloat.max) let string = (message.formattedText as NSString) let attributes = [NSFontAttributeName: UIFont(name: "Menlo-Regular", size: 13)!] let rect = string.boundingRectWithSize(size, options: .UsesLineFragmentOrigin, attributes: attributes, context: nil) return rect.size.height } }
apache-2.0
7b8eab47ba070a31510f133df6a7ebd5
32.227273
124
0.69357
4.3
false
false
false
false
WhisperSystems/Signal-iOS
SignalServiceKit/src/Util/OWSUserProfile+SDS.swift
1
24008
// // Copyright (c) 2019 Open Whisper Systems. All rights reserved. // import Foundation import GRDB import SignalCoreKit // NOTE: This file is generated by /Scripts/sds_codegen/sds_generate.py. // Do not manually edit it, instead run `sds_codegen.sh`. // MARK: - Record public struct UserProfileRecord: SDSRecord { public var tableMetadata: SDSTableMetadata { return OWSUserProfileSerializer.table } public static let databaseTableName: String = OWSUserProfileSerializer.table.tableName public var id: Int64? // This defines all of the columns used in the table // where this model (and any subclasses) are persisted. public let recordType: SDSRecordType public let uniqueId: String // Base class properties public let avatarFileName: String? public let avatarUrlPath: String? public let profileKey: Data? public let profileName: String? public let recipientPhoneNumber: String? public let recipientUUID: String? public let userProfileSchemaVersion: UInt public let username: String? public enum CodingKeys: String, CodingKey, ColumnExpression, CaseIterable { case id case recordType case uniqueId case avatarFileName case avatarUrlPath case profileKey case profileName case recipientPhoneNumber case recipientUUID case userProfileSchemaVersion case username } public static func columnName(_ column: UserProfileRecord.CodingKeys, fullyQualified: Bool = false) -> String { return fullyQualified ? "\(databaseTableName).\(column.rawValue)" : column.rawValue } } // MARK: - Row Initializer public extension UserProfileRecord { static var databaseSelection: [SQLSelectable] { return CodingKeys.allCases } init(row: Row) { id = row[0] recordType = row[1] uniqueId = row[2] avatarFileName = row[3] avatarUrlPath = row[4] profileKey = row[5] profileName = row[6] recipientPhoneNumber = row[7] recipientUUID = row[8] userProfileSchemaVersion = row[9] username = row[10] } } // MARK: - StringInterpolation public extension String.StringInterpolation { mutating func appendInterpolation(userProfileColumn column: UserProfileRecord.CodingKeys) { appendLiteral(UserProfileRecord.columnName(column)) } mutating func appendInterpolation(userProfileColumnFullyQualified column: UserProfileRecord.CodingKeys) { appendLiteral(UserProfileRecord.columnName(column, fullyQualified: true)) } } // MARK: - Deserialization // TODO: Rework metadata to not include, for example, columns, column indices. extension OWSUserProfile { // This method defines how to deserialize a model, given a // database row. The recordType column is used to determine // the corresponding model class. class func fromRecord(_ record: UserProfileRecord) throws -> OWSUserProfile { guard let recordId = record.id else { throw SDSError.invalidValue } switch record.recordType { case .userProfile: let uniqueId: String = record.uniqueId let avatarFileName: String? = record.avatarFileName let avatarUrlPath: String? = record.avatarUrlPath let profileKeySerialized: Data? = record.profileKey let profileKey: OWSAES256Key? = try SDSDeserialization.optionalUnarchive(profileKeySerialized, name: "profileKey") let profileName: String? = record.profileName let recipientPhoneNumber: String? = record.recipientPhoneNumber let recipientUUID: String? = record.recipientUUID let userProfileSchemaVersion: UInt = record.userProfileSchemaVersion let username: String? = record.username return OWSUserProfile(uniqueId: uniqueId, avatarFileName: avatarFileName, avatarUrlPath: avatarUrlPath, profileKey: profileKey, profileName: profileName, recipientPhoneNumber: recipientPhoneNumber, recipientUUID: recipientUUID, userProfileSchemaVersion: userProfileSchemaVersion, username: username) default: owsFailDebug("Unexpected record type: \(record.recordType)") throw SDSError.invalidValue } } } // MARK: - SDSModel extension OWSUserProfile: SDSModel { public var serializer: SDSSerializer { // Any subclass can be cast to it's superclass, // so the order of this switch statement matters. // We need to do a "depth first" search by type. switch self { default: return OWSUserProfileSerializer(model: self) } } public func asRecord() throws -> SDSRecord { return try serializer.asRecord() } public var sdsTableName: String { return UserProfileRecord.databaseTableName } public static var table: SDSTableMetadata { return OWSUserProfileSerializer.table } } // MARK: - Table Metadata extension OWSUserProfileSerializer { // This defines all of the columns used in the table // where this model (and any subclasses) are persisted. static let idColumn = SDSColumnMetadata(columnName: "id", columnType: .primaryKey, columnIndex: 0) static let recordTypeColumn = SDSColumnMetadata(columnName: "recordType", columnType: .int64, columnIndex: 1) static let uniqueIdColumn = SDSColumnMetadata(columnName: "uniqueId", columnType: .unicodeString, isUnique: true, columnIndex: 2) // Base class properties static let avatarFileNameColumn = SDSColumnMetadata(columnName: "avatarFileName", columnType: .unicodeString, isOptional: true, columnIndex: 3) static let avatarUrlPathColumn = SDSColumnMetadata(columnName: "avatarUrlPath", columnType: .unicodeString, isOptional: true, columnIndex: 4) static let profileKeyColumn = SDSColumnMetadata(columnName: "profileKey", columnType: .blob, isOptional: true, columnIndex: 5) static let profileNameColumn = SDSColumnMetadata(columnName: "profileName", columnType: .unicodeString, isOptional: true, columnIndex: 6) static let recipientPhoneNumberColumn = SDSColumnMetadata(columnName: "recipientPhoneNumber", columnType: .unicodeString, isOptional: true, columnIndex: 7) static let recipientUUIDColumn = SDSColumnMetadata(columnName: "recipientUUID", columnType: .unicodeString, isOptional: true, columnIndex: 8) static let userProfileSchemaVersionColumn = SDSColumnMetadata(columnName: "userProfileSchemaVersion", columnType: .int64, columnIndex: 9) static let usernameColumn = SDSColumnMetadata(columnName: "username", columnType: .unicodeString, isOptional: true, columnIndex: 10) // TODO: We should decide on a naming convention for // tables that store models. public static let table = SDSTableMetadata(collection: OWSUserProfile.collection(), tableName: "model_OWSUserProfile", columns: [ idColumn, recordTypeColumn, uniqueIdColumn, avatarFileNameColumn, avatarUrlPathColumn, profileKeyColumn, profileNameColumn, recipientPhoneNumberColumn, recipientUUIDColumn, userProfileSchemaVersionColumn, usernameColumn ]) } // MARK: - Save/Remove/Update @objc public extension OWSUserProfile { func anyInsert(transaction: SDSAnyWriteTransaction) { sdsSave(saveMode: .insert, transaction: transaction) } // This method is private; we should never use it directly. // Instead, use anyUpdate(transaction:block:), so that we // use the "update with" pattern. private func anyUpdate(transaction: SDSAnyWriteTransaction) { sdsSave(saveMode: .update, transaction: transaction) } @available(*, deprecated, message: "Use anyInsert() or anyUpdate() instead.") func anyUpsert(transaction: SDSAnyWriteTransaction) { let isInserting: Bool if OWSUserProfile.anyFetch(uniqueId: uniqueId, transaction: transaction) != nil { isInserting = false } else { isInserting = true } sdsSave(saveMode: isInserting ? .insert : .update, transaction: transaction) } // This method is used by "updateWith..." methods. // // This model may be updated from many threads. We don't want to save // our local copy (this instance) since it may be out of date. We also // want to avoid re-saving a model that has been deleted. Therefore, we // use "updateWith..." methods to: // // a) Update a property of this instance. // b) If a copy of this model exists in the database, load an up-to-date copy, // and update and save that copy. // b) If a copy of this model _DOES NOT_ exist in the database, do _NOT_ save // this local instance. // // After "updateWith...": // // a) Any copy of this model in the database will have been updated. // b) The local property on this instance will always have been updated. // c) Other properties on this instance may be out of date. // // All mutable properties of this class have been made read-only to // prevent accidentally modifying them directly. // // This isn't a perfect arrangement, but in practice this will prevent // data loss and will resolve all known issues. func anyUpdate(transaction: SDSAnyWriteTransaction, block: (OWSUserProfile) -> Void) { block(self) guard let dbCopy = type(of: self).anyFetch(uniqueId: uniqueId, transaction: transaction) else { return } // Don't apply the block twice to the same instance. // It's at least unnecessary and actually wrong for some blocks. // e.g. `block: { $0 in $0.someField++ }` if dbCopy !== self { block(dbCopy) } dbCopy.anyUpdate(transaction: transaction) } func anyRemove(transaction: SDSAnyWriteTransaction) { sdsRemove(transaction: transaction) } func anyReload(transaction: SDSAnyReadTransaction) { anyReload(transaction: transaction, ignoreMissing: false) } func anyReload(transaction: SDSAnyReadTransaction, ignoreMissing: Bool) { guard let latestVersion = type(of: self).anyFetch(uniqueId: uniqueId, transaction: transaction) else { if !ignoreMissing { owsFailDebug("`latest` was unexpectedly nil") } return } setValuesForKeys(latestVersion.dictionaryValue) } } // MARK: - OWSUserProfileCursor @objc public class OWSUserProfileCursor: NSObject { private let cursor: RecordCursor<UserProfileRecord>? init(cursor: RecordCursor<UserProfileRecord>?) { self.cursor = cursor } public func next() throws -> OWSUserProfile? { guard let cursor = cursor else { return nil } guard let record = try cursor.next() else { return nil } return try OWSUserProfile.fromRecord(record) } public func all() throws -> [OWSUserProfile] { var result = [OWSUserProfile]() while true { guard let model = try next() else { break } result.append(model) } return result } } // MARK: - Obj-C Fetch // TODO: We may eventually want to define some combination of: // // * fetchCursor, fetchOne, fetchAll, etc. (ala GRDB) // * Optional "where clause" parameters for filtering. // * Async flavors with completions. // // TODO: I've defined flavors that take a read transaction. // Or we might take a "connection" if we end up having that class. @objc public extension OWSUserProfile { class func grdbFetchCursor(transaction: GRDBReadTransaction) -> OWSUserProfileCursor { let database = transaction.database do { let cursor = try UserProfileRecord.fetchCursor(database) return OWSUserProfileCursor(cursor: cursor) } catch { owsFailDebug("Read failed: \(error)") return OWSUserProfileCursor(cursor: nil) } } // Fetches a single model by "unique id". class func anyFetch(uniqueId: String, transaction: SDSAnyReadTransaction) -> OWSUserProfile? { assert(uniqueId.count > 0) switch transaction.readTransaction { case .yapRead(let ydbTransaction): return OWSUserProfile.ydb_fetch(uniqueId: uniqueId, transaction: ydbTransaction) case .grdbRead(let grdbTransaction): let sql = "SELECT * FROM \(UserProfileRecord.databaseTableName) WHERE \(userProfileColumn: .uniqueId) = ?" return grdbFetchOne(sql: sql, arguments: [uniqueId], transaction: grdbTransaction) } } // Traverses all records. // Records are not visited in any particular order. class func anyEnumerate(transaction: SDSAnyReadTransaction, block: @escaping (OWSUserProfile, UnsafeMutablePointer<ObjCBool>) -> Void) { anyEnumerate(transaction: transaction, batched: false, block: block) } // Traverses all records. // Records are not visited in any particular order. class func anyEnumerate(transaction: SDSAnyReadTransaction, batched: Bool = false, block: @escaping (OWSUserProfile, UnsafeMutablePointer<ObjCBool>) -> Void) { let batchSize = batched ? Batching.kDefaultBatchSize : 0 anyEnumerate(transaction: transaction, batchSize: batchSize, block: block) } // Traverses all records. // Records are not visited in any particular order. // // If batchSize > 0, the enumeration is performed in autoreleased batches. class func anyEnumerate(transaction: SDSAnyReadTransaction, batchSize: UInt, block: @escaping (OWSUserProfile, UnsafeMutablePointer<ObjCBool>) -> Void) { switch transaction.readTransaction { case .yapRead(let ydbTransaction): OWSUserProfile.ydb_enumerateCollectionObjects(with: ydbTransaction) { (object, stop) in guard let value = object as? OWSUserProfile else { owsFailDebug("unexpected object: \(type(of: object))") return } block(value, stop) } case .grdbRead(let grdbTransaction): do { let cursor = OWSUserProfile.grdbFetchCursor(transaction: grdbTransaction) try Batching.loop(batchSize: batchSize, loopBlock: { stop in guard let value = try cursor.next() else { stop.pointee = true return } block(value, stop) }) } catch let error { owsFailDebug("Couldn't fetch models: \(error)") } } } // Traverses all records' unique ids. // Records are not visited in any particular order. class func anyEnumerateUniqueIds(transaction: SDSAnyReadTransaction, block: @escaping (String, UnsafeMutablePointer<ObjCBool>) -> Void) { anyEnumerateUniqueIds(transaction: transaction, batched: false, block: block) } // Traverses all records' unique ids. // Records are not visited in any particular order. class func anyEnumerateUniqueIds(transaction: SDSAnyReadTransaction, batched: Bool = false, block: @escaping (String, UnsafeMutablePointer<ObjCBool>) -> Void) { let batchSize = batched ? Batching.kDefaultBatchSize : 0 anyEnumerateUniqueIds(transaction: transaction, batchSize: batchSize, block: block) } // Traverses all records' unique ids. // Records are not visited in any particular order. // // If batchSize > 0, the enumeration is performed in autoreleased batches. class func anyEnumerateUniqueIds(transaction: SDSAnyReadTransaction, batchSize: UInt, block: @escaping (String, UnsafeMutablePointer<ObjCBool>) -> Void) { switch transaction.readTransaction { case .yapRead(let ydbTransaction): ydbTransaction.enumerateKeys(inCollection: OWSUserProfile.collection()) { (uniqueId, stop) in block(uniqueId, stop) } case .grdbRead(let grdbTransaction): grdbEnumerateUniqueIds(transaction: grdbTransaction, sql: """ SELECT \(userProfileColumn: .uniqueId) FROM \(UserProfileRecord.databaseTableName) """, batchSize: batchSize, block: block) } } // Does not order the results. class func anyFetchAll(transaction: SDSAnyReadTransaction) -> [OWSUserProfile] { var result = [OWSUserProfile]() anyEnumerate(transaction: transaction) { (model, _) in result.append(model) } return result } // Does not order the results. class func anyAllUniqueIds(transaction: SDSAnyReadTransaction) -> [String] { var result = [String]() anyEnumerateUniqueIds(transaction: transaction) { (uniqueId, _) in result.append(uniqueId) } return result } class func anyCount(transaction: SDSAnyReadTransaction) -> UInt { switch transaction.readTransaction { case .yapRead(let ydbTransaction): return ydbTransaction.numberOfKeys(inCollection: OWSUserProfile.collection()) case .grdbRead(let grdbTransaction): return UserProfileRecord.ows_fetchCount(grdbTransaction.database) } } // WARNING: Do not use this method for any models which do cleanup // in their anyWillRemove(), anyDidRemove() methods. class func anyRemoveAllWithoutInstantation(transaction: SDSAnyWriteTransaction) { switch transaction.writeTransaction { case .yapWrite(let ydbTransaction): ydbTransaction.removeAllObjects(inCollection: OWSUserProfile.collection()) case .grdbWrite(let grdbTransaction): do { try UserProfileRecord.deleteAll(grdbTransaction.database) } catch { owsFailDebug("deleteAll() failed: \(error)") } } if shouldBeIndexedForFTS { FullTextSearchFinder.allModelsWereRemoved(collection: collection(), transaction: transaction) } } class func anyRemoveAllWithInstantation(transaction: SDSAnyWriteTransaction) { // To avoid mutationDuringEnumerationException, we need // to remove the instances outside the enumeration. let uniqueIds = anyAllUniqueIds(transaction: transaction) var index: Int = 0 do { try Batching.loop(batchSize: Batching.kDefaultBatchSize, loopBlock: { stop in guard index < uniqueIds.count else { stop.pointee = true return } let uniqueId = uniqueIds[index] index = index + 1 guard let instance = anyFetch(uniqueId: uniqueId, transaction: transaction) else { owsFailDebug("Missing instance.") return } instance.anyRemove(transaction: transaction) }) } catch { owsFailDebug("Error: \(error)") } if shouldBeIndexedForFTS { FullTextSearchFinder.allModelsWereRemoved(collection: collection(), transaction: transaction) } } class func anyExists(uniqueId: String, transaction: SDSAnyReadTransaction) -> Bool { assert(uniqueId.count > 0) switch transaction.readTransaction { case .yapRead(let ydbTransaction): return ydbTransaction.hasObject(forKey: uniqueId, inCollection: OWSUserProfile.collection()) case .grdbRead(let grdbTransaction): let sql = "SELECT EXISTS ( SELECT 1 FROM \(UserProfileRecord.databaseTableName) WHERE \(userProfileColumn: .uniqueId) = ? )" let arguments: StatementArguments = [uniqueId] return try! Bool.fetchOne(grdbTransaction.database, sql: sql, arguments: arguments) ?? false } } } // MARK: - Swift Fetch public extension OWSUserProfile { class func grdbFetchCursor(sql: String, arguments: StatementArguments = StatementArguments(), transaction: GRDBReadTransaction) -> OWSUserProfileCursor { do { let sqlRequest = SQLRequest<Void>(sql: sql, arguments: arguments, cached: true) let cursor = try UserProfileRecord.fetchCursor(transaction.database, sqlRequest) return OWSUserProfileCursor(cursor: cursor) } catch { Logger.error("sql: \(sql)") owsFailDebug("Read failed: \(error)") return OWSUserProfileCursor(cursor: nil) } } class func grdbFetchOne(sql: String, arguments: StatementArguments = StatementArguments(), transaction: GRDBReadTransaction) -> OWSUserProfile? { assert(sql.count > 0) do { let sqlRequest = SQLRequest<Void>(sql: sql, arguments: arguments, cached: true) guard let record = try UserProfileRecord.fetchOne(transaction.database, sqlRequest) else { return nil } return try OWSUserProfile.fromRecord(record) } catch { owsFailDebug("error: \(error)") return nil } } } // MARK: - SDSSerializer // The SDSSerializer protocol specifies how to insert and update the // row that corresponds to this model. class OWSUserProfileSerializer: SDSSerializer { private let model: OWSUserProfile public required init(model: OWSUserProfile) { self.model = model } // MARK: - Record func asRecord() throws -> SDSRecord { let id: Int64? = nil let recordType: SDSRecordType = .userProfile let uniqueId: String = model.uniqueId // Base class properties let avatarFileName: String? = model.avatarFileName let avatarUrlPath: String? = model.avatarUrlPath let profileKey: Data? = optionalArchive(model.profileKey) let profileName: String? = model.profileName let recipientPhoneNumber: String? = model.recipientPhoneNumber let recipientUUID: String? = model.recipientUUID let userProfileSchemaVersion: UInt = model.userProfileSchemaVersion let username: String? = model.username return UserProfileRecord(id: id, recordType: recordType, uniqueId: uniqueId, avatarFileName: avatarFileName, avatarUrlPath: avatarUrlPath, profileKey: profileKey, profileName: profileName, recipientPhoneNumber: recipientPhoneNumber, recipientUUID: recipientUUID, userProfileSchemaVersion: userProfileSchemaVersion, username: username) } }
gpl-3.0
67380b267f4bd652b25f25cff9926d36
38.880399
342
0.630373
5.352954
false
false
false
false
jfosterdavis/Charles
Charles/DataViewController.swift
1
15502
// // DataViewController.swift // Charles // // Created by Jacob Foster Davis on 5/7/17. // Copyright ยฉ 2017 Zero Mu, LLC. All rights reserved. // import UIKit import AVFoundation import CoreData class DataViewController: CoreDataViewController, StoreReactor { @IBOutlet weak var characterNameLabel: UILabel! //page control @IBOutlet weak var pageControl: UIPageControl! var currentPage = 0 var numPages = 1 @IBOutlet weak var button1: UIButton! @IBOutlet weak var button2: UIButton! @IBOutlet weak var button3: UIButton! //level progress @IBOutlet weak var levelProgressView: UIProgressView! @IBOutlet weak var thisLevelLabel: UILabel! @IBOutlet weak var nextLevelLabel: UILabel! @IBOutlet weak var levelDescriptionLabel: UILabel! let progressViewProgressTintColorDefault = UIColor(red: 0.0/255.0, green: 64.0/255.0, blue: 128.0/255.0, alpha: 1) let progressViewProgressTintColorXPPerkActive = UIColor(red: 114/255.0, green: 42/255.0, blue: 183/255.0, alpha: 1) @IBOutlet weak var feedbackColorMoss: UILabel! //a hidden view only used to copy its text color @IBOutlet weak var progressViewLightTextColor: UILabel! //another hidden view var playerLevelBaseline = 0 //tracks the player level when they start an objective to compare if they made progress or not var playerProgressBaseline = 0 //tracks the player progress within the playerLevelBaseline level when they start an objective to compare if they made progress or not //and way to refer to which of the baselines in functions that do the same thing enum Baseline { case level case progress } //perk increasedScore @IBOutlet weak var perkIncreasedScoreUserFeedback: UILabel! @IBOutlet weak var perkIncreasedScoreUserFeedbackImageView: UIImageView! //perk precisionadjustment @IBOutlet weak var perkPrecisionAdjustmentUserFeedback: UIView! @IBOutlet weak var perkPrecisionAdjustmentUserFeedbackImageView: UIImageView! //Investment perk feedback //@IBOutlet weak var perkInvestmentScoreUserFeedback: UIImageView! //increasedXP @IBOutlet weak var perkIncreasedXPUserFeedbackImageView: UIImageView! //adaptation perk adaptclothing @IBOutlet weak var perkAdaptationFeedbackImageView: UIImageView! //entire view background @IBOutlet weak var backgroundView: UIView! @IBOutlet weak var topBackgroundView: UIView! //color objective and feedback @IBOutlet weak var objectiveFeedbackView: ColorMatchFeedbackView! var objectiveColor = UIColor(red: 0, green: 0, blue: 0, alpha: 1.0) //Synesthesia background blinker @IBOutlet weak var synesthesiaBackgroundBlinker: UIView! @IBOutlet weak var synesthesiaBackgroundBlinkerImageView: UIImageView! @IBOutlet weak var buttonStackViewMaskView: UIView! @IBOutlet weak var buttonStackView: UIStackView! var currentButtons = [UIButton]() //is current interaction with the character enabled var characterInteractionEnabled = true // MARK: AV Variables //continue audio from outside apps let audioSession = AVAudioSession.sharedInstance() //game audio let synth = AVSpeechSynthesizer() var textUtterance = AVSpeechUtterance(string: "") var audioPlayer: AVAudioPlayer! var audioEngine: AVAudioEngine! var audioPlayerNode: AVAudioPlayerNode! var changePitchEffect: AVAudioUnitTimePitch! //AV for Game Sounds (not character sounds_ var audioPlayerGameSounds: AVAudioPlayer! var audioEngineGameSounds: AVAudioEngine! var audioPlayerNodeGameSounds: AVAudioPlayerNode! var changePitchEffectGameSounds: AVAudioUnitTimePitch! //Synesthesia var audioPlayerNodeSynesthesia: AVAudioPlayerNode! var synesthesiaReverb: AVAudioUnitReverb! var synesthesiaDistortion: AVAudioUnitDistortion! //CoreData let keyCurrentScore = "CurrentScore" let keyXP = "keyXP" // MARK: Score var timer = Timer() @IBOutlet weak var justScoredLabel: UILabel! @IBOutlet weak var justScoredMessageLabel: UILabel! var pointsToLoseEachCycle = 20 //constants let minimumScoreToUnlockObjective = 600 let minimumScoreToUnlockStore = 300 let minimumLevelToUnlockMap = 11 //color stick view for Insight @IBOutlet weak var perkStickViewDeviation: InsightColorStickView! //Store @IBOutlet weak var storeButton: UIButton! @IBOutlet weak var mapButton: UIButton! @IBOutlet weak var scoreLabel: UILabel! var parentVC: ModelController! var dataObject: Character! var currentPhrase: Phrase! var currentSubphraseIndex = 0 override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. //allow outside audio (like from Music App) do { try audioSession.setCategory(AVAudioSessionCategoryPlayback, with: [.duckOthers, .allowAirPlay]) try audioSession.setActive(true) }catch{ // handle error } //audio audioEngine = AVAudioEngine() audioPlayer = AVAudioPlayer() //setup node audioPlayerNode = AVAudioPlayerNode() audioEngine.attach(audioPlayerNode) changePitchEffect = AVAudioUnitTimePitch() audioEngine.attach(changePitchEffect) audioEngine.connect(audioPlayerNode, to: changePitchEffect, format: nil) audioEngine.connect(changePitchEffect, to: audioEngine.outputNode, format: nil) //Synesthesia effects audioPlayerNodeSynesthesia = AVAudioPlayerNode() synesthesiaReverb = AVAudioUnitReverb() synesthesiaReverb.loadFactoryPreset(AVAudioUnitReverbPreset.plate) synesthesiaReverb.wetDryMix = 5 audioEngine.attach(synesthesiaReverb) synesthesiaDistortion = AVAudioUnitDistortion() synesthesiaDistortion.loadFactoryPreset(AVAudioUnitDistortionPreset.speechWaves) synesthesiaDistortion.wetDryMix = 0 audioEngine.attach(synesthesiaDistortion) //setup the same for the game sounds audioEngineGameSounds = AVAudioEngine() audioPlayerGameSounds = AVAudioPlayer() //setup node audioPlayerNodeGameSounds = AVAudioPlayerNode() audioEngineGameSounds.attach(audioPlayerNodeGameSounds) changePitchEffectGameSounds = AVAudioUnitTimePitch() audioEngineGameSounds.attach(changePitchEffectGameSounds) audioEngineGameSounds.connect(audioPlayerNodeGameSounds, to: changePitchEffectGameSounds, format: nil) audioEngineGameSounds.connect(changePitchEffectGameSounds, to: audioEngineGameSounds.outputNode, format: nil) //setup CoreData _ = setupFetchedResultsController(frcKey: keyCurrentScore, entityName: "CurrentScore", sortDescriptors: [], predicate: nil) _ = setupFetchedResultsController(frcKey: keyXP, entityName: "XP", sortDescriptors: [], predicate: nil) //set opacity of elements storeButton.alpha = 0 storeButton.isEnabled = false thisLevelLabel.alpha = 0.0 nextLevelLabel.alpha = 0 scoreLabel.alpha = 0 mapButton.alpha = 0 mapButton.isEnabled = false perkIncreasedScoreUserFeedback.alpha = 0 perkPrecisionAdjustmentUserFeedback.alpha = 0 perkStickViewDeviation.alpha = 0 perkIncreasedScoreUserFeedbackImageView.alpha = 0 perkPrecisionAdjustmentUserFeedbackImageView.alpha = 0 synesthesiaBackgroundBlinkerImageView.alpha = 0 perkIncreasedXPUserFeedbackImageView.alpha = 0 perkAdaptationFeedbackImageView.alpha = 0 //setup the color feedback view to recieve touches registerTouchRecognizerColorFeedback() //delegates //add placeholder buttons to the array of buttons currentButtons = [button1, button2, button3] //load the background based on the level setBackground(from: getUserCurrentLevel(), animate: false) //set the page control refreshPageControl() //mask the stackview roundStackViewMask() //add a listener so can tell when app enters background NotificationCenter.default.addObserver(self, selector: #selector(appEnteredBackground), name:NSNotification.Name.UIApplicationDidEnterBackground, object: nil) //housekeeping checkXPAndConsolidateIfNeccessary(consolidateAt: 300) //with 144 levels, should be plenty to prevent too much of this. //reducePlayerLevel(to: 144) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @objc override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.characterNameLabel!.text = dataObject.name //set opacity of elements //storeButton.alpha = 0 perkStickViewDeviation.alpha = 0 //set up the game initialLoadGame() //setup the score refreshScore() //if there is only one character, hide the page control, otherwise show if numPages > 1 { setPageControl(visible: true) } else { setPageControl(visible: false) } //stop the timer to avoide stacking penalties timer.invalidate() //start the timer timer = Timer.scheduledTimer(timeInterval: 5, target: self, selector: #selector(updateTimer), userInfo: nil, repeats: true) } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) //reloadButtons() } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() //round the button corners self.roundButtonCorners(topRadius: self.dataObject.topRadius, bottomRadius: self.dataObject.bottomRadius) roundStackViewMask() // perkPrecisionAdjustmentUserFeedback.roundCorners(with: 10) // storeButton.roundCorners(with: 5) // perkStoreButton.roundCorners(with: 5) // characterNameLabel.roundCorners(with: 5) // scoreLabel.roundCorners(with: 5) } override func viewDidDisappear(_ animated: Bool) { //stop the timer to avoide stacking penalties timer.invalidate() } /******************************************************/ /*******************///MARK: Page Control /******************************************************/ func refreshPageControl(){ //set the page control self.pageControl.numberOfPages = numPages self.pageControl.currentPage = currentPage self.pageControl.updateCurrentPageDisplay() } func setPageControl(visible: Bool) { self.pageControl.isHidden = !visible } /******************************************************/ /*******************///MARK: Storyboard and Interface /******************************************************/ func roundStackViewMask() { buttonStackViewMaskView.layer.masksToBounds = true let maskLayer = CAShapeLayer() maskLayer.path = UIBezierPath(roundedRect: buttonStackViewMaskView.bounds, byRoundingCorners: [.bottomLeft, .bottomRight], cornerRadii: CGSize(width: 15, height: 15)).cgPath buttonStackViewMaskView.layer.mask = maskLayer } /******************************************************/ /*******************///MARK: Misc /******************************************************/ func storeClosed() { let pVC = self.parentVC! pVC.storeClosed() //fade in and out the store buttons //self.storeButton.isHidden = false //self.storeButton.alpha = 1 //allow user to access the stores for a few seconds //fadeViewInThenOut(view: self.storeButton, fadeOutAfterSeconds: 6.3) // self.storeButton.fade(.inOrOut, resultAlpha: 0.3, // withDuration: 1, // delay: 3) // // //only control the perk store if the player level is above minimum + 2 // if self.getUserCurrentLevel().level > (self.minimumLevelToUnlockMap + 2) { // self.mapButton.fade(.inOrOut, resultAlpha: 0.3, // withDuration: 1, // delay: 3) // } } ///to be called by the entered background observer. presses the store button. @objc func appEnteredBackground(notification : NSNotification) { let characterLevel = getUserCurrentLevel() if characterLevel.level >= Levels.ReturnToDarknessLevelFirst.level && characterLevel.level <= Levels.ReturnToDarknessLevelLast.level { //user is in returning to darkness level of the game, so should see the store, not the map storeButtonPressed(self) } else if characterLevel.level > 10 { mapButtonPressed(self) } else { storeButtonPressed(self) } } /******************************************************/ /*******************///MARK: UI Button Actions /******************************************************/ @IBAction func storeButtonPressed(_ sender: Any) { //stop the timer timer.invalidate() // Create a new view controller and pass suitable data. let storeViewController = self.storyboard!.instantiateViewController(withIdentifier: "Store") as! StoreCollectionViewController //link this VC storeViewController.parentVC = self //pass the score storeViewController.score = getCurrentScore() //if this was called without the button, slide it in from bottom if sender as? DataViewController == self { storeViewController.modalTransitionStyle = .coverVertical } present(storeViewController, animated: true, completion: nil) } @IBAction func mapButtonPressed(_ sender: Any) { //stop the timer timer.invalidate() // Create a new view controller and pass suitable data. let mapViewController = self.storyboard!.instantiateViewController(withIdentifier: "MapCollectionViewController") as! MapCollectionViewController let currentLevel = getUserCurrentLevel().level mapViewController.initialLevelToScrollTo = currentLevel if isPlayerAtHighestLevelAndProgress() { //player is on last level mapViewController.playerHasFinishedInitialLevelToScrollTo = true mapViewController.includeDollarSignWhenSharing = true } else { mapViewController.playerHasFinishedInitialLevelToScrollTo = false } present(mapViewController, animated: true, completion: nil) } }
apache-2.0
19bbd0767043f0d3d9f3e267b3ba6867
34.965197
181
0.640539
5.290444
false
false
false
false
tonyli508/ObjectMapperDeep
ObjectMapper/Core/Map.swift
1
6468
// // Map.swift // ObjectMapper // // Created by Tristan Himmelman on 2015-10-09. // // The MIT License (MIT) // // Copyright (c) 2014-2015 Hearst // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation /// Required field assertion public class MapRequiredField { /** change this to achive different verification purpose, * like in test setUp function you may want to do this to turn on 'required field verification': MapRequiredField.assume = { (condition: Bool, message: String) in XCTAssert(condition, message) } * */ public static var assume = { (condition: Bool, message: String) in assert(condition, message) } } /// A class used for holding mapping data public final class Map { public let mappingType: MappingType public internal(set) var JSONDictionary: [String : AnyObject] = [:] public var currentValue: AnyObject? var currentKey: String? var keyIsNested = false // use this to mark is a required field to verify server response var isRequiredField = false let toObject: Bool // indicates whether the mapping is being applied to an existing object /// Counter for failing cases of deserializing values to `let` properties. private var failedCount: Int = 0 public init(mappingType: MappingType, JSONDictionary: [String : AnyObject], toObject: Bool = false) { self.mappingType = mappingType self.JSONDictionary = JSONDictionary self.toObject = toObject } /// Sets the current mapper value and key. /// The Key paramater can be a period separated string (ex. "distance.value") to access sub objects. public subscript(key: String) -> Map { // save key and value associated to it let nested = key.containsString(".") return self[key, nested: nested] } /// Mark property is a required field public subscript(key: String, required isRequired: Bool) -> Map { isRequiredField = isRequired let map = self[key, nested: true] // when is required, only verify server response for now // could be useful for POST as well, ehnnn.... if isRequiredField && mappingType == MappingType.FromJSON { // FIXME: somehow this doesn't work in unit test, so only ui test will trigger this which sucks MapRequiredField.assume(currentValue != nil, "\(key) is a required field, should not be nil") } return map } public subscript(key: String, nested nested: Bool) -> Map { // save key and value associated to it currentKey = key keyIsNested = nested // check if a value exists for the current key if nested == false { currentValue = JSONDictionary[key] } else { // break down the components of the key that are separated by . currentValue = valueFor(ArraySlice(key.componentsSeparatedByString(".")), dictionary: JSONDictionary) } return self } // MARK: Immutable Mapping public func value<T>() -> T? { return currentValue as? T } public func valueOr<T>(@autoclosure defaultValue: () -> T) -> T { return value() ?? defaultValue() } /// Returns current JSON value of type `T` if it is existing, or returns a /// unusable proxy value for `T` and collects failed count. public func valueOrFail<T>() -> T { if let value: T = value() { return value } else { // Collects failed count failedCount++ // Returns dummy memory as a proxy for type `T` let pointer = UnsafeMutablePointer<T>.alloc(0) pointer.dealloc(0) return pointer.memory } } /// Returns whether the receiver is success or failure. public var isValid: Bool { return failedCount == 0 } } /// Fetch value from JSON dictionary, loop through keyPathComponents until we reach the desired object private func valueFor(keyPathComponents: ArraySlice<String>, dictionary: [String: AnyObject]) -> AnyObject? { // Implement it as a tail recursive function. if keyPathComponents.isEmpty { return nil } if let keyPath = keyPathComponents.first { let object = dictionary[keyPath] if object is NSNull { return nil } else if let dict = object as? [String : AnyObject] where keyPathComponents.count > 1 { let tail = keyPathComponents.dropFirst() return valueFor(tail, dictionary: dict) } else if let array = object as? [AnyObject] where keyPathComponents.count > 1 { let tail = keyPathComponents.dropFirst() return valueFor(tail, dictionary: array) } else { return object } } return nil } /// Fetch value from JSON Array, loop through keyPathComponents them until we reach the desired object private func valueFor(keyPathComponents: ArraySlice<String>, dictionary: [AnyObject]) -> AnyObject? { if keyPathComponents.isEmpty { return nil } //Try to convert keypath to Int as index if let keyPath = keyPathComponents.first, let index = Int(keyPath) where index >= 0 && index < dictionary.count { let object = dictionary[index] if object is NSNull { return nil } else if let array = object as? [AnyObject] where keyPathComponents.count > 1 { let tail = keyPathComponents.dropFirst() return valueFor(tail, dictionary: array) } else if let dict = object as? [String : AnyObject] where keyPathComponents.count > 1 { let tail = keyPathComponents.dropFirst() return valueFor(tail, dictionary: dict) } else if let array = object as? [AnyObject] where keyPathComponents.count > 1 { let tail = keyPathComponents.dropFirst() return valueFor(tail, dictionary: array) } else { return object } } return nil }
mit
e3e4d72c79697674de15de9538daa55b
31.179104
109
0.71645
3.995059
false
false
false
false
blockchain/My-Wallet-V3-iOS
Modules/BlockchainNamespace/Tests/BlockchainNamespaceTests/Tag/Tag+ReferenceTests.swift
1
3280
@testable import BlockchainNamespace import XCTest final class TagReferenceTests: XCTestCase { let app = App() let id = "0d98d78bdba916ee6b556c2a39abd55f1adda467d319f8d492ea3df9c662671d" func test_reference_to_user() throws { let ref = try blockchain.user.name.first[] .ref(to: [blockchain.user.id: id]) .validated() XCTAssertFalse(ref.hasError) XCTAssertEqual(ref.indices[blockchain.user.id], id) XCTAssertEqual(ref.string, "blockchain.user.name.first") XCTAssertEqual(ref.id(ignoring: [blockchain.user.id[]]), "blockchain.user.name.first") XCTAssertEqual(ref.id(ignoring: []), "blockchain.user[\(id)].name.first") } func test_reference_with_invalid_indices() throws { let ref = blockchain.user.name.first[].reference XCTAssertThrowsError(try ref.validated()) XCTAssertNotNil(ref.error) } func test_reference_to_user_with_additional_context() throws { let ref = blockchain.user.name.first[] .ref( to: [ blockchain.user.id: id, blockchain.app.configuration.apple.pay.is.enabled: true ] ) XCTAssertEqual(ref.indices, [blockchain.user.id[]: id]) XCTAssertEqual( ref.context, Tag.Context( [ blockchain.user.id[]: id, blockchain.app.configuration.apple.pay.is.enabled[]: true ] ) ) } func test_init_id() throws { do { let ref = try Tag.Reference(id: "blockchain.user.name.first", in: app.language) XCTAssertEqual(ref.string, "blockchain.user.name.first") } do { let ref = try Tag.Reference(id: "blockchain.user[\(id)].name.first", in: app.language) XCTAssertEqual(ref.string, "blockchain.user.name.first") XCTAssertEqual(ref.context[blockchain.user.id], id) } do { let ref = try Tag.Reference(id: "blockchain.user[id].name.first", in: app.language) XCTAssertEqual(ref.string, "blockchain.user.name.first") XCTAssertEqual(ref.context[blockchain.user.id], "id") } do { let ref = try Tag.Reference(id: "blockchain.user[blockchain.user.id].name.first", in: app.language) XCTAssertEqual(ref.string, "blockchain.user.name.first") XCTAssertEqual(ref.context[blockchain.user.id], "blockchain.user.id") } } func test_init_id_missing_indices() throws { do { let ref = try Tag.Reference(id: "blockchain.user.name.first", in: app.language) XCTAssertEqual(ref.string, "blockchain.user.name.first") try ref.validated() } catch let error as Tag.Error { XCTAssertEqual(error.message, "Missing index blockchain.user.id for ref to blockchain.user.name.first") } } func test_ref_fetch_indices_from_state() throws { app.state.set(blockchain.user.id, to: id) let ref = try blockchain.user.name.first[] .ref(in: app) .validated() XCTAssertEqual(ref.indices[blockchain.user.id], id) } }
lgpl-3.0
1f272747d77d09dd3c0bdc5e0b32c002
34.268817
115
0.592378
4.004884
false
true
false
false
googlearchive/science-journal-ios
ScienceJournal/Extensions/UIView+ScienceJournal.swift
1
6653
/* * Copyright 2019 Google LLC. 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 extension UIView { struct Edge: OptionSet { let rawValue: Int static let top = Edge(rawValue: 1 << 0) static let trailing = Edge(rawValue: 1 << 1) static let leading = Edge(rawValue: 1 << 2) static let bottom = Edge(rawValue: 1 << 3) } /// Pin one view's anchors to the edges of another's. /// /// - Parameters: /// - toView: The view to pin to. /// - edges: The edges to pin to. /// - insets: Insets to apply to constant values for constraints. func pinToEdgesOfView(_ toView: UIView, andEdges edges: [Edge] = [.top, .trailing, .leading, .bottom], withInsets insets: UIEdgeInsets = .zero) { if edges.contains(.top) { topAnchor.constraint(equalTo: toView.topAnchor, constant: insets.top).isActive = true } if edges.contains(.leading) { leadingAnchor.constraint(equalTo: toView.leadingAnchor, constant: insets.left).isActive = true } if edges.contains(.trailing) { trailingAnchor.constraint(equalTo: toView.trailingAnchor, constant: -insets.right).isActive = true } if edges.contains(.bottom) { bottomAnchor.constraint(equalTo: toView.bottomAnchor, constant: -insets.bottom).isActive = true } } /// Animates the rotation transform of a view. /// /// - Parameters: /// - rotationAngle: The rotation transform, in radians, to animate to. /// - fromAngle: The rotation transform, in radians, to animate from. /// - duration: The duration of the rotation. func animateRotationTransform(to rotationAngle: CGFloat, from fromAngle: CGFloat, duration: TimeInterval) { let rotateAnimation = CABasicAnimation(keyPath: "transform.rotation") rotateAnimation.fromValue = fromAngle rotateAnimation.toValue = rotationAngle rotateAnimation.duration = duration rotateAnimation.isRemovedOnCompletion = false rotateAnimation.fillMode = .forwards rotateAnimation.timingFunction = CAMediaTimingFunction.init(name: .easeInEaseOut) layer.add(rotateAnimation, forKey: "rotate") } /// Creates a rotate and move animation that simulates a view rolling along a horizontal distance. /// Assumes view's constraints will reflect final position. /// /// - Parameters: /// - distance: The distance to roll. /// - duration: The duration of the roll. func animateRollRotationTransform(forDistance distance: CGFloat, duration: TimeInterval) { let percentCircumference = Double(abs(distance)) / (.pi * Double(frame.width)) let radiansToRotate = 2 * .pi * percentCircumference var fromRadians: CGFloat var toRadians: CGFloat if distance <= 0 { fromRadians = CGFloat(radiansToRotate) toRadians = 0 } else { fromRadians = 0 toRadians = CGFloat(radiansToRotate) } let moveAnimation = CABasicAnimation(keyPath: "transform.translation.x") moveAnimation.fromValue = -distance moveAnimation.duration = duration moveAnimation.fillMode = .forwards moveAnimation.timingFunction = CAMediaTimingFunction.init(name: .easeInEaseOut) layer.add(moveAnimation, forKey: "rollRotationMove") animateRotationTransform(to: toRadians, from: fromRadians, duration: duration) } /// Configures an accessibility wrapping view. /// /// - Parameters: /// - view: The view to configure. /// - label: The accessibility label. /// - hint: The optional accessibility hint. /// - traits: The optional accessibility traits. Defaults to UIAccessibilityTraitButton if not /// provided. func configureAccessibilityWrappingView(_ view: UIView, withLabel label: String? = nil, hint: String? = nil, traits: UIAccessibilityTraits = .button) { addSubview(view) view.translatesAutoresizingMaskIntoConstraints = false view.isAccessibilityElement = true view.accessibilityLabel = label view.accessibilityHint = hint view.accessibilityTraits = traits view.pinToEdgesOfView(self) sendSubviewToBack(view) } /// Returns the safe area insets if available, otherwise zero. var safeAreaInsetsOrZero: UIEdgeInsets { var insets: UIEdgeInsets = .zero if #available(iOS 11.0, *) { insets = safeAreaInsets } return insets } /// Adjusts the frame for user interface layout direction, if needed for RTL, assuming the frame /// is set for LTR. If there is no container width passed in, the width of the superview's bounds /// will be used, unless superview is nil, in which case this method does nothing. /// /// - Parameter containerWidth: The width of the containing bounds. func adjustFrameForLayoutDirection(inWidth containerWidth: CGFloat? = nil) { var containerWidth: CGFloat? { if let containerWidth = containerWidth { return containerWidth } else { // Use the width of the superview's bounds if there is no container width passed in. return superview?.bounds.width } } // If a container width was not passed in and the view does not have a superview, return. guard UIApplication.shared.userInterfaceLayoutDirection == .rightToLeft, let width = containerWidth else { return } frame.origin.x = width - frame.origin.x - frame.width } /// Returns an image snapshot of a view. var imageSnapshot: UIImage? { UIGraphicsBeginImageContextWithOptions(bounds.size, false, UIScreen.main.scale) defer { UIGraphicsEndImageContext() } guard let context = UIGraphicsGetCurrentContext() else { return nil } layer.render(in: context) return UIGraphicsGetImageFromCurrentImageContext() } }
apache-2.0
8712f6e92a4e3f05fd30686cdc08411b
38.135294
100
0.659251
4.902727
false
false
false
false
JulianNicholls/Uber-Clone
ParseStarterProject/AppDelegate.swift
2
7257
/** * Copyright (c) 2015-present, Parse, LLC. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ import UIKit import Parse // If you want to use any of the UI components, uncomment this line // import ParseUI // If you want to use Crash Reporting - uncomment this line // import ParseCrashReporting @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? //-------------------------------------- // MARK: - UIApplicationDelegate //-------------------------------------- func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Enable storing and querying data from Local Datastore. // Remove this line if you don't want to use Local Datastore features or want to use cachePolicy. Parse.enableLocalDatastore() // **************************************************************************** // Uncomment this line if you want to enable Crash Reporting // ParseCrashReporting.enable() // // Uncomment and fill in with your Parse credentials: Parse.setApplicationId("iS4npqe6xuRrSaeSY7xIJdRDyaGeXn1SE5y3q5c5", clientKey: "q8OySP8wORq9gYb2NWDAW28bsy6skFSgX0a89MT6") // // If you are using Facebook, uncomment and add your FacebookAppID to your bundle's plist as // described here: https://developers.facebook.com/docs/getting-started/facebook-sdk-for-ios/ // Uncomment the line inside ParseStartProject-Bridging-Header and the following line here: // PFFacebookUtils.initializeFacebook() // **************************************************************************** PFUser.enableAutomaticUser() let defaultACL = PFACL(); // If you would like all objects to be private by default, remove this line. defaultACL.setPublicReadAccess(true) PFACL.setDefaultACL(defaultACL, withAccessForCurrentUser:true) if application.applicationState != UIApplicationState.Background { // Track an app open here if we launch with a push, unless // "content_available" was used to trigger a background push (introduced in iOS 7). // In that case, we skip tracking here to avoid double counting the app-open. let preBackgroundPush = !application.respondsToSelector("backgroundRefreshStatus") let oldPushHandlerOnly = !self.respondsToSelector("application:didReceiveRemoteNotification:fetchCompletionHandler:") var noPushPayload = false; if let options = launchOptions { noPushPayload = options[UIApplicationLaunchOptionsRemoteNotificationKey] != nil; } if (preBackgroundPush || oldPushHandlerOnly || noPushPayload) { PFAnalytics.trackAppOpenedWithLaunchOptions(launchOptions) } } // // Swift 1.2 // // if application.respondsToSelector("registerUserNotificationSettings:") { // let userNotificationTypes = UIUserNotificationType.Alert | UIUserNotificationType.Badge | UIUserNotificationType.Sound // let settings = UIUserNotificationSettings(forTypes: userNotificationTypes, categories: nil) // application.registerUserNotificationSettings(settings) // application.registerForRemoteNotifications() // } else { // let types = UIRemoteNotificationType.Badge | UIRemoteNotificationType.Alert | UIRemoteNotificationType.Sound // application.registerForRemoteNotificationTypes(types) // } // // Swift 2.0 // // if #available(iOS 8.0, *) { // let types: UIUserNotificationType = [.Alert, .Badge, .Sound] // let settings = UIUserNotificationSettings(forTypes: types, categories: nil) // application.registerUserNotificationSettings(settings) // application.registerForRemoteNotifications() // } else { // let types: UIRemoteNotificationType = [.Alert, .Badge, .Sound] // application.registerForRemoteNotificationTypes(types) // } return true } //-------------------------------------- // MARK: Push Notifications //-------------------------------------- func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) { let installation = PFInstallation.currentInstallation() installation.setDeviceTokenFromData(deviceToken) installation.saveInBackground() PFPush.subscribeToChannelInBackground("") { (succeeded: Bool, error: NSError?) in if succeeded { print("UberAlles successfully subscribed to push notifications on the broadcast channel.\n"); } else { print("UberAlles failed to subscribe to push notifications on the broadcast channel with error = %@.\n", error) } } } func application(application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: NSError) { if error.code == 3010 { // print("Push notifications are not supported in the iOS Simulator.\n") } else { print("application:didFailToRegisterForRemoteNotificationsWithError: %@\n", error) } } func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) { PFPush.handlePush(userInfo) if application.applicationState == UIApplicationState.Inactive { PFAnalytics.trackAppOpenedWithRemoteNotificationPayload(userInfo) } } /////////////////////////////////////////////////////////// // Uncomment this method if you want to use Push Notifications with Background App Refresh /////////////////////////////////////////////////////////// // func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject], fetchCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void) { // if application.applicationState == UIApplicationState.Inactive { // PFAnalytics.trackAppOpenedWithRemoteNotificationPayload(userInfo) // } // } //-------------------------------------- // MARK: Facebook SDK Integration //-------------------------------------- /////////////////////////////////////////////////////////// // Uncomment this method if you are using Facebook /////////////////////////////////////////////////////////// // func application(application: UIApplication, openURL url: NSURL, sourceApplication: String?, annotation: AnyObject?) -> Bool { // return FBAppCall.handleOpenURL(url, sourceApplication:sourceApplication, session:PFFacebookUtils.session()) // } }
mit
c6679082048042629fcb730d67e86d34
45.819355
193
0.609894
5.861874
false
false
false
false
cornerstonecollege/402
402_2016_2/MovingLinesAndShapes/MovingLinesAndShapes/ViewController.swift
1
2915
// // ViewController.swift // MovingLinesAndShapes // // Created by Luiz on 2016-11-02. // Copyright ยฉ 2016 Ideia do Luiz. All rights reserved. // import UIKit class ViewController: UIViewController { var objArray = [CircleView]() var lineArray = [LineView]() var selectedCircle:CircleView? override func viewDidLoad() { super.viewDidLoad() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func tap(_ sender: AnyObject) { let posX = arc4random_uniform(UInt32(self.view.frame.width - 100)) let posY = arc4random_uniform(UInt32(self.view.frame.height - 100)) let circleFrame = CGRect(x: Int(posX), y: Int(posY), width: 100, height: 100) let circle = CircleView(frame: circleFrame) //circle.backgroundColor = UIColor.yellow self.view.addSubview(circle) self.objArray += [circle] self.updateLines() } func updateLines() { for (idx, circle) in objArray.enumerated() { // clear if it is dirty if idx != objArray.count - 1 && circle.line1 == nil || circle.line2 == nil { lineArray = [LineView]() } } var circle1:CircleView? var circle2:CircleView? if lineArray.count == 0 && objArray.count > 1 { for i in 0...objArray.count - 2 { circle1 = objArray[i] circle2 = objArray[i+1] } } else if lineArray.count > 0 && objArray.count > 2 { circle1 = objArray[objArray.count-2] circle2 = objArray[objArray.count-1] } if circle1 != nil && circle2 != nil { let line = LineView(circle1: circle1!, circle2:circle2!, superView:self.view) self.lineArray += [line] self.view.addSubview(line) } } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { if touches.first != nil { let point = touches.first!.location(in: self.view) for circle in self.objArray { if circle.frame.contains(point) { self.selectedCircle = circle break } } } } override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) { if let touch = touches.first { if selectedCircle != nil { self.selectedCircle!.center = touch.location(in: self.view) self.selectedCircle?.line1?.setNeedsDisplay() self.selectedCircle?.line2?.setNeedsDisplay() } } } override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { self.selectedCircle = nil } }
gpl-3.0
9e3c5beae75996f49e7ac6025b839de5
30.333333
89
0.557653
4.368816
false
false
false
false
Antondomashnev/Sourcery
Pods/XcodeEdit/Sources/PBXObject.swift
1
5749
// // PBXObject.swift // XcodeEdit // // Created by Tom Lokhorst on 2015-08-29. // Copyright ยฉ 2015 nonstrict. All rights reserved. // import Foundation typealias JsonObject = [String: AnyObject] public /* abstract */ class PBXObject { let id: String let dict: JsonObject let allObjects: AllObjects public lazy var isa: String = self.string("isa")! public required init(id: String, dict: AnyObject, allObjects: AllObjects) { self.id = id self.dict = dict as! JsonObject self.allObjects = allObjects } func bool(_ key: String) -> Bool? { guard let string = dict[key] as? String else { return nil } switch string { case "0": return false case "1": return true default: return nil } } func string(_ key: String) -> String? { return dict[key] as? String } func strings(_ key: String) -> [String]? { return dict[key] as? [String] } func object<T : PBXObject>(_ key: String) -> T? { guard let objectKey = dict[key] as? String else { return nil } let obj: T = allObjects.object(objectKey) return obj } func object<T : PBXObject>(_ key: String) -> T { let objectKey = dict[key] as! String return allObjects.object(objectKey) } func objects<T : PBXObject>(_ key: String) -> [T] { let objectKeys = dict[key] as! [String] return objectKeys.map(allObjects.object) } } public /* abstract */ class PBXContainer : PBXObject { } public class PBXProject : PBXContainer { public lazy var developmentRegion: String = self.string("developmentRegion")! public lazy var hasScannedForEncodings: Bool = self.bool("hasScannedForEncodings")! public lazy var knownRegions: [String] = self.strings("knownRegions")! public lazy var targets: [PBXNativeTarget] = self.objects("targets") public lazy var mainGroup: PBXGroup = self.object("mainGroup") public lazy var buildConfigurationList: XCConfigurationList = self.object("buildConfigurationList") } public /* abstract */ class PBXContainerItem : PBXObject { } public class PBXContainerItemProxy : PBXContainerItem { } public /* abstract */ class PBXProjectItem : PBXContainerItem { } public class PBXBuildFile : PBXProjectItem { public lazy var fileRef: PBXReference? = self.object("fileRef") } public /* abstract */ class PBXBuildPhase : PBXProjectItem { public lazy var files: [PBXBuildFile] = self.objects("files") } public class PBXCopyFilesBuildPhase : PBXBuildPhase { public lazy var name: String? = self.string("name") } public class PBXFrameworksBuildPhase : PBXBuildPhase { } public class PBXHeadersBuildPhase : PBXBuildPhase { } public class PBXResourcesBuildPhase : PBXBuildPhase { } public class PBXShellScriptBuildPhase : PBXBuildPhase { public lazy var name: String? = self.string("name") public lazy var shellScript: String = self.string("shellScript")! } public class PBXSourcesBuildPhase : PBXBuildPhase { } public class PBXBuildStyle : PBXProjectItem { } public class XCBuildConfiguration : PBXBuildStyle { public lazy var name: String = self.string("name")! } public /* abstract */ class PBXTarget : PBXProjectItem { public lazy var buildConfigurationList: XCConfigurationList = self.object("buildConfigurationList") public lazy var name: String = self.string("name")! public lazy var productName: String = self.string("productName")! public lazy var buildPhases: [PBXBuildPhase] = self.objects("buildPhases") } public class PBXAggregateTarget : PBXTarget { } public class PBXNativeTarget : PBXTarget { } public class PBXTargetDependency : PBXProjectItem { } public class XCConfigurationList : PBXProjectItem { } public class PBXReference : PBXContainerItem { public lazy var name: String? = self.string("name") public lazy var path: String? = self.string("path") public lazy var sourceTree: SourceTree = self.string("sourceTree").flatMap(SourceTree.init)! } public class PBXFileReference : PBXReference { // convenience accessor public lazy var fullPath: Path = self.allObjects.fullFilePaths[self.id]! } public class PBXReferenceProxy : PBXReference { // convenience accessor public lazy var remoteRef: PBXContainerItemProxy = self.object("remoteRef") } public class PBXGroup : PBXReference { public lazy var children: [PBXReference] = self.objects("children") // convenience accessors public lazy var subGroups: [PBXGroup] = self.children.ofType(PBXGroup.self) public lazy var fileRefs: [PBXFileReference] = self.children.ofType(PBXFileReference.self) } public class PBXVariantGroup : PBXGroup { } public class XCVersionGroup : PBXReference { } public enum SourceTree { case absolute case group case relativeTo(SourceTreeFolder) init?(sourceTreeString: String) { switch sourceTreeString { case "<absolute>": self = .absolute case "<group>": self = .group default: guard let sourceTreeFolder = SourceTreeFolder(rawValue: sourceTreeString) else { return nil } self = .relativeTo(sourceTreeFolder) } } } public enum SourceTreeFolder: String { case sourceRoot = "SOURCE_ROOT" case buildProductsDir = "BUILT_PRODUCTS_DIR" case developerDir = "DEVELOPER_DIR" case sdkRoot = "SDKROOT" } public enum Path { case absolute(String) case relativeTo(SourceTreeFolder, String) public func url(with urlForSourceTreeFolder: (SourceTreeFolder) -> URL) -> URL { switch self { case let .absolute(absolutePath): return URL(fileURLWithPath: absolutePath).standardizedFileURL case let .relativeTo(sourceTreeFolder, relativePath): let sourceTreeURL = urlForSourceTreeFolder(sourceTreeFolder) return sourceTreeURL.appendingPathComponent(relativePath).standardizedFileURL } } }
mit
7539b013b5bfd859cfcaf8334810bc3f
25.127273
101
0.720772
4.171263
false
false
false
false
sammyd/iOSDevUK-StackViews
StackReview/PancakeHouse.swift
6
4298
/* * Copyright (c) 2015 Razeware LLC * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ import UIKit import CoreLocation enum PriceGuide : Int { case Unknown = 0 case Low = 1 case Medium = 2 case High = 3 } extension PriceGuide : CustomStringConvertible { var description : String { switch self { case .Unknown: return "?" case .Low: return "$" case .Medium: return "$$" case .High: return "$$$" } } } enum PancakeRating { case Unknown case Rating(Int) } extension PancakeRating { init?(value: Int) { if value > 0 && value <= 5 { self = .Rating(value) } else { self = .Unknown } } } extension PancakeRating { var ratingImage : UIImage? { guard let baseName = ratingImageName else { return nil } return UIImage(named: baseName) } var smallRatingImage : UIImage? { guard let baseName = ratingImageName else { return nil } return UIImage(named: "\(baseName)_small") } private var ratingImageName : String? { switch self { case .Unknown: return nil case .Rating(let value): return "pancake_rate_\(value)" } } } struct PancakeHouse { let name: String let photo: UIImage? let thumbnail: UIImage? let priceGuide: PriceGuide let location: CLLocationCoordinate2D? let details: String let rating: PancakeRating let city: String } extension PancakeHouse { init?(dict: [String : AnyObject]) { guard let name = dict["name"] as? String, let priceGuideRaw = dict["priceGuide"] as? Int, let priceGuide = PriceGuide(rawValue: priceGuideRaw), let details = dict["details"] as? String, let ratingRaw = dict["rating"] as? Int, let rating = PancakeRating(value: ratingRaw), let city = dict["city"] as? String else { return nil } self.name = name self.priceGuide = priceGuide self.details = details self.rating = rating self.city = city if let imageName = dict["imageName"] as? String where !imageName.isEmpty { photo = UIImage(named: imageName) } else { photo = nil } if let thumbnailName = dict["thumbnailName"] as? String where !thumbnailName.isEmpty { thumbnail = UIImage(named: thumbnailName) } else { thumbnail = nil } if let latitude = dict["latitude"] as? Double, let longitude = dict["longitude"] as? Double { location = CLLocationCoordinate2D(latitude: latitude, longitude: longitude) } else { location = nil } } } extension PancakeHouse { static func loadDefaultPancakeHouses() -> [PancakeHouse]? { return self.loadPancakeHousesFromPlistNamed("pancake_houses") } static func loadPancakeHousesFromPlistNamed(plistName: String) -> [PancakeHouse]? { guard let path = NSBundle.mainBundle().pathForResource(plistName, ofType: "plist"), let array = NSArray(contentsOfFile: path) as? [[String : AnyObject]] else { return nil } return array.map { PancakeHouse(dict: $0) } .filter { $0 != nil } .map { $0! } } } extension PancakeHouse : CustomStringConvertible { var description : String { return "\(name) :: \(details)" } }
mit
7c791c87b90539f985834183d6495fbc
25.207317
90
0.659842
4.247036
false
false
false
false
evermeer/PassportScanner
Pods/EVGPUImage2/framework/Source/iOS/MovieOutput.swift
1
11749
import AVFoundation public protocol AudioEncodingTarget { func activateAudioTrack() func processAudioBuffer(_ sampleBuffer:CMSampleBuffer) } public class MovieOutput: ImageConsumer, AudioEncodingTarget { public let sources = SourceContainer() public let maximumInputs:UInt = 1 let assetWriter:AVAssetWriter let assetWriterVideoInput:AVAssetWriterInput var assetWriterAudioInput:AVAssetWriterInput? let assetWriterPixelBufferInput:AVAssetWriterInputPixelBufferAdaptor let size:Size let colorSwizzlingShader:ShaderProgram private var isRecording = false private var videoEncodingIsFinished = false private var audioEncodingIsFinished = false private var startTime:CMTime? private var previousFrameTime = kCMTimeNegativeInfinity private var previousAudioTime = kCMTimeNegativeInfinity private var encodingLiveVideo:Bool var pixelBuffer:CVPixelBuffer? = nil var renderFramebuffer:Framebuffer! var transform:CGAffineTransform { get { return assetWriterVideoInput.transform } set { assetWriterVideoInput.transform = transform } } public init(URL:Foundation.URL, size:Size, fileType:AVFileType = AVFileType.mov, liveVideo:Bool = false, settings:[String:AnyObject]? = nil) throws { if sharedImageProcessingContext.supportsTextureCaches() { self.colorSwizzlingShader = sharedImageProcessingContext.passthroughShader } else { self.colorSwizzlingShader = crashOnShaderCompileFailure("MovieOutput"){try sharedImageProcessingContext.programForVertexShader(defaultVertexShaderForInputs(1), fragmentShader:ColorSwizzlingFragmentShader)} } self.size = size assetWriter = try AVAssetWriter(url:URL, fileType:fileType) // Set this to make sure that a functional movie is produced, even if the recording is cut off mid-stream. Only the last second should be lost in that case. assetWriter.movieFragmentInterval = CMTimeMakeWithSeconds(1.0, 1000) var localSettings:[String:AnyObject] if let settings = settings { localSettings = settings } else { localSettings = [String:AnyObject]() } localSettings[AVVideoWidthKey] = localSettings[AVVideoWidthKey] ?? NSNumber(value:size.width) localSettings[AVVideoHeightKey] = localSettings[AVVideoHeightKey] ?? NSNumber(value:size.height) localSettings[AVVideoCodecKey] = localSettings[AVVideoCodecKey] ?? AVVideoCodecH264 as NSString assetWriterVideoInput = AVAssetWriterInput(mediaType:AVMediaType.video, outputSettings:localSettings) assetWriterVideoInput.expectsMediaDataInRealTime = liveVideo encodingLiveVideo = liveVideo // You need to use BGRA for the video in order to get realtime encoding. I use a color-swizzling shader to line up glReadPixels' normal RGBA output with the movie input's BGRA. let sourcePixelBufferAttributesDictionary:[String:AnyObject] = [kCVPixelBufferPixelFormatTypeKey as String:NSNumber(value:Int32(kCVPixelFormatType_32BGRA)), kCVPixelBufferWidthKey as String:NSNumber(value:size.width), kCVPixelBufferHeightKey as String:NSNumber(value:size.height)] assetWriterPixelBufferInput = AVAssetWriterInputPixelBufferAdaptor(assetWriterInput:assetWriterVideoInput, sourcePixelBufferAttributes:sourcePixelBufferAttributesDictionary) assetWriter.add(assetWriterVideoInput) } public func startRecording(transform:CGAffineTransform? = nil) { if let transform = transform { assetWriterVideoInput.transform = transform } startTime = nil sharedImageProcessingContext.runOperationSynchronously{ self.isRecording = self.assetWriter.startWriting() CVPixelBufferPoolCreatePixelBuffer(nil, self.assetWriterPixelBufferInput.pixelBufferPool!, &self.pixelBuffer) /* AVAssetWriter will use BT.601 conversion matrix for RGB to YCbCr conversion * regardless of the kCVImageBufferYCbCrMatrixKey value. * Tagging the resulting video file as BT.601, is the best option right now. * Creating a proper BT.709 video is not possible at the moment. */ CVBufferSetAttachment(self.pixelBuffer!, kCVImageBufferColorPrimariesKey, kCVImageBufferColorPrimaries_ITU_R_709_2, .shouldPropagate) CVBufferSetAttachment(self.pixelBuffer!, kCVImageBufferYCbCrMatrixKey, kCVImageBufferYCbCrMatrix_ITU_R_601_4, .shouldPropagate) CVBufferSetAttachment(self.pixelBuffer!, kCVImageBufferTransferFunctionKey, kCVImageBufferTransferFunction_ITU_R_709_2, .shouldPropagate) let bufferSize = GLSize(self.size) var cachedTextureRef:CVOpenGLESTexture? = nil let _ = CVOpenGLESTextureCacheCreateTextureFromImage(kCFAllocatorDefault, sharedImageProcessingContext.coreVideoTextureCache, self.pixelBuffer!, nil, GLenum(GL_TEXTURE_2D), GL_RGBA, bufferSize.width, bufferSize.height, GLenum(GL_BGRA), GLenum(GL_UNSIGNED_BYTE), 0, &cachedTextureRef) let cachedTexture = CVOpenGLESTextureGetName(cachedTextureRef!) self.renderFramebuffer = try! Framebuffer(context:sharedImageProcessingContext, orientation:.portrait, size:bufferSize, textureOnly:false, overriddenTexture:cachedTexture) } } public func finishRecording(_ completionCallback:(() -> Void)? = nil) { sharedImageProcessingContext.runOperationSynchronously{ self.isRecording = false if (self.assetWriter.status == .completed || self.assetWriter.status == .cancelled || self.assetWriter.status == .unknown) { sharedImageProcessingContext.runOperationAsynchronously{ completionCallback?() } return } if ((self.assetWriter.status == .writing) && (!self.videoEncodingIsFinished)) { self.videoEncodingIsFinished = true self.assetWriterVideoInput.markAsFinished() } if ((self.assetWriter.status == .writing) && (!self.audioEncodingIsFinished)) { self.audioEncodingIsFinished = true self.assetWriterAudioInput?.markAsFinished() } // Why can't I use ?? here for the callback? if let callback = completionCallback { self.assetWriter.finishWriting(completionHandler: callback) } else { self.assetWriter.finishWriting{} } } } public func newFramebufferAvailable(_ framebuffer:Framebuffer, fromSourceIndex:UInt) { defer { framebuffer.unlock() } guard isRecording else { return } // Ignore still images and other non-video updates (do I still need this?) guard let frameTime = framebuffer.timingStyle.timestamp?.asCMTime else { return } // If two consecutive times with the same value are added to the movie, it aborts recording, so I bail on that case guard (frameTime != previousFrameTime) else { return } if (startTime == nil) { if (assetWriter.status != .writing) { assetWriter.startWriting() } assetWriter.startSession(atSourceTime: frameTime) startTime = frameTime } // TODO: Run the following on an internal movie recording dispatch queue, context guard (assetWriterVideoInput.isReadyForMoreMediaData || (!encodingLiveVideo)) else { debugPrint("Had to drop a frame at time \(frameTime)") return } if !sharedImageProcessingContext.supportsTextureCaches() { let pixelBufferStatus = CVPixelBufferPoolCreatePixelBuffer(nil, assetWriterPixelBufferInput.pixelBufferPool!, &pixelBuffer) guard ((pixelBuffer != nil) && (pixelBufferStatus == kCVReturnSuccess)) else { return } } renderIntoPixelBuffer(pixelBuffer!, framebuffer:framebuffer) if (!assetWriterPixelBufferInput.append(pixelBuffer!, withPresentationTime:frameTime)) { debugPrint("Problem appending pixel buffer at time: \(frameTime)") } CVPixelBufferUnlockBaseAddress(pixelBuffer!, CVPixelBufferLockFlags(rawValue:CVOptionFlags(0))) if !sharedImageProcessingContext.supportsTextureCaches() { pixelBuffer = nil } } func renderIntoPixelBuffer(_ pixelBuffer:CVPixelBuffer, framebuffer:Framebuffer) { if !sharedImageProcessingContext.supportsTextureCaches() { renderFramebuffer = sharedImageProcessingContext.framebufferCache.requestFramebufferWithProperties(orientation:framebuffer.orientation, size:GLSize(self.size)) renderFramebuffer.lock() } renderFramebuffer.activateFramebufferForRendering() clearFramebufferWithColor(Color.black) CVPixelBufferLockBaseAddress(pixelBuffer, CVPixelBufferLockFlags(rawValue:CVOptionFlags(0))) renderQuadWithShader(colorSwizzlingShader, uniformSettings:ShaderUniformSettings(), vertexBufferObject:sharedImageProcessingContext.standardImageVBO, inputTextures:[framebuffer.texturePropertiesForOutputRotation(.noRotation)]) if sharedImageProcessingContext.supportsTextureCaches() { glFinish() } else { glReadPixels(0, 0, renderFramebuffer.size.width, renderFramebuffer.size.height, GLenum(GL_RGBA), GLenum(GL_UNSIGNED_BYTE), CVPixelBufferGetBaseAddress(pixelBuffer)) renderFramebuffer.unlock() } } // MARK: - // MARK: Audio support public func activateAudioTrack() { // TODO: Add ability to set custom output settings assetWriterAudioInput = AVAssetWriterInput(mediaType:AVMediaType.audio, outputSettings:nil) assetWriter.add(assetWriterAudioInput!) assetWriterAudioInput?.expectsMediaDataInRealTime = encodingLiveVideo } public func processAudioBuffer(_ sampleBuffer:CMSampleBuffer) { guard let assetWriterAudioInput = assetWriterAudioInput else { return } sharedImageProcessingContext.runOperationSynchronously{ let currentSampleTime = CMSampleBufferGetOutputPresentationTimeStamp(sampleBuffer) if (self.startTime == nil) { if (self.assetWriter.status != .writing) { self.assetWriter.startWriting() } self.assetWriter.startSession(atSourceTime: currentSampleTime) self.startTime = currentSampleTime } guard (assetWriterAudioInput.isReadyForMoreMediaData || (!self.encodingLiveVideo)) else { return } if (!assetWriterAudioInput.append(sampleBuffer)) { print("Trouble appending audio sample buffer") } } } } public extension Timestamp { public init(_ time:CMTime) { self.value = time.value self.timescale = time.timescale self.flags = TimestampFlags(rawValue:time.flags.rawValue) self.epoch = time.epoch } public var asCMTime:CMTime { get { return CMTimeMakeWithEpoch(value, timescale, epoch) } } }
bsd-3-clause
ae7dd58ef18345defc76ed668d969f48
47.751037
295
0.673164
5.839463
false
false
false
false
hermantai/samples
ios/SwiftUI-Cookbook-2nd-Edition/Chapter13-Handling-Core-Data-in-SwiftUI/06-Present-data-in-a-sectioned-list-with-@SectionedFetchRequest/SectionedContacts/SectionedContacts/CoreDataStack.swift
4
1198
// // CoreDataStack.swift // CoreDataStack // // Created by Giordano Scalzo on 02/09/2021. // import Foundation import CoreData class CoreDataStack: ObservableObject { private let persistentContainer: NSPersistentContainer var managedObjectContext: NSManagedObjectContext { persistentContainer.viewContext } init(modelName: String) { persistentContainer = { let container = NSPersistentContainer(name: modelName) container.loadPersistentStores { description, error in if let error = error { print(error) } } return container }() } func save () { guard managedObjectContext.hasChanges else { return } do { try managedObjectContext.save() } catch { print(error) } } func insertContact(firstName: String, lastName: String, phoneNumber: String) { let contact = Contact(context: managedObjectContext) contact.firstName = firstName contact.lastName = lastName contact.phoneNumber = phoneNumber } }
apache-2.0
84c6ba481b9333603cfe64256419c423
25.043478
66
0.588481
5.872549
false
false
false
false
fguchelaar/AdventOfCode2016
AdventOfCode2016/aoc-day16/main.swift
1
1371
// // main.swift // aoc-day16 // // Created by Frank Guchelaar on 16/12/2016. // Copyright ยฉ 2016 Awesomation. All rights reserved. // import Foundation extension Collection where Iterator.Element == Bool { func dragonCurve(length: Int) -> Array<Bool> { let selfAsArray = (self as! [Bool]) let dragonCurve = selfAsArray + [false] + selfAsArray.reversed().map{ !$0 } if dragonCurve.count < length { return dragonCurve.dragonCurve(length: length) } return [Bool](dragonCurve.prefix(length)) } func checksum() -> Array<Bool> { let selfAsArray = (self as! [Bool]) var checksum = [Bool](repeating: false, count: selfAsArray.count/2) for idx in stride(from: 0, to: selfAsArray.count, by: 2) { checksum[idx/2] = (selfAsArray[idx] == selfAsArray[idx.advanced(by: 1)]) } if checksum.count % 2 == 0 { return checksum.checksum() } return checksum } } var input = "10001001100000001".characters.map { $0 == "1" } // Part One print("--- PART ONE ---") measure { print ("Checksum: \(input.dragonCurve(length: 272).checksum().map { $0 ? "1" : "0" }.joined())") } // Part Two print("--- PART TWO ---") measure { print ("Checksum: \(input.dragonCurve(length: 35651584).checksum().map { $0 ? "1" : "0" }.joined())") }
mit
309bd9dfb5fd63eaacfcb183fdb912d4
28.782609
105
0.591241
3.503836
false
false
false
false
mirego/PinLayout
Sources/PinLayout+Between.swift
1
7235
// Copyright (c) 2017 Luc Dion // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. #if os(iOS) || os(tvOS) import UIKit #else import AppKit #endif extension PinLayout { // // horizontallyBetween(...) // @discardableResult public func horizontallyBetween(_ view1: View, and view2: View, aligned: VerticalAlign = .none) -> PinLayout { func context() -> String { return betweenContext("horizontallyBetween", view1, view2, aligned) } guard self.view != view1 && self.view != view2 else { warnWontBeApplied("the view being layouted cannot be used as one of the references.", context) return self } guard view1 != view2 else { warnWontBeApplied("reference views must be different.", context) return self } let anchors: [Anchor] switch aligned { case .top: anchors = [view1.anchor.topLeft, view1.anchor.topRight, view2.anchor.topLeft, view2.anchor.topRight] case .center: anchors = [view1.anchor.centerLeft, view1.anchor.centerRight, view2.anchor.centerLeft, view2.anchor.centerRight] case .bottom: anchors = [view1.anchor.bottomLeft, view1.anchor.bottomRight, view2.anchor.bottomLeft, view2.anchor.bottomRight] case .none: anchors = [view1.anchor.topLeft, view1.anchor.topRight, view2.anchor.topLeft, view2.anchor.topRight] } guard let coordinates = computeCoordinates(forAnchors: anchors, context), coordinates.count == anchors.count else { return self } let view1MinX = coordinates[0].x let view1MaxX = coordinates[1].x let view2MinX = coordinates[2].x let view2MaxX = coordinates[3].x if view1MaxX <= view2MinX { setLeft(view1MaxX, context) setRight(view2MinX, context) applyVerticalAlignment(aligned, coordinates: [coordinates[0]], context: context) } else if view2MaxX <= view1MinX { setLeft(view2MaxX, context) setRight(view1MinX, context) applyVerticalAlignment(aligned, coordinates: [coordinates[1]], context: context) } else { guard Pin.logWarnings && Pin.activeWarnings.noSpaceAvailableBetweenViews else { return self } warnWontBeApplied("there is no horizontal space between these views. (noSpaceAvailableBetweenViews)", context) } return self } // // verticallyBetween(...) // @discardableResult public func verticallyBetween(_ view1: View, and view2: View, aligned: HorizontalAlign = .none) -> PinLayout { func context() -> String { return betweenContext("verticallyBetween", view1, view2, aligned) } guard self.view != view1 && self.view != view2 else { warnWontBeApplied("the view being layouted cannot be used as one of the references.", context) return self } guard view1 != view2 else { warnWontBeApplied("reference views must be different.", context) return self } let anchors: [Anchor] switch aligned { case .left: anchors = [view1.anchor.topLeft, view1.anchor.bottomLeft, view2.anchor.topLeft, view2.anchor.bottomLeft] case .center: anchors = [view1.anchor.topCenter, view1.anchor.bottomCenter, view2.anchor.topCenter, view2.anchor.bottomCenter] case .right: anchors = [view1.anchor.topRight, view1.anchor.bottomRight, view2.anchor.topRight, view2.anchor.bottomRight] case .start: anchors = isLTR() ? [view1.anchor.topLeft, view1.anchor.bottomLeft, view2.anchor.topLeft, view2.anchor.bottomLeft] : [view1.anchor.topRight, view1.anchor.bottomRight, view2.anchor.topRight, view2.anchor.bottomRight] case .end: anchors = isLTR() ? [view1.anchor.topRight, view1.anchor.bottomRight, view2.anchor.topRight, view2.anchor.bottomRight] : [view1.anchor.topLeft, view1.anchor.bottomLeft, view2.anchor.topLeft, view2.anchor.bottomLeft] case .none: anchors = [view1.anchor.topLeft, view1.anchor.bottomLeft, view2.anchor.topLeft, view2.anchor.bottomLeft] } guard let coordinates = computeCoordinates(forAnchors: anchors, context), coordinates.count == anchors.count else { return self } let view1MinY = coordinates[0].y let view1MaxY = coordinates[1].y let view2MinY = coordinates[2].y let view2MaxY = coordinates[3].y if view1MaxY <= view2MinY { setTop(view1MaxY, context) setBottom(view2MinY, context) applyHorizontalAlignment(aligned, coordinates: [coordinates[0]], context: context) } else if view2MaxY <= view1MinY { setTop(view2MaxY, context) setBottom(view1MinY, context) applyHorizontalAlignment(aligned, coordinates: [coordinates[1]], context: context) } else { guard Pin.logWarnings && Pin.activeWarnings.noSpaceAvailableBetweenViews else { return self } warnWontBeApplied("there is no vertical space between these views. (noSpaceAvailableBetweenViews)", context) } return self } } // MARK: private extension PinLayout { fileprivate func betweenContext(_ type: String, _ view1: View, _ view2: View, _ aligned: HorizontalAlign) -> String { return betweenContext(type, view1, view2, aligned: aligned == HorizontalAlign.none ? nil : aligned.description) } fileprivate func betweenContext(_ type: String, _ view1: View, _ view2: View, _ aligned: VerticalAlign) -> String { return betweenContext(type, view1, view2, aligned: aligned == VerticalAlign.none ? nil : aligned.description) } private func betweenContext(_ type: String, _ view1: View, _ view2: View, aligned: String?) -> String { if let aligned = aligned { return "\(type)(\(viewDescription(view1)), \(viewDescription(view1)), aligned: .\(aligned))" } else { return "\(type)(\(viewDescription(view1)), \(viewDescription(view1)))" } } }
mit
fab3075760eaff7a411a6ef8f8d063e8
47.885135
134
0.660954
4.281065
false
false
false
false
DrabWeb/Komikan
Komikan/Komikan/KMMetadataFetcherViewController.swift
1
14371
// // KMMetadataFetcherViewController.swift // Komikan // // Created by Seth on 2016-02-27. // import Cocoa import Alamofire class KMMetadataFetcherViewController: NSViewController { /// The visual effect view for the background of the popover @IBOutlet var backgroundVisualEffectView: NSVisualEffectView! /// The view to animate transitions between views in the popover @IBOutlet var viewContainer: NSView! /// The view for searching for the series to grab the metadata from @IBOutlet var searchViewContainer: NSView! /// The view for applying the properties of the chosen series @IBOutlet var applyingViewContainer: NSView! /// The NSSearchField for the user to search for the series they want the metadata for @IBOutlet var seriesSearchField: NSSearchField! /// When text is entered into seriesSearchField... @IBAction func seriesSearchFieldInteracted(_ sender: AnyObject) { // Clear the results table seriesSearchResultsItems.removeAll(); // Search for the entered text _ = KMMetadataFetcher().searchForManga(seriesSearchField.stringValue, completionHandler: searchCompletionHandler); } /// The table view for the search results of the series search @IBOutlet var seriesSearchResultsTableView: NSTableView! /// The popup button in the apply properties view to choose whether or not to change the series @IBOutlet var applyPropertiesSeriesPopupButton: NSPopUpButton! /// The popup button in the apply properties view to choose whether or not to change the artist @IBOutlet var applyPropertiesArtistPopupButton: NSPopUpButton! /// The popup button in the apply properties view to choose whether or not to change the writer @IBOutlet var applyPropertiesWritersPopupButton: NSPopUpButton! /// The popup button in the apply properties view to choose whether or not to change the tags @IBOutlet var applyPropertiesTagsPopupButton: NSPopUpButton! /// The popup button in the apply properties view to choose whether or not to change the cover, and if so what cover to use @IBOutlet var applyPropertiesCoverPopupButton: KMMetadataFetcherCoverSelectionPopUpButton! /// The checkbox for the apply properties view to say if we want to append tags @IBOutlet var applyPropertiesAppendTagsCheckbox: NSButton! /// When we click the "Apply" button in the apply properties view... @IBAction func applyPropertiesApplyButtonPressed(_ sender: AnyObject) { // Dismiss the popover self.dismiss(self); // Apply the metadata applyMetadata(); } /// The items for the series search results table view var seriesSearchResultsItems : [KMMetadataFetcherSeriesSearchResultsItemData] = []; /// The KMMangaGridItem we have selected in the manga grid var selectedMangaGridItems : [KMMangaGridItem] = []; /// The series metadata the user selected var seriesMetadata : KMSeriesMetadata = KMSeriesMetadata(); override func viewDidLoad() { super.viewDidLoad() // Do view setup here. // Style the window styleWindow(); /// All the names of the series of the selected manga var selectedMangaSeries : [String] = []; // For every selected manga grid item... for(_, currentMangaGridItem) in selectedMangaGridItems.enumerated() { // Add this grid item's manga's series to the selected manga's series array selectedMangaSeries.append(currentMangaGridItem.manga.series); } // Set the search field to have the most frequent series seriesSearchField.stringValue = selectedMangaSeries.frequencies()[0].0; // Search for the series search fields string value _ = KMMetadataFetcher().searchForManga(seriesSearchField.stringValue, completionHandler: searchCompletionHandler); } /// Applys the chosen metadata to the selected manga func applyMetadata() { // Print to the log that we are applying metadata print("KMMetadataFetcherViewController: Applying metadata to selected manga"); // For every manga grid item in the selected manga grid item... for(_, currentMangaGridItem) in selectedMangaGridItems.enumerated() { /// The current items manga with the new modified values let modifiedManga : KMManga = currentMangaGridItem.manga; // If we said to set the series... if(applyPropertiesSeriesPopupButton.selectedItem?.title != "Dont Change") { // Set the series of the current manga to the selected series modifiedManga.series = applyPropertiesSeriesPopupButton.selectedItem!.title; } // If we said to set the artists... if(applyPropertiesArtistPopupButton.selectedItem?.title != "Dont Change") { // Set the artists of the current manga to the selected artists modifiedManga.artist = applyPropertiesArtistPopupButton.selectedItem!.title; } // If we said to set the writers... if(applyPropertiesWritersPopupButton.selectedItem?.title != "Dont Change") { // Set the writers of the current manga to the selected writers modifiedManga.writer = applyPropertiesWritersPopupButton.selectedItem!.title; } // If we said to set the tags... if(applyPropertiesTagsPopupButton.selectedItem?.title != "Dont Change") { // If we said to append the tags... if(Bool(applyPropertiesAppendTagsCheckbox.state as NSNumber)) { // Append the metadatas tags to the current manga's tags modifiedManga.tags.append(contentsOf: seriesMetadata.tags); } // If we said to replace the tags... else { // Replace the current manga's tags with the metadata's tags modifiedManga.tags = seriesMetadata.tags; } } // If we said to set the cover... if(applyPropertiesCoverPopupButton.selectedItem?.title != "Dont Change") { // Set the current manga's cover to the chosen cover modifiedManga.coverImage = applyPropertiesCoverPopupButton.selectedItem!.image!; } // Change the current grid items manga to the modified manga currentMangaGridItem.changeManga(modifiedManga); // Print to the log what manga we applied the metadata to print("KMMetadataFetcherViewController: Applied fetched metadata to \"" + modifiedManga.title + "\""); } // Post the notification to say we are done applying metadata NotificationCenter.default.post(name: Notification.Name(rawValue: "KMMetadataFetcherViewController.Finished"), object: nil); } // This will get called when the series search is completed func searchCompletionHandler(_ searchResults : [KMMetadataInfo]?, error : NSError?) { // If there were any search results... if(!(searchResults!.isEmpty)) { // For every item in the results of the search... for(_, currentItem) in searchResults!.enumerated() { // Add the current item's title and MU ID to the series search results table seriesSearchResultsItems.append(KMMetadataFetcherSeriesSearchResultsItemData(seriesName: currentItem.title, seriesId: currentItem.id)); } // Reload the search results table view seriesSearchResultsTableView.reloadData(); } // If there were no search results... else { // Clear the search results table seriesSearchResultsItems.removeAll(); // Reload the search results table view seriesSearchResultsTableView.reloadData(); } } // This will get called when the metadata fetching is completed func seriesMetadataCompletionHandler(_ metadata : KMSeriesMetadata?, error : NSError?) { // Set the series metadata seriesMetadata = metadata!; // Transition in the applying view viewContainer.animator().replaceSubview(searchViewContainer, with: applyingViewContainer); // Add the title and alternate titles to the series popup applyPropertiesSeriesPopupButton.addItem(withTitle: metadata!.title); applyPropertiesSeriesPopupButton.addItems(withTitles: metadata!.alternateTitles); // Add the writers to the writers popup applyPropertiesWritersPopupButton.addItem(withTitle: metadata!.writers.listString()); // Add the artists to the artists popup applyPropertiesArtistPopupButton.addItem(withTitle: metadata!.artists.listString()); // Add the tags to the tags popup applyPropertiesTagsPopupButton.addItem(withTitle: metadata!.tags.listString()); // For evert cover URL... for(_, currentCover) in metadata!.coverURLs.enumerated() { // Download the cover image Alamofire.request(currentCover.absoluteString.removingPercentEncoding!) .responseData { response in // If data isnt nil... if let data = response.result.value { /// The downloaded image let image : NSImage? = NSImage(data: data); // If image isnt nil... if(image != nil) { // The new menu item we will add to the covers popup let newCoverItem : NSMenuItem = NSMenuItem(); // Set the new items image to the cover we downloaded newCoverItem.image = image; // Clear the title of the new item newCoverItem.title = ""; // Resize the new items cover to 400 height newCoverItem.image = newCoverItem.image?.resizeToHeight(400); // Add the new itme to the covers popup self.applyPropertiesCoverPopupButton.menu?.addItem(newCoverItem); // Select the first cover self.applyPropertiesCoverPopupButton.selectItem(at: 2); } } }; } // Select the first added item in all the popups applyPropertiesSeriesPopupButton.selectItem(at: 2); applyPropertiesWritersPopupButton.selectItem(at: 2); applyPropertiesArtistPopupButton.selectItem(at: 2); applyPropertiesTagsPopupButton.selectItem(at: 2); } /// Styles the window func styleWindow() { // Set the background to be more vibrant backgroundVisualEffectView.material = .dark; } } extension KMMetadataFetcherViewController: NSTableViewDelegate { func numberOfRows(in aTableView: NSTableView) -> Int { // Return the amount of series search result items return self.seriesSearchResultsItems.count; } func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? { /// The cell view it is asking us about for the data let cellView : NSTableCellView = tableView.make(withIdentifier: tableColumn!.identifier, owner: self) as! NSTableCellView; // If the column is the Main Column... if(tableColumn!.identifier == "Main Column") { // If the item at the wanted index exists... if(row < self.seriesSearchResultsItems.count) { /// This items search result item data let seriesSearchResultListItemData = self.seriesSearchResultsItems[row]; // Set the label's string value to the search results item data cellView.textField!.stringValue = seriesSearchResultListItemData.seriesName; /// Set the data of the cell (cellView as? KMMetadataFetcherSeriesSearchResultsTableViewCell)?.data = seriesSearchResultListItemData; /// Set the cell's button's action to call seriesSearchResultItemPressed (cellView as? KMMetadataFetcherSeriesSearchResultsTableViewCell)?.selectButton.action = #selector(KMMetadataFetcherViewController.seriesSearchResultItemPressed(_:)); // Return the modified cell view return cellView; } } // Return the unmodified cell view, we didnt need to do anything to this one return cellView; } /// Called when we click on an item in the series search results func seriesSearchResultItemPressed(_ sender : AnyObject?) { /// The sender converted to KMMetadataFetcherSeriesSearchResultsTableViewCell let senderCell : KMMetadataFetcherSeriesSearchResultsTableViewCell = ((sender as! NSButton).superview as? KMMetadataFetcherSeriesSearchResultsTableViewCell)!; // Print to the log what teh user selectedand its ID print("KMMetadataFetcherViewController: Chose \"" + senderCell.data.seriesName + "\", ID:", senderCell.data.seriesId); /// The metadata info we will use to get the metadata for the selected item let metadataInfo : KMMetadataInfo = KMMetadataInfo(title: senderCell.data.seriesName, id: senderCell.data.seriesId); // Call the metadata getter so we can load the metadata _ = KMMetadataFetcher().getSeriesMetadata(metadataInfo, completionHandler: seriesMetadataCompletionHandler); } } extension KMMetadataFetcherViewController: NSTableViewDataSource { }
gpl-3.0
b851551b041b48cf7135e3169e21b814
46.429043
181
0.630645
5.523059
false
false
false
false
mrange/swift_streams
test_perf/src/main.swift
1
1883
// ---------------------------------------------------------------------------------------------- // Copyright 2015 Mรฅrten Rรฅnge // // 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. // ---------------------------------------------------------------------------------------------- var errors = 0 func test__tight_loop () { print (__FUNCTION__) var acc : Int64 = 0 for outer in 1...10000 { acc += from_start (1, toEnd: outer + 1) |> fold (0) { $0 + $1 } } print (acc) } func test__built_in () { print (__FUNCTION__) var acc : Int64 = 0 for outer in 1...10000 { acc += (1...outer).reduce (0) { $0 + $1 } } print (acc) } // ----------------------------------------------------------------------------- // ----------------------------------------------------------------------------- // ---==> TEST RUNNER <==-- // ----------------------------------------------------------------------------- // ----------------------------------------------------------------------------- let test_cases = [ test__built_in // , test__tight_loop ] for test_case in test_cases { // TODO: Catch exceptions test_case () } if errors == 0 { print ("All tests passed!") } else { print ("\(errors) test(s) failed!") } // -----------------------------------------------------------------------------
apache-2.0
5d8e113880a9199fdfacca6a79b618be
26.26087
97
0.41361
4.726131
false
true
false
false
atuooo/notGIF
notGIF/Controllers/SidebarTagList/SidebarTagListViewController.swift
1
6832
// // SideBarViewController.swift // notGIF // // Created by ooatuoo on 2017/6/1. // Copyright ยฉ 2017ๅนด xyz. All rights reserved. // import UIKit import RealmSwift import IQKeyboardManagerSwift class SidebarTagListViewController: UIViewController { fileprivate var tagResult: Results<Tag>! fileprivate var notifiToken: NotificationToken? fileprivate var selectTag: Tag! fileprivate var isEditingTag: Bool { return IQKeyboardManager.sharedManager().keyboardShowing } @IBOutlet weak var settingButton: UIButton! { didSet { settingButton.tintColor = UIColor.textTint.withAlphaComponent(0.8) settingButton.setTitleColor(UIColor.textTint.withAlphaComponent(0.8), for: .normal) settingButton.setTitle(String.trans_titleSettings, for: .normal) } } @IBOutlet weak var tableView: UITableView! { didSet { tableView.registerNibOf(TagListCell.self) tableView.tableFooterView = UIView() tableView.rowHeight = TagListCell.height } } @IBOutlet weak var addTagTextField: AddTagTextField! { didSet { addTagTextField.addTagHandler = { name in self.addTag(with: name) } } } @IBAction func showSettings(_ sender: Any) { present(UIStoryboard.settingNav, animated: true) { let drawer = self.parent as? DrawerViewController drawer?.showOrDissmissSideBar() } } override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = UIColor.sideBarBg guard let realm = try? Realm() else { return } if let tag = realm.object(ofType: Tag.self, forPrimaryKey: NGUserDefaults.lastSelectTagID) { selectTag = tag } else { selectTag = realm.object(ofType: Tag.self, forPrimaryKey: Config.defaultTagID) NGUserDefaults.lastSelectTagID = Config.defaultTagID } tagResult = realm.objects(Tag.self).sorted(byKeyPath: "createDate", ascending: false) notifiToken = tagResult.addNotificationBlock { [weak self] changes in guard let tableView = self?.tableView else { return } switch changes { case .initial: tableView.reloadData() case .update(_, let deletions, let insertions, let modifications): tableView.beginUpdates() tableView.insertRows(at: insertions.map{ IndexPath(row: $0, section: 0) }, with: .bottom) tableView.deleteRows(at: deletions.map{ IndexPath(row: $0, section: 0) }, with: .left) tableView.reloadRows(at: modifications.map{ IndexPath(row: $0, section: 0) }, with: .fade) tableView.endUpdates() case .error(let err): printLog(err.localizedDescription) } } } deinit { notifiToken?.stop() notifiToken = nil } } extension SidebarTagListViewController: UITableViewDelegate, UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return tagResult == nil ? 0 : tagResult.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell: TagListCell = tableView.dequeueReusableCell() let tag = tagResult[indexPath.item] cell.configure(with: tag, isSelected: selectTag.isInvalidated ? false : tag.id == selectTag.id) cell.editDoneHandler = { [weak self] text in guard let realm = try? Realm(), let sSelf = self, let editIP = tableView.indexPath(for: cell) else { return } try? realm.write { realm.add(sSelf.tagResult[editIP.item].update(with: text), update: true) } } return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { defer { tableView.deselectRow(at: indexPath, animated: true) } guard !isEditingTag else { return } selectTag = tagResult[indexPath.item] tableView.reloadData() (parent as? DrawerViewController)?.dismissSideBar() NotificationCenter.default.post(name: .didSelectTag, object: selectTag) } func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? { let actionSize = CGSize(width: 40, height: TagListCell.height) let editRowAction = UITableViewRowAction(size: actionSize, image: #imageLiteral(resourceName: "icon_tag_edit"), bgColor: .clear) { [weak self] (_, rowActionIP) in self?.beginEditTag(at: rowActionIP) } let deleteRowAction = UITableViewRowAction(size: actionSize, image: #imageLiteral(resourceName: "icon_tag_delete"), bgColor: .clear) { [weak self] (_, rowActionIP) in guard let sSelf = self else { return } Alert.show(.confirmDeleteTag(sSelf.tagResult[indexPath.item].name)) { self?.deleteTag(at: rowActionIP) } } return [editRowAction, deleteRowAction] } func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { return !isEditingTag && tagResult[indexPath.item].id != Config.defaultTagID } } // MARK: - Helper Method extension SidebarTagListViewController { fileprivate func beginEditTag(at indexPath: IndexPath) { guard let cell = tableView.cellForRow(at: indexPath) as? TagListCell else { return } tableView.setEditing(false, animated: true) cell.beginEdit() } fileprivate func deleteTag(at indexPath: IndexPath) { guard let realm = try? Realm() else { return } let tag = tagResult[indexPath.item] if tag.id == selectTag.id { // ่‹ฅๅˆ ้™คๅฝ“ๅ‰้€‰ไธญ Tag๏ผŒๅˆ™ๅฐ† gif ๅˆ—่กจๆ›ดๆ–ฐ่‡ณ้ป˜่ฎคๆ ‡็ญพ selectTag = tagResult[0] tableView.reloadRows(at: [IndexPath(row: 0, section: 0)], with: .fade) NotificationCenter.default.post(name: .didSelectTag, object: selectTag) } try? realm.write { realm.delete(tag) } } fileprivate func addTag(with name: String) { guard let realm = try? Realm() else { return } tableView.setEditing(false, animated: true) tableView.setContentOffset(.zero, animated: true) DispatchQueue.main.after(0.3) { try? realm.write { realm.add(Tag(name: name)) } } } }
mit
0091be97befd6b93832a72e6f5510351
34.742105
174
0.611103
4.725818
false
false
false
false
HuangJinyong/iOSDEV
JYTextField/JYTextField/JYTextField.swift
1
2091
// // JYTextField.swift // JYTextField // // Created by Jinyong on 2016/10/14. // Copyright ยฉ 2016ๅนด Jinyong. All rights reserved. // import UIKit class JYTextField: UITextField { private var password: String = "" // ็ผ“ๅญ˜ๅฏ†็  private var beginEditingObserver: AnyObject! //ๆณจๅ†Œ้”ฎ็›˜ๅณๅฐ†ๅผ€ๅง‹่พ“ๅ…ฅ็š„้€š็Ÿฅ private var endEditingObserver: AnyObject! // ๆณจๅ†Œ้”ฎ็›˜ๅณๅฐ†ๅฎŒๆˆ่พ“ๅ…ฅ็š„้€š็Ÿฅ override init(frame: CGRect) { super.init(frame: frame) awakeFromNib() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override func awakeFromNib() { // ็›‘ๅฌๆ–‡ๆœฌๆก†็š„่พ“ๅ…ฅ็Šถๆ€ beginEditingObserver = NotificationCenter.default.addObserver(forName: NSNotification.Name.UITextFieldTextDidBeginEditing, object: nil, queue: nil, using: { (note) in // ๅฝ“็›‘ๅฌๅˆฐๆ–‡ๆœฌๆก†ๅผ€ๅง‹ๅ‡†ๅค‡่พ“ๅ…ฅๆ—ถ๏ผŒๅฆ‚ๆžœๅฏ†็ ๆ˜ฏ้š่—๏ผŒๅ…ˆๅฐ†็ผ“ๅญ˜ๅฏ†็ ่ฟ˜ๅŽŸ๏ผŒๅ†่ฟ›่กŒ่พ“ๅ…ฅใ€‚ if self == note.object as! JYTextField && self.isSecureTextEntry { self.text = "" self.insertText(self.password) } }) endEditingObserver = NotificationCenter.default.addObserver(forName: NSNotification.Name.UITextFieldTextDidEndEditing, object: nil, queue: nil, using: { (note) in // ๅฎŒๆˆ่พ“ๅ…ฅๆ—ถ๏ผŒๅฏน่พ“ๅ…ฅ็š„ๅฏ†็ ่ฟ›่กŒ็ผ“ๅญ˜ใ€‚ if self == note.object as! JYTextField { self.password = self.text! } }) } deinit { NotificationCenter.default.removeObserver(beginEditingObserver) NotificationCenter.default.removeObserver(endEditingObserver) } // ้‡ๅ†™ๆญคๆ–นๆณ•๏ผŒๅฎž็Žฐๅฏนๆ–‡ๆœฌๆก†่ฟ›่กŒไบŒๆฌก็›‘ๅฌใ€‚ override var isSecureTextEntry: Bool{ get { return super.isSecureTextEntry } set{ self.resignFirstResponder() super.isSecureTextEntry = newValue self.becomeFirstResponder() } } }
apache-2.0
cb8fe2fbf578e9dd6ba19386e5cd8f24
29.491803
174
0.612903
4.570025
false
false
false
false
mentalfaculty/impeller
Examples/Listless/Listless/TagList.swift
1
1031
// // Tags.swift // Listless // // Created by Drew McCormack on 07/01/2017. // Copyright ยฉ 2017 The Mental Faculty B.V. All rights reserved. // import Foundation import Impeller struct TagList: Repositable, Equatable { static var repositedType: RepositedType { return "TagList" } var metadata = Metadata() var tags: [String] = [] var asString: String { return tags.joined(separator: " ") } init() {} init(fromText text:String) { let newTags = text.characters.split { $0 == " " }.map { String($0) }.filter { $0.characters.count > 0 } tags = Array(Set(newTags)).sorted() } init(readingFrom reader:PropertyReader) { tags = reader.read(Key.tags.rawValue)! } mutating func write(to writer:PropertyWriter) { writer.write(tags, for: Key.tags.rawValue) } enum Key: String { case tags } static func ==(left: TagList, right: TagList) -> Bool { return left.tags == right.tags } }
mit
a36d542727656c4892e3cc3ad54425f2
22.953488
111
0.595146
3.652482
false
false
false
false
Ben21hao/edx-app-ios-new
Source/OEXRouter+Swift.swift
1
15518
// // OEXRouter+Swift.swift // edX // // Created by Akiva Leffert on 5/7/15. // Copyright (c) 2015 edX. All rights reserved. // import Foundation // The router is an indirection point for navigation throw our app. // New router logic should live here so it can be written in Swift. // We should gradually migrate the existing router class here and then // get rid of the objc version enum CourseHTMLBlockSubkind { case Base case Problem } enum CourseBlockDisplayType { case Unknown case Outline case Unit case Video case HTML(CourseHTMLBlockSubkind) case Discussion(DiscussionModel) var isUnknown : Bool { switch self { case Unknown: return true default: return false } } } extension CourseBlock { var displayType : CourseBlockDisplayType { switch self.type { case .Unknown(_), .HTML: return multiDevice ? .HTML(.Base) : .Unknown case .Problem: return multiDevice ? .HTML(.Problem) : .Unknown case .Course: return .Outline case .Chapter: return .Outline case .Section: return .Outline case .Unit: return .Unit case let .Video(summary): return summary.onlyOnWeb ? .Unknown : .Video case let .Discussion(discussionModel): return .Discussion(discussionModel) } } } extension OEXRouter { func showCoursewareForCourseWithID(courseID : String, fromController controller : UIViewController) { showContainerForBlockWithID(nil, type: CourseBlockDisplayType.Outline, parentID: nil, courseID : courseID, fromController: controller) } func unitControllerForCourseID(courseID : String, blockID : CourseBlockID?, initialChildID : CourseBlockID?) -> CourseContentPageViewController { let contentPageController = CourseContentPageViewController(environment: environment, courseID: courseID, rootID: blockID, initialChildID: initialChildID) return contentPageController } func showContainerForBlockWithID(blockID : CourseBlockID?, type : CourseBlockDisplayType, parentID : CourseBlockID?, courseID : CourseBlockID, fromController controller: UIViewController) { switch type { case .Outline: fallthrough case .Unit: let outlineController = controllerForBlockWithID(blockID, type: type, courseID: courseID) controller.navigationController?.pushViewController(outlineController, animated: true) case .HTML: fallthrough case .Video: fallthrough case .Unknown: let pageController = unitControllerForCourseID(courseID, blockID: parentID, initialChildID: blockID) if let delegate = controller as? CourseContentPageViewControllerDelegate { pageController.navigationDelegate = delegate } controller.navigationController?.pushViewController(pageController, animated: true) case .Discussion: let pageController = unitControllerForCourseID(courseID, blockID: parentID, initialChildID: blockID) if let delegate = controller as? CourseContentPageViewControllerDelegate { pageController.navigationDelegate = delegate } controller.navigationController?.pushViewController(pageController, animated: true) } } func controllerForBlockWithID(blockID : CourseBlockID?, type : CourseBlockDisplayType, courseID : String) -> UIViewController { switch type { case .Outline: let outlineController = CourseOutlineViewController(environment: self.environment, courseID: courseID, rootID: blockID) return outlineController case .Unit: return unitControllerForCourseID(courseID, blockID: blockID, initialChildID: nil) case .HTML: let controller = HTMLBlockViewController(blockID: blockID, courseID : courseID, environment : environment) return controller case .Video: let controller = VideoBlockViewController(environment: environment, blockID: blockID, courseID: courseID) return controller case .Unknown: let controller = CourseUnknownBlockViewController(blockID: blockID, courseID : courseID, environment : environment) return controller case let .Discussion(discussionModel): let controller = DiscussionBlockViewController(blockID: blockID, courseID: courseID, topicID: discussionModel.topicID, environment: environment) return controller } } func controllerForBlock(block : CourseBlock, courseID : String) -> UIViewController { return controllerForBlockWithID(block.blockID, type: block.displayType, courseID: courseID) } @objc(showMyCoursesAnimated:pushingCourseWithID:) func showMyCourses(animated animated: Bool = true, pushingCourseWithID courseID: String? = nil) { let controller = EnrolledCoursesViewController(environment: self.environment) showContentStackWithRootController(controller, animated: animated) if let courseID = courseID { self.showCourseWithID(courseID, fromController: controller, animated: false) } } func showDiscussionResponsesFromViewController(controller: UIViewController, courseID : String, threadID : String, isDiscussionBlackedOut: Bool) { let storyboard = UIStoryboard(name: "DiscussionResponses", bundle: nil) let responsesViewController = storyboard.instantiateInitialViewController() as! DiscussionResponsesViewController responsesViewController.environment = environment responsesViewController.courseID = courseID responsesViewController.threadID = threadID responsesViewController.isDiscussionBlackedOut = isDiscussionBlackedOut controller.navigationController?.pushViewController(responsesViewController, animated: true) } func showDiscussionCommentsFromViewController(controller: UIViewController, courseID : String, response : DiscussionComment, closed : Bool, thread: DiscussionThread, isDiscussionBlackedOut: Bool) { let commentsVC = DiscussionCommentsViewController(environment: environment, courseID : courseID, responseItem: response, closed: closed, thread: thread, isDiscussionBlackedOut: isDiscussionBlackedOut) if let delegate = controller as? DiscussionCommentsViewControllerDelegate { commentsVC.delegate = delegate } controller.navigationController?.pushViewController(commentsVC, animated: true) } func showDiscussionNewCommentFromController(controller: UIViewController, courseID : String, thread:DiscussionThread, context: DiscussionNewCommentViewController.Context) { let newCommentViewController = DiscussionNewCommentViewController(environment: environment, courseID : courseID, thread:thread, context: context) if let delegate = controller as? DiscussionNewCommentViewControllerDelegate { newCommentViewController.delegate = delegate } let navigationController = UINavigationController(rootViewController: newCommentViewController) controller.presentViewController(navigationController, animated: true, completion: nil) } func showPostsFromController(controller : UIViewController, courseID : String, topic: DiscussionTopic) { let postsController = PostsViewController(environment: environment, courseID: courseID, topic: topic) controller.navigationController?.pushViewController(postsController, animated: true) } func showAllPostsFromController(controller : UIViewController, courseID : String, followedOnly following : Bool) { let postsController = PostsViewController(environment: environment, courseID: courseID, following : following) controller.navigationController?.pushViewController(postsController, animated: true) } func showPostsFromController(controller : UIViewController, courseID : String, queryString : String) { let postsController = PostsViewController(environment: environment, courseID: courseID, queryString : queryString) controller.navigationController?.pushViewController(postsController, animated: true) } func showDiscussionTopicsFromController(controller: UIViewController, courseID : String) { let topicsController = DiscussionTopicsViewController(environment: environment, courseID: courseID) controller.navigationController?.pushViewController(topicsController, animated: true) } func showDiscussionNewPostFromController(controller: UIViewController, courseID : String, selectedTopic : DiscussionTopic?) { let newPostController = DiscussionNewPostViewController(environment: environment, courseID: courseID, selectedTopic: selectedTopic) if let delegate = controller as? DiscussionNewPostViewControllerDelegate { newPostController.delegate = delegate } let navigationController = UINavigationController(rootViewController: newPostController) controller.presentViewController(navigationController, animated: true, completion: nil) } func showHandoutsFromController(controller : UIViewController, courseID : String) { let handoutsViewController = CourseHandoutsViewController(environment: environment, courseID: courseID) controller.navigationController?.pushViewController(handoutsViewController, animated: true) } func showProfileForUsername(controller: UIViewController? = nil, username : String, editable: Bool = true) { OEXAnalytics.sharedAnalytics().trackProfileViewed(username) let editable = self.environment.session.currentUser?.username == username // let profileController = UserProfileViewController(environment: environment, username: username, editable: editable) let profileController = TDUserCenterViewController(environment: environment, username: username, editable: editable) if let controller = controller { controller.navigationController?.pushViewController(profileController, animated: true) } else { self.showContentStackWithRootController(profileController, animated: true) } } func showProfileEditorFromController(controller : UIViewController) { guard let profile = environment.dataManager.userProfileManager.feedForCurrentUser().output.value else { return } let editController = UserProfileEditViewController(profile: profile, environment: environment) controller.navigationController?.pushViewController(editController, animated: true) } func showCertificate(url: NSURL, title: String?, fromController controller: UIViewController) { let c = CertificateViewController(environment: environment) c.title = title controller.navigationController?.pushViewController(c, animated: true) c.loadRequest(NSURLRequest(URL: url)) } func showCourseWithID(courseID : String, fromController: UIViewController, animated: Bool = true) { let controller = CourseDashboardViewController(environment: self.environment, courseID: courseID) fromController.navigationController?.pushViewController(controller, animated: animated) } func showCourseCatalog(bottomBar: UIView?) { let controller: UIViewController switch environment.config.courseEnrollmentConfig.type { case .Webview: controller = OEXFindCoursesViewController(bottomBar: bottomBar) case .Native, .None: controller = CourseCatalogViewController(environment: self.environment) } if revealController != nil { showContentStackWithRootController(controller, animated: true) } else { showControllerFromStartupScreen(controller) } self.environment.analytics.trackUserFindsCourses() } func showExploreCourses(bottomBar: UIView?) { let controller = OEXFindCoursesViewController(bottomBar: bottomBar) controller.startURL = .ExploreSubjects if revealController != nil { showContentStackWithRootController(controller, animated: true) } else { showControllerFromStartupScreen(controller) } } private func showControllerFromStartupScreen(controller: UIViewController) { let backButton = UIBarButtonItem(barButtonSystemItem: .Cancel, target: nil, action: nil) backButton.oex_setAction({ controller.dismissViewControllerAnimated(true, completion: nil) }) controller.navigationItem.leftBarButtonItem = backButton let navController = ForwardingNavigationController(rootViewController: controller) presentViewController(navController, fromController:nil, completion: nil) } func showCourseCatalogDetail(courseModel: OEXCourse, fromController: UIViewController) { // let detailController = CourseCatalogDetailViewController(environment: environment, courseModel: courseModel) let detailController = TDCourseCatalogDetailViewController(environment: environment, courseModel: courseModel) fromController.navigationController?.pushViewController(detailController, animated: true) } func showAppReviewIfNeeded(fromController: UIViewController) { if RatingViewController.canShowAppReview(environment){ let reviewController = RatingViewController(environment: environment) reviewController.modalPresentationStyle = UIModalPresentationStyle.OverCurrentContext reviewController.providesPresentationContextTransitionStyle = true reviewController.definesPresentationContext = true if let controller = fromController as? RatingViewControllerDelegate { reviewController.delegate = controller } fromController.presentViewController(reviewController, animated: false, completion: nil) } } // MARK: - LOGIN / LOGOUT func showSplash() { revealController = nil removeCurrentContentController() let splashController: UIViewController // if !environment.config.isRegistrationEnabled { splashController = loginViewController() // } // else if environment.config.newLogistrationFlowEnabled { // splashController = StartupViewController(environment: environment) // } else { // splashController = OEXLoginSplashViewController(environment: environment) // } makeContentControllerCurrent(splashController) } public func logout() { invalidateToken() environment.session.closeAndClearSession() showLoggedOutScreen() } func invalidateToken() { if let refreshToken = environment.session.token?.refreshToken, clientID = environment.config.oauthClientID() { let networkRequest = LogoutApi.invalidateToken(refreshToken, clientID: clientID) environment.networkManager.taskForRequest(networkRequest) { result in } } } // MARK: - Debug func showDebugPane() { let debugMenu = DebugMenuViewController(environment: environment) showContentStackWithRootController(debugMenu, animated: true) } }
apache-2.0
7ff3d9464d47e0ddc1dc93ab61339542
47.49375
208
0.719938
6.035784
false
false
false
false
loudnate/Loop
LoopUI/Views/HUDView.swift
1
2060
// // HUDView.swift // Loop // // Created by Bharat Mediratta on 12/20/16. // Copyright ยฉ 2016 LoopKit Authors. All rights reserved. // import UIKit import LoopKitUI public class HUDView: UIView, NibLoadable { @IBOutlet public weak var loopCompletionHUD: LoopCompletionHUDView! @IBOutlet public weak var glucoseHUD: GlucoseHUDView! @IBOutlet public weak var basalRateHUD: BasalRateHUDView! private var stackView: UIStackView! func setup() { stackView = (HUDView.nib().instantiate(withOwner: self, options: nil)[0] as! UIStackView) stackView.translatesAutoresizingMaskIntoConstraints = false self.addSubview(stackView) // Use AutoLayout to have the stack view fill its entire container. NSLayoutConstraint.activate([ stackView.centerXAnchor.constraint(equalTo: centerXAnchor), stackView.centerYAnchor.constraint(equalTo: centerYAnchor), stackView.widthAnchor.constraint(equalTo: widthAnchor), stackView.heightAnchor.constraint(equalTo: heightAnchor), ]) } public func removePumpManagerProvidedViews() { let standardViews: [UIView] = [loopCompletionHUD, glucoseHUD, basalRateHUD] let pumpManagerViews = stackView.subviews.filter { !standardViews.contains($0) } for view in pumpManagerViews { view.removeFromSuperview() } } public func addHUDView(_ viewToAdd: BaseHUDView) { let insertIndex = stackView.arrangedSubviews.firstIndex { (view) -> Bool in guard let hudView = view as? BaseHUDView else { return false } return viewToAdd.orderPriority <= hudView.orderPriority } stackView.insertArrangedSubview(viewToAdd, at: insertIndex ?? stackView.arrangedSubviews.count) } public override init(frame: CGRect) { super.init(frame: frame) setup() } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setup() } }
apache-2.0
af5ab8af2e1219b60e40987e6ed3fc75
32.754098
103
0.669257
4.961446
false
false
false
false
skywinder/GaugeKit
GaugeKit/UIColor+Blend.swift
1
1184
// // UIColor+Blend.swift // SWGauge // // Created by David Pelletier on 2015-03-06. // Copyright (c) 2015 Petr Korolev. All rights reserved. // import UIKit func + (left: UIColor, right: UIColor) -> UIColor { var lRed: CGFloat = 0 var lGreen: CGFloat = 0 var lBlue: CGFloat = 0 var lAlpha: CGFloat = 0 left.getRed(&lRed, green: &lGreen, blue: &lBlue, alpha: &lAlpha) var rRed: CGFloat = 0 var rGreen: CGFloat = 0 var rBlue: CGFloat = 0 var rAlpha: CGFloat = 0 right.getRed(&rRed, green: &rGreen, blue: &rBlue, alpha: &rAlpha) return UIColor( red: max(lRed, rRed), green: max(lGreen, rGreen), blue: max(lBlue, rBlue), alpha: max(lAlpha, rAlpha) ) } func * (left: CGFloat, right: UIColor) -> UIColor { var rRed: CGFloat = 0 var rGreen: CGFloat = 0 var rBlue: CGFloat = 0 var rAlpha: CGFloat = 0 right.getRed(&rRed, green: &rGreen, blue: &rBlue, alpha: &rAlpha) return UIColor( red: rRed * left, green: rGreen * left, blue: rBlue * left, alpha: rAlpha ) } func * (left: UIColor, right: CGFloat) -> UIColor { return right * left }
mit
94668e103840ae3af5e04a6e6a702be2
22.68
69
0.596284
3.174263
false
false
false
false
indisee/ITCiosScreenShotUploader
ItunesScreenshotUploader/Code/Screens/SettingsViewController.swift
1
1609
// // SettingsViewController.swift // ItunesScreenshotUploader // // Created by iN on 21/01/16. // Copyright ยฉ 2016 2tickets2dublin. All rights reserved. // import Cocoa class SettingsViewController: NSViewController { @IBOutlet weak var field1: NSTextField! @IBOutlet weak var field3: NSTextField! @IBOutlet weak var pathControll: NSPathControl! @IBOutlet weak var passwordTF: NSSecureTextField! @IBOutlet weak var saveCheckBox: NSButton! override func viewDidLoad() { super.viewDidLoad() ItunesConnectHandler.sharedInstance.fillCurrentValues() pathControll.url = URL(fileURLWithPath: ItunesConnectHandler.sharedInstance.ITCPath) field1.stringValue = ItunesConnectHandler.sharedInstance.ITMSUSER ?? "" field3.stringValue = ItunesConnectHandler.sharedInstance.ITMSSKU ?? "" passwordTF.stringValue = ItunesConnectHandler.sharedInstance.ITMSPASS ?? "" } @IBAction func save(_ sender: AnyObject) { self.view.window?.makeFirstResponder(nil) let ITMSPASS = passwordTF.stringValue let ITMSUSER = field1.stringValue let ITMSSKU = field3.stringValue let ITCPath = (pathControll.url?.path) ?? "" let storage = DefaultsStorage() storage.saveCredentialsIncludingPassword(saveCheckBox.state == 1, user: ITMSUSER, sku: ITMSSKU, password: ITMSPASS, path: ITCPath) ItunesConnectHandler.sharedInstance.fillCurrentValues() } @IBAction func changeDoSavePassword(_ sender: AnyObject) { } }
mit
b2a5e3ca4d9214a810b8977c5978cb8e
32.5
138
0.687189
4.529577
false
false
false
false
Urinx/SomeCodes
iOS/CloudIMTest/CloudIMTest/ContactTableViewController.swift
1
1268
// // ContactTableViewController.swift // CloudIMTest // // Created by Eular on 10/9/15. // Copyright ยฉ 2015 Eular. All rights reserved. // import UIKit class ContactTableViewController: UITableViewController { override func viewDidLoad() { super.viewDidLoad() let lb = UILabel() lb.text = "1ไฝ่”็ณปไบบ" lb.textAlignment = .Center lb.textColor = UIColor.grayColor() lb.frame = CGRectMake(0, 0, view.bounds.width, 60) tableView.tableFooterView = lb } override func viewWillAppear(animated: Bool) { self.tabBarController?.tabBar.hidden = false } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { tableView.deselectRowAtIndexPath(indexPath, animated: true) if indexPath.section == 1 && indexPath.row == 0 { let chatVC = RCConversationViewController() chatVC.targetId = WeixinId chatVC.userName = "Ai" chatVC.conversationType = .ConversationType_PRIVATE chatVC.title = "Ai" self.navigationController?.pushViewController(chatVC, animated: true) self.tabBarController?.tabBar.hidden = true } } }
gpl-2.0
a3f41ab730fd9453050042003ec1c182
29.707317
101
0.639396
4.733083
false
false
false
false
timd/Flashcardr
Flashcards/LearnCollectionViewCell.swift
1
1482
// // LearnCollectionViewCell.swift // Flashcards // // Created by Tim on 22/07/15. // Copyright (c) 2015 Tim Duckett. All rights reserved. // import UIKit class LearnCollectionViewCell: UICollectionViewCell { weak var delegate: LearnCellDelegateProtocol? @IBOutlet weak var mainAntwort: UILabel! @IBOutlet weak var antwortWort: UILabel! var showEnglisch: Bool = false var card: Card? { didSet { updateUI() } } required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override func drawRect(rect: CGRect) { super.drawRect(rect) } override func prepareForReuse() { mainAntwort.text = "" antwortWort.text = "" antwortWort.hidden = true } func didTapInCell() { antwortWort.hidden = false delegate?.didRevealAnswerForCell(self) } func updateUI() { let doubleTap = UITapGestureRecognizer(target: self, action: "didTapInCell") doubleTap.numberOfTapsRequired = 2 doubleTap.numberOfTouchesRequired = 1 self.contentView.addGestureRecognizer(doubleTap) if showEnglisch { mainAntwort.text = card?.englisch antwortWort.text = card?.deutsch } else { mainAntwort.text = card?.deutsch antwortWort.text = card?.englisch } antwortWort.hidden = true } }
mit
59ee1d1c1de52ea630bf5a5ca2609dff
22.15625
84
0.60054
4.295652
false
false
false
false
jungtong/MaruKit
Pod/Classes/MaruKit.swift
1
20778
// // MaruKit.swift // LernaFramework // // Created by jungtong on 2015. 9. 21.. // // import Foundation import LernaFramework public class MaruKit { // ์ตœ์‹ ๋งŒํ™” ๋ถˆ๋Ÿฌ์˜ค๊ธฐ class public func parseMaruNewPage(page: Int) throws -> [String : AnyObject] { var resultDict = [String : AnyObject]() var newArray = [[String : String]]() guard var dataString = LernaNetwork.getStringOfURL("\(maruURLNew)\(page)", timeLimit: 99) else { throw MaruError.InvalidURL } // ํ•„์š”ํ•œ ๋ถ€๋ถ„๋งŒ ์งค๋ผ๋‚ธ๋‹ค. do { try dataString.cropString(fromString: "๋งŒํ™” ์—…๋ฐ์ดํŠธ ์•Œ๋ฆผ", toString: "์ฒ˜์ŒํŽ˜์ด์ง€") } catch let error { throw error } // ์“ธ๋ฐ์—†๋Š” ๋ฌธ์ž์—ด ์ •๋ฆฌํ•˜๊ณ  dataString.cleanUp() // ๊ฐ๊ฐ์˜ ๊ฒŒ์‹œ๊ธ€ ๋‹จ์œ„๋กœ ๋ถ„์„! let arrayOfRange = dataString.rangeOfAllBetweenSubstrings(first: "<td class=\"subj", second: " <span>|</span>", firstInclude: false, secondInclude: false) for range in arrayOfRange { let subString = dataString.substringWithRange(range) guard let maruNewtitle = subString.subStringBetweenStringsReverse(first: "\">", second: "<span class=\"comment\">") else { throw MaruError.parseMaruNewError } guard var newMaruEpPath = subString.subStringBetweenStrings(first: "href=\"", second: "\">", firstInclude: false, secondInclude: false) else { throw MaruError.parseMaruNewError } if (newMaruEpPath.rangeOfString("uid=") != nil) { newMaruEpPath = newMaruEpPath.subStringReverseFindToEnd("uid=")! } else if (newMaruEpPath.rangeOfString("mangaup/") != nil) { newMaruEpPath = newMaruEpPath.subStringReverseFindToEnd("mangaup/")! } if newMaruEpPath == "" { throw MaruError.parseMaruNewError } // maruNewQImage ๋Š” ํ•„์ˆ˜์š”์†Œ๊ฐ€ ์•„๋‹˜. var maruNewQImage = subString.subStringBetweenStrings(first: "url(", second: ")\">", firstInclude: false, secondInclude: false) if maruNewQImage == nil { maruNewQImage = "" } // maruNewTime ๋Š” ํ•„์ˆ˜์š”์†Œ๊ฐ€ ์•„๋‹˜. var maruNewTime = subString.subStringReverseFindToEnd("<small>") if maruNewTime == nil { maruNewTime = "" } let newMaru: [String : String] = [ KEY_NEW_TITLE : maruNewtitle, KEY_NEW_ID : newMaruEpPath, KEY_NEW_DATETIME : maruNewTime!, KEY_NEW_QIMAGE : maruNewQImage! ] newArray.append(newMaru) } resultDict.updateValue(LernaUtil.getCurrentDataTime(), forKey: KEY_MARU_DATETIME) resultDict.updateValue(newArray, forKey: KEY_MARU_DATAARRAY) return resultDict } // ์ตœ์‹ ๋งŒํ™” ๋ถ„์„ class public func parseMaruNewId(newId: String) throws -> [String : AnyObject] { var resultDict = [String : AnyObject]() var maruEpArray = [[String : String]]() guard var dataString = LernaNetwork.getStringOfURL("\(maruURL)/b/mangaup/\(newId)") else { throw MaruError.InvalidURL } // ํƒ€์ดํ‹€ ์ฐพ๊ธฐ var maruNewTitle = dataString.subStringBetweenStrings(first: "<title>MARUMARU - ๋งˆ๋ฃจ๋งˆ๋ฃจ - ", second: "</title>", firstInclude: false, secondInclude: false) if maruNewTitle == nil { maruNewTitle = "" } // ํ•„์š”ํ•œ ๋ถ€๋ถ„๋งŒ ์งค๋ผ๋‚ธ๋‹ค. do { try dataString.cropString(fromString: "<div class=\"ctt_box\">", toString: "<div class=\"middle_box\">", isFirstFromString: true) } catch let error { throw error } // ์“ธ๋ฐ์—†๋Š” ๋ฌธ์ž์—ด ์ •๋ฆฌํ•˜๊ณ  dataString.cleanUp() // ์ธ๋„ค์ผ ์ฐพ๊ธฐ var thumbPath = dataString.subStringBetweenStrings(first: "<img src=\"http://", second: "\"", firstInclude: false, secondInclude: false) if thumbPath == nil { thumbPath = dataString.subStringBetweenStrings(first: "src=\"http://", second: "\"", firstInclude: false, secondInclude: false) } if thumbPath == nil { thumbPath = dataString.subStringBetweenSecondToFirst(first: "href=\"http://", second: "\" imageanchor=") } if thumbPath == nil || !(thumbPath?.rangeOfString(".png") == nil || thumbPath?.rangeOfString(".jpg") == nil) { // || thumbPath?.rangeOfString(".png") == nil thumbPath = "" } else { thumbPath = "http://\(thumbPath!)" } var maruID: String? // ๊ฐ๊ฐ์˜ ๊ฒŒ์‹œ๊ธ€ ๋‹จ์œ„๋กœ ๋ถ„์„! let arrayOfRange = dataString.rangeOfAllBetweenSubstrings(first: "<a target=\"_blank\"", second: "</a>", firstInclude: false, secondInclude: false) for range in arrayOfRange { var subString = dataString.substringWithRange(range) // ์“ธ๋ชจ์—†๋Š” ํƒœ๊ทธ๋“ค ์ง€์šฐ๊ณ  subString.removeSubStringBetweenStrings(first: "<", second: ">") let maruEpTitle = subString.subStringReverseFindToEnd(">") if maruEpTitle == nil { throw MaruError.ErrorTodo } if maruEpTitle == "" { continue } let maruEpPath = subString.subStringBetweenStrings(first: "href=\"", second: "\"", firstInclude: false, secondInclude: false) if maruEpPath == nil { throw MaruError.ErrorTodo } // maruEpPath ์˜๋งˆ์ง€๋ง‰์š”์†Œ๊บผ๋‚ด๊ธฐ (ID) let maruEpId = maruEpPath!.subStringReverseFindToEnd("/")! if maruEpTitle!.containsString("์ „ํŽธ") { maruID = maruEpPath?.subStringReverseFindToEnd("uid=") if maruID == nil { maruID = maruEpPath?.subStringReverseFindToEnd("manga/") } continue } let ep: [String : String] = [ KEY_EP_TITLE : maruEpTitle!, KEY_EP_ID : maruEpId, ] maruEpArray.append(ep) } if maruID == nil { maruID = "" } resultDict.updateValue(LernaUtil.getCurrentDataTime(), forKey: KEY_MARU_DATETIME) resultDict.updateValue(newId, forKey: KEY_NEW_ID) resultDict.updateValue(maruNewTitle!, forKey: KEY_NEW_TITLE) resultDict.updateValue(thumbPath!, forKey: KEY_MARU_QIMAGE) resultDict.updateValue(maruEpArray, forKey: KEY_MARU_DATAARRAY) resultDict.updateValue(maruID!, forKey: KEY_MARU_ID) return resultDict } // ์ „์ฒด๋งŒํ™” ๋ถˆ๋Ÿฌ์˜ค๊ธฐ class public func parseMaruAll(sort: Int) throws -> [String : AnyObject] { var resultDict = [String : AnyObject]() var maruArray = [[String : String]]() var page: Int = 1 while(true) { let parseResult: [String : AnyObject] do { parseResult = try parseMaruAllPage(sort, page: page) } catch let error { throw error } let maruDataArray: [[String : String]] = parseResult[KEY_MARU_DATAARRAY]! as! [[String : String]] if maruDataArray.count > 0 { maruArray.appendContentsOf(maruDataArray) page++ } else { break } } resultDict.updateValue(LernaUtil.getCurrentDataTime(), forKey: KEY_MARU_DATETIME) resultDict.updateValue(maruArray, forKey: KEY_MARU_DATAARRAY) return resultDict } // ์ „์ฒด๋งŒํ™” ํŽ˜์ด์ง€ ๋ณ„ ๋ถˆ๋Ÿฌ์˜ค๊ธฐ public class func parseMaruAllPage(sort: Int, page: Int) throws -> [String : AnyObject] { // DDLogInfo(" ์ „์ฒด๋ชฉ๋ก \(page) ํŽ˜์ด์ง€ ๋กœ๋”ฉ -> ") var resultDict = [String : AnyObject]() var maruArray = [[String : String]]() let urlString: String if (MaruEnum(rawValue: sort) == MaruEnum.AllSortNew) { urlString = "\(maruURLAllgid)\(page)" } else { urlString = "\(maruURLAllsubject)\(page)" } //--------------------------------------------- guard var dataString = LernaNetwork.getStringOfURL(urlString, timeLimit: 99) else { throw MaruError.AllMaru_getContents(String(page)) } // ํ•„์š”ํ•œ ๋ถ€๋ถ„๋งŒ ์งค๋ผ๋‚ธ๋‹ค. do { try dataString.cropString(fromString: "์ตœ์‹ ์ˆœ์œผ๋กœ ์ •๋ ฌ", toString: "๊ธ€์“ฐ๊ธฐ") } catch let error { throw error } // ์“ธ๋ฐ์—†๋Š” ๋ฌธ์ž์—ด ์ •๋ฆฌํ•˜๊ณ  dataString.cleanUp() // ๊ฐ๊ฐ์˜ ๊ฒŒ์‹œ๊ธ€ ๋‹จ์œ„๋กœ ๋ถ„์„! let arrayOfRange = dataString.rangeOfAllBetweenSubstrings(first: "<p class=\"crop\">", second: "comment", firstInclude: false, secondInclude: false) for range in arrayOfRange { let subString = dataString.substringWithRange(range) let maruTitle: String? if subString.containsString("cat") { maruTitle = subString.subStringBetweenStringsReverse(first: "</span>", second: "</a><span") } else { maruTitle = subString.subStringBetweenStringsReverse(first: "]", second: "</a><span") } // maruTitle ์ฐพ์ง€ ๋ชปํ•จ if maruTitle == nil { throw MaruError.AllMaru_parse_maruTitle(String(page)) } var maruID = subString.subStringBetweenStrings(first: "uid=", second: "\"", firstInclude: false, secondInclude: false) if maruID == nil { maruID = subString.subStringBetweenStrings(first: "/b/manga/", second: "\">", firstInclude: false, secondInclude: false) } if maruID == nil { throw MaruError.AllMaru_parse_maruID(String(page)) } // maruQImage ๋Š” ํ•„์ˆ˜์š”์†Œ๊ฐ€ ์•„๋‹˜. var maruQImage = subString.subStringBetweenStrings(first: "img src=\"", second: "\" ", firstInclude: false, secondInclude: false) if maruQImage == nil { maruQImage = "" } // maruCategory ๋Š” ํ•„์ˆ˜์š”์†Œ๊ฐ€ ์•„๋‹˜. var maruCategory = subString.subStringBetweenStrings(first: "class=\"cat\">[", second: "]", firstInclude: false, secondInclude: false) if maruCategory == nil { maruCategory = subString.subStringBetweenStrings(first: "[", second: "]", firstInclude: false, secondInclude: false) if maruCategory == nil { maruCategory = "" } } let maru: [String : String] = [ KEY_MARU_TITLE : maruTitle!, KEY_MARU_CATEGORY : maruCategory!, KEY_MARU_ID : maruID!, KEY_MARU_QIMAGE : maruQImage! ] maruArray.append(maru) } // DDLogInfo(" \(maruArray.count) ๊ฐœ.") resultDict.updateValue(LernaUtil.getCurrentDataTime(), forKey: KEY_MARU_DATETIME) resultDict.updateValue(maruArray, forKey: KEY_MARU_DATAARRAY) return resultDict } // MaruId ๋กœ๋”ฉ class public func parseMaruId(maruId: String) throws -> [String : AnyObject] { var resultDict = [String : AnyObject]() var maruEpArray = [[String : String]]() guard var dataString = LernaNetwork.getStringOfURL("\(maruURLID)\(maruId)") else { throw MaruError.ErrorTodo } // ํƒ€์ดํ‹€ ์ฐพ๊ธฐ var maruTitle = dataString.subStringBetweenStrings(first: "<title>MARUMARU - ๋งˆ๋ฃจ๋งˆ๋ฃจ - ", second: "</title>", firstInclude: false, secondInclude: false) if maruTitle == nil { maruTitle = "" } // ํ•„์š”ํ•œ ๋ถ€๋ถ„๋งŒ ์งค๋ผ๋‚ธ๋‹ค. do { try dataString.cropString(fromString: "์Šคํฌ๋žฉ", toString: "์ด ๊ธ€์„ ์ถ”์ฒœํ•ฉ๋‹ˆ๋‹ค!") } catch let error { throw error } // ์ธ๋„ค์ผ ์ฃผ์†Œ ์ฐพ๊ธฐ var thumbPath = dataString.subStringBetweenStrings(first: "<img src=\"http://", second: "\"", firstInclude: false, secondInclude: false) if thumbPath == nil { thumbPath = dataString.subStringBetweenStrings(first: "src=\"http://", second: "\"", firstInclude: false, secondInclude: false) } if thumbPath == nil { thumbPath = dataString.subStringBetweenSecondToFirst(first: "href=\"http://", second: "\" imageanchor=") } if thumbPath == nil || !(thumbPath?.rangeOfString(".png") == nil || thumbPath?.rangeOfString(".jpg") == nil) { // || thumbPath?.rangeOfString(".png") == nil thumbPath = "" } else { thumbPath = "http://\(thumbPath!)" } // ์“ธ๋ฐ์—†๋Š” ๋ฌธ์ž์—ด ์ •๋ฆฌํ•˜๊ณ  dataString.cleanUp() // ๊ฐ๊ฐ์˜ ๊ฒŒ์‹œ๊ธ€ ๋‹จ์œ„๋กœ ๋ถ„์„! let arrayOfRange = dataString.rangeOfAllBetweenSubstrings(first: "<a target=\"_blank\"", second: "/a>", firstInclude: false, secondInclude: false, first2: "<a class=\"con_link\"") for range in arrayOfRange { var subString = dataString.substringWithRange(range) // ์“ธ๋ชจ์—†๋Š” ํƒœ๊ทธ๋“ค ์ง€์šฐ๊ณ  subString.removeSubStringBetweenStrings(first: "<", second: ">") // ep title ์ฐพ๊ธฐ guard var maruEpTitle: String = subString.subStringBetweenStrings(first: ">", second: "<", firstInclude: false, secondInclude: false) else { throw MaruError.ErrorTodo } maruEpTitle = maruEpTitle.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()) if maruEpTitle == "" { continue } // ep path ์ฐพ๊ธฐ guard let maruEpPath = subString.subStringBetweenStrings(first: "href=\"", second: "\"", firstInclude: false, secondInclude: false) else { throw MaruError.ErrorTodo } // maruEpPath ์˜๋งˆ์ง€๋ง‰์š”์†Œ๊บผ๋‚ด๊ธฐ (ID) let maruEpId = maruEpPath.subStringReverseFindToEnd("/")! if Int(maruEpId) == nil { continue } // ์ค‘๋ณต๋œ maruEpPath๊ฐ€ ์žˆ์„ ๊ฒฝ์šฐ title ์ด์–ด์ฃผ๊ธฐ if maruEpArray.last?[KEY_EP_ID] == maruEpId { maruEpTitle = "\((maruEpArray.last?[KEY_EP_TITLE]!)!)\(maruEpTitle)" maruEpArray.removeLast() } if maruEpTitle == "" { continue } let ep: [String : String] = [ KEY_EP_TITLE : maruEpTitle, KEY_EP_ID : maruEpId, ] maruEpArray.append(ep) } resultDict.updateValue(LernaUtil.getCurrentDataTime(), forKey: KEY_MARU_DATETIME) resultDict.updateValue(maruId, forKey: KEY_MARU_ID) resultDict.updateValue(maruTitle!, forKey: KEY_MARU_TITLE) resultDict.updateValue(thumbPath!, forKey: KEY_MARU_QIMAGE) resultDict.updateValue(maruEpArray, forKey: KEY_MARU_DATAARRAY) return resultDict } // MARK: - Completion Handler // MaruEpId ๋กœ๋”ฉ class public func parseMaruEpId(maruEpId: String, completionHandler: (result: [String : AnyObject]) -> Void) throws { guard var dataString = LernaNetwork.getStringOfURL("\(maruURLEp)\(maruEpId)") else { throw MaruError.ErrorTodo } var resultDict = [String : AnyObject]() var resultArray = [String]() if (dataString.rangeOfString("password") != nil) { resultDict.updateValue("Password", forKey: KEY_RESULT) completionHandler(result: resultDict) return } if (dataString.rangeOfString("You are being redirected...") != nil) { resultDict.updateValue("Redirected", forKey: KEY_RESULT) completionHandler(result: resultDict) return } // ํ•„์š”ํ•œ ๋ถ€๋ถ„๋งŒ ์งค๋ผ๋‚ธ๋‹ค. do { if dataString.rangeOfString("Skip to content") != nil { try dataString.cropString(fromString: "Skip to content", toString: "๋Œ์•„๊ฐ€๊ธฐ") } else { try dataString.cropString(fromString: "midtext", toString: "๋Œ์•„๊ฐ€๊ธฐ") } } catch { resultDict.updateValue("ParseError1", forKey: KEY_RESULT) completionHandler(result: resultDict) return } // ์“ธ๋ฐ์—†๋Š” ๋ฌธ์ž์—ด ์ •๋ฆฌํ•˜๊ณ  dataString.cleanUp() let arrayOfRange = dataString.rangeOfAllBetweenSubstrings(first: "data-lazy-src=\"", second: "\"", firstInclude: false, secondInclude: false) if arrayOfRange.isEmpty { resultDict.updateValue("ParseError2", forKey: KEY_RESULT) completionHandler(result: resultDict) return } for range in arrayOfRange! { var subString = dataString.substringWithRange(range) // ?์ดํ›„ ์ง€์šฐ๊ธฐ if let range = subString.rangeOfString("?") { subString = subString.substringToIndex(range.startIndex) } // ์ค‘๋ณต๋˜์ง€ ์•Š๊ฒŒ ์ €์žฅ. if !resultArray.contains(subString) { resultArray.append(subString) } } resultDict.updateValue(resultArray, forKey: KEY_MARU_DATAARRAY) resultDict.updateValue(maruEpId, forKey: KEY_EP_ID) resultDict.updateValue(RESULT_SUCCESS, forKey: KEY_RESULT) completionHandler(result: resultDict) } // MaruId ๋กœ๋”ฉ class public func parseMaruId(maruId: String, completionHandler:(result: [String : AnyObject]?) -> Void) throws { dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), { do { completionHandler(result: try self.parseMaruId(maruId)) } catch { completionHandler(result: nil) } }) } // ์ „์ฒด๋งŒํ™” ๋ถˆ๋Ÿฌ์˜ค๊ธฐ class public func parseMaruAll(sort: Int, completionHandler:(result: [String : AnyObject]?) -> Void) throws { dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), { do { completionHandler(result: try self.parseMaruAll(sort)) } catch { completionHandler(result: nil) } }) } // ์ „์ฒด๋งŒํ™” ํŽ˜์ด์ง€ ๋ณ„ ๋ถˆ๋Ÿฌ์˜ค๊ธฐ public class func parseMaruAllPage(sort: Int, page: Int, completionHandler:(result: [String : AnyObject]?) -> Void) throws { dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), { do { completionHandler(result: try self.parseMaruAllPage(sort, page: page)) } catch { completionHandler(result: nil) } }) } // ์ตœ์‹ ๋งŒํ™” ํŽ˜์ด์ง€ ๋ถˆ๋Ÿฌ์˜ค๊ธฐ class public func parseMaruNewPage(page: Int, completionHandler:(result: [String : AnyObject]?) -> Void) throws { dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), { do { completionHandler(result: try self.parseMaruNewPage(page)) } catch { completionHandler(result: nil) } }) } // ์ตœ์‹ ๋งŒํ™” ๋ถ„์„ class public func parseMaruNewId(newId: String, completionHandler:(result: [String : AnyObject]?) -> Void) throws { dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), { do { completionHandler(result: try self.parseMaruNewId(newId)) } catch { completionHandler(result: nil) } }) } }
mit
d40b95ab8bccc5c8c3499d9fcac1f671
36.86148
187
0.545158
4.136844
false
false
false
false
hollance/swift-algorithm-club
Palindromes/Test/Palindrome.swift
3
699
import Foundation func isPalindrome(_ str: String) -> Bool { let strippedString = str.replacingOccurrences(of: "\\W", with: "", options: .regularExpression, range: nil) let length = strippedString.count if length > 1 { return palindrome(strippedString.lowercased(), left: 0, right: length - 1) } return false } private func palindrome(_ str: String, left: Int, right: Int) -> Bool { if left >= right { return true } let lhs = str[str.index(str.startIndex, offsetBy: left)] let rhs = str[str.index(str.startIndex, offsetBy: right)] if lhs != rhs { return false } return palindrome(str, left: left + 1, right: right - 1) }
mit
84008180dd0a2d485e5316d53e98cf32
25.884615
111
0.632332
3.926966
false
false
false
false
huangboju/Moots
Examples/SwipeBack/SwipeBack/AssistiveTouch.swift
1
2711
// // Copyright ยฉ 2016ๅนด xiAo_Ju. All rights reserved. // import UIKit class AssistiveTouch: UIButton { var originPoint = CGPoint.zero let screen = UIScreen.main.bounds convenience init(origin: CGPoint) { self.init(frame: CGRect(origin: origin, size: CGSize(width: 56, height: 56))) layer.cornerRadius = frame.width / 2 layer.shadowColor = UIColor.black.cgColor layer.shadowOffset = CGSize(width: 0, height: 2) layer.shadowOpacity = 0.26 layer.shadowPath = UIBezierPath(roundedRect: bounds, cornerRadius: bounds.width).cgPath } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { guard let touch = touches.first else { fatalError("touch can not be nil") } originPoint = touch.location(in: self) } override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) { guard let touch = touches.first else { fatalError("touch can not be nil") } let nowPoint = touch.location(in: self) let offsetX = nowPoint.x - originPoint.x let offsetY = nowPoint.y - originPoint.y center = CGPoint(x: center.x + offsetX, y: center.y + offsetY) } override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { reactBounds(touches: touches) } override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) { reactBounds(touches: touches) } func reactBounds(touches: Set<UITouch>) { guard let touch = touches.first else { fatalError("touch can not be nil") } let endPoint = touch.location(in: self) let offsetX = endPoint.x - originPoint.x let offsetY = endPoint.y - originPoint.y UIView.beginAnimations(nil, context: nil) UIView.setAnimationDuration(0.3) let padding: CGFloat = 25 let width = screen.width - padding let height = screen.height - padding if center.x + offsetX >= width / 2 { center = CGPoint(x: width - bounds.width / 2, y: center.y + offsetY) } else { center = CGPoint(x: bounds.width / 2 + padding, y: center.y + offsetY) } if center.y + offsetY >= height - bounds.height / 2 { center.y = height - bounds.height / 2 } else if center.y + offsetY < bounds.height / 2 { center.y = bounds.height / 2 + padding } UIView.commitAnimations() } override func addTarget(_ target: Any?, action: Selector, for controlEvents: UIControl.Event) { addGestureRecognizer(UITapGestureRecognizer(target: target, action: action)) } }
mit
a6246f32ebd59a9bcea2b1a1d30dad89
35.594595
99
0.619645
4.318979
false
false
false
false
convergeeducacao/Charts
Source/Charts/Renderers/ScatterChartRenderer.swift
2
8145
// // ScatterChartRenderer.swift // Charts // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/Charts // import Foundation import CoreGraphics #if !os(OSX) import UIKit #endif open class ScatterChartRenderer: LineScatterCandleRadarRenderer { open weak var dataProvider: ScatterChartDataProvider? public init(dataProvider: ScatterChartDataProvider?, animator: Animator?, viewPortHandler: ViewPortHandler?) { super.init(animator: animator, viewPortHandler: viewPortHandler) self.dataProvider = dataProvider } open override func drawData(context: CGContext) { guard let scatterData = dataProvider?.scatterData else { return } for i in 0 ..< scatterData.dataSetCount { guard let set = scatterData.getDataSetByIndex(i) else { continue } if set.isVisible { if !(set is IScatterChartDataSet) { fatalError("Datasets for ScatterChartRenderer must conform to IScatterChartDataSet") } drawDataSet(context: context, dataSet: set as! IScatterChartDataSet) } } } fileprivate var _lineSegments = [CGPoint](repeating: CGPoint(), count: 2) open func drawDataSet(context: CGContext, dataSet: IScatterChartDataSet) { guard let dataProvider = dataProvider, let animator = animator, let viewPortHandler = self.viewPortHandler else { return } let trans = dataProvider.getTransformer(forAxis: dataSet.axisDependency) let phaseY = animator.phaseY let entryCount = dataSet.entryCount var point = CGPoint() let valueToPixelMatrix = trans.valueToPixelMatrix if let renderer = dataSet.shapeRenderer { context.saveGState() for j in 0 ..< Int(min(ceil(Double(entryCount) * animator.phaseX), Double(entryCount))) { guard let e = dataSet.entryForIndex(j) else { continue } point.x = CGFloat(e.x) point.y = CGFloat(e.y * phaseY) point = point.applying(valueToPixelMatrix) if !viewPortHandler.isInBoundsRight(point.x) { break } if !viewPortHandler.isInBoundsLeft(point.x) || !viewPortHandler.isInBoundsY(point.y) { continue } renderer.renderShape(context: context, dataSet: dataSet, viewPortHandler: viewPortHandler, point: point, color: dataSet.color(atIndex: j)) } context.restoreGState() } else { print("There's no IShapeRenderer specified for ScatterDataSet", terminator: "\n") } } open override func drawValues(context: CGContext) { guard let dataProvider = dataProvider, let scatterData = dataProvider.scatterData, let animator = animator, let viewPortHandler = self.viewPortHandler else { return } // if values are drawn if isDrawingValuesAllowed(dataProvider: dataProvider) { guard let dataSets = scatterData.dataSets as? [IScatterChartDataSet] else { return } let phaseY = animator.phaseY var pt = CGPoint() for i in 0 ..< scatterData.dataSetCount { let dataSet = dataSets[i] if !shouldDrawValues(forDataSet: dataSet) { continue } let valueFont = dataSet.valueFont guard let formatter = dataSet.valueFormatter else { continue } let trans = dataProvider.getTransformer(forAxis: dataSet.axisDependency) let valueToPixelMatrix = trans.valueToPixelMatrix let shapeSize = dataSet.scatterShapeSize let lineHeight = valueFont.lineHeight _xBounds.set(chart: dataProvider, dataSet: dataSet, animator: animator) for j in stride(from: _xBounds.min, through: _xBounds.range + _xBounds.min, by: 1) { guard let e = dataSet.entryForIndex(j) else { break } pt.x = CGFloat(e.x) pt.y = CGFloat(e.y * phaseY) pt = pt.applying(valueToPixelMatrix) if (!viewPortHandler.isInBoundsRight(pt.x)) { break } // make sure the lines don't do shitty things outside bounds if (!viewPortHandler.isInBoundsLeft(pt.x) || !viewPortHandler.isInBoundsY(pt.y)) { continue } let text = formatter.stringForValue( e.y, entry: e, dataSetIndex: i, viewPortHandler: viewPortHandler) ChartUtils.drawText( context: context, text: text, point: CGPoint( x: pt.x, y: pt.y - shapeSize - lineHeight), align: .center, attributes: [NSFontAttributeName: valueFont, NSForegroundColorAttributeName: dataSet.valueTextColorAt(j)] ) } } } } open override func drawExtras(context: CGContext) { } open override func drawHighlighted(context: CGContext, indices: [Highlight]) { guard let dataProvider = dataProvider, let scatterData = dataProvider.scatterData, let animator = animator else { return } let chartXMax = dataProvider.chartXMax context.saveGState() for high in indices { guard let set = scatterData.getDataSetByIndex(high.dataSetIndex) as? IScatterChartDataSet, set.isHighlightEnabled else { continue } guard let e = set.entryForIndex(Int(high.x)) else { continue } if !isInBoundsX(entry: e, dataSet: set) { continue } context.setStrokeColor(set.highlightColor.cgColor) context.setLineWidth(set.highlightLineWidth) if set.highlightLineDashLengths != nil { context.setLineDash(phase: set.highlightLineDashPhase, lengths: set.highlightLineDashLengths!) } else { context.setLineDash(phase: 0.0, lengths: []) } let x = high.x // get the x-position let y = high.y * Double(animator.phaseY) if x > chartXMax * animator.phaseX { continue } let trans = dataProvider.getTransformer(forAxis: set.axisDependency) let pt = trans.pixelForValues(x: x, y: y) high.setDraw(pt: pt) // draw the lines drawHighlightLines(context: context, point: pt, set: set) } context.restoreGState() } }
apache-2.0
7f737654f19ef27a31ed97dea0ce5f21
31.975709
154
0.498588
6.260569
false
false
false
false
NilStack/NilColorKit
NilColorKit/ThemeViewController.swift
1
3267
// // ThemeViewController.swift // NilColorKit // // Created by Peng on 10/8/14. // Copyright (c) 2014 peng. All rights reserved. // import Foundation import UIKit class ThemeViewController: UIViewController, UISearchBarDelegate { let searchBar: UISearchBar = UISearchBar() init(color:UIColor){ NilThemeKit.setupTheme(primaryColor: color, secondaryColor: UIColor.whiteColor(), fontname: "HelveticaNeue-Light", lightStatusBar:true) super.init() } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) // Here you can init your properties } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. title = "Theme View" let toolBar: UIToolbar = UIToolbar(frame: CGRectMake(0.0, 0.0, CGRectGetWidth(view.frame), 35.0)) let flexibleItem: UIBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil) let dismissButton: UIBarButtonItem = UIBarButtonItem(title: "Dismiss", style: UIBarButtonItemStyle.Plain, target: self, action: Selector("dismiss") ) toolBar.items = [flexibleItem, dismissButton] searchBar.frame = CGRectMake(0.0, 0.0, CGRectGetWidth(view.frame), 50.0) searchBar.showsCancelButton = true searchBar.inputAccessoryView = toolBar searchBar.delegate = self view.addSubview(searchBar) let demoSwitch = UISwitch(frame: CGRectMake(20.0, 60.0, 100.0, 50.0)) demoSwitch.on = true view.addSubview(demoSwitch) let demoButton: UIButton = UIButton(frame: CGRectMake(20.0, 100.0, 100.0, 50.0)) demoButton.setTitle("UIButton", forState: UIControlState.Normal) demoButton.contentHorizontalAlignment = UIControlContentHorizontalAlignment.Left view.addSubview(demoButton) let aiView: UIActivityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.Gray) aiView.frame = CGRectMake(120.0, 100.0, 50.0, 50.0) view.addSubview(aiView) aiView.startAnimating() let segmentedControl: UISegmentedControl = UISegmentedControl(items: ["One", "Two"]) segmentedControl.frame = CGRectMake(20.0, 160.0, 200.0, 40.0) segmentedControl.selectedSegmentIndex = 0 view.addSubview(segmentedControl) let slider: UISlider = UISlider(frame: CGRectMake(20.0, 210.0, 200.0, 40.0)) slider.minimumValue = 0 slider.maximumValue = 100 slider.value = 50 view.addSubview(slider) let pageControl: UIPageControl = UIPageControl(frame: CGRectMake(0, CGRectGetHeight(view.frame) - 150, CGRectGetWidth(self.view.frame), 50) ) pageControl.numberOfPages = 3 view.addSubview(pageControl) } func dismiss() { searchBar.resignFirstResponder() } }
mit
2ea04dfe2c23a7d958af97ef10d96fe7
36.551724
157
0.663606
4.818584
false
false
false
false
klundberg/swift-corelibs-foundation
Tools/plutil/main.swift
1
12442
// 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 // #if os(OSX) || os(iOS) import Darwin import SwiftFoundation #elseif os(Linux) import Foundation import Glibc #endif func help() -> Int32 { print("plutil: [command_option] [other_options] file...\n" + "The file '-' means stdin\n" + "Command options are (-lint is the default):\n" + " -help show this message and exit\n" + " -lint check the property list files for syntax errors\n" + " -convert fmt rewrite property list files in format\n" + " fmt is one of: xml1 binary1 json\n" + " -p print property list in a human-readable fashion\n" + " (not for machine parsing! this 'format' is not stable)\n" + "There are some additional optional arguments that apply to -convert\n" + " -s be silent on success\n" + " -o path specify alternate file path name for result;\n" + " the -o option is used with -convert, and is only\n" + " useful with one file argument (last file overwrites);\n" + " the path '-' means stdout\n" + " -e extension specify alternate extension for converted files\n" + " -r if writing JSON, output in human-readable form\n" + " -- specifies that all further arguments are file names\n") return EXIT_SUCCESS } enum ExecutionMode { case Help case Lint case Convert case Print } enum ConversionFormat { case XML1 case Binary1 case JSON } struct Options { var mode: ExecutionMode = .Lint var silent: Bool = false var output: String? var fileExtension: String? var humanReadable: Bool? var conversionFormat: ConversionFormat? var inputs = [String]() } enum OptionParseError : Swift.Error { case UnrecognizedArgument(String) case MissingArgument(String) case InvalidFormat(String) } func parseArguments(_ args: [String]) throws -> Options { var opts = Options() var iterator = args.makeIterator() while let arg = iterator.next() { switch arg { case "--": while let path = iterator.next() { opts.inputs.append(path) } break case "-s": opts.silent = true break case "-o": if let path = iterator.next() { opts.output = path } else { throw OptionParseError.MissingArgument("-o requires a path argument") } break case "-convert": opts.mode = ExecutionMode.Convert if let format = iterator.next() { switch format { case "xml1": opts.conversionFormat = ConversionFormat.XML1 break case "binary1": opts.conversionFormat = ConversionFormat.Binary1 break case "json": opts.conversionFormat = ConversionFormat.JSON break default: throw OptionParseError.InvalidFormat(format) } } else { throw OptionParseError.MissingArgument("-convert requires a format argument of xml1 binary1 json") } break case "-e": if let ext = iterator.next() { opts.fileExtension = ext } else { throw OptionParseError.MissingArgument("-e requires an extension argument") } case "-help": opts.mode = ExecutionMode.Help break case "-lint": opts.mode = ExecutionMode.Lint break case "-p": opts.mode = ExecutionMode.Print break default: if arg.hasPrefix("-") && arg.utf8.count > 1 { throw OptionParseError.UnrecognizedArgument(arg) } break } } return opts } func lint(_ options: Options) -> Int32 { if options.output != nil { print("-o is not used with -lint") let _ = help() return EXIT_FAILURE } if options.fileExtension != nil { print("-e is not used with -lint") let _ = help() return EXIT_FAILURE } if options.inputs.count < 1 { print("No files specified.") let _ = help() return EXIT_FAILURE } let silent = options.silent var doError = false for file in options.inputs { let data : Data? if file == "-" { // stdin data = FileHandle.fileHandleWithStandardInput().readDataToEndOfFile() } else { data = try? Data(contentsOf: URL(fileURLWithPath: file)) } if let d = data { do { let _ = try PropertyListSerialization.propertyList(from: d, options: [], format: nil) if !silent { print("\(file): OK") } } catch { print("\(file): \(error)") } } else { print("\(file) does not exists or is not readable or is not a regular file") doError = true continue } } if doError { return EXIT_FAILURE } else { return EXIT_SUCCESS } } func convert(_ options: Options) -> Int32 { print("Unimplemented") return EXIT_FAILURE } enum DisplayType { case Primary case Key case Value } extension Dictionary { func display(_ indent: Int = 0, type: DisplayType = .Primary) { let indentation = String(repeating: Character(" "), count: indent * 2) if type == .Primary || type == .Key { print("\(indentation)[\n", terminator: "") } else { print("[\n", terminator: "") } forEach() { if let key = $0.0 as? String { key.display(indent + 1, type: .Key) } else { fatalError("plists should have strings as keys but got a \($0.0.dynamicType)") } print(" => ", terminator: "") displayPlist($0.1, indent: indent + 1, type: .Value) } print("\(indentation)]\n", terminator: "") } } extension Array { func display(_ indent: Int = 0, type: DisplayType = .Primary) { let indentation = String(repeating: Character(" "), count: indent * 2) if type == .Primary || type == .Key { print("\(indentation)[\n", terminator: "") } else { print("[\n", terminator: "") } for idx in 0..<count { print("\(indentation) \(idx) => ", terminator: "") displayPlist(self[idx], indent: indent + 1, type: .Value) } print("\(indentation)]\n", terminator: "") } } extension String { func display(_ indent: Int = 0, type: DisplayType = .Primary) { let indentation = String(repeating: Character(" "), count: indent * 2) if type == .Primary { print("\(indentation)\"\(self)\"\n", terminator: "") } else if type == .Key { print("\(indentation)\"\(self)\"", terminator: "") } else { print("\"\(self)\"\n", terminator: "") } } } extension Bool { func display(_ indent: Int = 0, type: DisplayType = .Primary) { let indentation = String(repeating: Character(" "), count: indent * 2) if type == .Primary { print("\(indentation)\"\(self ? "1" : "0")\"\n", terminator: "") } else if type == .Key { print("\(indentation)\"\(self ? "1" : "0")\"", terminator: "") } else { print("\"\(self ? "1" : "0")\"\n", terminator: "") } } } extension NSNumber { func display(_ indent: Int = 0, type: DisplayType = .Primary) { let indentation = String(repeating: Character(" "), count: indent * 2) if type == .Primary { print("\(indentation)\"\(self)\"\n", terminator: "") } else if type == .Key { print("\(indentation)\"\(self)\"", terminator: "") } else { print("\"\(self)\"\n", terminator: "") } } } extension NSData { func display(_ indent: Int = 0, type: DisplayType = .Primary) { let indentation = String(repeating: Character(" "), count: indent * 2) if type == .Primary { print("\(indentation)\"\(self)\"\n", terminator: "") } else if type == .Key { print("\(indentation)\"\(self)\"", terminator: "") } else { print("\"\(self)\"\n", terminator: "") } } } func displayPlist(_ plist: Any, indent: Int = 0, type: DisplayType = .Primary) { if let val = plist as? Dictionary<String, Any> { val.display(indent, type: type) } else if let val = plist as? Array<Any> { val.display(indent, type: type) } else if let val = plist as? String { val.display(indent, type: type) } else if let val = plist as? Bool { val.display(indent, type: type) } else if let val = plist as? NSNumber { val.display(indent, type: type) } else if let val = plist as? NSData { val.display(indent, type: type) } else { fatalError("unhandled type \(plist.dynamicType)") } } func display(_ options: Options) -> Int32 { if options.inputs.count < 1 { print("No files specified.") let _ = help() return EXIT_FAILURE } var doError = false for file in options.inputs { let data : Data? if file == "-" { // stdin data = FileHandle.fileHandleWithStandardInput().readDataToEndOfFile() } else { data = try? Data(contentsOf: URL(fileURLWithPath: file)) } if let d = data { do { let plist = try PropertyListSerialization.propertyList(from: d, options: [], format: nil) displayPlist(plist) } catch { print("\(file): \(error)") } } else { print("\(file) does not exists or is not readable or is not a regular file") doError = true continue } } if doError { return EXIT_FAILURE } else { return EXIT_SUCCESS } } func main() -> Int32 { var args = ProcessInfo.processInfo().arguments if args.count < 2 { print("No files specified.") return EXIT_FAILURE } // Throw away process path args.removeFirst() do { let opts = try parseArguments(args) switch opts.mode { case .Lint: return lint(opts) case .Convert: return convert(opts) case .Print: return display(opts) case .Help: return help() } } catch let err { switch err as! OptionParseError { case .UnrecognizedArgument(let arg): print("unrecognized option: \(arg)") let _ = help() break case .InvalidFormat(let format): print("unrecognized format \(format)\nformat should be one of: xml1 binary1 json") break case .MissingArgument(let errorStr): print(errorStr) break } return EXIT_FAILURE } } exit(main())
apache-2.0
cd858d820338f2b03d3ec6fd22bc4d63
30.419192
118
0.496865
4.696867
false
false
false
false