repo_name
stringlengths
6
91
ref
stringlengths
12
59
path
stringlengths
7
936
license
stringclasses
15 values
copies
stringlengths
1
3
content
stringlengths
61
714k
hash
stringlengths
32
32
line_mean
float64
4.88
60.8
line_max
int64
12
421
alpha_frac
float64
0.1
0.92
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
AckeeCZ/ACKReactiveExtensions
refs/heads/master
ACKReactiveExtensions/AlamofireImage/ImageDownloaderExtensions.swift
mit
1
// // ImageDownloaderExtensions.swift // AlamofireImage // // Created by Jakub Olejník on 15/04/2018. // import UIKit import Alamofire import ReactiveCocoa import ReactiveSwift import AlamofireImage public struct ImageDownloadError: Error { public let underlyingError: Error public init(underlyingError: Error) { self.underlyingError = underlyingError } } extension Reactive where Base: ImageDownloader { public func loadImage(with url: URL, filter: ImageFilter? = nil) -> SignalProducer<UIImage, ImageDownloadError> { return SignalProducer { [weak base = base] observer, lifetime in guard let base = base else { observer.sendInterrupted(); return } let request = URLRequest(url: url) base.download(request, filter: filter, completion: { response in switch response.result { case .success(let image): observer.send(value: image) observer.sendCompleted() case .failure(let error): observer.send(error: ImageDownloadError(underlyingError: error)) } }) } } }
4d9a742e409b2874a35c4df56bc850da
30.026316
117
0.634436
false
false
false
false
SoCM/iOS-FastTrack-2014-2015
refs/heads/master
04-App Architecture/Swift 3/4-4-Presentation/PresentingDemo1/PresentingDemo/ViewController.swift
mit
2
// // ViewController.swift // PresentingDemo // // Created by Nicholas Outram on 14/01/2016. // Copyright © 2016 Plymouth University. All rights reserved. // import UIKit class ViewController: UIViewController, ModalViewController1Protocol { @IBOutlet weak var resultLabel: UILabel! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "DEMO1" { if let vc = segue.destination as? ModalViewController1 { vc.titleText = "DEMO 1" vc.delegate = self } } } //Call back func dismissWithStringData(_ str: String) { self.dismiss(animated: true) { self.resultLabel.text = str } } }
c41ac917853668ff1aed7fc643f676fa
22.229167
80
0.587444
false
false
false
false
IngmarStein/swift
refs/heads/master
test/Interpreter/throwing_initializers.swift
apache-2.0
26
// RUN: %target-run-simple-swift // REQUIRES: executable_test import StdlibUnittest var ThrowingInitTestSuite = TestSuite("ThrowingInit") enum E : Error { case X } func unwrap(_ b: Bool) throws -> Int { if b { throw E.X } return 0 } class Bear { let x: LifetimeTracked /* Designated */ init(n: Int) { x = LifetimeTracked(0) } init(n: Int, before: Bool) throws { if before { throw E.X } self.x = LifetimeTracked(0) } init(n: Int, after: Bool) throws { self.x = LifetimeTracked(0) if after { throw E.X } } init(n: Int, before: Bool, after: Bool) throws { if before { throw E.X } self.x = LifetimeTracked(0) if after { throw E.X } } /* Convenience */ convenience init(before: Bool) throws { try unwrap(before) self.init(n: 0) } convenience init(before2: Bool) throws { try self.init(n: unwrap(before2)) } convenience init(before: Bool, before2: Bool) throws { try unwrap(before) try self.init(n: unwrap(before2)) } convenience init(during: Bool) throws { try self.init(n: 0, after: during) } convenience init(before: Bool, during: Bool) throws { try unwrap(before) try self.init(n: 0, after: during) } convenience init(after: Bool) throws { self.init(n: 0) try unwrap(after) } convenience init(before: Bool, after: Bool) throws { try unwrap(before) self.init(n: 0) try unwrap(after) } convenience init(during: Bool, after: Bool) throws { try self.init(n: 0, after: during) try unwrap(after) } convenience init(before: Bool, during: Bool, after: Bool) throws { try unwrap(before) try self.init(n: 0, after: during) try unwrap(after) } convenience init(before: Bool, before2: Bool, during: Bool, after: Bool) throws { try unwrap(before) try self.init(n: unwrap(before2), after: during) try unwrap(after) } } class PolarBear : Bear { let y: LifetimeTracked /* Designated */ override init(n: Int) { self.y = LifetimeTracked(0) super.init(n: n) } override init(n: Int, before: Bool) throws { if before { throw E.X } self.y = LifetimeTracked(0) super.init(n: n) } init(n: Int, during: Bool) throws { self.y = LifetimeTracked(0) try super.init(n: n, before: during) } init(n: Int, before: Bool, during: Bool) throws { self.y = LifetimeTracked(0) if before { throw E.X } try super.init(n: n, before: during) } override init(n: Int, after: Bool) throws { self.y = LifetimeTracked(0) super.init(n: n) if after { throw E.X } } init(n: Int, during: Bool, after: Bool) throws { self.y = LifetimeTracked(0) try super.init(n: n, before: during) if after { throw E.X } } override init(n: Int, before: Bool, after: Bool) throws { if before { throw E.X } self.y = LifetimeTracked(0) super.init(n: n) if after { throw E.X } } init(n: Int, before: Bool, during: Bool, after: Bool) throws { if before { throw E.X } self.y = LifetimeTracked(0) try super.init(n: n, before: during) if after { throw E.X } } } class GuineaPig<T> : Bear { let y: LifetimeTracked let t: T init(t: T, during: Bool) throws { self.y = LifetimeTracked(0) self.t = t try super.init(n: 0, before: during) } } struct Chimera { let x: LifetimeTracked let y: LifetimeTracked init(before: Bool) throws { if before { throw E.X } x = LifetimeTracked(0) y = LifetimeTracked(0) } init(during: Bool) throws { x = LifetimeTracked(0) if during { throw E.X } y = LifetimeTracked(0) } init(before: Bool, during: Bool) throws { if before { throw E.X } x = LifetimeTracked(0) if during { throw E.X } y = LifetimeTracked(0) } init(after: Bool) throws { x = LifetimeTracked(0) y = LifetimeTracked(0) if after { throw E.X } } init(before: Bool, after: Bool) throws { if before { throw E.X } x = LifetimeTracked(0) y = LifetimeTracked(0) if after { throw E.X } } init(during: Bool, after: Bool) throws { x = LifetimeTracked(0) if during { throw E.X } y = LifetimeTracked(0) if after { throw E.X } } init(before: Bool, during: Bool, after: Bool) throws { if before { throw E.X } x = LifetimeTracked(0) if during { throw E.X } y = LifetimeTracked(0) if after { throw E.X } } } func mustThrow<T>(_ f: () throws -> T) { do { try f() preconditionFailure("Didn't throw") } catch {} } ThrowingInitTestSuite.test("DesignatedInitFailure_Root") { mustThrow { try Bear(n: 0, before: true) } mustThrow { try Bear(n: 0, after: true) } mustThrow { try Bear(n: 0, before: true, after: false) } mustThrow { try Bear(n: 0, before: false, after: true) } } ThrowingInitTestSuite.test("DesignatedInitFailure_Derived") { mustThrow { try PolarBear(n: 0, before: true) } mustThrow { try PolarBear(n: 0, during: true) } mustThrow { try PolarBear(n: 0, before: true, during: false) } mustThrow { try PolarBear(n: 0, before: false, during: true) } mustThrow { try PolarBear(n: 0, after: true) } mustThrow { try PolarBear(n: 0, during: true, after: false) } mustThrow { try PolarBear(n: 0, during: false, after: true) } mustThrow { try PolarBear(n: 0, before: true, after: false) } mustThrow { try PolarBear(n: 0, before: false, after: true) } mustThrow { try PolarBear(n: 0, before: true, during: false, after: false) } mustThrow { try PolarBear(n: 0, before: false, during: true, after: false) } mustThrow { try PolarBear(n: 0, before: false, during: false, after: true) } } ThrowingInitTestSuite.test("DesignatedInitFailure_DerivedGeneric") { mustThrow { try GuineaPig(t: LifetimeTracked(0), during: true) } } ThrowingInitTestSuite.test("ConvenienceInitFailure_Root") { mustThrow { try Bear(before: true) } mustThrow { try Bear(before2: true) } mustThrow { try Bear(before: true, before2: false) } mustThrow { try Bear(before: false, before2: true) } mustThrow { try Bear(during: true) } mustThrow { try Bear(before: true, during: false) } mustThrow { try Bear(before: false, during: true) } mustThrow { try Bear(after: true) } mustThrow { try Bear(before: true, after: false) } mustThrow { try Bear(before: false, after: true) } mustThrow { try Bear(during: true, after: false) } mustThrow { try Bear(during: false, after: true) } mustThrow { try Bear(before: true, during: false, after: false) } mustThrow { try Bear(before: false, during: true, after: false) } mustThrow { try Bear(before: false, during: false, after: true) } mustThrow { try Bear(before: true, before2: false, during: false, after: false) } mustThrow { try Bear(before: false, before2: true, during: false, after: false) } mustThrow { try Bear(before: false, before2: false, during: true, after: false) } mustThrow { try Bear(before: false, before2: false, during: false, after: true) } } ThrowingInitTestSuite.test("ConvenienceInitFailure_Derived") { mustThrow { try PolarBear(before: true) } mustThrow { try PolarBear(before2: true) } mustThrow { try PolarBear(before: true, before2: false) } mustThrow { try PolarBear(before: false, before2: true) } mustThrow { try PolarBear(during: true) } mustThrow { try PolarBear(before: true, during: false) } mustThrow { try PolarBear(before: false, during: true) } mustThrow { try PolarBear(after: true) } mustThrow { try PolarBear(before: true, after: false) } mustThrow { try PolarBear(before: false, after: true) } mustThrow { try PolarBear(during: true, after: false) } mustThrow { try PolarBear(during: false, after: true) } mustThrow { try PolarBear(before: true, during: false, after: false) } mustThrow { try PolarBear(before: false, during: true, after: false) } mustThrow { try PolarBear(before: false, during: false, after: true) } mustThrow { try PolarBear(before: true, before2: false, during: false, after: false) } mustThrow { try PolarBear(before: false, before2: true, during: false, after: false) } mustThrow { try PolarBear(before: false, before2: false, during: true, after: false) } mustThrow { try PolarBear(before: false, before2: false, during: false, after: true) } } ThrowingInitTestSuite.test("InitFailure_Struct") { mustThrow { try Chimera(before: true) } mustThrow { try Chimera(during: true) } mustThrow { try Chimera(before: true, during: false) } mustThrow { try Chimera(before: false, during: true) } mustThrow { try Chimera(after: true) } mustThrow { try Chimera(before: true, after: false) } mustThrow { try Chimera(before: false, after: true) } mustThrow { try Chimera(during: true, after: false) } mustThrow { try Chimera(during: false, after: true) } mustThrow { try Chimera(before: true, during: false, after: false) } mustThrow { try Chimera(before: false, during: true, after: false) } mustThrow { try Chimera(before: false, during: false, after: true) } } runAllTests()
cade68d544d2f3ebf6deacf5bb6d7c78
25.184136
88
0.639619
false
false
false
false
faimin/ZDOpenSourceDemo
refs/heads/master
Floral/Pods/Hero/Sources/Preprocessors/DefaultAnimationPreprocessor.swift
mit
3
// The MIT License (MIT) // // Copyright (c) 2016 Luke Zhao <[email protected]> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import UIKit public enum HeroDefaultAnimationType { public enum Direction: HeroStringConvertible { case left, right, up, down public static func from(node: ExprNode) -> Direction? { switch node.name { case "left": return .left case "right": return .right case "up": return .up case "down": return .down default: return nil } } } case auto case push(direction: Direction) case pull(direction: Direction) case cover(direction: Direction) case uncover(direction: Direction) case slide(direction: Direction) case zoomSlide(direction: Direction) case pageIn(direction: Direction) case pageOut(direction: Direction) case fade case zoom case zoomOut indirect case selectBy(presenting: HeroDefaultAnimationType, dismissing: HeroDefaultAnimationType) public static func autoReverse(presenting: HeroDefaultAnimationType) -> HeroDefaultAnimationType { return .selectBy(presenting: presenting, dismissing: presenting.reversed()) } case none func reversed() -> HeroDefaultAnimationType { switch self { case .push(direction: .up): return .pull(direction: .down) case .push(direction: .right): return .pull(direction: .left) case .push(direction: .down): return .pull(direction: .up) case .push(direction: .left): return .pull(direction: .right) case .pull(direction: .up): return .push(direction: .down) case .pull(direction: .right): return .push(direction: .left) case .pull(direction: .down): return .push(direction: .up) case .pull(direction: .left): return .push(direction: .right) case .cover(direction: .up): return .uncover(direction: .down) case .cover(direction: .right): return .uncover(direction: .left) case .cover(direction: .down): return .uncover(direction: .up) case .cover(direction: .left): return .uncover(direction: .right) case .uncover(direction: .up): return .cover(direction: .down) case .uncover(direction: .right): return .cover(direction: .left) case .uncover(direction: .down): return .cover(direction: .up) case .uncover(direction: .left): return .cover(direction: .right) case .slide(direction: .up): return .slide(direction: .down) case .slide(direction: .down): return .slide(direction: .up) case .slide(direction: .left): return .slide(direction: .right) case .slide(direction: .right): return .slide(direction: .left) case .zoomSlide(direction: .up): return .zoomSlide(direction: .down) case .zoomSlide(direction: .down): return .zoomSlide(direction: .up) case .zoomSlide(direction: .left): return .zoomSlide(direction: .right) case .zoomSlide(direction: .right): return .zoomSlide(direction: .left) case .pageIn(direction: .up): return .pageOut(direction: .down) case .pageIn(direction: .right): return .pageOut(direction: .left) case .pageIn(direction: .down): return .pageOut(direction: .up) case .pageIn(direction: .left): return .pageOut(direction: .right) case .pageOut(direction: .up): return .pageIn(direction: .down) case .pageOut(direction: .right): return .pageIn(direction: .left) case .pageOut(direction: .down): return .pageIn(direction: .up) case .pageOut(direction: .left): return .pageIn(direction: .right) case .zoom: return .zoomOut case .zoomOut: return .zoom default: return self } } public var label: String? { let mirror = Mirror(reflecting: self) if let associated = mirror.children.first { let valuesMirror = Mirror(reflecting: associated.value) if !valuesMirror.children.isEmpty { let parameters = valuesMirror.children.map { ".\($0.value)" }.joined(separator: ",") return ".\(associated.label ?? "")(\(parameters))" } return ".\(associated.label ?? "")(.\(associated.value))" } return ".\(self)" } } extension HeroDefaultAnimationType: HeroStringConvertible { public static func from(node: ExprNode) -> HeroDefaultAnimationType? { let name: String = node.name let parameters: [ExprNode] = (node as? CallNode)?.arguments ?? [] switch name { case "auto": return .auto case "push": if let node = parameters.get(0), let direction = Direction.from(node: node) { return .push(direction: direction) } case "pull": if let node = parameters.get(0), let direction = Direction.from(node: node) { return .pull(direction: direction) } case "cover": if let node = parameters.get(0), let direction = Direction.from(node: node) { return .cover(direction: direction) } case "uncover": if let node = parameters.get(0), let direction = Direction.from(node: node) { return .uncover(direction: direction) } case "slide": if let node = parameters.get(0), let direction = Direction.from(node: node) { return .slide(direction: direction) } case "zoomSlide": if let node = parameters.get(0), let direction = Direction.from(node: node) { return .zoomSlide(direction: direction) } case "pageIn": if let node = parameters.get(0), let direction = Direction.from(node: node) { return .pageIn(direction: direction) } case "pageOut": if let node = parameters.get(0), let direction = Direction.from(node: node) { return .pageOut(direction: direction) } case "fade": return .fade case "zoom": return .zoom case "zoomOut": return .zoomOut case "selectBy": if let presentingNode = parameters.get(0), let presenting = HeroDefaultAnimationType.from(node: presentingNode), let dismissingNode = parameters.get(1), let dismissing = HeroDefaultAnimationType.from(node: dismissingNode) { return .selectBy(presenting: presenting, dismissing: dismissing) } case "none": return HeroDefaultAnimationType.none default: break } return nil } } class DefaultAnimationPreprocessor: BasePreprocessor { func shift(direction: HeroDefaultAnimationType.Direction, appearing: Bool, size: CGSize? = nil, transpose: Bool = false) -> CGPoint { let size = size ?? context.container.bounds.size let rtn: CGPoint switch direction { case .left, .right: rtn = CGPoint(x: (direction == .right) == appearing ? -size.width : size.width, y: 0) case .up, .down: rtn = CGPoint(x: 0, y: (direction == .down) == appearing ? -size.height : size.height) } if transpose { return CGPoint(x: rtn.y, y: rtn.x) } return rtn } override func process(fromViews: [UIView], toViews: [UIView]) { guard let hero = hero, let toView = hero.toView, let fromView = hero.fromView else { return } var defaultAnimation = hero.defaultAnimation let inNavigationController = hero.inNavigationController let inTabBarController = hero.inTabBarController let toViewController = hero.toViewController let fromViewController = hero.fromViewController let presenting = hero.isPresenting let fromOverFullScreen = hero.fromOverFullScreen let toOverFullScreen = hero.toOverFullScreen let animators = hero.animators if case .auto = defaultAnimation { if inNavigationController, let navAnim = toViewController?.navigationController?.hero.navigationAnimationType { defaultAnimation = navAnim } else if inTabBarController, let tabAnim = toViewController?.tabBarController?.hero.tabBarAnimationType { defaultAnimation = tabAnim } else if let modalAnim = (presenting ? toViewController : fromViewController)?.hero.modalAnimationType { defaultAnimation = modalAnim } } if case .selectBy(let presentAnim, let dismissAnim) = defaultAnimation { defaultAnimation = presenting ? presentAnim : dismissAnim } if case .auto = defaultAnimation { if animators.contains(where: { $0.canAnimate(view: toView, appearing: true) || $0.canAnimate(view: fromView, appearing: false) }) { defaultAnimation = .none } else if inNavigationController { defaultAnimation = presenting ? .push(direction:.left) : .pull(direction:.right) } else if inTabBarController { defaultAnimation = presenting ? .slide(direction:.left) : .slide(direction:.right) } else { defaultAnimation = .fade } } if case .none = defaultAnimation { return } context[fromView] = [.timingFunction(.standard), .duration(0.35)] context[toView] = [.timingFunction(.standard), .duration(0.35)] let shadowState: [HeroModifier] = [.shadowOpacity(0.5), .shadowColor(.black), .shadowRadius(5), .shadowOffset(.zero), .masksToBounds(false)] switch defaultAnimation { case .push(let direction): context.insertToViewFirst = false context[toView]!.append(contentsOf: [.translate(shift(direction: direction, appearing: true)), .shadowOpacity(0), .beginWith(modifiers: shadowState), .timingFunction(.deceleration)]) context[fromView]!.append(contentsOf: [.translate(shift(direction: direction, appearing: false) / 3), .overlay(color: .black, opacity: 0.1), .timingFunction(.deceleration)]) case .pull(let direction): context.insertToViewFirst = true context[fromView]!.append(contentsOf: [.translate(shift(direction: direction, appearing: false)), .shadowOpacity(0), .beginWith(modifiers: shadowState)]) context[toView]!.append(contentsOf: [.translate(shift(direction: direction, appearing: true) / 3), .overlay(color: .black, opacity: 0.1)]) case .slide(let direction): context[fromView]!.append(contentsOf: [.translate(shift(direction: direction, appearing: false))]) context[toView]!.append(contentsOf: [.translate(shift(direction: direction, appearing: true))]) case .zoomSlide(let direction): context[fromView]!.append(contentsOf: [.translate(shift(direction: direction, appearing: false)), .scale(0.8)]) context[toView]!.append(contentsOf: [.translate(shift(direction: direction, appearing: true)), .scale(0.8)]) case .cover(let direction): context.insertToViewFirst = false context[toView]!.append(contentsOf: [.translate(shift(direction: direction, appearing: true)), .shadowOpacity(0), .beginWith(modifiers: shadowState), .timingFunction(.deceleration)]) context[fromView]!.append(contentsOf: [.overlay(color: .black, opacity: 0.1), .timingFunction(.deceleration)]) case .uncover(let direction): context.insertToViewFirst = true context[fromView]!.append(contentsOf: [.translate(shift(direction: direction, appearing: false)), .shadowOpacity(0), .beginWith(modifiers: shadowState)]) context[toView]!.append(contentsOf: [.overlay(color: .black, opacity: 0.1)]) case .pageIn(let direction): context.insertToViewFirst = false context[toView]!.append(contentsOf: [.translate(shift(direction: direction, appearing: true)), .shadowOpacity(0), .beginWith(modifiers: shadowState), .timingFunction(.deceleration)]) context[fromView]!.append(contentsOf: [.scale(0.7), .overlay(color: .black, opacity: 0.1), .timingFunction(.deceleration)]) case .pageOut(let direction): context.insertToViewFirst = true context[fromView]!.append(contentsOf: [.translate(shift(direction: direction, appearing: false)), .shadowOpacity(0), .beginWith(modifiers: shadowState)]) context[toView]!.append(contentsOf: [.scale(0.7), .overlay(color: .black, opacity: 0.1)]) case .fade: // TODO: clean up this. overFullScreen logic shouldn't be here if !(fromOverFullScreen && !presenting) { context[toView] = [.fade] } #if os(tvOS) context[fromView] = [.fade] #else if (!presenting && toOverFullScreen) || !fromView.isOpaque || (fromView.backgroundColor?.alphaComponent ?? 1) < 1 { context[fromView] = [.fade] } #endif context[toView]!.append(.durationMatchLongest) context[fromView]!.append(.durationMatchLongest) case .zoom: context.insertToViewFirst = true context[fromView]!.append(contentsOf: [.scale(1.3), .fade]) context[toView]!.append(contentsOf: [.scale(0.7)]) case .zoomOut: context.insertToViewFirst = false context[toView]!.append(contentsOf: [.scale(1.3), .fade]) context[fromView]!.append(contentsOf: [.scale(0.7)]) default: fatalError("Not implemented") } } }
1b7b60e75ea63809167f95e9a3891b50
41.226629
137
0.627197
false
false
false
false
khoren93/SwiftHub
refs/heads/master
SwiftHub/Modules/Main/HomeTabBarController.swift
mit
1
// // HomeTabBarController.swift // SwiftHub // // Created by Khoren Markosyan on 1/5/18. // Copyright © 2018 Khoren Markosyan. All rights reserved. // import UIKit import RAMAnimatedTabBarController import Localize_Swift import RxSwift enum HomeTabBarItem: Int { case search, news, notifications, settings, login private func controller(with viewModel: ViewModel, navigator: Navigator) -> UIViewController { switch self { case .search: let vc = SearchViewController(viewModel: viewModel, navigator: navigator) return NavigationController(rootViewController: vc) case .news: let vc = EventsViewController(viewModel: viewModel, navigator: navigator) return NavigationController(rootViewController: vc) case .notifications: let vc = NotificationsViewController(viewModel: viewModel, navigator: navigator) return NavigationController(rootViewController: vc) case .settings: let vc = SettingsViewController(viewModel: viewModel, navigator: navigator) return NavigationController(rootViewController: vc) case .login: let vc = LoginViewController(viewModel: viewModel, navigator: navigator) return NavigationController(rootViewController: vc) } } var image: UIImage? { switch self { case .search: return R.image.icon_tabbar_search() case .news: return R.image.icon_tabbar_news() case .notifications: return R.image.icon_tabbar_activity() case .settings: return R.image.icon_tabbar_settings() case .login: return R.image.icon_tabbar_login() } } var title: String { switch self { case .search: return R.string.localizable.homeTabBarSearchTitle.key.localized() case .news: return R.string.localizable.homeTabBarEventsTitle.key.localized() case .notifications: return R.string.localizable.homeTabBarNotificationsTitle.key.localized() case .settings: return R.string.localizable.homeTabBarSettingsTitle.key.localized() case .login: return R.string.localizable.homeTabBarLoginTitle.key.localized() } } var animation: RAMItemAnimation { var animation: RAMItemAnimation switch self { case .search: animation = RAMFlipLeftTransitionItemAnimations() case .news: animation = RAMBounceAnimation() case .notifications: animation = RAMBounceAnimation() case .settings: animation = RAMRightRotationAnimation() case .login: animation = RAMBounceAnimation() } animation.theme.iconSelectedColor = themeService.attribute { $0.secondary } animation.theme.textSelectedColor = themeService.attribute { $0.secondary } return animation } func getController(with viewModel: ViewModel, navigator: Navigator) -> UIViewController { let vc = controller(with: viewModel, navigator: navigator) let item = RAMAnimatedTabBarItem(title: title, image: image, tag: rawValue) item.animation = animation item.theme.iconColor = themeService.attribute { $0.text } item.theme.textColor = themeService.attribute { $0.text } vc.tabBarItem = item return vc } } class HomeTabBarController: RAMAnimatedTabBarController, Navigatable { var viewModel: HomeTabBarViewModel? var navigator: Navigator! init(viewModel: ViewModel?, navigator: Navigator) { self.viewModel = viewModel as? HomeTabBarViewModel self.navigator = navigator super.init(nibName: nil, bundle: nil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. makeUI() bindViewModel() } func makeUI() { NotificationCenter.default .rx.notification(NSNotification.Name(LCLLanguageChangeNotification)) .subscribe { [weak self] (event) in self?.animatedItems.forEach({ (item) in item.title = HomeTabBarItem(rawValue: item.tag)?.title }) self?.setViewControllers(self?.viewControllers, animated: false) self?.setSelectIndex(from: 0, to: self?.selectedIndex ?? 0) }.disposed(by: rx.disposeBag) tabBar.theme.barTintColor = themeService.attribute { $0.primaryDark } themeService.typeStream.delay(DispatchTimeInterval.milliseconds(200), scheduler: MainScheduler.instance) .subscribe(onNext: { (theme) in switch theme { case .light(let color), .dark(let color): self.changeSelectedColor(color.color, iconSelectedColor: color.color) } }).disposed(by: rx.disposeBag) } func bindViewModel() { guard let viewModel = viewModel else { return } let input = HomeTabBarViewModel.Input(whatsNewTrigger: rx.viewDidAppear.mapToVoid()) let output = viewModel.transform(input: input) output.tabBarItems.delay(.milliseconds(50)).drive(onNext: { [weak self] (tabBarItems) in if let strongSelf = self { let controllers = tabBarItems.map { $0.getController(with: viewModel.viewModel(for: $0), navigator: strongSelf.navigator) } strongSelf.setViewControllers(controllers, animated: false) } }).disposed(by: rx.disposeBag) output.openWhatsNew.drive(onNext: { [weak self] (block) in if Configs.Network.useStaging == false { self?.navigator.show(segue: .whatsNew(block: block), sender: self, transition: .modal) } }).disposed(by: rx.disposeBag) } }
c6074eb55e549ab9b104175a137611cf
39.191781
139
0.657635
false
false
false
false
CoderZZF/DYZB
refs/heads/master
DYZB/DYZB/Classes/Home/Controller/HomeViewController.swift
apache-2.0
1
// // HomeViewController.swift // DYZB // // Created by zhangzhifu on 2017/3/15. // Copyright © 2017年 seemygo. All rights reserved. // import UIKit private let kTitleViewH : CGFloat = 40 class HomeViewController: UIViewController { // MARK:- 懒加载属性 fileprivate lazy var pageTitleView : PageTitleView = {[weak self] in let titleFrame = CGRect(x: 0, y: kStatusBarH + kNavigationBarH, width: kScreenW, height: kTitleViewH) let titles = ["推荐", "游戏", "娱乐", "趣玩"] let titleView = PageTitleView(frame: titleFrame, titles: titles) titleView.delegate = self return titleView }() fileprivate lazy var pageContentView : PageContentView = {[weak self] in // 1. 确定内容的frame let contentH = kScreenH - kStatusBarH - kNavigationBarH - kTitleViewH - kTabBarH let contentFrame = CGRect(x: 0, y: kStatusBarH + kNavigationBarH + kTitleViewH, width: kScreenW, height: contentH) // 2. 确定所有的子控制器 var childVcs = [UIViewController]() childVcs.append(RecommendViewController()) childVcs.append(GameViewController()) childVcs.append(AmuseViewController()) childVcs.append(FunnyViewController()) let contentView = PageContentView(frame: contentFrame, childVcs: childVcs, parentViewController: self) contentView.delegate = self return contentView }() // MARK:- 系统回调函数 override func viewDidLoad() { super.viewDidLoad() setupUI() } } // MARK:- 设置UI界面 extension HomeViewController { fileprivate func setupUI() { // 0 不需要调整UIScrollView的内边距 automaticallyAdjustsScrollViewInsets = false // 1. 设置导航栏 setupNavigationBar() // 2. 添加titleView view.addSubview(pageTitleView) // 3. 添加contentView view.addSubview(pageContentView) pageContentView.backgroundColor = UIColor.purple } // 设置导航栏 fileprivate func setupNavigationBar() { // 1. 设置左侧的Item navigationItem.leftBarButtonItem = UIBarButtonItem(imageName: "logo") // 2. 设置右侧的Item let size = CGSize(width: 40, height: 40) let historyItem = UIBarButtonItem(imageName: "image_my_history", highImageName: "Image_my_history_click", size: size) let searchItem = UIBarButtonItem(imageName: "btn_search", highImageName: "btn_search_clicked", size: size) let qrcodeItem = UIBarButtonItem(imageName: "Image_scan", highImageName: "Image_scan_click", size: size) navigationItem.rightBarButtonItems = [historyItem,searchItem,qrcodeItem] } } // MARK:- 遵守pageTitleViewDelegate extension HomeViewController : PageTitleViewDelegate { func pageTitleView(_ titleView: PageTitleView, selectedIndex index: Int) { pageContentView.setCurrentIndex(index) } } // MARK:- 遵守PageContentViewDelegate extension HomeViewController : PageContentViewDelegate { func pageContentView(_ contentView: PageContentView, progress: CGFloat, sourceIndex: Int, targetIndex: Int) { pageTitleView.setTitleWithProgress(progress, sourceIndex: sourceIndex, targetIndex: targetIndex) } }
64e17d47e5c9b8b79af3a1fe9efe431e
33.085106
125
0.67166
false
false
false
false
tejen/codepath-instagram
refs/heads/master
Instagram/Instagram/LoginViewController.swift
apache-2.0
1
// // LoginViewController.swift // Instagram // // Created by Tejen Hasmukh Patel on 3/5/16. // Copyright © 2016 Tejen. All rights reserved. // import UIKit import Parse class LoginViewController: UIViewController, UITextFieldDelegate { @IBOutlet var usernameField: UITextField! @IBOutlet var passwordField: UITextField! @IBOutlet var logoImageView: UIImageView! @IBOutlet var usernameFieldBackgroundView: UIView! @IBOutlet var passwordFieldBackgroundView: UIView! @IBOutlet var loginButtonSuperview: UIView! @IBOutlet var signupButtonSuperview: UIView! @IBOutlet var loginButton: UIButton! @IBOutlet var activityIndicatorView: UIActivityIndicatorView! var canSubmit = false; override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. usernameField.delegate = self; passwordField.delegate = self; usernameField.attributedPlaceholder = NSAttributedString(string:"Username", attributes:[NSForegroundColorAttributeName: UIColor(white: 1, alpha: 0.7)]); passwordField.attributedPlaceholder = NSAttributedString(string:"Password", attributes:[NSForegroundColorAttributeName: UIColor(white: 1, alpha: 0.7)]); usernameFieldBackgroundView.layer.cornerRadius = 5.0; passwordFieldBackgroundView.layer.cornerRadius = 5.0; loginButtonSuperview.layer.cornerRadius = 5.0; loginButtonSuperview.layer.borderWidth = 2; loginButtonSuperview.layer.borderColor = UIColor(white: 1, alpha: 0.15).CGColor; usernameField.addTarget(self, action: "textFieldDidChange", forControlEvents: UIControlEvents.EditingChanged); passwordField.addTarget(self, action: "textFieldDidChange", forControlEvents: UIControlEvents.EditingChanged); } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated); let tabBarController = appDelegate.window?.rootViewController as! TabBarController; tabBarController.view.alpha = 1.0; UIView.animateWithDuration(0.4, animations: { () -> Void in self.logoImageView.alpha = 1; self.usernameFieldBackgroundView.alpha = 1; self.passwordFieldBackgroundView.alpha = 1; self.loginButtonSuperview.alpha = 1; self.signupButtonSuperview.alpha = 1; }); } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func onSignIn(sender: AnyObject) { if(canSubmit != true) { return; } startSubmitting(); loginButton.setTitle("", forState: .Normal); User.logInWithUsernameInBackground(usernameField.text!, password: passwordField.text!) { (user: PFUser?, error: NSError?) -> Void in if(error != nil) { self.stopSubmitting(); print(error?.localizedDescription); let alertController = UIAlertController(title: "Login Failed", message: error?.localizedDescription, preferredStyle: UIAlertControllerStyle.Alert) alertController.addAction(UIAlertAction(title: "Dismiss", style: UIAlertActionStyle.Default,handler: nil)); self.presentViewController(alertController, animated: true, completion: nil); } else { self.dismissViewControllerAnimated(true, completion: nil); } } } @IBAction func onSignUp(sender: AnyObject) { // slide up and fade out elements UIView.animateWithDuration(0.4, animations: { () -> Void in self.logoImageView.alpha = 0; self.usernameFieldBackgroundView.alpha = 0; self.passwordFieldBackgroundView.alpha = 0; self.loginButtonSuperview.alpha = 0; self.signupButtonSuperview.alpha = 0; }) { (success: Bool) -> Void in self.performSegueWithIdentifier("toSignup", sender: self); } } func stopSubmitting() { enableSubmit(); activityIndicatorView.alpha = 0; activityIndicatorView.stopAnimating(); loginButton.setTitle("Login", forState: .Normal); } func startSubmitting() { disableSubmit(); loginButton.setTitle("", forState: .Normal); activityIndicatorView.startAnimating(); activityIndicatorView.alpha = 1; } func enableSubmit() { canSubmit = true; loginButton.setTitleColor(UIColor(white: 1, alpha: 1), forState: .Normal); loginButton.userInteractionEnabled = true; } func disableSubmit() { canSubmit = false; loginButton.setTitleColor(UIColor(white: 1, alpha: 0.4), forState: .Normal); loginButton.userInteractionEnabled = false; } func textFieldDidChange() { if(usernameField.text?.characters.count > 0) { if(passwordField.text?.characters.count > 0) { enableSubmit(); return; } } disableSubmit(); } func textFieldShouldReturn(textField: UITextField) -> Bool { view.endEditing(true); return false; } /* // 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. } */ }
7bd9075a7726703b29869b7b15e64057
35.484277
140
0.639545
false
false
false
false
naoto0822/try-reactive-swift
refs/heads/master
TryRxSwift/TryRxSwift/AllItemViewController.swift
mit
1
// // AllItemViewController.swift // TryRxSwift // // Created by naoto yamaguchi on 2016/04/12. // Copyright © 2016年 naoto yamaguchi. All rights reserved. // import UIKit import SafariServices import RxSwift class AllItemViewController: UITableViewController { // MARK: - Property @IBOutlet weak var pullToRefresh: UIRefreshControl! var centerIndicator = UIActivityIndicatorView() var footerIndicator = UIActivityIndicatorView() var viewModel = AllItemViewModel() var dataSource = AllItemViewDataSource() var delegate = AllItemViewDelegate() let disposeBag = DisposeBag() override func viewDidLoad() { super.viewDidLoad() self.configureBackgroundColor() self.configureTableView() self.centerIndicator = self.configureCenterIndicator self.footerIndicator = self.configureFooterIndicator self.itemRequest() self.bind() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Private private func configureTableView() { self.tableView.backgroundColor = UIColor.clearColor() self.tableView.delegate = self.delegate self.tableView.rowHeight = 110 self.tableView.estimatedRowHeight = 110 self.tableView.registerCell(nibName: "ItemCell", forCellReuseIdentifier: "itemCell") } private func itemRequest() { self.viewModel.firstRequest() } func bind() { self.viewModel.firstLoading .asDriver() .drive(self.centerIndicator.rx_animating) .addDisposableTo(self.disposeBag) self.pullToRefresh .rx_controlEvent(.ValueChanged) .subscribe { [weak self] (_) -> Void in self?.viewModel.refreshRequest() } .addDisposableTo(self.disposeBag) self.viewModel.refreshLoading .asDriver() .drive(self.pullToRefresh.rx_refreshing) .addDisposableTo(self.disposeBag) self.rx_reachBottom .filter { () -> Bool in self.footerIndicator.isAnimating() == false } .subscribe { [weak self] (event) -> Void in print("nextPageRequest") self?.viewModel.nextPageRequest() } .addDisposableTo(self.disposeBag) self.viewModel.nextPageLoading .asDriver() .drive(self.footerIndicator.rx_animating) .addDisposableTo(self.disposeBag) self.viewModel.items .asDriver() .drive ( self.tableView.rx_itemsWithDataSource(self.dataSource) ) .addDisposableTo(self.disposeBag) self.tableView.rx_itemSelected .bindNext { [weak self] (indexPath) -> Void in let item = self?.viewModel.items.value[indexPath.row] if let urlString = item?.url, url = NSURL(string: urlString) { let safariVC = SFSafariViewController(URL: url) self?.presentViewController( safariVC, animated: true, completion: nil ) } } .addDisposableTo(self.disposeBag) } }
4e00a257b8cf6299c159aefe06f8554a
30.088496
92
0.578423
false
false
false
false
lilongcnc/firefox-ios
refs/heads/master
Client/Frontend/Settings/SettingsTableViewController.swift
mpl-2.0
1
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Account import Base32 import Shared import UIKit import XCGLogger private var ShowDebugSettings: Bool = false private var DebugSettingsClickCount: Int = 0 // A base TableViewCell, to help minimize initialization and allow recycling. class SettingsTableViewCell: UITableViewCell { override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) indentationWidth = 0 layoutMargins = UIEdgeInsetsZero // So that the seperator line goes all the way to the left edge. separatorInset = UIEdgeInsetsZero } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } // A base setting class that shows a title. You probably want to subclass this, not use it directly. class Setting { private var cell: UITableViewCell? private var _title: NSAttributedString? // The title shown on the pref var title: NSAttributedString? { return _title } // An optional second line of text shown on the pref. var status: NSAttributedString? { return nil } // Whether or not to show this pref. var hidden: Bool { return false } var style: UITableViewCellStyle { return .Subtitle } var accessoryType: UITableViewCellAccessoryType { return .None } // Called when the cell is setup. Call if you need the default behaviour. func onConfigureCell(cell: UITableViewCell) { cell.detailTextLabel?.attributedText = status cell.textLabel?.attributedText = title cell.accessoryType = accessoryType cell.accessoryView = nil } // Called when the pref is tapped. func onClick(navigationController: UINavigationController?) { return } init(title: NSAttributedString? = nil) { self._title = title } } // A setting in the sections panel. Contains a sublist of Settings class SettingSection : Setting { private let children: [Setting] init(title: NSAttributedString? = nil, children: [Setting]) { self.children = children super.init(title: title) } var count: Int { var count = 0 for setting in children { if !setting.hidden { count++ } } return count } subscript(val: Int) -> Setting? { var i = 0 for setting in children { if !setting.hidden { if i == val { return setting } i++ } } return nil } } // A helper class for prefs that deal with sync. Handles reloading the tableView data if changes to // the fxAccount happen. private class AccountSetting: Setting, FxAContentViewControllerDelegate { let settings: SettingsTableViewController var profile: Profile { return settings.profile } override var title: NSAttributedString? { return nil } init(settings: SettingsTableViewController) { self.settings = settings super.init(title: nil) } override var accessoryType: UITableViewCellAccessoryType { return .None } func contentViewControllerDidSignIn(viewController: FxAContentViewController, data: JSON) -> Void { if data["keyFetchToken"].asString == nil || data["unwrapBKey"].asString == nil { // The /settings endpoint sends a partial "login"; ignore it entirely. NSLog("Ignoring didSignIn with keyFetchToken or unwrapBKey missing.") return } // TODO: Error handling. let account = FirefoxAccount.fromConfigurationAndJSON(profile.accountConfiguration, data: data)! settings.profile.setAccount(account) // Reload the data to reflect the new Account immediately. settings.tableView.reloadData() // And start advancing the Account state in the background as well. settings.SELrefresh() settings.navigationController?.popToRootViewControllerAnimated(true) } func contentViewControllerDidCancel(viewController: FxAContentViewController) { NSLog("didCancel") settings.navigationController?.popToRootViewControllerAnimated(true) } } private class WithAccountSetting: AccountSetting { override var hidden: Bool { return !profile.hasAccount() } } private class WithoutAccountSetting: AccountSetting { override var hidden: Bool { return profile.hasAccount() } } // Sync setting for connecting a Firefox Account. Shown when we don't have an account. private class ConnectSetting: WithoutAccountSetting { override var accessoryType: UITableViewCellAccessoryType { return .DisclosureIndicator } override var title: NSAttributedString? { return NSAttributedString(string: NSLocalizedString("Sign in", comment: "Text message / button in the settings table view"), attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor]) } override func onClick(navigationController: UINavigationController?) { let viewController = FxAContentViewController() viewController.delegate = self viewController.url = settings.profile.accountConfiguration.signInURL navigationController?.pushViewController(viewController, animated: true) } } // Sync setting for disconnecting a Firefox Account. Shown when we have an account. private class DisconnectSetting: WithAccountSetting { override var accessoryType: UITableViewCellAccessoryType { return .None } override var title: NSAttributedString? { return NSAttributedString(string: NSLocalizedString("Log Out", comment: "Button in settings screen to disconnect from your account"), attributes: [NSForegroundColorAttributeName: UIConstants.DestructiveRed]) } override func onClick(navigationController: UINavigationController?) { let alertController = UIAlertController( title: NSLocalizedString("Log Out?", comment: "Title of the 'log out firefox account' alert"), message: NSLocalizedString("Firefox will stop syncing with your account, but won’t delete any of your browsing data on this device.", comment: "Text of the 'log out firefox account' alert"), preferredStyle: UIAlertControllerStyle.Alert) alertController.addAction( UIAlertAction(title: NSLocalizedString("Cancel", comment: "Cancel button in the 'log out firefox account' alert"), style: .Cancel) { (action) in // Do nothing. }) alertController.addAction( UIAlertAction(title: NSLocalizedString("Log Out", comment: "Disconnect button in the 'log out firefox account' alert"), style: .Destructive) { (action) in self.settings.profile.removeAccount() // Refresh, to show that we no longer have an Account immediately. self.settings.SELrefresh() }) navigationController?.presentViewController(alertController, animated: true, completion: nil) } } private class SyncNowSetting: WithAccountSetting { private let syncNowTitle = NSAttributedString(string: NSLocalizedString("Sync Now", comment: "Sync Firefox Account"), attributes: [NSForegroundColorAttributeName: UIColor.grayColor(), NSFontAttributeName: UIFont.systemFontOfSize(UIConstants.DefaultStandardFontSize, weight: UIFontWeightRegular)]) private let log = XCGLogger.defaultInstance() override var accessoryType: UITableViewCellAccessoryType { return .None } override var style: UITableViewCellStyle { return .Value1 } override var title: NSAttributedString? { return syncNowTitle } override func onConfigureCell(cell: UITableViewCell) { cell.textLabel?.attributedText = title cell.accessoryType = accessoryType cell.accessoryView = nil self.cell = cell } override func onClick(navigationController: UINavigationController?) { if let cell = self.cell { cell.userInteractionEnabled = false cell.textLabel?.attributedText = NSAttributedString(string: NSLocalizedString("Syncing...", comment: "Syncing Firefox Account"), attributes: [NSForegroundColorAttributeName: UIConstants.ControlTintColor]) profile.syncManager.syncEverything().uponQueue(dispatch_get_main_queue()) { result in if result.isSuccess { self.log.debug("Sync succeeded.") } else { self.log.debug("Sync failed.") } } dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 3 * Int64(NSEC_PER_SEC)), dispatch_get_main_queue(), { () -> Void in cell.textLabel?.attributedText = self.syncNowTitle cell.userInteractionEnabled = true }) } } } // Sync setting that shows the current Firefox Account status. private class AccountStatusSetting: WithAccountSetting { override var accessoryType: UITableViewCellAccessoryType { if let account = profile.getAccount() { switch account.actionNeeded { case .NeedsVerification: // We link to the resend verification email page. return .DisclosureIndicator case .NeedsPassword: // We link to the re-enter password page. return .DisclosureIndicator case .None, .NeedsUpgrade: // In future, we'll want to link to /settings and an upgrade page, respectively. return .None } } return .DisclosureIndicator } override var title: NSAttributedString? { if let account = profile.getAccount() { return NSAttributedString(string: account.email, attributes: [NSFontAttributeName: UIConstants.DefaultStandardFontBold, NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor]) } return nil } override var status: NSAttributedString? { if let account = profile.getAccount() { switch account.actionNeeded { case .None: return nil case .NeedsVerification: return NSAttributedString(string: NSLocalizedString("Verify your email address.", comment: "Text message in the settings table view"), attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor]) case .NeedsPassword: let string = NSLocalizedString("Enter your password to connect.", comment: "Text message in the settings table view") let range = NSRange(location: 0, length: count(string)) let orange = UIColor(red: 255.0 / 255, green: 149.0 / 255, blue: 0.0 / 255, alpha: 1) let attrs : [NSObject : AnyObject]? = [NSForegroundColorAttributeName : orange] let res = NSMutableAttributedString(string: string) res.setAttributes(attrs, range: range) return res case .NeedsUpgrade: let string = NSLocalizedString("Upgrade Firefox to connect.", comment: "Text message in the settings table view") let range = NSRange(location: 0, length: count(string)) let orange = UIColor(red: 255.0 / 255, green: 149.0 / 255, blue: 0.0 / 255, alpha: 1) let attrs : [NSObject : AnyObject]? = [NSForegroundColorAttributeName : orange] let res = NSMutableAttributedString(string: string) res.setAttributes(attrs, range: range) return res } } return nil } override func onClick(navigationController: UINavigationController?) { let viewController = FxAContentViewController() viewController.delegate = self if let account = profile.getAccount() { switch account.actionNeeded { case .NeedsVerification: let cs = NSURLComponents(URL: account.configuration.settingsURL, resolvingAgainstBaseURL: false) cs?.queryItems?.append(NSURLQueryItem(name: "email", value: account.email)) viewController.url = cs?.URL case .NeedsPassword: let cs = NSURLComponents(URL: account.configuration.forceAuthURL, resolvingAgainstBaseURL: false) cs?.queryItems?.append(NSURLQueryItem(name: "email", value: account.email)) viewController.url = cs?.URL case .None, .NeedsUpgrade: // In future, we'll want to link to /settings and an upgrade page, respectively. if let cs = NSURLComponents(URL: account.configuration.forceAuthURL, resolvingAgainstBaseURL: false) { cs.queryItems?.append(NSURLQueryItem(name: "email", value: account.email)) viewController.url = cs.URL } } } navigationController?.pushViewController(viewController, animated: true) } } // For great debugging! private class RequirePasswordDebugSetting: WithAccountSetting { override var hidden: Bool { if !ShowDebugSettings { return true } if let account = profile.getAccount() where account.actionNeeded != FxAActionNeeded.NeedsPassword { return false } return true } override var title: NSAttributedString? { return NSAttributedString(string: NSLocalizedString("Debug: require password", comment: "Debug option"), attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor]) } override func onClick(navigationController: UINavigationController?) { profile.getAccount()?.makeSeparated() settings.tableView.reloadData() } } // For great debugging! private class RequireUpgradeDebugSetting: WithAccountSetting { override var hidden: Bool { if !ShowDebugSettings { return true } if let account = profile.getAccount() where account.actionNeeded != FxAActionNeeded.NeedsUpgrade { return false } return true } override var title: NSAttributedString? { return NSAttributedString(string: NSLocalizedString("Debug: require upgrade", comment: "Debug option"), attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor]) } override func onClick(navigationController: UINavigationController?) { profile.getAccount()?.makeDoghouse() settings.tableView.reloadData() } } // For great debugging! private class ForgetSyncAuthStateDebugSetting: WithAccountSetting { override var hidden: Bool { if !ShowDebugSettings { return true } if let account = profile.getAccount() { return false } return true } override var title: NSAttributedString? { return NSAttributedString(string: NSLocalizedString("Debug: forget Sync auth state", comment: "Debug option"), attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor]) } override func onClick(navigationController: UINavigationController?) { profile.getAccount()?.syncAuthState.invalidate() settings.tableView.reloadData() } } // Show the current version of Firefox private class VersionSetting : Setting { let settings: SettingsTableViewController init(settings: SettingsTableViewController) { self.settings = settings super.init(title: nil) } override var title: NSAttributedString? { let appVersion = NSBundle.mainBundle().objectForInfoDictionaryKey("CFBundleShortVersionString") as! String let buildNumber = NSBundle.mainBundle().objectForInfoDictionaryKey("CFBundleVersion") as! String return NSAttributedString(string: String(format: NSLocalizedString("Version %@ (%@)", comment: "Version number of Firefox shown in settings"), appVersion, buildNumber), attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor]) } override func onClick(navigationController: UINavigationController?) { if AppConstants.BuildChannel != .Aurora { DebugSettingsClickCount += 1 if DebugSettingsClickCount >= 5 { DebugSettingsClickCount = 0 ShowDebugSettings = !ShowDebugSettings settings.tableView.reloadData() } } } } // Opens the the license page in a new tab private class LicenseAndAcknowledgementsSetting: Setting { init() { super.init(title: NSAttributedString(string: NSLocalizedString("Licenses", comment: "Settings item that opens a tab containing the licenses. See http://mzl.la/1NSAWCG"), attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor])) } override func onClick(navigationController: UINavigationController?) { navigationController?.dismissViewControllerAnimated(true, completion: { if let appDelegate = UIApplication.sharedApplication().delegate as? AppDelegate { let rootNavigationController = appDelegate.rootViewController rootNavigationController.popViewControllerAnimated(true) if let url = NSURL(string: WebServer.sharedInstance.URLForResource("license", module: "about")) { appDelegate.browserViewController.openURLInNewTab(url) } } }) } } // Opens the on-boarding screen again private class ShowIntroductionSetting: Setting { let profile: Profile init(settings: SettingsTableViewController) { self.profile = settings.profile super.init(title: NSAttributedString(string: NSLocalizedString("Show Tour", comment: "Show the on-boarding screen again from the settings"), attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor])) } override func onClick(navigationController: UINavigationController?) { navigationController?.dismissViewControllerAnimated(true, completion: { if let appDelegate = UIApplication.sharedApplication().delegate as? AppDelegate { let rootNavigationController = appDelegate.rootViewController appDelegate.browserViewController.presentIntroViewController(force: true) } }) } } // Opens the the SUMO page in a new tab private class OpenSupportPageSetting: Setting { init() { super.init(title: NSAttributedString(string: NSLocalizedString("Help", comment: "Show the SUMO support page from the Support section in the settings. see http://mzl.la/1dmM8tZ"), attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor])) } override func onClick(navigationController: UINavigationController?) { navigationController?.dismissViewControllerAnimated(true, completion: { if let appDelegate = UIApplication.sharedApplication().delegate as? AppDelegate { let rootNavigationController = appDelegate.rootViewController rootNavigationController.popViewControllerAnimated(true) if let url = NSURL(string: "https://support.mozilla.org/products/ios") { appDelegate.browserViewController.openURLInNewTab(url) } } }) } } class UseCompactTabLayoutSetting: Setting { let profile: Profile init(settings: SettingsTableViewController) { self.profile = settings.profile super.init(title: NSAttributedString(string: NSLocalizedString("Use Compact Tabs", comment: "Setting to enable compact tabs in the tab overview"), attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor])) } override func onConfigureCell(cell: UITableViewCell) { super.onConfigureCell(cell) let control = UISwitch() control.onTintColor = UIConstants.ControlTintColor control.addTarget(self, action: "switchValueChanged:", forControlEvents: UIControlEvents.ValueChanged) control.on = profile.prefs.boolForKey("CompactTabLayout") ?? true cell.accessoryView = control } @objc func switchValueChanged(control: UISwitch) { profile.prefs.setBool(control.on, forKey: "CompactTabLayout") } } // Opens the search settings pane private class SearchSetting: Setting { let profile: Profile override var accessoryType: UITableViewCellAccessoryType { return .DisclosureIndicator } override var style: UITableViewCellStyle { return .Value1 } override var status: NSAttributedString { return NSAttributedString(string: profile.searchEngines.defaultEngine.shortName) } init(settings: SettingsTableViewController) { self.profile = settings.profile super.init(title: NSAttributedString(string: NSLocalizedString("Search", comment: "Open search section of settings"), attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor])) } override func onClick(navigationController: UINavigationController?) { let viewController = SearchSettingsTableViewController() viewController.model = profile.searchEngines navigationController?.pushViewController(viewController, animated: true) } } private class ClearPrivateDataSetting: Setting { let profile: Profile var tabManager: TabManager! init(settings: SettingsTableViewController) { self.profile = settings.profile self.tabManager = settings.tabManager let clearTitle = NSLocalizedString("Clear Private Data", comment: "Label used as an item in Settings. When touched it will open a dialog prompting the user to make sure they want to clear all of their private data.") super.init(title: NSAttributedString(string: clearTitle, attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor])) } override func onClick(navigationController: UINavigationController?) { let clearable = EverythingClearable(profile: profile, tabmanager: tabManager) var title: String { return NSLocalizedString("Clear Everything", tableName: "ClearPrivateData", comment: "Title of the Clear private data dialog.") } var message: String { return NSLocalizedString("Are you sure you want to clear all of your data? This will also close all open tabs.", tableName: "ClearPrivateData", comment: "Message shown in the dialog prompting users if they want to clear everything") } let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.Alert) let clearString = NSLocalizedString("Clear", tableName: "ClearPrivateData", comment: "Used as a button label in the dialog to Clear private data dialog") alert.addAction(UIAlertAction(title: clearString, style: UIAlertActionStyle.Destructive, handler: { (action) -> Void in clearable.clear() >>== { NSNotificationCenter.defaultCenter().postNotificationName(NotificationPrivateDataCleared, object: nil) } })) let cancelString = NSLocalizedString("Cancel", tableName: "ClearPrivateData", comment: "Used as a button label in the dialog to cancel clear private data dialog") alert.addAction(UIAlertAction(title: cancelString, style: UIAlertActionStyle.Cancel, handler: { (action) -> Void in })) navigationController?.presentViewController(alert, animated: true) { () -> Void in } } } private class SendCrashReportsSetting: Setting { let profile: Profile init(settings: SettingsTableViewController) { self.profile = settings.profile super.init(title: NSAttributedString(string: NSLocalizedString("Send Crash Reports", comment: "Setting to enable the sending of crash reports"), attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor])) } override func onConfigureCell(cell: UITableViewCell) { super.onConfigureCell(cell) let control = UISwitch() control.onTintColor = UIConstants.ControlTintColor control.addTarget(self, action: "switchValueChanged:", forControlEvents: UIControlEvents.ValueChanged) control.on = profile.prefs.boolForKey("crashreports.send.always") ?? false cell.accessoryView = control } @objc func switchValueChanged(control: UISwitch) { profile.prefs.setBool(control.on, forKey: "crashreports.send.always") configureActiveCrashReporter(profile.prefs.boolForKey("crashreports.send.always")) } } private class PopupBlockingSettings: Setting { let prefs: Prefs let tabManager: TabManager! let prefKey = "blockPopups" init(settings: SettingsTableViewController) { self.prefs = settings.profile.prefs self.tabManager = settings.tabManager let title = NSLocalizedString("Block Pop-up Windows", comment: "Block pop-up windows setting") super.init(title: NSAttributedString(string: title)) } override func onConfigureCell(cell: UITableViewCell) { super.onConfigureCell(cell) let control = UISwitch() control.onTintColor = UIConstants.ControlTintColor control.addTarget(self, action: "switchValueChanged:", forControlEvents: UIControlEvents.ValueChanged) control.on = prefs.boolForKey(prefKey) ?? true cell.accessoryView = control } @objc func switchValueChanged(toggle: UISwitch) { prefs.setObject(toggle.on, forKey: prefKey) } } // The base settings view controller. class SettingsTableViewController: UITableViewController { private let Identifier = "CellIdentifier" private let SectionHeaderIdentifier = "SectionHeaderIdentifier" private var settings = [SettingSection]() var profile: Profile! var tabManager: TabManager! override func viewDidLoad() { super.viewDidLoad() let privacyTitle = NSLocalizedString("Privacy", comment: "Privacy section title") let accountDebugSettings: [Setting] if AppConstants.BuildChannel != .Aurora { accountDebugSettings = [ // Debug settings: RequirePasswordDebugSetting(settings: self), RequireUpgradeDebugSetting(settings: self), ForgetSyncAuthStateDebugSetting(settings: self), ] } else { accountDebugSettings = [] } var generalSettings = [ SearchSetting(settings: self), PopupBlockingSettings(settings: self), ] // There is nothing to show in the Customize section if we don't include the compact tab layout // setting on iPad. When more options are added that work on both device types, this logic can // be changed. if UIDevice.currentDevice().userInterfaceIdiom == .Phone { generalSettings += [UseCompactTabLayoutSetting(settings: self)] } settings += [ SettingSection(title: nil, children: [ // Without a Firefox Account: ConnectSetting(settings: self), // With a Firefox Account: AccountStatusSetting(settings: self), SyncNowSetting(settings: self) ] + accountDebugSettings), SettingSection(title: NSAttributedString(string: NSLocalizedString("General", comment: "General settings section title")), children: generalSettings) ] settings += [ SettingSection(title: NSAttributedString(string: privacyTitle), children: [ ClearPrivateDataSetting(settings: self), SendCrashReportsSetting(settings: self) ]), SettingSection(title: NSAttributedString(string: NSLocalizedString("Support", comment: "Support section title")), children: [ ShowIntroductionSetting(settings: self), OpenSupportPageSetting() ]), SettingSection(title: NSAttributedString(string: NSLocalizedString("About", comment: "About settings section title")), children: [ VersionSetting(settings: self), LicenseAndAcknowledgementsSetting(), DisconnectSetting(settings: self) ]) ] navigationItem.title = NSLocalizedString("Settings", comment: "Settings") navigationItem.leftBarButtonItem = UIBarButtonItem( title: NSLocalizedString("Done", comment: "Done button on left side of the Settings view controller title bar"), style: UIBarButtonItemStyle.Done, target: navigationController, action: "SELdone") tableView.registerClass(SettingsTableViewCell.self, forCellReuseIdentifier: Identifier) tableView.registerClass(SettingsTableSectionHeaderView.self, forHeaderFooterViewReuseIdentifier: SectionHeaderIdentifier) tableView.tableFooterView = SettingsTableFooterView(frame: CGRect(x: 0, y: 0, width: view.frame.width, height: 128)) tableView.separatorColor = UIConstants.TableViewSeparatorColor tableView.backgroundColor = UIConstants.TableViewHeaderBackgroundColor } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) SELrefresh() } @objc private func SELrefresh() { // Through-out, be aware that modifying the control while a refresh is in progress is /not/ supported and will likely crash the app. if let account = self.profile.getAccount() { // Add the refresh control right away. if refreshControl == nil { refreshControl = UIRefreshControl() refreshControl?.addTarget(self, action: "SELrefresh", forControlEvents: UIControlEvents.ValueChanged) } refreshControl?.beginRefreshing() account.advance().upon { _ in dispatch_async(dispatch_get_main_queue()) { () -> Void in self.tableView.reloadData() self.refreshControl?.endRefreshing() } } } else { // Remove the refresh control immediately after ending the refresh. refreshControl?.endRefreshing() if let refreshControl = self.refreshControl { refreshControl.removeFromSuperview() } refreshControl = nil self.tableView.reloadData() } } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let section = settings[indexPath.section] if let setting = section[indexPath.row] { var cell: UITableViewCell! if let status = setting.status { // Work around http://stackoverflow.com/a/9999821 and http://stackoverflow.com/a/25901083 by using a new cell. // I could not make any setNeedsLayout solution work in the case where we disconnect and then connect a new account. // Be aware that dequeing and then ignoring a cell appears to cause issues; only deque a cell if you're going to return it. cell = SettingsTableViewCell(style: setting.style, reuseIdentifier: nil) } else { cell = tableView.dequeueReusableCellWithIdentifier(Identifier, forIndexPath: indexPath) as! UITableViewCell } setting.onConfigureCell(cell) return cell } return tableView.dequeueReusableCellWithIdentifier(Identifier, forIndexPath: indexPath) as! UITableViewCell } override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return settings.count } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { let section = settings[section] return section.count } override func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let headerView = tableView.dequeueReusableHeaderFooterViewWithIdentifier(SectionHeaderIdentifier) as! SettingsTableSectionHeaderView let section = settings[section] if let sectionTitle = section.title?.string { headerView.titleLabel.text = sectionTitle.uppercaseString } return headerView } override func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { // empty headers should be 13px high, but headers with text should be 44 var height: CGFloat = 13 let section = settings[section] if let sectionTitle = section.title { if sectionTitle.length > 0 { height = 44 } } return height } override func tableView(tableView: UITableView, willSelectRowAtIndexPath indexPath: NSIndexPath) -> NSIndexPath? { let section = settings[indexPath.section] if let setting = section[indexPath.row] { setting.onClick(navigationController) } return nil } override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { if (indexPath.section == 0 && indexPath.row == 0) { return 64 } //make account/sign-in row taller, as per design specs return 44 } } class SettingsTableFooterView: UITableViewHeaderFooterView { var logo: UIImageView = { var image = UIImageView(image: UIImage(named: "settingsFlatfox")) image.contentMode = UIViewContentMode.Center return image }() override init(reuseIdentifier: String?) { super.init(reuseIdentifier: reuseIdentifier) } override init(frame: CGRect) { super.init(frame: frame) self.contentView.backgroundColor = UIConstants.TableViewHeaderBackgroundColor var topBorder = UIView(frame: CGRect(x: 0, y: 0, width: frame.width, height: 0.5)) topBorder.backgroundColor = UIConstants.TableViewSeparatorColor addSubview(topBorder) addSubview(logo) logo.snp_makeConstraints { (make) -> Void in make.centerY.centerX.equalTo(self) } } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } class SettingsTableSectionHeaderView: UITableViewHeaderFooterView { var titleLabel: UILabel = { var headerLabel = UILabel() var frame = headerLabel.frame frame.origin.x = 15 frame.origin.y = 25 headerLabel.frame = frame headerLabel.textColor = UIConstants.TableViewHeaderTextColor headerLabel.font = UIFont.systemFontOfSize(12.0, weight: UIFontWeightRegular) return headerLabel }() override init(reuseIdentifier: String?) { super.init(reuseIdentifier: reuseIdentifier) } override init(frame: CGRect) { super.init(frame: frame) self.contentView.backgroundColor = UIConstants.TableViewHeaderBackgroundColor addSubview(titleLabel) self.clipsToBounds = true } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func drawRect(rect: CGRect) { let topBorder = CALayer() topBorder.frame = CGRectMake(0.0, 0.0, rect.size.width, 0.5) topBorder.backgroundColor = UIConstants.SeparatorColor.CGColor layer.addSublayer(topBorder) let bottomBorder = CALayer() bottomBorder.frame = CGRectMake(0.0, rect.size.height - 0.5, rect.size.width, 0.5) bottomBorder.backgroundColor = UIConstants.SeparatorColor.CGColor layer.addSublayer(bottomBorder) } override func layoutSubviews() { super.layoutSubviews() titleLabel.sizeToFit() } }
e47f03b2eaae5244c0a47ebb509bd103
42.259928
300
0.68013
false
false
false
false
psharanda/LayoutOps
refs/heads/master
Demos/Demos/DocGenViewController.swift
mit
1
// // Created by Pavel Sharanda on 11.11.16. // Copyright © 2016 psharanda. All rights reserved. // import UIKit class DocGenViewController: UIViewController { fileprivate let sections: [Section] init(sections: [Section]) { self.sections = sections super.init(nibName: nil, bundle: nil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = UIColor.white } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) makeSnapshots() } fileprivate struct SectionRow { let sectionTitle: String let row: RowProtocol } fileprivate func makeSnapshots() { warnAboutSRCROOT = true let allRows = sections.flatMap { section in section.rows.map { SectionRow(sectionTitle: section.title, row: $0) } } let codebaseString = (try! NSString(contentsOfFile: Bundle.main.path(forResource: "Codebase.generated.txt", ofType: nil)!, encoding: String.Encoding.utf8.rawValue)) as String var currentRowIndex = 0 var markdownString = "" var currentSectionString = "" func renderRow(_ completion: @escaping ()->Void) { let sectionRow = allRows[currentRowIndex] if currentSectionString != sectionRow.sectionTitle { currentSectionString = sectionRow.sectionTitle markdownString += "### \(currentSectionString)" markdownString += "\n" } markdownString += "#### \(sectionRow.row.title)" markdownString += "\n" markdownString += sectionRow.row.comments markdownString += "\n" let v1 = sectionRow.row.view view.addSubview(v1) v1.frame = CGRect(x: 0, y: 0, width: 320, height: 480) v1.layoutIfNeeded() v1.backgroundColor = UIColor(white: 0.9, alpha: 1) let layoutCode = extractLayoutSourceCode(codebaseString , view: v1) markdownString += "```swift" markdownString += "\n" markdownString += layoutCode markdownString += "\n" markdownString += "```" markdownString += "\n" let v2 = sectionRow.row.view view.addSubview(v2) v2.frame = CGRect(x: 0, y: 0, width: 480, height: 320) v2.layoutIfNeeded() v2.backgroundColor = UIColor(white: 0.9, alpha: 1) after { let f1 = "\(sectionRow.sectionTitle)_\(sectionRow.row.title)_portrait.png".stringForFilePath let img1 = imageWithView(v1) saveImageAsPngInTempFolder(img1, name: f1) v1.removeFromSuperview() let f2 = "\(sectionRow.sectionTitle)__\(sectionRow.row.title)_landscape.png".stringForFilePath let img2 = imageWithView(v2) saveImageAsPngInTempFolder(img2, name: f2) v2.removeFromSuperview() markdownString += "<img src=\"https://raw.githubusercontent.com/psharanda/LayoutOps/master/README/\(f1)\" alt=\"\(sectionRow.row.title)\" width=\"\(img1.size.width/2)\" height=\"\(img1.size.height/2)\"/> " markdownString += "<img src=\"https://raw.githubusercontent.com/psharanda/LayoutOps/master/README/\(f2)\" alt=\"\(sectionRow.row.title)\" width=\"\(img2.size.width/2)\" height=\"\(img2.size.height/2)\"/>" markdownString += "\n" currentRowIndex += 1 if currentRowIndex >= allRows.count { completion() } else { renderRow(completion) } } } renderRow { let mdPath = (documentationPath() as NSString).appendingPathComponent("DEMOS.md") let _ = try?(markdownString as NSString).write(toFile: mdPath, atomically: false, encoding: String.Encoding.utf8.rawValue) print("Documentation saved to "+documentationPath()) _ = self.navigationController?.popViewController(animated: true) } } } private func extractLayoutSourceCode(_ codebase: String, view: UIView) -> String { let scanner = Scanner(string: codebase) scanner.charactersToBeSkipped = nil let className = String(describing: type(of: view)) if scanner.scanUpToString("class \(className)") != nil { if scanner.scanUpToString("super.layoutSubviews()") != nil { if let code = scanner.scanUpToString("static") { var almostResult = code.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines) almostResult = almostResult.trimmingCharacters(in: CharacterSet(charactersIn: "}")) almostResult = almostResult.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines) return (almostResult as NSString).replacingOccurrences(of: "super.layoutSubviews()", with: "").replacingOccurrences(of: "\n ", with: "\n") } } } return "<<error>>" } private func after(_ f: @escaping ()->Void) { DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + Double(Int64(0.1 * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC), execute: f) } private func imageWithView(_ view: UIView) -> UIImage { UIGraphicsBeginImageContextWithOptions(view.bounds.size, view.isOpaque, 0.0) view.drawHierarchy(in: view.bounds, afterScreenUpdates: false) let img = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return img! } private func saveImageAsPngInTempFolder(_ image: UIImage, name: String) { #if swift(>=4.2) let imgData = image.pngData() #else let imgData = UIImagePNGRepresentation(image) #endif if let imgData = imgData { let imgPath = (documentationPath() as NSString).appendingPathComponent(name) try? imgData.write(to: URL(fileURLWithPath: imgPath), options: []) } } private func isSimulator() -> Bool { return TARGET_OS_SIMULATOR != 0 } var warnAboutSRCROOT = true private func documentationPath() -> String { if isSimulator() { if CommandLine.arguments.count < 2 { if warnAboutSRCROOT { print("WARNING: Add '$SRCROOT' to 'Arguments passed on launch' section to generate documentation in README folder") warnAboutSRCROOT = false } return NSTemporaryDirectory() } else { return ((CommandLine.arguments[1] as NSString).deletingLastPathComponent as NSString).appendingPathComponent("README") } } else { return NSTemporaryDirectory() } } extension String { var stringForFilePath: String { // characterSet contains all illegal characters on OS X and Windows let characterSet = CharacterSet(charactersIn: "\"\\/?<>:*|") // replace "-" with character of choice return components(separatedBy: characterSet).joined(separator: "-") } }
39824093b91d0d46a1180abc1bfd1292
35.458537
221
0.589109
false
false
false
false
russbishop/swift
refs/heads/master
benchmark/single-source/Phonebook.swift
apache-2.0
1
//===--- Phonebook.swift --------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // This test is based on util/benchmarks/Phonebook, with modifications // for performance measuring. import TestsUtils var words=[ "James", "John", "Robert", "Michael", "William", "David", "Richard", "Joseph", "Charles", "Thomas", "Christopher", "Daniel", "Matthew", "Donald", "Anthony", "Paul", "Mark", "George", "Steven", "Kenneth", "Andrew", "Edward", "Brian", "Joshua", "Kevin", "Ronald", "Timothy", "Jason", "Jeffrey", "Gary", "Ryan", "Nicholas", "Eric", "Stephen", "Jacob", "Larry", "Frank", "Jonathan", "Scott", "Justin", "Raymond", "Brandon", "Gregory", "Samuel", "Patrick", "Benjamin", "Jack", "Dennis", "Jerry", "Alexander", "Tyler", "Douglas", "Henry", "Peter", "Walter", "Aaron", "Jose", "Adam", "Harold", "Zachary", "Nathan", "Carl", "Kyle", "Arthur", "Gerald", "Lawrence", "Roger", "Albert", "Keith", "Jeremy", "Terry", "Joe", "Sean", "Willie", "Jesse", "Ralph", "Billy", "Austin", "Bruce", "Christian", "Roy", "Bryan", "Eugene", "Louis", "Harry", "Wayne", "Ethan", "Jordan", "Russell", "Alan", "Philip", "Randy", "Juan", "Howard", "Vincent", "Bobby", "Dylan", "Johnny", "Phillip", "Craig"] // This is a phone book record. struct Record : Comparable { var first: String var last: String init(_ first_ : String,_ last_ : String) { first = first_ last = last_ } } func ==(lhs: Record, rhs: Record) -> Bool { return lhs.last == rhs.last && lhs.first == rhs.first } func <(lhs: Record, rhs: Record) -> Bool { if lhs.last < rhs.last { return true } if lhs.last > rhs.last { return false } if lhs.first < rhs.first { return true } return false } @inline(never) public func run_Phonebook(_ N: Int) { // The list of names in the phonebook. var Names : [Record] = [] for first in words { for last in words { Names.append(Record(first, last)) } } for _ in 1...N { var t = Names; t.sort() } }
4321883413b079f2ed13127abcafba99
31.77027
81
0.579381
false
false
false
false
aclissold/Alamofire
refs/heads/master
Tests/ResponseTests.swift
mit
5
// ResponseTests.swift // // Copyright (c) 2014–2015 Alamofire Software Foundation (http://alamofire.org/) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Alamofire import Foundation import XCTest class JSONResponseTestCase: BaseTestCase { func testGETRequestJSONResponse() { // Given let URL = "http://httpbin.org/get" let expectation = expectationWithDescription("\(URL)") var request: NSURLRequest? var response: NSHTTPURLResponse? var JSON: AnyObject? var error: NSError? // When Alamofire.request(.GET, URL, parameters: ["foo": "bar"]) .responseJSON { responseRequest, responseResponse, responseJSON, responseError in request = responseRequest response = responseResponse JSON = responseJSON error = responseError expectation.fulfill() } waitForExpectationsWithTimeout(self.defaultTimeout, handler: nil) // Then XCTAssertNotNil(request, "request should not be nil") XCTAssertNotNil(response, "response should not be nil") XCTAssertNotNil(JSON, "JSON should not be nil") XCTAssertNil(error, "error should be nil") if let args = JSON?["args"] as? NSObject { XCTAssertEqual(args, ["foo": "bar"], "args should match parameters") } else { XCTFail("args should not be nil") } } func testPOSTRequestJSONResponse() { // Given let URL = "http://httpbin.org/post" let expectation = expectationWithDescription("\(URL)") var request: NSURLRequest? var response: NSHTTPURLResponse? var JSON: AnyObject? var error: NSError? // When Alamofire.request(.POST, URL, parameters: ["foo": "bar"]) .responseJSON { responseRequest, responseResponse, responseJSON, responseError in request = responseRequest response = responseResponse JSON = responseJSON error = responseError expectation.fulfill() } waitForExpectationsWithTimeout(self.defaultTimeout, handler: nil) // Then XCTAssertNotNil(request, "request should not be nil") XCTAssertNotNil(response, "response should not be nil") XCTAssertNotNil(JSON, "JSON should not be nil") XCTAssertNil(error, "error should be nil") if let form = JSON?["form"] as? NSObject { XCTAssertEqual(form, ["foo": "bar"], "form should match parameters") } else { XCTFail("form should not be nil") } } } // MARK: - class RedirectResponseTestCase: BaseTestCase { func testThatRequestWillPerformHTTPRedirectionByDefault() { // Given let redirectURLString = "http://www.apple.com" let URLString = "http://httpbin.org/redirect-to?url=\(redirectURLString)" let expectation = expectationWithDescription("Request should redirect to \(redirectURLString)") var request: NSURLRequest? var response: NSHTTPURLResponse? var data: AnyObject? var error: NSError? // When Alamofire.request(.GET, URLString) .response { responseRequest, responseResponse, responseData, responseError in request = responseRequest response = responseResponse data = responseData error = responseError expectation.fulfill() } waitForExpectationsWithTimeout(self.defaultTimeout, handler: nil) // Then XCTAssertNotNil(request, "request should not be nil") XCTAssertNotNil(response, "response should not be nil") XCTAssertNotNil(data, "data should not be nil") XCTAssertNil(error, "error should be nil") XCTAssertEqual(response?.URL?.URLString ?? "", redirectURLString, "response URL should match the redirect URL") XCTAssertEqual(response?.statusCode ?? -1, 200, "response should have a 200 status code") } func testThatRequestWillPerformRedirectionMultipleTimesByDefault() { // Given let redirectURLString = "http://httpbin.org/get" let URLString = "http://httpbin.org/redirect/5" let expectation = expectationWithDescription("Request should redirect to \(redirectURLString)") var request: NSURLRequest? var response: NSHTTPURLResponse? var data: AnyObject? var error: NSError? // When Alamofire.request(.GET, URLString) .response { responseRequest, responseResponse, responseData, responseError in request = responseRequest response = responseResponse data = responseData error = responseError expectation.fulfill() } waitForExpectationsWithTimeout(self.defaultTimeout, handler: nil) // Then XCTAssertNotNil(request, "request should not be nil") XCTAssertNotNil(response, "response should not be nil") XCTAssertNotNil(data, "data should not be nil") XCTAssertNil(error, "error should be nil") XCTAssertEqual(response?.URL?.URLString ?? "", redirectURLString, "response URL should match the redirect URL") XCTAssertEqual(response?.statusCode ?? -1, 200, "response should have a 200 status code") } func testThatTaskOverrideClosureCanPerformHTTPRedirection() { // Given let redirectURLString = "http://www.apple.com" let URLString = "http://httpbin.org/redirect-to?url=\(redirectURLString)" let expectation = expectationWithDescription("Request should redirect to \(redirectURLString)") let delegate: Alamofire.Manager.SessionDelegate = Alamofire.Manager.sharedInstance.delegate delegate.taskWillPerformHTTPRedirection = { _, _, _, request in return request } var request: NSURLRequest? var response: NSHTTPURLResponse? var data: AnyObject? var error: NSError? // When Alamofire.request(.GET, URLString) .response { responseRequest, responseResponse, responseData, responseError in request = responseRequest response = responseResponse data = responseData error = responseError expectation.fulfill() } waitForExpectationsWithTimeout(self.defaultTimeout, handler: nil) // Then XCTAssertNotNil(request, "request should not be nil") XCTAssertNotNil(response, "response should not be nil") XCTAssertNotNil(data, "data should not be nil") XCTAssertNil(error, "error should be nil") XCTAssertEqual(response?.URL?.URLString ?? "", redirectURLString, "response URL should match the redirect URL") XCTAssertEqual(response?.statusCode ?? -1, 200, "response should have a 200 status code") } func testThatTaskOverrideClosureCanCancelHTTPRedirection() { // Given let redirectURLString = "http://www.apple.com" let URLString = "http://httpbin.org/redirect-to?url=\(redirectURLString)" let expectation = expectationWithDescription("Request should not redirect to \(redirectURLString)") let delegate: Alamofire.Manager.SessionDelegate = Alamofire.Manager.sharedInstance.delegate delegate.taskWillPerformHTTPRedirection = { _, _, _, _ in return nil } var request: NSURLRequest? var response: NSHTTPURLResponse? var data: AnyObject? var error: NSError? // When Alamofire.request(.GET, URLString) .response { responseRequest, responseResponse, responseData, responseError in request = responseRequest response = responseResponse data = responseData error = responseError expectation.fulfill() } waitForExpectationsWithTimeout(self.defaultTimeout, handler: nil) // Then XCTAssertNotNil(request, "request should not be nil") XCTAssertNotNil(response, "response should not be nil") XCTAssertNotNil(data, "data should not be nil") XCTAssertNil(error, "error should be nil") XCTAssertEqual(response?.URL?.URLString ?? "", URLString, "response URL should match the origin URL") XCTAssertEqual(response?.statusCode ?? -1, 302, "response should have a 302 status code") } func testThatTaskOverrideClosureIsCalledMultipleTimesForMultipleHTTPRedirects() { // Given let redirectURLString = "http://httpbin.org/get" let URLString = "http://httpbin.org/redirect/5" let expectation = expectationWithDescription("Request should redirect to \(redirectURLString)") let delegate: Alamofire.Manager.SessionDelegate = Alamofire.Manager.sharedInstance.delegate var totalRedirectCount = 0 delegate.taskWillPerformHTTPRedirection = { _, _, _, request in ++totalRedirectCount return request } var request: NSURLRequest? var response: NSHTTPURLResponse? var data: AnyObject? var error: NSError? // When Alamofire.request(.GET, URLString) .response { responseRequest, responseResponse, responseData, responseError in request = responseRequest response = responseResponse data = responseData error = responseError expectation.fulfill() } waitForExpectationsWithTimeout(self.defaultTimeout, handler: nil) // Then XCTAssertNotNil(request, "request should not be nil") XCTAssertNotNil(response, "response should not be nil") XCTAssertNotNil(data, "data should not be nil") XCTAssertNil(error, "error should be nil") XCTAssertEqual(response?.URL?.URLString ?? "", redirectURLString, "response URL should match the redirect URL") XCTAssertEqual(response?.statusCode ?? -1, 200, "response should have a 200 status code") XCTAssertEqual(totalRedirectCount, 5, "total redirect count should be 5") } }
35e195ff7ff6e1ee1a5ac4ba45df5af3
37.493243
119
0.64727
false
false
false
false
hanhailong/practice-swift
refs/heads/master
HealthKit/Observing changes in HealthKit/Observing changes in HealthKit/ViewController.swift
mit
2
// // ViewController.swift // Observing changes in HealthKit // // Created by Domenico Solazzo on 08/05/15. // License MIT // import UIKit import HealthKit class ViewController: UIViewController { // Body mass let weightQuantityType = HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierBodyMass) lazy var types: Set<NSObject> = { return Set<NSObject>(arrayLiteral: self.weightQuantityType) }() // Health store lazy var healthStore = HKHealthStore() // Predicate lazy var predicate: NSPredicate = { let now = NSDate() let yesterday = NSCalendar.currentCalendar().dateByAddingUnit( NSCalendarUnit.DayCalendarUnit, value: -1, toDate: now, options: NSCalendarOptions.WrapComponents) return HKQuery.predicateForSamplesWithStartDate( yesterday, endDate: now, options: HKQueryOptions.StrictEndDate) }() // Observer Query lazy var query: HKObserverQuery = {[weak self] in let strongSelf = self! return HKObserverQuery(sampleType: strongSelf.weightQuantityType, predicate: strongSelf.predicate, updateHandler: strongSelf.weightChangedHandler ) }() override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) if HKHealthStore.isHealthDataAvailable(){ healthStore.requestAuthorizationToShareTypes(nil, readTypes: types, completion: {[weak self] (succeeded:Bool, error:NSError!) -> Void in let strongSelf = self! if succeeded && error != nil{ dispatch_async(dispatch_get_main_queue(), strongSelf.startObservingWeightChanges) }else{ if let theError = error{ println("Error \(theError)") } } }) }else{ println("Health data is not available") } } override func viewDidDisappear(animated: Bool) { super.viewDidDisappear(animated) stopObservingWeightChanges() } func startObservingWeightChanges(){ healthStore.executeQuery(query) healthStore.enableBackgroundDeliveryForType(weightQuantityType, frequency: HKUpdateFrequency.Immediate) { (succeeded:Bool, error:NSError!) -> Void in if succeeded{ println("Enabled background delivery of weight changes") }else{ if let theError = error{ print("Failed to enabled background changes") println("Error \(theError)") } } } } func stopObservingWeightChanges(){ healthStore.stopQuery(query) healthStore.disableAllBackgroundDeliveryWithCompletion{ (succeeded: Bool, error: NSError!) in if succeeded{ println("Disabled background delivery of weight changes") } else { if let theError = error{ print("Failed to disable background delivery of weight changes. ") println("Error = \(theError)") } } } } // Fetching the changes func fetchRecordedWeightsInLastDay(){ // Sorting let sortDescriptor = NSSortDescriptor(key: HKSampleSortIdentifierEndDate, ascending: true) // Query let query = HKSampleQuery(sampleType: weightQuantityType, predicate: predicate, limit: Int(HKObjectQueryNoLimit), sortDescriptors: [sortDescriptor]) {[weak self] (query:HKSampleQuery!, results:[AnyObject]!, error: NSError!) -> Void in if results.count > 0{ for sample in results as! [HKQuantitySample]{ // Get the weight in kilograms from the quantity let weightInKilograms = sample.quantity.doubleValueForUnit( HKUnit.gramUnitWithMetricPrefix(.Kilo) ) // Get the value of KG, localized for the user let formatter = NSMassFormatter() let kilogramSuffix = formatter.unitStringFromValue(weightInKilograms, unit:.Kilogram) dispatch_async(dispatch_get_main_queue(), {[weak self] in let strongSelf = self! println("Weight has been changed to " + "\(weightInKilograms) \(kilogramSuffix)") println("Change date = \(sample.startDate)") }) } }else{ print("Could not read the user's weight ") println("or no weight data was available") } } healthStore.executeQuery(query) } func weightChangedHandler(query: HKObserverQuery!, completionHandler: HKObserverQueryCompletionHandler!, error: NSError!){ } }
dac83df9d93f11ffeb13e3a56d563199
34.178808
169
0.551205
false
false
false
false
Ajunboys/actor-platform
refs/heads/master
actor-apps/app-ios/Actor/Controllers/Conversation/Cells/AABubbleServiceCell.swift
mit
55
// // Copyright (c) 2015 Actor LLC. <https://actor.im> // import Foundation // MARK: - class AABubbleServiceCell : AABubbleCell { private static let serviceBubbleFont = UIFont(name: "HelveticaNeue-Medium", size: 12)! // MARK: - // MARK: Private vars private let serviceText = UILabel() // MARK: - // MARK: Constructors init(frame: CGRect) { super.init(frame: frame, isFullSize: true) serviceText.font = AABubbleServiceCell.serviceBubbleFont; serviceText.lineBreakMode = .ByWordWrapping; serviceText.numberOfLines = 0; serviceText.textColor = UIColor.whiteColor() serviceText.contentMode = UIViewContentMode.Center serviceText.textAlignment = NSTextAlignment.Center self.contentInsets = UIEdgeInsets( top: 3, left: 8, bottom: 3, right: 8) self.bubbleInsets = UIEdgeInsets( top: 3, left: 0, bottom: 3, right: 0) mainView.addSubview(serviceText) bindBubbleType(.Service, isCompact: false) } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - // MARK: Bind override func bind(message: AMMessage, reuse: Bool, cellLayout: CellLayout, setting: CellSetting) { if (!reuse) { serviceText.text = MSG.getFormatter().formatFullServiceMessageWithSenderId(message.getSenderId(), withContent: message.getContent() as! AMServiceContent) } } // MARK: - // MARK: Getters class func measureServiceHeight(message: AMMessage) -> CGFloat { var text = MSG.getFormatter().formatFullServiceMessageWithSenderId(message.getSenderId(), withContent: message.getContent() as! AMServiceContent) return measureText(text).height + 3 + 3 + 3 + 3 } // MARK: - // MARK: Layout override func layoutContent(maxWidth: CGFloat, offsetX: CGFloat) { var insets = fullContentInsets var contentWidth = self.contentView.frame.width var contentHeight = self.contentView.frame.height var bubbleHeight = contentHeight - insets.top - insets.bottom var bubbleWidth = CGFloat(AABubbleServiceCell.maxServiceTextWidth) let serviceTextSize = serviceText.sizeThatFits(CGSize(width: bubbleWidth, height: CGFloat.max)) serviceText.frame = CGRectMake((contentWidth - serviceTextSize.width) / 2.0, insets.top, serviceTextSize.width, serviceTextSize.height); layoutBubble(serviceTextSize.width, contentHeight: serviceTextSize.height) } private static let maxServiceTextWidth = 260 private class func measureText(message: String) -> CGRect { println("measureText:service") var messageValue = message as NSString; var style = NSMutableParagraphStyle(); style.lineBreakMode = NSLineBreakMode.ByWordWrapping; var size = CGSize(width: maxServiceTextWidth, height: 0); var rect = messageValue.boundingRectWithSize(size, options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes: [NSFontAttributeName: serviceBubbleFont, NSParagraphStyleAttributeName: style], context: nil); return CGRectMake(0, 0, round(rect.width), round(rect.height)) } }
cafad8c58f8af1f10684a2ffda2a5966
34.340206
221
0.651299
false
false
false
false
elationfoundation/Reporta-iOS
refs/heads/master
IWMF/TableViewCell/Arabic/ARLocationListingCell.swift
gpl-3.0
1
// // ARLocationListingCell.swift // IWMF // // // // import UIKit class ARLocationListingCell: UITableViewCell { @IBOutlet weak var lblTitle: UILabel! @IBOutlet weak var lblDetail: UILabel! var title : String! = "" var value : NSString! = "" var detail : String! = "" override func awakeFromNib() { super.awakeFromNib() } override func setSelected(selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) } func intialize() { self.lblTitle.font = Utility.setFont() self.lblDetail.font = Utility.setDetailFont() if value != nil { if value.length > 0 { self.lblTitle.text = value as String } else { self.lblTitle.text = title } } else { self.lblTitle.text = title } self.lblDetail.text = detail } }
b5c9959ed278bb3fa4102e8aaea783c2
23.315789
63
0.565547
false
false
false
false
LeeShiYoung/LSYWeibo
refs/heads/master
Pods/ALCameraViewController/ALCameraViewController/ViewController/PhotoLibraryViewController.swift
artistic-2.0
1
// // ALImagePickerViewController.swift // ALImagePickerViewController // // Created by Alex Littlejohn on 2015/06/09. // Copyright (c) 2015 zero. All rights reserved. // import UIKit import Photos internal let ImageCellIdentifier = "ImageCell" internal let CameraCellIdentifier = "CameraCell" internal let defaultItemSpacing: CGFloat = 1 public typealias PhotoLibraryViewSelectionComplete = (asset: PHAsset?) -> Void public typealias PhotoLibraryViewSelectionAssetsComplete = (assets: [PHAsset], photoGraph: UIImage?) -> Void public typealias OpenCameraComplete = () -> Void public class PhotoLibraryViewController: UIViewController { static let manger: PhotoLibraryViewController = { return PhotoLibraryViewController() }() class func photoManger() -> PhotoLibraryViewController { return manger } var selectAssets: [PHAsset]? // var selectTag: [Int]? private var assets: PHFetchResult? = nil public var onSelectionComplete: PhotoLibraryViewSelectionComplete? public var onSelectionAssetsComplete: PhotoLibraryViewSelectionAssetsComplete? // public var onOpenCameraComplete: OpenCameraComplete? private lazy var collectionView: UICollectionView = { let layout = UICollectionViewFlowLayout() layout.itemSize = CameraGlobals.shared.photoLibraryThumbnailSize layout.minimumInteritemSpacing = defaultItemSpacing layout.minimumLineSpacing = defaultItemSpacing layout.sectionInset = UIEdgeInsetsZero let collectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: layout) collectionView.translatesAutoresizingMaskIntoConstraints = false collectionView.backgroundColor = UIColor.whiteColor() return collectionView }() public override func viewDidLoad() { super.viewDidLoad() selectAssets = [PHAsset]() // selectTag = [Int]() setNeedsStatusBarAppearanceUpdate() // let buttonImage = UIImage(named: "libraryCancel", inBundle: CameraGlobals.shared.bundle, compatibleWithTraitCollection: nil)?.imageWithRenderingMode(UIImageRenderingMode.AlwaysOriginal) navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: #selector(PhotoLibraryViewController.close)) navigationItem.rightBarButtonItem = UIBarButtonItem(title: "下一步", style: UIBarButtonItemStyle.Plain, target: self, action: #selector(PhotoLibraryViewController.next)) navigationItem.rightBarButtonItem?.enabled = false view.backgroundColor = UIColor(white: 0.2, alpha: 1) view.addSubview(collectionView) ImageFetcher() .onFailure(onFailure) .onSuccess(onSuccess) .fetch() } @objc private func close() { dismissViewControllerAnimated(true, completion: nil) } @objc private func next() { onSelectionAssetsComplete?(assets: selectAssets!, photoGraph: nil) } public override func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() collectionView.frame = view.bounds } public override func preferredStatusBarStyle() -> UIStatusBarStyle { return UIStatusBarStyle.LightContent } public func present(inViewController: UIViewController, animated: Bool) { let navigationController = UINavigationController(rootViewController: self) navigationController.navigationBar.barTintColor = UIColor.redColor() navigationController.navigationBar.barStyle = UIBarStyle.Default inViewController.presentViewController(navigationController, animated: animated, completion: nil) } public func dismiss() { onSelectionComplete?(asset: nil) } private func onSuccess(photos: PHFetchResult) { assets = photos configureCollectionView() } private func onFailure(error: NSError) { let permissionsView = PermissionsView(frame: view.bounds) permissionsView.titleLabel.text = localizedString("permissions.library.title") permissionsView.descriptionLabel.text = localizedString("permissions.library.description") view.addSubview(permissionsView) } private func configureCollectionView() { collectionView.registerClass(ImageCell.self, forCellWithReuseIdentifier: ImageCellIdentifier) collectionView.registerClass(CameraCollectionViewCell.self, forCellWithReuseIdentifier: CameraCellIdentifier) collectionView.delegate = self collectionView.dataSource = self } // private func itemAtIndexPath(indexPath: NSIndexPath) -> PHAsset? { // return assets?[indexPath.row] as? PHAsset // } private func itemAtIndexPath(index: Int) -> PHAsset? { return assets?[index-1] as? PHAsset } private lazy var animatior: PopAnimatior = { let anitor = PopAnimatior(presentCompletion: { (toView, duration, context) in self.presentAnimation(toView, duration: duration, context: context) }, dismissCompletion: { (fromView, duration, context) in self.disMissAnimation(fromView, duration: duration, context: context) }) return anitor }() } // MARK: - UICollectionViewDataSource - extension PhotoLibraryViewController : UICollectionViewDataSource { public func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { // return assets?.count ?? 1 return assets?.count == nil ? 1 : assets!.count + 1 } public func collectionView(collectionView: UICollectionView, willDisplayCell cell: UICollectionViewCell, forItemAtIndexPath indexPath: NSIndexPath) { if cell is CameraCollectionViewCell { (cell as! CameraCollectionViewCell).delegate = self } if cell is ImageCell { // if let model = itemAtIndexPath(indexPath) { if let model = itemAtIndexPath(indexPath.item) { (cell as! ImageCell).configureWithModel(model) (cell as! ImageCell).selectBtn.tag = indexPath.item+2000 (cell as! ImageCell).delegate = self } } } public func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { return indexPath.item == 0 ? collectionView.dequeueReusableCellWithReuseIdentifier(CameraCellIdentifier, forIndexPath: indexPath) : collectionView.dequeueReusableCellWithReuseIdentifier(ImageCellIdentifier, forIndexPath: indexPath) } } // MARK: - UICollectionViewDelegate - extension PhotoLibraryViewController : UICollectionViewDelegateFlowLayout { public func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) { onSelectionComplete?(asset: itemAtIndexPath(indexPath.item)) // onSelectionComplete?(asset: selectAssets) } } // MARK: - ImageCellDelegate extension PhotoLibraryViewController: ImageCellDelegate, CameraCellDelegate { // 当前选中 func selectAsset(tag: Int) { let asset = itemAtIndexPath(tag) selectAssets!.append(asset!) navigationItem.rightBarButtonItem?.enabled = true } // 移除选中 func removeAsset(tag: Int) { let asset = assets?[tag] as? PHAsset selectAssets!.removeAtIndex(selectAssets!.indexOf(asset!)!) selectAssets?.count == 0 ? (navigationItem.rightBarButtonItem?.enabled = false) : (navigationItem.rightBarButtonItem?.enabled = true) } // 打开相机 func openCamera() { let cameraVC = CameraManagerViewController { (image) in self.dismissViewControllerAnimated(false, completion: nil) self.onSelectionAssetsComplete?(assets: [], photoGraph: image) } let naviVC = UINavigationController(rootViewController: cameraVC) naviVC.transitioningDelegate = animatior naviVC.modalPresentationStyle = UIModalPresentationStyle.Custom presentViewController(naviVC, animated: true, completion: nil) } // 出现动画 private func presentAnimation(toView: UIView?, duration: NSTimeInterval, context: UIViewControllerContextTransitioning) { let y = -UIScreen.mainScreen().bounds.size.height toView?.frame.origin.y = y UIView.animateWithDuration(duration, animations: { self.view.frame.origin.y = -y toView?.frame.origin.y = 0.0 }) { (_) in context.completeTransition(true) } } // 消失动画 private func disMissAnimation(fromView: UIView?, duration: NSTimeInterval, context: UIViewControllerContextTransitioning) { let y = -UIScreen.mainScreen().bounds.size.height UIView.animateWithDuration(duration, animations: { self.view.frame.origin.y = 0 fromView?.frame.origin.y = y }) { (_) in context.completeTransition(true) } } }
669450dfbcb8178be882622f9b5ad153
34.788462
239
0.682106
false
false
false
false
julienbodet/wikipedia-ios
refs/heads/develop
Wikipedia/Code/OnThisDayCollectionViewCell+WMFFeedContentDisplaying.swift
mit
1
import UIKit extension OnThisDayCollectionViewCell { public func configure(with onThisDayEvent: WMFFeedOnThisDayEvent, dataStore: MWKDataStore, showArticles: Bool = true, theme: Theme, layoutOnly: Bool, shouldAnimateDots: Bool) { let previews = onThisDayEvent.articlePreviews ?? [] let currentYear = Calendar.current.component(.year, from: Date()) apply(theme: theme) titleLabel.text = onThisDayEvent.yearString let articleSiteURL = onThisDayEvent.siteURL let articleLanguage = onThisDayEvent.language if let eventYear = onThisDayEvent.year { let yearsSinceEvent = currentYear - eventYear.intValue subTitleLabel.text = String.localizedStringWithFormat(WMFLocalizedDateFormatStrings.yearsAgo(forSiteURL: articleSiteURL), yearsSinceEvent) } else { subTitleLabel.text = nil } descriptionLabel.text = onThisDayEvent.text if showArticles { articles = previews.map { (articlePreview) -> CellArticle in return CellArticle(articleURL:articlePreview.articleURL, title: articlePreview.displayTitle, titleHTML: articlePreview.displayTitleHTML, description: articlePreview.descriptionOrSnippet, imageURL: articlePreview.thumbnailURL) } } descriptionLabel.accessibilityLanguage = articleLanguage semanticContentAttributeOverride = MWLanguageInfo.semanticContentAttribute(forWMFLanguage: articleLanguage) isImageViewHidden = true timelineView.shouldAnimateDots = shouldAnimateDots setNeedsLayout() } }
19f206e63acba8d53d2e03684d1ab329
43.052632
241
0.69773
false
false
false
false
samphomsopha/mvvm
refs/heads/master
Carthage/Checkouts/Bond/Sources/Bond/DynamicSubject.swift
gpl-3.0
1
// // The MIT License (MIT) // // Copyright (c) 2016 Srdan Rasic (@srdanrasic) // // 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 ReactiveKit import Foundation public typealias DynamicSubject<Element> = DynamicSubject2<Element, NoError> public struct DynamicSubject2<Element, Error: Swift.Error>: SubjectProtocol, BindableProtocol { private weak var target: AnyObject? private var signal: Signal<Void, Error> private let context: ExecutionContext private let getter: (AnyObject) -> Result<Element, Error> private let setter: (AnyObject, Element) -> Void private let subject = PublishSubject<Void, Error>() private let triggerEventOnSetting: Bool public init<Target: Deallocatable>(target: Target, signal: Signal<Void, Error>, context: ExecutionContext, get: @escaping (Target) -> Result<Element, Error>, set: @escaping (Target, Element) -> Void, triggerEventOnSetting: Bool = true) { self.target = target self.signal = signal self.context = context self.getter = { get($0 as! Target) } self.setter = { set($0 as! Target, $1) } self.triggerEventOnSetting = triggerEventOnSetting } public init<Target: Deallocatable>(target: Target, signal: Signal<Void, Error>, context: ExecutionContext, get: @escaping (Target) -> Element, set: @escaping (Target, Element) -> Void, triggerEventOnSetting: Bool = true) { self.target = target self.signal = signal self.context = context self.getter = { .success(get($0 as! Target)) } self.setter = { set($0 as! Target, $1) } self.triggerEventOnSetting = triggerEventOnSetting } private init(_target: AnyObject, signal: Signal<Void, Error>, context: ExecutionContext, get: @escaping (AnyObject) -> Result<Element, Error>, set: @escaping (AnyObject, Element) -> Void, triggerEventOnSetting: Bool = true) { self.target = _target self.signal = signal self.context = context self.getter = { get($0) } self.setter = { set($0, $1) } self.triggerEventOnSetting = triggerEventOnSetting } public func on(_ event: Event<Element, Error>) { if case .next(let element) = event, let target = target { setter(target, element) if triggerEventOnSetting { subject.next() } } } public func observe(with observer: @escaping (Event<Element, Error>) -> Void) -> Disposable { guard let target = target else { observer(.completed); return NonDisposable.instance } let getter = self.getter return signal.start(with: ()).merge(with: subject).tryMap { [weak target] () -> Result<Element?, Error> in if let target = target { switch getter(target) { case .success(let element): return .success(element) case .failure(let error): return .failure(error) } } else { return .success(nil) } }.ignoreNil().take(until: (target as! Deallocatable).deallocated).observe(with: observer) } public func bind(signal: Signal<Element, NoError>) -> Disposable { if let target = target { let setter = self.setter let subject = self.subject let context = self.context let triggerEventOnSetting = self.triggerEventOnSetting return signal.take(until: (target as! Deallocatable).deallocated).observe { [weak target] event in context.execute { [weak target] in switch event { case .next(let element): guard let target = target else { return } setter(target, element) if triggerEventOnSetting { subject.next() } default: break } } } } else { return NonDisposable.instance } } /// Current value if the target is alive, otherwise `nil`. public var value: Element! { if let target = target { switch getter(target) { case .success(let value): return value case .failure: return nil } } else { return nil } } /// Transform the `getter` and `setter` by applying a `transform` on them. public func bidirectionalMap<U>(to getTransform: @escaping (Element) -> U, from setTransform: @escaping (U) -> Element) -> DynamicSubject2<U, Error>! { guard let target = target else { return nil } return DynamicSubject2<U, Error>( _target: target, signal: signal, context: context, get: { [getter] (target) -> Result<U, Error> in switch getter(target) { case .success(let value): return .success(getTransform(value)) case .failure(let error): return .failure(error) } }, set: { [setter] (target, element) in setter(target, setTransform(element)) } ) } } extension ReactiveExtensions where Base: Deallocatable { public func dynamicSubject<Element>(signal: Signal<Void, NoError>, context: ExecutionContext, triggerEventOnSetting: Bool = true, get: @escaping (Base) -> Element, set: @escaping (Base, Element) -> Void) -> DynamicSubject<Element> { return DynamicSubject(target: base, signal: signal, context: context, get: get, set: set, triggerEventOnSetting: triggerEventOnSetting) } } extension ReactiveExtensions where Base: Deallocatable, Base: BindingExecutionContextProvider { public func dynamicSubject<Element>(signal: Signal<Void, NoError>, triggerEventOnSetting: Bool = true, get: @escaping (Base) -> Element, set: @escaping (Base, Element) -> Void) -> DynamicSubject<Element> { return dynamicSubject(signal: signal, context: base.bindingExecutionContext, triggerEventOnSetting: triggerEventOnSetting, get: get, set: set) } }
a78e71743571f5d0b7af9b31606a1e6e
36.505263
146
0.634016
false
false
false
false
mac-cain13/DocumentStore
refs/heads/master
DocumentStore/Query/KeyPath+ConstantValues.swift
mit
1
// // KeyPath+ConstantValues.swift // DocumentStore // // Created by Mathijs Kadijk on 07-07-17. // Copyright © 2017 Mathijs Kadijk. All rights reserved. // import Foundation // MARK: Compare `KeyPath`s to constant values /// Equal operator. /// /// - Warning: Using a `KeyPath` that is not an `Index` for the related `Document` will result in /// a fatal error. /// /// - Parameters: /// - left: `KeyPath` on the left side of the comparison /// - right: `StorableValue` on the right side of the comparison /// - Returns: A `Predicate` representing the comparison public func == <Root, Value>(left: KeyPath<Root, Value>, right: Value) -> Predicate<Root> where Value: IndexableValue { let rightExpression = Expression<Root, Value>(forConstantValue: right) return Predicate(left: left.expressionOrFatalError, right: rightExpression, comparisonOperator: .equalTo) } /// Not equal operator. /// /// - Warning: Using a `KeyPath` that is not an `Index` for the related `Document` will result in /// a fatal error. /// /// - Parameters: /// - left: `KeyPath` on the left side of the comparison /// - right: Value on the right side of the comparison to compare against /// - Returns: A `Predicate` representing the comparison public func != <Root, Value>(left: KeyPath<Root, Value>, right: Value) -> Predicate<Root> where Value: IndexableValue { let rightExpression = Expression<Root, Value>(forConstantValue: right) return Predicate(left: left.expressionOrFatalError, right: rightExpression, comparisonOperator: .notEqualTo) } /// Greater than operator. /// /// - Warning: Using a `KeyPath` that is not an `Index` for the related `Document` will result in /// a fatal error. /// /// - Note: Will work on all types, even on for example strings. /// /// - Parameters: /// - left: `KeyPath` on the left side of the comparison /// - right: Value on the right side of the comparison to compare against /// - Returns: A `Predicate` representing the comparison public func > <Root, Value>(left: KeyPath<Root, Value>, right: Value) -> Predicate<Root> where Value: IndexableValue { let rightExpression = Expression<Root, Value>(forConstantValue: right) return Predicate(left: left.expressionOrFatalError, right: rightExpression, comparisonOperator: .greaterThan) } /// Greater than or equal operator. /// /// - Warning: Using a `KeyPath` that is not an `Index` for the related `Document` will result in /// a fatal error. /// /// - Note: Will work on all types, even on for example strings. /// /// - Parameters: /// - left: `KeyPath` on the left side of the comparison /// - right: Value on the right side of the comparison to compare against /// - Returns: A `Predicate` representing the comparison public func >= <Root, Value>(left: KeyPath<Root, Value>, right: Value) -> Predicate<Root> where Value: IndexableValue { let rightExpression = Expression<Root, Value>(forConstantValue: right) return Predicate(left: left.expressionOrFatalError, right: rightExpression, comparisonOperator: .greaterThanOrEqualTo) } /// Less than operator. /// /// - Warning: Using a `KeyPath` that is not an `Index` for the related `Document` will result in /// a fatal error. /// /// - Note: Will work on all types, even on for example strings. /// /// - Parameters: /// - left: `KeyPath` on the left side of the comparison /// - right: Value on the right side of the comparison to compare against /// - Returns: A `Predicate` representing the comparison public func < <Root, Value>(left: KeyPath<Root, Value>, right: Value) -> Predicate<Root> where Value: IndexableValue { let rightExpression = Expression<Root, Value>(forConstantValue: right) return Predicate(left: left.expressionOrFatalError, right: rightExpression, comparisonOperator: .lessThan) } /// Less than or equal operator. /// /// - Warning: Using a `KeyPath` that is not an `Index` for the related `Document` will result in /// a fatal error. /// /// - Note: Will work on all types, even on for example strings. /// /// - Parameters: /// - left: `KeyPath` on the left side of the comparison /// - right: Value on the right side of the comparison to compare against /// - Returns: A `Predicate` representing the comparison public func <= <Root, Value>(left: KeyPath<Root, Value>, right: Value) -> Predicate<Root> where Value: IndexableValue { let rightExpression = Expression<Root, Value>(forConstantValue: right) return Predicate(left: left.expressionOrFatalError, right: rightExpression, comparisonOperator: .lessThanOrEqualTo) } /// Like operator, similar in behavior to SQL LIKE. /// /// - Warning: Using a `KeyPath` that is not an `Index` for the related `Document` will result in /// a fatal error. /// /// - Note: ? and * are allowed as wildcard characters, where ? matches 1 character and * matches 0 /// or more characters. /// /// - Parameters: /// - left: `KeyPath` on the left side of the comparison /// - right: Like pattern on the right side of the comparison /// - Returns: A `Predicate` representing the comparison public func ~= <Root>(left: KeyPath<Root, String>, right: String) -> Predicate<Root> { let rightExpression = Expression<Root, String>(forConstantValue: right) return Predicate(left: left.expressionOrFatalError, right: rightExpression, comparisonOperator: .like) } /// Equates the `KeyPath` to false. /// /// - Warning: Using a `KeyPath` that is not an `Index` for the related `Document` will result in /// a fatal error. /// /// - Parameter keyPath: `KeyPath` to check for the value false /// - Returns: A `Predicate` representing the comparison prefix public func ! <Root>(keyPath: KeyPath<Root, Bool>) -> Predicate<Root> { let rightExpression = Expression<Root, Bool>(forConstantValue: false) return Predicate(left: keyPath.expressionOrFatalError, right: rightExpression, comparisonOperator: .equalTo) }
5983bdaa92790b1ba33d7bc47d0c5a23
43.977273
120
0.704228
false
false
false
false
xqz001/WWDC
refs/heads/master
WWDC/Session.swift
bsd-2-clause
1
// // Video.swift // WWDC // // Created by Guilherme Rambo on 18/04/15. // Copyright (c) 2015 Guilherme Rambo. All rights reserved. // import Foundation let SessionProgressDidChangeNotification = "SessionProgressDidChangeNotification" struct Session { var date: String? var description: String var focus: [String] var id: Int var slides: String? var title: String var track: String var url: String var year: Int var hd_url: String? var progress: Double { get { return DataStore.SharedStore.fetchSessionProgress(self) } set { DataStore.SharedStore.putSessionProgress(self, progress: newValue) NSNotificationCenter.defaultCenter().postNotificationName(SessionProgressDidChangeNotification, object: self.progressKey) } } var currentPosition: Double { get { return DataStore.SharedStore.fetchSessionCurrentPosition(self) } set { DataStore.SharedStore.putSessionCurrentPosition(self, position: newValue) } } var progressKey: String { get { return "\(year)-\(id)-progress" } } var currentPositionKey: String { get { return "\(year)-\(id)-currentPosition" } } init(date: String?, description: String, focus: [String], id: Int, slides: String?, title: String, track: String, url: String, year: Int, hd_url: String?) { self.date = date self.description = description self.focus = focus self.id = id self.slides = slides self.title = title self.track = track self.url = url self.year = year self.hd_url = hd_url } }
9c8ea2879fb3da3b2b47d79a5279686b
24.528571
158
0.598544
false
false
false
false
mleiv/SerializableData
refs/heads/master
SerializableDataDemo/SerializableDataDemo/UserDefaultsPersonsController.swift
mit
1
// // UserDefaultsPersonsController.swift // SerializableDataDemo // // Created by Emily Ivie on 10/16/15. // Copyright © 2015 Emily Ivie. All rights reserved. // import UIKit class UserDefaultsPersonsController: UITableViewController { var persons: [UserDefaultsPerson] = [] @IBOutlet weak var headerView: UIView! override func viewDidLoad() { super.viewDidLoad() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) loadData() // expand header headerView.layoutIfNeeded() headerView.subviews.first?.sizeToFit() headerView.frame.size.height = (headerView.subviews.first?.bounds.height ?? 20.0) + 10.0 tableView.tableHeaderView = headerView } func loadData() { persons = UserDefaultsPerson.getAll() tableView.reloadData() } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return persons.count } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if let indexPath = tableView.indexPathForSelectedRow , (indexPath as NSIndexPath).row < persons.count { let person = persons[(indexPath as NSIndexPath).row] if let controller = segue.destination as? UserDefaultsPersonController { controller.person = person } } super.prepare(for: segue, sender: sender) } override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { if (indexPath as NSIndexPath).row < persons.count { view.isUserInteractionEnabled = false var person = persons.remove(at: (indexPath as NSIndexPath).row) _ = person.delete() tableView.beginUpdates() tableView.deleteRows(at: [indexPath], with: UITableViewRowAnimation.automatic) tableView.endUpdates() view.isUserInteractionEnabled = true } } } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "Person", for: indexPath) if (indexPath as NSIndexPath).row < persons.count { let person = persons[(indexPath as NSIndexPath).row] cell.textLabel?.text = person.name var titleParts = [String]() if let profession = person.profession , profession.isEmpty == false { titleParts.append(profession) } if let organization = person.organization , organization.isEmpty == false { titleParts.append("@\(organization)") } cell.detailTextLabel?.text = titleParts.joined(separator: " ") } return cell } }
1bc251484955b2e76705c9954e56be67
35.313953
136
0.627602
false
false
false
false
ianyh/Highball
refs/heads/master
Highball/PhotoTableViewCell.swift
mit
1
// // PhotoTableViewCell.swift // Highball // // Created by Ian Ynda-Hummel on 8/27/14. // Copyright (c) 2014 ianynda. All rights reserved. // import UIKit import Cartography class PhotoTableViewCell: UITableViewCell { var imageViews: Array<UIImageView>! var contentLabel: UILabel! var post: Dictionary<String, AnyObject>? { didSet { if let post = self.post { let json = JSONValue(post) let photos = json["photos"].array! let photoSetLayout = json["photoset_layout"].string!.componentsSeparatedByString("") let photoCount = photos.count for imageView in self.imageViews { imageView.removeFromSuperview() } while photoCount < self.imageViews.count { self.imageViews.append(UIImageView()) } var imageViews = self.imageViews var photoIndex = 0 for (layoutRow, layoutRowString) in enumerate(photoSetLayout) { var layoutRowCount = layoutRowString.toInt()! var lastImageView: UIImageView? while layoutRowCount > 0 { let imageView = imageViews.removeAtIndex(0) let imageURLString = photos[photoIndex]["original_size"]["url"].string! imageView.setImageWithURL(NSURL(string: imageURLString)) self.contentView.addSubview(imageView) if let leftImageView = lastImageView { layout(imageView) { imageView in } } layoutRowCount-- photoIndex++ } } } } } override required init(style: UITableViewCellStyle, reuseIdentifier: String!) { super.init(style: style, reuseIdentifier: reuseIdentifier) self.setUpCell() } required init(coder aDecoder: NSCoder) { return super.init(coder: aDecoder) } func setUpCell() { self.imageViews = Array<UIImageView>() } }
84c1ea8d62f9b6f1c505bf6b478d783f
29.520548
100
0.533662
false
false
false
false
ColinConduff/BlocFit
refs/heads/master
BlocFit/Main Components/MainViewC.swift
mit
1
// // MainViewC.swift // BlocFit // // Created by Colin Conduff on 10/1/16. // Copyright © 2016 Colin Conduff. All rights reserved. // import UIKit import CoreData import CoreLocation import MultipeerConnectivity import GameKit /** Used by the sideMenu to notify the MainViewC that the user would like to segue to an auxiliary view. */ internal protocol SegueCoordinationDelegate: class { func transition(withSegueIdentifier identifier: String) } /** Used by the topMenu to notify the MainViewC that the user would like to either open the sideMenu or segue to the current bloc table view or the multipeer browser view. */ internal protocol TopMenuDelegate: class { func toggleSideMenu() func segueToCurrentBlocTable() func presentMCBrowserAndStartMCAssistant() } /** Used by the MultipeerManager to notify the MainViewC that the user has connected with a nearby peer. */ internal protocol MultipeerViewHandlerProtocol: class { func addToCurrentBloc(blocMember: BlocMember) func blocMembersContains(blocMember: BlocMember) -> Bool } /** Used by the Run History Table to notify the MainViewC that the user would like to display a past run path on the map and its values on the dashboard. */ internal protocol LoadRunDelegate: class { func tellMapToLoadRun(run: Run) } /** Used by the MapController to request the current bloc members from the MainViewC. */ internal protocol RequestMainDataDelegate: class { func getCurrentBlocMembers() -> [BlocMember] } /** Used by the GameKitManager to request that the MainViewC present GameKit-related view controller. */ internal protocol GameViewPresenterDelegate: class { func presentGameVC(_ viewController: UIViewController) } /** The initial view controller for the application. The MainViewC is responsible for controlling most of the communication and navigation between child view controllers. It also controls the opening and closing of the side menu view. */ final class MainViewC: UIViewController, LoadRunDelegate, RequestMainDataDelegate, SegueCoordinationDelegate, TopMenuDelegate, MultipeerViewHandlerProtocol, GameViewPresenterDelegate { // MARK: - Properties private weak var multipeerManagerDelegate: MultipeerManagerDelegate! private weak var dashboardUpdateDelegate: DashboardControllerProtocol! private weak var mapNotificationDelegate: MapNotificationDelegate! private weak var gameKitManagerDelegate: GameKitManagerDelegate! // used to set the dashboard's delegate in the prepare for segue method // need to find a way to do so without keeping this reference private weak var mapViewC: MapViewC? @IBOutlet weak var sideMenuContainerView: UIView! @IBOutlet weak var sideMenuContainerWidthConstraint: NSLayoutConstraint! // Created when the side menu is openned // Destroyed when the side menu is closed private weak var dismissSideMenuView: DismissSideMenuView? // Can be edited by CurrentBlocTableViewC // need a better way to synchronize blocMembers array across multiple classes private var blocMembers = [BlocMember]() { didSet { // Notify map and dashboard of change mapNotificationDelegate.blocMembersDidChange(blocMembers) dashboardUpdateDelegate.update(blocMembersCount: blocMembers.count) } } // MARK: - View Controller Lifecycle methods override func viewDidLoad() { super.viewDidLoad() hideSideMenu() } override func viewWillAppear(_ animated: Bool) { self.navigationController?.setNavigationBarHidden(true, animated: animated) super.viewWillAppear(animated) GameKitManager.sharedInstance.gameViewPresenterDelegate = self gameKitManagerDelegate = GameKitManager.sharedInstance multipeerManagerDelegate = MultipeerManager.sharedInstance MultipeerManager.sharedInstance.multipeerViewHandlerDelegate = self } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) gameKitManagerDelegate.authenticatePlayer() } override func viewWillDisappear(_ animated: Bool) { self.navigationController?.setNavigationBarHidden(false, animated: animated) super.viewWillDisappear(animated) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } // MARK: - Orientation Transition method override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { super.viewWillTransition(to: size, with: coordinator) coordinator.animate(alongsideTransition: nil) { coordinatorContext in self.tapHideSideMenu() } } // MARK: - Side Menu Methods // should be moved to a separate controller? private func hideSideMenu() { sideMenuContainerWidthConstraint.constant = 20 sideMenuContainerView.isHidden = true } // Used by dismiss side menu view UITapGestureRecognizer internal func tapHideSideMenu() { hideSideMenu() sideMenuAnimation() dismissSideMenuView?.removeFromSuperview() } private func showSideMenu() { let newWidth = view.bounds.width * 2 / 3 sideMenuContainerWidthConstraint.constant = newWidth sideMenuContainerView.isHidden = false dismissSideMenuView = DismissSideMenuView(mainVC: self, sideMenuWidth: newWidth) sideMenuAnimation() } private func sideMenuAnimation() { UIView.animate(withDuration: 0.5) { self.view.layoutIfNeeded() } } // MARK: - Action Button IBAction Method private var actionButtonImageIsStartButton = true @IBAction func actionButtonPressed(_ sender: UIButton) { let authorizedToProceed = mapNotificationDelegate.didPressActionButton() if authorizedToProceed { if actionButtonImageIsStartButton { sender.setImage(#imageLiteral(resourceName: "StopRunButton"), for: .normal) } else { sender.setImage(#imageLiteral(resourceName: "StartRunButton"), for: .normal) } actionButtonImageIsStartButton = !actionButtonImageIsStartButton } } // MARK: - Navigation // TODO: - Create a Navigator class for managing navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == SegueIdentifier.dashboardEmbedSegue { if let dashboardViewC = segue.destination as? DashboardViewC { prepareForDashboard(dashboardViewC) } } else if segue.identifier == SegueIdentifier.mapEmbedSegue { mapViewC = segue.destination as? MapViewC prepareForMap(mapViewC!) } else if segue.identifier == SegueIdentifier.runHistoryTableSegue { if let runHistoryTableViewC = segue.destination as? RunHistoryTableViewC { runHistoryTableViewC.loadRunDelegate = self } } else if segue.identifier == SegueIdentifier.currentBlocTableSegue { if let currentBlocTableViewC = segue.destination as? CurrentBlocTableViewC { currentBlocTableViewC.currentBlocTableDataSource = CurrentBlocTableDataSource(blocMembers: blocMembers) } } else if segue.identifier == SegueIdentifier.sideMenuTableEmbedSegue { if let sideMenuTableViewC = segue.destination as? SideMenuTableViewC { sideMenuTableViewC.tableDelegate = SideMenuTableDelegate(segueCoordinator: self) } } else if segue.identifier == SegueIdentifier.topMenuEmbedSegue { if let topMenuViewC = segue.destination as? TopMenuViewC { topMenuViewC.topMenuDelegate = self } } } private func prepareForDashboard(_ dashboardViewC: DashboardViewC) { let dashboardController = DashboardController() dashboardViewC.controller = dashboardController dashboardUpdateDelegate = dashboardController mapViewC?.dashboardUpdateDelegate = dashboardUpdateDelegate } private func prepareForMap(_ mapViewC: MapViewC) { let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext mapViewC.controller = MapController(requestMainDataDelegate: self, scoreReporterDelegate: GameKitManager.sharedInstance, context: context) mapNotificationDelegate = mapViewC.controller as! MapNotificationDelegate! mapViewC.dashboardUpdateDelegate = dashboardUpdateDelegate } // Updates the current blocMembers array if the user removes any // using the current bloc table view @IBAction func undwindToMainViewC(_ sender: UIStoryboardSegue) { if sender.identifier == SegueIdentifier.unwindFromCurrentBlocTable { if let currentBlocTableVC = sender.source as? CurrentBlocTableViewC, let currentBlocTableDataSource = currentBlocTableVC.currentBlocTableDataSource { blocMembers = currentBlocTableDataSource.blocMembers } } } // MARK: - LoadRunDelegate method internal func tellMapToLoadRun(run: Run) { mapNotificationDelegate.loadSavedRun(run: run) } // MARK: - RequestMainDataDelegate method // used by the map to get current bloc members internal func getCurrentBlocMembers() -> [BlocMember] { return blocMembers } // MARK: - SegueCoordinationDelegate method // (for the side menu) internal func transition(withSegueIdentifier identifier: String) { if identifier == SegueIdentifier.gameCenterSegue { gameKitManagerDelegate.showLeaderboard() } else { performSegue(withIdentifier: identifier, sender: self) } } // MARK: - TopMenuProtocol methods internal func segueToCurrentBlocTable() { performSegue(withIdentifier: SegueIdentifier.currentBlocTableSegue, sender: self) } internal func toggleSideMenu() { sideMenuContainerView.isHidden ? showSideMenu() : hideSideMenu() } // Called from TopMenuViewC when user clicks multipeer button internal func presentMCBrowserAndStartMCAssistant() { let mcBrowserVC = multipeerManagerDelegate.prepareMCBrowser() self.present(mcBrowserVC, animated: true, completion: nil) } // MARK: - MultipeerViewHandlerDelegate methods internal func blocMembersContains(blocMember: BlocMember) -> Bool { // should be in view model not view return blocMembers.contains(blocMember) } internal func addToCurrentBloc(blocMember: BlocMember) { // should not be handled by view DispatchQueue.main.sync { blocMembers.append(blocMember) } } // MARK: - GameKitManagerDelegate methods internal func presentGameVC(_ viewController: UIViewController) { present(viewController, animated: true, completion: nil) } }
796d958cad2f2051b9fb1f9e280dea45
36.528053
184
0.693167
false
false
false
false
Bouke/HAP
refs/heads/master
Sources/HAPDemo/createLogHandler.swift
mit
1
import Foundation import Logging func createLogHandler(label: String) -> LogHandler { var handler = StreamLogHandler.standardOutput(label: label) #if DEBUG switch label { case "hap.encryption": handler.logLevel = .info case "hap", _ where label.starts(with: "hap."): handler.logLevel = .debug default: handler.logLevel = .info } #else switch label { case "bridge": handler.logLevel = .info default: handler.logLevel = .warning } #endif return handler }
6b93523ef2d907cd513eac8549822fda
23.76
63
0.550889
false
false
false
false
nessBautista/iOSBackup
refs/heads/master
RxSwift_01/Pods/SwiftLocation/Sources/SwiftLocation/VisitsRequest.swift
cc0-1.0
2
/* * SwiftLocation * Easy and Efficent Location Tracker for Swift * * Created by: Daniele Margutti * Email: [email protected] * Web: http://www.danielemargutti.com * Twitter: @danielemargutti * * Copyright © 2017 Daniele Margutti * * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * */ import Foundation import CoreLocation import MapKit /// Callback for Visit requests /// /// - onDidVisit: callback called when a new visit is generated /// - onError: callback called on error public enum VisitObserver { public typealias onVisit = ((CLVisit) -> (Void)) public typealias onFailure = ((Error) -> (Void)) case onDidVisit(_: Context, _: onVisit) case onError(_: Context, _: onFailure) } // MARK: - Visit Request public class VisitsRequest: Request { /// Returns a Boolean value indicating whether two values are equal. /// /// Equality is the inverse of inequality. For any values `a` and `b`, /// `a == b` implies that `a != b` is `false`. /// /// - Parameters: /// - lhs: A value to compare. /// - rhs: Another value to compare. public static func ==(lhs: VisitsRequest, rhs: VisitsRequest) -> Bool { return lhs.hashValue == rhs.hashValue } /// Unique identifier of the request private var identifier = NSUUID().uuidString public var cancelOnError: Bool = false /// Assigned request name, used for your own convenience public var name: String? /// Hash value for Hashable protocol public var hashValue: Int { return identifier.hash } /// Callback to call when request's state did change public var onStateChange: ((_ old: RequestState, _ new: RequestState) -> (Void))? private var registeredCallbacks: [VisitObserver] = [] /// This represent the current state of the Request internal var _previousState: RequestState = .idle internal(set) var _state: RequestState = .idle { didSet { if _previousState != _state { onStateChange?(_previousState,_state) _previousState = _state } } } public var state: RequestState { get { return self._state } } public var requiredAuth: Authorization { return .always } /// Description of the request public var description: String { let name = (self.name ?? self.identifier) return "[VIS:\(name)] (Status=\(self.state), Queued=\(self.isInQueue))" } /// `true` if request is on location queue public var isInQueue: Bool { return Location.isQueued(self) == true } /// Initialize a new visit request. /// Visit objects contain as much information about the visit as possible but may not always include both the arrival /// and departure times. For example, when the user arrives at a location, the system may send an event with only an arrival time. When /// the user departs a location, the event can contain both the arrival time (if your app was monitoring visits prior to the user’s /// arrival) and the departure time. /// /// - Parameters: /// - event: callback called when a new visit is generated /// - error: callback called when an error is thrown /// - Throws: throw an exception if application is not configured correctly to receive Visits events. App should /// require always authorization. public init(name: String? = nil, event: @escaping VisitObserver.onVisit, error: @escaping VisitObserver.onFailure) throws { guard CLLocationManager.appAuthorization == .always else { throw LocationError.other("NSLocationAlwaysUsageDescription in Info.plist is required to use Visits feature") } self.name = name self.register(callback: VisitObserver.onDidVisit(.main, event)) self.register(callback: VisitObserver.onError(.main, error)) } /// Register a new callback for this request /// /// - Parameter callback: callback to register public func register(callback: VisitObserver?) { guard let callback = callback else { return } self.registeredCallbacks.append(callback) } /// Pause events dispatch for this request public func pause() { Location.pause(self) } /// Resume events dispatch for this request public func resume() { Location.start(self) } /// Cancel request and remove it from queue. public func cancel() { Location.cancel(self) } public func onResume() { } public func onPause() { } public func onCancel() { } public var isBackgroundRequest: Bool { return true } /// Dispatch CLVisit object to registered callbacks /// /// - Parameter visit: visited object internal func dispatch(visit: CLVisit) { self.registeredCallbacks.forEach { if case .onDidVisit(let context, let handler) = $0 { context.queue.async { handler(visit) } } } } /// Dispatch error to registered callbacks /// /// - Parameter error: error public func dispatch(error: Error) { self.registeredCallbacks.forEach { if case .onError(let context, let handler) = $0 { context.queue.async { handler(error) } } } if self.cancelOnError == true { // remove from main location queue self.cancel() self._state = .failed(error) } } }
8b61ce3da6979817317c1e154aca766d
28.207729
137
0.70956
false
false
false
false
aschwaighofer/swift
refs/heads/master
test/IRGen/prespecialized-metadata/struct-inmodule-1argument-clang_node-1distinct_use.swift
apache-2.0
3
// RUN: %empty-directory(%t) // RUN: %build-irgen-test-overlays(mock-sdk-directory: %S/../Inputs) // REQUIRES: OS=macosx || OS=ios || OS=tvos || OS=watchos || OS=linux-gnu // RUN: %target-swift-frontend(mock-sdk: -sdk %S/../Inputs -I %t) -prespecialize-generic-metadata -target %module-target-future -primary-file %s -emit-ir | %FileCheck %s -DINT=i%target-ptrsize // UNSUPPORTED: CPU=i386 && OS=ios // UNSUPPORTED: CPU=armv7 && OS=ios // UNSUPPORTED: CPU=armv7s && OS=ios // REQUIRES: objc_interop import Foundation @inline(never) func consume<T>(_ t: T) { withExtendedLifetime(t) { t in } } struct Value<T> { let value: T init(_ value: T) { self.value = value } } // CHECK: define hidden swiftcc void @"$s4main4doityyF"() #{{[0-9]+}} { // CHECK: [[TYPE:%[0-9]+]] = call %swift.type* @__swift_instantiateConcreteTypeFromMangledName({ i32, i32 }* @"$s4main5ValueVySo12NSDictionaryCGMD") #{{[0-9]+}} // CHECK: call swiftcc void @"$s4main7consumeyyxlF"(%swift.opaque* noalias nocapture {{%.*}}, %swift.type* [[TYPE]]) // CHECK: } func doit() { consume(Value(NSDictionary())) } doit() // CHECK: ; Function Attrs: noinline nounwind readnone // CHECK: define hidden swiftcc %swift.metadata_response @"$s4main5ValueVMa"([[INT]] %0, %swift.type* %1) #{{[0-9]+}} { // CHECK: entry: // CHECK: [[ERASED_TYPE:%[0-9]+]] = bitcast %swift.type* %1 to i8* // CHECK: {{%[0-9]+}} = call swiftcc %swift.metadata_response @__swift_instantiateGenericMetadata([[INT]] %0, i8* [[ERASED_TYPE]], i8* undef, i8* undef, %swift.type_descriptor* bitcast ({{.+}}$s4main5ValueVMn{{.+}} to %swift.type_descriptor*)) #{{[0-9]+}} // CHECK: ret %swift.metadata_response {{%[0-9]+}} // CHECK: }
00d637e49819a95b2004cfb66c2be206
38.395349
257
0.644038
false
false
false
false
tiagomartinho/FastBike
refs/heads/master
FastBikeTests/BikeStationFinderTests.swift
mit
1
import XCTest import CoreLocation @testable import FastBike class BikeStationFinderTests: XCTestCase { func testFindsNearestBike() { let location = CLLocation(latitude: 42, longitude: 42) let noBikesStationLocation = CLLocation(latitude: 43, longitude: 41) let bikesStationLocation = CLLocation(latitude: 50, longitude: 50) let noBikesStation = BikeStation(name: "", address: "", id: "", bikes: 0, slots: 20, totalSlots: 20, location: noBikesStationLocation) let bikesStation = BikeStation(name: "", address: "", id: "", bikes: 1, slots: 20, totalSlots: 20, location: bikesStationLocation) let bikeStations = [noBikesStation, bikesStation] let foundBikeStation = BikeStationFinder.nearestBike(location: location, bikeStations: bikeStations) XCTAssertEqual(bikesStation, foundBikeStation) } func testFindsNearestStation() { let location = CLLocation(latitude: 42, longitude: 42) let fullStationLocation = CLLocation(latitude: 43, longitude: 41) let vacantStationLocation = CLLocation(latitude: 50, longitude: 50) let fullStation = BikeStation(name: "", address: "", id: "", bikes: 20, slots: 0, totalSlots: 20, location: fullStationLocation) let vacantStation = BikeStation(name: "", address: "", id: "", bikes: 1, slots: 20, totalSlots: 20, location: vacantStationLocation) let bikeStations = [fullStation, vacantStation] let foundBikeStation = BikeStationFinder.nearestStation(location: location, bikeStations: bikeStations) XCTAssertEqual(vacantStation, foundBikeStation) } }
826b31894317aa30ad0d8ec5b16e248f
51.516129
142
0.710074
false
true
false
false
EclipseSoundscapes/EclipseSoundscapes
refs/heads/master
Example/Pods/RxSwift/RxSwift/Observables/SingleAsync.swift
apache-2.0
6
// // SingleAsync.swift // RxSwift // // Created by Junior B. on 09/11/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // extension ObservableType { /** The single operator is similar to first, but throws a `RxError.noElements` or `RxError.moreThanOneElement` if the source Observable does not emit exactly one element before successfully completing. - seealso: [single operator on reactivex.io](http://reactivex.io/documentation/operators/first.html) - returns: An observable sequence that emits a single element or throws an exception if more (or none) of them are emitted. */ public func single() -> Observable<Element> { return SingleAsync(source: self.asObservable()) } /** The single operator is similar to first, but throws a `RxError.NoElements` or `RxError.MoreThanOneElement` if the source Observable does not emit exactly one element before successfully completing. - seealso: [single operator on reactivex.io](http://reactivex.io/documentation/operators/first.html) - parameter predicate: A function to test each source element for a condition. - returns: An observable sequence that emits a single element or throws an exception if more (or none) of them are emitted. */ public func single(_ predicate: @escaping (Element) throws -> Bool) -> Observable<Element> { return SingleAsync(source: self.asObservable(), predicate: predicate) } } private final class SingleAsyncSink<Observer: ObserverType> : Sink<Observer>, ObserverType { typealias Element = Observer.Element typealias Parent = SingleAsync<Element> private let _parent: Parent private var _seenValue: Bool = false init(parent: Parent, observer: Observer, cancel: Cancelable) { self._parent = parent super.init(observer: observer, cancel: cancel) } func on(_ event: Event<Element>) { switch event { case .next(let value): do { let forward = try self._parent._predicate?(value) ?? true if !forward { return } } catch let error { self.forwardOn(.error(error as Swift.Error)) self.dispose() return } if self._seenValue { self.forwardOn(.error(RxError.moreThanOneElement)) self.dispose() return } self._seenValue = true self.forwardOn(.next(value)) case .error: self.forwardOn(event) self.dispose() case .completed: if self._seenValue { self.forwardOn(.completed) } else { self.forwardOn(.error(RxError.noElements)) } self.dispose() } } } final class SingleAsync<Element>: Producer<Element> { typealias Predicate = (Element) throws -> Bool private let _source: Observable<Element> fileprivate let _predicate: Predicate? init(source: Observable<Element>, predicate: Predicate? = nil) { self._source = source self._predicate = predicate } override func run<Observer: ObserverType>(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element { let sink = SingleAsyncSink(parent: self, observer: observer, cancel: cancel) let subscription = self._source.subscribe(sink) return (sink: sink, subscription: subscription) } }
d0d59686dcb88d74a5400e90138b9361
33.990385
171
0.622699
false
false
false
false
yzyzsun/CurriculaTable
refs/heads/master
CurriculaTable/CurriculaTable.swift
mit
1
// // CurriculaTable.swift // CurriculaTable // // Created by Sun Yaozhu on 2016-09-10. // Copyright © 2016 Sun Yaozhu. All rights reserved. // import UIKit public class CurriculaTable: UIView { private let controller = CurriculaTableController() private let collectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: UICollectionViewFlowLayout()) public var weekdaySymbolType = CurriculaTableWeekdaySymbolType.short { didSet { collectionView.reloadData() } } public var firstWeekday = CurriculaTableWeekday.monday { didSet { collectionView.reloadData() drawCurricula() } } public var numberOfPeriods = 13 { didSet { collectionView.reloadData() drawCurricula() } } public var curricula = [CurriculaTableItem]() { didSet { drawCurricula() } } public var bgColor = UIColor.clear { didSet { collectionView.backgroundColor = bgColor } } public var symbolsBgColor = UIColor.clear { didSet { collectionView.reloadData() } } public var symbolsFontSize = CGFloat(14) { didSet { collectionView.reloadData() } } public var heightOfWeekdaySymbols = CGFloat(28) { didSet { collectionView.reloadData() drawCurricula() } } public var widthOfPeriodSymbols = CGFloat(32) { didSet { collectionView.reloadData() drawCurricula() } } public var borderWidth = CGFloat(0) { didSet { collectionView.reloadData() } } public var borderColor = UIColor.clear { didSet { collectionView.reloadData() } } public var cornerRadius = CGFloat(0) { didSet { drawCurricula() } } public var rectEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0) { didSet { drawCurricula() } } public var textEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0) { didSet { drawCurricula() } } public var textFontSize = CGFloat(11) { didSet { drawCurricula() } } public var textAlignment = NSTextAlignment.center { didSet { drawCurricula() } } public var maximumNameLength = 0 { didSet { drawCurricula() } } var weekdaySymbols: [String] { var weekdaySymbols = [String]() switch weekdaySymbolType { case .normal: weekdaySymbols = Calendar.current.standaloneWeekdaySymbols case .short: weekdaySymbols = Calendar.current.shortStandaloneWeekdaySymbols case .veryShort: weekdaySymbols = Calendar.current.veryShortStandaloneWeekdaySymbols } let firstWeekdayIndex = firstWeekday.rawValue - 1 weekdaySymbols.rotate(shiftingToStart: firstWeekdayIndex) return weekdaySymbols } var averageHeight: CGFloat { return (collectionView.frame.height - heightOfWeekdaySymbols) / CGFloat(numberOfPeriods) } var averageWidth: CGFloat { return (collectionView.frame.width - widthOfPeriodSymbols) / 7 - 0.1 } public override init(frame: CGRect) { super.init(frame: frame) initialize() } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) initialize() } private func initialize() { controller.curriculaTable = self controller.collectionView = collectionView collectionView.dataSource = controller collectionView.delegate = controller collectionView.backgroundColor = bgColor addSubview(collectionView) } public override func layoutSubviews() { super.layoutSubviews() collectionView.frame = bounds collectionView.reloadData() drawCurricula() } private func drawCurricula() { for subview in subviews { if !(subview is UICollectionView) { subview.removeFromSuperview() } } for (index, curriculum) in curricula.enumerated() { let weekdayIndex = (curriculum.weekday.rawValue - firstWeekday.rawValue + 7) % 7 let x = widthOfPeriodSymbols + averageWidth * CGFloat(weekdayIndex) + rectEdgeInsets.left let y = heightOfWeekdaySymbols + averageHeight * CGFloat(curriculum.startPeriod - 1) + rectEdgeInsets.top let width = averageWidth - rectEdgeInsets.left - rectEdgeInsets.right let height = averageHeight * CGFloat(curriculum.endPeriod - curriculum.startPeriod + 1) - rectEdgeInsets.top - rectEdgeInsets.bottom let view = UIView(frame: CGRect(x: x, y: y, width: width, height: height)) view.backgroundColor = curriculum.bgColor view.layer.cornerRadius = cornerRadius view.layer.masksToBounds = true let label = UILabel(frame: CGRect(x: textEdgeInsets.left, y: textEdgeInsets.top, width: view.frame.width - textEdgeInsets.left - textEdgeInsets.right, height: view.frame.height - textEdgeInsets.top - textEdgeInsets.bottom)) var name = curriculum.name if maximumNameLength > 0 { name.truncate(maximumNameLength) } let attrStr = NSMutableAttributedString(string: name + "\n\n" + curriculum.place, attributes: [NSAttributedString.Key.font: UIFont.systemFont(ofSize: textFontSize)]) attrStr.setAttributes([NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: textFontSize)], range: NSRange(0..<name.count)) label.attributedText = attrStr label.textColor = curriculum.textColor label.textAlignment = textAlignment label.numberOfLines = 0 label.tag = index label.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(curriculumTapped))) label.isUserInteractionEnabled = true view.addSubview(label) addSubview(view) } } @objc func curriculumTapped(_ sender: UITapGestureRecognizer) { let curriculum = curricula[(sender.view as! UILabel).tag] curriculum.tapHandler(curriculum) } }
d805f67d9f0bd16cc32569f46b972f83
29.668203
235
0.600451
false
false
false
false
mindbody/Conduit
refs/heads/main
Tests/ConduitTests/Networking/Serialization/XML/XMLNodeTestsSubjects.swift
apache-2.0
1
// // XMLSubjects.swift // Conduit // // Created by Eneko Alonso on 8/30/18. // Copyright © 2018 MINDBODY. All rights reserved. // import Foundation import Conduit extension XMLNodeTests { static let xml = XMLNode(name: "xml", children: [ XMLNode(name: "clients", children: [ XMLNode(name: "client", children: [ XMLNode(name: "id", value: "client1"), XMLNode(name: "name", value: "Bob"), XMLNode(name: "clientonly", value: "Foo"), XMLNode(name: "customers", children: [ XMLNode(name: "customer", children: [ XMLNode(name: "id", value: "customer1"), XMLNode(name: "name", value: "Customer Awesome") ]), XMLNode(name: "customer", children: [ XMLNode(name: "id", value: "customer2"), XMLNode(name: "name", value: "Another Customer") ]) ]) ]), XMLNode(name: "client", children: [ XMLNode(name: "id", value: "client2"), XMLNode(name: "name", value: "Job"), XMLNode(name: "clientonly", value: "Bar"), XMLNode(name: "customers", children: [ XMLNode(name: "customer", children: [ XMLNode(name: "id", value: "customer3"), XMLNode(name: "name", value: "Yet Another Customer") ]) ]) ]), XMLNode(name: "client", children: [ XMLNode(name: "id", value: "client3"), XMLNode(name: "name", value: "Joe"), XMLNode(name: "clientonly", value: "Baz") ]) ]), XMLNode(name: "id", value: "root1"), XMLNode(name: "name", value: "I'm Root"), XMLNode(name: "rootonly", value: "Root only") ]) static let xmlDict: XMLDictionary = [ "clients": [ [ "client": [ "id": "client1", "name": "Bob", "clientonly": "Foo", "customers": [ [ "customer": [ "id": "customer1", "name": "Customer Awesome" ] ], [ "customer": [ "id": "customer2", "name": "Another Customer" ] ] ] ] ], [ "client": [ "id": "client2", "name": "Job", "clientonly": "Bar", "customers": [ [ "customer": [ "id": "customer3", "name": "Yet Another Customer" ] ] ] ] ], [ "client": [ "id": "client3", "name": "Joe", "clientonly": "Baz" ] ] ], "id": "root1", "name": "I'm Root", "rootonly": "Root only" ] static let xmlWithIdentifiers = """ <Parent> <Child Identifier="Child1">Foo</Child> <Child Identifier="Child2">Bar</Child> <Child Identifier="Child3">Baz</Child> </Parent> """ static let testSubjects: [XMLNode] = [xml, XMLNode(name: "xml", children: xmlDict)] }
1b11ee872386bbba3dc5feb885ceca98
33.035088
87
0.362371
false
false
false
false
henrinormak/Heimdall
refs/heads/master
Example/HeimdallExample/ViewController.swift
mit
4
// // ViewController.swift // HeimdallExample // // Created by Henri Normak on 23/04/15. // Copyright (c) 2015 Henri Normak. All rights reserved. // import UIKit import Heimdall class ViewController: UIViewController, UITextViewDelegate { @IBOutlet var textView: UITextView! @IBOutlet var bottomConstraint: NSLayoutConstraint! var heimdall: Heimdall? var text: String = "" override func viewDidLoad() { super.viewDidLoad() self.heimdall = Heimdall(tagPrefix: "com.hnormak.heimdall.example", keySize: 1024) NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillChange:", name: UIKeyboardWillChangeFrameNotification, object: nil) } deinit { NSNotificationCenter.defaultCenter().removeObserver(self) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // UITextView delegate func textViewDidChange(textView: UITextView) -> Void { self.text = textView.text } // Switching content @IBAction func showPlainText() -> Void { self.textView.editable = true self.textView.text = self.text } @IBAction func showDecryptedText() -> Void { self.textView.editable = false if let encrypted = heimdall?.encrypt(self.text), decrypted = heimdall?.decrypt(encrypted) { self.textView.text = decrypted } } @IBAction func showEncryptedText() -> Void { self.textView.editable = false if let encrypted = heimdall?.encrypt(self.text) { self.textView.text = encrypted } } @IBAction func showEncryptedSignature() -> Void { self.textView.editable = false if let signature = heimdall?.sign(self.text) { self.textView.text = signature } } // Keyboard insetting func keyboardWillChange(notification: NSNotification) { if let userInfo = notification.userInfo, value = userInfo[UIKeyboardFrameEndUserInfoKey] as? NSValue, duration = userInfo[UIKeyboardAnimationDurationUserInfoKey] as? Double, curve = userInfo[UIKeyboardAnimationCurveUserInfoKey] as? UInt { let frame = value.CGRectValue() let intersection = CGRectIntersection(frame, self.view.frame) self.view.setNeedsLayout() self.bottomConstraint.constant = CGRectGetHeight(intersection) UIView.animateWithDuration(duration, delay: 0.0, options: UIViewAnimationOptions(rawValue: curve), animations: { _ in self.view.setNeedsLayout() }, completion: nil) } } }
1cb6b5537433f92c19453defa213280c
33.111111
246
0.647847
false
false
false
false
MLSDev/TRON
refs/heads/main
Source/TRON/Combine.swift
mit
1
// // Combine.swift // TRON // // Created by Denys Telezhkin on 15.06.2020. // Copyright © 2020 Denys Telezhkin. 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. import Foundation import Alamofire /// Error that is created in case `DownloadAPIRequest` errors out, but Alamofire and URL loading system report error as nil. /// Practically, this should never happen ¯\_(ツ)_/¯ . public struct DownloadError<T, Failure: Error>: Error { /// Reported `DownloadResponse` public let response: DownloadResponse<T, Failure> /// Creates `DownloadError` for `DownloadAPIRequest`. /// /// - Parameter response: response created by `Alamofire`. public init(_ response: DownloadResponse<T, Failure>) { self.response = response } } /// Type-erased cancellation token. public protocol RequestCancellable { /// Cancel current request func cancelRequest() } extension DataRequest: RequestCancellable { /// Cancel DataRequest public func cancelRequest() { _ = cancel() } } extension DownloadRequest: RequestCancellable { /// Cancel DownloadRequest public func cancelRequest() { _ = cancel() } } #if canImport(Combine) import Combine /// Provides Combine.Publisher for APIRequest public extension APIRequest { @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *) /// A Combine `Publisher` that publishes the `AnyPublisher<Model, ErrorModel>` of `APIRequest`. /// - Returns: type-erased publisher func publisher() -> AnyPublisher<Model, ErrorModel> { TRONPublisher { subscriber in self.perform(withSuccess: { model in _ = subscriber.receive(model) subscriber.receive(completion: .finished) }, failure: { error in subscriber.receive(completion: .failure(error)) }) }.eraseToAnyPublisher() } } /// Provides Combine.Publisher for UploadAPIRequest public extension UploadAPIRequest { @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *) /// A Combine `Publisher` that publishes the `AnyPublisher<Model, ErrorModel>` of `UploadAPIRequest`. /// - Returns: type-erased publisher func publisher() -> AnyPublisher<Model, ErrorModel> { TRONPublisher { subscriber in self.perform(withSuccess: { model in _ = subscriber.receive(model) subscriber.receive(completion: .finished) }, failure: { error in subscriber.receive(completion: .failure(error)) }) }.eraseToAnyPublisher() } } /// Provides Combine.Publisher for DownloadAPIRequest public extension DownloadAPIRequest { @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *) /// A Combine `Publisher` that publishes the `AnyPublisher<Model, ErrorModel>` of `DownloadAPIRequest`. /// - Returns: type-erased publisher func publisher() -> AnyPublisher<Model, ErrorModel> { TRONPublisher { subscriber in self.perform(withSuccess: { success in _ = subscriber.receive(success) subscriber.receive(completion: .finished) }, failure: { error in subscriber.receive(completion: .failure(error)) }) }.eraseToAnyPublisher() } } // This should be already provided in Combine, but it's not. // Adapted from https://github.com/Moya/Moya/blob/development/Sources/CombineMoya/MoyaPublisher.swift @available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) internal class TRONPublisher<Model, ErrorModel: Error>: Publisher { typealias Failure = ErrorModel typealias Output = Model private class Subscription: Combine.Subscription { private var performCall: (() -> RequestCancellable?)? private var cancellable: RequestCancellable? private var subscriber: AnySubscriber<Output, Failure>? init(subscriber: AnySubscriber<Output, Failure>, callback: @escaping (AnySubscriber<Output, Failure>) -> RequestCancellable?) { performCall = { callback(subscriber) } self.subscriber = subscriber } func request(_ demand: Subscribers.Demand) { guard demand > .none else { return } cancellable = performCall?() } func cancel() { cancellable?.cancelRequest() subscriber = nil performCall = nil } } private let callback: (AnySubscriber<Output, Failure>) -> RequestCancellable? init(callback: @escaping (AnySubscriber<Output, Failure>) -> RequestCancellable?) { self.callback = callback } internal func receive<S>(subscriber: S) where S: Subscriber, Failure == S.Failure, Output == S.Input { let subscription = Subscription(subscriber: AnySubscriber(subscriber), callback: callback) subscriber.receive(subscription: subscription) } } #endif
d45b4a99932b6c9ba880aa6305392a29
35.347561
135
0.673712
false
false
false
false
ConnorJennison/CollectionTracker
refs/heads/master
CollectionTracker/ViewController.swift
gpl-3.0
1
// // ViewController.swift // CollectionTracker // // Created by Connor Jennison on 9/20/17. // Copyright © 2017 Connor Jennison. All rights reserved. // import UIKit class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { @IBOutlet weak var itemListTableView: UITableView! var items : [Item] = [] override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. itemListTableView.delegate = self itemListTableView.dataSource = self } override func viewWillAppear(_ animated: Bool) { let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext do{ items = try context.fetch(Item.fetchRequest()) } catch{ print("Error getting core data") } itemListTableView.reloadData() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return items.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = UITableViewCell() let item = items[indexPath.row] cell.textLabel!.text = item.title cell.imageView!.image = UIImage(data: item.image! as Data) return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let item = items[indexPath.row] performSegue(withIdentifier: "itemSegue", sender: item) } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { let nextVC = segue.destination as! ItemViewController nextVC.item = sender as? Item } }
dc0638d7ec00779be454a71c68eadc73
29.123077
102
0.644535
false
false
false
false
cliqz-oss/browser-ios
refs/heads/development
Storage/SQL/DeferredDBOperation.swift
mpl-2.0
2
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import Shared import XCGLogger import Deferred private let log = Logger.syncLogger private let DeferredQueue = DispatchQueue(label: "BrowserDBQueue", attributes: []) /** This class is written to mimick an NSOperation, but also provide Deferred capabilities as well. Usage: let deferred = DeferredDBOperation({ (db, err) -> Int // ... Do something long running return 1 }, withDb: myDb, onQueue: myQueue).start(onQueue: myQueue) deferred.upon { res in // if cancelled res.isFailure = true }) // ... Some time later deferred.cancel() */ class DeferredDBOperation<T>: Deferred<Maybe<T>>, Cancellable { /// Cancelled is wrapping a ReadWrite lock to make access to it thread-safe. fileprivate var cancelledLock = LockProtected<Bool>(item: false) var cancelled: Bool { get { return self.cancelledLock.withReadLock({ cancelled -> Bool in return cancelled }) } set { cancelledLock.withWriteLock { cancelled -> T? in cancelled = newValue return nil } } } /// Executing is wrapping a ReadWrite lock to make access to it thread-safe. fileprivate var connectionLock = LockProtected<SQLiteDBConnection?>(item: nil) fileprivate var connection: SQLiteDBConnection? { get { // We want to avoid leaking this connection. If you want access to it, // you should use a read/write lock directly. return nil } set { connectionLock.withWriteLock { connection -> T? in connection = newValue return nil } } } fileprivate var db: SwiftData fileprivate var block: (_ connection: SQLiteDBConnection, _ err: inout NSError?) -> T init(db: SwiftData, block: @escaping (_ connection: SQLiteDBConnection, _ err: inout NSError?) -> T) { self.block = block self.db = db super.init() } func start(onQueue queue: DispatchQueue = DeferredQueue) -> DeferredDBOperation<T> { queue.async(execute: self.main) return self } fileprivate func main() { if self.cancelled { let err = NSError(domain: "mozilla", code: 9, userInfo: [NSLocalizedDescriptionKey: "Operation was cancelled before starting"]) fill(Maybe(failure: DatabaseError(err: err))) return } var result: T? = nil let err = db.withConnection(SwiftData.Flags.readWriteCreate) { (db) -> NSError? in self.connection = db if self.cancelled { return NSError(domain: "mozilla", code: 9, userInfo: [NSLocalizedDescriptionKey: "Operation was cancelled before starting"]) } var error: NSError? = nil result = self.block(db, &error) if error == nil { log.verbose("Modified rows: \(db.numberOfRowsModified).") } self.connection = nil return error } if let result = result { fill(Maybe(success: result)) return } fill(Maybe(failure: DatabaseError(err: err))) } func cancel() { self.cancelled = true self.connectionLock.withReadLock({ connection -> () in connection?.interrupt() return () }) } }
dab0ac1bf1861267017f9fce4a7bfc63
31.460177
140
0.593784
false
false
false
false
SwiftyVK/SwiftyVK
refs/heads/master
Library/Sources/Extensions/VKAppProxy.swift
mit
2
import Foundation protocol VKAppProxy: class { @discardableResult func send(query: String) throws -> Bool func handle(url: URL, app: String?) -> String? } final class VKAppProxyImpl: VKAppProxy { private let baseUrl = "vkauthorize://authorize?" private let appId: String private let urlOpener: URLOpener private let appLifecycleProvider: AppLifecycleProvider init( appId: String, urlOpener: URLOpener, appLifecycleProvider: AppLifecycleProvider ) { self.appId = appId self.urlOpener = urlOpener self.appLifecycleProvider = appLifecycleProvider } deinit { appLifecycleProvider.unsubscribe(self) } @discardableResult func send(query: String) throws -> Bool { guard try openVkApp(query: query) else { return false } guard wait(to: .inactive, timeout: .now() + 1) else { return false } guard wait(to: .active, timeout: .distantFuture) else { return false } return true } private func openVkApp(query: String) throws -> Bool { guard let url = URL(string: baseUrl + query) else { throw VKError.cantBuildVKAppUrl(baseUrl + query) } return DispatchQueue.anywayOnMain { guard urlOpener.canOpenURL(url) else { return false } guard urlOpener.openURL(url) else { return false } return true } } private func wait(to appState: AppState, timeout: DispatchTime) -> Bool { defer { appLifecycleProvider.unsubscribe(self) } let semaphore = DispatchSemaphore(value: 0) appLifecycleProvider.subscribe(self) { if $0 == appState { semaphore.signal() } } switch semaphore.wait(timeout: timeout) { case .success: return true case .timedOut: return false } } func handle(url: URL, app: String?) -> String? { let isAppCorrect = (app == "com.vk.vkclient" || app == "com.vk.vkhd" || app == nil) let isSchemeCorrect = url.scheme == "vk\(appId)" let isHostCorrect = url.host == "authorize" guard isAppCorrect && isSchemeCorrect && isHostCorrect else { return nil } guard let fragment = url.fragment, fragment.contains("access_token") else { return nil } return fragment } }
d079476781c8ca8a8d250531cd926ab7
26.391753
91
0.552126
false
false
false
false
Dhvl-Golakiya/DGSwiftExtension
refs/heads/master
Pod/Classes/ArrayExtension.swift
mit
1
// // Created by Dhvl Golakiya on 02/04/16. // Copyright (c) 2016 Dhvl Golakiya. All rights reserved. // import Foundation extension Array { // Make Comma separated String from array public var toCommaString: String! { let stringArray = self as? NSArray if let stringArray = stringArray { return stringArray.componentsJoined(by: ",") } return "" } // Remove Specific object from Array public mutating func removeObject<U: Equatable>(_ object: U) { var index: Int? for (idx, objectToCompare) in self.enumerated() { if let to = objectToCompare as? U { if object == to { index = idx } } } if(index != nil) { self.remove(at: index!) } } // Chack Array contain specific object public func containsObject<T:AnyObject>(_ item:T) -> Bool { for element in self { if item === element as? T { return true } } return false } // Get Index of specific object public func indexOfObject<T : Equatable>(_ x:T) -> Int? { for i in 0...self.count { if self[i] as! T == x { return i } } return nil } // Gets the object at the specified index, if it exists. public func get(_ index: Int) -> Element? { return index >= 0 && index < count ? self[index] : nil } }
2f7165bf22d1a18b1542cb50d064ee5c
23.887097
66
0.510693
false
false
false
false
FedeGens/WeePager
refs/heads/master
WeePagerDemo/Cachy.swift
mit
1
// // Cachy.swift // Cachy // // Created by Federico Gentile on 28/12/16. // Copyright © 2016 Federico Gentile. All rights reserved. // import UIKit class Cachy { private static var kMaxTime = 86400 private static var kMaxImagesToSave = 100 private static let kCachyFilePrefix = "ImgCachyPrefix" private static let kCachyFolderName = "ImgCachy" private static var cachyImageDataArray = [CachyImageData]() private static var isFirstTime = true //MARK: internal methods //Cachy setup static func setExpireTime(seconds: Int) { kMaxTime = seconds } static func setMaxImages(number: Int) { kMaxImagesToSave = number } //clean all static func purge() { removeAll() } static func getFirstTime() -> Bool { return Cachy.isFirstTime } //called first time static func refreshDirectory() { isFirstTime = false checkMainDirectory() getImagesReferencesFromDirectory() checkCachyImageTimestamp() } //check if image exists static func getCachyImage(link: String) -> UIImage? { let myLink = link.replacingOccurrences(of: "/", with: "--").replacingOccurrences(of: "_", with: "--").addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)! guard let elem = cachyImageDataArray.filter({$0.imageName == myLink}).first else { return nil } return getImageFromDirectory(data: elem) } //save cachy image static func saveImage(image: UIImage, name: String) { saveImageToDirectory(image: image, name: name) } //MARK: Check main directory private static func checkMainDirectory() { if !checkMainDirectoryExists() { createMainDirectory() } } private static func createMainDirectory() { let documentsDirectory = getDocumentsDirectory() let dataPath = documentsDirectory.appendingPathComponent(kCachyFolderName) do { try FileManager.default.createDirectory(atPath: dataPath.path, withIntermediateDirectories: true, attributes: nil) } catch let error as NSError { print(error.localizedDescription) } } private static func checkMainDirectoryExists() -> Bool { let url = getDocumentsDirectory() let filePath = url.appendingPathComponent(kCachyFolderName).path let fileManager = FileManager.default if fileManager.fileExists(atPath: filePath) { return true } else { return false } } //get image from directory and update timestamp private static func getImageFromDirectory(data: CachyImageData) -> UIImage { if Int(CFAbsoluteTimeGetCurrent()) - Int(data.timestamp)! < 10 { return UIImage(contentsOfFile: getCachyDirectory().appendingPathComponent(data.getFilename()).path)! } do { let path = getCachyDirectory() let originPath = path.appendingPathComponent(data.getFilename()) let (timestamp, _, newName) = createFilename(name: data.imageName) let destinationPath = path.appendingPathComponent(newName) try FileManager.default.moveItem(at: originPath, to: destinationPath) //update timestamp let index = cachyImageDataArray.index(where: {$0.imageName == data.imageName})! cachyImageDataArray[index].timestamp = timestamp return UIImage(contentsOfFile: getCachyDirectory().appendingPathComponent(cachyImageDataArray[index].getFilename()).path)! } catch { print(error) return getImageFromDirectoryWithName(name: data.imageName) } } private static func getImageFromDirectoryWithName(name: String) -> UIImage { do { let urls = try FileManager.default.contentsOfDirectory(at: getCachyDirectory(), includingPropertiesForKeys: nil, options: []) if let imageUrl = urls.filter({$0.absoluteString.contains(name)}).first { return UIImage(contentsOfFile: imageUrl.path)! } } catch { print(error) } return UIImage() } private static func checkCachyImageTimestamp() { for elem in cachyImageDataArray { if !elem.isTimestampValid() { removeElem(data: elem) } } } //MARK: get image reference from directory private static func getImagesReferencesFromDirectory() { let documentsUrl = getCachyDirectory() do { // Get directory contents url let directoryContents = try FileManager.default.contentsOfDirectory(at: documentsUrl, includingPropertiesForKeys: nil, options: []) //filter let imageFiles = directoryContents.filter{ $0.absoluteString.contains(kCachyFilePrefix) } createLocalCachyArray(myUrls: imageFiles) } catch let error as NSError { print(error.localizedDescription) } } private static func createLocalCachyArray(myUrls: [URL]) { //init array cachyImageDataArray = [CachyImageData]() for url in myUrls { let myString = url.absoluteString.components(separatedBy: "_") cachyImageDataArray.append(CachyImageData.createCachyImageData(timestamp: myString[1], imageName: myString[2])) } } //MARK: Save image to directory private static func createFilename(name: String) -> (String, String, String) { let myName = name.replacingOccurrences(of: "/", with: "--").replacingOccurrences(of: "_", with: "--") let timestamp = String(Int(CFAbsoluteTimeGetCurrent())) let filename = kCachyFilePrefix + "_" + timestamp + "_" + myName return (timestamp, myName, filename.removingPercentEncoding!) } private static func saveImageToDirectory(image: UIImage, name: String) { if let data = image.jpegData(compressionQuality: 0.3) { let (timestamp, myName, myFilename) = createFilename(name: name) let filename = getCachyDirectory().appendingPathComponent(myFilename) if !checkImageExists(name: myName) { do { try data.write(to: filename) addElemToCachyArray(timestamp: timestamp, name: myName) checkCachySize() } catch { print("error") } } } } private static func checkImageExists(name: String) -> Bool{ if (cachyImageDataArray.filter({$0.imageName == name}).first == nil) { return false } return true } private static func addElemToCachyArray(timestamp: String, name: String) { cachyImageDataArray.append(CachyImageData.createCachyImageData(timestamp: timestamp, imageName: name)) } //check size private static func checkCachySize() { if cachyImageDataArray.count > kMaxImagesToSave { removeElem(data: cachyImageDataArray[0]) } } //MARK: Remove image from directory private static func removeElem(data: CachyImageData) { let fileManager = FileManager.default let path = getCachyDirectory() let filePath = path.appendingPathComponent(data.getFilename()) do { try fileManager.removeItem(at: filePath) let index = cachyImageDataArray.index(where: {$0.imageName == data.imageName})! cachyImageDataArray.remove(at: index) } catch let error as NSError { print(error.debugDescription) } } private static func removeAll() { let fileManager = FileManager.default let path = getCachyDirectory() do { try fileManager.removeItem(at: path) checkMainDirectory() } catch { print(error) } } //MARK: Directory Utility private static func getDocumentsDirectory() -> URL { let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask) let documentsDirectory = paths[0] return documentsDirectory } private static func getCachyDirectory() -> URL { let cachyDirectory = getDocumentsDirectory().appendingPathComponent(kCachyFolderName) return cachyDirectory } //MARK: cachy struct private struct CachyImageData { var timestamp = "" var imageName = "" static func createCachyImageData(timestamp: String, imageName: String) -> CachyImageData { var myCachyImageData = CachyImageData() myCachyImageData.timestamp = timestamp myCachyImageData.imageName = imageName return myCachyImageData } func getFilename() -> String { let encodedFilename = kCachyFilePrefix + "_" + String(timestamp) + "_" + imageName return encodedFilename.removingPercentEncoding! } func isTimestampValid() -> Bool { return (Int(CFAbsoluteTimeGetCurrent()) - Int(timestamp)!) < kMaxTime } } }
f0c0bf6c72adcec0b1e698e2a3fc6288
34.052239
172
0.617202
false
false
false
false
ninewine/SaturnTimer
refs/heads/master
SaturnTimer/View/AnimatableTag/Television/Television.swift
mit
1
// // Television.swift // SaturnTimer // // Created by Tidy Nine on 2/18/16. // Copyright © 2016 Tidy Nine. All rights reserved. // import UIKit import pop class Television: AnimatableTag { fileprivate let _body: CAShapeLayer = CAShapeLayer() fileprivate let _st_screen: CAShapeLayer = CAShapeLayer() fileprivate let _antenna1: CAShapeLayer = CAShapeLayer() fileprivate let _antenna2: CAShapeLayer = CAShapeLayer() fileprivate let _switch: CAShapeLayer = CAShapeLayer() fileprivate let _speaker1: CAShapeLayer = CAShapeLayer() fileprivate let _speaker2: CAShapeLayer = CAShapeLayer() fileprivate var _snowAry: [CALayer]! fileprivate let _duration: CFTimeInterval = 1.0 override func viewConfig() { _fixedSize = CGSize(width: 23, height: 24) super.viewConfig() _body.path = _TelevisionLayerPath.bodyPath.cgPath _st_screen.path = _TelevisionLayerPath.screenPath.cgPath _antenna1.path = _TelevisionLayerPath.antennaPath1.cgPath _antenna2.path = _TelevisionLayerPath.antennaPath2.cgPath _switch.path = _TelevisionLayerPath.switchPath.cgPath _speaker1.path = _TelevisionLayerPath.speakerPath1.cgPath _speaker2.path = _TelevisionLayerPath.speakerPath2.cgPath let layersStroke = [_body, _st_screen, _antenna1, _antenna2, _switch, _speaker1, _speaker2] for layer in layersStroke { layer.isOpaque = true layer.lineCap = kCALineCapRound layer.lineWidth = 1.5 layer.strokeStart = 0.0 layer.strokeEnd = 0.0 layer.strokeColor = currentAppearenceColor() layer.fillColor = UIColor.clear.cgColor _contentView.layer.addSublayer(layer) } _antenna1.frame = CGRect(x: 6, y: 3.28, width: 12, height: 6.56) _antenna2.frame = CGRect(x: 6, y: 3.28, width: 12, height: 6.56) _antenna1.anchorPoint = CGPoint(x: 1.0, y: 1.0) _antenna2.anchorPoint = CGPoint(x: 0.0, y: 1.0) //Snow _snowAry = (0..<9).flatMap({ (index) -> CALayer? in let snow = CALayer() snow.frame = CGRect(x: 0, y: 0, width: 1, height: 1) let row: Int = index / 3 let col: Int = index % 3 let gap: Int = 2 snow.opacity = 0.0 snow.position = CGPoint(x: CGFloat(row * gap) + 7.3, y: CGFloat(col * gap) + 13.1) snow.backgroundColor = HelperColor.lightGrayColor.cgColor _contentView.layer.addSublayer(snow) return snow }) _snowAry = _snowAry.shuffled() enterAnimation() } override func layersNeedToBeHighlighted() -> [CAShapeLayer]? { return [_body, _st_screen, _antenna1, _antenna2, _switch, _speaker1, _speaker2] } override func startAnimation() { _pausing = false televisionAnimation() snowAnimation() } override func stopAnimation() { _pausing = true _antenna1.transform = CATransform3DIdentity _antenna2.transform = CATransform3DIdentity for snow in _snowAry { snow.pop_removeAllAnimations() snow.opacity = 0.0 } } // Enter Animation func enterAnimation () { _body.pathStokeAnimationFrom(0.0, to: 1.0, duration: _duration, type: .end) {[weak self] () -> Void in guard let _self = self else {return} _self._st_screen.pathStokeAnimationFrom(0.0, to: 1.0, duration: _self._duration * 0.5, type: .end, completion: {[weak self] () -> Void in guard let _self = self else {return} _self._switch.pathStokeAnimationFrom(0.0, to: 1.0, duration: _self._duration * 0.5, type: .end, completion: {[weak self] () -> Void in guard let _self = self else {return} _self._speaker1.pathStokeAnimationFrom(0.0, to: 1.0, duration: _self._duration * 0.5, type: .end) _self._speaker2.pathStokeAnimationFrom(0.0, to: 1.0, duration: _self._duration * 0.5, type: .end, completion: {[weak self] () -> Void in guard let _self = self else {return} _self._antenna1.pathStokeAnimationFrom(0.0, to: 1.0, duration: _self._duration * 0.5, type: .end) _self._antenna2.pathStokeAnimationFrom(0.0, to: 1.0, duration: _self._duration * 0.5, type: .end, completion: {[weak self] () -> Void in guard let _self = self else {return} _self.televisionAnimation() _self.snowAnimation() }) }) }) }) } } //Television Animation func televisionAnimation () { if _pausing { return } let rotationAnimFrom1 = POPSpringAnimation(propertyNamed: kPOPLayerRotation) rotationAnimFrom1?.toValue = -(Double.pi * 0.5) * 0.2 rotationAnimFrom1?.completionBlock = {[weak self] (anim, finished) in guard let _self = self else {return} let rotationAnimTo1 = POPSpringAnimation(propertyNamed: kPOPLayerRotation) rotationAnimTo1?.toValue = 0 _self._antenna1.pop_add(rotationAnimTo1, forKey: "RotationAnimTo") } _antenna1.pop_add(rotationAnimFrom1, forKey: "RotationAnimFrom") let rotationAnimFrom2 = POPSpringAnimation(propertyNamed: kPOPLayerRotation) rotationAnimFrom2?.toValue = Double.pi * 0.2 rotationAnimFrom2?.completionBlock = {[weak self] (anim, finished) in guard let _self = self else {return} let rotationAnimTo2 = POPSpringAnimation(propertyNamed: kPOPLayerRotation) rotationAnimTo2?.toValue = 0 rotationAnimTo2?.completionBlock = { (anim, finished) in DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1.0, execute: {[weak self] in self?.televisionAnimation() }) } _self._antenna2.pop_add(rotationAnimTo2, forKey: "RotationAnimTo") } _antenna2.pop_add(rotationAnimFrom2, forKey: "RotationAnimFrom") } //Snow Animation func snowAnimation () { for (index, snow) in _snowAry.enumerated() { let opacityAnim = POPBasicAnimation(propertyNamed: kPOPLayerOpacity) opacityAnim?.toValue = 1.0 opacityAnim?.repeatForever = true opacityAnim?.autoreverses = true opacityAnim?.duration = 0.6 opacityAnim?.beginTime = CACurrentMediaTime() + CFTimeInterval(index) * 0.7 snow.pop_add(opacityAnim, forKey: "OpacityAnimation") } } }
465ab4ba0d9eba39a06875e4dfbc69b4
30.184211
142
0.682869
false
false
false
false
ReactiveX/RxSwift
refs/heads/develop
Example/Pods/RxSwift/RxSwift/Observables/Filter.swift
gpl-3.0
8
// // Filter.swift // RxSwift // // Created by Krunoslav Zaher on 2/17/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // extension ObservableType { /** Filters the elements of an observable sequence based on a predicate. - seealso: [filter operator on reactivex.io](http://reactivex.io/documentation/operators/filter.html) - parameter predicate: A function to test each source element for a condition. - returns: An observable sequence that contains elements from the input sequence that satisfy the condition. */ public func filter(_ predicate: @escaping (Element) throws -> Bool) -> Observable<Element> { Filter(source: self.asObservable(), predicate: predicate) } } extension ObservableType { /** Skips elements and completes (or errors) when the observable sequence completes (or errors). Equivalent to filter that always returns false. - seealso: [ignoreElements operator on reactivex.io](http://reactivex.io/documentation/operators/ignoreelements.html) - returns: An observable sequence that skips all elements of the source sequence. */ public func ignoreElements() -> Observable<Never> { self.flatMap { _ in Observable<Never>.empty() } } } final private class FilterSink<Observer: ObserverType>: Sink<Observer>, ObserverType { typealias Predicate = (Element) throws -> Bool typealias Element = Observer.Element private let predicate: Predicate init(predicate: @escaping Predicate, observer: Observer, cancel: Cancelable) { self.predicate = predicate super.init(observer: observer, cancel: cancel) } func on(_ event: Event<Element>) { switch event { case .next(let value): do { let satisfies = try self.predicate(value) if satisfies { self.forwardOn(.next(value)) } } catch let e { self.forwardOn(.error(e)) self.dispose() } case .completed, .error: self.forwardOn(event) self.dispose() } } } final private class Filter<Element>: Producer<Element> { typealias Predicate = (Element) throws -> Bool private let source: Observable<Element> private let predicate: Predicate init(source: Observable<Element>, predicate: @escaping Predicate) { self.source = source self.predicate = predicate } override func run<Observer: ObserverType>(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element { let sink = FilterSink(predicate: self.predicate, observer: observer, cancel: cancel) let subscription = self.source.subscribe(sink) return (sink: sink, subscription: subscription) } }
fb066b18ff18f4fa4155e1629000095b
32.976744
171
0.645791
false
false
false
false
watson-developer-cloud/ios-sdk
refs/heads/master
Sources/AssistantV1/Models/RuntimeResponseGenericRuntimeResponseTypeChannelTransfer.swift
apache-2.0
1
/** * (C) Copyright IBM Corp. 2021. * * 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 /** RuntimeResponseGenericRuntimeResponseTypeChannelTransfer. Enums with an associated value of RuntimeResponseGenericRuntimeResponseTypeChannelTransfer: RuntimeResponseGeneric */ public struct RuntimeResponseGenericRuntimeResponseTypeChannelTransfer: Codable, Equatable { /** The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. */ public var responseType: String /** The message to display to the user when initiating a channel transfer. */ public var messageToUser: String /** Information used by an integration to transfer the conversation to a different channel. */ public var transferInfo: ChannelTransferInfo /** An array of objects specifying channels for which the response is intended. If **channels** is present, the response is intended only for a built-in integration and should not be handled by an API client. */ public var channels: [ResponseGenericChannel]? // Map each property name to the key that shall be used for encoding/decoding. private enum CodingKeys: String, CodingKey { case responseType = "response_type" case messageToUser = "message_to_user" case transferInfo = "transfer_info" case channels = "channels" } /** Initialize a `RuntimeResponseGenericRuntimeResponseTypeChannelTransfer` with member variables. - parameter responseType: The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. - parameter messageToUser: The message to display to the user when initiating a channel transfer. - parameter transferInfo: Information used by an integration to transfer the conversation to a different channel. - parameter channels: An array of objects specifying channels for which the response is intended. If **channels** is present, the response is intended only for a built-in integration and should not be handled by an API client. - returns: An initialized `RuntimeResponseGenericRuntimeResponseTypeChannelTransfer`. */ public init( responseType: String, messageToUser: String, transferInfo: ChannelTransferInfo, channels: [ResponseGenericChannel]? = nil ) { self.responseType = responseType self.messageToUser = messageToUser self.transferInfo = transferInfo self.channels = channels } }
8f802d4640c56517296ba76975836e6e
37
121
0.722431
false
false
false
false
CodingGirl1208/FlowerField
refs/heads/master
FlowerField/FlowerField/HomeTableViewController.swift
mit
1
// // HomeTableViewController.swift // FlowerField // // Created by 易屋之家 on 16/8/9. // Copyright © 2016年 xuping. All rights reserved. // import UIKit private let HomeArticleReuseIdentifier = "HomeArticleReuseIdentifier" class HomeTableViewController: UITableViewController { // 文章数组 var articles = [Article]() // 所有的主题分类 var categories : [Category]? // 选中的分类 var selectedCategry : Category? // 当前页 var currentPage : Int = 0 override func viewDidLoad() { super.viewDidLoad() setup() } //MARK: - 基本设置 private func setup(){ navigationItem.leftBarButtonItem = UIBarButtonItem(customView: menuBtn) navigationItem.rightBarButtonItem = UIBarButtonItem.init(title: "TOP", style: .Plain, target: self, action: #selector(HomeTableViewController.toTop)) navigationItem.titleView = themeBtn // 设置tableview相关 tableView.registerClass(HomeArticleTableViewCell.self, forCellReuseIdentifier: HomeArticleReuseIdentifier) tableView.rowHeight = 330; tableView.separatorStyle = .None tableView.tableFooterView = UIView() } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) getList() } //MARK: - 懒加载 private lazy var themeBtn : ThemeButton = ThemeButton() private lazy var menuBtn : UIButton = { let btn = UIButton() btn.frame.size = CGSize.init(width: 20, height: 20) btn.setImage(UIImage(named: "menu"), forState: .Normal) btn.addTarget(self, action: #selector(HomeTableViewController.toTop), forControlEvents: .TouchUpInside) return btn }() @objc private func toTop(){ } private func getList() { // 参数设置 var paramters = [String : AnyObject]() paramters["currentPageIndex"] = "\(currentPage)" paramters["pageSize"] = "5" NetWorkTool.sharedTools.AFGetRequset("http://m.htxq.net/servlet/SysArticleServlet?action=mainList", Parameters: paramters) { (scucessValue, failureError) in if scucessValue === NSNull(){ print("err:\(failureError)") } else{ // print("lll:\(scucessValue!["result"])"); if let result = scucessValue!["result"]{ for dict in result as! [[String:AnyObject]] { self.articles.append(Article.init(dict: dict)) } print("hhh:\(self.articles[0])") self.tableView.reloadData() } } } } 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.articles.count ?? 0 } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier(HomeArticleReuseIdentifier, forIndexPath: indexPath) as! HomeArticleTableViewCell cell.selectionStyle = .None let count = self.articles.count ?? 0 if count > 0 { let article: Article = self.articles[indexPath.row] cell.article = article cell.clickHeadImage = {[weak self] article in let columnist = ColumnistCollectionViewController() columnist.author = article?.author self!.navigationController?.pushViewController(columnist, animated: true) } } return cell } /* // Override to support conditional editing of the table view. override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } */ /* // Override to support editing the table view. override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { // Delete the row from the data source tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } else if editingStyle == .Insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } */ /* // Override to support rearranging the table view. override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the item to be re-orderable. return true } */ /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
9528d4b85d4f8c22529090fbe70e1fb8
30.523077
164
0.602245
false
false
false
false
ospr/UIPlayground
refs/heads/master
UIPlaygroundUI/SpringBoardAppCollectionViewController.swift
mit
1
// // SpringBoardAppCollectionViewController.swift // UIPlayground // // Created by Kip Nicol on 9/20/16. // Copyright © 2016 Kip Nicol. All rights reserved. // import UIKit protocol SpringBoardAppCollectionViewControllerDelegate: class { func springBoardAppCollectionViewController(_ viewController: SpringBoardAppCollectionViewController, didSelectAppInfo appInfo: SpringBoardAppInfo, selectedAppIconButton: UIButton) func springBoardAppCollectionViewControllerDidUpdateEditMode(_ viewController: SpringBoardAppCollectionViewController) } private let reuseIdentifier = "Cell" struct SpringBoardAppInfo { let appName: String let image: UIImage } class SpringBoardAppCollectionViewController: UICollectionViewController, UICollectionViewDelegateFlowLayout { let appCollectionLayout: SpringBoardAppCollectionLayout let appInfoItems: [SpringBoardAppInfo] var editModeEnabled: Bool = false { didSet { if editModeEnabled != oldValue { // Reload cells to start/stop animations collectionView!.reloadData() } } } weak var delegate: SpringBoardAppCollectionViewControllerDelegate? fileprivate var appInfoByAppIconButtons = [UIButton : SpringBoardAppInfo]() init(appInfoItems: [SpringBoardAppInfo], appCollectionLayout: SpringBoardAppCollectionLayout) { self.appCollectionLayout = appCollectionLayout self.appInfoItems = appInfoItems let viewLayout = UICollectionViewFlowLayout() viewLayout.minimumInteritemSpacing = appCollectionLayout.minimumInteritemSpacing viewLayout.minimumLineSpacing = appCollectionLayout.minimumLineSpacing viewLayout.itemSize = appCollectionLayout.itemSize viewLayout.sectionInset = appCollectionLayout.sectionInset super.init(collectionViewLayout: viewLayout) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - View Lifecycle override func viewDidLoad() { super.viewDidLoad() collectionView!.backgroundColor = .clear collectionView!.register(SpringBoardAppIconViewCell.self, forCellWithReuseIdentifier: "AppIconCell") } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) // The cells stop animating sometimes when the view disappears // (eg spring board page view transitions) for cell in collectionView!.visibleCells { if let cell = cell as? SpringBoardAppIconViewCell { updateCellAnimations(cell) } } } // MARK: - UICollectionViewDataSource override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return appInfoItems.count } override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let appInfo = appInfoItems[indexPath.row] let appIconCell = collectionView.dequeueReusableCell(withReuseIdentifier: "AppIconCell", for: indexPath) as! SpringBoardAppIconViewCell appIconCell.delegate = self appIconCell.appNameLabel.text = appInfo.appName appIconCell.appIconImage = appInfo.image appIconCell.appIconLength = appCollectionLayout.iconLength appIconCell.appIconButtonView.removeTarget(nil, action: nil, for: .allEvents) appIconCell.appIconButtonView.addTarget(self, action: #selector(appIconButtonWasTapped), for: .touchUpInside) appInfoByAppIconButtons[appIconCell.appIconButtonView] = appInfo updateCellAnimations(appIconCell) return appIconCell } // MARK: - Working with Animations func updateCellAnimations(_ cell: SpringBoardAppIconViewCell) { let jitterAnimationKey = "Jitter" if editModeEnabled { if cell.layer.animation(forKey: jitterAnimationKey) == nil { let jitterAnimation = CAAnimation.jitterAnimation() // Add a offset to the animation time to cause the cells // to jitter at different offsets jitterAnimation.timeOffset = CACurrentMediaTime() + drand48() cell.layer.add(jitterAnimation, forKey: jitterAnimationKey) } } else { cell.layer.removeAnimation(forKey: jitterAnimationKey) } cell.appIconButtonView.isUserInteractionEnabled = !editModeEnabled } // MARK: - Handling touch events func appIconButtonWasTapped(sender: UIButton) { let appInfo = appInfoByAppIconButtons[sender]! delegate?.springBoardAppCollectionViewController(self, didSelectAppInfo: appInfo, selectedAppIconButton: sender) } } extension SpringBoardAppCollectionViewController: SpringBoardAppIconViewCellDelegate { func springBoardAppIconViewCell(didLongPress springBoardAppIconViewCell: SpringBoardAppIconViewCell) { delegate?.springBoardAppCollectionViewControllerDidUpdateEditMode(self) } }
a2eea7c01f3cb5e27cc2d234bb7e658f
37.086957
184
0.703387
false
false
false
false
delannoyk/SoundcloudSDK
refs/heads/master
sources/SoundcloudSDK/model/Enums.swift
mit
1
// // Enums.swift // SoundcloudSDK // // Created by Kevin DELANNOY on 24/02/15. // Copyright (c) 2015 Kevin Delannoy. All rights reserved. // import Foundation public enum SharingAccess: String { case `public` = "public" case `private` = "private" } public enum PlaylistType: String { case epSingle = "ep single" case album = "album" case compilation = "compilation" case projectFiles = "project files" case archive = "archive" case showcase = "showcase" case demo = "demo" case samplePack = "sample pack" case other = "other" }
b7da65e4b231cfc541b80846fdb478a9
21.307692
59
0.655172
false
false
false
false
drewcrawford/DCAKit
refs/heads/master
DCAKit/Controls/MockupPower.swift
mit
1
// // MockupPower.swift // DCAKit // // Created by Drew Crawford on 1/20/15. // Copyright (c) 2015 DrewCrawfordApps. // This file is part of DCAKit. It is subject to the license terms in the LICENSE // file found in the top level of this distribution and at // https://github.com/drewcrawford/DCAKit/blob/master/LICENSE. // No part of DCAKit, including this file, may be copied, modified, // propagated, or distributed except according to the terms contained // in the LICENSE file. import UIKit @IBDesignable class MockupPower : UIImageView { @IBInspectable var alwaysTakeTouch: Bool = false private var recognizer : UIPanGestureRecognizer! = nil let totalSlide = CGFloat(100.0) override func awakeFromNib() { recognizer = UIPanGestureRecognizer(target: self, action: "panned") recognizer.minimumNumberOfTouches = 2 self.addGestureRecognizer(recognizer) self.userInteractionEnabled = true self.alpha = 1.0 //match translation better if (!self.hidden) { BlueLog.warn("A mockup is on.") } } @objc func panned() { switch(recognizer.state) { case .Ended, .Cancelled: recognizer.setTranslation(CGPointZero, inView: self) return default: break } var proposedAlpha = (totalSlide - recognizer.translationInView(self).y) / totalSlide if (proposedAlpha < 0) { proposedAlpha = 0.01 } if (proposedAlpha > 1) { proposedAlpha = 1} self.alpha = proposedAlpha } //MARK: Decide whether to handle the touch with this one weird trick private var dontStackOverflow = false override func hitTest(point: CGPoint, withEvent event: UIEvent?) -> UIView? { if alwaysTakeTouch { return self } if (dontStackOverflow) { return nil } let window = UIApplication.sharedApplication().delegate!.window!! let windowCoordinates = window.convertPoint(point, fromView: self) dontStackOverflow = true let hitTest = window.hitTest(windowCoordinates, withEvent: event) dontStackOverflow = false self.userInteractionEnabled = true if hitTest == nil { return self } if hitTest!.dynamicType === UIView.self { return self } if hitTest!.hierarchyContainsTag(1337) && !self.hidden { return self } //set tag to 1337 to get always-mockup behavior return nil } } private extension UIView { /**Determine if the given tag is associated with the view or its superviews. */ func hierarchyContainsTag(tag: Int) -> Bool { if self.tag == tag { return true } if self.superview != nil { return superview!.hierarchyContainsTag(tag) } return false } }
9afc51c1e6a3d0aba9e7e15e9cbea269
35.24359
126
0.646851
false
true
false
false
TonyStark106/NiceKit
refs/heads/master
Example/Pods/Siren/Sources/SirenDateExtension.swift
mit
1
// // SirenDateExtension.swift // SirenExample // // Created by Arthur Sabintsev on 3/21/17. // Copyright © 2017 Sabintsev iOS Projects. All rights reserved. // import Foundation internal extension Date { static func days(since date: Date) -> Int { let calendar = Calendar.current let components = calendar.dateComponents([.day], from: date, to: Date()) return components.day ?? 0 } static func days(since dateString: String) -> Int? { let dateformatter = DateFormatter() dateformatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss'Z'" guard let releaseDate = dateformatter.date(from: dateString) else { return nil } return days(since: releaseDate) } }
0228ac026a9d91c24590b2502272ce03
25.571429
80
0.639785
false
true
false
false
luckymore0520/leetcode
refs/heads/master
Trapping Rain Water.playground/Contents.swift
mit
1
//: Playground - noun: a place where people can play import UIKit //Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining. // //For example, //Given [0,1,0,2,1,0,1,3,2,1,2,1], return 6. class Solution { func trap(_ height: [Int]) -> Int { if (height.count <= 2) { return 0 } var water = 0 for i in 0...height.count - 2 { let current = height[i] let right = height[i+1] //右边更低且右边至少有两个才可能存水 if (right < current && i+1 < height.count-1) { var highest = right for j in i+2...height.count-1 { let next = height[j] if (next > highest) { water += (min(next,current) - highest) * (j - i - 1) highest = next } if (highest > current) { break } } } } return water } } let solution = Solution() solution.trap([])
a7a494e896b8f3d22ef422bd43b3f3b7
27.073171
152
0.46
false
false
false
false
aquarchitect/MyKit
refs/heads/master
Sources/Shared/Extensions/CoreGraphics/CGRect+.swift
mit
1
// // CGRect+.swift // MyKit // // Created by Hai Nguyen. // Copyright (c) 2015 Hai Nguyen. // import CoreGraphics public extension CGRect { var center: CGPoint { get { return CGPoint(x: self.midX, y: self.midY) } set { self.origin.x = newValue.x - self.width/2 self.origin.y = newValue.y - self.height/2 } } init(center: CGPoint, sideLength: CGFloat) { let origin = CGPoint(x: center.x - sideLength/2, y: center.y - sideLength/2) let size = CGSize(sideLength: sideLength) self.init(origin: origin, size: size) } init(center: CGPoint, size: CGSize) { let origin = CGPoint(x: center.x - size.width/2, y: center.y - size.height/2) self.init(origin: origin, size: size) } } public extension CGRect { typealias Tile = (column: Int, row: Int, rect: CGRect) func slices(_ rect: CGRect, intoTilesOf size: CGSize) -> AnyIterator<Tile> { let firstColumn = Int(rect.minX/size.width) let lastColumn = Int(rect.maxX/size.width) + 1 let firstRow = Int(rect.minY/size.height) let lastRow = Int(rect.maxY/size.height) + 1 var i = firstColumn, j = firstRow return AnyIterator<Tile> { while i < lastColumn && j < lastRow { let rect = CGRect( x: size.width * CGFloat(i), y: size.height * CGFloat(j), width: size.width, height: size.height ) let tile: Tile = (i, j, self.intersection(rect)) if i == lastColumn - 1 { i = firstColumn; j += 1 } else { i += 1 } if tile.rect.isEmpty { continue } else { return tile } } return nil } } }
0b5a9cc001cd53b122c6d94a402075c3
25.105263
85
0.492944
false
false
false
false
TechnologySpeaks/smile-for-life
refs/heads/master
smile-for-life/CalendarOralEventsViewController.swift
mit
1
// // CalendarViewController.swift // smile-for-life // // Created by Lisa Swanson on 2/29/16. // Copyright © 2016 Technology Speaks. All rights reserved. // // // CalendarMasterViewController.swift // SmileCalendar // // Created by Lisa Swanson on 7/23/16. // Copyright © 2016 Technology Speaks. All rights reserved. // /* import UIKit let reuseIdentifierOld = "MasterCell" let dataOld = CalendarArrayData() class CalendarOralEventsViewController: UIViewController { @IBOutlet weak var masterCollectionView: UICollectionView! override func viewDidLoad() { super.viewDidLoad() print(UIScreen.main.bounds.size) self.masterCollectionView.register(MasterCellCollectionViewCell.self, forCellWithReuseIdentifier: reuseIdentifierOld) // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ } extension CalendarOralEventsViewController: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout { func numberOfSections(in collectionView: UICollectionView) -> Int { // print("Number of sections \(calendarData.numberOfOralHygieneEventSections)") return dataOld.sectionHeaders.count } func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView { let cellHeader = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "MasterSectionHeader", for: indexPath) as! MasterHeaderSectionCollectionReusableView // if let title = calendarData.titleForOralHygieneEventSections(indexPath) { // section.sectionHeader = title // } cellHeader.sectionHeader = dataOld.sectionHeaders[(indexPath as NSIndexPath).row] return cellHeader } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of items return 1 } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let oralEventCell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! MasterCellCollectionViewCell oralEventCell.backgroundColor = UIColor.clear // Configure the cell return oralEventCell } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { return CGSize(width: view.frame.width - 20, height: 90) } } */
4f7888a6aafad4fdf8d373b222575c3f
31.340206
188
0.747211
false
false
false
false
ithree1113/LocationTalk
refs/heads/master
LocationTalk/Extension.swift
mit
1
// // Extension.swift // LocationTalk // // Created by 鄭宇翔 on 2017/2/23. // Copyright © 2017年 鄭宇翔. All rights reserved. // import Foundation import UIKit extension UIView { func makeCircle(radius: Int) { let maskPath = UIBezierPath.init(roundedRect: self.bounds, byRoundingCorners: .allCorners, cornerRadii: CGSize.init(width: radius, height: radius)) let maskLayer = CAShapeLayer.init() maskLayer.frame = self.bounds maskLayer.path = maskPath.cgPath self.layer.mask = maskLayer } }
08cb5e1ef528d8ba396707face55027a
24.045455
155
0.664247
false
false
false
false
JackLearning/Weibo
refs/heads/master
Weibo/Weibo/Classes/Module/Home/StatusCell/WBRefreshControl.swift
mit
1
// // WBRefreshControl.swift // Weibo // // Created by ZhuZongchao on 15/12/23. // Copyright © 2015年 apple. All rights reserved. // import UIKit import SnapKit enum WBRefreshStatus:Int { // 默认状态 case Normal = 0 // 用户下拉到临界值 还没有松手刷新的状态 case Pulling = 1 // 正在刷新的状态 case Refreshing = 2 } // 刷新控件的高度 private let RefreshViewHeight: CGFloat = 60 class WBRefreshControl: UIControl { //定义属性 保存上一次刷新的状态 var oldStatus:WBRefreshStatus = .Normal //MARK:定义外部模型属性 var status: WBRefreshStatus = .Normal { didSet { // 根据不同的状态 更改显示的逻辑 switch status { case .Pulling : print("准备起飞") //1,修改提示文案 tipLabel.text = "准备起飞" //2,旋转箭头 UIView.animateWithDuration(0.25, animations: { () -> Void in self.arrowIcon.transform = CGAffineTransformMakeRotation( CGFloat(M_PI)) }) case .Refreshing: print("正在起飞") tipLabel.text = "正在起飞" // 隐藏箭头 显示转动的小菊花 arrowIcon.hidden = true loadIcon.startAnimating() // 应该主动触发 control 方法的响应事件 // 修改contentInset var inset = scrollView!.contentInset inset.top += RefreshViewHeight scrollView?.contentInset = inset sendActionsForControlEvents(.ValueChanged) sendActionsForControlEvents(.ValueChanged) case .Normal: // 回到从前 最初的状态 重置 print("下拉起飞") tipLabel.text = "下拉起飞" arrowIcon.hidden = false loadIcon.stopAnimating() // 修改contentInset inset.Top 会被多减一次 if oldStatus == .Refreshing { var inset = scrollView!.contentInset inset.top -= RefreshViewHeight scrollView?.contentInset = inset } // 重置箭头方向 UIView.animateWithDuration(0.25, animations: { () -> Void in self.arrowIcon.transform = CGAffineTransformIdentity }) } // 所有的设置结束后 保存上一次的刷新状态 oldStatus = status } } // 实现kvo方法 override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) { // 1,获取tableView的临界值 let insetTop = scrollView?.contentInset.top ?? 0 let condationValue = -(RefreshViewHeight + insetTop) // 2,获取tableView的contentOffset let offsetY = scrollView?.contentOffset.y ?? 0 if scrollView!.dragging { if status == .Normal && offsetY < condationValue { // 用户下拉到临界值 还没松手刷新的状态 status = .Pulling } else if status == .Pulling && offsetY > condationValue { // 进入默认状态 status = .Normal } } else { // 不是在拉拽的状态 并且当前视图的status 是pulling状态 再执行刷新操作 if status == .Pulling { status = .Refreshing } } // 3,比较对应的临界值和位移的大小 } func endRefreshing() { let delta = dispatch_time(DISPATCH_TIME_NOW, Int64(1) * Int64(NSEC_PER_SEC)) dispatch_after(delta, dispatch_get_main_queue()) { () -> Void in self.status = .Normal } } // view的生命周期方法 // 子视图将要添加到父视图的时候 override func willMoveToSuperview(newSuperview: UIView?) { super.willMoveToSuperview(newSuperview) // 可以获取到当前空间的父视图 // 1,获取tableView if let myFather = newSuperview as? UIScrollView { // 如果父视图能够转化为 滚动视图 // 观察 滚动视图的contentOffset self.scrollView = myFather // 设置kvo self.scrollView?.addObserver(self, forKeyPath: "contentOffset", options: .New, context: nil) } } // 移除kvo 观察 deinit { self.scrollView?.removeObserver(self, forKeyPath: "contentOffset") } // 定义属性 记录父视图 var scrollView :UIScrollView? // MARK:重写构造方法 override init(frame: CGRect) { // 在视图内部确定frame let rect = CGRect(x: 0, y: -RefreshViewHeight, width: screenW, height: RefreshViewHeight) super.init(frame: rect) setupUI() //设置颜色 backgroundColor = UIColor.randomColor() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // 设置页面和布局 private func setupUI() { // 添加子视图 addSubview(tipLabel) addSubview(arrowIcon) addSubview(loadIcon) // 设置约束 tipLabel.snp_makeConstraints { (make) -> Void in make.centerX.equalTo(self.snp_centerX).offset(15) make.centerY.equalTo(self.snp_centerY) } arrowIcon.snp_makeConstraints { (make) -> Void in make.right.equalTo(tipLabel.snp_left).offset(-5) make.centerY.equalTo(tipLabel.snp_centerY) } loadIcon.snp_makeConstraints { (make) -> Void in make.center.equalTo(arrowIcon) } } //MARK:懒加载所有的子视图 private lazy var arrowIcon:UIImageView = UIImageView(image: UIImage(named:"tableview_pull_refresh")) private lazy var tipLabel:UILabel = UILabel(title: "下拉起飞", color: UIColor.randomColor(), fontSize: 14) private lazy var loadIcon :UIActivityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: .Gray) }
ee47d8d325c68fc3f9f2674a2f31599f
24.130045
157
0.557915
false
false
false
false
iAugux/Zoom-Contacts
refs/heads/master
Phonetic/AppDelegate.swift
mit
1
// // AppDelegate.swift // Phonetic // // Created by Augus on 1/27/16. // Copyright © 2016 iAugus. All rights reserved. // import UIKit import Contacts let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? let contactStore = CNContactStore() func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { createShortcutItemsWithIcons() application.statusBarStyle = .LightContent window?.backgroundColor = UIColor.clearColor() window?.tintColor = GLOBAL_CUSTOM_COLOR // clear icon badge number if needed. application.applicationIconBadgeNumber = 0 application.beginBackgroundTaskWithName("showNotification", expirationHandler: nil) return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. // fixes UI bug if let rootViewController = window?.rootViewController as? ViewController { if !rootViewController.isProcessing { rootViewController.progress?.alpha = 0 } } } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. // clear icon badge number application.applicationIconBadgeNumber = 0 // fixes UI bugs if let rootViewController = window?.rootViewController as? ViewController { if !rootViewController.isProcessing { UIView.animateWithDuration(0.5, delay: 0, options: .CurveEaseInOut, animations: { () -> Void in rootViewController.progress?.alpha = 1 }, completion: nil) } else { // replay if needed rootViewController.playVideoIfNeeded() } } } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } } extension AppDelegate { // Detecting touching outside of the popover override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { guard UIDevice.isPad else { return } DEBUGLog("Touched Began") kShouldRepresentPolyphonicVC = false } }
e71e8eaaff43b600437b720027655568
37.393939
285
0.685346
false
false
false
false
pksprojects/ElasticSwift
refs/heads/master
Tests/ElasticSwiftQueryDSLTests/ScriptTests.swift
mit
1
// // ScriptTests.swift // ElasticSwiftQueryDSLTests // // Created by Prafull Kumar Soni on 9/2/19. // import Logging import UnitTestSettings import XCTest @testable import ElasticSwiftCodableUtils @testable import ElasticSwiftQueryDSL class ScriptTests: XCTestCase { let logger = Logger(label: "org.pksprojects.ElasticSwiftQueryDSLTests.ScriptTests", factory: logFactory) override func setUp() { // Put setup code here. This method is called before the invocation of each test method in the class. super.setUp() XCTAssert(isLoggingConfigured) logger.info("====================TEST=START===============================") } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() logger.info("====================TEST=END===============================") } func testScript_encode_short() throws { let script = Script("ctx._source.likes++") let dic = ["script": script] let encoded = try JSONEncoder().encode(dic) let encodedStr = String(data: encoded, encoding: .utf8)! logger.debug("Script Encode test: \(encodedStr)") let decodedDic = try JSONDecoder().decode([String: CodableValue].self, from: encoded) let expectedDic = try JSONDecoder().decode([String: CodableValue].self, from: "{\"script\":\"ctx._source.likes++\"}".data(using: .utf8)!) XCTAssertEqual(expectedDic, decodedDic) } func testScript_decode_short() throws { let jsonStr = "{\"script\":\"ctx._source.likes++\"}" let decoded = try JSONDecoder().decode([String: Script].self, from: jsonStr.data(using: .utf8)!) logger.debug("Script Decode test: \(decoded)") XCTAssertEqual("ctx._source.likes++", decoded["script"]!.source) } func testScript_encode() throws { let script = Script("doc['my_field'] * multiplier", lang: "expression", params: ["multiplier": 2]) let encoded = try JSONEncoder().encode(script) let encodedStr = String(data: encoded, encoding: .utf8)! logger.debug("Script Encode test: \(encodedStr)") let decodedDic = try JSONDecoder().decode([String: CodableValue].self, from: encoded) let expectedDic = try JSONDecoder().decode([String: CodableValue].self, from: "{\"lang\":\"expression\",\"params\":{\"multiplier\":2},\"source\":\"doc['my_field'] * multiplier\"}".data(using: .utf8)!) XCTAssertEqual(expectedDic, decodedDic) } func testScript_decode() throws { let jsonStr = "{\"lang\":\"expression\",\"source\":\"doc['my_field'] * multiplier\",\"params\":{\"multiplier\": 2}}" let decoded = try JSONDecoder().decode(Script.self, from: jsonStr.data(using: .utf8)!) logger.debug("Script Decode test: \(decoded)") XCTAssertEqual("doc['my_field'] * multiplier", decoded.source) XCTAssertEqual(2, decoded.params!["multiplier"]!) XCTAssertEqual("expression", decoded.lang!) } }
6c48f31747ffb840fb93b4eb1416f352
35.247059
208
0.627394
false
true
false
false
hooman/swift
refs/heads/main
stdlib/public/core/StringUnicodeScalarView.swift
apache-2.0
3
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // FIXME(ABI)#71 : The UTF-16 string view should have a custom iterator type to // allow performance optimizations of linear traversals. extension String { /// A view of a string's contents as a collection of Unicode scalar values. /// /// You can access a string's view of Unicode scalar values by using its /// `unicodeScalars` property. Unicode scalar values are the 21-bit codes /// that are the basic unit of Unicode. Each scalar value is represented by /// a `Unicode.Scalar` instance and is equivalent to a UTF-32 code unit. /// /// let flowers = "Flowers 💐" /// for v in flowers.unicodeScalars { /// print(v.value) /// } /// // 70 /// // 108 /// // 111 /// // 119 /// // 101 /// // 114 /// // 115 /// // 32 /// // 128144 /// /// Some characters that are visible in a string are made up of more than one /// Unicode scalar value. In that case, a string's `unicodeScalars` view /// contains more elements than the string itself. /// /// let flag = "🇵🇷" /// for c in flag { /// print(c) /// } /// // 🇵🇷 /// /// for v in flag.unicodeScalars { /// print(v.value) /// } /// // 127477 /// // 127479 /// /// You can convert a `String.UnicodeScalarView` instance back into a string /// using the `String` type's `init(_:)` initializer. /// /// let favemoji = "My favorite emoji is 🎉" /// if let i = favemoji.unicodeScalars.firstIndex(where: { $0.value >= 128 }) { /// let asciiPrefix = String(favemoji.unicodeScalars[..<i]) /// print(asciiPrefix) /// } /// // Prints "My favorite emoji is " @frozen public struct UnicodeScalarView: Sendable { @usableFromInline internal var _guts: _StringGuts @inlinable @inline(__always) internal init(_ _guts: _StringGuts) { self._guts = _guts _invariantCheck() } } } extension String.UnicodeScalarView { #if !INTERNAL_CHECKS_ENABLED @inlinable @inline(__always) internal func _invariantCheck() {} #else @usableFromInline @inline(never) @_effects(releasenone) internal func _invariantCheck() { // TODO: Assert start/end are scalar aligned } #endif // INTERNAL_CHECKS_ENABLED } extension String.UnicodeScalarView: BidirectionalCollection { public typealias Index = String.Index /// The position of the first Unicode scalar value if the string is /// nonempty. /// /// If the string is empty, `startIndex` is equal to `endIndex`. @inlinable @inline(__always) public var startIndex: Index { return _guts.startIndex } /// The "past the end" position---that is, the position one greater than /// the last valid subscript argument. /// /// In an empty Unicode scalars view, `endIndex` is equal to `startIndex`. @inlinable @inline(__always) public var endIndex: Index { return _guts.endIndex } /// Returns the next consecutive location after `i`. /// /// - Precondition: The next location exists. @inlinable @inline(__always) public func index(after i: Index) -> Index { let i = _guts.scalarAlign(i) _internalInvariant(i < endIndex) // TODO(String performance): isASCII fast-path if _fastPath(_guts.isFastUTF8) { let len = _guts.fastUTF8ScalarLength(startingAt: i._encodedOffset) return i.encoded(offsetBy: len)._scalarAligned } return _foreignIndex(after: i) } @_alwaysEmitIntoClient // Swift 5.1 bug fix public func distance(from start: Index, to end: Index) -> Int { return _distance(from: _guts.scalarAlign(start), to: _guts.scalarAlign(end)) } /// Returns the previous consecutive location before `i`. /// /// - Precondition: The previous location exists. @inlinable @inline(__always) public func index(before i: Index) -> Index { let i = _guts.scalarAlign(i) precondition(i._encodedOffset > 0) // TODO(String performance): isASCII fast-path if _fastPath(_guts.isFastUTF8) { let len = _guts.withFastUTF8 { utf8 -> Int in return _utf8ScalarLength(utf8, endingAt: i._encodedOffset) } _internalInvariant(len <= 4, "invalid UTF8") return i.encoded(offsetBy: -len)._scalarAligned } return _foreignIndex(before: i) } /// Accesses the Unicode scalar value at the given position. /// /// The following example searches a string's Unicode scalars view for a /// capital letter and then prints the character and Unicode scalar value /// at the found index: /// /// let greeting = "Hello, friend!" /// if let i = greeting.unicodeScalars.firstIndex(where: { "A"..."Z" ~= $0 }) { /// print("First capital letter: \(greeting.unicodeScalars[i])") /// print("Unicode scalar value: \(greeting.unicodeScalars[i].value)") /// } /// // Prints "First capital letter: H" /// // Prints "Unicode scalar value: 72" /// /// - Parameter position: A valid index of the character view. `position` /// must be less than the view's end index. @inlinable @inline(__always) public subscript(position: Index) -> Unicode.Scalar { String(_guts)._boundsCheck(position) let i = _guts.scalarAlign(position) return _guts.errorCorrectedScalar(startingAt: i._encodedOffset).0 } } extension String.UnicodeScalarView { @frozen public struct Iterator: IteratorProtocol, Sendable { @usableFromInline internal var _guts: _StringGuts @usableFromInline internal var _position: Int = 0 @usableFromInline internal var _end: Int @inlinable internal init(_ guts: _StringGuts) { self._end = guts.count self._guts = guts } @inlinable @inline(__always) public mutating func next() -> Unicode.Scalar? { guard _fastPath(_position < _end) else { return nil } let (result, len) = _guts.errorCorrectedScalar(startingAt: _position) _position &+= len return result } } @inlinable public __consuming func makeIterator() -> Iterator { return Iterator(_guts) } } extension String.UnicodeScalarView: CustomStringConvertible { @inlinable @inline(__always) public var description: String { return String(_guts) } } extension String.UnicodeScalarView: CustomDebugStringConvertible { public var debugDescription: String { return "StringUnicodeScalarView(\(self.description.debugDescription))" } } extension String { /// Creates a string corresponding to the given collection of Unicode /// scalars. /// /// You can use this initializer to create a new string from a slice of /// another string's `unicodeScalars` view. /// /// let picnicGuest = "Deserving porcupine" /// if let i = picnicGuest.unicodeScalars.firstIndex(of: " ") { /// let adjective = String(picnicGuest.unicodeScalars[..<i]) /// print(adjective) /// } /// // Prints "Deserving" /// /// The `adjective` constant is created by calling this initializer with a /// slice of the `picnicGuest.unicodeScalars` view. /// /// - Parameter unicodeScalars: A collection of Unicode scalar values. @inlinable @inline(__always) public init(_ unicodeScalars: UnicodeScalarView) { self.init(unicodeScalars._guts) } /// The index type for a string's `unicodeScalars` view. public typealias UnicodeScalarIndex = UnicodeScalarView.Index /// The string's value represented as a collection of Unicode scalar values. @inlinable public var unicodeScalars: UnicodeScalarView { @inline(__always) get { return UnicodeScalarView(_guts) } @inline(__always) set { _guts = newValue._guts } } } extension String.UnicodeScalarView: RangeReplaceableCollection { /// Creates an empty view instance. @inlinable @inline(__always) public init() { self.init(_StringGuts()) } /// Reserves enough space in the view's underlying storage to store the /// specified number of ASCII characters. /// /// Because a Unicode scalar value can require more than a single ASCII /// character's worth of storage, additional allocation may be necessary /// when adding to a Unicode scalar view after a call to /// `reserveCapacity(_:)`. /// /// - Parameter n: The minimum number of ASCII character's worth of storage /// to allocate. /// /// - Complexity: O(*n*), where *n* is the capacity being reserved. public mutating func reserveCapacity(_ n: Int) { self._guts.reserveCapacity(n) } /// Appends the given Unicode scalar to the view. /// /// - Parameter c: The character to append to the string. public mutating func append(_ c: Unicode.Scalar) { self._guts.append(String(c)._guts) } /// Appends the Unicode scalar values in the given sequence to the view. /// /// - Parameter newElements: A sequence of Unicode scalar values. /// /// - Complexity: O(*n*), where *n* is the length of the resulting view. public mutating func append<S: Sequence>(contentsOf newElements: S) where S.Element == Unicode.Scalar { // TODO(String performance): Skip extra String allocation let scalars = String(decoding: newElements.map { $0.value }, as: UTF32.self) self = (String(self._guts) + scalars).unicodeScalars } /// Replaces the elements within the specified bounds with the given Unicode /// scalar values. /// /// Calling this method invalidates any existing indices for use with this /// string. /// /// - Parameters: /// - bounds: The range of elements to replace. The bounds of the range /// must be valid indices of the view. /// - newElements: The new Unicode scalar values to add to the string. /// /// - Complexity: O(*m*), where *m* is the combined length of the view and /// `newElements`. If the call to `replaceSubrange(_:with:)` simply /// removes elements at the end of the string, the complexity is O(*n*), /// where *n* is equal to `bounds.count`. public mutating func replaceSubrange<C>( _ bounds: Range<Index>, with newElements: C ) where C: Collection, C.Element == Unicode.Scalar { // TODO(String performance): Skip extra String and Array allocation let utf8Replacement = newElements.flatMap { String($0).utf8 } let replacement = utf8Replacement.withUnsafeBufferPointer { return String._uncheckedFromUTF8($0) } var copy = String(_guts) copy.replaceSubrange(bounds, with: replacement) self = copy.unicodeScalars } } // Index conversions extension String.UnicodeScalarIndex { /// Creates an index in the given Unicode scalars view that corresponds /// exactly to the specified `UTF16View` position. /// /// The following example finds the position of a space in a string's `utf16` /// view and then converts that position to an index in the string's /// `unicodeScalars` view: /// /// let cafe = "Café 🍵" /// /// let utf16Index = cafe.utf16.firstIndex(of: 32)! /// let scalarIndex = String.Index(utf16Index, within: cafe.unicodeScalars)! /// /// print(String(cafe.unicodeScalars[..<scalarIndex])) /// // Prints "Café" /// /// If the index passed as `sourcePosition` doesn't have an exact /// corresponding position in `unicodeScalars`, the result of the /// initializer is `nil`. For example, an attempt to convert the position of /// the trailing surrogate of a UTF-16 surrogate pair results in `nil`. /// /// - Parameters: /// - sourcePosition: A position in the `utf16` view of a string. /// `utf16Index` must be an element of /// `String(unicodeScalars).utf16.indices`. /// - unicodeScalars: The `UnicodeScalarView` in which to find the new /// position. public init?( _ sourcePosition: String.Index, within unicodeScalars: String.UnicodeScalarView ) { guard unicodeScalars._guts.isOnUnicodeScalarBoundary(sourcePosition) else { return nil } self = sourcePosition } /// Returns the position in the given string that corresponds exactly to this /// index. /// /// This example first finds the position of a space (UTF-8 code point `32`) /// in a string's `utf8` view and then uses this method find the same position /// in the string. /// /// let cafe = "Café 🍵" /// let i = cafe.unicodeScalars.firstIndex(of: "🍵")! /// let j = i.samePosition(in: cafe)! /// print(cafe[j...]) /// // Prints "🍵" /// /// - Parameter characters: The string to use for the index conversion. /// This index must be a valid index of at least one view of `characters`. /// - Returns: The position in `characters` that corresponds exactly to /// this index. If this index does not have an exact corresponding /// position in `characters`, this method returns `nil`. For example, /// an attempt to convert the position of a UTF-8 continuation byte /// returns `nil`. public func samePosition(in characters: String) -> String.Index? { return String.Index(self, within: characters) } } // Reflection extension String.UnicodeScalarView: CustomReflectable { /// Returns a mirror that reflects the Unicode scalars view of a string. public var customMirror: Mirror { return Mirror(self, unlabeledChildren: self) } } //===--- Slicing Support --------------------------------------------------===// /// In Swift 3.2, in the absence of type context, /// /// someString.unicodeScalars[ /// someString.unicodeScalars.startIndex /// ..< someString.unicodeScalars.endIndex] /// /// was deduced to be of type `String.UnicodeScalarView`. Provide a /// more-specific Swift-3-only `subscript` overload that continues to produce /// `String.UnicodeScalarView`. extension String.UnicodeScalarView { public typealias SubSequence = Substring.UnicodeScalarView @available(swift, introduced: 4) public subscript(r: Range<Index>) -> String.UnicodeScalarView.SubSequence { return String.UnicodeScalarView.SubSequence(self, _bounds: r) } } // Foreign string Support extension String.UnicodeScalarView { @usableFromInline @inline(never) @_effects(releasenone) internal func _foreignIndex(after i: Index) -> Index { _internalInvariant(_guts.isForeign) let cu = _guts.foreignErrorCorrectedUTF16CodeUnit(at: i) let len = UTF16.isLeadSurrogate(cu) ? 2 : 1 return i.encoded(offsetBy: len)._scalarAligned } @usableFromInline @inline(never) @_effects(releasenone) internal func _foreignIndex(before i: Index) -> Index { _internalInvariant(_guts.isForeign) let priorIdx = i.priorEncoded let cu = _guts.foreignErrorCorrectedUTF16CodeUnit(at: priorIdx) let len = UTF16.isTrailSurrogate(cu) ? 2 : 1 return i.encoded(offsetBy: -len)._scalarAligned } }
33347b59a6b91bd9169a8f91ecdd7047
34.004598
85
0.656794
false
false
false
false
wallflyrepo/Ject
refs/heads/master
Example/Sources/Graph.swift
apache-2.0
2
// // Graph.swift // Pods // // Created by Williams, Joshua on 9/25/17. // // import Foundation /** * Default Dependency Graph. This graph determines whether a dependency is a Singleton or not. If it is a Singleton, it is stored in a dictionary * to be used later. This class is public so you can subclass it. **/ public class Graph: DependencyGraph { /** * Dictionary that holds singleton dependencies **/ private var singletonDependencyGraph = [String: Injectable]() /** * LogManager instance to log things. **/ private var logManager: LogManager? /** * Default constructor **/ init() { //Default Constructor } /** * Instantiate this class with a log manager **/ init(_ logManager: LogManager) { self.logManager = logManager } /** * Construct a new default instance. **/ public static func newInstance() -> Graph { return Graph(LogManager(Graph.self)) } /** * Retrieves the name of the class passed as a parameter. **/ private func description(_ type: Any) -> String { return String(describing: type) } /** * Returns a dependency from the singleton dependency graph or nil **/ private func getDependency<T: Injectable>(_ injectableClass: Any) -> T? { let className = description(injectableClass) guard let dependency = singletonDependencyGraph[className] else { logManager?.print("Dependency \(className) was not found. instantiating.") return nil } logManager?.print("Dependency \(className) was found.") return dependency as? T } /** * Injects an Injectable dependency into a class using its Type (Class.self). **/ public func inject<T: Injectable>(_ injectableClass: T.Type) -> T { return inject(injectableClass.init()) } /** * Injects an Injectable dependency into a class using an instance of the class. **/ public func inject<T: Injectable>(_ injectableClass: Injectable) -> T { let key = type(of: injectableClass as Any) var resolvedDependency: T if(injectableClass.isSingleton()) { if let dependency: T = getDependency(key) { return dependency } singletonDependencyGraph[description(key)] = injectableClass.inject(dependencyGraph: self) resolvedDependency = inject(injectableClass) } else { resolvedDependency = injectableClass.inject(dependencyGraph: self) as! T } return resolvedDependency } }
2e932e71425be72f1a1c149421974b63
27.574468
145
0.611318
false
false
false
false
jverdi/Gramophone
refs/heads/master
Source/Client/Request.swift
mit
1
// // Request.swift // Gramophone // // Copyright (c) 2017 Jared Verdi. 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. // import Foundation import protocol Decodable.Decodable import Result extension Client { enum HTTPMethod: String { case get = "GET" case post = "POST" case delete = "DELETE" } @discardableResult func request<DecodableType: Decodable>(method: HTTPMethod, apiResource: Resource, params: [Param: Any]? = nil, options: RequestOptions? = nil, completion: @escaping (APIResult<DecodableType>) -> Void) -> URLSessionDataTask? { guard hasValidAccessToken(accessToken) else { completion(Result.failure(APIError.authenticationRequired(responseError: nil))); return nil } var parameters: [String: Any] = [ Param.accessToken.rawValue: accessToken! ] params?.forEach{ parameters[$0.rawValue] = $1 } guard let url = resource(apiResource, options: options, parameters: parameters) else { completion(Result.failure(APIError.invalidURL(path: apiResource.uri()))); return nil } var request = URLRequest(url: url) request.httpMethod = method.rawValue if .post == method || .delete == method { if let queryItems = queryItems(options: nil, parameters: parameters), queryItems.count > 0 { var components = URLComponents() components.queryItems = queryItems if let postString = components.query { request.httpBody = postString.data(using: .utf8) } } } return fetch(request: request, completion: completion) } @discardableResult func fetch<DecodableType: Decodable>(request: URLRequest, completion: @escaping (APIResult<DecodableType>) -> Void) -> URLSessionDataTask { return fetch(request: request) { result, response in DispatchQueue.main.async { switch result { case Result.success(let data): self.handleJSON(data.data, response, completion) case Result.failure(let error): completion(.failure(error)) } } } } @discardableResult func fetch(request: URLRequest, completion: @escaping (APIResult<Data>, URLResponse?) -> Void) -> URLSessionDataTask { var req = request if let accessToken = accessToken { req = addAccessToken(accessToken, toRequest: req) } let task = urlSession.dataTask(with: request) { [weak self] data, response, error in if let data = data { completion(Result.success(APIResponse<Data>(data: data)), response) return } if let httpResponse = response as? HTTPURLResponse, let error = self?.serverError(forStatusCode: httpResponse.statusCode) { completion(Result.failure(error), response) return } if let error = error { completion(Result.failure(APIError.unknownError(responseError: error)), response) return } let apiError = APIError.invalidHTTPResponse(response: response) completion(Result.failure(apiError), response) } task.resume() return task } func addAccessToken(_ accessToken: String, toRequest request: URLRequest) -> URLRequest { var req = request var headerFields = req.allHTTPHeaderFields ?? [String: String]() headerFields["Authorization"] = "Token token=\"\(accessToken)\"" req.allHTTPHeaderFields = headerFields return req } func serverError(forStatusCode statusCode: Int) -> APIError? { switch statusCode { case 500: return APIError.serverError case 502: return APIError.badGateway case 503: return APIError.serviceUnavailable case 504: return APIError.gatewayTimeout default: return nil } } @discardableResult func get<DecodableType: Decodable>(_ apiResource: Resource, params: [Param: Any]? = nil, options: RequestOptions? = nil, completion: @escaping (APIResult<DecodableType>) -> Void) -> URLSessionDataTask? { return request(method: .get, apiResource: apiResource, params: params, options: options, completion: completion) } @discardableResult func post<DecodableType: Decodable>(_ apiResource: Resource, params: [Param: Any]? = nil, options: RequestOptions? = nil, completion: @escaping (APIResult<DecodableType>) -> Void) -> URLSessionDataTask? { return request(method: .post, apiResource: apiResource, params: params, options: options, completion: completion) } @discardableResult func delete<DecodableType: Decodable>(_ apiResource: Resource, params: [Param: Any]? = nil, options: RequestOptions? = nil, completion: @escaping (APIResult<DecodableType>) -> Void) -> URLSessionDataTask? { return request(method: .delete, apiResource: apiResource, params: params, options: options, completion: completion) } } enum Param: String { case clientID = "client_id" case redirectURI = "redirect_uri" case responseType = "response_type" case scope = "scope" case accessToken = "access_token" case searchQuery = "q" case relationshipAction = "action" case latitude = "lat" case longitude = "lng" case distance = "distance" case commentText = "text" case url = "url" } public struct RequestOptions { let minID: String? let maxID: String? let count: Int? public init(minID: String? = nil, maxID: String? = nil, count: Int? = nil) { self.minID = minID self.maxID = maxID self.count = count } public func toParameters() -> [String: Any] { var optionsParams: [String: Any] = [:] if let count = count { optionsParams["count"] = count } if let minID = minID { optionsParams["min_id"] = minID } if let maxID = maxID { optionsParams["max_id"] = maxID } return optionsParams } }
3fd8630c2f5c69b107aefd2df23a9d35
38.784211
229
0.618468
false
false
false
false
CodaFi/swift
refs/heads/main
validation-test/compiler_crashers_2_fixed/0022-rdar21625478.swift
apache-2.0
28
// RUN: %target-swift-frontend %s -emit-silgen import StdlibUnittest public struct MyRange<Bound : ForwardIndex> { var startIndex: Bound var endIndex: Bound } public protocol ForwardIndex : Equatable { associatedtype Distance : SignedNumeric func successor() -> Self } public protocol MySequence { associatedtype Iterator : IteratorProtocol associatedtype SubSequence = Void func makeIterator() -> Iterator var underestimatedCount: Int { get } func map<T>( _ transform: (Iterator.Element) -> T ) -> [T] func filter( _ isIncluded: (Iterator.Element) -> Bool ) -> [Iterator.Element] func _customContainsEquatableElement( _ element: Iterator.Element ) -> Bool? func _preprocessingPass<R>( _ preprocess: (Self) -> R ) -> R? func _copyToContiguousArray() -> ContiguousArray<Iterator.Element> func _copyContents( initializing ptr: UnsafeMutablePointer<Iterator.Element> ) -> UnsafeMutablePointer<Iterator.Element> } extension MySequence { var underestimatedCount: Int { return 0 } public func map<T>( _ transform: (Iterator.Element) -> T ) -> [T] { return [] } public func filter( _ isIncluded: (Iterator.Element) -> Bool ) -> [Iterator.Element] { return [] } public func _customContainsEquatableElement( _ element: Iterator.Element ) -> Bool? { return nil } public func _preprocessingPass<R>( _ preprocess: (Self) -> R ) -> R? { return nil } public func _copyToContiguousArray() -> ContiguousArray<Iterator.Element> { fatalError() } public func _copyContents( initializing ptr: UnsafeMutablePointer<Iterator.Element> ) -> UnsafeMutablePointer<Iterator.Element> { fatalError() } } public protocol MyIndexable : MySequence { associatedtype Index : ForwardIndex var startIndex: Index { get } var endIndex: Index { get } associatedtype _Element subscript(_: Index) -> _Element { get } } public protocol MyCollection : MyIndexable { associatedtype Iterator : IteratorProtocol = IndexingIterator<Self> associatedtype SubSequence : MySequence subscript(_: Index) -> Iterator.Element { get } subscript(_: MyRange<Index>) -> SubSequence { get } var first: Iterator.Element? { get } var isEmpty: Bool { get } var count: Index.Distance { get } func _customIndexOfEquatableElement(_ element: Iterator.Element) -> Index?? } extension MyCollection { public var isEmpty: Bool { return startIndex == endIndex } public func _preprocessingPass<R>( _ preprocess: (Self) -> R ) -> R? { return preprocess(self) } public var count: Index.Distance { return 0 } public func _customIndexOfEquatableElement(_ element: Iterator.Element) -> Index?? { return nil } } public struct IndexingIterator<I : MyIndexable> : IteratorProtocol { public func next() -> I._Element? { return nil } } protocol Resettable : AnyObject { func reset() } internal var _allResettables: [Resettable] = [] public class TypeIndexed<Value> : Resettable { public init(_ value: Value) { self.defaultValue = value _allResettables.append(self) } public subscript(t: Any.Type) -> Value { get { return byType[ObjectIdentifier(t)] ?? defaultValue } set { byType[ObjectIdentifier(t)] = newValue } } public func reset() { byType = [:] } internal var byType: [ObjectIdentifier:Value] = [:] internal var defaultValue: Value } //===--- LoggingWrappers.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 // //===----------------------------------------------------------------------===// public protocol Wrapper { associatedtype Base init(_: Base) var base: Base {get set} } public protocol LoggingType : Wrapper { associatedtype Log : AnyObject } extension LoggingType { public var log: Log.Type { return Log.self } public var selfType: Any.Type { return type(of: self) } } public class IteratorLog { public static func dispatchTester<G : IteratorProtocol>( _ g: G ) -> LoggingIterator<LoggingIterator<G>> { return LoggingIterator(LoggingIterator(g)) } public static var next = TypeIndexed(0) } public struct LoggingIterator<Base: IteratorProtocol> : IteratorProtocol, LoggingType { public typealias Log = IteratorLog public init(_ base: Base) { self.base = base } public mutating func next() -> Base.Element? { Log.next[selfType] += 1 return base.next() } public var base: Base } public class SequenceLog { public static func dispatchTester<S: MySequence>( _ s: S ) -> LoggingSequence<LoggingSequence<S>> { return LoggingSequence(LoggingSequence(s)) } public static var iterator = TypeIndexed(0) public static var underestimatedCount = TypeIndexed(0) public static var map = TypeIndexed(0) public static var filter = TypeIndexed(0) public static var _customContainsEquatableElement = TypeIndexed(0) public static var _preprocessingPass = TypeIndexed(0) public static var _copyToContiguousArray = TypeIndexed(0) public static var _copyContents = TypeIndexed(0) } public protocol LoggingSequenceType : MySequence, LoggingType { associatedtype Base : MySequence associatedtype Log : AnyObject = SequenceLog associatedtype Iterator : IteratorProtocol = LoggingIterator<Base.Iterator> } extension LoggingSequenceType { public var underestimatedCount: Int { SequenceLog.underestimatedCount[selfType] += 1 return base.underestimatedCount } } extension LoggingSequenceType where Log == SequenceLog, Iterator == LoggingIterator<Base.Iterator> { public func makeIterator() -> LoggingIterator<Base.Iterator> { Log.iterator[selfType] += 1 return LoggingIterator(base.makeIterator()) } public func map<T>( _ transform: (Base.Iterator.Element) -> T ) -> [T] { Log.map[selfType] += 1 return base.map(transform) } public func filter( _ isIncluded: (Base.Iterator.Element) -> Bool ) -> [Base.Iterator.Element] { Log.filter[selfType] += 1 return base.filter(isIncluded) } public func _customContainsEquatableElement( _ element: Base.Iterator.Element ) -> Bool? { Log._customContainsEquatableElement[selfType] += 1 return base._customContainsEquatableElement(element) } /// If `self` is multi-pass (i.e., a `Collection`), invoke /// `preprocess` on `self` and return its result. Otherwise, return /// `nil`. public func _preprocessingPass<R>( _ preprocess: (Self) -> R ) -> R? { Log._preprocessingPass[selfType] += 1 return base._preprocessingPass { _ in preprocess(self) } } /// Create a native array buffer containing the elements of `self`, /// in the same order. public func _copyToContiguousArray() -> ContiguousArray<Base.Iterator.Element> { Log._copyToContiguousArray[selfType] += 1 return base._copyToContiguousArray() } /// Copy a Sequence into an array. public func _copyContents( initializing ptr: UnsafeMutablePointer<Base.Iterator.Element> ) -> UnsafeMutablePointer<Base.Iterator.Element> { Log._copyContents[selfType] += 1 return base._copyContents(initializing: ptr) } } public struct LoggingSequence< Base_: MySequence > : LoggingSequenceType, MySequence { public typealias Log = SequenceLog public typealias Base = Base_ public init(_ base: Base_) { self.base = base } public var base: Base_ } public class CollectionLog : SequenceLog { public class func dispatchTester<C: MyCollection>( _ c: C ) -> LoggingCollection<LoggingCollection<C>> { return LoggingCollection(LoggingCollection(c)) } static var startIndex = TypeIndexed(0) static var endIndex = TypeIndexed(0) static var subscriptIndex = TypeIndexed(0) static var subscriptRange = TypeIndexed(0) static var isEmpty = TypeIndexed(0) static var count = TypeIndexed(0) static var _customIndexOfEquatableElement = TypeIndexed(0) static var first = TypeIndexed(0) } public protocol LoggingCollectionType : LoggingSequenceType, MyCollection { associatedtype Base : MyCollection associatedtype Index : ForwardIndex = Base.Index } extension LoggingCollectionType where Index == Base.Index { public var startIndex: Base.Index { CollectionLog.startIndex[selfType] += 1 return base.startIndex } public var endIndex: Base.Index { CollectionLog.endIndex[selfType] += 1 return base.endIndex } public subscript(position: Base.Index) -> Base.Iterator.Element { CollectionLog.subscriptIndex[selfType] += 1 return base[position] } public subscript(_prext_bounds: MyRange<Base.Index>) -> Base.SubSequence { CollectionLog.subscriptRange[selfType] += 1 return base[_prext_bounds] } public var isEmpty: Bool { CollectionLog.isEmpty[selfType] += 1 return base.isEmpty } public var count: Base.Index.Distance { CollectionLog.count[selfType] += 1 return base.count } public func _customIndexOfEquatableElement(_ element: Base.Iterator.Element) -> Base.Index?? { CollectionLog._customIndexOfEquatableElement[selfType] += 1 return base._customIndexOfEquatableElement(element) } public var first: Base.Iterator.Element? { CollectionLog.first[selfType] += 1 return base.first } } public struct LoggingCollection<Base_ : MyCollection> : LoggingCollectionType { public typealias Iterator = LoggingIterator<Base.Iterator> public typealias Log = CollectionLog public typealias Base = Base_ public typealias SubSequence = Base.SubSequence public func makeIterator() -> Iterator { return Iterator(base.makeIterator()) } public init(_ base: Base_) { self.base = base } public var base: Base_ } public func expectCustomizable< T : Wrapper >(_: T, _ counters: TypeIndexed<Int>, stackTrace: SourceLocStack? = nil, file: String = #file, line: UInt = #line, collectMoreInfo: (()->String)? = nil ) where T : LoggingType, T.Base : Wrapper, T.Base : LoggingType, T.Log == T.Base.Log { expectNotEqual( 0, counters[T.self], collectMoreInfo?() ?? "", stackTrace: stackTrace ?? SourceLocStack(), file: file, line: line) expectEqual( counters[T.self], counters[T.Base.self], collectMoreInfo?() ?? "", stackTrace: stackTrace ?? SourceLocStack(), file: file, line: line) } public func expectNotCustomizable< T : Wrapper >(_: T, _ counters: TypeIndexed<Int>, stackTrace: SourceLocStack? = nil, file: String = #file, line: UInt = #line, collectMoreInfo: (()->String)? = nil ) where T : LoggingType, T.Base : Wrapper, T.Base : LoggingType, T.Log == T.Base.Log { expectNotEqual( 0, counters[T.self], collectMoreInfo?() ?? "", stackTrace: stackTrace ?? SourceLocStack(), file: file, line: line) expectEqual( 0, counters[T.Base.self], collectMoreInfo?() ?? "", stackTrace: stackTrace ?? SourceLocStack(), file: file, line: line) }
0037bc921ef60a95b8941da563439620
25.328671
96
0.686764
false
false
false
false
rechsteiner/Parchment
refs/heads/main
Parchment/Enums/InvalidationState.swift
mit
1
import UIKit /// Used to represent what to invalidate in a collection view /// layout. We need to be able to invalidate the layout multiple times /// with different invalidation contexts before `invalidateLayout` is /// called and we can use we can use this to determine exactly how /// much we need to invalidate by adding together the states each /// time a new context is invalidated. public enum InvalidationState { case nothing case everything case sizes public init(_ invalidationContext: UICollectionViewLayoutInvalidationContext) { if invalidationContext.invalidateEverything { self = .everything } else if invalidationContext.invalidateDataSourceCounts { self = .everything } else if let context = invalidationContext as? PagingInvalidationContext { if context.invalidateSizes { self = .sizes } else { self = .nothing } } else { self = .nothing } } public static func + (lhs: InvalidationState, rhs: InvalidationState) -> InvalidationState { switch (lhs, rhs) { case (.everything, _), (_, .everything): return .everything case (.sizes, _), (_, .sizes): return .sizes case (.nothing, _), (_, .nothing): return .nothing default: return .everything } } }
bd942adff9a5a11ab4e08c9b75deb7b8
33.095238
96
0.613827
false
false
false
false
brentsimmons/Evergreen
refs/heads/ios-candidate
Account/Sources/Account/Feedly/Operations/FeedlyOrganiseParsedItemsByFeedOperation.swift
mit
1
// // FeedlyOrganiseParsedItemsByFeedOperation.swift // Account // // Created by Kiel Gillard on 20/9/19. // Copyright © 2019 Ranchero Software, LLC. All rights reserved. // import Foundation import RSParser import os.log protocol FeedlyParsedItemsByFeedProviding { var parsedItemsByFeedProviderName: String { get } var parsedItemsKeyedByFeedId: [String: Set<ParsedItem>] { get } } /// Group articles by their feeds. final class FeedlyOrganiseParsedItemsByFeedOperation: FeedlyOperation, FeedlyParsedItemsByFeedProviding { private let account: Account private let parsedItemProvider: FeedlyParsedItemProviding private let log: OSLog var parsedItemsByFeedProviderName: String { return name ?? String(describing: Self.self) } var parsedItemsKeyedByFeedId: [String : Set<ParsedItem>] { precondition(Thread.isMainThread) // Needs to be on main thread because Feed is a main-thread-only model type. return itemsKeyedByFeedId } private var itemsKeyedByFeedId = [String: Set<ParsedItem>]() init(account: Account, parsedItemProvider: FeedlyParsedItemProviding, log: OSLog) { self.account = account self.parsedItemProvider = parsedItemProvider self.log = log } override func run() { defer { didFinish() } let items = parsedItemProvider.parsedEntries var dict = [String: Set<ParsedItem>](minimumCapacity: items.count) for item in items { let key = item.feedURL let value: Set<ParsedItem> = { if var items = dict[key] { items.insert(item) return items } else { return [item] } }() dict[key] = value } os_log(.debug, log: log, "Grouped %i items by %i feeds for %@", items.count, dict.count, parsedItemProvider.parsedItemProviderName) itemsKeyedByFeedId = dict } }
73a047f09f2c1b26f313d20c88c2ca96
25.328358
133
0.731859
false
false
false
false
chrishulbert/gondola-appletv
refs/heads/master
Gondola TVOS/ViewControllers/MovieViewController.swift
mit
1
// // MovieViewController.swift // Gondola TVOS // // Created by Chris on 15/02/2017. // Copyright © 2017 Chris Hulbert. All rights reserved. // // This shows the details of a movie and lets you play it. import UIKit import AVKit class MovieViewController: UIViewController { let movie: MovieMetadata let image: UIImage? init(movie: MovieMetadata, image: UIImage?) { self.movie = movie self.image = image super.init(nibName: nil, bundle: nil) } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } lazy var rootView = MovieView() override func loadView() { view = rootView } override func viewDidLoad() { super.viewDidLoad() rootView.title.text = movie.name rootView.overview.text = movie.overview rootView.image.image = image rootView.details.text = "Release date: \(movie.releaseDate)\nVote: \(movie.vote)" rootView.background.alpha = 0 ServiceHelpers.imageRequest(path: movie.backdrop) { result in DispatchQueue.main.async { switch result { case .success(let image): self.rootView.background.image = image UIView.animate(withDuration: 0.3) { self.rootView.background.alpha = 1 } case .failure(let error): NSLog("error: \(error)") } } } rootView.play.addTarget(self, action: #selector(tapPlay), for: .primaryActionTriggered) } @objc func tapPlay() { pushPlayer(media: movie.media) } } class MovieView: UIView { let background = UIImageView() let dim = UIView() let title = UILabel() let overview = UILabel() let image = UIImageView() let details = UILabel() let play = UIButton(type: .system) init() { super.init(frame: CGRect.zero) backgroundColor = UIColor.black background.contentMode = .scaleAspectFill addSubview(background) dim.backgroundColor = UIColor(white: 0, alpha: 0.7) addSubview(dim) title.textColor = UIColor.white title.font = UIFont.systemFont(ofSize: 60, weight: .thin) addSubview(title) overview.textColor = UIColor.white overview.font = UIFont.systemFont(ofSize: 30, weight: .light) overview.numberOfLines = 0 addSubview(overview) image.contentMode = .scaleAspectFit addSubview(image) details.textColor = UIColor(white: 1, alpha: 0.7) details.numberOfLines = 0 details.font = UIFont.systemFont(ofSize: 25, weight: .light) addSubview(details) play.setTitle("Play", for: .normal) addSubview(play) } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func layoutSubviews() { super.layoutSubviews() let w = bounds.width let h = bounds.height background.frame = bounds dim.frame = bounds // Top row. title.frame = CGRect(x: LayoutHelpers.sideMargins, y: LayoutHelpers.vertMargins, width: w - 2*LayoutHelpers.sideMargins, height: ceil(title.font.lineHeight)) // Image under it. let imageWidth = round(w * 0.25) let aspect: CGFloat if let image = image.image, image.size.width > 0 { aspect = image.size.height / image.size.width } else { aspect = 0 } let imageHeight = round(imageWidth * aspect) image.frame = CGRect(x: LayoutHelpers.sideMargins, y: title.frame.maxY + 40, width: imageWidth, height: imageHeight) // Details under image. let detailsTop = image.frame.maxY + 40 let detailsBottom = h - LayoutHelpers.vertMargins let detailsWidth = imageWidth let maxDetailsHeight = detailsBottom - detailsTop let textDetailsHeight = ceil(details.sizeThatFits(CGSize(width: detailsWidth, height: 999)).height) let detailsHeight = min(textDetailsHeight, maxDetailsHeight) details.frame = CGRect(x: image.frame.minX, y: detailsTop, width: detailsWidth, height: detailsHeight) let overviewLeft = image.frame.maxX + LayoutHelpers.sideMargins let overviewRight = w - LayoutHelpers.sideMargins let overviewTop = image.frame.minY let overviewBottom = h - LayoutHelpers.vertMargins let overviewWidth = overviewRight - overviewLeft let maxOverviewHeight = overviewBottom - overviewTop let textOverviewHeight = ceil(overview.sizeThatFits(CGSize(width: overviewWidth, height: 999)).height) let overviewHeight = min(textOverviewHeight, maxOverviewHeight) overview.frame = CGRect(x: overviewLeft, y: overviewTop, width: overviewWidth, height: overviewHeight) // Center bottom. let playSize = play.intrinsicContentSize play.frame = CGRect(origin: CGPoint(x: round(w/2 - playSize.width/2), y: round(h - LayoutHelpers.vertMargins - playSize.height - 8)), // -8 to compensate for focus growth size: playSize) } }
a0c5be44a5d4d834a440b18e5d355b9f
32.886905
144
0.581064
false
false
false
false
codingTheHole/BuildingAppleWatchProjectsBook
refs/heads/master
Xcode Projects by Chapter/5086_Code_Ch05_OnQ/On Q completed/On Q WatchKit Extension/WatchConnectivity.swift
cc0-1.0
1
// // WatchConnectivity.swift // On Q // // Created by Stuart Grimshaw on 17/10/15. // Copyright © 2015 Stuart Grimshaw. All rights reserved. // import WatchConnectivity class WatchConnectivityManager: NSObject, WCSessionDelegate { static let sharedManager = WatchConnectivityManager() let dataManager = WatchDataManager.sharedManager private override init() { super.init() if WCSession.isSupported() { let session = WCSession.defaultSession() session.delegate = self session.activateSession() } } func session(session: WCSession, didReceiveApplicationContext applicationContext: [String : AnyObject]) { if let prompts = applicationContext[kPromptsKey] as! [Prompt]? { WatchDataManager.sharedManager.updatePrompts(prompts) } } }
d023b262f04e6f9a3c1538524bf211d2
24.121212
109
0.694813
false
false
false
false
geraldWilliam/Tenkay
refs/heads/master
Pod/Classes/JSON.swift
mit
1
// // JSON.swift // Tenkay // // Created by Gerald Burke on 2/20/16. // Copyright © 2016 Gerald Burke. All rights reserved. // import Foundation let jsonErrorDomain = "json_error_domain" public typealias JSON = [String : AnyObject] /** Get the raw data from the JSON object */ public extension Dictionary where Key: StringLiteralConvertible, Value: AnyObject { public func data() -> Result<NSData> { do { guard let dict = (self as? AnyObject) as? JSON else { let error = NSError(domain: jsonErrorDomain, code: 999, userInfo: [ NSLocalizedDescriptionKey : "data() must be called on a value of type JSON (aka [String : AnyObject])" ] ) return .Error(error) } let jsonData = try NSJSONSerialization.dataWithJSONObject(dict, options: .PrettyPrinted) return .Value(jsonData) } catch { return .Error(error) } } }
11cfb764d16acc5787bc1a814b62bccb
25.057143
112
0.648738
false
false
false
false
glimpseio/BricBrac
refs/heads/main
Sources/BricBrac/BricBrac.swift
mit
1
// // BricBrac.swift // BricBrac // // Created by Marc Prud'hommeaux on 7/18/15. // Copyright © 2010-2021 io.glimpse. All rights reserved. // /// A BricBrac is a user-defined type that can serialize/deserialize to/from some Bric /// In addition to conforming to Bricable and Bracable, it also provides Equatable implementations /// and the ability to perform a deep copy with `bricbrac()`; note that standard primitives like String and Bool /// conform to both Bricable and Bracable but not to BricBrac because we don't want to conflict with their own /// Equatable and Hashable implementations public protocol BricBrac: Bricable, Bracable { // /// Perform semantic validation of the BricBrac; this could verify requirements that // /// cannot be addressed by the type system, such as string and array length requirements // func validate() throws } public extension BricBrac { /// Returns a deep copy of this instance func bricbrac() throws -> Self { return try Self.brac(bric: self.bric()) } // /// The default validation method does nothing // func validate() { } } /// A BricBrac that only bracs elements that do not conform to the underlying type /// Useful for handling "not" elements of the JSON Schema spec public struct NotBrac<T> : ExpressibleByNilLiteral { public init() { } public init(nilLiteral: ()) { } } extension NotBrac : Encodable where T : Encodable { /// Encoding a NotBrac is a no-op public func encode(to encoder: Encoder) throws { } } extension NotBrac : Decodable where T : Decodable { public init(from decoder: Decoder) throws { do { _ = try T.init(from: decoder) } catch { self = NotBrac() } throw BracError.shouldNotBracError(type: T.self, path: []) } } extension NotBrac : Bricable where T : Bricable { /// this type does not bric to anything public func bric() -> Bric { return .nul } } extension NotBrac : Bracable where T : Bracable { public static func brac(bric: Bric) throws -> NotBrac { do { _ = try T.brac(bric: bric) } catch { return NotBrac() } throw BracError.shouldNotBracError(type: T.self, path: []) } } extension NotBrac : Equatable where T : Equatable { public static func ==<T>(lhs: NotBrac<T>, rhs: NotBrac<T>) -> Bool { return true // two Nots are always equal because their existance just signifies the absence of the underlying type to deserialize } }
6c22fd972ad9ab66960952320dfd2fac
33.819444
137
0.672916
false
false
false
false
huonw/swift
refs/heads/master
benchmark/single-source/SequenceAlgos.swift
apache-2.0
3
//===--- ArrayAppend.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 // This benchmark tests closureless versions of min and max, both contains, // repeatElement and reduce, on a number of different sequence types. // To avoid too many little micro benchmarks, it measures them all together // for each sequence type. public let SequenceAlgos = [ BenchmarkInfo(name: "SequenceAlgosList", runFunction: run_SequenceAlgosList, tags: [.validation, .api], setUpFunction: { buildWorkload() }, tearDownFunction: nil), BenchmarkInfo(name: "SequenceAlgosArray", runFunction: run_SequenceAlgosArray, tags: [.validation, .api], setUpFunction: { buildWorkload() }, tearDownFunction: nil), BenchmarkInfo(name: "SequenceAlgosContiguousArray", runFunction: run_SequenceAlgosContiguousArray, tags: [.validation, .api], setUpFunction: { buildWorkload() }, tearDownFunction: nil), BenchmarkInfo(name: "SequenceAlgosRange", runFunction: run_SequenceAlgosRange, tags: [.validation, .api], setUpFunction: { buildWorkload() }, tearDownFunction: nil), BenchmarkInfo(name: "SequenceAlgosUnfoldSequence", runFunction: run_SequenceAlgosUnfoldSequence, tags: [.validation, .api], setUpFunction: { buildWorkload() }, tearDownFunction: nil), BenchmarkInfo(name: "SequenceAlgosAnySequence", runFunction: run_SequenceAlgosAnySequence, tags: [.validation, .api], setUpFunction: { buildWorkload() }, tearDownFunction: nil), ] extension List: Sequence { struct Iterator: IteratorProtocol { var _list: List<Element> mutating func next() -> Element? { guard case let .node(x,xs) = _list else { return nil } _list = xs return x } } func makeIterator() -> Iterator { return Iterator(_list: self) } } extension List: Equatable where Element: Equatable { static func == (lhs: List<Element>, rhs: List<Element>) -> Bool { return lhs.elementsEqual(rhs) } } func benchmarkSequenceAlgos<S: Sequence>(s: S, n: Int) where S.Element == Int { CheckResults(s.reduce(0, &+) == (n*(n-1))/2) let mn = s.min() let mx = s.max() CheckResults(mn == 0 && mx == n-1) CheckResults(s.starts(with: s)) } let n = 10_000 let r = 0..<(n*100) let l = List(0..<n) let c = ContiguousArray(0..<(n*100)) let a = Array(0..<(n*100)) let y = AnySequence(0..<n) let s = sequence(first: 0, next: { $0 < n&-1 ? $0&+1 : nil}) func buildWorkload() { _ = l.makeIterator() _ = c.makeIterator() _ = a.makeIterator() _ = y.makeIterator() _ = s.makeIterator() } func benchmarkEquatableSequenceAlgos<S: Sequence>(s: S, n: Int) where S.Element == Int, S: Equatable { CheckResults(repeatElement(s, count: 1).contains(s)) CheckResults(!repeatElement(s, count: 1).contains { $0 != s }) } @inline(never) public func run_SequenceAlgosRange(_ N: Int) { for _ in 0..<N { benchmarkSequenceAlgos(s: r, n: r.count) benchmarkEquatableSequenceAlgos(s: r, n: r.count) } } @inline(never) public func run_SequenceAlgosArray(_ N: Int) { for _ in 0..<N { benchmarkSequenceAlgos(s: a, n: a.count) benchmarkEquatableSequenceAlgos(s: a, n: a.count) } } @inline(never) public func run_SequenceAlgosContiguousArray(_ N: Int) { for _ in 0..<N { benchmarkSequenceAlgos(s: c, n: c.count) benchmarkEquatableSequenceAlgos(s: c, n: c.count) } } @inline(never) public func run_SequenceAlgosAnySequence(_ N: Int) { for _ in 0..<N { benchmarkSequenceAlgos(s: y, n: n) } } @inline(never) public func run_SequenceAlgosUnfoldSequence(_ N: Int) { for _ in 0..<N { benchmarkSequenceAlgos(s: s, n: n) } } @inline(never) public func run_SequenceAlgosList(_ N: Int) { for _ in 0..<N { benchmarkSequenceAlgos(s: l, n: n) benchmarkEquatableSequenceAlgos(s: l, n: n) } } enum List<Element> { case end indirect case node(Element, List<Element>) init<S: BidirectionalCollection>(_ elements: S) where S.Element == Element { self = elements.reversed().reduce(.end) { .node($1,$0) } } }
7c828f4ecf44a9535f0944d5293b02a7
32.135338
187
0.668255
false
false
false
false
abelsanchezali/ViewBuilder
refs/heads/master
Source/Document/Addin/Properties/Numeric.swift
mit
1
// // Numeric.swift // ViewBuilder // // Created by Abel Sanchez on 10/21/16. // Copyright © 2016 Abel Sanchez. All rights reserved. // import Foundation import CoreGraphics // MARK: IntMaxConvertible Protocol protocol IntMaxConvertible { func toIntMax() -> Int64 } // MARK: IntMaxConvertible for Integer Types extension Int: IntMaxConvertible { func toIntMax() -> Int64 { return Int64(self) } } extension UInt: IntMaxConvertible { func toIntMax() -> Int64 { return Int64(self) } } extension Int8: IntMaxConvertible { func toIntMax() -> Int64 { return Int64(self) } } extension Int16: IntMaxConvertible { func toIntMax() -> Int64 { return Int64(self) } } extension Int32: IntMaxConvertible { func toIntMax() -> Int64 { return Int64(self) } } extension Int64: IntMaxConvertible { func toIntMax() -> Int64 { return Int64(self) } } extension UInt8: IntMaxConvertible { func toIntMax() -> Int64 { return Int64(self) } } extension UInt16: IntMaxConvertible { func toIntMax() -> Int64 { return Int64(self) } } extension UInt32: IntMaxConvertible { func toIntMax() -> Int64 { return Int64(self) } } extension UInt64: IntMaxConvertible { func toIntMax() -> Int64 { return Int64(self) } } // MARK: Int extension Int { public init?(value: Any) { switch value { case let v as IntMaxConvertible: self = Int(v.toIntMax()) break case let str as String: guard let v = Int(str) else { return nil } self = v break default: return nil } } } // MARK: DoubleMax Convertible Protocol public typealias DoubleMax = Double protocol DoubleMaxConvertible { func toDoubleMax() -> Double } extension Double: DoubleMaxConvertible { func toDoubleMax() -> Double { return self } } extension Float: DoubleMaxConvertible { func toDoubleMax() -> Double { return Double(self) } } extension CGFloat: DoubleMaxConvertible { func toDoubleMax() -> Double { return Double(self) } } // MARK: Double extension Double { public init?(value: Any) { switch value { case let v as Double: self = v break case let v as IntMaxConvertible: self = Double(v.toIntMax()) break case let v as DoubleMaxConvertible: self = v.toDoubleMax() break case let str as String: guard let v = Double(str) else { return nil } self = v break default: return nil } } }
1af2044d605232b1640da72c89347bee
17.286667
55
0.586219
false
false
false
false
rjeprasad/RappleColorPicker
refs/heads/master
Example/RappleColorPicker/ViewController.swift
mit
1
// // ViewController.swift // RappleColorPicker // // Created by Rajeev Prasad on 11/28/2015. // Copyright (c) 2018 Rajeev Prasad. All rights reserved. // import UIKit import RappleColorPicker class ViewController: UIViewController, RappleColorPickerDelegate { @IBOutlet var box1: UIButton! @IBOutlet var box2: UIButton! @IBOutlet var box3: UIButton! override func viewDidLoad() { super.viewDidLoad() } @IBAction func openColorPallet(_ sender:UIButton?) { /* picker without title */ let attributes : [RappleCPAttributeKey : AnyObject] = [ .BGColor : UIColor.yellow.withAlphaComponent(0.6), .TintColor : UIColor.red.withAlphaComponent(0.6), .Style : RappleCPStyleCircle as AnyObject, .BorderColor : UIColor.red.withAlphaComponent(0.6), .ScreenBGColor : UIColor.orange.withAlphaComponent(0.4) ] RappleColorPicker.openColorPallet(onViewController: self, origin: CGPoint(x: sender!.frame.midX - 115, y: sender!.frame.minY - 50), attributes: attributes) { (color, tag) in self.view.backgroundColor = color RappleColorPicker.close() } } @IBAction func openColorPalletForBox(_ sender:UIButton?){ let tag = sender?.tag ?? 0 RappleColorPicker.openColorPallet(title: "Color Picker", tag: tag) { (color, tag) in switch tag { case 1: self.box1.backgroundColor = color case 2: self.box2.backgroundColor = color case 3: self.box3.backgroundColor = color default: () } RappleColorPicker.close() } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } }
daabd72762763515d15150cbac85f031
30.322034
181
0.607684
false
false
false
false
JGiola/swift
refs/heads/main
test/Generics/protocol_typealias_serialization.swift
apache-2.0
6
// RUN: %empty-directory(%t) // RUN: %target-swift-frontend -emit-module %S/Inputs/protocol_typealias_other.swift -emit-module-path %t/protocol_typealias_other.swiftmodule -module-name protocol_typealias_other // RUN: %target-swift-frontend -typecheck %s -I %t -debug-generic-signatures 2>&1 | %FileCheck %s import protocol_typealias_other // CHECK-LABEL: .useP1@ // CHECK-NEXT: <T where T : P1, T.[P1]Y.[P2]Z == Int> func useP1<T : P1>(_: T) where T.X == Int {} // CHECK-LABEL: .useP2@ // CHECK-NEXT: <T where T : P2, T.[P2]Z == Int> func useP2<T : P2>(_: T) where T.C == Array<Int> {}
2b6a02ae4ea2c26365d3248785a25727
44.384615
180
0.667797
false
false
false
false
1er4y/IYSlideView
refs/heads/0.2.1
Carthage/Checkouts/Nimble/Sources/Nimble/Matchers/EndWith.swift
apache-2.0
131
import Foundation /// A Nimble matcher that succeeds when the actual sequence's last element /// is equal to the expected value. public func endWith<S: Sequence, T: Equatable>(_ endingElement: T) -> NonNilMatcherFunc<S> where S.Iterator.Element == T { return NonNilMatcherFunc { actualExpression, failureMessage in failureMessage.postfixMessage = "end with <\(endingElement)>" if let actualValue = try actualExpression.evaluate() { var actualGenerator = actualValue.makeIterator() var lastItem: T? var item: T? repeat { lastItem = item item = actualGenerator.next() } while(item != nil) return lastItem == endingElement } return false } } /// A Nimble matcher that succeeds when the actual collection's last element /// is equal to the expected object. public func endWith(_ endingElement: Any) -> NonNilMatcherFunc<NMBOrderedCollection> { return NonNilMatcherFunc { actualExpression, failureMessage in failureMessage.postfixMessage = "end with <\(endingElement)>" guard let collection = try actualExpression.evaluate() else { return false } guard collection.count > 0 else { return false } #if os(Linux) guard let collectionValue = collection.object(at: collection.count - 1) as? NSObject else { return false } #else let collectionValue = collection.object(at: collection.count - 1) as AnyObject #endif return collectionValue.isEqual(endingElement) } } /// A Nimble matcher that succeeds when the actual string contains the expected substring /// where the expected substring's location is the actual string's length minus the /// expected substring's length. public func endWith(_ endingSubstring: String) -> NonNilMatcherFunc<String> { return NonNilMatcherFunc { actualExpression, failureMessage in failureMessage.postfixMessage = "end with <\(endingSubstring)>" if let collection = try actualExpression.evaluate() { return collection.hasSuffix(endingSubstring) } return false } } #if _runtime(_ObjC) extension NMBObjCMatcher { public class func endWithMatcher(_ expected: Any) -> NMBObjCMatcher { return NMBObjCMatcher(canMatchNil: false) { actualExpression, failureMessage in let actual = try! actualExpression.evaluate() if let _ = actual as? String { let expr = actualExpression.cast { $0 as? String } return try! endWith(expected as! String).matches(expr, failureMessage: failureMessage) } else { let expr = actualExpression.cast { $0 as? NMBOrderedCollection } return try! endWith(expected).matches(expr, failureMessage: failureMessage) } } } } #endif
f5cdc6f77787c2e4276e843c64240476
38.12
103
0.65167
false
false
false
false
busybusy/AnalyticsKit
refs/heads/master
AnalyticsKitDebugProvider.swift
mit
1
import Foundation import UIKit public class AnalyticsKitDebugProvider: NSObject, AnalyticsKitProvider { public func applicationWillEnterForeground() {} public func applicationDidEnterBackground() {} public func applicationWillTerminate() {} public func uncaughtException(_ exception: NSException) {} public func logScreen(_ screenName: String) {} public func logScreen(_ screenName: String, withProperties properties: [String: Any]) {} public func endTimedEvent(_ event: String, withProperties properties: [String: Any]) {} fileprivate weak var alertController: UIAlertController? // Logging public func logEvent(_ event: String) { } public func logEvent(_ event: String, withProperty key: String, andValue value: String) { } public func logEvent(_ event: String, withProperties properties: [String: Any]) { } public func logEvent(_ event: String, timed: Bool) { logEvent(event) } public func logEvent(_ event: String, withProperties properties: [String: Any], timed: Bool) { logEvent(event, withProperties: properties) } public func logError(_ name: String, message: String?, exception: NSException?) { let message = "\(name)\n\n\(message ?? "nil")\n\n\(exception?.description ?? "nil")" showAlert(message) } public func logError(_ name: String, message: String?, error: Error?) { let message = "\(name)\n\n\(message ?? "nil")\n\n\(error?.localizedDescription ?? "nil")" showAlert(message) } fileprivate func showAlert(_ message: String) { if Thread.isMainThread { showAlertController(message) } else { DispatchQueue.main.async { self.showAlertController(message) } } } fileprivate func showAlertController(_ message: String) { // dismiss any already visible alert if let alertController = self.alertController { alertController.dismiss(animated: false, completion: nil) } let alertController = UIAlertController(title: "AnalyticsKit Received Error", message: message, preferredStyle: .alert) alertController.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil)) self.present(alertController) self.alertController = alertController } fileprivate func present(_ alertController: UIAlertController) { if let rootVC = UIApplication.shared.keyWindow?.rootViewController { presentFromController(alertController, controller: rootVC) } } fileprivate func presentFromController(_ alertController: UIAlertController, controller: UIViewController) { if let navVC = controller as? UINavigationController, let visibleVC = navVC.visibleViewController { presentFromController(alertController, controller: visibleVC) } else if let tabVC = controller as? UITabBarController, let selectedVC = tabVC.selectedViewController { presentFromController(alertController, controller: selectedVC) } else { controller.present(alertController, animated: true, completion: nil) } } }
5da95698f36430f6c61c9666a8a0616e
41.733333
127
0.682371
false
false
false
false
wilfreddekok/Antidote
refs/heads/master
Antidote/AddFriendController.swift
mpl-2.0
1
// This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. import UIKit import SnapKit private struct Constants { static let TextViewTopOffset = 5.0 static let TextViewXOffset = 5.0 static let QrCodeBottomSpacerDeltaHeight = 70.0 static let SendAlertTextViewBottomOffset = -10.0 static let SendAlertTextViewXOffset = 5.0 static let SendAlertTextViewHeight = 70.0 } protocol AddFriendControllerDelegate: class { func addFriendControllerScanQRCode( controller: AddFriendController, validateCodeHandler: String -> Bool, didScanHander: String -> Void) func addFriendControllerDidFinish(controller: AddFriendController) } class AddFriendController: UIViewController { weak var delegate: AddFriendControllerDelegate? private let theme: Theme private weak var submanagerFriends: OCTSubmanagerFriends! private var textView: UITextView! private var orTopSpacer: UIView! private var qrCodeBottomSpacer: UIView! private var orLabel: UILabel! private var qrCodeButton: UIButton! private var cachedMessage: String? init(theme: Theme, submanagerFriends: OCTSubmanagerFriends) { self.theme = theme self.submanagerFriends = submanagerFriends super.init(nibName: nil, bundle: nil) addNavigationButtons() edgesForExtendedLayout = .None title = String(localized: "add_contact_title") } required convenience init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func loadView() { loadViewWithBackgroundColor(theme.colorForType(.NormalBackground)) createViews() installConstraints() updateSendButton() } } extension AddFriendController { func qrCodeButtonPressed() { func prepareString(string: String) -> String { var string = string string = string.uppercaseString.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()) if string.hasPrefix("TOX:") { return string.substringFromIndex(string.startIndex.advancedBy(4)) } return string } delegate?.addFriendControllerScanQRCode(self, validateCodeHandler: { return isAddressString(prepareString($0)) }, didScanHander: { [unowned self] in self.textView.text = prepareString($0) self.updateSendButton() }) } func sendButtonPressed() { textView.resignFirstResponder() let messageView = UITextView() messageView.text = cachedMessage messageView.placeholder = String(localized: "add_contact_default_message_text") messageView.font = UIFont.systemFontOfSize(17.0) messageView.layer.cornerRadius = 5.0 messageView.layer.masksToBounds = true let alert = SDCAlertController( title: String(localized: "add_contact_default_message_title"), message: nil, preferredStyle: .Alert) alert.contentView.addSubview(messageView) messageView.snp_makeConstraints { $0.top.equalTo(alert.contentView) $0.bottom.equalTo(alert.contentView).offset(Constants.SendAlertTextViewBottomOffset); $0.leading.equalTo(alert.contentView).offset(Constants.SendAlertTextViewXOffset); $0.trailing.equalTo(alert.contentView).offset(-Constants.SendAlertTextViewXOffset); $0.height.equalTo(Constants.SendAlertTextViewHeight); } alert.addAction(SDCAlertAction(title: String(localized: "alert_cancel"), style: .Default, handler: nil)) alert.addAction(SDCAlertAction(title: String(localized: "add_contact_send"), style: .Recommended) { [unowned self] action in self.cachedMessage = messageView.text let message = messageView.text.isEmpty ? messageView.placeholder : messageView.text do { try self.submanagerFriends.sendFriendRequestToAddress(self.textView.text, message: message) } catch let error as NSError { handleErrorWithType(.ToxAddFriend, error: error) return } self.delegate?.addFriendControllerDidFinish(self) }) alert.presentWithCompletion(nil) } } extension AddFriendController: UITextViewDelegate { func textView(textView: UITextView, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool { if text == "\n" { textView.resignFirstResponder() return false } let resultText = (textView.text! as NSString).stringByReplacingCharactersInRange(range, withString: text) let maxLength = Int(kOCTToxAddressLength) if resultText.lengthOfBytesUsingEncoding(NSUTF8StringEncoding) > maxLength { textView.text = resultText.substringToByteLength(maxLength, encoding: NSUTF8StringEncoding) return false } return true } func textViewDidChange(textView: UITextView) { updateSendButton() } } private extension AddFriendController { func addNavigationButtons() { navigationItem.rightBarButtonItem = UIBarButtonItem( title: String(localized: "add_contact_send"), style: .Done, target: self, action: #selector(AddFriendController.sendButtonPressed)) } func createViews() { textView = UITextView() textView.placeholder = String(localized: "add_contact_tox_id_placeholder") textView.delegate = self textView.scrollEnabled = false textView.font = UIFont.systemFontOfSize(17) textView.textColor = theme.colorForType(.NormalText) textView.backgroundColor = .clearColor() textView.returnKeyType = .Done textView.layer.cornerRadius = 5.0 textView.layer.borderWidth = 0.5 textView.layer.borderColor = theme.colorForType(.SeparatorsAndBorders).CGColor textView.layer.masksToBounds = true view.addSubview(textView) orTopSpacer = createSpacer() qrCodeBottomSpacer = createSpacer() orLabel = UILabel() orLabel.text = String(localized: "add_contact_or_label") orLabel.textColor = theme.colorForType(.NormalText) orLabel.backgroundColor = .clearColor() view.addSubview(orLabel) qrCodeButton = UIButton(type: .System) qrCodeButton.setTitle(String(localized: "add_contact_use_qr"), forState: .Normal) qrCodeButton.titleLabel!.font = UIFont.antidoteFontWithSize(16.0, weight: .Bold) qrCodeButton.addTarget(self, action: #selector(AddFriendController.qrCodeButtonPressed), forControlEvents: .TouchUpInside) view.addSubview(qrCodeButton) } func createSpacer() -> UIView { let spacer = UIView() spacer.backgroundColor = .clearColor() view.addSubview(spacer) return spacer } func installConstraints() { textView.snp_makeConstraints { $0.top.equalTo(view).offset(Constants.TextViewTopOffset) $0.leading.equalTo(view).offset(Constants.TextViewXOffset) $0.trailing.equalTo(view).offset(-Constants.TextViewXOffset) $0.bottom.equalTo(view.snp_centerY) } orTopSpacer.snp_makeConstraints { $0.top.equalTo(textView.snp_bottom) } orLabel.snp_makeConstraints { $0.top.equalTo(orTopSpacer.snp_bottom) $0.centerX.equalTo(view) } qrCodeButton.snp_makeConstraints { $0.top.equalTo(orLabel.snp_bottom) $0.centerX.equalTo(view) } qrCodeBottomSpacer.snp_makeConstraints { $0.top.equalTo(qrCodeButton.snp_bottom) $0.bottom.equalTo(view) $0.height.equalTo(orTopSpacer) } } func updateSendButton() { navigationItem.rightBarButtonItem!.enabled = isAddressString(textView.text) } }
c726c75f861d3b45056cc2156215bca2
33.35
132
0.663149
false
false
false
false
ntwf/TheTaleClient
refs/heads/1.2/stable
TheTale/Stores/Map/Map.swift
mit
1
// // Map.swift // the-tale // // Created by Mikhail Vospennikov on 04/07/2017. // Copyright © 2017 Mikhail Vospennikov. All rights reserved. // import Foundation import UIKit struct Map { var turn: String var formatVersion: String var height: Int var width: Int var mapVersion: String var image: [[UIImage]] var places: [PlaceInfo] } extension Map: JSONDecodable { init?(jsonObject: JSON) { let sizeBlock = CGSize(width: 32, height: 32) guard let turn = jsonObject["turn"] as? Int, let region = jsonObject["region"] as? JSON, let formatVersion = region["format_version"] as? String, let height = region["height"] as? Int, let width = region["width"] as? Int, let mapVersion = region["map_version"] as? String, let mapArrayObject = region["draw_info"] as? NSArray, let placesJSON = region["places"] as? JSON else { return nil } var drawInfo: [[UIImage]] = [] for mapArrayLine in mapArrayObject { guard let mapArrayLine = mapArrayLine as? NSArray else { break } var mapLine: [UIImage] = [] for mapBlock in mapArrayLine { guard let mapBlock = mapBlock as? NSArray else { break } var mapItem: [DrawBlock] = [] for mapItems in mapBlock { guard let mapItems = mapItems as? NSArray, let block = DrawBlock(arrayObject: mapItems) else { break } mapItem.append(block) } let imagesArray = mapItem.map { (String($0.blockID), Double($0.blockAngle) ) } guard let mapImage = UIImage(prefix: "map_default", imagesNamed: imagesArray, size: sizeBlock) else { break } mapLine.append(mapImage) } drawInfo.append(mapLine) } var places: [PlaceInfo] = [] for (_, value) in placesJSON { guard let placeJSON = value as? JSON, let place = PlaceInfo(jsonObject: placeJSON) else { break } places.append(place) } self.turn = String(turn) self.formatVersion = formatVersion self.height = height self.width = width self.mapVersion = mapVersion self.image = drawInfo self.places = places } init?() { self.init(jsonObject: [:]) } }
3efb4bcad7340516198d677a2cb5c033
26.977011
109
0.56779
false
false
false
false
TheTekton/Malibu
refs/heads/master
MalibuTests/Specs/Request/ContentTypeSpec.swift
mit
1
@testable import Malibu import Quick import Nimble class ContentTypeSpec: QuickSpec { override func spec() { describe("ContentType") { var contentType: ContentType! context("when it is Query type") { beforeEach { contentType = .Query } describe("#value") { it("returns nil") { expect(contentType.header).to(beNil()) } } describe("#encoder") { it("returns nil") { expect(contentType.encoder).to(beNil()) } } describe("#hashValue") { it("returns a hash value") { expect(contentType.hashValue).to(equal("query".hashValue)) } } describe("#equal") { it("compares for value equality") { expect(contentType).toNot(equal(ContentType.JSON)) expect(contentType).to(equal(ContentType.Query)) expect(contentType).toNot(equal(ContentType.Custom("application/custom"))) } } } context("when it is FormURLEncoded type") { beforeEach { contentType = .FormURLEncoded } describe("#value") { it("returns a correct string value") { expect(contentType.header).to(equal("application/x-www-form-urlencoded")) } } describe("#encoder") { it("returns a corresponding encoder") { expect(contentType.encoder is FormURLEncoder).to(beTrue()) } } describe("#hashValue") { it("returns a hash value of corresponding string value") { expect(contentType.hashValue).to(equal(contentType.header?.hashValue)) } } describe("#equal") { it("compares for value equality") { expect(contentType).toNot(equal(ContentType.JSON)) expect(contentType).to(equal(ContentType.FormURLEncoded)) expect(contentType).toNot(equal(ContentType.Custom("application/custom"))) } } } context("when it is JSON type") { beforeEach { contentType = .JSON } describe("#value") { it("returns a correct string value") { expect(contentType.header).to(equal("application/json")) } } describe("#encoder") { it("returns a corresponding encoder") { expect(contentType.encoder is JSONEncoder).to(beTrue()) } } describe("#hashValue") { it("returns a hash value of corresponding string value") { expect(contentType.hashValue).to(equal(contentType.header?.hashValue)) } } describe("#equal") { it("compares for value equality") { expect(contentType).to(equal(ContentType.JSON)) expect(contentType).toNot(equal(ContentType.FormURLEncoded)) expect(contentType).toNot(equal(ContentType.Custom("application/custom"))) } } } context("when it is MultipartFormData type") { beforeEach { contentType = .MultipartFormData } describe("#value") { it("returns a correct string value") { expect(contentType.header).to(equal("multipart/form-data; boundary=\(boundary)")) } } describe("#encoder") { it("returns a corresponding encoder") { expect(contentType.encoder is MultipartFormEncoder).to(beTrue()) } } describe("#hashValue") { it("returns a hash value of corresponding string value") { expect(contentType.hashValue).to(equal(contentType.header?.hashValue)) } } describe("#equal") { it("compares for value equality") { expect(contentType).to(equal(ContentType.MultipartFormData)) expect(contentType).toNot(equal(ContentType.JSON)) expect(contentType).toNot(equal(ContentType.FormURLEncoded)) expect(contentType).toNot(equal(ContentType.Custom("application/custom"))) } } } context("when it is Custom type") { beforeEach { contentType = .Custom("application/custom") } describe("#value") { it("returns a correct string value") { expect(contentType.header).to(equal("application/custom")) } } describe("#encoder") { it("returns nil") { expect(contentType.encoder).to(beNil()) } } describe("#hashValue") { it("returns a hash value of corresponding string value") { expect(contentType.hashValue).to(equal(contentType.header?.hashValue)) } } describe("#equal") { it("compares for value equality") { expect(contentType).toNot(equal(ContentType.JSON)) expect(contentType).toNot(equal(ContentType.FormURLEncoded)) expect(contentType).to(equal(ContentType.Custom("application/custom"))) } } } } } }
75f618b9f3fca9f68ea564a1cdb5e70f
28.635838
93
0.55393
false
false
false
false
guillermo-ag-95/App-Development-with-Swift-for-Students
refs/heads/master
3A - Building AR Apps with Xcode/Guided Project - AR Drawing/ARKit-Drawing/ARKit-Drawing/Options/OptionsContainerViewController.swift
mit
1
import UIKit import SceneKit protocol OptionsViewControllerDelegate: class { func objectSelected(node: SCNNode) func undoLastObject() func togglePlaneVisualization() func resetScene() } class OptionsContainerViewController: UIViewController, UINavigationControllerDelegate { private var shape: Shape! private var color: UIColor! private var nav: UINavigationController? weak var delegate: OptionsViewControllerDelegate? override func viewDidLoad() { super.viewDidLoad() let navigationController = UINavigationController(rootViewController: rootOptionPicker()) nav = navigationController transition(to: navigationController) } override func viewWillLayoutSubviews() { preferredContentSize = CGSize(width: 320, height: 600) } private func rootOptionPicker() -> UIViewController { let options = [ Option(option: ShapeOption.addShape), Option(option: ShapeOption.addScene), Option(option: ShapeOption.togglePlane, showsDisclosureIndicator: false), Option(option: ShapeOption.undoLastShape, showsDisclosureIndicator: false), Option(option: ShapeOption.resetScene, showsDisclosureIndicator: false) ] let selector = OptionSelectorViewController(options: options) selector.optionSelectionCallback = { [unowned self] option in switch option { case .addShape: self.nav?.pushViewController(self.shapePicker(), animated: true) case .addScene: self.nav?.pushViewController(self.scenePicker(), animated: true) case .togglePlane: self.delegate?.togglePlaneVisualization() case .undoLastShape: self.delegate?.undoLastObject() case .resetScene: self.delegate?.resetScene() } } return selector } private func scenePicker() -> UIViewController { let resourceFolder = "models.scnassets" let availableScenes: [String] = { let modelsURL = Bundle.main.url(forResource: resourceFolder, withExtension: nil)! let fileEnumerator = FileManager().enumerator(at: modelsURL, includingPropertiesForKeys: [])! return fileEnumerator.compactMap { element in let url = element as! URL guard url.pathExtension == "scn" else { return nil } return url.lastPathComponent } }() let options = availableScenes.map { Option(name: $0, option: $0, showsDisclosureIndicator: false) } let selector = OptionSelectorViewController(options: options) selector.optionSelectionCallback = { [unowned self] name in let nameWithoutExtension = name.replacingOccurrences(of: ".scn", with: "") let scene = SCNScene(named: "\(resourceFolder)/\(nameWithoutExtension)/\(name)")! self.delegate?.objectSelected(node: scene.rootNode) } return selector } private func shapePicker() -> UIViewController { let shapes: [Shape] = [.box, .sphere, .cylinder, .cone, .torus] let options = shapes.map { Option(option: $0) } let selector = OptionSelectorViewController(options: options) selector.optionSelectionCallback = { [unowned self] option in self.shape = option self.nav?.pushViewController(self.colorPicker(), animated: true) } return selector } private func colorPicker() -> UIViewController { let colors: [(String, UIColor)] = [("Red", .red), ("Yellow", .yellow), ("Orange", .orange), ("Green", .green), ("Blue", .blue), ("Brown", .brown), ("White", .white)] let options = colors.map { Option(name: $0.0, option: $0.1, showsDisclosureIndicator: true) } let selector = OptionSelectorViewController(options: options) selector.optionSelectionCallback = { [unowned self] option in self.color = option self.nav?.pushViewController(self.sizePicker(), animated: true) } return selector } private func sizePicker() -> UIViewController { let sizes: [Size] = [.small, .medium, .large] let options = sizes.map { Option(option: $0, showsDisclosureIndicator: false) } let selector = OptionSelectorViewController(options: options) selector.optionSelectionCallback = { [unowned self] option in let node = self.createNode(shape: self.shape, color: self.color, size: option) self.delegate?.objectSelected(node: node) } return selector } private func createNode(shape: Shape, color: UIColor, size: Size) -> SCNNode { let geometry: SCNGeometry let meters: CGFloat switch size { case .small: meters = 0.033 case .medium: meters = 0.1 case .large: meters = 0.3 } switch shape { case .box: geometry = SCNBox(width: meters, height: meters, length: meters, chamferRadius: 0.0) case .cone: geometry = SCNCone(topRadius: 0.0, bottomRadius: meters, height: meters) case .cylinder: geometry = SCNCylinder(radius: meters / 2, height: meters) case .sphere: geometry = SCNSphere(radius: meters) case .torus: geometry = SCNTorus(ringRadius: meters*1.5, pipeRadius: meters * 0.2) } geometry.firstMaterial?.diffuse.contents = color return SCNNode(geometry: geometry) } }
f72a5f214e10c4b5ba4920888546bc3d
37.196078
173
0.606092
false
false
false
false
AlbertXYZ/HDCP
refs/heads/dev
BarsAroundMe/Pods/RxSwift/RxSwift/Observables/Implementations/Using.swift
apache-2.0
47
// // Using.swift // RxSwift // // Created by Yury Korolev on 10/15/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // final class UsingSink<ResourceType: Disposable, O: ObserverType> : Sink<O>, ObserverType { typealias SourceType = O.E typealias Parent = Using<SourceType, ResourceType> private let _parent: Parent init(parent: Parent, observer: O, cancel: Cancelable) { _parent = parent super.init(observer: observer, cancel: cancel) } func run() -> Disposable { var disposable = Disposables.create() do { let resource = try _parent._resourceFactory() disposable = resource let source = try _parent._observableFactory(resource) return Disposables.create( source.subscribe(self), disposable ) } catch let error { return Disposables.create( Observable.error(error).subscribe(self), disposable ) } } func on(_ event: Event<SourceType>) { switch event { case let .next(value): forwardOn(.next(value)) case let .error(error): forwardOn(.error(error)) dispose() case .completed: forwardOn(.completed) dispose() } } } class Using<SourceType, ResourceType: Disposable>: Producer<SourceType> { typealias E = SourceType typealias ResourceFactory = () throws -> ResourceType typealias ObservableFactory = (ResourceType) throws -> Observable<SourceType> fileprivate let _resourceFactory: ResourceFactory fileprivate let _observableFactory: ObservableFactory init(resourceFactory: @escaping ResourceFactory, observableFactory: @escaping ObservableFactory) { _resourceFactory = resourceFactory _observableFactory = observableFactory } override func run<O : ObserverType>(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == E { let sink = UsingSink(parent: self, observer: observer, cancel: cancel) let subscription = sink.run() return (sink: sink, subscription: subscription) } }
4dc88bb38b10e59c980cd5befc8db4bd
29.773333
139
0.606586
false
false
false
false
clwm01/RTKit
refs/heads/master
RTKit/RTText.swift
apache-2.0
1
// // RTText.swift // RTKit // // Created by Rex Tsao on 9/4/2016. // Copyright © 2016 rexcao.net. All rights reserved. // import Foundation public class RTText { /// Make the phone number to be asterisk. This will turn the numbers which start with /// the third to the six to be asterisk. public class func blurPhone(phone: String) -> String { let chars = phone.cStringUsingEncoding(NSUTF8StringEncoding) var res = "" for i in 0 ..< chars!.count { var tmp = String(chars![i]) if i >= 3 && i <= 6 { tmp = "*" } res += tmp } return res } public class func encodeUrl(url: String) -> String { let customAllowedSet = NSCharacterSet(charactersInString: "#%<>@\\^`{|}").invertedSet return url.stringByAddingPercentEncodingWithAllowedCharacters(customAllowedSet)! } public class func decodeUrl(url: String) -> String { return url.stringByRemovingPercentEncoding! } } public extension NSRange { /// Make String in swift can use stringByReplacingCharactersInRange public func toRange(string: String) -> Range<String.Index> { let startIndex = string.startIndex.advancedBy(self.location) let endIndex = startIndex.advancedBy(self.length) return startIndex..<endIndex } }
b600dd72a3cb6c5603113e2b8d9956fc
29.622222
93
0.624546
false
false
false
false
raymondshadow/SwiftDemo
refs/heads/master
SwiftApp/StudyNote/StudyNote/ImageRender/SNSDWebImageViewController.swift
apache-2.0
1
// // SNSDWebImageViewController.swift // StudyNote // // Created by wuyongpeng on 2019/9/2. // Copyright © 2019 Raymond. All rights reserved. // import UIKit import SDWebImage extension UIImageView { @objc dynamic func sn_setImage(urlStr: String) { } } class SNSDWebImageViewController: UIViewController { private lazy var imgView: FLAnimatedImageView = { let imv = FLAnimatedImageView(frame: CGRect(x: 0, y: 120, width: 100, height: 100)) imv.layer.borderWidth = 1 imv.layer.borderColor = UIColor.red.cgColor return imv }() @objc private lazy dynamic var progressView: UIProgressView = { let view = UIProgressView(frame: CGRect(x: 30, y: 100, width: 100, height: 10)) view.trackTintColor = UIColor.red view.backgroundColor = UIColor.red view.progressTintColor = UIColor.green view.progressViewStyle = .default view.layer.cornerRadius = 0 view.layer.masksToBounds = true return view }() @objc override dynamic func viewDidLoad() { super.viewDidLoad() self.view.addSubview(imgView) self.view.addSubview(progressView) } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { progressView.setProgress(0.8, animated: true) } }
3ae5fee6ea32bd0bc2ade6d6d78f7bd2
26.816327
91
0.645635
false
false
false
false
silence0201/Swift-Study
refs/heads/master
Swifter/24instanceType.playground/Contents.swift
mit
1
//: Playground - noun: a place where people can play import Foundation let date1 = NSDate() let name1: AnyClass! = object_getClass(date1) print(name1) // 输出: // __NSDate class A { var cls = NSData.self } var cls = A.self var c = NSString.self let date2 = NSDate() let name2 = type(of: date2) print(name2) // 输出: // __NSDate let string = "Hello" let name = type(of: string) print(name) debugPrint(name) // 输出: // Swift.String
108fc1fd0740126bee8b9d495695a909
13.566667
52
0.663616
false
false
false
false
blockchain/My-Wallet-V3-iOS
refs/heads/master
Modules/RemoteNotifications/Sources/RemoteNotificationsKit/Authorization/RemoteNotificationAuthorizer.swift
lgpl-3.0
1
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import AnalyticsKit import Combine import ToolKit import UserNotifications final class RemoteNotificationAuthorizer { // MARK: - Private Properties private let application: UIApplicationRemoteNotificationsAPI private let analyticsRecorder: AnalyticsEventRecorderAPI private let userNotificationCenter: UNUserNotificationCenterAPI private let options: UNAuthorizationOptions // MARK: - Setup init( application: UIApplicationRemoteNotificationsAPI, analyticsRecorder: AnalyticsEventRecorderAPI, userNotificationCenter: UNUserNotificationCenterAPI, options: UNAuthorizationOptions = [.alert, .badge, .sound] ) { self.application = application self.analyticsRecorder = analyticsRecorder self.userNotificationCenter = userNotificationCenter self.options = options } // MARK: - Private Accessors private func requestAuthorization() -> AnyPublisher<Void, RemoteNotificationAuthorizerError> { Deferred { [analyticsRecorder, userNotificationCenter, options] () -> AnyPublisher<Void, RemoteNotificationAuthorizerError> in AnyPublisher<Void, RemoteNotificationAuthorizerError> .just(()) .handleEvents( receiveOutput: { _ in analyticsRecorder.record( event: AnalyticsEvents.Permission.permissionSysNotifRequest ) } ) .flatMap { userNotificationCenter .requestAuthorizationPublisher( options: options ) .mapError(RemoteNotificationAuthorizerError.system) } .handleEvents( receiveOutput: { isGranted in let event: AnalyticsEvents.Permission if isGranted { event = .permissionSysNotifApprove } else { event = .permissionSysNotifDecline } analyticsRecorder.record(event: event) } ) .flatMap { isGranted -> AnyPublisher<Void, RemoteNotificationAuthorizerError> in guard isGranted else { return .failure(.permissionDenied) } return .just(()) } .eraseToAnyPublisher() } .eraseToAnyPublisher() } private var isNotDetermined: AnyPublisher<Bool, Never> { status .map { $0 == .notDetermined } .eraseToAnyPublisher() } } // MARK: - RemoteNotificationAuthorizationStatusProviding extension RemoteNotificationAuthorizer: RemoteNotificationAuthorizationStatusProviding { var status: AnyPublisher<UNAuthorizationStatus, Never> { Deferred { [userNotificationCenter] in Future { [userNotificationCenter] promise in userNotificationCenter.getAuthorizationStatus { status in promise(.success(status)) } } } .eraseToAnyPublisher() } } // MARK: - RemoteNotificationRegistering extension RemoteNotificationAuthorizer: RemoteNotificationRegistering { func registerForRemoteNotificationsIfAuthorized() -> AnyPublisher<Void, RemoteNotificationAuthorizerError> { isAuthorized .flatMap { isAuthorized -> AnyPublisher<Void, RemoteNotificationAuthorizerError> in guard isAuthorized else { return .failure(.unauthorizedStatus) } return .just(()) } .receive(on: DispatchQueue.main) .handleEvents( receiveOutput: { [unowned application] _ in application.registerForRemoteNotifications() }, receiveCompletion: { completion in switch completion { case .failure(let error): Logger.shared .error("Token registration failed with error: \(String(describing: error))") case .finished: break } } ) .eraseToAnyPublisher() } } // MARK: - RemoteNotificationAuthorizing extension RemoteNotificationAuthorizer: RemoteNotificationAuthorizationRequesting { // TODO: Handle a `.denied` case func requestAuthorizationIfNeeded() -> AnyPublisher<Void, RemoteNotificationAuthorizerError> { isNotDetermined .flatMap { isNotDetermined -> AnyPublisher<Void, RemoteNotificationAuthorizerError> in guard isNotDetermined else { return .failure(.statusWasAlreadyDetermined) } return .just(()) } .receive(on: DispatchQueue.main) .flatMap { [requestAuthorization] in requestAuthorization() } .receive(on: DispatchQueue.main) .handleEvents( receiveOutput: { [unowned application] _ in application.registerForRemoteNotifications() }, receiveCompletion: { completion in switch completion { case .failure(let error): Logger.shared .error("Remote notification authorization failed with error: \(error)") case .finished: break } } ) .eraseToAnyPublisher() } } extension AnalyticsEvents { enum Permission: AnalyticsEvent { case permissionSysNotifRequest case permissionSysNotifApprove case permissionSysNotifDecline public var name: String { switch self { // Permission - remote notification system request case .permissionSysNotifRequest: return "permission_sys_notif_request" // Permission - remote notification system approve case .permissionSysNotifApprove: return "permission_sys_notif_approve" // Permission - remote notification system decline case .permissionSysNotifDecline: return "permission_sys_notif_decline" } } } }
910b74d46983be5d036d48663dfee323
35.867403
112
0.565413
false
false
false
false
Webtrekk/webtrekk-ios-sdk
refs/heads/master
Source/Internal/CryptoSwift/MD5.swift
mit
1
// // CryptoSwift // // Copyright (C) 2014-2017 Marcin Krzyżanowski <[email protected]> // This software is provided 'as-is', without any express or implied warranty. // // In no event will the authors be held liable for any damages arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose,including commercial applications, // and to alter it and redistribute it freely, subject to the following restrictions: // // - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. // If you use this software in a product, an acknowledgment in the product documentation is required. // - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. // - This notice may not be removed or altered from any source or binary distribution. // public final class MD5: DigestType { static let blockSize: Int = 64 static let digestLength: Int = 16 // 128 / 8 fileprivate static let hashInitialValue: [UInt32] = [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476] fileprivate var accumulated = [UInt8]() fileprivate var processedBytesTotalCount: Int = 0 fileprivate var accumulatedHash: [UInt32] = MD5.hashInitialValue /** specifies the per-round shift amounts */ private let s: [UInt32] = [ 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21 ] /** binary integer part of the sines of integers (Radians) */ private let k: [UInt32] = [ 0xd76aa478, 0xe8c7b756, 0x242070db, 0xc1bdceee, 0xf57c0faf, 0x4787c62a, 0xa8304613, 0xfd469501, 0x698098d8, 0x8b44f7af, 0xffff5bb1, 0x895cd7be, 0x6b901122, 0xfd987193, 0xa679438e, 0x49b40821, 0xf61e2562, 0xc040b340, 0x265e5a51, 0xe9b6c7aa, 0xd62f105d, 0x2441453, 0xd8a1e681, 0xe7d3fbc8, 0x21e1cde6, 0xc33707d6, 0xf4d50d87, 0x455a14ed, 0xa9e3e905, 0xfcefa3f8, 0x676f02d9, 0x8d2a4c8a, 0xfffa3942, 0x8771f681, 0x6d9d6122, 0xfde5380c, 0xa4beea44, 0x4bdecfa9, 0xf6bb4b60, 0xbebfbc70, 0x289b7ec6, 0xeaa127fa, 0xd4ef3085, 0x4881d05, 0xd9d4d039, 0xe6db99e5, 0x1fa27cf8, 0xc4ac5665, 0xf4292244, 0x432aff97, 0xab9423a7, 0xfc93a039, 0x655b59c3, 0x8f0ccc92, 0xffeff47d, 0x85845dd1, 0x6fa87e4f, 0xfe2ce6e0, 0xa3014314, 0x4e0811a1, 0xf7537e82, 0xbd3af235, 0x2ad7d2bb, 0xeb86d391 ] public init() { } public func calculate(for bytes: [UInt8]) -> [UInt8] { do { return try update(withBytes: bytes.slice, isLast: true) } catch { fatalError() } } // mutating currentHash in place is way faster than returning new result fileprivate func process(block chunk: ArraySlice<UInt8>, currentHash: inout [UInt32]) { assert(chunk.count == 16 * 4) // Initialize hash value for this chunk: var A: UInt32 = currentHash[0] var B: UInt32 = currentHash[1] var C: UInt32 = currentHash[2] var D: UInt32 = currentHash[3] var dTemp: UInt32 = 0 // Main loop for j in 0..<k.count { var g = 0 var F: UInt32 = 0 switch j { case 0...15: F = (B & C) | ((~B) & D) g = j case 16...31: F = (D & B) | (~D & C) g = (5 * j + 1) % 16 case 32...47: F = B ^ C ^ D g = (3 * j + 5) % 16 case 48...63: F = C ^ (B | (~D)) g = (7 * j) % 16 default: break } dTemp = D D = C C = B // break chunk into sixteen 32-bit words M[j], 0 ≤ j ≤ 15 and get M[g] value let gAdvanced = g << 2 var Mg = UInt32(chunk[chunk.startIndex &+ gAdvanced]) Mg |= UInt32(chunk[chunk.startIndex &+ gAdvanced &+ 1]) << 8 Mg |= UInt32(chunk[chunk.startIndex &+ gAdvanced &+ 2]) << 16 Mg |= UInt32(chunk[chunk.startIndex &+ gAdvanced &+ 3]) << 24 B = B &+ rotateLeft(A &+ F &+ k[j] &+ Mg, by: s[j]) A = dTemp } currentHash[0] = currentHash[0] &+ A currentHash[1] = currentHash[1] &+ B currentHash[2] = currentHash[2] &+ C currentHash[3] = currentHash[3] &+ D } } extension MD5: Updatable { public func update(withBytes bytes: ArraySlice<UInt8>, isLast: Bool = false) throws -> [UInt8] { accumulated += bytes if isLast { let lengthInBits = (processedBytesTotalCount + accumulated.count) * 8 let lengthBytes = lengthInBits.bytes(totalBytes: 64 / 8) // A 64-bit representation of b // Step 1. Append padding bitPadding(to: &accumulated, blockSize: MD5.blockSize, allowance: 64 / 8) // Step 2. Append Length a 64-bit representation of lengthInBits accumulated += lengthBytes.reversed() } var processedBytes = 0 for chunk in accumulated.batched(by: MD5.blockSize) { if isLast || (accumulated.count - processedBytes) >= MD5.blockSize { process(block: chunk, currentHash: &accumulatedHash) processedBytes += chunk.count } } accumulated.removeFirst(processedBytes) processedBytesTotalCount += processedBytes // output current hash var result = [UInt8]() result.reserveCapacity(MD5.digestLength) for hElement in accumulatedHash { let hLE = hElement.littleEndian result += [UInt8](arrayLiteral: UInt8(hLE & 0xff), UInt8((hLE >> 8) & 0xff), UInt8((hLE >> 16) & 0xff), UInt8((hLE >> 24) & 0xff)) } // reset hash value for instance if isLast { accumulatedHash = MD5.hashInitialValue } return result } }
da022a70357af73492cbd7fac18336d5
37.08589
142
0.586823
false
false
false
false
HenvyLuk/BabyGuard
refs/heads/master
BabyGuard/CVCalendar/CVDate.swift
apache-2.0
1
// // CVDate.swift // CVCalendar // // Created by Мак-ПК on 12/31/14. // Copyright (c) 2014 GameApp. All rights reserved. // import UIKit public final class CVDate: NSObject { private let date: NSDate public let year: Int public let month: Int public let week: Int public let day: Int public init(date: NSDate) { let dateRange = Manager.dateRange(date) self.date = date self.year = dateRange.year self.month = dateRange.month self.week = dateRange.weekOfMonth self.day = dateRange.day super.init() } public init(day: Int, month: Int, week: Int, year: Int) { if let date = Manager.dateFromYear(year, month: month, week: week, day: day) { self.date = date } else { self.date = NSDate() } self.year = year self.month = month self.week = week self.day = day super.init() } } extension CVDate { public func convertedDate() -> NSDate? { let calendar = NSCalendar.currentCalendar() let comps = Manager.componentsForDate(NSDate()) comps.year = year comps.month = month comps.weekOfMonth = week comps.day = day return calendar.dateFromComponents(comps) } } extension CVDate { public var globalDescription: String { get { let month = dateFormattedStringWithFormat("MMMM", fromDate: date) return "\(month), \(year)" } } public var commonDescription: String { get { let month = dateFormattedStringWithFormat("MM", fromDate: date) let day = dateFormattedStringWithFormat("dd", fromDate: date) //return "\(day) \(month), \(year)" return "\(year)\(month)\(day)" } } } private extension CVDate { func dateFormattedStringWithFormat(format: String, fromDate date: NSDate) -> String { let formatter = NSDateFormatter() formatter.dateFormat = format return formatter.stringFromDate(date) } }
b02b7edaf2b62ac8bccee5b74be9da65
23.137931
89
0.585714
false
false
false
false
00buggy00/SwiftOpenGLTutorials
refs/heads/master
SwiftOpenGLRefactor/GraphicSceneObjects.swift
mit
1
// // GraphicSceneObjects.swift // SwiftOpenGLRefactor // // Created by Myles Schultz on 1/19/18. // Copyright © 2018 MyKo. All rights reserved. // import Foundation import Quartz import OpenGL.GL3 func glLogCall(file: String, line: Int) -> Bool { var error = GLenum(GL_NO_ERROR) repeat { error = glGetError() switch error { case GLenum(GL_INVALID_ENUM): print("\(file), line: \(line), ERROR: invalid Enum") return false case GLenum(GL_INVALID_VALUE): print("\(file), line: \(line), ERROR: invalid value passed") return false case GLenum(GL_INVALID_OPERATION): print("\(file), line: \(line), ERROR: invalid operation attempted") return false case GLenum(GL_INVALID_FRAMEBUFFER_OPERATION): print("\(file), line: \(line), ERROR: invalid framebuffer operation attempted") return false case GLenum(GL_OUT_OF_MEMORY): print("\(file), line: \(line), ERROR: out of memory") return false default: return true } } while error != GLenum(GL_NO_ERROR) } func glCall<T>(_ function: @autoclosure () -> T, file: String = #file, line: Int = #line) -> T { while glGetError() != GL_NO_ERROR {} let result = function() assert(glLogCall(file: file, line: line)) return result } protocol OpenGLObject { var id: GLuint { get set } func bind() func unbind() mutating func delete() } struct Vertex { var position: Float3 var normal: Float3 var textureCoordinate: Float2 var color: Float3 } struct VertexBufferObject: OpenGLObject { var id: GLuint = 0 let type: GLenum = GLenum(GL_ARRAY_BUFFER) var vertexCount: Int32 { return Int32(data.count) } var data: [Vertex] = [] mutating func load(_ data: [Vertex]) { self.data = data glCall(glGenBuffers(1, &id)) bind() glCall(glBufferData(GLenum(GL_ARRAY_BUFFER), data.count * MemoryLayout<Vertex>.size, data, GLenum(GL_STATIC_DRAW))) } func bind() { glCall(glBindBuffer(type, id)) } func unbind() { glCall(glBindBuffer(type, id)) } mutating func delete() { glCall(glDeleteBuffers(1, &id)) } } struct VertexArrayObject: OpenGLObject { var id: GLuint = 0 mutating func layoutVertexPattern() { glCall(glGenVertexArrays(1, &id)) bind() glCall(glVertexAttribPointer(0, 3, GLenum(GL_FLOAT), GLboolean(GL_FALSE), 44, UnsafePointer<GLuint>(bitPattern: 0))) glCall(glEnableVertexAttribArray(0)) glCall(glVertexAttribPointer(1, 3, GLenum(GL_FLOAT), GLboolean(GL_FALSE), 44, UnsafePointer<GLuint>(bitPattern: 12))) glCall(glEnableVertexAttribArray(1)) glCall(glVertexAttribPointer(2, 2, GLenum(GL_FLOAT), GLboolean(GL_FALSE), 44, UnsafePointer<GLuint>(bitPattern: 24))) glCall(glEnableVertexAttribArray(2)) glCall(glVertexAttribPointer(3, 3, GLenum(GL_FLOAT), GLboolean(GL_FALSE), 44, UnsafePointer<GLuint>(bitPattern:32))) glCall(glEnableVertexAttribArray(3)) } func bind() { glCall(glBindVertexArray(id)) } func unbind() { glCall(glBindVertexArray(id)) } mutating func delete() { glCall(glDeleteVertexArrays(1, &id)) } } enum TextureSlot: GLint { case texture1 = 33984 } struct TextureBufferObject: OpenGLObject { var id: GLuint = 0 var textureSlot: GLint = TextureSlot.texture1.rawValue mutating func loadTexture(named name: String) { guard let textureData = NSImage(named: NSImage.Name(rawValue: name))?.tiffRepresentation else { Swift.print("Image name not located in Image Asset Catalog") return } glCall(glGenTextures(1, &id)) bind() glCall(glTexParameteri(GLenum(GL_TEXTURE_2D), GLenum(GL_TEXTURE_MIN_FILTER), GL_LINEAR)) glCall(glTexParameteri(GLenum(GL_TEXTURE_2D), GLenum(GL_TEXTURE_MAG_FILTER), GL_LINEAR)) glCall(glTexParameteri(GLenum(GL_TEXTURE_2D), GLenum(GL_TEXTURE_WRAP_S), GL_REPEAT)) glCall(glTexParameteri(GLenum(GL_TEXTURE_2D), GLenum(GL_TEXTURE_WRAP_T), GL_REPEAT)) glCall(glTexImage2D(GLenum(GL_TEXTURE_2D), 0, GL_RGBA, 256, 256, 0, GLenum(GL_RGBA), GLenum(GL_UNSIGNED_BYTE), (textureData as NSData).bytes)) } func bind() { glCall(glBindTexture(GLenum(GL_TEXTURE_2D), id)) } func unbind() { glCall(glBindTexture(GLenum(GL_TEXTURE_2D), 0)) } mutating func delete() { glCall(glDeleteTextures(1, &id)) } } enum ShaderType: UInt32 { case vertex = 35633 /* GL_VERTEX_SHADER */ case fragment = 35632 /* GL_FRAGMENT_SHADER */ } struct Shader: OpenGLObject { var id: GLuint = 0 mutating func create(withVertex vertexSource: String, andFragment fragmentSource: String) { id = glCall(glCreateProgram()) let vertex = compile(shaderType: .vertex, withSource: vertexSource) let fragment = compile(shaderType: .fragment, withSource: fragmentSource) link(vertexShader: vertex, fragmentShader: fragment) } func compile(shaderType type: ShaderType, withSource source: String) -> GLuint { let shader = glCall(glCreateShader(type.rawValue)) var pointerToShader = UnsafePointer<GLchar>(source.cString(using: String.Encoding.ascii)) glCall(glShaderSource(shader, 1, &pointerToShader, nil)) glCall(glCompileShader(shader)) var compiled: GLint = 0 glCall(glGetShaderiv(shader, GLbitfield(GL_COMPILE_STATUS), &compiled)) if compiled <= 0 { print("Could not compile shader type: \(type), getting log...") var logLength: GLint = 0 print("Log length: \(logLength)") glCall(glGetShaderiv(shader, GLenum(GL_INFO_LOG_LENGTH), &logLength)) if logLength > 0 { let cLog = UnsafeMutablePointer<CChar>.allocate(capacity: Int(logLength)) glCall(glGetShaderInfoLog(shader, GLsizei(logLength), &logLength, cLog)) Swift.print("\n\t\(String.init(cString: cLog))") free(cLog) } } return shader } func link(vertexShader vertex: GLuint, fragmentShader fragment: GLuint) { glCall(glAttachShader(id, vertex)) glCall(glAttachShader(id, fragment)) glCall(glLinkProgram(id)) var linked: GLint = 0 glCall(glGetProgramiv(id, UInt32(GL_LINK_STATUS), &linked)) if linked <= 0 { Swift.print("Could not link, getting log") var logLength: GLint = 0 glCall(glGetProgramiv(id, UInt32(GL_INFO_LOG_LENGTH), &logLength)) Swift.print(" logLength = \(logLength)") if logLength > 0 { let cLog = UnsafeMutablePointer<CChar>.allocate(capacity: Int(logLength)) glCall(glGetProgramInfoLog(id, GLsizei(logLength), &logLength, cLog)) Swift.print("log: \(String.init(cString:cLog))") free(cLog) } } glCall(glDeleteShader(vertex)) glCall(glDeleteShader(fragment)) } func setInitialUniforms(for scene: inout Scene) { // let location = glCall(glGetUniformLocation(id, "sample")) // glCall(glUniform1i(location, scene.tbo.textureSlot)) bind() scene.light.attach(toShader: self) scene.light.updateParameters(for: self) scene.camera.attach(toShader: self) scene.camera.updateParameters(for: self) } func bind() { glCall(glUseProgram(id)) } func unbind() { glCall(glUseProgram(0)) } func delete() { glCall(glDeleteProgram(id)) } } struct DisplayLink { let id: CVDisplayLink let displayLinkOutputCallback: CVDisplayLinkOutputCallback = {(displayLink: CVDisplayLink, inNow: UnsafePointer<CVTimeStamp>, inOutputTime: UnsafePointer<CVTimeStamp>, flagsIn: CVOptionFlags, flagsOut: UnsafeMutablePointer<CVOptionFlags>, displayLinkContext: UnsafeMutableRawPointer?) -> CVReturn in // print("fps: \(Double(inNow.pointee.videoTimeScale) / Double(inNow.pointee.videoRefreshPeriod))") let view = unsafeBitCast(displayLinkContext, to: GraphicView.self) view.displayLink?.currentTime = Double(inNow.pointee.videoTime) / Double(inNow.pointee.videoTimeScale) let result = view.drawView() return result } var currentTime: Double = 0.0 { willSet { deltaTime = currentTime - newValue } } var deltaTime: Double = 0.0 init?(forView view: GraphicView) { var newID: CVDisplayLink? if CVDisplayLinkCreateWithActiveCGDisplays(&newID) == kCVReturnSuccess { self.id = newID! CVDisplayLinkSetOutputCallback(id, displayLinkOutputCallback, UnsafeMutableRawPointer(Unmanaged.passUnretained(view).toOpaque())) } else { return nil } } func start() { CVDisplayLinkStart(id) } func stop() { CVDisplayLinkStop(id) } } struct Light { private enum Parameter: String { case color = "light.color" case position = "light.position" case ambientStrength = "light.ambient" case specularStrength = "light.specStrength" case specularHardness = "light.specHardness" } var color: [GLfloat] = [1.0, 1.0, 1.0] { didSet { parametersToUpdate.append(.color) } } var position: [GLfloat] = [0.0, 1.0, 0.5] { didSet { parametersToUpdate.append(.position) } } var ambietStrength: GLfloat = 0.25 { didSet { parametersToUpdate.append(.ambientStrength) } } var specularStrength: GLfloat = 3.0 { didSet { parametersToUpdate.append(.specularStrength) } } var specularHardness: GLfloat = 32 { didSet { parametersToUpdate.append(.specularHardness) } } private var shaderParameterLocations = [GLuint : [Parameter : Int32]]() private var parametersToUpdate: [Parameter] = [.color, .position, .ambientStrength, .specularStrength, .specularHardness] mutating func attach(toShader shader: Shader) { let shader = shader.id var parameterLocations = [Parameter : Int32]() parameterLocations[.color] = glCall(glGetUniformLocation(shader, Parameter.color.rawValue)) parameterLocations[.position] = glCall(glGetUniformLocation(shader, Parameter.position.rawValue)) parameterLocations[.ambientStrength] = glCall(glGetUniformLocation(shader, Parameter.ambientStrength.rawValue)) parameterLocations[.specularStrength] = glCall(glGetUniformLocation(shader, Parameter.specularStrength.rawValue)) parameterLocations[.specularHardness] = glCall(glGetUniformLocation(shader, Parameter.specularHardness.rawValue)) shaderParameterLocations[shader] = parameterLocations } mutating func updateParameters(for shader: Shader) { if let parameterLocations = shaderParameterLocations[shader.id] { for parameter in parametersToUpdate { switch parameter { case .color: if let location = parameterLocations[parameter] { glCall(glUniform3fv(location, 1, color)) } case .position: if let location = parameterLocations[parameter] { glCall(glUniform3fv(location, 1, position)) } case .ambientStrength: if let location = parameterLocations[parameter] { glCall(glUniform1f(location, ambietStrength)) } case .specularStrength: if let location = parameterLocations[parameter] { glCall(glUniform1f(location, specularStrength)) } case .specularHardness: if let location = parameterLocations[parameter] { glCall(glUniform1f(location, specularHardness)) } } } parametersToUpdate.removeAll() } } } struct Camera: Asset { private enum Parameter: String { case position = "view" case projection = "projection" } var name: String = "Camera" var position = FloatMatrix4() { didSet { parametersToUpdate.insert(.position) } } var projection = FloatMatrix4() { didSet { parametersToUpdate.insert(.projection) } } private var shaderParameterLocations = [GLuint : [Parameter : Int32]]() private var parametersToUpdate: Set<Parameter> = [.position, .projection] mutating func attach(toShader shader: Shader) { let shader = shader.id var parameterLocations = [Parameter : Int32]() parameterLocations[.position] = glCall(glGetUniformLocation(shader, Parameter.position.rawValue)) parameterLocations[.projection] = glCall(glGetUniformLocation(shader, Parameter.projection.rawValue)) shaderParameterLocations[shader] = parameterLocations } mutating func updateParameters(for shader: Shader) { if let parameterLocations = shaderParameterLocations[shader.id] { for parameter in parametersToUpdate { switch parameter { case .position: if let location = parameterLocations[parameter] { glCall(glUniformMatrix4fv(location, 1, GLboolean(GL_FALSE), position.columnMajorArray())) } case .projection: if let location = parameterLocations[parameter] { glCall(glUniformMatrix4fv(location, 1, GLboolean(GL_FALSE), projection.columnMajorArray())) } } } parametersToUpdate.removeAll() } } } struct Scene { var shader = Shader() var vao = VertexArrayObject() var vbo = VertexBufferObject() var tbo = TextureBufferObject() var light = Light() var camera = Camera() let data: [Vertex] = [ Vertex(position: Float3(x: -1.0, y: -1.0, z: 1.0), /* Front face 1 */ normal: Float3(x: 0.0, y: 0.0, z: 1.0), textureCoordinate: Float2(x: 0.0, y: 0.0), color: Float3(x: 1.0, y: 0.0, z: 0.0)), Vertex(position: Float3(x: 1.0, y: -1.0, z: 1.0), normal: Float3(x: 0.0, y: 0.0, z: 1.0), textureCoordinate: Float2(x: 1.0, y: 0.0), color: Float3(x: 0.0, y: 0.0, z: 1.0)), Vertex(position: Float3(x: 1.0, y: 1.0, z: 1.0), normal: Float3(x: 0.0, y: 0.0, z: 1.0), textureCoordinate: Float2(x: 1.0, y: 1.0), color: Float3(x: 0.0, y: 1.0, z: 0.0)), Vertex(position: Float3(x: 1.0, y: 1.0, z: 1.0), /* Front face 2 */ normal: Float3(x: 0.0, y: 0.0, z: 1.0), textureCoordinate: Float2(x: 1.0, y: 1.0), color: Float3(x: 0.0, y: 1.0, z: 0.0)), Vertex(position: Float3(x: -1.0, y: 1.0, z: 1.0), normal: Float3(x: 0.0, y: 0.0, z: 1.0), textureCoordinate: Float2(x: 0.0, y: 1.0), color: Float3(x: 1.0, y: 1.0, z: 1.0)), Vertex(position: Float3(x: -1.0, y: -1.0, z: 1.0), normal: Float3(x: 0.0, y: 0.0, z: 1.0), textureCoordinate: Float2(x: 0.0, y: 0.0), color: Float3(x: 1.0, y: 0.0, z: 0.0)), Vertex(position: Float3(x: 1.0, y: -1.0, z: 1.0), /* Right face 1 */ normal: Float3(x: 1.0, y: 0.0, z: 0.0), textureCoordinate: Float2(x: 0.0, y: 0.0), color: Float3(x: 0.0, y: 0.0, z: 1.0)), Vertex(position: Float3(x: 1.0, y: -1.0, z: -1.0), normal: Float3(x: 1.0, y: 0.0, z: 0.0), textureCoordinate: Float2(x: 1.0, y: 0.0), color: Float3(x: 1.0, y: 1.0, z: 0.0)), Vertex(position: Float3(x: 1.0, y: 1.0, z: -1.0), normal: Float3(x: 1.0, y: 0.0, z: 0.0), textureCoordinate: Float2(x: 1.0, y: 1.0), color: Float3(x: 0.0, y: 1.0, z: 1.0)), Vertex(position: Float3(x: 1.0, y: 1.0, z: -1.0), /* Right face 2 */ normal: Float3(x: 1.0, y: 0.0, z: 0.0), textureCoordinate: Float2(x: 1.0, y: 1.0), color: Float3(x: 0.0, y: 1.0, z: 1.0)), Vertex(position: Float3(x: 1.0, y: 1.0, z: 1.0), normal: Float3(x: 1.0, y: 0.0, z: 0.0), textureCoordinate: Float2(x: 0.0, y: 1.0), color: Float3(x: 0.0, y: 1.0, z: 0.0)), Vertex(position: Float3(x: 1.0, y: -1.0, z: 1.0), normal: Float3(x: 1.0, y: 0.0, z: 0.0), textureCoordinate: Float2(x: 0.0, y: 0.0), color: Float3(x: 0.0, y: 0.0, z: 1.0)), Vertex(position: Float3(x: 1.0, y: -1.0, z: -1.0), /* Back face 1 */ normal: Float3(x: 0.0, y: 0.0, z: -1.0), textureCoordinate: Float2(x: 0.0, y: 0.0), color: Float3(x: 1.0, y: 1.0, z: 0.0)), Vertex(position: Float3(x: -1.0, y: -1.0, z: -1.0), normal: Float3(x: 0.0, y: 0.0, z: -1.0), textureCoordinate: Float2(x: 1.0, y: 0.0), color: Float3(x: 0.0, y: 0.0, z: 0.0)), Vertex(position: Float3(x: -1.0, y: 1.0, z: -1.0), normal: Float3(x: 0.0, y: 0.0, z: -1.0), textureCoordinate: Float2(x: 1.0, y: 1.0), color: Float3(x: 1.0, y: 0.0, z: 1.0)), Vertex(position: Float3(x: -1.0, y: 1.0, z: -1.0), /* Back face 2 */ normal: Float3(x: 0.0, y: 0.0, z: -1.0), textureCoordinate: Float2(x: 1.0, y: 1.0), color: Float3(x: 1.0, y: 0.0, z: 1.0)), Vertex(position: Float3(x: 1.0, y: 1.0, z: -1.0), normal: Float3(x: 0.0, y: 0.0, z: -1.0), textureCoordinate: Float2(x: 0.0, y: 1.0), color: Float3(x: 0.0, y: 1.0, z: 1.0)), Vertex(position: Float3(x: 1.0, y: -1.0, z: -1.0), normal: Float3(x: 0.0, y: 0.0, z: -1.0), textureCoordinate: Float2(x: 0.0, y: 0.0), color: Float3(x: 1.0, y: 1.0, z: 0.0)), Vertex(position: Float3(x: -1.0, y: -1.0, z: -1.0), /* Left face 1 */ normal: Float3(x: -1.0, y: 0.0, z: 0.0), textureCoordinate: Float2(x: 0.0, y: 0.0), color: Float3(x: 0.0, y: 0.0, z: 0.0)), Vertex(position: Float3(x: -1.0, y: -1.0, z: 1.0), normal: Float3(x: -1.0, y: 0.0, z: 0.0), textureCoordinate: Float2(x: 1.0, y: 0.0), color: Float3(x: 1.0, y: 0.0, z: 0.0)), Vertex(position: Float3(x: -1.0, y: 1.0, z: 1.0), normal: Float3(x: -1.0, y: 0.0, z: 0.0), textureCoordinate: Float2(x: 1.0, y: 1.0), color: Float3(x: 1.0, y: 1.0, z: 1.0)), Vertex(position: Float3(x: -1.0, y: 1.0, z: 1.0), /* Left face 2 */ normal: Float3(x: -1.0, y: 0.0, z: 0.0), textureCoordinate: Float2(x: 1.0, y: 1.0), color: Float3(x: 1.0, y: 1.0, z: 1.0)), Vertex(position: Float3(x: -1.0, y: 1.0, z: -1.0), normal: Float3(x: -1.0, y: 0.0, z: 0.0), textureCoordinate: Float2(x: 0.0, y: 1.0), color: Float3(x: 1.0, y: 0.0, z: 1.0)), Vertex(position: Float3(x: -1.0, y: -1.0, z: -1.0), normal: Float3(x: -1.0, y: 0.0, z: 0.0), textureCoordinate: Float2(x: 0.0, y: 0.0), color: Float3(x: 0.0, y: 0.0, z: 0.0)), Vertex(position: Float3(x: -1.0, y: -1.0, z: 1.0), /* Bottom face 1 */ normal: Float3(x: 0.0, y: -1.0, z: 0.0), textureCoordinate: Float2(x: 0.0, y: 0.0), color: Float3(x: 1.0, y: 0.0, z: 0.0)), Vertex(position: Float3(x: -1.0, y: -1.0, z: -1.0), normal: Float3(x: 0.0, y: -1.0, z: 0.0), textureCoordinate: Float2(x: 1.0, y: 0.0), color: Float3(x: 0.0, y: 0.0, z: 0.0)), Vertex(position: Float3(x: 1.0, y: -1.0, z: -1.0), normal: Float3(x: 0.0, y: -1.0, z: 0.0), textureCoordinate: Float2(x: 1.0, y: 1.0), color: Float3(x: 1.0, y: 1.0, z: 0.0)), Vertex(position: Float3(x: 1.0, y: -1.0, z: -1.0), /* Bottom face 2 */ normal: Float3(x: 0.0, y: -1.0, z: 0.0), textureCoordinate: Float2(x: 1.0, y: 1.0), color: Float3(x: 1.0, y: 1.0, z: 0.0)), Vertex(position: Float3(x: 1.0, y: -1.0, z: 1.0), normal: Float3(x: 0.0, y: -1.0, z: 0.0), textureCoordinate: Float2(x: 0.0, y: 1.0), color: Float3(x: 0.0, y: 0.0, z: 1.0)), Vertex(position: Float3(x: -1.0, y: -1.0, z: 1.0), normal: Float3(x: 0.0, y: -1.0, z: 0.0), textureCoordinate: Float2(x: 0.0, y: 0.0), color: Float3(x: 1.0, y: 0.0, z: 0.0)), Vertex(position: Float3(x: -1.0, y: 1.0, z: 1.0), /* Top face 1 */ normal: Float3(x: 0.0, y: 1.0, z: 0.0), textureCoordinate: Float2(x: 0.0, y: 0.0), color: Float3(x: 1.0, y: 1.0, z: 1.0)), Vertex(position: Float3(x: 1.0, y: 1.0, z: 1.0), normal: Float3(x: 0.0, y: 1.0, z: 0.0), textureCoordinate: Float2(x: 0.0, y: 1.0), color: Float3(x: 0.0, y: 1.0, z: 0.0)), Vertex(position: Float3(x: 1.0, y: 1.0, z: -1.0), normal: Float3(x: 0.0, y: 1.0, z: 0.0), textureCoordinate: Float2(x: 1.0, y: 1.0), color: Float3(x: 0.0, y: 1.0, z: 1.0)), Vertex(position: Float3(x: 1.0, y: 1.0, z: -1.0), /* Top face 2 */ normal: Float3(x: 0.0, y: 1.0, z: 0.0), textureCoordinate: Float2(x: 1.0, y: 1.0), color: Float3(x: 0.0, y: 1.0, z: 1.0)), Vertex(position: Float3(x: -1.0, y: 1.0, z: -1.0), normal: Float3(x: 0.0, y: 1.0, z: 0.0), textureCoordinate: Float2(x: 0.0, y: 1.0), color: Float3(x: 1.0, y: 0.0, z: 1.0)), Vertex(position: Float3(x: -1.0, y: 1.0, z: 1.0), normal: Float3(x: 0.0, y: 1.0, z: 0.0), textureCoordinate: Float2(x: 0.0, y: 0.0), color: Float3(x: 1.0, y: 1.0, z: 1.0)) ] mutating func load(into view: GraphicView) { tbo.loadTexture(named: "Texture") vbo.load(data) vao.layoutVertexPattern() vao.unbind() camera.position = FloatMatrix4().translate(x: 0.0, y: 0.0, z: -5.0) // camera.projection = FloatMatrix4.orthographic(width: Float(view.bounds.size.width), height: Float(view.bounds.size.height)) camera.projection = FloatMatrix4.projection(aspect: Float(view.bounds.size.width / view.bounds.size.height)) let vertexSource = "#version 330 core \n" + "layout (location = 0) in vec3 position; \n" + "layout (location = 1) in vec3 normal; \n" + "layout (location = 2) in vec2 texturePosition; \n" + "layout (location = 3) in vec3 color; \n" + "out vec3 passPosition; \n" + "out vec3 passNormal; \n" + "out vec2 passTexturePosition; \n" + "out vec3 passColor; \n" + "uniform mat4 view; \n" + "uniform mat4 projection; \n" + "void main() \n" + "{ \n" + " gl_Position = projection * view * vec4(position, 1.0); \n" + " passPosition = position; \n" + " passNormal = normal; \n" + " passTexturePosition = texturePosition; \n" + " passColor = color; \n" + "} \n" let fragmentSource = "#version 330 core \n" + "uniform sampler2D sample; \n" + "uniform struct Light { \n" + " vec3 color; \n" + " vec3 position; \n" + " float ambient; \n" + " float specStrength; \n" + " float specHardness; \n" + "} light; \n" + "in vec3 passPosition; \n" + "in vec3 passNormal; \n" + "in vec2 passTexturePosition; \n" + "in vec3 passColor; \n" + "out vec4 outColor; \n" + "void main() \n" + "{ \n" + " vec3 normal = normalize(passNormal); \n" + " vec3 lightRay = normalize(light.position - passPosition); \n" + " float intensity = dot(normal, lightRay); \n" + " intensity = clamp(intensity, 0, 1); \n" + " vec3 viewer = normalize(vec3(0.0, 0.0, 0.2) - passPosition); \n" + " vec3 reflection = reflect(lightRay, normal); \n" + " float specular = pow(max(dot(viewer, reflection), 0.0), light.specHardness); \n" + " vec3 light = light.ambient + light.color * intensity + light.specStrength * specular * light.color; \n" + " vec3 surface = texture(sample, passTexturePosition).rgb * passColor; \n" + " vec3 rgb = surface * light; \n" + " outColor = vec4(rgb, 1.0); \n" + "} \n" shader.create(withVertex: vertexSource, andFragment: fragmentSource) shader.setInitialUniforms(for: &self) } mutating func update(with value: Float) { light.position = [sin(value), -5.0, 5.0] camera.position = FloatMatrix4().translate(x: 0.0, y: 0.0, z: -5.0).rotateYAxis(value).rotateXAxis(-0.5) } mutating func draw(with renderer: Renderer) { shader.bind() vao.bind() light.updateParameters(for: shader) camera.updateParameters(for: shader) renderer.render(vbo.vertexCount, as: .triangles) vao.unbind() } mutating func delete() { vao.delete() vbo.delete() tbo.delete() shader.delete() } }
46b4f850f98f9b1c25c34b5f908e7ea6
43.981763
303
0.48902
false
false
false
false
Pocketbrain/nativeadslib-ios
refs/heads/master
PocketMediaNativeAdsExample/CustomIntegration/CustomIntegrationViewController.swift
mit
1
// // CustomIntegration.swift // PocketMediaNativeAdsExample // // Created by Iain Munro on 09/01/2017. // Copyright © 2017 PocketMedia. All rights reserved. // import Foundation import UIKit import PocketMediaNativeAds class CustomIntegrationController: UIViewController, NativeAdsConnectionDelegate { @IBOutlet weak var getButton: UIButton! @IBOutlet weak var adImage: UIImageView! @IBOutlet weak var adTitle: UILabel! @IBOutlet weak var adDescription: UILabel! var requester: NativeAdsRequest? var ad: NativeAd? var _requesting: Bool = false var requesting: Bool { get { return _requesting } set(newVal) { _requesting = newVal getButton.isEnabled = !_requesting } } override func viewDidLoad() { requester = NativeAdsRequest(adPlacementToken: "894d2357e086434a383a1c29868a0432958a3165", delegate: self) let click = UITapGestureRecognizer(target: self, action: #selector(tap(_:))) adImage.addGestureRecognizer(click) adTitle.addGestureRecognizer(click) } func tap(_ gestureRecognizer: UITapGestureRecognizer) { ad?.openAdUrl(FullscreenBrowser(parentViewController: self)) } /** Called the moment the user click on "get an ad" */ @IBAction func getAd(_ sender: UIButton) { if requesting { return } requesting = true self.requester?.retrieveAds(1) } /** This method is invoked whenever while retrieving NativeAds an error has occured */ func didReceiveError(_ error: Error) { requesting = false print(error) } /** This method allows the delegate to receive a collection of NativeAds after making an NativeAdRequest. - nativeAds: Collection of NativeAds received after making a NativeAdRequest */ func didReceiveResults(_ nativeAds: [NativeAd]) { requesting = false showAd(ad: nativeAds[0]) } /** Called to display an ad. */ private func showAd(ad: NativeAd) { self.ad = ad adTitle.text = ad.campaignName adImage.nativeSetImageFromURL(ad.campaignImage) adDescription.text = ad.campaignDescription } }
3697e834037dd93f0553313b64625f22
26.756098
114
0.654657
false
false
false
false
stripe/stripe-ios
refs/heads/master
StripePayments/StripePayments/API Bindings/Legacy Compatability/StripeAPI+Deprecated.swift
mit
1
// // StripeAPI+Deprecated.swift // StripePayments // // Created by David Estes on 10/15/21. // Copyright © 2021 Stripe, Inc. All rights reserved. // import Foundation import PassKit extension StripeAPI { /// A convenience method to build a `PKPaymentRequest` with sane default values. /// You will still need to configure the `paymentSummaryItems` property to indicate /// what the user is purchasing, as well as the optional `requiredShippingAddressFields`, /// `requiredBillingAddressFields`, and `shippingMethods` properties to indicate /// what contact information your application requires. /// Note that this method sets the payment request's countryCode to "US" and its /// currencyCode to "USD". /// - Parameter merchantIdentifier: Your Apple Merchant ID. /// - Returns: a `PKPaymentRequest` with proper default values. Returns nil if running on < iOS8. /// @deprecated Use `paymentRequestWithMerchantIdentifier:country:currency:` instead. /// Apple Pay is available in many countries and currencies, and you should use /// the appropriate values for your business. @available( *, deprecated, message: "Use `paymentRequestWithMerchantIdentifier:country:currency:` instead." ) @objc(paymentRequestWithMerchantIdentifier:) public class func paymentRequest( withMerchantIdentifier merchantIdentifier: String ) -> PKPaymentRequest { return self.paymentRequest( withMerchantIdentifier: merchantIdentifier, country: "US", currency: "USD" ) } } // MARK: Deprecated top-level Stripe functions. // These are included so Xcode can offer guidance on how to replace top-level Stripe usage. /// :nodoc: @available( *, deprecated, message: "Use StripeAPI.defaultPublishableKey instead. (StripeAPI.defaultPublishableKey = \"pk_12345_xyzabc\")" ) public func setDefaultPublishableKey(_ publishableKey: String) { StripeAPI.defaultPublishableKey = publishableKey } /// :nodoc: @available( *, deprecated, message: "Use StripeAPI.advancedFraudSignalsEnabled instead." ) public var advancedFraudSignalsEnabled: Bool { get { StripeAPI.advancedFraudSignalsEnabled } set { StripeAPI.advancedFraudSignalsEnabled = newValue } } /// :nodoc: @available( *, deprecated, message: "Use StripeAPI.jcbPaymentNetworkSupported instead." ) public var jcbPaymentNetworkSupported: Bool { get { StripeAPI.jcbPaymentNetworkSupported } set { StripeAPI.jcbPaymentNetworkSupported = newValue } } /// :nodoc: @available( *, deprecated, message: "Use StripeAPI.additionalEnabledApplePayNetworks instead." ) public var additionalEnabledApplePayNetworks: [PKPaymentNetwork] { get { StripeAPI.additionalEnabledApplePayNetworks } set { StripeAPI.additionalEnabledApplePayNetworks = newValue } } /// :nodoc: @available( *, deprecated, message: "Use StripeAPI.canSubmitPaymentRequest(_:) instead." ) public func canSubmitPaymentRequest(_ paymentRequest: PKPaymentRequest) -> Bool { return StripeAPI.canSubmitPaymentRequest(paymentRequest) } /// :nodoc: @available( *, deprecated, message: "Use StripeAPI.deviceSupportsApplePay() instead." ) public func deviceSupportsApplePay() -> Bool { return StripeAPI.deviceSupportsApplePay() } /// :nodoc: @available( *, deprecated, message: "Use StripeAPI.paymentRequest(withMerchantIdentifier:country:currency:) instead." ) public func paymentRequest( withMerchantIdentifier merchantIdentifier: String, country countryCode: String, currency currencyCode: String ) -> PKPaymentRequest { return StripeAPI.paymentRequest( withMerchantIdentifier: merchantIdentifier, country: countryCode, currency: currencyCode ) } /// :nodoc: @available( *, deprecated, message: "Use StripeAPI.paymentRequest(withMerchantIdentifier:country:currency:) instead." ) func paymentRequest( withMerchantIdentifier merchantIdentifier: String ) -> PKPaymentRequest { return StripeAPI.paymentRequest( withMerchantIdentifier: merchantIdentifier, country: "US", currency: "USD" ) } /// :nodoc: @available( *, deprecated, message: "Use StripeAPI.handleURLCallback(with:) instead." ) public func handleURLCallback(with url: URL) -> Bool { return StripeAPI.handleURLCallback(with: url) }
4afb89e9f15ab564577f62be5c250f99
25.923077
110
0.701758
false
false
false
false
AlphaCluster/NewsBlur
refs/heads/master
clients/ios/Other Sources/SAConfettiView/Classes/SAConfettiView.swift
mit
2
// // SAConfettiView.swift // Pods // // Created by Sudeep Agarwal on 12/14/15. // // import UIKit import QuartzCore public class SAConfettiView: UIView, CAAnimationDelegate { public enum ConfettiType { case Confetti case Triangle case Star case Diamond case Image(UIImage) } var emitter: CAEmitterLayer! public var colors: [UIColor]! public var intensity: Float! public var type: ConfettiType! required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setup() } public override init(frame: CGRect) { super.init(frame: frame) setup() } func setup() { colors = [UIColor(red:0.95, green:0.40, blue:0.27, alpha:1.0), UIColor(red:1.00, green:0.78, blue:0.36, alpha:1.0), UIColor(red:0.48, green:0.78, blue:0.64, alpha:1.0), UIColor(red:0.30, green:0.76, blue:0.85, alpha:1.0), UIColor(red:0.58, green:0.39, blue:0.55, alpha:1.0)] intensity = 0.5 type = .Confetti } @objc public func startConfetti() -> Void { emitter = CAEmitterLayer() emitter.emitterPosition = CGPoint(x: self.center.x, y: 0) emitter.emitterShape = CAEmitterLayerEmitterShape.line emitter.emitterSize = CGSize(width: 40.0, height: 1) var cells = [CAEmitterCell]() for color in colors { cells.append(confettiWithColor(color: color)) } emitter.emitterCells = cells layer.addSublayer(emitter) let animation = CAKeyframeAnimation(keyPath: "birthRate") animation.duration = 1 animation.keyTimes = [0.5, 2.0] animation.values = [2.0, 0.0] animation.repeatCount = MAXFLOAT animation.delegate = self emitter.add(animation, forKey: "confettis") } override public func layoutSubviews() { super.layoutSubviews() emitter.emitterPosition = CGPoint(x: self.center.x, y: 0) } @objc public func stopConfetti() { emitter?.birthRate = 0 } func imageForType(type: ConfettiType) -> UIImage? { var fileName: String! switch type { case .Confetti: fileName = "confetti" case .Triangle: fileName = "triangle" case .Star: fileName = "star" case .Diamond: fileName = "diamond" case let .Image(customImage): return customImage } return UIImage(imageLiteralResourceName: fileName) } func confettiWithColor(color: UIColor) -> CAEmitterCell { let confetti = CAEmitterCell() confetti.birthRate = 6.0 * intensity confetti.lifetime = 14.0 * intensity confetti.lifetimeRange = 0 confetti.color = color.cgColor confetti.velocity = CGFloat(350.0 * intensity) confetti.velocityRange = CGFloat(80.0 * intensity) confetti.emissionLongitude = CGFloat(Double.pi) confetti.emissionRange = CGFloat(Double.pi / 4.0) confetti.spin = CGFloat(3.5 * intensity) confetti.spinRange = CGFloat(4.0 * intensity) confetti.scaleRange = CGFloat(intensity) confetti.scaleSpeed = CGFloat(-0.1 * intensity) confetti.contents = imageForType(type: type)!.cgImage return confetti } }
ecb8574afec712328b958356d5b6f62c
27.852459
70
0.578977
false
false
false
false
kinetic-fit/sensors-swift-trainers
refs/heads/master
Sources/SwiftySensorsTrainers/WahooTrainerSerializer.swift
mit
1
// // WahooTrainerSerializer.swift // SwiftySensorsTrainers // // https://github.com/kinetic-fit/sensors-swift-trainers // // Copyright © 2017 Kinetic. All rights reserved. // import Foundation import SwiftySensors /** Message Serializer / Deserializer for Wahoo Trainers. Work In Progress! */ open class WahooTrainerSerializer { open class Response { fileprivate(set) var operationCode: OperationCode! } public enum OperationCode: UInt8 { case unlock = 32 case setResistanceMode = 64 case setStandardMode = 65 case setErgMode = 66 case setSimMode = 67 case setSimCRR = 68 case setSimWindResistance = 69 case setSimGrade = 70 case setSimWindSpeed = 71 case setWheelCircumference = 72 } public static func unlockCommand() -> [UInt8] { return [ WahooTrainerSerializer.OperationCode.unlock.rawValue, 0xee, // unlock code 0xfc // unlock code ] } public static func setResistanceMode(_ resistance: Float) -> [UInt8] { let norm = UInt16((1 - resistance) * 16383) return [ WahooTrainerSerializer.OperationCode.setResistanceMode.rawValue, UInt8(norm & 0xFF), UInt8(norm >> 8 & 0xFF) ] } public static func setStandardMode(level: UInt8) -> [UInt8] { return [ WahooTrainerSerializer.OperationCode.setStandardMode.rawValue, level ] } public static func seErgMode(_ watts: UInt16) -> [UInt8] { return [ WahooTrainerSerializer.OperationCode.setErgMode.rawValue, UInt8(watts & 0xFF), UInt8(watts >> 8 & 0xFF) ] // response: 0x01 0x42 0x01 0x00 watts1 watts2 } public static func seSimMode(weight: Float, rollingResistanceCoefficient: Float, windResistanceCoefficient: Float) -> [UInt8] { // Weight units are Kg // TODO: Throw Error if weight, rrc or wrc are not within "sane" values let weightN = UInt16(max(0, min(655.35, weight)) * 100) let rrcN = UInt16(max(0, min(65.535, rollingResistanceCoefficient)) * 1000) let wrcN = UInt16(max(0, min(65.535, windResistanceCoefficient)) * 1000) return [ WahooTrainerSerializer.OperationCode.setSimMode.rawValue, UInt8(weightN & 0xFF), UInt8(weightN >> 8 & 0xFF), UInt8(rrcN & 0xFF), UInt8(rrcN >> 8 & 0xFF), UInt8(wrcN & 0xFF), UInt8(wrcN >> 8 & 0xFF) ] } public static func setSimCRR(_ rollingResistanceCoefficient: Float) -> [UInt8] { // TODO: Throw Error if rrc is not within "sane" value range let rrcN = UInt16(max(0, min(65.535, rollingResistanceCoefficient)) * 1000) return [ WahooTrainerSerializer.OperationCode.setSimCRR.rawValue, UInt8(rrcN & 0xFF), UInt8(rrcN >> 8 & 0xFF) ] } public static func setSimWindResistance(_ windResistanceCoefficient: Float) -> [UInt8] { // TODO: Throw Error if wrc is not within "sane" value range let wrcN = UInt16(max(0, min(65.535, windResistanceCoefficient)) * 1000) return [ WahooTrainerSerializer.OperationCode.setSimWindResistance.rawValue, UInt8(wrcN & 0xFF), UInt8(wrcN >> 8 & 0xFF) ] } public static func setSimGrade(_ grade: Float) -> [UInt8] { // TODO: Throw Error if grade is not between -1 and 1 let norm = UInt16((min(1, max(-1, grade)) + 1.0) * 65535 / 2.0) return [ WahooTrainerSerializer.OperationCode.setSimGrade.rawValue, UInt8(norm & 0xFF), UInt8(norm >> 8 & 0xFF) ] } public static func setSimWindSpeed(_ metersPerSecond: Float) -> [UInt8] { let norm = UInt16((max(-32.767, min(32.767, metersPerSecond)) + 32.767) * 1000) return [ WahooTrainerSerializer.OperationCode.setSimWindSpeed.rawValue, UInt8(norm & 0xFF), UInt8(norm >> 8 & 0xFF) ] } public static func setWheelCircumference(_ millimeters: Float) -> [UInt8] { let norm = UInt16(max(0, millimeters) * 10) return [ WahooTrainerSerializer.OperationCode.setWheelCircumference.rawValue, UInt8(norm & 0xFF), UInt8(norm >> 8 & 0xFF) ] } public static func readReponse(_ data: Data) -> Response? { let bytes = data.map { $0 } if bytes.count > 1 { let result = bytes[0] // 01 = success let opCodeRaw = bytes[1] if let opCode = WahooTrainerSerializer.OperationCode(rawValue: opCodeRaw) { let response: Response switch opCode { default: response = Response() } response.operationCode = opCode return response } else { SensorManager.logSensorMessage?("Unrecognized Operation Code: \(opCodeRaw)") } if result == 1 { SensorManager.logSensorMessage?("Success for operation: \(opCodeRaw)") } } return nil } }
a5e43bfa3203174e54411ecf364f7994
33.923567
131
0.563378
false
false
false
false
Johnykutty/SwiftLint
refs/heads/master
Source/SwiftLintFramework/Rules/RuleConfigurations/PrivateUnitTestConfiguration.swift
mit
2
// // PrivateUnitTestConfiguration.swift // SwiftLint // // Created by Cristian Filipov on 8/5/16. // Copyright © 2016 Realm. All rights reserved. // import Foundation import SourceKittenFramework public struct PrivateUnitTestConfiguration: RuleConfiguration, Equatable { public let identifier: String public var name: String? public var message = "Regex matched." public var regex: NSRegularExpression! public var included: NSRegularExpression? public var severityConfiguration = SeverityConfiguration(.warning) public var severity: ViolationSeverity { return severityConfiguration.severity } public var consoleDescription: String { return "\(severity.rawValue): \(regex.pattern)" } public var description: RuleDescription { return RuleDescription(identifier: identifier, name: name ?? identifier, description: "") } public init(identifier: String) { self.identifier = identifier } public mutating func apply(configuration: Any) throws { guard let configurationDict = configuration as? [String: Any] else { throw ConfigurationError.unknownConfiguration } if let regexString = configurationDict["regex"] as? String { regex = try .cached(pattern: regexString) } if let includedString = configurationDict["included"] as? String { included = try .cached(pattern: includedString) } if let name = configurationDict["name"] as? String { self.name = name } if let message = configurationDict["message"] as? String { self.message = message } if let severityString = configurationDict["severity"] as? String { try severityConfiguration.apply(configuration: severityString) } } } public func == (lhs: PrivateUnitTestConfiguration, rhs: PrivateUnitTestConfiguration) -> Bool { return lhs.identifier == rhs.identifier && lhs.message == rhs.message && lhs.regex == rhs.regex && lhs.included?.pattern == rhs.included?.pattern && lhs.severity == rhs.severity }
482106329bc111587590ee12f454a456
32.71875
97
0.665894
false
true
false
false
pr0gramm3r8hai/DGSegmentedControl
refs/heads/master
DGSegmentedControl/ViewController.swift
mit
1
// // ViewController.swift // DGSegmentedControl // // Created by dip on 2/17/16. // Copyright © 2016 apple. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var segmentedControl: DGSegmentedControl! @IBOutlet weak var displayGround: UIView! @IBOutlet weak var info: UILabel! override func viewDidLoad() { super.viewDidLoad() decorateSegmentedControl() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } //MARK:- Action @IBAction func segmentValueChanged(_ sender: AnyObject) { if sender.selectedIndex == 0{ self.displayGround.backgroundColor = UIColor.gray self.info.text = "First Segment selected" } else { self.displayGround.backgroundColor = UIColor(red: 0.761, green: 0.722, blue: 0.580, alpha: 1.00) self.info.text = "Second Segment selected" } } //MARK:- Segment control func decorateSegmentedControl(){ segmentedControl.items = ["First Segment","Second Segment"] segmentedControl.font = UIFont(name: "Avenir-Black", size: 12) segmentedControl.borderColor = UIColor(red: 0.988, green: 0.820, blue: 0.447, alpha: 1.00) segmentedControl.selectedIndex = 0 segmentedControl.borderSize = 2 segmentedControl.thumbColor = UIColor(red: 0.988, green: 0.820, blue: 0.447, alpha: 1.00) segmentedControl.selectedLabelColor = UIColor.black segmentedControl.thumUnderLineSize = 8 segmentedControl.font = UIFont.systemFont(ofSize: 18) self.segmentValueChanged(self.segmentedControl) } }
e48515b02a0d2a04fdc017119d72ef06
32.166667
108
0.651033
false
false
false
false
TeamDeverse/BC-Agora
refs/heads/master
BC-Agora/ViewController.swift
mit
1
// // ViewController.swift // BC-Agora // // Created by William Bowditch on 11/13/15. // Copyright © 2015 William Bowditch. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet var button: UIButton! @IBOutlet var bcLogo: UIImageView! @IBOutlet var user: UITextField! @IBOutlet var password: UITextField! @IBOutlet var wrongUser: UILabel! @IBOutlet var wrongPassword: UILabel! var json_dict = [:] override func viewDidLoad() { super.viewDidLoad() bcLogo.image = UIImage(named: "BostonCollegeEagles.svg") print("hello") let json_data = getJSON("https://raw.githubusercontent.com/TeamDeverse/BC-Agora/master/user_example.json") json_dict = getJSON_dict(json_data) //checkLogin() //self.navigationController!.navigationBar.titleTextAttributes = [ NSFontAttributeName: UIFont(name: "Georgia", size: 20)! ] navigationController!.navigationBar.barTintColor = UIColor(red: 0.5, green: 0.1, blue: 0.1, alpha: 1) let titleDict: NSDictionary = [NSForegroundColorAttributeName: UIColor.whiteColor(), NSFontAttributeName: UIFont(name: "Georgia-Bold", size: 20)!] self.navigationController!.navigationBar.titleTextAttributes = titleDict as? [String: AnyObject] //self.navigationController!.navigationBar.titleTextAttributes = [ NSFontAttributeName: UIFont(name: "Georgia", size: 20)!] navigationController?.navigationBar.tintColor = UIColor.whiteColor() //avigationController?.navigationBar.titleTextAttributes = titleDict as? [String: AnyObject] let cornerRadius : CGFloat = 5.0 let borderAlpha : CGFloat = 0.7 user.layer.borderWidth = 1.0 user.layer.borderColor = UIColor(white: 1.0, alpha: borderAlpha).CGColor user.layer.cornerRadius = cornerRadius user.backgroundColor = UIColor.clearColor() password.layer.borderWidth = 1.0 password.layer.borderColor = UIColor(white: 1.0, alpha: borderAlpha).CGColor password.layer.cornerRadius = cornerRadius password.backgroundColor = UIColor.clearColor() // Do any additional setup after loading the view, typically from a nib. // self.view.backgroundColor = UIColor(patternImage: UIImage(named: "gasson")!) UIGraphicsBeginImageContext(self.view.frame.size) UIImage(named: "gasson")?.drawInRect(self.view.bounds) let image: UIImage = UIGraphicsGetImageFromCurrentImageContext() let imageView = UIImageView(image: image) imageView.alpha = 0.9 UIGraphicsEndImageContext() self.view.insertSubview(imageView, atIndex: 0) //self.view.addSubview(imageView) print("test1") button.frame = CGRectMake(100, 100, 200, 40) button.setTitle("Login", forState: UIControlState.Normal) button.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal) button.backgroundColor = UIColor.clearColor() button.layer.borderWidth = 1.0 button.layer.borderColor = UIColor(white: 1.0, alpha: borderAlpha).CGColor button.layer.cornerRadius = cornerRadius //self.view.backgroundColor = UIColor(patternImage: image) //.colorWithAlphaComponent(0.7)// } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func getJSON(urlToRequest: String) -> NSData{ return NSData(contentsOfURL: NSURL(string: urlToRequest)!)! } func getJSON_dict(json_data: NSData) -> NSDictionary { do { if let jsonResult = try NSJSONSerialization.JSONObjectWithData(json_data, options: []) as? NSDictionary { return jsonResult //let k = jsonResult.allKeys //print(k) } } catch { print(error) } return [:] } @IBAction func pressLogin(sender: AnyObject) { self.wrongPassword.text?.removeAll() self.wrongUser.text?.removeAll() checkLogin() } func loadUserDefault() { //NSUser Default //PS file //run code before checkLogin code } func checkLogin(){ let user_data = json_dict["username"] as! String let pass_data = json_dict["password"]as! String print(user_data) print(pass_data) if self.user.text == "" { wrongUser.text = "Please enter a username." } if self.password.text == "" { wrongPassword.text = "Please enter a password." } if self.password.text != pass_data { wrongPassword.text = "Incorrect password" } if self.user.text! == user_data && self.password.text! == pass_data { print("correct") self.performSegueWithIdentifier("loginSegue", sender: nil) } else{ print(self.password.text) //print(pass_data) } print("working") } }
8b9b1901bbe76db5f1fdf16891842d9d
31.780488
154
0.606399
false
false
false
false
googlearchive/science-journal-ios
refs/heads/master
ScienceJournal/UI/DrawerView.swift
apache-2.0
1
/* * 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 import third_party_objective_c_material_components_ios_components_ShadowLayer_ShadowLayer import third_party_objective_c_material_components_ios_components_Tabs_Tabs /// A protocol for the drawer view to update its delegate about selected items. public protocol DrawerViewDelegate: class { /// Called when an item was selected. /// /// - Parameters: /// - drawerView: The drawer view. /// - index: The index of the item selected. func drawerView(_ drawerView: DrawerView, didSelectItemAtIndex index: Int) /// Called when the drawer is about to change its position. /// /// - Parameters: /// - drawerView: The drawer view. /// - position: The drawer position. func drawerView(_ drawerView: DrawerView, willChangePosition position: DrawerPosition) /// Called when the drawer changed its position. /// /// - Parameters: /// - drawerView: The drawer view. /// - position: The drawer position. func drawerView(_ drawerView: DrawerView, didChangePosition position: DrawerPosition) /// Called when the drawer is panning. /// /// - Parameters: /// - drawerView: The drawer view. func drawerViewIsPanning(_ drawerView: DrawerView) /// Called when the drawer view was panned upward beyond its bounds. /// /// - Parameters: /// - drawerView: The drawer view. /// - panDistance: The distance of the pan upward beyond the drawer's bounds. func drawerView(_ drawerView: DrawerView, didPanBeyondBounds panDistance: CGFloat) } /// A UIView subclass to wrap the drawer's grabber in an accessibility view with a custom activation /// action. class GrabberWrapperView: UIView { var activationEvent: (() -> Void)? override func accessibilityActivate() -> Bool { activationEvent?() return true } } // swiftlint:disable type_body_length /// A container view with a tab bar that slides up from the bottom over a parent view. Can be /// minimized (only shows the tab bar), cover the bottom half of the view or display fullscreen /// (parent view is hidden). open class DrawerView: UIView, MDCTabBarDelegate { // MARK: - Constants /// The background color of the drawer's main bar, which contains tabs. static let barBackgroundColor = UIColor(red: 0.196, green: 0.196, blue: 0.196, alpha: 1) /// The background color of the drawer's action bar. static let actionBarBackgroundColor = UIColor(red: 0.196, green: 0.196, blue: 0.196, alpha: 0.95) /// The background color to be used to darken the statusBar frame when the drawer is open to full. static let statusBarBackgroundColor = UIColor(red: 0.176, green: 0.176, blue: 0.176, alpha: 1) private enum Metrics { static let tabBarGrabberOriginY: CGFloat = 6 static let tabBarGrabberWrapperSize = CGSize(width: 30, height: 30) } // MARK: - Properties /// The panning view. let panningView = UIView() /// The tab bar. let tabBar = MDCTabBar() /// The recording indicator bar. let recordingBar = RecordingBar() /// Whether or not the drawer can be open half. This should be set to false when the device is in /// landscape. var canOpenHalf = true /// Whether or not the drawer can be open to a custom position. This should be set to false when /// the device is in landscape. var canOpenToCustomPosition = true /// Position of the drawer when it is fully open. let openFullPosition = DrawerPosition(canShowKeyboard: true) /// Position of the drawer when it is halfway open. let openHalfPosition = DrawerPosition(canShowKeyboard: false) /// Position of the drawer when it is when only the tab bar is showing. let peekingPosition = DrawerPosition(canShowKeyboard: false) { 0 } /// Whether or not the drawer is in sidebar mode. While it is, panning is not supported. var isDisplayedAsSidebar = false { didSet { grabber.isHidden = isDisplayedAsSidebar grabberWrapper.accessibilityElementsHidden = isDisplayedAsSidebar } } /// A custom drawer position for the drawer. Valid only if its pan distance falls between peeking /// and open full. fileprivate(set) var customPosition: DrawerPosition? /// The current drawer position. var currentPosition: DrawerPosition private weak var delegate: DrawerViewDelegate? // The content view for a view controller's view to be displayed. private let contentView = UIView() private let drawerItems: [DrawerItem] // The total available height the drawer view can fill, set externally in // `updateContentViewHeight()`. Used to determine the full height drawer position, as well as // content view height. private var availableHeight: CGFloat? // All drawer positions. private var drawerPositions: [DrawerPosition] { var positions = [peekingPosition, openFullPosition] if canOpenHalf { positions.append(openHalfPosition) } if canOpenToCustomPosition, let customPosition = customPosition { positions.append(customPosition) } positions.sort { $0.panDistance > $1.panDistance } return positions } // The distance between peeking and open full positions. private var maximumPanDistance: CGFloat { return peekingPosition.panDistance - openFullPosition.panDistance } // The percentage of the distance between pan positions that must be traveled to move to the next // pan position. private let panPercentage: CGFloat = 0.15 // The duration for the animation if the pan is from full to peeking. private let fullToPeekingAnimationDuration = 0.5 private let minimumAnimationDuration = 0.1 private let grabber = UIImageView(image: UIImage(named: "grabber")) private let grabberWrapper = GrabberWrapperView() private let tabBarShadowMetrics = MDCShadowMetrics(elevation: ShadowElevation.appBar.rawValue) private let tabBarWrapper = UIView() private var panningViewOriginY: CGFloat { return bounds.maxY - ViewConstants.toolbarHeight - safeAreaInsetsOrZero.bottom + currentPanDistance } private var currentPanDistance: CGFloat = 0 { didSet { // Update the panning view's y origin for the pan distance. panningView.frame.origin.y = panningViewOriginY // Pan distance is how far the panning view has moved up the screen (negative view coordinate // direction). The visible height of the content view is the same amount (but non-negative). contentView.frame.size.height = safeAreaInsetsOrZero.bottom + max(openHalfPosition.contentHeight, -currentPanDistance) updateDisplayedViewFrame() } } private var displayedView: UIView? // MARK: - Public /// Designated initializer. /// /// - Parameters: /// - items: The drawer items. /// - delegate: The delegate. public init(items: [DrawerItem], delegate: DrawerViewDelegate) { drawerItems = items self.delegate = delegate currentPosition = peekingPosition super.init(frame: .zero) // Set drawer position content height closures. openFullPosition.contentHeightClosure = { [unowned self] in var height: CGFloat { // The view height is adequate when `availableHeight` has not been set. However, // `availableHeight` should be used when set, because the view height sometimes includes the // status bar. guard let availableHeight = self.availableHeight else { return self.bounds.size.height } return availableHeight } return height - ViewConstants.toolbarHeight - self.safeAreaInsetsOrZero.top - self.safeAreaInsetsOrZero.bottom } openHalfPosition.contentHeightClosure = { [unowned self] in self.openFullPosition.contentHeight / 2 } let panGestureRecognizer = UIPanGestureRecognizer(target: self, action: #selector(handlePanGesture(_:))) addGestureRecognizer(panGestureRecognizer) configureView() } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override open func point(inside point: CGPoint, with event: UIEvent?) -> Bool { // Only count the panning view as part of the drawer view. return panningView.point(inside: convert(point, to: panningView), with: event) } override open func safeAreaInsetsDidChange() { setNeedsLayout() updateTabBarWrapperHeightForCurrentPosition() updateContentViewHeight() // If the safe area insets change, the drawer positions change. Pan to the correct distance for // the current drawer position. panToCurrentPosition(animated: false) } /// Adds a view as a subview of `contentView` and sets it to be full size. /// /// - Parameter view: The view to display. func displayViewInContentView(_ view: UIView) { contentView.addSubview(view) displayedView = view updateDisplayedViewFrame() } /// Pans the distance associated with the current position. Needed because the pan distance /// changes per position when the size of the view changes. /// /// - Parameter animated: Whether or not to animate. func panToCurrentPosition(animated: Bool) { panToPosition(currentPosition, animated: animated) } /// Pans to `position`, and captures the new position into `currentPosition`. /// /// - Parameters: /// - position: The position to animate to. /// - animated: Whether or not to animate. /// - completion: Called when the pan completes. func panToPosition(_ position: DrawerPosition, animated: Bool = true, completion: (() -> Void)? = nil) { // Calculate animation duration based on the remaining distance. let distanceRemaining = position.panDistance - currentPanDistance let remainingRatio = abs(distanceRemaining / maximumPanDistance) let duration = animated ? max(fullToPeekingAnimationDuration * Double(remainingRatio), minimumAnimationDuration) : 0 delegate?.drawerView(self, willChangePosition: position) let previousPosition = currentPosition currentPosition = position self.updateGrabberAccessibilityLabel() func animatePan(completion panCompletion: (() -> Void)? = nil) { UIView.animate(withDuration: duration, delay: 0, options: [.curveEaseOut], animations: { self.currentPanDistance = position.panDistance }, completion: { (_) in self.delegate?.drawerView(self, didChangePosition: self.currentPosition) self.accessibilityViewIsModal = (self.currentPosition == self.openFullPosition) && UIDevice.current.userInterfaceIdiom != .pad panCompletion?() completion?() }) } if previousPosition == peekingPosition { updateTabBarWrapperHeight(expanded: position == peekingPosition, animated: true) animatePan() } else { animatePan(completion: { self.updateTabBarWrapperHeight(expanded: position == self.peekingPosition, animated: true) }) } } // Updates the accessibility label of the grabber wrapper based on the drawer's current position. private func updateGrabberAccessibilityLabel() { var label = "\(String.drawerGrabberContentDescription), " switch currentPosition { case openFullPosition: label += String.drawerGrabberPositionFullContentDescription case openHalfPosition: label += String.drawerGrabberPositionHalfContentDescription case peekingPosition: label += String.drawerGrabberPositionClosedContentDescription default: label += String.drawerGrabberPositionCustomContentDescription } grabberWrapper.accessibilityLabel = label } /// Completes the pan by snapping to the proper drawer position. /// /// - Parameter velocity: The ending velocity of the pan. func completePan(withVelocity velocity: CGFloat) { let isVelocityHigh = abs(velocity) > 500 // Is the drawer's pan distance below the pan distance of the previous position? If not, it is // above or at the same position. let isDrawerBelowPreviousPosition = currentPanDistance > currentPosition.panDistance // Was the ending velocity in the opposite direction than the current pan distance of the // drawer? If so, return to the previous position if the velocity was high enough. let isVelocityOpposingPanDirection = isDrawerBelowPreviousPosition && velocity < 0 || !isDrawerBelowPreviousPosition && velocity > 0 if isVelocityOpposingPanDirection && isVelocityHigh { panToCurrentPosition(animated: true) } else { let position = nextPosition(below: isDrawerBelowPreviousPosition, withPanDistance: currentPanDistance, skipDistanceCheck: isVelocityHigh) panToPosition(position) } } /// Pans the drawer by a distance. /// /// - Parameter distance: The distance to pan the drawer. func pan(distance: CGFloat) { // Update the panning view's pan distance to a value clamped between open full and peeking. let clampedPanDistance = (openFullPosition.panDistance...peekingPosition.panDistance).clamp( panDistance(withAdditionalPan: distance)) currentPanDistance = clampedPanDistance } /// Whether or not the content view is visible. var isContentViewVisible: Bool { return currentPanDistance < 0 } /// The visible height of the drawer, including the toolbar. var visibleHeight: CGFloat { return alpha == 0 ? 0 : ViewConstants.toolbarHeight - currentPanDistance } /// The visible height of the drawer's content view. var visibleContentHeight: CGFloat { return alpha == 0 ? 0 : -currentPanDistance } /// Sets the available height and updates content view height. This needs to be set when the view /// frame is updated. func setAvailableHeight(_ height: CGFloat) { // Only update content view height if the view height is greater than 0 and is not the same as // it was the last time it was set. guard height > 0 && (availableHeight == nil || height > availableHeight! || height < availableHeight!) else { return } availableHeight = height updateContentViewHeight() } /// Sets the custom drawer position. Only valid if its pan distance falls between peeking and open /// full. /// /// - Parameter customPosition: The custom drawer position. func setCustomPosition(_ position: DrawerPosition) { guard position.panDistance < peekingPosition.panDistance && position.panDistance > openFullPosition.panDistance else { return } customPosition = position } /// Removes the custom drawer position. func removeCustomPosition() { customPosition = nil } /// Whether or not the drawer has a custom position set. var hasCustomPosition: Bool { return customPosition != nil } /// Resets the available height, since it is shared for all experiments. func resetHeight() { availableHeight = nil } /// Updates the drawer's shadow to show or not depending on position. /// /// - Parameter position: The new drawer position. func updateDrawerShadow(for position: DrawerPosition) { var newOpacity: Float if position == openFullPosition { newOpacity = 0 } else { newOpacity = tabBarShadowMetrics.bottomShadowOpacity } guard newOpacity != self.tabBarWrapper.layer.shadowOpacity else { return } UIView.animate(withDuration: 0.15) { self.tabBarWrapper.layer.shadowOpacity = newOpacity } } override open func accessibilityPerformEscape() -> Bool { // If the drawer is open full, allow the escape gesture to bring it to half. if currentPosition == openFullPosition { panToPosition(openHalfPosition) return true } return false } override open func layoutSubviews() { super.layoutSubviews() // Panning view. panningView.frame = CGRect(x: 0, y: panningViewOriginY, width: bounds.width, height: bounds.height) // Tab bar. tabBarWrapper.frame.size.width = panningView.bounds.width let tabBarHeight = MDCTabBar.defaultHeight(for: .images) // The tab bar should be layed out at the bottom of the global toolbar height. let tabBarMinY = ViewConstants.toolbarHeight - tabBarHeight tabBar.frame = CGRect(x: safeAreaInsetsOrZero.left, y: tabBarMinY, width: tabBarWrapper.bounds.width - safeAreaInsetsOrZero.left - safeAreaInsetsOrZero.right, height: tabBarHeight) // Tab bar grabber. grabber.frame = CGRect(x: (bounds.width - grabber.frame.width) / 2, y: Metrics.tabBarGrabberOriginY, width: grabber.frame.width, height: grabber.frame.height) grabberWrapper.frame = CGRect(x: grabber.frame.midX - Metrics.tabBarGrabberWrapperSize.width / 2, y: grabber.frame.midY - Metrics.tabBarGrabberWrapperSize.height / 2, width: Metrics.tabBarGrabberWrapperSize.width, height: Metrics.tabBarGrabberWrapperSize.height) // Content view. contentView.frame.origin.y = tabBarWrapper.frame.maxY contentView.frame.size.width = panningView.bounds.width displayedView?.frame = contentView.bounds // Recording bar. recordingBar.frame.origin.y = tabBarWrapper.frame.maxY recordingBar.frame.size.width = panningView.bounds.width } // MARK: - Private private func configureView() { // Panning view. addSubview(panningView) // Tab bar. tabBarWrapper.backgroundColor = DrawerView.barBackgroundColor panningView.addSubview(tabBarWrapper) updateTabBarWrapperHeightForCurrentPosition() tabBar.delegate = self tabBar.items = drawerItems.enumerated().map { (index, item) in UITabBarItem(title: item.accessibilityLabel, image: item.tabBarImage, tag: index) } tabBar.disableScrolling() tabBar.barTintColor = DrawerView.barBackgroundColor tabBar.inkColor = .clear tabBar.itemAppearance = .images tabBar.tintColor = .white tabBar.selectedItemTintColor = .white tabBar.unselectedItemTintColor = UIColor(red: 0.510, green: 0.518, blue: 0.522, alpha: 1.0) tabBarWrapper.addSubview(tabBar) // Customize the MDCShadow metrics to put the shadow above the tab bar, but use the same metrics // as a normal app bar shadow. tabBarWrapper.layer.shadowOffset = CGSize(width: tabBarShadowMetrics.bottomShadowOffset.width, height: -tabBarShadowMetrics.bottomShadowOffset.height) tabBarWrapper.layer.shadowRadius = tabBarShadowMetrics.bottomShadowRadius tabBarWrapper.layer.shadowOpacity = tabBarShadowMetrics.bottomShadowOpacity tabBarWrapper.layer.shouldRasterize = true tabBarWrapper.layer.rasterizationScale = UIScreen.main.scale // Tab bar grabber. panningView.addSubview(grabber) grabber.tintColor = UIColor(red: 0.388, green: 0.396, blue: 0.396, alpha: 1.0) // Tab bar wrapping view for accessibility purposes. Creates a larger tap target for the // grabber and gives it both a label and hint which describes its current position. Also adds // a custom a11y action which moves the drawer to the next best position. panningView.addSubview(grabberWrapper) grabberWrapper.isUserInteractionEnabled = false grabberWrapper.isAccessibilityElement = true grabberWrapper.accessibilityLabel = String.drawerGrabberContentDescription grabberWrapper.accessibilityHint = String.drawerGrabberContentDetails grabberWrapper.activationEvent = { [weak self] in self?.panToNextAccessibilityPosition() } // Content view. contentView.clipsToBounds = true contentView.backgroundColor = .white panningView.insertSubview(contentView, belowSubview: tabBarWrapper) // Recording bar. recordingBar.sizeToFit() panningView.insertSubview(recordingBar, aboveSubview: tabBarWrapper) } /// The next position for the drawer based on pan position and whether to return the next position /// below or above. /// /// - Parameters: /// - below: Whether the next position should be below the current position. Otherwise above. /// - panDistance: The pan distance of the panning view. /// - isSkippingDistanceCheck: If true, the next position will be returned regardless of how far /// away it is. /// - Returns: The position. private func nextPosition(below: Bool, withPanDistance panDistance: CGFloat, skipDistanceCheck isSkippingDistanceCheck: Bool) -> DrawerPosition { // If the position is above open full, return open full. if panDistance < openFullPosition.panDistance { return openFullPosition } // If the position is below peeking, return peeking. if panDistance > peekingPosition.panDistance { return peekingPosition } // If moving to the next position below the previous one, reverse the order of the positions. let orderedPositions = below ? drawerPositions.reversed() : drawerPositions // The index of the next position. var nextPositionIndex: Int { // Current position index. guard let indexOfCurrentPosition = orderedPositions.firstIndex(where: { $0 == currentPosition }) else { return 0 } // Next position index is +1 from the current index. let nextPositionIndex = indexOfCurrentPosition + 1 // The next index can't be beyond the last index. guard nextPositionIndex < orderedPositions.endIndex else { return orderedPositions.endIndex - 1 } return nextPositionIndex } // Check positions that are beyond the pan distance. let positionsToCheck = orderedPositions[nextPositionIndex...orderedPositions.endIndex - 1] // Check each position. If it is far enough away from the current position, return it. If none // are, return the previous position. var position = currentPosition for nextPosition in positionsToCheck { if isSkippingDistanceCheck { if below && nextPosition.panDistance > currentPanDistance || !below && nextPosition.panDistance < currentPanDistance { // If overriding the distance check, use this position if it is beyond the pan distance. return nextPosition } else { continue } } if below { let distanceBetween = nextPosition.panDistance - position.panDistance let farEnoughForNextPosition = position.panDistance + distanceBetween * panPercentage if panDistance > farEnoughForNextPosition { position = nextPosition continue } } else { let distanceBetween = position.panDistance - nextPosition.panDistance let farEnoughForNextPosition = position.panDistance - distanceBetween * panPercentage if panDistance < farEnoughForNextPosition { position = nextPosition continue } } break } return position } /// Attempts to determine the best next drawer position based on its current position and then /// pans to it. Only used when accessibility-based events change the drawer /// position. private func panToNextAccessibilityPosition() { var nextPosition = openHalfPosition if currentPosition == openFullPosition { nextPosition = peekingPosition } else if currentPosition == customPosition { nextPosition = openFullPosition } else if currentPosition == peekingPosition { nextPosition = openHalfPosition } else if currentPosition == openHalfPosition { nextPosition = openFullPosition } panToPosition(nextPosition) } // The pan distance of the panning view added to an additional pan distance. private func panDistance(withAdditionalPan pan: CGFloat) -> CGFloat { return currentPosition.panDistance + pan } /// Updates the tab bar wrapper height. /// /// - Parameters: /// - expanded: Whether or not it should expand into the bottom safe area inset. /// - animated: Whether or not to animate the change. /// - additionalHeight: Any additional height to add to the wrapper's height. private func updateTabBarWrapperHeight(expanded: Bool, animated: Bool = false, additionalHeight: CGFloat = 0) { let newHeight = ViewConstants.toolbarHeight + (expanded ? safeAreaInsetsOrZero.bottom + additionalHeight : 0) guard newHeight < tabBarWrapper.frame.height || newHeight > tabBarWrapper.frame.height else { return } let duration = animated ? (expanded ? 0.05 : 0.1) : 0 UIView.animate(withDuration: duration, delay: 0, options: .curveEaseOut, animations: { self.tabBarWrapper.frame.size.height = newHeight self.setNeedsLayout() }) } private func updateTabBarWrapperHeightForCurrentPosition(animated: Bool = false) { updateTabBarWrapperHeight(expanded: currentPosition == peekingPosition, animated: animated) } private func updateContentViewHeight() { contentView.frame.size.height = safeAreaInsetsOrZero.bottom + max(openHalfPosition.contentHeight, currentPosition.contentHeight) updateDisplayedViewFrame() } private func updateDisplayedViewFrame() { displayedView?.frame = contentView.bounds displayedView?.layoutIfNeeded() } // MARK: - Gesture recognizer @objc private func handlePanGesture(_ panGestureRecognizer: UIPanGestureRecognizer) { guard !isDisplayedAsSidebar else { return } let gestureDistance = panGestureRecognizer.translation(in: self).y let totalPanDistance = panDistance(withAdditionalPan: gestureDistance) // Expand the tab bar wrapper when pan distance is within 1 of its original position, otherwise // collapse it. This is to handle showing/hiding the expanded portion while panning is still // occuring, before the animation to the final position has begun. Pass along the remaining // pan distance as additional height, to ensure the space below the tab bar is fully covered by // the wrapper view. updateTabBarWrapperHeight(expanded: totalPanDistance > -1, animated: true, additionalHeight: abs(totalPanDistance)) switch panGestureRecognizer.state { case .changed: pan(distance: gestureDistance) delegate?.drawerViewIsPanning(self) let panDistanceBeyondBounds = -totalPanDistance - openFullPosition.contentHeight if panDistanceBeyondBounds > 0 { delegate?.drawerView(self, didPanBeyondBounds: panDistanceBeyondBounds) } case .ended: completePan(withVelocity: panGestureRecognizer.velocity(in: self).y) default: break } } // MARK: - MDCTabBarDelegate public func tabBar(_ tabBar: MDCTabBar, didSelect item: UITabBarItem) { self.delegate?.drawerView(self, didSelectItemAtIndex: item.tag) } }
94755267afc30720288759d316e13ee6
37.44675
100
0.700975
false
false
false
false
airspeedswift/swift
refs/heads/master
test/IDE/complete_attributes.swift
apache-2.0
12
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=TOP_LEVEL_ATTR_1 -code-completion-keywords=false | %FileCheck %s -check-prefix=ERROR_COMMON // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=MEMBER_DECL_ATTR_1 -code-completion-keywords=false | %FileCheck %s -check-prefix=ERROR_COMMON // ERROR_COMMON: found code completion token // ERROR_COMMON-NOT: Keyword/ @#^TOP_LEVEL_ATTR_1^# class TopLevelDeclAttr1 {} class MemberDeclAttribute { @#^MEMBER_DECL_ATTR_1^# func memberDeclAttr1() {} }
ed0207c995ca9f294d147f60c73176c8
51.454545
184
0.750433
false
true
false
false
klevison/AccordionTableViewController
refs/heads/master
Classes/AccordionTableViewController.swift
mit
1
// // Accordion.swift // AccordionTableViewController // // Created by Klevison Matias on 1/6/17. // Copyright © 2017 Klevison. All rights reserved. // import UIKit //MARK: AccordionTableViewController protocol AccordionTableViewControllerDelegate: class { func accordionTableViewControllerSectionDidOpen(section: Section) func accordionTableViewControllerSectionDidClose(section: Section) } class AccordionTableViewController: UITableViewController { var openAnimation: UITableViewRowAnimation = .fade var closeAnimation: UITableViewRowAnimation = .fade var sections = [Section]() var oneSectionAlwaysOpen = false weak var delegate: AccordionTableViewControllerDelegate? fileprivate let sectionHeaderViewIdentifier = "SectionHeaderViewIdentifier" fileprivate let sectionCellID = "CellIdentifier" var openedSection: Section? { return sections .filter { $0.open == true } .first } override func viewDidLoad() { super.viewDidLoad() setupTableView() } private func setupTableView() { let sectionHeaderNib = UINib(nibName: "SectionHeaderView", bundle: nil) tableView.register(sectionHeaderNib, forHeaderFooterViewReuseIdentifier: sectionHeaderViewIdentifier) tableView.bounces = false tableView.separatorStyle = .none } func reloadOpenedSection() { openedSection .flatMap { [IndexPath(row: 0, section: $0.sectionIndex!)] } .map { tableView.reloadRows(at: $0, with: openAnimation) } } private func indexPathsToDelete() -> [IndexPath] { if let previousOpenSection = openedSection, let previousOpenSectionIndex = previousOpenSection.sectionIndex { return [IndexPath(row: 0, section: previousOpenSectionIndex)] } return [IndexPath]() } private func updateTable(insert indexPathsToInsert: [IndexPath], delete indexPathsToDelete: [IndexPath]) { tableView.beginUpdates() tableView.insertRows(at: indexPathsToInsert, with: openAnimation) tableView.deleteRows(at: indexPathsToDelete, with: closeAnimation) tableView.endUpdates() let sectionRect = tableView.rect(forSection: indexPathsToInsert[0].section) tableView.scrollRectToVisible(sectionRect, animated: true) if let index = indexPathsToInsert.first?.section { delegate?.accordionTableViewControllerSectionDidOpen(section: sections[index]) } if let index = indexPathsToDelete.first?.section { delegate?.accordionTableViewControllerSectionDidClose(section: sections[index]) } } func openSection(at index: Int) { let indexPathsToInsert = [IndexPath(row: 0, section: index)] let indexPathsToDelete = self.indexPathsToDelete() if let previousOpenSection = openedSection, let previousOpenSectionIndex = previousOpenSection.sectionIndex { previousOpenSection.open = false guard let praviousSectionHeaderView = tableView.headerView(forSection: previousOpenSectionIndex) as? SectionHeaderView else { return } praviousSectionHeaderView.disclosureButton.isSelected = false delegate?.accordionTableViewControllerSectionDidClose(section: previousOpenSection) } sections[index].open = true updateTable(insert: indexPathsToInsert, delete: indexPathsToDelete) } func closeSection(at index: Int) { let currentSection = sections[index] currentSection.open = false if tableView.numberOfRows(inSection: index) > 0 { var indexPathsToDelete = [IndexPath]() indexPathsToDelete.append(IndexPath(row: 0, section: index)) tableView.deleteRows(at: indexPathsToDelete, with: closeAnimation) } delegate?.accordionTableViewControllerSectionDidClose(section: currentSection) } } extension AccordionTableViewController { override func numberOfSections(in tableView: UITableView) -> Int { return sections.count } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if sections[section].open { return 1 } return 0 } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let section = sections[indexPath.section] let cellIdentifier = "\(sectionCellID)\(section.sectionIndex!)" tableView.register(UITableViewCell.self, forCellReuseIdentifier: cellIdentifier) let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as UITableViewCell cell.contentView.addSubview(section.view!) cell.contentView.autoresizesSubviews = false cell.contentView.frame = section.view!.frame return cell } override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return sections[indexPath.section].view?.frame.size.height ?? 0 } override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return sections[section].appearance.headerHeight } override func tableView(_ tableView: UITableView, shouldHighlightRowAt indexPath: IndexPath) -> Bool { return false } override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { guard let sectionHeaderView = tableView.dequeueReusableHeaderFooterView(withIdentifier: sectionHeaderViewIdentifier) as? SectionHeaderView else { return nil } let currentSection = sections[section] if currentSection.backgroundColor != nil { currentSection.appearance.headerColor = currentSection.backgroundColor! } currentSection.sectionIndex = section currentSection.headerView = sectionHeaderView sectionHeaderView.headerSectionAppearence = currentSection.appearance sectionHeaderView.titleLabel.text = currentSection.title sectionHeaderView.section = section sectionHeaderView.delegate = self sectionHeaderView.disclosureButton.isSelected = currentSection.open //TODO: refact it if let overlayView = currentSection.overlayView { sectionHeaderView.addOverHeaderSubView(view: overlayView) } if oneSectionAlwaysOpen && section == 0 && openedSection == nil{ openSection(at: section) sectionHeaderView.disclosureButton.isSelected = true } return sectionHeaderView } } extension AccordionTableViewController: SectionHeaderViewDelegate { func sectionHeaderView(sectionHeaderView: SectionHeaderView, selectedAtIndex index: Int) { let section = sections[index] if !section.open { openSection(at: index) sectionHeaderView.disclosureButton.isSelected = true } else if !oneSectionAlwaysOpen { closeSection(at: index) sectionHeaderView.disclosureButton.isSelected = oneSectionAlwaysOpen && openedSection?.sectionIndex == index } } } //MARK: Section final class Section { var open = false var view: UIView? var overlayView: UIView? var headerView: SectionHeaderView? var title: String? var backgroundColor: UIColor? var sectionIndex: Int? var appearance = Appearance() } //MARK: Appearance final class Appearance { var headerHeight = CGFloat(50) var headerFont = UIFont.systemFont(ofSize: 15) var headerTitleColor = UIColor.black var headerColor = UIColor.white var headerSeparatorColor = UIColor.black var headerArrowImageOpened = #imageLiteral(resourceName: "carat") var headerArrowImageClosed = #imageLiteral(resourceName: "carat-open") } //MARK: SectionHeaderView protocol SectionHeaderViewDelegate: class { func sectionHeaderView(sectionHeaderView: SectionHeaderView, selectedAtIndex index: NSInteger) } final class SectionHeaderView: UITableViewHeaderFooterView { @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var disclosureButton: UIButton! @IBOutlet weak var headerSeparatorView: UIView! @IBOutlet weak var backgroundHeaderView: UIView! @IBOutlet weak var overHeaderView: UIView! weak var delegate: SectionHeaderViewDelegate? var section: NSInteger? var headerSectionAppearence: Appearance? { didSet { headerSeparatorView.backgroundColor = headerSectionAppearence!.headerSeparatorColor backgroundHeaderView.backgroundColor = headerSectionAppearence!.headerColor titleLabel.font = headerSectionAppearence!.headerFont titleLabel.textColor = headerSectionAppearence!.headerTitleColor disclosureButton.setImage(headerSectionAppearence!.headerArrowImageOpened, for: .normal) disclosureButton.setImage(headerSectionAppearence!.headerArrowImageClosed, for: .selected) } } override func awakeFromNib() { super.awakeFromNib() let tapGesture = UITapGestureRecognizer(target: self, action: #selector(SectionHeaderView.toggleOpen(_:))) self.addGestureRecognizer(tapGesture) } override func prepareForReuse() { super.prepareForReuse() overHeaderView.subviews.forEach { $0.removeFromSuperview() } } func addOverHeaderSubView(view: UIView) { self.overHeaderView.addSubview(view) } @IBAction func toggleOpen(_ sender: AnyObject) { delegate?.sectionHeaderView(sectionHeaderView: self, selectedAtIndex: section!) } }
3b22100e3245542aa4d1c97f56f25853
35.156134
153
0.708102
false
false
false
false
Palleas/Synchronizable
refs/heads/master
Synchronizable/Synchronizable.swift
mit
1
// // Synchronizable.swift // Synchronizable // // Created by Romain Pouclet on 2016-09-04. // Copyright © 2016 Perfectly-Cooked. All rights reserved. // import Foundation protocol Identifiable { var identifier: String { get } } extension Identifiable { func isEqual(to identifiable: Identifiable) -> Bool { return identifier == identifiable.identifier } } protocol Synchronizable: Identifiable { associatedtype PersistedType: Persistable func compare(against persistable: PersistedType) -> Diff<Self> } protocol Persistable: Identifiable { } enum Diff<S: Synchronizable> { case insert(S) case update(S) case delete(identifier: String) case none var key: String { switch self { case .insert(_): return "Insert" case .update(_): return "Update" case .delete(_): return "Delete" case .none: return "None" } } } extension Diff { static func reducer<P: Persistable, S: Synchronizable>(_ local: [P], remote: [S]) -> [Diff<S>] where S.PersistedType == P { let persistedIds = Set(local.map { $0.identifier }) let synchronizedIds = Set(remote.map { $0.identifier }) let deleted: [Diff<S>] = persistedIds.subtracting(synchronizedIds).map { .delete(identifier: $0) } return deleted + remote .map { synchronized in if !persistedIds.contains(synchronized.identifier) { return .insert(synchronized) } if let persisted = local.filter({ synchronized.isEqual(to: $0) }).first { return synchronized.compare(against: persisted) } return .none } } }
9380a7e66a20962775051725803e0d45
24.144928
127
0.610375
false
false
false
false
cikelengfeng/Jude
refs/heads/master
Jude/Antlr4/atn/LexerTypeAction.swift
mit
2
/// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. /// Use of this file is governed by the BSD 3-clause license that /// can be found in the LICENSE.txt file in the project root. /// Implements the {@code type} lexer action by calling {@link org.antlr.v4.runtime.Lexer#setType} /// with the assigned type. /// /// - Sam Harwell /// - 4.2 public class LexerTypeAction: LexerAction, CustomStringConvertible { fileprivate final var type: Int /// Constructs a new {@code type} action with the specified token type value. /// - parameter type: The type to assign to the token using {@link org.antlr.v4.runtime.Lexer#setType}. public init(_ type: Int) { self.type = type } /// Gets the type to assign to a token created by the lexer. /// - returns: The type to assign to a token created by the lexer. public func getType() -> Int { return type } /// {@inheritDoc} /// - returns: This method returns {@link org.antlr.v4.runtime.atn.LexerActionType#TYPE}. public override func getActionType() -> LexerActionType { return LexerActionType.type } /// {@inheritDoc} /// - returns: This method returns {@code false}. override public func isPositionDependent() -> Bool { return false } /// {@inheritDoc} /// /// <p>This action is implemented by calling {@link org.antlr.v4.runtime.Lexer#setType} with the /// value provided by {@link #getType}.</p> public override func execute(_ lexer: Lexer) { lexer.setType(type) } override public var hashValue: Int { var hash: Int = MurmurHash.initialize() hash = MurmurHash.update(hash, getActionType().rawValue) hash = MurmurHash.update(hash, type) return MurmurHash.finish(hash, 2) } public var description: String { return "type(\(type))" } } public func ==(lhs: LexerTypeAction, rhs: LexerTypeAction) -> Bool { if lhs === rhs { return true } return lhs.type == rhs.type }
9a2b050151e00a13dfe87fe7e60055a2
27.929577
107
0.63778
false
false
false
false
shu223/ARKit-Sampler
refs/heads/master
common/ARPlaneAnchor+Visualize.swift
mit
1
// // ARPlaneAnchor+Visualize.swift // // Created by Shuichi Tsutsumi on 2017/08/29. // Copyright © 2017 Shuichi Tsutsumi. All rights reserved. // import Foundation import ARKit extension ARPlaneAnchor { @discardableResult func addPlaneNode(on node: SCNNode, geometry: SCNGeometry, contents: Any) -> SCNNode { guard let material = geometry.materials.first else { fatalError() } if let program = contents as? SCNProgram { material.program = program } else { material.diffuse.contents = contents } let planeNode = SCNNode(geometry: geometry) DispatchQueue.main.async(execute: { node.addChildNode(planeNode) }) return planeNode } func addPlaneNode(on node: SCNNode, contents: Any) { let geometry = SCNPlane(width: CGFloat(extent.x), height: CGFloat(extent.z)) let planeNode = addPlaneNode(on: node, geometry: geometry, contents: contents) planeNode.transform = SCNMatrix4MakeRotation(-Float.pi / 2.0, 1, 0, 0) } func findPlaneNode(on node: SCNNode) -> SCNNode? { for childNode in node.childNodes { if childNode.geometry as? SCNPlane != nil { return childNode } } return nil } func findShapedPlaneNode(on node: SCNNode) -> SCNNode? { for childNode in node.childNodes { if childNode.geometry as? ARSCNPlaneGeometry != nil { return childNode } } return nil } @available(iOS 11.3, *) func findPlaneGeometryNode(on node: SCNNode) -> SCNNode? { for childNode in node.childNodes { if childNode.geometry as? ARSCNPlaneGeometry != nil { return childNode } } return nil } @available(iOS 11.3, *) func updatePlaneGeometryNode(on node: SCNNode) { DispatchQueue.main.async(execute: { guard let planeGeometry = self.findPlaneGeometryNode(on: node)?.geometry as? ARSCNPlaneGeometry else { return } planeGeometry.update(from: self.geometry) }) } func updatePlaneNode(on node: SCNNode) { DispatchQueue.main.async(execute: { guard let plane = self.findPlaneNode(on: node)?.geometry as? SCNPlane else { return } guard !PlaneSizeEqualToExtent(plane: plane, extent: self.extent) else { return } plane.width = CGFloat(self.extent.x) plane.height = CGFloat(self.extent.z) }) } } fileprivate func PlaneSizeEqualToExtent(plane: SCNPlane, extent: vector_float3) -> Bool { if plane.width != CGFloat(extent.x) || plane.height != CGFloat(extent.z) { return false } else { return true } }
a4355c851754438fb0566eb115269ccc
30.230769
123
0.601337
false
false
false
false
Erez-Panda/LiveBankSDK
refs/heads/master
Pod/Classes/PassiveLinearInterpView.swift
mit
1
// // LinearInterpView.swift // Panda4rep // // Created by Erez Haim on 5/8/15. // Copyright (c) 2015 Erez. All rights reserved. // import UIKit class PassiveLinearInterpView: UIView { var path : UIBezierPath? var enabled = false // Only override drawRect: if you perform custom drawing. // An empty implementation adversely affects performance during animation. override func drawRect(rect: CGRect) { SignColors.sharedInstance.uicolorFromHex(0x000F7D).setStroke() path?.stroke() // Drawing code } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) initPath() } required override init(frame: CGRect) { super.init(frame: frame) initPath() } func initPath(){ self.multipleTouchEnabled = false self.backgroundColor = UIColor.clearColor() path = UIBezierPath() path?.lineWidth = 1.0 } func moveToPoint(point: CGPoint){ path?.moveToPoint(point) } func addPoint(point: CGPoint){ path?.addLineToPoint(point) self.setNeedsDisplay() } func cleanView(){ self.path?.removeAllPoints() self.setNeedsDisplay() } }
693e12e249d9bf01ea0ad75f6dda9693
20.661017
78
0.607981
false
false
false
false
korrolion/smartrate
refs/heads/master
Example/SmartRate/ViewController.swift
mit
1
// // ViewController.swift // SmartRate // // Created by korrolion on 07/17/2017. // Copyright (c) 2017 korrolion. All rights reserved. // import UIKit class ViewController: UIViewController { static let breakNotificationName = Notification.Name("breakNotification") static let step1NotificationName = Notification.Name("step1Notification") static let step2NotificationName = Notification.Name("step2Notification") static let step3NotificationName = Notification.Name("step3Notification") static let duplicateActionNotificationName = NSNotification.Name("duplicateActionNotification") override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } @IBAction private func breakAction() { NotificationCenter.default.post(Notification(name: ViewController.breakNotificationName)) } @IBAction private func step1Action() { NotificationCenter.default.post(Notification(name: ViewController.step1NotificationName)) } @IBAction private func step2Action() { NotificationCenter.default.post(Notification(name: ViewController.step2NotificationName)) } @IBAction private func step3Action() { NotificationCenter.default.post(Notification(name: ViewController.step3NotificationName)) } @IBAction private func pressAction() { NotificationCenter.default.post(Notification(name: ViewController.duplicateActionNotificationName)) } }
428fc10a5db3e8fee7af83160a806042
31.978723
107
0.731613
false
false
false
false
Swiftline/Swiftline
refs/heads/master
SwiftlineTests/SwiftlineTests/AgreeTests.swift
apache-2.0
4
import Foundation import Quick import Nimble @testable import Swiftline class AgreeTest: QuickSpec { override func spec() { var promptPrinter: DummyPromptPrinter! beforeEach { promptPrinter = DummyPromptPrinter() PromptSettings.printer = promptPrinter } it("returns true if yes is passed") { PromptSettings.reader = DummyPromptReader(toReturn: "Yes") let ret = agree("Are you a test?") expect(ret).to(equal(true)) expect(promptPrinter.printed).to(equal("Are you a test? ")) } it("returns true if n is passed") { PromptSettings.reader = DummyPromptReader(toReturn: "n") let ret = agree("Are you a test?") expect(ret).to(equal(false)) expect(promptPrinter.printed).to(equal("Are you a test? ")) } it("keeps asking if wrong parameter are passed") { PromptSettings.reader = DummyPromptReader(toReturn: "a", "n") let ret = agree("Are you a test?") expect(ret).to(equal(false)) let prompts = "Are you a test? Please enter \"yes\" or \"no\".\nAre you a test? " expect(promptPrinter.printed).to(equal(prompts)) } } }
bcdd021abe6618035122d7464a79f7d1
30.111111
95
0.532857
false
true
false
false
prasanth223344/celapp
refs/heads/master
Cgrams/ATSketchKit/ATColorPicker.swift
mit
1
// // ATColorPicker.swift // ATSketchKit // // Created by Arnaud Thiercelin on 1/17/16. // Copyright © 2016 Arnaud Thiercelin. 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. import UIKit /** This class provides a basic view to pick a new color using a color map */ @IBDesignable public class ATColorPicker: UIView { public var delegate: ATColorPickerDelegate? public enum ColorSpace { case hsv case custom } public var colorSpace = ColorSpace.hsv public override init(frame: CGRect) { super.init(frame: frame) self.configure() } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.configure() } func configure() { } // MARK: - Drawing public override func draw(_ rect: CGRect) { self.drawColorMap(rect) } func drawColorMap(_ rect: CGRect) { let context = UIGraphicsGetCurrentContext() for x in 0..<Int(rect.size.width) { for y in 0..<Int(rect.size.height) { let point = CGPoint(x: CGFloat(x), y: CGFloat(y)) let color = colorAtPoint(point, inRect: rect) color.setFill() let rect = CGRect(x: CGFloat(x), y: CGFloat(y), width: 1.0, height: 1.0) context?.fill(rect) } } } // MARK: - Event handling public override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { // kickstart the flow. } public override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) { let point = touches.first!.location(in: self) let color = self.colorAtPoint(point, inRect: self.bounds) NSLog("Color At Point[\(point.x),\(point.y)]: \(color)") if self.delegate != nil { self.delegate!.colorPicker(self, didChangeToSelectedColor: color) } } public override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { let point = touches.first!.location(in: self) let color = self.colorAtPoint(point, inRect: self.bounds) if self.delegate != nil { self.delegate!.colorPicker(self, didEndSelectionWithColor: color) } } // MARK: - Convenience color methods func colorAtPoint(_ point: CGPoint, inRect rect: CGRect) -> UIColor { var color = UIColor.white switch colorSpace { case .hsv: color = self.hsvColorAtPoint(point, inRect: rect) default: color = self.customColorAtPoint(point, inRect: rect) } return color } func customColorAtPoint(_ point: CGPoint, inRect rect: CGRect) -> UIColor { let x = point.x let y = point.y let redValue = (y/rect.size.height + (rect.size.width - x)/rect.size.width) / 2 let greenValue = ((rect.size.height - y)/rect.size.height + (rect.size.width - x)/rect.size.width) / 2 let blueValue = (y/rect.size.height + x/rect.size.width) / 2 let color = UIColor(red: redValue, green: greenValue, blue: blueValue, alpha: 1.0) return color } func hsvColorAtPoint(_ point: CGPoint, inRect rect: CGRect) -> UIColor { return UIColor(hue: point.x/rect.size.width, saturation: point.y/rect.size.height, brightness: 1.0, alpha: 1.0) } public override var description: String { get { return self.debugDescription } } public override var debugDescription: String{ get { return "ATColorPicker \n" + "ColorSpace: \(self.colorSpace)\n" } } }
dd3bb3709ac0a3b74025f230b0d31a0a
29.421429
113
0.702747
false
false
false
false
kevin0511/MyCM
refs/heads/master
cm/cm/Common.swift
mit
1
// // Common.swift // CM // // Created by Kevin on 2017/5/14. // Copyright © 2017年 Kevin. All rights reserved. // import UIKit let kScreenW :CGFloat = UIScreen.main.bounds.width let kScreenH :CGFloat = UIScreen.main.bounds.height let kStateBarH :CGFloat = 20 let kNavgationBarH :CGFloat = 44 let kTabBarH :CGFloat = 48 let kMainTitleViewH :CGFloat = 60 let kColorMainGreen = UIColor(r:28,g:221,b:177)
3636c93d5965453aa510f9bea1400f74
22.05
62
0.644252
false
false
false
false
liuduoios/DynamicCollectionView
refs/heads/master
DynamicCollectionViewDemo/DynamicCollectionViewDemo/MyCollectionViewCell.swift
mit
1
// // MyCollectionViewCell.swift // DynamicCollectionViewDemo // // Created by 刘铎 on 15/11/24. // Copyright © 2015年 liuduoios. All rights reserved. // import UIKit import DynamicCollectionView class MyCollectionViewCell: DynamicCollectionViewCell<Model> { typealias ItemType = Model var label: UILabel = { let label = UILabel(frame: CGRectZero) label.textAlignment = .Center return label }() var sublabel: UILabel = { let sublabel = UILabel(frame: CGRectZero) sublabel.textAlignment = .Center return sublabel }() override init(frame: CGRect) { super.init(frame: frame) contentView.backgroundColor = UIColor.darkGrayColor() label.frame = CGRect(x: 0, y: 0, width: CGRectGetWidth(contentView.bounds), height: CGRectGetHeight(contentView.bounds) / 2.0) contentView.addSubview(label) sublabel.frame = CGRect(x: 0, y: CGRectGetHeight(contentView.bounds) / 2.0, width: CGRectGetWidth(contentView.bounds), height: CGRectGetHeight(contentView.bounds) / 2.0) contentView.addSubview(sublabel) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func bindModel(model: ItemType) { label.text = model.text sublabel.text = model.subtext } }
caf002409e77bf9839dbed6af9e21ad6
28.531915
177
0.659222
false
false
false
false
vmouta/VMLogger
refs/heads/master
Pod/Classes/implementation/Formatters/ANSIColorLogFormatter.swift
mit
1
// // ANSIColorLogFormatter.swift // XCGLogger: https://github.com/DaveWoodCom/XCGLogger // // Created by Dave Wood on 2016-08-30. // Copyright © 2016 Dave Wood, Cerebral Gardens. // Some rights reserved: https://github.com/DaveWoodCom/XCGLogger/blob/master/LICENSE.txt // // MARK: - ANSIColorLogFormatter /// A log formatter that will add ANSI colour codes to the message open class ANSIColorLogFormatter: BaseLogFormatter { /// ANSI Escape code public static let escape: String = "\u{001b}[" /// ANSI Reset colours code public static let reset: String = "\(escape)m" /// Enum to specify ANSI colours public enum ANSIColor: CustomStringConvertible { case black case red case green case yellow case blue case magenta case cyan case lightGrey, lightGray case darkGrey, darkGray case lightRed case lightGreen case lightYellow case lightBlue case lightMagenta case lightCyan case white case `default` case rgb(red: Int, green: Int, blue: Int) case colorIndex(number: Int) public var foregroundCode: String { switch self { case .black: return "30" case .red: return "31" case .green: return "32" case .yellow: return "33" case .blue: return "34" case .magenta: return "35" case .cyan: return "36" case .lightGrey, .lightGray: return "37" case .darkGrey, .darkGray: return "90" case .lightRed: return "91" case .lightGreen: return "92" case .lightYellow: return "93" case .lightBlue: return "94" case .lightMagenta: return "95" case .lightCyan: return "96" case .white: return "97" case .default: // Note: Different from the default: at the end of a switch, this is the `default` colour return "39" case .rgb(let red, let green, let blue): return "38;2;\(min(max(0, red), 255));\(min(max(0, green), 255));\(min(max(0, blue), 255))" case .colorIndex(let number): return "38;5;\(min(max(0, number), 255))" } } public var backgroundCode: String { switch self { case .black: return "40" case .red: return "41" case .green: return "42" case .yellow: return "43" case .blue: return "44" case .magenta: return "45" case .cyan: return "46" case .lightGrey, .lightGray: return "47" case .darkGrey, .darkGray: return "100" case .lightRed: return "101" case .lightGreen: return "102" case .lightYellow: return "103" case .lightBlue: return "104" case .lightMagenta: return "105" case .lightCyan: return "106" case .white: return "107" case .default: // Note: Different from the default: at the end of a switch, this is the `default` colour return "49" case .rgb(let red, let green, let blue): return "48;2;\(min(max(0, red), 255));\(min(max(0, green), 255));\(min(max(0, blue), 255))" case .colorIndex(let number): return "48;5;\(min(max(0, number), 255))" } } /// Human readable description of this colour (CustomStringConvertible) public var description: String { switch self { case .black: return "Black" case .red: return "Red" case .green: return "Green" case .yellow: return "Yellow" case .blue: return "Blue" case .magenta: return "Magenta" case .cyan: return "Cyan" case .lightGrey, .lightGray: return "Light Grey" case .darkGrey, .darkGray: return "Dark Grey" case .lightRed: return "Light Red" case .lightGreen: return "Light Green" case .lightYellow: return "Light Yellow" case .lightBlue: return "Light Blue" case .lightMagenta: return "Light Magenta" case .lightCyan: return "Light Cyan" case .white: return "White" case .default: // Note: Different from the default: at the end of a switch, this is the `default` colour return "Default" case .rgb(let red, let green, let blue): return String(format: "(r: %d, g: %d, b: %d) #%02X%02X%02X", red, green, blue, red, green, blue) case .colorIndex(let number): return "ANSI color index: \(number)" } } } /// Enum to specific ANSI options public enum ANSIOption: CustomStringConvertible { case bold case faint case italic case underline case blink case blinkFast case strikethrough public var code: String { switch self { case .bold: return "1" case .faint: return "2" case .italic: return "3" case .underline: return "4" case .blink: return "5" case .blinkFast: return "6" case .strikethrough: return "9" } } public var description: String { switch self { case .bold: return "Bold" case .faint: return "Faint" case .italic: return "Italic" case .underline: return "Underline" case .blink: return "Blink" case .blinkFast: return "Blink Fast" case .strikethrough: return "Strikethrough" } } } /// Internal cache of the ANSI codes for each log level internal var formatStrings: [LogLevel: String] = [:] /// Internal cache of the description for each log level internal var descriptionStrings: [LogLevel: String] = [:] public init() { super.init() resetFormatting() } public required convenience init?(configuration: Dictionary<String, Any>) { self.init() } /// Set the colours and/or options for a specific log level. /// /// - Parameters: /// - level: The log level. /// - foregroundColor: The text colour of the message. **Default:** Restore default text colour /// - backgroundColor: The background colour of the message. **Default:** Restore default background colour /// - options: Array of ANSIOptions to apply to the message. **Default:** No options /// /// - Returns: Nothing /// open func colorize(level: LogLevel, with foregroundColor: ANSIColor = .default, on backgroundColor: ANSIColor = .default, options: [ANSIOption] = []) { var codes: [String] = [foregroundColor.foregroundCode, backgroundColor.backgroundCode] var description: String = "\(foregroundColor) on \(backgroundColor)" for option in options { codes.append(option.code) description += "/\(option)" } formatStrings[level] = ANSIColorLogFormatter.escape + codes.joined(separator: ";") + "m" descriptionStrings[level] = description } /// Set the colours and/or options for a specific log level. /// /// - Parameters: /// - level: The log level. /// - custom: A specific ANSI code to use. /// /// - Returns: Nothing /// open func colorize(level: LogLevel, custom: String) { if custom.hasPrefix(ANSIColorLogFormatter.escape) { formatStrings[level] = "\(custom)" descriptionStrings[level] = "Custom: \(String(custom[custom.index(custom.startIndex, offsetBy: 2)...]))" } else { formatStrings[level] = ANSIColorLogFormatter.escape + "\(custom)" descriptionStrings[level] = "Custom: \(custom)" } } /// Get the cached ANSI codes for the specified log level. /// /// - Parameters: /// - level: The log level. /// /// - Returns: The ANSI codes for the specified log level. /// internal func formatString(for level: LogLevel) -> String { return formatStrings[level] ?? ANSIColorLogFormatter.reset } /// Apply a default set of colours. /// /// - Parameters: None /// /// - Returns: Nothing /// open func resetFormatting() { colorize(level: .verbose, with: .white, options: [.bold]) colorize(level: .debug, with: .black) colorize(level: .info, with: .blue) colorize(level: .warning, with: .yellow) colorize(level: .error, with: .red, options: [.bold]) colorize(level: .severe, with: .white, on: .red) colorize(level: .event) colorize(level: .off) } /// Clear all previously set colours. (Sets each log level back to default) /// /// - Parameters: None /// /// - Returns: Nothing /// open func clearFormatting() { colorize(level: .verbose) colorize(level: .debug) colorize(level: .info) colorize(level: .warning) colorize(level: .error) colorize(level: .severe) colorize(level: .event) colorize(level: .off) } /** Returns a formatted representation of the given `LogEntry`. :param: entry The `LogEntry` being formatted. :returns: The formatted representation of `entry`. This particular implementation will never return `nil`. */ override open func formatLogEntry(_ entry: LogEntry, message: String) -> String? { return "\(formatString(for: entry.logLevel))\(message)\(ANSIColorLogFormatter.reset)" } // MARK: - CustomDebugStringConvertible open override var debugDescription: String { get { let type = Mirror(reflecting: self).subjectType var description: String = "\(type): \(self.dateFormatter), \(self.severityTagLenght), \(self.identityTagLenght)" for level in LogLevel.allLevels { description += "\n\t- \(stringRepresentationOfSeverity(level)) > \(descriptionStrings[level] ?? "None")" } return description } } }
8f4a4feff47e9bdedcc3375f3bcdcdbf
31.783862
155
0.516086
false
false
false
false