hexsha
stringlengths 40
40
| size
int64 3
1.03M
| content
stringlengths 3
1.03M
| avg_line_length
float64 1.33
100
| max_line_length
int64 2
1k
| alphanum_fraction
float64 0.25
0.99
|
---|---|---|---|---|---|
efe975e5477cd0e5583acb33dd4fbeb95f330d0a | 1,616 | //
// Rotation3DEffectXYAndZAxes.swift
// SwiftUIViewsMasteryDemo
//
// Created by RecherJ on 2021/7/27.
//
import SwiftUI
struct Rotation3DEffectXYAndZAxes: View {
@State private var degrees = -65.0
var body: some View {
VStack(spacing: 20) {
Text("Rotation 3D Effect")
.font(.largeTitle)
Text("X, Y & Z Axes")
.font(.title)
.foregroundColor(.gray)
Text("Now it gets a little more complicated to think on all 3 axes. Plot the vector using X, Y and Z values.")
.frame(maxWidth: .infinity)
.padding()
.background(Color.yellow)
.layoutPriority(1)
.font(.title)
Text("axis: (x: 2.0, y: 4.0, z: 3.0)")
Image("XYZ")
.resizable()
.frame(width: 200, height: 200)
RoundedRectangle(cornerRadius: 10)
.fill(Color.yellow)
.opacity(0.7)
.overlay(
Text("Move slider to adjust rotation")
.font(.largeTitle)
.bold()
)
.rotation3DEffect(
Angle(degrees: degrees),
axis: (x: 2.0, y: 4.0, z: 3.0)
)
Slider(value: $degrees, in: -180...180, step: 1)
.padding()
Text("Crazy!")
}
}
}
struct Rotation3DEffectXYAndZAxes_Previews: PreviewProvider {
static var previews: some View {
Rotation3DEffectXYAndZAxes()
}
}
| 29.925926 | 122 | 0.481436 |
ffd570879be71f39d4836e6f740a27cef1382218 | 8,466 | //
// OrderCartViewController.swift
// DoorDash
//
// Created by Marvin Zhan on 2018-10-11.
// Copyright © 2018 Monster. All rights reserved.
//
import UIKit
import IGListKit
import SnapKit
protocol OrderCartViewControllerDelegate: class {
func presentStorePage(storeID: String)
func presentCheckoutPage()
func presentItemDetailPage(itemID: String, storeID: String, selectedData: ItemSelectedData?)
func dismiss()
}
final class OrderCartViewController: BaseViewController {
lazy var adapter: ListAdapter = {
return ListAdapter(updater: ListAdapterUpdater(), viewController: self)
}()
private let viewModel: OrderCartViewModel
private let collectionView: UICollectionView
private let continueButton: OrderTwoTitlesButton
private let gradientButtonView: GradientButtonView
weak var delegate: OrderCartViewControllerDelegate?
override init() {
collectionView = UICollectionView(
frame: .zero, collectionViewLayout: UICollectionViewFlowLayout()
)
gradientButtonView = GradientButtonView()
continueButton = OrderTwoTitlesButton()
viewModel = OrderCartViewModel()
super.init()
adapter.dataSource = self
}
deinit {
NotificationCenter.default.removeObserver(self)
print("OrderCartViewController deinit")
}
override func viewDidLoad() {
super.viewDidLoad()
setupUI()
setupActions()
}
override func viewWillAppear(_ animated: Bool) {
loadData()
}
private func loadData(showLoadingIndicator: Bool = true) {
setupUIInteractionState(enable: false)
if showLoadingIndicator {
pageLoadingIndicator.show()
}
viewModel.fetchCurrentCart { (errorMsg, isCartEmpty) in
self.pageLoadingIndicator.hide()
self.setupUIInteractionState(enable: true)
if let errorMsg = errorMsg {
log.error(errorMsg)
return
}
self.navigationItem.title = self.viewModel.cartViewModel?.storeDisplayName
self.adapter.performUpdates(animated: true)
self.gradientButtonView.isHidden = isCartEmpty
self.continueButton.isHidden = isCartEmpty
self.updateContinueButtonText()
ApplicationDependency.manager.informMainTabbarVCUpdateCart()
}
}
private func setupActions() {
NotificationCenter.default.addObserver(self, selector: #selector(willEnterForeground), name: UIApplication.willEnterForegroundNotification, object: nil)
let tap = UITapGestureRecognizer(target: self, action: #selector(continueButtonTapped))
continueButton.addGestureRecognizer(tap)
}
private func removeItem(id: Int64) {
setupUIInteractionState(enable: false)
self.pageLoadingIndicator.show()
self.viewModel.removeItem(id: id, completion: { (errorMsg) in
self.setupUIInteractionState(enable: true)
if let error = errorMsg {
self.pageLoadingIndicator.hide()
log.error(error)
self.presentErrorAlertView(title: "Whoops", message: error)
return
}
self.loadData(showLoadingIndicator: false)
})
}
}
extension OrderCartViewController {
@objc
private func willEnterForeground() {
loadData()
}
@objc
private func continueButtonTapped() {
self.delegate?.presentCheckoutPage()
}
@objc
private func dismissButtonTapped() {
self.delegate?.dismiss()
}
}
extension OrderCartViewController {
private func setupUI() {
self.view.backgroundColor = theme.colors.white
setupNavigationBar()
setupCollectionView()
setupGradientButtonView()
setupContinueButton()
setupConstraints()
}
private func setupNavigationBar() {
self.navigationController?.navigationBar.setBackgroundImage(UIImage(), for: UIBarMetrics.default)
self.navigationController?.navigationBar.shadowImage = UIImage()
let leftBarButton = UIBarButtonItem(title: "Back", style: .plain, target: self, action: #selector(dismissButtonTapped))
leftBarButton.setTitleTextAttributes([NSAttributedString.Key.font: theme.fonts.medium18], for: .normal)
self.navigationItem.setLeftBarButtonItems([leftBarButton], animated: false)
let backBarButton = UIBarButtonItem(title: "My Cart", style: .plain, target: nil, action: nil)
backBarButton.setTitleTextAttributes([NSAttributedString.Key.font: theme.fonts.medium18], for: .normal)
self.navigationItem.backBarButtonItem = backBarButton
}
private func setupCollectionView() {
self.view.addSubview(collectionView)
adapter.collectionView = collectionView
collectionView.backgroundColor = theme.colors.white
collectionView.alwaysBounceVertical = true
let inset = UIEdgeInsets(top: 0, left: 0, bottom: GradientButtonView.height - 50, right: 0)
collectionView.contentInset = inset
collectionView.showsVerticalScrollIndicator = false
}
private func setupGradientButtonView() {
gradientButtonView.isHidden = true
self.view.addSubview(gradientButtonView)
}
private func setupContinueButton() {
self.continueButton.isHidden = true
self.view.addSubview(continueButton)
}
private func setupConstraints() {
collectionView.snp.makeConstraints { (make) in
make.edges.equalToSuperview()
}
gradientButtonView.snp.makeConstraints { (make) in
make.leading.trailing.bottom.equalToSuperview()
make.height.equalTo(GradientButtonView.height)
}
continueButton.snp.makeConstraints { (make) in
make.leading.trailing.equalToSuperview().inset(16)
make.bottom.equalTo(gradientButtonView).offset(-45)
make.height.equalTo(48)
}
}
private func updateContinueButtonText() {
self.continueButton.setupTexts(
title: "Continue",
price: viewModel.cartViewModel?.totalBeforeTaxDisplay ?? ""
)
}
private func setupUIInteractionState(enable: Bool) {
self.collectionView.isUserInteractionEnabled = enable
self.continueButton.isUserInteractionEnabled = enable
}
}
extension OrderCartViewController: ListAdapterDataSource {
func objects(for listAdapter: ListAdapter) -> [ListDiffable] {
return viewModel.sectionData
}
func listAdapter(_ listAdapter: ListAdapter, sectionControllerFor object: Any) -> ListSectionController {
switch object {
case is OrderCartItemPresentingModel:
let controller = OrderCartItemSectionController()
controller.userRemovedItem = { [weak self] id in
self?.removeItem(id: id)
}
controller.userTappedItem = { [weak self] id in
guard let storeID = self?.viewModel.cartViewModel?.storeID else {
log.error("WTF, no store id?")
return
}
self?.delegate?.presentItemDetailPage(
itemID: String(id),
storeID: storeID,
selectedData: self?.viewModel.generateItemSelectedData(itemID: id)
)
}
return controller
case is OrderCartAddMoreItemsPresentingModel:
let controller = OrderCartAddMoreItemsSectionController()
controller.addMoreItemTapped = { [weak self] in
guard let id = self?.viewModel.cartViewModel?.storeID else {
log.error("WTF, no store id?")
return
}
self?.delegate?.presentStorePage(storeID: id)
}
return controller
case is OrderCartPromoCodePresentingModel:
return OrderCartPromoCodeSectionController()
case is OrderCartPriceDisplayPresentingModel:
return OrderCartPriceDisplaySectionController()
case is OrderCartEmptyDataPresentingModel:
return OrderCartEmptyDataSectionController()
default:
return OrderCartItemSectionController()
}
}
func emptyView(for listAdapter: ListAdapter) -> UIView? {
return nil
}
}
| 35.275 | 160 | 0.656863 |
89e159797e6a342a9f2e4c750a8f6d1740ce6fbe | 2,838 | //
// ObjectListTableViewController.swift
// PairRandomizer
//
// Created by Alex Kennedy on 10/16/20.
// Copyright © 2020 Alex Kennedy. All rights reserved.
//
import UIKit
class ObjectListTableViewController: UITableViewController {
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
tableView.reloadData()
}
// MARK: - actions
@IBAction func randomizeButtonTapped(_ sender: Any) {
ListController.shared.randomize()
tableView.reloadData()
}
@IBAction func addObjectButtonTapped(_ sender: Any) {
}
@IBAction func saveButtonTapped(_ sender: Any) {
ListController.shared.saveToPersistenStore()
}
// MARK: - Table view data source
override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let headerLabel = UILabel()
headerLabel.text = "Group \(section.self + 1)"
headerLabel.backgroundColor = .lightGray
return headerLabel
}
override func numberOfSections(in tableView: UITableView) -> Int {
return ListController.shared.objects.count / 2
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if section == 0 {
return 2
}
if section == 1 {
return 2
}
if section == 2 {
return 2
}
if section == 3 {
return 2
}
if section == 4 {
return 2
}
if section == 5 {
return 2
}
return 2
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "objectCell", for: indexPath)
let list = ListController.shared.objects[indexPath.row]
cell.textLabel?.text = "\(list.object)"
return cell
}
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
let object = ListController.shared.objects[indexPath.row]
ListController.shared.deleteObject(object: object)
tableView.deleteRows(at: [indexPath], with: .fade)
}
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "toAddObjectVC" {
guard let index = tableView.indexPathForSelectedRow,
let destination = segue.destination as? AddObjectViewController else { return }
let object = ListController.shared.objects[index.row]
destination.object = object
}
}
}
| 28.666667 | 137 | 0.613108 |
9c368028003304ad05099e6940a8b9c03e3719b4 | 15,978 | //
// GDRichContentAlertView.swift
// GaodiLicai
//
// Created by zhangyr on 2017/1/18.
// Copyright © 2017年 quchaogu. All rights reserved.
// 260
import UIKit
private let BUTTON_TAG_OFFSET = 100
private let ALERTVIEW_WIDTH :CGFloat = 260 * UIScreen.main.bounds.width / 375
@objc public protocol SMAlertViewDelegate: NSObjectProtocol {
@objc optional func smAlert(_ alert : SMAlertView , clickButtonAtIndex buttonIndex : Int)
}
public class SMAlertView: UIView {
public lazy var attributesTitle: [NSAttributedString.Key: Any] = [NSAttributedString.Key.foregroundColor: HexColor(COLOR_COMMON_BLACK),
NSAttributedString.Key.font: UIFont.boldFontOfSize(18)]
public lazy var attributesMessage: [NSAttributedString.Key: Any] = [NSAttributedString.Key.foregroundColor: HexColor(COLOR_COMMON_BLACK_3),
NSAttributedString.Key.font: UIFont.normalFontOfSize(14)]
public lazy var attributesTips: [NSAttributedString.Key: Any] = [NSAttributedString.Key.foregroundColor: HexColor(COLOR_COMMON_BLACK_9),
NSAttributedString.Key.font: UIFont.normalFontOfSize(12)]
public lazy var attributesButton: [NSAttributedString.Key: Any] = [NSAttributedString.Key.foregroundColor: HexColor(COLOR_COMMON_BLACK_3),
NSAttributedString.Key.font: UIFont.boldFontOfSize(16)]
public var canDismissOutside: Bool = false
public var messageAlignment: NSTextAlignment = .center
public var cornerRadius: CGFloat = 0
public var titleSpace: CGFloat = 12
public var messageSpace: CGFloat = 15
public var tipsSpace: CGFloat = 18
public var buttonSpace: CGFloat = 26
public var buttonHeight: CGFloat = 45
public var topSpace: CGFloat = 24
public var bottomSpace: CGFloat = 44
public var animationDuration: TimeInterval = 0.3
public var delayDuration: TimeInterval = 0
public var needTimer: Bool = false
public var duration: TimeInterval = 0
public var tips: String?
public var timeoutBlock: (() -> Void)?
public var cancelButtonIndex: Int {return 0}
public var closeButtonIndex: Int {return 999}
public var needClose: Bool = false
public var closeImage: UIImage? = UIImage(named: "main_event_close_hover")
public var userInfo: Any?
override public init(frame: CGRect) {
super.init(frame: frame)
self.backgroundColor = UIColor.black.withAlphaComponent(0.3)
}
convenience public init(image: UIImage? = nil,
title: String?,
message: Any?,
delegate: SMAlertViewDelegate?,
cancelButtonTitle: String?) {
self.init(frame: CGRect(x: 0,
y: 0,
width: UIScreen.main.bounds.width,
height: UIScreen.main.bounds.height))
self.image = image
self.title = title
self.message = message
self.delegate = delegate
self.hasCancel = false
if cancelButtonTitle != nil {
self.hasCancel = true
self.buttonTitles = []
self.buttonTitles?.append(cancelButtonTitle!)
}
}
convenience public init(image: UIImage? = nil,
title: String?,
message: Any?,
delegate: SMAlertViewDelegate?,
cancelButtonTitle: String?,
otherButtonTitles: String,
_ moreButtonTitles: String...) {
self.init(image: image,
title: title,
message: message,
delegate: delegate,
cancelButtonTitle: cancelButtonTitle)
if self.buttonTitles == nil {
self.buttonTitles = []
}
self.buttonTitles?.append(otherButtonTitles)
for bStr in moreButtonTitles {
self.buttonTitles?.append(bStr)
}
}
public func setButtonAtrributes(_ attributes: [NSAttributedString.Key: Any], atIndex index: Int) {
if buttonsAttributes == nil {
buttonsAttributes = [:]
}
_ = buttonsAttributes?.updateValue(attributes, forKey: index)
}
public func show(inView view: UIView? = UtilTools.getAppDelegate()?.window ?? nil) {
guard view != nil else {
return
}
layoutViews()
view?.addSubview(self)
self.alpha = 0
UIView.animate(withDuration: animationDuration, animations: {
self.alpha = 1
}, completion: {(bool) in
if self.delayDuration > 0.0001 {
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + self.delayDuration , execute: {
self.dismiss()
})
}
})
}
private func layoutViews() {
contentView = UIView(frame: CGRect(x: 0,
y: 0,
width: ALERTVIEW_WIDTH,
height: 0))
contentView.backgroundColor = HexColor(COLOR_COMMON_WHITE)
contentView.layer.cornerRadius = cornerRadius
contentView.layer.shadowColor = UIColor.black.cgColor
contentView.layer.shadowRadius = 2
contentView.layer.shadowOpacity = 0.5
contentView.layer.shadowOffset = CGSize(width: 2, height: 2)
self.addSubview(contentView)
var tmpY: CGFloat = topSpace
if needClose {
let closeBtn = BaseButton(frame: CGRect(x: ALERTVIEW_WIDTH - 12 - 30,
y: 6,
width: 30,
height: 30))
closeBtn.contentHorizontalAlignment = .right
closeBtn.setImage(closeImage, for: UIControl.State.normal)
closeBtn.tag = 999 + BUTTON_TAG_OFFSET
closeBtn.addTarget(self, action: #selector(SMAlertView.buttonClick(btn:)), for: UIControl.Event.touchUpInside)
contentView.addSubview(closeBtn)
}
if image != nil {
let imageV = UIImageView(frame: CGRect(x: (ALERTVIEW_WIDTH - imageWidth) / 2,
y: tmpY,
width: imageWidth,
height: imageHeight))
imageV.image = image
contentView.addSubview(imageV)
tmpY += imageHeight
}
if title != nil {
tmpY += tmpY <= topSpace ? 0 : titleSpace
let titleLabel = UILabel(frame: CGRect(x: 16,
y: tmpY,
width: ALERTVIEW_WIDTH - 32,
height: 0))
titleLabel.numberOfLines = 0
titleLabel.textAlignment = .center
titleLabel.attributedText = NSAttributedString(string: title!, attributes: attributesTitle)
contentView.addSubview(titleLabel)
let size = titleLabel.sizeThatFits(CGSize(width: ALERTVIEW_WIDTH - 32, height: 999))
titleLabel.frame.size.height = size.height
tmpY += size.height
}
if message != nil {
tmpY += tmpY <= topSpace ? 0 : messageSpace
let msgLabel = UILabel(frame: CGRect(x: 16,
y: tmpY,
width: ALERTVIEW_WIDTH - 32,
height: 0))
msgLabel.numberOfLines = 0
msgLabel.textAlignment = messageAlignment
if let attriMsg = message as? NSAttributedString {
msgLabel.attributedText = attriMsg
}else if let msg = message as? String {
msgLabel.attributedText = NSAttributedString(string: msg, attributes: attributesMessage)
}else{
msgLabel.text = ""
}
contentView.addSubview(msgLabel)
let size = msgLabel.sizeThatFits(CGSize(width: ALERTVIEW_WIDTH - 32, height: 999))
msgLabel.frame.size.height = size.height
tmpY += size.height
if size.height > 24 {
msgLabel.textAlignment = .left
}
}
if tips != nil {
tmpY += tmpY <= topSpace ? 0 : tipsSpace
let tipLabel = UILabel(frame: CGRect(x: 16,
y: tmpY,
width: ALERTVIEW_WIDTH - 32,
height: 0))
tipLabel.numberOfLines = 0
tipLabel.textAlignment = .center
tipLabel.attributedText = NSAttributedString(string: tips!, attributes: attributesTips)
contentView.addSubview(tipLabel)
let size = tipLabel.sizeThatFits(CGSize(width: ALERTVIEW_WIDTH - 32, height: 999))
tipLabel.frame.size.height = size.height
tmpY += size.height
if needTimer && duration > 1 {
timer = Timer(timeInterval: 1,
target: self,
selector: #selector(SMAlertView.timerRun(timer:)),
userInfo: tipLabel,
repeats: true)
tipLabel.attributedText = NSAttributedString(string: "\(Int(duration))秒后,\(tips!)", attributes: attributesTips)
RunLoop.current.add(timer!, forMode: RunLoop.Mode.common)
}
}
if buttonTitles != nil && buttonTitles!.count > 0 {
tmpY += tmpY <= topSpace ? 0 : buttonSpace
let isDouble = buttonTitles!.count == 2
let buttonW = isDouble ? ALERTVIEW_WIDTH / 2 : ALERTVIEW_WIDTH
for i in 0 ..< buttonTitles!.count {
let tmpX = (isDouble && i != 0) ? buttonW : 0
let button = BaseButton(frame: CGRect(x: tmpX,
y: tmpY,
width: buttonW,
height: buttonHeight))
button.layer.cornerRadius = cornerRadius
if hasCancel {
button.tag = BUTTON_TAG_OFFSET + i
}else{
button.tag = BUTTON_TAG_OFFSET + i + 1
}
button.addTarget(self, action: #selector(SMAlertView.buttonClick(btn:)), for: UIControl.Event.touchUpInside)
var attr: [NSAttributedString.Key: Any]? = attributesButton
if let attri = buttonsAttributes?[i] {
attr = attri
}
let aStr = NSAttributedString(string: buttonTitles![i], attributes: attr)
button.setAttributedTitle(aStr, for: UIControl.State.normal)
contentView.addSubview(button)
if !isDouble || i == 1 {
tmpY += buttonHeight
let topLine = UIView(frame: CGRect(x: 0,
y: button.frame.minY,
width: ALERTVIEW_WIDTH,
height: 0.5))
topLine.backgroundColor = HexColor("#e0e0e0")
contentView.addSubview(topLine)
}
if isDouble && i == 1 {
let midLine = UIView(frame: CGRect(x: button.frame.minX,
y: button.frame.minY,
width: 0.5,
height: button.frame.height))
midLine.backgroundColor = HexColor("#e0e0e0")
contentView.addSubview(midLine)
}
}
}else{
tmpY += bottomSpace
}
contentView.frame.size.height = tmpY
contentView.center = self.center
}
@objc private func buttonClick(btn: UIButton) {
timer?.invalidate()
dismiss()
delegate?.smAlert?(self, clickButtonAtIndex: btn.tag - BUTTON_TAG_OFFSET)
}
private func dismiss() {
UIView.animate(withDuration: animationDuration, animations: {
self.alpha = 0
}, completion: {(bool) in
self.timeoutBlock?()
self.removeFromSuperview()
})
}
private func getRectForString(_ string: String, withAttribute attri: [NSAttributedString.Key: Any]) -> CGRect {
return NSString(string: string).boundingRect(with: CGSize(width: ALERTVIEW_WIDTH - 32, height: 999), options: NSStringDrawingOptions.usesLineFragmentOrigin, attributes: attri, context: nil)
}
@objc private func timerRun(timer: Timer) {
duration -= 1
if Int(duration) <= 0 {
timer.invalidate()
dismiss()
}else{
if let label = timer.userInfo as? UILabel {
label.attributedText = NSAttributedString(string: "\(Int(duration))秒后,\(tips!)", attributes: attributesTips)
}
}
}
override public func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
if let touch = touches.first {
let location = touch.location(in: self)
if !contentView.frame.contains(location) && canDismissOutside {
dismiss()
}
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private var hasCancel: Bool = false
private weak var delegate: SMAlertViewDelegate?
private var image: UIImage?
private var title: String?
private var message: Any?
private var buttonTitles: [String]?
private var buttonsAttributes: [Int: [NSAttributedString.Key: Any]]?
private var contentView: UIView!
private var timer: Timer?
private var imageWidth: CGFloat {
if image == nil {
return 0
}else{
return image!.size.width
}
}
private var imageHeight: CGFloat {
if image == nil {
return 0
}else{
return image!.size.height
}
}
}
| 45.651429 | 197 | 0.488234 |
50e50767f43ff7601ced8ef85e971de720c3e803 | 1,148 | //
// ScrollFinishMixin.swift
// Mixin
//
// Created by one on 30/11/2017.
// Copyright © 2017 one. All rights reserved.
//
import UIKit
public protocol ScrollFinishMixin: ScrollViewMixinable {
func scrollFinish(_ scrollView: UIScrollView)
}
public extension ScrollFinishMixin {
private func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
if !decelerate {
scrollFinish(scrollView)
}
}
private func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
scrollFinish(scrollView)
}
private func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) {
DispatchQueue.main.asyncAfter(deadline: .now() + 0.05) {
self.scrollFinish(scrollView)
}
}
public var scrollViewDelegate_ScrollFinishMixin: UIScrollViewDelegate {
return BlockUIScrollViewDelegate(
scrollViewDidEndDragging: scrollViewDidEndDragging,
scrollViewDidEndDecelerating: scrollViewDidEndDecelerating,
scrollViewDidEndScrollingAnimation: scrollViewDidEndScrollingAnimation
)
}
}
| 31.027027 | 104 | 0.715157 |
0145bfd0d08361807125d0473cfcd884a5f37c42 | 15,691 | //
// TMDBConvenience.swift
// TheMovieManager
//
// Created by Jarrod Parkes on 2/11/15.
// Copyright (c) 2015 Jarrod Parkes. All rights reserved.
//
import UIKit
import Foundation
// MARK: - TMDBClient (Convenient Resource Methods)
extension TMDBClient {
// MARK: Authentication (GET) Methods
/*
Steps for Authentication...
https://www.themoviedb.org/documentation/api/sessions
Step 1: Create a new request token
Step 2a: Ask the user for permission via the website
Step 3: Create a session ID
Bonus Step: Go ahead and get the user id 😄!
*/
func authenticateWithViewController(_ hostViewController: UIViewController, completionHandlerForAuth: @escaping (_ success: Bool, _ errorString: String?) -> Void) {
// chain completion handlers for each request so that they run one after the other
getRequestToken() { (success, requestToken, errorString) in
if success {
// success! we have the requestToken!
self.requestToken = requestToken
self.loginWithToken(requestToken, hostViewController: hostViewController) { (success, errorString) in
if success {
self.getSessionID(requestToken) { (success, sessionID, errorString) in
if success {
// success! we have the sessionID!
self.sessionID = sessionID
self.getUserID() { (success, userID, errorString) in
if success {
if let userID = userID {
// and the userID 😄!
self.userID = userID
}
}
completionHandlerForAuth(success, errorString)
}
} else {
completionHandlerForAuth(success, errorString)
}
}
} else {
completionHandlerForAuth(success, errorString)
}
}
} else {
completionHandlerForAuth(success, errorString)
}
}
}
private func getRequestToken(_ completionHandlerForToken: @escaping (_ success: Bool, _ requestToken: String?, _ errorString: String?) -> Void) {
/* 1. Specify parameters, method (if has {key}), and HTTP body (if POST) */
let parameters = [String:AnyObject]()
/* 2. Make the request */
let _ = taskForGETMethod(Methods.AuthenticationTokenNew, parameters: parameters) { (results, error) in
/* 3. Send the desired value(s) to completion handler */
if let error = error {
print(error)
completionHandlerForToken(false, nil, "Login Failed (Request Token).")
} else {
if let requestToken = results?[TMDBClient.JSONResponseKeys.RequestToken] as? String {
completionHandlerForToken(true, requestToken, nil)
} else {
print("Could not find \(TMDBClient.JSONResponseKeys.RequestToken) in \(results!)")
completionHandlerForToken(false, nil, "Login Failed (Request Token).")
}
}
}
}
/* This function opens a TMDBAuthViewController to handle Step 2a of the auth flow */
private func loginWithToken(_ requestToken: String?, hostViewController: UIViewController, completionHandlerForLogin: @escaping (_ success: Bool, _ errorString: String?) -> Void) {
let authorizationURL = URL(string: "\(TMDBClient.Constants.AuthorizationURL)\(requestToken!)")
let request = URLRequest(url: authorizationURL!)
let webAuthViewController = hostViewController.storyboard!.instantiateViewController(withIdentifier: "TMDBAuthViewController") as! TMDBAuthViewController
webAuthViewController.urlRequest = request
webAuthViewController.requestToken = requestToken
webAuthViewController.completionHandlerForView = completionHandlerForLogin
let webAuthNavigationController = UINavigationController()
webAuthNavigationController.pushViewController(webAuthViewController, animated: false)
performUIUpdatesOnMain {
hostViewController.present(webAuthNavigationController, animated: true, completion: nil)
}
}
private func getSessionID(_ requestToken: String?, completionHandlerForSession: @escaping (_ success: Bool, _ sessionID: String?, _ errorString: String?) -> Void) {
/* 1. Specify parameters, method (if has {key}), and HTTP body (if POST) */
let parameters = [TMDBClient.ParameterKeys.RequestToken: requestToken!]
/* 2. Make the request */
let _ = taskForGETMethod(Methods.AuthenticationSessionNew, parameters: parameters as [String:AnyObject]) { (results, error) in
/* 3. Send the desired value(s) to completion handler */
if let error = error {
print(error)
completionHandlerForSession(false, nil, "Login Failed (Session ID).")
} else {
if let sessionID = results?[TMDBClient.JSONResponseKeys.SessionID] as? String {
completionHandlerForSession(true, sessionID, nil)
} else {
print("Could not find \(TMDBClient.JSONResponseKeys.SessionID) in \(results!)")
completionHandlerForSession(false, nil, "Login Failed (Session ID).")
}
}
}
}
private func getUserID(_ completionHandlerForUserID: @escaping (_ success: Bool, _ userID: Int?, _ errorString: String?) -> Void) {
/* 1. Specify parameters, method (if has {key}), and HTTP body (if POST) */
let parameters = [TMDBClient.ParameterKeys.SessionID: TMDBClient.sharedInstance().sessionID!]
/* 2. Make the request */
let _ = taskForGETMethod(Methods.Account, parameters: parameters as [String:AnyObject]) { (results, error) in
/* 3. Send the desired value(s) to completion handler */
if let error = error {
print(error)
completionHandlerForUserID(false, nil, "Login Failed (User ID).")
} else {
if let userID = results?[TMDBClient.JSONResponseKeys.UserID] as? Int {
completionHandlerForUserID(true, userID, nil)
} else {
print("Could not find \(TMDBClient.JSONResponseKeys.UserID) in \(results!)")
completionHandlerForUserID(false, nil, "Login Failed (User ID).")
}
}
}
}
// MARK: GET Convenience Methods
func getFavoriteMovies(_ completionHandlerForFavMovies: @escaping (_ result: [TMDBMovie]?, _ error: NSError?) -> Void) {
/* 1. Specify parameters, method (if has {key}), and HTTP body (if POST) */
let parameters = [TMDBClient.ParameterKeys.SessionID: TMDBClient.sharedInstance().sessionID!]
var mutableMethod: String = Methods.AccountIDFavoriteMovies
mutableMethod = substituteKeyInMethod(mutableMethod, key: TMDBClient.URLKeys.UserID, value: String(TMDBClient.sharedInstance().userID!))!
/* 2. Make the request */
let _ = taskForGETMethod(mutableMethod, parameters: parameters as [String:AnyObject]) { (results, error) in
/* 3. Send the desired value(s) to completion handler */
if let error = error {
completionHandlerForFavMovies(nil, error)
} else {
if let results = results?[TMDBClient.JSONResponseKeys.MovieResults] as? [[String:AnyObject]] {
let movies = TMDBMovie.moviesFromResults(results)
completionHandlerForFavMovies(movies, nil)
} else {
completionHandlerForFavMovies(nil, NSError(domain: "getFavoriteMovies parsing", code: 0, userInfo: [NSLocalizedDescriptionKey: "Could not parse getFavoriteMovies"]))
}
}
}
}
func getWatchlistMovies(_ completionHandlerForWatchlist: @escaping (_ result: [TMDBMovie]?, _ error: NSError?) -> Void) {
/* 1. Specify parameters, method (if has {key}), and HTTP body (if POST) */
let parameters = [TMDBClient.ParameterKeys.SessionID: TMDBClient.sharedInstance().sessionID!]
var mutableMethod: String = Methods.AccountIDWatchlistMovies
mutableMethod = substituteKeyInMethod(mutableMethod, key: TMDBClient.URLKeys.UserID, value: String(TMDBClient.sharedInstance().userID!))!
/* 2. Make the request */
let _ = taskForGETMethod(mutableMethod, parameters: parameters as [String:AnyObject]) { (results, error) in
/* 3. Send the desired value(s) to completion handler */
if let error = error {
completionHandlerForWatchlist(nil, error)
} else {
if let results = results?[TMDBClient.JSONResponseKeys.MovieResults] as? [[String:AnyObject]] {
let movies = TMDBMovie.moviesFromResults(results)
completionHandlerForWatchlist(movies, nil)
} else {
completionHandlerForWatchlist(nil, NSError(domain: "getWatchlistMovies parsing", code: 0, userInfo: [NSLocalizedDescriptionKey: "Could not parse getWatchlistMovies"]))
}
}
}
}
func getMoviesForSearchString(_ searchString: String, completionHandlerForMovies: @escaping (_ result: [TMDBMovie]?, _ error: NSError?) -> Void) -> URLSessionDataTask? {
/* 1. Specify parameters, method (if has {key}), and HTTP body (if POST) */
let parameters = [TMDBClient.ParameterKeys.Query: searchString]
/* 2. Make the request */
let task = taskForGETMethod(Methods.SearchMovie, parameters: parameters as [String:AnyObject]) { (results, error) in
/* 3. Send the desired value(s) to completion handler */
if let error = error {
completionHandlerForMovies(nil, error)
} else {
if let results = results?[TMDBClient.JSONResponseKeys.MovieResults] as? [[String:AnyObject]] {
let movies = TMDBMovie.moviesFromResults(results)
completionHandlerForMovies(movies, nil)
} else {
completionHandlerForMovies(nil, NSError(domain: "getMoviesForSearchString parsing", code: 0, userInfo: [NSLocalizedDescriptionKey: "Could not parse getMoviesForSearchString"]))
}
}
}
return task
}
func getConfig(_ completionHandlerForConfig: @escaping (_ didSucceed: Bool, _ error: NSError?) -> Void) {
/* 1. Specify parameters, method (if has {key}), and HTTP body (if POST) */
let parameters = [String:AnyObject]()
/* 2. Make the request */
let _ = taskForGETMethod(Methods.Config, parameters: parameters) { (results, error) in
/* 3. Send the desired value(s) to completion handler */
if let error = error {
completionHandlerForConfig(false, error)
} else if let newConfig = TMDBConfig(dictionary: results as! [String:AnyObject]) {
self.config = newConfig
completionHandlerForConfig(true, nil)
} else {
completionHandlerForConfig(false, NSError(domain: "getConfig parsing", code: 0, userInfo: [NSLocalizedDescriptionKey: "Could not parse getConfig"]))
}
}
}
// MARK: POST Convenience Methods
func postToFavorites(_ movie: TMDBMovie, favorite: Bool, completionHandlerForFavorite: @escaping (_ result: Int?, _ error: NSError?) -> Void) {
/* 1. Specify parameters, method (if has {key}), and HTTP body (if POST) */
let parameters = [TMDBClient.ParameterKeys.SessionID : TMDBClient.sharedInstance().sessionID!]
var mutableMethod: String = Methods.AccountIDFavorite
mutableMethod = substituteKeyInMethod(mutableMethod, key: TMDBClient.URLKeys.UserID, value: String(TMDBClient.sharedInstance().userID!))!
let jsonBody = "{\"\(TMDBClient.JSONBodyKeys.MediaType)\": \"movie\",\"\(TMDBClient.JSONBodyKeys.MediaID)\": \"\(movie.id)\",\"\(TMDBClient.JSONBodyKeys.Favorite)\": \(favorite)}"
/* 2. Make the request */
let _ = taskForPOSTMethod(mutableMethod, parameters: parameters as [String:AnyObject], jsonBody: jsonBody) { (results, error) in
/* 3. Send the desired value(s) to completion handler */
if let error = error {
completionHandlerForFavorite(nil, error)
} else {
if let results = results?[TMDBClient.JSONResponseKeys.StatusCode] as? Int {
completionHandlerForFavorite(results, nil)
} else {
completionHandlerForFavorite(nil, NSError(domain: "postToFavoritesList parsing", code: 0, userInfo: [NSLocalizedDescriptionKey: "Could not parse postToFavoritesList"]))
}
}
}
}
func postToWatchlist(_ movie: TMDBMovie, watchlist: Bool, completionHandlerForWatchlist: @escaping (_ result: Int?, _ error: NSError?) -> Void) {
/* 1. Specify parameters, method (if has {key}), and HTTP body (if POST) */
let parameters = [TMDBClient.ParameterKeys.SessionID : TMDBClient.sharedInstance().sessionID!]
var mutableMethod: String = Methods.AccountIDWatchlist
mutableMethod = substituteKeyInMethod(mutableMethod, key: TMDBClient.URLKeys.UserID, value: String(TMDBClient.sharedInstance().userID!))!
let jsonBody = "{\"\(TMDBClient.JSONBodyKeys.MediaType)\": \"movie\",\"\(TMDBClient.JSONBodyKeys.MediaID)\": \"\(movie.id)\",\"\(TMDBClient.JSONBodyKeys.Watchlist)\": \(watchlist)}"
/* 2. Make the request */
let _ = taskForPOSTMethod(mutableMethod, parameters: parameters as [String:AnyObject], jsonBody: jsonBody) { (results, error) in
/* 3. Send the desired value(s) to completion handler */
if let error = error {
completionHandlerForWatchlist(nil, error)
} else {
if let results = results?[TMDBClient.JSONResponseKeys.StatusCode] as? Int {
completionHandlerForWatchlist(results, nil)
} else {
completionHandlerForWatchlist(nil, NSError(domain: "postToWatchlist parsing", code: 0, userInfo: [NSLocalizedDescriptionKey: "Could not parse postToWatchlist"]))
}
}
}
}
}
| 50.616129 | 196 | 0.580906 |
4a4eff6089ec3a4f5c7389fcc44aa6eb86e6fc01 | 228 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
let start = compose ( [ {
struct S {
deinit {
class
case ,
| 22.8 | 87 | 0.736842 |
902089aec870ec7b754fee9cbfc002a4279a64ee | 965 | //
// MRKGenericBuilder.swift
// mrkViper
//
// Created by Marc Flores on 23/12/2018.
// Copyright © 2018 Marc Flores. All rights reserved.
//
import Foundation
import UIKit
public typealias MRKBuilderComponents<V:MRKViewControllerBase,I:MRKInteractorBase,
W:MRKWireframeBase,P:MRKPresenterBase<V,I,W>> = ( viewController:V, interactor:I, wireframe:W, presenter:P)
public func MRKBuilder<
V:MRKViewControllerBase,
I:MRKInteractorBase,
W:MRKWireframeBase,
P:MRKPresenterBase<V,I,W>>( _ PresenterType:P.Type ) -> MRKBuilderComponents<V,I,W,P> {
let viewController = V()
let interactor = I.init()
let presenter = P.init()
let wireframe = W.init()
interactor.presenter = presenter
presenter.interactor = interactor
presenter.viewController = viewController
presenter.wireframe = wireframe
viewController.presenter = presenter
return (viewController, interactor, wireframe, presenter)
}
| 27.571429 | 111 | 0.720207 |
ef2a9899864ca6b29d23575631f0e95cc1b9faa5 | 48,046 | //===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2017-2018 Apple Inc. and the SwiftNIO project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import NIOConcurrencyHelpers
import Dispatch
/// Returned once a task was scheduled on the `EventLoop` for later execution.
///
/// A `Scheduled` allows the user to either `cancel()` the execution of the scheduled task (if possible) or obtain a reference to the `EventLoopFuture` that
/// will be notified once the execution is complete.
public struct Scheduled<T> {
/* private but usableFromInline */ @usableFromInline let _promise: EventLoopPromise<T>
@inlinable
public init(promise: EventLoopPromise<T>, cancellationTask: @escaping () -> Void) {
self._promise = promise
promise.futureResult.whenFailure { error in
guard let err = error as? EventLoopError else {
return
}
if err == .cancelled {
cancellationTask()
}
}
}
/// Try to cancel the execution of the scheduled task.
///
/// Whether this is successful depends on whether the execution of the task already begun.
/// This means that cancellation is not guaranteed.
@inlinable
public func cancel() {
self._promise.fail(EventLoopError.cancelled)
}
/// Returns the `EventLoopFuture` which will be notified once the execution of the scheduled task completes.
@inlinable
public var futureResult: EventLoopFuture<T> {
return self._promise.futureResult
}
}
/// Returned once a task was scheduled to be repeatedly executed on the `EventLoop`.
///
/// A `RepeatedTask` allows the user to `cancel()` the repeated scheduling of further tasks.
public final class RepeatedTask {
private let delay: TimeAmount
private let eventLoop: EventLoop
private let cancellationPromise: EventLoopPromise<Void>?
private var scheduled: Optional<Scheduled<EventLoopFuture<Void>>>
private var task: Optional<(RepeatedTask) -> EventLoopFuture<Void>>
internal init(interval: TimeAmount, eventLoop: EventLoop, cancellationPromise: EventLoopPromise<Void>? = nil, task: @escaping (RepeatedTask) -> EventLoopFuture<Void>) {
self.delay = interval
self.eventLoop = eventLoop
self.cancellationPromise = cancellationPromise
self.task = task
self.scheduled = nil
}
internal func begin(in delay: TimeAmount) {
if self.eventLoop.inEventLoop {
self.begin0(in: delay)
} else {
self.eventLoop.execute {
self.begin0(in: delay)
}
}
}
private func begin0(in delay: TimeAmount) {
self.eventLoop.assertInEventLoop()
guard let task = self.task else {
return
}
self.scheduled = self.eventLoop.scheduleTask(in: delay) {
task(self)
}
self.reschedule()
}
/// Try to cancel the execution of the repeated task.
///
/// Whether the execution of the task is immediately canceled depends on whether the execution of a task has already begun.
/// This means immediate cancellation is not guaranteed.
///
/// The safest way to cancel is by using the passed reference of `RepeatedTask` inside the task closure.
///
/// If the promise parameter is not `nil`, the passed promise is fulfilled when cancellation is complete.
/// Passing a promise does not prevent fulfillment of any promise provided on original task creation.
public func cancel(promise: EventLoopPromise<Void>? = nil) {
if self.eventLoop.inEventLoop {
self.cancel0(localCancellationPromise: promise)
} else {
self.eventLoop.execute {
self.cancel0(localCancellationPromise: promise)
}
}
}
private func cancel0(localCancellationPromise: EventLoopPromise<Void>?) {
self.eventLoop.assertInEventLoop()
self.scheduled?.cancel()
self.scheduled = nil
self.task = nil
// Possible states at this time are:
// 1) Task is scheduled but has not yet executed.
// 2) Task is currently executing and invoked `cancel()` on itself.
// 3) Task is currently executing and `cancel0()` has been reentrantly invoked.
// 4) NOT VALID: Task is currently executing and has NOT invoked `cancel()` (`EventLoop` guarantees serial execution)
// 5) NOT VALID: Task has completed execution in a success state (`reschedule()` ensures state #2).
// 6) Task has completed execution in a failure state.
// 7) Task has been fully cancelled at a previous time.
//
// It is desirable that the task has fully completed any execution before any cancellation promise is
// fulfilled. States 2 and 3 occur during execution, so the requirement is implemented by deferring
// fulfillment to the next `EventLoop` cycle. The delay is harmless to other states and distinguishing
// them from 2 and 3 is not practical (or necessarily possible), so is used unconditionally. Check the
// promises for nil so as not to otherwise invoke `execute()` unnecessarily.
if self.cancellationPromise != nil || localCancellationPromise != nil {
self.eventLoop.execute {
self.cancellationPromise?.succeed(())
localCancellationPromise?.succeed(())
}
}
}
private func reschedule() {
self.eventLoop.assertInEventLoop()
guard let scheduled = self.scheduled else {
return
}
scheduled.futureResult.whenSuccess { future in
future.whenComplete { (_: Result<Void, Error>) in
self.reschedule0()
}
}
scheduled.futureResult.whenFailure { (_: Error) in
self.cancel0(localCancellationPromise: nil)
}
}
private func reschedule0() {
self.eventLoop.assertInEventLoop()
guard self.task != nil else {
return
}
self.scheduled = self.eventLoop.scheduleTask(in: self.delay) {
// we need to repeat this as we might have been cancelled in the meantime
guard let task = self.task else {
return self.eventLoop.makeSucceededFuture(())
}
return task(self)
}
self.reschedule()
}
}
/// An iterator over the `EventLoop`s forming an `EventLoopGroup`.
///
/// Usually returned by an `EventLoopGroup`'s `makeIterator()` method.
///
/// let group = MultiThreadedEventLoopGroup(numberOfThreads: 1)
/// group.makeIterator().forEach { loop in
/// // Do something with each loop
/// }
///
public struct EventLoopIterator: Sequence, IteratorProtocol {
public typealias Element = EventLoop
private var eventLoops: IndexingIterator<[EventLoop]>
/// Create an `EventLoopIterator` from an array of `EventLoop`s.
public init(_ eventLoops: [EventLoop]) {
self.eventLoops = eventLoops.makeIterator()
}
/// Advances to the next `EventLoop` and returns it, or `nil` if no next element exists.
///
/// - returns: The next `EventLoop` if a next element exists; otherwise, `nil`.
public mutating func next() -> EventLoop? {
return self.eventLoops.next()
}
}
/// An EventLoop processes IO / tasks in an endless loop for `Channel`s until it's closed.
///
/// Usually multiple `Channel`s share the same `EventLoop` for processing IO / tasks and so share the same processing `NIOThread`.
/// For a better understanding of how such an `EventLoop` works internally the following pseudo code may be helpful:
///
/// ```
/// while eventLoop.isOpen {
/// /// Block until there is something to process for 1...n Channels
/// let readyChannels = blockUntilIoOrTasksAreReady()
/// /// Loop through all the Channels
/// for channel in readyChannels {
/// /// Process IO and / or tasks for the Channel.
/// /// This may include things like:
/// /// - accept new connection
/// /// - connect to a remote host
/// /// - read from socket
/// /// - write to socket
/// /// - tasks that were submitted via EventLoop methods
/// /// and others.
/// processIoAndTasks(channel)
/// }
/// }
/// ```
///
/// Because an `EventLoop` may be shared between multiple `Channel`s it's important to _NOT_ block while processing IO / tasks. This also includes long running computations which will have the same
/// effect as blocking in this case.
public protocol EventLoop: EventLoopGroup {
/// Returns `true` if the current `NIOThread` is the same as the `NIOThread` that is tied to this `EventLoop`. `false` otherwise.
var inEventLoop: Bool { get }
/// Submit a given task to be executed by the `EventLoop`
func execute(_ task: @escaping () -> Void)
/// Submit a given task to be executed by the `EventLoop`. Once the execution is complete the returned `EventLoopFuture` is notified.
///
/// - parameters:
/// - task: The closure that will be submitted to the `EventLoop` for execution.
/// - returns: `EventLoopFuture` that is notified once the task was executed.
func submit<T>(_ task: @escaping () throws -> T) -> EventLoopFuture<T>
/// Schedule a `task` that is executed by this `EventLoop` at the given time.
///
/// - parameters:
/// - task: The synchronous task to run. As with everything that runs on the `EventLoop`, it must not block.
/// - returns: A `Scheduled` object which may be used to cancel the task if it has not yet run, or to wait
/// on the completion of the task.
///
/// - note: You can only cancel a task before it has started executing.
@discardableResult
func scheduleTask<T>(deadline: NIODeadline, _ task: @escaping () throws -> T) -> Scheduled<T>
/// Schedule a `task` that is executed by this `EventLoop` after the given amount of time.
///
/// - parameters:
/// - task: The synchronous task to run. As with everything that runs on the `EventLoop`, it must not block.
/// - returns: A `Scheduled` object which may be used to cancel the task if it has not yet run, or to wait
/// on the completion of the task.
///
/// - note: You can only cancel a task before it has started executing.
@discardableResult
func scheduleTask<T>(in: TimeAmount, _ task: @escaping () throws -> T) -> Scheduled<T>
/// Asserts that the current thread is the one tied to this `EventLoop`.
/// Otherwise, the process will be abnormally terminated as per the semantics of `preconditionFailure(_:file:line:)`.
func preconditionInEventLoop(file: StaticString, line: UInt)
/// Asserts that the current thread is _not_ the one tied to this `EventLoop`.
/// Otherwise, the process will be abnormally terminated as per the semantics of `preconditionFailure(_:file:line:)`.
func preconditionNotInEventLoop(file: StaticString, line: UInt)
}
extension EventLoopGroup {
public var description: String {
return String(describing: self)
}
}
/// Represents a time _interval_.
///
/// - note: `TimeAmount` should not be used to represent a point in time.
public struct TimeAmount: Equatable {
@available(*, deprecated, message: "This typealias doesn't serve any purpose. Please use Int64 directly.")
public typealias Value = Int64
/// The nanoseconds representation of the `TimeAmount`.
public let nanoseconds: Int64
private init(_ nanoseconds: Int64) {
self.nanoseconds = nanoseconds
}
/// Creates a new `TimeAmount` for the given amount of nanoseconds.
///
/// - parameters:
/// - amount: the amount of nanoseconds this `TimeAmount` represents.
/// - returns: the `TimeAmount` for the given amount.
public static func nanoseconds(_ amount: Int64) -> TimeAmount {
return TimeAmount(amount)
}
/// Creates a new `TimeAmount` for the given amount of microseconds.
///
/// - parameters:
/// - amount: the amount of microseconds this `TimeAmount` represents.
/// - returns: the `TimeAmount` for the given amount.
public static func microseconds(_ amount: Int64) -> TimeAmount {
return TimeAmount(amount * 1000)
}
/// Creates a new `TimeAmount` for the given amount of milliseconds.
///
/// - parameters:
/// - amount: the amount of milliseconds this `TimeAmount` represents.
/// - returns: the `TimeAmount` for the given amount.
public static func milliseconds(_ amount: Int64) -> TimeAmount {
return TimeAmount(amount * (1000 * 1000))
}
/// Creates a new `TimeAmount` for the given amount of seconds.
///
/// - parameters:
/// - amount: the amount of seconds this `TimeAmount` represents.
/// - returns: the `TimeAmount` for the given amount.
public static func seconds(_ amount: Int64) -> TimeAmount {
return TimeAmount(amount * (1000 * 1000 * 1000))
}
/// Creates a new `TimeAmount` for the given amount of minutes.
///
/// - parameters:
/// - amount: the amount of minutes this `TimeAmount` represents.
/// - returns: the `TimeAmount` for the given amount.
public static func minutes(_ amount: Int64) -> TimeAmount {
return TimeAmount(amount * (1000 * 1000 * 1000 * 60))
}
/// Creates a new `TimeAmount` for the given amount of hours.
///
/// - parameters:
/// - amount: the amount of hours this `TimeAmount` represents.
/// - returns: the `TimeAmount` for the given amount.
public static func hours(_ amount: Int64) -> TimeAmount {
return TimeAmount(amount * (1000 * 1000 * 1000 * 60 * 60))
}
}
extension TimeAmount: Comparable {
public static func < (lhs: TimeAmount, rhs: TimeAmount) -> Bool {
return lhs.nanoseconds < rhs.nanoseconds
}
}
extension TimeAmount {
public static func + (lhs: TimeAmount, rhs: TimeAmount) -> TimeAmount {
return TimeAmount(lhs.nanoseconds + rhs.nanoseconds)
}
public static func - (lhs: TimeAmount, rhs: TimeAmount) -> TimeAmount {
return TimeAmount(lhs.nanoseconds - rhs.nanoseconds)
}
public static func * <T: BinaryInteger>(lhs: T, rhs: TimeAmount) -> TimeAmount {
return TimeAmount(Int64(lhs) * rhs.nanoseconds)
}
public static func * <T: BinaryInteger>(lhs: TimeAmount, rhs: T) -> TimeAmount {
return TimeAmount(lhs.nanoseconds * Int64(rhs))
}
}
/// Represents a point in time.
///
/// Stores the time in nanoseconds as returned by `DispatchTime.now().uptimeNanoseconds`
///
/// `NIODeadline` allow chaining multiple tasks with the same deadline without needing to
/// compute new timeouts for each step
///
/// ```
/// func doSomething(deadline: NIODeadline) -> EventLoopFuture<Void> {
/// return step1(deadline: deadline).flatMap {
/// step2(deadline: deadline)
/// }
/// }
/// doSomething(deadline: .now() + .seconds(5))
/// ```
///
/// - note: `NIODeadline` should not be used to represent a time interval
public struct NIODeadline: Equatable, Hashable {
@available(*, deprecated, message: "This typealias doesn't serve any purpose, please use UInt64 directly.")
public typealias Value = UInt64
// This really should be an UInt63 but we model it as Int64 with >=0 assert
private var _uptimeNanoseconds: Int64 {
didSet {
assert(self._uptimeNanoseconds >= 0)
}
}
/// The nanoseconds since boot representation of the `NIODeadline`.
public var uptimeNanoseconds: UInt64 {
return .init(self._uptimeNanoseconds)
}
public static let distantPast = NIODeadline(0)
public static let distantFuture = NIODeadline(.init(Int64.max))
private init(_ nanoseconds: Int64) {
precondition(nanoseconds >= 0)
self._uptimeNanoseconds = nanoseconds
}
public static func now() -> NIODeadline {
return NIODeadline.uptimeNanoseconds(DispatchTime.now().uptimeNanoseconds)
}
public static func uptimeNanoseconds(_ nanoseconds: UInt64) -> NIODeadline {
return NIODeadline(Int64(min(UInt64(Int64.max), nanoseconds)))
}
}
extension NIODeadline: Comparable {
public static func < (lhs: NIODeadline, rhs: NIODeadline) -> Bool {
return lhs.uptimeNanoseconds < rhs.uptimeNanoseconds
}
public static func > (lhs: NIODeadline, rhs: NIODeadline) -> Bool {
return lhs.uptimeNanoseconds > rhs.uptimeNanoseconds
}
}
extension NIODeadline: CustomStringConvertible {
public var description: String {
return self.uptimeNanoseconds.description
}
}
extension NIODeadline {
public static func - (lhs: NIODeadline, rhs: NIODeadline) -> TimeAmount {
// This won't ever crash, NIODeadlines are guaranteed to be within 0 ..< 2^63-1 nanoseconds so the result can
// definitely be stored in a TimeAmount (which is an Int64).
return .nanoseconds(Int64(lhs.uptimeNanoseconds) - Int64(rhs.uptimeNanoseconds))
}
public static func + (lhs: NIODeadline, rhs: TimeAmount) -> NIODeadline {
let partial: Int64
let overflow: Bool
(partial, overflow) = Int64(lhs.uptimeNanoseconds).addingReportingOverflow(rhs.nanoseconds)
if overflow {
assert(rhs.nanoseconds > 0) // this certainly must have overflowed towards +infinity
return NIODeadline.distantFuture
}
guard partial >= 0 else {
return NIODeadline.uptimeNanoseconds(0)
}
return NIODeadline(partial)
}
public static func - (lhs: NIODeadline, rhs: TimeAmount) -> NIODeadline {
if rhs.nanoseconds < 0 {
// The addition won't crash because the worst that could happen is `UInt64(Int64.max) + UInt64(Int64.max)`
// which fits into an UInt64 (and will then be capped to Int64.max == distantFuture by `uptimeNanoseconds`).
return NIODeadline.uptimeNanoseconds(lhs.uptimeNanoseconds + rhs.nanoseconds.magnitude)
} else if rhs.nanoseconds > lhs.uptimeNanoseconds {
// Cap it at `0` because otherwise this would be negative.
return NIODeadline.init(0)
} else {
// This will be positive but still fix in an Int64.
let result = Int64(lhs.uptimeNanoseconds) - rhs.nanoseconds
assert(result >= 0)
return NIODeadline(result)
}
}
}
extension EventLoop {
/// Submit `task` to be run on this `EventLoop`.
///
/// The returned `EventLoopFuture` will be completed when `task` has finished running. It will be succeeded with
/// `task`'s return value or failed if the execution of `task` threw an error.
///
/// - parameters:
/// - task: The synchronous task to run. As everything that runs on the `EventLoop`, it must not block.
/// - returns: An `EventLoopFuture` containing the result of `task`'s execution.
@inlinable
public func submit<T>(_ task: @escaping () throws -> T) -> EventLoopFuture<T> {
let promise: EventLoopPromise<T> = makePromise(file: #file, line: #line)
self.execute {
do {
promise.succeed(try task())
} catch let err {
promise.fail(err)
}
}
return promise.futureResult
}
/// Submit `task` to be run on this `EventLoop`.
///
/// The returned `EventLoopFuture` will be completed when `task` has finished running. It will be identical to
/// the `EventLoopFuture` returned by `task`.
///
/// - parameters:
/// - task: The asynchronous task to run. As with everything that runs on the `EventLoop`, it must not block.
/// - returns: An `EventLoopFuture` identical to the `EventLooopFuture` returned from `task`.
@inlinable
public func flatSubmit<T>(_ task: @escaping () -> EventLoopFuture<T>) -> EventLoopFuture<T> {
return self.submit(task).flatMap { $0 }
}
/// Schedule a `task` that is executed by this `EventLoop` at the given time.
///
/// - parameters:
/// - task: The asynchronous task to run. As with everything that runs on the `EventLoop`, it must not block.
/// - returns: A `Scheduled` object which may be used to cancel the task if it has not yet run, or to wait
/// on the full execution of the task, including its returned `EventLoopFuture`.
///
/// - note: You can only cancel a task before it has started executing.
@discardableResult
public func flatScheduleTask<T>(deadline: NIODeadline,
file: StaticString = #file,
line: UInt = #line,
_ task: @escaping () throws -> EventLoopFuture<T>) -> Scheduled<T> {
let promise: EventLoopPromise<T> = self.makePromise(file:#file, line: line)
let scheduled = self.scheduleTask(deadline: deadline, task)
scheduled.futureResult.flatMap { $0 }.cascade(to: promise)
return .init(promise: promise, cancellationTask: { scheduled.cancel() })
}
/// Schedule a `task` that is executed by this `EventLoop` after the given amount of time.
///
/// - parameters:
/// - task: The asynchronous task to run. As everything that runs on the `EventLoop`, it must not block.
/// - returns: A `Scheduled` object which may be used to cancel the task if it has not yet run, or to wait
/// on the full execution of the task, including its returned `EventLoopFuture`.
///
/// - note: You can only cancel a task before it has started executing.
@discardableResult
public func flatScheduleTask<T>(in delay: TimeAmount,
file: StaticString = #file,
line: UInt = #line,
_ task: @escaping () throws -> EventLoopFuture<T>) -> Scheduled<T> {
let promise: EventLoopPromise<T> = self.makePromise(file: file, line: line)
let scheduled = self.scheduleTask(in: delay, task)
scheduled.futureResult.flatMap { $0 }.cascade(to: promise)
return .init(promise: promise, cancellationTask: { scheduled.cancel() })
}
/// Creates and returns a new `EventLoopPromise` that will be notified using this `EventLoop` as execution `NIOThread`.
@inlinable
public func makePromise<T>(of type: T.Type = T.self, file: StaticString = #file, line: UInt = #line) -> EventLoopPromise<T> {
return EventLoopPromise<T>(eventLoop: self, file: file, line: line)
}
/// Creates and returns a new `EventLoopFuture` that is already marked as failed. Notifications will be done using this `EventLoop` as execution `NIOThread`.
///
/// - parameters:
/// - error: the `Error` that is used by the `EventLoopFuture`.
/// - returns: a failed `EventLoopFuture`.
@inlinable
public func makeFailedFuture<T>(_ error: Error, file: StaticString = #file, line: UInt = #line) -> EventLoopFuture<T> {
return EventLoopFuture<T>(eventLoop: self, error: error, file: file, line: line)
}
/// Creates and returns a new `EventLoopFuture` that is already marked as success. Notifications will be done using this `EventLoop` as execution `NIOThread`.
///
/// - parameters:
/// - result: the value that is used by the `EventLoopFuture`.
/// - returns: a succeeded `EventLoopFuture`.
@inlinable
public func makeSucceededFuture<Success>(_ value: Success, file: StaticString = #file, line: UInt = #line) -> EventLoopFuture<Success> {
return EventLoopFuture<Success>(eventLoop: self, value: value, file: file, line: line)
}
/// An `EventLoop` forms a singular `EventLoopGroup`, returning itself as the 'next' `EventLoop`.
///
/// - returns: Itself, because an `EventLoop` forms a singular `EventLoopGroup`.
public func next() -> EventLoop {
return self
}
/// Close this `EventLoop`.
public func close() throws {
// Do nothing
}
/// Schedule a repeated task to be executed by the `EventLoop` with a fixed delay between the end and start of each
/// task.
///
/// - parameters:
/// - initialDelay: The delay after which the first task is executed.
/// - delay: The delay between the end of one task and the start of the next.
/// - promise: If non-nil, a promise to fulfill when the task is cancelled and all execution is complete.
/// - task: The closure that will be executed.
/// - return: `RepeatedTask`
@discardableResult
public func scheduleRepeatedTask(initialDelay: TimeAmount, delay: TimeAmount, notifying promise: EventLoopPromise<Void>? = nil, _ task: @escaping (RepeatedTask) throws -> Void) -> RepeatedTask {
let futureTask: (RepeatedTask) -> EventLoopFuture<Void> = { repeatedTask in
do {
try task(repeatedTask)
return self.makeSucceededFuture(())
} catch {
return self.makeFailedFuture(error)
}
}
return self.scheduleRepeatedAsyncTask(initialDelay: initialDelay, delay: delay, notifying: promise, futureTask)
}
/// Schedule a repeated asynchronous task to be executed by the `EventLoop` with a fixed delay between the end and
/// start of each task.
///
/// - note: The delay is measured from the completion of one run's returned future to the start of the execution of
/// the next run. For example: If you schedule a task once per second but your task takes two seconds to
/// complete, the time interval between two subsequent runs will actually be three seconds (2s run time plus
/// the 1s delay.)
///
/// - parameters:
/// - initialDelay: The delay after which the first task is executed.
/// - delay: The delay between the end of one task and the start of the next.
/// - promise: If non-nil, a promise to fulfill when the task is cancelled and all execution is complete.
/// - task: The closure that will be executed.
/// - return: `RepeatedTask`
@discardableResult
public func scheduleRepeatedAsyncTask(initialDelay: TimeAmount,
delay: TimeAmount,
notifying promise: EventLoopPromise<Void>? = nil,
_ task: @escaping (RepeatedTask) -> EventLoopFuture<Void>) -> RepeatedTask {
let repeated = RepeatedTask(interval: delay, eventLoop: self, cancellationPromise: promise, task: task)
repeated.begin(in: initialDelay)
return repeated
}
/// Returns an `EventLoopIterator` over this `EventLoop`.
///
/// - returns: `EventLoopIterator`
public func makeIterator() -> EventLoopIterator {
return EventLoopIterator([self])
}
/// Asserts that the current thread is the one tied to this `EventLoop`.
/// Otherwise, if running in debug mode, the process will be abnormally terminated as per the semantics of
/// `preconditionFailure(_:file:line:)`. Never has any effect in release mode.
///
/// - note: This is not a customization point so calls to this function can be fully optimized out in release mode.
@inlinable
public func assertInEventLoop(file: StaticString = #file, line: UInt = #line) {
debugOnly {
self.preconditionInEventLoop(file: file, line: line)
}
}
/// Asserts that the current thread is _not_ the one tied to this `EventLoop`.
/// Otherwise, if running in debug mode, the process will be abnormally terminated as per the semantics of
/// `preconditionFailure(_:file:line:)`. Never has any effect in release mode.
///
/// - note: This is not a customization point so calls to this function can be fully optimized out in release mode.
@inlinable
public func assertNotInEventLoop(file: StaticString = #file, line: UInt = #line) {
debugOnly {
self.preconditionNotInEventLoop(file: file, line: line)
}
}
/// Checks the necessary condition of currently running on the called `EventLoop` for making forward progress.
@inlinable
public func preconditionInEventLoop(file: StaticString = #file, line: UInt = #line) {
precondition(self.inEventLoop, file: file, line: line)
}
/// Checks the necessary condition of currently _not_ running on the called `EventLoop` for making forward progress.
@inlinable
public func preconditionNotInEventLoop(file: StaticString = #file, line: UInt = #line) {
precondition(!self.inEventLoop, file: file, line: line)
}
}
/// Internal representation of a `Registration` to an `Selector`.
///
/// Whenever a `Selectable` is registered to a `Selector` a `Registration` is created internally that is also provided within the
/// `SelectorEvent` that is provided to the user when an event is ready to be consumed for a `Selectable`. As we need to have access to the `ServerSocketChannel`
/// and `SocketChannel` (to dispatch the events) we create our own `Registration` that holds a reference to these.
enum NIORegistration: Registration {
case serverSocketChannel(ServerSocketChannel, SelectorEventSet)
case socketChannel(SocketChannel, SelectorEventSet)
case datagramChannel(DatagramChannel, SelectorEventSet)
case pipeChannel(PipeChannel, PipeChannel.Direction, SelectorEventSet)
/// The `SelectorEventSet` in which this `NIORegistration` is interested in.
var interested: SelectorEventSet {
set {
switch self {
case .serverSocketChannel(let c, _):
self = .serverSocketChannel(c, newValue)
case .socketChannel(let c, _):
self = .socketChannel(c, newValue)
case .datagramChannel(let c, _):
self = .datagramChannel(c, newValue)
case .pipeChannel(let c, let d, _):
self = .pipeChannel(c, d, newValue)
}
}
get {
switch self {
case .serverSocketChannel(_, let i):
return i
case .socketChannel(_, let i):
return i
case .datagramChannel(_, let i):
return i
case .pipeChannel(_, _, let i):
return i
}
}
}
}
/// Provides an endless stream of `EventLoop`s to use.
public protocol EventLoopGroup: class {
/// Returns the next `EventLoop` to use.
///
/// The algorithm that is used to select the next `EventLoop` is specific to each `EventLoopGroup`. A common choice
/// is _round robin_.
func next() -> EventLoop
/// Shuts down the eventloop gracefully. This function is clearly an outlier in that it uses a completion
/// callback instead of an EventLoopFuture. The reason for that is that NIO's EventLoopFutures will call back on an event loop.
/// The virtue of this function is to shut the event loop down. To work around that we call back on a DispatchQueue
/// instead.
func shutdownGracefully(queue: DispatchQueue, _ callback: @escaping (Error?) -> Void)
/// Returns an `EventLoopIterator` over the `EventLoop`s in this `EventLoopGroup`.
///
/// - returns: `EventLoopIterator`
func makeIterator() -> EventLoopIterator
}
extension EventLoopGroup {
public func shutdownGracefully(_ callback: @escaping (Error?) -> Void) {
self.shutdownGracefully(queue: .global(), callback)
}
public func syncShutdownGracefully() throws {
if let eventLoop = MultiThreadedEventLoopGroup.currentEventLoop {
preconditionFailure("""
BUG DETECTED: syncShutdownGracefully() must not be called when on an EventLoop.
Calling syncShutdownGracefully() on any EventLoop can lead to deadlocks.
Current eventLoop: \(eventLoop)
""")
}
let errorStorageLock = Lock()
var errorStorage: Error? = nil
let continuation = DispatchWorkItem {}
self.shutdownGracefully { error in
if let error = error {
errorStorageLock.withLock {
errorStorage = error
}
}
continuation.perform()
}
continuation.wait()
try errorStorageLock.withLock {
if let error = errorStorage {
throw error
}
}
}
}
private let nextEventLoopGroupID = NIOAtomic.makeAtomic(value: 0)
/// Called per `NIOThread` that is created for an EventLoop to do custom initialization of the `NIOThread` before the actual `EventLoop` is run on it.
typealias ThreadInitializer = (NIOThread) -> Void
/// An `EventLoopGroup` which will create multiple `EventLoop`s, each tied to its own `NIOThread`.
///
/// The effect of initializing a `MultiThreadedEventLoopGroup` is to spawn `numberOfThreads` fresh threads which will
/// all run their own `EventLoop`. Those threads will not be shut down until `shutdownGracefully` or
/// `syncShutdownGracefully` is called.
///
/// - note: It's good style to call `MultiThreadedEventLoopGroup.shutdownGracefully` or
/// `MultiThreadedEventLoopGroup.syncShutdownGracefully` when you no longer need this `EventLoopGroup`. In
/// many cases that is just before your program exits.
/// - warning: Unit tests often spawn one `MultiThreadedEventLoopGroup` per unit test to force isolation between the
/// tests. In those cases it's important to shut the `MultiThreadedEventLoopGroup` down at the end of the
/// test. A good place to start a `MultiThreadedEventLoopGroup` is the `setUp` method of your `XCTestCase`
/// subclass, a good place to shut it down is the `tearDown` method.
public final class MultiThreadedEventLoopGroup: EventLoopGroup {
private enum RunState {
case running
case closing([(DispatchQueue, (Error?) -> Void)])
case closed(Error?)
}
private static let threadSpecificEventLoop = ThreadSpecificVariable<SelectableEventLoop>()
private let myGroupID: Int
private let index = NIOAtomic<Int>.makeAtomic(value: 0)
private let eventLoops: [SelectableEventLoop]
private let shutdownLock: Lock = Lock()
private var runState: RunState = .running
private static func runTheLoop(thread: NIOThread,
canEventLoopBeShutdownIndividually: Bool,
selectorFactory: @escaping () throws -> NIO.Selector<NIORegistration>,
initializer: @escaping ThreadInitializer,
_ callback: @escaping (SelectableEventLoop) -> Void) {
assert(NIOThread.current == thread)
initializer(thread)
do {
let loop = SelectableEventLoop(thread: thread,
selector: try selectorFactory(),
canBeShutdownIndividually: canEventLoopBeShutdownIndividually)
threadSpecificEventLoop.currentValue = loop
defer {
threadSpecificEventLoop.currentValue = nil
}
callback(loop)
try loop.run()
} catch {
// We fatalError here because the only reasons this can be hit is if the underlying kqueue/epoll give us
// errors that we cannot handle which is an unrecoverable error for us.
fatalError("Unexpected error while running SelectableEventLoop: \(error).")
}
}
private static func setupThreadAndEventLoop(name: String,
selectorFactory: @escaping () throws -> NIO.Selector<NIORegistration>,
initializer: @escaping ThreadInitializer) -> SelectableEventLoop {
let lock = Lock()
/* the `loopUpAndRunningGroup` is done by the calling thread when the EventLoop has been created and was written to `_loop` */
let loopUpAndRunningGroup = DispatchGroup()
/* synchronised by `lock` */
var _loop: SelectableEventLoop! = nil
loopUpAndRunningGroup.enter()
NIOThread.spawnAndRun(name: name, detachThread: false) { t in
MultiThreadedEventLoopGroup.runTheLoop(thread: t,
canEventLoopBeShutdownIndividually: false, // part of MTELG
selectorFactory: selectorFactory,
initializer: initializer) { l in
lock.withLock {
_loop = l
}
loopUpAndRunningGroup.leave()
}
}
loopUpAndRunningGroup.wait()
return lock.withLock { _loop }
}
/// Creates a `MultiThreadedEventLoopGroup` instance which uses `numberOfThreads`.
///
/// - note: Don't forget to call `shutdownGracefully` or `syncShutdownGracefully` when you no longer need this
/// `EventLoopGroup`. If you forget to shut the `EventLoopGroup` down you will leak `numberOfThreads`
/// (kernel) threads which are costly resources. This is especially important in unit tests where one
/// `MultiThreadedEventLoopGroup` is started per test case.
///
/// - arguments:
/// - numberOfThreads: The number of `Threads` to use.
public convenience init(numberOfThreads: Int) {
self.init(numberOfThreads: numberOfThreads, selectorFactory: NIO.Selector<NIORegistration>.init)
}
internal convenience init(numberOfThreads: Int,
selectorFactory: @escaping () throws -> NIO.Selector<NIORegistration>) {
precondition(numberOfThreads > 0, "numberOfThreads must be positive")
let initializers: [ThreadInitializer] = Array(repeating: { _ in }, count: numberOfThreads)
self.init(threadInitializers: initializers, selectorFactory: selectorFactory)
}
/// Creates a `MultiThreadedEventLoopGroup` instance which uses the given `ThreadInitializer`s. One `NIOThread` per `ThreadInitializer` is created and used.
///
/// - arguments:
/// - threadInitializers: The `ThreadInitializer`s to use.
internal init(threadInitializers: [ThreadInitializer],
selectorFactory: @escaping () throws -> NIO.Selector<NIORegistration> = { try .init() }) {
let myGroupID = nextEventLoopGroupID.add(1)
self.myGroupID = myGroupID
var idx = 0
self.eventLoops = threadInitializers.map { initializer in
// Maximum name length on linux is 16 by default.
let ev = MultiThreadedEventLoopGroup.setupThreadAndEventLoop(name: "NIO-ELT-\(myGroupID)-#\(idx)",
selectorFactory: selectorFactory,
initializer: initializer)
idx += 1
return ev
}
}
/// Returns the `EventLoop` for the calling thread.
///
/// - returns: The current `EventLoop` for the calling thread or `nil` if none is assigned to the thread.
public static var currentEventLoop: EventLoop? {
return threadSpecificEventLoop.currentValue
}
/// Returns an `EventLoopIterator` over the `EventLoop`s in this `MultiThreadedEventLoopGroup`.
///
/// - returns: `EventLoopIterator`
public func makeIterator() -> EventLoopIterator {
return EventLoopIterator(self.eventLoops)
}
/// Returns the next `EventLoop` from this `MultiThreadedEventLoopGroup`.
///
/// `MultiThreadedEventLoopGroup` uses _round robin_ across all its `EventLoop`s to select the next one.
///
/// - returns: The next `EventLoop` to use.
public func next() -> EventLoop {
return eventLoops[abs(index.add(1) % eventLoops.count)]
}
/// Shut this `MultiThreadedEventLoopGroup` down which causes the `EventLoop`s and their associated threads to be
/// shut down and release their resources.
///
/// Even though calling `shutdownGracefully` more than once should be avoided, it is safe to do so and execution
/// of the `handler` is guaranteed.
///
/// - parameters:
/// - queue: The `DispatchQueue` to run `handler` on when the shutdown operation completes.
/// - handler: The handler which is called after the shutdown operation completes. The parameter will be `nil`
/// on success and contain the `Error` otherwise.
public func shutdownGracefully(queue: DispatchQueue, _ handler: @escaping (Error?) -> Void) {
// This method cannot perform its final cleanup using EventLoopFutures, because it requires that all
// our event loops still be alive, and they may not be. Instead, we use Dispatch to manage
// our shutdown signaling, and then do our cleanup once the DispatchQueue is empty.
let g = DispatchGroup()
let q = DispatchQueue(label: "nio.shutdownGracefullyQueue", target: queue)
let wasRunning: Bool = self.shutdownLock.withLock {
// We need to check the current `runState` and react accordingly.
switch self.runState {
case .running:
// If we are still running, we set the `runState` to `closing`,
// so that potential future invocations know, that the shutdown
// has already been initiaited.
self.runState = .closing([])
return true
case .closing(var callbacks):
// If we are currently closing, we need to register the `handler`
// for invocation after the shutdown is completed.
callbacks.append((q, handler))
self.runState = .closing(callbacks)
return false
case .closed(let error):
// If we are already closed, we can directly dispatch the `handler`
q.async {
handler(error)
}
return false
}
}
// If the `runState` was not `running` when `shutdownGracefully` was called,
// the shutdown has already been initiated and we have to return here.
guard wasRunning else {
return
}
var result: Result<Void, Error> = .success(())
for loop in self.eventLoops {
g.enter()
loop.initiateClose(queue: q) { closeResult in
switch closeResult {
case .success:
()
case .failure(let error):
result = .failure(error)
}
g.leave()
}
}
g.notify(queue: q) {
for loop in self.eventLoops {
loop.syncFinaliseClose(joinThread: true)
}
var overallError: Error?
var queueCallbackPairs: [(DispatchQueue, (Error?) -> Void)]? = nil
self.shutdownLock.withLock {
switch self.runState {
case .closed, .running:
preconditionFailure("MultiThreadedEventLoopGroup in illegal state when closing: \(self.runState)")
case .closing(let callbacks):
queueCallbackPairs = callbacks
switch result {
case .success:
overallError = nil
case .failure(let error):
overallError = error
}
self.runState = .closed(overallError)
}
}
queue.async {
handler(overallError)
}
for queueCallbackPair in queueCallbackPairs! {
queueCallbackPair.0.async {
queueCallbackPair.1(overallError)
}
}
}
}
/// Convert the calling thread into an `EventLoop`.
///
/// This function will not return until the `EventLoop` has stopped. You can initiate stopping the `EventLoop` by
/// calling `eventLoop.shutdownGracefully` which will eventually make this function return.
///
/// - parameters:
/// - callback: Called _on_ the `EventLoop` that the calling thread was converted to, providing you the
/// `EventLoop` reference. Just like usually on the `EventLoop`, do not block in `callback`.
public static func withCurrentThreadAsEventLoop(_ callback: @escaping (EventLoop) -> Void) {
let callingThread = NIOThread.current
MultiThreadedEventLoopGroup.runTheLoop(thread: callingThread,
canEventLoopBeShutdownIndividually: true,
selectorFactory: NIO.Selector<NIORegistration>.init,
initializer: { _ in }) { loop in
loop.assertInEventLoop()
callback(loop)
}
}
}
extension MultiThreadedEventLoopGroup: CustomStringConvertible {
public var description: String {
return "MultiThreadedEventLoopGroup { threadPattern = NIO-ELT-\(self.myGroupID)-#* }"
}
}
@usableFromInline
internal final class ScheduledTask {
let task: () -> Void
private let failFn: (Error) ->()
@usableFromInline
internal let _readyTime: NIODeadline
@usableFromInline
init(_ task: @escaping () -> Void, _ failFn: @escaping (Error) -> Void, _ time: NIODeadline) {
self.task = task
self.failFn = failFn
self._readyTime = time
}
func readyIn(_ t: NIODeadline) -> TimeAmount {
if _readyTime < t {
return .nanoseconds(0)
}
return _readyTime - t
}
func fail(_ error: Error) {
failFn(error)
}
}
extension ScheduledTask: CustomStringConvertible {
@usableFromInline
var description: String {
return "ScheduledTask(readyTime: \(self._readyTime))"
}
}
extension ScheduledTask: Comparable {
@usableFromInline
static func < (lhs: ScheduledTask, rhs: ScheduledTask) -> Bool {
return lhs._readyTime < rhs._readyTime
}
@usableFromInline
static func == (lhs: ScheduledTask, rhs: ScheduledTask) -> Bool {
return lhs === rhs
}
}
/// Different `Error`s that are specific to `EventLoop` operations / implementations.
public enum EventLoopError: Error {
/// An operation was executed that is not supported by the `EventLoop`
case unsupportedOperation
/// An scheduled task was cancelled.
case cancelled
/// The `EventLoop` was shutdown already.
case shutdown
/// Shutting down the `EventLoop` failed.
case shutdownFailed
}
extension EventLoopError: CustomStringConvertible {
public var description: String {
switch self {
case .unsupportedOperation:
return "EventLoopError: the executed operation is not supported by the event loop"
case .cancelled:
return "EventLoopError: the scheduled task was cancelled"
case .shutdown:
return "EventLoopError: the event loop is shutdown"
case .shutdownFailed:
return "EventLoopError: failed to shutdown the event loop"
}
}
}
| 43.206835 | 198 | 0.6305 |
4838a0a1b2bf9731e9b7be1c6861efad1d2fdb2b | 722 | //
// PersonController.swift
//
//
import Fluent
import Vapor
struct PersonController {
func index(req: Request) throws -> EventLoopFuture<[Person]> {
return Person.query(on: req.db)
.sort(\.$surname, .ascending)
.all()
}
func create(req: Request) throws -> EventLoopFuture<Person> {
let person = try req.content.decode(Person.self)
return person.save(on: req.db).map { person }
}
func delete(req: Request) throws -> EventLoopFuture<HTTPStatus> {
return Person.find(req.parameters.get("personID"), on: req.db)
.unwrap(or: Abort(.notFound))
.flatMap { $0.delete(on: req.db) }
.transform(to: .ok)
}
}
| 25.785714 | 70 | 0.594183 |
f5bdf3c9ad559baf76f1c8fa82580d013ad32383 | 7,135 | //
// BolusTests.swift
// OmniKitTests
//
// Created by Eelke Jager on 04/09/2018.
// Copyright © 2018 Pete Schwamb. All rights reserved.
//
import Foundation
import XCTest
@testable import OmniKit
class BolusTests: XCTestCase {
func testSetBolusCommand() {
// 2017-09-11T11:07:57.476872 ID1:1f08ced2 PTYPE:PDM SEQ:18 ID2:1f08ced2 B9:18 BLEN:31 MTYPE:1a0e BODY:bed2e16b02010a0101a000340034170d000208000186a0 CRC:fd
// 2017-09-11T11:07:57.552574 ID1:1f08ced2 PTYPE:ACK SEQ:19 ID2:1f08ced2 CRC:b8
// 2017-09-11T11:07:57.734557 ID1:1f08ced2 PTYPE:CON SEQ:20 CON:00000000000003c0 CRC:a9
do {
// Decode
let cmd = try SetInsulinScheduleCommand(encodedData: Data(hexadecimalString: "1a0ebed2e16b02010a0101a000340034")!)
XCTAssertEqual(0xbed2e16b, cmd.nonce)
if case SetInsulinScheduleCommand.DeliverySchedule.bolus(let units, let timeBetweenPulses) = cmd.deliverySchedule {
XCTAssertEqual(2.6, units)
XCTAssertEqual(.seconds(1), timeBetweenPulses)
} else {
XCTFail("Expected ScheduleEntry.bolus type")
}
} catch (let error) {
XCTFail("message decoding threw error: \(error)")
}
// Encode
let timeBetweenPulses = TimeInterval(seconds: 1)
let scheduleEntry = SetInsulinScheduleCommand.DeliverySchedule.bolus(units: 2.6, timeBetweenPulses: timeBetweenPulses)
let cmd = SetInsulinScheduleCommand(nonce: 0xbed2e16b, deliverySchedule: scheduleEntry)
XCTAssertEqual("1a0ebed2e16b02010a0101a000340034", cmd.data.hexadecimalString)
}
func testBolusExtraCommand() {
// 30U bolus
// 17 0d 7c 1770 00030d40 000000000000
do {
// Decode
let cmd = try BolusExtraCommand(encodedData: Data(hexadecimalString: "170d7c177000030d40000000000000")!)
XCTAssertEqual(30.0, cmd.units)
XCTAssertEqual(false, cmd.acknowledgementBeep)
XCTAssertEqual(true, cmd.completionBeep)
XCTAssertEqual(.hours(1), cmd.programReminderInterval)
XCTAssertEqual(.seconds(2), cmd.timeBetweenPulses)
XCTAssertEqual(0, cmd.squareWaveUnits)
XCTAssertEqual(0, cmd.squareWaveDuration)
} catch (let error) {
XCTFail("message decoding threw error: \(error)")
}
// Encode typical prime
let cmd = BolusExtraCommand(units: 2.6, timeBetweenPulses: .seconds(1))
XCTAssertEqual("170d000208000186a0000000000000", cmd.data.hexadecimalString)
}
func testBolusExtraOddPulseCount() {
// 17 0d 7c 00fa 00030d40 000000000000
let cmd = BolusExtraCommand(units: 1.25, acknowledgementBeep: false, completionBeep: true, programReminderInterval: .hours(1))
XCTAssertEqual("170d7c00fa00030d40000000000000", cmd.data.hexadecimalString)
}
// 1a 0e NNNNNNNN 02 CCCC HH SSSS 0ppp 0ppp 17 LL RR NNNN XXXXXXXX
// 1a 0e 19e4890b 02 0025 01 0020 0002 0002 17 0d 00 001e 00030d40
// 0ppp = $0002 -> 2 pulses
// NNNN = $001e = 30 (dec) / 10 -> 3 pulses
// Found in PDM logs: 1a0e243085c802002501002000020002 170d00001400030d40000000000000
func testBolusAndBolusExtraMatch() {
let bolusAmount = 0.1
// 1a 0e NNNNNNNN 02 CCCC HH SSSS 0ppp 0ppp
// 1a 0e 243085c8 02 0025 01 0020 0002 0002
let timeBetweenPulses = TimeInterval(seconds: 2)
let scheduleEntry = SetInsulinScheduleCommand.DeliverySchedule.bolus(units: bolusAmount, timeBetweenPulses: timeBetweenPulses)
let bolusCommand = SetInsulinScheduleCommand(nonce: 0x243085c8, deliverySchedule: scheduleEntry)
XCTAssertEqual("1a0e243085c802002501002000020002", bolusCommand.data.hexadecimalString)
// 17 LL RR NNNN XXXXXXXX
// 17 0d 00 0014 00030d40 000000000000
let bolusExtraCommand = BolusExtraCommand(units: bolusAmount)
XCTAssertEqual("170d00001400030d40000000000000", bolusExtraCommand.data.hexadecimalString)
}
func testBolusAndBolusExtraMatch2() {
let bolusAmount = 0.15
let timeBetweenPulses = TimeInterval(seconds: 2)
let scheduleEntry = SetInsulinScheduleCommand.DeliverySchedule.bolus(units: bolusAmount, timeBetweenPulses: timeBetweenPulses)
let bolusCommand = SetInsulinScheduleCommand(nonce: 0x243085c8, deliverySchedule: scheduleEntry)
XCTAssertEqual("1a0e243085c802003701003000030003", bolusCommand.data.hexadecimalString)
let bolusExtraCommand = BolusExtraCommand(units: bolusAmount)
XCTAssertEqual("170d00001e00030d40000000000000", bolusExtraCommand.data.hexadecimalString)
}
func testLargeBolus() {
let bolusAmount = 29.95
let timeBetweenPulses = TimeInterval(seconds: 2)
let scheduleEntry = SetInsulinScheduleCommand.DeliverySchedule.bolus(units: bolusAmount, timeBetweenPulses: timeBetweenPulses)
let bolusCommand = SetInsulinScheduleCommand(nonce: 0x31204ba7, deliverySchedule: scheduleEntry)
XCTAssertEqual("1a0e31204ba702014801257002570257", bolusCommand.data.hexadecimalString)
let bolusExtraCommand = BolusExtraCommand(units: bolusAmount, acknowledgementBeep: false, completionBeep: true, programReminderInterval: .hours(1))
XCTAssertEqual("170d7c176600030d40000000000000", bolusExtraCommand.data.hexadecimalString)
}
func testOddBolus() {
// 1a 0e NNNNNNNN 02 CCCC HH SSSS 0ppp 0ppp
// 1a 0e cf9e81ac 02 00e5 01 0290 0029 0029
let bolusAmount = 2.05
let timeBetweenPulses = TimeInterval(seconds: 2)
let scheduleEntry = SetInsulinScheduleCommand.DeliverySchedule.bolus(units: bolusAmount, timeBetweenPulses: timeBetweenPulses)
let bolusCommand = SetInsulinScheduleCommand(nonce: 0xcf9e81ac, deliverySchedule: scheduleEntry)
XCTAssertEqual("1a0ecf9e81ac0200e501029000290029", bolusCommand.data.hexadecimalString)
// 17 LL RR NNNN XXXXXXXX
// 17 0d 3c 019a 00030d40 0000 00000000
let bolusExtraCommand = BolusExtraCommand(units: bolusAmount, acknowledgementBeep: false, completionBeep: false, programReminderInterval: .hours(1))
XCTAssertEqual("170d3c019a00030d40000000000000", bolusExtraCommand.data.hexadecimalString)
}
func testCancelBolusCommand() {
do {
// Decode 1f 05 4d91f8ff 64
let cmd = try CancelDeliveryCommand(encodedData: Data(hexadecimalString: "1f054d91f8ff64")!)
XCTAssertEqual(0x4d91f8ff, cmd.nonce)
XCTAssertEqual(.beeeeeep, cmd.beepType)
XCTAssertEqual(.bolus, cmd.deliveryType)
} catch (let error) {
XCTFail("message decoding threw error: \(error)")
}
// Encode
let cmd = CancelDeliveryCommand(nonce: 0x4d91f8ff, deliveryType: .bolus, beepType: .beeeeeep)
XCTAssertEqual("1f054d91f8ff64", cmd.data.hexadecimalString)
}
}
| 47.566667 | 167 | 0.690399 |
ccd594ff407dd2a3bf8bf086d7e231588b427866 | 2,183 | //
// AppDelegate.swift
// AHFuture
//
// Created by AlexHmelevskiAG on 04/08/2017.
// Copyright (c) 2017 AlexHmelevskiAG. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| 46.446809 | 285 | 0.755383 |
6902d9ef55ea79c3bded73cf18f1f26831e0da1a | 237 | //
// Actions.swift
// ReduxSwiftExamples
//
// Created by Andy Saw on 2018/10/28.
// Copyright © 2018 andyksaw. All rights reserved.
//
import ReduxSwift
struct IncrementCounterAction: StoreActionable {
let amount: Int
}
| 15.8 | 51 | 0.696203 |
38a84f491a903e9f76631da42ac8562a4467cd4e | 74,637 | import XCTest
import CleanReversi
import CleanReversiAsync
import CleanReversiApp
class GameControllerTests: XCTestCase {
func testInit() {
do { // Without a saved game
let delegate = TestDelegate()
_ = GameController(delegate: delegate)
XCTAssertEqual(delegate.message, .turn(.dark))
XCTAssertEqual(delegate.diskCounts, [.dark: 2, .light: 2])
XCTAssertEqual(delegate.players, [.dark: .manual, .light: .manual])
XCTAssertEqual(delegate.playerActivityIndicatorVisibilities, [.dark: false, .light: false])
XCTAssertEqual(delegate.board, Board(width: 8, height: 8))
XCTAssertNil(delegate.passAlertSide)
XCTAssertFalse(delegate.isWatingForBoardAnimation())
XCTAssertFalse(delegate.isWatingForResetGameConfirmation())
XCTAssertFalse(delegate.isWatingForPassAlertCompletion())
XCTAssertEqual(delegate.savedState, GameController.SavedState(
turn: .dark,
darkPlayer: .manual,
lightPlayer: .manual,
board: Board(width: 8, height: 8)
))
XCTAssertNil(delegate.boardForMove)
XCTAssertNil(delegate.sideForMove)
XCTAssertFalse(delegate.isWaitingForMoveOfAI())
}
do { // With a saved game
let delegate = TestDelegate()
let board = Board("""
---xxoo-
x-xx-oxx
xxx-xxox
ooooxxo-
--xoxxx-
----x--o
--------
--------
""")
let savedState: GameController.SavedState = .init(
turn: .light,
darkPlayer: .computer,
lightPlayer: .computer,
board: board
)
delegate.savedState = savedState
_ = GameController(delegate: delegate)
XCTAssertEqual(delegate.message, .turn(.light))
XCTAssertEqual(delegate.diskCounts, [.dark: 20, .light: 11])
XCTAssertEqual(delegate.players, [.dark: .computer, .light: .computer])
XCTAssertEqual(delegate.playerActivityIndicatorVisibilities, [.dark: false, .light: false])
XCTAssertEqual(delegate.board, board)
XCTAssertNil(delegate.passAlertSide)
XCTAssertFalse(delegate.isWatingForBoardAnimation())
XCTAssertFalse(delegate.isWatingForResetGameConfirmation())
XCTAssertFalse(delegate.isWatingForPassAlertCompletion())
XCTAssertEqual(delegate.savedState, savedState)
XCTAssertNil(delegate.boardForMove)
XCTAssertNil(delegate.sideForMove)
XCTAssertFalse(delegate.isWaitingForMoveOfAI())
}
do { // With a saved game finished
let delegate = TestDelegate()
let board = Board("""
oxxxxxxx
xxxxxxxx
xxxxxxxx
xxxxxxxx
xxxxxxxx
xxxxxxxx
xxxxxxxx
xxxxxxxx
""")
let savedState: GameController.SavedState = .init(
turn: nil,
darkPlayer: .manual,
lightPlayer: .computer,
board: board
)
delegate.savedState = savedState
_ = GameController(delegate: delegate)
XCTAssertEqual(delegate.message, .result(winner: .dark))
XCTAssertEqual(delegate.diskCounts, [.dark: 63, .light: 1])
XCTAssertEqual(delegate.players, [.dark: .manual, .light: .computer])
XCTAssertEqual(delegate.playerActivityIndicatorVisibilities, [.dark: false, .light: false])
XCTAssertEqual(delegate.board, board)
XCTAssertNil(delegate.passAlertSide)
XCTAssertFalse(delegate.isWatingForBoardAnimation())
XCTAssertFalse(delegate.isWatingForResetGameConfirmation())
XCTAssertFalse(delegate.isWatingForPassAlertCompletion())
XCTAssertEqual(delegate.savedState, savedState)
XCTAssertNil(delegate.boardForMove)
XCTAssertNil(delegate.sideForMove)
XCTAssertFalse(delegate.isWaitingForMoveOfAI())
}
}
func testStart() {
do {
let delegate = TestDelegate()
let controller = GameController(delegate: delegate)
do {
try controller.start()
} catch _ {
XCTFail()
return
}
XCTAssertEqual(delegate.message, .turn(.dark))
XCTAssertEqual(delegate.diskCounts, [.dark: 2, .light: 2])
XCTAssertEqual(delegate.players, [.dark: .manual, .light: .manual])
XCTAssertEqual(delegate.playerActivityIndicatorVisibilities, [.dark: false, .light: false])
XCTAssertEqual(delegate.board, Board(width: 8, height: 8))
XCTAssertNil(delegate.passAlertSide)
XCTAssertFalse(delegate.isWatingForBoardAnimation())
XCTAssertFalse(delegate.isWatingForResetGameConfirmation())
XCTAssertFalse(delegate.isWatingForPassAlertCompletion())
XCTAssertEqual(delegate.savedState, GameController.SavedState(
turn: .dark,
darkPlayer: .manual,
lightPlayer: .manual,
board: Board(width: 8, height: 8)
))
XCTAssertNil(delegate.boardForMove)
XCTAssertNil(delegate.sideForMove)
XCTAssertFalse(delegate.isWaitingForMoveOfAI())
// Duplicate `start` calls cause errors
do {
try controller.start()
XCTFail()
return
} catch let error as GameController.StartError {
switch error {
case .alreadyStarted:
break
}
} catch _ {
XCTFail()
return
}
}
// With a saved game with a turn of a computer player.
// - The activity indicator of the light player must be visible
// - Properties related to `moveHandler` must be set
do {
let delegate = TestDelegate()
let board = Board("""
--------
--------
--------
---ox---
---xxx--
--------
--------
--------
""")
let savedState: GameController.SavedState = .init(
turn: .light,
darkPlayer: .computer,
lightPlayer: .computer,
board: board
)
delegate.savedState = savedState
let controller = GameController(delegate: delegate)
do {
try controller.start()
} catch _ {
XCTFail()
return
}
XCTAssertEqual(delegate.message, .turn(.light))
XCTAssertEqual(delegate.diskCounts, [.dark: 4, .light: 1])
XCTAssertEqual(delegate.players, [.dark: .computer, .light: .computer])
XCTAssertEqual(delegate.playerActivityIndicatorVisibilities, [.dark: false, .light: true])
XCTAssertEqual(delegate.board, board)
XCTAssertNil(delegate.passAlertSide)
XCTAssertFalse(delegate.isWatingForBoardAnimation())
XCTAssertFalse(delegate.isWatingForResetGameConfirmation())
XCTAssertFalse(delegate.isWatingForPassAlertCompletion())
XCTAssertEqual(delegate.savedState, savedState)
XCTAssertEqual(delegate.boardForMove, board)
XCTAssertEqual(delegate.sideForMove, .light)
XCTAssertTrue(delegate.isWaitingForMoveOfAI())
}
}
func testSetPlayer() {
let delegate = TestDelegate()
let board0: Board = .init(width: 8, height: 8)
let board1: Board = Board("""
--------
--------
---x----
---xx---
---xo---
--------
--------
--------
""")
let savedState: GameController.SavedState = .init(
turn: .dark,
darkPlayer: .manual,
lightPlayer: .manual,
board: board0
)
let controller = GameController(delegate: delegate)
do {
try controller.start()
} catch _ {
XCTFail()
return
}
// Sets a player mode of the turn to `.computer` and the AI starts thinking.
// - The activity indicator of the dark player must be made visible
// - Properties related to `moveHandler` must be set
// - Player modes in the saved state must be updated
do {
delegate.setPlayer(.computer, of: .dark)
controller.setPlayer(.computer, of: .dark)
XCTAssertEqual(delegate.message, .turn(.dark))
XCTAssertEqual(delegate.diskCounts, [.dark: 2, .light: 2])
XCTAssertEqual(delegate.players, [.dark: .computer, .light: .manual])
XCTAssertEqual(delegate.playerActivityIndicatorVisibilities, [.dark: true, .light: false])
XCTAssertEqual(delegate.board, board0)
XCTAssertNil(delegate.passAlertSide)
XCTAssertFalse(delegate.isWatingForBoardAnimation())
XCTAssertFalse(delegate.isWatingForResetGameConfirmation())
XCTAssertFalse(delegate.isWatingForPassAlertCompletion())
XCTAssertEqual(delegate.savedState, GameController.SavedState(
turn: .dark,
darkPlayer: .computer,
lightPlayer: .manual,
board: board0
))
XCTAssertEqual(delegate.boardForMove, board0)
XCTAssertEqual(delegate.sideForMove, .dark)
XCTAssertTrue(delegate.isWaitingForMoveOfAI())
}
// Set a player mode of the turn back to `.manual` while the AI is thinking.
// - The activity indicator of the dark player must be made invisible
// - Properties related to `moveHandler` must be unset
// - Player modes in the saved state must be updated
do {
let moveHandler = delegate.moveHandler!
delegate.setPlayer(.manual, of: .dark)
controller.setPlayer(.manual, of: .dark)
XCTAssertEqual(delegate.message, .turn(.dark))
XCTAssertEqual(delegate.diskCounts, [.dark: 2, .light: 2])
XCTAssertEqual(delegate.players, [.dark: .manual, .light: .manual])
XCTAssertEqual(delegate.playerActivityIndicatorVisibilities, [.dark: false, .light: false])
XCTAssertEqual(delegate.board, board0)
XCTAssertNil(delegate.passAlertSide)
XCTAssertFalse(delegate.isWatingForBoardAnimation())
XCTAssertFalse(delegate.isWatingForResetGameConfirmation())
XCTAssertFalse(delegate.isWatingForPassAlertCompletion())
XCTAssertEqual(delegate.savedState, savedState)
XCTAssertNil(delegate.boardForMove)
XCTAssertNil(delegate.sideForMove)
XCTAssertFalse(delegate.isWaitingForMoveOfAI())
// Calling handlers after cancelled must be ignored.
moveHandler(3, 2)
XCTAssertEqual(delegate.message, .turn(.dark))
XCTAssertEqual(delegate.diskCounts, [.dark: 2, .light: 2])
XCTAssertEqual(delegate.players, [.dark: .manual, .light: .manual])
XCTAssertEqual(delegate.playerActivityIndicatorVisibilities, [.dark: false, .light: false])
XCTAssertEqual(delegate.board, board0)
XCTAssertNil(delegate.passAlertSide)
XCTAssertFalse(delegate.isWatingForBoardAnimation())
XCTAssertFalse(delegate.isWatingForResetGameConfirmation())
XCTAssertFalse(delegate.isWatingForPassAlertCompletion())
XCTAssertEqual(delegate.savedState, savedState)
XCTAssertNil(delegate.boardForMove)
XCTAssertNil(delegate.sideForMove)
XCTAssertFalse(delegate.isWaitingForMoveOfAI())
}
// Set a `.light` player mode to `.computer` while `turn` is `.dark`.
// - The activity indicator of the light player must keep invisible
// - Properties related to `moveHandler` must keep unset
// - Player modes in the saved state must be updated
do {
delegate.setPlayer(.computer, of: .light)
controller.setPlayer(.computer, of: .light)
XCTAssertEqual(delegate.message, .turn(.dark))
XCTAssertEqual(delegate.diskCounts, [.dark: 2, .light: 2])
XCTAssertEqual(delegate.players, [.dark: .manual, .light: .computer])
XCTAssertEqual(delegate.playerActivityIndicatorVisibilities, [.dark: false, .light: false])
XCTAssertEqual(delegate.board, board0)
XCTAssertNil(delegate.passAlertSide)
XCTAssertFalse(delegate.isWatingForBoardAnimation())
XCTAssertFalse(delegate.isWatingForResetGameConfirmation())
XCTAssertFalse(delegate.isWatingForPassAlertCompletion())
XCTAssertEqual(delegate.savedState, GameController.SavedState(
turn: .dark,
darkPlayer: .manual,
lightPlayer: .computer,
board: board0
))
XCTAssertNil(delegate.boardForMove)
XCTAssertNil(delegate.sideForMove)
XCTAssertFalse(delegate.isWaitingForMoveOfAI())
}
// Set a `.dark` player mode to `.computer` while board animations.
// - The activity indicator of the dark player must keep invisible
// - Properties related to `moveHandler` must keep unset
// - Player modes in the saved state must be updated
do {
delegate.setPlayer(.manual, of: .dark)
controller.setPlayer(.manual, of: .dark)
do {
try controller.placeDiskAt(x: 3, y: 2)
} catch _ {
XCTFail()
return
}
delegate.setPlayer(.computer, of: .dark)
controller.setPlayer(.computer, of: .dark)
XCTAssertEqual(delegate.message, .turn(.dark))
XCTAssertEqual(delegate.diskCounts, [.dark: 2, .light: 2]) // Updated after animations
XCTAssertEqual(delegate.players, [.dark: .computer, .light: .computer])
XCTAssertEqual(delegate.playerActivityIndicatorVisibilities, [.dark: false, .light: false])
XCTAssertEqual(delegate.board, board1)
XCTAssertNil(delegate.passAlertSide)
XCTAssertTrue(delegate.isWatingForBoardAnimation())
XCTAssertFalse(delegate.isWatingForResetGameConfirmation())
XCTAssertFalse(delegate.isWatingForPassAlertCompletion())
XCTAssertEqual(delegate.savedState, GameController.SavedState(
turn: .light,
darkPlayer: .computer,
lightPlayer: .computer,
board: board1
))
XCTAssertNil(delegate.boardForMove)
XCTAssertNil(delegate.sideForMove)
XCTAssertFalse(delegate.isWaitingForMoveOfAI())
}
}
func testReset() {
do {
let delegate = TestDelegate()
let board = Board("""
---xxoo-
x-xx-oxx
xxx-xxox
ooooxxo-
--xoxxx-
----x--o
--------
--------
""")
let savedState: GameController.SavedState = .init(
turn: .light,
darkPlayer: .manual,
lightPlayer: .manual,
board: board
)
delegate.savedState = savedState
let controller = GameController(delegate: delegate)
do {
try controller.start()
} catch _ {
XCTFail()
return
}
do { // During confirmations
controller.reset()
XCTAssertEqual(delegate.message, .turn(.light))
XCTAssertEqual(delegate.diskCounts, [.dark: 20, .light: 11])
XCTAssertEqual(delegate.players, [.dark: .manual, .light: .manual])
XCTAssertEqual(delegate.playerActivityIndicatorVisibilities, [.dark: false, .light: false])
XCTAssertEqual(delegate.board, board)
XCTAssertNil(delegate.passAlertSide)
XCTAssertFalse(delegate.isWatingForBoardAnimation())
XCTAssertTrue(delegate.isWatingForResetGameConfirmation())
XCTAssertFalse(delegate.isWatingForPassAlertCompletion())
XCTAssertEqual(delegate.savedState, savedState)
XCTAssertNil(delegate.boardForMove)
XCTAssertNil(delegate.sideForMove)
XCTAssertFalse(delegate.isWaitingForMoveOfAI())
}
do { // Cancels condirmation
do {
try delegate.completeResetGameConfirmation(isConfirmed: false)
} catch _ {
XCTFail()
return
}
XCTAssertEqual(delegate.message, .turn(.light))
XCTAssertEqual(delegate.diskCounts, [.dark: 20, .light: 11])
XCTAssertEqual(delegate.players, [.dark: .manual, .light: .manual])
XCTAssertEqual(delegate.playerActivityIndicatorVisibilities, [.dark: false, .light: false])
XCTAssertEqual(delegate.board, board)
XCTAssertNil(delegate.passAlertSide)
XCTAssertFalse(delegate.isWatingForBoardAnimation())
XCTAssertFalse(delegate.isWatingForResetGameConfirmation())
XCTAssertFalse(delegate.isWatingForPassAlertCompletion())
XCTAssertEqual(delegate.savedState, savedState)
XCTAssertNil(delegate.boardForMove)
XCTAssertNil(delegate.sideForMove)
XCTAssertFalse(delegate.isWaitingForMoveOfAI())
}
do { // Resets games
controller.reset()
do {
try delegate.completeResetGameConfirmation(isConfirmed: true)
} catch _ {
XCTFail()
return
}
XCTAssertEqual(delegate.message, .turn(.dark))
XCTAssertEqual(delegate.diskCounts, [.dark: 2, .light: 2])
XCTAssertEqual(delegate.players, [.dark: .manual, .light: .manual])
XCTAssertEqual(delegate.playerActivityIndicatorVisibilities, [.dark: false, .light: false])
XCTAssertEqual(delegate.board, Board(width: 8, height: 8))
XCTAssertNil(delegate.passAlertSide)
XCTAssertFalse(delegate.isWatingForBoardAnimation())
XCTAssertFalse(delegate.isWatingForResetGameConfirmation())
XCTAssertFalse(delegate.isWatingForPassAlertCompletion())
XCTAssertEqual(delegate.savedState, GameController.SavedState(
turn: .dark,
darkPlayer: .manual,
lightPlayer: .manual,
board: Board(width: 8, height: 8)
))
XCTAssertNil(delegate.boardForMove)
XCTAssertNil(delegate.sideForMove)
XCTAssertFalse(delegate.isWaitingForMoveOfAI())
}
}
do { // Resets during waiting for moves of `.computer`
let delegate = TestDelegate()
let board = Board("""
--------
--------
--------
---ox---
---xxx--
--------
--------
--------
""")
let savedState: GameController.SavedState = .init(
turn: .light,
darkPlayer: .computer,
lightPlayer: .computer,
board: board
)
delegate.savedState = savedState
let controller = GameController(delegate: delegate)
do {
try controller.start()
} catch _ {
XCTFail()
return
}
controller.reset()
XCTAssertTrue(delegate.isWatingForResetGameConfirmation())
do {
try delegate.completeResetGameConfirmation(isConfirmed: true)
} catch _ {
XCTFail()
return
}
XCTAssertEqual(delegate.message, .turn(.dark))
XCTAssertEqual(delegate.diskCounts, [.dark: 2, .light: 2])
XCTAssertEqual(delegate.players, [.dark: .manual, .light: .manual])
XCTAssertEqual(delegate.playerActivityIndicatorVisibilities, [.dark: false, .light: false])
XCTAssertEqual(delegate.board, Board(width: 8, height: 8))
XCTAssertNil(delegate.passAlertSide)
XCTAssertFalse(delegate.isWatingForBoardAnimation())
XCTAssertFalse(delegate.isWatingForResetGameConfirmation())
XCTAssertFalse(delegate.isWatingForPassAlertCompletion())
XCTAssertEqual(delegate.savedState, GameController.SavedState(
turn: .dark,
darkPlayer: .manual,
lightPlayer: .manual,
board: Board(width: 8, height: 8)
))
XCTAssertNil(delegate.boardForMove)
XCTAssertNil(delegate.sideForMove)
XCTAssertFalse(delegate.isWaitingForMoveOfAI())
}
do { // Resets during waiting for borad animations
let delegate = TestDelegate()
let board = Board("""
--------
--------
--------
---ox---
---xxx--
--------
--------
--------
""")
let savedState: GameController.SavedState = .init(
turn: .light,
darkPlayer: .manual,
lightPlayer: .manual,
board: board
)
delegate.savedState = savedState
let controller = GameController(delegate: delegate)
do {
try controller.start()
} catch _ {
XCTFail()
return
}
do {
try controller.placeDiskAt(x: 3, y: 5)
} catch _ {
XCTFail()
return
}
XCTAssertTrue(delegate.isWatingForBoardAnimation())
controller.reset()
XCTAssertTrue(delegate.isWatingForResetGameConfirmation())
do {
try delegate.completeResetGameConfirmation(isConfirmed: true)
} catch _ {
XCTFail()
return
}
XCTAssertEqual(delegate.message, .turn(.dark))
XCTAssertEqual(delegate.diskCounts, [.dark: 2, .light: 2])
XCTAssertEqual(delegate.players, [.dark: .manual, .light: .manual])
XCTAssertEqual(delegate.playerActivityIndicatorVisibilities, [.dark: false, .light: false])
XCTAssertEqual(delegate.board, Board(width: 8, height: 8))
XCTAssertNil(delegate.passAlertSide)
XCTAssertFalse(delegate.isWatingForBoardAnimation())
XCTAssertFalse(delegate.isWatingForResetGameConfirmation())
XCTAssertFalse(delegate.isWatingForPassAlertCompletion())
XCTAssertEqual(delegate.savedState, GameController.SavedState(
turn: .dark,
darkPlayer: .manual,
lightPlayer: .manual,
board: Board(width: 8, height: 8)
))
XCTAssertNil(delegate.boardForMove)
XCTAssertNil(delegate.sideForMove)
XCTAssertFalse(delegate.isWaitingForMoveOfAI())
}
}
func testPlaceDisk() {
do {
let delegate = TestDelegate()
let controller = GameController(delegate: delegate)
do {
try controller.start()
} catch _ {
XCTFail()
return
}
let board0: Board = .init(width: 8, height: 8)
let board1: Board = .init("""
--------
--------
--------
---ox---
---xx---
----x---
--------
--------
""")
let board2: Board = .init("""
--------
--------
--------
---ox---
---xo---
----xo--
--------
--------
""")
do { // during wating for a player
func assertDelegate() {
XCTAssertEqual(delegate.message, .turn(.dark))
XCTAssertEqual(delegate.diskCounts, [.dark: 2, .light: 2])
XCTAssertEqual(delegate.players, [.dark: .manual, .light: .manual])
XCTAssertEqual(delegate.playerActivityIndicatorVisibilities, [.dark: false, .light: false])
XCTAssertEqual(delegate.board, board0)
XCTAssertNil(delegate.passAlertSide)
XCTAssertFalse(delegate.isWatingForBoardAnimation())
XCTAssertFalse(delegate.isWatingForResetGameConfirmation())
XCTAssertFalse(delegate.isWatingForPassAlertCompletion())
XCTAssertEqual(delegate.savedState, GameController.SavedState(
turn: .dark,
darkPlayer: .manual,
lightPlayer: .manual,
board: board0
))
XCTAssertNil(delegate.boardForMove)
XCTAssertNil(delegate.sideForMove)
XCTAssertFalse(delegate.isWaitingForMoveOfAI())
}
assertDelegate()
// invalid placing disks during wating for a player
for y in 0 ..< 8 {
for x in 0 ..< 8 {
if board0.canPlaceDisk(.dark, atX: x, y: y) { continue }
do {
try controller.placeDiskAt(x: x, y: y)
XCTFail()
return
} catch GameController.MoveError.invalidMove(
.illegalPosition(x: let ex, y: let ey)
) {
XCTAssertEqual(ex, x)
XCTAssertEqual(ey, y)
assertDelegate()
} catch _ {
XCTFail()
return
}
}
}
}
do { // move of the dark-side player
try controller.placeDiskAt(x: 4, y: 5)
} catch _ {
XCTFail()
return
}
do { // during board animations
func assertDelegate() {
XCTAssertEqual(delegate.message, .turn(.dark))
XCTAssertEqual(delegate.diskCounts, [.dark: 2, .light: 2]) // Updated after animations
XCTAssertEqual(delegate.players, [.dark: .manual, .light: .manual])
XCTAssertEqual(delegate.playerActivityIndicatorVisibilities, [.dark: false, .light: false])
XCTAssertEqual(delegate.board, board1)
XCTAssertNil(delegate.passAlertSide)
XCTAssertTrue(delegate.isWatingForBoardAnimation())
XCTAssertFalse(delegate.isWatingForResetGameConfirmation())
XCTAssertFalse(delegate.isWatingForPassAlertCompletion())
XCTAssertEqual(delegate.savedState, GameController.SavedState(
turn: .light,
darkPlayer: .manual,
lightPlayer: .manual,
board: board1
))
XCTAssertNil(delegate.boardForMove)
XCTAssertNil(delegate.sideForMove)
XCTAssertFalse(delegate.isWaitingForMoveOfAI())
}
assertDelegate()
// invalid placing disks during animations
for y in 0 ..< 8 {
for x in 0 ..< 8 {
do {
try controller.placeDiskAt(x: x, y: y)
XCTFail()
return
} catch GameController.MoveError.duringAnimations {
assertDelegate()
} catch _ {
XCTFail()
return
}
}
}
}
do { // completes board animations
try delegate.completeBoardAnimation()
} catch _ {
XCTFail()
return
}
do { // during wating for a player
func assertDelegate() {
XCTAssertEqual(delegate.message, .turn(.light))
XCTAssertEqual(delegate.diskCounts, [.dark: 4, .light: 1])
XCTAssertEqual(delegate.players, [.dark: .manual, .light: .manual])
XCTAssertEqual(delegate.playerActivityIndicatorVisibilities, [.dark: false, .light: false])
XCTAssertEqual(delegate.board, board1)
XCTAssertNil(delegate.passAlertSide)
XCTAssertFalse(delegate.isWatingForBoardAnimation())
XCTAssertFalse(delegate.isWatingForResetGameConfirmation())
XCTAssertFalse(delegate.isWatingForPassAlertCompletion())
XCTAssertEqual(delegate.savedState, GameController.SavedState(
turn: .light,
darkPlayer: .manual,
lightPlayer: .manual,
board: board1
))
XCTAssertNil(delegate.boardForMove)
XCTAssertNil(delegate.sideForMove)
XCTAssertFalse(delegate.isWaitingForMoveOfAI())
}
assertDelegate()
// invalid placing disks during wating for a player
for y in 0 ..< 8 {
for x in 0 ..< 8 {
if board1.canPlaceDisk(.light, atX: x, y: y) { continue }
do {
try controller.placeDiskAt(x: x, y: y)
XCTFail()
return
} catch GameController.MoveError.invalidMove(
.illegalPosition(x: let ex, y: let ey)
) {
XCTAssertEqual(ex, x)
XCTAssertEqual(ey, y)
assertDelegate()
} catch _ {
XCTFail()
return
}
}
}
}
do { // move of the light-side player
try controller.placeDiskAt(x: 5, y: 5)
} catch _ {
XCTFail()
return
}
do { // during board animations
func assertDelegate() {
XCTAssertEqual(delegate.message, .turn(.light))
XCTAssertEqual(delegate.diskCounts, [.dark: 4, .light: 1]) // Updated after animations
XCTAssertEqual(delegate.players, [.dark: .manual, .light: .manual])
XCTAssertEqual(delegate.playerActivityIndicatorVisibilities, [.dark: false, .light: false])
XCTAssertEqual(delegate.board, board2)
XCTAssertNil(delegate.passAlertSide)
XCTAssertTrue(delegate.isWatingForBoardAnimation())
XCTAssertFalse(delegate.isWatingForResetGameConfirmation())
XCTAssertFalse(delegate.isWatingForPassAlertCompletion())
XCTAssertEqual(delegate.savedState, GameController.SavedState(
turn: .dark,
darkPlayer: .manual,
lightPlayer: .manual,
board: board2
))
XCTAssertNil(delegate.boardForMove)
XCTAssertNil(delegate.sideForMove)
XCTAssertFalse(delegate.isWaitingForMoveOfAI())
}
assertDelegate()
// invalid placing disks during animations
for y in 0 ..< 8 {
for x in 0 ..< 8 {
do {
try controller.placeDiskAt(x: x, y: y)
XCTFail()
return
} catch GameController.MoveError.duringAnimations {
assertDelegate()
} catch _ {
XCTFail()
return
}
}
}
}
do { // completes board animations
try delegate.completeBoardAnimation()
} catch _ {
XCTFail()
return
}
do { // result
XCTAssertEqual(delegate.message, .turn(.dark))
XCTAssertEqual(delegate.diskCounts, [.dark: 3, .light: 3])
XCTAssertEqual(delegate.players, [.dark: .manual, .light: .manual])
XCTAssertEqual(delegate.playerActivityIndicatorVisibilities, [.dark: false, .light: false])
XCTAssertEqual(delegate.board, board2)
XCTAssertNil(delegate.passAlertSide)
XCTAssertFalse(delegate.isWatingForBoardAnimation())
XCTAssertFalse(delegate.isWatingForResetGameConfirmation())
XCTAssertFalse(delegate.isWatingForPassAlertCompletion())
XCTAssertEqual(delegate.savedState, GameController.SavedState(
turn: .dark,
darkPlayer: .manual,
lightPlayer: .manual,
board: board2
))
XCTAssertNil(delegate.boardForMove)
XCTAssertNil(delegate.sideForMove)
XCTAssertFalse(delegate.isWaitingForMoveOfAI())
}
}
do { // passes
let delegate = TestDelegate()
let board0: Board = .init("""
--------
--------
--------
xxxxxxxx
oooooooo
oooooooo
oooooooo
oooooooo
""")
let board1: Board = .init("""
--------
--------
-------o
xxxxxxoo
oooooooo
oooooooo
oooooooo
oooooooo
""")
let savedState: GameController.SavedState = .init(
turn: .light,
darkPlayer: .manual,
lightPlayer: .manual,
board: board0
)
delegate.savedState = savedState
let controller = GameController(delegate: delegate)
do {
try controller.start()
} catch _ {
XCTFail()
return
}
do { // during wating for a player
XCTAssertEqual(delegate.message, .turn(.light))
XCTAssertEqual(delegate.diskCounts, [.dark: 8, .light: 32])
XCTAssertEqual(delegate.players, [.dark: .manual, .light: .manual])
XCTAssertEqual(delegate.playerActivityIndicatorVisibilities, [.dark: false, .light: false])
XCTAssertEqual(delegate.board, board0)
XCTAssertNil(delegate.passAlertSide)
XCTAssertFalse(delegate.isWatingForBoardAnimation())
XCTAssertFalse(delegate.isWatingForResetGameConfirmation())
XCTAssertFalse(delegate.isWatingForPassAlertCompletion())
XCTAssertEqual(delegate.savedState, GameController.SavedState(
turn: .light,
darkPlayer: .manual,
lightPlayer: .manual,
board: board0
))
XCTAssertNil(delegate.boardForMove)
XCTAssertNil(delegate.sideForMove)
XCTAssertFalse(delegate.isWaitingForMoveOfAI())
}
do { // move of the light-side player
try controller.placeDiskAt(x: 7, y: 2)
} catch _ {
XCTFail()
return
}
do { // during board animations
XCTAssertEqual(delegate.message, .turn(.light))
XCTAssertEqual(delegate.diskCounts, [.dark: 8, .light: 32]) // Updated after animations
XCTAssertEqual(delegate.players, [.dark: .manual, .light: .manual])
XCTAssertEqual(delegate.playerActivityIndicatorVisibilities, [.dark: false, .light: false])
XCTAssertEqual(delegate.board, board1)
XCTAssertNil(delegate.passAlertSide)
XCTAssertTrue(delegate.isWatingForBoardAnimation())
XCTAssertFalse(delegate.isWatingForResetGameConfirmation())
XCTAssertFalse(delegate.isWatingForPassAlertCompletion())
XCTAssertEqual(delegate.savedState, GameController.SavedState(
turn: .light, // it can be omitted to save passes
darkPlayer: .manual,
lightPlayer: .manual,
board: board1
))
XCTAssertNil(delegate.boardForMove)
XCTAssertNil(delegate.sideForMove)
XCTAssertFalse(delegate.isWaitingForMoveOfAI())
}
do { // completes board animations
try delegate.completeBoardAnimation()
} catch _ {
XCTFail()
return
}
do { // pass of the dark-side player
XCTAssertEqual(delegate.message, .turn(.dark))
XCTAssertEqual(delegate.diskCounts, [.dark: 6, .light: 35])
XCTAssertEqual(delegate.players, [.dark: .manual, .light: .manual])
XCTAssertEqual(delegate.playerActivityIndicatorVisibilities, [.dark: false, .light: false])
XCTAssertEqual(delegate.board, board1)
XCTAssertEqual(delegate.passAlertSide, .dark)
XCTAssertFalse(delegate.isWatingForBoardAnimation())
XCTAssertFalse(delegate.isWatingForResetGameConfirmation())
XCTAssertTrue(delegate.isWatingForPassAlertCompletion())
XCTAssertEqual(delegate.savedState, GameController.SavedState(
turn: .light, // it can be omitted to save passes
darkPlayer: .manual,
lightPlayer: .manual,
board: board1
))
XCTAssertNil(delegate.boardForMove)
XCTAssertNil(delegate.sideForMove)
XCTAssertFalse(delegate.isWaitingForMoveOfAI())
}
do { // dismisses a pass plert
try delegate.completePassAlert()
} catch _ {
XCTFail()
return
}
do { // result
XCTAssertEqual(delegate.message, .turn(.light))
XCTAssertEqual(delegate.diskCounts, [.dark: 6, .light: 35])
XCTAssertEqual(delegate.players, [.dark: .manual, .light: .manual])
XCTAssertEqual(delegate.playerActivityIndicatorVisibilities, [.dark: false, .light: false])
XCTAssertEqual(delegate.board, board1)
XCTAssertNil(delegate.passAlertSide)
XCTAssertFalse(delegate.isWatingForBoardAnimation())
XCTAssertFalse(delegate.isWatingForResetGameConfirmation())
XCTAssertFalse(delegate.isWatingForPassAlertCompletion())
XCTAssertEqual(delegate.savedState, GameController.SavedState(
turn: .light,
darkPlayer: .manual,
lightPlayer: .manual,
board: board1
))
XCTAssertNil(delegate.boardForMove)
XCTAssertNil(delegate.sideForMove)
XCTAssertFalse(delegate.isWaitingForMoveOfAI())
}
}
do { // over
let delegate = TestDelegate()
let board0: Board = .init("""
--oxxxxx
xxxxxxxx
xxxxxxxx
xxxxxxxx
xxxxxxxx
xxxxxxxx
xxxxxxxx
xxxxxxxx
""")
let board1: Board = .init("""
-xxxxxxx
xxxxxxxx
xxxxxxxx
xxxxxxxx
xxxxxxxx
xxxxxxxx
xxxxxxxx
xxxxxxxx
""")
let savedState: GameController.SavedState = .init(
turn: .dark,
darkPlayer: .manual,
lightPlayer: .manual,
board: board0
)
delegate.savedState = savedState
let controller = GameController(delegate: delegate)
do {
try controller.start()
} catch _ {
XCTFail()
return
}
do { // during wating for a player
XCTAssertEqual(delegate.message, .turn(.dark))
XCTAssertEqual(delegate.diskCounts, [.dark: 61, .light: 1])
XCTAssertEqual(delegate.players, [.dark: .manual, .light: .manual])
XCTAssertEqual(delegate.playerActivityIndicatorVisibilities, [.dark: false, .light: false])
XCTAssertEqual(delegate.board, board0)
XCTAssertNil(delegate.passAlertSide)
XCTAssertFalse(delegate.isWatingForBoardAnimation())
XCTAssertFalse(delegate.isWatingForResetGameConfirmation())
XCTAssertFalse(delegate.isWatingForPassAlertCompletion())
XCTAssertEqual(delegate.savedState, GameController.SavedState(
turn: .dark,
darkPlayer: .manual,
lightPlayer: .manual,
board: board0
))
XCTAssertNil(delegate.boardForMove)
XCTAssertNil(delegate.sideForMove)
XCTAssertFalse(delegate.isWaitingForMoveOfAI())
}
do { // move of the light-side player
try controller.placeDiskAt(x: 1, y: 0)
} catch _ {
XCTFail()
return
}
do { // during board animations
XCTAssertEqual(delegate.message, .turn(.dark))
XCTAssertEqual(delegate.diskCounts, [.dark: 61, .light: 1]) // Updated after animations
XCTAssertEqual(delegate.players, [.dark: .manual, .light: .manual])
XCTAssertEqual(delegate.playerActivityIndicatorVisibilities, [.dark: false, .light: false])
XCTAssertEqual(delegate.board, board1)
XCTAssertNil(delegate.passAlertSide)
XCTAssertTrue(delegate.isWatingForBoardAnimation())
XCTAssertFalse(delegate.isWatingForResetGameConfirmation())
XCTAssertFalse(delegate.isWatingForPassAlertCompletion())
XCTAssertEqual(delegate.savedState, GameController.SavedState(
turn: nil,
darkPlayer: .manual,
lightPlayer: .manual,
board: board1
))
XCTAssertNil(delegate.boardForMove)
XCTAssertNil(delegate.sideForMove)
XCTAssertFalse(delegate.isWaitingForMoveOfAI())
}
do { // completes board animations
try delegate.completeBoardAnimation()
} catch _ {
XCTFail()
return
}
do { // result
XCTAssertEqual(delegate.message, .result(winner: .dark))
XCTAssertEqual(delegate.diskCounts, [.dark: 63, .light: 0])
XCTAssertEqual(delegate.players, [.dark: .manual, .light: .manual])
XCTAssertEqual(delegate.playerActivityIndicatorVisibilities, [.dark: false, .light: false])
XCTAssertEqual(delegate.board, board1)
XCTAssertNil(delegate.passAlertSide)
XCTAssertFalse(delegate.isWatingForBoardAnimation())
XCTAssertFalse(delegate.isWatingForResetGameConfirmation())
XCTAssertFalse(delegate.isWatingForPassAlertCompletion())
XCTAssertEqual(delegate.savedState, GameController.SavedState(
turn: nil,
darkPlayer: .manual,
lightPlayer: .manual,
board: board1
))
XCTAssertNil(delegate.boardForMove)
XCTAssertNil(delegate.sideForMove)
XCTAssertFalse(delegate.isWaitingForMoveOfAI())
}
}
}
func testComputers() {
do {
let delegate = TestDelegate()
let controller = GameController(delegate: delegate)
delegate.setPlayer(.computer, of: .dark)
controller.setPlayer(.computer, of: .dark)
delegate.setPlayer(.computer, of: .light)
controller.setPlayer(.computer, of: .light)
do {
try controller.start()
} catch _ {
XCTFail()
return
}
let board0: Board = .init(width: 8, height: 8)
let board1: Board = .init("""
--------
--------
--------
---ox---
---xx---
----x---
--------
--------
""")
let board2: Board = .init("""
--------
--------
--------
---ox---
---xo---
----xo--
--------
--------
""")
do { // during wating for a player
func assertDelegate() {
XCTAssertEqual(delegate.message, .turn(.dark))
XCTAssertEqual(delegate.diskCounts, [.dark: 2, .light: 2])
XCTAssertEqual(delegate.players, [.dark: .computer, .light: .computer])
XCTAssertEqual(delegate.playerActivityIndicatorVisibilities, [.dark: true, .light: false])
XCTAssertEqual(delegate.board, board0)
XCTAssertNil(delegate.passAlertSide)
XCTAssertFalse(delegate.isWatingForBoardAnimation())
XCTAssertFalse(delegate.isWatingForResetGameConfirmation())
XCTAssertFalse(delegate.isWatingForPassAlertCompletion())
XCTAssertEqual(delegate.savedState, GameController.SavedState(
turn: .dark,
darkPlayer: .computer,
lightPlayer: .computer,
board: board0
))
XCTAssertEqual(delegate.boardForMove, board0)
XCTAssertEqual(delegate.sideForMove, .dark)
XCTAssertTrue(delegate.isWaitingForMoveOfAI())
}
assertDelegate()
// invalid placing disks during wating for a player
for y in 0 ..< 8 {
for x in 0 ..< 8 {
do {
try controller.placeDiskAt(x: x, y: y)
XCTFail()
return
} catch GameController.MoveError.playerInTurnIsNotManual {
assertDelegate()
} catch _ {
XCTFail()
return
}
}
}
}
do { // move of the dark-side player
try delegate.handleMoveOfAIAt(x: 4, y: 5)
} catch _ {
XCTFail()
return
}
do { // during board animations
func assertDelegate() {
XCTAssertEqual(delegate.message, .turn(.dark))
XCTAssertEqual(delegate.diskCounts, [.dark: 2, .light: 2]) // Updated after animations
XCTAssertEqual(delegate.players, [.dark: .computer, .light: .computer])
XCTAssertEqual(delegate.playerActivityIndicatorVisibilities, [.dark: false, .light: false])
XCTAssertEqual(delegate.board, board1)
XCTAssertNil(delegate.passAlertSide)
XCTAssertTrue(delegate.isWatingForBoardAnimation())
XCTAssertFalse(delegate.isWatingForResetGameConfirmation())
XCTAssertFalse(delegate.isWatingForPassAlertCompletion())
XCTAssertEqual(delegate.savedState, GameController.SavedState(
turn: .light,
darkPlayer: .computer,
lightPlayer: .computer,
board: board1
))
XCTAssertNil(delegate.boardForMove)
XCTAssertNil(delegate.sideForMove)
XCTAssertFalse(delegate.isWaitingForMoveOfAI())
}
assertDelegate()
// invalid placing disks during animations
for y in 0 ..< 8 {
for x in 0 ..< 8 {
do {
try controller.placeDiskAt(x: x, y: y)
XCTFail()
return
} catch GameController.MoveError.duringAnimations {
assertDelegate()
} catch _ {
XCTFail()
return
}
}
}
}
do { // completes board animations
try delegate.completeBoardAnimation()
} catch _ {
XCTFail()
return
}
do { // placing diks while a computer player is thinking
func assertDelegate() {
XCTAssertEqual(delegate.message, .turn(.light))
XCTAssertEqual(delegate.diskCounts, [.dark: 4, .light: 1])
XCTAssertEqual(delegate.players, [.dark: .computer, .light: .computer])
XCTAssertEqual(delegate.playerActivityIndicatorVisibilities, [.dark: false, .light: true])
XCTAssertEqual(delegate.board, board1)
XCTAssertNil(delegate.passAlertSide)
XCTAssertFalse(delegate.isWatingForBoardAnimation())
XCTAssertFalse(delegate.isWatingForResetGameConfirmation())
XCTAssertFalse(delegate.isWatingForPassAlertCompletion())
XCTAssertEqual(delegate.savedState, GameController.SavedState(
turn: .light,
darkPlayer: .computer,
lightPlayer: .computer,
board: board1
))
XCTAssertEqual(delegate.boardForMove, board1)
XCTAssertEqual(delegate.sideForMove, .light)
XCTAssertTrue(delegate.isWaitingForMoveOfAI())
}
assertDelegate()
for y in 0 ..< 8 {
for x in 0 ..< 8 {
do {
try controller.placeDiskAt(x: x, y: y)
XCTFail()
return
} catch GameController.MoveError.playerInTurnIsNotManual {
assertDelegate()
} catch _ {
XCTFail()
return
}
}
}
}
do { // move of the light-side player
try delegate.handleMoveOfAIAt(x: 5, y: 5)
} catch _ {
XCTFail()
return
}
do { // during board animations
func assertDelegate() {
XCTAssertEqual(delegate.message, .turn(.light))
XCTAssertEqual(delegate.diskCounts, [.dark: 4, .light: 1]) // Updated after animations
XCTAssertEqual(delegate.players, [.dark: .computer, .light: .computer])
XCTAssertEqual(delegate.playerActivityIndicatorVisibilities, [.dark: false, .light: false])
XCTAssertEqual(delegate.board, board2)
XCTAssertNil(delegate.passAlertSide)
XCTAssertTrue(delegate.isWatingForBoardAnimation())
XCTAssertFalse(delegate.isWatingForResetGameConfirmation())
XCTAssertFalse(delegate.isWatingForPassAlertCompletion())
XCTAssertEqual(delegate.savedState, GameController.SavedState(
turn: .dark,
darkPlayer: .computer,
lightPlayer: .computer,
board: board2
))
XCTAssertNil(delegate.boardForMove)
XCTAssertNil(delegate.sideForMove)
XCTAssertFalse(delegate.isWaitingForMoveOfAI())
}
assertDelegate()
// invalid placing disks during animations
for y in 0 ..< 8 {
for x in 0 ..< 8 {
do {
try controller.placeDiskAt(x: x, y: y)
XCTFail()
return
} catch GameController.MoveError.duringAnimations {
assertDelegate()
} catch _ {
XCTFail()
return
}
}
}
}
do { // completes board animations
try delegate.completeBoardAnimation()
} catch _ {
XCTFail()
return
}
do { // result
XCTAssertEqual(delegate.message, .turn(.dark))
XCTAssertEqual(delegate.diskCounts, [.dark: 3, .light: 3])
XCTAssertEqual(delegate.players, [.dark: .computer, .light: .computer])
XCTAssertEqual(delegate.playerActivityIndicatorVisibilities, [.dark: true, .light: false])
XCTAssertEqual(delegate.board, board2)
XCTAssertNil(delegate.passAlertSide)
XCTAssertFalse(delegate.isWatingForBoardAnimation())
XCTAssertFalse(delegate.isWatingForResetGameConfirmation())
XCTAssertFalse(delegate.isWatingForPassAlertCompletion())
XCTAssertEqual(delegate.savedState, GameController.SavedState(
turn: .dark,
darkPlayer: .computer,
lightPlayer: .computer,
board: board2
))
XCTAssertEqual(delegate.boardForMove, board2)
XCTAssertEqual(delegate.sideForMove, .dark)
XCTAssertTrue(delegate.isWaitingForMoveOfAI())
}
}
do { // passes
let delegate = TestDelegate()
let board0: Board = .init("""
--------
--------
--------
xxxxxxxx
oooooooo
oooooooo
oooooooo
oooooooo
""")
let board1: Board = .init("""
--------
--------
-------o
xxxxxxoo
oooooooo
oooooooo
oooooooo
oooooooo
""")
let savedState: GameController.SavedState = .init(
turn: .light,
darkPlayer: .computer,
lightPlayer: .computer,
board: board0
)
delegate.savedState = savedState
let controller = GameController(delegate: delegate)
do {
try controller.start()
} catch _ {
XCTFail()
return
}
do { // during wating for a player
XCTAssertEqual(delegate.message, .turn(.light))
XCTAssertEqual(delegate.diskCounts, [.dark: 8, .light: 32])
XCTAssertEqual(delegate.players, [.dark: .computer, .light: .computer])
XCTAssertEqual(delegate.playerActivityIndicatorVisibilities, [.dark: false, .light: true])
XCTAssertEqual(delegate.board, board0)
XCTAssertNil(delegate.passAlertSide)
XCTAssertFalse(delegate.isWatingForBoardAnimation())
XCTAssertFalse(delegate.isWatingForResetGameConfirmation())
XCTAssertFalse(delegate.isWatingForPassAlertCompletion())
XCTAssertEqual(delegate.savedState, GameController.SavedState(
turn: .light,
darkPlayer: .computer,
lightPlayer: .computer,
board: board0
))
XCTAssertEqual(delegate.boardForMove, board0)
XCTAssertEqual(delegate.sideForMove, .light)
XCTAssertTrue(delegate.isWaitingForMoveOfAI())
}
do { // move of the light-side player
try delegate.handleMoveOfAIAt(x: 7, y: 2)
} catch _ {
XCTFail()
return
}
do { // during board animations
XCTAssertEqual(delegate.message, .turn(.light))
XCTAssertEqual(delegate.diskCounts, [.dark: 8, .light: 32]) // Updated after animations
XCTAssertEqual(delegate.players, [.dark: .computer, .light: .computer])
XCTAssertEqual(delegate.playerActivityIndicatorVisibilities, [.dark: false, .light: false])
XCTAssertEqual(delegate.board, board1)
XCTAssertNil(delegate.passAlertSide)
XCTAssertTrue(delegate.isWatingForBoardAnimation())
XCTAssertFalse(delegate.isWatingForResetGameConfirmation())
XCTAssertFalse(delegate.isWatingForPassAlertCompletion())
XCTAssertEqual(delegate.savedState, GameController.SavedState(
turn: .light, // it can be omitted to save passes
darkPlayer: .computer,
lightPlayer: .computer,
board: board1
))
XCTAssertNil(delegate.boardForMove)
XCTAssertNil(delegate.sideForMove)
XCTAssertFalse(delegate.isWaitingForMoveOfAI())
}
do { // completes board animations
try delegate.completeBoardAnimation()
} catch _ {
XCTFail()
return
}
do { // pass of the dark-side player
XCTAssertEqual(delegate.message, .turn(.dark))
XCTAssertEqual(delegate.diskCounts, [.dark: 6, .light: 35])
XCTAssertEqual(delegate.players, [.dark: .computer, .light: .computer])
XCTAssertEqual(delegate.playerActivityIndicatorVisibilities, [.dark: false, .light: false])
XCTAssertEqual(delegate.board, board1)
XCTAssertEqual(delegate.passAlertSide, .dark)
XCTAssertFalse(delegate.isWatingForBoardAnimation())
XCTAssertFalse(delegate.isWatingForResetGameConfirmation())
XCTAssertTrue(delegate.isWatingForPassAlertCompletion())
XCTAssertEqual(delegate.savedState, GameController.SavedState(
turn: .light, // it can be omitted to save passes
darkPlayer: .computer,
lightPlayer: .computer,
board: board1
))
XCTAssertNil(delegate.boardForMove)
XCTAssertNil(delegate.sideForMove)
XCTAssertFalse(delegate.isWaitingForMoveOfAI())
}
do { // dismisses a pass plert
try delegate.completePassAlert()
} catch _ {
XCTFail()
return
}
do { // result
XCTAssertEqual(delegate.message, .turn(.light))
XCTAssertEqual(delegate.diskCounts, [.dark: 6, .light: 35])
XCTAssertEqual(delegate.players, [.dark: .computer, .light: .computer])
XCTAssertEqual(delegate.playerActivityIndicatorVisibilities, [.dark: false, .light: true])
XCTAssertEqual(delegate.board, board1)
XCTAssertNil(delegate.passAlertSide)
XCTAssertFalse(delegate.isWatingForBoardAnimation())
XCTAssertFalse(delegate.isWatingForResetGameConfirmation())
XCTAssertFalse(delegate.isWatingForPassAlertCompletion())
XCTAssertEqual(delegate.savedState, GameController.SavedState(
turn: .light,
darkPlayer: .computer,
lightPlayer: .computer,
board: board1
))
XCTAssertEqual(delegate.boardForMove, board1)
XCTAssertEqual(delegate.sideForMove, .light)
XCTAssertTrue(delegate.isWaitingForMoveOfAI())
}
}
do { // over
let delegate = TestDelegate()
let board0: Board = .init("""
--oxxxxx
xxxxxxxx
xxxxxxxx
xxxxxxxx
xxxxxxxx
xxxxxxxx
xxxxxxxx
xxxxxxxx
""")
let board1: Board = .init("""
-xxxxxxx
xxxxxxxx
xxxxxxxx
xxxxxxxx
xxxxxxxx
xxxxxxxx
xxxxxxxx
xxxxxxxx
""")
let savedState: GameController.SavedState = .init(
turn: .dark,
darkPlayer: .computer,
lightPlayer: .computer,
board: board0
)
delegate.savedState = savedState
let controller = GameController(delegate: delegate)
do {
try controller.start()
} catch _ {
XCTFail()
return
}
do { // during wating for a player
XCTAssertEqual(delegate.message, .turn(.dark))
XCTAssertEqual(delegate.diskCounts, [.dark: 61, .light: 1])
XCTAssertEqual(delegate.players, [.dark: .computer, .light: .computer])
XCTAssertEqual(delegate.playerActivityIndicatorVisibilities, [.dark: true, .light: false])
XCTAssertEqual(delegate.board, board0)
XCTAssertNil(delegate.passAlertSide)
XCTAssertFalse(delegate.isWatingForBoardAnimation())
XCTAssertFalse(delegate.isWatingForResetGameConfirmation())
XCTAssertFalse(delegate.isWatingForPassAlertCompletion())
XCTAssertEqual(delegate.savedState, GameController.SavedState(
turn: .dark,
darkPlayer: .computer,
lightPlayer: .computer,
board: board0
))
XCTAssertEqual(delegate.boardForMove, board0)
XCTAssertEqual(delegate.sideForMove, .dark)
XCTAssertTrue(delegate.isWaitingForMoveOfAI())
}
do { // move of the light-side player
try delegate.handleMoveOfAIAt(x: 1, y: 0)
} catch _ {
XCTFail()
return
}
do { // during board animations
XCTAssertEqual(delegate.message, .turn(.dark))
XCTAssertEqual(delegate.diskCounts, [.dark: 61, .light: 1]) // Updated after animations
XCTAssertEqual(delegate.players, [.dark: .computer, .light: .computer])
XCTAssertEqual(delegate.playerActivityIndicatorVisibilities, [.dark: false, .light: false])
XCTAssertEqual(delegate.board, board1)
XCTAssertNil(delegate.passAlertSide)
XCTAssertTrue(delegate.isWatingForBoardAnimation())
XCTAssertFalse(delegate.isWatingForResetGameConfirmation())
XCTAssertFalse(delegate.isWatingForPassAlertCompletion())
XCTAssertEqual(delegate.savedState, GameController.SavedState(
turn: nil,
darkPlayer: .computer,
lightPlayer: .computer,
board: board1
))
XCTAssertNil(delegate.boardForMove)
XCTAssertNil(delegate.sideForMove)
XCTAssertFalse(delegate.isWaitingForMoveOfAI())
}
do { // completes board animations
try delegate.completeBoardAnimation()
} catch _ {
XCTFail()
return
}
do { // result
XCTAssertEqual(delegate.message, .result(winner: .dark))
XCTAssertEqual(delegate.diskCounts, [.dark: 63, .light: 0])
XCTAssertEqual(delegate.players, [.dark: .computer, .light: .computer])
XCTAssertEqual(delegate.playerActivityIndicatorVisibilities, [.dark: false, .light: false])
XCTAssertEqual(delegate.board, board1)
XCTAssertNil(delegate.passAlertSide)
XCTAssertFalse(delegate.isWatingForBoardAnimation())
XCTAssertFalse(delegate.isWatingForResetGameConfirmation())
XCTAssertFalse(delegate.isWatingForPassAlertCompletion())
XCTAssertEqual(delegate.savedState, GameController.SavedState(
turn: nil,
darkPlayer: .computer,
lightPlayer: .computer,
board: board1
))
XCTAssertNil(delegate.boardForMove)
XCTAssertNil(delegate.sideForMove)
XCTAssertFalse(delegate.isWaitingForMoveOfAI())
}
} }
}
class TestDelegate {
// GameControllerDelegate
private(set) var message: GameController.Message?
private(set) var diskCounts: [Disk: Int] = [:]
private(set) var players: [Disk: GameController.Player] = [:]
private(set) var playerActivityIndicatorVisibilities: [Disk: Bool] = [:]
private(set) var board: Board?
private(set) var passAlertSide: Disk?
private(set) var boardAnimationCompletion: (() -> Void)?
private(set) var resetGameConfirmationCompletion: ((Bool) -> Void)?
private(set) var passAlertCompletion: (() -> Void)?
// GameControllerSaveDelegate
var savedState: GameController.SavedState?
// GameControllerStrategyDelegate
private(set) var boardForMove: Board?
private(set) var sideForMove: Disk?
private(set) var moveHandler: ((Int, Int) -> Void)?
}
extension TestDelegate: GameControllerDelegate {
func updateMessage(_ message: GameController.Message, animated isAnimated: Bool) {
self.message = message
}
func updateDiskCountsOf(dark darkDiskCount: Int, light lightDiskCount: Int, animated isAnimated: Bool) {
diskCounts[.dark] = darkDiskCount
diskCounts[.light] = lightDiskCount
}
func updatePlayer(_ player: GameController.Player, of side: Disk, animated isAnimated: Bool) {
players[side] = player
}
func updatePlayerActivityInidicatorVisibility(_ isVisible: Bool, of side: Disk, animated isAnimated: Bool) {
playerActivityIndicatorVisibilities[side] = isVisible
}
func updateBoard(_ board: Board, animated isAnimated: Bool, completion: @escaping () -> Void) -> Canceller {
self.board = board
boardAnimationCompletion = completion
let canceller = Canceller { [weak self] in
self?.boardAnimationCompletion = nil
}
if !isAnimated {
try! completeBoardAnimation()
}
return canceller
}
func confirmToResetGame(completion: @escaping (Bool) -> Void) {
resetGameConfirmationCompletion = completion
}
func alertPass(of side: Disk, completion: @escaping () -> Void) {
passAlertSide = side
passAlertCompletion = completion
}
func completeBoardAnimation() throws {
guard let completion = boardAnimationCompletion else { throw GeneralError() }
completion()
boardAnimationCompletion = nil
}
func completeResetGameConfirmation(isConfirmed: Bool) throws {
guard let completion = resetGameConfirmationCompletion else { throw GeneralError() }
completion(isConfirmed)
resetGameConfirmationCompletion = nil
}
func completePassAlert() throws {
guard let completion = passAlertCompletion else { throw GeneralError() }
completion()
passAlertSide = nil
passAlertCompletion = nil
}
func setPlayer(_ player: GameController.Player, of side: Disk) {
players[side] = player
}
func clearPlayers() {
players = [:]
}
func isWatingForBoardAnimation() -> Bool {
boardAnimationCompletion != nil
}
func isWatingForResetGameConfirmation() -> Bool {
resetGameConfirmationCompletion != nil
}
func isWatingForPassAlertCompletion() -> Bool {
passAlertCompletion != nil
}
}
extension TestDelegate: GameControllerSaveDelegate {
func saveGame(_ state: GameController.SavedState) throws {
savedState = state
}
func loadGame() throws -> GameController.SavedState {
guard let savedState = savedState else { throw GeneralError() }
return savedState
}
}
extension TestDelegate: GameControllerStrategyDelegate {
func move(for board: Board, of side: Disk, handler: @escaping (Int, Int) -> Void) -> Canceller {
boardForMove = board
sideForMove = side
moveHandler = handler
return Canceller { [weak self] in
guard let self = self else { return }
self.boardForMove = nil
self.sideForMove = nil
self.moveHandler = nil
}
}
func handleMoveOfAIAt(x: Int, y: Int) throws {
guard let completion = moveHandler else { throw GeneralError() }
completion(x, y)
boardForMove = nil
sideForMove = nil
moveHandler = nil
}
func isWaitingForMoveOfAI() -> Bool {
moveHandler != nil
}
}
| 39.097433 | 112 | 0.509318 |
8ac2861c6ebaa513d0ca3a676493fe13528f7502 | 13,761 | // RUN: %target-run-simple-swift
// REQUIRES: executable_test
// REQUIRES: rdar50301438
// REQUIRES: objc_interop
// UNSUPPORTED: OS=watchos
import StdlibUnittest
import Accelerate
var AccelerateQuadratureTests = TestSuite("Accelerate_Quadrature")
//===----------------------------------------------------------------------===//
//
// Quadrature Tests
//
//===----------------------------------------------------------------------===//
if #available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) {
func vectorExp(x: UnsafeBufferPointer<Double>,
y: UnsafeMutableBufferPointer<Double>) {
let radius: Double = 12.5
for i in 0 ..< x.count {
y[i] = sqrt(radius * radius - pow(x[i] - radius, 2))
}
}
AccelerateQuadratureTests.test("Quadrature/QNG") {
var diameter: Double = 25
// New API: Scalar
let quadrature = Quadrature(integrator: .nonAdaptive,
absoluteTolerance: 1.0e-8,
relativeTolerance: 1.0e-2)
let result = quadrature.integrate(over: 0.0 ... diameter) { x in
let radius = diameter * 0.5
return sqrt(radius * radius - pow(x - radius, 2))
}
// New API: Vectorized
let vQuadrature = Quadrature(integrator: .nonAdaptive,
absoluteTolerance: 1.0e-8,
relativeTolerance: 1.0e-2)
let vRresult = vQuadrature.integrate(over: 0.0 ... diameter,
integrand: vectorExp)
// Legacy API
var integrateFunction: quadrature_integrate_function = {
return quadrature_integrate_function(
fun: { (arg: UnsafeMutableRawPointer?,
n: Int,
x: UnsafePointer<Double>,
y: UnsafeMutablePointer<Double>
) in
guard let diameter = arg?.load(as: Double.self) else {
return
}
let r = diameter * 0.5
(0 ..< n).forEach { i in
y[i] = sqrt(r * r - pow(x[i] - r, 2))
}
},
fun_arg: &diameter)
}()
var options = quadrature_integrate_options(integrator: QUADRATURE_INTEGRATE_QNG,
abs_tolerance: 1.0e-8,
rel_tolerance: 1.0e-2,
qag_points_per_interval: 0,
max_intervals: 0)
var status = QUADRATURE_SUCCESS
var legacyEstimatedAbsoluteError: Double = 0
let legacyResult = quadrature_integrate(&integrateFunction,
0.0,
diameter,
&options,
&status,
&legacyEstimatedAbsoluteError,
0,
nil)
switch result {
case .success(let integralResult, let estimatedAbsoluteError):
expectEqual(integralResult, legacyResult)
expectEqual(estimatedAbsoluteError, legacyEstimatedAbsoluteError)
switch vRresult {
case .success(let vIntegralResult, let vEstimatedAbsoluteError):
expectEqual(integralResult, vIntegralResult)
expectEqual(estimatedAbsoluteError, vEstimatedAbsoluteError)
case .failure(_):
expectationFailure("Vectorized non-adaptive integration failed.", trace: "",
stackTrace: SourceLocStack())
}
case .failure( _):
expectationFailure("Non-adaptive integration failed.", trace: "",
stackTrace: SourceLocStack())
}
}
AccelerateQuadratureTests.test("Quadrature/QAGS") {
var diameter: Double = 25
// New API
let quadrature = Quadrature(integrator: .adaptiveWithSingularities(maxIntervals: 11),
absoluteTolerance: 1.0e-8,
relativeTolerance: 1.0e-2)
let result = quadrature.integrate(over: 0.0 ... diameter) { x in
let radius = diameter * 0.5
return sqrt(radius * radius - pow(x - radius, 2))
}
// New API: Vectorized
let vQuadrature = Quadrature(integrator: .adaptiveWithSingularities(maxIntervals: 11),
absoluteTolerance: 1.0e-8,
relativeTolerance: 1.0e-2)
let vRresult = vQuadrature.integrate(over: 0.0 ... diameter,
integrand: vectorExp)
// Legacy API
var integrateFunction: quadrature_integrate_function = {
return quadrature_integrate_function(
fun: { (arg: UnsafeMutableRawPointer?,
n: Int,
x: UnsafePointer<Double>,
y: UnsafeMutablePointer<Double>
) in
guard let diameter = arg?.load(as: Double.self) else {
return
}
let r = diameter * 0.5
(0 ..< n).forEach { i in
y[i] = sqrt(r * r - pow(x[i] - r, 2))
}
},
fun_arg: &diameter)
}()
var options = quadrature_integrate_options(integrator: QUADRATURE_INTEGRATE_QAGS,
abs_tolerance: 1.0e-8,
rel_tolerance: 1.0e-2,
qag_points_per_interval: 0,
max_intervals: 11)
var status = QUADRATURE_SUCCESS
var legacyEstimatedAbsoluteError = Double(0)
let legacyResult = quadrature_integrate(&integrateFunction,
0,
diameter,
&options,
&status,
&legacyEstimatedAbsoluteError,
0,
nil)
switch result {
case .success(let integralResult, let estimatedAbsoluteError):
expectEqual(integralResult, legacyResult)
expectEqual(estimatedAbsoluteError, legacyEstimatedAbsoluteError)
switch vRresult {
case .success(let vIntegralResult, let vEstimatedAbsoluteError):
expectEqual(integralResult, vIntegralResult)
expectEqual(estimatedAbsoluteError, vEstimatedAbsoluteError)
case .failure(_):
expectationFailure("Vectorized adaptive with singularities integration failed.", trace: "",
stackTrace: SourceLocStack())
}
case .failure( _):
expectationFailure("Adaptive with singularities integration failed.", trace: "",
stackTrace: SourceLocStack())
}
}
AccelerateQuadratureTests.test("Quadrature/QAG") {
var diameter: Double = 25
// New API
let quadrature = Quadrature(integrator: .adaptive(pointsPerInterval: .sixtyOne,
maxIntervals: 7),
absoluteTolerance: 1.0e-8,
relativeTolerance: 1.0e-2)
let result = quadrature.integrate(over: 0.0 ... diameter) { x in
let radius: Double = diameter * 0.5
return sqrt(radius * radius - pow(x - radius, 2))
}
// New API: Vectorized
let vQuadrature = Quadrature(integrator: .adaptive(pointsPerInterval: .sixtyOne,
maxIntervals: 7),
absoluteTolerance: 1.0e-8,
relativeTolerance: 1.0e-2)
let vRresult = vQuadrature.integrate(over: 0.0 ... diameter,
integrand: vectorExp)
// Legacy API
var integrateFunction: quadrature_integrate_function = {
return quadrature_integrate_function(
fun: { (arg: UnsafeMutableRawPointer?,
n: Int,
x: UnsafePointer<Double>,
y: UnsafeMutablePointer<Double>
) in
guard let diameter = arg?.load(as: Double.self) else {
return
}
let r = diameter * 0.5
(0 ..< n).forEach { i in
y[i] = sqrt(r * r - pow(x[i] - r, 2))
}
},
fun_arg: &diameter)
}()
var options = quadrature_integrate_options(integrator: QUADRATURE_INTEGRATE_QAG,
abs_tolerance: 1.0e-8,
rel_tolerance: 1.0e-2,
qag_points_per_interval: 61,
max_intervals: 7)
var status = QUADRATURE_SUCCESS
var legacyEstimatedAbsoluteError = Double(0)
let legacyResult = quadrature_integrate(&integrateFunction,
0,
diameter,
&options,
&status,
&legacyEstimatedAbsoluteError,
0,
nil)
switch result {
case .success(let integralResult, let estimatedAbsoluteError):
expectEqual(integralResult, legacyResult)
expectEqual(estimatedAbsoluteError, legacyEstimatedAbsoluteError)
switch vRresult {
case .success(let vIntegralResult, let vEstimatedAbsoluteError):
expectEqual(integralResult, vIntegralResult)
expectEqual(estimatedAbsoluteError, vEstimatedAbsoluteError)
case .failure(_):
expectationFailure("Vectorized adaptive integration failed.", trace: "",
stackTrace: SourceLocStack())
}
case .failure( _):
expectationFailure("Adaptive integration failed.", trace: "",
stackTrace: SourceLocStack())
}
}
AccelerateQuadratureTests.test("Quadrature/ToleranceProperties") {
var quadrature = Quadrature(integrator: .qng,
absoluteTolerance: 1,
relativeTolerance: 2)
expectEqual(quadrature.absoluteTolerance, 1)
expectEqual(quadrature.relativeTolerance, 2)
quadrature.absoluteTolerance = 101
quadrature.relativeTolerance = 102
expectEqual(quadrature.absoluteTolerance, 101)
expectEqual(quadrature.relativeTolerance, 102)
}
AccelerateQuadratureTests.test("Quadrature/QAGPointsPerInterval") {
expectEqual(Quadrature.QAGPointsPerInterval.fifteen.points, 15)
expectEqual(Quadrature.QAGPointsPerInterval.twentyOne.points, 21)
expectEqual(Quadrature.QAGPointsPerInterval.thirtyOne.points, 31)
expectEqual(Quadrature.QAGPointsPerInterval.fortyOne.points, 41)
expectEqual(Quadrature.QAGPointsPerInterval.fiftyOne.points, 51)
expectEqual(Quadrature.QAGPointsPerInterval.sixtyOne.points, 61)
}
AccelerateQuadratureTests.test("Quadrature/ErrorDescription") {
let a = Quadrature.Error(quadratureStatus: QUADRATURE_ERROR)
expectEqual(a.errorDescription, "Generic error.")
let b = Quadrature.Error(quadratureStatus: QUADRATURE_INVALID_ARG_ERROR)
expectEqual(b.errorDescription, "Invalid Argument.")
let c = Quadrature.Error(quadratureStatus: QUADRATURE_INTERNAL_ERROR)
expectEqual(c.errorDescription, "This is a bug in the Quadrature code, please file a bug report.")
let d = Quadrature.Error(quadratureStatus: QUADRATURE_INTEGRATE_MAX_EVAL_ERROR)
expectEqual(d.errorDescription, "The requested accuracy limit could not be reached with the allowed number of evals/subdivisions.")
let e = Quadrature.Error(quadratureStatus: QUADRATURE_INTEGRATE_BAD_BEHAVIOUR_ERROR)
expectEqual(e.errorDescription, "Extremely bad integrand behaviour, or excessive roundoff error occurs at some points of the integration interval.")
}
}
runAllTests()
| 44.247588 | 156 | 0.482668 |
3a9df843876c3ac18180dd7ff698af37e4d6842f | 1,026 | //
// VITMobileSSOFrameworkTests.swift
// VITMobileSSOFrameworkTests
//
// Created by Antti Laitinen on 21/02/2017.
// Copyright © 2017 VaultIT. All rights reserved.
//
import XCTest
@testable import VITMobileSSOFramework
class VITMobileSSOFrameworkTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measure {
// Put the code you want to measure the time of here.
}
}
}
| 27.72973 | 111 | 0.653021 |
e59752896654890e1f0b5a7bbedfd7eab536ad56 | 1,160 | //
// UIColor.swift
// NSAttributeStringTest
//
// Created by zdc on 2020/03/10.
// Copyright © 2020 tolv. All rights reserved.
//
import UIKit
extension UIColor
{
convenience init(red: Int, green: Int, blue: Int) {
self.init(red: CGFloat(red) / 255.0, green: CGFloat(green) / 255.0, blue: CGFloat(blue) / 255.0, alpha: 1.0)
}
convenience init(red: Int, green: Int, blue: Int, alpha: CGFloat){
self.init(red: CGFloat(red) / 255.0, green: CGFloat(green) / 255.0, blue: CGFloat(blue) / 255.0, alpha: alpha)
}
func createColorImage() -> UIImage {
// 1x1のbitmapを作成
let rect = CGRect(x: 0, y: 0, width: 1, height: 1)
UIGraphicsBeginImageContextWithOptions(rect.size, false, 0.0)
guard let context = UIGraphicsGetCurrentContext() else { assertionFailure(); return UIImage() }
// bitmapを塗りつぶし
context.setFillColor(self.cgColor)
context.fill(rect)
// UIImageに変換
guard let image: UIImage = UIGraphicsGetImageFromCurrentImageContext() else { assertionFailure(); return UIImage() }
UIGraphicsEndImageContext()
return image
}
}
| 33.142857 | 124 | 0.639655 |
1a638aabc597da42d84b70ffe4f2277e317fdc6c | 1,360 | //
// SampleiOSUITests.swift
// SampleiOSUITests
//
// Created by mlaskowski on 11/07/2020.
// Copyright © 2020 Michal Laskowski. All rights reserved.
//
import XCTest
import mokttp
final class SampleiOSUITests: XCTestCase {
private var httpServer: HttpServer!
override func setUpWithError() throws {
continueAfterFailure = false
httpServer = HttpServer()
}
override func tearDownWithError() throws {
httpServer.stop()
}
func testStubs() {
let port: Int32 = Int32.random(in: 1025...10000)
httpServer.router = MockRouter()
httpServer.start(port: port)
// UI tests must launch the application that they test.
let app = XCUIApplication()
app.launchArguments = ["-contributors_url", "http://localhost:\(port)"]
app.launch()
app.segmentedControls.buttons["original"].tap()
app.buttons["contributors"].tap()
XCTAssertTrue(app.staticTexts["xcuitest"].waitForExistence(timeout: 5.0))
}
}
final class MockRouter: Router {
func handleRequest(request: Request) -> Response {
let data = try! JSONSerialization.data(withJSONObject: [
["login": "xcuitest", "contributions": 1]
], options: [])
return Response(status: 200, headers: [:], body: data, contentType: "application/json")
}
}
| 27.755102 | 95 | 0.645588 |
561d421a3771b9a01a2f9ee3140910ec0a8b347e | 2,304 | //
// SceneDelegate.swift
// EvolvAppExample
//
// Created by Aliaksandr Dvoineu on 31.05.21.
//
import UIKit
class SceneDelegate: UIResponder, UIWindowSceneDelegate {
var window: UIWindow?
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
// Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
// If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
// This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).
guard let _ = (scene as? UIWindowScene) else { return }
}
func sceneDidDisconnect(_ scene: UIScene) {
// Called as the scene is being released by the system.
// This occurs shortly after the scene enters the background, or when its session is discarded.
// Release any resources associated with this scene that can be re-created the next time the scene connects.
// The scene may re-connect later, as its session was not necessarily discarded (see `application:didDiscardSceneSessions` instead).
}
func sceneDidBecomeActive(_ scene: UIScene) {
// Called when the scene has moved from an inactive state to an active state.
// Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive.
}
func sceneWillResignActive(_ scene: UIScene) {
// Called when the scene will move from an active state to an inactive state.
// This may occur due to temporary interruptions (ex. an incoming phone call).
}
func sceneWillEnterForeground(_ scene: UIScene) {
// Called as the scene transitions from the background to the foreground.
// Use this method to undo the changes made on entering the background.
}
func sceneDidEnterBackground(_ scene: UIScene) {
// Called as the scene transitions from the foreground to the background.
// Use this method to save data, release shared resources, and store enough scene-specific state information
// to restore the scene back to its current state.
}
}
| 43.471698 | 147 | 0.71441 |
1a05531ffc1ed1a47a2849c2c00dc1fbc3dd1603 | 4,413 | import SwiftUI
import Combine
import KeyboardObserving
import SwiftMatrixSDK
struct RoomContainerView: View {
@ObservedObject var room: NIORoom
@State var showAttachmentPicker = false
@State var eventToReactTo: String?
var body: some View {
RoomView(
events: room.events(),
isDirect: room.isDirect,
showAttachmentPicker: $showAttachmentPicker,
onCommit: { message in
self.room.send(text: message)
},
onReact: { eventId in
self.eventToReactTo = eventId
},
onRedact: { eventId, reason in
self.room.redact(eventId: eventId, reason: reason)
},
onEdit: { message, eventId in
self.room.edit(text: message, eventId: eventId)
}
)
.navigationBarTitle(Text(room.summary.displayname ?? ""), displayMode: .inline)
.keyboardObserving()
.actionSheet(isPresented: $showAttachmentPicker) {
self.attachmentPickerSheet
}
.sheet(item: $eventToReactTo) { eventId in
ReactionPicker { reaction in
self.room.react(toEventId: eventId, emoji: reaction)
self.eventToReactTo = nil
}
}
.onAppear { self.room.markAllAsRead() }
.environmentObject(room)
}
var attachmentPickerSheet: ActionSheet {
ActionSheet(title: Text(L10n.Room.attachmentPlaceholder))
}
}
struct RoomView: View {
@Environment(\.userId) var userId
@EnvironmentObject var room: NIORoom
var events: EventCollection
var isDirect: Bool
@Binding var showAttachmentPicker: Bool
var onCommit: (String) -> Void
var onReact: (String) -> Void
var onRedact: (String, String?) -> Void
var onEdit: (String, String) -> Void
@State private var editEventId: String?
@State private var eventToRedact: String?
@State private var message = ""
var body: some View {
VStack {
ReverseList(events.renderableEvents) { event in
EventContainerView(event: event,
reactions: self.events.reactions(for: event),
connectedEdges: self.events.connectedEdges(of: event),
showSender: !self.isDirect,
edits: self.events.relatedEvents(of: event),
contextMenuModel: EventContextMenuModel(
event: event,
userId: self.userId,
onReact: { self.onReact(event.eventId) },
onReply: { },
onEdit: { self.edit(event: event) },
onRedact: { self.eventToRedact = event.eventId }))
.padding(.horizontal)
}
if !(room.room.typingUsers?.filter { $0 != userId }.isEmpty ?? false) {
TypingIndicatorView()
}
MessageComposerView(message: $message,
showAttachmentPicker: $showAttachmentPicker,
onCommit: send)
.padding(.horizontal)
.padding(.bottom, 10)
}
.alert(item: $eventToRedact) { eventId in
Alert(title: Text(L10n.Room.Remove.title),
message: Text(L10n.Room.Remove.message),
primaryButton: .destructive(Text(L10n.Room.Remove.action), action: { self.onRedact(eventId, nil) }),
secondaryButton: .cancel())
}
}
private func send() {
if editEventId == nil {
onCommit(message)
message = ""
} else {
onEdit(message, editEventId!)
message = ""
editEventId = nil
}
}
private func edit(event: MXEvent) {
message = event.content["body"] as? String ?? ""
editEventId = event.eventId
}
}
//struct ConversationView_Previews: PreviewProvider {
// static var previews: some View {
// NavigationView {
// ConversationView()
// .accentColor(.purple)
// .navigationBarTitle("Morpheus", displayMode: .inline)
// }
// }
//}
| 34.209302 | 118 | 0.529798 |
0acc6c00d31c635d9a44ff67d456cacf20c3ba5d | 500 | //
// ViewController.swift
// TestKitchen
//
// Created by qianfeng on 16/8/15.
// Copyright © 2016年 leicun. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
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.
}
}
| 19.230769 | 80 | 0.668 |
14cbf3484bfa8359fce0211d3974a1add1648142 | 651 | //
// UITableView.swift
// iTunesSearchApp
//
// Created by Erdem on 8.03.2022.
//
import UIKit
extension UITableView {
/**
This method hides UITableView with alpha value animation.
- Parameters:
- hidden:
- animated:
- completion?:
*/
func setTableViewHidden(_ hidden: Bool, animated: Bool, completion: (() -> Void)? = nil) {
let duration = animated ? 0.3 : 0
UIView.animate(withDuration: duration) {
self.alpha = hidden ? 0 : 1
} completion: { _ in
if let completion = completion {
completion()
}
}
}
}
| 21.7 | 94 | 0.537634 |
c1329f61437aa80ee3c60759873a43f935c381dd | 6,979 | //
// StarNode.swift
// lottie-swift
//
// Created by Brandon Withrow on 1/21/19.
//
import Foundation
import QuartzCore
class StarNodeProperties: NodePropertyMap, KeypathSearchable {
var keypathName: String
init(star: Star) {
self.keypathName = star.name
self.direction = star.direction
self.position = NodeProperty(provider: KeyframeInterpolator(keyframes: star.position.keyframes))
self.outerRadius = NodeProperty(provider: KeyframeInterpolator(keyframes: star.outerRadius.keyframes))
self.outerRoundedness = NodeProperty(provider: KeyframeInterpolator(keyframes: star.outerRoundness.keyframes))
if let innerRadiusKeyframes = star.innerRadius?.keyframes {
self.innerRadius = NodeProperty(provider: KeyframeInterpolator(keyframes: innerRadiusKeyframes))
} else {
self.innerRadius = NodeProperty(provider: SingleValueProvider(Vector1D(0)))
}
if let innderRoundedness = star.innerRoundness?.keyframes {
self.innerRoundedness = NodeProperty(provider: KeyframeInterpolator(keyframes: innderRoundedness))
} else {
self.innerRoundedness = NodeProperty(provider: SingleValueProvider(Vector1D(0)))
}
self.rotation = NodeProperty(provider: KeyframeInterpolator(keyframes: star.rotation.keyframes))
self.points = NodeProperty(provider: KeyframeInterpolator(keyframes: star.points.keyframes))
self.keypathProperties = [
"Position" : position,
"Outer Radius" : outerRadius,
"Outer Roundedness" : outerRoundedness,
"Inner Radius" : innerRadius,
"Inner Roundedness" : innerRoundedness,
"Rotation" : rotation,
"Points" : points
]
self.properties = Array(keypathProperties.values)
}
let keypathProperties: [String : AnyNodeProperty]
let properties: [AnyNodeProperty]
let direction: PathDirection
let position: NodeProperty<Vector3D>
let outerRadius: NodeProperty<Vector1D>
let outerRoundedness: NodeProperty<Vector1D>
let innerRadius: NodeProperty<Vector1D>
let innerRoundedness: NodeProperty<Vector1D>
let rotation: NodeProperty<Vector1D>
let points: NodeProperty<Vector1D>
}
class StarNode: AnimatorNode, PathNode {
let properties: StarNodeProperties
let pathOutput: PathOutputNode
init(parentNode: AnimatorNode?, star: Star) {
self.pathOutput = PathOutputNode(parent: parentNode?.outputNode)
self.properties = StarNodeProperties(star: star)
self.parentNode = parentNode
}
// MARK: Animator Node
var propertyMap: NodePropertyMap & KeypathSearchable {
return properties
}
let parentNode: AnimatorNode?
var hasLocalUpdates: Bool = false
var hasUpstreamUpdates: Bool = false
var lastUpdateFrame: CGFloat? = nil
/// Magic number needed for building path data
static let PolystarConstant: CGFloat = 0.47829
func rebuildOutputs(frame: CGFloat) {
let outerRadius = properties.outerRadius.value.cgFloatValue
let innerRadius = properties.innerRadius.value.cgFloatValue
let outerRoundedness = properties.outerRoundedness.value.cgFloatValue * 0.01
let innerRoundedness = properties.innerRoundedness.value.cgFloatValue * 0.01
let numberOfPoints = properties.points.value.cgFloatValue
let rotation = properties.rotation.value.cgFloatValue
let position = properties.position.value.pointValue
var currentAngle = (rotation - 90).toRadians()
let anglePerPoint = (2 * CGFloat.pi) / numberOfPoints
let halfAnglePerPoint = anglePerPoint / 2.0
let partialPointAmount = numberOfPoints - floor(numberOfPoints)
var point: CGPoint = .zero
var partialPointRadius: CGFloat = 0
if partialPointAmount != 0 {
currentAngle += halfAnglePerPoint * (1 - partialPointAmount)
partialPointRadius = innerRadius + partialPointAmount * (outerRadius - innerRadius)
point.x = (partialPointRadius * cos(currentAngle))
point.y = (partialPointRadius * sin(currentAngle))
currentAngle += anglePerPoint * partialPointAmount / 2
} else {
point.x = (outerRadius * cos(currentAngle))
point.y = (outerRadius * sin(currentAngle))
currentAngle += halfAnglePerPoint
}
var vertices = [CurveVertex]()
vertices.append(CurveVertex(point: point + position, inTangentRelative: .zero, outTangentRelative: .zero))
var previousPoint = point
var longSegment = false
let numPoints: Int = Int(ceil(numberOfPoints) * 2)
for i in 0..<numPoints {
var radius = longSegment ? outerRadius : innerRadius
var dTheta = halfAnglePerPoint
if partialPointRadius != 0 && i == numPoints - 2 {
dTheta = anglePerPoint * partialPointAmount / 2
}
if partialPointRadius != 0 && i == numPoints - 1 {
radius = partialPointRadius
}
previousPoint = point
point.x = (radius * cos(currentAngle))
point.y = (radius * sin(currentAngle))
if innerRoundedness == 0 && outerRoundedness == 0 {
vertices.append(CurveVertex(point: point + position, inTangentRelative: .zero, outTangentRelative: .zero))
} else {
let cp1Theta = (atan2(previousPoint.y, previousPoint.x) - CGFloat.pi / 2)
let cp1Dx = cos(cp1Theta)
let cp1Dy = sin(cp1Theta)
let cp2Theta = (atan2(point.y, point.x) - CGFloat.pi / 2)
let cp2Dx = cos(cp2Theta)
let cp2Dy = sin(cp2Theta)
let cp1Roundedness = longSegment ? innerRoundedness : outerRoundedness
let cp2Roundedness = longSegment ? outerRoundedness : innerRoundedness
let cp1Radius = longSegment ? innerRadius : outerRadius
let cp2Radius = longSegment ? outerRadius : innerRadius
var cp1 = CGPoint(x: cp1Radius * cp1Roundedness * StarNode.PolystarConstant * cp1Dx,
y: cp1Radius * cp1Roundedness * StarNode.PolystarConstant * cp1Dy)
var cp2 = CGPoint(x: cp2Radius * cp2Roundedness * StarNode.PolystarConstant * cp2Dx,
y: cp2Radius * cp2Roundedness * StarNode.PolystarConstant * cp2Dy)
if partialPointAmount != 0 {
if i == 0 {
cp1 = cp1 * partialPointAmount
} else if i == numPoints - 1 {
cp2 = cp2 * partialPointAmount
}
}
let previousVertex = vertices[vertices.endIndex-1]
vertices[vertices.endIndex-1] = CurveVertex(previousVertex.inTangent, previousVertex.point, previousVertex.point - cp1 + position)
vertices.append(CurveVertex(point: point + position, inTangentRelative: cp2, outTangentRelative: .zero))
}
currentAngle += dTheta
longSegment = !longSegment
}
let reverse = properties.direction == .counterClockwise
if reverse {
vertices = vertices.reversed()
}
var path = BezierPath()
for vertex in vertices {
path.addVertex(reverse ? vertex.reversed() : vertex)
}
path.close()
pathOutput.setPath(path, updateFrame: frame)
}
}
| 38.988827 | 138 | 0.695229 |
09a56d7a59a549b0295aab03349e2cc1e6449a60 | 737 | //
// Http.swift
// Kitty
//
// Created by Ashkan Ferdowsi on 18/08/2019.
// Copyright © 2019 Ashkan. All rights reserved.
//
import Foundation
import Alamofire
class Http {
var headers: HTTPHeaders = [String:String]()
func execute (request: HttpRequest, completion: @escaping(_ isSuccessful: Bool) -> ()) {
if (request.shouldAddHeader()) {
headers = [
"x-api-key": request.KITTY_API_KEY
]
}
run(request: request) { (isSuccessful) in
completion(isSuccessful)
}
}
func run(request: HttpRequest, completion: @escaping(_ isSuccessful: Bool) -> ()) {
fatalError("Should be overriden in subclasses.")
}
}
| 23.774194 | 92 | 0.583446 |
181280ea61f62082efc102bea68cc41cbd56c90f | 752 | //
// CategoryModel.swift
// IncredibleNetworkManager_Example
//
// Created by Fabio Gustavo Hoffmann on 25/03/18.
// Copyright © 2018 CocoaPods. All rights reserved.
//
import UIKit
class CategoryModel: BaseModel {
let id: String
let title: String
let photoCount: Int
let links: [String: String]
required init(dictionary: JSON) {
id = dictionary.parseString(key: "id")
title = dictionary.parseString(key: "title")
photoCount = dictionary.parseInt(key: "photo_count")
if let linksDictionary = dictionary["links"] as? [String: String] {
links = linksDictionary
} else {
links = [:]
}
}
func toDictionary() -> JSON {
return [:]
}
}
| 22.117647 | 75 | 0.610372 |
792918fa61cc46367298ad0c74278105520288ff | 1,860 | //
// SeperateChartViewController.swift
// IotApp
//
// Created by Abhishek Ravi on 13/06/17.
// Copyright © 2017 Abhishek Ravi. All rights reserved.
//
import UIKit
import SwiftChart
class SeperateChartViewController: UIViewController {
@IBOutlet weak var chartTemperature: Chart!
@IBOutlet weak var chartHumidity: Chart!
@IBOutlet weak var chartPressure: Chart!
var data: ChartsData?
override func viewDidLoad() {
super.viewDidLoad()
intializeView()
prepareCharts()
}
func intializeView(){
self.navigationItem.title = "Charts"
}
func prepareCharts(){
if let chartsData = data{
// Temperature
let series = ChartSeries(getFloat(values:chartsData.temperatureLog))
series.color = UIColor.red
series.area = true
self.chartTemperature.add(series)
// Humidity
let seriesHumdity = ChartSeries(getFloat(values:chartsData.humidityLog))
seriesHumdity.color = UIColor.green
seriesHumdity.area = true
self.chartHumidity.add(seriesHumdity)
// Pressure
let seriesPressure = ChartSeries(getFloat(values:chartsData.pressureLog))
seriesPressure.color = UIColor.purple
seriesPressure.area = true
self.chartPressure.add(seriesPressure)
}
}
func getFloat(values:[Double])->[Float]{
var data:[Float] = []
for item in values{
data.append(Float(item))
}
return data
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| 24.8 | 85 | 0.582258 |
acad0af65f15dfba9651a57cc2fd730b16b23b73 | 3,752 | //
// UIViewController.swift
// MVVMSwiftExample
//
// Created by Dino Bartosak on 26/09/16.
// Copyright © 2016 Toptal. All rights reserved.
//
import UIKit
import MMPopupView
public extension UIViewController {
func xmg_turnToViewController(_ targetVC : UIViewController?){
if let tempVC = targetVC {
tempVC.hidesBottomBarWhenPushed = true
self.navigationController?.pushViewController(tempVC, animated: true)
}
}
@objc func xmg_back () {
self.navigationController?.popViewController(animated: true)
}
/// 返回到指定的vc
///
/// - Parameter targetVC: 元类型
func xmg_backToTargetViewController (_ targetVC:AnyClass) {
for VC in (self.navigationController?.viewControllers)! {
if VC.isKind(of: targetVC) {
self.navigationController?.popToViewController(VC, animated: true)
break
}
}
}
func xmg_backToFrontTargetViewController (_ index:Int) {
if let allNum = self.navigationController?.viewControllers.count{
var Newindex:Int = allNum - index - 1
if Newindex < 0{
Newindex = 0//防止越界
}
for (i,vc) in (self.navigationController?.viewControllers)!.enumerated() {
if i == Newindex {
self.navigationController?.popToViewController(vc, animated: true)
}
}
}
}
///点击评论 自己或者对方
func xmg_showSubSheetView(_ isMe:Bool,confirm:@escaping (_ index:Int)->()){
let block:(Int)->Void = {(index) in
confirm(index)
}
if isMe{
let items = [MMItemMake("删除", .normal, block)!] as [Any]
let sheetView = MMSheetView.init(title: "", items: items)
sheetView?.show()
}else{
let items = [MMItemMake("投诉", .normal, block)!] as [Any]
let sheetView = MMSheetView.init(title: "", items: items)
sheetView?.show()
}
}
///点击评论 自己或者对方
func xmg_showSheetView(_ isMe:Bool,confirm:@escaping (_ index:Int)->()){
let block:(Int)->Void = {(index) in
confirm(index)
}
if isMe{
let items = [MMItemMake("回复", .normal, block),MMItemMake("删除", .normal, block)]
let sheetView = MMSheetView.init(title: "", items: items as [Any])
sheetView?.show()
}else{
let items = [MMItemMake("回复", .normal, block),MMItemMake("投诉", .normal, block)]
let sheetView = MMSheetView.init(title: "", items: items as [Any])
sheetView?.show()
}
}
func xmg_showTipAlertView(_ tipString:String, confirm:@escaping ()->()){
let block:(Int)->Void = {(index) in
if index == 1 {
confirm()
}
}
let items = [MMItemMake("取消", .normal, block)!,
MMItemMake("确认", .highlight, block)!] as [Any]
let alertView = MMAlertView.init(title: tipString, detail: nil, items: items)
alertView?.show()
}
func xmg_showProblemAlertView(_ tipString:String, confirm:@escaping ()->()){
let block:(Int)->Void = {(index) in
if index == 1 {
confirm()
}
}
let items = [MMItemMake("在想想", .normal, block)!,
MMItemMake("是", .normal, block)!] as [Any]
let alertView = MMAlertView.init(title: tipString, detail: nil, items: items)
alertView?.show()
}
}
| 29.3125 | 91 | 0.523721 |
bb25b471444267d141d8d4ed68dfedfc269d7d20 | 648 | //
// AppDelegate.swift
// SoundcloudAppTest
//
// Created by Kevin DELANNOY on 18/07/15.
// Copyright (c) 2015 Kevin Delannoy. All rights reserved.
//
import UIKit
import Soundcloud
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
Soundcloud.clientIdentifier = ""
Soundcloud.clientSecret = ""
Soundcloud.redirectURI = ""
return true
}
}
| 27 | 144 | 0.716049 |
2804e6af5b3b8d9b5d5b366c480e6d8c7dc7801a | 2,586 | //
// URLRequest.swift
// Network-Testing
//
// Created by Vikram on 05/09/2019.
// Copyright © 2019 Vikram. All rights reserved.
//
import Foundation
public extension URLRequest {
private func percentEscapeString(_ string: String) -> String {
var characterSet = CharacterSet.alphanumerics
characterSet.insert(charactersIn: "-._*")
return string
.addingPercentEncoding(withAllowedCharacters: characterSet)!
.replacingOccurrences(of: " ", with: "+")
.replacingOccurrences(of: " ", with: "+", options: [], range: nil)
}
mutating func encodeParameters(parameters: [String: String]) {
let parameterArray = parameters.map { (arg) -> String in
let (key, value) = arg
return "\(key)=\(self.percentEscapeString(value))"
}
guard let data = parameterArray.joined(separator: "&").data(using: .utf8) else { return }
httpBody = data
}
init?(baseURL: URL,
path: String,
httpMethod: HTTPMethod,
headerValues: HTTPHeaders? = nil,
queryParameters: QueryParameters? = nil,
bodyType: HTTPBodyType,
body: Encodable? = nil,
cachePolicy: URLRequest.CachePolicy = .useProtocolCachePolicy) {
guard let url = URL(baseURL: baseURL, path: path, queryParameters: queryParameters) else { return nil }
var request = URLRequest(url: url)
request.httpMethod = httpMethod.value
if let headerValues = headerValues {
headerValues.forEach { request.setValue($0.value, forHTTPHeaderField: $0.key) }
}
switch bodyType {
case .none:
break
case let .formEncoded(parameters: parameters):
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.encodeParameters(parameters: parameters)
case .json:
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.httpBody = body?.encode()
}
request.cachePolicy = cachePolicy
self = request
}
}
public extension URL {
init?(baseURL: URL, path: String, queryParameters: QueryParameters?) {
guard
var components = URLComponents(string: baseURL.absoluteString + path)
else { return nil }
if let queryParameters = queryParameters {
components.setQueryItems(with: queryParameters)
}
guard let url = components.url else { return nil }
self = url
}
}
| 31.925926 | 111 | 0.620263 |
e88495a04f144809c8b135a2cb9d3f298105a6d6 | 1,095 | //===--- NSDictionaryCastToSwift.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
//
//===----------------------------------------------------------------------===//
// Performance benchmark for casting NSDictionary to Swift Dictionary
// rdar://problem/18539730
//
// Description:
// Create an NSDictionary instance and cast it to [String: NSObject].
import Foundation
import TestsUtils
@inline(never)
public func run_NSDictionaryCastToSwift(_ N: Int) {
#if _runtime(_ObjC)
let NSDict = NSDictionary()
var swiftDict = [String: NSObject]()
for _ in 1...10000*N {
swiftDict = NSDict as! [String: NSObject]
if !swiftDict.isEmpty {
break
}
}
CheckResults(swiftDict.isEmpty)
#endif
}
| 31.285714 | 80 | 0.623744 |
62d50f47ddb177546d0cf63156f77ef7bd00731f | 2,045 | //
// AppDelegate.swift
// SampleToday
//
// Created by Don Mag on 11/25/16.
// Copyright © 2016 Don Mag. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| 43.510638 | 279 | 0.787286 |
ef581e1654e36c12d76ee3e55de4e7740611c0bd | 1,676 | //
// HomePageModule.swift
// HomePageModule
//
// Created by Giuseppe Lanza on 25/11/2019.
// Copyright © 2019 MERLin Tech. All rights reserved.
//
public enum HomePagePresentationType {
case movies
case tvSeries
}
public class HomePageContext: ModuleContextProtocol {
public typealias ModuleType = HomePageModule
public var routingContext: String
fileprivate var presentationType: HomePagePresentationType
public init(routingContext: String,
presentationType: HomePagePresentationType) {
self.routingContext = routingContext
self.presentationType = presentationType
}
public func make() -> (AnyModule, UIViewController) {
let module = ModuleType(usingContext: self)
return (module, module.prepareRootViewController())
}
}
public enum HomePageEvents: EventProtocol {
case movieSelected(Movie)
}
public class HomePageModule: ModuleProtocol, EventsProducer {
public var events: Observable<HomePageEvents> { return _events.asObservable() }
private var _events = PublishSubject<HomePageEvents>()
public var context: HomePageContext
public func unmanagedRootViewController() -> UIViewController {
let model: HomePageModel = context.presentationType == .movies ? HomeMoviesModel() : HomeSeriesModel()
let viewModel = HomePageViewModel(model: model,
events: _events)
let viewController = HomeViewController(with: viewModel)
return viewController
}
public required init(usingContext buildContext: HomePageContext) {
self.context = buildContext
}
}
| 31.622642 | 110 | 0.698091 |
90ef69cfe699075d291b13390887c3c48393d77e | 2,872 | //
// SceneDelegate.swift
// DemoCornershop
//
// Created by Everis on 8/7/20.
// Copyright © 2020 Everis. All rights reserved.
//
import UIKit
class SceneDelegate: UIResponder, UIWindowSceneDelegate {
var window: UIWindow?
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
// Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
// If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
// This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).
guard let windowScene = (scene as? UIWindowScene) else { return }
window = UIWindow(frame: UIScreen.main.bounds)
window?.windowScene = windowScene
let nav = UINavigationController(rootViewController: WelcomeViewController())
nav.navigationBar.prefersLargeTitles = true
window?.rootViewController = nav
window?.makeKeyAndVisible()
}
func sceneDidDisconnect(_ scene: UIScene) {
// Called as the scene is being released by the system.
// This occurs shortly after the scene enters the background, or when its session is discarded.
// Release any resources associated with this scene that can be re-created the next time the scene connects.
// The scene may re-connect later, as its session was not neccessarily discarded (see `application:didDiscardSceneSessions` instead).
}
func sceneDidBecomeActive(_ scene: UIScene) {
// Called when the scene has moved from an inactive state to an active state.
// Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive.
}
func sceneWillResignActive(_ scene: UIScene) {
// Called when the scene will move from an active state to an inactive state.
// This may occur due to temporary interruptions (ex. an incoming phone call).
}
func sceneWillEnterForeground(_ scene: UIScene) {
// Called as the scene transitions from the background to the foreground.
// Use this method to undo the changes made on entering the background.
}
func sceneDidEnterBackground(_ scene: UIScene) {
// Called as the scene transitions from the foreground to the background.
// Use this method to save data, release shared resources, and store enough scene-specific state information
// to restore the scene back to its current state.
// Save changes in the application's managed object context when the application transitions to the background.
(UIApplication.shared.delegate as? AppDelegate)?.saveContext()
}
}
| 44.184615 | 147 | 0.711003 |
fec49d5ae6f8f5267793403aec20424ed3014c12 | 2,289 | import XCTest
@testable import Storage
class PathBuilderTests: XCTestCase {
static var allTests = [
("testConfigurableNodesPathTemplate", testConfigurableNodesPathTemplate),
("testConfigurableAllAliases", testConfigurableAllAliases),
("testConfigurableAllAliasesFailed", testConfigurableAllAliasesFailed)
]
func testConfigurableNodesPathTemplate() {
let entity = FileEntity(
fileName: "smile",
fileExtension: "jpg",
mime: "image/jpg"
)
expectNoThrow() {
let builder = try ConfigurablePathBuilder(template: "/myapp/#mimeFolder/#file")
let path = try builder.build(entity: entity)
XCTAssertEqual(path, "/myapp/images/original/smile.jpg")
}
}
func testConfigurableAllAliases() {
let entity = FileEntity(
fileName: "test.png",
folder: "myfolder",
mime: "image/png"
)
let expected: [(Template.Alias, String)] = [
(.file, "test.png"),
(.fileName, "test"),
(.fileExtension, "png"),
(.folder, "myfolder"),
(.mime, "image/png"),
(.mimeFolder, "images/original")
]
expectNoThrow() {
try expected.forEach { (alias, expected) in
let builder = try ConfigurablePathBuilder(template: alias.rawValue)
let path = try builder.build(entity: entity)
XCTAssertEqual(path, expected)
}
}
}
func testConfigurableAllAliasesFailed() {
let entity = FileEntity()
let expected: [(Template.Alias, Template.Error)] = [
(.file, .malformedFileName),
(.fileName, .fileNameNotProvided),
(.fileExtension, .fileExtensionNotProvided),
(.folder, .folderNotProvided),
(.mime, .mimeNotProvided),
(.mimeFolder, .mimeFolderNotProvided)
]
expected.forEach { (alias, error) in
expect(toThrow: error) {
let builder = try ConfigurablePathBuilder(template: alias.rawValue)
_ = try builder.build(entity: entity)
}
}
}
}
| 32.7 | 91 | 0.553517 |
758794e079be7261b6c5cdad6661c8b8d0f19375 | 551 | //
// Foundation+Migration.swift
// R.swift.Library
//
// Created by Tom Lokhorst on 2016-09-08.
// Copyright © 2016 Mathijs Kadijk. All rights reserved.
//
import Foundation
// Renames from Swift 2 to Swift 3
public extension Bundle {
@available(*, unavailable, renamed: "url(forResource:)")
public func URLForResource(_ resource: FileResourceType) -> URL? {
fatalError()
}
@available(*, unavailable, renamed: "path(forResource:)")
public func pathForResource(_ resource: FileResourceType) -> String? {
fatalError()
}
}
| 21.192308 | 72 | 0.6951 |
61cad16ed9c0e3b1f55d89d8590f8cd2b1c03f00 | 1,012 | //
// Resolver.swift
// LocalizationHelperKit
//
// Created by Chung Tran on 24/07/2021.
//
@_exported import Resolver
extension Resolver: ResolverRegistering {
#if DEBUG
static let mock = Resolver(parent: main)
#endif
public static func registerAllServices() {
register {StringsFileGenerator() as FileGeneratorType}
register {UserDefaultsProjectRepository() as ProjectRepositoryType}
register {FilePickerService() as FilePickerServiceType}
register {XCodeProjectService() as XCodeProjectServiceType}
#if DEBUG
// mock.register {FakeStringsFileGenerator() as FileGeneratorType}
// mock.register {InMemoryProjectRepository.default as ProjectRepositoryType}
// mock.register {MockFilePickerService() as FilePickerServiceType}
// mock.register {OpenProjectHandler_Preview() as OpenProjectHandler}
// register entire container as replacement for main
// root = mock
#endif
}
}
| 31.625 | 84 | 0.69664 |
46fd537d498c16710957110c575c43bc881234c7 | 5,926 | //===----------------------------------------------------------------------===//
//
// This source file is part of the swift-sample-distributed-actors-transport open source project
//
// Copyright (c) 2021 Apple Inc. and the swift-sample-distributed-actors-transport project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of swift-sample-distributed-actors-transport project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import _Distributed
import NIO
import NIOHTTP1
import Foundation
import Tracing
import _NIOConcurrency
private final class HTTPHandler: @unchecked Sendable, ChannelInboundHandler, RemovableChannelHandler {
typealias InboundIn = HTTPServerRequestPart
typealias OutboundOut = HTTPServerResponsePart
private let transport: FishyTransport
private var messageBytes: ByteBuffer = ByteBuffer()
private var messageRecipientURI: String = ""
private var state: State = .idle
private enum State {
case idle
case waitingForRequestBody
case sendingResponse
mutating func requestReceived() {
precondition(self == .idle, "Invalid state for request received: \(self)")
self = .waitingForRequestBody
}
mutating func requestComplete() {
precondition(self == .waitingForRequestBody, "Invalid state for request complete: \(self)")
self = .sendingResponse
}
mutating func responseComplete() {
precondition(self == .sendingResponse, "Invalid state for response complete: \(self)")
self = .idle
}
}
init(transport: FishyTransport) {
self.transport = transport
}
func handlerAdded(context: ChannelHandlerContext) {
}
func handlerRemoved(context: ChannelHandlerContext) {
}
func channelRead(context: ChannelHandlerContext, data: NIOAny) {
switch unwrapInboundIn(data) {
case .head(let head):
guard case .POST = head.method else {
self.respond405(context: context)
return
}
messageRecipientURI = head.uri
state.requestReceived()
case .body(var bytes):
if (state == State.idle) { return }
messageBytes.writeBuffer(&bytes)
case .end:
if (state == State.idle) { return }
onMessageComplete(context: context, messageBytes: messageBytes)
state.requestComplete()
messageBytes.clear()
messageRecipientURI = ""
}
}
func onMessageComplete(context: ChannelHandlerContext, messageBytes: ByteBuffer) {
let decoder = JSONDecoder()
decoder.userInfo[.actorTransportKey] = transport
let envelope: Envelope
do {
envelope = try decoder.decode(Envelope.self, from: messageBytes)
} catch {
// TODO: log the error
return
}
let promise = context.eventLoop.makePromise(of: Data.self)
promise.completeWithTask {
try await self.transport.deliver(envelope: envelope)
}
promise.futureResult.whenComplete { result in
var headers = HTTPHeaders()
headers.add(name: "Content-Type", value: "application/json")
let responseHead: HTTPResponseHead
let responseBody: ByteBuffer
switch result {
case .failure(let error):
responseHead = HTTPResponseHead(version: .init(major: 1, minor: 1),
status: .internalServerError,
headers: headers)
responseBody = ByteBuffer(string: "Error: \(error)")
case .success(let data):
responseHead = HTTPResponseHead(version: .init(major: 1, minor: 1),
status: .ok,
headers: headers)
responseBody = ByteBuffer(data: data)
}
headers.add(name: "Content-Length", value: String(responseBody.readableBytes))
headers.add(name: "Connection", value: "close")
context.write(self.wrapOutboundOut(.head(responseHead)), promise: nil)
context.write(self.wrapOutboundOut(.body(.byteBuffer(responseBody))), promise: nil)
context.write(self.wrapOutboundOut(.end(nil))).whenComplete { (_: Result<Void, Error>) in
context.close(promise: nil)
}
context.flush()
}
}
private func respond405(context: ChannelHandlerContext) {
var headers = HTTPHeaders()
headers.add(name: "Connection", value: "close")
headers.add(name: "Content-Length", value: "0")
let head = HTTPResponseHead(version: .http1_1,
status: .methodNotAllowed,
headers: headers)
context.write(self.wrapOutboundOut(.head(head)), promise: nil)
context.write(self.wrapOutboundOut(.end(nil))).whenComplete { (_: Result<Void, Error>) in
context.close(promise: nil)
}
context.flush()
}
}
final class FishyServer {
var group: EventLoopGroup
let transport: FishyTransport
var channel: Channel! = nil
init(group: EventLoopGroup, transport: FishyTransport) {
self.group = group
self.transport = transport
}
func bootstrap(host: String, port: Int) throws {
assert(channel == nil)
let bootstrap = ServerBootstrap(group: group)
// Specify backlog and enable SO_REUSEADDR for the server itself
.serverChannelOption(ChannelOptions.backlog, value: 256)
.serverChannelOption(ChannelOptions.socketOption(.so_reuseaddr), value: 1)
// Set the handlers that are applied to the accepted Channels
.childChannelInitializer { channel in
let httpHandler = HTTPHandler(transport: self.transport)
return channel.pipeline.configureHTTPServerPipeline().flatMap {
channel.pipeline.addHandler(httpHandler)
}
}
// Enable SO_REUSEADDR for the accepted Channels
.childChannelOption(ChannelOptions.socketOption(.so_reuseaddr), value: 1)
channel = try bootstrap.bind(host: host, port: port).wait()
assert(channel.localAddress != nil, "localAddress was nil!")
}
}
| 32.740331 | 102 | 0.669423 |
d59acd69a4740bd263936b839cc57b148ec021b8 | 821 | //
// MoviesViewModel.swift
// Will
//
// Created by Edric D. on 9/16/19.
// Copyright © 2019 The Upside Down. All rights reserved.
//
import UIKit
import Kingfisher
class CreditsItemCollectionViewCell: UICollectionViewCell {
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var jobLabel: UILabel!
@IBOutlet weak var profileImage: SwiftShadowImageView!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
func bind(_ viewModel: CreditsItemViewModel?) {
nameLabel.text = viewModel?.name
profileImage.imageView.kf.setImage(with: viewModel?.profileURL, placeholder: UIImage(named: "posterImage"))
jobLabel.text = viewModel?.job
if viewModel?.job == nil {
jobLabel.isEnabled = false
}
}
}
| 24.878788 | 115 | 0.672351 |
f9a143753eecedce619cb8038514478bda145d2e | 419 | //
// ZQTimeTool.swift
// QQMusic
//
// Created by 仲琦 on 16/5/21.
// Copyright © 2016年 仲琦. All rights reserved.
//
import UIKit
class ZQTimeTool: NSObject {
class func getFormatTime(time: NSTimeInterval) -> String{
let min = Int(time / 60)
let sec = Int(time) % 60
let resultStr = String(format: "%02d:%02d", min, sec)
return resultStr
}
}
| 17.458333 | 61 | 0.558473 |
7658015622e56b0f2490d6ce03d652c61db9e5be | 3,682 | //
// UIIntroCatAnimation.swift
// SaveTheCat
//
// Created by Christopher Francisco on 3/17/20.
// Copyright © 2020 Christopher Francisco. All rights reserved.
//
import Foundation
import UIKit
class UIIntroCatAnimation:UICButton {
let darkCatImage:UIImage = UIImage(named: "darkCat.png")!;
let lightCatImage:UIImage = UIImage(named: "lightCat.png")!;
let darkIntroText:UIImage = UIImage(named: "darkIntroText.png")!;
let lightIntroText:UIImage = UIImage(named: "lightIntroText.png")!;
var introTextView:UIImageView?
var fadeInAnimation:UIViewPropertyAnimator?
var fadeOutAnimation:UIViewPropertyAnimator?
var waitForFadeInTimer:Timer?
var introTextRotationTimer:Timer?
init(parentView:UIView, frame:CGRect) {
super.init(parentView: parentView, frame: frame, backgroundColor: UIColor.clear);
self.alpha = 0.0;
setIntroTextImage();
setCompiledStyle();
setupIntroTextRotationTimer();
}
/*
Create timer to rotate
the text continouslly
*/
func setupIntroTextRotationTimer() {
introTextRotationTimer = Timer.scheduledTimer(withTimeInterval: 0.01, repeats: true, block: { _ in
self.introTextView!.transform = self.introTextView!.transform.rotated(by: CGFloat.pi * 0.005);
})
}
/*
Creates the radial text
*/
func setIntroTextImage() {
introTextView = UIImageView(frame: frame);
introTextView!.transform = introTextView!.transform.translatedBy(x: 0.0, y: introTextView!.frame.height * 0.015);
introTextView!.backgroundColor = UIColor.clear;
introTextView!.contentMode = UIView.ContentMode.scaleAspectFit;
addSubview(introTextView!);
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
/*
Makes the intro cat animation
opaque over time
*/
func setupFadeInAnimation() {
fadeInAnimation = UIViewPropertyAnimator(duration: 2.0, curve: .easeIn, animations: {
self.alpha = 1.0;
})
}
/*
Timer that fades and plays
the meow sound
*/
func setupWaitForFadeInTimer() {
waitForFadeInTimer = Timer.scheduledTimer(withTimeInterval: 0.01, repeats: true, block: { _ in
if (self.alpha == 1.0) {
SoundController.kittenMeow();
self.setupFadeOutAnimation();
self.fadeOutAnimation!.startAnimation();
self.waitForFadeInTimer!.invalidate();
}
})
}
/*
Animation that makes the intro cat
animation transparent
*/
func setupFadeOutAnimation() {
fadeOutAnimation = UIViewPropertyAnimator(duration: 2.0, curve: .easeOut, animations: {
self.alpha = 0.0;
})
fadeOutAnimation!.addCompletion({ _ in
self.introTextRotationTimer!.invalidate();
})
}
/*
Updates the appearance of the intro cat
animation based on the theme of the OS
*/
func setCompiledStyle() {
if (ViewController.uiStyleRawValue == 1) {
self.setImage(darkCatImage, for: .normal);
introTextView!.image = darkIntroText;
} else {
self.setImage(lightCatImage, for: .normal);
introTextView!.image = lightIntroText;
}
self.imageView!.contentMode = UIView.ContentMode.scaleAspectFit;
}
func fadeIn() {
setupFadeInAnimation();
fadeInAnimation!.startAnimation();
}
func fadeOut() {
setupWaitForFadeInTimer();
}
}
| 29.693548 | 121 | 0.624932 |
e4840940925735cea59379d329fbbdaee3c9adbe | 3,115 | //
// HotKeyParser.swift
// PassHUD
// Source: https://github.com/marshallbrekka/AutoWin/blob/master/AutoWin/Util/AWKeyCodes.swift
import Foundation
import Carbon
import Cocoa
let modifiersToKeyCodes: NSDictionary = [
"cmd" : cmdKey,
"ctrl" : controlKey,
"opt" : optionKey,
"shift": shiftKey
]
let charsToKeyCodes :NSDictionary = [
"a":kVK_ANSI_A,
"b":kVK_ANSI_B,
"c":kVK_ANSI_C,
"d":kVK_ANSI_D,
"e":kVK_ANSI_E,
"f":kVK_ANSI_F,
"g":kVK_ANSI_G,
"h":kVK_ANSI_H,
"i":kVK_ANSI_I,
"j":kVK_ANSI_J,
"k":kVK_ANSI_K,
"l":kVK_ANSI_L,
"m":kVK_ANSI_M,
"n":kVK_ANSI_N,
"o":kVK_ANSI_O,
"p":kVK_ANSI_P,
"q":kVK_ANSI_Q,
"r":kVK_ANSI_R,
"s":kVK_ANSI_S,
"t":kVK_ANSI_T,
"u":kVK_ANSI_U,
"v":kVK_ANSI_V,
"w":kVK_ANSI_W,
"x":kVK_ANSI_X,
"y":kVK_ANSI_Y,
"z":kVK_ANSI_Z,
"0":kVK_ANSI_0,
"1":kVK_ANSI_1,
"2":kVK_ANSI_2,
"3":kVK_ANSI_3,
"4":kVK_ANSI_4,
"5":kVK_ANSI_5,
"6":kVK_ANSI_6,
"7":kVK_ANSI_7,
"8":kVK_ANSI_8,
"9":kVK_ANSI_9,
"`":kVK_ANSI_Grave,
"=":kVK_ANSI_Equal,
"-":kVK_ANSI_Minus,
"]":kVK_ANSI_RightBracket,
"[":kVK_ANSI_LeftBracket,
"\"":kVK_ANSI_Quote,
";":kVK_ANSI_Semicolon,
"\\":kVK_ANSI_Backslash,
",":kVK_ANSI_Comma,
"/":kVK_ANSI_Slash,
".":kVK_ANSI_Period,
"§":kVK_ISO_Section,
"f1":kVK_F1,
"f2":kVK_F2,
"f3":kVK_F3,
"f4":kVK_F4,
"f5":kVK_F5,
"f6":kVK_F6,
"f7":kVK_F7,
"f8":kVK_F8,
"f9":kVK_F9,
"f10":kVK_F10,
"f11":kVK_F11,
"f12":kVK_F12,
"f13":kVK_F13,
"f14":kVK_F14,
"f15":kVK_F15,
"f16":kVK_F16,
"f17":kVK_F17,
"f18":kVK_F18,
"f19":kVK_F19,
"f20":kVK_F20,
"pad.":kVK_ANSI_KeypadDecimal,
"pad*":kVK_ANSI_KeypadMultiply,
"pad+":kVK_ANSI_KeypadPlus,
"pad/":kVK_ANSI_KeypadDivide,
"pad-":kVK_ANSI_KeypadMinus,
"pad=":kVK_ANSI_KeypadEquals,
"pad0":kVK_ANSI_Keypad0,
"pad1":kVK_ANSI_Keypad1,
"pad2":kVK_ANSI_Keypad2,
"pad3":kVK_ANSI_Keypad3,
"pad4":kVK_ANSI_Keypad4,
"pad5":kVK_ANSI_Keypad5,
"pad6":kVK_ANSI_Keypad6,
"pad7":kVK_ANSI_Keypad7,
"pad8":kVK_ANSI_Keypad8,
"pad9":kVK_ANSI_Keypad9,
"padclear":kVK_ANSI_KeypadClear,
"padenter":kVK_ANSI_KeypadEnter,
"return":kVK_Return,
"tab":kVK_Tab,
"space":kVK_Space,
"delete":kVK_Delete,
"escape":kVK_Escape,
"help":kVK_Help,
"home":kVK_Home,
"pageup":kVK_PageUp,
"forwarddelete":kVK_ForwardDelete,
"end":kVK_End,
"pagedown":kVK_PageDown,
"left":kVK_LeftArrow,
"right":kVK_RightArrow,
"down":kVK_DownArrow,
"up":kVK_UpArrow
]
class HotKeyParser {
class func charToKeyCode(_ char: String) -> UInt32 {
return charsToKeyCodes.object(forKey: char) as! UInt32
}
class func modifiersToModCode(_ modifiers: [String]) -> UInt32 {
var code: UInt32 = 0
for mod in modifiers {
let modCode = modifiersToKeyCodes.object(forKey: mod) as! UInt32
code |= modCode
}
return code
}
}
| 22.904412 | 95 | 0.614125 |
012414ddedc5daabd3c9bca67e81a8645252fee6 | 2,977 | /*
* Copyright 2020 ZUP IT SERVICOS EM TECNOLOGIA E INOVACAO SA
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import UIKit
extension NavigationBarItem {
func toBarButtonItem(
controller: BeagleScreenViewController
) -> UIBarButtonItem {
let barButtonItem = NavigationBarButtonItem(barItem: self, controller: controller)
return barButtonItem
}
final private class NavigationBarButtonItem: UIBarButtonItem {
private let barItem: NavigationBarItem
private weak var controller: BeagleScreenViewController?
init(
barItem: NavigationBarItem,
controller: BeagleScreenViewController
) {
self.barItem = barItem
self.controller = controller
super.init()
if let localImage = barItem.image {
handleContextOnNavigationBarImage(icon: localImage)
accessibilityHint = barItem.text
} else {
title = barItem.text
}
accessibilityIdentifier = barItem.id
target = self
action = #selector(triggerAction)
ViewConfigurator.applyAccessibility(barItem.accessibility, to: self)
}
private func handleContextOnNavigationBarImage(icon: String) {
let expression: Expression<String> = "\(icon)"
let renderer = controller?.renderer
// Since `BeagleScreenViewController` creates a different view hierarchy, to get the correct hierarchy we need to use the `view` from our `controller`.
guard case .view(let view) = controller?.content else { return }
renderer?.observe(expression, andUpdateManyIn: view) { icon in
guard let icon = icon else { return }
self.image = UIImage(
named: icon,
in: self.controller?.dependencies.appBundle,
compatibleWith: nil
)?.withRenderingMode(.alwaysOriginal)
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
@objc private func triggerAction() {
if case .view(let view) = controller?.content {
controller?.execute(actions: [barItem.action], event: nil, origin: view)
}
}
}
}
| 37.2125 | 163 | 0.612697 |
90377c3180e11ef047f6229bd861cdc37c036d80 | 1,389 | //
// CustomPopAnimator.swift
// VKClient
//
// Created by Сергей Черных on 19.09.2021.
//
import UIKit
class CustomPopAnimator: NSObject, UIViewControllerAnimatedTransitioning {
private let duration: TimeInterval = 0.5
func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return duration
}
func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
guard let source = transitionContext.viewController(forKey: .from),
let destination = transitionContext.viewController(forKey: .to)
else { return }
transitionContext.containerView.addSubview(destination.view)
transitionContext.containerView.sendSubviewToBack(destination.view)
source.view.layer.anchorPoint = CGPoint(x: 0, y: 0)
destination.view.frame = source.view.frame
UIView.animate(
withDuration: duration,
animations: {
source.view.transform = CGAffineTransform(rotationAngle: -.pi/2)
}) { finished in
if finished && !transitionContext.transitionWasCancelled {
source.view.transform = .identity
}
transitionContext.completeTransition( finished && !transitionContext.transitionWasCancelled)
}
}
}
| 33.878049 | 109 | 0.666667 |
0aa8ebefcec73425ad83677f21553e45450e0e3f | 713 | //
// SourceEditorExtension.swift
// XCodeTCAExtension
//
// Created by Van Simmons on 8/10/20.
// Copyright © 2020 ComputeCycles, LLC. All rights reserved.
//
import Foundation
import XcodeKit
class SourceEditorExtension: NSObject, XCSourceEditorExtension {
/*
func extensionDidFinishLaunching() {
// If your extension needs to do any work at launch, implement this optional method.
}
*/
/*
var commandDefinitions: [[XCSourceEditorCommandDefinitionKey: Any]] {
// If your extension needs to return a collection of command definitions that differs from those in its Info.plist, implement this optional property getter.
return []
}
*/
}
| 25.464286 | 164 | 0.68864 |
89064e9d68ca26777ee92425154e7e3678bb814e | 712 | //
// _ _ ______ _ ___ _
// / \ (_) .' ____ \ (_) .' ..] / |_
// / _ \ _ .--. __ | (___ \_| _ _ __ __ _| |_ `| |-'
// / ___ \ [ `/'`\] [ | _.____`. [ \ [ \ [ ] [ | '-| |-' | |
// _/ / \ \_ | | | | | \____) | \ \/\ \/ / | | | | | |,
// |____| |____| [___] [___] \______.' \__/\__/ [___] [___] \__/
// GitHub: https://github.com/AnnieAri
// ASError.swift
// Alamofire
//
// Created by AriSwift on 2018/12/24.
//
//
import Foundation
public enum ASError: Error {
case deserializeFailed
case requestFailed
}
| 33.904762 | 79 | 0.328652 |
9b102f2f56d42c0464aaa01cc95fbdb2262f8db2 | 11,182 | //
// Encryption.swift
// StandUp-iOS
//
// Created by Peter on 12/01/19.
// Copyright © 2019 BlockchainCommons. All rights reserved.
//
import Foundation
import CryptoKit
import KeychainSwift
class Encryption {
let keychain = KeychainSwift()
let ud = UserDefaults.standard
func encryptData(dataToEncrypt: Data, completion: @escaping ((encryptedData: Data?, error: Bool)) -> Void) {
if let key = self.keychain.getData("privateKey") {
let k = SymmetricKey(data: key)
if let sealedBox = try? ChaChaPoly.seal(dataToEncrypt, using: k) {
let encryptedData = sealedBox.combined
completion((encryptedData,false))
} else {
completion((nil,true))
}
}
}
func decryptData(dataToDecrypt: Data, completion: @escaping ((Data?)) -> Void) {
if #available(iOS 13.0, *) {
if let key = self.keychain.getData("privateKey") {
do {
let box = try ChaChaPoly.SealedBox.init(combined: dataToDecrypt)
let k = SymmetricKey(data: key)
let decryptedData = try ChaChaPoly.open(box, using: k)
completion((decryptedData))
} catch {
print("failed decrypting")
completion((nil))
}
}
}
}
func getNode(completion: @escaping ((node: NodeStruct?, error: Bool)) -> Void) {
if #available(iOS 13.0, *) {
if let key = keychain.getData("privateKey") {
let pk = SymmetricKey(data: key)
let cd = CoreDataService()
cd.retrieveEntity(entityName: .nodes) { (nodes, errorDescription) in
if errorDescription == nil {
if nodes!.count > 0 {
for node in nodes! {
if (node["isActive"] as! Bool) {
var decryptedNode = node
var loopCount = 0
for (k, value) in node {
if k != "isActive" && k != "id" && k != "network" {
loopCount += 1
let dataToDecrypt = value as! Data
do {
let box = try ChaChaPoly.SealedBox.init(combined: dataToDecrypt)
let decryptedData = try ChaChaPoly.open(box, using: pk)
if let decryptedValue = String(data: decryptedData, encoding: .utf8) {
decryptedNode[k] = decryptedValue
if loopCount == 4 {
// we know there will be 7 keys, so can check the loop has finished here
let nodeStruct = NodeStruct.init(dictionary: decryptedNode)
decryptedNode.removeAll()
completion((nodeStruct,false))
}
} else {
completion((nil,true))
}
} catch {
print("error decryting node")
completion((nil,true))
}
}
}
}
}
} else {
print("no nodes")
completion((nil,true))
}
} else {
print("error getting nodes: \(errorDescription!)")
}
}
} else {
print("private key not accessible")
completion((nil,true))
}
} else {
completion((nil,true))
}
}
func saveNode(newNode: [String:Any], completion: @escaping ((success: Bool, error: String?)) -> Void) {
if #available(iOS 13.0, *) {
if let key = self.keychain.getData("privateKey") {
let cd = CoreDataService()
let pk = SymmetricKey(data: key)
var encryptedNode = newNode
func save() {
for (k, value) in newNode {
if k != "id" && k != "isActive" && k != "network" {
let stringToEncrypt = value as! String
if let dataToEncrypt = stringToEncrypt.data(using: .utf8) {
if let sealedBox = try? ChaChaPoly.seal(dataToEncrypt, using: pk) {
let encryptedData = sealedBox.combined
encryptedNode[k] = encryptedData
} else {
completion((false, "node encryption failed"))
}
} else {
completion((false, "node encryption failed"))
}
}
}
cd.saveEntity(dict: encryptedNode, entityName: .nodes) {
if !cd.errorBool {
completion((true, nil))
} else {
completion((false, nil))
}
}
}
cd.retrieveEntity(entityName: .nodes) { (existingNodes, errorDescription) in
if errorDescription == nil && existingNodes != nil {
if existingNodes!.count > 0 {
var nodeAlreadyExists = false
for (i, n) in existingNodes!.enumerated() {
let existingOnionEncrypted = n["onionAddress"] as! Data
self.decryptData(dataToDecrypt: existingOnionEncrypted) { (decrpytedOnion) in
if decrpytedOnion != nil {
if (newNode["onionAddress"] as! String) == String(data: decrpytedOnion!, encoding: .utf8) {
nodeAlreadyExists = true
}
if i + 1 == existingNodes!.count {
if !nodeAlreadyExists {
save()
} else {
completion((false, "node already added"))
}
}
}
}
}
} else {
save()
}
}
}
} else {
completion((false, nil))
}
} else {
completion((false, nil))
}
}
}
| 39.373239 | 131 | 0.253264 |
895fefc4c4bc476d5c69947b40aa17220a959a48 | 4,407 | //
// Operation.swift
// Parse
//
// Created by Rex Sheng on 1/15/16.
// Copyright © 2016 Rex Sheng. All rights reserved.
//
public enum Operation {
case AddUnique(String, [AnyObject])
case Remove(String, [AnyObject])
case Add(String, [AnyObject])
case Increase(String, Int)
case SetValue(String, ParseType)
case AddRelation(String, Pointer)
case RemoveRelation(String, Pointer)
case SetSecurity(String)
case ClearSecurity
case DeleteColumn(String)
}
public class _Operations {
var operations: [Operation]
init(operations: [Operation]) {
self.operations = operations
}
}
public class Operations<T: ParseObject>: _Operations {
let object: T
public init(_ object: T, operations: [Operation]) {
self.object = object
super.init(operations: operations)
}
}
extension Operations {
func updateRelations() {
let this = Pointer(className: T.className, objectId: object.objectId)
for operation in operations {
switch operation {
case .AddRelation(let key, let pointer):
RelationsCache.of(this, key: key, toClass: pointer.className) { (relation) in
relation.addObject(pointer)
}
case .RemoveRelation(let key, let pointer):
RelationsCache.of(this, key: key, toClass: pointer.className) { (relation) in
relation.removeObjectId(pointer.objectId)
}
default:
continue
}
}
}
}
extension ParseObject {
public func operation() -> Operations<Self> {
return Operations(self, operations: [])
}
public static func operation() -> Operations<Self> {
return Self().operation()
}
public func addRelation<U: ParseObject>(key: String, to: U) -> Operations<Self> {
return operation().addRelation(key, to: to)
}
public func removeRelation<U: ParseObject>(key: String, to: U) -> Operations<Self> {
return operation().removeRelation(key, to: to)
}
}
extension Data {
public func convertIntoOperation(op: _Operations, convertPointer: (Pointer -> Pointer?)? = nil) {
for (key, value) in raw {
switch key {
case "objectId", "createdAt", "updatedAt":
continue
default:
if let c = convertPointer, value = value as? Pointer.RawValue,
pointer = Pointer(value), converted = c(pointer) {
op.operation(.SetValue(key, converted))
} else {
op.operation(.SetValue(key, AnyWrapper(value)))
}
}
}
}
}
extension _Operations {
static func convertToOperation<U: ParseObject>(key: String, value: U?) -> Operation {
if let value = value {
if let file = value as? File, name = file.name.get() {
return .SetValue(key, AnyWrapper(["name": name, "__type": "File"]))
}
return .SetValue(key, Pointer(object: value))
} else {
return .SetValue(key, ParseValue(nil))
}
}
public func operation(operation: Operation) -> Self {
operations.append(operation)
return self
}
public func set(key: String, value: [AnyObject]) -> Self {
return operation(.SetValue(key, AnyWrapper(value)))
}
public func set(key: String, value: ParseValueLiteralConvertible) -> Self {
if let date = value as? NSDate {
return set(key, value: Date(date: date))
}
return set(key, value: ParseValue(value))
}
public func set<U: ParseObject>(key: String, value: U) -> Self {
return operation(_Operations.convertToOperation(key, value: value))
}
public func set<U: ParseType>(key: String, value: U) -> Self {
return operation(.SetValue(key, value))
}
public func addRelation<U: ParseObject>(key: String, to: U) -> Self {
return operation(.AddRelation(key, Pointer(object: to)))
}
public func addUnique(key: String, object: AnyObject) -> Self {
return operation(.AddUnique(key, [object]))
}
public func add(key: String, object: AnyObject) -> Self {
return operation(.Add(key, [object]))
}
public func remove(key: String, object: AnyObject) -> Self {
return operation(.Remove(key, [object]))
}
public func addUnique(key: String, objects: [AnyObject]) -> Self {
return operation(.AddUnique(key, objects))
}
public func add(key: String, objects: [AnyObject]) -> Self {
return operation(.Add(key, objects))
}
public func remove(key: String, objects: [AnyObject]) -> Self {
return operation(.Remove(key, objects))
}
public func increase(key: String, amount: Int) -> Self {
return operation(.Increase(key, amount))
}
public func removeRelation<U: ParseObject>(key: String, to: U) -> Self {
return operation(.RemoveRelation(key, Pointer(object: to)))
}
} | 26.871951 | 98 | 0.689358 |
e0a22d2d452c540746088e486aa8c86c639057ce | 11,156 | // This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
import CoreFoundation
#if os(OSX) || os(iOS)
internal let kCFCompareLessThan = CFComparisonResult.compareLessThan
internal let kCFCompareEqualTo = CFComparisonResult.compareEqualTo
internal let kCFCompareGreaterThan = CFComparisonResult.compareGreaterThan
#endif
internal enum _NSSimpleObjCType : UnicodeScalar {
case ID = "@"
case Class = "#"
case Sel = ":"
case Char = "c"
case UChar = "C"
case Short = "s"
case UShort = "S"
case Int = "i"
case UInt = "I"
case Long = "l"
case ULong = "L"
case LongLong = "q"
case ULongLong = "Q"
case Float = "f"
case Double = "d"
case Bitfield = "b"
case Bool = "B"
case Void = "v"
case Undef = "?"
case Ptr = "^"
case CharPtr = "*"
case Atom = "%"
case ArrayBegin = "["
case ArrayEnd = "]"
case UnionBegin = "("
case UnionEnd = ")"
case StructBegin = "{"
case StructEnd = "}"
case Vector = "!"
case Const = "r"
}
extension Int {
init(_ v: _NSSimpleObjCType) {
self.init(UInt8(ascii: v.rawValue))
}
}
extension Int8 {
init(_ v: _NSSimpleObjCType) {
self.init(Int(v))
}
}
extension String {
init(_ v: _NSSimpleObjCType) {
self.init(v.rawValue)
}
}
extension _NSSimpleObjCType {
init?(_ v: UInt8) {
self.init(rawValue: UnicodeScalar(v))
}
init?(_ v: String?) {
if let rawValue = v?.unicodeScalars.first {
self.init(rawValue: rawValue)
} else {
return nil
}
}
}
// mapping of ObjC types to sizes and alignments (note that .Int is 32-bit)
// FIXME use a generic function, unfortuantely this seems to promote the size to 8
private let _NSObjCSizesAndAlignments : Dictionary<_NSSimpleObjCType, (Int, Int)> = [
.ID : ( sizeof(AnyObject.self), alignof(AnyObject.self) ),
.Class : ( sizeof(AnyClass.self), alignof(AnyClass.self) ),
.Char : ( sizeof(CChar.self), alignof(CChar.self) ),
.UChar : ( sizeof(UInt8.self), alignof(UInt8.self) ),
.Short : ( sizeof(Int16.self), alignof(Int16.self) ),
.UShort : ( sizeof(UInt16.self), alignof(UInt16.self) ),
.Int : ( sizeof(Int32.self), alignof(Int32.self) ),
.UInt : ( sizeof(UInt32.self), alignof(UInt32.self) ),
.Long : ( sizeof(Int32.self), alignof(Int32.self) ),
.ULong : ( sizeof(UInt32.self), alignof(UInt32.self) ),
.LongLong : ( sizeof(Int64.self), alignof(Int64.self) ),
.ULongLong : ( sizeof(UInt64.self), alignof(UInt64.self) ),
.Float : ( sizeof(Float.self), alignof(Float.self) ),
.Double : ( sizeof(Double.self), alignof(Double.self) ),
.Bool : ( sizeof(Bool.self), alignof(Bool.self) ),
.CharPtr : ( sizeof(UnsafePointer<CChar>.self), alignof(UnsafePointer<CChar>.self))
]
internal func _NSGetSizeAndAlignment(_ type: _NSSimpleObjCType,
_ size : inout Int,
_ align : inout Int) -> Bool {
guard let sizeAndAlignment = _NSObjCSizesAndAlignments[type] else {
return false
}
size = sizeAndAlignment.0
align = sizeAndAlignment.1
return true
}
public func NSGetSizeAndAlignment(_ typePtr: UnsafePointer<Int8>,
_ sizep: UnsafeMutablePointer<Int>?,
_ alignp: UnsafeMutablePointer<Int>?) -> UnsafePointer<Int8> {
let type = _NSSimpleObjCType(UInt8(typePtr.pointee))!
var size : Int = 0
var align : Int = 0
if !_NSGetSizeAndAlignment(type, &size, &align) {
// FIXME: This used to return nil, but the corresponding Darwin
// implementation is defined as returning a non-optional value.
fatalError("invalid type encoding")
}
sizep?.pointee = size
alignp?.pointee = align
return typePtr.advanced(by: 1)
}
public enum ComparisonResult : Int {
case orderedAscending = -1
case orderedSame
case orderedDescending
internal static func _fromCF(_ val: CFComparisonResult) -> ComparisonResult {
if val == kCFCompareLessThan {
return .orderedAscending
} else if val == kCFCompareGreaterThan {
return .orderedDescending
} else {
return .orderedSame
}
}
}
/* Note: QualityOfService enum is available on all platforms, but it may not be implemented on all platforms. */
public enum NSQualityOfService : Int {
/* UserInteractive QoS is used for work directly involved in providing an interactive UI such as processing events or drawing to the screen. */
case userInteractive
/* UserInitiated QoS is used for performing work that has been explicitly requested by the user and for which results must be immediately presented in order to allow for further user interaction. For example, loading an email after a user has selected it in a message list. */
case userInitiated
/* Utility QoS is used for performing work which the user is unlikely to be immediately waiting for the results. This work may have been requested by the user or initiated automatically, does not prevent the user from further interaction, often operates at user-visible timescales and may have its progress indicated to the user by a non-modal progress indicator. This work will run in an energy-efficient manner, in deference to higher QoS work when resources are constrained. For example, periodic content updates or bulk file operations such as media import. */
case utility
/* Background QoS is used for work that is not user initiated or visible. In general, a user is unaware that this work is even happening and it will run in the most efficient manner while giving the most deference to higher QoS work. For example, pre-fetching content, search indexing, backups, and syncing of data with external systems. */
case background
/* Default QoS indicates the absence of QoS information. Whenever possible QoS information will be inferred from other sources. If such inference is not possible, a QoS between UserInitiated and Utility will be used. */
case `default`
}
public struct SortOptions: OptionSet {
public let rawValue : UInt
public init(rawValue: UInt) { self.rawValue = rawValue }
public static let concurrent = SortOptions(rawValue: UInt(1 << 0))
public static let stable = SortOptions(rawValue: UInt(1 << 4))
}
public struct EnumerationOptions: OptionSet {
public let rawValue : UInt
public init(rawValue: UInt) { self.rawValue = rawValue }
public static let concurrent = EnumerationOptions(rawValue: UInt(1 << 0))
public static let reverse = EnumerationOptions(rawValue: UInt(1 << 1))
}
public typealias Comparator = (AnyObject, AnyObject) -> ComparisonResult
public let NSNotFound: Int = Int.max
internal func NSRequiresConcreteImplementation(_ fn: String = #function, file: StaticString = #file, line: UInt = #line) -> Never {
fatalError("\(fn) must be overriden in subclass implementations", file: file, line: line)
}
internal func NSUnimplemented(_ fn: String = #function, file: StaticString = #file, line: UInt = #line) -> Never {
fatalError("\(fn) is not yet implemented", file: file, line: line)
}
internal func NSInvalidArgument(_ message: String, method: String = #function, file: StaticString = #file, line: UInt = #line) -> Never {
fatalError("\(method): \(message)", file: file, line: line)
}
internal struct _CFInfo {
// This must match _CFRuntimeBase
var info: UInt32
var pad : UInt32
init(typeID: CFTypeID) {
// This matches what _CFRuntimeCreateInstance does to initialize the info value
info = UInt32((UInt32(typeID) << 8) | (UInt32(0x80)))
pad = 0
}
init(typeID: CFTypeID, extra: UInt32) {
info = UInt32((UInt32(typeID) << 8) | (UInt32(0x80)))
pad = extra
}
}
internal protocol _CFBridgable {
associatedtype CFType
var _cfObject: CFType { get }
}
internal protocol _SwiftBridgable {
associatedtype SwiftType
var _swiftObject: SwiftType { get }
}
internal protocol _NSBridgable {
associatedtype NSType
var _nsObject: NSType { get }
}
#if os(OSX) || os(iOS)
private let _SwiftFoundationModuleName = "SwiftFoundation"
#else
private let _SwiftFoundationModuleName = "Foundation"
#endif
/**
Returns the class name for a class. For compatibility with Foundation on Darwin,
Foundation classes are returned as unqualified names.
Only top-level Swift classes (Foo.bar) are supported at present. There is no
canonical encoding for other types yet, except for the mangled name, which is
neither stable nor human-readable.
*/
public func NSStringFromClass(_ aClass: AnyClass) -> String {
let aClassName = String(reflecting: aClass).bridge()
let components = aClassName.components(separatedBy: ".")
guard components.count == 2 else {
fatalError("NSStringFromClass: \(String(reflecting: aClass)) is not a top-level class")
}
if components[0] == _SwiftFoundationModuleName {
return components[1]
} else {
return String(aClassName)
}
}
/**
Returns the class metadata given a string. For compatibility with Foundation on Darwin,
unqualified names are looked up in the Foundation module.
Only top-level Swift classes (Foo.bar) are supported at present. There is no
canonical encoding for other types yet, except for the mangled name, which is
neither stable nor human-readable.
*/
public func NSClassFromString(_ aClassName: String) -> AnyClass? {
let aClassNameWithPrefix : String
let components = aClassName.bridge().components(separatedBy: ".")
switch components.count {
case 1:
guard !aClassName.hasPrefix("_Tt") else {
NSLog("*** NSClassFromString(\(aClassName)): cannot yet decode mangled class names")
return nil
}
aClassNameWithPrefix = _SwiftFoundationModuleName + "." + aClassName
break
case 2:
aClassNameWithPrefix = aClassName
break
default:
NSLog("*** NSClassFromString(\(aClassName)): nested class names not yet supported")
return nil
}
return _typeByName(aClassNameWithPrefix) as? AnyClass
}
| 37.816949 | 571 | 0.642076 |
1aa2f50391947cd14696c0d38737f8c1acd17fc9 | 23,045 | //
// ViewController.swift
// IonicRunner
//
import UIKit
import WebKit
import Cordova
open class CAPBridgeViewController: UIViewController, CAPBridgeDelegate, WKScriptMessageHandler, WKUIDelegate, WKNavigationDelegate {
private var webView: WKWebView?
public var bridgedWebView: WKWebView? {
return webView
}
public var bridgedViewController: UIViewController? {
return self
}
public let cordovaParser = CDVConfigParser.init();
private var hostname: String?
private var allowNavigationConfig: [String]?
private var basePath: String = ""
private let assetsFolder = "public"
private enum WebViewLoadingState {
case unloaded
case initialLoad(isOpaque: Bool)
case subsequentLoad
}
private var webViewLoadingState = WebViewLoadingState.unloaded
private var isStatusBarVisible = true
private var statusBarStyle: UIStatusBarStyle = .default
private var statusBarAnimation: UIStatusBarAnimation = .slide
@objc public var supportedOrientations: Array<Int> = []
@objc public var startDir = ""
@objc public var config: String?
// Construct the Capacitor runtime
public var bridge: CAPBridge?
private var handler: CAPAssetHandler?
private var urlPath: String?
open func setUrlPath(path: String) {
self.urlPath = path
}
override open func loadView() {
let configUrl = Bundle.main.url(forResource: "config", withExtension: "xml")
let configParser = XMLParser(contentsOf: configUrl!)!;
configParser.delegate = cordovaParser
configParser.parse()
guard let startPath = self.getStartPath() else {
return
}
setStatusBarDefaults()
setScreenOrientationDefaults()
let capConfig = CAPConfig(self.config)
HTTPCookieStorage.shared.cookieAcceptPolicy = HTTPCookie.AcceptPolicy.always
let webViewConfiguration = WKWebViewConfiguration()
self.handler = CAPAssetHandler()
self.handler!.setAssetPath(startPath)
var specifiedScheme = CAPBridge.CAP_DEFAULT_SCHEME
let configScheme = capConfig.getString("server.iosScheme") ?? CAPBridge.CAP_DEFAULT_SCHEME
// check if WebKit handles scheme and if it is valid according to Apple's documentation
if !WKWebView.handlesURLScheme(configScheme) && configScheme.range(of: "^[a-z][a-z0-9.+-]*$", options: [.regularExpression, .caseInsensitive], range: nil, locale: nil) != nil {
specifiedScheme = configScheme.lowercased()
}
webViewConfiguration.setURLSchemeHandler(self.handler, forURLScheme: specifiedScheme)
let o = WKUserContentController()
o.add(self, name: "bridge")
webViewConfiguration.userContentController = o
configureWebView(configuration: webViewConfiguration)
if let appendUserAgent = (capConfig.getValue("ios.appendUserAgent") as? String) ?? (capConfig.getValue("appendUserAgent") as? String) {
webViewConfiguration.applicationNameForUserAgent = appendUserAgent
}
webView = WKWebView(frame: .zero, configuration: webViewConfiguration)
webView?.scrollView.bounces = false
let availableInsets = ["automatic", "scrollableAxes", "never", "always"]
if let contentInset = (capConfig.getValue("ios.contentInset") as? String),
let index = availableInsets.firstIndex(of: contentInset) {
webView?.scrollView.contentInsetAdjustmentBehavior = UIScrollView.ContentInsetAdjustmentBehavior.init(rawValue: index)!
} else {
webView?.scrollView.contentInsetAdjustmentBehavior = .never
}
webView?.uiDelegate = self
webView?.navigationDelegate = self
if let allowsLinkPreview = (capConfig.getValue("ios.allowsLinkPreview") as? Bool) {
webView?.allowsLinkPreview = allowsLinkPreview
}
webView?.configuration.preferences.setValue(true, forKey: "allowFileAccessFromFileURLs")
view = webView
setKeyboardRequiresUserInteraction(false)
bridge = CAPBridge(self, o, capConfig, specifiedScheme)
if let backgroundColor = (bridge!.config.getValue("ios.backgroundColor") as? String) ?? (bridge!.config.getValue("backgroundColor") as? String) {
webView?.backgroundColor = UIColor(fromHex: backgroundColor)
webView?.scrollView.backgroundColor = UIColor(fromHex: backgroundColor)
} else if #available(iOS 13, *) {
// Use the system background colors if background is not set by user
webView?.backgroundColor = UIColor.systemBackground
webView?.scrollView.backgroundColor = UIColor.systemBackground
}
if let overrideUserAgent = (bridge!.config.getValue("ios.overrideUserAgent") as? String) ?? (bridge!.config.getValue("overrideUserAgent") as? String) {
webView?.customUserAgent = overrideUserAgent
}
}
private func getStartPath() -> String? {
var resourcesPath = assetsFolder
if !startDir.isEmpty {
resourcesPath = URL(fileURLWithPath: resourcesPath).appendingPathComponent(startDir).relativePath
}
guard var startPath = Bundle.main.path(forResource: resourcesPath, ofType: nil) else {
printLoadError()
return nil
}
if !isDeployDisabled() && !isNewBinary() {
let defaults = UserDefaults.standard
let persistedPath = defaults.string(forKey: "serverBasePath")
if (persistedPath != nil && !persistedPath!.isEmpty) {
let libPath = NSSearchPathForDirectoriesInDomains(.libraryDirectory, .userDomainMask, true)[0]
let cordovaDataDirectory = (libPath as NSString).appendingPathComponent("NoCloud")
let snapshots = (cordovaDataDirectory as NSString).appendingPathComponent("ionic_built_snapshots")
startPath = (snapshots as NSString).appendingPathComponent((persistedPath! as NSString).lastPathComponent)
}
}
self.basePath = startPath
return startPath
}
func isDeployDisabled() -> Bool {
let val = cordovaParser.settings.object(forKey: "DisableDeploy".lowercased()) as? NSString
return val?.boolValue ?? false
}
func isNewBinary() -> Bool {
if let plist = Bundle.main.infoDictionary {
if let versionCode = plist["CFBundleVersion"] as? String, let versionName = plist["CFBundleShortVersionString"] as? String {
let prefs = UserDefaults.standard
let lastVersionCode = prefs.string(forKey: "lastBinaryVersionCode")
let lastVersionName = prefs.string(forKey: "lastBinaryVersionName")
if !versionCode.isEqual(lastVersionCode) || !versionName.isEqual(lastVersionName) {
prefs.set(versionCode, forKey: "lastBinaryVersionCode")
prefs.set(versionName, forKey: "lastBinaryVersionName")
prefs.set("", forKey: "serverBasePath")
prefs.synchronize()
return true
}
}
}
return false
}
override open func viewDidLoad() {
super.viewDidLoad()
self.becomeFirstResponder()
loadWebView()
}
func printLoadError() {
let fullStartPath = URL(fileURLWithPath: assetsFolder).appendingPathComponent(startDir)
CAPLog.print("⚡️ ERROR: Unable to load \(fullStartPath.relativePath)/index.html")
CAPLog.print("⚡️ This file is the root of your web app and must exist before")
CAPLog.print("⚡️ Capacitor can run. Ensure you've run capacitor copy at least")
CAPLog.print("⚡️ or, if embedding, that this directory exists as a resource directory.")
}
func fatalLoadError() -> Never {
printLoadError()
exit(1)
}
func loadWebView() {
// Set the webview to be not opaque on the inital load. This prevents
// the webview from showing a white background, which is its default
// loading display, as that can appear as a screen flash. This might
// have already been set by something else, like a plugin, so we want
// to save the current value to reset it on success or failure.
if let webView = webView, case .unloaded = webViewLoadingState {
webViewLoadingState = .initialLoad(isOpaque: webView.isOpaque)
webView.isOpaque = false
}
let fullStartPath = URL(fileURLWithPath: assetsFolder).appendingPathComponent(startDir).appendingPathComponent("index")
if Bundle.main.path(forResource: fullStartPath.relativePath, ofType: "html") == nil {
fatalLoadError()
}
hostname = bridge!.config.getString("server.url") ?? "\(bridge!.getLocalUrl())"
allowNavigationConfig = bridge!.config.getValue("server.allowNavigation") as? Array<String>
if let urlPath = self.urlPath {
hostname! += urlPath
}
if bridge!.isDevMode() && bridge!.config.getString("server.url") != nil {
let toastPlugin = bridge!.getOrLoadPlugin(pluginName: "Toast") as? CAPToastPlugin
toastPlugin!.showToast(vc: self, text: "Using app server \(hostname!)", duration: 3500)
}
CAPLog.print("⚡️ Loading app at \(hostname!)...")
let request = URLRequest(url: URL(string: hostname!)!)
_ = webView?.load(request)
}
func setServerPath(path: String) {
self.basePath = path
self.handler?.setAssetPath(path)
}
open func setStatusBarDefaults() {
if let plist = Bundle.main.infoDictionary {
if let statusBarHidden = plist["UIStatusBarHidden"] as? Bool {
if (statusBarHidden) {
self.isStatusBarVisible = false
}
}
if let statusBarStyle = plist["UIStatusBarStyle"] as? String {
if (statusBarStyle == "UIStatusBarStyleDarkContent") {
if #available(iOS 13.0, *) {
self.statusBarStyle = .darkContent
} else {
self.statusBarStyle = .default
}
} else if (statusBarStyle != "UIStatusBarStyleDefault") {
self.statusBarStyle = .lightContent
}
}
}
}
open func setScreenOrientationDefaults() {
if let plist = Bundle.main.infoDictionary {
if let orientations = plist["UISupportedInterfaceOrientations"] as? Array<String> {
for orientation in orientations {
if orientation == "UIInterfaceOrientationPortrait" {
self.supportedOrientations.append(UIInterfaceOrientation.portrait.rawValue)
}
if orientation == "UIInterfaceOrientationPortraitUpsideDown" {
self.supportedOrientations.append(UIInterfaceOrientation.portraitUpsideDown.rawValue)
}
if orientation == "UIInterfaceOrientationLandscapeLeft" {
self.supportedOrientations.append(UIInterfaceOrientation.landscapeLeft.rawValue)
}
if orientation == "UIInterfaceOrientationLandscapeRight" {
self.supportedOrientations.append(UIInterfaceOrientation.landscapeRight.rawValue)
}
}
if self.supportedOrientations.count == 0 {
self.supportedOrientations.append(UIInterfaceOrientation.portrait.rawValue)
}
}
}
}
open func configureWebView(configuration: WKWebViewConfiguration) {
configuration.allowsInlineMediaPlayback = true
configuration.suppressesIncrementalRendering = false
configuration.allowsAirPlayForMediaPlayback = true
configuration.mediaTypesRequiringUserActionForPlayback = []
}
open func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
// Reset the bridge on each navigation
bridge!.reset()
}
open func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
NotificationCenter.default.post(name: Notification.Name(CAPNotifications.DecidePolicyForNavigationAction.name()), object: navigationAction)
let navUrl = navigationAction.request.url!
/*
* Give plugins the chance to handle the url
*/
if let plugins = bridge?.plugins {
for pluginObject in plugins {
let plugin = pluginObject.value
let selector = NSSelectorFromString("shouldOverrideLoad:")
if plugin.responds(to: selector) {
let shouldOverrideLoad = plugin.shouldOverrideLoad(navigationAction)
if (shouldOverrideLoad != nil) {
if (shouldOverrideLoad == true) {
decisionHandler(.cancel)
return
} else if shouldOverrideLoad == false {
decisionHandler(.allow)
return
}
}
}
}
}
if let allowNavigation = allowNavigationConfig, let requestHost = navUrl.host {
for pattern in allowNavigation {
if matchHost(host: requestHost, pattern: pattern.lowercased()) {
decisionHandler(.allow)
return
}
}
}
if navUrl.absoluteString.range(of: hostname!) == nil && (navigationAction.targetFrame == nil || (navigationAction.targetFrame?.isMainFrame)!) {
if UIApplication.shared.applicationState == .active {
UIApplication.shared.open(navUrl, options: [:], completionHandler: nil)
}
decisionHandler(.cancel)
return
}
decisionHandler(.allow)
}
open func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
if case .initialLoad(let isOpaque) = webViewLoadingState {
webView.isOpaque = isOpaque
webViewLoadingState = .subsequentLoad
}
CAPLog.print("⚡️ WebView loaded")
}
open func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
if case .initialLoad(let isOpaque) = webViewLoadingState {
webView.isOpaque = isOpaque
webViewLoadingState = .subsequentLoad
}
CAPLog.print("⚡️ WebView failed to load")
CAPLog.print("⚡️ Error: " + error.localizedDescription)
}
open func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) {
CAPLog.print("⚡️ WebView failed provisional navigation")
CAPLog.print("⚡️ Error: " + error.localizedDescription)
}
open func webViewWebContentProcessDidTerminate(_ webView: WKWebView) {
webView.reload()
}
open override func canPerformUnwindSegueAction(_ action: Selector, from fromViewController: UIViewController, withSender sender: Any) -> Bool {
return false
}
open func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
guard let bridge = bridge else {
return
}
self.userContentController(userContentController, didReceive: message, bridge: bridge)
}
typealias ClosureType = @convention(c) (Any, Selector, UnsafeRawPointer, Bool, Bool, Any?) -> Void
typealias NewClosureType = @convention(c) (Any, Selector, UnsafeRawPointer, Bool, Bool, Bool, Any?) -> Void
func setKeyboardRequiresUserInteraction( _ value: Bool) {
let frameworkName = "WK"
let className = "ContentView"
guard let wkc = NSClassFromString(frameworkName + className) else {
return
}
let oldSelector: Selector = sel_getUid("_startAssistingNode:userIsInteracting:blurPreviousNode:userObject:")
let newSelector: Selector = sel_getUid("_startAssistingNode:userIsInteracting:blurPreviousNode:changingActivityState:userObject:")
let newerSelector: Selector = sel_getUid("_elementDidFocus:userIsInteracting:blurPreviousNode:changingActivityState:userObject:")
let ios13Selector: Selector = sel_getUid("_elementDidFocus:userIsInteracting:blurPreviousNode:activityStateChanges:userObject:")
if let method = class_getInstanceMethod(wkc, oldSelector) {
let originalImp: IMP = method_getImplementation(method)
let original: ClosureType = unsafeBitCast(originalImp, to: ClosureType.self)
let block : @convention(block) (Any, UnsafeRawPointer, Bool, Bool, Any?) -> Void = { (me, arg0, arg1, arg2, arg3) in
original(me, oldSelector, arg0, !value, arg2, arg3)
}
let imp: IMP = imp_implementationWithBlock(block)
method_setImplementation(method, imp)
}
if let method = class_getInstanceMethod(wkc, newSelector) {
self.swizzleAutofocusMethod(method, newSelector, value)
}
if let method = class_getInstanceMethod(wkc, newerSelector) {
self.swizzleAutofocusMethod(method, newerSelector, value)
}
if let method = class_getInstanceMethod(wkc, ios13Selector) {
self.swizzleAutofocusMethod(method, ios13Selector, value)
}
}
func swizzleAutofocusMethod(_ method: Method, _ selector: Selector, _ value: Bool) {
let originalImp: IMP = method_getImplementation(method)
let original: NewClosureType = unsafeBitCast(originalImp, to: NewClosureType.self)
let block : @convention(block) (Any, UnsafeRawPointer, Bool, Bool, Bool, Any?) -> Void = { (me, arg0, arg1, arg2, arg3, arg4) in
original(me, selector, arg0, !value, arg2, arg3, arg4)
}
let imp: IMP = imp_implementationWithBlock(block)
method_setImplementation(method, imp)
}
func handleJSStartupError(_ error: [String:Any]) {
let message = error["message"] ?? "No message"
let url = error["url"] as? String ?? ""
let line = error["line"] ?? ""
let col = error["col"] ?? ""
var filename = ""
if let filenameIndex = url.range(of: "/", options: .backwards)?.lowerBound {
let index = url.index(after: filenameIndex)
filename = String(url[index...])
}
CAPLog.print("\n⚡️ ------ STARTUP JS ERROR ------\n")
CAPLog.print("⚡️ \(message)")
CAPLog.print("⚡️ URL: \(url)")
CAPLog.print("⚡️ \(filename):\(line):\(col)")
CAPLog.print("\n⚡️ See above for help with debugging blank-screen issues")
}
func matchHost(host: String, pattern: String) -> Bool {
if pattern == "*" {
return true
}
var host = host.split(separator: ".")
var pattern = pattern.split(separator: ".")
if host.count != pattern.count {
return false
}
if host == pattern {
return true
}
let wildcards = pattern.enumerated().filter { $0.element == "*" }
for wildcard in wildcards.reversed() {
host.remove(at: wildcard.offset)
pattern.remove(at: wildcard.offset)
}
return host == pattern
}
override open func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override open var prefersStatusBarHidden: Bool {
get {
return !isStatusBarVisible
}
}
override open var preferredStatusBarStyle: UIStatusBarStyle {
get {
return statusBarStyle
}
}
override open var preferredStatusBarUpdateAnimation: UIStatusBarAnimation {
get {
return statusBarAnimation
}
}
open func setStatusBarVisible(_ isStatusBarVisible: Bool) {
self.isStatusBarVisible = isStatusBarVisible
UIView.animate(withDuration: 0.2, animations: {
self.setNeedsStatusBarAppearanceUpdate()
})
}
open func setStatusBarStyle(_ statusBarStyle: UIStatusBarStyle) {
self.statusBarStyle = statusBarStyle
UIView.animate(withDuration: 0.2, animations: {
self.setNeedsStatusBarAppearanceUpdate()
})
}
open func setStatusBarAnimation(_ statusBarAnimation: UIStatusBarAnimation) {
self.statusBarAnimation = statusBarAnimation
}
open func webView(_ webView: WKWebView, runJavaScriptAlertPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping () -> Void) {
let alertController = UIAlertController(title: nil, message: message, preferredStyle: .alert)
alertController.addAction(UIAlertAction(title: "Ok", style: .default, handler: { (action) in
completionHandler()
}))
self.present(alertController, animated: true, completion: nil)
}
open func webView(_ webView: WKWebView, runJavaScriptConfirmPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping (Bool) -> Void) {
let alertController = UIAlertController(title: nil, message: message, preferredStyle: .alert)
alertController.addAction(UIAlertAction(title: "Ok", style: .default, handler: { (action) in
completionHandler(true)
}))
alertController.addAction(UIAlertAction(title: "Cancel", style: .default, handler: { (action) in
completionHandler(false)
}))
self.present(alertController, animated: true, completion: nil)
}
open func webView(_ webView: WKWebView, runJavaScriptTextInputPanelWithPrompt prompt: String, defaultText: String?, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping (String?) -> Void) {
let alertController = UIAlertController(title: nil, message: prompt, preferredStyle: .alert)
alertController.addTextField { (textField) in
textField.text = defaultText
}
alertController.addAction(UIAlertAction(title: "Ok", style: .default, handler: { (action) in
if let text = alertController.textFields?.first?.text {
completionHandler(text)
} else {
completionHandler(defaultText)
}
}))
alertController.addAction(UIAlertAction(title: "Cancel", style: .default, handler: { (action) in
completionHandler(nil)
}))
self.present(alertController, animated: true, completion: nil)
}
open func webView(_ webView: WKWebView, createWebViewWith configuration: WKWebViewConfiguration, for navigationAction: WKNavigationAction, windowFeatures: WKWindowFeatures) -> WKWebView? {
if (navigationAction.request.url != nil) {
UIApplication.shared.open(navigationAction.request.url!, options: [:], completionHandler: nil)
}
return nil
}
open func getWebView() -> WKWebView {
return self.webView!
}
open func getServerBasePath() -> String {
return self.basePath
}
open func setServerBasePath(path: String) {
setServerPath(path: path)
let request = URLRequest(url: URL(string: hostname!)!)
DispatchQueue.main.async {
_ = self.getWebView().load(request)
}
}
override open var supportedInterfaceOrientations: UIInterfaceOrientationMask {
var ret = 0
if self.supportedOrientations.contains(UIInterfaceOrientation.portrait.rawValue) {
ret = ret | (1 << UIInterfaceOrientation.portrait.rawValue)
}
if self.supportedOrientations.contains(UIInterfaceOrientation.portraitUpsideDown.rawValue) {
ret = ret | (1 << UIInterfaceOrientation.portraitUpsideDown.rawValue)
}
if self.supportedOrientations.contains(UIInterfaceOrientation.landscapeRight.rawValue) {
ret = ret | (1 << UIInterfaceOrientation.landscapeRight.rawValue)
}
if self.supportedOrientations.contains(UIInterfaceOrientation.landscapeLeft.rawValue) {
ret = ret | (1 << UIInterfaceOrientation.landscapeLeft.rawValue)
}
return UIInterfaceOrientationMask.init(rawValue: UInt(ret))
}
/**
* Add hooks to detect failed HTTP requests
func webView(webView: WKWebView,
didFailProvisionalNavigation navigation: WKNavigation!,
withError error: NSError) {
if error.code == -1001 { // TIMED OUT:
// CODE to handle TIMEOUT
} else if error.code == -1003 { // SERVER CANNOT BE FOUND
// CODE to handle SERVER not found
} else if error.code == -1100 { // URL NOT FOUND ON SERVER
// CODE to handle URL not found
}
}
*/
}
| 37.840722 | 204 | 0.702235 |
fb21573636569914c050d03945e7d066bb07d876 | 12,145 | // RUN: %target-swift-frontend -emit-silgen -sdk %S/Inputs -I %S/Inputs -enable-source-import %s | %FileCheck %s
// FIXME: rdar://problem/19648117 Needs splitting objc parts out
// XFAIL: linux
import Foundation
func takesMutablePointer(_ x: UnsafeMutablePointer<Int>) {}
func takesConstPointer(_ x: UnsafePointer<Int>) {}
func takesMutableVoidPointer(_ x: UnsafeMutableRawPointer) {}
func takesConstVoidPointer(_ x: UnsafeRawPointer) {}
func takesMutableRawPointer(_ x: UnsafeMutableRawPointer) {}
func takesConstRawPointer(_ x: UnsafeRawPointer) {}
// CHECK-LABEL: sil hidden @_TF18pointer_conversion16pointerToPointerFTGSpSi_GSPSi_Sv_T_
// CHECK: bb0([[MP:%.*]] : $UnsafeMutablePointer<Int>, [[CP:%.*]] : $UnsafePointer<Int>, [[MRP:%.*]] : $UnsafeMutableRawPointer):
func pointerToPointer(_ mp: UnsafeMutablePointer<Int>,
_ cp: UnsafePointer<Int>, _ mrp: UnsafeMutableRawPointer) {
// There should be no conversion here
takesMutablePointer(mp)
// CHECK: [[TAKES_MUTABLE_POINTER:%.*]] = function_ref @_TF18pointer_conversion19takesMutablePointer
// CHECK: apply [[TAKES_MUTABLE_POINTER]]([[MP]])
takesMutableVoidPointer(mp)
// CHECK: [[TAKES_MUTABLE_VOID_POINTER:%.*]] = function_ref @_TF18pointer_conversion23takesMutableVoidPointer
// CHECK: [[CONVERT:%.*]] = function_ref @_TFs32_convertPointerToPointerArgument
// CHECK: apply [[CONVERT]]<UnsafeMutablePointer<Int>, UnsafeMutableRawPointer>
// CHECK: apply [[TAKES_MUTABLE_VOID_POINTER]]
takesMutableRawPointer(mp)
// CHECK: [[TAKES_MUTABLE_RAW_POINTER:%.*]] = function_ref @_TF18pointer_conversion22takesMutableRawPointerFSvT_ :
// CHECK: [[CONVERT:%.*]] = function_ref @_TFs32_convertPointerToPointerArgument
// CHECK: apply [[CONVERT]]<UnsafeMutablePointer<Int>, UnsafeMutableRawPointer>
// CHECK: apply [[TAKES_MUTABLE_RAW_POINTER]]
takesConstPointer(mp)
// CHECK: [[TAKES_CONST_POINTER:%.*]] = function_ref @_TF18pointer_conversion17takesConstPointerFGSPSi_T_
// CHECK: [[CONVERT:%.*]] = function_ref @_TFs32_convertPointerToPointerArgument
// CHECK: apply [[CONVERT]]<UnsafeMutablePointer<Int>, UnsafePointer<Int>>
// CHECK: apply [[TAKES_CONST_POINTER]]
takesConstVoidPointer(mp)
// CHECK: [[TAKES_CONST_VOID_POINTER:%.*]] = function_ref @_TF18pointer_conversion21takesConstVoidPointerFSVT_
// CHECK: [[CONVERT:%.*]] = function_ref @_TFs32_convertPointerToPointerArgument
// CHECK: apply [[CONVERT]]<UnsafeMutablePointer<Int>, UnsafeRawPointer>
// CHECK: apply [[TAKES_CONST_VOID_POINTER]]
takesConstRawPointer(mp)
// CHECK: [[TAKES_CONST_RAW_POINTER:%.*]] = function_ref @_TF18pointer_conversion20takesConstRawPointerFSVT_ :
// CHECK: [[CONVERT:%.*]] = function_ref @_TFs32_convertPointerToPointerArgument
// CHECK: apply [[CONVERT]]<UnsafeMutablePointer<Int>, UnsafeRawPointer>
// CHECK: apply [[TAKES_CONST_RAW_POINTER]]
takesConstPointer(cp)
// CHECK: [[TAKES_CONST_POINTER:%.*]] = function_ref @_TF18pointer_conversion17takesConstPointerFGSPSi_T_
// CHECK: apply [[TAKES_CONST_POINTER]]([[CP]])
takesConstVoidPointer(cp)
// CHECK: [[TAKES_CONST_VOID_POINTER:%.*]] = function_ref @_TF18pointer_conversion21takesConstVoidPointerFSVT_
// CHECK: [[CONVERT:%.*]] = function_ref @_TFs32_convertPointerToPointerArgument
// CHECK: apply [[CONVERT]]<UnsafePointer<Int>, UnsafeRawPointer>
// CHECK: apply [[TAKES_CONST_VOID_POINTER]]
takesConstRawPointer(cp)
// CHECK: [[TAKES_CONST_RAW_POINTER:%.*]] = function_ref @_TF18pointer_conversion20takesConstRawPointerFSVT_
// CHECK: [[CONVERT:%.*]] = function_ref @_TFs32_convertPointerToPointerArgument
// CHECK: apply [[CONVERT]]<UnsafePointer<Int>, UnsafeRawPointer>
// CHECK: apply [[TAKES_CONST_RAW_POINTER]]
takesConstRawPointer(mrp)
// CHECK: [[TAKES_CONST_RAW_POINTER:%.*]] = function_ref @_TF18pointer_conversion20takesConstRawPointerFSVT_
// CHECK: [[CONVERT:%.*]] = function_ref @_TFs32_convertPointerToPointerArgument
// CHECK: apply [[CONVERT]]<UnsafeMutableRawPointer, UnsafeRawPointer>
// CHECK: apply [[TAKES_CONST_RAW_POINTER]]
}
// CHECK-LABEL: sil hidden @_TF18pointer_conversion14arrayToPointerFT_T_
func arrayToPointer() {
var ints = [1,2,3]
takesMutablePointer(&ints)
// CHECK: [[TAKES_MUTABLE_POINTER:%.*]] = function_ref @_TF18pointer_conversion19takesMutablePointer
// CHECK: [[CONVERT_MUTABLE:%.*]] = function_ref @_TFs37_convertMutableArrayToPointerArgument
// CHECK: [[OWNER:%.*]] = apply [[CONVERT_MUTABLE]]<Int, UnsafeMutablePointer<Int>>([[POINTER_BUF:%[0-9]*]],
// CHECK: [[POINTER:%.*]] = load [trivial] [[POINTER_BUF]]
// CHECK: apply [[TAKES_MUTABLE_POINTER]]([[POINTER]])
// CHECK: destroy_value [[OWNER]]
takesConstPointer(ints)
// CHECK: [[TAKES_CONST_POINTER:%.*]] = function_ref @_TF18pointer_conversion17takesConstPointerFGSPSi_T_
// CHECK: [[CONVERT_CONST:%.*]] = function_ref @_TFs35_convertConstArrayToPointerArgument
// CHECK: [[OWNER:%.*]] = apply [[CONVERT_CONST]]<Int, UnsafePointer<Int>>([[POINTER_BUF:%[0-9]*]],
// CHECK: [[POINTER:%.*]] = load [trivial] [[POINTER_BUF]]
// CHECK: apply [[TAKES_CONST_POINTER]]([[POINTER]])
// CHECK: destroy_value [[OWNER]]
takesMutableRawPointer(&ints)
// CHECK: [[TAKES_MUTABLE_RAW_POINTER:%.*]] = function_ref @_TF18pointer_conversion22takesMutableRawPointerFSvT_ :
// CHECK: [[CONVERT_MUTABLE:%.*]] = function_ref @_TFs37_convertMutableArrayToPointerArgument
// CHECK: [[OWNER:%.*]] = apply [[CONVERT_MUTABLE]]<Int, UnsafeMutableRawPointer>([[POINTER_BUF:%[0-9]*]],
// CHECK: [[POINTER:%.*]] = load [trivial] [[POINTER_BUF]]
// CHECK: apply [[TAKES_MUTABLE_RAW_POINTER]]([[POINTER]])
// CHECK: destroy_value [[OWNER]]
takesConstRawPointer(ints)
// CHECK: [[TAKES_CONST_RAW_POINTER:%.*]] = function_ref @_TF18pointer_conversion20takesConstRawPointerFSVT_ :
// CHECK: [[CONVERT_CONST:%.*]] = function_ref @_TFs35_convertConstArrayToPointerArgument
// CHECK: [[OWNER:%.*]] = apply [[CONVERT_CONST]]<Int, UnsafeRawPointer>([[POINTER_BUF:%[0-9]*]],
// CHECK: [[POINTER:%.*]] = load [trivial] [[POINTER_BUF]]
// CHECK: apply [[TAKES_CONST_RAW_POINTER]]([[POINTER]])
// CHECK: destroy_value [[OWNER]]
}
// CHECK-LABEL: sil hidden @_TF18pointer_conversion15stringToPointerFSST_
func stringToPointer(_ s: String) {
takesConstVoidPointer(s)
// CHECK: [[TAKES_CONST_VOID_POINTER:%.*]] = function_ref @_TF18pointer_conversion21takesConstVoidPointerFSV
// CHECK: [[CONVERT_STRING:%.*]] = function_ref @_TFs40_convertConstStringToUTF8PointerArgument
// CHECK: [[OWNER:%.*]] = apply [[CONVERT_STRING]]<UnsafeRawPointer>([[POINTER_BUF:%[0-9]*]],
// CHECK: [[POINTER:%.*]] = load [trivial] [[POINTER_BUF]]
// CHECK: apply [[TAKES_CONST_VOID_POINTER]]([[POINTER]])
// CHECK: destroy_value [[OWNER]]
takesConstRawPointer(s)
// CHECK: [[TAKES_CONST_RAW_POINTER:%.*]] = function_ref @_TF18pointer_conversion20takesConstRawPointerFSV
// CHECK: [[CONVERT_STRING:%.*]] = function_ref @_TFs40_convertConstStringToUTF8PointerArgument
// CHECK: [[OWNER:%.*]] = apply [[CONVERT_STRING]]<UnsafeRawPointer>([[POINTER_BUF:%[0-9]*]],
// CHECK: [[POINTER:%.*]] = load [trivial] [[POINTER_BUF]]
// CHECK: apply [[TAKES_CONST_RAW_POINTER]]([[POINTER]])
// CHECK: destroy_value [[OWNER]]
}
// CHECK-LABEL: sil hidden @_TF18pointer_conversion14inoutToPointerFT_T_
func inoutToPointer() {
var int = 0
// CHECK: [[INT:%.*]] = alloc_box ${ var Int }
// CHECK: [[PB:%.*]] = project_box [[INT]]
takesMutablePointer(&int)
// CHECK: [[TAKES_MUTABLE:%.*]] = function_ref @_TF18pointer_conversion19takesMutablePointer
// CHECK: [[POINTER:%.*]] = address_to_pointer [[PB]]
// CHECK: [[CONVERT:%.*]] = function_ref @_TFs30_convertInOutToPointerArgument
// CHECK: apply [[CONVERT]]<UnsafeMutablePointer<Int>>({{%.*}}, [[POINTER]])
// CHECK: apply [[TAKES_MUTABLE]]
var logicalInt: Int {
get { return 0 }
set { }
}
takesMutablePointer(&logicalInt)
// CHECK: [[TAKES_MUTABLE:%.*]] = function_ref @_TF18pointer_conversion19takesMutablePointer
// CHECK: [[GETTER:%.*]] = function_ref @_TFF18pointer_conversion14inoutToPointerFT_T_gL_10logicalIntSi
// CHECK: apply [[GETTER]]
// CHECK: [[CONVERT:%.*]] = function_ref @_TFs30_convertInOutToPointerArgument
// CHECK: apply [[CONVERT]]<UnsafeMutablePointer<Int>>
// CHECK: apply [[TAKES_MUTABLE]]
// CHECK: [[SETTER:%.*]] = function_ref @_TFF18pointer_conversion14inoutToPointerFT_T_sL_10logicalIntSi
// CHECK: apply [[SETTER]]
takesMutableRawPointer(&int)
// CHECK: [[TAKES_MUTABLE:%.*]] = function_ref @_TF18pointer_conversion22takesMutableRawPointer
// CHECK: [[POINTER:%.*]] = address_to_pointer [[PB]]
// CHECK: [[CONVERT:%.*]] = function_ref @_TFs30_convertInOutToPointerArgument
// CHECK: apply [[CONVERT]]<UnsafeMutableRawPointer>({{%.*}}, [[POINTER]])
// CHECK: apply [[TAKES_MUTABLE]]
takesMutableRawPointer(&logicalInt)
// CHECK: [[TAKES_MUTABLE:%.*]] = function_ref @_TF18pointer_conversion22takesMutableRawPointer
// CHECK: [[GETTER:%.*]] = function_ref @_TFF18pointer_conversion14inoutToPointerFT_T_gL_10logicalIntSi
// CHECK: apply [[GETTER]]
// CHECK: [[CONVERT:%.*]] = function_ref @_TFs30_convertInOutToPointerArgument
// CHECK: apply [[CONVERT]]<UnsafeMutableRawPointer>
// CHECK: apply [[TAKES_MUTABLE]]
// CHECK: [[SETTER:%.*]] = function_ref @_TFF18pointer_conversion14inoutToPointerFT_T_sL_10logicalIntSi
// CHECK: apply [[SETTER]]
}
class C {}
func takesPlusOnePointer(_ x: UnsafeMutablePointer<C>) {}
func takesPlusZeroPointer(_ x: AutoreleasingUnsafeMutablePointer<C>) {}
func takesPlusZeroOptionalPointer(_ x: AutoreleasingUnsafeMutablePointer<C?>) {}
// CHECK-LABEL: sil hidden @_TF18pointer_conversion19classInoutToPointerFT_T_
func classInoutToPointer() {
var c = C()
// CHECK: [[VAR:%.*]] = alloc_box ${ var C }
// CHECK: [[PB:%.*]] = project_box [[VAR]]
takesPlusOnePointer(&c)
// CHECK: [[TAKES_PLUS_ONE:%.*]] = function_ref @_TF18pointer_conversion19takesPlusOnePointer
// CHECK: [[POINTER:%.*]] = address_to_pointer [[PB]]
// CHECK: [[CONVERT:%.*]] = function_ref @_TFs30_convertInOutToPointerArgument
// CHECK: apply [[CONVERT]]<UnsafeMutablePointer<C>>({{%.*}}, [[POINTER]])
// CHECK: apply [[TAKES_PLUS_ONE]]
takesPlusZeroPointer(&c)
// CHECK: [[TAKES_PLUS_ZERO:%.*]] = function_ref @_TF18pointer_conversion20takesPlusZeroPointerFGVs33AutoreleasingUnsafeMutablePointerCS_1C_T_
// CHECK: [[WRITEBACK:%.*]] = alloc_stack $@sil_unmanaged C
// CHECK: [[OWNED:%.*]] = load_borrow [[PB]]
// CHECK: [[UNOWNED:%.*]] = ref_to_unmanaged [[OWNED]]
// CHECK: store [[UNOWNED]] to [trivial] [[WRITEBACK]]
// CHECK: [[POINTER:%.*]] = address_to_pointer [[WRITEBACK]]
// CHECK: [[CONVERT:%.*]] = function_ref @_TFs30_convertInOutToPointerArgument
// CHECK: apply [[CONVERT]]<AutoreleasingUnsafeMutablePointer<C>>({{%.*}}, [[POINTER]])
// CHECK: apply [[TAKES_PLUS_ZERO]]
// CHECK: [[UNOWNED_OUT:%.*]] = load [trivial] [[WRITEBACK]]
// CHECK: [[OWNED_OUT:%.*]] = unmanaged_to_ref [[UNOWNED_OUT]]
// CHECK: [[OWNED_OUT_COPY:%.*]] = copy_value [[OWNED_OUT]]
// CHECK: assign [[OWNED_OUT_COPY]] to [[PB]]
var cq: C? = C()
takesPlusZeroOptionalPointer(&cq)
}
// Check that pointer types don't bridge anymore.
@objc class ObjCMethodBridging : NSObject {
// CHECK-LABEL: sil hidden [thunk] @_TToFC18pointer_conversion18ObjCMethodBridging11pointerArgs{{.*}} : $@convention(objc_method) (UnsafeMutablePointer<Int>, UnsafePointer<Int>, AutoreleasingUnsafeMutablePointer<ObjCMethodBridging>, ObjCMethodBridging)
@objc func pointerArgs(_ x: UnsafeMutablePointer<Int>,
y: UnsafePointer<Int>,
z: AutoreleasingUnsafeMutablePointer<ObjCMethodBridging>) {}
}
// rdar://problem/21505805
// CHECK-LABEL: sil hidden @_TF18pointer_conversion22functionInoutToPointerFT_T_
func functionInoutToPointer() {
// CHECK: [[BOX:%.*]] = alloc_box ${ var @callee_owned () -> () }
var f: () -> () = {}
// CHECK: [[REABSTRACT_BUF:%.*]] = alloc_stack $@callee_owned (@in ()) -> @out ()
// CHECK: address_to_pointer [[REABSTRACT_BUF]]
takesMutableVoidPointer(&f)
}
| 52.124464 | 254 | 0.721449 |
e931410acd94a55cc526833cc4e4617e407b240c | 2,156 | //
// AppDelegate.swift
// MustacheDemoiOS
//
// Created by Gwendal Roué on 10/03/2015.
// Copyright (c) 2015 Gwendal Roué. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| 45.87234 | 285 | 0.754638 |
d6b945333486751415dabae396930f965d9a531d | 12,255 | //
// ThemeViewController.swift
// zhihuDaily 2.0
//
// Created by Nirvana on 10/15/15.
// Copyright © 2015 NSNirvana. All rights reserved.
//
import UIKit
import Alamofire
import SwiftyJSON
import SDWebImage
class ThemeViewController: UIViewController {
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var navTitleLabel: UILabel!
@IBOutlet weak var topConstant: NSLayoutConstraint!
var id = ""
var name = ""
var firstDisplay = true
var dragging = false
var triggered = false
var navImageView: UIImageView!
var themeSubview: ParallaxHeaderView!
var animator: ZFModalTransitionAnimator!
var loadCircleView: PNCircleChart!
var loadingView: UIActivityIndicatorView!
override func viewDidLoad() {
super.viewDidLoad()
self.automaticallyAdjustsScrollViewInsets = false
//清空原数据
self.appCloud().themeContent = nil
//拿到新数据
refreshData(nil)
//创建leftBarButtonItem
let leftButton = UIBarButtonItem(image: UIImage(named: "leftArrow"), style: .Plain, target: self.revealViewController(), action: "revealToggle:")
leftButton.tintColor = UIColor.whiteColor()
self.navigationItem.setLeftBarButtonItem(leftButton, animated: false)
//为当前view添加手势识别
self.view.addGestureRecognizer(self.revealViewController().panGestureRecognizer())
self.view.addGestureRecognizer(self.revealViewController().tapGestureRecognizer())
//生成并配置HeaderImageView
navImageView = UIImageView(frame: CGRectMake(0, 0, self.view.frame.width, 64))
navImageView.contentMode = UIViewContentMode.ScaleAspectFill
navImageView.clipsToBounds = true
//将其添加到ParallaxView
themeSubview = ParallaxHeaderView.parallaxThemeHeaderViewWithSubView(navImageView, forSize: CGSizeMake(self.view.frame.width, 64), andImage: navImageView.image) as! ParallaxHeaderView
themeSubview.delegate = self
//将ParallaxView设置为tableHeaderView,主View添加tableView
self.tableView.tableHeaderView = themeSubview
self.view.addSubview(tableView)
//设置NavigationBar为透明
self.navigationController?.navigationBar.lt_setBackgroundColor(UIColor.clearColor())
self.navigationController?.navigationBar.shadowImage = UIImage()
//初始化下拉加载loadCircleView
let comp1 = self.navTitleLabel.frame.width/2
let comp2 = (self.navTitleLabel.text! as NSString).sizeWithAttributes(nil).width/2
let loadCircleViewXPosition = comp1 - comp2 - 35
loadCircleView = PNCircleChart(frame: CGRect(x: loadCircleViewXPosition, y: 3, width: 15, height: 15), total: 100, current: 0, clockwise: true, shadow: false, shadowColor: nil, displayCountingLabel: false, overrideLineWidth: 1)
loadCircleView.backgroundColor = UIColor.clearColor()
loadCircleView.strokeColor = UIColor.whiteColor()
loadCircleView.strokeChart()
loadCircleView.transform = CGAffineTransformMakeRotation(CGFloat(M_PI))
self.navTitleLabel.addSubview(loadCircleView)
//初始化下拉加载loadingView
loadingView = UIActivityIndicatorView(frame: CGRect(x: loadCircleViewXPosition+2.5, y: 5.5, width: 10, height: 10))
self.navTitleLabel.addSubview(loadingView)
//tableView基础设置
self.tableView.delegate = self
self.tableView.dataSource = self
self.tableView.separatorStyle = .None
self.tableView.showsVerticalScrollIndicator = false
}
override func viewDidAppear(animated: Bool) {
self.tableView.reloadData()
if !firstDisplay {
self.topConstant.constant = -44
} else {
self.topConstant.constant = -64
firstDisplay = false
}
}
func refreshData(completionHandler: (()->())?) {
//更改标题
navTitleLabel.text = name
//获取数据
Alamofire.request(.GET, "http://news-at.zhihu.com/api/4/theme/" + id).responseJSON { (_, _, dataResult) -> Void in
guard dataResult.error == nil else {
print("数据获取失败")
return
}
let data = JSON(dataResult.value!)
//取得Story
let storyData = data["stories"]
//暂时注入themeStory
var themeStory: [ContentStoryModel] = []
for i in 0 ..< storyData.count {
//判断是否含图
if storyData[i]["images"] != nil {
themeStory.append(ContentStoryModel(images: [storyData[i]["images"][0].string!], id: String(storyData[i]["id"]), title: storyData[i]["title"].string!))
} else {
//若不含图
themeStory.append(ContentStoryModel(images: [""], id: String(storyData[i]["id"]), title: storyData[i]["title"].string!))
}
}
//取得avatars
let avatarsData = data["editors"]
//暂时注入editorsAvatars
var editorsAvatars: [String] = []
for i in 0 ..< avatarsData.count {
editorsAvatars.append(avatarsData[i]["avatar"].string!)
}
//更新图片
self.navImageView.sd_setImageWithURL(NSURL(string: data["background"].string!), completed: { (image, _, _, _) -> Void in
self.themeSubview.blurViewImage = image
self.themeSubview.refreshBlurViewForNewImage()
})
//注入themeContent
self.appCloud().themeContent = ThemeContentModel(stories: themeStory, background: data["background"].string!, editorsAvatars: editorsAvatars)
//刷新数据
self.tableView.reloadData()
if let completionHandler = completionHandler {
completionHandler()
}
}
}
//设置StatusBar颜色
override func preferredStatusBarStyle() -> UIStatusBarStyle {
return .LightContent
}
//获取总代理
func appCloud() -> AppDelegate {
return UIApplication.sharedApplication().delegate as! AppDelegate
}
}
extension ThemeViewController: UITableViewDelegate, UITableViewDataSource, ParallaxHeaderViewDelegate {
//实现Parallax效果
func scrollViewDidScroll(scrollView: UIScrollView) {
let header = self.tableView.tableHeaderView as! ParallaxHeaderView
header.layoutThemeHeaderViewForScrollViewOffset(scrollView.contentOffset)
let offsetY = scrollView.contentOffset.y
if offsetY <= 0 {
let ratio = -offsetY*2
if ratio <= 100 {
if triggered == false && loadCircleView.hidden == true {
loadCircleView.hidden = false
}
loadCircleView.updateChartByCurrent(ratio)
} else {
if loadCircleView.current != 100 {
loadCircleView.updateChartByCurrent(100)
}
//第一次检测到松手
if !dragging && !triggered {
loadCircleView.hidden = true
loadingView.startAnimating()
refreshData({ () -> () in
self.loadingView.stopAnimating()
})
triggered = true
}
}
if triggered == true && offsetY == 0 {
triggered = false
}
} else {
if loadCircleView.hidden != true {
loadCircleView.hidden = true
}
}
}
func scrollViewDidEndDragging(scrollView: UIScrollView, willDecelerate decelerate: Bool) {
dragging = false
}
func scrollViewWillBeginDragging(scrollView: UIScrollView) {
dragging = true
}
//设置滑动极限
func lockDirection() {
self.tableView.contentOffset.y = -95
}
//处理UITableViewDataSource
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
//如果还未获取到数据
if appCloud().themeContent == nil {
return 0
}
//如含有数据
return appCloud().themeContent!.stories.count + 1
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
//取得已读新闻数组以供配置
let readNewsIdArray = NSUserDefaults.standardUserDefaults().objectForKey(Keys.readNewsId) as! [String]
if indexPath.row == 0 {
let cell = tableView.dequeueReusableCellWithIdentifier("themeEditorTableViewCell") as! ThemeEditorTableViewCell
for (index, editorsAvatar) in appCloud().themeContent!.editorsAvatars.enumerate() {
let avatar = UIImageView(frame: CGRectMake(62 + CGFloat(37 * index), 12.5, 20, 20))
avatar.contentMode = .ScaleAspectFill
avatar.layer.cornerRadius = 10
avatar.clipsToBounds = true
avatar.sd_setImageWithURL(NSURL(string: editorsAvatar))
cell.contentView.addSubview(avatar)
}
return cell
}
//取到Story数据
let tempContentStoryItem = appCloud().themeContent!.stories[indexPath.row - 1]
//保证图片一定存在,选择合适的Cell类型
guard tempContentStoryItem.images[0] != "" else {
let cell = tableView.dequeueReusableCellWithIdentifier("themeTextTableViewCell") as! ThemeTextTableViewCell
//验证是否已被点击过
if let _ = readNewsIdArray.indexOf(tempContentStoryItem.id) {
cell.themeTextLabel.textColor = UIColor.lightGrayColor()
} else {
cell.themeTextLabel.textColor = UIColor.blackColor()
}
cell.themeTextLabel.text = tempContentStoryItem.title
return cell
}
//处理图片存在的情况
let cell = tableView.dequeueReusableCellWithIdentifier("themeContentTableViewCell") as! ThemeContentTableViewCell
//验证是否已被点击过
if let _ = readNewsIdArray.indexOf(tempContentStoryItem.id) {
cell.themeContentLabel.textColor = UIColor.lightGrayColor()
} else {
cell.themeContentLabel.textColor = UIColor.blackColor()
}
cell.themeContentLabel.text = tempContentStoryItem.title
cell.themeContentImageView.sd_setImageWithURL(NSURL(string: tempContentStoryItem.images[0]))
return cell
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
if indexPath.row == 0 {
return 45
}
return 92
}
//处理UITableViewDelegate
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
if indexPath.row == 0 {
return
}
//拿到webViewController
let webViewController = self.storyboard?.instantiateViewControllerWithIdentifier("webViewController") as! WebViewController
webViewController.newsId = appCloud().themeContent!.stories[self.tableView.indexPathForSelectedRow!.row - 1].id
webViewController.index = indexPath.row - 1
webViewController.isThemeStory = true
//取得已读新闻数组以供修改
var readNewsIdArray = NSUserDefaults.standardUserDefaults().objectForKey(Keys.readNewsId) as! [String]
//记录已被选中的id
readNewsIdArray.append(webViewController.newsId)
NSUserDefaults.standardUserDefaults().setObject(readNewsIdArray, forKey: Keys.readNewsId)
//对animator进行初始化
animator = ZFModalTransitionAnimator(modalViewController: webViewController)
self.animator.dragable = true
self.animator.bounces = false
self.animator.behindViewAlpha = 0.7
self.animator.behindViewScale = 0.9
self.animator.transitionDuration = 0.7
self.animator.direction = ZFModalTransitonDirection.Right
//设置webViewController
webViewController.transitioningDelegate = self.animator
//实施转场
self.presentViewController(webViewController, animated: true) { () -> Void in
}
}
}
| 38.904762 | 235 | 0.620645 |
1a1583a12c240a64481fa049e875ac8dbe946a65 | 1,048 | //
// ServerNetwork.swift
// PIALibrary
//
// Created by Jose Antonio Blaya Garcia on 06/05/2020.
// Copyright © 2020 Private Internet Access, Inc.
//
// This file is part of the Private Internet Access iOS Client.
//
// The Private Internet Access iOS Client is free software: you can redistribute it and/or
// modify it under the terms of the GNU General Public License as published by the Free
// Software Foundation, either version 3 of the License, or (at your option) any later version.
//
// The Private Internet Access iOS Client is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
// or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
// details.
//
// You should have received a copy of the GNU General Public License along with the Private
// Internet Access iOS Client. If not, see <https://www.gnu.org/licenses/>.
//
import Foundation
public enum ServersNetwork: String {
case legacy
case gen4
}
| 36.137931 | 96 | 0.736641 |
724dd9b22636b18395e8a2494008bcd1772bfba5 | 930 | //
// CollectionViewCell.swift
// Clean
//
// Created by Artem Eremeev on 26/09/2019.
// Copyright © 2019 Artem Eremeev. All rights reserved.
//
import UIKit
import RxSwift
open class CollectionViewCell<ViewModel: ViewModelType>: UICollectionViewCell, CellType, ViewType {
public let disposeBag = DisposeBag()
public private(set) var reusableDisposeBag = DisposeBag()
public typealias ViewModel = ViewModel
open func bind(viewModel: ViewModel) {
viewModel.subscribeIfNeeded()
}
public func set(viewModel: ViewModelType) {
guard let viewModel = viewModel as? ViewModel else {
fatalError("Не удается преобразовать ViewModelType в \(String(describing: ViewModel.self))")
}
self.bind(viewModel: viewModel)
}
override public func prepareForReuse() {
super.prepareForReuse()
reusableDisposeBag = DisposeBag()
}
}
| 26.571429 | 104 | 0.680645 |
f86a574078a44dc8b4daf5185b9ab242c97a39ad | 2,707 | //
// TransformPIX.swift
// Pixels
//
// Created by Hexagons on 2018-08-28.
// Copyright © 2018 Hexagons. All rights reserved.
//
import CoreGraphics
public class TransformPIX: PIXSingleEffect, PIXofaKind {
let kind: PIX.Kind = .transform
override open var shader: String { return "effectSingleTransformPIX" }
// FIXME: shaderAspect
// MARK: - Public Properties
public var position: CGPoint = .zero { didSet { setNeedsRender() } }
public var rotation: CGFloat = 0.0 { didSet { setNeedsRender() } }
public var scale: CGFloat = 1.0 { didSet { setNeedsRender() } }
public var size: CGSize = CGSize(width: 1.0, height: 1.0) { didSet { setNeedsRender() } }
// MARK: - Property Helpers
enum CodingKeys: String, CodingKey {
case position; case rotation; case scale; case size
}
open override var uniforms: [CGFloat] {
return [position.x, position.y, rotation, scale, size.width, size.height]
}
// MARK: - JSON
required convenience init(from decoder: Decoder) throws {
self.init()
let container = try decoder.container(keyedBy: CodingKeys.self)
position = try container.decode(CGPoint.self, forKey: .position)
rotation = try container.decode(CGFloat.self, forKey: .rotation)
scale = try container.decode(CGFloat.self, forKey: .scale)
size = try container.decode(CGSize.self, forKey: .size)
setNeedsRender()
}
public override func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(position, forKey: .position)
try container.encode(rotation, forKey: .rotation)
try container.encode(scale, forKey: .scale)
try container.encode(size, forKey: .size)
}
}
public extension PIXOut {
func _move(by position: CGPoint) -> TransformPIX {
let transformPix = TransformPIX()
transformPix.name = "position:transform"
transformPix.inPix = self as? PIX & PIXOut
transformPix.position = position
return transformPix
}
func _rotatate(by rotation: CGFloat) -> TransformPIX {
let transformPix = TransformPIX()
transformPix.name = "rotatate:transform"
transformPix.inPix = self as? PIX & PIXOut
transformPix.rotation = rotation
return transformPix
}
func _scale(by scale: CGFloat) -> TransformPIX {
let transformPix = TransformPIX()
transformPix.name = "scale:transform"
transformPix.inPix = self as? PIX & PIXOut
transformPix.scale = scale
return transformPix
}
}
| 32.614458 | 93 | 0.644256 |
ab6b7ad18ff672481a87306313a998a601b49559 | 348 | //
// Object+Util.swift
// TwitterMock
//
// Created by Tracy Wu on 2019-04-02.
// Copyright © 2019 TW. All rights reserved.
//
import Foundation
import RealmSwift
extension Object {
func makeCopy() -> Self {
return type(of: self).init(value: self,
schema: .partialPrivateShared())
}
}
| 18.315789 | 67 | 0.58046 |
48c37a2b6d39a170878dd2c2521abb9468e205cb | 1,218 | // swift-tools-version:5.1
// The swift-tools-version declares the minimum version of Swift required to build this package.
import PackageDescription
let package = Package(
name: "FieldValidatorLibrary",
platforms: [
//.macOS(.v10_10),
//.tvOS(.v9),
//.watchOS(.v2),
.iOS(.v13)
],
products: [
// Products define the executables and libraries produced by a package, and make them visible to other packages.
.library(
name: "FieldValidatorLibrary",
targets: ["FieldValidatorLibrary"]),
],
//dependencies: [
// Dependencies declare other packages that this package depends on.
// .package(url: /* package url */, from: "1.0.0"),
//],
targets: [
// Targets are the basic building blocks of a package. A target can define a module or a test suite.
// Targets can depend on other targets in this package, and on products in packages which this package depends on.
.target(
name: "FieldValidatorLibrary",
dependencies: []),
.testTarget(
name: "FieldValidatorLibraryTests",
dependencies: ["FieldValidatorLibrary"]),
]
)
| 34.8 | 122 | 0.614943 |
5bdc224c0d91644bcf249b6f793416123682b4a8 | 144 | internal extension XRPCurrency {
init(currency: Org_Xrpl_Rpc_V1_Currency) {
self.name = currency.name
self.code = currency.code
}
}
| 20.571429 | 44 | 0.722222 |
09217ed8cf60bb9761a11516a03477d88145873b | 570 | //
// Address.swift
// SpreadsheetView
//
// Created by Kishikawa Katsumi on 3/16/17.
// Copyright © 2017 Kishikawa Katsumi. All rights reserved.
//
import Foundation
struct Address: Hashable {
let row: Int
let column: Int
let rowIndex: Int
let columnIndex: Int
public func hash(into hasher: inout Hasher) {
let value = 32768 * rowIndex + columnIndex
hasher.combine(value)
}
static func ==(lhs: Address, rhs: Address) -> Bool {
return lhs.rowIndex == rhs.rowIndex && lhs.columnIndex == rhs.columnIndex
}
}
| 21.923077 | 81 | 0.647368 |
22d77378fd5f18dc1ff2f11a2b435d12dbed5be8 | 793 | //
// MainProtocols.swift
// RememberPoint
//
// Created by Pavel Chehov on 03/01/2019.
// Copyright © 2019 Pavel Chehov. All rights reserved.
//
import UIKit
protocol AlertProtocol {
func showAlert(title: String?, message: String?, okText: String?)
func showConfirmAlert(
title: String?,
message: String?,
confirmStyle: UIAlertAction.Style?,
cancelStyle: UIAlertAction.Style?,
confirmText: String?,
confirmCallback: ((UIAlertAction) -> Void)?,
cancelText: String?,
cancelCallback: ((UIAlertAction) -> Void)?
)
func showActionSheet(title: String?, text: String?, actions: [UIAlertAction])
}
protocol LoadableViewProtocol {
var isLoaded: Bool { get }
var loadedCallback: (() -> Void)? { get set }
}
| 26.433333 | 81 | 0.649433 |
14610cb03cd2133da77bf0cf32fd6a7618c429a7 | 4,154 | //
// MLCardFormApiRouter.swift
// CardForm
//
// Created by Juan sebastian Sanzone on 10/30/19.
// Copyright © 2019 JS. All rights reserved.
//
import Foundation
enum MLCardFormApiRouter {
case getCardData(MLCardFormBinService.QueryParams, MLCardFormBinService.Headers)
case postCardTokenData(MLCardFormAddCardService.KeyParam, MLCardFormAddCardService.Headers, MLCardFormTokenizationBody)
case postCardData(MLCardFormAddCardService.AddCardParams, MLCardFormAddCardService.Headers, MLCardFormAddCardBody)
var scheme: String {
return "https"
}
var host: String {
switch self {
case .getCardData, .postCardTokenData, .postCardData:
return "api.mercadopago.com"
}
}
var path: String {
switch self {
case .getCardData:
return "/production/px_mobile/v1/card"
case .postCardTokenData:
return "/v1/card_tokens"
case .postCardData:
return "/production/px_mobile/v1/card"
}
}
var headers: [String : String]? {
switch self {
case .getCardData(_ , let headers):
return [MLCardFormBinService.HeadersKeys.userAgent.getKey: headers.userAgent,
MLCardFormBinService.HeadersKeys.xDensity.getKey: headers.xDensity,
MLCardFormBinService.HeadersKeys.acceptLanguage.getKey: headers.acceptLanguage,
MLCardFormBinService.HeadersKeys.xProductId.getKey: headers.xProductId]
case .postCardTokenData(_, let headers, _), .postCardData(_, let headers, _):
return [MLCardFormAddCardService.HeadersKeys.contentType.getKey: headers.contentType]
}
}
var parameters: [URLQueryItem] {
switch self {
case .getCardData(let queryParams, _):
var urlQueryItems = [
URLQueryItem(name: MLCardFormBinService.QueryKeys.bin.getKey, value: queryParams.bin),
URLQueryItem(name: MLCardFormBinService.QueryKeys.siteId.getKey, value: queryParams.siteId),
URLQueryItem(name: MLCardFormBinService.QueryKeys.platform.getKey, value: queryParams.platform),
URLQueryItem(name: MLCardFormBinService.QueryKeys.odr.getKey, value: String(queryParams.odr))
]
if let excludedPaymentTypes = queryParams.excludedPaymentTypes {
urlQueryItems.append(URLQueryItem(name: MLCardFormBinService.QueryKeys.excludedPaymentTypes.getKey, value: excludedPaymentTypes))
}
return urlQueryItems
case.postCardTokenData(let queryParams, _, _):
var urlQueryItems:[URLQueryItem] = []
if let accessToken = queryParams.accessToken {
urlQueryItems.append(URLQueryItem(name: MLCardFormAddCardService.QueryKeys.accessToken.getKey, value: accessToken))
} else if let publicKey = queryParams.publicKey {
urlQueryItems.append(URLQueryItem(name: MLCardFormAddCardService.QueryKeys.publicKey.getKey, value: publicKey))
}
return urlQueryItems
case .postCardData(let queryParams, _, _):
let urlQueryItems = [
URLQueryItem(name: MLCardFormAddCardService.QueryKeys.accessToken.getKey, value: queryParams.accessToken),
]
return urlQueryItems
}
}
var method: String {
switch self {
case .getCardData:
return "GET"
case .postCardTokenData,
.postCardData:
return "POST"
}
}
var body: Data? {
switch self {
case .postCardTokenData(_, _, let tokenizationBody):
return encode(tokenizationBody)
case .postCardData(_, _, let addCardBody):
return encode(addCardBody)
default:
return nil
}
}
}
// MARK: Encoding
private extension MLCardFormApiRouter {
func encode<T: Codable>(_ body: T) -> Data? {
let encoder = JSONEncoder()
encoder.keyEncodingStrategy = .convertToSnakeCase
let body = try? encoder.encode(body)
return body
}
}
| 37.423423 | 145 | 0.647328 |
03824fb403d579694eeed4ee3d4c6a7e9711f11e | 3,908 | // Copyright 2020 Google LLC
//
// 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 Firebase
class AnalyticsViewController: UIViewController {
private lazy var analyticsView = AnalyticsView(frame: view.frame)
override func viewDidLoad() {
super.viewDidLoad()
configureNavigationBar()
view.addSubview(analyticsView)
configureControls()
}
// MARK: - Firebase 🔥
// MARK: Set User Properties
@objc
private func seasonDidChange(_ control: UISegmentedControl) {
let season = control.titleForSegment(at: control.selectedSegmentIndex)!
analyticsView.seasonImageView.image = UIImage(named: season)
Analytics.setUserProperty(season, forName: "favorite_season") // 🔥
}
@objc
private func unitsDidChange(_ control: UISegmentedControl) {
let preferredUnits = control.titleForSegment(at: control.selectedSegmentIndex)!
Analytics.setUserProperty(preferredUnits, forName: "preferred_units") // 🔥
}
// MARK: Event Logging
@objc
private func preferredTemperatureFeelDidChange(_ control: UISegmentedControl) {
let temperatureFeelPreference = control.titleForSegment(at: control.selectedSegmentIndex)!
Analytics.logEvent("hot_or_cold_switch", parameters: ["value": temperatureFeelPreference]) // 🔥
}
@objc
private func preferredConditionsDidChange(_ control: UISegmentedControl) {
let conditionsPreference = control.titleForSegment(at: control.selectedSegmentIndex)!
Analytics.logEvent("rainy_or_sunny_switch", parameters: ["value": conditionsPreference]) // 🔥
}
@objc
private func sliderDidChange(_ control: UISlider) {
let value = Int(control.value)
analyticsView.sliderTemperatureLabel.text = "\(value)°"
Analytics.logEvent("preferred_temperature_changed", parameters: ["preference": value]) // 🔥
}
@objc
private func buttonTapped() {
Analytics.logEvent("blog_button_tapped", parameters: nil) // 🔥
let navController = UINavigationController(rootViewController: BlogViewController())
navigationController?.present(navController, animated: true)
}
// MARK: - Private Helpers
private func configureControls() {
analyticsView.seasonPicker.addTarget(
self,
action: #selector(seasonDidChange(_:)),
for: .valueChanged
)
analyticsView.preferredUnitsPicker.addTarget(
self,
action: #selector(unitsDidChange(_:)),
for: .valueChanged
)
analyticsView.temperatureSlider.addTarget(
self,
action: #selector(sliderDidChange(_:)),
for: .valueChanged
)
analyticsView.preferredTemperatureFeelPicker.addTarget(
self,
action: #selector(preferredTemperatureFeelDidChange(_:)),
for: .valueChanged
)
analyticsView.preferredConditionsPicker.addTarget(
self,
action: #selector(preferredConditionsDidChange(_:)),
for: .valueChanged
)
analyticsView.postButton.addTarget(
self,
action: #selector(buttonTapped),
for: .touchUpInside
)
}
private func configureNavigationBar() {
navigationItem.title = "Firebase Analytics"
guard let navigationBar = navigationController?.navigationBar else { return }
navigationBar.prefersLargeTitles = true
navigationBar.titleTextAttributes = [.foregroundColor: UIColor.systemOrange]
navigationBar.largeTitleTextAttributes = [.foregroundColor: UIColor.systemOrange]
}
}
| 32.297521 | 99 | 0.732856 |
72c7b04e81da37850df8b892b2f1d06e339f28b9 | 1,450 | //
// ViewControllerExtension.swift
// Calendar to Calendar
//
// Created by Jack Rosen on 7/16/18.
// Copyright © 2018 Jack Rosen. All rights reserved.
//
import Foundation
import UIKit
import StoreKit
extension UIViewController{
// Helper for showing an alert
func showAlert(title : String, message: String = "", closure: ((UIAlertAction) -> ())? = nil) {
DispatchQueue.main.async(execute: {
let alert = UIAlertController(
title: title,
message: message,
preferredStyle: UIAlertController.Style.alert
)
let ok = UIAlertAction(
title: "OK",
style: UIAlertAction.Style.default,
handler: closure
)
alert.addAction(ok)
self.present(alert, animated: true, completion: nil)
})
}
//Ends the view from editing
@objc func dismissKeyboard() {
view.endEditing(true)
}
//Creates a tap gesture to dismiss the keyboard
func createDismissedKeyboard(){
let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(dismissKeyboard))
tap.cancelsTouchesInView = false
self.view.addGestureRecognizer(tap)
}
//Makes date pickers have the minimum date as today
func setUpDatePickers(_ pickers: UIDatePicker...){
pickers.forEach({$0.minimumDate = Date()})
}
}
| 30.851064 | 114 | 0.614483 |
87944f55f3f0620097f3f8c2e253ccadcdc25334 | 27,860 | //
// PieRadarChartViewBase.swift
// Charts
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/Charts
//
import Foundation
import CoreGraphics
#if !os(OSX)
import UIKit
#endif
/// Base class of PieChartView and RadarChartView.
open class PieRadarChartViewBase: ChartViewBase
{
/// holds the normalized version of the current rotation angle of the chart
fileprivate var _rotationAngle = CGFloat(270.0)
/// holds the raw version of the current rotation angle of the chart
fileprivate var _rawRotationAngle = CGFloat(270.0)
/// flag that indicates if rotation is enabled or not
@objc open var rotationEnabled = true
/// Sets the minimum offset (padding) around the chart, defaults to 0.0
@objc open var minOffset = CGFloat(0.0)
/// iOS && OSX only: Enabled multi-touch rotation using two fingers.
fileprivate var _rotationWithTwoFingers = false
fileprivate var _tapGestureRecognizer: NSUITapGestureRecognizer!
#if !os(tvOS)
fileprivate var _rotationGestureRecognizer: NSUIRotationGestureRecognizer!
#endif
public override init(frame: CGRect)
{
super.init(frame: frame)
}
public required init?(coder aDecoder: NSCoder)
{
super.init(coder: aDecoder)
}
deinit
{
stopDeceleration()
}
internal override func initialize()
{
super.initialize()
_tapGestureRecognizer = NSUITapGestureRecognizer(target: self, action: #selector(tapGestureRecognized(_:)))
self.addGestureRecognizer(_tapGestureRecognizer)
#if !os(tvOS)
_rotationGestureRecognizer = NSUIRotationGestureRecognizer(target: self, action: #selector(rotationGestureRecognized(_:)))
self.addGestureRecognizer(_rotationGestureRecognizer)
_rotationGestureRecognizer.isEnabled = rotationWithTwoFingers
#endif
}
internal override func calcMinMax()
{
/*_xAxis.axisRange = Double((_data?.xVals.count ?? 0) - 1)*/
}
open override var maxVisibleCount: Int
{
get
{
return data?.entryCount ?? 0
}
}
open override func notifyDataSetChanged()
{
calcMinMax()
if let data = _data , _legend !== nil
{
_legendRenderer.computeLegend(data: data)
}
calculateOffsets()
setNeedsDisplay()
}
internal override func calculateOffsets()
{
var legendLeft = CGFloat(0.0)
var legendRight = CGFloat(0.0)
var legendBottom = CGFloat(0.0)
var legendTop = CGFloat(0.0)
if _legend != nil && _legend.enabled && !_legend.drawInside
{
let fullLegendWidth = min(_legend.neededWidth, _viewPortHandler.chartWidth * _legend.maxSizePercent)
switch _legend.orientation
{
case .vertical:
var xLegendOffset: CGFloat = 0.0
if _legend.horizontalAlignment == .left
|| _legend.horizontalAlignment == .right
{
if _legend.verticalAlignment == .center
{
// this is the space between the legend and the chart
let spacing = CGFloat(13.0)
xLegendOffset = fullLegendWidth + spacing
}
else
{
// this is the space between the legend and the chart
let spacing = CGFloat(8.0)
let legendWidth = fullLegendWidth + spacing
let legendHeight = _legend.neededHeight + _legend.textHeightMax
let c = self.midPoint
let bottomX = _legend.horizontalAlignment == .right
? self.bounds.width - legendWidth + 15.0
: legendWidth - 15.0
let bottomY = legendHeight + 15
let distLegend = distanceToCenter(x: bottomX, y: bottomY)
let reference = getPosition(center: c, dist: self.radius,
angle: angleForPoint(x: bottomX, y: bottomY))
let distReference = distanceToCenter(x: reference.x, y: reference.y)
let minOffset = CGFloat(5.0)
if bottomY >= c.y
&& self.bounds.height - legendWidth > self.bounds.width
{
xLegendOffset = legendWidth
}
else if distLegend < distReference
{
let diff = distReference - distLegend
xLegendOffset = minOffset + diff
}
}
}
switch _legend.horizontalAlignment
{
case .left:
legendLeft = xLegendOffset
case .right:
legendRight = xLegendOffset
case .center:
switch _legend.verticalAlignment
{
case .top:
legendTop = min(_legend.neededHeight, _viewPortHandler.chartHeight * _legend.maxSizePercent)
case .bottom:
legendBottom = min(_legend.neededHeight, _viewPortHandler.chartHeight * _legend.maxSizePercent)
default:
break
}
}
case .horizontal:
var yLegendOffset: CGFloat = 0.0
if _legend.verticalAlignment == .top
|| _legend.verticalAlignment == .bottom
{
// It's possible that we do not need this offset anymore as it
// is available through the extraOffsets, but changing it can mean
// changing default visibility for existing apps.
let yOffset = self.requiredLegendOffset
yLegendOffset = min(
_legend.neededHeight + yOffset,
_viewPortHandler.chartHeight * _legend.maxSizePercent)
}
switch _legend.verticalAlignment
{
case .top:
legendTop = yLegendOffset
case .bottom:
legendBottom = yLegendOffset
default:
break
}
}
legendLeft += self.requiredBaseOffset
legendRight += self.requiredBaseOffset
legendTop += self.requiredBaseOffset
legendBottom += self.requiredBaseOffset
}
legendTop += self.extraTopOffset
legendRight += self.extraRightOffset
legendBottom += self.extraBottomOffset
legendLeft += self.extraLeftOffset
var minOffset = self.minOffset
if (self.isKind(of: RadarChartView.self))
{
let x = self.xAxis
if x.isEnabled && x.drawLabelsEnabled
{
minOffset = max(minOffset, x.labelRotatedWidth)
}
}
let offsetLeft = max(minOffset, legendLeft)
let offsetTop = max(minOffset, legendTop)
let offsetRight = max(minOffset, legendRight)
let offsetBottom = max(minOffset, max(self.requiredBaseOffset, legendBottom))
_viewPortHandler.restrainViewPort(offsetLeft: offsetLeft, offsetTop: offsetTop, offsetRight: offsetRight, offsetBottom: offsetBottom)
}
/// - returns: The angle relative to the chart center for the given point on the chart in degrees.
/// The angle is always between 0 and 360°, 0° is NORTH, 90° is EAST, ...
@objc open func angleForPoint(x: CGFloat, y: CGFloat) -> CGFloat
{
let c = centerOffsets
let tx = Double(x - c.x)
let ty = Double(y - c.y)
let length = sqrt(tx * tx + ty * ty)
let r = acos(ty / length)
var angle = r * ChartUtils.Math.RAD2DEG
if x > c.x
{
angle = 360.0 - angle
}
// add 90° because chart starts EAST
angle = angle + 90.0
// neutralize overflow
if angle > 360.0
{
angle = angle - 360.0
}
return CGFloat(angle)
}
/// Calculates the position around a center point, depending on the distance
/// from the center, and the angle of the position around the center.
@objc open func getPosition(center: CGPoint, dist: CGFloat, angle: CGFloat) -> CGPoint
{
return CGPoint(x: center.x + dist * cos(angle * ChartUtils.Math.FDEG2RAD),
y: center.y + dist * sin(angle * ChartUtils.Math.FDEG2RAD))
}
/// - returns: The distance of a certain point on the chart to the center of the chart.
@objc open func distanceToCenter(x: CGFloat, y: CGFloat) -> CGFloat
{
let c = self.centerOffsets
var dist = CGFloat(0.0)
var xDist = CGFloat(0.0)
var yDist = CGFloat(0.0)
if x > c.x
{
xDist = x - c.x
}
else
{
xDist = c.x - x
}
if y > c.y
{
yDist = y - c.y
}
else
{
yDist = c.y - y
}
// pythagoras
dist = sqrt(pow(xDist, 2.0) + pow(yDist, 2.0))
return dist
}
/// - returns: The xIndex for the given angle around the center of the chart.
/// -1 if not found / outofbounds.
@objc open func indexForAngle(_ angle: CGFloat) -> Int
{
fatalError("indexForAngle() cannot be called on PieRadarChartViewBase")
}
/// current rotation angle of the pie chart
///
/// **default**: 270 --> top (NORTH)
/// - returns: Will always return a normalized value, which will be between 0.0 < 360.0
@objc open var rotationAngle: CGFloat
{
get
{
return _rotationAngle
}
set
{
_rawRotationAngle = newValue
_rotationAngle = ChartUtils.normalizedAngleFromAngle(newValue)
setNeedsDisplay()
}
}
/// gets the raw version of the current rotation angle of the pie chart the returned value could be any value, negative or positive, outside of the 360 degrees.
/// this is used when working with rotation direction, mainly by gestures and animations.
@objc open var rawRotationAngle: CGFloat
{
return _rawRotationAngle
}
/// - returns: The diameter of the pie- or radar-chart
@objc open var diameter: CGFloat
{
var content = _viewPortHandler.contentRect
content.origin.x += extraLeftOffset
content.origin.y += extraTopOffset
content.size.width -= extraLeftOffset + extraRightOffset
content.size.height -= extraTopOffset + extraBottomOffset
return min(content.width, content.height)
}
/// - returns: The radius of the chart in pixels.
@objc open var radius: CGFloat
{
fatalError("radius cannot be called on PieRadarChartViewBase")
}
/// - returns: The required offset for the chart legend.
@objc internal var requiredLegendOffset: CGFloat
{
fatalError("requiredLegendOffset cannot be called on PieRadarChartViewBase")
}
/// - returns: The base offset needed for the chart without calculating the
/// legend size.
@objc internal var requiredBaseOffset: CGFloat
{
fatalError("requiredBaseOffset cannot be called on PieRadarChartViewBase")
}
open override var chartYMax: Double
{
return 0.0
}
open override var chartYMin: Double
{
return 0.0
}
@objc open var isRotationEnabled: Bool { return rotationEnabled }
/// flag that indicates if rotation is done with two fingers or one.
/// when the chart is inside a scrollview, you need a two-finger rotation because a one-finger rotation eats up all touch events.
///
/// On iOS this will disable one-finger rotation.
/// On OSX this will keep two-finger multitouch rotation, and one-pointer mouse rotation.
///
/// **default**: false
@objc open var rotationWithTwoFingers: Bool
{
get
{
return _rotationWithTwoFingers
}
set
{
_rotationWithTwoFingers = newValue
#if !os(tvOS)
_rotationGestureRecognizer.isEnabled = _rotationWithTwoFingers
#endif
}
}
/// flag that indicates if rotation is done with two fingers or one.
/// when the chart is inside a scrollview, you need a two-finger rotation because a one-finger rotation eats up all touch events.
///
/// On iOS this will disable one-finger rotation.
/// On OSX this will keep two-finger multitouch rotation, and one-pointer mouse rotation.
///
/// **default**: false
@objc open var isRotationWithTwoFingers: Bool
{
return _rotationWithTwoFingers
}
// MARK: - Animation
fileprivate var _spinAnimator: Animator!
/// Applys a spin animation to the Chart.
@objc open func spin(duration: TimeInterval, fromAngle: CGFloat, toAngle: CGFloat, easing: ChartEasingFunctionBlock?)
{
if _spinAnimator != nil
{
_spinAnimator.stop()
}
_spinAnimator = Animator()
_spinAnimator.updateBlock = {
self.rotationAngle = (toAngle - fromAngle) * CGFloat(self._spinAnimator.phaseX) + fromAngle
}
_spinAnimator.stopBlock = { self._spinAnimator = nil }
_spinAnimator.animate(xAxisDuration: duration, easing: easing)
}
@objc open func spin(duration: TimeInterval, fromAngle: CGFloat, toAngle: CGFloat, easingOption: ChartEasingOption)
{
spin(duration: duration, fromAngle: fromAngle, toAngle: toAngle, easing: easingFunctionFromOption(easingOption))
}
@objc open func spin(duration: TimeInterval, fromAngle: CGFloat, toAngle: CGFloat)
{
spin(duration: duration, fromAngle: fromAngle, toAngle: toAngle, easing: nil)
}
@objc open func stopSpinAnimation()
{
if _spinAnimator != nil
{
_spinAnimator.stop()
}
}
// MARK: - Gestures
fileprivate var _rotationGestureStartPoint: CGPoint!
fileprivate var _isRotating = false
fileprivate var _startAngle = CGFloat(0.0)
fileprivate struct AngularVelocitySample
{
var time: TimeInterval
var angle: CGFloat
}
fileprivate var _velocitySamples = [AngularVelocitySample]()
fileprivate var _decelerationLastTime: TimeInterval = 0.0
fileprivate var _decelerationDisplayLink: NSUIDisplayLink!
fileprivate var _decelerationAngularVelocity: CGFloat = 0.0
@objc internal final func processRotationGestureBegan(location: CGPoint)
{
self.resetVelocity()
if rotationEnabled
{
self.sampleVelocity(touchLocation: location)
}
self.setGestureStartAngle(x: location.x, y: location.y)
_rotationGestureStartPoint = location
}
@objc internal final func processRotationGestureMoved(location: CGPoint)
{
if isDragDecelerationEnabled
{
sampleVelocity(touchLocation: location)
}
if !_isRotating &&
distance(
eventX: location.x,
startX: _rotationGestureStartPoint.x,
eventY: location.y,
startY: _rotationGestureStartPoint.y) > CGFloat(8.0)
{
_isRotating = true
}
else
{
self.updateGestureRotation(x: location.x, y: location.y)
setNeedsDisplay()
}
}
@objc internal final func processRotationGestureEnded(location: CGPoint)
{
if isDragDecelerationEnabled
{
stopDeceleration()
sampleVelocity(touchLocation: location)
_decelerationAngularVelocity = calculateVelocity()
if _decelerationAngularVelocity != 0.0
{
_decelerationLastTime = CACurrentMediaTime()
_decelerationDisplayLink = NSUIDisplayLink(target: self, selector: #selector(PieRadarChartViewBase.decelerationLoop))
_decelerationDisplayLink.add(to: RunLoop.main, forMode: RunLoopMode.commonModes)
}
}
}
@objc internal final func processRotationGestureCancelled()
{
if _isRotating
{
_isRotating = false
}
}
#if !os(OSX)
open override func nsuiTouchesBegan(_ touches: Set<NSUITouch>, withEvent event: NSUIEvent?)
{
// if rotation by touch is enabled
if rotationEnabled
{
stopDeceleration()
if !rotationWithTwoFingers
{
let touch = touches.first as NSUITouch!
let touchLocation = touch?.location(in: self)
processRotationGestureBegan(location: touchLocation!)
}
}
if !_isRotating
{
super.nsuiTouchesBegan(touches, withEvent: event)
}
}
open override func nsuiTouchesMoved(_ touches: Set<NSUITouch>, withEvent event: NSUIEvent?)
{
if rotationEnabled && !rotationWithTwoFingers
{
let touch = touches.first as NSUITouch!
let touchLocation = touch?.location(in: self)
processRotationGestureMoved(location: touchLocation!)
}
if !_isRotating
{
super.nsuiTouchesMoved(touches, withEvent: event)
}
}
open override func nsuiTouchesEnded(_ touches: Set<NSUITouch>, withEvent event: NSUIEvent?)
{
if !_isRotating
{
super.nsuiTouchesEnded(touches, withEvent: event)
}
if rotationEnabled && !rotationWithTwoFingers
{
let touch = touches.first as NSUITouch!
let touchLocation = touch?.location(in: self)
processRotationGestureEnded(location: touchLocation!)
}
if _isRotating
{
_isRotating = false
}
}
open override func nsuiTouchesCancelled(_ touches: Set<NSUITouch>?, withEvent event: NSUIEvent?)
{
super.nsuiTouchesCancelled(touches, withEvent: event)
processRotationGestureCancelled()
}
#endif
#if os(OSX)
open override func mouseDown(with theEvent: NSEvent)
{
// if rotation by touch is enabled
if rotationEnabled
{
stopDeceleration()
let location = self.convert(theEvent.locationInWindow, from: nil)
processRotationGestureBegan(location: location)
}
if !_isRotating
{
super.mouseDown(with: theEvent)
}
}
open override func mouseDragged(with theEvent: NSEvent)
{
if rotationEnabled
{
let location = self.convert(theEvent.locationInWindow, from: nil)
processRotationGestureMoved(location: location)
}
if !_isRotating
{
super.mouseDragged(with: theEvent)
}
}
open override func mouseUp(with theEvent: NSEvent)
{
if !_isRotating
{
super.mouseUp(with: theEvent)
}
if rotationEnabled
{
let location = self.convert(theEvent.locationInWindow, from: nil)
processRotationGestureEnded(location: location)
}
if _isRotating
{
_isRotating = false
}
}
#endif
fileprivate func resetVelocity()
{
_velocitySamples.removeAll(keepingCapacity: false)
}
fileprivate func sampleVelocity(touchLocation: CGPoint)
{
let currentTime = CACurrentMediaTime()
_velocitySamples.append(AngularVelocitySample(time: currentTime, angle: angleForPoint(x: touchLocation.x, y: touchLocation.y)))
// Remove samples older than our sample time - 1 seconds
var i = 0, count = _velocitySamples.count
while (i < count - 2)
{
if currentTime - _velocitySamples[i].time > 1.0
{
_velocitySamples.remove(at: 0)
i -= 1
count -= 1
}
else
{
break
}
i += 1
}
}
fileprivate func calculateVelocity() -> CGFloat
{
if _velocitySamples.isEmpty
{
return 0.0
}
var firstSample = _velocitySamples[0]
var lastSample = _velocitySamples[_velocitySamples.count - 1]
// Look for a sample that's closest to the latest sample, but not the same, so we can deduce the direction
var beforeLastSample = firstSample
for i in stride(from: (_velocitySamples.count - 1), through: 0, by: -1)
{
beforeLastSample = _velocitySamples[i]
if beforeLastSample.angle != lastSample.angle
{
break
}
}
// Calculate the sampling time
var timeDelta = lastSample.time - firstSample.time
if timeDelta == 0.0
{
timeDelta = 0.1
}
// Calculate clockwise/ccw by choosing two values that should be closest to each other,
// so if the angles are two far from each other we know they are inverted "for sure"
var clockwise = lastSample.angle >= beforeLastSample.angle
if (abs(lastSample.angle - beforeLastSample.angle) > 270.0)
{
clockwise = !clockwise
}
// Now if the "gesture" is over a too big of an angle - then we know the angles are inverted, and we need to move them closer to each other from both sides of the 360.0 wrapping point
if lastSample.angle - firstSample.angle > 180.0
{
firstSample.angle += 360.0
}
else if firstSample.angle - lastSample.angle > 180.0
{
lastSample.angle += 360.0
}
// The velocity
var velocity = abs((lastSample.angle - firstSample.angle) / CGFloat(timeDelta))
// Direction?
if !clockwise
{
velocity = -velocity
}
return velocity
}
/// sets the starting angle of the rotation, this is only used by the touch listener, x and y is the touch position
fileprivate func setGestureStartAngle(x: CGFloat, y: CGFloat)
{
_startAngle = angleForPoint(x: x, y: y)
// take the current angle into consideration when starting a new drag
_startAngle -= _rotationAngle
}
/// updates the view rotation depending on the given touch position, also takes the starting angle into consideration
fileprivate func updateGestureRotation(x: CGFloat, y: CGFloat)
{
self.rotationAngle = angleForPoint(x: x, y: y) - _startAngle
}
@objc open func stopDeceleration()
{
if _decelerationDisplayLink !== nil
{
_decelerationDisplayLink.remove(from: RunLoop.main, forMode: RunLoopMode.commonModes)
_decelerationDisplayLink = nil
}
}
@objc fileprivate func decelerationLoop()
{
let currentTime = CACurrentMediaTime()
_decelerationAngularVelocity *= self.dragDecelerationFrictionCoef
let timeInterval = CGFloat(currentTime - _decelerationLastTime)
self.rotationAngle += _decelerationAngularVelocity * timeInterval
_decelerationLastTime = currentTime
if(abs(_decelerationAngularVelocity) < 0.001)
{
stopDeceleration()
}
}
/// - returns: The distance between two points
fileprivate func distance(eventX: CGFloat, startX: CGFloat, eventY: CGFloat, startY: CGFloat) -> CGFloat
{
let dx = eventX - startX
let dy = eventY - startY
return sqrt(dx * dx + dy * dy)
}
/// - returns: The distance between two points
fileprivate func distance(from: CGPoint, to: CGPoint) -> CGFloat
{
let dx = from.x - to.x
let dy = from.y - to.y
return sqrt(dx * dx + dy * dy)
}
/// reference to the last highlighted object
fileprivate var _lastHighlight: Highlight!
@objc fileprivate func tapGestureRecognized(_ recognizer: NSUITapGestureRecognizer)
{
if recognizer.state == NSUIGestureRecognizerState.ended
{
if !self.isHighLightPerTapEnabled { return }
let location = recognizer.location(in: self)
let high = self.getHighlightByTouchPoint(location)
self.highlightValue(high, callDelegate: true)
}
}
#if !os(tvOS)
@objc fileprivate func rotationGestureRecognized(_ recognizer: NSUIRotationGestureRecognizer)
{
if recognizer.state == NSUIGestureRecognizerState.began
{
stopDeceleration()
_startAngle = self.rawRotationAngle
}
if recognizer.state == NSUIGestureRecognizerState.began || recognizer.state == NSUIGestureRecognizerState.changed
{
let angle = ChartUtils.Math.FRAD2DEG * recognizer.nsuiRotation
self.rotationAngle = _startAngle + angle
setNeedsDisplay()
}
else if recognizer.state == NSUIGestureRecognizerState.ended
{
let angle = ChartUtils.Math.FRAD2DEG * recognizer.nsuiRotation
self.rotationAngle = _startAngle + angle
setNeedsDisplay()
if isDragDecelerationEnabled
{
stopDeceleration()
_decelerationAngularVelocity = ChartUtils.Math.FRAD2DEG * recognizer.velocity
if _decelerationAngularVelocity != 0.0
{
_decelerationLastTime = CACurrentMediaTime()
_decelerationDisplayLink = NSUIDisplayLink(target: self, selector: #selector(PieRadarChartViewBase.decelerationLoop))
_decelerationDisplayLink.add(to: RunLoop.main, forMode: RunLoopMode.commonModes)
}
}
}
}
#endif
}
| 31.767389 | 191 | 0.55944 |
d91b9f33c9da60dba19d4880af910d118490d238 | 3,127 | //
// ListInteractorTests.swift
// WhereIsMyApple
//
// Created by Raymond Law on 1/8/18.
// Copyright (c) 2018 Clean Swift LLC. All rights reserved.
//
// This file was generated by the Clean Swift Xcode Templates so
// you can apply clean architecture to your iOS and Mac projects,
// see http://clean-swift.com
//
@testable import WhereIsMyApple
import XCTest
import MapKit
class ListInteractorTests: XCTestCase
{
// MARK: Subject under test
var sut: ListInteractor!
// MARK: Test lifecycle
override func setUp()
{
super.setUp()
setupListInteractor()
}
override func tearDown()
{
super.tearDown()
}
// MARK: Test setup
func setupListInteractor()
{
sut = ListInteractor()
}
// MARK: Test doubles
class ListPresentationLogicSpy: ListPresentationLogic
{
var presentFetchStoresCalled = false
var presentLocateStoreCalled = false
var presentLocateStoreAltCalled = false
func presentFetchStores(response: List.FetchStores.Response)
{
presentFetchStoresCalled = true
}
func presentLocateStore(response: List.LocateStore.Response)
{
presentLocateStoreCalled = true
}
func presentLocateStoreAlt(response: List.LocateStore.Response)
{
presentLocateStoreAltCalled = true
}
}
class GeocoderSpy: CLGeocoder
{
var geocodeAddressStringCalled = false
let geocodeAddressStringExpectation = XCTestExpectation(description: "Wait for geocodeAddressString to invoke the completion handler")
override func geocodeAddressString(_ addressString: String, completionHandler: @escaping CLGeocodeCompletionHandler)
{
geocodeAddressStringCalled = true
let placemark = Seeds.placemark
completionHandler([placemark], nil)
geocodeAddressStringExpectation.fulfill()
}
}
// MARK: Tests
func testFetchStoresShouldAskPresenterToFormatStoresResult()
{
// Given
let spy = ListPresentationLogicSpy()
sut.presenter = spy
// When
let request = List.FetchStores.Request()
sut.fetchStores(request: request)
// Then
XCTAssertTrue(spy.presentFetchStoresCalled, "fetchStores(request:) should ask the presenter to format the stores result")
}
func testLocateStoreShouldAskPresenterToFormatLocatedStore()
{
// Given
let spy = ListPresentationLogicSpy()
sut.presenter = spy
let geocoderSpy = GeocoderSpy()
sut.geocoder = geocoderSpy
// When
let store = Seeds.Stores.tysonsCorner
let request = List.LocateStore.Request(name: store.name, address: store.address)
sut.locateStore(request: request)
wait(for: [geocoderSpy.geocodeAddressStringExpectation], timeout: 10.0)
// Then
switch sut.dependencyInjection {
case .method:
XCTAssertTrue(spy.presentLocateStoreAltCalled, "locateStore(request:) should ask the presenter to format the located store")
case .extractAndOverrideCall:
XCTAssertTrue(spy.presentLocateStoreCalled, "locateStore(request:) should ask the presenter to format the located store")
}
}
}
| 26.058333 | 138 | 0.710265 |
f521104a0e377b9ca580017b81bacfd33908781d | 2,443 | //
/**
* Copyright (c) 2019 Razeware LLC
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* Notwithstanding the foregoing, you may not use, copy, modify, merge, publish,
* distribute, sublicense, create a derivative work, and/or sell copies of the
* Software in any work that is designed, intended, or marketed for pedagogical or
* instructional purposes related to programming, coding, application development,
* or information technology. Permission for such use, copying, modification,
* merger, publication, distribution, sublicensing, creation of derivative works,
* or sale is expressly withheld.
*
* 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 ModelIO
extension MDLVertexDescriptor {
static var defaultVertexDescriptor: MDLVertexDescriptor = {
let vertexDescriptor = MDLVertexDescriptor()
var offset = 0
vertexDescriptor.attributes[0] = MDLVertexAttribute(name: MDLVertexAttributePosition,
format: .float3,
offset: 0, bufferIndex: 0)
offset += MemoryLayout<float3>.stride
// add the normal attribute here
vertexDescriptor.attributes[1] = MDLVertexAttribute(name: MDLVertexAttributeNormal, format: .float3, offset: offset, bufferIndex: 0)
offset += MemoryLayout<float3>.stride
vertexDescriptor.layouts[0] = MDLVertexBufferLayout(stride: offset)
return vertexDescriptor
}()
}
| 46.980769 | 136 | 0.728203 |
1649a1abf0c65563b28553fb9c28b38750511e9b | 919 | //
// PhotoCell.swift
// ToDoDemo
//
// Created by Mars on 21/05/2017.
// Copyright © 2017 Mars. All rights reserved.
//
import UIKit
import RxSwift
class PhotoCell: UICollectionViewCell {
@IBOutlet var imageView: UIImageView!
@IBOutlet weak var checkmark: UIImageView!
var representedAssetIdentifier: String!
var isCheckmarked: Bool = false
override func prepareForReuse() {
super.prepareForReuse()
imageView.image = nil
}
func flipCheckmark() {
self.isCheckmarked = !self.isCheckmarked
}
func selected() {
self.flipCheckmark()
setNeedsDisplay()
UIView.animate(withDuration: 0.1,
animations: { [weak self] in
if let isCheckmarked = self?.isCheckmarked {
self?.checkmark.alpha = isCheckmarked ? 1 : 0
}
})
}
}
| 21.880952 | 61 | 0.584331 |
5d05cc5a0c4f13f50d33d5f9e2f23bc6804ae02f | 1,690 | //
// CalculatorButtonItem.swift
// HelloWorld
//
// Created by 冯旭超 on 2020/3/19.
// Copyright © 2020 冯旭超. All rights reserved.
//
import Foundation
import SwiftUI
enum CalculatorButtonItem {
enum Op: String {
case plus = "+"
case minus = "-"
case divide = "÷"
case multiply = "×"
case equal = "="
}
enum Command: String {
case clear = "AC"
case flip = "+/-"
case percent = "%"
}
case digit(Int)
case dot
case op(Op)
case command(Command)
}
extension CalculatorButtonItem {
var title: String {
switch self {
case .digit(let value):
return String(value)
case .dot: return "."
case .op(let op): return op.rawValue
case .command(let command): return command.rawValue
}
}
var size: CGSize {
if case .digit(let value) = self, value == 0 {
return CGSize(width: 88 * 2 + 8, height: 88)
}
return CGSize(width: 88, height: 88)
}
var backgroundColorName: String {
switch self {
case .digit, .dot:
return "digitBackground"
case .op: return "operatorBackground"
case .command: return "CalculatorButtonItem.Command"
}
}
}
extension CalculatorButtonItem: Hashable {}
extension CalculatorButtonItem:
CustomStringConvertible {
var description: String {
switch self {
case .digit(let num): return String(num)
case .dot: return "."
case .op(let op): return op.rawValue
case .command(let command): return command.rawValue
}
}
}
| 22.837838 | 63 | 0.554438 |
d781138c17d47cff8710250c61f1ee79064e6147 | 589 | //
// CharacterListWireFrameTests.swift
// ArdaOnatOBSSCase
//
// Created by Arda Onat on 23.05.2021.
// Copyright (c) 2021 ___ORGANIZATIONNAME___. All rights reserved.
//
@testable import ArdaOnatOBSSCase
import XCTest
class CharacterListWireFrameTests: XCTestCase {
// MARK: - Properties
var wireframe: CharacterListWireframeProtocol!
// MARK: - Life Cycle
override func setUp() {
super.setUp()
wireframe = CharacterListWireframe()
}
override func tearDown() {
super.tearDown()
}
// MARK: - Tests
}
| 19 | 67 | 0.646859 |
e91052418722bbc0b06f99acafb4b3ccb7887ded | 675 | //
// MovieCell.swift
// Flicks
//
// Created by Poojan Dave on 1/11/17.
// Copyright © 2017 Poojan Dave. All rights reserved.
//
import UIKit
class MovieCell: UITableViewCell {
//Outlets of titleLabel, overviewLabel, and posterView
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var overviewLabel: UILabel!
@IBOutlet weak var posterView: UIImageView!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
| 22.5 | 65 | 0.675556 |
034ce2aa99e0e7aed716663e18cc7709652f28d9 | 2,376 | import Foundation
public struct HPInt64: HttpParameter {
let name: String
let defaultValue: Int64
let minValue: Int64?
let maxValue: Int64?
let clamped: Bool
let suppressDefault: Bool
public init(_ name: String, default: Int64 = 0, min: Int64? = nil, max: Int64? = nil, clamped: Bool = false, suppressDefault: Bool = true) {
self.name = name
self.defaultValue = `default`
self.minValue = min
self.maxValue = max
self.clamped = clamped
self.suppressDefault = suppressDefault
}
public init(_ name: String, default: Int64 = 0, in range: CountableClosedRange<Int64>, clamped: Bool = false, suppressDefault: Bool = true) {
self.name = name
self.defaultValue = `default`
self.minValue = range.lowerBound
self.maxValue = range.upperBound
self.clamped = clamped
self.suppressDefault = suppressDefault
}
}
// MARK: - HttpParameterInternal
extension HPInt64: HttpParameterInternal {}
// MARK: - HttpParameterCodable
extension HPInt64: HttpParameterCodable, HPBinaryIntegerSupport {
func dataMsgPack(_ value: Int64) throws -> Data {
let (count, mode) = MessagePackUtil.prepare(string: name)
let data: Data
switch value {
case -32...0x0000_0000_0000_007F:
data = MessagePackUtil.write(capacity: count + 1) { stream in
stream.write(name, mode: mode)
stream.write(Int8(value))
}
case -128...(-33):
data = MessagePackUtil.write(capacity: count + 2) { stream in
stream.write(name, mode: mode)
stream.write(UInt8(0xD0))
stream.write(Int8(value))
}
case 0x0000_0000_0000_0080...0x0000_0000_0000_7FFF, -32_768...(-129):
data = MessagePackUtil.write(capacity: count + 3) { stream in
stream.write(name, mode: mode)
stream.write(UInt8(0xD1))
stream.write(Int16(value).bigEndian)
}
case 0x0000_0000_0000_8000...0x0000_0000_7FFF_FFFF, -2_147_483_648...(-32_769):
data = MessagePackUtil.write(capacity: count + 5) { stream in
stream.write(name, mode: mode)
stream.write(UInt8(0xD2))
stream.write(Int32(value).bigEndian)
}
case 0x0000_0000_8000_0000...0x7FFF_FFFF_FFFF_FFFF, -9_223_372_036_854_775_808...(-2_147_483_649):
data = MessagePackUtil.write(capacity: count + 9) { stream in
stream.write(name, mode: mode)
stream.write(UInt8(0xD3))
stream.write(value.bigEndian)
}
default:
throw HttpParameterBuildError.unreachable
}
return data
}
}
| 28.97561 | 142 | 0.715067 |
9baecb82d390865c3d218fdc3bdca79ac006ef17 | 1,977 | //
// ExtensionCommands.swift
// LucidCodeGenExtension
//
// Created by Théophane Rupin on 12/22/20.
//
import Foundation
import Commander
import LucidCodeGenCore
import PathKit
// MARK: - Commands
public enum ExtensionCommands {
public static func generator<Generator>(_ generatorType: Generator.Type) -> Group where Generator: ExtensionGenerator {
Group {
$0.extensionCommand(name: "configuration") {
ExtensionGeneratorConfiguration(
name: Generator.name,
outputDirectory: Generator.outputDirectory,
targetName: Generator.targetName
)
}
$0.extensionCommand(name: "generate") { (input: ExtensionGeneratorInput) -> [SwiftFile] in
try Generator(input.parameters).generate(
for: input.elements,
in: input.directory,
organizationName: input.organizationName
)
}
}
}
}
// MARK: - Utils
private extension Group {
func extensionCommand<Output>(name: String = ExtensionCommand<Void, Output>.defaultCommandName,
run: @escaping () throws -> Output) where Output: Codable {
command(
name,
Argument<String>("io-path")
) { ioPath in
let command = ExtensionCommand<Void, Output>()
try command.respond(ioPath: Path(ioPath), run: run)
}
}
func extensionCommand<Input, Output>(name: String = ExtensionCommand<Input, Output>.defaultCommandName,
run: @escaping (Input) throws -> Output) where Input: Codable, Output: Codable {
command(
name,
Argument<String>("io-path")
) { ioPath in
let command = ExtensionCommand<Input, Output>()
try command.respond(ioPath: Path(ioPath), run: run)
}
}
}
| 29.954545 | 123 | 0.570561 |
b9539a175b1b5f1bea6d543ec7153608354956d4 | 2,479 | //
// APITransbank.swift
// Transbank
//
// Created by Jon Olivet on 8/28/18.
// Copyright © 2018 Jon Olivet. All rights reserved.
//
import Alamofire
import BasicCommons
protocol APITransbankProtocol {
func getMovieSummary(page: String,
success: @escaping (_ result: MovieSummaryResult, Int) -> Void,
failure: @escaping (_ error: NTError, Int) -> Void)
func getMovieDetail(movieId: String,
success: @escaping (_ result: MovieDetailResult, Int) -> Void,
failure: @escaping (_ error: NTError, Int) -> Void)
}
class APITransbank: AuthenticatedAPI, APITransbankProtocol {
// MARK: - Movie Summary
func getMovieSummary(
page: String,
success: @escaping (_ result: MovieSummaryResult, Int) -> Void,
failure: @escaping (_ error: NTError, Int) -> Void
) {
let url = Configuration.Api.movieSummary + page
self.requestGeneric(
type: MovieSummaryResult.self,
url: url,
method: HTTPMethod.get,
parameters: nil,
encoding: JSONEncoding.default,
validStatusCodes: [Int](200..<300),
onSuccess: { movieSummaryModel, _, statusCode in
success(movieSummaryModel!, statusCode!)
}, onFailure: { error, statusCode in
failure(error, statusCode)
}
)
}
// MARK: - Movie Detail
func getMovieDetail(
movieId: String,
success: @escaping (_ result: MovieDetailResult, Int) -> Void,
failure: @escaping (_ error: NTError, Int) -> Void
) {
let url = APITransbank.formatGetDetailResource(Configuration.Api.movieDetail, movieId)
self.requestGeneric(
type: MovieDetailResult.self,
url: url,
method: HTTPMethod.get,
parameters: nil,
encoding: JSONEncoding.default,
validStatusCodes: [Int](200..<300),
onSuccess: { movieSummaryModel, _, statusCode in
success(movieSummaryModel!, statusCode!)
}, onFailure: { error, statusCode in
failure(error, statusCode)
}
)
}
class func formatGetDetailResource(_ resource: String, _ movieId: String) -> String {
let instancedResource = resource.replacingOccurrences(of: "{movie_id}", with: movieId)
return instancedResource
}
}
| 32.618421 | 94 | 0.589754 |
916c4bfa9c0618ea91463406aff5552ca9317444 | 449 | //
// PageData.swift
// Storizy-iOS
//
// Created by 임수정 on 2021/11/26.
//
import Foundation
struct PageData: Codable {
var userId: Int?
var isPublic: Bool?
var isLiked: Bool?
var projectId: Int?
var projectTitle: String?
var pageId: Int?
var title: String?
var content: String?
var startDate: String?
var endDate: String?
var imageCount: Int?
var tags: [TagData?]
var projectColor: String?
}
| 18.708333 | 33 | 0.636971 |
1aa4665d2772004c1fe77c552ba8078b2dad57c2 | 17,096 | //
// LTMorphingLabel.swift
// https://github.com/lexrus/LTMorphingLabel
//
// The MIT License (MIT)
// Copyright (c) 2017 Lex Tang, http://lexrus.com
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files
// (the “Software”), to deal in the Software without restriction,
// including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software,
// and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
// CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
// TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
import Foundation
import UIKit
import QuartzCore
private func < <T : Comparable>(lhs: T?, rhs: T?) -> Bool {
switch (lhs, rhs) {
case let (l?, r?):
return l < r
case (nil, _?):
return true
default:
return false
}
}
private func >= <T : Comparable>(lhs: T?, rhs: T?) -> Bool {
switch (lhs, rhs) {
case let (l?, r?):
return l >= r
default:
return !(lhs < rhs)
}
}
enum LTMorphingPhases: Int {
case start, appear, disappear, draw, progress, skipFrames
}
typealias LTMorphingStartClosure =
() -> Void
typealias LTMorphingEffectClosure =
(Character, _ index: Int, _ progress: Float) -> LTCharacterLimbo
typealias LTMorphingDrawingClosure =
(LTCharacterLimbo) -> Bool
typealias LTMorphingManipulateProgressClosure =
(_ index: Int, _ progress: Float, _ isNewChar: Bool) -> Float
typealias LTMorphingSkipFramesClosure =
() -> Int
@objc public protocol LTMorphingLabelDelegate {
@objc optional func morphingDidStart(_ label: LTMorphingLabel)
@objc optional func morphingDidComplete(_ label: LTMorphingLabel)
@objc optional func morphingOnProgress(_ label: LTMorphingLabel, progress: Float)
}
// MARK: - LTMorphingLabel
@IBDesignable open class LTMorphingLabel: UILabel {
@IBInspectable open var morphingProgress: Float = 0.0
@IBInspectable open var morphingDuration: Float = 0.6
@IBInspectable open var morphingCharacterDelay: Float = 0.026
@IBInspectable open var morphingEnabled: Bool = true
@IBOutlet open weak var delegate: LTMorphingLabelDelegate?
open var morphingEffect: LTMorphingEffect = .scale
var startClosures = [String: LTMorphingStartClosure]()
var effectClosures = [String: LTMorphingEffectClosure]()
var drawingClosures = [String: LTMorphingDrawingClosure]()
var progressClosures = [String: LTMorphingManipulateProgressClosure]()
var skipFramesClosures = [String: LTMorphingSkipFramesClosure]()
var diffResults: LTStringDiffResult?
var previousText = ""
var currentFrame = 0
var totalFrames = 0
var totalDelayFrames = 0
var totalWidth: Float = 0.0
var previousRects = [CGRect]()
var newRects = [CGRect]()
var charHeight: CGFloat = 0.0
var skipFramesCount: Int = 0
#if TARGET_INTERFACE_BUILDER
let presentingInIB = true
#else
let presentingInIB = false
#endif
open var fontOrDefault: UIFont {
font ?? UIFont.systemFont(ofSize: 15)
}
open var fontPointSize: CGFloat {
fontOrDefault.pointSize
}
override open var font: UIFont? {
get {
return super.font ?? UIFont.systemFont(ofSize: 15)
}
set {
super.font = newValue
setNeedsLayout()
}
}
override open var text: String! {
get {
return super.text ?? ""
}
set {
guard text != newValue else { return }
if newValue == "0" { return }
previousText = text ?? ""
diffResults = previousText.diffWith(newValue)
super.text = newValue ?? ""
morphingProgress = 0.0
currentFrame = 0
totalFrames = 0
setNeedsLayout()
if !morphingEnabled {
return
}
if presentingInIB {
morphingDuration = 0.01
morphingProgress = 0.5
} else if previousText != text {
displayLink.isPaused = false
let closureKey = "\(morphingEffect.description)\(LTMorphingPhases.start)"
if let closure = startClosures[closureKey] {
return closure()
}
delegate?.morphingDidStart?(self)
}
}
}
open override func setNeedsLayout() {
super.setNeedsLayout()
previousRects = rectsOfEachCharacter(previousText, withFont: fontOrDefault)
newRects = rectsOfEachCharacter(text ?? "", withFont: fontOrDefault)
}
override open var bounds: CGRect {
get {
return super.bounds
}
set {
super.bounds = newValue
setNeedsLayout()
}
}
override open var frame: CGRect {
get {
return super.frame
}
set {
super.frame = newValue
setNeedsLayout()
}
}
fileprivate lazy var displayLink: CADisplayLink = {
let displayLink = CADisplayLink(
target: self,
selector: #selector(LTMorphingLabel.displayFrameTick)
)
displayLink.add(to: .current, forMode: RunLoop.Mode.common)
return displayLink
}()
deinit {
displayLink.remove(from: .current, forMode: RunLoop.Mode.common)
displayLink.invalidate()
}
lazy var emitterView: LTEmitterView = {
let emitterView = LTEmitterView(frame: self.bounds)
self.addSubview(emitterView)
return emitterView
}()
}
// MARK: - Animation extension
extension LTMorphingLabel {
@objc func displayFrameTick() {
if displayLink.duration > 0.0 && totalFrames == 0 {
var frameRate = Float(0)
if #available(iOS 10.0, tvOS 10.0, *) {
var frameInterval = 1
if displayLink.preferredFramesPerSecond == 60 {
frameInterval = 1
} else if displayLink.preferredFramesPerSecond == 30 {
frameInterval = 2
} else {
frameInterval = 1
}
frameRate = Float(displayLink.duration) / Float(frameInterval)
} else {
frameRate = Float(displayLink.duration) / Float(displayLink.frameInterval)
}
totalFrames = Int(ceil(morphingDuration / frameRate))
let totalDelay = Float((text!).count) * morphingCharacterDelay
totalDelayFrames = Int(ceil(totalDelay / frameRate))
}
currentFrame += 1
if previousText != text && currentFrame < totalFrames + totalDelayFrames + 5 {
morphingProgress += 1.0 / Float(totalFrames)
let closureKey = "\(morphingEffect.description)\(LTMorphingPhases.skipFrames)"
if let closure = skipFramesClosures[closureKey] {
skipFramesCount += 1
if skipFramesCount > closure() {
skipFramesCount = 0
setNeedsDisplay()
}
} else {
setNeedsDisplay()
}
if let onProgress = delegate?.morphingOnProgress {
onProgress(self, morphingProgress)
}
} else {
displayLink.isPaused = true
delegate?.morphingDidComplete?(self)
}
}
// Could be enhanced by kerning text:
// http://stackoverflow.com/questions/21443625/core-text-calculate-letter-frame-in-ios
func rectsOfEachCharacter(_ textToDraw: String, withFont font: UIFont) -> [CGRect] {
var charRects = [CGRect]()
var leftOffset: CGFloat = 0.0
charHeight = "Leg".size(withAttributes: [.font: font]).height
let topOffset = (bounds.size.height - charHeight) / 2.0
for char in textToDraw {
let charSize = String(char).size(withAttributes: [.font: font])
charRects.append(
CGRect(
origin: CGPoint(
x: leftOffset,
y: topOffset
),
size: charSize
)
)
leftOffset += charSize.width
}
totalWidth = Float(leftOffset)
var stringLeftOffSet: CGFloat = 0.0
switch textAlignment {
case .center:
stringLeftOffSet = CGFloat((Float(bounds.size.width) - totalWidth) / 2.0)
case .right:
stringLeftOffSet = CGFloat(Float(bounds.size.width) - totalWidth)
default:
()
}
var offsetedCharRects = [CGRect]()
for r in charRects {
offsetedCharRects.append(r.offsetBy(dx: stringLeftOffSet, dy: 0.0))
}
return offsetedCharRects
}
func limboOfOriginalCharacter(
_ char: Character,
index: Int,
progress: Float) -> LTCharacterLimbo {
var currentRect = previousRects[index]
let oriX = Float(currentRect.origin.x)
var newX = Float(currentRect.origin.x)
let diffResult = diffResults!.0[index]
var currentFontSize: CGFloat = self.fontPointSize
var currentAlpha: CGFloat = 1.0
switch diffResult {
// Move the character that exists in the new text to current position
case .same:
newX = Float(newRects[index].origin.x)
currentRect.origin.x = CGFloat(
LTEasing.easeOutQuint(progress, oriX, newX - oriX)
)
case .move(let offset):
newX = Float(newRects[index + offset].origin.x)
currentRect.origin.x = CGFloat(
LTEasing.easeOutQuint(progress, oriX, newX - oriX)
)
case .moveAndAdd(let offset):
newX = Float(newRects[index + offset].origin.x)
currentRect.origin.x = CGFloat(
LTEasing.easeOutQuint(progress, oriX, newX - oriX)
)
default:
// Otherwise, remove it
// Override morphing effect with closure in extenstions
if let closure = effectClosures[
"\(morphingEffect.description)\(LTMorphingPhases.disappear)"
] {
return closure(char, index, progress)
} else {
// And scale it by default
let fontEase = CGFloat(
LTEasing.easeOutQuint(
progress, 0, Float(self.fontPointSize)
)
)
// For emojis
currentFontSize = max(0.0001, self.fontPointSize - fontEase)
currentAlpha = CGFloat(1.0 - progress)
currentRect = previousRects[index].offsetBy(
dx: 0,
dy: CGFloat(self.fontPointSize - currentFontSize)
)
}
}
return LTCharacterLimbo(
char: char,
rect: currentRect,
alpha: currentAlpha,
size: currentFontSize,
drawingProgress: 0.0
)
}
func limboOfNewCharacter(
_ char: Character,
index: Int,
progress: Float) -> LTCharacterLimbo {
let currentRect = newRects[index]
var currentFontSize = CGFloat(
LTEasing.easeOutQuint(progress, 0, Float(self.fontPointSize))
)
if let closure = effectClosures[
"\(morphingEffect.description)\(LTMorphingPhases.appear)"
] {
return closure(char, index, progress)
} else {
currentFontSize = CGFloat(
LTEasing.easeOutQuint(progress, 0.0, Float(self.fontPointSize))
)
// For emojis
currentFontSize = max(0.0001, currentFontSize)
let yOffset = CGFloat(self.fontPointSize - currentFontSize)
return LTCharacterLimbo(
char: char,
rect: currentRect.offsetBy(dx: 0, dy: yOffset),
alpha: CGFloat(morphingProgress),
size: currentFontSize,
drawingProgress: 0.0
)
}
}
func limboOfCharacters() -> [LTCharacterLimbo] {
var limbo = [LTCharacterLimbo]()
// Iterate original characters
for (i, character) in previousText.enumerated() {
var progress: Float = 0.0
if let closure = progressClosures[
"\(morphingEffect.description)\(LTMorphingPhases.progress)"
] {
progress = closure(i, morphingProgress, false)
} else {
progress = min(1.0, max(0.0, morphingProgress + morphingCharacterDelay * Float(i)))
}
let limboOfCharacter = limboOfOriginalCharacter(character, index: i, progress: progress)
limbo.append(limboOfCharacter)
}
// Add new characters
for (i, character) in (text!).enumerated() {
if i >= diffResults?.0.count {
break
}
var progress: Float = 0.0
if let closure = progressClosures[
"\(morphingEffect.description)\(LTMorphingPhases.progress)"
] {
progress = closure(i, morphingProgress, true)
} else {
progress = min(1.0, max(0.0, morphingProgress - morphingCharacterDelay * Float(i)))
}
// Don't draw character that already exists
if diffResults?.skipDrawingResults[i] == true {
continue
}
if let diffResult = diffResults?.0[i] {
switch diffResult {
case .moveAndAdd, .replace, .add, .delete:
let limboOfCharacter = limboOfNewCharacter(
character,
index: i,
progress: progress
)
limbo.append(limboOfCharacter)
default:
()
}
}
}
return limbo
}
}
// MARK: - Drawing extension
extension LTMorphingLabel {
override open func didMoveToSuperview() {
if let s = text {
text = s
}
// Load all morphing effects
for effectName: String in LTMorphingEffect.allValues {
let effectFunc = Selector("\(effectName)Load")
if responds(to: effectFunc) {
perform(effectFunc)
}
}
}
override open func drawText(in rect: CGRect) {
if !morphingEnabled || limboOfCharacters().count == 0 {
super.drawText(in: rect)
return
}
for charLimbo in limboOfCharacters() {
let charRect = charLimbo.rect
let willAvoidDefaultDrawing: Bool = {
if let closure = drawingClosures[
"\(morphingEffect.description)\(LTMorphingPhases.draw)"
] {
return closure($0)
}
return false
}(charLimbo)
if !willAvoidDefaultDrawing {
var attrs: [NSAttributedString.Key: Any] = [
.foregroundColor: textColor.withAlphaComponent(charLimbo.alpha)
]
if let font = UIFont(name: fontOrDefault.fontName, size: charLimbo.size) {
attrs[.font] = font
}
let s = String(charLimbo.char)
s.draw(in: charRect, withAttributes: attrs)
}
}
}
}
| 33.003861 | 100 | 0.541179 |
036a9e7794c3a61f65b46d996b3f8953bec5701b | 1,976 | // MainController.swift
// Themeful
//
// Created by XMFraker on 2018/12/11
// Copyright © XMFraker All rights reserved. (https://github.com/ws00801526)
// @class MainController
// @version <#class version#>
// @abstract <#class description#>
import UIKit
import Themeful
import CoreLocation
class MainController: UIViewController {
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var imageView: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
setupTheme()
if let URL = Bundle.main.url(forResource: "Valentine", withExtension: "strings") {
print("URL \(URL)")
print("URL after delete last component \(URL.deletingLastPathComponent())")
}
}
override var preferredStatusBarStyle: UIStatusBarStyle {
return ThemeStatusBarStylePicker.init("Global.status").style
}
fileprivate func setupTheme() {
let _ = self.nameLabel.theme.setText("main.name")
let _ = self.imageView.theme.setImage("main.image")
let _ = self.navigationItem.theme.setTitle("main.title")
let _ = self.navigationController?.navigationBar.theme
.setBackgroundColorImage("Global.nav.backgroundColor")
.setTitleTextAttributes("Global.nav.textAttributes")
}
@IBAction func handleThemeChanged(_ sender: UISwitch) {
// ThemeManager.duration = (arc4random() % 2 == 0) ? 0.2 : 0.0
ThemeManager.duration = 0
let themePath = ThemePath.mainBundle
let theme = sender.isOn ? Theme("Valentine.strings", path: themePath) : Theme("Chinese.strings", path: themePath)
let _ = ThemeManager.setTheme(theme: theme)
setNeedsStatusBarAppearanceUpdate()
// if let image = ThemeManager.colorImage("Global.nav.backgroundColor") {
// self.navigationController?.navigationBar.setBackgroundImage(image, for: .default)
// }
}
}
| 35.927273 | 121 | 0.654858 |
e87dce301b867c9b2b2515d2ad759be77a60259b | 17,199 | import UIKit
import CoreData
/**
Event API contains the endpoints to Create/Read/Update/Delete Events.
*/
class EventAPI {
fileprivate let persistenceManager: PersistenceManager!
fileprivate var mainContextInstance: NSManagedObjectContext!
fileprivate let idNamespace = MovieAttributes.eventId.rawValue
fileprivate let productionNamespace = MovieAttributes.production.rawValue
fileprivate let longDescriptionNamespace = MovieAttributes.longDescription.rawValue
fileprivate let titleNamespace = MovieAttributes.title.rawValue
fileprivate let dateNamespace = MovieAttributes.date.rawValue
fileprivate let countryNamespace = MovieAttributes.country.rawValue
fileprivate let attendeesNamespace = MovieAttributes.actors.rawValue
//Utilize Singleton pattern by instanciating EventAPI only once.
class var sharedInstance: EventAPI {
struct Singleton {
static let instance = EventAPI()
}
return Singleton.instance
}
init() {
self.persistenceManager = PersistenceManager.sharedInstance
self.mainContextInstance = persistenceManager.getMainContextInstance()
}
/**
Retrieve an Event
Scenario:
Given that there there is only a single event in the datastore
Let say we only created one event in the datastore, then this function will get that single persisted event
Thus calling this method multiple times will result in getting always the same event.
- Returns: a found Event item, or nil
*/
func getSingleAndOnlyEvent(eventTitle: String) -> Event? {
var fetchedResultEvent: Event?
// Create request on Event entity
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: EntityTypes.Event.rawValue)
//Execute Fetch request
do {
let fetchedResults = try self.mainContextInstance.fetch(fetchRequest) as! [Event]
fetchRequest.fetchLimit = 1
if fetchedResults.count != 0 {
fetchedResultEvent = fetchedResults.first
}
} catch let fetchError as NSError {
print("retrieve single event error: \(fetchError.localizedDescription)")
}
return fetchedResultEvent
}
// MARK: Create
/**
Create a single Event item, and persist it to Datastore via Worker(minion),
that synchronizes with Main context.
- Parameter eventDetails: <Dictionary<String, AnyObject> A single Event item to be persisted to the Datastore.
- Returns: Void
*/
func saveEvent(_ eventDetails: Dictionary<String, AnyObject>) {
//Minion Context worker with Private Concurrency type.
let minionManagedObjectContextWorker: NSManagedObjectContext =
NSManagedObjectContext.init(concurrencyType: NSManagedObjectContextConcurrencyType.privateQueueConcurrencyType)
minionManagedObjectContextWorker.parent = self.mainContextInstance
//Create new Object of Event entity
let eventItem = NSEntityDescription.insertNewObject(forEntityName: EntityTypes.Event.rawValue,
into: minionManagedObjectContextWorker) as! Event
//Assign field values
for (key, value) in eventDetails {
for attribute in MovieAttributes.getAll {
if (key == attribute.rawValue) {
eventItem.setValue(value, forKey: key)
}
}
}
//Save current work on Minion workers
self.persistenceManager.saveWorkerContext(minionManagedObjectContextWorker)
//Save and merge changes from Minion workers with Main context
self.persistenceManager.mergeWithMainContext()
//Post notification to update datasource of a given Viewcontroller/UITableView
self.postUpdateNotification()
}
/**
Create a single Event item, and persist it to Datastore via Worker(minion),
that synchronizes with Main context.
- Parameter eventDetails: <Dictionary<String, AnyObject> A single Event item to be persisted to the Datastore.
- Returns: Void
*/
func saveEvent(_ eventTitle: String?) {
//Minion Context worker with Private Concurrency type.
let minionManagedObjectContextWorker: NSManagedObjectContext =
NSManagedObjectContext.init(concurrencyType: NSManagedObjectContextConcurrencyType.privateQueueConcurrencyType)
minionManagedObjectContextWorker.parent = self.mainContextInstance
//Create new Object of Event entity
let eventItem = NSEntityDescription.insertNewObject(forEntityName: EntityTypes.Event.rawValue,
into: minionManagedObjectContextWorker) as! Event
if eventTitle == nil {
eventItem.title = "mocked title"
} else {
eventItem.title = eventTitle!
eventItem.country = "mocked country"
eventItem.production = "mocked production"
eventItem.longDescription = "mocked long_description"
eventItem.date = Date()
eventItem.eventId = "123456789"
}
//Save current work on Minion workers
self.persistenceManager.saveWorkerContext(minionManagedObjectContextWorker)
//Save and merge changes from Minion workers with Main context
self.persistenceManager.mergeWithMainContext()
//Post notification to update datasource of a given Viewcontroller/UITableView
self.postUpdateNotification()
}
/**
Create new Events from a given list, and persist it to Datastore via Worker(minion),
that synchronizes with Main context.
- Parameter eventsList: Array<AnyObject> Contains events to be persisted to the Datastore.
- Returns: Void
*/
func saveEventsList(_ eventsList: Array<AnyObject>) {
DispatchQueue.global().async {
//Minion Context worker with Private Concurrency type.
let minionManagedObjectContextWorker: NSManagedObjectContext =
NSManagedObjectContext.init(concurrencyType: NSManagedObjectContextConcurrencyType.privateQueueConcurrencyType)
minionManagedObjectContextWorker.parent = self.mainContextInstance
//Create eventEntity, process member field values
for index in 0..<eventsList.count {
let eventItem: Dictionary<String, NSObject> = eventsList[index] as! Dictionary<String, NSObject>
//Check that an Event to be stored has a date, title and country.
if eventItem[self.dateNamespace] as! String != ""
&& eventItem[self.titleNamespace] as! String != ""
&& eventItem[self.countryNamespace] as! String != "" {
//Create new Object of Event entity
let item = NSEntityDescription.insertNewObject(forEntityName: EntityTypes.Event.rawValue,
into: minionManagedObjectContextWorker) as! Event
//Add member field values
item.setValue(DateFormatter.getDateFromString(eventItem[self.dateNamespace] as! String), forKey: self.dateNamespace)
item.setValue(eventItem[self.titleNamespace], forKey: self.titleNamespace)
item.setValue(eventItem[self.countryNamespace], forKey: self.countryNamespace)
item.setValue(eventItem[self.idNamespace], forKey: self.idNamespace)
item.setValue(eventItem[self.productionNamespace], forKey: self.productionNamespace)
item.setValue(eventItem[self.longDescriptionNamespace], forKey: self.longDescriptionNamespace)
item.setValue(eventItem[self.attendeesNamespace], forKey: self.attendeesNamespace)
//Save current work on Minion workers
self.persistenceManager.saveWorkerContext(minionManagedObjectContextWorker)
}
}
//Save and merge changes from Minion workers with Main context
self.persistenceManager.mergeWithMainContext()
//Post notification to update datasource of a given Viewcontroller/UITableView
DispatchQueue.main.async {
self.postUpdateNotification()
}
}
}
// MARK: Read
/**
Retrieves all event items stored in the persistence layer, default (overridable)
parameters:
- Parameter sortedByDate: Bool flag to add sort rule: by Date
- Parameter sortAscending: Bool flag to set rule on sorting: Ascending / Descending date.
- Returns: Array<Event> with found events in datastore
*/
func getAllEvents(_ sortedByDate: Bool = true, sortAscending: Bool = true) -> Array<Event> {
var fetchedResults: Array<Event> = Array<Event>()
// Create request on Event entity
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: EntityTypes.Event.rawValue)
//Create sort descriptor to sort retrieved Events by Date, ascending
if sortedByDate {
let sortDescriptor = NSSortDescriptor(key: dateNamespace,
ascending: sortAscending)
let sortDescriptors = [sortDescriptor]
fetchRequest.sortDescriptors = sortDescriptors
}
//Execute Fetch request
do {
fetchedResults = try self.mainContextInstance.fetch(fetchRequest) as! [Event]
} catch let fetchError as NSError {
print("retrieveById error: \(fetchError.localizedDescription)")
fetchedResults = Array<Event>()
}
return fetchedResults
}
/**
Retrieve an Event, found by it's stored UUID.
- Parameter eventId: UUID of Event item to retrieve
- Returns: Array of Found Event items, or empty Array
*/
func getEventById(_ eventId: NSString) -> Array<Event> {
var fetchedResults: Array<Event> = Array<Event>()
// Create request on Event entity
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: EntityTypes.Event.rawValue)
//Add a predicate to filter by eventId
let findByIdPredicate =
NSPredicate(format: "\(idNamespace) = %@", eventId)
fetchRequest.predicate = findByIdPredicate
//Execute Fetch request
do {
fetchedResults = try self.mainContextInstance.fetch(fetchRequest) as! [Event]
} catch let fetchError as NSError {
print("retrieveById error: \(fetchError.localizedDescription)")
fetchedResults = Array<Event>()
}
return fetchedResults
}
/**
Retrieves all event items stored in the persistence layer
and sort it by Date within a given range of (default) current date and
(default)7 days from current date (is overridable, parameters are optional).
- Parameter sortByDate: Bool default and overridable is set to True
- Parameter sortAscending: Bool default and overridable is set to True
- Parameter startDate: NSDate default and overridable is set to previous year
- Parameter endDate: NSDate default and overridable is set to 1 week from current date
- Returns: Array<Event> with found events in datastore based on
sort descriptor, in this case Date an dgiven date range.
*/
func getEventsInDateRange(_ sortByDate: Bool = true, sortAscending: Bool = true,
startDate: Date = Date(timeInterval:-189216000, since:Date()),
endDate: Date = (Calendar.current as NSCalendar)
.date(
byAdding: .day, value: 7,
to: Date(),
options: NSCalendar.Options(rawValue: 0))!) -> Array<Event> {
// Create request on Event entity
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: EntityTypes.Event.rawValue)
//Create sort descriptor to sort retrieved Events by Date, ascending
let sortDescriptor = NSSortDescriptor(key: MovieAttributes.date.rawValue,
ascending: sortAscending)
let sortDescriptors = [sortDescriptor]
fetchRequest.sortDescriptors = sortDescriptors
//Create predicate to filter by start- / end date
let findByDateRangePredicate = NSPredicate(format: "(\(dateNamespace) >= %@) AND (\(dateNamespace) <= %@)", startDate as CVarArg, endDate as CVarArg)
fetchRequest.predicate = findByDateRangePredicate
//Execute Fetch request
var fetchedResults = Array<Event>()
do {
fetchedResults = try self.mainContextInstance.fetch(fetchRequest) as! [Event]
} catch let fetchError as NSError {
print("retrieveItemsSortedByDateInDateRange error: \(fetchError.localizedDescription)")
}
return fetchedResults
}
// MARK: Update
/**
Update all events (batch update) attendees list.
Since privacy is always a concern to take into account,
anonymise the attendees list for every event.
- Returns: Void
*/
// func anonimizeAttendeesList() {
// // Create a fetch request for the entity Person
// let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: EntityTypes.Event.rawValue)
//
// // Execute the fetch request
// var fetchedResults = Array<Event>()
// do {
// fetchedResults = try self.mainContextInstance.fetch(fetchRequest) as! [Event]
//
// for event in fetchedResults {
// //get count of current attendees list
// let currCount = (event as Event).attendees.count
//
// //Create an anonymised list of attendees
// //with count of current attendees list
// let anonymisedList = [String](repeating: "Anonymous", count: currCount!)
//
// //Update current attendees list with anonymised list, shallow copy.
// (event as Event).attendees = anonymisedList as AnyObject
// }
// } catch let updateError as NSError {
// print("updateAllEventAttendees error: \(updateError.localizedDescription)")
// }
// }
/**
Update event item for specific keys.
- Parameter eventItemToUpdate: Event the passed event to update it's member fields
- Parameter newEventItemDetails: Dictionary<String,AnyObject> the details to be updated
- Returns: Void
*/
func updateEvent(_ eventItemToUpdate: Event, newEventItemDetails: Dictionary<String, AnyObject>) {
let minionManagedObjectContextWorker: NSManagedObjectContext =
NSManagedObjectContext.init(concurrencyType: NSManagedObjectContextConcurrencyType.privateQueueConcurrencyType)
minionManagedObjectContextWorker.parent = self.mainContextInstance
//Assign field values
for (key, value) in newEventItemDetails {
for attribute in MovieAttributes.getAll {
if (key == attribute.rawValue) {
eventItemToUpdate.setValue(value, forKey: key)
}
}
}
//Persist new Event to datastore (via Managed Object Context Layer).
self.persistenceManager.saveWorkerContext(minionManagedObjectContextWorker)
self.persistenceManager.mergeWithMainContext()
self.postUpdateNotification()
}
// MARK: Delete
/**
Delete all Event items from persistence layer.
- Returns: Void
*/
func deleteAllEvents() {
let retrievedItems = getAllEvents()
//Delete all event items from persistance layer
for item in retrievedItems {
self.mainContextInstance.delete(item)
}
//Save and merge changes from Minion workers with Main context
self.persistenceManager.mergeWithMainContext()
//Post notification to update datasource of a given Viewcontroller/UITableView
self.postUpdateNotification()
}
/**
Delete a single Event item from persistence layer.
- Parameter eventItem: Event to be deleted
- Returns: Void
*/
func deleteEvent(_ eventItem: Event) {
print(eventItem)
//Delete event item from persistance layer
self.mainContextInstance.delete(eventItem)
//Save and merge changes from Minion workers with Main context
self.persistenceManager.mergeWithMainContext()
//Post notification to update datasource of a given Viewcontroller/UITableView
self.postUpdateNotification()
}
/**
Post update notification to let the registered listeners refresh it's datasource.
- Returns: Void
*/
fileprivate func postUpdateNotification() {
NotificationCenter.default.post(name: Notification.Name(rawValue: "updateEventTableData"), object: nil)
}
}
| 41.244604 | 157 | 0.655794 |
0ee53e0a3580b4f6d94914502f7692636bb73efa | 21,716 | //
// FlagStoreSpec.swift
// LaunchDarklyTests
//
// Copyright © 2017 Catamorphic Co. All rights reserved.
//
import Foundation
import Quick
import Nimble
@testable import LaunchDarkly
final class FlagStoreSpec: QuickSpec {
struct FlagKeys {
static let newInt = "new-int-flag"
}
struct DefaultValues {
static let bool = false
static let int = 3
static let double = 2.71828
static let string = "defaultValue string"
static let array = [0]
static let dictionary: [String: Any] = [DarklyServiceMock.FlagKeys.string: DarklyServiceMock.FlagValues.string]
}
struct TestContext {
let flagStore: FlagStore!
let featureFlags: [LDFlagKey: FeatureFlag]!
init() {
featureFlags = DarklyServiceMock.Constants.stubFeatureFlags()
flagStore = FlagStore(featureFlags: featureFlags)
}
}
override func spec() {
initSpec()
replaceStoreSpec()
updateStoreSpec()
deleteFlagSpec()
featureFlagSpec()
}
func initSpec() {
var subject: FlagStore!
var featureFlags: [LDFlagKey: FeatureFlag]!
describe("init") {
context("without an initial flag store") {
it("has no feature flags") {
subject = FlagStore()
expect(subject.featureFlags.isEmpty) == true
}
}
context("with an initial flag store") {
it("has matching feature flags") {
featureFlags = DarklyServiceMock.Constants.stubFeatureFlags()
subject = FlagStore(featureFlags: featureFlags)
expect(subject.featureFlags) == featureFlags
}
}
context("with an initial flag store without elements") {
it("has matching feature flags") {
featureFlags = DarklyServiceMock.Constants.stubFeatureFlags(includeVariations: false, includeVersions: false, includeFlagVersions: false)
subject = FlagStore(featureFlags: featureFlags)
expect(subject.featureFlags) == featureFlags
}
}
context("with an initial flag dictionary") {
it("has the feature flags") {
featureFlags = DarklyServiceMock.Constants.stubFeatureFlags()
subject = FlagStore(featureFlagDictionary: featureFlags.dictionaryValue)
expect(subject.featureFlags) == featureFlags
}
}
}
}
func replaceStoreSpec() {
let featureFlags: [LDFlagKey: FeatureFlag] = DarklyServiceMock.Constants.stubFeatureFlags(includeNullValue: false)
var flagStore: FlagStore!
describe("replaceStore") {
context("with new flag values") {
it("causes FlagStore to replace the flag values") {
flagStore = FlagStore()
waitUntil(timeout: .seconds(1)) { done in
flagStore.replaceStore(newFlags: featureFlags, completion: done)
}
expect(flagStore.featureFlags) == featureFlags
}
}
context("with new flag value dictionary") {
it("causes FlagStore to replace the flag values") {
flagStore = FlagStore()
waitUntil(timeout: .seconds(1)) { done in
flagStore.replaceStore(newFlags: featureFlags.dictionaryValue, completion: done)
}
expect(flagStore.featureFlags) == featureFlags
}
}
context("with invalid dictionary") {
it("causes FlagStore to empty the flag values") {
flagStore = FlagStore(featureFlags: featureFlags)
waitUntil(timeout: .seconds(1)) { done in
flagStore.replaceStore(newFlags: ["fakeKey": "Not a flag dict"], completion: done)
}
expect(flagStore.featureFlags.isEmpty).to(beTrue())
}
}
}
}
func updateStoreSpec() {
var testContext: TestContext!
var updateDictionary: [String: Any]!
describe("updateStore") {
beforeEach {
testContext = TestContext()
}
context("when feature flag does not already exist") {
beforeEach {
updateDictionary = FlagMaintainingMock.stubPatchDictionary(key: FlagKeys.newInt,
value: DarklyServiceMock.FlagValues.alternate(DarklyServiceMock.FlagValues.int),
variation: DarklyServiceMock.Constants.variation,
version: DarklyServiceMock.Constants.version)
waitUntil { done in
testContext.flagStore.updateStore(updateDictionary: updateDictionary, completion: done)
}
}
it("adds the new flag to the store") {
let featureFlag = testContext.flagStore.featureFlags[FlagKeys.newInt]
expect(AnyComparer.isEqual(featureFlag?.value, to: updateDictionary?.value)).to(beTrue())
expect(featureFlag?.variation) == updateDictionary?.variation
expect(featureFlag?.version) == updateDictionary?.version
}
}
context("when the feature flag exists") {
context("and the update version > existing version") {
beforeEach {
updateDictionary = FlagMaintainingMock.stubPatchDictionary(key: DarklyServiceMock.FlagKeys.int,
value: DarklyServiceMock.FlagValues.alternate(DarklyServiceMock.FlagValues.int),
variation: DarklyServiceMock.Constants.variation + 1,
version: DarklyServiceMock.Constants.version + 1)
waitUntil { done in
testContext.flagStore.updateStore(updateDictionary: updateDictionary, completion: done)
}
}
it("updates the feature flag to the update value") {
let featureFlag = testContext.flagStore.featureFlags[DarklyServiceMock.FlagKeys.int]
expect(AnyComparer.isEqual(featureFlag?.value, to: updateDictionary?.value)).to(beTrue())
expect(featureFlag?.variation) == updateDictionary?.variation
expect(featureFlag?.version) == updateDictionary?.version
}
}
context("and the new value is null") {
beforeEach {
updateDictionary = FlagMaintainingMock.stubPatchDictionary(key: DarklyServiceMock.FlagKeys.int,
value: NSNull(),
variation: DarklyServiceMock.Constants.variation + 1,
version: DarklyServiceMock.Constants.version + 1)
waitUntil { done in
testContext.flagStore.updateStore(updateDictionary: updateDictionary, completion: done)
}
}
it("updates the feature flag to the update value") {
let featureFlag = testContext.flagStore.featureFlags[DarklyServiceMock.FlagKeys.int]
expect(featureFlag?.value).to(beNil())
expect(featureFlag?.variation) == updateDictionary.variation
expect(featureFlag?.version) == updateDictionary.version
}
}
context("and the update version == existing version") {
beforeEach {
updateDictionary = FlagMaintainingMock.stubPatchDictionary(key: DarklyServiceMock.FlagKeys.int,
value: DarklyServiceMock.FlagValues.alternate(DarklyServiceMock.FlagValues.int),
variation: DarklyServiceMock.Constants.variation,
version: DarklyServiceMock.Constants.version)
waitUntil { done in
testContext.flagStore.updateStore(updateDictionary: updateDictionary, completion: done)
}
}
it("does not change the feature flag value") {
expect(testContext.flagStore.featureFlags) == testContext.featureFlags
}
}
context("and the update version < existing version") {
beforeEach {
updateDictionary = FlagMaintainingMock.stubPatchDictionary(key: DarklyServiceMock.FlagKeys.int,
value: DarklyServiceMock.FlagValues.alternate(DarklyServiceMock.FlagValues.int),
variation: DarklyServiceMock.Constants.variation - 1,
version: DarklyServiceMock.Constants.version - 1)
waitUntil { done in
testContext.flagStore.updateStore(updateDictionary: updateDictionary, completion: done)
}
}
it("does not change the feature flag value") {
expect(testContext.flagStore.featureFlags) == testContext.featureFlags
}
}
}
context("when the update dictionary is missing the flagKey") {
beforeEach {
updateDictionary = FlagMaintainingMock.stubPatchDictionary(key: nil,
value: DarklyServiceMock.FlagValues.alternate(DarklyServiceMock.FlagValues.int),
variation: DarklyServiceMock.Constants.variation + 1,
version: DarklyServiceMock.Constants.version + 1)
waitUntil { done in
testContext.flagStore.updateStore(updateDictionary: updateDictionary, completion: done)
}
}
it("makes no changes") {
expect(testContext.flagStore.featureFlags) == testContext.featureFlags
}
}
context("when the update dictionary is missing the value") {
beforeEach {
updateDictionary = FlagMaintainingMock.stubPatchDictionary(key: DarklyServiceMock.FlagKeys.int,
value: nil,
variation: DarklyServiceMock.Constants.variation + 1,
version: DarklyServiceMock.Constants.version + 1)
waitUntil { done in
testContext.flagStore.updateStore(updateDictionary: updateDictionary, completion: done)
}
}
it("updates the feature flag to the update value") {
let featureFlag = testContext.flagStore.featureFlags[DarklyServiceMock.FlagKeys.int]
expect(AnyComparer.isEqual(featureFlag?.value, to: updateDictionary.value)).to(beTrue())
expect(featureFlag?.variation) == updateDictionary.variation
expect(featureFlag?.version) == updateDictionary.version
}
}
context("when the update dictionary is missing the variation") {
beforeEach {
updateDictionary = FlagMaintainingMock.stubPatchDictionary(key: DarklyServiceMock.FlagKeys.int,
value: DarklyServiceMock.FlagValues.alternate(DarklyServiceMock.FlagValues.int),
variation: nil,
version: DarklyServiceMock.Constants.version + 1)
waitUntil { done in
testContext.flagStore.updateStore(updateDictionary: updateDictionary, completion: done)
}
}
it("updates the feature flag to the update value") {
let featureFlag = testContext.flagStore.featureFlags[DarklyServiceMock.FlagKeys.int]
expect(AnyComparer.isEqual(featureFlag?.value, to: updateDictionary.value)).to(beTrue())
expect(featureFlag?.variation).to(beNil())
expect(featureFlag?.version) == updateDictionary.version
}
}
context("when the update dictionary is missing the version") {
beforeEach {
updateDictionary = FlagMaintainingMock.stubPatchDictionary(key: DarklyServiceMock.FlagKeys.int,
value: DarklyServiceMock.FlagValues.alternate(DarklyServiceMock.FlagValues.int),
variation: DarklyServiceMock.Constants.variation + 1,
version: nil)
waitUntil { done in
testContext.flagStore.updateStore(updateDictionary: updateDictionary, completion: done)
}
}
it("updates the feature flag to the update value") {
let featureFlag = testContext.flagStore.featureFlags[DarklyServiceMock.FlagKeys.int]
expect(AnyComparer.isEqual(featureFlag?.value, to: updateDictionary.value)).to(beTrue())
expect(featureFlag?.variation) == updateDictionary.variation
expect(featureFlag?.version).to(beNil())
}
}
context("when the update dictionary has more keys than needed") {
beforeEach {
updateDictionary = FlagMaintainingMock.stubPatchDictionary(key: DarklyServiceMock.FlagKeys.int,
value: DarklyServiceMock.FlagValues.alternate(DarklyServiceMock.FlagValues.int),
variation: DarklyServiceMock.Constants.variation + 1,
version: DarklyServiceMock.Constants.version + 1,
includeExtraKey: true)
waitUntil { done in
testContext.flagStore.updateStore(updateDictionary: updateDictionary, completion: done)
}
}
it("updates the feature flag to the update value") {
let featureFlag = testContext.flagStore.featureFlags[DarklyServiceMock.FlagKeys.int]
expect(AnyComparer.isEqual(featureFlag?.value, to: updateDictionary.value)).to(beTrue())
expect(featureFlag?.variation) == updateDictionary.variation
expect(featureFlag?.version) == updateDictionary.version
}
}
}
}
func deleteFlagSpec() {
var testContext: TestContext!
var deleteDictionary: [String: Any]!
describe("deleteFlag") {
beforeEach {
testContext = TestContext()
}
context("when the flag exists") {
context("and the new version > existing version") {
beforeEach {
deleteDictionary = FlagMaintainingMock.stubDeleteDictionary(key: DarklyServiceMock.FlagKeys.int, version: DarklyServiceMock.Constants.version + 1)
waitUntil { done in
testContext.flagStore.deleteFlag(deleteDictionary: deleteDictionary, completion: done)
}
}
it("removes the feature flag from the store") {
expect(testContext.flagStore.featureFlags[DarklyServiceMock.FlagKeys.int]).to(beNil())
}
}
context("and the new version == existing version") {
beforeEach {
deleteDictionary = FlagMaintainingMock.stubDeleteDictionary(key: DarklyServiceMock.FlagKeys.int, version: DarklyServiceMock.Constants.version)
waitUntil { done in
testContext.flagStore.deleteFlag(deleteDictionary: deleteDictionary, completion: done)
}
}
it("makes no changes to the flag store") {
expect(testContext.flagStore.featureFlags) == testContext.featureFlags
}
}
context("and the new version < existing version") {
beforeEach {
deleteDictionary = FlagMaintainingMock.stubDeleteDictionary(key: DarklyServiceMock.FlagKeys.int, version: DarklyServiceMock.Constants.version - 1)
waitUntil { done in
testContext.flagStore.deleteFlag(deleteDictionary: deleteDictionary, completion: done)
}
}
it("makes no changes to the flag store") {
expect(testContext.flagStore.featureFlags) == testContext.featureFlags
}
}
}
context("when the flag doesn't exist") {
beforeEach {
deleteDictionary = FlagMaintainingMock.stubDeleteDictionary(key: FlagKeys.newInt, version: DarklyServiceMock.Constants.version + 1)
waitUntil { done in
testContext.flagStore.deleteFlag(deleteDictionary: deleteDictionary, completion: done)
}
}
it("makes no changes to the flag store") {
expect(testContext.flagStore.featureFlags) == testContext.featureFlags
}
}
context("when delete dictionary is missing the key") {
beforeEach {
deleteDictionary = FlagMaintainingMock.stubDeleteDictionary(key: nil, version: DarklyServiceMock.Constants.version + 1)
waitUntil { done in
testContext.flagStore.deleteFlag(deleteDictionary: deleteDictionary, completion: done)
}
}
it("makes no changes to the flag store") {
expect(testContext.flagStore.featureFlags) == testContext.featureFlags
}
}
context("when delete dictionary is missing the version") {
beforeEach {
deleteDictionary = FlagMaintainingMock.stubDeleteDictionary(key: DarklyServiceMock.FlagKeys.int, version: nil)
waitUntil { done in
testContext.flagStore.deleteFlag(deleteDictionary: deleteDictionary, completion: done)
}
}
it("makes no changes to the flag store") {
expect(testContext.flagStore.featureFlags) == testContext.featureFlags
}
}
}
}
func featureFlagSpec() {
var flagStore: FlagStore!
describe("featureFlag") {
beforeEach {
flagStore = FlagStore(featureFlags: DarklyServiceMock.Constants.stubFeatureFlags())
}
context("when flag key exists") {
it("returns the feature flag") {
flagStore.featureFlags.forEach { flagKey, featureFlag in
expect(flagStore.featureFlag(for: flagKey)?.allPropertiesMatch(featureFlag)).to(beTrue())
}
}
}
context("when flag key doesn't exist") {
it("returns nil") {
let featureFlag = flagStore.featureFlag(for: DarklyServiceMock.FlagKeys.unknown)
expect(featureFlag).to(beNil())
}
}
}
}
}
| 53.752475 | 170 | 0.506309 |
e0edfbd74891362e1309c46143963ff6e7feb6b9 | 3,908 | //
// JKBulletView.swift
// JKImageSlider
//
// Created by Jayesh Kawli Backup on 7/31/16.
// Copyright © 2016 Jayesh Kawli Backup. All rights reserved.
//
import UIKit
class JKBulletView: UIView {
let numberOfBullets: Int
var highlightedBulletImageView: UIImageView
var unhighlightedBulletViewsCollection: [UIImageView]
var highlightedBulletHorizontalConstraint: NSLayoutConstraint?
var animationDuration: CFTimeInterval = 0.75;
init(numberOfBullets: Int) {
self.numberOfBullets = numberOfBullets
self.highlightedBulletImageView = UIImageView(image: UIImage(named: "bullet_black"))
self.unhighlightedBulletViewsCollection = []
super.init(frame: CGRect.zero)
var previousBulletImageView: UIImageView?
for i in 0..<numberOfBullets {
let imageView = UIImageView()
imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.image = UIImage(named: "bullet_grey")
self.addSubview(imageView)
if i == 0 {
self.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-[imageView(30)]", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["imageView": imageView]))
} else if i == numberOfBullets - 1 {
if let previousImageView = previousBulletImageView {
self.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:[previousBulletImageView]-[imageView(30)]-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["imageView": imageView, "previousBulletImageView": previousImageView]))
}
} else {
if let previousImageView = previousBulletImageView {
self.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:[previousBulletImageView]-[imageView(30)]", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["imageView": imageView, "previousBulletImageView": previousImageView]))
}
}
self.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[imageView]|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["imageView": imageView]))
self.unhighlightedBulletViewsCollection.append(imageView)
previousBulletImageView = imageView
}
highlightedBulletImageView.translatesAutoresizingMaskIntoConstraints = false
self.addSubview(highlightedBulletImageView)
self.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[highlightedBulletImageView]|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["highlightedBulletImageView": highlightedBulletImageView]))
self.addConstraint(NSLayoutConstraint(item: highlightedBulletImageView, attribute: .Width, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1.0, constant: 30))
moveToIndex(0)
}
func moveToIndex(index: Int) {
let currentImageView = self.unhighlightedBulletViewsCollection[index]
if let highlightedBulletHorConstraint = highlightedBulletHorizontalConstraint {
self.removeConstraint(highlightedBulletHorConstraint)
}
let newConstraint = NSLayoutConstraint(item: highlightedBulletImageView, attribute: .CenterX, relatedBy: .Equal, toItem: currentImageView, attribute: .CenterX, multiplier: 1.0, constant: 0)
self.addConstraint(newConstraint)
if let _ = self.highlightedBulletHorizontalConstraint {
UIView.animateWithDuration(animationDuration) {
self.layoutIfNeeded()
}
}
self.highlightedBulletHorizontalConstraint = newConstraint
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| 52.106667 | 274 | 0.698823 |
2f56902aa35d1cd547002dacc1cb39b6be153466 | 22,883 |
// Warning: This file is automatically generated and your changes will be overwritten.
// See `Sources/Codegen/Readme.md` for more details.
/// Splom traces generate scatter plot matrix visualizations.
///
/// Each splom `dimensions` items correspond to a generated axis. Values for each of those
/// dimensions are set in `dimensions[i].values`. Splom traces support all `scattergl` marker style
/// attributes. Specify `layout.grid` attributes and/or layout x-axis and y-axis attributes for more
/// control over the axis positioning and style.
///
/// - SeeAlso:
/// Documentation for
/// [Python](https://plot.ly/python/reference/#splom),
/// [JavaScript](https://plot.ly/javascript/reference/#splom) or
/// [R](https://plot.ly/r/reference/#splom)
public struct ScatterPlotMatrix: Trace {
public let type: String = "splom"
public let animatable: Bool = false
/// Determines whether or not this trace is visible.
///
/// If *legendonly*, the trace is not drawn, but can appear as a legend item (provided that the
/// legend itself is visible).
public var visible: Shared.Visible? = nil
/// Determines whether or not an item corresponding to this trace is shown in the legend.
public var showLegend: Bool? = nil
/// Sets the legend group for this trace.
///
/// Traces part of the same legend group hide/show at the same time when toggling legend items.
public var legendGroup: String? = nil
/// Sets the trace name.
///
/// The trace name appear as the legend item and on hover.
public var name: String? = nil
/// Assign an id to this trace, Use this to provide object constancy between traces during
/// animations and transitions.
public var uid: String? = nil
/// Assigns id labels to each datum.
///
/// These ids for object constancy of data points during animation. Should be an array of strings,
/// not numbers or any other type.
public var ids: [String]? = nil
/// Assigns extra data each datum.
///
/// This may be useful when listening to hover, click and selection events. Note that, *scatter*
/// traces also appends customdata items in the markers DOM elements
public var customData: [String]? = nil
/// Assigns extra meta information associated with this trace that can be used in various text
/// attributes.
///
/// Attributes such as trace `name`, graph, axis and colorbar `title.text`, annotation `text`
/// `rangeselector`, `updatemenues` and `sliders` `label` text all support `meta`. To access the
/// trace `meta` values in an attribute in the same trace, simply use `%{meta[i]}` where `i` is the
/// index or key of the `meta` item in question. To access trace `meta` in layout attributes, use
/// `%{data[n[.meta[i]}` where `i` is the index or key of the `meta` and `n` is the trace index.
public var meta: Data<Anything>? = nil
/// Array containing integer indices of selected points.
///
/// Has an effect only for traces that support selections. Note that an empty array means an empty
/// selection where the `unselected` are turned on for all points, whereas, any other non-array
/// values means no selection all where the `selected` and `unselected` styles have no effect.
public var selectedPoints: Anything? = nil
/// Determines which trace information appear on hover.
///
/// If `none` or `skip` are set, no information is displayed upon hovering. But, if `none` is set,
/// click and hover events are still fired.
public var hoverInfo: Shared.HoverInfo? = nil
public var hoverLabel: Shared.HoverLabel? = nil
public var stream: Shared.Stream? = nil
public var transforms: [Transform] = []
/// Controls persistence of some user-driven changes to the trace: `constraintrange` in `parcoords`
/// traces, as well as some `editable: true` modifications such as `name` and `colorbar.title`.
///
/// Defaults to `layout.uirevision`. Note that other user-driven trace attribute changes are
/// controlled by `layout` attributes: `trace.visible` is controlled by `layout.legend.uirevision`,
/// `selectedpoints` is controlled by `layout.selectionrevision`, and `colorbar.(x|y)` (accessible
/// with `config: {editable: true}`) is controlled by `layout.editrevision`. Trace changes are
/// tracked by `uid`, which only falls back on trace index if no `uid` is provided. So if your app
/// can add/remove traces before the end of the `data` array, such that the same trace has a
/// different index, you can still preserve user-driven changes if you give each trace a `uid` that
/// stays with it as it moves.
public var uiRevision: Anything? = nil
public struct Dimension: Encodable {
/// Determines whether or not this dimension is shown on the graph.
///
/// Note that even visible false dimension contribute to the default grid generate by this splom
/// trace.
public var visible: Bool? = nil
/// Sets the label corresponding to this splom dimension.
public var label: String? = nil
/// Sets the dimension values to be plotted.
public var values: [Double]? = nil
public struct Axis: Encodable {
/// Sets the axis type for this dimension's generated x and y axes.
///
/// Note that the axis `type` values set in layout take precedence over this attribute.
public enum `Type`: String, Encodable {
case linear
case log
case date
case category
}
/// Sets the axis type for this dimension's generated x and y axes.
///
/// Note that the axis `type` values set in layout take precedence over this attribute.
public var type: `Type`? = nil
/// Determines whether or not the x & y axes generated by this dimension match.
///
/// Equivalent to setting the `matches` axis attribute in the layout with the correct axis id.
public var matches: Bool? = nil
/// Creates `Axis` object with specified properties.
///
/// - Parameters:
/// - type: Sets the axis type for this dimension's generated x and y axes.
/// - matches: Determines whether or not the x & y axes generated by this dimension match.
public init(type: `Type`? = nil, matches: Bool? = nil) {
self.type = type
self.matches = matches
}
}
public var axis: Axis? = nil
/// When used in a template, named items are created in the output figure in addition to any items
/// the figure already has in this array.
///
/// You can modify these items in the output figure by making your own item with `templateitemname`
/// matching this `name` alongside your modifications (including `visible: false` or `enabled:
/// false` to hide it). Has no effect outside of a template.
public var name: String? = nil
/// Used to refer to a named item in this array in the template.
///
/// Named items from the template will be created even without a matching item in the input figure,
/// but you can modify one by making an item with `templateitemname` matching its `name`, alongside
/// your modifications (including `visible: false` or `enabled: false` to hide it). If there is no
/// template or no matching item, this item will be hidden unless you explicitly show it with
/// `visible: true`.
public var templateItemName: String? = nil
/// Decoding and encoding keys compatible with Plotly schema.
enum CodingKeys: String, CodingKey {
case visible
case label
case values
case axis
case name
case templateItemName = "templateitemname"
}
/// Creates `Dimension` object with specified properties.
///
/// - Parameters:
/// - visible: Determines whether or not this dimension is shown on the graph.
/// - label: Sets the label corresponding to this splom dimension.
/// - values: Sets the dimension values to be plotted.
/// - axis:
/// - name: When used in a template, named items are created in the output figure in addition to any
/// items the figure already has in this array.
/// - templateItemName: Used to refer to a named item in this array in the template.
public init(visible: Bool? = nil, label: String? = nil, values: [Double]? = nil, axis: Axis? =
nil, name: String? = nil, templateItemName: String? = nil) {
self.visible = visible
self.label = label
self.values = values
self.axis = axis
self.name = name
self.templateItemName = templateItemName
}
}
public var dimensions: [Dimension]? = nil
/// Sets text elements associated with each (x,y) pair to appear on hover.
///
/// If a single string, the same string appears over all the data points. If an array of string, the
/// items are mapped in order to the this trace's (x,y) coordinates.
public var text: Data<String>? = nil
/// Same as `text`.
public var hoverText: Data<String>? = nil
/// Template string used for rendering the information that appear on hover box.
///
/// Note that this will override `hoverinfo`. Variables are inserted using %{variable}, for example
/// "y: %{y}". Numbers are formatted using d3-format's syntax %{variable:d3-format}, for example
/// "Price: %{y:$.2f}".
/// https://github.com/d3/d3-3.x-api-reference/blob/master/Formatting.md#d3_format for details on
/// the formatting syntax. Dates are formatted using d3-time-format's syntax
/// %{variable|d3-time-format}, for example "Day: %{2019-01-01|%A}".
/// https://github.com/d3/d3-3.x-api-reference/blob/master/Time-Formatting.md#format for details on
/// the date formatting syntax. The variables available in `hovertemplate` are the ones emitted as
/// event data described at this link https://plot.ly/javascript/plotlyjs-events/#event-data.
/// Additionally, every attributes that can be specified per-point (the ones that are `arrayOk:
/// true`) are available. Anything contained in tag `<extra>` is displayed in the secondary box, for
/// example "<extra>{fullData.name}</extra>". To hide the secondary box completely, use an empty tag
/// `<extra></extra>`.
public var hoverTemplate: Data<String>? = nil
public var marker: Shared.SymbolicMarker? = nil
/// Sets the list of x axes corresponding to dimensions of this splom trace.
///
/// By default, a splom will match the first N xaxes where N is the number of input dimensions. Note
/// that, in case where `diagonal.visible` is false and `showupperhalf` or `showlowerhalf` is false,
/// this splom trace will generate one less x-axis and one less y-axis.
public var xAxes: InfoArray? = nil
/// Sets the list of y axes corresponding to dimensions of this splom trace.
///
/// By default, a splom will match the first N yaxes where N is the number of input dimensions. Note
/// that, in case where `diagonal.visible` is false and `showupperhalf` or `showlowerhalf` is false,
/// this splom trace will generate one less x-axis and one less y-axis.
public var yAxes: InfoArray? = nil
public struct Diagonal: Encodable {
/// Determines whether or not subplots on the diagonal are displayed.
public var visible: Bool? = nil
/// Creates `Diagonal` object with specified properties.
///
/// - Parameters:
/// - visible: Determines whether or not subplots on the diagonal are displayed.
public init(visible: Bool? = nil) {
self.visible = visible
}
}
public var diagonal: Diagonal? = nil
/// Determines whether or not subplots on the upper half from the diagonal are displayed.
public var showUpperHalf: Bool? = nil
/// Determines whether or not subplots on the lower half from the diagonal are displayed.
public var showLowerHalf: Bool? = nil
public struct Selected: Encodable {
public struct Marker: Encodable {
/// Sets the marker opacity of selected points.
public var opacity: Double? = nil
/// Sets the marker color of selected points.
public var color: Color? = nil
/// Sets the marker size of selected points.
public var size: Double? = nil
/// Creates `Marker` object with specified properties.
///
/// - Parameters:
/// - opacity: Sets the marker opacity of selected points.
/// - color: Sets the marker color of selected points.
/// - size: Sets the marker size of selected points.
public init(opacity: Double? = nil, color: Color? = nil, size: Double? = nil) {
self.opacity = opacity
self.color = color
self.size = size
}
}
public var marker: Marker? = nil
/// Creates `Selected` object with specified properties.
public init(marker: Marker? = nil) {
self.marker = marker
}
}
public var selected: Selected? = nil
public struct Unselected: Encodable {
public struct Marker: Encodable {
/// Sets the marker opacity of unselected points, applied only when a selection exists.
public var opacity: Double? = nil
/// Sets the marker color of unselected points, applied only when a selection exists.
public var color: Color? = nil
/// Sets the marker size of unselected points, applied only when a selection exists.
public var size: Double? = nil
/// Creates `Marker` object with specified properties.
///
/// - Parameters:
/// - opacity: Sets the marker opacity of unselected points, applied only when a selection exists.
/// - color: Sets the marker color of unselected points, applied only when a selection exists.
/// - size: Sets the marker size of unselected points, applied only when a selection exists.
public init(opacity: Double? = nil, color: Color? = nil, size: Double? = nil) {
self.opacity = opacity
self.color = color
self.size = size
}
}
public var marker: Marker? = nil
/// Creates `Unselected` object with specified properties.
public init(marker: Marker? = nil) {
self.marker = marker
}
}
public var unselected: Unselected? = nil
/// Sets the opacity of the trace.
public var opacity: Double? = nil
/// Decoding and encoding keys compatible with Plotly schema.
enum CodingKeys: String, CodingKey {
case type
case visible
case showLegend = "showlegend"
case legendGroup = "legendgroup"
case name
case uid
case ids
case customData = "customdata"
case meta
case selectedPoints = "selectedpoints"
case hoverInfo = "hoverinfo"
case hoverLabel = "hoverlabel"
case stream
case transforms
case uiRevision = "uirevision"
case dimensions
case text
case hoverText = "hovertext"
case hoverTemplate = "hovertemplate"
case marker
case xAxes = "xaxes"
case yAxes = "yaxes"
case diagonal
case showUpperHalf = "showupperhalf"
case showLowerHalf = "showlowerhalf"
case selected
case unselected
case opacity
}
/// Creates `ScatterPlotMatrix` object from the most frequently used properties.
///
/// - Parameters:
/// - name: Sets the trace name.
/// - text: Sets text elements associated with each (x,y) pair to appear on hover.
/// - hoverText: Same as `text`.
/// - marker:
public init(name: String? = nil, text: Data<String>? = nil, hoverText: Data<String>? = nil,
marker: Shared.SymbolicMarker? = nil) {
self.name = name
self.text = text
self.hoverText = hoverText
self.marker = marker
}
/// Creates `ScatterPlotMatrix` object with specified properties.
///
/// - Parameters:
/// - visible: Determines whether or not this trace is visible.
/// - showLegend: Determines whether or not an item corresponding to this trace is shown in the
/// legend.
/// - legendGroup: Sets the legend group for this trace.
/// - name: Sets the trace name.
/// - uid: Assign an id to this trace, Use this to provide object constancy between traces during
/// animations and transitions.
/// - ids: Assigns id labels to each datum.
/// - customData: Assigns extra data each datum.
/// - meta: Assigns extra meta information associated with this trace that can be used in various
/// text attributes.
/// - selectedPoints: Array containing integer indices of selected points.
/// - hoverInfo: Determines which trace information appear on hover.
/// - hoverLabel:
/// - stream:
/// - transforms:
/// - uiRevision: Controls persistence of some user-driven changes to the trace: `constraintrange`
/// in `parcoords` traces, as well as some `editable: true` modifications such as `name` and
/// `colorbar.title`.
/// - dimensions:
/// - text: Sets text elements associated with each (x,y) pair to appear on hover.
/// - hoverText: Same as `text`.
/// - hoverTemplate: Template string used for rendering the information that appear on hover box.
/// - marker:
/// - xAxes: Sets the list of x axes corresponding to dimensions of this splom trace.
/// - yAxes: Sets the list of y axes corresponding to dimensions of this splom trace.
/// - diagonal:
/// - showUpperHalf: Determines whether or not subplots on the upper half from the diagonal are
/// displayed.
/// - showLowerHalf: Determines whether or not subplots on the lower half from the diagonal are
/// displayed.
/// - selected:
/// - unselected:
/// - opacity: Sets the opacity of the trace.
public init(visible: Shared.Visible? = nil, showLegend: Bool? = nil, legendGroup: String? = nil,
name: String? = nil, uid: String? = nil, ids: [String]? = nil, customData: [String]? = nil,
meta: Data<Anything>? = nil, selectedPoints: Anything? = nil, hoverInfo: Shared.HoverInfo? =
nil, hoverLabel: Shared.HoverLabel? = nil, stream: Shared.Stream? = nil, transforms: [Transform]
= [], uiRevision: Anything? = nil, dimensions: [Dimension]? = nil, text: Data<String>? = nil,
hoverText: Data<String>? = nil, hoverTemplate: Data<String>? = nil, marker:
Shared.SymbolicMarker? = nil, xAxes: InfoArray? = nil, yAxes: InfoArray? = nil, diagonal:
Diagonal? = nil, showUpperHalf: Bool? = nil, showLowerHalf: Bool? = nil, selected: Selected? =
nil, unselected: Unselected? = nil, opacity: Double? = nil) {
self.visible = visible
self.showLegend = showLegend
self.legendGroup = legendGroup
self.name = name
self.uid = uid
self.ids = ids
self.customData = customData
self.meta = meta
self.selectedPoints = selectedPoints
self.hoverInfo = hoverInfo
self.hoverLabel = hoverLabel
self.stream = stream
self.transforms = transforms
self.uiRevision = uiRevision
self.dimensions = dimensions
self.text = text
self.hoverText = hoverText
self.hoverTemplate = hoverTemplate
self.marker = marker
self.xAxes = xAxes
self.yAxes = yAxes
self.diagonal = diagonal
self.showUpperHalf = showUpperHalf
self.showLowerHalf = showLowerHalf
self.selected = selected
self.unselected = unselected
self.opacity = opacity
}
/// Encodes the object in a format compatible with Plotly.
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(type, forKey: .type)
try container.encodeIfPresent(visible, forKey: .visible)
try container.encodeIfPresent(showLegend, forKey: .showLegend)
try container.encodeIfPresent(legendGroup, forKey: .legendGroup)
try container.encodeIfPresent(name, forKey: .name)
try container.encodeIfPresent(uid, forKey: .uid)
try container.encodeIfPresent(ids, forKey: .ids)
try container.encodeIfPresent(customData, forKey: .customData)
try container.encodeIfPresent(meta, forKey: .meta)
try container.encodeIfPresent(selectedPoints, forKey: .selectedPoints)
try container.encodeIfPresent(hoverInfo, forKey: .hoverInfo)
try container.encodeIfPresent(hoverLabel, forKey: .hoverLabel)
try container.encodeIfPresent(stream, forKey: .stream)
var transformsContainer = container.nestedUnkeyedContainer(forKey: .transforms)
for transform in transforms { try transform.encode(to: transformsContainer.superEncoder()) }
try container.encodeIfPresent(uiRevision, forKey: .uiRevision)
try container.encodeIfPresent(dimensions, forKey: .dimensions)
try container.encodeIfPresent(text, forKey: .text)
try container.encodeIfPresent(hoverText, forKey: .hoverText)
try container.encodeIfPresent(hoverTemplate, forKey: .hoverTemplate)
try container.encodeIfPresent(marker, forKey: .marker)
try container.encodeIfPresent(xAxes, forKey: .xAxes)
try container.encodeIfPresent(yAxes, forKey: .yAxes)
try container.encodeIfPresent(diagonal, forKey: .diagonal)
try container.encodeIfPresent(showUpperHalf, forKey: .showUpperHalf)
try container.encodeIfPresent(showLowerHalf, forKey: .showLowerHalf)
try container.encodeIfPresent(selected, forKey: .selected)
try container.encodeIfPresent(unselected, forKey: .unselected)
try container.encodeIfPresent(opacity, forKey: .opacity)
}
} | 47.181443 | 112 | 0.633789 |
ac2ac8d7408337cbb46eb39bbce2053e68358d37 | 899 | //
// MedalsHelper.swift
// Elite
//
// Created by Leandro Wauters on 10/31/19.
// Copyright © 2019 Pritesh Nadiadhara. All rights reserved.
//
import Foundation
import UIKit
struct MedalsHelper {
static let eliteImage = UIImage(named: "Elite")!
static let bronzeMedalImage = UIImage(named: "bronzeMedal")!
static let silverMedalImage = UIImage(named: "silverMedal")!
static let goldMedalImage = UIImage(named: "goldMedal")!
static let platinumMedalImage = UIImage(named: "platinumMedal")!
static let diamondMedalImage = UIImage(named: "diamondMedal")!
let medals = [1 : eliteImage, 2 : diamondMedalImage, 3 : platinumMedalImage, 4 : goldMedalImage, 5 : silverMedalImage, 6 : bronzeMedalImage]
func getMedalImages(ranking: Int) -> UIImage? {
if let image = medals[ranking] {
return image
}
return nil
}
}
| 29.966667 | 145 | 0.675195 |
26af7d30c3a28f5f9a781b8ef8467d31b0398399 | 321 | //
// ChatErrorVideoCell.swift
// LiveChat
//
// Created by Ali Ammar Hilal on 16.05.2021.
//
import UIKit
final class ChatErrorVideoCell: ChatVideoMessageCell {
override func layoutViews() {
errorView.isHidden = false
fileFormatIcon.setSize(.init(width: 20, height: 24))
fileStack.centerInSuperview()
}
}
| 17.833333 | 54 | 0.725857 |
9bba8c1070a90d605fead5f579a557836bc0db08 | 1,797 | //
// Copyright © 2019 xcodereleases.com
// MIT license - see LICENSE.md
//
import ArgumentParser
import xcinfoCore
extension XCInfo {
struct Install: ParsableCommand {
static var configuration = CommandConfiguration(
abstract: "Install an Xcode version",
discussion: "Install a specific version of Xcode."
)
@OptionGroup()
var globals: DefaultOptions
@Argument(
help: "A version number of an Xcode version or `latest`.",
transform: XcodeVersion.init
)
var xcodeVersion: XcodeVersion
@Flag(default: true, inversion: .prefixedNo,
help: "Update the list of known Xcode versions."
)
var updateList: Bool
@Flag(
name: [.customLong("sleep")],
default: false,
inversion: .prefixedNo,
help: "Let the system sleep during execution."
)
var disableSleep: Bool
@Flag(
name: [.customLong("no-symlink")],
help: "Skip creating a symbolic link to `/Applications/Xcode.app`."
)
var skipSymlinkCreation: Bool
@Flag(
name: [.customLong("no-xcode-select")],
help: "Skip selecting the new Xcode version as the current Command Line Tools."
)
var skipXcodeSelection: Bool
func run() throws {
let core = xcinfoCore(verbose: globals.isVerbose, useANSI: globals.useANSI)
core.install(releaseName: xcodeVersion.asString(),
updateVersionList: updateList,
disableSleep: disableSleep,
skipSymlinkCreation: skipSymlinkCreation,
skipXcodeSelection: true)
}
}
}
| 29.95 | 91 | 0.570395 |
38f7d7105868563a02826ed92d30558b5adb0c45 | 1,267 | // RateLimiter
//
// Copyright (c) 2021 elfenlaid
//
// 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 Logging
public struct RateLimiter {
public static func setLogLevel(_ level: Logger.Level) {
log.logLevel = level
}
}
| 42.233333 | 81 | 0.754538 |
4af9b0e96d3541e8a7305f90843ee1609ee437f9 | 4,609 | //
// retryWithBehavior.swift
// RxSwiftExt
//
// Created by Anton Efimenko on 17/07/16.
// Copyright © 2016 RxSwift Community. All rights reserved.
//
import Foundation
import RxSwift
/**
Specifies how observable sequence will be repeated in case of an error
- Immediate: Will be immediatelly repeated specified number of times
- Delayed: Will be repeated after specified delay specified number of times
- ExponentialDelayed: Will be repeated specified number of times.
Delay will be incremented by multiplier after each iteration (multiplier = 0.5 means 50% increment)
- CustomTimerDelayed: Will be repeated specified number of times. Delay will be calculated by custom closure
*/
public enum RepeatBehavior {
case immediate (maxCount: UInt)
case delayed (maxCount: UInt, time: Double)
case exponentialDelayed (maxCount: UInt, initial: Double, multiplier: Double)
case customTimerDelayed (maxCount: UInt, delayCalculator: (UInt) -> DispatchTimeInterval)
}
public typealias RetryPredicate = (Error) -> Bool
extension RepeatBehavior {
/**
Extracts maxCount and calculates delay for current RepeatBehavior
- parameter currentAttempt: Number of current attempt
- returns: Tuple with maxCount and calculated delay for provided attempt
*/
func calculateConditions(_ currentRepetition: UInt) -> (maxCount: UInt, delay: DispatchTimeInterval) {
switch self {
case .immediate(let max):
// if Immediate, return 0.0 as delay
return (maxCount: max, delay: .never)
case .delayed(let max, let time):
// return specified delay
return (maxCount: max, delay: .milliseconds(Int(time * 1000)))
case .exponentialDelayed(let max, let initial, let multiplier):
// if it's first attempt, simply use initial delay, otherwise calculate delay
let delay = currentRepetition == 1 ? initial : initial * pow(1 + multiplier, Double(currentRepetition - 1))
return (maxCount: max, delay: .milliseconds(Int(delay * 1000)))
case .customTimerDelayed(let max, let delayCalculator):
// calculate delay using provided calculator
return (maxCount: max, delay: delayCalculator(currentRepetition))
}
}
}
extension ObservableType {
/**
Repeats the source observable sequence using given behavior in case of an error or until it successfully terminated
- parameter behavior: Behavior that will be used in case of an error
- parameter scheduler: Schedular that will be used for delaying subscription after error
- parameter shouldRetry: Custom optional closure for checking error (if returns true, repeat will be performed)
- returns: Observable sequence that will be automatically repeat if error occurred
*/
public func retry(_ behavior: RepeatBehavior, scheduler: SchedulerType = MainScheduler.instance, shouldRetry: RetryPredicate? = nil) -> Observable<Element> {
return retry(1, behavior: behavior, scheduler: scheduler, shouldRetry: shouldRetry)
}
/**
Repeats the source observable sequence using given behavior in case of an error or until it successfully terminated
- parameter currentAttempt: Number of current attempt
- parameter behavior: Behavior that will be used in case of an error
- parameter scheduler: Schedular that will be used for delaying subscription after error
- parameter shouldRetry: Custom optional closure for checking error (if returns true, repeat will be performed)
- returns: Observable sequence that will be automatically repeat if error occurred
*/
internal func retry(_ currentAttempt: UInt, behavior: RepeatBehavior, scheduler: SchedulerType = MainScheduler.instance, shouldRetry: RetryPredicate? = nil)
-> Observable<Element> {
guard currentAttempt > 0 else { return Observable.empty() }
// calculate conditions for bahavior
let conditions = behavior.calculateConditions(currentAttempt)
return catchError { error -> Observable<Element> in
// return error if exceeds maximum amount of retries
guard conditions.maxCount > currentAttempt else { return Observable.error(error) }
if let shouldRetry = shouldRetry, !shouldRetry(error) {
// also return error if predicate says so
return Observable.error(error)
}
guard conditions.delay != .never else {
// if there is no delay, simply retry
return self.retry(currentAttempt + 1, behavior: behavior, scheduler: scheduler, shouldRetry: shouldRetry)
}
// otherwise retry after specified delay
return Observable<Void>.just(()).delaySubscription(conditions.delay, scheduler: scheduler).flatMapLatest {
self.retry(currentAttempt + 1, behavior: behavior, scheduler: scheduler, shouldRetry: shouldRetry)
}
}
}
}
| 43.895238 | 158 | 0.76112 |
03f140fcb189030723d9dbd049c3350e509a07b1 | 4,746 | //
// Copyright (C) 2017-2021 HERE Europe B.V.
//
// 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 EarlGrey
@testable import MSDKUI
import NMAKit
enum WaypointActions {
/// Checks a waypoint name.
///
/// - Parameter matcher: The GREYMatcher of the targeted element.
/// - Parameter expectedName: The expected name of the waypoint.
static func checkWaypointName(withId matcher: GREYMatcher, expectedName: String?) {
GREYAssertNotNil(expectedName, reason: "A comparison string is provided")
EarlGrey.selectElement(with: matcher).perform(
GREYActionBlock.action(withName: "checkWaypointName") { element, errorOrNil in
guard
errorOrNil != nil,
let cell = element as? UITableViewCell,
let item = RoutePlannerActions.getWaypointItem(inside: cell) else {
return false
}
// Does the waypoint name match the expected name?
return item.entry.name == expectedName
}
)
}
/// Checks if "To" label is displayed
///
/// - Parameter matcher: The GREYMatcher of the targeted element.
static func checkWaypointToLabelDisplayed(forWaypoint matcher: GREYMatcher) {
checkWaypointLabel(forWaypoint: matcher, labelToTest: TestStrings.to, shouldBeDisplayed: true)
}
/// Checks if "From" label is displayed
///
/// - Parameter matcher: The GREYMatcher of the targeted element.
static func checkWaypointFromLabelDisplayed(forWaypoint matcher: GREYMatcher) {
checkWaypointLabel(forWaypoint: matcher, labelToTest: TestStrings.from, shouldBeDisplayed: true)
}
/// Checks if "To" label is hidden
///
/// - Parameter matcher: The GREYMatcher of the targeted element.
static func checkWaypointToLabelHidden(forWaypoint matcher: GREYMatcher) {
checkWaypointLabel(forWaypoint: matcher, labelToTest: TestStrings.to, shouldBeDisplayed: false)
}
/// Checks if "From" label is hidden
///
/// - Parameter matcher: The GREYMatcher of the targeted element.
static func checkWaypointFromLabelHidden(forWaypoint matcher: GREYMatcher) {
checkWaypointLabel(forWaypoint: matcher, labelToTest: TestStrings.from, shouldBeDisplayed: false)
}
/// Checks if specified label has correct visibility for waypoint
///
/// - Parameter matcher: The GREYMatcher of the targeted element.
/// - Parameter labelToTest: Label string that will be checked.
/// - Parameter shouldBeDisaplyed: true if label should be visible, false otherwise.
private static func checkWaypointLabel(forWaypoint matcher: GREYMatcher, labelToTest: String, shouldBeDisplayed: Bool) {
EarlGrey.selectElement(with: matcher).perform(
GREYActionBlock.action(withName: "checkWaypointLabel") { element, errorOrNil in
guard
errorOrNil != nil,
let cell = element as? UITableViewCell,
let item = RoutePlannerActions.getWaypointItem(inside: cell) else {
return false
}
// Label must not be nil
GREYAssertNotNil(item.label.text, reason: "Waypoint label must not be nil!")
let isDisplayed = item.label.text?.starts(with: labelToTest) ?? false
return shouldBeDisplayed == isDisplayed
}
)
}
/// Sets current map view to new coordinates.
///
/// - Parameter mapData: Latitude and longitude coordinates.
static func switchMapViewTo(mapData: NMAGeoCoordinates) {
EarlGrey.selectElement(with: WaypointMatchers.waypointMapView).perform(
GREYActionBlock.action(withName: "Set map geo center to coordinates") { element, errorOrNil in
guard
errorOrNil != nil,
let mapView = element as? NMAMapView else {
return false
}
// Center current map view to specified coordinates
mapView.set(geoCenter: mapData, animation: .none)
return true
}
)
}
}
| 41.269565 | 124 | 0.647914 |
902f72f7558b44c4c4c8c04a075649f8fc898db6 | 1,707 | /**
* Copyright IBM Corporation 2018
*
* 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
/**
Tokenization dictionary describing how words are tokenized during ingestion and at query time.
*/
internal struct TokenDict: Codable, Equatable {
/**
An array of tokenization rules. Each rule contains, the original `text` string, component `tokens`, any alternate
character set `readings`, and which `part_of_speech` the text is from.
*/
public var tokenizationRules: [TokenDictRule]?
// Map each property name to the key that shall be used for encoding/decoding.
private enum CodingKeys: String, CodingKey {
case tokenizationRules = "tokenization_rules"
}
/**
Initialize a `TokenDict` with member variables.
- parameter tokenizationRules: An array of tokenization rules. Each rule contains, the original `text` string,
component `tokens`, any alternate character set `readings`, and which `part_of_speech` the text is from.
- returns: An initialized `TokenDict`.
*/
public init(
tokenizationRules: [TokenDictRule]? = nil
)
{
self.tokenizationRules = tokenizationRules
}
}
| 33.470588 | 118 | 0.714118 |
7297a8a651dc08df59a37ded9d755c62431147fa | 1,393 | //
// ArticleDetailViewController.swift
// KenticoCloud
//
// Created by Martin Makarsky on 21/08/2017.
// Copyright © 2017 Kentico Software. All rights reserved.
//
import UIKit
class ArticleDetailViewController: UIViewController {
// MARK: Properties
var article: Article?
var image: UIImage?
@IBOutlet weak var articleTitle: UILabel!
@IBOutlet weak var titleImage: UIImageView!
@IBOutlet weak var scrollView: UIScrollView!
@IBOutlet weak var contentView: UIView!
@IBOutlet var content: UILabel!
@IBOutlet var backButton: UIButton!
// MARK: Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewWillAppear(_ animated: Bool) {
backButton.stylePinkButton()
if let body = article?.bodyCopy?.htmlContentString {
content.styleWithRichtextString(richtextString: body)
}
if let image = image {
titleImage.image = image
}
if let article = article{
self.articleTitle.text = article.title?.value
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
// MARK: Outlet actions
@IBAction func navigateBack(_ sender: Any) {
_ = navigationController?.popViewController(animated: true)
}
}
| 24.438596 | 67 | 0.63173 |
5bf5ba15d1b40282cf7cc295dba904dcc3ec6b82 | 8,962 | //
// Extensions.swift
// JZCalendarWeekView
//
// Created by Jeff Zhang on 16/4/18.
// Copyright © 2018 Jeff Zhang. All rights reserved.
//
import UIKit
extension NSObject {
static var className: String {
return String(describing: self)
}
}
extension UICollectionView {
func setContentOffsetWithoutDelegate(_ contentOffset: CGPoint, animated: Bool) {
let tempDelegate = self.delegate
self.delegate = nil
self.setContentOffset(contentOffset, animated: animated)
self.delegate = tempDelegate
}
}
// Anchor Constraints from JZiOSFramework
extension UIView {
func setAnchorConstraintsEqualTo(widthAnchor: CGFloat?=nil, heightAnchor: CGFloat?=nil, centerXAnchor: NSLayoutXAxisAnchor?=nil, centerYAnchor: NSLayoutYAxisAnchor?=nil) {
self.translatesAutoresizingMaskIntoConstraints = false
if let width = widthAnchor{
self.widthAnchor.constraint(equalToConstant: width).isActive = true
}
if let height = heightAnchor{
self.heightAnchor.constraint(equalToConstant: height).isActive = true
}
if let centerX = centerXAnchor{
self.centerXAnchor.constraint(equalTo: centerX).isActive = true
}
if let centerY = centerYAnchor{
self.centerYAnchor.constraint(equalTo: centerY).isActive = true
}
}
// bottomAnchor & trailingAnchor should be negative
func setAnchorConstraintsEqualTo(widthAnchor: CGFloat?=nil, heightAnchor: CGFloat?=nil, topAnchor: (NSLayoutYAxisAnchor,CGFloat)?=nil, bottomAnchor: (NSLayoutYAxisAnchor,CGFloat)?=nil, leadingAnchor: (NSLayoutXAxisAnchor,CGFloat)?=nil, trailingAnchor: (NSLayoutXAxisAnchor,CGFloat)?=nil) {
self.translatesAutoresizingMaskIntoConstraints = false
if let width = widthAnchor{
self.widthAnchor.constraint(equalToConstant: width).isActive = true
}
if let height = heightAnchor{
self.heightAnchor.constraint(equalToConstant: height).isActive = true
}
if let topY = topAnchor{
self.topAnchor.constraint(equalTo: topY.0, constant: topY.1).isActive = true
}
if let botY = bottomAnchor{
self.bottomAnchor.constraint(equalTo: botY.0, constant: botY.1).isActive = true
}
if let leadingX = leadingAnchor{
self.leadingAnchor.constraint(equalTo: leadingX.0, constant: leadingX.1).isActive = true
}
if let trailingX = trailingAnchor{
self.trailingAnchor.constraint(equalTo: trailingX.0, constant: trailingX.1).isActive = true
}
}
func setAnchorCenterVerticallyTo(view: UIView, widthAnchor: CGFloat?=nil, heightAnchor: CGFloat?=nil, leadingAnchor: (NSLayoutXAxisAnchor,CGFloat)?=nil, trailingAnchor: (NSLayoutXAxisAnchor,CGFloat)?=nil) {
self.translatesAutoresizingMaskIntoConstraints = false
setAnchorConstraintsEqualTo(widthAnchor: widthAnchor, heightAnchor: heightAnchor, centerYAnchor: view.centerYAnchor)
if let leadingX = leadingAnchor{
self.leadingAnchor.constraint(equalTo: leadingX.0, constant: leadingX.1).isActive = true
}
if let trailingX = trailingAnchor{
self.trailingAnchor.constraint(equalTo: trailingX.0, constant: trailingX.1).isActive = true
}
}
func setAnchorCenterHorizontallyTo(view: UIView, widthAnchor: CGFloat?=nil, heightAnchor: CGFloat?=nil, topAnchor: (NSLayoutYAxisAnchor,CGFloat)?=nil, bottomAnchor: (NSLayoutYAxisAnchor,CGFloat)?=nil) {
self.translatesAutoresizingMaskIntoConstraints = false
setAnchorConstraintsEqualTo(widthAnchor: widthAnchor, heightAnchor: heightAnchor, centerXAnchor: view.centerXAnchor)
if let topY = topAnchor{
self.topAnchor.constraint(equalTo: topY.0, constant: topY.1).isActive = true
}
if let botY = bottomAnchor{
self.bottomAnchor.constraint(equalTo: botY.0, constant: botY.1).isActive = true
}
}
func setAnchorConstraintsFullSizeTo(view: UIView, padding: CGFloat = 0) {
self.translatesAutoresizingMaskIntoConstraints = false
self.topAnchor.constraint(equalTo: view.topAnchor, constant: padding).isActive = true
self.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -padding).isActive = true
self.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: padding).isActive = true
self.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -padding).isActive = true
}
func addSubviews(_ views: [UIView]) {
views.forEach({ self.addSubview($0)})
}
var snapshot: UIImage? {
UIGraphicsBeginImageContextWithOptions(bounds.size, false, UIScreen.main.scale)
drawHierarchy(in: bounds, afterScreenUpdates: true)
let result = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return result
}
func setDefaultShadow() {
self.layer.shadowColor = UIColor.black.cgColor
self.layer.shadowOpacity = 0.05
self.layer.shadowOffset = CGSize.zero
self.layer.shadowRadius = 4
self.layer.masksToBounds = false
}
}
extension UILabel {
class func getLabelWidth(_ height:CGFloat, font:UIFont, text:String) -> CGFloat{
let label = UILabel(frame: CGRect(x: 0, y: 0, width: .greatestFiniteMagnitude, height: height))
label.font = font
label.numberOfLines = 0
label.text = text
label.sizeToFit()
return label.frame.width
}
}
extension Date {
var isToday: Bool {
return Calendar.current.isDateInToday(self)
}
var isYesterday: Bool {
return Calendar.current.isDateInYesterday(self)
}
var isTomorrow: Bool {
return Calendar.current.isDateInTomorrow(self)
}
static func getCurrentWeekDays(firstDayOfWeek: DayOfWeek?=nil) -> [Date] {
var calendar = Calendar.current
calendar.firstWeekday = (firstDayOfWeek ?? .Sunday).rawValue
let today = calendar.startOfDay(for: Date())
let dayOfWeek = calendar.component(.weekday, from: today)
let weekdays = calendar.range(of: .weekday, in: .weekOfYear, for: today)!
let days = (weekdays.lowerBound ..< weekdays.upperBound).compactMap { calendar.date(byAdding: .day, value: $0 - dayOfWeek, to: today) }
return days
}
func add(component: Calendar.Component, value: Int) -> Date {
return Calendar.current.date(byAdding: component, value: value, to: self)!
}
var startOfDay: Date {
return Calendar.current.startOfDay(for: self)
}
var endOfDay: Date {
return self.set(hour: 23, minute: 59, second: 59)
}
func getDayOfWeek() -> DayOfWeek {
let weekDayNum = Calendar.current.component(.weekday, from: self)
let weekDay = DayOfWeek(rawValue: weekDayNum)!
return weekDay
}
func getTimeIgnoreSecondsFormat() -> String {
let formatter = DateFormatter()
formatter.dateFormat = "HH:mm"
return formatter.string(from: self)
}
static func daysBetween(start: Date, end: Date, ignoreHours: Bool) -> Int {
let startDate = ignoreHours ? start.startOfDay : start
let endDate = ignoreHours ? end.startOfDay : end
return Calendar.current.dateComponents([.day], from: startDate, to: endDate).day!
}
static let components: Set<Calendar.Component> = [.year, .month, .day, .hour, .minute, .second, .weekday]
private var dateComponents: DateComponents {
return Calendar.current.dateComponents(Date.components, from: self)
}
var year: Int { return dateComponents.year! }
var month: Int { return dateComponents.month! }
var day: Int { return dateComponents.day! }
var hour: Int { return dateComponents.hour! }
var minute: Int { return dateComponents.minute! }
var second: Int { return dateComponents.second! }
var weekday: Int { return dateComponents.weekday! }
func set(year: Int?=nil, month: Int?=nil, day: Int?=nil, hour: Int?=nil, minute: Int?=nil, second: Int?=nil, tz: String?=nil) -> Date {
let timeZone = Calendar.current.timeZone
let year = year ?? self.year
let month = month ?? self.month
let day = day ?? self.day
let hour = hour ?? self.hour
let minute = minute ?? self.minute
let second = second ?? self.second
let dateComponents = DateComponents(timeZone:timeZone, year:year, month:month, day:day, hour:hour, minute:minute, second:second)
let date = Calendar.current.date(from: dateComponents)
return date!
}
}
| 38.965217 | 293 | 0.658447 |
20be6cd37497cc4ff0dead956b30e21b34009102 | 1,436 | //
// UICollectionViewDelegateDatasource.swift
// LearningShotUIKit
//
// Created by Mateus de Campos on 03/01/17.
// Copyright © 2017 Mateus Campos. All rights reserved.
//
import UIKit
class UICollectionViewDelegateDatasource: NSObject, UICollectionViewDelegate, UICollectionViewDataSource {
var data:Array<AnyObject>?
var selectionDelegate: SelectionProtocol?
init(data:Array<AnyObject>?, selectionDelegate: SelectionProtocol?) {
self.data = data
self.selectionDelegate = selectionDelegate
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
if let count = self.data?.count {
return count
}
return 0
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "UICollectionViewCustonCellIdentifier", for: indexPath) as? UICollectionViewCustonCell
if let color = data?[indexPath.row]{
cell?.setup(color: color as! UIColor)
}
return cell!
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
if let color = data?[indexPath.row]{
self.selectionDelegate?.didSelectedColor(color: color as! UIColor)
}
}
}
| 32.636364 | 161 | 0.688719 |
4bb686594ee2c298969522a668ff7531226cc4a1 | 6,032 | //
// FileKitErrorType.swift
// FileKit
//
// The MIT License (MIT)
//
// Copyright (c) 2015-2017 Nikolai Vazquez
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
// MARK: FileKitError
/// An error that can be thrown by FileKit.
public enum FileKitError: Error {
/// A file does not exist.
case fileDoesNotExist(path: Path)
/// A file already exists at operation destination.
case fileAlreadyExists(path: Path)
/// Could not change the current directory.
case changeDirectoryFail(from: Path, to: Path, error: Error)
/// A symbolic link could not be created.
case createSymlinkFail(from: Path, to: Path, error: Error)
/// A hard link could not be created.
case createHardlinkFail(from: Path, to: Path, error: Error)
/// A file could not be created.
case createFileFail(path: Path)
/// A directory could not be created.
case createDirectoryFail(path: Path, error: Error)
/// A file could not be deleted.
case deleteFileFail(path: Path, error: Error)
/// A file could not be read from.
case readFromFileFail(path: Path, error: Error)
/// A file could not be written to.
case writeToFileFail(path: Path, error: Error)
/// A file could not be moved.
case moveFileFail(from: Path, to: Path, error: Error)
/// A file could not be copied.
case copyFileFail(from: Path, to: Path, error: Error)
/// One or many attributes could not be changed.
case attributesChangeFail(path: Path, error: Error)
// MARK: - Reason
/// An error that could be cause of `FileKitError`
enum ReasonError: Error {
/// Failed to read or convert to specific type.
case conversion(Any)
/// A file stream/handle is alread closed.
case closed
/// Failed to encode string using specific encoding.
case encoding(String.Encoding, data: String)
}
}
// MARK: - Message
extension FileKitError {
/// The reason for why the error occured.
public var message: String {
switch self {
case let .fileDoesNotExist(path):
return "File does not exist at \"\(path)\""
case let .fileAlreadyExists(path):
return "File already exists at \"\(path)\""
case let .changeDirectoryFail(fromPath, toPath, _):
return "Could not change the directory from \"\(fromPath)\" to \"\(toPath)\""
case let .createSymlinkFail(fromPath, toPath, _):
return "Could not create symlink from \"\(fromPath)\" to \"\(toPath)\""
case let .createHardlinkFail(fromPath, toPath, _):
return "Could not create a hard link from \"\(fromPath)\" to \"\(toPath)\""
case let .createFileFail(path):
return "Could not create file at \"\(path)\""
case let .createDirectoryFail(path, _):
return "Could not create a directory at \"\(path)\""
case let .deleteFileFail(path, _):
return "Could not delete file at \"\(path)\""
case let .readFromFileFail(path, _):
return "Could not read from file at \"\(path)\""
case let .writeToFileFail(path, _):
return "Could not write to file at \"\(path)\""
case let .moveFileFail(fromPath, toPath, _):
return "Could not move file at \"\(fromPath)\" to \"\(toPath)\""
case let .copyFileFail(fromPath, toPath, _):
return "Could not copy file from \"\(fromPath)\" to \"\(toPath)\""
case let .attributesChangeFail(path, _):
return "Could not change file attrubutes at \"\(path)\""
}
}
}
// MARK: - CustomStringConvertible
extension FileKitError: CustomStringConvertible {
/// A textual representation of `self`.
public var description: String {
return String(describing: type(of: self)) + "(" + message + ")"
}
}
// MARK: - CustomDebugStringConvertible
extension FileKitError: CustomDebugStringConvertible {
/// A textual representation of this instance, suitable for debugging.
public var debugDescription: String {
if let error = error {
return "\(self.description) \(error)"
}
return self.description
}
}
// MARK: - underlying error
extension FileKitError {
/// Return the underlying error if any
public var error: Error? {
switch self {
case .changeDirectoryFail(_, _, let error),
.createSymlinkFail(_, _, let error),
.createHardlinkFail(_, _, let error),
.createDirectoryFail(_, let error),
.deleteFileFail(_, let error),
.readFromFileFail(_, let error),
.writeToFileFail(_, let error),
.moveFileFail(_, _, let error),
.copyFileFail(_, _, let error):
return error
case .fileDoesNotExist,
.fileAlreadyExists,
.createFileFail,
.attributesChangeFail:
return nil
}
}
}
| 35.482353 | 89 | 0.64191 |
f9cf425311b4861e8dc190e4575cac37f80cd053 | 371 | // Automatically generated by the Fast Binary Encoding compiler, do not modify!
// https://github.com/chronoxor/FastBinaryEncoding
// Source: test.fbe
// Version: 1.3.0.0
import ChronoxorFbe
import ChronoxorProto
// Fast Binary Encoding Test receiver listener
public protocol ReceiverListener: ChronoxorProto.ReceiverListener {
}
public extension ReceiverListener {
}
| 24.733333 | 79 | 0.797844 |
79fd4475dd207517e076e6fe773eedea58eb9e12 | 2,235 | //
// TimeMachinePIX.swift
// PixelKit
//
// Created by Hexagons on 2019-03-16.
// Copyright © 2019 Hexagons. All rights reserved.
//
import LiveValues
import RenderKit
import Metal
public class TimeMachinePIX: PIXMergerEffect {
override open var shaderName: String { return "effectMergerTimeMachinePIX" }
// MARK: - Public Properties
public var seconds: LiveFloat = LiveFloat(1.0, max: 10.0)
// MARK: - Private Properties
struct CachedTexture {
let texture: MTLTexture
let date: Date
}
var textureCache: [CachedTexture] = []
// MARK: - Property Helpers
override public var liveValues: [LiveValue] {
return [seconds]
}
// MARK: - Life Cycle
public required init() {
super.init()
name = "timeMachine"
// customMergerRenderActive = true
// customMergerRenderDelegate = self
PixelKit.main.render.listenToFrames {
self.frameLoop()
self.setNeedsRender()
}
}
// MARK: - Frame Loop
func frameLoop() {
if let firstCachedTexture = textureCache.first {
if -firstCachedTexture.date.timeIntervalSinceNow > (1.0 / Double(PixelKit.main.render.fps)) {
let newCachedTexture = CachedTexture(texture: firstCachedTexture.texture, date: Date())
textureCache.insert(newCachedTexture, at: 0)
}
}
let count = textureCache.count
for i in 0..<count {
let ir = count - i - 1
if -textureCache[ir].date.timeIntervalSinceNow > Double(seconds.uniform) {
textureCache.remove(at: ir)
}
}
}
// MARK: - Custom Render
public func customRender(_ texture: MTLTexture, with commandBuffer: MTLCommandBuffer) -> [MTLTexture] {
if let textureCopy = try? Texture.copy(texture: texture, on: pixelKit.render.metalDevice, in: pixelKit.render.commandQueue) {
textureCache.insert(CachedTexture(texture: textureCopy, date: Date()), at: 0)
}
return textureCache.map({$0.texture})
}
// FIXME: Dissconnect: Empty array
}
| 27.592593 | 133 | 0.596868 |
f7895050b953b97cf1fdc83af0d1f223254d4773 | 2,658 | //
// ViewController.swift
// CurrencyExchange-Mac
//
// Created by admin on 12/18/15.
// Copyright © 2015 __ASIAINFO__. All rights reserved.
//
import Cocoa
class CurrencyTextField: NSTextField {
var currencySymbol: CurrencySymbol?
}
class ViewController: NSViewController {
var textFields: [CurrencyTextField] = [CurrencyTextField]()
var cachedRates: NSDictionary?
override func viewDidLoad() {
super.viewDidLoad()
CurrencyService.getLatestCurrency(success: {result in
print(result)
self.cachedRates = (result as? NSDictionary)?["rates"] as? NSDictionary
})
var rawValue = 0
view.wantsLayer = true
view.layer?.backgroundColor = NSColor.redColor().CGColor
var previousView: NSView = view
repeat {
let symbol = CurrencySymbol(rawValue: rawValue)
let textField = CurrencyTextField()
textField.delegate = self
view.addSubview(textField)
let label = NSTextField()
view.addSubview(label)
label.editable = false
label.bordered = false
label.backgroundColor = NSColor.redColor()
textField.currencySymbol = symbol
label.stringValue = (symbol?.chineseLocaleName())!
label.sizeToFit()
label.mas_makeConstraints({(make) -> Void in
make.leading.equalTo()(self.view)
make.height.equalTo()(20)
make.width.equalTo()(50)
if previousView == self.view {
make.top.equalTo()(self.view)
} else {
make.top.equalTo()(previousView.mas_bottom).offset()(20)
}
})
textField.mas_makeConstraints({(make) -> Void in
make.top.equalTo()(label)
make.leading.equalTo()(label.mas_trailing)
make.bottom.equalTo()(label)
make.trailing.equalTo()(self.view)
})
textFields.append(textField)
previousView = label
rawValue++
} while CurrencySymbol(rawValue: rawValue) != nil
}
override func mouseDown(theEvent: NSEvent) {
view.window?.endEditingFor(nil)
}
override var representedObject: AnyObject? {
didSet {
// Update the view, if already loaded.
}
}
}
extension ViewController: NSTextFieldDelegate {
override func controlTextDidEndEditing(obj: NSNotification) {
let t = obj.object as! CurrencyTextField
if let number = Float(t.stringValue) {
for ct in textFields {
if ct == t {
continue
}
let tSymbolString: String! = t.currencySymbol?.symbolString()
let ctSymbolString: String! = ct.currencySymbol?.symbolString()
if let cachedRatesAbsolute = cachedRates {
let rate = (cachedRatesAbsolute[ctSymbolString]!.floatValue)! / (cachedRatesAbsolute[tSymbolString]!.floatValue)!
ct.stringValue = "\(number * rate)"
}
}
}
}
}
| 25.075472 | 118 | 0.68924 |
e208ec774e91cccada0b98f722ec33dc442bfe50 | 11,026 | // Copyright (c) 2022 Razeware LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// Notwithstanding the foregoing, you may not use, copy, modify, merge, publish,
// distribute, sublicense, create a derivative work, and/or sell copies of the
// Software in any work that is designed, intended, or marketed for pedagogical or
// instructional purposes related to programming, coding, application development,
// or information technology. Permission for such use, copying, modification,
// merger, publication, distribution, sublicensing, creation of derivative works,
// or sale is expressly withheld.
//
// 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 Combine
import AVFoundation
protocol DownloadProcessorModel {
var id: UUID { get }
var localURL: URL? { get }
var remoteURL: URL? { get }
}
protocol DownloadProcessorDelegate: AnyObject {
func downloadProcessor(_ processor: DownloadProcessor, downloadModelForDownloadWithID downloadID: UUID) -> DownloadProcessorModel?
func downloadProcessor(_ processor: DownloadProcessor, didStartDownloadWithID downloadID: UUID)
func downloadProcessor(_ processor: DownloadProcessor, downloadWithID downloadID: UUID, didUpdateProgress progress: Double)
func downloadProcessor(_ processor: DownloadProcessor, didFinishDownloadWithID downloadID: UUID)
func downloadProcessor(_ processor: DownloadProcessor, didCancelDownloadWithID downloadID: UUID)
func downloadProcessor(_ processor: DownloadProcessor, downloadWithID downloadID: UUID, didFailWithError error: Error)
}
private extension URLSessionDownloadTask {
var downloadID: UUID? {
get { taskDescription.flatMap(UUID.init) }
set { taskDescription = newValue?.uuidString ?? "" }
}
}
private extension AVAssetDownloadTask {
var downloadID: UUID? {
get { taskDescription.flatMap(UUID.init) }
set { taskDescription = newValue?.uuidString ?? "" }
}
}
enum DownloadProcessorError: Error {
case invalidArguments
case unknownDownload
}
// Manage a list of files to download—either queued, in progress, paused or failed.
final class DownloadProcessor: NSObject {
static let sessionIdentifier = "com.razeware.emitron.DownloadProcessor"
static let sdBitrate = 250_000
private var downloadQuality: Attachment.Kind {
settingsManager.downloadQuality
}
private let settingsManager: SettingsManager
init(settingsManager: SettingsManager) {
self.settingsManager = settingsManager
super.init()
populateDownloadListFromSession()
}
private lazy var session: AVAssetDownloadURLSession = {
let config = URLSessionConfiguration.background(withIdentifier: DownloadProcessor.sessionIdentifier)
// Uncommenting this causes the download task to fail with POSIX 22. But seemingly only with
// Vimeo URLs. So that's handy.
// config.isDiscretionary = true
config.sessionSendsLaunchEvents = true
return AVAssetDownloadURLSession(configuration: config, assetDownloadDelegate: self, delegateQueue: .none)
}()
var backgroundSessionCompletionHandler: (() -> Void)?
private var currentDownloads = [AVAssetDownloadTask]()
private var throttleList = [UUID: Double]()
weak var delegate: DownloadProcessorDelegate!
}
extension DownloadProcessor {
func add(download: DownloadProcessorModel) throws {
guard let remoteURL = download.remoteURL else { throw DownloadProcessorError.invalidArguments }
let hlsAsset = AVURLAsset(url: remoteURL)
var options: [String: Any]?
if downloadQuality == .sdVideoFile {
options = [AVAssetDownloadTaskMinimumRequiredMediaBitrateKey: DownloadProcessor.sdBitrate]
}
guard let downloadTask = session.makeAssetDownloadTask(asset: hlsAsset, assetTitle: "\(download.id))", assetArtworkData: nil, options: options) else { return }
downloadTask.downloadID = download.id
downloadTask.resume()
currentDownloads.append(downloadTask)
delegate.downloadProcessor(self, didStartDownloadWithID: download.id)
}
func cancelDownload(_ download: DownloadProcessorModel) throws {
guard let downloadTask = currentDownloads.first(where: { $0.downloadID == download.id }) else { throw DownloadProcessorError.unknownDownload }
downloadTask.cancel()
}
func cancelAllDownloads() {
currentDownloads.forEach { $0.cancel() }
}
func pauseAllDownloads() {
currentDownloads.forEach { $0.suspend() }
}
func resumeAllDownloads() {
currentDownloads.forEach { $0.resume() }
}
}
extension DownloadProcessor {
private func getDownloadTasksFromSession() -> [AVAssetDownloadTask] {
var tasks = [AVAssetDownloadTask]()
// Use a semaphore to make an async call synchronous
// --There's no point in trying to complete instantiating this class without this list.
let semaphore = DispatchSemaphore(value: 0)
session.getAllTasks { downloadTasks in
let myTasks = downloadTasks as! [AVAssetDownloadTask]
tasks = myTasks
semaphore.signal()
}
_ = semaphore.wait(timeout: .distantFuture)
return tasks
}
private func populateDownloadListFromSession() {
currentDownloads = getDownloadTasksFromSession()
}
}
extension DownloadProcessor: AVAssetDownloadDelegate {
func urlSession(_ session: URLSession, assetDownloadTask: AVAssetDownloadTask, didLoad timeRange: CMTimeRange, totalTimeRangesLoaded loadedTimeRanges: [NSValue], timeRangeExpectedToLoad: CMTimeRange) {
guard let downloadID = assetDownloadTask.downloadID else { return }
var percentComplete = 0.0
for value in loadedTimeRanges {
let loadedTimeRange: CMTimeRange = value.timeRangeValue
percentComplete += CMTimeGetSeconds(loadedTimeRange.duration) / CMTimeGetSeconds(timeRangeExpectedToLoad.duration)
}
if let lastReportedProgress = throttleList[downloadID],
abs(percentComplete - lastReportedProgress) < 0.02 {
// Less than a 2% change—it's a no-op
return
}
throttleList[downloadID] = percentComplete
delegate.downloadProcessor(self, downloadWithID: downloadID, didUpdateProgress: percentComplete)
}
func urlSession(_ session: URLSession, assetDownloadTask: AVAssetDownloadTask, didFinishDownloadingTo location: URL) {
guard
let downloadID = assetDownloadTask.downloadID,
let delegate = delegate
else { return }
let download = delegate.downloadProcessor(self, downloadModelForDownloadWithID: downloadID)
guard let localURL = download?.localURL else { return }
do {
try FileManager.removeExistingFile(at: localURL)
try FileManager.default.moveItem(at: location, to: localURL)
} catch {
delegate.downloadProcessor(self, downloadWithID: downloadID, didFailWithError: error)
}
}
}
extension DownloadProcessor: URLSessionDownloadDelegate {
// When the background session has finished sending us events, we can tell the system we're done.
func urlSessionDidFinishEvents(forBackgroundURLSession session: URLSession) {
guard let backgroundSessionCompletionHandler = backgroundSessionCompletionHandler else { return }
// Need to marshal back to the main queue
DispatchQueue.main.async(execute: backgroundSessionCompletionHandler)
}
// Used to update the progress stats of a download task
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
guard let downloadID = downloadTask.downloadID else { return }
let progress = Double(totalBytesWritten) / Double(totalBytesExpectedToWrite)
// We want to call the progress update every 2%
if let lastReportedProgress = throttleList[downloadID],
abs(progress - lastReportedProgress) < 0.02 {
// Less than a 2% change—it's a no-op
return
}
// Update the throttle list and make the delegate call
throttleList[downloadID] = progress
delegate.downloadProcessor(self, downloadWithID: downloadID, didUpdateProgress: progress)
}
// Download completed—move the file to the appropriate place and update the DB
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {
guard let downloadID = downloadTask.downloadID,
let delegate = delegate else { return }
let download = delegate.downloadProcessor(self, downloadModelForDownloadWithID: downloadID)
guard let localURL = download?.localURL else { return }
do {
try FileManager.default.moveItem(at: location, to: localURL)
} catch {
delegate.downloadProcessor(self, downloadWithID: downloadID, didFailWithError: error)
}
}
// Use this to handle and client-side download errors
func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
guard let downloadTask = task as? AVAssetDownloadTask, let downloadID = downloadTask.downloadID else { return }
if let error = error as NSError? {
let cancellationReason = (error.userInfo[NSURLErrorBackgroundTaskCancelledReasonKey] as? NSNumber)?.intValue
if cancellationReason == NSURLErrorCancelledReasonUserForceQuitApplication || cancellationReason == NSURLErrorCancelledReasonBackgroundUpdatesDisabled {
// The download was cancelled for technical reasons, but we might be able to restart it...
currentDownloads.removeAll { $0 == downloadTask }
} else if error.code == NSURLErrorCancelled {
// User-requested cancellation
currentDownloads.removeAll { $0 == downloadTask }
delegate.downloadProcessor(self, didCancelDownloadWithID: downloadID)
} else {
// Unknown error
currentDownloads.removeAll { $0 == downloadTask }
delegate.downloadProcessor(self, downloadWithID: downloadID, didFailWithError: error)
}
} else {
// Success!
currentDownloads.removeAll { $0 == downloadTask }
delegate.downloadProcessor(self, didFinishDownloadWithID: downloadID)
}
}
}
| 41.451128 | 203 | 0.751496 |
914e3b99479ee86bf945335a08883544c435e4ee | 10,423 |
//
// ProductCapabilityLegacy.swift
//
// Generated on 20/09/18
/*
* Copyright 2019 Arcus Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import Foundation
import PromiseKit
import RxSwift
// MARK: Legacy Support
public class ProductCapabilityLegacy: NSObject, ArcusProductCapability, ArcusPromiseConverter {
public var disposeBag: DisposeBag = DisposeBag()
private static let capability: ProductCapabilityLegacy = ProductCapabilityLegacy()
static let ProductCertCOMPATIBLE: String = ProductCert.compatible.rawValue
static let ProductCertNONE: String = ProductCert.none.rawValue
static let ProductCertWORKS: String = ProductCert.works.rawValue
static let ProductBatteryPrimSize_9V: String = ProductBatteryPrimSize._9v.rawValue
static let ProductBatteryPrimSizeAAAA: String = ProductBatteryPrimSize.aaaa.rawValue
static let ProductBatteryPrimSizeAAA: String = ProductBatteryPrimSize.aaa.rawValue
static let ProductBatteryPrimSizeAA: String = ProductBatteryPrimSize.aa.rawValue
static let ProductBatteryPrimSizeC: String = ProductBatteryPrimSize.c.rawValue
static let ProductBatteryPrimSizeD: String = ProductBatteryPrimSize.d.rawValue
static let ProductBatteryPrimSizeCR123: String = ProductBatteryPrimSize.cr123.rawValue
static let ProductBatteryPrimSizeCR2: String = ProductBatteryPrimSize.cr2.rawValue
static let ProductBatteryPrimSizeCR2032: String = ProductBatteryPrimSize.cr2032.rawValue
static let ProductBatteryPrimSizeCR2430: String = ProductBatteryPrimSize.cr2430.rawValue
static let ProductBatteryPrimSizeCR2450: String = ProductBatteryPrimSize.cr2450.rawValue
static let ProductBatteryPrimSizeCR14250: String = ProductBatteryPrimSize.cr14250.rawValue
static let ProductBatteryBackSize_9V: String = ProductBatteryBackSize._9v.rawValue
static let ProductBatteryBackSizeAAAA: String = ProductBatteryBackSize.aaaa.rawValue
static let ProductBatteryBackSizeAAA: String = ProductBatteryBackSize.aaa.rawValue
static let ProductBatteryBackSizeAA: String = ProductBatteryBackSize.aa.rawValue
static let ProductBatteryBackSizeC: String = ProductBatteryBackSize.c.rawValue
static let ProductBatteryBackSizeD: String = ProductBatteryBackSize.d.rawValue
static let ProductBatteryBackSizeCR123: String = ProductBatteryBackSize.cr123.rawValue
static let ProductBatteryBackSizeCR2: String = ProductBatteryBackSize.cr2.rawValue
static let ProductBatteryBackSizeCR2032: String = ProductBatteryBackSize.cr2032.rawValue
static let ProductBatteryBackSizeCR2430: String = ProductBatteryBackSize.cr2430.rawValue
static let ProductBatteryBackSizeCR2450: String = ProductBatteryBackSize.cr2450.rawValue
static let ProductBatteryBackSizeCR14250: String = ProductBatteryBackSize.cr14250.rawValue
static let ProductPairingModeEXTERNAL_APP: String = ProductPairingMode.external_app.rawValue
static let ProductPairingModeWIFI: String = ProductPairingMode.wifi.rawValue
static let ProductPairingModeHUB: String = ProductPairingMode.hub.rawValue
static let ProductPairingModeIPCD: String = ProductPairingMode.ipcd.rawValue
static let ProductPairingModeOAUTH: String = ProductPairingMode.oauth.rawValue
static let ProductPairingModeBRIDGED_DEVICE: String = ProductPairingMode.bridged_device.rawValue
public static func getId(_ model: ProductModel) -> String? {
return capability.getProductId(model)
}
public static func getName(_ model: ProductModel) -> String? {
return capability.getProductName(model)
}
public static func getShortName(_ model: ProductModel) -> String? {
return capability.getProductShortName(model)
}
public static func getDescription(_ model: ProductModel) -> String? {
return capability.getProductDescription(model)
}
public static func getManufacturer(_ model: ProductModel) -> String? {
return capability.getProductManufacturer(model)
}
public static func getVendor(_ model: ProductModel) -> String? {
return capability.getProductVendor(model)
}
public static func getAddDevImg(_ model: ProductModel) -> String? {
return capability.getProductAddDevImg(model)
}
public static func getCert(_ model: ProductModel) -> String? {
return capability.getProductCert(model)?.rawValue
}
public static func getCanBrowse(_ model: ProductModel) -> NSNumber? {
guard let canBrowse: Bool = capability.getProductCanBrowse(model) else {
return nil
}
return NSNumber(value: canBrowse)
}
public static func getCanSearch(_ model: ProductModel) -> NSNumber? {
guard let canSearch: Bool = capability.getProductCanSearch(model) else {
return nil
}
return NSNumber(value: canSearch)
}
public static func getArcusProductId(_ model: ProductModel) -> String? {
return capability.getProductArcusProductId(model)
}
public static func getArcusVendorId(_ model: ProductModel) -> String? {
return capability.getProductArcusVendorId(model)
}
public static func getArcusModelId(_ model: ProductModel) -> String? {
return capability.getProductArcusModelId(model)
}
public static func getArcusComUrl(_ model: ProductModel) -> String? {
return capability.getProductArcusComUrl(model)
}
public static func getHelpUrl(_ model: ProductModel) -> String? {
return capability.getProductHelpUrl(model)
}
public static func getPairVideoUrl(_ model: ProductModel) -> String? {
return capability.getProductPairVideoUrl(model)
}
public static func getBatteryPrimSize(_ model: ProductModel) -> String? {
return capability.getProductBatteryPrimSize(model)?.rawValue
}
public static func getBatteryPrimNum(_ model: ProductModel) -> NSNumber? {
guard let batteryPrimNum: Int = capability.getProductBatteryPrimNum(model) else {
return nil
}
return NSNumber(value: batteryPrimNum)
}
public static func getBatteryBackSize(_ model: ProductModel) -> String? {
return capability.getProductBatteryBackSize(model)?.rawValue
}
public static func getBatteryBackNum(_ model: ProductModel) -> NSNumber? {
guard let batteryBackNum: Int = capability.getProductBatteryBackNum(model) else {
return nil
}
return NSNumber(value: batteryBackNum)
}
public static func getKeywords(_ model: ProductModel) -> String? {
return capability.getProductKeywords(model)
}
public static func getOTA(_ model: ProductModel) -> NSNumber? {
guard let OTA: Bool = capability.getProductOTA(model) else {
return nil
}
return NSNumber(value: OTA)
}
public static func getProtoFamily(_ model: ProductModel) -> String? {
return capability.getProductProtoFamily(model)
}
public static func getProtoSpec(_ model: ProductModel) -> String? {
return capability.getProductProtoSpec(model)
}
public static func getDriver(_ model: ProductModel) -> String? {
return capability.getProductDriver(model)
}
public static func getAdded(_ model: ProductModel) -> Date? {
guard let added: Date = capability.getProductAdded(model) else {
return nil
}
return added
}
public static func getLastChanged(_ model: ProductModel) -> Date? {
guard let lastChanged: Date = capability.getProductLastChanged(model) else {
return nil
}
return lastChanged
}
public static func getCategories(_ model: ProductModel) -> [String]? {
return capability.getProductCategories(model)
}
public static func getPair(_ model: ProductModel) -> [Any]? {
return capability.getProductPair(model)
}
public static func getRemoval(_ model: ProductModel) -> [Any]? {
return capability.getProductRemoval(model)
}
public static func getReset(_ model: ProductModel) -> [Any]? {
return capability.getProductReset(model)
}
public static func getPopulations(_ model: ProductModel) -> [String]? {
return capability.getProductPopulations(model)
}
public static func getScreen(_ model: ProductModel) -> String? {
return capability.getProductScreen(model)
}
public static func getBlacklisted(_ model: ProductModel) -> NSNumber? {
guard let blacklisted: Bool = capability.getProductBlacklisted(model) else {
return nil
}
return NSNumber(value: blacklisted)
}
public static func getHubRequired(_ model: ProductModel) -> NSNumber? {
guard let hubRequired: Bool = capability.getProductHubRequired(model) else {
return nil
}
return NSNumber(value: hubRequired)
}
public static func getMinAppVersion(_ model: ProductModel) -> String? {
return capability.getProductMinAppVersion(model)
}
public static func getMinHubFirmware(_ model: ProductModel) -> String? {
return capability.getProductMinHubFirmware(model)
}
public static func getDevRequired(_ model: ProductModel) -> String? {
return capability.getProductDevRequired(model)
}
public static func getCanDiscover(_ model: ProductModel) -> NSNumber? {
guard let canDiscover: Bool = capability.getProductCanDiscover(model) else {
return nil
}
return NSNumber(value: canDiscover)
}
public static func getAppRequired(_ model: ProductModel) -> NSNumber? {
guard let appRequired: Bool = capability.getProductAppRequired(model) else {
return nil
}
return NSNumber(value: appRequired)
}
public static func getInstallManualUrl(_ model: ProductModel) -> String? {
return capability.getProductInstallManualUrl(model)
}
public static func getPairingMode(_ model: ProductModel) -> String? {
return capability.getProductPairingMode(model)?.rawValue
}
public static func getPairingIdleTimeoutMs(_ model: ProductModel) -> NSNumber? {
guard let pairingIdleTimeoutMs: Int = capability.getProductPairingIdleTimeoutMs(model) else {
return nil
}
return NSNumber(value: pairingIdleTimeoutMs)
}
}
| 37.225 | 98 | 0.758995 |
012d2c0fcffea09d821b5c3dcd7512769127b363 | 3,784 | /**
* Copyright IBM Corporation 2018
*
* 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
/**
Feedback data for submission.
*/
public struct FeedbackDataInput: Codable, Equatable {
/**
The type of feedback. The only permitted value is `element_classification`.
*/
public var feedbackType: String
/**
Brief information about the input document.
*/
public var document: ShortDoc?
/**
An optional string identifying the model ID. The only permitted value is `contracts`.
*/
public var modelID: String?
/**
An optional string identifying the version of the model used.
*/
public var modelVersion: String?
/**
The numeric location of the identified element in the document, represented with two integers labeled `begin` and
`end`.
*/
public var location: Location
/**
The text on which to submit feedback.
*/
public var text: String
/**
The original labeling from the input document, without the submitted feedback.
*/
public var originalLabels: OriginalLabelsIn
/**
The updated labeling from the input document, accounting for the submitted feedback.
*/
public var updatedLabels: UpdatedLabelsIn
// Map each property name to the key that shall be used for encoding/decoding.
private enum CodingKeys: String, CodingKey {
case feedbackType = "feedback_type"
case document = "document"
case modelID = "model_id"
case modelVersion = "model_version"
case location = "location"
case text = "text"
case originalLabels = "original_labels"
case updatedLabels = "updated_labels"
}
/**
Initialize a `FeedbackDataInput` with member variables.
- parameter feedbackType: The type of feedback. The only permitted value is `element_classification`.
- parameter location: The numeric location of the identified element in the document, represented with two
integers labeled `begin` and `end`.
- parameter text: The text on which to submit feedback.
- parameter originalLabels: The original labeling from the input document, without the submitted feedback.
- parameter updatedLabels: The updated labeling from the input document, accounting for the submitted feedback.
- parameter document: Brief information about the input document.
- parameter modelID: An optional string identifying the model ID. The only permitted value is `contracts`.
- parameter modelVersion: An optional string identifying the version of the model used.
- returns: An initialized `FeedbackDataInput`.
*/
public init(
feedbackType: String,
location: Location,
text: String,
originalLabels: OriginalLabelsIn,
updatedLabels: UpdatedLabelsIn,
document: ShortDoc? = nil,
modelID: String? = nil,
modelVersion: String? = nil
)
{
self.feedbackType = feedbackType
self.location = location
self.text = text
self.originalLabels = originalLabels
self.updatedLabels = updatedLabels
self.document = document
self.modelID = modelID
self.modelVersion = modelVersion
}
}
| 33.192982 | 118 | 0.686047 |
91544afd4a963e66490867e6337947929ed431b6 | 287 | //
// ViewController.swift
// FlowerSpot
//
// Created by Kostadin Samardzhiev on 13.01.22.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
}
| 14.35 | 58 | 0.658537 |
9b6e5e6ca883b0843c5149a54151c06a5f7ab491 | 7,966 | import Foundation
// FIXME: comparison operators with optionals were removed from the Swift Standard Libary.
// Consider refactoring the code to use the non-optional operators.
fileprivate func < <T : Comparable>(lhs: T?, rhs: T?) -> Bool {
switch (lhs, rhs) {
case let (l?, r?):
return l < r
case (nil, _?):
return true
default:
return false
}
}
// FIXME: comparison operators with optionals were removed from the Swift Standard Libary.
// Consider refactoring the code to use the non-optional operators.
fileprivate func > <T : Comparable>(lhs: T?, rhs: T?) -> Bool {
switch (lhs, rhs) {
case let (l?, r?):
return l > r
default:
return rhs < lhs
}
}
class PluginRTCDataChannel : NSObject, RTCDataChannelDelegate {
var rtcDataChannel: RTCDataChannel?
var eventListener: ((_ data: NSDictionary) -> Void)?
var eventListenerForBinaryMessage: ((_ data: Data) -> Void)?
var lostStates = Array<String>()
var lostMessages = Array<RTCDataBuffer>()
/**
* Constructor for pc.createDataChannel().
*/
init(
rtcPeerConnection: RTCPeerConnection,
label: String,
options: NSDictionary?,
eventListener: @escaping (_ data: NSDictionary) -> Void,
eventListenerForBinaryMessage: @escaping (_ data: Data) -> Void
) {
PluginUtils.debug("PluginRTCDataChannel#init()")
self.eventListener = eventListener
self.eventListenerForBinaryMessage = eventListenerForBinaryMessage
let rtcDataChannelInit = RTCDataChannelConfiguration.init()
if options?.object(forKey: "ordered") != nil {
rtcDataChannelInit.isOrdered = options!.object(forKey: "ordered") as! Bool
}
if options?.object(forKey: "maxPacketLifeTime") != nil {
// TODO: rtcDataChannel.maxRetransmitTime always reports 0.
rtcDataChannelInit.maxRetransmitTimeMs = options!.object(forKey: "maxPacketLifeTime") as! Int
}
if options?.object(forKey: "maxRetransmits") != nil {
rtcDataChannelInit.maxRetransmits = options!.object(forKey: "maxRetransmits") as! Int32
}
// TODO: error: expected member name following '.'
// https://code.google.com/p/webrtc/issues/detail?id=4614
// if options?.objectForKey("protocol") != nil {
// rtcDataChannelInit.protocol = options!.objectForKey("protocol") as! String
// }
if options?.object(forKey: "protocol") != nil {
rtcDataChannelInit.`protocol` = options!.object(forKey: "protocol") as! String
}
if options?.object(forKey: "negotiated") != nil {
rtcDataChannelInit.isNegotiated = options!.object(forKey: "negotiated") as! Bool
}
if options?.object(forKey: "id") != nil {
rtcDataChannelInit.channelId = options!.object(forKey: "id") as! Int32
}
self.rtcDataChannel = rtcPeerConnection.dataChannel(forLabel: label, configuration: rtcDataChannelInit)
if self.rtcDataChannel == nil {
NSLog("PluginRTCDataChannel#init() | rtcPeerConnection.createDataChannelWithLabel() failed")
return
}
// Report definitive data to update the JS instance.
self.eventListener!([
"type": "new",
"channel": [
"ordered": self.rtcDataChannel!.isOrdered,
"maxPacketLifeTime": self.rtcDataChannel!.maxPacketLifeTime,
"maxRetransmits": self.rtcDataChannel!.maxRetransmits,
"protocol": self.rtcDataChannel!.`protocol`,
"negotiated": self.rtcDataChannel!.isNegotiated,
"id": self.rtcDataChannel!.channelId,
"readyState": PluginRTCDataChannel.stateToString(state: self.rtcDataChannel!.readyState),
"bufferedAmount": self.rtcDataChannel!.bufferedAmount
]
])
}
deinit {
PluginUtils.debug("PluginRTCDataChannel#deinit()")
}
/**
* Constructor for pc.ondatachannel event.
*/
init(rtcDataChannel: RTCDataChannel) {
PluginUtils.debug("PluginRTCDataChannel#init()")
self.rtcDataChannel = rtcDataChannel
}
func run() {
PluginUtils.debug("PluginRTCDataChannel#run()")
self.rtcDataChannel!.delegate = self
//if data channel is created after there is a connection,
// we need to dispatch its current state.
if (self.rtcDataChannel?.readyState != RTCDataChannelState.connecting) {
dataChannelDidChangeState(self.rtcDataChannel!);
}
}
func setListener(
_ eventListener: @escaping (_ data: NSDictionary) -> Void,
eventListenerForBinaryMessage: @escaping (_ data: Data) -> Void
) {
PluginUtils.debug("PluginRTCDataChannel#setListener()")
self.eventListener = eventListener
self.eventListenerForBinaryMessage = eventListenerForBinaryMessage
for readyState in self.lostStates {
self.eventListener!([
"type": "statechange",
"readyState": readyState
])
}
self.lostStates.removeAll()
for buffer in self.lostMessages {
self.emitReceivedMessage(buffer)
}
self.lostMessages.removeAll()
}
func sendString(
_ data: String,
callback: (_ data: NSDictionary) -> Void
) {
PluginUtils.debug("PluginRTCDataChannel#sendString()")
let buffer = RTCDataBuffer(
data: (data.data(using: String.Encoding.utf8))!,
isBinary: false
)
let result = self.rtcDataChannel!.sendData(buffer)
if !result {
NSLog("PluginRTCDataChannel#sendString() | RTCDataChannel#sendData() failed")
}
}
func sendBinary(
_ data: Data,
callback: (_ data: NSDictionary) -> Void
) {
PluginUtils.debug("PluginRTCDataChannel#sendBinary()")
let buffer = RTCDataBuffer(
data: data,
isBinary: true
)
let result = self.rtcDataChannel!.sendData(buffer)
if !result {
NSLog("PluginRTCDataChannel#sendBinary() | RTCDataChannel#sendData() failed")
}
}
func close() {
PluginUtils.debug("PluginRTCDataChannel#close()")
self.rtcDataChannel!.close()
}
static func stateToString(state: RTCDataChannelState) -> String {
switch state {
case RTCDataChannelState.connecting:
return "connecting"
case RTCDataChannelState.open:
return "open"
case RTCDataChannelState.closing:
return "closing"
case RTCDataChannelState.closed:
return "closed"
}
}
func getState() -> String {
return PluginRTCDataChannel.stateToString(state: self.rtcDataChannel!.readyState)
}
/**
* Methods inherited from RTCDataChannelDelegate.
*/
/** The data channel state changed. */
func dataChannelDidChangeState(_ channel: RTCDataChannel) {
let state_str = self.getState()
PluginUtils.debug("PluginRTCDataChannel | state changed [state:%@]", String(describing: state_str))
if self.eventListener != nil {
self.eventListener!([
"type": "statechange",
"readyState": state_str
])
} else {
// It may happen that the eventListener is not yet set, so store the lost states.
self.lostStates.append(state_str)
}
}
/** The data channel successfully received a data buffer. */
func dataChannel(_ channel: RTCDataChannel, didReceiveMessageWith buffer: RTCDataBuffer) {
if !buffer.isBinary {
PluginUtils.debug("PluginRTCDataChannel | utf8 message received")
if self.eventListener != nil {
self.emitReceivedMessage(buffer)
} else {
// It may happen that the eventListener is not yet set, so store the lost messages.
self.lostMessages.append(buffer)
}
} else {
PluginUtils.debug("PluginRTCDataChannel | binary message received")
if self.eventListenerForBinaryMessage != nil {
self.emitReceivedMessage(buffer)
} else {
// It may happen that the eventListener is not yet set, so store the lost messages.
self.lostMessages.append(buffer)
}
}
}
/** The data channel's |bufferedAmount| changed. */
func dataChannel(_ channel: RTCDataChannel, didChangeBufferedAmount amount: UInt64) {
PluginUtils.debug("PluginRTCDataChannel | didChangeBufferedAmount %d", amount)
self.eventListener!([
"type": "bufferedamount",
"bufferedAmount": amount
])
}
func emitReceivedMessage(_ buffer: RTCDataBuffer) {
if !buffer.isBinary {
let message = NSString(
data: buffer.data,
encoding: String.Encoding.utf8.rawValue
)
self.eventListener!([
"type": "message",
"message": message! as String
])
} else {
self.eventListenerForBinaryMessage!(buffer.data)
}
}
}
| 28.45 | 105 | 0.716671 |
d73ca9e95111a21aefbab1220cc26254914e557b | 799 | // ----------------------------------------------------------------------------
//
// CheckTests.IsFalse.swift
//
// @author Alexander Bragin <[email protected]>
// @copyright Copyright (c) 2017, Roxie Mobile Ltd. All rights reserved.
// @link https://www.roxiemobile.com/
//
// ----------------------------------------------------------------------------
@testable import SwiftCommonsDiagnostics
import XCTest
// ----------------------------------------------------------------------------
extension CheckTests {
// MARK: - Tests
func testIsFalse() {
let method = "Check.isFalse"
checkThrowsError(method) {
try Check.isFalse(2 > 1)
}
checkNotThrowsError(method) {
try Check.isFalse(1 > 2)
}
}
}
| 24.96875 | 80 | 0.42428 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.