repo_name
stringlengths 6
91
| path
stringlengths 8
968
| copies
stringclasses 210
values | size
stringlengths 2
7
| content
stringlengths 61
1.01M
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6
99.8
| line_max
int64 12
1k
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.89
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
ikesyo/ReactiveTask | Sources/Errors.swift | 1 | 1322 | //
// Errors.swift
// ReactiveTask
//
// Created by Justin Spahr-Summers on 2014-12-01.
// Copyright (c) 2014 Carthage. All rights reserved.
//
import Foundation
/// An error originating from ReactiveTask.
public enum TaskError: Error {
/// A shell task exited unsuccessfully.
case shellTaskFailed(Task, exitCode: Int32, standardError: String?)
/// An error was returned from a POSIX API.
case posixError(Int32)
}
extension TaskError: CustomStringConvertible {
public var description: String {
switch self {
case let .shellTaskFailed(task, exitCode, standardError):
var description = "A shell task (\(task)) failed with exit code \(exitCode)"
if let standardError = standardError {
description += ":\n\(standardError)"
}
return description
case let .posixError(code):
return NSError(domain: NSPOSIXErrorDomain, code: Int(code), userInfo: nil).description
}
}
}
extension TaskError: Equatable {
public static func == (lhs: TaskError, rhs: TaskError) -> Bool {
switch (lhs, rhs) {
case let (.shellTaskFailed(lhsTask, lhsCode, lhsErr), .shellTaskFailed(rhsTask, rhsCode, rhsErr)):
return lhsTask == rhsTask && lhsCode == rhsCode && lhsErr == rhsErr
case let (.posixError(lhsCode), .posixError(rhsCode)):
return lhsCode == rhsCode
default:
return false
}
}
}
| mit | 82539df7fdc5487452145e2a9585c1d1 | 25.44 | 100 | 0.707262 | 3.682451 | false | false | false | false |
artsy/eigen | ios/Artsy/View_Controllers/SerifModalWebNavigationController.swift | 1 | 2541 | import UIKit
class SerifModalWebNavigationController: UINavigationController, UINavigationControllerDelegate {
override init(rootViewController: UIViewController) {
super.init(rootViewController: rootViewController)
(rootViewController as? ARExternalWebBrowserViewController)?.statusBarStyle = .lightContent
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
view.layer.cornerRadius = 0
view.superview?.layer.cornerRadius = 0
}
override func viewDidLoad() {
super.viewDidLoad()
self.setupView()
self.delegate = self
}
func setupView() {
guard let view = view else {
return
}
view.backgroundColor = .white
edgesForExtendedLayout = UIRectEdge()
setNavigationBarHidden(true, animated: false)
let dimension = 40
let closeButton = ARMenuButton()
closeButton.setBorderColor(.artsyGrayRegular(), for: UIControl.State(), animated: false)
closeButton.setBackgroundColor(.white, for: UIControl.State(), animated: false)
closeButton.setImage(UIImage(named:"serif_modal_close"), for: UIControl.State())
closeButton.addTarget(self, action: #selector(dismissMe), for: .touchUpInside)
view.addSubview(closeButton)
closeButton.alignTrailingEdge(withView: view, predicate: "-20")
closeButton.alignTopEdge(withView: view, predicate: "20")
closeButton.constrainWidth("\(dimension)", height: "\(dimension)")
}
override var supportedInterfaceOrientations : UIInterfaceOrientationMask {
return traitDependentSupportedInterfaceOrientations
}
override var shouldAutorotate : Bool {
return traitDependentAutorotateSupport
}
@objc func dismissMe() {
presentingViewController?.dismiss(animated: true, completion: nil)
}
func navigationController(_ navigationController: UINavigationController, willShow viewController: UIViewController, animated: Bool) {
(viewController as? ARExternalWebBrowserViewController)?.scrollView.contentInsetAdjustmentBehavior = .never
(viewController as? ARExternalWebBrowserViewController)?.statusBarStyle = .lightContent
}
}
| mit | 5db7c507ac9889a271bccc54745e6be5 | 35.826087 | 138 | 0.705234 | 5.697309 | false | false | false | false |
sun409377708/swiftDemo | SinaSwiftPractice/SinaSwiftPractice/Classes/Tools/EmoticonKeyboard(完整版)/HMEmoticonKeyboardView.swift | 1 | 7668 | //
// HMEmoticonKeyboardView.swift
// SinaWeibo
//
// Created by apple on 16/10/7.
// Copyright © 2016年 itcast. All rights reserved.
//
import UIKit
import SnapKit
let emoticonKeyboardHeight: CGFloat = 220
let emoticonToolBarHeight: CGFloat = 37
private let EmoticonCellId = "EmoticonCellId"
class HMEmoticonKeyboardView: UIView {
override init(frame: CGRect) {
super.init(frame: frame)
//backgroundColor = #colorLiteral(red: 0.9254902005, green: 0.2352941185, blue: 0.1019607857, alpha: 1)
setupUI()
//测试调用
print(HMEmoticonTools.sharedEmoticonTools.allEmoticons)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func setupUI() {
addSubview(toolBar)
addSubview(collectionView)
addSubview(pageControl)
addSubview(recentLabel)
//设置约束
toolBar.snp.makeConstraints { (make) in
make.bottom.left.right.equalTo(self)
make.height.equalTo(emoticonToolBarHeight)
}
collectionView.snp.makeConstraints { (make) in
make.top.left.right.equalTo(self)
make.bottom.equalTo(toolBar.snp.top)
}
pageControl.snp.makeConstraints { (make) in
//pageControl 内容显示默认是居中的
make.left.right.equalTo(self)
make.bottom.equalTo(toolBar.snp.top)
}
recentLabel.snp.makeConstraints { (make) in
make.center.equalTo(pageControl)
}
//实现toolBar闭包
toolBar.emoticonTypeSelectClosure = { type in
print(type)
//滚动collectionView
let indexPath = IndexPath(item: 0, section: type.rawValue)
//animated: false 为了解决pageControl出现跑马灯的特效
self.collectionView.scrollToItem(at: indexPath, at: UICollectionViewScrollPosition.left, animated: false)
self.updatePageControlData(indexPath: indexPath)
}
//设置UI界面的时候 就手动调用更新数据的方法
//主队列异步 实际上还是主队列 当前任务的优先级是比较低优先级 等到主队列空闲的时候 才会执行代码块中的任务
DispatchQueue.main.async {
// self.updatePageControlData(indexPath: IndexPath(item: 0, section: 0))
}
regsiterNotification()
}
private func regsiterNotification() {
NotificationCenter.default.addObserver(self, selector: #selector(reloadData), name: NSNotification.Name(KsaveRecentEmoticon), object: nil)
}
@objc private func reloadData() {
//刷新第0组
//如果当前显示的就是第0组 就不执行刷新
let indexPath = collectionView.indexPathsForVisibleItems.last!
if indexPath.section != 0 {
collectionView.reloadItems(at: [IndexPath(item: 0, section: 0)])
}
}
override func layoutSubviews() {
super.layoutSubviews()
self.updatePageControlData(indexPath: IndexPath(item: 0, section: 0))
}
/// 根据indexPath 更新pageControl的显示数据
///
/// - parameter indexPath: 索引对象
func updatePageControlData(indexPath: IndexPath) {
//1. 根据indexPath.section --> 获取到allEmoticons对应的二维数组
let pageEmoticons = HMEmoticonTools.sharedEmoticonTools.allEmoticons[indexPath.section]
//设置pageControl的数据
pageControl.numberOfPages = pageEmoticons.count
pageControl.currentPage = indexPath.item
//设置最近文本的显示 和 pageControl的显示
pageControl.isHidden = indexPath.section == 0
recentLabel.isHidden = indexPath.section != 0
}
//懒加载子控件
lazy var collectionView: UICollectionView = {
//实例化流水布局对象
let layout = UICollectionViewFlowLayout()
//设置滚动方向
layout.scrollDirection = .horizontal
layout.minimumLineSpacing = 0
layout.itemSize = CGSize(width: UIScreen.main.bounds.width, height: emoticonKeyboardHeight - emoticonToolBarHeight)
let cv = UICollectionView(frame: CGRect.zero, collectionViewLayout: layout)
//注册cell
cv.register(HMEmoticonCell.self, forCellWithReuseIdentifier: EmoticonCellId)
//实现数据源方法
//设置数据源代理
cv.dataSource = self
//设置代理
cv.delegate = self
cv.isPagingEnabled = true
cv.bounces = false
//设置背景颜色
cv.backgroundColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1)
return cv
}()
//底部工具条
lazy var toolBar: HMEmoticonToolBar = HMEmoticonToolBar()
private lazy var pageControl : UIPageControl = {
let page = UIPageControl()
page.numberOfPages = 5
page.currentPage = 2
//OC项目运行环境下LLDB看的
let selectedImage = UIImage(named: "compose_keyboard_dot_selected", in: HMEmoticonTools.sharedEmoticonTools.sourceBundle, compatibleWith: nil)
let normalImage = UIImage(named: "compose_keyboard_dot_normal", in: HMEmoticonTools.sharedEmoticonTools.sourceBundle, compatibleWith: nil)
page.setValue(selectedImage, forKey: "_currentPageImage")
page.setValue(normalImage, forKey: "_pageImage")
return page
}()
//最近提示文字
private lazy var recentLabel: UILabel = {
let l = UILabel()
l.text = "最近使用的表情"
l.textColor = UIColor.orange
l.font = UIFont.systemFont(ofSize: 10)
l.sizeToFit()
return l
}()
deinit {
NotificationCenter.default.removeObserver(self)
}
}
//collectionView的数据源方法
extension HMEmoticonKeyboardView: UICollectionViewDataSource, UICollectionViewDelegate {
//实现必选的协议方法
func numberOfSections(in collectionView: UICollectionView) -> Int {
let sectionEmoticon = HMEmoticonTools.sharedEmoticonTools.allEmoticons
return sectionEmoticon.count
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
//swift中非空数组和空数组的地址是不一样
let sectionEmoticon = HMEmoticonTools.sharedEmoticonTools.allEmoticons
return sectionEmoticon[section].count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: EmoticonCellId, for: indexPath) as! HMEmoticonCell
cell.indexPath = indexPath
//获取模型数组 --> 一维数组
let emoticons = HMEmoticonTools.sharedEmoticonTools.allEmoticons[indexPath.section][indexPath.item]
cell.emoticons = emoticons
return cell
}
//实现代理方法
func scrollViewDidScroll(_ scrollView: UIScrollView) {
let contentOffsetx = scrollView.contentOffset.x + 0.5 * UIScreen.main.bounds.width
let point = CGPoint(x: contentOffsetx, y: 1)
//根据一个点来确定indexPath
let indexPath = collectionView.indexPathForItem(at: point)
//让toolBar去更新选中的按钮
self.toolBar.setEmoticonTypeSelected(indexPath: indexPath!)
//更新pageControl
self.updatePageControlData(indexPath: indexPath!)
}
}
| mit | 31d24444e2df1443c7ab1386bccf22bc | 33.05314 | 150 | 0.653 | 4.838023 | false | false | false | false |
dotty2883/AudioKit | Tests/Tests/AKVCOscillator.swift | 14 | 2268 | //
// main.swift
// AudioKit
//
// Created by Nick Arner and Aurelius Prochazka on 12/24/14.
// Copyright (c) 2014 Aurelius Prochazka. All rights reserved.
//
import Foundation
let testDuration: NSTimeInterval = 10.0
class Instrument : AKInstrument {
override init() {
super.init()
let pulseWidthLine = AKLine(firstPoint: 0.ak, secondPoint: 1.ak, durationBetweenPoints: 10.ak)
let frequencyLine = AKLine(firstPoint: 110.ak, secondPoint: 880.ak, durationBetweenPoints: 10.ak)
let note = VCONote()
let vcOscillator = AKVCOscillator()
vcOscillator.waveformType = note.waveformType
vcOscillator.pulseWidth = pulseWidthLine
vcOscillator.frequency = frequencyLine
setAudioOutput(vcOscillator)
enableParameterLog(
"\n\n\nWaveform Type = ",
parameter: note.waveformType,
timeInterval:10
)
enableParameterLog(
"Frequency = ",
parameter: frequencyLine,
timeInterval:0.2
)
enableParameterLog(
"Pulse Width = ",
parameter: pulseWidthLine,
timeInterval:0.2
)
}
}
class VCONote: AKNote {
var waveformType = AKNoteProperty()
override init() {
super.init()
addProperty(waveformType)
}
convenience init(waveformType: AKConstant) {
self.init()
self.waveformType.floatValue = waveformType.floatValue
}
}
AKOrchestra.testForDuration(testDuration)
let instrument = Instrument()
AKOrchestra.addInstrument(instrument)
let note1 = VCONote(waveformType: AKVCOscillator.waveformTypeForSquare())
let note2 = VCONote(waveformType: AKVCOscillator.waveformTypeForSawtooth())
let note3 = VCONote(waveformType: AKVCOscillator.waveformTypeForSquareWithPWM())
let note4 = VCONote(waveformType: AKVCOscillator.waveformTypeForTriangleWithRamp())
note1.duration.floatValue = 2.0
note2.duration.floatValue = 2.0
note3.duration.floatValue = 2.0
note4.duration.floatValue = 2.0
instrument.playNote(note1)
instrument.playNote(note2, afterDelay: 2.0)
instrument.playNote(note3, afterDelay: 4.0)
instrument.playNote(note4, afterDelay: 6.0)
NSThread.sleepForTimeInterval(NSTimeInterval(testDuration))
| mit | 783d0ec16845fb56075f686606a076c0 | 26.325301 | 105 | 0.690917 | 4.536 | false | false | false | false |
idappthat/UTANow-iOS | UTANow/MapViewController.swift | 1 | 1469 | //
// MapViewController.swift
// UTANow
//
// Created by Cameron Moreau on 12/2/15.
// Copyright © 2015 Mobi. All rights reserved.
//
import UIKit
import Mapbox
class MapViewController: UIViewController, MGLMapViewDelegate {
@IBOutlet weak var mapView: MGLMapView!
var markerPoint: CLLocationCoordinate2D?
var markerTitle: String?
@IBAction func cancelAction(sender: AnyObject) {
self.dismissViewControllerAnimated(true, completion: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
mapView.delegate = self
//Place marker if send in by previous view
if let point = markerPoint {
let marker = MGLPointAnnotation()
marker.coordinate = point
marker.title = markerTitle
mapView.addAnnotation(marker)
//Zoom on marker
mapView.setCenterCoordinate(point, zoomLevel: 17, animated: true)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//Use default marker
func mapView(mapView: MGLMapView, imageForAnnotation annotation: MGLAnnotation) -> MGLAnnotationImage? {
return nil
}
//Show annotation text
func mapView(mapView: MGLMapView, annotationCanShowCallout annotation: MGLAnnotation) -> Bool {
return true
}
}
| mit | 1a0a82b3a6eb4f569ac96090c4cf6e98 | 25.690909 | 108 | 0.641689 | 5.224199 | false | false | false | false |
C4Framework/C4iOS | C4/UI/PlayerLayer.swift | 2 | 5155 | // Copyright © 2015 C4
//
// 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 QuartzCore
import AVFoundation
/// Extension for CAShapeLayer that allows overriding the actions for specific properties.
public class PlayerLayer: AVPlayerLayer {
/// A boolean value that, when true, prevents the animation of a shape's properties.
///
/// ````
/// ShapeLayer.disableActions = true
/// circle.fillColor = red
/// ShapeLayer.disableActions = false
///
/// This value can be set globally, after which changes to any shape's properties will be immediate.
public static var disableActions = true
/// This method searches for the given action object of the layer. Actions define dynamic behaviors for a layer. For example, the animatable properties of a layer typically have corresponding action objects to initiate the actual animations. When that property changes, the layer looks for the action object associated with the property name and executes it. You can also associate custom action objects with your layer to implement app-specific actions.
///
/// - parameter key: The identifier of the action.
///
/// - returns: the action object assigned to the specified key.
public override func action(forKey key: String) -> CAAction? {
if ShapeLayer.disableActions == true {
return nil
}
let animatableProperties = [Layer.rotationKey]
if !animatableProperties.contains(key) {
return super.action(forKey: key)
}
let animation: CABasicAnimation
if let viewAnimation = ViewAnimation.stack.last as? ViewAnimation, viewAnimation.spring != nil {
animation = CASpringAnimation(keyPath: key)
} else {
animation = CABasicAnimation(keyPath: key)
}
animation.configureOptions()
animation.fromValue = value(forKey: key)
if key == Layer.rotationKey {
if let layer = presentation() {
animation.fromValue = layer.value(forKey: key)
}
}
return animation
}
private var _rotation = 0.0
/// The value of the receiver's current rotation state.
/// This value is cumulative, and can represent values beyong +/- π
@objc public dynamic var rotation: Double {
return _rotation
}
/// Initializes a new C4Layer
public override init() {
super.init()
}
/// Initializes a new C4Layer from a specified layer of any other type.
/// - parameter layer: Another CALayer
public override init(layer: Any) {
super.init(layer: layer)
if let layer = layer as? PlayerLayer {
_rotation = layer._rotation
}
}
/// Initializes a new C4Layer from data in a given unarchiver.
/// - parameter coder: An unarchiver object.
public required init?(coder: NSCoder) {
super.init(coder: coder)
}
/// Sets a value for a given key.
/// - parameter value: The value for the property identified by key.
/// - parameter key: The name of one of the receiver's properties
public override func setValue(_ value: Any?, forKey key: String) {
super.setValue(value, forKey: key)
if key == Layer.rotationKey {
_rotation = value as? Double ?? 0.0
}
}
/// Returns a Boolean indicating whether changes to the specified key require the layer to be redisplayed.
/// - parameter key: A string that specifies an attribute of the layer.
/// - returns: A Boolean indicating whether changes to the specified key require the layer to be redisplayed.
public override class func needsDisplay(forKey key: String) -> Bool {
if key == Layer.rotationKey {
return true
}
return super.needsDisplay(forKey: key)
}
/// Reloads the content of this layer.
/// Do not call this method directly.
public override func display() {
guard let presentation = presentation() else {
return
}
setValue(presentation._rotation, forKeyPath: "transform.rotation.z")
}
}
| mit | 4f849dd634a8bc1549fed8617ff63e7e | 40.224 | 459 | 0.675917 | 4.861321 | false | false | false | false |
brightdigit/speculid | frameworks/speculid/Controllers/CommandLineRunner.swift | 1 | 2788 | import Foundation
public struct InvalidDocumentURL: Error {
public let url: URL
}
extension Operation: CommandLineActivityProtocol {}
public struct UnknownArgumentsError: Error {
public let arguments: [String]
}
public class CommandLineRunner: CommandLineRunnerProtocol {
public var errorStream: TextOutputStream
public var outputStream: TextOutputStream
private let _versionProvider: VersionProvider?
public var versionProvider: VersionProvider {
_versionProvider ?? Application.current
}
public init(outputStream: TextOutputStream, errorStream: TextOutputStream, versionProvider: VersionProvider? = nil) {
self.outputStream = outputStream
self.errorStream = errorStream
_versionProvider = versionProvider
}
public func activity(withArguments arguments: SpeculidCommandArgumentSet, _ completed: @escaping (CommandLineActivityProtocol, Error?) -> Void) -> CommandLineActivityProtocol {
var error: Error?
let operation = AsyncBlockOperation { completed in
switch arguments {
case .help:
self.outputStream.write(Application.helpText)
return completed()
case let .unknown(arguments):
self.errorStream.write(Application.unknownCommandMessage(fromArguments: arguments))
self.outputStream.write(Application.helpText)
error = UnknownArgumentsError(arguments: arguments)
return completed()
case .version:
if let version = self.versionProvider.version {
self.outputStream.write(version.developmentDescription)
} else {
self.outputStream.write("\(Application.bundle.infoDictionary?["CFBundleShortVersionString"]) (\(Application.bundle.infoDictionary?["CFBundleVersion"]))")
}
#if DEBUG
self.outputStream.write(" DEBUG")
#endif
return completed()
case let .process(url, update):
let documents: [SpeculidDocumentProtocol]
do {
documents = try Application.current.documents(url: url)
} catch let caughtError {
error = caughtError
return completed()
}
// guard let document = tryDocument else {
// error = InvalidDocumentURL(url: url)
// return completed()
// }
error = Application.current.builder.build(documents: documents)
return completed()
case .debugLocation:
self.outputStream.write(Bundle.main.bundleURL.absoluteString)
return completed()
case let .install(type):
if type.contains(.command) {
error = CommandLineInstaller.startSync()
return completed()
} else {
return completed()
}
}
}
operation.completionBlock = {
completed(operation, error)
}
return operation
}
}
| mit | ce01ac925a1478e59edb6dad44035b5f | 34.74359 | 178 | 0.682209 | 5.211215 | false | false | false | false |
e155707/remote | Afuro/Afuro/Main/MainController.swift | 1 | 13966 | //
// ViewController.swift
// AfuRo
//
// Created by 赤堀 貴一 on 2017/11/26.
// Copyright © 2017年 Ryukyu. All rights reserved.
//
import UIKit
import SceneKit
import ARKit
import MapKit
class MainController: UIViewController, ARSCNViewDelegate,CLLocationManagerDelegate {
let cameraController = CameraController()
let login = Login()
@IBOutlet var ARView: ARSCNView!
// ボタンを追加
//@IBOutlet var afuroView: UIView!
@IBOutlet var rightButton: UIButton!
@IBOutlet var leftButton: UIButton!
@IBOutlet var upButton: UIButton!
@IBOutlet var downButton: UIButton!
// アフロの大きさを調整するボタン
@IBOutlet var plusButton: UIButton!
@IBOutlet var minusButton: UIButton!
@IBOutlet weak var ARSwitch: UISwitch!
@IBOutlet weak var AROnOffLabel: UILabel!
enum ButtonTag: Int {
case Right = 1
case Left = 2
case Up = 3
case Down = 4
case Plus = 5
case Minus = 6
}
// ボタンを押した時に, 移動する量を調整する.
let moveAmount:Float = 1;
// 合計の歩いた数を格納する変数
var totalStepsData = 0
// Afuroの増える大きさを調整する係数.
// 今の計算式 アフロの大きさ = 1 + 歩数(totalStepsData) * afuroScaleCoeff
let afuroScaleCoeff:Float = 1;
let dataController = DataController()
override func viewDidLoad() {
super.viewDidLoad()
// Set the view's delegate
ARView.delegate = self
// Show statistics such as fps and timing information
ARView.showsStatistics = true
// Create a new scene
let scene = SCNScene()
// Set the scene to the view
ARView.scene = scene
initMoveButton();
guard
let afuroScene = SCNScene(named: "art.scnassets/daefile/aforo.scn"),
let afuroNode = afuroScene.rootNode.childNode(withName:"afuro" , recursively: true)
else{ return }
setLocationManager()
// これまでの歩数の取得
totalStepsData = dataController.getTotalStepsData()
print("totalStepsDate =\(dataController.getTotalStepsData())")
// アフロの位置
afuroNode.position = SCNVector3(0,0,1)
afuroNode.position = SCNVector3(0,0,-3)
// アフロの回転
afuroNode.eulerAngles = SCNVector3(-90,0,0)
totalStepsData += login.loginGetSteps()
// アフロの大きさの調整
afuroNode.scale.x = 1 + Float(totalStepsData) * afuroScaleCoeff
afuroNode.scale.y = 1 + Float(totalStepsData) * afuroScaleCoeff
afuroNode.scale.z = 1 + Float(totalStepsData) * afuroScaleCoeff
ARView.scene.rootNode.addChildNode(afuroNode)
ARSwitch.addTarget(self, action: #selector(MainController.onClickARSwitch(sender:)), for: UIControlEvents.valueChanged)
AROnOffLabel.text = "on"
AROnOffLabel.textColor = UIColor.red
// アプリ終了時にsaveDataを呼ぶための関数.
let notificationCenter = NotificationCenter.default
notificationCenter.addObserver(
self,
selector: #selector(self.saveData),
name:NSNotification.Name.UIApplicationWillTerminate,
object: nil)
}
// データを保存する関数.
@objc func saveData(){
dataController.setTotalStepsData(totalStepsData)
}
// アフロを移動させるボタンの設定.
func initMoveButton(){
/* ボタンのタグの意味 上のenumを参照
* 1 : 右のボタン.
* 2 : 左のボタン.
* 3 : 上のボタン.
* 4 : 下のボタン.
* 5 : アフロが大きくなるボタン.
* 6 : アフロが小さくなるボタン.
*/
// 右に移動させるボタンの設定.
// タグの設定.
rightButton.tag = ButtonTag.Right.rawValue;
// タップされている間, moveNodeを呼ぶよう設定.
rightButton.addTarget(self, action: #selector(self.touchButtonMoveNode), for: .touchDown)
// 左に移動させるボタンの設定.
// タグの設定.
leftButton.tag = ButtonTag.Left.rawValue;
// タップされている間, moveNodeを呼ぶよう設定.
leftButton.addTarget(self, action: #selector(self.touchButtonMoveNode), for: .touchDown)
// 上に移動させるボタンの設定.
// タグの設定.
upButton.tag = ButtonTag.Up.rawValue;
// タップされている間, moveNodeを呼ぶよう設定.
upButton.addTarget(self, action: #selector(self.touchButtonMoveNode), for: .touchDown)
// 下に移動させるボタンの設定.
// タグの設定.
downButton.tag = ButtonTag.Down.rawValue;
// タップされている間, moveNodeを呼ぶよう設定.
downButton.addTarget(self, action: #selector(self.touchButtonMoveNode), for: .touchDown)
// アフロを大きくさせるボタンの設定.
// タグの設定.
plusButton.tag = ButtonTag.Plus.rawValue;
// タップされている間, moveNodeを呼ぶよう設定.
plusButton.addTarget(self, action: #selector(self.touchButtonScale), for: .touchDown)
// アフロを大きくさせるボタンの設定.
// タグの設定.
minusButton.tag = ButtonTag.Minus.rawValue;
// タップされている間, moveNodeを呼ぶよう設定.
minusButton.addTarget(self, action: #selector(self.touchButtonScale), for: .touchDown)
}
// ボタンがタップされた時に呼び出されるメソッド
@objc func touchButtonMoveNode(_ moveButton: UIButton){
guard
let afuroNode = ARView.scene.rootNode.childNode(withName: "afuro", recursively: true)
else{ print("afuroが...ない!"); return}
// afuroを移動させる.
switch moveButton.tag {
case ButtonTag.Right.rawValue:
afuroNode.position.x += moveAmount * 1
print("right")
break
case ButtonTag.Left.rawValue:
afuroNode.position.x += moveAmount * -1
print("left")
break
case ButtonTag.Up.rawValue:
afuroNode.position.y += moveAmount * 1
print("up")
break
case ButtonTag.Down.rawValue:
afuroNode.position.y += moveAmount * -1
print("down")
break
default:
return
}
}
//
@objc func touchButtonScale(_ moveButton: UIButton){
guard
let afuroNode = ARView.scene.rootNode.childNode(withName: "afuro", recursively: true)
else{ print("afuroが...ない!"); return}
// afuroを移動させる.
switch moveButton.tag {
case ButtonTag.Plus.rawValue:
afuroNode.scale.x += afuroScaleCoeff * 1
afuroNode.scale.y += afuroScaleCoeff * 1
afuroNode.scale.z += afuroScaleCoeff * 1
print("plus")
break
case ButtonTag.Minus.rawValue:
afuroNode.scale.x += afuroScaleCoeff * -1
afuroNode.scale.y += afuroScaleCoeff * -1
afuroNode.scale.z += afuroScaleCoeff * -1
print("minus")
break
default:
return
}
}
@objc func shutter(){
cameraController.savePicture(ARView.snapshot())
}
@objc func onClickARSwitch(sender: UISwitch){
if sender.isOn {
AROnOffLabel.text = "on"
AROnOffLabel.textColor = UIColor.red
}else {
AROnOffLabel.text = "off"
AROnOffLabel.textColor = UIColor.blue
}
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
// Create a session configuration
let configuration = ARWorldTrackingConfiguration()
// Run the view's session
ARView.session.run(configuration)
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
// Pause the view's session
ARView.session.pause()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Release any cached data, images, etc that aren't in use.
}
func getStepsHealthKit() -> Int{
let healthDataController = HealthDataController()
// ヘルスケアから取ってきた歩数を保存する変数
var healthStepsData = 0
// ヘルスケアのデータの取得
if healthDataController.checkAuthorization() {
// もしヘルスケアのアクセスがtrueなら, 今の時刻と最後に歩いた時刻の間の歩いた数の合計を取得.
healthStepsData = healthDataController.getStepsHealthKit(startDate: dataController.getLastDateData(), endDate: Date())
}else{
// // もしヘルスケアにアクセスできないなら, ダミー関数を取得.
healthStepsData = healthDataController.getDummyStepsData()
}
return healthStepsData
}
let locationManager = CLLocationManager()
var oldLocation: CLLocation?
// 位置情報の設定
func setLocationManager(){
// 現在位置情報の精度, 誤差を決定. 以下の様なものがある
// - kCLLocationAccuracyBestForNavigation ナビゲーションに最適な値
// - kCLLocationAccuracyBest 最高精度(iOS,macOSのデフォルト値)
// - kCLLocationAccuracyNearestTenMeters 10m
// - kCLLocationAccuracyHundredMeters 100m(watchOSのデフォルト値)
// - kCLLocationAccuracyKilometer 1Km
// - kCLLocationAccuracyThreeKilometers 3Km
locationManager.desiredAccuracy = kCLLocationAccuracyBest
// 現在位置からどれぐらい動いたら更新するか. 単位はm
locationManager.distanceFilter = 10
locationManager.delegate = self
locationManager.startUpdatingLocation()
}
// 位置情報がlocationManager.distanceFilterの値分更新された時に呼び出されるメソッド.
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
guard let location: CLLocation = locations.last else { return }
if oldLocation == nil {
oldLocation = location
}
let locationDistance = location.distance(from: oldLocation!)
print("moveDistance = \(locationDistance)")
totalStepsData += Int(locationDistance)
saveData()
oldLocation = location
}
//起動時と, 位置情報のアクセス許可が変更された場合に呼び出されるメソッド. ここで位置情報のアクセス許可をとる.
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
switch status {
case .notDetermined:
print("ユーザーはこのアプリケーションに関してまだ選択を行っていません")
// 位置情報アクセスを常に許可するかを問いかける
locationManager.requestAlwaysAuthorization()
break
case .denied:
print("ローケーションサービスの設定が「無効」になっています (ユーザーによって、明示的に拒否されています)")
// 位置情報アクセスを常に許可するかを問いかける
locationManager.requestAlwaysAuthorization()
// 「設定 > プライバシー > 位置情報サービス で、位置情報サービスの利用を許可して下さい」を表示する
ErrorController().notGetLocation()
break
case .restricted:
print("このアプリケーションは位置情報サービスを使用できません(ユーザによって拒否されたわけではありません)")
// 「このアプリは、位置情報を取得できないために、正常に動作できません」を表示する
ErrorController().notGetLocation()
break
case .authorizedAlways:
print("常時、位置情報の取得が許可されています。")
break
case .authorizedWhenInUse:
print("起動時のみ、位置情報の取得が許可されています。")
locationManager.requestAlwaysAuthorization()
// 位置情報取得の開始処理
break
}
}
// MARK: - ARSCNViewDelegate
/*
// Override to create and configure nodes for anchors added to the view's session.
func renderer(_ renderer: SCNSceneRenderer, nodeFor anchor: ARAnchor) -> SCNNode? {
let node = SCNNode()
return node
}
*/
func session(_ session: ARSession, didFailWithError error: Error) {
// Present an error message to the user
}
func sessionWasInterrupted(_ session: ARSession) {
// Inform the user that the session has been interrupted, for example, by presenting an overlay
}
func sessionInterruptionEnded(_ session: ARSession) {
// Reset tracking and/or remove existing anchors if consistent tracking is required
}
}
| mit | b06c13484c04028cb0735fbc89683bfc | 30.204724 | 130 | 0.599041 | 4.738541 | false | false | false | false |
notbenoit/tvOS-Twitch | Code/tvOS/AppDelegate.swift | 1 | 5319 | // Copyright (c) 2015 Benoit Layer
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
import WebImage
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Add a search view controller to the root `UITabBarController`.
if let tabController = window?.rootViewController as? UITabBarController {
tabController.viewControllers?.append(packagedSearchController())
}
WebImage.SDWebImageManager.shared().imageCache.maxCacheAge = 60 * 60 * 24 * 30
WebImage.SDWebImageManager.shared().imageCache.cleanDisk()
return true
}
func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey: Any]) -> Bool {
if
let tabBarController = window?.rootViewController as? UITabBarController,
let homeViewController = tabBarController.viewControllers?.first as? TwitchHomeViewController,
let gameName = URLComponents(url: url, resolvingAgainstBaseURL: false)?
.queryItems?
.filter({ $0.name == "name" })
.first?.value {
homeViewController.selectGame(gameName)
}
return true
}
// MARK: Convenience
/*
A method demonstrating how to encapsulate a `UISearchController` for presentation in, for example, a `UITabBarController`
*/
func packagedSearchController() -> UIViewController {
// Load a `SearchResultsViewController` from its storyboard.
let storyboard = UIStoryboard(name: "Search", bundle: nil)
guard let searchResultsController = storyboard.instantiateInitialViewController() as? SearchResultsViewController else {
fatalError("Unable to instatiate a SearchResultsViewController from the storyboard.")
}
/*
Create a UISearchController, passing the `searchResultsController` to
use to display search results.
*/
let searchController = UISearchController(searchResultsController: searchResultsController)
searchController.view.backgroundColor = UIColor.white
searchController.searchResultsUpdater = searchResultsController
searchController.searchBar.placeholder = NSLocalizedString("Starcraft, ESL, Overwatch...", comment: "")
// Contain the `UISearchController` in a `UISearchContainerViewController`.
let searchContainer = UISearchContainerViewController(searchController: searchController)
searchContainer.title = NSLocalizedString("Search", comment: "")
// Finally contain the `UISearchContainerViewController` in a `UINavigationController`.
let searchNavigationController = UINavigationController(rootViewController: searchContainer)
return searchNavigationController
}
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:.
}
}
| bsd-3-clause | 33f48292828c9fc0c37d5692b6d94082 | 48.25 | 279 | 0.784922 | 5.070543 | false | false | false | false |
mattjgalloway/emoncms-ios | Pods/Former/Former/RowFormers/SliderRowFormer.swift | 1 | 3356 | //
// SliderRowFormer.swift
// Former-Demo
//
// Created by Ryo Aoyama on 7/31/15.
// Copyright © 2015 Ryo Aoyama. All rights reserved.
//
import UIKit
public protocol SliderFormableRow: FormableRow {
func formSlider() -> UISlider
func formTitleLabel() -> UILabel?
func formDisplayLabel() -> UILabel?
}
open class SliderRowFormer<T: UITableViewCell>
: BaseRowFormer<T>, Formable where T: SliderFormableRow {
// MARK: Public
open var value: Float = 0
open var titleDisabledColor: UIColor? = .lightGray
open var displayDisabledColor: UIColor? = .lightGray
public required init(instantiateType: Former.InstantiateType = .Class, cellSetup: ((T) -> Void)? = nil) {
super.init(instantiateType: instantiateType, cellSetup: cellSetup)
}
open override func initialized() {
super.initialized()
rowHeight = 88
}
@discardableResult
public final func onValueChanged(_ handler: @escaping ((Float) -> Void)) -> Self {
onValueChanged = handler
return self
}
@discardableResult
public final func displayTextFromValue(_ handler: @escaping ((Float) -> String)) -> Self {
displayTextFromValue = handler
return self
}
@discardableResult
public final func adjustedValueFromValue(_ handler: @escaping ((Float) -> Float)) -> Self {
adjustedValueFromValue = handler
return self
}
open override func cellInitialized(_ cell: T) {
super.cellInitialized(cell)
cell.formSlider().addTarget(self, action: #selector(SliderRowFormer.valueChanged(slider:)), for: .valueChanged)
}
open override func update() {
super.update()
cell.selectionStyle = .none
let titleLabel = cell.formTitleLabel()
let displayLabel = cell.formDisplayLabel()
let slider = cell.formSlider()
slider.value = adjustedValueFromValue?(value) ?? value
slider.isEnabled = enabled
displayLabel?.text = displayTextFromValue?(value) ?? "\(value)"
if enabled {
_ = titleColor.map { titleLabel?.textColor = $0 }
_ = displayColor.map { displayLabel?.textColor = $0 }
titleColor = nil
displayColor = nil
} else {
if titleColor == nil { titleColor = titleLabel?.textColor ?? .black }
if displayColor == nil { displayColor = displayLabel?.textColor ?? .black }
titleLabel?.textColor = titleDisabledColor
displayLabel?.textColor = displayDisabledColor
}
}
// MARK: Private
private final var onValueChanged: ((Float) -> Void)?
private final var displayTextFromValue: ((Float) -> String)?
private final var adjustedValueFromValue: ((Float) -> Float)?
private final var titleColor: UIColor?
private final var displayColor: UIColor?
private dynamic func valueChanged(slider: UISlider) {
let displayLabel = cell.formDisplayLabel()
let value = slider.value
let adjustedValue = adjustedValueFromValue?(value) ?? value
self.value = adjustedValue
slider.value = adjustedValue
displayLabel?.text = displayTextFromValue?(adjustedValue) ?? "\(adjustedValue)"
onValueChanged?(adjustedValue)
}
}
| mit | 946cf1852ce7619c599b87b8eef10d9f | 32.55 | 119 | 0.63696 | 5.161538 | false | false | false | false |
LesCoureurs/Courir | Courir/Pods/SwiftyGif/SwiftyGif/SwiftyGifManager.swift | 1 | 2651 | //
// SwiftyGifManager.swift
//
//
import ImageIO
import UIKit
import Foundation
public class SwiftyGifManager {
private var timer: CADisplayLink?
private var displayViews: [UIImageView] = []
private var totalGifSize: Int
private var memoryLimit: Int
public var haveCache: Bool
public init(memoryLimit: Int) {
self.memoryLimit = memoryLimit
self.totalGifSize = 0
self.haveCache = true
self.timer = CADisplayLink(target: self, selector: #selector(self.updateImageView))
self.timer!.addToRunLoop(.mainRunLoop(), forMode: NSRunLoopCommonModes)
}
public func addImageView(imageView: UIImageView) {
self.totalGifSize += imageView.gifImage!.imageSize!
if self.totalGifSize > memoryLimit && self.haveCache {
self.haveCache = false
for imageView in self.displayViews{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH,0)){
imageView.checkCache()
}
}
}
self.displayViews.append(imageView)
}
public func deleteImageView(imageView: UIImageView){
if let index = self.displayViews.indexOf(imageView) {
if index >= 0 && index < self.displayViews.count-1 {
self.displayViews.removeAtIndex(index)
self.totalGifSize -= imageView.gifImage!.imageSize!
if self.totalGifSize < memoryLimit && !self.haveCache {
self.haveCache = true
for imageView in self.displayViews{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH,0)){
imageView.checkCache()
}
}
}
}
}
}
public func containsImageView(imageView: UIImageView) -> Bool{
return self.displayViews.contains(imageView)
}
public func hasCache(imageView: UIImageView) -> Bool{
if imageView.displaying == false {
return false
}
if imageView.loopTime == -1 || imageView.loopTime >= 5 {
return self.haveCache
}else{
return false
}
}
@objc func updateImageView(){
for imageView in self.displayViews {
dispatch_async(dispatch_get_main_queue()){
imageView.image = imageView.currentImage
}
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH,0)){
imageView.updateCurrentImage()
}
}
}
} | mit | cd4c9bb958fba4d4a22a4e6e590c4ef9 | 31.341463 | 98 | 0.577895 | 5.117761 | false | false | false | false |
Raizlabs/ios-template | PRODUCTNAME/app/Pods/Swiftilities/Pod/Classes/Lifecycle/Framework/DefaultBehaviors.swift | 1 | 2715 | //
// DefaultBehaviors.swift
// Swiftilities
//
// Created by Michael Skiba on 2/23/17.
// Copyright© 2016 Raizlabs
//
import Foundation
import ObjectiveC.runtime
import UIKit
public struct DefaultBehaviors {
private static let forcedIgnoredClasses: [UIViewController.Type] = [
LifecycleBehaviorViewController.self,
UINavigationController.self,
UITabBarController.self,
]
public let behaviors: [ViewControllerLifecycleBehavior]
public let ignoredClasses: [UIViewController.Type]
public init(behaviors: [ViewControllerLifecycleBehavior], ignoredClasses: [UIViewController.Type] = []) {
self.behaviors = behaviors
self.ignoredClasses = ignoredClasses
}
/// **Swizzles** `viewDidLoad` to add default behaviors to all view controllers.
///
/// - Parameter behaviors: The default behaviors to add
public func inject() {
let selector = #selector(UIViewController.viewDidLoad)
typealias ViewDidLoadIMP = @convention(c)(UIViewController, Selector) -> Void
let instanceViewDidLoad = class_getInstanceMethod(UIViewController.self, selector)
assert(instanceViewDidLoad != nil, "UIViewController should implement \(selector)")
var originalIMP: IMP? = nil
let ignored = self.ignoredClasses
let behaviors = self.behaviors
let swizzledIMPBlock: @convention(block) (UIViewController) -> Void = { (receiver) in
// Invoke the original IMP if it exists
if originalIMP != nil {
let imp = unsafeBitCast(originalIMP, to: ViewDidLoadIMP.self)
imp(receiver, selector)
}
DefaultBehaviors.inject(behaviors: behaviors, into: receiver, ignoring: ignored)
}
let swizzledIMP = imp_implementationWithBlock(unsafeBitCast(swizzledIMPBlock, to: AnyObject.self))
originalIMP = method_setImplementation(instanceViewDidLoad!, swizzledIMP)
}
private static func inject(behaviors: [ViewControllerLifecycleBehavior],
into viewController: UIViewController,
ignoring ignoredClasses: [UIViewController.Type]) {
for type in ignoredClasses + forcedIgnoredClasses {
guard !viewController.isKind(of: type) else {
return
}
}
// Prevents swizzing view controllers that are not subclassed from UIKit
let uiKitBundle = Bundle(for: UIViewController.self)
let receiverBundle = Bundle(for: type(of: viewController))
guard uiKitBundle != receiverBundle else {
return
}
viewController.addBehaviors(behaviors)
}
}
| mit | b3035601e472dd78a75aa0cc0ac2dfba | 36.694444 | 109 | 0.666175 | 5.269903 | false | false | false | false |
ivygulch/IVGRouter | IVGRouter/source/router/RouteSequenceItem.swift | 1 | 1663 | //
// RouteSequence.swift
// IVGRouter
//
// Created by Douglas Sjoquist on 4/24/16.
// Copyright © 2016 Ivy Gulch LLC. All rights reserved.
//
import Foundation
public typealias RouteSequenceOptions = [String: AnyObject]
public struct RouteSequenceItem: Equatable {
public let segmentIdentifier: Identifier
public let data: RouteSegmentDataType?
public let options: RouteSequenceOptions
public init(segmentIdentifier: Identifier, data: RouteSegmentDataType?, options: RouteSequenceOptions = [:]) {
self.segmentIdentifier = segmentIdentifier
self.data = data
self.options = options
}
public static func transform(_ item: Any) -> RouteSequenceItem? {
if let routeSequenceItem = item as? RouteSequenceItem {
return routeSequenceItem
} else if let segmentIdentifier = item as? Identifier {
return RouteSequenceItem(segmentIdentifier: segmentIdentifier, data: nil, options: [: ])
} else if let (segmentIdentifier, options) = item as? (Identifier, RouteSequenceOptions) {
return RouteSequenceItem(segmentIdentifier: segmentIdentifier, data: nil, options: options)
} else if let (name, options) = item as? (String, RouteSequenceOptions) {
return RouteSequenceItem(segmentIdentifier: Identifier(name: name), data: nil, options: options)
}
print("Invalid sourceItem: \(item)")
return nil
}
}
public func ==(lhs: RouteSequenceItem, rhs: RouteSequenceItem) -> Bool {
return lhs.segmentIdentifier == rhs.segmentIdentifier
&& String(describing: lhs.options) == String(describing: rhs.options)
}
| mit | c6560ad9985e3b8ecfb844e1d2c06dbd | 37.651163 | 114 | 0.697353 | 4.961194 | false | false | false | false |
robotwholearned/GettingStarted | FoodTracker/MealTableViewController.swift | 1 | 4919 | //
// MealTableViewController.swift
// FoodTracker
//
// Created by Sandquist, Cassandra - Cassandra on 3/12/16.
// Copyright © 2016 robotwholearned. All rights reserved.
//
import UIKit
enum RatingLevels: Int {
case One = 1, Two, Three, Four, Five
}
struct MealNames {
static let capreseSalad = "Caprese Salad"
static let chickenAndPotatoes = "Chicken and Potatoes"
static let pastaAndMeatballs = "Pasta with Meatballs"
}
class MealTableViewController: UITableViewController {
//MARK: Properties
var meals = [Meal]()
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.leftBarButtonItem = editButtonItem()
if let loadedMeals = loadMeals() {
meals += loadedMeals
} else {
loadSampleMeals()
}
}
func loadSampleMeals() {
let photo1 = R.image.meal1()
let meal1 = Meal(name: MealNames.capreseSalad, photo: photo1, rating: RatingLevels.Four.rawValue)!
let photo2 = R.image.meal2()
let meal2 = Meal(name: MealNames.chickenAndPotatoes, photo: photo2, rating: RatingLevels.Five.rawValue)!
let photo3 = R.image.meal3()
let meal3 = Meal(name: MealNames.pastaAndMeatballs, photo: photo3, rating: RatingLevels.Three.rawValue)!
meals += [meal1, meal2, meal3]
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return meals.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(R.reuseIdentifier.mealTableViewCell.identifier, forIndexPath: indexPath) as! MealTableViewCell
// Fetches the appropriate meal for the data source layout.
let meal = meals[indexPath.row]
cell.nameLabel.text = meal.name
cell.photoImageView?.image = meal.photo
cell.ratingControl.rating = meal.rating
return cell
}
@IBAction func unwindToMealList (segue: UIStoryboardSegue) {
if let sourceViewController = segue.sourceViewController as? MealViewController, meal = sourceViewController.meal {
if let selectedIndexPath = tableView.indexPathForSelectedRow {
meals[selectedIndexPath.row] = meal
tableView.reloadRowsAtIndexPaths([selectedIndexPath], withRowAnimation: .None)
} else {
// Add a new meal.
let newIndexPath = NSIndexPath(forRow: meals.count, inSection: 0)
meals.append(meal)
tableView.insertRowsAtIndexPaths([newIndexPath], withRowAnimation: .Bottom)
}
saveMeals()
}
}
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
meals.removeAtIndex(indexPath.row)
saveMeals()
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
return true
}
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == R.segue.mealTableViewController.showDetail.identifier {
let mealDetailViewController = segue.destinationViewController as! MealViewController
if let selectedMealCell = sender as? MealTableViewCell {
let indexPath = tableView.indexPathForCell(selectedMealCell)!
let selectedMeal = meals[indexPath.row]
mealDetailViewController.meal = selectedMeal
}
} else if segue.identifier == R.segue.mealTableViewController.addItem.identifier {
print("Adding new meal.")
}
}
// MARK: NSCoding
func saveMeals() {
let isSuccessfulSave = NSKeyedArchiver.archiveRootObject(meals, toFile: Meal.ArchiveURL.path!)
if !isSuccessfulSave {
print("Failed to save meals...")
}
}
func loadMeals() -> [Meal]? {
return NSKeyedUnarchiver.unarchiveObjectWithFile(Meal.ArchiveURL.path!) as? [Meal]
}
}
| mit | 8713f956f550ceebaaf514ad99771e0d | 34.381295 | 157 | 0.665718 | 5.023493 | false | false | false | false |
cnharris10/CHRadarGraph | Example/Tests/CHSectorLabelSpec.swift | 1 | 814 | import Quick
import Nimble
import CHRadarGraph
class CHSectorLabelSpec: QuickSpec {
override func spec() {
describe("CHSectorLabel") {
var text: String!
beforeEach {
text = "text"
}
context("#init") {
it("will initialize with text") {
let label = CHSectorLabel(text: text)
expect(label.text) == text
}
it("will initialize with text, boldness, and a color ") {
let isBold = true
let color = UIColor.black.cgColor
let label = CHSectorLabel(text: text, isBold: isBold, color: color)
expect(label.text) == text
}
}
}
}
}
| mit | 94da9e7918bf544a37ceb22353ab3f03 | 22.941176 | 87 | 0.459459 | 4.963415 | false | false | false | false |
ul7290/realm-cocoa | RealmSwift-swift1.2/ObjectSchema.swift | 2 | 2558 | ////////////////////////////////////////////////////////////////////////////
//
// Copyright 2014 Realm Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////
import Foundation
import Realm
/**
This class represents Realm model object schemas.
When using Realm, `ObjectSchema` objects allow performing migrations and
introspecting the database's schema.
`ObjectSchema`s map to tables in the core database.
*/
public final class ObjectSchema: Printable {
// MARK: Properties
internal let rlmObjectSchema: RLMObjectSchema
/// Array of persisted `Property` objects for an object.
public var properties: [Property] {
return (rlmObjectSchema.properties as! [RLMProperty]).map { Property($0) }
}
/// The name of the class this schema describes.
public var className: String { return rlmObjectSchema.className }
/// The property that serves as the primary key, if there is a primary key.
public var primaryKeyProperty: Property? {
if let rlmProperty = rlmObjectSchema.primaryKeyProperty {
return Property(rlmProperty)
}
return nil
}
/// Returns a human-readable description of the properties contained in this object schema.
public var description: String { return rlmObjectSchema.description }
// MARK: Initializers
internal init(_ rlmObjectSchema: RLMObjectSchema) {
self.rlmObjectSchema = rlmObjectSchema
}
// MARK: Property Retrieval
/// Returns the property with the given name, if it exists.
public subscript(propertyName: String) -> Property? {
if let rlmProperty = rlmObjectSchema[propertyName] {
return Property(rlmProperty)
}
return nil
}
}
// MARK: Equatable
extension ObjectSchema: Equatable {}
/// Returns whether the two object schemas are equal.
public func ==(lhs: ObjectSchema, rhs: ObjectSchema) -> Bool {
return lhs.rlmObjectSchema.isEqualToObjectSchema(rhs.rlmObjectSchema)
}
| apache-2.0 | 45d472037f99679e1ba0fc9b7ff43469 | 31.379747 | 95 | 0.671618 | 5.126253 | false | false | false | false |
TechnologySpeaks/smile-for-life | smile-for-life/SQLiteInsertIntoDatabase.swift | 1 | 5186 | //
// SQLiteInsertIntoDatabase.swift
// smile-for-life
//
// Created by Lisa Swanson on 8/14/16.
// Copyright © 2016 Technology Speaks. All rights reserved.
//
import Foundation
class InsertStatments {
let insertUsers = "INSERT INTO Contact (name) VALUES (?, ?);"
let insertSectionHeaders = "INSERT INTO SectionHeaders (sectionLabel, userId) VALUES (?, ?);"
let insertOralEvents = "INSERT INTO OralEvents (created, eventLabel, sectionLabelId) VALUES (?, ?, ?);"
}
//class TableColumns {
// struct User {
// let id: Int32
// let name: String
//
// }
//
//// struct SectionHeaders {
//// let id: Int32
//// let sectionLabel: String
//// let userId: Int32
//// }
//
// struct OralEvent {
//// let id: Int32
// let created: NSString
// let eventLabel: String
// let userId: Int32
// }
//}
extension SQLiteDatabase {
func insertOralEvent(_ oralEvent: OralEvent) throws {
print("I am in insert OralEvent")
let insertSqlForOralEvents = "INSERT INTO OralEvents (created, eventLabel, userId) VALUES (?, ?, ?);"
let insertStatement = try prepareStatement(insertSqlForOralEvents)
defer {
sqlite3_finalize(insertStatement)
}
let eventLabel: NSString = oralEvent.eventName as NSString
guard sqlite3_bind_text(insertStatement, 1, oralEvent.dateStringified, -1, nil) == SQLITE_OK &&
sqlite3_bind_text(insertStatement, 2, eventLabel.utf8String, -1, nil) == SQLITE_OK && sqlite3_bind_int(insertStatement, 3, oralEvent.calendarOwnerId) == SQLITE_OK else {
throw SQLiteError.insertFail(message: "Failed to bind statement to data")
}
guard sqlite3_step(insertStatement) == SQLITE_DONE else {
throw SQLiteError.step(message: "Can NOT insert into OralEvents table.")
}
print("Successfully inserted row into OralEvents tables.")
}
// func insertUser(user: Users) throws {
// print("I am in insert")
// let insertSql = "INSERT INTO Users (id, name) VALUES (?, ?);"
// let insertStatement = try prepareStatement(insertSql)
// defer {
// print("I am in defer")
// sqlite3_finalize(insertStatement)
// }
//
// let name: NSString = user.name
// guard sqlite3_bind_int(insertStatement, 1, user.id) == SQLITE_OK &&
// sqlite3_bind_text(insertStatement, 2, name.UTF8String, -1, nil) == SQLITE_OK else {
// throw SQLiteError.InsertFail(message: "Failed to bind statement to data")
// }
//
// guard sqlite3_step(insertStatement) == SQLITE_DONE else {
// throw SQLiteError.Step(message: "Can NOT insert into Users table.")
// }
//
// print("Successfully inserted row into Users tables.")
// }
func insertUser(_ user: String) throws {
print("I am in insert")
let insertSql = "INSERT INTO Users (name) VALUES (?);"
let insertStatement = try prepareStatement(insertSql)
defer {
print("I am in defer")
sqlite3_finalize(insertStatement)
}
let name: NSString = user as NSString
guard sqlite3_bind_text(insertStatement, 1, name.utf8String, -1, nil) == SQLITE_OK else {
throw SQLiteError.insertFail(message: "Failed to bind statement to data")
}
guard sqlite3_step(insertStatement) == SQLITE_DONE else {
throw SQLiteError.step(message: "Can NOT insert into Users table.")
}
print("Successfully inserted row into Users tables.")
}
}
extension SQLiteDatabase {
func users(_ id: Int32) -> Users? {
let querySql = "SELECT * FROM Users;"
guard let queryStatement = try? prepareStatement(querySql) else {
return nil
}
defer {
sqlite3_finalize(queryStatement)
}
// guard sqlite3_bind_int(queryStatement, 1, id) == SQLITE_OK else {
// return nil
// }
guard sqlite3_step(queryStatement) == SQLITE_ROW else {
return nil
}
print(queryStatement.debugDescription)
let id = sqlite3_column_int(queryStatement, 0)
let queryResultCol1 = sqlite3_column_text(queryStatement, 1)
let name = String(cString: queryResultCol1!)
// var bytes: (CChar, CChar, CChar, CChar) = (0x61, 0x62, 0x63, 0)
// let name = withUnsafePointer(to: &bytes) { queryResultCol1 -> String in return String(cString: UnsafeRawPointer(queryResultCol1).assumingMemoryBound(to: CChar.self))
// }
return Users(id: id, name: name)
}
}
//extension SQLiteDatabase {
// func users(id: Int32) -> Users? {
// let querySql = "SELECT * FROM Users WHERE id = ?;"
// guard let queryStatement = try? prepareStatement(querySql) else {
// return nil
// }
//
// defer {
// sqlite3_finalize(queryStatement)
// }
//
// guard sqlite3_bind_int(queryStatement, 1, id) == SQLITE_OK else {
// return nil
// }
//
// guard sqlite3_step(queryStatement) == SQLITE_ROW else {
// return nil
// }
//
// print(queryStatement.debugDescription)
// let id = sqlite3_column_int(queryStatement, 0)
//
// let queryResultCol1 = sqlite3_column_text(queryStatement, 1)
// let name = String.fromCString(UnsafePointer<CChar>(queryResultCol1))!
//
// return Users(id: id, name: name)
// }
//}
| mit | df1d6908230c3d83b2884f2c0e9a1189 | 30.047904 | 175 | 0.646095 | 3.784672 | false | false | false | false |
pecuniabanking/pecunia-client | Source/AccountStatementsHandler.swift | 1 | 3877 | //
// AccountStatementsHandler.swift
// Pecunia
//
// Created by Frank Emminghaus on 03.04.21.
// Copyright © 2021 Frank Emminghaus. All rights reserved.
//
import Foundation
import HBCI4Swift
class AccountStatementsHandler : NSObject {
let account:BankAccount;
let context:NSManagedObjectContext
@objc init(_ account:BankAccount, context:NSManagedObjectContext) {
self.account = account;
self.context = context;
}
func getLastStatement() -> (year:Int, number:Int)? {
let fetchRequest = NSFetchRequest<NSFetchRequestResult>();
fetchRequest.entity = NSEntityDescription.entity(forEntityName: "AccountStatement", in: self.context);
fetchRequest.predicate = NSPredicate(format: "account = %@", self.account);
fetchRequest.sortDescriptors = [NSSortDescriptor(key: "startDate", ascending: false)];
do {
if let statements = try context.fetch(fetchRequest) as? [AccountStatement] {
if let statement = statements.first {
if let shortDate = ShortDate(date: statement.startDate) {
return (Int(shortDate.year), statement.number.intValue);
}
}
}
}
catch {
return nil;
}
return nil;
}
func getStatementsForYear(year:Int, fromNumber:Int) throws ->Bool {
var number = fromNumber
while true {
guard let statement = try HBCIBackend.backend.getAccountStatement(number, year: year, bankAccount: self.account) else {
break;
}
guard statement.document != nil else {
break;
}
if statement.format.intValue == AccountStatementFormat.MT940.rawValue {
statement.convertStatementsToPDF(for: self.account);
}
let entity = statement.entity;
let attributeKeys = Array<String>(entity.attributesByName.keys);
let attributeValues = statement.dictionaryWithValues(forKeys: attributeKeys)
let newStatement = NSEntityDescription.insertNewObject(forEntityName: "AccountStatement", into: self.context) as! AccountStatement
newStatement.setValuesForKeys(attributeValues)
newStatement.account = account
if newStatement.number == nil || newStatement.number.intValue == 0 {
newStatement.number = NSNumber(value: number)
}
number += 1
}
return number > fromNumber;
}
func getAccountStatements() throws {
// AccountStatementList transaction (HKKAU) is not supported by all institutes. So we try to get the
// account statements one by one
var startYear = Int(ShortDate.current()!.year);
do {
if var (year, number) = getLastStatement() {
while year <= startYear {
_ = try getStatementsForYear(year: year, fromNumber: number+1);
year += 1;
number = 0;
}
} else {
// we start with the current year and then go back
while try getStatementsForYear(year: startYear, fromNumber: 1) {
startYear -= 1
}
}
try self.context.save()
}
catch HBCIError.userAbort {
throw HBCIError.userAbort;
}
catch let error as NSError {
let alert = NSAlert(error: error);
alert.runModal();
}
}
@objc func getAccountStatementsNoException() -> Bool {
do {
try self.getAccountStatements();
}
catch {
return false;
}
return true;
}
}
| gpl-2.0 | bc241d7212ceefb34eb09ad099b1c5fe | 33.300885 | 142 | 0.566305 | 5.230769 | false | false | false | false |
drinkapoint/DrinkPoint-iOS | DrinkPoint/DrinkPoint/Games/Triple/TripleDrink.swift | 1 | 1273 | //
// TripleDrink.swift
// DrinkPoint
//
// Created by Paul Kirk Adams on 6/24/16.
// Copyright © 2016 Paul Kirk Adams. All rights reserved.
//
import SpriteKit
enum DrinkType: Int, CustomStringConvertible {
case Unknown = 0, Martini, Wine, Beer, Whiskey, BloodyMary, BlueLagoon
var spriteName: String {
let spriteNames = [
"Martini",
"Wine",
"Beer",
"Whiskey",
"BloodyMary",
"BlueLagoon"]
return spriteNames[rawValue - 1]
}
var highlightedSpriteName: String {
return spriteName + "-Highlighted"
}
var description: String {
return spriteName
}
static func random() -> DrinkType {
return DrinkType(rawValue: Int(arc4random_uniform(6)) + 1)!
}
}
func ==(lhs: Drink, rhs: Drink) -> Bool {
return lhs.column == rhs.column && lhs.row == rhs.row
}
class Drink: CustomStringConvertible, Hashable {
var column: Int
var row: Int
let drinkType: DrinkType
var sprite: SKSpriteNode?
init(column: Int, row: Int, drinkType: DrinkType) {
self.column = column
self.row = row
self.drinkType = drinkType
}
var description: String {
return "type:\(drinkType) square:(\(column),\(row))"
}
var hashValue: Int {
return row * 10 + column
}
} | mit | 666395484d9149ee5f17bcf167efe865 | 18.890625 | 72 | 0.632862 | 3.676301 | false | false | false | false |
samuraisalad/Pocky | Pocky/Device.swift | 1 | 833 | //
// device.swift
// Pocky
//
// Created by Hitoshi Saito on 2015/06/20.
// Copyright (c) 2015年 Hitoshi Saito. All rights reserved.
//
struct Device {
var id: String
var sort: Int
var type: String
var label: String
var carrier: String
var model: String
var modelNumber: String
var os: String
var displayName: String {
get {
return String(format: "%@ %@ %@", label, model, modelNumber)
}
}
init(id: String, sort: String, type: String, label: String, carrier: String, model: String, modelNumber: String, os: String) {
self.id = id
self.sort = sort.toInt()!
self.type = type
self.label = label
self.carrier = carrier
self.model = model
self.modelNumber = modelNumber
self.os = os
}
} | mit | d45a499543a013255606584bc67c2725 | 23.470588 | 130 | 0.581227 | 3.777273 | false | false | false | false |
duycao2506/SASCoffeeIOS | SAS Coffee/Extension/UIColor+Extension.swift | 1 | 1287 | //
// UIColor+Extension.swift
// SAS Coffee
//
// Created by Duy Cao on 9/1/17.
// Copyright © 2017 Duy Cao. All rights reserved.
//
import UIKit
extension UIColor {
convenience init(red: Int, green: Int, blue: Int) {
assert(red >= 0 && red <= 255, "Invalid red component")
assert(green >= 0 && green <= 255, "Invalid green component")
assert(blue >= 0 && blue <= 255, "Invalid blue component")
self.init(red: CGFloat(red) / 255.0, green: CGFloat(green) / 255.0, blue: CGFloat(blue) / 255.0, alpha: 1.0)
}
convenience init(rgb: Int) {
self.init(
red: (rgb >> 16) & 0xFF,
green: (rgb >> 8) & 0xFF,
blue: rgb & 0xFF
)
}
convenience init(red: Int, green: Int, blue: Int, a: Int = 0xFF) {
self.init(
red: CGFloat(red) / 255.0,
green: CGFloat(green) / 255.0,
blue: CGFloat(blue) / 255.0,
alpha: CGFloat(a) / 255.0
)
}
// let's suppose alpha is the first component (ARGB)
convenience init(argb: Int) {
self.init(
red: (argb >> 16) & 0xFF,
green: (argb >> 8) & 0xFF,
blue: argb & 0xFF,
a: (argb >> 24) & 0xFF
)
}
}
| gpl-3.0 | 7ce2010298dbc5595beacadcb2dd3fb1 | 26.956522 | 116 | 0.502333 | 3.456989 | false | false | false | false |
timkettering/SwiftTicTacToe | TicTacToe/StartGameView.swift | 1 | 4201 | //
// StartGameView.swift
// TicTacToe
//
// Created by Tim Kettering on 7/6/15.
//
//
import UIKit
class StartGameView: UIView {
let LIGHT_YELLOW = UIColor(red: 255.0/255.0, green: 255.0/255.0, blue: 102.0/255.0, alpha: 1.0)
var topic: String? {
didSet {
titleLabel.text = self.topic
}
}
var titleLabel = UILabel()
var messageLabel = UILabel()
var computerFirstBtn = UIButton(type: UIButton.ButtonType.system)
var playerFirstBtn = UIButton(type: UIButton.ButtonType.system)
var viewsBucket = [String: UIView]()
weak var delegate: GameViewController?
override init(frame: CGRect) {
super.init(frame: frame)
self.backgroundColor = UIColor.clear
let containerView = UIView()
containerView.translatesAutoresizingMaskIntoConstraints = false
containerView.backgroundColor = UIColor.black
containerView.alpha = 0.8
self.addSubview(containerView)
self.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-150-[containerView]-150-|", options: [], metrics: nil, views: ["containerView": containerView]))
self.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-30-[containerView]-30-|", options: [], metrics: nil, views: ["containerView": containerView]))
// draw labels
titleLabel.text = topic
titleLabel.textAlignment = NSTextAlignment.center
titleLabel.textColor = UIColor.white
titleLabel.font = UIFont(name: ApplicationAppearance.AppFont.rawValue, size: 33.0)
titleLabel.translatesAutoresizingMaskIntoConstraints = false
containerView.addSubview(titleLabel)
viewsBucket["titleLabel"] = titleLabel
computerFirstBtn.setTitle("Computer Plays First", for: UIControl.State())
computerFirstBtn.titleLabel?.font = UIFont(name: ApplicationAppearance.AppFont.rawValue, size: 24.0)
computerFirstBtn.setTitleColor(LIGHT_YELLOW, for: UIControl.State())
computerFirstBtn.addTarget(self, action: #selector(StartGameView.userWantsComputerToGoFirst), for: UIControl.Event.touchUpInside)
computerFirstBtn.translatesAutoresizingMaskIntoConstraints = false
containerView.addSubview(computerFirstBtn)
viewsBucket["computerFirstBtn"] = computerFirstBtn
playerFirstBtn.setTitle("Player Plays First", for: UIControl.State())
playerFirstBtn.titleLabel?.font = UIFont(name: ApplicationAppearance.AppFont.rawValue, size: 24.0)
playerFirstBtn.setTitleColor(LIGHT_YELLOW, for: UIControl.State())
playerFirstBtn.addTarget(self, action: #selector(StartGameView.userWantsToGoFirst), for: UIControl.Event.touchUpInside)
playerFirstBtn.translatesAutoresizingMaskIntoConstraints = false
containerView.addSubview(playerFirstBtn)
viewsBucket["playerFirstBtn"] = playerFirstBtn
// do layout
containerView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-[titleLabel]-|", options: [], metrics: nil, views: viewsBucket))
containerView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-[computerFirstBtn]-|", options: [], metrics: nil, views: viewsBucket))
containerView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-[playerFirstBtn]-|", options: [], metrics: nil, views: viewsBucket))
containerView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-[titleLabel]", options: [], metrics: nil, views: viewsBucket))
containerView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:[computerFirstBtn]-15-[playerFirstBtn]-|", options: [], metrics: nil, views: viewsBucket))
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: Button Target Events
@objc func userWantsComputerToGoFirst() {
self.startNewGameWith(false)
}
@objc func userWantsToGoFirst() {
self.startNewGameWith(true)
}
// MARK: Delegate Methods
func startNewGameWith(_ playerGoesFirst: Bool) {
delegate?.startNewGame(playerGoesFirst)
}
}
| mit | a45a76379db73a70ec9e982b68c4d295 | 43.221053 | 179 | 0.713402 | 5.043217 | false | false | false | false |
SusanDoggie/Doggie | Sources/DoggieMath/Accelerate/Radix2CooleyTukey/cooleytukey_4.swift | 1 | 4745 | //
// cooleytukey_4.swift
//
// The MIT License
// Copyright (c) 2015 - 2022 Susan Cheng. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
@inlinable
@inline(__always)
func cooleytukey_forward_4<T: FloatingPoint>(_ input: UnsafePointer<T>, _ in_stride: Int, _ in_count: Int, _ out_real: UnsafeMutablePointer<T>, _ out_imag: UnsafeMutablePointer<T>, _ out_stride: Int) {
var input = input
var out_real = out_real
var out_imag = out_imag
let a = input.pointee
input += in_stride
let b = in_count > 1 ? input.pointee : 0
input += in_stride
let c = in_count > 2 ? input.pointee : 0
input += in_stride
let d = in_count > 3 ? input.pointee : 0
let e = a + c
let f = a - c
let g = b + d
let h = b - d
out_real.pointee = e + g
out_imag.pointee = 0
out_real += out_stride
out_imag += out_stride
out_real.pointee = f
out_imag.pointee = -h
out_real += out_stride
out_imag += out_stride
out_real.pointee = e - g
out_imag.pointee = 0
out_real += out_stride
out_imag += out_stride
out_real.pointee = f
out_imag.pointee = h
}
@inlinable
@inline(__always)
func cooleytukey_forward_4<T: FloatingPoint>(_ in_real: UnsafePointer<T>, _ in_imag: UnsafePointer<T>, _ in_stride: Int, _ in_count: (Int, Int), _ out_real: UnsafeMutablePointer<T>, _ out_imag: UnsafeMutablePointer<T>, _ out_stride: Int) {
var in_real = in_real
var in_imag = in_imag
var out_real = out_real
var out_imag = out_imag
let a = in_real.pointee
let b = in_imag.pointee
in_real += in_stride
in_imag += in_stride
let c = in_count.0 > 1 ? in_real.pointee : 0
let d = in_count.1 > 1 ? in_imag.pointee : 0
in_real += in_stride
in_imag += in_stride
let e = in_count.0 > 2 ? in_real.pointee : 0
let f = in_count.1 > 2 ? in_imag.pointee : 0
in_real += in_stride
in_imag += in_stride
let g = in_count.0 > 3 ? in_real.pointee : 0
let h = in_count.1 > 3 ? in_imag.pointee : 0
let i = a + e
let j = b + f
let k = a - e
let l = b - f
let m = c + g
let n = d + h
let o = c - g
let p = d - h
out_real.pointee = i + m
out_imag.pointee = j + n
out_real += out_stride
out_imag += out_stride
out_real.pointee = k + p
out_imag.pointee = l - o
out_real += out_stride
out_imag += out_stride
out_real.pointee = i - m
out_imag.pointee = j - n
out_real += out_stride
out_imag += out_stride
out_real.pointee = k - p
out_imag.pointee = l + o
}
@inlinable
@inline(__always)
func cooleytukey_inverse_4<T: FloatingPoint>(_ input: UnsafePointer<T>, _ in_stride: Int, _ in_count: Int, _ out_real: UnsafeMutablePointer<T>, _ out_imag: UnsafeMutablePointer<T>, _ out_stride: Int) {
var input = input
var out_real = out_real
var out_imag = out_imag
let a = input.pointee
input += in_stride
let b = in_count > 1 ? input.pointee : 0
input += in_stride
let c = in_count > 2 ? input.pointee : 0
input += in_stride
let d = in_count > 3 ? input.pointee : 0
let e = a + c
let f = a - c
let g = b + d
let h = b - d
out_real.pointee = e + g
out_imag.pointee = 0
out_real += out_stride
out_imag += out_stride
out_real.pointee = f
out_imag.pointee = h
out_real += out_stride
out_imag += out_stride
out_real.pointee = e - g
out_imag.pointee = 0
out_real += out_stride
out_imag += out_stride
out_real.pointee = f
out_imag.pointee = -h
}
| mit | 08dbce56f2958951678c8972c5575bce | 27.757576 | 239 | 0.606322 | 3.406317 | false | false | false | false |
skedgo/tripkit-ios | Sources/TripKitUI/vendor/RxDataSources/CollectionViewSectionedDataSource.swift | 1 | 6150 | //
// CollectionViewSectionedDataSource.swift
// RxDataSources
//
// Created by Krunoslav Zaher on 7/2/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
#if os(iOS) || os(tvOS)
import Foundation
import UIKit
#if !RX_NO_MODULE
import RxCocoa
#endif
open class CollectionViewSectionedDataSource<Section: SectionModelType>
: NSObject
, UICollectionViewDataSource
, SectionedViewDataSourceType {
public typealias Item = Section.Item
public typealias Section = Section
public typealias ConfigureCell = (CollectionViewSectionedDataSource<Section>, UICollectionView, IndexPath, Item) -> UICollectionViewCell
public typealias ConfigureSupplementaryView = (CollectionViewSectionedDataSource<Section>, UICollectionView, String, IndexPath) -> UICollectionReusableView
public typealias MoveItem = (CollectionViewSectionedDataSource<Section>, _ sourceIndexPath:IndexPath, _ destinationIndexPath:IndexPath) -> Void
public typealias CanMoveItemAtIndexPath = (CollectionViewSectionedDataSource<Section>, IndexPath) -> Bool
public init(
configureCell: @escaping ConfigureCell,
configureSupplementaryView: ConfigureSupplementaryView? = nil,
moveItem: @escaping MoveItem = { _, _, _ in () },
canMoveItemAtIndexPath: @escaping CanMoveItemAtIndexPath = { _, _ in false }
) {
self.configureCell = configureCell
self.configureSupplementaryView = configureSupplementaryView
self.moveItem = moveItem
self.canMoveItemAtIndexPath = canMoveItemAtIndexPath
}
#if DEBUG
// If data source has already been bound, then mutating it
// afterwards isn't something desired.
// This simulates immutability after binding
var _dataSourceBound: Bool = false
private func ensureNotMutatedAfterBinding() {
assert(!_dataSourceBound, "Data source is already bound. Please write this line before binding call (`bindTo`, `drive`). Data source must first be completely configured, and then bound after that, otherwise there could be runtime bugs, glitches, or partial malfunctions.")
}
#endif
// This structure exists because model can be mutable
// In that case current state value should be preserved.
// The state that needs to be preserved is ordering of items in section
// and their relationship with section.
// If particular item is mutable, that is irrelevant for this logic to function
// properly.
public typealias SectionModelSnapshot = SectionModel<Section, Item>
private var _sectionModels: [SectionModelSnapshot] = []
open var sectionModels: [Section] {
return _sectionModels.map { Section(original: $0.model, items: $0.items) }
}
open subscript(section: Int) -> Section {
let sectionModel = self._sectionModels[section]
return Section(original: sectionModel.model, items: sectionModel.items)
}
open subscript(indexPath: IndexPath) -> Item {
get {
return self._sectionModels[indexPath.section].items[indexPath.item]
}
set(item) {
var section = self._sectionModels[indexPath.section]
section.items[indexPath.item] = item
self._sectionModels[indexPath.section] = section
}
}
open func model(at indexPath: IndexPath) throws -> Any {
return self[indexPath]
}
open func setSections(_ sections: [Section]) {
self._sectionModels = sections.map { SectionModelSnapshot(model: $0, items: $0.items) }
}
open var configureCell: ConfigureCell {
didSet {
#if DEBUG
ensureNotMutatedAfterBinding()
#endif
}
}
open var configureSupplementaryView: ConfigureSupplementaryView? {
didSet {
#if DEBUG
ensureNotMutatedAfterBinding()
#endif
}
}
open var moveItem: MoveItem {
didSet {
#if DEBUG
ensureNotMutatedAfterBinding()
#endif
}
}
open var canMoveItemAtIndexPath: ((CollectionViewSectionedDataSource<Section>, IndexPath) -> Bool)? {
didSet {
#if DEBUG
ensureNotMutatedAfterBinding()
#endif
}
}
// UICollectionViewDataSource
open func numberOfSections(in collectionView: UICollectionView) -> Int {
return _sectionModels.count
}
open func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return _sectionModels[section].items.count
}
open func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
precondition(indexPath.item < _sectionModels[indexPath.section].items.count)
return configureCell(self, collectionView, indexPath, self[indexPath])
}
open func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
return configureSupplementaryView!(self, collectionView, kind, indexPath)
}
open func collectionView(_ collectionView: UICollectionView, canMoveItemAt indexPath: IndexPath) -> Bool {
guard let canMoveItem = canMoveItemAtIndexPath?(self, indexPath) else {
return false
}
return canMoveItem
}
open func collectionView(_ collectionView: UICollectionView, moveItemAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
self._sectionModels.moveFromSourceIndexPath(sourceIndexPath, destinationIndexPath: destinationIndexPath)
self.moveItem(self, sourceIndexPath, destinationIndexPath)
}
override open func responds(to aSelector: Selector!) -> Bool {
if aSelector == #selector(UICollectionViewDataSource.collectionView(_:viewForSupplementaryElementOfKind:at:)) {
return configureSupplementaryView != nil
}
else {
return super.responds(to: aSelector)
}
}
}
#endif
| apache-2.0 | 9fac54434fa3890b388b668a4b85110c | 36.723926 | 280 | 0.684176 | 5.741363 | false | true | false | false |
TonnyTao/HowSwift | how_to_update_view_in_mvvm.playground/Pages/5 kvo.xcplaygroundpage/Contents.swift | 1 | 1065 | import Foundation
import UIKit
//ViewController.swift
class ViewController: UITableViewController {
let viewModel = ViewModel()
func setup() {
viewModel.addObserver(
self,
forKeyPath: #keyPath(ViewModel.state),
options: [.new],
context: nil
)
viewModel.fetch()
}
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if keyPath == #keyPath(ViewModel.state) {
let state = change?[.newKey] as? [Admin]
print("notified", state)
self.tableView.reloadData()
}
}
}
//ViewModel.swift
class ViewModel: NSObject {
@objc dynamic var state: [Admin]?
func fetch() {
[Admin].fetch { [weak self] data in
self?.state = data
}
}
}
final class Admin: NSObject, Resource {
required override init() {}
}
let vc = ViewController()
vc.setup()
| mit | 55f20d9b7f80bd7064aaaab5ec915628 | 20.734694 | 151 | 0.565258 | 4.863014 | false | false | false | false |
skedgo/tripkit-ios | Sources/TripKitUI/views/results/TKUIResultsSectionHeaderView.swift | 1 | 3695 | //
// TKUIResultsSectionHeaderView.swift
// TripKitUI
//
// Created by Adrian Schönig on 04.10.19.
// Copyright © 2019 SkedGo Pty Ltd. All rights reserved.
//
import UIKit
import TripKit
class TKUIResultsSectionHeaderView: UITableViewHeaderFooterView {
static let forSizing: TKUIResultsSectionHeaderView = {
let header = TKUIResultsSectionHeaderView()
header.badgeIcon.image = .badgeLeaf
return header
}()
static let reuseIdentifier = "TKUIResultsSectionHeaderView"
@IBOutlet weak var wrapper: UIView!
@IBOutlet weak var badgeIcon: UIImageView!
@IBOutlet weak var badgeLabel: UILabel!
private init() {
super.init(reuseIdentifier: nil)
didInit()
}
override init(reuseIdentifier: String?) {
super.init(reuseIdentifier: reuseIdentifier)
didInit()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
didInit()
}
override func prepareForReuse() {
super.prepareForReuse()
badgeIcon.image = nil
badgeLabel.text = nil
}
var badge: (icon: UIImage?, text: String, color: UIColor)? {
get {
(badgeIcon.image, badgeLabel.text ?? "", badgeLabel.textColor ?? .tkLabelPrimary)
}
set {
badgeIcon.image = newValue?.icon
badgeIcon.tintColor = newValue?.color
badgeLabel.text = newValue?.text
badgeLabel.textColor = newValue?.color
}
}
private func didInit() {
contentView.backgroundColor = .tkBackgroundGrouped
let wrapper = UIView()
wrapper.backgroundColor = .tkBackground
wrapper.translatesAutoresizingMaskIntoConstraints = false
self.wrapper = wrapper
contentView.addSubview(wrapper)
NSLayoutConstraint.activate([
wrapper.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 0),
wrapper.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 16),
contentView.bottomAnchor.constraint(equalTo: wrapper.bottomAnchor, constant: 0),
contentView.trailingAnchor.constraint(equalTo: wrapper.trailingAnchor, constant: 0)
])
let badgeIcon = UIImageView()
badgeIcon.contentMode = .scaleAspectFit
badgeIcon.tintColor = .tkFilledButtonTextColor
badgeIcon.widthAnchor.constraint(equalToConstant: 16).isActive = true
badgeIcon.heightAnchor.constraint(equalToConstant: 16).isActive = true
badgeIcon.translatesAutoresizingMaskIntoConstraints = false
self.badgeIcon = badgeIcon
wrapper.addSubview(badgeIcon)
let badgeLabel = UILabel()
badgeLabel.numberOfLines = 1
badgeLabel.text = nil
badgeLabel.textColor = .tkFilledButtonTextColor
badgeLabel.font = TKStyleManager.boldCustomFont(forTextStyle: .subheadline)
badgeLabel.translatesAutoresizingMaskIntoConstraints = false
self.badgeLabel = badgeLabel
wrapper.addSubview(badgeLabel)
let bottomWrapperMarginConstraint = wrapper.bottomAnchor.constraint(equalTo: badgeIcon.bottomAnchor, constant: 4)
bottomWrapperMarginConstraint.priority = UILayoutPriority(rawValue: 999)
let badgeTopMarginConstraint = badgeIcon.topAnchor.constraint(equalTo: wrapper.topAnchor, constant: 16)
badgeTopMarginConstraint.priority = UILayoutPriority(rawValue: 999)
NSLayoutConstraint.activate([
badgeIcon.leadingAnchor.constraint(equalTo: wrapper.leadingAnchor, constant: 16),
badgeLabel.leadingAnchor.constraint(equalTo: badgeIcon.trailingAnchor, constant: 8),
wrapper.trailingAnchor.constraint(equalTo: badgeLabel.trailingAnchor, constant: 16),
badgeTopMarginConstraint,
badgeLabel.centerYAnchor.constraint(equalTo: badgeIcon.centerYAnchor),
bottomWrapperMarginConstraint
])
}
}
| apache-2.0 | 19d85810d76bd3a570d0dddb22109b9c | 32.27027 | 117 | 0.735445 | 5.143454 | false | false | false | false |
material-motion/material-motion-swift | src/MotionRuntime.swift | 2 | 10063 | /*
Copyright 2016-present The Material Motion Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import Foundation
import UIKit
import IndefiniteObservable
/**
A motion runtime provides a mechanism for associating interactions with targets.
Runtimes are cheap to create and scoped a specific view hierarchy. You typically create a new
runtime for each view controller that plans to make use of reactive motion.
The simplest primitive of a motion runtime is a connection from a stream to a reactive property.
Interactions are expected to create these connections when added to the runtime.
Runtimes also act as a cache for reactive objects, ensuring that any associated reactive property
instances are consistently used.
*/
public final class MotionRuntime {
deinit {
_visualizationView?.removeFromSuperview()
subscriptions.forEach { $0.unsubscribe() }
}
/**
Creates a motion runtime instance with the provided container view.
*/
public init(containerView: UIView) {
self.containerView = containerView
}
/**
In general, the container view is the view within which all motion associated to this runtime
occurs.
Interactions make use of the container view when doing things like registering gesture
recognizers and calculating relative coordinates.
*/
public let containerView: UIView
/**
When enabled, debug visualizations will be drawn atop the container view for any interactions
that support debug visualization.
*/
public var shouldVisualizeMotion = false
/**
Associates an interaction with the runtime.
Invokes the interaction's add method and stores the interaction instance for the lifetime of the
runtime.
*/
public func add<I: Interaction>(_ interaction: I, to target: I.Target, constraints: I.Constraints? = nil) where I.Target: AnyObject {
interactions.append(interaction)
interaction.add(to: target, withRuntime: self, constraints: constraints)
if let manipulation = interaction as? Manipulation {
aggregateManipulationState.observe(state: manipulation.state, withRuntime: self)
}
let identifier = ObjectIdentifier(target)
var targetInteractions = targets[identifier] ?? []
targetInteractions.append(interaction)
targets[identifier] = targetInteractions
}
/**
Returns all interactions added to the given target.
Example usage:
let draggables = runtime.interactions(ofType: Draggable.self, for: view)
*/
public func interactions<I>(ofType: I.Type, for target: I.Target) -> [I] where I: Interaction, I.Target: AnyObject {
guard let interactions = targets[ObjectIdentifier(target)] else {
return []
}
return interactions.flatMap { $0 as? I }
}
/**
Creates a toggling association between one interaction's state and the other interaction's
enabling.
The provided interaction will be disabled when otherInteraction's state is active, and enabled
when otherInteraction's state is at rest.
This is most commonly used to disable a spring when a gestural interaction is active.
*/
public func toggle(_ interaction: Togglable, inReactionTo otherInteraction: Stateful) {
connect(otherInteraction.state.rewrite([.atRest: true, .active: false]), to: interaction.enabled)
}
/**
Initiates an interaction by disabling and then immediately re-enabling the interaction when the
otherInteraction's state is active.
*/
public func start(_ interaction: Togglable, whenActive otherInteraction: Stateful) {
let state = otherInteraction.state.dedupe()
interaction.enabled.value = false
connect(state.rewrite([.active: false]), to: interaction.enabled)
connect(state.rewrite([.active: true]), to: interaction.enabled)
}
/**
Initiates interaction B when interaction A changes to certain state
*/
public func start(_ interactionA: Togglable, when interactionB: Stateful, is state: MotionState) {
connect(interactionB.state.dedupe().rewrite([state: true]), to: interactionA.enabled)
}
/**
Connects a stream's output to a reactive property.
This method is primarily intended to be used by interactions and its presence in application
logic implies that an applicable interaction is not available.
*/
public func connect<O: MotionObservableConvertible>(_ stream: O, to property: ReactiveProperty<O.T>) {
write(stream.asStream(), to: property)
}
/**
The view to which visualization elements should be registered.
This view will be added as an overlay to the runtime's container view.
Use this view like so:
runtime.add(tossable, to: view) { $0.visualize(in: runtime.visualizationView) }
*/
public var visualizationView: UIView {
if let visualizationView = _visualizationView {
return visualizationView
}
let view = UIView(frame: .init(x: 0, y: containerView.bounds.maxY, width: containerView.bounds.width, height: 0))
view.autoresizingMask = [.flexibleWidth, .flexibleTopMargin]
view.isUserInteractionEnabled = false
view.backgroundColor = UIColor(white: 0, alpha: 0.1)
containerView.addSubview(view)
_visualizationView = view
return view
}
private var _visualizationView: UIView?
// MARK: Reactive object storage
/**
Returns a reactive version of the given object.
*/
public func get(_ view: UIView) -> Reactive<UIView> {
return Reactive(view)
}
/**
Returns a reactive version of the given object.
*/
public func get(_ layer: CALayer) -> Reactive<CALayer> {
return Reactive(layer)
}
/**
Returns a reactive version of the given object.
*/
public func get(_ layer: CAShapeLayer) -> Reactive<CAShapeLayer> {
return Reactive(layer)
}
/**
Returns a reactive version of the given object and caches the returned result for future access.
*/
public func get(_ scrollView: UIScrollView) -> MotionObservable<CGPoint> {
return get(scrollView) { scrollViewToStream($0) }
}
/**
Returns a reactive version of the given object and caches the returned result for future access.
*/
public func get(_ slider: UISlider) -> MotionObservable<CGFloat> {
return get(slider) { sliderToStream($0) }
}
/**
Returns a reactive version of the given object and caches the returned result for future access.
*/
public func get<O: UIGestureRecognizer>(_ gestureRecognizer: O) -> ReactiveUIGestureRecognizer<O> {
return get(gestureRecognizer) {
let reactiveObject = ReactiveUIGestureRecognizer<O>($0, containerView: containerView)
if reactiveObject.gestureRecognizer.view == nil {
containerView.addGestureRecognizer(reactiveObject.gestureRecognizer)
}
return reactiveObject
}
}
/**
Executes a block when all of the provided Stateful interactions have come to rest.
*/
public func whenAllAtRest(_ interactions: [Stateful], body: @escaping () -> Void) {
guard interactions.count > 0 else {
body()
return
}
var subscriptions: [Subscription] = []
var activeIndices = Set<Int>()
for (index, stream) in interactions.enumerated() {
subscriptions.append(stream.state.dedupe().subscribeToValue { state in
if state == .active {
activeIndices.insert(index)
} else if activeIndices.contains(index) {
activeIndices.remove(index)
if activeIndices.count == 0 {
body()
}
}
})
}
self.subscriptions.append(contentsOf: subscriptions)
}
/**
A Boolean stream indicating whether the runtime is currently being directly manipulated by the
user.
*/
public var isBeingManipulated: MotionObservable<Bool> {
return aggregateManipulationState.asStream().rewrite([.active: true, .atRest: false])
}
private let aggregateManipulationState = AggregateMotionState()
private func write<O: MotionObservableConvertible, T>(_ stream: O, to property: ReactiveProperty<T>) where O.T == T {
subscriptions.append(stream.subscribe(next: { property.value = $0 },
coreAnimation: property.coreAnimation,
visualization: { [weak self] view in
guard let strongSelf = self else { return }
if !strongSelf.shouldVisualizeMotion { return }
property.visualize(view, in: strongSelf.containerView)
}))
}
private func get<T: AnyObject, U: AnyObject>(_ object: T, initializer: (T) -> U) -> U {
let identifier = ObjectIdentifier(object)
if let reactiveObject = reactiveObjects[identifier] {
// If a UIPanGestureRecognizer is fetched using runtime.get while typed as a
// UIGestureRecognizer, the ReactiveUIGestureRecognizer instance will be created as a
// ReactiveUIGestureRecognizer<UIGestureRecognizer>, meaning we can't cast using as down to a
// ReactiveUIGestureRecognizer<UIPanGestureRecognizer>. We know this is safe to do within the
// context of the runtime, so we do a forced bit cast here instead of an `as` cast.
return unsafeBitCast(reactiveObject, to: U.self)
}
let reactiveObject = initializer(object)
reactiveObjects[identifier] = reactiveObject
return reactiveObject
}
private var reactiveObjects: [ObjectIdentifier: AnyObject] = [:]
private var targets: [ObjectIdentifier: [Any]] = [:]
private var subscriptions: [Subscription] = []
private var interactions: [Any] = []
}
| apache-2.0 | 0c0dd328f9757c82a9f0d99c998eb6a5 | 35.197842 | 135 | 0.706747 | 4.863702 | false | false | false | false |
grantmagdanz/InupiaqKeyboard | Keyboard/KeyboardViewController.swift | 1 | 41067 | //
// KeyboardViewController.swift
// Keyboard
//
// Created by Alexei Baboulevitch on 6/9/14.
// Updated by Grant Magdanz on 9/24/15.
// Copyright (c) 2015 Apple. All rights reserved.
//
import UIKit
import AudioToolbox
enum TTDeviceType{
case TTDeviceTypeIPhone4
case TTDeviceTypeIPhone5
case TTDeviceTypeIPhone6
case TTDeviceTypeIPhone6p
}
var deviceType = TTDeviceType.TTDeviceTypeIPhone5
let metrics: [String:Double] = [
"topBanner": 30
]
func metric(name: String) -> CGFloat { return CGFloat(metrics[name]!) }
// TODO: move this somewhere else and localize
let kAutoCapitalization = "kAutoCapitalization"
let kPeriodShortcut = "kPeriodShortcut"
let kKeyboardClicks = "kKeyboardClicks"
let kSmallLowercase = "kSmallLowercase"
class KeyboardViewController: UIInputViewController {
let backspaceDelay: NSTimeInterval = 0.5
let backspaceRepeat: NSTimeInterval = 0.07
var keyboard: Keyboard!
var forwardingView: ForwardingView!
var layout: KeyboardLayout?
var heightConstraint: NSLayoutConstraint?
var bannerView: ExtraView?
var settingsView: ExtraView?
var viewLongPopUp:CYRKeyboardButtonView = CYRKeyboardButtonView()
var button = CYRKeyboardButton()
var currentMode: Int {
didSet {
if oldValue != currentMode {
setMode(currentMode)
}
forwardingView.currentMode = currentMode
}
}
var backspaceActive: Bool {
get {
return (backspaceDelayTimer != nil) || (backspaceRepeatTimer != nil)
}
}
var backspaceDelayTimer: NSTimer?
var backspaceRepeatTimer: NSTimer?
enum AutoPeriodState {
case NoSpace
case FirstSpace
}
var autoPeriodState: AutoPeriodState = .NoSpace
var lastCharCountInBeforeContext: Int = 0
var shiftState: ShiftState {
didSet {
switch shiftState {
case .Disabled:
self.updateKeyCaps(false)
case .Enabled:
self.updateKeyCaps(true)
case .Locked:
self.updateKeyCaps(true)
}
}
}
// state tracking during shift tap
var shiftWasMultitapped: Bool = false
var shiftStartingState: ShiftState?
var keyboardHeight: CGFloat {
get {
if let constraint = self.heightConstraint {
return constraint.constant
}
else {
return 0
}
}
set {
self.setHeight(newValue)
}
}
// TODO: why does the app crash if this isn't here?
convenience init() {
self.init(nibName: nil, bundle: nil)
}
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
// set setting defaults
NSUserDefaults.standardUserDefaults().registerDefaults([
kAutoCapitalization: true,
kPeriodShortcut: true,
kKeyboardClicks: false,
kSmallLowercase: true
])
self.keyboard = defaultKeyboard()
self.shiftState = .Disabled
self.currentMode = 0
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
self.forwardingView = ForwardingView(frame: CGRectZero)
self.view.addSubview(self.forwardingView)
initializePopUp()
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("defaultsChanged:"), name: NSUserDefaultsDidChangeNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("hideExpandView:"), name: "hideExpandViewNotification", object: nil)
}
required init?(coder: NSCoder) {
fatalError("NSCoding not supported")
}
deinit {
backspaceDelayTimer?.invalidate()
backspaceRepeatTimer?.invalidate()
NSNotificationCenter.defaultCenter().removeObserver(self)
}
func defaultsChanged(notification: NSNotification) {
self.updateKeyCaps(self.shiftState.uppercase())
}
// without this here kludge, the height constraint for the keyboard does not work for some reason
var kludge: UIView?
func setupKludge() {
if self.kludge == nil {
let kludge = UIView()
self.view.addSubview(kludge)
kludge.translatesAutoresizingMaskIntoConstraints = false
kludge.hidden = true
let a = NSLayoutConstraint(item: kludge, attribute: NSLayoutAttribute.Left, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.Left, multiplier: 1, constant: 0)
let b = NSLayoutConstraint(item: kludge, attribute: NSLayoutAttribute.Right, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.Left, multiplier: 1, constant: 0)
let c = NSLayoutConstraint(item: kludge, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.Top, multiplier: 1, constant: 0)
let d = NSLayoutConstraint(item: kludge, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.Top, multiplier: 1, constant: 0)
self.view.addConstraints([a, b, c, d])
self.kludge = kludge
}
}
/*
BUG NOTE
For some strange reason, a layout pass of the entire keyboard is triggered
whenever a popup shows up, if one of the following is done:
a) The forwarding view uses an autoresizing mask.
b) The forwarding view has constraints set anywhere other than init.
On the other hand, setting (non-autoresizing) constraints or just setting the
frame in layoutSubviews works perfectly fine.
I don't really know what to make of this. Am I doing Autolayout wrong, is it
a bug, or is it expected behavior? Perhaps this has to do with the fact that
the view's frame is only ever explicitly modified when set directly in layoutSubviews,
and not implicitly modified by various Autolayout constraints
(even though it should really not be changing).
*/
var constraintsAdded: Bool = false
func setupLayout() {
if !constraintsAdded {
self.layout = self.dynamicType.layoutClass.init(model: self.keyboard, superview: self.forwardingView, layoutConstants: self.dynamicType.layoutConstants, globalColors: self.dynamicType.globalColors, darkMode: self.darkMode(), solidColorMode: self.solidColorMode())
self.layout?.initialize()
self.setMode(0)
self.setupKludge()
self.updateKeyCaps(self.shiftState.uppercase())
self.setCapsIfNeeded()
self.updateAppearances(self.darkMode())
self.addInputTraitsObservers()
self.constraintsAdded = true
}
}
// only available after frame becomes non-zero
func darkMode() -> Bool {
let darkMode = { () -> Bool in
return textDocumentProxy.keyboardAppearance == UIKeyboardAppearance.Dark
}()
return darkMode
}
func solidColorMode() -> Bool {
return UIAccessibilityIsReduceTransparencyEnabled()
}
var lastLayoutBounds: CGRect?
override func viewDidLayoutSubviews() {
if view.bounds == CGRectZero {
return
}
self.setupLayout()
let orientationSavvyBounds = CGRectMake(0, 0, self.view.bounds.width, self.heightForOrientation(self.interfaceOrientation, withTopBanner: false))
if (lastLayoutBounds != nil && lastLayoutBounds == orientationSavvyBounds) {
// do nothing
}
else {
let uppercase = self.shiftState.uppercase()
let characterUppercase = (NSUserDefaults.standardUserDefaults().boolForKey(kSmallLowercase) ? uppercase : true)
self.forwardingView.frame = orientationSavvyBounds
self.layout?.layoutKeys(self.currentMode, uppercase: uppercase, characterUppercase: characterUppercase, shiftState: self.shiftState)
self.lastLayoutBounds = orientationSavvyBounds
self.setupKeys()
}
self.bannerView?.frame = CGRectMake(0, 0, self.view.bounds.width, metric("topBanner"))
let newOrigin = CGPointMake(0, self.view.bounds.height - self.forwardingView.bounds.height)
self.forwardingView.frame.origin = newOrigin
}
override func loadView() {
super.loadView()
if let aBanner = self.createBanner() {
aBanner.hidden = true
self.view.insertSubview(aBanner, belowSubview: self.forwardingView)
self.bannerView = aBanner
}
}
override func viewWillAppear(animated: Bool) {
self.bannerView?.hidden = false
self.keyboardHeight = self.heightForOrientation(self.interfaceOrientation, withTopBanner: true)
}
override func willRotateToInterfaceOrientation(toInterfaceOrientation: UIInterfaceOrientation, duration: NSTimeInterval) {
self.forwardingView.resetTrackedViews()
self.shiftStartingState = nil
self.shiftWasMultitapped = false
// optimization: ensures smooth animation
if let keyPool = self.layout?.keyPool {
for view in keyPool {
view.shouldRasterize = true
}
}
self.keyboardHeight = self.heightForOrientation(toInterfaceOrientation, withTopBanner: true)
}
override func didRotateFromInterfaceOrientation(fromInterfaceOrientation: UIInterfaceOrientation) {
// optimization: ensures quick mode and shift transitions
if let keyPool = self.layout?.keyPool {
for view in keyPool {
view.shouldRasterize = false
}
}
}
func heightForOrientation(orientation: UIInterfaceOrientation, withTopBanner: Bool) -> CGFloat {
let isPad = UIDevice.currentDevice().userInterfaceIdiom == UIUserInterfaceIdiom.Pad
//TODO: hardcoded stuff
let actualScreenWidth = (UIScreen.mainScreen().nativeBounds.size.width / UIScreen.mainScreen().nativeScale)
let canonicalPortraitHeight = (isPad ? CGFloat(264) : CGFloat(orientation.isPortrait && actualScreenWidth >= 400 ? 226 : 216))
let canonicalLandscapeHeight = (isPad ? CGFloat(352) : CGFloat(162))
let topBannerHeight = (withTopBanner ? metric("topBanner") : 0)
return CGFloat(orientation.isPortrait ? canonicalPortraitHeight + topBannerHeight : canonicalLandscapeHeight + topBannerHeight)
}
func hideExpandView(notification: NSNotification)
{
if notification.userInfo != nil
{
let title = notification.userInfo!["text"] as! String
if let proxy = (self.textDocumentProxy as? UIKeyInput)
{
if self.shiftState == .Enabled
{
proxy.insertText(title.capitalizedString)
}
else if self.shiftState == .Locked
{
proxy.insertText(title.uppercaseString)
}
else
{
proxy.insertText(title.lowercaseString)
}
}
self.setCapsIfNeeded()
}
viewLongPopUp.hidden = true
}
/*
BUG NOTE
None of the UIContentContainer methods are called for this controller.
*/
//override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) {
// super.viewWillTransitionToSize(size, withTransitionCoordinator: coordinator)
//}
func setupKeys() {
if self.layout == nil {
return
}
for page in keyboard.pages {
for rowKeys in page.rows { // TODO: quick hack
for key in rowKeys {
if let keyView = self.layout?.viewForKey(key) {
keyView.removeTarget(nil, action: nil, forControlEvents: UIControlEvents.AllEvents)
switch key.type {
case Key.KeyType.KeyboardChange:
keyView.addTarget(self, action: "advanceTapped:", forControlEvents: .TouchUpInside)
case Key.KeyType.Backspace:
let cancelEvents: UIControlEvents = [UIControlEvents.TouchUpInside, UIControlEvents.TouchUpInside, UIControlEvents.TouchDragExit, UIControlEvents.TouchUpOutside, UIControlEvents.TouchCancel, UIControlEvents.TouchDragOutside]
keyView.addTarget(self, action: "backspaceDown:", forControlEvents: .TouchDown)
keyView.addTarget(self, action: "backspaceUp:", forControlEvents: cancelEvents)
case Key.KeyType.Shift:
keyView.addTarget(self, action: Selector("shiftDown:"), forControlEvents: .TouchDown)
keyView.addTarget(self, action: Selector("shiftUp:"), forControlEvents: .TouchUpInside)
keyView.addTarget(self, action: Selector("shiftDoubleTapped:"), forControlEvents: .TouchDownRepeat)
case
Key.KeyType.LetterChange,
Key.KeyType.NumberChange,
Key.KeyType.SpecialCharacterChange:
keyView.addTarget(self, action: Selector("modeChangeTapped:"), forControlEvents: .TouchDown)
case Key.KeyType.Settings:
keyView.addTarget(self, action: Selector("toggleSettings"), forControlEvents: .TouchUpInside)
default:
break
}
if key.isCharacter {
if UIDevice.currentDevice().userInterfaceIdiom != UIUserInterfaceIdiom.Pad {
keyView.addTarget(self, action: Selector("showPopup:"), forControlEvents: [.TouchDown, .TouchDragInside, .TouchDragEnter])
keyView.addTarget(keyView, action: Selector("hidePopup"), forControlEvents: [.TouchDragExit, .TouchCancel])
keyView.addTarget(self, action: Selector("hidePopupDelay:"), forControlEvents: [.TouchUpInside, .TouchUpOutside, .TouchDragOutside])
}
keyView.addTarget(self, action: Selector("keyCharDoubleTapped:"), forControlEvents: .TouchDownRepeat)
}
if key.hasOutput {
keyView.addTarget(self, action: "keyPressedHelper:", forControlEvents: .TouchUpInside)
}
if key.type != Key.KeyType.Shift && key.type != Key.KeyType.LetterChange &&
key.type != Key.KeyType.NumberChange && key.type != Key.KeyType.SpecialCharacterChange {
keyView.addTarget(self, action: Selector("highlightKey:"), forControlEvents: [.TouchDown, .TouchDragInside, .TouchDragEnter])
keyView.addTarget(self, action: Selector("unHighlightKey:"), forControlEvents: [.TouchUpInside, .TouchUpOutside, .TouchDragOutside, .TouchDragExit, .TouchCancel])
}
keyView.addTarget(self, action: Selector("playKeySound"), forControlEvents: .TouchDown)
}
}
}
}
}
/////////////////
// POPUP DELAY //
/////////////////
var keyWithDelayedPopup: KeyboardKey?
var popupDelayTimer: NSTimer?
func showPopup(sender: KeyboardKey) {
if sender == self.keyWithDelayedPopup {
self.popupDelayTimer?.invalidate()
}
sender.showPopup()
}
func hidePopupDelay(sender: KeyboardKey) {
self.popupDelayTimer?.invalidate()
if sender != self.keyWithDelayedPopup {
self.keyWithDelayedPopup?.hidePopup()
self.keyWithDelayedPopup = sender
}
if sender.popup != nil {
self.popupDelayTimer = NSTimer.scheduledTimerWithTimeInterval(0.05, target: self, selector: Selector("hidePopupCallback"), userInfo: nil, repeats: false)
}
}
func hidePopupCallback() {
self.keyWithDelayedPopup?.hidePopup()
self.keyWithDelayedPopup = nil
self.popupDelayTimer = nil
}
/////////////////////
// POPUP DELAY END //
/////////////////////
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated
}
// TODO: this is currently not working as intended; only called when selection changed -- iOS bug
override func textDidChange(textInput: UITextInput?) {
self.contextChanged()
}
func contextChanged() {
self.setCapsIfNeeded()
self.autoPeriodState = .NoSpace
}
func setHeight(height: CGFloat) {
if self.heightConstraint == nil {
self.heightConstraint = NSLayoutConstraint(
item:self.view,
attribute:NSLayoutAttribute.Height,
relatedBy:NSLayoutRelation.Equal,
toItem:nil,
attribute:NSLayoutAttribute.NotAnAttribute,
multiplier:0,
constant:height)
self.heightConstraint!.priority = 999
self.view.addConstraint(self.heightConstraint!) // TODO: what if view already has constraint added?
}
else {
self.heightConstraint?.constant = height
}
}
func updateAppearances(appearanceIsDark: Bool) {
self.layout?.solidColorMode = self.solidColorMode()
self.layout?.darkMode = appearanceIsDark
self.layout?.updateKeyAppearance()
self.bannerView?.darkMode = appearanceIsDark
self.settingsView?.darkMode = appearanceIsDark
}
func highlightKey(sender: KeyboardKey) {
sender.highlighted = true
}
func unHighlightKey(sender: KeyboardKey) {
sender.highlighted = false
}
func keyPressedHelper(sender: KeyboardKey) {
if let model = self.layout?.keyForView(sender) {
self.keyPressed(model)
// auto exit from special char subkeyboard
if model.type == Key.KeyType.Space || model.type == Key.KeyType.Return {
self.currentMode = 0
}
else if model.lowercaseOutput == "'" {
self.currentMode = 0
}
else if model.type == Key.KeyType.Character {
self.currentMode = 0
}
// auto period on double space
// TODO: timeout
self.handleAutoPeriod(model)
// TODO: reset context
}
self.setCapsIfNeeded()
}
func handleAutoPeriod(key: Key) {
if !NSUserDefaults.standardUserDefaults().boolForKey(kPeriodShortcut) {
return
}
if self.autoPeriodState == .FirstSpace {
if key.type != Key.KeyType.Space {
self.autoPeriodState = .NoSpace
return
}
let charactersAreInCorrectState = { () -> Bool in
let previousContext = self.textDocumentProxy.documentContextBeforeInput
if previousContext == nil || (previousContext!).characters.count < 3 {
return false
}
var index = previousContext!.endIndex
index = index.predecessor()
if previousContext![index] != " " {
return false
}
index = index.predecessor()
if previousContext![index] != " " {
return false
}
index = index.predecessor()
let char = previousContext![index]
if self.characterIsWhitespace(char) || self.characterIsPunctuation(char) || char == "," {
return false
}
return true
}()
if charactersAreInCorrectState {
self.textDocumentProxy.deleteBackward()
self.textDocumentProxy.deleteBackward()
self.textDocumentProxy.insertText(".")
self.textDocumentProxy.insertText(" ")
}
self.autoPeriodState = .NoSpace
}
else {
if key.type == Key.KeyType.Space {
self.autoPeriodState = .FirstSpace
}
}
}
func cancelBackspaceTimers() {
self.backspaceDelayTimer?.invalidate()
self.backspaceRepeatTimer?.invalidate()
self.backspaceDelayTimer = nil
self.backspaceRepeatTimer = nil
}
func backspaceDown(sender: KeyboardKey) {
cancelBackspaceTimers()
let textDocumentProxy = self.textDocumentProxy
let context = textDocumentProxy.documentContextBeforeInput
if context != nil && context!.characters.count > 1 {
// if the character to delete is a new line character, we need
// to delete the empty space character as well.
let index = context!.endIndex.predecessor()
if context![index] == "\n" {
textDocumentProxy.deleteBackward()
}
}
textDocumentProxy.deleteBackward()
setCapsIfNeeded()
// trigger for subsequent deletes
backspaceDelayTimer = NSTimer.scheduledTimerWithTimeInterval(backspaceDelay - backspaceRepeat,
target: self, selector: Selector("backspaceDelayCallback"), userInfo: nil, repeats: false)
}
func backspaceUp(sender: KeyboardKey) {
self.cancelBackspaceTimers()
}
func backspaceDelayCallback() {
self.backspaceDelayTimer = nil
self.backspaceRepeatTimer = NSTimer.scheduledTimerWithTimeInterval(backspaceRepeat, target: self, selector: Selector("backspaceRepeatCallback"), userInfo: nil, repeats: true)
}
func backspaceRepeatCallback() {
playKeySound()
let textDocumentProxy = self.textDocumentProxy
let context = textDocumentProxy.documentContextBeforeInput
if context != nil && context!.characters.count > 1 {
// if the character to delete is a new line character, we need
// to delete the empty space character as well.
let index = context!.endIndex.predecessor()
if context![index] == "\n" {
textDocumentProxy.deleteBackward()
}
}
textDocumentProxy.deleteBackward()
setCapsIfNeeded()
}
func shiftDown(sender: KeyboardKey) {
self.shiftStartingState = self.shiftState
if let shiftStartingState = self.shiftStartingState {
if shiftStartingState.uppercase() {
// handled by shiftUp
return
}
else {
switch self.shiftState {
case .Disabled:
self.shiftState = .Enabled
case .Enabled:
self.shiftState = .Disabled
case .Locked:
self.shiftState = .Disabled
}
(sender.shape as? ShiftShape)?.withLock = false
}
}
}
func shiftUp(sender: KeyboardKey) {
if self.shiftWasMultitapped {
// do nothing
}
else {
if let shiftStartingState = self.shiftStartingState {
if !shiftStartingState.uppercase() {
// handled by shiftDown
}
else {
switch self.shiftState {
case .Disabled:
self.shiftState = .Enabled
case .Enabled:
self.shiftState = .Disabled
case .Locked:
self.shiftState = .Disabled
}
(sender.shape as? ShiftShape)?.withLock = false
}
}
}
self.shiftStartingState = nil
self.shiftWasMultitapped = false
}
func shiftDoubleTapped(sender: KeyboardKey) {
self.shiftWasMultitapped = true
switch self.shiftState {
case .Disabled:
self.shiftState = .Locked
case .Enabled:
self.shiftState = .Locked
case .Locked:
self.shiftState = .Disabled
}
}
func updateKeyCaps(uppercase: Bool) {
let characterUppercase = (NSUserDefaults.standardUserDefaults().boolForKey(kSmallLowercase) ? uppercase : true)
self.layout?.updateKeyCaps(false, uppercase: uppercase, characterUppercase: characterUppercase, shiftState: self.shiftState)
}
func modeChangeTapped(sender: KeyboardKey) {
if let toMode = self.layout?.viewToModel[sender]?.toMode {
self.currentMode = toMode
}
}
func setMode(mode: Int) {
self.forwardingView.resetTrackedViews()
self.shiftStartingState = nil
self.shiftWasMultitapped = false
let uppercase = self.shiftState.uppercase()
let characterUppercase = (NSUserDefaults.standardUserDefaults().boolForKey(kSmallLowercase) ? uppercase : true)
self.layout?.layoutKeys(mode, uppercase: uppercase, characterUppercase: characterUppercase, shiftState: self.shiftState)
self.setupKeys()
}
func advanceTapped(sender: KeyboardKey) {
self.forwardingView.resetTrackedViews()
self.shiftStartingState = nil
self.shiftWasMultitapped = false
self.advanceToNextInputMode()
}
@IBAction func toggleSettings() {
// lazy load settings
if self.settingsView == nil {
if let aSettings = self.createSettings() {
aSettings.darkMode = self.darkMode()
aSettings.hidden = true
self.view.addSubview(aSettings)
self.settingsView = aSettings
aSettings.translatesAutoresizingMaskIntoConstraints = false
let widthConstraint = NSLayoutConstraint(item: aSettings, attribute: NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.Width, multiplier: 1, constant: 0)
let heightConstraint = NSLayoutConstraint(item: aSettings, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.Height, multiplier: 1, constant: 0)
let centerXConstraint = NSLayoutConstraint(item: aSettings, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.CenterX, multiplier: 1, constant: 0)
let centerYConstraint = NSLayoutConstraint(item: aSettings, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.CenterY, multiplier: 1, constant: 0)
self.view.addConstraint(widthConstraint)
self.view.addConstraint(heightConstraint)
self.view.addConstraint(centerXConstraint)
self.view.addConstraint(centerYConstraint)
}
}
if let settings = self.settingsView {
let hidden = settings.hidden
settings.hidden = !hidden
self.forwardingView.hidden = hidden
self.forwardingView.userInteractionEnabled = !hidden
self.bannerView?.hidden = hidden
}
}
func setCapsIfNeeded() -> Bool {
if self.shouldAutoCapitalize() {
switch self.shiftState {
case .Disabled:
self.shiftState = .Enabled
case .Enabled:
self.shiftState = .Enabled
case .Locked:
self.shiftState = .Locked
}
return true
}
else {
switch self.shiftState {
case .Disabled:
self.shiftState = .Disabled
case .Enabled:
self.shiftState = .Disabled
case .Locked:
self.shiftState = .Locked
}
return false
}
}
func characterIsPunctuation(character: Character) -> Bool {
return (character == ".") || (character == "!") || (character == "?")
}
func characterIsNewline(character: Character) -> Bool {
return (character == "\n") || (character == "\r")
}
func characterIsWhitespace(character: Character) -> Bool {
// there are others, but who cares
return (character == " ") || (character == "\n") || (character == "\r") || (character == "\t")
}
func stringIsWhitespace(string: String?) -> Bool {
if string != nil {
for char in (string!).characters {
if !characterIsWhitespace(char) {
return false
}
}
}
return true
}
func shouldAutoCapitalize() -> Bool {
if !NSUserDefaults.standardUserDefaults().boolForKey(kAutoCapitalization) {
return false
}
if let autocapitalization = textDocumentProxy.autocapitalizationType {
switch autocapitalization {
case .None:
return false
case .Words:
if let beforeContext = textDocumentProxy.documentContextBeforeInput {
let previousCharacter = beforeContext[beforeContext.endIndex.predecessor()]
return self.characterIsWhitespace(previousCharacter)
}
else {
return true
}
case .Sentences:
if let beforeContext = textDocumentProxy.documentContextBeforeInput {
let offset = min(3, beforeContext.characters.count)
var index = beforeContext.endIndex
for (var i = 0; i < offset; i += 1) {
index = index.predecessor()
let char = beforeContext[index]
if characterIsPunctuation(char) {
if i == 0 {
return false //not enough spaces after punctuation
}
else {
return true //punctuation with at least one space after it
}
}
else {
if !characterIsWhitespace(char) {
return false //hit a foreign character before getting to 3 spaces
}
else if characterIsNewline(char) {
return true //hit start of line
}
}
}
return true //either got 3 spaces or hit start of line
}
else {
return true
}
case .AllCharacters:
return true
}
}
else {
return false
}
}
// this only works if full access is enabled
func playKeySound() {
if !NSUserDefaults.standardUserDefaults().boolForKey(kKeyboardClicks) {
return
}
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), {
AudioServicesPlaySystemSound(1104)
})
}
// setups long pressed popup keys
func initializePopUp() {
button.hidden = true
button.forwordingView = forwardingView
button.frame = CGRectMake(0, 0, 20, 20)
button.tag = 111
self.view.insertSubview(self.button, aboveSubview: self.forwardingView)
button.setupInputOptionsConfigurationWithView(forwardingView)
button.hidden = true
viewLongPopUp.hidden = true
}
// called when a key that is allowed to have multiple characters is pressed and held
// shows multiple options
func keyCharDoubleTapped(sender: KeyboardKey) {
if sender.tag == 888 {
sender.hidePopup()
if let key = self.layout?.keyForView(sender) {
var arrOptions: [String] = []
if (key.type == Key.KeyType.Character) {
if self.shiftState == .Locked {
// convert all letters to uppercase
arrOptions = key.extraCharacters.map(
{ (letter: String) -> String in
return (letter as NSString).uppercaseString})
} else if self.shiftState == .Enabled || !NSUserDefaults.standardUserDefaults().boolForKey(kSmallLowercase) {
// capitalize the String
arrOptions = key.extraCharacters.map(
{ (letter: String) -> String in
return (letter as NSString).capitalizedString})
} else {
// convert to lowercase
arrOptions = key.extraCharacters.map(
{ (letter: String) -> String in
return (letter as NSString).lowercaseString})
}
}
if arrOptions.count > 0 {
if arrOptions[0].characters.count > 0 {
var offsetY : CGFloat = 9
if KeyboardViewController.getDeviceType() == TTDeviceType.TTDeviceTypeIPhone4 {
offsetY = 9
if self.interfaceOrientation == UIInterfaceOrientation.LandscapeLeft || self.interfaceOrientation == UIInterfaceOrientation.LandscapeRight {
offsetY = 3
}
} else if KeyboardViewController.getDeviceType() == TTDeviceType.TTDeviceTypeIPhone5 {
offsetY = 9
if self.interfaceOrientation == UIInterfaceOrientation.LandscapeLeft || self.interfaceOrientation == UIInterfaceOrientation.LandscapeRight {
offsetY = 3
}
} else if KeyboardViewController.getDeviceType() == TTDeviceType.TTDeviceTypeIPhone6 {
offsetY = 13
if self.interfaceOrientation == UIInterfaceOrientation.LandscapeLeft || self.interfaceOrientation == UIInterfaceOrientation.LandscapeRight {
offsetY = 3
}
} else if KeyboardViewController.getDeviceType() == TTDeviceType.TTDeviceTypeIPhone6p {
offsetY = 16
if self.interfaceOrientation == UIInterfaceOrientation.LandscapeLeft || self.interfaceOrientation == UIInterfaceOrientation.LandscapeRight {
offsetY = 3
}
}
self.button.removeFromSuperview()
self.button.frame = CGRectMake(sender.frame.origin.x, sender.frame.origin.y + sender.frame.size.height - offsetY, sender.frame.size.width, sender.frame.size.height)
// self.button.frame = CGRectMake(sender.frame.origin.x, sender.frame.origin.y , sender.frame.size.width, sender.frame.size.height)
self.view.insertSubview(self.button, aboveSubview: self.forwardingView)
self.viewLongPopUp = self.button.showLongPopUpOptions()
self.button.input = sender.text
self.button.hidden = true
self.button.inputOptions = arrOptions
self.viewLongPopUp.hidden = false
for anyView in self.view.subviews {
if anyView is CYRKeyboardButtonView {
anyView.removeFromSuperview()
}
}
self.viewLongPopUp.userInteractionEnabled = false;
button.setupInputOptionsConfigurationWithView(forwardingView)
self.view.insertSubview(self.viewLongPopUp, aboveSubview: self.forwardingView)
self.forwardingView.isLongPressEnable = true
self.view.bringSubviewToFront(self.viewLongPopUp)
//self.forwardingView.resetTrackedViews()
//sender.hidePopup()
//self.view.addSubview(self.viewLongPopUp)
sender.tag = 0
}
}
}
}
}
// returns the device type
class func getDeviceType()->TTDeviceType {
var height = UIScreen.mainScreen().bounds.size.height
if UIScreen.mainScreen().bounds.size.height < UIScreen.mainScreen().bounds.size.width {
height = UIScreen.mainScreen().bounds.size.width
}
switch (height) {
case 480:
deviceType = TTDeviceType.TTDeviceTypeIPhone4 ;
break;
case 568:
deviceType = TTDeviceType.TTDeviceTypeIPhone5 ;
break;
case 667:
deviceType = TTDeviceType.TTDeviceTypeIPhone6 ;
break;
case 736:
deviceType = TTDeviceType.TTDeviceTypeIPhone6p ;
break;
default:
break;
}
return deviceType
}
//////////////////////////////////////
// MOST COMMONLY EXTENDABLE METHODS //
//////////////////////////////////////
class var layoutClass: KeyboardLayout.Type { get { return KeyboardLayout.self }}
class var layoutConstants: LayoutConstants.Type { get { return LayoutConstants.self }}
class var globalColors: GlobalColors.Type { get { return GlobalColors.self }}
func keyPressed(key: Key) {
textDocumentProxy.insertText(key.outputForCase(self.shiftState.uppercase()))
}
// a banner that sits in the empty space on top of the keyboard
func createBanner() -> ExtraView? {
// note that dark mode is not yet valid here, so we just put false for clarity
//return ExtraView(globalColors: self.dynamicType.globalColors, darkMode: false, solidColorMode: self.solidColorMode())
return nil
}
// a settings view that replaces the keyboard when the settings button is pressed
func createSettings() -> ExtraView? {
// note that dark mode is not yet valid here, so we just put false for clarity
let settingsView = DefaultSettings(globalColors: self.dynamicType.globalColors, darkMode: false, solidColorMode: self.solidColorMode())
settingsView.backButton?.addTarget(self, action: Selector("toggleSettings"), forControlEvents: UIControlEvents.TouchUpInside)
return settingsView
}
}
| bsd-3-clause | 958a457d6e0194f783928d69347bf3c7 | 38.4875 | 275 | 0.561838 | 6.260213 | false | false | false | false |
crossroadlabs/reSwiftInception | reSwift/Controllers/SearchListVC.swift | 1 | 3464 | //
// SearchListVC.swift
// reSwift
//
// Created by Roman Stolyarchuk on 10/18/17.
// Copyright © 2017 Crossroad Labs s.r.o. All rights reserved.
//
import UIKit
class SearchListVC: UIViewController, UISearchBarDelegate {
@IBOutlet weak var searchBar: UISearchBar!
@IBOutlet weak var searchListTV: UITableView!
@IBOutlet weak var segmentControl: UISegmentedControl!
@IBOutlet weak var hideKeyboardButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
//118,36,32
searchBar.changeSearchBarColor(color: UIColor(red: 118/255, green: 36/255, blue: 32/255, alpha: 1))
searchBar.changeSearchTextColor(color: .white)
searchBar.clearBackground()
searchListTV.delegate = self
searchListTV.dataSource = self
searchListTV.register(UINib(nibName: "SearchCell", bundle: nil), forCellReuseIdentifier: "SearchCell")
searchListTV.register(UINib(nibName: "UserCell", bundle: nil), forCellReuseIdentifier: "UserCell")
segmentControl.sendActions(for: .valueChanged)
hideKeyboardButton.isHidden = true
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
view.endEditing(true)
}
override var preferredStatusBarStyle: UIStatusBarStyle {
return .lightContent
}
@IBAction func segmentedControlAction(sender: UISegmentedControl) {
if(sender.selectedSegmentIndex == 0)
{
print("Repositories")
}
else if(sender.selectedSegmentIndex == 1)
{
print("Users")
}
searchListTV.reloadData()
}
@IBAction func hideButton(sender: UIButton) {
view.endEditing(true)
hideKeyboardButton.isHidden = true
}
func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
hideKeyboardButton.isHidden = false
}
}
extension SearchListVC: UITableViewDelegate,UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 10
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if segmentControl.selectedSegmentIndex == 0 {
if let cell = tableView.dequeueReusableCell(withIdentifier: "SearchCell") as? SearchCell {
return cell
}
} else {
if let cell = tableView.dequeueReusableCell(withIdentifier: "UserCell") as? UserCell {
return cell
}
}
return UITableViewCell()
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if segmentControl.selectedSegmentIndex == 0 {
if let repoVC = UIStoryboard(name: "Repositories", bundle: nil).instantiateViewController(withIdentifier: "RepositoriesController") as? RepositoriesController {
self.navigationController?.pushViewController(repoVC, animated: true)
}
} else {
if let profileVC = UIStoryboard(name: "Profile", bundle: nil).instantiateViewController(withIdentifier: "ProfileVC") as? ProfileVC {
self.navigationController?.pushViewController(profileVC, animated: true)
}
}
}
}
| bsd-3-clause | c4b04975e0ced609bfccd63736ac4e95 | 32.95098 | 172 | 0.647993 | 5.419405 | false | false | false | false |
tad-iizuka/swift-sdk | Source/TextToSpeechV1/Models/CustomVoiceUpdate.swift | 3 | 1710 | /**
* Copyright IBM Corporation 2016
*
* 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 RestKit
/** A custom voice model used by the Text to Speech service. */
public struct CustomVoiceUpdate: JSONEncodable {
/// The new name for the custom voice model.
private let name: String?
/// The new description for the custom voice model.
private let description: String?
/// A list of words and their translations from the custom voice model.
private let words: [Word]
/// Used to initialize a `CustomVoiceUpdate` model.
public init(name: String? = nil, description: String? = nil, words: [Word] = []) {
self.name = name
self.description = description
self.words = words
}
/// Used internally to serialize a `CustomVoiceUpdate` model to JSON.
public func toJSONObject() -> Any {
var json = [String: Any]()
if let name = name {
json["name"] = name
}
if let description = description {
json["description"] = description
}
json["words"] = words.map { word in word.toJSONObject() }
return json
}
}
| apache-2.0 | c45349f1b85fbf1b3a26cde47c33be67 | 31.884615 | 86 | 0.652632 | 4.511873 | false | false | false | false |
mozilla-mobile/prox | Prox/Prox/PlaceDetails/PlaceDetailsTravelTimesView.swift | 1 | 2905 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
class PlaceDetailsTravelTimesView: PlaceDetailsIconInfoView, TravelTimesView {
fileprivate var idForTravelTimesView: String?
convenience init() {
self.init(enableForwardArrow: true)
}
func getIDForTravelTimesView() -> String? { return idForTravelTimesView }
func setIDForTravelTimesView(_ id: String) { idForTravelTimesView = id }
func prepareTravelTimesUIForReuse() {
self.isLoading = false
forwardArrowView.isHidden = true
primaryTextLabel.text = nil
secondaryTextLabel.text = nil
iconView.image = nil
}
func setTravelTimesUIIsLoading(_ isLoading: Bool) {
// Problem: we get rate-limited for travel times requests. When rate limited, one of the
// requests never returns, leaving the user with a loading spinner. The loading spinner
// hides the "View on Map" text, which allows the user to click through for directions.
//
// HACK: We request travel times on startup in order to sort the list of places. In practice,
// this means we never see a spinner when the content is loading but only in the problem
// situtation above. So instead of adding complexity by managing the state of our active
// directions requests, we just show "View on Map" instead.
updateTravelTimesUIForResult(.noData, durationInMinutes: nil)
}
func updateTravelTimesUIForResult(_ result: TravelTimesViewResult, durationInMinutes: Int?) {
iconView.isHidden = false
secondaryTextLabel.numberOfLines = 1
switch result {
case .userHere:
isPrimaryTextLabelHidden = true
forwardArrowView.isHidden = true
secondaryTextLabel.text = "You're here!"
iconView.image = UIImage(named: "icon_here")
case .walkingDist:
isPrimaryTextLabelHidden = false
forwardArrowView.isHidden = false
primaryTextLabel.text = "\(durationInMinutes!) min"
secondaryTextLabel.text = "Walking"
iconView.image = UIImage(named: "icon_walkingdist")
case .drivingDist:
isPrimaryTextLabelHidden = false
forwardArrowView.isHidden = false
primaryTextLabel.text = "\(durationInMinutes!) min"
secondaryTextLabel.text = "Driving"
iconView.image = UIImage(named: "icon_drivingdist")
case .noData:
isPrimaryTextLabelHidden = true
forwardArrowView.isHidden = false
secondaryTextLabel.numberOfLines = 2
secondaryTextLabel.text = "Check map\nfor distance"
iconView.isHidden = true
}
}
}
| mpl-2.0 | 2f5a626c0190b25519080bf24c057a61 | 40.5 | 101 | 0.664716 | 5.078671 | false | false | false | false |
skyfe79/RxPlayground | RxToDoList-MVVM/Pods/RxCocoa/RxCocoa/Common/Observables/NSURLSession+Rx.swift | 18 | 8187 | //
// NSURLSession+Rx.swift
// RxCocoa
//
// Created by Krunoslav Zaher on 3/23/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
#if !RX_NO_MODULE
import RxSwift
#endif
/**
RxCocoa URL errors.
*/
public enum RxCocoaURLError
: ErrorType
, CustomDebugStringConvertible {
/**
Unknown error occurred.
*/
case Unknown
/**
Response is not NSHTTPURLResponse
*/
case NonHTTPResponse(response: NSURLResponse)
/**
Response is not successful. (not in `200 ..< 300` range)
*/
case HTTPRequestFailed(response: NSHTTPURLResponse, data: NSData?)
/**
Deserialization error.
*/
case DeserializationError(error: ErrorType)
}
public extension RxCocoaURLError {
/**
A textual representation of `self`, suitable for debugging.
*/
public var debugDescription: String {
switch self {
case .Unknown:
return "Unknown error has occurred."
case let .NonHTTPResponse(response):
return "Response is not NSHTTPURLResponse `\(response)`."
case let .HTTPRequestFailed(response, _):
return "HTTP request failed with `\(response.statusCode)`."
case let .DeserializationError(error):
return "Error during deserialization of the response: \(error)"
}
}
}
func escapeTerminalString(value: String) -> String {
return value.stringByReplacingOccurrencesOfString("\"", withString: "\\\"", options:[], range: nil)
}
func convertURLRequestToCurlCommand(request: NSURLRequest) -> String {
let method = request.HTTPMethod ?? "GET"
var returnValue = "curl -i -v -X \(method) "
if request.HTTPMethod == "POST" && request.HTTPBody != nil {
let maybeBody = NSString(data: request.HTTPBody!, encoding: NSUTF8StringEncoding) as? String
if let body = maybeBody {
returnValue += "-d \"\(escapeTerminalString(body))\" "
}
}
for (key, value) in request.allHTTPHeaderFields ?? [:] {
let escapedKey = escapeTerminalString((key as String) ?? "")
let escapedValue = escapeTerminalString((value as String) ?? "")
returnValue += "-H \"\(escapedKey): \(escapedValue)\" "
}
let URLString = request.URL?.absoluteString ?? "<unknown url>"
returnValue += "\"\(escapeTerminalString(URLString))\""
return returnValue
}
func convertResponseToString(data: NSData!, _ response: NSURLResponse!, _ error: NSError!, _ interval: NSTimeInterval) -> String {
let ms = Int(interval * 1000)
if let response = response as? NSHTTPURLResponse {
if 200 ..< 300 ~= response.statusCode {
return "Success (\(ms)ms): Status \(response.statusCode)"
}
else {
return "Failure (\(ms)ms): Status \(response.statusCode)"
}
}
if let error = error {
if error.domain == NSURLErrorDomain && error.code == NSURLErrorCancelled {
return "Cancelled (\(ms)ms)"
}
return "Failure (\(ms)ms): NSError > \(error)"
}
return "<Unhandled response from server>"
}
extension NSURLSession {
/**
Observable sequence of responses for URL request.
Performing of request starts after observer is subscribed and not after invoking this method.
**URL requests will be performed per subscribed observer.**
Any error during fetching of the response will cause observed sequence to terminate with error.
- parameter request: URL request.
- returns: Observable sequence of URL responses.
*/
@warn_unused_result(message="http://git.io/rxs.uo")
public func rx_response(request: NSURLRequest) -> Observable<(NSData, NSHTTPURLResponse)> {
return Observable.create { observer in
// smart compiler should be able to optimize this out
var d: NSDate?
if Logging.URLRequests(request) {
d = NSDate()
}
let task = self.dataTaskWithRequest(request) { (data, response, error) in
if Logging.URLRequests(request) {
let interval = NSDate().timeIntervalSinceDate(d ?? NSDate())
print(convertURLRequestToCurlCommand(request))
print(convertResponseToString(data, response, error, interval))
}
guard let response = response, data = data else {
observer.on(.Error(error ?? RxCocoaURLError.Unknown))
return
}
guard let httpResponse = response as? NSHTTPURLResponse else {
observer.on(.Error(RxCocoaURLError.NonHTTPResponse(response: response)))
return
}
observer.on(.Next(data, httpResponse))
observer.on(.Completed)
}
let t = task
t.resume()
return AnonymousDisposable {
task.cancel()
}
}
}
/**
Observable sequence of response data for URL request.
Performing of request starts after observer is subscribed and not after invoking this method.
**URL requests will be performed per subscribed observer.**
Any error during fetching of the response will cause observed sequence to terminate with error.
If response is not HTTP response with status code in the range of `200 ..< 300`, sequence
will terminate with `(RxCocoaErrorDomain, RxCocoaError.NetworkError)`.
- parameter request: URL request.
- returns: Observable sequence of response data.
*/
@warn_unused_result(message="http://git.io/rxs.uo")
public func rx_data(request: NSURLRequest) -> Observable<NSData> {
return rx_response(request).map { (data, response) -> NSData in
if 200 ..< 300 ~= response.statusCode {
return data ?? NSData()
}
else {
throw RxCocoaURLError.HTTPRequestFailed(response: response, data: data)
}
}
}
/**
Observable sequence of response JSON for URL request.
Performing of request starts after observer is subscribed and not after invoking this method.
**URL requests will be performed per subscribed observer.**
Any error during fetching of the response will cause observed sequence to terminate with error.
If response is not HTTP response with status code in the range of `200 ..< 300`, sequence
will terminate with `(RxCocoaErrorDomain, RxCocoaError.NetworkError)`.
If there is an error during JSON deserialization observable sequence will fail with that error.
- parameter request: URL request.
- returns: Observable sequence of response JSON.
*/
@warn_unused_result(message="http://git.io/rxs.uo")
public func rx_JSON(request: NSURLRequest) -> Observable<AnyObject> {
return rx_data(request).map { (data) -> AnyObject in
do {
return try NSJSONSerialization.JSONObjectWithData(data ?? NSData(), options: [])
} catch let error {
throw RxCocoaURLError.DeserializationError(error: error)
}
}
}
/**
Observable sequence of response JSON for GET request with `URL`.
Performing of request starts after observer is subscribed and not after invoking this method.
**URL requests will be performed per subscribed observer.**
Any error during fetching of the response will cause observed sequence to terminate with error.
If response is not HTTP response with status code in the range of `200 ..< 300`, sequence
will terminate with `(RxCocoaErrorDomain, RxCocoaError.NetworkError)`.
If there is an error during JSON deserialization observable sequence will fail with that error.
- parameter URL: URL of `NSURLRequest` request.
- returns: Observable sequence of response JSON.
*/
@warn_unused_result(message="http://git.io/rxs.uo")
public func rx_JSON(URL: NSURL) -> Observable<AnyObject> {
return rx_JSON(NSURLRequest(URL: URL))
}
}
| mit | bf79907ade4c0b88cbbe5a0aea25f3fd | 33.394958 | 130 | 0.629612 | 5.187579 | false | false | false | false |
practicalswift/swift | stdlib/public/core/SetCasting.swift | 6 | 3124 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2018 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
//
//===----------------------------------------------------------------------===//
//===--- Compiler conversion/casting entry points for Set<Element> --------===//
/// Perform a non-bridged upcast that always succeeds.
///
/// - Precondition: `BaseValue` is a base class or base `@objc`
/// protocol (such as `AnyObject`) of `DerivedValue`.
@inlinable
public func _setUpCast<DerivedValue, BaseValue>(_ source: Set<DerivedValue>)
-> Set<BaseValue> {
var builder = _SetBuilder<BaseValue>(count: source.count)
for x in source {
builder.add(member: x as! BaseValue)
}
return builder.take()
}
/// Called by the casting machinery.
@_silgen_name("_swift_setDownCastIndirect")
internal func _setDownCastIndirect<SourceValue, TargetValue>(
_ source: UnsafePointer<Set<SourceValue>>,
_ target: UnsafeMutablePointer<Set<TargetValue>>) {
target.initialize(to: _setDownCast(source.pointee))
}
/// Implements a forced downcast. This operation should have O(1) complexity.
///
/// The cast can fail if bridging fails. The actual checks and bridging can be
/// deferred.
///
/// - Precondition: `DerivedValue` is a subtype of `BaseValue` and both
/// are reference types.
@inlinable
public func _setDownCast<BaseValue, DerivedValue>(_ source: Set<BaseValue>)
-> Set<DerivedValue> {
#if _runtime(_ObjC)
if _isClassOrObjCExistential(BaseValue.self)
&& _isClassOrObjCExistential(DerivedValue.self) {
guard source._variant.isNative else {
return Set(_immutableCocoaSet: source._variant.asCocoa.object)
}
return Set(_immutableCocoaSet: source._variant.asNative.bridged())
}
#endif
return _setDownCastConditional(source)!
}
/// Called by the casting machinery.
@_silgen_name("_swift_setDownCastConditionalIndirect")
internal func _setDownCastConditionalIndirect<SourceValue, TargetValue>(
_ source: UnsafePointer<Set<SourceValue>>,
_ target: UnsafeMutablePointer<Set<TargetValue>>
) -> Bool {
if let result: Set<TargetValue> = _setDownCastConditional(source.pointee) {
target.initialize(to: result)
return true
}
return false
}
/// Implements a conditional downcast.
///
/// If the cast fails, the function returns `nil`. All checks should be
/// performed eagerly.
///
/// - Precondition: `DerivedValue` is a subtype of `BaseValue` and both
/// are reference types.
@inlinable
public func _setDownCastConditional<BaseValue, DerivedValue>(
_ source: Set<BaseValue>
) -> Set<DerivedValue>? {
var result = Set<DerivedValue>(minimumCapacity: source.count)
for member in source {
if let derivedMember = member as? DerivedValue {
result.insert(derivedMember)
continue
}
return nil
}
return result
}
| apache-2.0 | b7c3010a5f4747aa49d4efeacd849a88 | 32.591398 | 80 | 0.684059 | 4.443812 | false | false | false | false |
lerigos/music-service | iOS_9/Pods/SwiftyVK/Source/SDK/Models/Token.swift | 2 | 6751 | import Foundation
private var tokenInstance : Token! {
willSet {
if newValue != nil {
Token.notifyExist()
}
else {
Token.notifyNotExist()
}
}
}
internal class Token: NSObject, NSCoding {
internal private(set) static var revoke = true
private var token : String
private var expires : Int
private var isOffline = false
private var parameters : Dictionary<String, String>
override var description : String {
return "Token with parameters: \(parameters))"
}
init(urlString: String) {
let parameters = Token.parse(urlString)
token = parameters["access_token"]!
expires = 0 + Int(NSDate().timeIntervalSince1970)
if parameters["expires_in"] != nil {expires += Int(parameters["expires_in"]!)!}
isOffline = (parameters["expires_in"]?.isEmpty == false && (Int(parameters["expires_in"]!) == 0) || parameters["expires_in"] == nil)
self.parameters = parameters
super.init()
tokenInstance = self
Token.revoke = true
VK.Log.put("Token", "INIT \(self)")
save()
}
init(token: String, expires : Int = 0, parameters: Dictionary<String, String> = [:]) {
self.token = token
self.expires = expires
self.parameters = parameters
super.init()
tokenInstance = self
Token.revoke = true
VK.Log.put("Token", "INIT \(self)")
save()
}
class func get() -> String? {
VK.Log.put("Token", "Getting")
if tokenInstance != nil && self.isExpired() == false {
return tokenInstance.token
}
else if let _ = _load() where self.isExpired() == false {
return tokenInstance.token
}
return nil
}
class var exist : Bool {
return tokenInstance != nil
}
private class func parse(request: String) -> Dictionary<String, String> {
let cleanRequest = request.componentsSeparatedByString("#")[1]
let preParameters = cleanRequest.componentsSeparatedByString("&")
var parameters = Dictionary<String, String>()
for keyValueString in preParameters {
let keyValueArray = keyValueString.componentsSeparatedByString("=")
parameters[keyValueArray[0]] = keyValueArray[1]
}
VK.Log.put("Token", "Parse from parameters: \(parameters)")
return parameters
}
private class func isExpired() -> Bool {
if tokenInstance == nil {
return true
}
else if tokenInstance.isOffline == false && tokenInstance.expires < Int(NSDate().timeIntervalSince1970) {
VK.Log.put("Token", "Expired")
revoke = false
Token.remove()
return true
}
return false
}
private class func _load() -> Token? {
let parameters = VK.delegate.vkTokenPath()
let useDefaults = parameters.useUserDefaults
let filePath = parameters.alternativePath
if useDefaults {tokenInstance = self.loadFromDefaults()}
else {tokenInstance = self.loadFromFile(filePath)}
return tokenInstance
}
private class func loadFromDefaults() -> Token? {
let defaults = NSUserDefaults.standardUserDefaults()
if !(defaults.objectForKey("Token") != nil) {return nil}
let object: AnyObject! = NSKeyedUnarchiver.unarchiveObjectWithData(defaults.objectForKey("Token") as! NSData)
if object == nil {
VK.Log.put("Token", "Load from NSUSerDefaults failed")
return nil
}
VK.Log.put("Token", "Loaded from NSUserDefaults")
return object as? Token
}
///Загрузка из файла
private class func loadFromFile(filePath : String) -> Token? {
let manager = NSFileManager.defaultManager()
if !manager.fileExistsAtPath(filePath) {
VK.Log.put("Token", "Loaded from file \(filePath) failed")
return nil
}
let token = (NSKeyedUnarchiver.unarchiveObjectWithFile(filePath)) as? Token
VK.Log.put("Token", "Loaded from file: \(filePath)")
return token
}
func save() {
let parameters = VK.delegate.vkTokenPath()
let useDefaults = parameters.useUserDefaults
let filePath = parameters.alternativePath
if useDefaults {saveToDefaults()}
else {saveToFile(filePath)}
}
private func saveToDefaults() {
let defaults = NSUserDefaults.standardUserDefaults()
defaults.setObject(NSKeyedArchiver.archivedDataWithRootObject(self), forKey: "Token")
defaults.synchronize()
VK.Log.put("Token", "Saved to NSUserDefaults")
}
private func saveToFile(filePath : String) {
let manager = NSFileManager.defaultManager()
if manager.fileExistsAtPath(filePath) {
do {
try manager.removeItemAtPath(filePath)
}
catch _ {}
}
NSKeyedArchiver.archiveRootObject(self, toFile: filePath)
VK.Log.put("Token", "Saved to file: \(filePath)")
}
class func remove() {
let parameters = VK.delegate.vkTokenPath()
let useDefaults = parameters.useUserDefaults
let filePath = parameters.alternativePath
let defaults = NSUserDefaults.standardUserDefaults()
if defaults.objectForKey("Token") != nil {defaults.removeObjectForKey("Token")}
defaults.synchronize()
if !useDefaults {
let manager = NSFileManager.defaultManager()
if manager.fileExistsAtPath(filePath) {
do {try manager.removeItemAtPath(filePath)}
catch _ {}
}
}
if tokenInstance != nil {tokenInstance = nil}
VK.Log.put("Token", "Remove")
}
private class func notifyExist() {
if VK.state != .Authorized {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
NSThread.sleepForTimeInterval(0.1)
if tokenInstance != nil {
VK.delegate.vkDidAutorize(tokenInstance.parameters)
}
}
}
}
private class func notifyNotExist() {
if VK.state == .Authorized {
VK.delegate.vkDidUnautorize()
}
}
deinit {VK.Log.put("Token", "DEINIT \(self)")}
//MARK: - NSCoding protocol
func encodeWithCoder(aCoder: NSCoder) {
aCoder.encodeObject(parameters, forKey: "parameters")
aCoder.encodeObject(token, forKey: "token")
aCoder.encodeInteger(expires, forKey: "expires")
aCoder.encodeBool(isOffline, forKey: "isOffline")
}
required init?(coder aDecoder: NSCoder) {
token = aDecoder.decodeObjectForKey("token") as! String
expires = aDecoder.decodeIntegerForKey("expires")
isOffline = aDecoder.decodeBoolForKey("isOffline")
if let parameters = aDecoder.decodeObjectForKey("parameters") as? Dictionary<String, String> {
self.parameters = parameters
}
else {
self.parameters = [:]
}
}
}
| apache-2.0 | 16622f77eba37c892a50065fcafc00d9 | 25.415686 | 138 | 0.642072 | 4.576087 | false | false | false | false |
blockchain/My-Wallet-V3-iOS | Modules/FeatureTransaction/Sources/FeatureTransactionUI/FiatAccountTransactions/Deposit/DepositRoot/DepositRootRouter.swift | 1 | 6784 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
import AnalyticsKit
import DIKit
import MoneyKit
import PlatformKit
import PlatformUIKit
import RIBs
import RxSwift
import ToolKit
import UIComponentsKit
protocol DepositRootInteractable: Interactable,
TransactionFlowListener,
PaymentMethodListener,
AddNewBankAccountListener
{
var router: DepositRootRouting? { get set }
var listener: DepositRootListener? { get set }
func bankLinkingComplete()
func bankLinkingClosed(isInteractive: Bool)
}
final class DepositRootRouter: RIBs.Router<DepositRootInteractable>, DepositRootRouting {
// MARK: - Private Properties
private var transactionRouter: ViewableRouting?
private var paymentMethodRouter: ViewableRouting?
private var linkBankFlowRouter: LinkBankFlowStarter?
private let topMostViewControllerProviding: TopMostViewControllerProviding
private let analyticsRecorder: AnalyticsEventRecorderAPI
private let disposeBag = DisposeBag()
// MARK: - Init
init(
interactor: DepositRootInteractable,
topMostViewControllerProviding: TopMostViewControllerProviding = resolve(),
analyticsRecorder: AnalyticsEventRecorderAPI = resolve()
) {
self.topMostViewControllerProviding = topMostViewControllerProviding
self.analyticsRecorder = analyticsRecorder
super.init(interactor: interactor)
interactor.router = self
}
// MARK: - Overrides
override func didLoad() {
super.didLoad()
interactor.activate()
}
// MARK: - DepositRootRouting
func routeToLinkABank() {
dismissTopMost(weak: self) { (self) in
self.showLinkBankFlow()
}
}
func dismissBankLinkingFlow() {
topMostViewControllerProviding
.topMostViewController?
.dismiss(animated: true, completion: nil)
linkBankFlowRouter = nil
}
func dismissWireInstructionFlow() {
detachCurrentChild()
topMostViewControllerProviding
.topMostViewController?
.dismiss(animated: true, completion: nil)
}
func dismissPaymentMethodFlow() {
if let router = paymentMethodRouter {
detachChild(router)
topMostViewControllerProviding
.topMostViewController?
.dismiss(animated: true, completion: nil)
paymentMethodRouter = nil
}
}
func startWithLinkABank() {
showLinkBankFlow()
}
func startWithWireInstructions(currency: FiatCurrency) {
showWireTransferScreen(fiatCurrency: currency)
}
func routeToWireInstructions(currency: FiatCurrency) {
dismissTopMost(weak: self) { (self) in
self.showWireTransferScreen(fiatCurrency: currency)
}
}
func routeToDepositLanding() {
let builder = PaymentMethodBuilder()
paymentMethodRouter = builder.build(withListener: interactor)
if let router = paymentMethodRouter {
let viewControllable = router.viewControllable.uiviewController
attachChild(router)
present(viewController: viewControllable)
}
}
func startDeposit(target: FiatAccount, sourceAccount: LinkedBankAccount?) {
showDepositFlow(target: target, sourceAccount: sourceAccount)
}
func routeToDeposit(target: FiatAccount, sourceAccount: LinkedBankAccount?) {
dismissTopMost(weak: self) { (self) in
self.showDepositFlow(target: target, sourceAccount: sourceAccount)
}
}
func dismissTransactionFlow() {
guard let router = transactionRouter else { return }
detachChild(router)
transactionRouter = nil
}
// MARK: - Private Functions
private func detachCurrentChild() {
guard let currentRouter = children.last else {
return
}
detachChild(currentRouter)
}
private func showDepositFlow(target: FiatAccount, sourceAccount: LinkedBankAccount?) {
let builder = TransactionFlowBuilder()
transactionRouter = builder.build(
withListener: interactor,
action: .deposit,
sourceAccount: sourceAccount,
target: target
)
if let router = transactionRouter {
let viewControllable = router.viewControllable.uiviewController
attachChild(router)
present(viewController: viewControllable)
}
}
private func showLinkBankFlow() {
let builder = LinkBankFlowRootBuilder()
let router = builder.build()
linkBankFlowRouter = router
analyticsRecorder.record(event: AnalyticsEvents.New.Withdrawal.linkBankClicked(origin: .deposit))
router.startFlow()
.subscribe(onNext: { [weak self] effect in
guard let self = self else { return }
switch effect {
case .closeFlow(let isInteractive):
self.interactor.bankLinkingClosed(isInteractive: isInteractive)
case .bankLinked:
self.interactor.bankLinkingComplete()
}
})
.disposed(by: disposeBag)
}
private func showWireTransferScreen(fiatCurrency: FiatCurrency) {
let builder = AddNewBankAccountBuilder(currency: fiatCurrency, isOriginDeposit: false)
let addNewBankRouter = builder.build(listener: interactor)
let viewControllable = addNewBankRouter.viewControllable.uiviewController
attachChild(addNewBankRouter)
present(viewController: viewControllable)
}
private func present(viewController: UIViewController) {
guard let topViewController = topMostViewControllerProviding.topMostViewController else {
fatalError("Expected a ViewController")
}
guard topViewController is UINavigationController == false else {
fatalError("Cannot present a `UINavigationController` over another.")
}
guard viewController is UINavigationController == false else {
topViewController.present(viewController, animated: true, completion: nil)
return
}
let navController = UINavigationController(rootViewController: viewController)
topViewController.present(navController, animated: true, completion: nil)
}
private func dismissTopMost(weak object: DepositRootRouter, _ selector: @escaping (DepositRootRouter) -> Void) {
guard let viewController = topMostViewControllerProviding.topMostViewController else {
selector(object)
return
}
viewController.dismiss(animated: true, completion: {
selector(object)
})
}
}
| lgpl-3.0 | 1203211f09026455a7d03dc8dcde4163 | 32.413793 | 116 | 0.671089 | 5.822318 | false | false | false | false |
soberman/ARSLineProgress | Source/ARSInfiniteLoader.swift | 1 | 2516 | //
// ARSInfiniteLoader.swift
// ARSLineProgress
//
// Created by Yaroslav Arsenkin on 09/10/2016.
// Copyright © 2016 Iaroslav Arsenkin. All rights reserved.
//
// Website: http://arsenkin.com
//
import UIKit
final class ARSInfiniteLoader: ARSLoader {
@objc var emptyView = UIView()
@objc var backgroundBlurView: UIVisualEffectView
@objc var backgroundSimpleView: UIView
@objc var backgroundFullView: UIView
@objc var backgroundView: UIView {
switch ars_config.backgroundViewStyle {
case .blur:
return backgroundBlurView
case .simple:
return backgroundSimpleView
case .full:
return backgroundFullView
}
}
@objc var outerCircle = CAShapeLayer()
@objc var middleCircle = CAShapeLayer()
@objc var innerCircle = CAShapeLayer()
@objc weak var targetView: UIView?
init() {
backgroundBlurView = ARSBlurredBackgroundRect().view
backgroundSimpleView = ARSSimpleBackgroundRect().view
backgroundFullView = ARSFullBackgroundRect().view
NotificationCenter.default.addObserver(self,
selector: #selector(ARSInfiniteLoader.orientationChanged(_:)),
name: UIDevice.orientationDidChangeNotification,
object: nil)
}
deinit {
NotificationCenter.default.removeObserver(self,
name: UIDevice.orientationDidChangeNotification,
object: nil)
}
@objc func orientationChanged(_ notification: Notification) {
ars_dispatchOnMainQueue {
if let loader = ars_currentLoader {
if let targetView = loader.targetView {
ars_createdFrameForBackgroundView(loader.backgroundView, onView: targetView)
} else {
ars_createdFrameForBackgroundView(loader.backgroundView, onView: nil)
}
}
}
}
}
extension ARSInfiniteLoader {
func ars_showOnView(_ view: UIView?, completionBlock: (() -> Void)?) {
if ars_createdFrameForBackgroundView(backgroundView, onView: view) == false { return }
targetView = view
ars_createCircles(outerCircle,
middleCircle: middleCircle,
innerCircle: innerCircle,
onView: ((backgroundView as? UIVisualEffectView)?.contentView) ?? backgroundView,
loaderType: .infinite)
ars_animateCircles(outerCircle, middleCircle: middleCircle, innerCircle: innerCircle)
ars_presentLoader(self, onView: view, completionBlock: completionBlock)
}
}
| mit | 9b57c9988002831b31a9eac87ecb55cb | 30.049383 | 103 | 0.671571 | 4.736347 | false | false | false | false |
otakisan/SmartToDo | SmartToDo/Views/Cells/ToDoEditorDateBaseTableViewCell.swift | 1 | 2621 | //
// ToDoEditorDateBaseTableViewCell.swift
// SmartToDo
//
// Created by Takashi Ikeda on 2014/11/02.
// Copyright (c) 2014年 ti. All rights reserved.
//
import UIKit
class ToDoEditorDateBaseTableViewCell: ToDoEditorBaseTableViewCell {
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
}
func completeDelegate() -> ((UIView) -> Void)? {
return self.didFinishDetailView
}
func didFinishDetailView(detailView : UIView){
if let view = detailView as? UIDatePicker {
self.setValueForDate(view)
}
}
func setValueForDate(datePicker : UIDatePicker){
// Subclass Must Implement
}
override func setValueOfCell(value: AnyObject) {
if let entityData = value as? NSDate {
self.setDateStringOfCell(self.stringFromDate(entityData))
}
}
func setDateStringOfCell(value : String){
}
func dateFormatter() -> NSDateFormatter {
// データとしての日付と表示としての日付の扱いを分けるとすれば
// データ:数値もしくはロケールによらない固定フォーマット
// 表示:ロケールに応じたフォーマット
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy/MM/dd"
return dateFormatter
}
func stringFromDate(date : NSDate) -> String {
return self.dateFormatter().stringFromDate(date)
}
func dateFromString(dateString : String) -> NSDate? {
return self.dateFormatter().dateFromString(dateString)
}
func loadDetailView() -> CommonDatePickerViewController? {
let vc = NSBundle.mainBundle().loadNibNamed("CommonDatePickerViewController", owner: CommonDatePickerViewController(), options: nil)[0] as? CommonDatePickerViewController
return vc
}
override func createDetailView() -> UIViewController? {
var vc : CommonDatePickerViewController?
if !self.readOnly {
vc = self.loadDetailView()
vc?.setViewValue(self.detailViewInitValue()!)
vc?.completeDelegate = self.didFinishDetailView
}
return vc
}
func detailViewInitValue() -> AnyObject? {
return NSDate()
}
var readOnly : Bool {
get{ return false }
}
}
| mit | 8d38375cd64fd76b937199b8b2fe12db | 26.175824 | 178 | 0.627173 | 4.926295 | false | false | false | false |
karwa/swift-corelibs-foundation | Foundation/NSNotificationQueue.swift | 3 | 7540 | // 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
public enum NSPostingStyle : UInt {
case PostWhenIdle
case PostASAP
case PostNow
}
public struct NSNotificationCoalescing : OptionSet {
public let rawValue : UInt
public init(rawValue: UInt) { self.rawValue = rawValue }
public static let CoalescingOnName = NSNotificationCoalescing(rawValue: 1 << 0)
public static let CoalescingOnSender = NSNotificationCoalescing(rawValue: 1 << 1)
}
public class NSNotificationQueue : NSObject {
internal typealias NotificationQueueList = NSMutableArray
internal typealias NSNotificationListEntry = (NSNotification, [String]) // Notification ans list of modes the notification may be posted in.
internal typealias NSNotificationList = [NSNotificationListEntry] // The list of notifications to post
internal let notificationCenter: NSNotificationCenter
internal var asapList = NSNotificationList()
internal var idleList = NSNotificationList()
internal lazy var idleRunloopObserver: CFRunLoopObserver = {
return CFRunLoopObserverCreateWithHandler(kCFAllocatorDefault, CFOptionFlags(kCFRunLoopBeforeTimers), true, 0) {[weak self] observer, activity in
self!.notifyQueues(.PostWhenIdle)
}
}()
internal lazy var asapRunloopObserver: CFRunLoopObserver = {
return CFRunLoopObserverCreateWithHandler(kCFAllocatorDefault, CFOptionFlags(kCFRunLoopBeforeWaiting | kCFRunLoopExit), true, 0) {[weak self] observer, activity in
self!.notifyQueues(.PostASAP)
}
}()
// The NSNotificationQueue instance is associated with current thread.
// The _notificationQueueList represents a list of notification queues related to the current thread.
private static var _notificationQueueList = NSThreadSpecific<NSMutableArray>()
internal static var notificationQueueList: NotificationQueueList {
return _notificationQueueList.get() {
return NSMutableArray()
}
}
// The default notification queue for the current thread.
private static var _defaultQueue = NSThreadSpecific<NSNotificationQueue>()
public class func defaultQueue() -> NSNotificationQueue {
return _defaultQueue.get() {
return NSNotificationQueue(notificationCenter: NSNotificationCenter.defaultCenter())
}
}
public init(notificationCenter: NSNotificationCenter) {
self.notificationCenter = notificationCenter
super.init()
NSNotificationQueue.registerQueue(self)
}
deinit {
NSNotificationQueue.unregisterQueue(self)
removeRunloopObserver(self.idleRunloopObserver)
removeRunloopObserver(self.asapRunloopObserver)
}
public func enqueueNotification(_ notification: NSNotification, postingStyle: NSPostingStyle) {
enqueueNotification(notification, postingStyle: postingStyle, coalesceMask: [.CoalescingOnName, .CoalescingOnSender], forModes: nil)
}
public func enqueueNotification(_ notification: NSNotification, postingStyle: NSPostingStyle, coalesceMask: NSNotificationCoalescing, forModes modes: [String]?) {
var runloopModes = [NSDefaultRunLoopMode]
if let modes = modes {
runloopModes = modes
}
if !coalesceMask.isEmpty {
self.dequeueNotificationsMatching(notification, coalesceMask: coalesceMask)
}
switch postingStyle {
case .PostNow:
let currentMode = NSRunLoop.currentRunLoop().currentMode
if currentMode == nil || runloopModes.contains(currentMode!) {
self.notificationCenter.postNotification(notification)
}
case .PostASAP: // post at the end of the current notification callout or timer
addRunloopObserver(self.asapRunloopObserver)
self.asapList.append((notification, runloopModes))
case .PostWhenIdle: // wait until the runloop is idle, then post the notification
addRunloopObserver(self.idleRunloopObserver)
self.idleList.append((notification, runloopModes))
}
}
public func dequeueNotificationsMatching(_ notification: NSNotification, coalesceMask: NSNotificationCoalescing) {
var predicate: (NSNotificationListEntry) -> Bool
switch coalesceMask {
case [.CoalescingOnName, .CoalescingOnSender]:
predicate = { (entryNotification, _) in
return notification.object !== entryNotification.object || notification.name != entryNotification.name
}
case [.CoalescingOnName]:
predicate = { (entryNotification, _) in
return notification.name != entryNotification.name
}
case [.CoalescingOnSender]:
predicate = { (entryNotification, _) in
return notification.object !== entryNotification.object
}
default:
return
}
self.asapList = self.asapList.filter(predicate)
self.idleList = self.idleList.filter(predicate)
}
// MARK: Private
private func addRunloopObserver(_ observer: CFRunLoopObserver) {
CFRunLoopAddObserver(NSRunLoop.currentRunLoop()._cfRunLoop, observer, kCFRunLoopDefaultMode)
CFRunLoopAddObserver(NSRunLoop.currentRunLoop()._cfRunLoop, observer, kCFRunLoopCommonModes)
}
private func removeRunloopObserver(_ observer: CFRunLoopObserver) {
CFRunLoopRemoveObserver(NSRunLoop.currentRunLoop()._cfRunLoop, observer, kCFRunLoopDefaultMode)
CFRunLoopRemoveObserver(NSRunLoop.currentRunLoop()._cfRunLoop, observer, kCFRunLoopCommonModes)
}
private func notify(_ currentMode: String?, notificationList: inout NSNotificationList) {
for (idx, (notification, modes)) in notificationList.enumerated().reversed() {
if currentMode == nil || modes.contains(currentMode!) {
self.notificationCenter.postNotification(notification)
notificationList.remove(at: idx)
}
}
}
/**
Gets queues from the notificationQueueList and posts all notification from the list related to the postingStyle parameter.
*/
private func notifyQueues(_ postingStyle: NSPostingStyle) {
let currentMode = NSRunLoop.currentRunLoop().currentMode
for queue in NSNotificationQueue.notificationQueueList {
let notificationQueue = queue as! NSNotificationQueue
if postingStyle == .PostWhenIdle {
notificationQueue.notify(currentMode, notificationList: ¬ificationQueue.idleList)
} else {
notificationQueue.notify(currentMode, notificationList: ¬ificationQueue.asapList)
}
}
}
private static func registerQueue(_ notificationQueue: NSNotificationQueue) {
self.notificationQueueList.addObject(notificationQueue)
}
private static func unregisterQueue(_ notificationQueue: NSNotificationQueue) {
guard self.notificationQueueList.indexOfObject(notificationQueue) != NSNotFound else {
return
}
self.notificationQueueList.removeObject(notificationQueue)
}
}
| apache-2.0 | ca6bf4ca0ee61b5a5cc34387e5d73ce9 | 42.085714 | 171 | 0.702122 | 5.8314 | false | false | false | false |
chrisjmendez/swift-exercises | Music/MIDI/Playgrounds/InputSource.playground/Contents.swift | 1 | 1917 | //: Matt Grippaldi http://mattg411.com/swift-coremidi-callbacks/
import Cocoa
import CoreMIDI
import XCPlayground
func getDisplayName(obj: MIDIObjectRef) -> String {
var param: Unmanaged<CFString>?
var name: String = "Error";
let err: OSStatus = MIDIObjectGetStringProperty(obj, kMIDIPropertyDisplayName, ¶m)
if err == OSStatus(noErr)
{
name = param!.takeRetainedValue() as String
}
return name;
}
func MyMIDIReadProc(pktList: UnsafePointer<MIDIPacketList>,
readProcRefCon: UnsafeMutablePointer<Void>, srcConnRefCon: UnsafeMutablePointer<Void>) -> Void {
let packetList:MIDIPacketList = pktList.memory;
let srcRef:MIDIEndpointRef = UnsafeMutablePointer<MIDIEndpointRef>(COpaquePointer(srcConnRefCon)).memory;
print("MIDI Received From Source: \(getDisplayName(srcRef))");
var packet:MIDIPacket = packetList.packet;
for _ in 1...packetList.numPackets
{
let bytes = Mirror(reflecting: packet.data).children;
var dumpStr = "";
// bytes mirror contains all the zero values in the ridiulous packet data tuple
// so use the packet length to iterate.
var i = packet.length;
for (_, attr) in bytes.enumerate()
{
dumpStr += String(format:"$%02X ", attr.value as! UInt8);
--i;
if (i <= 0)
{
break;
}
}
print(dumpStr)
packet = MIDIPacketNext(&packet).memory;
}
}
var midiClient: MIDIClientRef = 0;
var inPort:MIDIPortRef = 0;
var src:MIDIEndpointRef = MIDIGetSource(0);
MIDIClientCreate("MidiTestClient", nil, nil, &midiClient);
MIDIInputPortCreate(midiClient, "MidiTest_InPort", MyMIDIReadProc, nil, &inPort);
MIDIPortConnectSource(inPort, src, &src);
// Keep playground running
XCPlaygroundPage.currentPage.needsIndefiniteExecution = true;
| mit | 3222934379b14c4018eca9d63f659d5a | 30.42623 | 116 | 0.65832 | 4.122581 | false | false | false | false |
josve05a/wikipedia-ios | Wikipedia/Code/WMFAuthAccountCreationInfoFetcher.swift | 3 | 2059 |
public enum WMFAuthAccountCreationError: LocalizedError {
case cannotExtractInfo
case cannotCreateAccountsNow
public var errorDescription: String? {
switch self {
case .cannotExtractInfo:
return "Could not extract account creation info"
case .cannotCreateAccountsNow:
return "Unable to create accounts at this time"
}
}
}
public typealias WMFAuthAccountCreationInfoBlock = (WMFAuthAccountCreationInfo) -> Void
public struct WMFAuthAccountCreationInfo {
let canCreateAccounts:Bool
let captcha: WMFCaptcha?
init(canCreateAccounts:Bool, captcha:WMFCaptcha?) {
self.canCreateAccounts = canCreateAccounts
self.captcha = captcha
}
}
public class WMFAuthAccountCreationInfoFetcher: Fetcher {
public func fetchAccountCreationInfoForSiteURL(_ siteURL: URL, success: @escaping WMFAuthAccountCreationInfoBlock, failure: @escaping WMFErrorHandler){
let parameters = [
"action": "query",
"meta": "authmanagerinfo",
"amirequestsfor": "create",
"format": "json"
]
performMediaWikiAPIPOST(for: siteURL, with: parameters) { (result, response, error) in
if let error = error {
failure(error)
return
}
guard
let query = result?["query"] as? [String : AnyObject],
let authmanagerinfo = query["authmanagerinfo"] as? [String : AnyObject],
let requests = authmanagerinfo["requests"] as? [[String : AnyObject]]
else {
failure(WMFAuthAccountCreationError.cannotExtractInfo)
return
}
guard authmanagerinfo["cancreateaccounts"] != nil else {
failure(WMFAuthAccountCreationError.cannotCreateAccountsNow)
return
}
success(WMFAuthAccountCreationInfo.init(canCreateAccounts: true, captcha: WMFCaptcha.captcha(from: requests)))
}
}
}
| mit | 307f658bc7edca146b0343abf50f0055 | 36.436364 | 155 | 0.624575 | 5.719444 | false | false | false | false |
sjf0213/DingShan | DingshanSwift/DingshanSwift/ProfileViewCell.swift | 1 | 1849 | //
// ProfileViewCell.swift
// DingshanSwift
//
// Created by xiong qi on 15/11/18.
// Copyright © 2015年 song jufeng. All rights reserved.
//
import Foundation
class ProfileViewCell:UITableViewCell
{
var icon = UIImageView()
var title = UILabel()
var arrow = UIImageView()
override init(style astyle:UITableViewCellStyle, reuseIdentifier str:String?) {
super.init(style:astyle, reuseIdentifier:str)
self.backgroundColor = UIColor.whiteColor()
self.selectionStyle = UITableViewCellSelectionStyle.None
icon = UIImageView(frame: CGRect(x: 15, y: 9, width: 54, height: 27))
icon.backgroundColor = UIColor.redColor().colorWithAlphaComponent(0.5)
icon.clipsToBounds = true;
self.contentView.addSubview(icon)
title = UILabel(frame: CGRect(x: 84, y: 12, width: self.bounds.size.width - 114 - 50, height: 20))
title.font = UIFont.systemFontOfSize(17.0)
title.text = "..."
self.contentView.addSubview(title)
arrow = UIImageView(frame: CGRect(x: self.bounds.size.width-50, y: 12, width: 20, height: 20))
arrow.backgroundColor = UIColor.redColor().colorWithAlphaComponent(0.5)
self.contentView.addSubview(arrow)
let topline = UIView(frame: CGRect(x: 15.0, y: 88-0.5, width: self.bounds.width - 30.0, height: 0.5))
topline.backgroundColor = UIColor(white: 216/255.0, alpha: 1.0)
self.contentView.addSubview(topline)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func clearData()
{
title.text = ""
}
func loadCellData(data:Dictionary<String,String>)
{
title.text = data["title"]
icon.image = UIImage.init(named: data["image"]!)
}
} | mit | dd1b842a26ad22b0a9dc578119ef504d | 33.203704 | 109 | 0.638678 | 4.021786 | false | false | false | false |
laurentVeliscek/AudioKit | Examples/iOS/SongProcessor/SongProcessor/View Controllers/MoogLadderViewController.swift | 2 | 1412 | //
// MoogLadderViewController.swift
// SongProcessor
//
// Created by Aurelius Prochazka on 6/22/16.
// Copyright © 2016 AudioKit. All rights reserved.
//
import UIKit
class MoogLadderViewController: UIViewController {
@IBOutlet weak var cutoffFrequncySlider: UISlider!
@IBOutlet weak var resonanceSlider: UISlider!
@IBOutlet weak var mixSlider: UISlider!
let songProcessor = SongProcessor.sharedInstance
override func viewDidLoad() {
super.viewDidLoad()
cutoffFrequncySlider.minimumValue = 12.0
cutoffFrequncySlider.maximumValue = 10000.0
if let freq = songProcessor.moogLadder?.cutoffFrequency {
cutoffFrequncySlider.value = Float(freq)
}
if let res = songProcessor.moogLadder?.resonance {
resonanceSlider.value = Float(res)
}
if let balance = songProcessor.filterMixer?.balance {
mixSlider.value = Float(balance)
}
}
@IBAction func updateCutoff(sender: UISlider) {
songProcessor.moogLadder?.cutoffFrequency = Double(sender.value)
}
@IBAction func updateResonance(sender: UISlider) {
songProcessor.moogLadder?.resonance = Double(sender.value)
}
@IBAction func updateMix(sender: UISlider) {
songProcessor.filterMixer?.balance = Double(sender.value)
}
}
| mit | 5ad697f5a03b02fe4ad6ef26e823e3d4 | 27.795918 | 72 | 0.652729 | 4.950877 | false | false | false | false |
policante/PageControl | Example/PageControl/CardItemViewController.swift | 1 | 1388 | //
// CardItemViewController.swift
// PageControl
//
// Created by Rodrigo Martins on 08/09/17.
// Copyright © 2017 CocoaPods. All rights reserved.
//
import UIKit
protocol CardDelegate {
func removeCard(_ user: MyUser)
}
class CardItemViewController: UIViewController {
@IBOutlet weak var name: UILabel!
@IBOutlet weak var email: UILabel!
@IBOutlet weak var following: UILabel!
@IBOutlet weak var followers: UILabel!
@IBOutlet weak var photo: UIImageView!
@IBOutlet weak var btnRemove: UIButton!
var user: MyUser!
var delegate: CardDelegate!
override func viewDidLoad() {
super.viewDidLoad()
name.text = user.name!
email.text = user.email!
following.text = "\(user.following)"
followers.text = "\(user.followers)"
photo.image = user.boy ? #imageLiteral(resourceName: "boy") : #imageLiteral(resourceName: "girl")
photo.layer.cornerRadius = photo.frame.size.height / 2
btnRemove.layer.cornerRadius = btnRemove.frame.size.height / 2
}
func animateImage(){
guard self.photo != nil else {
return
}
UIView.transition(with: self.photo, duration: 1.0, options: .transitionFlipFromLeft, animations: nil)
}
@IBAction func doRemove(_ sender: Any) {
self.delegate.removeCard(self.user)
}
}
| mit | 604e3891db5c2fdb33827b60f90cdc0e | 26.196078 | 109 | 0.644557 | 4.228659 | false | false | false | false |
drumnkyle/music-notation-swift | Tests/MusicNotationCoreTests/MeasureTests.swift | 1 | 75432 | //
// MeasureTests.swift
// MusicNotationCore
//
// Created by Kyle Sherman on 7/13/15.
// Copyright © 2015 Kyle Sherman. All rights reserved.
//
@testable import MusicNotationCoreMac
import XCTest
class MeasureTests: XCTestCase {
var measure: Measure!
var timeSignature: TimeSignature!
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
timeSignature = TimeSignature(topNumber: 4, bottomNumber: 4, tempo: 120)
measure = Measure(
timeSignature: timeSignature,
key: Key(noteLetter: .c)
)
}
override func tearDown() {
super.tearDown()
measure = nil
timeSignature = nil
}
func testAddNote() {
XCTAssertEqual(measure.notes[0].count, 0)
measure.append(Note(noteDuration: .whole, pitch: SpelledPitch(noteLetter: .c, octave: .octave0)))
measure.append(Note(noteDuration: .quarter, pitch: SpelledPitch(noteLetter: .d, accidental: .sharp, octave: .octave0)))
measure.append(Note(restDuration: .whole))
XCTAssertEqual(measure.notes[0].count, 3)
}
// MARK: - replaceNotereplaceNote<T: NoteCollection>(at:with:T)
// MARK: Failures
// MARK: Successes
func testReplaceNoteInTuplet() {
let note = Note(noteDuration: .quarter, pitch: SpelledPitch(noteLetter: .a, octave: .octave1))
let notes = [
Note(noteDuration: .sixteenth, pitch: SpelledPitch(noteLetter: .c, octave: .octave1)),
Note(noteDuration: .sixteenth, pitch: SpelledPitch(noteLetter: .c, octave: .octave1)),
Note(noteDuration: .sixteenth, pitch: SpelledPitch(noteLetter: .a, octave: .octave1)),
]
assertNoErrorThrown {
let tuplet = try Tuplet(3, .sixteenth, notes: notes)
measure.append(tuplet)
measure.append(note)
XCTAssertEqual(measure.noteCount[0], 4)
// TODO: confirm that 1/4 actually fits in a 3,.sixteenth Tuplet.
try measure.replaceNote(at: 1, with: note)
}
}
func testReplaceNote() {
XCTAssertEqual(measure.notes[0].count, 0)
let note1 = Note(restDuration: .whole)
let note2 = Note(restDuration: .eighth)
measure.append(note1)
measure.append(note2)
assertNoErrorThrown {
XCTAssertEqual(measure.noteCount[0], 2)
try measure.replaceNote(at: 1, with: note1)
let resultNote1 = try measure.note(at: 0, inSet: 0)
let resultNote2 = try measure.note(at: 1, inSet: 0)
XCTAssertEqual(resultNote1, note1)
XCTAssertEqual(resultNote2, note1)
}
}
// MARK: - replaceNote<T: NoteCollection>(at:with:[T])
// MARK: Failures
func testRepalceNoteWithInvalidNoteCollection() {
measure.append(Note(restDuration: .whole))
assertThrowsError(MeasureError.invalidNoteCollection) {
try measure.replaceNote(at: 0, with: [Note]())
}
}
// MARK: Successes
func testReplaceNoteWithNotesPreservingTie() {
XCTAssertEqual(measure.notes[0].count, 0)
let note1 = Note(restDuration: .whole)
let note2 = Note(restDuration: .eighth)
measure.append(note1)
measure.append(note2)
assertNoErrorThrown {
XCTAssertEqual(measure.noteCount[0], 2)
try measure.modifyTie(at: 0, requestedTieState: .begin, inSet: 0)
try measure.replaceNote(at: 0, with: [note2, note1])
XCTAssertEqual(measure.noteCount[0], 3)
var resultNote1 = try measure.note(at: 0, inSet: 0)
var resultNote2 = try measure.note(at: 1, inSet: 0)
XCTAssertEqual(resultNote1, note2)
XCTAssertEqual(resultNote2.tie, .begin)
// Clear tie result before compare
resultNote2.tie = nil
XCTAssertEqual(resultNote2, note1)
// Note replace the note and index 1, which should
// have a .beginAndEnd tie state.
try measure.modifyTie(at: 0, requestedTieState: .begin, inSet: 0)
try measure.replaceNote(at: 1, with: [note2])
XCTAssertEqual(measure.noteCount[0], 3)
resultNote1 = try measure.note(at: 1, inSet: 0)
resultNote2 = try measure.note(at: 2, inSet: 0)
XCTAssertEqual(resultNote1.tie, .beginAndEnd)
XCTAssertEqual(resultNote2.tie, .end)
// Now insert a couple of notes at the index containing
// the .beginAndEnd tie. This should change the tie.
try measure.replaceNote(at: 1, with: [note1, note2])
XCTAssertEqual(measure.noteCount[0], 4)
// Make sure we end up with 2 separate ties now.
for i in [0, 2] {
resultNote1 = try measure.note(at: i, inSet: 0)
resultNote2 = try measure.note(at: i + 1, inSet: 0)
XCTAssertEqual(resultNote1.tie, .begin)
XCTAssertEqual(resultNote2.tie, .end)
}
}
}
func testReplaceNoteWithTupletPreservingTie() {
XCTAssertEqual(measure.notes[0].count, 0)
let note = Note(noteDuration: .whole, pitch: SpelledPitch(noteLetter: .c, octave: .octave1))
let notes = [
Note(noteDuration: .sixteenth, pitch: SpelledPitch(noteLetter: .c, octave: .octave1)),
Note(noteDuration: .sixteenth, pitch: SpelledPitch(noteLetter: .c, octave: .octave1)),
Note(noteDuration: .sixteenth, pitch: SpelledPitch(noteLetter: .a, octave: .octave1)),
]
measure.append(note)
measure.append(note)
assertNoErrorThrown {
let tuplet = try Tuplet(3, .sixteenth, notes: notes)
XCTAssertEqual(measure.noteCount[0], 2)
try measure.startTie(at: 0, inSet: 0)
try measure.replaceNote(at: 1, with: [tuplet])
XCTAssertEqual(measure.noteCount[0], 4)
var resultNote = try measure.note(at: 1, inSet: 0)
XCTAssertEqual(resultNote.tie, .end)
// Clear tie result before compare
resultNote.tie = nil
XCTAssertEqual(resultNote, notes[0])
}
}
// MARK: - replaceNotes<T: NoteCollection>(in:with:T)
// MARK: Failures
func testReplaceNotesInRangeInvalidIndex() {
let note = Note(noteDuration: .quarter, pitch: SpelledPitch(noteLetter: .a, octave: .octave1))
let notes = [
Note(noteDuration: .sixteenth, pitch: SpelledPitch(noteLetter: .c, octave: .octave1)),
Note(noteDuration: .sixteenth, pitch: SpelledPitch(noteLetter: .c, octave: .octave1)),
Note(noteDuration: .sixteenth, pitch: SpelledPitch(noteLetter: .a, octave: .octave1)),
]
assertThrowsError(MeasureError.tupletNotCompletelyCovered) {
let tuplet = try Tuplet(3, .sixteenth, notes: notes)
measure.append(tuplet)
measure.append(note)
XCTAssertEqual(measure.noteCount[0], 4)
try measure.replaceNotes(in: 2 ... 3, with: note)
}
}
// MARK: Successes
func testReplaceNotes() {
XCTAssertEqual(measure.notes[0].count, 0)
let note1 = Note(restDuration: .whole)
let note2 = Note(restDuration: .eighth)
measure.append(note1)
measure.append(note2)
assertNoErrorThrown {
XCTAssertEqual(measure.noteCount[0], 2)
try measure.replaceNotes(in: 0 ... 1, with: note2)
XCTAssertEqual(measure.noteCount[0], 1)
}
}
// MARK: - replaceNotes<T: NoteCollection>(in:with:[T])
// MARK: Failures
func testReplaceNotesInRangeInvalidTie() {
XCTAssertEqual(measure.notes[0].count, 0)
var note1 = Note(restDuration: .whole)
note1.tie = .beginAndEnd
let note2 = Note(restDuration: .eighth)
measure.append(note1)
measure.append(note2)
assertThrowsError(MeasureError.invalidTieState) {
XCTAssertEqual(measure.noteCount[0], 2)
try measure.replaceNotes(in: 0 ... 1, with: [note1, note2])
}
}
func testReplaceNotesInRangeWithInvalidIndexRange() {
let note = Note(noteDuration: .quarter, pitch: SpelledPitch(noteLetter: .a, octave: .octave1))
let notes = [
Note(noteDuration: .sixteenth, pitch: SpelledPitch(noteLetter: .c, octave: .octave1)),
Note(noteDuration: .sixteenth, pitch: SpelledPitch(noteLetter: .c, octave: .octave1)),
Note(noteDuration: .sixteenth, pitch: SpelledPitch(noteLetter: .a, octave: .octave1)),
]
assertThrowsError(MeasureError.tupletNotCompletelyCovered) {
let tuplet = try Tuplet(3, .sixteenth, notes: notes)
measure.append(tuplet)
measure.append(note)
XCTAssertEqual(measure.noteCount[0], 4)
try measure.replaceNotes(in: 2 ... 3, with: [note, note])
}
}
// MARK: Successes
func testReplaceNotesInRangeWithOtherNotes() {
XCTAssertEqual(measure.notes[0].count, 0)
let note1 = Note(restDuration: .whole)
let note2 = Note(restDuration: .eighth)
measure.append(note1)
measure.append(note2)
assertNoErrorThrown {
XCTAssertEqual(measure.noteCount[0], 2)
try measure.replaceNotes(in: 0 ... 1, with: [note2, note1])
let resultNote1 = try measure.note(at: 0, inSet: 0)
let resultNote2 = try measure.note(at: 1, inSet: 0)
XCTAssertEqual(measure.noteCount[0], 2)
XCTAssertEqual(resultNote1, note2)
XCTAssertEqual(resultNote2, note1)
}
}
func testReplaceTupletInRangeWithNotes() {
XCTAssertEqual(measure.notes[0].count, 0)
let note1 = Note(noteDuration: .eighth, pitch: SpelledPitch(noteLetter: .c, octave: .octave1))
let note2 = Note(noteDuration: .eighth, pitch: SpelledPitch(noteLetter: .a, octave: .octave1))
let note3 = Note(noteDuration: .eighth, pitch: SpelledPitch(noteLetter: .c, octave: .octave1))
assertNoErrorThrown {
let tuplet = try Tuplet(3, .eighth, notes: [note1, note2, note3])
measure.append(note3)
measure.append(tuplet)
try measure.startTie(at: 0, inSet: 0)
XCTAssertEqual(measure.noteCount[0], 4)
try measure.replaceNotes(in: 1 ... 3, with: [note2, note1])
var resultNote1 = try measure.note(at: 1, inSet: 0)
let resultNote2 = try measure.note(at: 2, inSet: 0)
XCTAssertEqual(measure.noteCount[0], 3)
XCTAssertEqual(resultNote1.tie, .end)
resultNote1.tie = nil
XCTAssertEqual(resultNote1, note2)
XCTAssertEqual(resultNote2, note1)
}
}
// MARK: - insert(_:NoteCollection:at)
// MARK: Failures
func testInsertNoteIndexOutOfRange() {
XCTAssertEqual(measure.notes[0].count, 0)
assertThrowsError(MeasureError.noteIndexOutOfRange) {
try measure.insert(Note(restDuration: .whole), at: 1)
}
}
func testInsertInvalidTupletIndex() {
let note1 = Note(noteDuration: .quarter, pitch: SpelledPitch(noteLetter: .a, octave: .octave1))
let note2 = Note(noteDuration: .quarter, pitch: SpelledPitch(noteLetter: .b, octave: .octave1))
measure.append(note1)
measure.append(note2)
let notes = [
Note(noteDuration: .eighth, pitch: SpelledPitch(noteLetter: .c, octave: .octave1)),
Note(noteDuration: .eighth, pitch: SpelledPitch(noteLetter: .c, octave: .octave1)),
Note(noteDuration: .eighth, pitch: SpelledPitch(noteLetter: .a, octave: .octave1)),
]
assertThrowsError(MeasureError.invalidTupletIndex) {
let tuplet = try Tuplet(3, .eighth, notes: notes)
try measure.insert(tuplet, at: 1)
try measure.insert(tuplet, at: 2)
}
}
// MARK: Successes
func testInsertNote() {
XCTAssertEqual(measure.notes[0].count, 0)
let note1 = Note(restDuration: .whole)
let note2 = Note(restDuration: .eighth)
let note3 = Note(restDuration: .quarter)
measure.append(note1)
measure.append(note2)
assertNoErrorThrown {
try measure.insert(note3, at: 1)
XCTAssertEqual(measure.notes[0].count, 3)
print(measure!)
let resultNote1 = try measure.note(at: 0, inSet: 0)
let resultNote2 = try measure.note(at: 1, inSet: 0)
let resultNote3 = try measure.note(at: 2, inSet: 0)
XCTAssertEqual(resultNote1, note1)
XCTAssertEqual(resultNote2, note3)
XCTAssertEqual(resultNote3, note2)
}
}
func testInsertTuplet() {
let note1 = Note(noteDuration: .quarter, pitch: SpelledPitch(noteLetter: .a, octave: .octave1))
let note2 = Note(noteDuration: .quarter, pitch: SpelledPitch(noteLetter: .b, octave: .octave1))
measure.append(note1)
measure.append(note2)
let notes = [
Note(noteDuration: .eighth, pitch: SpelledPitch(noteLetter: .c, octave: .octave1)),
Note(noteDuration: .eighth, pitch: SpelledPitch(noteLetter: .c, octave: .octave1)),
Note(noteDuration: .eighth, pitch: SpelledPitch(noteLetter: .a, octave: .octave1)),
]
assertNoErrorThrown {
let tuplet = try Tuplet(3, .eighth, notes: notes)
try measure.insert(tuplet, at: 1)
let resultNote1 = try measure.note(at: 0)
let resultTuplet = measure.notes[0][1] as! Tuplet
let resultNote2 = try measure.note(at: 4)
XCTAssertEqual(measure.noteCount[0], 5)
XCTAssertEqual(note1, resultNote1)
XCTAssertEqual(tuplet, resultTuplet)
XCTAssertEqual(note2, resultNote2)
}
}
// MARK: - removeNote(at)
// MARK: Failures
func testRemoveNoteFromTuplet() {
XCTAssertEqual(measure.notes[0].count, 0)
let note1 = Note(restDuration: .eighth)
measure.append(note1)
assertThrowsError(MeasureError.removeNoteFromTuplet) {
let tuplet = try Tuplet(3, .eighth, notes: [note1, note1, note1])
measure.append(tuplet)
try measure.removeNote(at: 1)
}
}
func testRemoveNoteInvalidTieStateStart() {
var note = Note(noteDuration: .quarter, pitch: SpelledPitch(noteLetter: .c, octave: .octave1))
note.tie = .end
measure.append(note)
measure.append(Note(noteDuration: .eighth, pitch: SpelledPitch(noteLetter: .c, octave: .octave1)))
assertThrowsError(MeasureError.invalidTieState) {
try measure.removeNote(at: 0)
}
}
func testRemoveNoteInvalidTieStateEnd() {
var note = Note(noteDuration: .quarter, pitch: SpelledPitch(noteLetter: .c, octave: .octave1))
note.tie = .begin
measure.append(Note(noteDuration: .eighth, pitch: SpelledPitch(noteLetter: .c, octave: .octave1)))
measure.append(note)
assertThrowsError(MeasureError.invalidTieState) {
XCTAssertEqual(measure.noteCount[0], 2)
try measure.removeNote(at: 1)
}
}
// MARK: Successes
func testRemoveNote() {
XCTAssertEqual(measure.notes[0].count, 0)
let note1 = Note(restDuration: .whole)
let note2 = Note(restDuration: .eighth)
let note3 = Note(restDuration: .quarter)
measure.append(note1)
measure.append(note2)
measure.append(note3)
assertNoErrorThrown {
try measure.removeNote(at: 1)
XCTAssertEqual(measure.notes[0].count, 2)
let resultNote1 = try measure.note(at: 0, inSet: 0)
let resultNote2 = try measure.note(at: 1, inSet: 0)
XCTAssertEqual(resultNote1, note1)
XCTAssertEqual(resultNote2, note3)
}
}
func testRemoveNoteWithEndTie() {
measure.append(Note(noteDuration: .quarter, pitch: SpelledPitch(noteLetter: .c, octave: .octave1)))
measure.append(Note(noteDuration: .eighth, pitch: SpelledPitch(noteLetter: .c, octave: .octave1)))
assertNoErrorThrown {
try measure.startTie(at: 0, inSet: 0)
try measure.removeNote(at: 1)
}
}
// MARK: - removeNotesInRange()
// MARK: Failures
func testRemoveNotesInRangeInvalidTieAtStart() {
XCTAssertEqual(measure.notes[0].count, 0)
var note1 = Note(restDuration: .whole)
note1.tie = .end
let note2 = Note(restDuration: .eighth)
measure.append(note1)
measure.append(note2)
assertThrowsError(MeasureError.invalidTieState) {
XCTAssertEqual(measure.noteCount[0], 2)
try measure.removeNotesInRange(0 ... 1)
}
}
func testRemoveNotesInRangeInvalidTieAtEnd() {
XCTAssertEqual(measure.notes[0].count, 0)
let note1 = Note(restDuration: .whole)
var note2 = Note(restDuration: .eighth)
note2.tie = .begin
measure.append(note1)
measure.append(note2)
assertThrowsError(MeasureError.invalidTieState) {
XCTAssertEqual(measure.noteCount[0], 2)
try measure.removeNotesInRange(0 ... 1)
}
}
func testRemoveNotesWithInvalidRangeStart() {
measure.append(Note(noteDuration: .eighth, pitch: SpelledPitch(noteLetter: .c, octave: .octave1)))
let notes = [
Note(noteDuration: .eighth, pitch: SpelledPitch(noteLetter: .c, octave: .octave1)),
Note(noteDuration: .eighth, pitch: SpelledPitch(noteLetter: .c, octave: .octave1)),
Note(noteDuration: .eighth, pitch: SpelledPitch(noteLetter: .a, octave: .octave1)),
]
assertThrowsError(MeasureError.tupletNotCompletelyCovered) {
let tuplet = try Tuplet(3, .eighth, notes: notes)
measure.append(tuplet)
XCTAssertEqual(measure.noteCount[0], 4)
try measure.removeNotesInRange(0 ... 1)
}
}
func testRemoveNotesWithInvalidRangeEnd() {
let notes = [
Note(noteDuration: .eighth, pitch: SpelledPitch(noteLetter: .c, octave: .octave1)),
Note(noteDuration: .eighth, pitch: SpelledPitch(noteLetter: .c, octave: .octave1)),
Note(noteDuration: .eighth, pitch: SpelledPitch(noteLetter: .a, octave: .octave1)),
]
assertThrowsError(MeasureError.tupletNotCompletelyCovered) {
let tuplet = try Tuplet(3, .eighth, notes: notes)
measure.append(tuplet)
measure.append(Note(noteDuration: .eighth, pitch: SpelledPitch(noteLetter: .c, octave: .octave1)))
XCTAssertEqual(measure.noteCount[0], 4)
try measure.removeNotesInRange(2 ... 3)
}
}
// MARK: Successes
func testRemoveNotesInRange() {
XCTAssertEqual(measure.notes[0].count, 0)
let note1 = Note(restDuration: .whole)
let note2 = Note(restDuration: .eighth)
let note3 = Note(restDuration: .quarter)
measure.append(note1)
measure.append(Note(restDuration: .quarter))
measure.append(Note(restDuration: .quarter))
measure.append(Note(restDuration: .quarter))
measure.append(Note(restDuration: .quarter))
measure.append(note2)
measure.append(note3)
assertNoErrorThrown {
XCTAssertEqual(measure.notes[0].count, 7)
try measure.removeNotesInRange(1 ... 4)
XCTAssertEqual(measure.notes[0].count, 3)
let resultNote1 = try measure.note(at: 0, inSet: 0)
let resultNote2 = try measure.note(at: 1, inSet: 0)
let resultNote3 = try measure.note(at: 2, inSet: 0)
XCTAssertEqual(resultNote1, note1)
XCTAssertEqual(resultNote2, note2)
XCTAssertEqual(resultNote3, note3)
}
}
func testRemoveNotesWithTupletsInRange() {
XCTAssertEqual(measure.notes[0].count, 0)
let note1 = Note(restDuration: .whole)
let note2 = Note(restDuration: .eighth)
let note3 = Note(restDuration: .quarter)
measure.append(note1)
measure.append(Note(restDuration: .quarter))
measure.append(Note(restDuration: .quarter))
measure.append(Note(restDuration: .quarter))
measure.append(Note(restDuration: .quarter))
measure.append(note2)
measure.append(note3)
let notes = [
Note(noteDuration: .eighth, pitch: SpelledPitch(noteLetter: .c, octave: .octave1)),
Note(noteDuration: .eighth, pitch: SpelledPitch(noteLetter: .c, octave: .octave1)),
Note(noteDuration: .eighth, pitch: SpelledPitch(noteLetter: .a, octave: .octave1)),
]
assertNoErrorThrown {
let tuplet = try Tuplet(3, .eighth, notes: notes)
try measure.insert(tuplet, at: 4)
XCTAssertEqual(measure.notes[0].count, 8)
try measure.removeNotesInRange(1 ... 7)
XCTAssertEqual(measure.notes[0].count, 3)
let resultNote1 = try measure.note(at: 0, inSet: 0)
let resultNote2 = try measure.note(at: 1, inSet: 0)
let resultNote3 = try measure.note(at: 2, inSet: 0)
XCTAssertEqual(resultNote1, note1)
XCTAssertEqual(resultNote2, note2)
XCTAssertEqual(resultNote3, note3)
}
}
// MARK: - createTuplet()
// MARK: Failures
func testCreateTupletInvalidTupletIndexStart() {
let note1 = Note(noteDuration: .eighth, pitch: SpelledPitch(noteLetter: .a, octave: .octave1))
let note2 = Note(noteDuration: .eighth, pitch: SpelledPitch(noteLetter: .b, octave: .octave1))
let note3 = Note(noteDuration: .eighth, pitch: SpelledPitch(noteLetter: .c, octave: .octave1))
assertThrowsError(MeasureError.invalidTupletIndex) {
let tuplet = try Tuplet(3, .eighth, notes: [note1, note2, note3])
measure.append(tuplet)
measure.append(Note(noteDuration: .quarter, pitch: SpelledPitch(noteLetter: .c, octave: .octave1)))
try measure.createTuplet(3, .quarter, fromNotesInRange: 1 ... 3)
}
}
func testCreateTupletInvalidTupletIndexEnd() {
let note1 = Note(noteDuration: .eighth, pitch: SpelledPitch(noteLetter: .a, octave: .octave1))
let note2 = Note(noteDuration: .eighth, pitch: SpelledPitch(noteLetter: .b, octave: .octave1))
let note3 = Note(noteDuration: .eighth, pitch: SpelledPitch(noteLetter: .c, octave: .octave1))
measure.append(note1)
assertThrowsError(MeasureError.invalidTupletIndex) {
let tuplet = try Tuplet(3, .eighth, notes: [note1, note2, note3])
measure.append(tuplet)
try measure.createTuplet(3, .quarter, fromNotesInRange: 0 ... 2)
}
}
func testCreateTupletNoteIndexOutOfRange() {
measure.append(Note(noteDuration: .quarter, pitch: SpelledPitch(noteLetter: .a, octave: .octave1)))
measure.append(Note(noteDuration: .quarter, pitch: SpelledPitch(noteLetter: .b, octave: .octave1)))
measure.append(Note(noteDuration: .quarter, pitch: SpelledPitch(noteLetter: .c, octave: .octave1)))
assertThrowsError(MeasureError.noteIndexOutOfRange) {
try measure.createTuplet(3, .quarter, fromNotesInRange: 0 ... 3)
}
}
func testCreateTupletNoteInvalidNoteRange() {
measure.append(Note(noteDuration: .quarter, pitch: SpelledPitch(noteLetter: .a, octave: .octave1)))
measure.append(Note(noteDuration: .quarter, pitch: SpelledPitch(noteLetter: .b, octave: .octave1)))
measure.append(Note(noteDuration: .quarter, pitch: SpelledPitch(noteLetter: .c, octave: .octave1)))
assertThrowsError(MeasureError.noteIndexOutOfRange) {
try measure.createTuplet(3, .quarter, fromNotesInRange: 0 ... 3)
}
}
// TODO: Find a way to reach the MeasureError.invalidNoteRange code path
// https://github.com/drumnkyle/music-notation-core/issues/128
// MARK: Successes
func testCreateTuplet() {
measure.append(Note(noteDuration: .quarter, pitch: SpelledPitch(noteLetter: .a, octave: .octave1)))
measure.append(Note(noteDuration: .quarter, pitch: SpelledPitch(noteLetter: .b, octave: .octave1)))
measure.append(Note(noteDuration: .quarter, pitch: SpelledPitch(noteLetter: .c, octave: .octave1)))
assertNoErrorThrown {
try measure.createTuplet(3, .quarter, fromNotesInRange: 0 ... 2)
XCTAssert(measure.notes[0].count == 1)
}
}
// MARK: - breakdownTuplet(at)
// MARK: Failures
func testBreakDownTupletInvalidIndex() {
measure.append(Note(noteDuration: .eighth, pitch: SpelledPitch(noteLetter: .a, octave: .octave1)))
assertThrowsError(MeasureError.invalidTupletIndex) {
XCTAssert(measure.noteCount[0] == 1)
try measure.breakdownTuplet(at: 0)
}
}
// MARK: Successes
func testBreakDownTuplet() {
let note1 = Note(noteDuration: .eighth, pitch: SpelledPitch(noteLetter: .a, octave: .octave1))
let note2 = Note(noteDuration: .eighth, pitch: SpelledPitch(noteLetter: .b, octave: .octave1))
let note3 = Note(noteDuration: .eighth, pitch: SpelledPitch(noteLetter: .c, octave: .octave1))
assertNoErrorThrown {
let tuplet = try Tuplet(3, .eighth, notes: [note1, note2, note3])
measure.append(tuplet)
try measure.breakdownTuplet(at: 0)
XCTAssert(measure.noteCount[0] == 3)
let resultNote1 = try measure.note(at: 0)
let resultNote2 = try measure.note(at: 1)
let resultNote3 = try measure.note(at: 2)
XCTAssertEqual(resultNote1, note1)
XCTAssertEqual(resultNote2, note2)
XCTAssertEqual(resultNote3, note3)
}
}
// MARK: - prepTieForInsertion
// MARK: Failures
func testPrepTieForInsertNoteRemoveTie() {
measure.append(Note(noteDuration: .quarter, pitch: SpelledPitch(noteLetter: .c, octave: .octave1)))
measure.append(Note(noteDuration: .eighth, pitch: SpelledPitch(noteLetter: .c, octave: .octave1)))
assertThrowsError(MeasureError.invalidTieState) {
try measure.startTie(at: 0, inSet: 0)
let note = Note(noteDuration: .quarter, pitch: SpelledPitch(noteLetter: .c, octave: .octave1))
try measure.insert(note, at: 1, inSet: 0)
}
}
// MARK: Successes
func testPrepTieForInsertNote() {
measure.append(Note(noteDuration: .quarter, pitch: SpelledPitch(noteLetter: .c, octave: .octave1)))
measure.append(Note(noteDuration: .eighth, pitch: SpelledPitch(noteLetter: .c, octave: .octave1)))
measure.append(Note(noteDuration: .quarter, pitch: SpelledPitch(noteLetter: .c, octave: .octave1)))
assertNoErrorThrown {
try measure.startTie(at: 1, inSet: 0)
let note = Note(noteDuration: .quarter, pitch: SpelledPitch(noteLetter: .a, octave: .octave1))
try measure.insert(note, at: 1, inSet: 0)
let note1 = try measure.note(at: 1, inSet: 0)
let note2 = try measure.note(at: 2, inSet: 0)
let note3 = try measure.note(at: 3, inSet: 0)
XCTAssertNil(note1.tie)
XCTAssertNotNil(note2.tie)
XCTAssert(note2.tie == .begin)
XCTAssertNotNil(note3.tie)
XCTAssert(note3.tie == .end)
}
}
// MARK: - startTie(at:)
// MARK: Successes
func testStartTieNoNextNote() {
measure.append(Note(noteDuration: .quarter, pitch: SpelledPitch(noteLetter: .c, octave: .octave1)))
// Only change note to .begin
assertNoErrorThrown {
try measure.startTie(at: 0, inSet: 0)
let note = measure.notes[0][0] as! Note
XCTAssertNotNil(note.tie)
XCTAssert(note.tie == .begin)
}
}
func testStartTieHasNextNote() {
measure.append(Note(noteDuration: .quarter, pitch: SpelledPitch(noteLetter: .c, octave: .octave1)))
measure.append(Note(noteDuration: .eighth, pitch: SpelledPitch(noteLetter: .c, octave: .octave1)))
assertNoErrorThrown {
try measure.startTie(at: 0, inSet: 0)
let note1 = measure.notes[0][0] as! Note
let note2 = measure.notes[0][1] as! Note
XCTAssertNotNil(note1.tie)
XCTAssert(note1.tie == .begin)
XCTAssertNotNil(note2.tie)
XCTAssert(note2.tie == .end)
}
}
func testStartTieNoteAlreadyBeginningOfTie() {
measure.append(Note(noteDuration: .quarter, pitch: SpelledPitch(noteLetter: .c, octave: .octave1)))
measure.append(Note(noteDuration: .eighth, pitch: SpelledPitch(noteLetter: .c, octave: .octave1)))
assertNoErrorThrown {
try measure.startTie(at: 0, inSet: 0)
try measure.startTie(at: 0, inSet: 0)
let note1 = measure.notes[0][0] as! Note
let note2 = measure.notes[0][1] as! Note
XCTAssert(note1.tie == .begin)
XCTAssert(note2.tie == .end)
}
}
func testStartTieNextNoteInTuplet() {
measure.append(Note(noteDuration: .quarter, pitch: SpelledPitch(noteLetter: .c, octave: .octave1)))
measure.append(Note(noteDuration: .eighth, pitch: SpelledPitch(noteLetter: .c, octave: .octave1)))
measure.append(Note(noteDuration: .eighth, pitch: SpelledPitch(noteLetter: .c, octave: .octave1)))
let notes = [
Note(noteDuration: .eighth, pitch: SpelledPitch(noteLetter: .c, octave: .octave1)),
Note(noteDuration: .eighth, pitch: SpelledPitch(noteLetter: .a, octave: .octave1)),
Note(noteDuration: .eighth, pitch: SpelledPitch(noteLetter: .a, octave: .octave1)),
]
assertNoErrorThrown {
// setup
let tuplet = try Tuplet(3, .eighth, notes: notes)
measure.append(tuplet)
// test
try measure.startTie(at: 2, inSet: 0)
let note1 = measure.notes[0][2] as! Note
let tuplet2 = measure.notes[0][3] as! Tuplet
XCTAssert(note1.tie == .begin)
XCTAssert(try tuplet2.note(at: 0).tie == .end)
}
}
func testStartTieLastNoteOfTupletNoNextNote() {
// Just change to .begin
measure.append(Note(noteDuration: .quarter, pitch: SpelledPitch(noteLetter: .c, octave: .octave1)))
measure.append(Note(noteDuration: .eighth, pitch: SpelledPitch(noteLetter: .c, octave: .octave1)))
measure.append(Note(noteDuration: .eighth, pitch: SpelledPitch(noteLetter: .c, octave: .octave1)))
let notes = [
Note(noteDuration: .eighth, pitch: SpelledPitch(noteLetter: .c, octave: .octave1)),
Note(noteDuration: .eighth, pitch: SpelledPitch(noteLetter: .a, octave: .octave1)),
Note(noteDuration: .eighth, pitch: SpelledPitch(noteLetter: .a, octave: .octave1)),
]
assertNoErrorThrown {
// setup
let tupletSetup = try Tuplet(3, .eighth, notes: notes)
measure.append(tupletSetup)
// test
try measure.startTie(at: 2, inSet: 0)
try measure.startTie(at: 5, inSet: 0)
let tuplet = measure.notes[0][3] as! Tuplet
XCTAssert(try tuplet.note(at: 2).tie == .begin)
}
}
func testStartTieNoteIsEndOfAnotherTie() {
measure.append(Note(noteDuration: .quarter, pitch: SpelledPitch(noteLetter: .c, octave: .octave1)))
measure.append(Note(noteDuration: .eighth, pitch: SpelledPitch(noteLetter: .c, octave: .octave1)))
measure.append(Note(noteDuration: .eighth, pitch: SpelledPitch(noteLetter: .c, octave: .octave1)))
let notes = [
Note(noteDuration: .eighth, pitch: SpelledPitch(noteLetter: .c, octave: .octave1)),
Note(noteDuration: .eighth, pitch: SpelledPitch(noteLetter: .c, octave: .octave1)),
Note(noteDuration: .eighth, pitch: SpelledPitch(noteLetter: .a, octave: .octave1)),
]
assertNoErrorThrown {
// setup
let tupletSetup = try Tuplet(3, .eighth, notes: notes)
measure.append(tupletSetup)
try measure.startTie(at: 2, inSet: 0)
// test
try measure.startTie(at: 3, inSet: 0)
let tuplet = measure.notes[0][3] as! Tuplet
XCTAssert(try tuplet.note(at: 0).tie == .beginAndEnd)
XCTAssert(try tuplet.note(at: 1).tie == .end)
}
}
func testStartTieLastNoteOfTupletHasNextNote() {
measure.append(Note(noteDuration: .quarter, pitch: SpelledPitch(noteLetter: .c, octave: .octave1)))
measure.append(Note(noteDuration: .eighth, pitch: SpelledPitch(noteLetter: .c, octave: .octave1)))
measure.append(Note(noteDuration: .eighth, pitch: SpelledPitch(noteLetter: .c, octave: .octave1)))
let notes = [
Note(noteDuration: .eighth, pitch: SpelledPitch(noteLetter: .c, octave: .octave1)),
Note(noteDuration: .eighth, pitch: SpelledPitch(noteLetter: .a, octave: .octave1)),
Note(noteDuration: .eighth, pitch: SpelledPitch(noteLetter: .a, octave: .octave1)),
]
assertNoErrorThrown {
// setup
let tupletSetup = try Tuplet(3, .eighth, notes: notes)
measure.append(tupletSetup)
try measure.startTie(at: 2, inSet: 0)
// test
try measure.startTie(at: 5, inSet: 0)
let tuplet = measure.notes[0][3] as! Tuplet
XCTAssert(try tuplet.note(at: 2).tie == .begin)
}
}
func testStartTieLastNoteOfTupletNextNoteTuplet() {
assertNoErrorThrown {
let note = Note(noteDuration: .sixteenth,
pitch: SpelledPitch(noteLetter: .c, octave: .octave1))
let tuplet1 = try Tuplet(3, .sixteenth, notes: [note, note, note])
let tuplet2 = try Tuplet(5, .sixteenth, notes: [note, note, note, note, note])
measure.append(tuplet1)
measure.append(tuplet2)
try measure.startTie(at: 2, inSet: 0)
let note1 = noteFromMeasure(measure, noteIndex: 0, tupletIndex: 2)
let note2 = noteFromMeasure(measure, noteIndex: 1, tupletIndex: 0)
XCTAssert(note1.tie == .begin)
XCTAssert(note2.tie == .end)
}
}
func testStartTieInNestedTuplet() {
assertNoErrorThrown {
let note = Note(noteDuration: .eighth,
pitch: SpelledPitch(noteLetter: .c, octave: .octave1))
let triplet = try Tuplet(3, .eighth, notes: [note, note, note])
let tuplet = try Tuplet(3, .eighth, notes: [triplet, note])
measure.append(tuplet)
measure.append(note)
try measure.startTie(at: 3, inSet: 0)
let note1 = try measure.note(at: 3)
let note2 = try measure.note(at: 4)
XCTAssert(note1.tie == .begin)
XCTAssert(note2.tie == .end)
}
}
// MARK: - startTie(at:)
// MARK: Failures
func testStartTieNoteHasDiffPitch() {
measure.append(Note(noteDuration: .quarter, pitch: SpelledPitch(noteLetter: .a, octave: .octave1)))
measure.append(Note(noteDuration: .eighth, pitch: SpelledPitch(noteLetter: .c, octave: .octave1)))
assertThrowsError(MeasureError.notesMustHaveSamePitchesToTie) {
try measure.startTie(at: 0, inSet: 0)
}
}
func testStartTieNextNoteInTupletDiffPitch() {
measure.append(Note(noteDuration: .quarter, pitch: SpelledPitch(noteLetter: .c, octave: .octave1)))
measure.append(Note(noteDuration: .eighth, pitch: SpelledPitch(noteLetter: .c, octave: .octave1)))
measure.append(Note(noteDuration: .eighth, pitch: SpelledPitch(noteLetter: .c, octave: .octave1)))
let notes = [
Note(noteDuration: .eighth, pitch: SpelledPitch(noteLetter: .a, octave: .octave1)),
Note(noteDuration: .eighth, pitch: SpelledPitch(noteLetter: .a, octave: .octave1)),
Note(noteDuration: .eighth, pitch: SpelledPitch(noteLetter: .a, octave: .octave1)),
]
assertThrowsError(MeasureError.notesMustHaveSamePitchesToTie) {
let tuplet = try Tuplet(3, .eighth, notes: notes)
measure.append(tuplet)
try measure.startTie(at: 2, inSet: 0)
}
}
// MARK: - removeTie(at:)
// MARK: Failures
func testRemoveTieNoNoteAtIndex() {
measure.append(Note(noteDuration: .eighth, pitch: SpelledPitch(noteLetter: .c, octave: .octave1)))
measure.append(Note(noteDuration: .eighth, pitch: SpelledPitch(noteLetter: .c, octave: .octave1)))
measure.append(Note(noteDuration: .eighth, pitch: SpelledPitch(noteLetter: .c, octave: .octave1)))
measure.append(Note(noteDuration: .eighth, pitch: SpelledPitch(noteLetter: .c, octave: .octave1)))
assertThrowsError(MeasureError.noteIndexOutOfRange) {
try measure.removeTie(at: 4, inSet: 0)
}
}
// MARK: Successes
func testRemoveTieNoTie() {
measure.append(Note(noteDuration: .eighth, pitch: SpelledPitch(noteLetter: .c, octave: .octave1)))
measure.append(Note(noteDuration: .eighth, pitch: SpelledPitch(noteLetter: .c, octave: .octave1)))
measure.append(Note(noteDuration: .eighth, pitch: SpelledPitch(noteLetter: .c, octave: .octave1)))
measure.append(Note(noteDuration: .eighth, pitch: SpelledPitch(noteLetter: .c, octave: .octave1)))
assertNoErrorThrown {
try measure.removeTie(at: 0, inSet: 0)
let firstNote = noteFromMeasure(measure, noteIndex: 0, tupletIndex: nil)
let secondNote = noteFromMeasure(measure, noteIndex: 1, tupletIndex: nil)
XCTAssertNil(firstNote.tie)
XCTAssertNil(secondNote.tie)
}
}
func testRemoveTieBeginOfTie() {
measure.append(Note(noteDuration: .eighth, pitch: SpelledPitch(noteLetter: .c, octave: .octave1)))
measure.append(Note(noteDuration: .eighth, pitch: SpelledPitch(noteLetter: .c, octave: .octave1)))
measure.append(Note(noteDuration: .eighth, pitch: SpelledPitch(noteLetter: .c, octave: .octave1)))
measure.append(Note(noteDuration: .eighth, pitch: SpelledPitch(noteLetter: .c, octave: .octave1)))
assertNoErrorThrown {
setTie(at: 0)
try measure.removeTie(at: 0, inSet: 0)
let firstNote = noteFromMeasure(measure, noteIndex: 0, tupletIndex: nil)
let secondNote = noteFromMeasure(measure, noteIndex: 1, tupletIndex: nil)
XCTAssertNil(firstNote.tie)
XCTAssertNil(secondNote.tie)
}
}
func testRemoveTieFromBeginAndEnd() {
measure.append(Note(noteDuration: .eighth, pitch: SpelledPitch(noteLetter: .c, octave: .octave1)))
measure.append(Note(noteDuration: .eighth, pitch: SpelledPitch(noteLetter: .c, octave: .octave1)))
measure.append(Note(noteDuration: .eighth, pitch: SpelledPitch(noteLetter: .c, octave: .octave1)))
measure.append(Note(noteDuration: .eighth, pitch: SpelledPitch(noteLetter: .c, octave: .octave1)))
assertNoErrorThrown {
setTie(at: 0)
setTie(at: 1)
try measure.removeTie(at: 1, inSet: 0)
let firstNote = noteFromMeasure(measure, noteIndex: 1, tupletIndex: nil)
let secondNote = noteFromMeasure(measure, noteIndex: 2, tupletIndex: nil)
XCTAssert(firstNote.tie == .end)
XCTAssertNil(secondNote.tie)
}
}
func testRemoveTieBeginsInTuplet() {
measure.append(Note(noteDuration: .eighth, pitch: SpelledPitch(noteLetter: .c, octave: .octave1)))
measure.append(Note(noteDuration: .eighth, pitch: SpelledPitch(noteLetter: .c, octave: .octave1)))
measure.append(Note(noteDuration: .eighth, pitch: SpelledPitch(noteLetter: .c, octave: .octave1)))
measure.append(Note(noteDuration: .eighth, pitch: SpelledPitch(noteLetter: .c, octave: .octave1)))
let note = Note(noteDuration: .sixteenth,
pitch: SpelledPitch(noteLetter: .c, octave: .octave1))
assertNoErrorThrown {
let tuplet = try Tuplet(3, .sixteenth, notes: [note, note, note])
measure.append(tuplet)
measure.append(note)
}
assertNoErrorThrown {
setTie(at: 6)
try measure.removeTie(at: 6, inSet: 0)
let firstNote = noteFromMeasure(measure, noteIndex: 4, tupletIndex: 2)
let secondNote = noteFromMeasure(measure, noteIndex: 5, tupletIndex: nil)
XCTAssertNil(firstNote.tie)
XCTAssertNil(secondNote.tie)
}
}
func testRemoveTieBeginAndEndInOneTuplet() {
measure.append(Note(noteDuration: .eighth, pitch: SpelledPitch(noteLetter: .c, octave: .octave1)))
measure.append(Note(noteDuration: .eighth, pitch: SpelledPitch(noteLetter: .c, octave: .octave1)))
measure.append(Note(noteDuration: .eighth, pitch: SpelledPitch(noteLetter: .c, octave: .octave1)))
measure.append(Note(noteDuration: .eighth, pitch: SpelledPitch(noteLetter: .c, octave: .octave1)))
let note = Note(noteDuration: .sixteenth, pitch: SpelledPitch(noteLetter: .c, octave: .octave1))
assertNoErrorThrown {
let tuplet = try Tuplet(3, .sixteenth, notes: [note, note, note])
measure.append(tuplet)
measure.append(note)
}
assertNoErrorThrown {
setTie(at: 5)
try measure.removeTie(at: 5, inSet: 0)
let firstNote = noteFromMeasure(measure, noteIndex: 4, tupletIndex: 1)
let secondNote = noteFromMeasure(measure, noteIndex: 4, tupletIndex: 2)
XCTAssertNil(firstNote.tie)
XCTAssertNil(secondNote.tie)
}
}
func testRemoveTieEndsInTuplet() {
measure.append(Note(noteDuration: .eighth, pitch: SpelledPitch(noteLetter: .c, octave: .octave1)))
measure.append(Note(noteDuration: .eighth, pitch: SpelledPitch(noteLetter: .c, octave: .octave1)))
measure.append(Note(noteDuration: .eighth, pitch: SpelledPitch(noteLetter: .c, octave: .octave1)))
measure.append(Note(noteDuration: .eighth, pitch: SpelledPitch(noteLetter: .c, octave: .octave1)))
let note = Note(noteDuration: .sixteenth, pitch: SpelledPitch(noteLetter: .c, octave: .octave1))
assertNoErrorThrown {
let tuplet = try Tuplet(3, .sixteenth, notes: [note, note, note])
measure.append(tuplet)
measure.append(note)
}
assertNoErrorThrown {
setTie(at: 4)
try measure.removeTie(at: 4, inSet: 0)
let firstNote = noteFromMeasure(measure, noteIndex: 4, tupletIndex: 0)
let secondNote = noteFromMeasure(measure, noteIndex: 4, tupletIndex: 1)
XCTAssertNil(firstNote.tie)
XCTAssertNil(secondNote.tie)
}
}
func testRemoveTieTupletToOtherTuplet() {
measure.append(Note(noteDuration: .eighth, pitch: SpelledPitch(noteLetter: .c, octave: .octave1)))
measure.append(Note(noteDuration: .eighth, pitch: SpelledPitch(noteLetter: .c, octave: .octave1)))
measure.append(Note(noteDuration: .eighth, pitch: SpelledPitch(noteLetter: .c, octave: .octave1)))
measure.append(Note(noteDuration: .eighth, pitch: SpelledPitch(noteLetter: .c, octave: .octave1)))
let note = Note(noteDuration: .sixteenth, pitch: SpelledPitch(noteLetter: .c, octave: .octave1))
assertNoErrorThrown {
let tuplet = try Tuplet(3, .sixteenth, notes: [note, note, note])
measure.append(tuplet)
measure.append(note)
}
assertNoErrorThrown {
let tuplet1 = try Tuplet(5, .sixteenth, notes: [note, note, note, note, note])
let tuplet2 = try Tuplet(3, .sixteenth, notes: [note, note, note])
measure.append(tuplet1)
measure.append(tuplet2)
setTie(at: 11)
try measure.removeTie(at: 11, inSet: 0)
let firstNote = noteFromMeasure(measure, noteIndex: 6, tupletIndex: 3)
let secondNote = noteFromMeasure(measure, noteIndex: 7, tupletIndex: 0)
XCTAssertNil(firstNote.tie)
XCTAssertNil(secondNote.tie)
}
}
// MARK: - noteCollectionIndexFromNoteIndex(_:)
// MARK: Successes
func testNoteCollectionIndexFromNoteIndexNoTuplets() {
// NoteIndex should be the same if there are no tuplets
measure.append(Note(restDuration: .quarter))
measure.append(Note(restDuration: .quarter))
measure.append(Note(restDuration: .quarter))
assertNoErrorThrown {
let index = try measure.noteCollectionIndex(fromNoteIndex: 2, inSet: 0)
XCTAssertEqual(index.noteIndex, 2)
XCTAssertNil(index.tupletIndex)
}
}
func testNoteCollectionIndexFromNoteIndexWithinTuplet() {
// NoteIndex should be the beginning of the tuplet if the index specified
// is within the tuplet, and tupletIndex should be the index of the note
// within the tuplet
measure.append(Note(restDuration: .quarter))
assertNoErrorThrown {
let note1 = Note(noteDuration: .eighth,
pitch: SpelledPitch(noteLetter: .a, octave: .octave1))
let note2 = Note(noteDuration: .eighth,
pitch: SpelledPitch(noteLetter: .b, octave: .octave1))
let note3 = Note(noteDuration: .eighth,
pitch: SpelledPitch(noteLetter: .c, octave: .octave1))
measure.append(try Tuplet(3, .eighth, notes: [note1, note2, note3]))
let index = try measure.noteCollectionIndex(fromNoteIndex: 2, inSet: 0)
XCTAssertEqual(index.noteIndex, 1)
XCTAssertNotNil(index.tupletIndex)
XCTAssertEqual(index.tupletIndex!, 1)
// Properly address regular note coming after a tuplet
measure.append(Note(restDuration: .eighth))
let index2 = try measure.noteCollectionIndex(fromNoteIndex: 4, inSet: 0)
XCTAssertEqual(index2.noteIndex, 2)
XCTAssertNil(index2.tupletIndex)
}
}
// MARK: - hasClefAfterNote(at:) -> Bool
// MARK: False
func testHasClefAfterNoteInvalidIndex() {
measure.append(Note(restDuration: .quarter))
measure.append(Note(restDuration: .quarter))
XCTAssertFalse(measure.hasClefAfterNote(at: 3, inSet: 0))
}
func testHasClefAfterNoteNoClefsFirstIndex() {
measure.append(Note(restDuration: .quarter))
measure.append(Note(restDuration: .quarter))
XCTAssertFalse(measure.hasClefAfterNote(at: 1, inSet: 0))
}
func testHasClefAfterNoteNoClefsMiddleIndex() {
measure.append(Note(restDuration: .quarter))
measure.append(Note(restDuration: .quarter))
assertNoErrorThrown {
try measure.changeClef(Clef.treble, at: 0, inSet: 0)
}
XCTAssertFalse(measure.hasClefAfterNote(at: 1, inSet: 0))
}
func testHasClefAfterNoteMiddleOfTuplet() {
let quarter = Note(restDuration: .quarter)
let eighth = Note(noteDuration: .eighth, pitch: SpelledPitch(noteLetter: .c, octave: .octave1))
assertNoErrorThrown {
let tuplet = try Tuplet(3, .eighth, notes: [eighth, eighth, eighth])
measure.append(quarter)
measure.append(quarter)
measure.append(tuplet)
measure.append(eighth)
measure.append(eighth)
try measure.changeClef(Clef.treble, at: 3, inSet: 0)
}
XCTAssertFalse(measure.hasClefAfterNote(at: 3, inSet: 0))
}
func KNOWNISSUEtestHasClefAfterNoteMiddleOfCompoundTuplet() {
// FIXME: throws MeasureError.cannotCalculateTicksWithinCompoundTuplet error
// https://github.com/drumnkyle/music-notation-core/issues/129
let note = Note(restDuration: .eighth)
measure.append(note)
assertNoErrorThrown {
let triplet = try Tuplet(3, .eighth, notes: [note, note, note])
let compoundTuplet = try Tuplet(5, .eighth, notes: [note, note, triplet, note])
measure.append(compoundTuplet)
try measure.changeClef(Clef.treble, at: 3, inSet: 0)
}
XCTAssertFalse(measure.hasClefAfterNote(at: 4, inSet: 0))
}
func testHasClefAfterNoteNoteOfClefChange() {
measure.append(Note(restDuration: .quarter))
measure.append(Note(restDuration: .quarter))
assertNoErrorThrown {
try measure.changeClef(Clef.treble, at: 1, inSet: 0)
}
XCTAssertFalse(measure.hasClefAfterNote(at: 1, inSet: 0))
}
func testHasClefAfterNoteNoteAfterClefChange() {
measure.append(Note(restDuration: .quarter))
measure.append(Note(restDuration: .quarter))
measure.append(Note(restDuration: .quarter))
assertNoErrorThrown {
try measure.changeClef(Clef.treble, at: 1, inSet: 0)
}
XCTAssertFalse(measure.hasClefAfterNote(at: 2, inSet: 0))
}
// MARK: True
func testHasClefAfterNoteOneClefNoteBefore() {
measure.append(Note(restDuration: .quarter))
measure.append(Note(restDuration: .quarter))
measure.append(Note(restDuration: .quarter))
assertNoErrorThrown {
try measure.changeClef(Clef.treble, at: 2, inSet: 0)
}
XCTAssertTrue(measure.hasClefAfterNote(at: 1, inSet: 0))
}
func testHasClefAfterNoteMultipleClefsNoteBefore() {
measure.append(Note(restDuration: .quarter))
measure.append(Note(restDuration: .quarter))
measure.append(Note(restDuration: .quarter))
measure.append(Note(restDuration: .quarter))
assertNoErrorThrown {
try measure.changeClef(Clef.treble, at: 2, inSet: 0)
try measure.changeClef(Clef.treble, at: 3, inSet: 0)
}
XCTAssertTrue(measure.hasClefAfterNote(at: 1, inSet: 0))
}
func testHasClefAfterNoteMultipleClefsNoteInMiddle() {
measure.append(Note(restDuration: .quarter))
measure.append(Note(restDuration: .quarter))
measure.append(Note(restDuration: .quarter))
measure.append(Note(restDuration: .quarter))
assertNoErrorThrown {
try measure.changeClef(Clef.treble, at: 1, inSet: 0)
try measure.changeClef(Clef.treble, at: 3, inSet: 0)
}
XCTAssertTrue(measure.hasClefAfterNote(at: 2, inSet: 0))
}
// MARK: - cumulativeTicks(at:inSet:) throws -> Int
// MARK: Failures
func testCumulativeTicksInvalidNoteIndex() {
let note = Note(restDuration: .quarter)
measure.append(note)
assertThrowsError(MeasureError.noteIndexOutOfRange) {
_ = try measure.cumulativeTicks(at: 2, inSet: 0)
}
}
func testCumulativeTicksInvalidSetIndex() {
let note = Note(restDuration: .quarter)
measure.append(note)
assertThrowsError(MeasureError.noteIndexOutOfRange) {
_ = try measure.cumulativeTicks(at: 0, inSet: 1)
}
}
func KNOWNISSUEtestCumulativeTicksInMiddleOfCompoundTuplet() {
let note = Note(restDuration: .eighth)
measure.append(note)
assertNoErrorThrown {
let triplet = try Tuplet(3, .eighth, notes: [note, note, note])
let compoundTuplet = try Tuplet(5, .eighth, notes: [note, note, triplet, note])
measure.append(compoundTuplet)
}
print(measure.debugDescription)
// FIXME: there is no implementation of throw MeasureError.cannotCalculateTicksWithinCompoundTuplet in cumulativeTicks
// https://github.com/drumnkyle/music-notation-core/issues/129
assertThrowsError(MeasureError.cannotCalculateTicksWithinCompoundTuplet) {
_ = try measure.cumulativeTicks(at: 4)
}
}
// MARK: Successes
func testCumulativeTicksBeginning() {
let note = Note(restDuration: .quarter)
measure.append(note)
measure.append(note)
measure.append(note)
measure.append(note, inSet: 1)
assertNoErrorThrown {
XCTAssertEqual(try measure.cumulativeTicks(at: 0, inSet: 0), 0)
XCTAssertEqual(try measure.cumulativeTicks(at: 0, inSet: 1), 0)
}
}
func testCumulativeTicksAllNotes() {
let quarter = Note(restDuration: .quarter)
let eighth = Note(restDuration: .eighth)
measure.append(quarter)
measure.append(quarter)
measure.append(eighth)
measure.append(eighth)
measure.append(eighth)
measure.append(quarter)
measure.append(quarter)
measure.append(quarter, inSet: 1)
measure.append(quarter, inSet: 1)
measure.append(quarter, inSet: 1)
let quarterTicks = NoteDuration.quarter.ticks
let eighthTicks = NoteDuration.eighth.ticks
assertNoErrorThrown {
var currentValue = quarterTicks
XCTAssertEqual(try measure.cumulativeTicks(at: 1, inSet: 0), currentValue)
currentValue += quarterTicks
XCTAssertEqual(try measure.cumulativeTicks(at: 2, inSet: 0), currentValue)
currentValue += eighthTicks
XCTAssertEqual(try measure.cumulativeTicks(at: 3, inSet: 0), currentValue)
currentValue += eighthTicks
XCTAssertEqual(try measure.cumulativeTicks(at: 4, inSet: 0), currentValue)
currentValue += eighthTicks
XCTAssertEqual(try measure.cumulativeTicks(at: 5, inSet: 0), currentValue)
currentValue += quarterTicks
XCTAssertEqual(try measure.cumulativeTicks(at: 6, inSet: 0), currentValue)
var currentSet1Value = quarterTicks
XCTAssertEqual(try measure.cumulativeTicks(at: 1, inSet: 0), currentSet1Value)
currentSet1Value += quarterTicks
XCTAssertEqual(try measure.cumulativeTicks(at: 2, inSet: 0), currentSet1Value)
}
}
func testCumulativeTicksBeginningOfTuplet() {
let quarter = Note(restDuration: .quarter)
let eighth = Note(noteDuration: .eighth, pitch: SpelledPitch(noteLetter: .c, octave: .octave1))
assertNoErrorThrown {
let tuplet = try Tuplet(3, .eighth, notes: [eighth, eighth, eighth])
measure.append(quarter)
measure.append(quarter)
measure.append(tuplet)
measure.append(eighth)
measure.append(eighth)
let quarterTicks = NoteDuration.quarter.ticks
let eighthTicks = NoteDuration.eighth.ticks
XCTAssertEqual(try measure.cumulativeTicks(at: 1, inSet: 0), quarterTicks)
XCTAssertEqual(try measure.cumulativeTicks(at: 2, inSet: 0), 2 * quarterTicks)
XCTAssertEqual(try measure.cumulativeTicks(at: 3, inSet: 0), 2 * quarterTicks + 1 / 3 * tuplet.ticks)
XCTAssertEqual(try measure.cumulativeTicks(at: 4, inSet: 0), 2 * quarterTicks + 2 / 3 * tuplet.ticks)
XCTAssertEqual(try measure.cumulativeTicks(at: 5, inSet: 0), 2 * quarterTicks + tuplet.ticks)
XCTAssertEqual(try measure.cumulativeTicks(at: 6, inSet: 0), 2 * quarterTicks + tuplet.ticks + eighthTicks)
}
}
func testCumulativeTicksMiddleOfTuplet() {
let note = Note(restDuration: .eighth)
measure.append(note)
assertNoErrorThrown {
let triplet = try Tuplet(3, .eighth, notes: [note, note, note])
measure.append(triplet)
}
assertNoErrorThrown {
let ticks = try measure.cumulativeTicks(at: 2)
XCTAssertEqual(ticks, note.ticks + note.ticks * 2 / 3)
}
}
func KNOWNISSUEtestCumulativeTicksAtBeginningOfCompoundTuplet() {
// FIXME: throws MeasureError.cannotCalculateTicksWithinCompoundTuplet
// https://github.com/drumnkyle/music-notation-core/issues/129
let note = Note(restDuration: .eighth)
measure.append(note)
assertNoErrorThrown {
let triplet = try Tuplet(3, .eighth, notes: [note, note, note])
let compoundTuplet = try Tuplet(5, .eighth, notes: [note, note, triplet, note])
measure.append(compoundTuplet)
print(measure.debugDescription) // |4/4: [1/8R, 6[1/8R, 1/8R, 3[1/8R, 1/8R, 1/8R], 1/8R]]|
let eighthTicks = NoteDuration.eighth.ticks
let eachCompoundTicks = compoundTuplet.ticks / Double(compoundTuplet.groupingOrder)
let eachTripletTicks = 2 * eachCompoundTicks / Double(triplet.groupingOrder)
var currentTicks = eighthTicks
XCTAssertEqual(try measure.cumulativeTicks(at: 1, inSet: 0), currentTicks)
currentTicks += eachCompoundTicks
XCTAssertEqual(try measure.cumulativeTicks(at: 2, inSet: 0), currentTicks)
currentTicks += eachCompoundTicks
XCTAssertEqual(try measure.cumulativeTicks(at: 3, inSet: 0), currentTicks)
currentTicks += eachTripletTicks
XCTAssertEqual(try measure.cumulativeTicks(at: 4, inSet: 0), currentTicks)
currentTicks += eachTripletTicks
XCTAssertEqual(try measure.cumulativeTicks(at: 5, inSet: 0), currentTicks)
currentTicks += eachTripletTicks
XCTAssertEqual(try measure.cumulativeTicks(at: 6, inSet: 0), currentTicks)
}
}
// MARK: - clef(at:inSet:)
// MARK: Successes
func test1ClefAtBeginningNoOriginal() {
let note = Note(noteDuration: .eighth, pitch: SpelledPitch(noteLetter: .c, octave: .octave1))
var testMeasure = Measure(timeSignature: timeSignature, notes: [
[
note, note, note, note,
],
])
assertNoErrorThrown {
let newClef: Clef = .bass
try testMeasure.changeClef(newClef, at: 0)
XCTAssertEqual(try testMeasure.clef(at: 0, inSet: 0), newClef)
try (1 ..< testMeasure.noteCount[0]).forEach {
XCTAssertEqual(try testMeasure.clef(at: $0, inSet: 0), newClef)
}
}
}
func test1ClefAtBeginningWithOriginal() {
let note = Note(noteDuration: .eighth, pitch: SpelledPitch(noteLetter: .c, octave: .octave1))
var testMeasure = Measure(timeSignature: timeSignature, notes: [
[
note, note, note, note,
],
])
let originalClef: Clef = .treble
testMeasure.originalClef = originalClef
assertNoErrorThrown {
let newClef: Clef = .bass
try testMeasure.changeClef(newClef, at: 0)
XCTAssertEqual(try testMeasure.clef(at: 0, inSet: 0), newClef)
try (1 ..< testMeasure.noteCount[0]).forEach {
XCTAssertEqual(try testMeasure.clef(at: $0, inSet: 0), newClef)
}
}
}
func test1ClefAtBeginningAnd1Other() {
let note = Note(noteDuration: .eighth, pitch: SpelledPitch(noteLetter: .c, octave: .octave1))
var testMeasure = Measure(timeSignature: timeSignature, notes: [
[
note, note, note, note,
],
])
assertNoErrorThrown {
let newClef1: Clef = .bass
let newClef2: Clef = .alto
try testMeasure.changeClef(newClef1, at: 0)
try testMeasure.changeClef(newClef2, at: 2)
try (0 ..< 2).forEach {
XCTAssertEqual(try testMeasure.clef(at: $0, inSet: 0), newClef1)
}
try (2 ..< testMeasure.noteCount[0]).forEach {
XCTAssertEqual(try testMeasure.clef(at: $0, inSet: 0), newClef2)
}
}
}
func test1ClefAtEndWithOriginal() {
let note = Note(noteDuration: .eighth, pitch: SpelledPitch(noteLetter: .c, octave: .octave1))
var testMeasure = Measure(timeSignature: timeSignature, notes: [
[
note, note, note, note,
],
])
let originalClef: Clef = .treble
testMeasure.originalClef = originalClef
assertNoErrorThrown {
let newClef: Clef = .bass
try testMeasure.changeClef(newClef, at: 3)
try (0 ..< 3).forEach {
XCTAssertEqual(try testMeasure.clef(at: $0, inSet: 0), originalClef)
}
try (3 ..< testMeasure.noteCount[0]).forEach {
XCTAssertEqual(try testMeasure.clef(at: $0, inSet: 0), newClef)
}
}
}
func test2ClefsInDifferentSetsWithOriginal() {
let eighth = Note(noteDuration: .eighth, pitch: SpelledPitch(noteLetter: .c, octave: .octave1))
let sixteenth = Note(noteDuration: .sixteenth, pitch: SpelledPitch(noteLetter: .c, octave: .octave1))
var testMeasure = Measure(timeSignature: timeSignature, notes: [
[
sixteenth, sixteenth, sixteenth, sixteenth, sixteenth, sixteenth, sixteenth, sixteenth,
],
[
eighth, eighth, eighth, eighth,
],
])
let originalClef: Clef = .treble
testMeasure.originalClef = originalClef
assertNoErrorThrown {
let newClef1: Clef = .bass
let newClef2: Clef = .alto
try testMeasure.changeClef(newClef1, at: 2, inSet: 1) // Set 0: 5th note changes. Set 1: 3rd note changes.
try testMeasure.changeClef(newClef2, at: 7, inSet: 0) // Set 0: 8th note changes. Set 1: No change.
// set 0
try (0 ..< 4).forEach {
XCTAssertEqual(try testMeasure.clef(at: $0, inSet: 0), originalClef)
}
try (4 ..< 7).forEach {
XCTAssertEqual(try testMeasure.clef(at: $0, inSet: 0), newClef1)
}
try (7 ..< testMeasure.noteCount[0]).forEach {
XCTAssertEqual(try testMeasure.clef(at: $0, inSet: 0), newClef2)
}
// set 1
try (0 ..< 2).forEach {
XCTAssertEqual(try testMeasure.clef(at: $0, inSet: 1), originalClef)
}
try (2 ..< testMeasure.noteCount[1]).forEach {
XCTAssertEqual(try testMeasure.clef(at: $0, inSet: 1), newClef1)
}
}
}
func test2ClefsInDifferentSetsNoOriginal() {
let eighth = Note(noteDuration: .eighth, pitch: SpelledPitch(noteLetter: .c, octave: .octave1))
let sixteenth = Note(noteDuration: .sixteenth, pitch: SpelledPitch(noteLetter: .c, octave: .octave1))
var testMeasure = Measure(timeSignature: timeSignature, notes: [
[
sixteenth, sixteenth, sixteenth, sixteenth, sixteenth, sixteenth, sixteenth, sixteenth,
],
[
eighth, eighth, eighth, eighth,
],
])
assertNoErrorThrown {
let newClef1: Clef = .bass
let newClef2: Clef = .alto
try testMeasure.changeClef(newClef1, at: 2, inSet: 1) // Set 0: 5th note changes. Set 1: 3rd note changes.
try testMeasure.changeClef(newClef2, at: 7, inSet: 0) // Set 0: 8th note changes. Set 1: No change.
// set 0
(0 ..< 4).forEach { index in
assertThrowsError(MeasureError.noClefSpecified) {
_ = try testMeasure.clef(at: index, inSet: 0)
}
}
try (4 ..< 7).forEach {
XCTAssertEqual(try testMeasure.clef(at: $0, inSet: 0), newClef1)
}
try (7 ..< testMeasure.noteCount[0]).forEach {
XCTAssertEqual(try testMeasure.clef(at: $0, inSet: 0), newClef2)
}
// set 1
(0 ..< 2).forEach { index in
assertThrowsError(MeasureError.noClefSpecified) {
_ = try testMeasure.clef(at: index, inSet: 1)
}
}
try (2 ..< testMeasure.noteCount[1]).forEach {
XCTAssertEqual(try testMeasure.clef(at: $0, inSet: 1), newClef1)
}
}
}
// MARK: Failures
func testNoClefsNoOriginal() {
let note = Note(noteDuration: .eighth, pitch: SpelledPitch(noteLetter: .c, octave: .octave1))
let testMeasure = Measure(timeSignature: timeSignature, notes: [
[
note, note, note, note,
],
])
(0 ..< testMeasure.noteCount[0]).forEach { index in
assertThrowsError(MeasureError.noClefSpecified) {
_ = try testMeasure.clef(at: index, inSet: 0)
}
}
}
func test1ClefNotAtBeginningNoOriginal() {
let note = Note(noteDuration: .eighth, pitch: SpelledPitch(noteLetter: .c, octave: .octave1))
var testMeasure = Measure(timeSignature: timeSignature, notes: [
[
note, note, note, note,
],
])
let newClef: Clef = .alto
assertNoErrorThrown {
try testMeasure.changeClef(.alto, at: 2)
}
(0 ..< 2).forEach { index in
assertThrowsError(MeasureError.noClefSpecified) {
_ = try testMeasure.clef(at: index, inSet: 0)
}
}
assertNoErrorThrown {
try (2 ..< testMeasure.noteCount[0]).forEach {
XCTAssertEqual(try testMeasure.clef(at: $0, inSet: 0), newClef)
}
}
}
func testClefsInvalidNoteIndex() {
let note = Note(noteDuration: .eighth, pitch: SpelledPitch(noteLetter: .c, octave: .octave1))
let testMeasure = Measure(timeSignature: timeSignature, notes: [
[
note, note, note, note,
],
])
assertThrowsError(MeasureError.noteIndexOutOfRange) {
_ = try testMeasure.clef(at: 17, inSet: 0)
}
}
func testClefsInvalidSetIndex() {
let note = Note(noteDuration: .eighth, pitch: SpelledPitch(noteLetter: .c, octave: .octave1))
let testMeasure = Measure(timeSignature: timeSignature, notes: [
[
note, note, note, note,
],
])
assertThrowsError(MeasureError.noteIndexOutOfRange) {
_ = try testMeasure.clef(at: 0, inSet: 3)
}
}
// MARK: - changeClef(_:at:inSet:) throws
// MARK: Failures
func testChangeClefInvalidNoteIndex() {
let note = Note(noteDuration: .eighth, pitch: SpelledPitch(noteLetter: .c, octave: .octave1))
var measure = Measure(timeSignature: timeSignature, notes: [
[
note, note, note, note,
],
])
assertThrowsError(MeasureError.noteIndexOutOfRange) {
try measure.changeClef(.bass, at: 5)
}
XCTAssertNil(measure.originalClef)
XCTAssertNil(measure.lastClef)
XCTAssertEqual(measure.clefs, [:])
}
func testChangeClefInvalidSetIndex() {
let note = Note(noteDuration: .eighth, pitch: SpelledPitch(noteLetter: .c, octave: .octave1))
var measure = Measure(timeSignature: timeSignature, notes: [
[
note, note, note, note,
],
])
assertThrowsError(MeasureError.noteIndexOutOfRange) {
try measure.changeClef(.bass, at: 3, inSet: 1)
}
XCTAssertNil(measure.originalClef)
XCTAssertNil(measure.lastClef)
XCTAssertEqual(measure.clefs, [:])
}
// MARK: Successes
func testChangeClefAtBeginningNoOthers() {
let eighth = Note(noteDuration: .eighth, pitch: SpelledPitch(noteLetter: .c, octave: .octave1))
let quarter = Note(noteDuration: .sixteenth, pitch: SpelledPitch(noteLetter: .c, octave: .octave1))
var measure = Measure(timeSignature: timeSignature, notes: [
[
quarter, quarter, quarter, quarter,
],
[
eighth, eighth, eighth, eighth, eighth, eighth, eighth, eighth,
],
])
assertNoErrorThrown {
try measure.changeClef(.bass, at: 0, inSet: 0)
XCTAssertEqual(measure.clefs, [0: .bass])
XCTAssertEqual(measure.lastClef, .bass)
XCTAssertEqual(measure.originalClef, nil)
}
}
func testChangeClefAtBeginningNoOthersSecondSet() {
let eighth = Note(noteDuration: .eighth, pitch: SpelledPitch(noteLetter: .c, octave: .octave1))
let quarter = Note(noteDuration: .sixteenth, pitch: SpelledPitch(noteLetter: .c, octave: .octave1))
var measure = Measure(timeSignature: timeSignature, notes: [
[
quarter, quarter, quarter, quarter,
],
[
eighth, eighth, eighth, eighth, eighth, eighth, eighth, eighth,
],
])
assertNoErrorThrown {
try measure.changeClef(.bass, at: 0, inSet: 1)
XCTAssertEqual(measure.clefs, [0: .bass])
XCTAssertEqual(measure.lastClef, .bass)
XCTAssertEqual(measure.originalClef, nil)
}
}
func testChangeClefAtBeginningAlreadyThere() {
let eighth = Note(noteDuration: .eighth, pitch: SpelledPitch(noteLetter: .c, octave: .octave1))
let quarter = Note(noteDuration: .sixteenth, pitch: SpelledPitch(noteLetter: .c, octave: .octave1))
var measure = Measure(timeSignature: timeSignature, notes: [
[
quarter, quarter, quarter, quarter,
],
[
eighth, eighth, eighth, eighth, eighth, eighth, eighth, eighth,
],
])
assertNoErrorThrown {
try measure.changeClef(.bass, at: 0, inSet: 1)
try measure.changeClef(.treble, at: 0, inSet: 1)
XCTAssertEqual(measure.clefs, [0: .treble])
XCTAssertEqual(measure.lastClef, .treble)
XCTAssertEqual(measure.originalClef, nil)
}
}
func testChangeClefInMiddleNoOthers() {
let eighth = Note(noteDuration: .eighth, pitch: SpelledPitch(noteLetter: .c, octave: .octave1))
let quarter = Note(noteDuration: .sixteenth, pitch: SpelledPitch(noteLetter: .c, octave: .octave1))
var measure = Measure(timeSignature: timeSignature, notes: [
[
quarter, quarter, quarter, quarter,
],
[
eighth, eighth, eighth, eighth, eighth, eighth, eighth, eighth,
],
])
assertNoErrorThrown {
try measure.changeClef(.bass, at: 3, inSet: 1)
XCTAssertEqual(measure.clefs, [3072: .bass])
XCTAssertEqual(measure.lastClef, .bass)
XCTAssertEqual(measure.originalClef, nil)
}
}
func testChangeClefInMiddleHasBeginning() {
let eighth = Note(noteDuration: .eighth, pitch: SpelledPitch(noteLetter: .c, octave: .octave1))
let quarter = Note(noteDuration: .sixteenth, pitch: SpelledPitch(noteLetter: .c, octave: .octave1))
var measure = Measure(timeSignature: timeSignature, notes: [
[
quarter, quarter, quarter, quarter,
],
[
eighth, eighth, eighth, eighth, eighth, eighth, eighth, eighth,
],
])
assertNoErrorThrown {
try measure.changeClef(.treble, at: 0, inSet: 1)
try measure.changeClef(.bass, at: 3, inSet: 1)
XCTAssertEqual(measure.clefs, [0: .treble, 3072: .bass])
XCTAssertEqual(measure.lastClef, .bass)
XCTAssertEqual(measure.originalClef, nil)
}
}
func testChangeClefInMiddleHasEnd() {
let eighth = Note(noteDuration: .eighth, pitch: SpelledPitch(noteLetter: .c, octave: .octave1))
let quarter = Note(noteDuration: .sixteenth, pitch: SpelledPitch(noteLetter: .c, octave: .octave1))
var measure = Measure(timeSignature: timeSignature, notes: [
[
quarter, quarter, quarter, quarter,
],
[
eighth, eighth, eighth, eighth, eighth, eighth, eighth, eighth,
],
])
print(measure.debugDescription)
assertNoErrorThrown {
try measure.changeClef(.bass, at: 3, inSet: 1)
try measure.changeClef(.treble, at: 7, inSet: 1)
XCTAssertEqual(measure.clefs, [3072: .bass, 7168: .treble])
XCTAssertEqual(measure.lastClef, .treble)
XCTAssertEqual(measure.originalClef, nil)
}
}
func testChangeClefInMiddleHasBeginningAndEnd() {
let eighth = Note(noteDuration: .eighth, pitch: SpelledPitch(noteLetter: .c, octave: .octave1))
let quarter = Note(noteDuration: .sixteenth, pitch: SpelledPitch(noteLetter: .c, octave: .octave1))
var measure = Measure(timeSignature: timeSignature, notes: [
[
quarter, quarter, quarter, quarter,
],
[
eighth, eighth, eighth, eighth, eighth, eighth, eighth, eighth,
],
])
assertNoErrorThrown {
try measure.changeClef(.treble, at: 0, inSet: 1)
try measure.changeClef(.bass, at: 3, inSet: 1)
try measure.changeClef(.treble, at: 7, inSet: 1)
XCTAssertEqual(measure.clefs, [0: .treble, 3072: .bass, 7168: .treble])
XCTAssertEqual(measure.lastClef, .treble)
XCTAssertEqual(measure.originalClef, nil)
}
print(measure.debugDescription)
}
func testChangeClefWithinTuplet() {
let quarter = Note(restDuration: .quarter)
let eighth = Note(noteDuration: .eighth, pitch: SpelledPitch(noteLetter: .c, octave: .octave1))
assertNoErrorThrown {
let tuplet = try Tuplet(3, .eighth, notes: [eighth, eighth, eighth])
measure.append(quarter)
measure.append(quarter)
measure.append(tuplet)
measure.append(eighth)
measure.append(eighth)
try measure.changeClef(.bass, at: 5, inSet: 0)
XCTAssertEqual(measure.clefs, [6144: .bass])
XCTAssertEqual(measure.lastClef, .bass)
XCTAssertEqual(measure.originalClef, nil)
}
}
// MARK: - changeFirstClefIfNeeded(to:) -> Bool
// MARK: Return False
func testChangeFirstClefIfNeededWhenNotEmpty() {
// Setup
let eighth = Note(noteDuration: .eighth, pitch: SpelledPitch(noteLetter: .c, octave: .octave1))
let quarter = Note(noteDuration: .sixteenth, pitch: SpelledPitch(noteLetter: .c, octave: .octave1))
var measure = Measure(timeSignature: timeSignature, notes: [
[
quarter, quarter, quarter, quarter,
],
[
eighth, eighth, eighth, eighth, eighth, eighth, eighth, eighth,
],
])
assertNoErrorThrown {
try measure.changeClef(.bass, at: 0)
}
// Test
XCTAssertEqual(measure.changeFirstClefIfNeeded(to: .treble), false)
XCTAssertEqual(measure.lastClef, .bass)
XCTAssertEqual(measure.originalClef, nil)
XCTAssertEqual(measure.clefs, [0: .bass])
}
// MARK: Return True
func testChangeFirstClefIfNeededWhenEmtpy() {
// Setup
let eighth = Note(noteDuration: .eighth, pitch: SpelledPitch(noteLetter: .c, octave: .octave1))
let quarter = Note(noteDuration: .sixteenth, pitch: SpelledPitch(noteLetter: .c, octave: .octave1))
var measure = Measure(timeSignature: timeSignature, notes: [
[
quarter, quarter, quarter, quarter,
],
[
eighth, eighth, eighth, eighth, eighth, eighth, eighth, eighth,
],
])
// Test
XCTAssertEqual(measure.changeFirstClefIfNeeded(to: .treble), true)
XCTAssertEqual(measure.lastClef, .treble)
XCTAssertEqual(measure.originalClef, .treble)
XCTAssertTrue(measure.clefs.isEmpty)
}
// MARK: - Collection Conformance
func testMapEmpty() {
let mappedMeasureSlices = measure.compactMap { $0 }
let expectedMeasureSlices: [MeasureSlice] = []
XCTAssertTrue(mappedMeasureSlices.isEmpty)
XCTAssertTrue(expectedMeasureSlices.isEmpty)
let repeatedMeasure = RepeatedMeasure(timeSignature: timeSignature)
let repeatedMappedMeasureSlices = repeatedMeasure.map { $0 }
XCTAssertTrue(repeatedMappedMeasureSlices.isEmpty)
XCTAssertTrue(expectedMeasureSlices.isEmpty)
}
func testMapSingleNoteSet() {
measure.append(Note(restDuration: .quarter))
measure.append(Note(restDuration: .quarter))
measure.append(Note(restDuration: .eighth))
measure.append(Note(restDuration: .eighth))
measure.append(Note(restDuration: .quarter))
let repeatedMeasure = RepeatedMeasure(
timeSignature: timeSignature,
notes: [
[
Note(restDuration: .quarter),
Note(restDuration: .quarter),
Note(restDuration: .eighth),
Note(restDuration: .eighth),
Note(restDuration: .quarter),
],
]
)
let repeatedMappedMeasureSlices = repeatedMeasure.map { $0 }
let mappedMeasureSlices = measure.compactMap { $0 }
let expectedMeasureSlices: [[MeasureSlice]] = [
[MeasureSlice(noteSetIndex: 0, noteCollection: Note(restDuration: .quarter))],
[MeasureSlice(noteSetIndex: 0, noteCollection: Note(restDuration: .quarter))],
[MeasureSlice(noteSetIndex: 0, noteCollection: Note(restDuration: .eighth))],
[MeasureSlice(noteSetIndex: 0, noteCollection: Note(restDuration: .eighth))],
[MeasureSlice(noteSetIndex: 0, noteCollection: Note(restDuration: .quarter))],
]
var count = 0
zip(mappedMeasureSlices, expectedMeasureSlices).forEach {
XCTAssertEqual($0, $1)
count += 1
}
XCTAssertEqual(count, expectedMeasureSlices.count)
var repeatedCount = 0
zip(repeatedMappedMeasureSlices, expectedMeasureSlices).forEach {
XCTAssertEqual($0, $1)
repeatedCount += 1
}
XCTAssertEqual(repeatedCount, expectedMeasureSlices.count)
}
func testMapMultipleNoteSets() {
measure.append(Note(restDuration: .quarter), inSet: 0)
measure.append(Note(restDuration: .sixteenth), inSet: 1)
measure.append(Note(restDuration: .quarter), inSet: 0)
measure.append(Note(restDuration: .thirtySecond), inSet: 1)
measure.append(Note(restDuration: .eighth), inSet: 0)
measure.append(Note(restDuration: .quarter), inSet: 1)
measure.append(Note(restDuration: .eighth), inSet: 0)
measure.append(Note(restDuration: .quarter), inSet: 1)
measure.append(Note(restDuration: .quarter), inSet: 0)
measure.append(Note(restDuration: .quarter), inSet: 1)
measure.append(Note(restDuration: .whole), inSet: 1)
measure.append(Note(restDuration: .whole), inSet: 1)
let repeatedMeasure = RepeatedMeasure(
timeSignature: timeSignature,
notes: [
[
Note(restDuration: .quarter),
Note(restDuration: .quarter),
Note(restDuration: .eighth),
Note(restDuration: .eighth),
Note(restDuration: .quarter),
],
[
Note(restDuration: .sixteenth),
Note(restDuration: .thirtySecond),
Note(restDuration: .quarter),
Note(restDuration: .quarter),
Note(restDuration: .quarter),
Note(restDuration: .whole),
Note(restDuration: .whole),
],
]
)
let repeatedMappedMeasureSlices = repeatedMeasure.map { $0 }
let mappedMeasureSlices = measure.compactMap { $0 }
let expectedMeasureSlices: [[MeasureSlice]] = [
[
MeasureSlice(noteSetIndex: 0, noteCollection: Note(restDuration: .quarter)),
MeasureSlice(noteSetIndex: 1, noteCollection: Note(restDuration: .sixteenth)),
],
[
MeasureSlice(noteSetIndex: 0, noteCollection: Note(restDuration: .quarter)),
MeasureSlice(noteSetIndex: 1, noteCollection: Note(restDuration: .thirtySecond)),
],
[
MeasureSlice(noteSetIndex: 0, noteCollection: Note(restDuration: .eighth)),
MeasureSlice(noteSetIndex: 1, noteCollection: Note(restDuration: .quarter)),
],
[
MeasureSlice(noteSetIndex: 0, noteCollection: Note(restDuration: .eighth)),
MeasureSlice(noteSetIndex: 1, noteCollection: Note(restDuration: .quarter)),
],
[
MeasureSlice(noteSetIndex: 0, noteCollection: Note(restDuration: .quarter)),
MeasureSlice(noteSetIndex: 1, noteCollection: Note(restDuration: .quarter)),
],
[
MeasureSlice(noteSetIndex: 1, noteCollection: Note(restDuration: .whole)),
],
[
MeasureSlice(noteSetIndex: 1, noteCollection: Note(restDuration: .whole)),
],
]
var count = 0
zip(mappedMeasureSlices, expectedMeasureSlices).forEach {
XCTAssertEqual($0, $1)
count += 1
}
XCTAssertEqual(count, expectedMeasureSlices.count)
var repeatedCount = 0
zip(repeatedMappedMeasureSlices, expectedMeasureSlices).forEach {
XCTAssertEqual($0, $1)
repeatedCount += 1
}
XCTAssertEqual(repeatedCount, expectedMeasureSlices.count)
}
func testReversed() {
measure.append(Note(restDuration: .whole), inSet: 0)
measure.append(Note(restDuration: .thirtySecond), inSet: 1)
measure.append(Note(restDuration: .quarter), inSet: 0)
measure.append(Note(restDuration: .sixtyFourth), inSet: 1)
measure.append(Note(restDuration: .eighth), inSet: 0)
measure.append(Note(restDuration: .oneTwentyEighth), inSet: 1)
measure.append(Note(restDuration: .sixteenth), inSet: 0)
measure.append(Note(restDuration: .twoFiftySixth), inSet: 1)
let repeatedMeasure = RepeatedMeasure(
timeSignature: timeSignature,
notes: [
[
Note(restDuration: .whole),
Note(restDuration: .quarter),
Note(restDuration: .eighth),
Note(restDuration: .sixteenth),
],
[
Note(restDuration: .thirtySecond),
Note(restDuration: .sixtyFourth),
Note(restDuration: .oneTwentyEighth),
Note(restDuration: .twoFiftySixth),
],
]
)
let repeatedReversedMeasureSlices = repeatedMeasure.reversed()
let reversedMeasureSlices = measure.reversed()
let expectedMeasureSlices: [[MeasureSlice]] = [
[
MeasureSlice(noteSetIndex: 0, noteCollection: Note(restDuration: .sixteenth)),
MeasureSlice(noteSetIndex: 1, noteCollection: Note(restDuration: .twoFiftySixth)),
],
[
MeasureSlice(noteSetIndex: 0, noteCollection: Note(restDuration: .eighth)),
MeasureSlice(noteSetIndex: 1, noteCollection: Note(restDuration: .oneTwentyEighth)),
],
[
MeasureSlice(noteSetIndex: 0, noteCollection: Note(restDuration: .quarter)),
MeasureSlice(noteSetIndex: 1, noteCollection: Note(restDuration: .sixtyFourth)),
],
[
MeasureSlice(noteSetIndex: 0, noteCollection: Note(restDuration: .whole)),
MeasureSlice(noteSetIndex: 1, noteCollection: Note(restDuration: .thirtySecond)),
],
]
var count = 0
zip(reversedMeasureSlices, expectedMeasureSlices).forEach {
XCTAssertEqual($0, $1)
count += 1
}
XCTAssertEqual(count, expectedMeasureSlices.count)
var repeatedCount = 0
zip(repeatedReversedMeasureSlices, expectedMeasureSlices).forEach {
XCTAssertEqual($0, $1)
repeatedCount += 1
}
XCTAssertEqual(repeatedCount, expectedMeasureSlices.count)
}
func testIterator() {
measure.append(Note(restDuration: .whole), inSet: 0)
measure.append(Note(restDuration: .thirtySecond), inSet: 1)
measure.append(Note(restDuration: .quarter), inSet: 0)
measure.append(Note(restDuration: .eighth), inSet: 1)
let repeatedMeasure = RepeatedMeasure(
timeSignature: timeSignature,
notes: [
[
Note(restDuration: .whole),
Note(restDuration: .quarter),
],
[
Note(restDuration: .thirtySecond),
Note(restDuration: .eighth),
],
]
)
let expectedMeasureSlice1: [MeasureSlice] = [
MeasureSlice(noteSetIndex: 0, noteCollection: Note(restDuration: .whole)),
MeasureSlice(noteSetIndex: 1, noteCollection: Note(restDuration: .thirtySecond)),
]
let expectedMeasureSlice2: [MeasureSlice] = [
MeasureSlice(noteSetIndex: 0, noteCollection: Note(restDuration: .quarter)),
MeasureSlice(noteSetIndex: 1, noteCollection: Note(restDuration: .eighth)),
]
let expectedMeasureSlices = [expectedMeasureSlice1, expectedMeasureSlice2]
var iterator = measure.makeIterator()
var iteratorCount = 0
while let next = iterator.next() {
XCTAssertEqual(next, expectedMeasureSlices[iteratorCount])
iteratorCount += 1
}
XCTAssertEqual(iteratorCount, expectedMeasureSlices.count)
var repeatedIterator = repeatedMeasure.makeIterator()
var repeatedIteratorCount = 0
while let next = repeatedIterator.next() {
XCTAssertEqual(next, expectedMeasureSlices[repeatedIteratorCount])
repeatedIteratorCount += 1
}
XCTAssertEqual(repeatedIteratorCount, expectedMeasureSlices.count)
}
// MARK: - Helpers
private func setTie(at index: Int, functionName: String = #function, lineNum: Int = #line) {
assertNoErrorThrown {
try measure.startTie(at: index, inSet: 0)
let noteCollectionIndex1 = try measure.noteCollectionIndex(fromNoteIndex: index, inSet: 0)
let noteCollectionIndex2 = try measure.noteCollectionIndex(fromNoteIndex: index + 1, inSet: 0)
let firstNote = noteFromMeasure(measure, noteIndex: noteCollectionIndex1.noteIndex,
tupletIndex: noteCollectionIndex1.tupletIndex)
let secondNote = noteFromMeasure(measure, noteIndex: noteCollectionIndex2.noteIndex,
tupletIndex: noteCollectionIndex2.tupletIndex)
XCTAssert(firstNote.tie == .begin || firstNote.tie == .beginAndEnd,
"\(functionName): \(lineNum)")
XCTAssert(secondNote.tie == .end || secondNote.tie == .beginAndEnd,
"\(functionName): \(lineNum)")
}
}
private func noteFromMeasure(_ measure: Measure, noteIndex: Int, tupletIndex: Int?) -> Note {
if let tupletIndex = tupletIndex {
let tuplet = measure.notes[0][noteIndex] as! Tuplet
return try! tuplet.note(at: tupletIndex)
} else {
return measure.notes[0][noteIndex] as! Note
}
}
}
| mit | ef76d3c130ba4f4f20f092e7d9cce88f | 35.369817 | 121 | 0.717689 | 3.538869 | false | true | false | false |
RyanMacG/poppins | Poppins/Models/ImageFetcher.swift | 3 | 1931 | import Foundation
import Runes
@objc class ImageFetcher {
let imageCache: Cache<UIImage>
let purger: CachePurger
let operationQueue: AsyncQueue
var inProgress: [String] = []
init() {
imageCache = Cache<UIImage>()
purger = CachePurger(cache: imageCache)
operationQueue = AsyncQueue(name: "PoppinsCacheQueue", maxOperations: NSOperationQueueDefaultMaxConcurrentOperationCount)
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("didReceiveMemoryWarning"), name: UIApplicationDidReceiveMemoryWarningNotification, object: .None)
}
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self)
}
func didReceiveMemoryWarning() {
inProgress = []
}
func fetchImage(size: CGSize, path: String) -> UIImage? {
if let image = imageCache.itemForKey(path) {
return image
} else {
if size == CGSizeZero { return .None }
dispatch_to_main {
objc_sync_enter(self.inProgress)
if contains(self.inProgress, path) { return }
self.inProgress.append(path)
objc_sync_exit(self.inProgress)
let operation = ImageFetcherOperation(path: path, size: size) { image in
curry(self.imageCache.setItem) <^> image <*> path
dispatch_to_main {
objc_sync_enter(self.inProgress)
self.inProgress.removeAtIndex <^> find(self.inProgress, path)
objc_sync_exit(self.inProgress)
NSNotificationCenter.defaultCenter().postNotificationName("CacheDidUpdate", object: .None)
}
}
self.operationQueue.addOperation(operation)
}
return .None
}
}
}
| mit | 85393cc3eeb356558f43bc2b15e6b8df | 35.433962 | 180 | 0.581046 | 5.439437 | false | false | false | false |
mspvirajpatel/SwiftyBase | SwiftyBase/Classes/Utility/AppEnumerable.swift | 1 | 893 | //
// AppEnumerable.swift
// SwiftyBase
//
// Created by MacMini-2 on 08/09/17.
//
import Foundation
public protocol AppEnumerable: RawRepresentable {
static var enumerate: AnySequence<Self> { get }
static var elements: [Self] { get }
static var count: Int { get }
static var startIndex: Int { get }
}
public extension AppEnumerable where RawValue == Int {
static var enumerate: AnySequence<Self> {
return AnySequence { () -> AnyIterator<Self> in
var i = startIndex
return AnyIterator { () -> Self? in
let element = Self(rawValue: i)
i += 1
return element
}
}
}
static var elements: [Self] {
return Array(enumerate)
}
static var count: Int {
return elements.count
}
static var startIndex: Int {
return 0
}
}
| mit | 8995f6ed1998edfad998338d8756dbb7 | 21.325 | 55 | 0.569989 | 4.420792 | false | false | false | false |
plaetzchen/OctoPrintApp | OctoPrint/OverviewTableViewController.swift | 2 | 3693 | //
// ViewController.swift
// OctoPrint
//
// Created by Michael Teeuw on 22-07-15.
// Copyright © 2015 Michael Teeuw. All rights reserved.
//
import UIKit
class OverviewTableViewController: UITableViewController {
let sections = ["Version", "State"]
override func viewDidLoad() {
title = "Info"
super.viewDidLoad()
NSNotificationCenter.defaultCenter().addObserver(self, selector: "updateUI", key: .DidUpdatePrinter, object: OPManager.sharedInstance)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "updateUI", key: .DidUpdateVersion, object: OPManager.sharedInstance)
OPManager.sharedInstance.updateVersion()
OPManager.sharedInstance.updatePrinter(autoUpdate:1)
OPManager.sharedInstance.updateSettings()
updateUI()
}
func updateUI() {
tableView.reloadData()
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return sections.count
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
switch section {
case 0:
return 2
case 1:
return 1
default:
return 0
}
}
override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return sections[section]
}
override func tableView(tableView: UITableView, titleForFooterInSection section: Int) -> String? {
if section == tableView.numberOfSections - 1 {
if let updated = OPManager.sharedInstance.updateTimeStamp {
let formattedDate = NSDateFormatter.localizedStringFromDate(updated,dateStyle: NSDateFormatterStyle.MediumStyle, timeStyle: .MediumStyle)
return "Last update: \(formattedDate)"
}
}
return nil
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let shortPath = (indexPath.section, indexPath.row)
switch shortPath {
case (0, 0):
let cell = tableView.dequeueReusableCellWithIdentifier("BasicCell", forIndexPath: indexPath)
cell.textLabel?.text = "API"
cell.detailTextLabel?.text = OPManager.sharedInstance.apiVersion
cell.userInteractionEnabled = false
return cell
case (0, 1):
let cell = tableView.dequeueReusableCellWithIdentifier("BasicCell", forIndexPath: indexPath)
cell.textLabel?.text = "Server"
cell.detailTextLabel?.text = OPManager.sharedInstance.serverVersion
cell.userInteractionEnabled = false
return cell
case (1, 0):
let cell = tableView.dequeueReusableCellWithIdentifier("BasicCell", forIndexPath: indexPath)
cell.textLabel?.text = "Printer"
cell.detailTextLabel?.text = OPManager.sharedInstance.printerStateText
cell.userInteractionEnabled = false
return cell
default:
let cell = tableView.dequeueReusableCellWithIdentifier("BasicCell", forIndexPath: indexPath)
cell.textLabel?.text = "Unknown cell!"
return cell
}
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
}
}
| mit | aee6c6b6a32a1551efe704533b4fa9fb | 30.288136 | 142 | 0.621614 | 5.832543 | false | false | false | false |
luzefeng/MLSwiftBasic | MLSwiftBasic/Classes/Refresh/ZLSwifthRefresh/ZLSwiftHeadView.swift | 1 | 11041 | //
// ZLSwiftHeadView.swift
// ZLSwiftRefresh
//
// Created by 张磊 on 15-3-6.
// Copyright (c) 2015年 com.zixue101.www. All rights reserved.
//
import UIKit
var KVOContext = ""
let imageViewW:CGFloat = 50
let labelTextW:CGFloat = 150
public class ZLSwiftHeadView: UIView {
private var headLabel: UILabel = UILabel()
var headImageView : UIImageView = UIImageView()
var scrollView:UIScrollView = UIScrollView()
var customAnimation:Bool = false
var pullImages:[UIImage] = [UIImage]()
var animationStatus:HeaderViewRefreshAnimationStatus?
var activityView: UIActivityIndicatorView?
var nowLoading:Bool = false{
willSet {
if (newValue == true){
self.nowLoading = newValue
self.scrollView.contentOffset = CGPointMake(0, -ZLSwithRefreshHeadViewHeight)//UIEdgeInsetsMake(ZLSwithRefreshHeadViewHeight, 0, self.scrollView.contentInset.bottom, 0)
}
}
}
var action: (() -> ()) = {}
var nowAction: (() -> ()) = {}
private var refreshTempAction:(() -> Void) = {}
convenience init(action :(() -> ()), frame: CGRect) {
self.init(frame: frame)
self.action = action
self.nowAction = action
}
override init(frame: CGRect) {
super.init(frame: frame)
self.setupUI()
}
public required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
var imgName:String {
set {
if(!self.customAnimation){
// 默认动画
if (self.animationStatus != .headerViewRefreshArrowAnimation){
self.headImageView.image = self.imageBundleWithNamed(named: "dropdown_anim__000\(newValue)")
}else{
// 箭头动画
self.headImageView.image = self.imageBundleWithNamed(named: "arrow")
}
}else{
if (self.pullImages.count > newValue.toInt()){
var image = self.pullImages[newValue.toInt()!]
self.headImageView.image = image
}
}
}
get {
return self.imgName
}
}
func setupUI(){
var headImageView:UIImageView = UIImageView(frame: CGRectZero)
headImageView.contentMode = .Center
headImageView.clipsToBounds = true;
self.addSubview(headImageView)
self.headImageView = headImageView
var headLabel:UILabel = UILabel(frame: self.frame)
headLabel.text = ZLSwithRefreshHeadViewText
headLabel.textAlignment = .Center
headLabel.clipsToBounds = true;
self.addSubview(headLabel)
self.headLabel = headLabel
var activityView = UIActivityIndicatorView(activityIndicatorStyle: .Gray)
self.addSubview(activityView)
self.activityView = activityView
}
func startAnimation(){
if (!self.customAnimation){
if (self.animationStatus != .headerViewRefreshArrowAnimation){
var results:[AnyObject] = []
for i in 1..<4{
var image:UIImage = self.imageBundleWithNamed(named: "dropdown_loading_0\(i)")
if image.size.height > 0 && image.size.width > 0 {
results.append(image)
}
}
self.headImageView.animationImages = results as [AnyObject]?
self.headImageView.animationDuration = 0.6
}else{
self.headImageView.hidden = true
self.activityView?.startAnimating()
}
}else{
var duration:Double = Double(self.pullImages.count) * 0.1
self.headImageView.animationDuration = duration
}
self.headLabel.text = ZLSwithRefreshLoadingText
if (self.animationStatus != .headerViewRefreshArrowAnimation){
self.headImageView.animationRepeatCount = 0
self.headImageView.startAnimating()
}
}
func stopAnimation(){
self.nowLoading = false
self.headLabel.text = ZLSwithRefreshHeadViewText
UIView.animateWithDuration(0.25, animations: { () -> Void in
if (abs(self.scrollView.contentOffset.y) >= self.getNavigationHeight() + ZLSwithRefreshHeadViewHeight){
self.scrollView.contentInset = UIEdgeInsetsMake(self.getNavigationHeight(), 0, self.scrollView.contentInset.bottom, 0)
}else{
self.scrollView.contentInset = UIEdgeInsetsMake(self.getNavigationHeight() + self.scrollView.contentOffset.y, 0, self.scrollView.contentInset.bottom, 0)
}
})
if (self.animationStatus == .headerViewRefreshArrowAnimation){
self.activityView?.stopAnimating()
self.headImageView.hidden = false
}else{
self.headImageView.stopAnimating()
}
}
public override func layoutSubviews() {
super.layoutSubviews()
headLabel.sizeToFit()
headLabel.frame = CGRectMake((self.frame.size.width - labelTextW) / 2, -self.scrollView.frame.origin.y, labelTextW, self.frame.size.height)
headImageView.frame = CGRectMake(headLabel.frame.origin.x - imageViewW - 5, headLabel.frame.origin.y, imageViewW, self.frame.size.height)
self.activityView?.frame = headImageView.frame
}
public override func willMoveToSuperview(newSuperview: UIView!) {
superview?.removeObserver(self, forKeyPath: contentOffsetKeyPath, context: &KVOContext)
if (newSuperview != nil && newSuperview.isKindOfClass(UIScrollView)) {
self.scrollView = newSuperview as! UIScrollView
newSuperview.addObserver(self, forKeyPath: contentOffsetKeyPath, options: .Initial, context: &KVOContext)
}
}
func imageBundleWithNamed(#named: String!) -> UIImage{
return UIImage(named: ZLSwiftRefreshBundleName.stringByAppendingPathComponent(named))!
}
//MARK: KVO methods
public override func observeValueForKeyPath(keyPath: String, ofObject object: AnyObject, change: [NSObject : AnyObject], context: UnsafeMutablePointer<()>) {
if (self.action == nil) {
return;
}
var scrollView:UIScrollView = self.scrollView
// change contentOffset
var scrollViewContentOffsetY:CGFloat = scrollView.contentOffset.y
var height = ZLSwithRefreshHeadViewHeight
if (ZLSwithRefreshHeadViewHeight > animations){
height = animations
}
if (scrollViewContentOffsetY + self.getNavigationHeight() != 0 && scrollViewContentOffsetY <= -height - scrollView.contentInset.top + 20) {
if (self.animationStatus == .headerViewRefreshArrowAnimation){
UIView.animateWithDuration(0.15, animations: { () -> Void in
self.headImageView.transform = CGAffineTransformMakeRotation(CGFloat(M_PI))
})
}
// 上拉刷新
self.headLabel.text = ZLSwithRefreshRecoderText
if scrollView.dragging == false && self.headImageView.isAnimating() == false{
if refreshTempAction != nil {
refreshStatus = .Refresh
self.startAnimation()
UIView.animateWithDuration(0.25, animations: { () -> Void in
if scrollView.contentInset.top == 0 {
scrollView.contentInset = UIEdgeInsetsMake(self.getNavigationHeight(), 0, scrollView.contentInset.bottom, 0)
}else{
scrollView.contentInset = UIEdgeInsetsMake(ZLSwithRefreshHeadViewHeight + scrollView.contentInset.top, 0, scrollView.contentInset.bottom, 0)
}
})
if (nowLoading == true){
nowAction()
nowAction = {}
nowLoading = false
}else{
refreshTempAction()
refreshTempAction = {}
}
}
}
}else{
// 上拉刷新
if (nowLoading == true){
self.headLabel.text = ZLSwithRefreshLoadingText
}else if(scrollView.dragging == true){
self.headLabel.text = ZLSwithRefreshHeadViewText
}
if (self.animationStatus == .headerViewRefreshArrowAnimation){
UIView.animateWithDuration(0.15, animations: { () -> Void in
self.headImageView.transform = CGAffineTransformIdentity
})
}
refreshTempAction = self.action
}
// 上拉刷新
if (nowLoading == true){
self.headLabel.text = ZLSwithRefreshLoadingText
}
if (scrollViewContentOffsetY <= 0){
var v:CGFloat = scrollViewContentOffsetY + scrollView.contentInset.top
if ((!self.customAnimation) && (v < -animations || v > animations)){
v = animations
}
if (self.customAnimation){
v *= CGFloat(CGFloat(self.pullImages.count) / ZLSwithRefreshHeadViewHeight)
if (Int(abs(v)) > self.pullImages.count - 1){
v = CGFloat(self.pullImages.count - 1);
}
}
if ((Int)(abs(v)) > 0){
self.imgName = "\((Int)(abs(v)))"
}
}
}
//MARK: getNavigaition Height -> delete
func getNavigationHeight() -> CGFloat{
var vc = UIViewController()
if self.getViewControllerWithView(self).isKindOfClass(UIViewController) == true {
vc = self.getViewControllerWithView(self) as! UIViewController
}
var top = vc.navigationController?.navigationBar.frame.height
if top == nil{
top = 0
}
// iOS7
var offset:CGFloat = 20
if((UIDevice.currentDevice().systemVersion as NSString).floatValue < 7.0){
offset = 0
}
return offset + top!
}
func getViewControllerWithView(vcView:UIView) -> AnyObject{
if( (vcView.nextResponder()?.isKindOfClass(UIViewController) ) == true){
return vcView.nextResponder() as! UIViewController
}
if(vcView.superview == nil){
return vcView
}
return self.getViewControllerWithView(vcView.superview!)
}
deinit{
var scrollView = superview as? UIScrollView
scrollView?.removeObserver(self, forKeyPath: contentOffsetKeyPath, context: &KVOContext)
}
}
| mit | df21c6c4fd18226035b332f7826b5129 | 36.65411 | 184 | 0.570987 | 5.55303 | false | false | false | false |
trill-lang/trill | Sources/AST/Generic.swift | 2 | 1617 | ///
/// Generic.swift
///
/// Copyright 2016-2017 the Trill project authors.
/// Licensed under the MIT License.
///
/// Full license text available at https://github.com/trill-lang/trill
///
import Foundation
import Source
public class GenericParamDecl: TypeDecl {
public var constraints: [TypeRefExpr] {
return conformances
}
public init(name: Identifier, constraints: [TypeRefExpr]) {
super.init(name: name,
properties: [],
methods: [],
staticMethods: [],
initializers: [],
subscripts: [],
modifiers: [],
conformances: constraints,
deinit: nil,
sourceRange: name.range)
self.type = .typeVariable(name: name.name)
}
public override func attributes() -> [String : Any] {
var superAttrs = super.attributes()
if !conformances.isEmpty {
superAttrs["conformances"] = conformances.map { $0.name.name }.joined(separator: ", ")
}
return superAttrs
}
}
public class GenericParam: ASTNode {
public let typeName: TypeRefExpr
public var decl: GenericParamDecl? = nil
public init(typeName: TypeRefExpr) {
self.typeName = typeName
super.init(sourceRange: typeName.sourceRange)
}
public override func attributes() -> [String : Any] {
var superAttrs = super.attributes()
superAttrs["type"] = typeName.name.name
if let decl = decl {
superAttrs["decl"] = decl.name.name
}
return superAttrs
}
}
| mit | c1a9f1e8dac36c605db8302c9af8d23c | 27.368421 | 98 | 0.58256 | 4.755882 | false | false | false | false |
yannickl/DynamicButton | Sources/DynamicButtonPathVector.swift | 1 | 1936 | /*
* DynamicButton
*
* Copyright 2015-present Yannick Loriot.
* http://yannickloriot.com
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
import UIKit
/**
A path vector is a structure compound of 4 paths (p1, p2, p3, p4). It defines the geometric shape used to draw a `DynamicButton`.
*/
public struct DynamicButtonPathVector {
/// The path p1.
public let p1: CGPath
/// The path p2.
public let p2: CGPath
/// The path p3.
public let p3: CGPath
/// The path p4.
public let p4: CGPath
/// Default constructor.
public init(p1 : CGPath, p2 : CGPath, p3 : CGPath, p4 : CGPath) {
self.p1 = p1
self.p2 = p2
self.p3 = p3
self.p4 = p4
}
/// The path vectore whose each path are equals to zero.
public static let zero: DynamicButtonPathVector = DynamicButtonPathVector(p1: CGMutablePath(), p2: CGMutablePath(), p3: CGMutablePath(), p4: CGMutablePath())
}
| mit | 6a0c82e752b858dee37448d3f69eb6bb | 34.2 | 159 | 0.722107 | 4.084388 | false | false | false | false |
serluca/luhn | Sources/Luhn.swift | 1 | 3358 | // Luhn.swift
//
// Copyright (c) 2016 Luca Serpico
//
// 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
/**
A base-independent implementation of the Luhn algorithm for Swift. Useful for generating and verifying check digits in arbitrary bases. https://github.com/serluca/luhn
*/
public class Luhn{
private static func luhn(string: String, alphabet: String) throws -> Int {
let base: Int = alphabet.characters.count
let reversedInts = try string.characters.reversed().map { try alphabet.index(of: $0) }
return reversedInts.enumerated().reduce(0, {(sum, val) in
let odd = val.offset % 2 == 1
return sum + (odd ? ((val.element / (base/2)) + ((2*val.element) % base)) : val.element)
}) % base
}
/**
Calculates the Luhn check character for the given input string. This
character should be appended to the input string to produce a valid Luhn
string in the given base.
@param baseString Consectetur adipisicing elit.
@param alphabet The alphabet to use, by default it uses the decimal alphabet
@return The character to append to the baseString to have a valid Luhn string in the given base
*/
public static func generate(baseString: String, alphabet: String = "0123456789") throws -> Character {
var d = try luhn(string: baseString + String(alphabet.character(at: 0)), alphabet: alphabet)
if d != 0 {
d = alphabet.characters.count - d
}
return alphabet.character(at: d)
}
/**
Verifies that the given string is a valid Luhn string in the given alphabet.
@param string The string to verify
@param alphabet The alphabet to use, by default it uses the decimal alphabet
@return A boolean value that indicates wheter or not the string is a valid Lunh string in the given alphabet
*/
public static func verify(string: String, alphabet: String = "0123456789") throws -> Bool {
return try luhn(string: string, alphabet: alphabet) == 0
}
}
extension String{
func character(at index: Int) -> Character {
return self[self.index(self.startIndex, offsetBy: index)]
}
func index(of character: Character) throws -> Int {
let range: Range<String.Index>? = self.range(of: String(character))
if let startingIndex = range?.lowerBound {
return self.distance(from: self.startIndex, to: startingIndex)
}
throw LuhnError.characterNotFound(character, self)
}
}
| mit | c9d2914253ba403c7d6ace45746a55e0 | 38.97619 | 167 | 0.737939 | 3.983393 | false | false | false | false |
BellAppLab/JustTest | JustTest/JustTest/Serialising.swift | 1 | 3112 | //
// Serialising.swift
// JustTest
//
// Created by André Abou Chami Campana on 06/04/2016.
// Copyright © 2016 Bell App Lab. All rights reserved.
//
import Foundation
/*
Source: https://github.com/Alamofire/Alamofire
*/
//MARK: Objects
public protocol ResponseObjectSerializable {
init?(response: NSHTTPURLResponse, representation: AnyObject)
}
extension Request {
public func responseObject<T: ResponseObjectSerializable>(completionHandler: Response<T, NSError> -> Void) -> Self {
let responseSerializer = ResponseSerializer<T, NSError> { request, response, data, error in
guard error == nil else { return .Failure(error!) }
let JSONResponseSerializer = Request.JSONResponseSerializer(options: .AllowFragments)
let result = JSONResponseSerializer.serializeResponse(request, response, data, error)
switch result {
case .Success(let value):
if let
response = response,
responseObject = T(response: response, representation: value)
{
return .Success(responseObject)
} else {
let failureReason = "JSON could not be serialized into response object: \(value)"
let error = Error.errorWithCode(.JSONSerializationFailed, failureReason: failureReason)
return .Failure(error)
}
case .Failure(let error):
return .Failure(error)
}
}
return response(responseSerializer: responseSerializer, completionHandler: completionHandler)
}
}
//MARK: Collections
public protocol ResponseCollectionSerializable {
static func collection(response response: NSHTTPURLResponse, representation: AnyObject) -> [Self]
}
extension Request {
public func responseCollection<T: ResponseCollectionSerializable>(completionHandler: Response<[T], NSError> -> Void) -> Self {
let responseSerializer = ResponseSerializer<[T], NSError> { request, response, data, error in
guard error == nil else { return .Failure(error!) }
let JSONSerializer = Request.JSONResponseSerializer(options: .AllowFragments)
let result = JSONSerializer.serializeResponse(request, response, data, error)
switch result {
case .Success(let value):
if let response = response {
return .Success(T.collection(response: response, representation: value))
} else {
let failureReason = "Response collection could not be serialized due to nil response"
let error = Error.errorWithCode(.JSONSerializationFailed, failureReason: failureReason)
return .Failure(error)
}
case .Failure(let error):
return .Failure(error)
}
}
return response(responseSerializer: responseSerializer, completionHandler: completionHandler)
}
}
| mit | 6d8a338f4e2227ea2667efa526be7799 | 37.875 | 130 | 0.619614 | 5.675182 | false | false | false | false |
kyle8998/Practice-Coding-Questions | leetcode/9-Easy-Palindrome-Number/answer.swift | 1 | 569 | class Solution {
func isPalindrome(_ x: Int) -> Bool {
// If x is negative
if x < 0 {
return false
}
var digits = abs(x)
// Creates a new number to fill in
var result = 0
// Loop through for the amount of digits there are
while digits > 0 {
// Create the resulting number in reverse of x
result = result * 10 + digits % 10
digits = digits / 10
}
// if result is equal to x, it is a palindrome
return (result == abs(x))
}
}
| unlicense | 6deda2587ac81b4741b899bf93021de0 | 26.095238 | 58 | 0.500879 | 4.552 | false | false | false | false |
cmoulton/grokRouterAndStrongTypes | grok101/ViewController.swift | 1 | 1702 | //
// ViewController.swift
// grok101
//
// Created by Christina Moulton on 2015-10-20.
// Copyright © 2015 Teak Mobile Inc. 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 viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
// MARK: Get Post #1
/*Post.postByID(1, completionHandler: { result in
if let error = result.error {
// got an error in getting the data, need to handle it
print("error calling POST on /posts")
print(error)
return
}
guard let post = result.value else {
print("error calling POST on /posts: result is nil")
return
}
// success!
print(post.description())
print(post.title)
})*/
// MARK: POST
// Create new post
guard let newPost = Post(aTitle: "Frist Psot", aBody: "I iz fisrt", anId: nil, aUserId: 1) else {
print("error: newPost isn't a Post")
return
}
newPost.save { result in
if let error = result.error {
// got an error in getting the data, need to handle it
print("error calling POST on /posts")
print(error)
return
}
guard let post = result.value else {
print("error calling POST on /posts: result is nil")
return
}
// success!
print(post.description())
print(post.title)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| mit | 2c6c3f744d3ba54b9a9e46f34b1fed9c | 24.014706 | 101 | 0.609053 | 4.179361 | false | false | false | false |
christophhagen/Signal-iOS | Signal/src/call/CallService.swift | 1 | 74899 | //
// Copyright (c) 2017 Open Whisper Systems. All rights reserved.
//
import Foundation
import PromiseKit
import WebRTC
import SignalServiceKit
import SignalMessaging
/**
* `CallService` is a global singleton that manages the state of WebRTC-backed Signal Calls
* (as opposed to legacy "RedPhone Calls").
*
* It serves as a connection between the `CallUIAdapter` and the `PeerConnectionClient`.
*
* ## Signaling
*
* Signaling refers to the setup and tear down of the connection. Before the connection is established, this must happen
* out of band (using Signal Service), but once the connection is established it's possible to publish updates
* (like hangup) via the established channel.
*
* Signaling state is synchronized on the main thread and only mutated in the handleXXX family of methods.
*
* Following is a high level process of the exchange of messages that takes place during call signaling.
*
* ### Key
*
* --[SOMETHING]--> represents a message of type "Something" sent from the caller to the callee
* <--[SOMETHING]-- represents a message of type "Something" sent from the callee to the caller
* SS: Message sent via Signal Service
* DC: Message sent via WebRTC Data Channel
*
* ### Message Exchange / State Flow Overview
*
* | Caller | Callee |
* +----------------------------+-------------------------+
* Start outgoing call: `handleOutgoingCall`...
--[SS.CallOffer]-->
* ...and start generating ICE updates.
* As ICE candidates are generated, `handleLocalAddedIceCandidate` is called.
* and we *store* the ICE updates for later.
*
* Received call offer: `handleReceivedOffer`
* Send call answer
* <--[SS.CallAnswer]--
* Start generating ICE updates.
* As they are generated `handleLocalAddedIceCandidate` is called
which immediately sends the ICE updates to the Caller.
* <--[SS.ICEUpdate]-- (sent multiple times)
*
* Received CallAnswer: `handleReceivedAnswer`
* So send any stored ice updates (and send future ones immediately)
* --[SS.ICEUpdates]-->
*
* Once compatible ICE updates have been exchanged...
* both parties: `handleIceConnected`
*
* Show remote ringing UI
* Connect to offered Data Channel
* Show incoming call UI.
*
* If callee answers Call
* send connected message
* <--[DC.ConnectedMesage]--
* Received connected message
* Show Call is connected.
*
* Hang up (this could equally be sent by the Callee)
* --[DC.Hangup]-->
* --[SS.Hangup]-->
*/
enum CallError: Error {
case providerReset
case assertionError(description: String)
case disconnected
case externalError(underlyingError: Error)
case timeout(description: String)
case obsoleteCall(description: String)
}
// Should be roughly synced with Android client for consistency
private let connectingTimeoutSeconds: TimeInterval = 120
// All Observer methods will be invoked from the main thread.
protocol CallServiceObserver: class {
/**
* Fired whenever the call changes.
*/
func didUpdateCall(call: SignalCall?)
/**
* Fired whenever the local or remote video track become active or inactive.
*/
func didUpdateVideoTracks(call: SignalCall?,
localVideoTrack: RTCVideoTrack?,
remoteVideoTrack: RTCVideoTrack?)
}
// This class' state should only be accessed on the main queue.
@objc class CallService: NSObject, CallObserver, PeerConnectionClientDelegate {
// MARK: - Properties
var observers = [Weak<CallServiceObserver>]()
// MARK: Dependencies
private let accountManager: AccountManager
private let messageSender: MessageSender
private let contactsManager: OWSContactsManager
private let storageManager: TSStorageManager
// Exposed by environment.m
internal let notificationsAdapter: CallNotificationsAdapter
internal var callUIAdapter: CallUIAdapter!
// MARK: Class
static let fallbackIceServer = RTCIceServer(urlStrings: ["stun:stun1.l.google.com:19302"])
// MARK: Ivars
var peerConnectionClient: PeerConnectionClient? {
didSet {
AssertIsOnMainThread()
Logger.debug("\(self.logTag) .peerConnectionClient setter: \(oldValue != nil) -> \(peerConnectionClient != nil) \(String(describing: peerConnectionClient))")
}
}
var call: SignalCall? {
didSet {
AssertIsOnMainThread()
oldValue?.removeObserver(self)
call?.addObserverAndSyncState(observer: self)
updateIsVideoEnabled()
// Prevent device from sleeping while we have an active call.
if oldValue != call {
if let oldValue = oldValue {
DeviceSleepManager.sharedInstance.removeBlock(blockObject: oldValue)
}
stopAnyCallTimer()
if let call = call {
DeviceSleepManager.sharedInstance.addBlock(blockObject: call)
self.startCallTimer()
}
}
Logger.debug("\(self.logTag) .call setter: \(oldValue?.identifiersForLogs as Optional) -> \(call?.identifiersForLogs as Optional)")
for observer in observers {
observer.value?.didUpdateCall(call: call)
}
}
}
// Used to coordinate promises across delegate methods
private var fulfillCallConnectedPromise: (() -> Void)?
private var rejectCallConnectedPromise: ((Error) -> Void)?
/**
* In the process of establishing a connection between the clients (ICE process) we must exchange ICE updates.
* Because this happens via Signal Service it's possible the callee user has not accepted any change in the caller's
* identity. In which case *each* ICE update would cause an "identity change" warning on the callee's device. Since
* this could be several messages, the caller stores all ICE updates until receiving positive confirmation that the
* callee has received a message from us. This positive confirmation comes in the form of the callees `CallAnswer`
* message.
*/
var sendIceUpdatesImmediately = true
var pendingIceUpdateMessages = [OWSCallIceUpdateMessage]()
// Used by waitForPeerConnectionClient to make sure any received
// ICE messages wait until the peer connection client is set up.
private var fulfillPeerConnectionClientPromise: (() -> Void)?
private var rejectPeerConnectionClientPromise: ((Error) -> Void)?
private var peerConnectionClientPromise: Promise<Void>?
// Used by waituntilReadyToSendIceUpdates to make sure CallOffer was
// sent before sending any ICE updates.
private var fulfillReadyToSendIceUpdatesPromise: (() -> Void)?
private var rejectReadyToSendIceUpdatesPromise: ((Error) -> Void)?
private var readyToSendIceUpdatesPromise: Promise<Void>?
weak var localVideoTrack: RTCVideoTrack? {
didSet {
AssertIsOnMainThread()
Logger.info("\(self.logTag) \(#function)")
fireDidUpdateVideoTracks()
}
}
weak var remoteVideoTrack: RTCVideoTrack? {
didSet {
AssertIsOnMainThread()
Logger.info("\(self.logTag) \(#function)")
fireDidUpdateVideoTracks()
}
}
var isRemoteVideoEnabled = false {
didSet {
AssertIsOnMainThread()
Logger.info("\(self.logTag) \(#function): \(isRemoteVideoEnabled)")
fireDidUpdateVideoTracks()
}
}
required init(accountManager: AccountManager, contactsManager: OWSContactsManager, messageSender: MessageSender, notificationsAdapter: CallNotificationsAdapter) {
self.accountManager = accountManager
self.contactsManager = contactsManager
self.messageSender = messageSender
self.notificationsAdapter = notificationsAdapter
self.storageManager = TSStorageManager.shared()
super.init()
SwiftSingletons.register(self)
self.createCallUIAdapter()
NotificationCenter.default.addObserver(self,
selector: #selector(didEnterBackground),
name: NSNotification.Name.UIApplicationDidEnterBackground,
object: nil)
NotificationCenter.default.addObserver(self,
selector: #selector(didBecomeActive),
name: NSNotification.Name.UIApplicationDidBecomeActive,
object: nil)
}
deinit {
NotificationCenter.default.removeObserver(self)
}
func didEnterBackground() {
AssertIsOnMainThread()
self.updateIsVideoEnabled()
}
func didBecomeActive() {
AssertIsOnMainThread()
self.updateIsVideoEnabled()
}
/**
* Choose whether to use CallKit or a Notification backed interface for calling.
*/
public func createCallUIAdapter() {
AssertIsOnMainThread()
if self.call != nil {
Logger.warn("\(self.logTag) ending current call in \(#function). Did user toggle callkit preference while in a call?")
self.terminateCall()
}
self.callUIAdapter = CallUIAdapter(callService: self, contactsManager: self.contactsManager, notificationsAdapter: self.notificationsAdapter)
}
// MARK: - Service Actions
/**
* Initiate an outgoing call.
*/
public func handleOutgoingCall(_ call: SignalCall) -> Promise<Void> {
AssertIsOnMainThread()
guard self.call == nil else {
let errorDescription = "\(self.logTag) call was unexpectedly already set."
Logger.error(errorDescription)
call.state = .localFailure
OWSProdError(OWSAnalyticsEvents.callServiceCallAlreadySet(), file: #file, function: #function, line: #line)
return Promise(error: CallError.assertionError(description: errorDescription))
}
self.call = call
sendIceUpdatesImmediately = false
pendingIceUpdateMessages = []
let callRecord = TSCall(timestamp: NSDate.ows_millisecondTimeStamp(), withCallNumber: call.remotePhoneNumber, callType: RPRecentCallTypeOutgoingIncomplete, in: call.thread)
callRecord.save()
call.callRecord = callRecord
let promise = getIceServers().then { iceServers -> Promise<HardenedRTCSessionDescription> in
Logger.debug("\(self.logTag) got ice servers:\(iceServers) for call: \(call.identifiersForLogs)")
guard self.call == call else {
throw CallError.obsoleteCall(description: "obsolete call in \(#function)")
}
guard self.peerConnectionClient == nil else {
let errorDescription = "\(self.logTag) peerconnection was unexpectedly already set."
Logger.error(errorDescription)
OWSProdError(OWSAnalyticsEvents.callServicePeerConnectionAlreadySet(), file: #file, function: #function, line: #line)
throw CallError.assertionError(description: errorDescription)
}
let useTurnOnly = Environment.current().preferences.doCallsHideIPAddress()
let peerConnectionClient = PeerConnectionClient(iceServers: iceServers, delegate: self, callDirection: .outgoing, useTurnOnly: useTurnOnly)
Logger.debug("\(self.logTag) setting peerConnectionClient in \(#function) for call: \(call.identifiersForLogs)")
self.peerConnectionClient = peerConnectionClient
self.fulfillPeerConnectionClientPromise?()
return peerConnectionClient.createOffer()
}.then { (sessionDescription: HardenedRTCSessionDescription) -> Promise<Void> in
guard self.call == call else {
throw CallError.obsoleteCall(description: "obsolete call in \(#function)")
}
guard let peerConnectionClient = self.peerConnectionClient else {
owsFail("Missing peerConnectionClient in \(#function)")
throw CallError.obsoleteCall(description: "Missing peerConnectionClient in \(#function)")
}
return peerConnectionClient.setLocalSessionDescription(sessionDescription).then {
let offerMessage = OWSCallOfferMessage(callId: call.signalingId, sessionDescription: sessionDescription.sdp)
let callMessage = OWSOutgoingCallMessage(thread: call.thread, offerMessage: offerMessage)
return self.messageSender.sendPromise(message: callMessage)
}
}.then {
guard self.call == call else {
throw CallError.obsoleteCall(description: "obsolete call in \(#function)")
}
// For outgoing calls, wait until call offer is sent before we send any ICE updates, to ensure message ordering for
// clients that don't support receiving ICE updates before receiving the call offer.
self.readyToSendIceUpdates(call: call)
let (callConnectedPromise, fulfill, reject) = Promise<Void>.pending()
self.fulfillCallConnectedPromise = fulfill
self.rejectCallConnectedPromise = reject
// Don't let the outgoing call ring forever. We don't support inbound ringing forever anyway.
let timeout: Promise<Void> = after(interval: connectingTimeoutSeconds).then { () -> Void in
// rejecting a promise by throwing is safely a no-op if the promise has already been fulfilled
OWSProdInfo(OWSAnalyticsEvents.callServiceErrorTimeoutWhileConnectingOutgoing(), file: #file, function: #function, line: #line)
throw CallError.timeout(description: "timed out waiting to receive call answer")
}
return race(timeout, callConnectedPromise)
}.then {
Logger.info(self.call == call
? "\(self.logTag) outgoing call connected: \(call.identifiersForLogs)."
: "\(self.logTag) obsolete outgoing call connected: \(call.identifiersForLogs).")
}.catch { error in
Logger.error("\(self.logTag) placing call \(call.identifiersForLogs) failed with error: \(error)")
if let callError = error as? CallError {
OWSProdInfo(OWSAnalyticsEvents.callServiceErrorOutgoingConnectionFailedInternal(), file: #file, function: #function, line: #line)
self.handleFailedCall(failedCall: call, error: callError)
} else {
OWSProdInfo(OWSAnalyticsEvents.callServiceErrorOutgoingConnectionFailedExternal(), file: #file, function: #function, line: #line)
let externalError = CallError.externalError(underlyingError: error)
self.handleFailedCall(failedCall: call, error: externalError)
}
}
promise.retainUntilComplete()
return promise
}
func readyToSendIceUpdates(call: SignalCall) {
AssertIsOnMainThread()
guard self.call == call else {
self.handleFailedCall(failedCall: call, error: .obsoleteCall(description:"obsolete call in \(#function)"))
return
}
if self.fulfillReadyToSendIceUpdatesPromise == nil {
createReadyToSendIceUpdatesPromise()
}
guard let fulfillReadyToSendIceUpdatesPromise = self.fulfillReadyToSendIceUpdatesPromise else {
OWSProdError(OWSAnalyticsEvents.callServiceMissingFulfillReadyToSendIceUpdatesPromise(), file: #file, function: #function, line: #line)
self.handleFailedCall(failedCall: call, error: CallError.assertionError(description: "failed to create fulfillReadyToSendIceUpdatesPromise"))
return
}
fulfillReadyToSendIceUpdatesPromise()
}
/**
* Called by the call initiator after receiving a CallAnswer from the callee.
*/
public func handleReceivedAnswer(thread: TSContactThread, callId: UInt64, sessionDescription: String) {
Logger.info("\(self.logTag) received call answer for call: \(callId) thread: \(thread.contactIdentifier())")
AssertIsOnMainThread()
guard let call = self.call else {
Logger.warn("\(self.logTag) ignoring obsolete call: \(callId) in \(#function)")
return
}
guard call.signalingId == callId else {
Logger.warn("\(self.logTag) ignoring mismatched call: \(callId) currentCall: \(call.signalingId) in \(#function)")
return
}
// Now that we know the recipient trusts our identity, we no longer need to enqueue ICE updates.
self.sendIceUpdatesImmediately = true
if pendingIceUpdateMessages.count > 0 {
Logger.error("\(self.logTag) Sending \(pendingIceUpdateMessages.count) pendingIceUpdateMessages")
let callMessage = OWSOutgoingCallMessage(thread: thread, iceUpdateMessages: pendingIceUpdateMessages)
let sendPromise = messageSender.sendPromise(message: callMessage).catch { error in
Logger.error("\(self.logTag) failed to send ice updates in \(#function) with error: \(error)")
}
sendPromise.retainUntilComplete()
}
guard let peerConnectionClient = self.peerConnectionClient else {
OWSProdError(OWSAnalyticsEvents.callServicePeerConnectionMissing(), file: #file, function: #function, line: #line)
handleFailedCall(failedCall: call, error: CallError.assertionError(description: "peerConnectionClient was unexpectedly nil in \(#function)"))
return
}
let sessionDescription = RTCSessionDescription(type: .answer, sdp: sessionDescription)
let setDescriptionPromise = peerConnectionClient.setRemoteSessionDescription(sessionDescription).then {
Logger.debug("\(self.logTag) successfully set remote description")
}.catch { error in
if let callError = error as? CallError {
OWSProdInfo(OWSAnalyticsEvents.callServiceErrorHandleReceivedErrorInternal(), file: #file, function: #function, line: #line)
self.handleFailedCall(failedCall: call, error: callError)
} else {
OWSProdInfo(OWSAnalyticsEvents.callServiceErrorHandleReceivedErrorExternal(), file: #file, function: #function, line: #line)
let externalError = CallError.externalError(underlyingError: error)
self.handleFailedCall(failedCall: call, error: externalError)
}
}
setDescriptionPromise.retainUntilComplete()
}
/**
* User didn't answer incoming call
*/
public func handleMissedCall(_ call: SignalCall) {
AssertIsOnMainThread()
// Insert missed call record
if let callRecord = call.callRecord {
if callRecord.callType == RPRecentCallTypeIncoming {
callRecord.updateCallType(RPRecentCallTypeMissed)
}
} else {
call.callRecord = TSCall(timestamp: NSDate.ows_millisecondTimeStamp(),
withCallNumber: call.thread.contactIdentifier(),
callType: RPRecentCallTypeMissed,
in: call.thread)
}
assert(call.callRecord != nil)
call.callRecord?.save()
self.callUIAdapter.reportMissedCall(call)
}
/**
* Received a call while already in another call.
*/
private func handleLocalBusyCall(_ call: SignalCall) {
Logger.info("\(self.logTag) \(#function) for call: \(call.identifiersForLogs) thread: \(call.thread.contactIdentifier())")
AssertIsOnMainThread()
let busyMessage = OWSCallBusyMessage(callId: call.signalingId)
let callMessage = OWSOutgoingCallMessage(thread: call.thread, busyMessage: busyMessage)
let sendPromise = messageSender.sendPromise(message: callMessage)
sendPromise.retainUntilComplete()
handleMissedCall(call)
}
/**
* The callee was already in another call.
*/
public func handleRemoteBusy(thread: TSContactThread, callId: UInt64) {
Logger.info("\(self.logTag) \(#function) for thread: \(thread.contactIdentifier())")
AssertIsOnMainThread()
guard let call = self.call else {
Logger.warn("\(self.logTag) ignoring obsolete call: \(callId) in \(#function)")
return
}
guard call.signalingId == callId else {
Logger.warn("\(self.logTag) ignoring mismatched call: \(callId) currentCall: \(call.signalingId) in \(#function)")
return
}
guard thread.contactIdentifier() == call.remotePhoneNumber else {
Logger.warn("\(self.logTag) ignoring obsolete call in \(#function)")
return
}
call.state = .remoteBusy
callUIAdapter.remoteBusy(call)
terminateCall()
}
/**
* Received an incoming call offer. We still have to complete setting up the Signaling channel before we notify
* the user of an incoming call.
*/
public func handleReceivedOffer(thread: TSContactThread, callId: UInt64, sessionDescription callerSessionDescription: String) {
AssertIsOnMainThread()
let newCall = SignalCall.incomingCall(localId: UUID(), remotePhoneNumber: thread.contactIdentifier(), signalingId: callId)
Logger.info("\(self.logTag) receivedCallOffer: \(newCall.identifiersForLogs)")
let untrustedIdentity = OWSIdentityManager.shared().untrustedIdentityForSending(toRecipientId: thread.contactIdentifier())
guard untrustedIdentity == nil else {
Logger.warn("\(self.logTag) missed a call due to untrusted identity: \(newCall.identifiersForLogs)")
let callerName = self.contactsManager.displayName(forPhoneIdentifier: thread.contactIdentifier())
switch untrustedIdentity!.verificationState {
case .verified:
owsFail("\(self.logTag) shouldn't have missed a call due to untrusted identity if the identity is verified")
self.notificationsAdapter.presentMissedCall(newCall, callerName: callerName)
case .default:
self.notificationsAdapter.presentMissedCallBecauseOfNewIdentity(call: newCall, callerName: callerName)
case .noLongerVerified:
self.notificationsAdapter.presentMissedCallBecauseOfNoLongerVerifiedIdentity(call: newCall, callerName: callerName)
}
let callRecord = TSCall(timestamp: NSDate.ows_millisecondTimeStamp(),
withCallNumber: thread.contactIdentifier(),
callType: RPRecentCallTypeMissedBecauseOfChangedIdentity,
in: thread)
assert(newCall.callRecord == nil)
newCall.callRecord = callRecord
callRecord.save()
terminateCall()
return
}
guard self.call == nil else {
let existingCall = self.call!
// TODO on iOS10+ we can use CallKit to swap calls rather than just returning busy immediately.
Logger.info("\(self.logTag) receivedCallOffer: \(newCall.identifiersForLogs) but we're already in call: \(existingCall.identifiersForLogs)")
handleLocalBusyCall(newCall)
if existingCall.remotePhoneNumber == newCall.remotePhoneNumber {
Logger.info("\(self.logTag) handling call from current call user as remote busy.: \(newCall.identifiersForLogs) but we're already in call: \(existingCall.identifiersForLogs)")
// If we're receiving a new call offer from the user we already think we have a call with,
// terminate our current call to get back to a known good state. If they call back, we'll
// be ready.
//
// TODO: Auto-accept this incoming call if our current call was either a) outgoing or
// b) never connected. There will be a bit of complexity around making sure that two
// parties that call each other at the same time end up connected.
switch existingCall.state {
case .idle, .dialing, .remoteRinging:
// If both users are trying to call each other at the same time,
// both should see busy.
handleRemoteBusy(thread: existingCall.thread, callId: existingCall.signalingId)
case .answering, .localRinging, .connected, .localFailure, .localHangup, .remoteHangup, .remoteBusy:
// If one user calls another while the other has a "vestigial" call with
// that same user, fail the old call.
terminateCall()
}
}
return
}
Logger.info("\(self.logTag) starting new call: \(newCall.identifiersForLogs)")
self.call = newCall
var backgroundTask = OWSBackgroundTask(label:"\(#function)", completionBlock: { [weak self] _ in
AssertIsOnMainThread()
guard let strongSelf = self else {
return
}
let timeout = CallError.timeout(description: "background task time ran out before call connected.")
guard strongSelf.call == newCall else {
Logger.warn("\(strongSelf.logTag) ignoring obsolete call in \(#function)")
return
}
strongSelf.handleFailedCall(failedCall: newCall, error: timeout)
})
let incomingCallPromise = firstly {
return getIceServers()
}.then { (iceServers: [RTCIceServer]) -> Promise<HardenedRTCSessionDescription> in
// FIXME for first time call recipients I think we'll see mic/camera permission requests here,
// even though, from the users perspective, no incoming call is yet visible.
guard self.call == newCall else {
throw CallError.obsoleteCall(description: "getIceServers() response for obsolete call")
}
assert(self.peerConnectionClient == nil, "Unexpected PeerConnectionClient instance")
// For contacts not stored in our system contacts, we assume they are an unknown caller, and we force
// a TURN connection, so as not to reveal any connectivity information (IP/port) to the caller.
let unknownCaller = self.contactsManager.signalAccount(forRecipientId: thread.contactIdentifier()) == nil
let useTurnOnly = unknownCaller || Environment.current().preferences.doCallsHideIPAddress()
Logger.debug("\(self.logTag) setting peerConnectionClient in \(#function) for: \(newCall.identifiersForLogs)")
let peerConnectionClient = PeerConnectionClient(iceServers: iceServers, delegate: self, callDirection: .incoming, useTurnOnly: useTurnOnly)
self.peerConnectionClient = peerConnectionClient
self.fulfillPeerConnectionClientPromise?()
let offerSessionDescription = RTCSessionDescription(type: .offer, sdp: callerSessionDescription)
let constraints = RTCMediaConstraints(mandatoryConstraints: nil, optionalConstraints: nil)
// Find a sessionDescription compatible with my constraints and the remote sessionDescription
return peerConnectionClient.negotiateSessionDescription(remoteDescription: offerSessionDescription, constraints: constraints)
}.then { (negotiatedSessionDescription: HardenedRTCSessionDescription) in
Logger.debug("\(self.logTag) set the remote description for: \(newCall.identifiersForLogs)")
guard self.call == newCall else {
throw CallError.obsoleteCall(description: "negotiateSessionDescription() response for obsolete call")
}
let answerMessage = OWSCallAnswerMessage(callId: newCall.signalingId, sessionDescription: negotiatedSessionDescription.sdp)
let callAnswerMessage = OWSOutgoingCallMessage(thread: thread, answerMessage: answerMessage)
return self.messageSender.sendPromise(message: callAnswerMessage)
}.then {
guard self.call == newCall else {
throw CallError.obsoleteCall(description: "sendPromise(message: ) response for obsolete call")
}
Logger.debug("\(self.logTag) successfully sent callAnswerMessage for: \(newCall.identifiersForLogs)")
// There's nothing technically forbidding receiving ICE updates before receiving the CallAnswer, but this
// a more intuitive ordering.
self.readyToSendIceUpdates(call: newCall)
let (promise, fulfill, reject) = Promise<Void>.pending()
let timeout: Promise<Void> = after(interval: connectingTimeoutSeconds).then { () -> Void in
// rejecting a promise by throwing is safely a no-op if the promise has already been fulfilled
OWSProdInfo(OWSAnalyticsEvents.callServiceErrorTimeoutWhileConnectingIncoming(), file: #file, function: #function, line: #line)
throw CallError.timeout(description: "timed out waiting for call to connect")
}
// This will be fulfilled (potentially) by the RTCDataChannel delegate method
self.fulfillCallConnectedPromise = fulfill
self.rejectCallConnectedPromise = reject
return race(promise, timeout)
}.then {
Logger.info(self.call == newCall
? "\(self.logTag) incoming call connected: \(newCall.identifiersForLogs)."
: "\(self.logTag) obsolete incoming call connected: \(newCall.identifiersForLogs).")
}.catch { error in
guard self.call == newCall else {
Logger.debug("\(self.logTag) ignoring error: \(error) for obsolete call: \(newCall.identifiersForLogs).")
return
}
if let callError = error as? CallError {
OWSProdInfo(OWSAnalyticsEvents.callServiceErrorIncomingConnectionFailedInternal(), file: #file, function: #function, line: #line)
self.handleFailedCall(failedCall: newCall, error: callError)
} else {
OWSProdInfo(OWSAnalyticsEvents.callServiceErrorIncomingConnectionFailedExternal(), file: #file, function: #function, line: #line)
let externalError = CallError.externalError(underlyingError: error)
self.handleFailedCall(failedCall: newCall, error: externalError)
}
}.always {
Logger.debug("\(self.logTag) ending background task awaiting inbound call connection")
backgroundTask = nil
}
incomingCallPromise.retainUntilComplete()
}
/**
* Remote client (could be caller or callee) sent us a connectivity update
*/
public func handleRemoteAddedIceCandidate(thread: TSContactThread, callId: UInt64, sdp: String, lineIndex: Int32, mid: String) {
waitForPeerConnectionClient().then { () -> Void in
AssertIsOnMainThread()
guard let call = self.call else {
Logger.warn("ignoring remote ice update for thread: \(thread.uniqueId) since there is no current call. Call already ended?")
return
}
guard call.signalingId == callId else {
Logger.warn("\(self.logTag) ignoring mismatched call: \(callId) currentCall: \(call.signalingId) in \(#function)")
return
}
guard thread.contactIdentifier() == call.thread.contactIdentifier() else {
Logger.warn("ignoring remote ice update for thread: \(thread.uniqueId) due to thread mismatch. Call already ended?")
return
}
guard let peerConnectionClient = self.peerConnectionClient else {
Logger.warn("ignoring remote ice update for thread: \(thread.uniqueId) since there is no current peerConnectionClient. Call already ended?")
return
}
peerConnectionClient.addRemoteIceCandidate(RTCIceCandidate(sdp: sdp, sdpMLineIndex: lineIndex, sdpMid: mid))
}.catch { error in
OWSProdInfo(OWSAnalyticsEvents.callServiceErrorHandleRemoteAddedIceCandidate(), file: #file, function: #function, line: #line)
Logger.error("\(self.logTag) in \(#function) waitForPeerConnectionClient failed with error: \(error)")
}.retainUntilComplete()
}
/**
* Local client (could be caller or callee) generated some connectivity information that we should send to the
* remote client.
*/
private func handleLocalAddedIceCandidate(_ iceCandidate: RTCIceCandidate) {
AssertIsOnMainThread()
guard let call = self.call else {
OWSProdError(OWSAnalyticsEvents.callServiceCallMissing(), file: #file, function: #function, line: #line)
self.handleFailedCurrentCall(error: CallError.assertionError(description: "ignoring local ice candidate, since there is no current call."))
return
}
// Wait until we've sent the CallOffer before sending any ice updates for the call to ensure
// intuitive message ordering for other clients.
waitUntilReadyToSendIceUpdates().then { () -> Void in
guard call == self.call else {
self.handleFailedCurrentCall(error: .obsoleteCall(description: "current call changed since we became ready to send ice updates"))
return
}
guard call.state != .idle else {
// This will only be called for the current peerConnectionClient, so
// fail the current call.
OWSProdError(OWSAnalyticsEvents.callServiceCallUnexpectedlyIdle(), file: #file, function: #function, line: #line)
self.handleFailedCurrentCall(error: CallError.assertionError(description: "ignoring local ice candidate, since call is now idle."))
return
}
let iceUpdateMessage = OWSCallIceUpdateMessage(callId: call.signalingId, sdp: iceCandidate.sdp, sdpMLineIndex: iceCandidate.sdpMLineIndex, sdpMid: iceCandidate.sdpMid)
if self.sendIceUpdatesImmediately {
Logger.info("\(self.logTag) in \(#function). Sending immediately.")
let callMessage = OWSOutgoingCallMessage(thread: call.thread, iceUpdateMessage: iceUpdateMessage)
let sendPromise = self.messageSender.sendPromise(message: callMessage)
sendPromise.retainUntilComplete()
} else {
// For outgoing messages, we wait to send ice updates until we're sure client received our call message.
// e.g. if the client has blocked our message due to an identity change, we'd otherwise
// bombard them with a bunch *more* undecipherable messages.
Logger.info("\(self.logTag) in \(#function). Enqueing for later.")
self.pendingIceUpdateMessages.append(iceUpdateMessage)
return
}
}.catch { error in
OWSProdInfo(OWSAnalyticsEvents.callServiceErrorHandleLocalAddedIceCandidate(), file: #file, function: #function, line: #line)
Logger.error("\(self.logTag) in \(#function) waitUntilReadyToSendIceUpdates failed with error: \(error)")
}.retainUntilComplete()
}
/**
* The clients can now communicate via WebRTC.
*
* Called by both caller and callee. Compatible ICE messages have been exchanged between the local and remote
* client.
*/
private func handleIceConnected() {
AssertIsOnMainThread()
guard let call = self.call else {
// This will only be called for the current peerConnectionClient, so
// fail the current call.
OWSProdError(OWSAnalyticsEvents.callServiceCallMissing(), file: #file, function: #function, line: #line)
handleFailedCurrentCall(error: CallError.assertionError(description: "\(self.logTag) ignoring \(#function) since there is no current call."))
return
}
Logger.info("\(self.logTag) in \(#function): \(call.identifiersForLogs).")
switch call.state {
case .dialing:
call.state = .remoteRinging
case .answering:
call.state = .localRinging
self.callUIAdapter.reportIncomingCall(call, thread: call.thread)
case .remoteRinging:
Logger.info("\(self.logTag) call already ringing. Ignoring \(#function): \(call.identifiersForLogs).")
case .connected:
Logger.info("\(self.logTag) Call reconnected \(#function): \(call.identifiersForLogs).")
default:
Logger.debug("\(self.logTag) unexpected call state for \(#function): \(call.state): \(call.identifiersForLogs).")
}
}
/**
* The remote client (caller or callee) ended the call.
*/
public func handleRemoteHangup(thread: TSContactThread, callId: UInt64) {
Logger.debug("\(self.logTag) in \(#function)")
AssertIsOnMainThread()
guard let call = self.call else {
// This may happen if we hang up slightly before they hang up.
handleFailedCurrentCall(error: .obsoleteCall(description:"\(self.logTag) call was unexpectedly nil in \(#function)"))
return
}
guard call.signalingId == callId else {
Logger.warn("\(self.logTag) ignoring mismatched call: \(callId) currentCall: \(call.signalingId) in \(#function)")
return
}
guard thread.contactIdentifier() == call.thread.contactIdentifier() else {
// This can safely be ignored.
// We don't want to fail the current call because an old call was slow to send us the hangup message.
Logger.warn("\(self.logTag) ignoring hangup for thread: \(thread.contactIdentifier()) which is not the current call: \(call.identifiersForLogs)")
return
}
Logger.info("\(self.logTag) in \(#function): \(call.identifiersForLogs).")
switch call.state {
case .idle, .dialing, .answering, .localRinging, .localFailure, .remoteBusy, .remoteRinging:
handleMissedCall(call)
case .connected, .localHangup, .remoteHangup:
Logger.info("\(self.logTag) call is finished.")
}
call.state = .remoteHangup
// Notify UI
callUIAdapter.remoteDidHangupCall(call)
// self.call is nil'd in `terminateCall`, so it's important we update it's state *before* calling `terminateCall`
terminateCall()
}
/**
* User chose to answer call referred to by call `localId`. Used by the Callee only.
*
* Used by notification actions which can't serialize a call object.
*/
public func handleAnswerCall(localId: UUID) {
AssertIsOnMainThread()
guard let call = self.call else {
// This should never happen; return to a known good state.
owsFail("\(self.logTag) call was unexpectedly nil in \(#function)")
OWSProdError(OWSAnalyticsEvents.callServiceCallMissing(), file: #file, function: #function, line: #line)
handleFailedCurrentCall(error: CallError.assertionError(description: "\(self.logTag) call was unexpectedly nil in \(#function)"))
return
}
guard call.localId == localId else {
// This should never happen; return to a known good state.
owsFail("\(self.logTag) callLocalId:\(localId) doesn't match current calls: \(call.localId)")
OWSProdError(OWSAnalyticsEvents.callServiceCallIdMismatch(), file: #file, function: #function, line: #line)
handleFailedCurrentCall(error: CallError.assertionError(description: "\(self.logTag) callLocalId:\(localId) doesn't match current calls: \(call.localId)"))
return
}
self.handleAnswerCall(call)
}
/**
* User chose to answer call referred to by call `localId`. Used by the Callee only.
*/
public func handleAnswerCall(_ call: SignalCall) {
AssertIsOnMainThread()
Logger.debug("\(self.logTag) in \(#function)")
guard let currentCall = self.call else {
OWSProdError(OWSAnalyticsEvents.callServiceCallMissing(), file: #file, function: #function, line: #line)
handleFailedCall(failedCall: call, error: CallError.assertionError(description: "\(self.logTag) ignoring \(#function) since there is no current call"))
return
}
guard call == currentCall else {
// This could conceivably happen if the other party of an old call was slow to send us their answer
// and we've subsequently engaged in another call. Don't kill the current call, but just ignore it.
Logger.warn("\(self.logTag) ignoring \(#function) for call other than current call")
return
}
guard let peerConnectionClient = self.peerConnectionClient else {
OWSProdError(OWSAnalyticsEvents.callServicePeerConnectionMissing(), file: #file, function: #function, line: #line)
handleFailedCall(failedCall: call, error: CallError.assertionError(description: "\(self.logTag) missing peerconnection client in \(#function)"))
return
}
Logger.info("\(self.logTag) in \(#function): \(call.identifiersForLogs).")
let callRecord = TSCall(timestamp: NSDate.ows_millisecondTimeStamp(), withCallNumber: call.remotePhoneNumber, callType: RPRecentCallTypeIncomingIncomplete, in: call.thread)
callRecord.save()
call.callRecord = callRecord
let message = DataChannelMessage.forConnected(callId: call.signalingId)
peerConnectionClient.sendDataChannelMessage(data: message.asData(), description: "connected", isCritical: true)
handleConnectedCall(call)
}
/**
* For outgoing call, when the callee has chosen to accept the call.
* For incoming call, when the local user has chosen to accept the call.
*/
func handleConnectedCall(_ call: SignalCall) {
Logger.info("\(self.logTag) in \(#function)")
AssertIsOnMainThread()
guard let peerConnectionClient = self.peerConnectionClient else {
OWSProdError(OWSAnalyticsEvents.callServicePeerConnectionMissing(), file: #file, function: #function, line: #line)
handleFailedCall(failedCall: call, error: CallError.assertionError(description: "\(self.logTag) peerConnectionClient unexpectedly nil in \(#function)"))
return
}
Logger.info("\(self.logTag) handleConnectedCall: \(call.identifiersForLogs).")
assert(self.fulfillCallConnectedPromise != nil)
// cancel connection timeout
self.fulfillCallConnectedPromise?()
call.state = .connected
// We don't risk transmitting any media until the remote client has admitted to being connected.
ensureAudioState(call: call, peerConnectionClient: peerConnectionClient)
peerConnectionClient.setLocalVideoEnabled(enabled: shouldHaveLocalVideoTrack())
}
/**
* Local user chose to decline the call vs. answering it.
*
* The call is referred to by call `localId`, which is included in Notification actions.
*
* Incoming call only.
*/
public func handleDeclineCall(localId: UUID) {
AssertIsOnMainThread()
guard let call = self.call else {
// This should never happen; return to a known good state.
owsFail("\(self.logTag) call was unexpectedly nil in \(#function)")
OWSProdError(OWSAnalyticsEvents.callServiceCallMissing(), file: #file, function: #function, line: #line)
handleFailedCurrentCall(error: CallError.assertionError(description: "\(self.logTag) call was unexpectedly nil in \(#function)"))
return
}
guard call.localId == localId else {
// This should never happen; return to a known good state.
owsFail("\(self.logTag) callLocalId:\(localId) doesn't match current calls: \(call.localId)")
OWSProdError(OWSAnalyticsEvents.callServiceCallIdMismatch(), file: #file, function: #function, line: #line)
handleFailedCurrentCall(error: CallError.assertionError(description: "\(self.logTag) callLocalId:\(localId) doesn't match current calls: \(call.localId)"))
return
}
self.handleDeclineCall(call)
}
/**
* Local user chose to decline the call vs. answering it.
*
* Incoming call only.
*/
public func handleDeclineCall(_ call: SignalCall) {
AssertIsOnMainThread()
Logger.info("\(self.logTag) in \(#function): \(call.identifiersForLogs).")
if let callRecord = call.callRecord {
owsFail("Not expecting callrecord to already be set")
callRecord.updateCallType(RPRecentCallTypeIncomingDeclined)
} else {
let callRecord = TSCall(timestamp: NSDate.ows_millisecondTimeStamp(), withCallNumber: call.remotePhoneNumber, callType: RPRecentCallTypeIncomingDeclined, in: call.thread)
callRecord.save()
call.callRecord = callRecord
}
// Currently we just handle this as a hangup. But we could offer more descriptive action. e.g. DataChannel message
handleLocalHungupCall(call)
}
/**
* Local user chose to end the call.
*
* Can be used for Incoming and Outgoing calls.
*/
func handleLocalHungupCall(_ call: SignalCall) {
AssertIsOnMainThread()
guard let currentCall = self.call else {
Logger.info("\(self.logTag) in \(#function), but no current call. Other party hung up just before us.")
// terminating the call might be redundant, but it shouldn't hurt.
terminateCall()
return
}
guard call == currentCall else {
OWSProdError(OWSAnalyticsEvents.callServiceCallMismatch(), file: #file, function: #function, line: #line)
handleFailedCall(failedCall: call, error: CallError.assertionError(description: "\(self.logTag) ignoring \(#function) for call other than current call"))
return
}
Logger.info("\(self.logTag) in \(#function): \(call.identifiersForLogs).")
call.state = .localHangup
// TODO something like this lifted from Signal-Android.
// this.accountManager.cancelInFlightRequests();
// this.messageSender.cancelInFlightRequests();
if let peerConnectionClient = self.peerConnectionClient {
// If the call is connected, we can send the hangup via the data channel for faster hangup.
let message = DataChannelMessage.forHangup(callId: call.signalingId)
peerConnectionClient.sendDataChannelMessage(data: message.asData(), description: "hangup", isCritical: true)
} else {
Logger.info("\(self.logTag) ending call before peer connection created. Device offline or quick hangup.")
}
// If the call hasn't started yet, we don't have a data channel to communicate the hang up. Use Signal Service Message.
let hangupMessage = OWSCallHangupMessage(callId: call.signalingId)
let callMessage = OWSOutgoingCallMessage(thread: call.thread, hangupMessage: hangupMessage)
let sendPromise = self.messageSender.sendPromise(message: callMessage).then {
Logger.debug("\(self.logTag) successfully sent hangup call message to \(call.thread.contactIdentifier())")
}.catch { error in
OWSProdInfo(OWSAnalyticsEvents.callServiceErrorHandleLocalHungupCall(), file: #file, function: #function, line: #line)
Logger.error("\(self.logTag) failed to send hangup call message to \(call.thread.contactIdentifier()) with error: \(error)")
}
sendPromise.retainUntilComplete()
terminateCall()
}
/**
* Local user toggled to mute audio.
*
* Can be used for Incoming and Outgoing calls.
*/
func setIsMuted(call: SignalCall, isMuted: Bool) {
AssertIsOnMainThread()
guard call == self.call else {
// This can happen after a call has ended. Reproducible on iOS11, when the other party ends the call.
Logger.info("\(self.logTag) ignoring mute request for obsolete call")
return
}
call.isMuted = isMuted
guard let peerConnectionClient = self.peerConnectionClient else {
// The peer connection might not be created yet.
return
}
ensureAudioState(call: call, peerConnectionClient: peerConnectionClient)
}
/**
* Local user toggled to hold call. Currently only possible via CallKit screen,
* e.g. when another Call comes in.
*/
func setIsOnHold(call: SignalCall, isOnHold: Bool) {
AssertIsOnMainThread()
guard call == self.call else {
Logger.info("\(self.logTag) ignoring held request for obsolete call")
return
}
call.isOnHold = isOnHold
guard let peerConnectionClient = self.peerConnectionClient else {
// The peer connection might not be created yet.
return
}
ensureAudioState(call: call, peerConnectionClient: peerConnectionClient)
}
func ensureAudioState(call: SignalCall, peerConnectionClient: PeerConnectionClient) {
guard call.state == .connected else {
peerConnectionClient.setAudioEnabled(enabled: false)
return
}
guard !call.isMuted else {
peerConnectionClient.setAudioEnabled(enabled: false)
return
}
guard !call.isOnHold else {
peerConnectionClient.setAudioEnabled(enabled: false)
return
}
peerConnectionClient.setAudioEnabled(enabled: true)
}
/**
* Local user toggled video.
*
* Can be used for Incoming and Outgoing calls.
*/
func setHasLocalVideo(hasLocalVideo: Bool) {
AssertIsOnMainThread()
guard let frontmostViewController = UIApplication.shared.frontmostViewController else {
owsFail("\(self.logTag) could not identify frontmostViewController in \(#function)")
return
}
frontmostViewController.ows_ask(forCameraPermissions: { [weak self] granted in
guard let strongSelf = self else {
return
}
if (granted) {
// Success callback; camera permissions are granted.
strongSelf.setHasLocalVideoWithCameraPermissions(hasLocalVideo: hasLocalVideo)
} else {
// Failed callback; camera permissions are _NOT_ granted.
// We don't need to worry about the user granting or remoting this permission
// during a call while the app is in the background, because changing this
// permission kills the app.
OWSAlerts.showAlert(withTitle: NSLocalizedString("MISSING_CAMERA_PERMISSION_TITLE", comment: "Alert title when camera is not authorized"),
message: NSLocalizedString("MISSING_CAMERA_PERMISSION_MESSAGE", comment: "Alert body when camera is not authorized"))
}
})
}
private func setHasLocalVideoWithCameraPermissions(hasLocalVideo: Bool) {
AssertIsOnMainThread()
guard let call = self.call else {
// This should never happen; return to a known good state.
owsFail("\(self.logTag) call was unexpectedly nil in \(#function)")
OWSProdError(OWSAnalyticsEvents.callServiceCallMissing(), file: #file, function: #function, line: #line)
handleFailedCurrentCall(error: CallError.assertionError(description: "\(self.logTag) call unexpectedly nil in \(#function)"))
return
}
call.hasLocalVideo = hasLocalVideo
guard let peerConnectionClient = self.peerConnectionClient else {
// The peer connection might not be created yet.
return
}
if call.state == .connected {
peerConnectionClient.setLocalVideoEnabled(enabled: shouldHaveLocalVideoTrack())
}
}
func handleCallKitStartVideo() {
AssertIsOnMainThread()
self.setHasLocalVideo(hasLocalVideo: true)
}
/**
* Local client received a message on the WebRTC data channel.
*
* The WebRTC data channel is a faster signaling channel than out of band Signal Service messages. Once it's
* established we use it to communicate further signaling information. The one sort-of exception is that with
* hangup messages we redundantly send a Signal Service hangup message, which is more reliable, and since the hangup
* action is idemptotent, there's no harm done.
*
* Used by both Incoming and Outgoing calls.
*/
private func handleDataChannelMessage(_ message: OWSWebRTCProtosData) {
AssertIsOnMainThread()
guard let call = self.call else {
// This should never happen; return to a known good state.
owsFail("\(self.logTag) received data message, but there is no current call. Ignoring.")
OWSProdError(OWSAnalyticsEvents.callServiceCallMissing(), file: #file, function: #function, line: #line)
handleFailedCurrentCall(error: CallError.assertionError(description: "\(self.logTag) received data message, but there is no current call. Ignoring."))
return
}
if message.hasConnected() {
Logger.debug("\(self.logTag) remote participant sent Connected via data channel: \(call.identifiersForLogs).")
let connected = message.connected!
guard connected.id == call.signalingId else {
// This should never happen; return to a known good state.
owsFail("\(self.logTag) received connected message for call with id:\(connected.id) but current call has id:\(call.signalingId)")
OWSProdError(OWSAnalyticsEvents.callServiceCallIdMismatch(), file: #file, function: #function, line: #line)
handleFailedCurrentCall(error: CallError.assertionError(description: "\(self.logTag) received connected message for call with id:\(connected.id) but current call has id:\(call.signalingId)"))
return
}
self.callUIAdapter.recipientAcceptedCall(call)
handleConnectedCall(call)
} else if message.hasHangup() {
Logger.debug("\(self.logTag) remote participant sent Hangup via data channel: \(call.identifiersForLogs).")
let hangup = message.hangup!
guard hangup.id == call.signalingId else {
// This should never happen; return to a known good state.
owsFail("\(self.logTag) received hangup message for call with id:\(hangup.id) but current call has id:\(call.signalingId)")
OWSProdError(OWSAnalyticsEvents.callServiceCallIdMismatch(), file: #file, function: #function, line: #line)
handleFailedCurrentCall(error: CallError.assertionError(description: "\(self.logTag) received hangup message for call with id:\(hangup.id) but current call has id:\(call.signalingId)"))
return
}
handleRemoteHangup(thread: call.thread, callId: hangup.id)
} else if message.hasVideoStreamingStatus() {
Logger.debug("\(self.logTag) remote participant sent VideoStreamingStatus via data channel: \(call.identifiersForLogs).")
self.isRemoteVideoEnabled = message.videoStreamingStatus.enabled()
} else {
Logger.info("\(self.logTag) received unknown or empty DataChannelMessage: \(call.identifiersForLogs).")
}
}
// MARK: - PeerConnectionClientDelegate
/**
* The connection has been established. The clients can now communicate.
*/
internal func peerConnectionClientIceConnected(_ peerConnectionClient: PeerConnectionClient) {
AssertIsOnMainThread()
guard peerConnectionClient == self.peerConnectionClient else {
Logger.debug("\(self.logTag) \(#function) Ignoring event from obsolete peerConnectionClient")
return
}
self.handleIceConnected()
}
/**
* The connection failed to establish. The clients will not be able to communicate.
*/
internal func peerConnectionClientIceFailed(_ peerConnectionClient: PeerConnectionClient) {
AssertIsOnMainThread()
guard peerConnectionClient == self.peerConnectionClient else {
Logger.debug("\(self.logTag) \(#function) Ignoring event from obsolete peerConnectionClient")
return
}
// Return to a known good state.
self.handleFailedCurrentCall(error: CallError.disconnected)
}
/**
* During the Signaling process each client generates IceCandidates locally, which contain information about how to
* reach the local client via the internet. The delegate must shuttle these IceCandates to the other (remote) client
* out of band, as part of establishing a connection over WebRTC.
*/
internal func peerConnectionClient(_ peerConnectionClient: PeerConnectionClient, addedLocalIceCandidate iceCandidate: RTCIceCandidate) {
AssertIsOnMainThread()
guard peerConnectionClient == self.peerConnectionClient else {
Logger.debug("\(self.logTag) \(#function) Ignoring event from obsolete peerConnectionClient")
return
}
self.handleLocalAddedIceCandidate(iceCandidate)
}
/**
* Once the peerconnection is established, we can receive messages via the data channel, and notify the delegate.
*/
internal func peerConnectionClient(_ peerConnectionClient: PeerConnectionClient, received dataChannelMessage: OWSWebRTCProtosData) {
AssertIsOnMainThread()
guard peerConnectionClient == self.peerConnectionClient else {
Logger.debug("\(self.logTag) \(#function) Ignoring event from obsolete peerConnectionClient")
return
}
self.handleDataChannelMessage(dataChannelMessage)
}
internal func peerConnectionClient(_ peerConnectionClient: PeerConnectionClient, didUpdateLocal videoTrack: RTCVideoTrack?) {
AssertIsOnMainThread()
guard peerConnectionClient == self.peerConnectionClient else {
Logger.debug("\(self.logTag) \(#function) Ignoring event from obsolete peerConnectionClient")
return
}
self.localVideoTrack = videoTrack
}
internal func peerConnectionClient(_ peerConnectionClient: PeerConnectionClient, didUpdateRemote videoTrack: RTCVideoTrack?) {
AssertIsOnMainThread()
guard peerConnectionClient == self.peerConnectionClient else {
Logger.debug("\(self.logTag) \(#function) Ignoring event from obsolete peerConnectionClient")
return
}
self.remoteVideoTrack = videoTrack
}
// MARK: Helpers
private func waitUntilReadyToSendIceUpdates() -> Promise<Void> {
AssertIsOnMainThread()
if self.readyToSendIceUpdatesPromise == nil {
createReadyToSendIceUpdatesPromise()
}
guard let readyToSendIceUpdatesPromise = self.readyToSendIceUpdatesPromise else {
OWSProdError(OWSAnalyticsEvents.callServiceCouldNotCreateReadyToSendIceUpdatesPromise(), file: #file, function: #function, line: #line)
return Promise(error: CallError.assertionError(description: "failed to create readyToSendIceUpdatesPromise"))
}
return readyToSendIceUpdatesPromise
}
private func createReadyToSendIceUpdatesPromise() {
AssertIsOnMainThread()
guard self.readyToSendIceUpdatesPromise == nil else {
owsFail("expected readyToSendIceUpdatesPromise to be nil")
return
}
guard self.fulfillReadyToSendIceUpdatesPromise == nil else {
owsFail("expected fulfillReadyToSendIceUpdatesPromise to be nil")
return
}
guard self.rejectReadyToSendIceUpdatesPromise == nil else {
owsFail("expected rejectReadyToSendIceUpdatesPromise to be nil")
return
}
let (promise, fulfill, reject) = Promise<Void>.pending()
self.fulfillReadyToSendIceUpdatesPromise = fulfill
self.rejectReadyToSendIceUpdatesPromise = reject
self.readyToSendIceUpdatesPromise = promise
}
private func waitForPeerConnectionClient() -> Promise<Void> {
AssertIsOnMainThread()
guard self.peerConnectionClient == nil else {
// peerConnectionClient already set
return Promise(value: ())
}
if self.peerConnectionClientPromise == nil {
createPeerConnectionClientPromise()
}
guard let peerConnectionClientPromise = self.peerConnectionClientPromise else {
OWSProdError(OWSAnalyticsEvents.callServiceCouldNotCreatePeerConnectionClientPromise(), file: #file, function: #function, line: #line)
return Promise(error: CallError.assertionError(description: "failed to create peerConnectionClientPromise"))
}
return peerConnectionClientPromise
}
private func createPeerConnectionClientPromise() {
AssertIsOnMainThread()
guard self.peerConnectionClientPromise == nil else {
owsFail("expected peerConnectionClientPromise to be nil")
return
}
guard self.fulfillPeerConnectionClientPromise == nil else {
owsFail("expected fulfillPeerConnectionClientPromise to be nil")
return
}
guard self.rejectPeerConnectionClientPromise == nil else {
owsFail("expected rejectPeerConnectionClientPromise to be nil")
return
}
let (promise, fulfill, reject) = Promise<Void>.pending()
self.fulfillPeerConnectionClientPromise = fulfill
self.rejectPeerConnectionClientPromise = reject
self.peerConnectionClientPromise = promise
}
/**
* RTCIceServers are used when attempting to establish an optimal connection to the other party. SignalService supplies
* a list of servers, plus we have fallback servers hardcoded in the app.
*/
private func getIceServers() -> Promise<[RTCIceServer]> {
AssertIsOnMainThread()
return firstly {
return accountManager.getTurnServerInfo()
}.then { turnServerInfo -> [RTCIceServer] in
Logger.debug("\(self.logTag) got turn server urls: \(turnServerInfo.urls)")
return turnServerInfo.urls.map { url in
if url.hasPrefix("turn") {
// Only "turn:" servers require authentication. Don't include the credentials to other ICE servers
// as 1.) they aren't used, and 2.) the non-turn servers might not be under our control.
// e.g. we use a public fallback STUN server.
return RTCIceServer(urlStrings: [url], username: turnServerInfo.username, credential: turnServerInfo.password)
} else {
return RTCIceServer(urlStrings: [url])
}
} + [CallService.fallbackIceServer]
}.recover { error -> [RTCIceServer] in
Logger.error("\(self.logTag) fetching ICE servers failed with error: \(error)")
Logger.warn("\(self.logTag) using fallback ICE Servers")
return [CallService.fallbackIceServer]
}
}
// This method should be called when either: a) we know or assume that
// the error is related to the current call. b) the error is so serious
// that we want to terminate the current call (if any) in order to
// return to a known good state.
public func handleFailedCurrentCall(error: CallError) {
Logger.debug("\(self.logTag) in \(#function)")
// Return to a known good state by ending the current call, if any.
handleFailedCall(failedCall: self.call, error: error)
}
// This method should be called when a fatal error occurred for a call.
//
// * If we know which call it was, we should update that call's state
// to reflect the error.
// * IFF that call is the current call, we want to terminate it.
public func handleFailedCall(failedCall: SignalCall?, error: CallError) {
AssertIsOnMainThread()
if case CallError.assertionError(description:let description) = error {
owsFail(description)
}
if let failedCall = failedCall {
if failedCall.state == .answering {
assert(failedCall.callRecord == nil)
// call failed before any call record could be created, make one now.
handleMissedCall(failedCall)
}
assert(failedCall.callRecord != nil)
// It's essential to set call.state before terminateCall, because terminateCall nils self.call
failedCall.error = error
failedCall.state = .localFailure
self.callUIAdapter.failCall(failedCall, error: error)
// Only terminate the current call if the error pertains to the current call.
guard failedCall == self.call else {
Logger.debug("\(self.logTag) in \(#function) ignoring obsolete call: \(failedCall.identifiersForLogs).")
return
}
Logger.error("\(self.logTag) call: \(failedCall.identifiersForLogs) failed with error: \(error)")
} else {
Logger.error("\(self.logTag) unknown call failed with error: \(error)")
}
// Only terminate the call if it is the current call.
terminateCall()
}
/**
* Clean up any existing call state and get ready to receive a new call.
*/
private func terminateCall() {
AssertIsOnMainThread()
Logger.debug("\(self.logTag) in \(#function)")
self.localVideoTrack = nil
self.remoteVideoTrack = nil
self.isRemoteVideoEnabled = false
self.peerConnectionClient?.terminate()
Logger.debug("\(self.logTag) setting peerConnectionClient in \(#function)")
self.peerConnectionClient = nil
self.call?.removeAllObservers()
self.call = nil
self.sendIceUpdatesImmediately = true
Logger.info("\(self.logTag) clearing pendingIceUpdateMessages")
self.pendingIceUpdateMessages = []
self.fulfillCallConnectedPromise = nil
if let rejectCallConnectedPromise = self.rejectCallConnectedPromise {
rejectCallConnectedPromise(CallError.obsoleteCall(description: "Terminating call"))
}
self.rejectCallConnectedPromise = nil
// In case we're still waiting on the peer connection setup somewhere, we need to reject it to avoid a memory leak.
// There is no harm in rejecting a previously fulfilled promise.
if let rejectPeerConnectionClientPromise = self.rejectPeerConnectionClientPromise {
rejectPeerConnectionClientPromise(CallError.obsoleteCall(description: "Terminating call"))
}
self.rejectPeerConnectionClientPromise = nil
self.fulfillPeerConnectionClientPromise = nil
self.peerConnectionClientPromise = nil
// In case we're still waiting on this promise somewhere, we need to reject it to avoid a memory leak.
// There is no harm in rejecting a previously fulfilled promise.
if let rejectReadyToSendIceUpdatesPromise = self.rejectReadyToSendIceUpdatesPromise {
rejectReadyToSendIceUpdatesPromise(CallError.obsoleteCall(description: "Terminating call"))
}
self.fulfillReadyToSendIceUpdatesPromise = nil
self.rejectReadyToSendIceUpdatesPromise = nil
self.readyToSendIceUpdatesPromise = nil
}
// MARK: - CallObserver
internal func stateDidChange(call: SignalCall, state: CallState) {
AssertIsOnMainThread()
Logger.info("\(self.logTag) \(#function): \(state)")
updateIsVideoEnabled()
}
internal func hasLocalVideoDidChange(call: SignalCall, hasLocalVideo: Bool) {
AssertIsOnMainThread()
Logger.info("\(self.logTag) \(#function): \(hasLocalVideo)")
self.updateIsVideoEnabled()
}
internal func muteDidChange(call: SignalCall, isMuted: Bool) {
AssertIsOnMainThread()
// Do nothing
}
internal func holdDidChange(call: SignalCall, isOnHold: Bool) {
AssertIsOnMainThread()
// Do nothing
}
internal func audioSourceDidChange(call: SignalCall, audioSource: AudioSource?) {
AssertIsOnMainThread()
// Do nothing
}
// MARK: - Video
private func shouldHaveLocalVideoTrack() -> Bool {
AssertIsOnMainThread()
guard let call = self.call else {
return false
}
// The iOS simulator doesn't provide any sort of camera capture
// support or emulation (http://goo.gl/rHAnC1) so don't bother
// trying to open a local stream.
return (!Platform.isSimulator &&
UIApplication.shared.applicationState != .background &&
call.state == .connected &&
call.hasLocalVideo)
}
//TODO only fire this when it's changed? as of right now it gets called whenever you e.g. lock the phone while it's incoming ringing.
private func updateIsVideoEnabled() {
AssertIsOnMainThread()
guard let call = self.call else {
return
}
guard let peerConnectionClient = self.peerConnectionClient else {
return
}
let shouldHaveLocalVideoTrack = self.shouldHaveLocalVideoTrack()
Logger.info("\(self.logTag) \(#function): \(shouldHaveLocalVideoTrack)")
self.peerConnectionClient?.setLocalVideoEnabled(enabled: shouldHaveLocalVideoTrack)
let message = DataChannelMessage.forVideoStreamingStatus(callId: call.signalingId, enabled: shouldHaveLocalVideoTrack)
peerConnectionClient.sendDataChannelMessage(data: message.asData(), description: "videoStreamingStatus", isCritical: false)
}
// MARK: - Observers
// The observer-related methods should be invoked on the main thread.
func addObserverAndSyncState(observer: CallServiceObserver) {
AssertIsOnMainThread()
observers.append(Weak(value: observer))
// Synchronize observer with current call state
let call = self.call
let localVideoTrack = self.localVideoTrack
let remoteVideoTrack = self.isRemoteVideoEnabled ? self.remoteVideoTrack : nil
observer.didUpdateVideoTracks(call: call,
localVideoTrack: localVideoTrack,
remoteVideoTrack: remoteVideoTrack)
}
// The observer-related methods should be invoked on the main thread.
func removeObserver(_ observer: CallServiceObserver) {
AssertIsOnMainThread()
while let index = observers.index(where: { $0.value === observer }) {
observers.remove(at: index)
}
}
// The observer-related methods should be invoked on the main thread.
func removeAllObservers() {
AssertIsOnMainThread()
observers = []
}
private func fireDidUpdateVideoTracks() {
AssertIsOnMainThread()
let call = self.call
let localVideoTrack = self.localVideoTrack
let remoteVideoTrack = self.isRemoteVideoEnabled ? self.remoteVideoTrack : nil
for observer in observers {
observer.value?.didUpdateVideoTracks(call: call,
localVideoTrack: localVideoTrack,
remoteVideoTrack: remoteVideoTrack)
}
}
// MARK: CallViewController Timer
var activeCallTimer: Timer?
func startCallTimer() {
AssertIsOnMainThread()
if self.activeCallTimer != nil {
owsFail("\(self.logTag) activeCallTimer should only be set once per call")
self.activeCallTimer!.invalidate()
self.activeCallTimer = nil
}
self.activeCallTimer = WeakTimer.scheduledTimer(timeInterval: 1, target: self, userInfo: nil, repeats: true) { [weak self] timer in
guard let strongSelf = self else {
return
}
guard let call = strongSelf.call else {
owsFail("\(strongSelf.logTag) call has since ended. Timer should have been invalidated.")
timer.invalidate()
return
}
strongSelf.ensureCallScreenPresented(call: call)
}
}
func ensureCallScreenPresented(call: SignalCall) {
guard let connectedDate = call.connectedDate else {
// Ignore; call hasn't connected yet.
return
}
let kMaxViewPresentationDelay = 2.5
guard fabs(connectedDate.timeIntervalSinceNow) > kMaxViewPresentationDelay else {
// Ignore; call connected recently.
return
}
let frontmostViewController = UIApplication.shared.frontmostViewControllerIgnoringAlerts
guard nil != frontmostViewController as? CallViewController else {
OWSProdError(OWSAnalyticsEvents.callServiceCallViewCouldNotPresent(), file: #file, function: #function, line: #line)
owsFail("\(self.logTag) in \(#function) Call terminated due to call view presentation delay: \(frontmostViewController.debugDescription).")
self.terminateCall()
return
}
}
func stopAnyCallTimer() {
AssertIsOnMainThread()
self.activeCallTimer?.invalidate()
self.activeCallTimer = nil
}
}
| gpl-3.0 | a36803d0940e4aea1d0a97e55fef5840 | 43.214286 | 207 | 0.649314 | 5.610832 | false | false | false | false |
Esri/arcgis-runtime-samples-ios | arcgis-ios-sdk-samples/Maps/Apply scheduled updates to preplanned map area/ApplyScheduledUpdatesToPreplannedMapAreaViewController.swift | 1 | 8201 | //
// Copyright © 2019 Esri.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import UIKit
import ArcGIS
/// A view controller that manages the interface of the Apply Scheduled Updates
/// to Preplanned Map Area sample.
class ApplyScheduledUpdatesToPreplannedMapAreaViewController: UIViewController {
/// The map view managed by the view controller.
@IBOutlet weak var mapView: AGSMapView!
/// The mobile map package used by this sample.
var mobileMapPackage: AGSMobileMapPackage!
/// The sync task used to check for scheduled updates.
var offlineMapSyncTask: AGSOfflineMapSyncTask!
/// The sync job used to apply updates to the offline map.
var offlineMapSyncJob: AGSOfflineMapSyncJob!
/// The temporary URL to store the mobile map package.
var temporaryMobileMapPackageURL: URL!
required init?(coder: NSCoder) {
let mobileMapPackageURL = Bundle.main.url(forResource: "canyonlands", withExtension: nil)!
do {
let temporaryDirectoryURL = try FileManager.default.url(
for: .itemReplacementDirectory,
in: .userDomainMask,
appropriateFor: mobileMapPackageURL,
create: true
)
temporaryMobileMapPackageURL = temporaryDirectoryURL.appendingPathComponent(ProcessInfo.processInfo.globallyUniqueString)
try FileManager.default.copyItem(at: mobileMapPackageURL, to: temporaryMobileMapPackageURL)
mobileMapPackage = AGSMobileMapPackage(fileURL: temporaryMobileMapPackageURL)
} catch {
print("Error setting up mobile map package: \(error)")
mobileMapPackage = nil
}
super.init(coder: coder)
mobileMapPackage?.load { [weak self] (error) in
let result: Result<Void, Error>
if let error = error {
result = .failure(error)
} else {
result = .success(())
}
self?.mobileMapPackageDidLoad(with: result)
}
}
deinit {
if let mobileMapPackage = mobileMapPackage {
mobileMapPackage.close()
try? FileManager.default.removeItem(at: mobileMapPackage.fileURL)
}
}
/// Called in response to the mobile map package load operation completing.
/// - Parameter result: The result of the load operation.
func mobileMapPackageDidLoad(with result: Result<Void, Error>) {
switch result {
case .success:
let map = self.mobileMapPackage.maps.first!
loadViewIfNeeded()
mapView.map = map
let offlineMapSyncTask = AGSOfflineMapSyncTask(map: map)
offlineMapSyncTask.checkForUpdates { [weak self] (updatesInfo, error) in
if let updatesInfo = updatesInfo {
self?.offlineMapSyncTaskDidComplete(with: .success(updatesInfo))
} else if let error = error {
self?.offlineMapSyncTaskDidComplete(with: .failure(error))
}
}
self.offlineMapSyncTask = offlineMapSyncTask
case .failure(let error):
presentAlert(error: error)
}
}
/// Called in response to the offline map sync task completing.
/// - Parameter result: The result of the sync task.
func offlineMapSyncTaskDidComplete(with result: Result<AGSOfflineMapUpdatesInfo, Error>) {
switch result {
case .success(let updatesInfo):
let alertController: UIAlertController
if updatesInfo.downloadAvailability == .available {
let downloadSize = updatesInfo.scheduledUpdatesDownloadSize
let measurement = Measurement(
value: Double(downloadSize),
unit: UnitInformationStorage.bytes
)
let downloadSizeString = ByteCountFormatter.string(from: measurement, countStyle: .file)
alertController = UIAlertController(
title: "Scheduled Updates Available",
message: "A \(downloadSizeString) update is available. Would you like to apply it?",
preferredStyle: .alert
)
let applyAction = UIAlertAction(title: "Apply", style: .default) { (_) in
self.applyScheduledUpdates()
}
alertController.addAction(applyAction)
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel)
alertController.addAction(cancelAction)
alertController.preferredAction = applyAction
} else {
alertController = UIAlertController(
title: "Scheduled Updates Unavailable",
message: "There are no updates available.",
preferredStyle: .alert
)
let okayAction = UIAlertAction(title: "OK", style: .default)
alertController.addAction(okayAction)
alertController.preferredAction = okayAction
}
present(alertController, animated: true)
case .failure(let error):
presentAlert(error: error)
}
}
/// Apply available updates to the offline map.
func applyScheduledUpdates() {
offlineMapSyncTask.defaultOfflineMapSyncParameters { [weak self] (parameters, error) in
guard let self = self else { return }
if let parameters = parameters {
let offlineMapSyncJob = self.offlineMapSyncTask.offlineMapSyncJob(with: parameters)
offlineMapSyncJob.start(statusHandler: nil) { [weak self] (result, error) in
if let result = result {
self?.offlineMapSyncJobDidComplete(with: .success(result))
} else if let error = error {
self?.offlineMapSyncJobDidComplete(with: .failure(error))
}
}
self.offlineMapSyncJob = offlineMapSyncJob
} else if let error = error {
self.presentAlert(error: error)
}
}
}
/// Called in response to the offline map sync job completing.
/// - Parameter result: The result of the sync job.
func offlineMapSyncJobDidComplete(with result: Result<AGSOfflineMapSyncResult, Error>) {
switch result {
case .success(let result):
guard result.isMobileMapPackageReopenRequired else {
break
}
mobileMapPackage.close()
// Create a new instance of the updated mobile map package and load.
let updatedMobileMapPackage = AGSMobileMapPackage(fileURL: temporaryMobileMapPackageURL)
updatedMobileMapPackage.load { [weak self] (error) in
guard let self = self else { return }
if let error = error {
self.presentAlert(error: error)
} else {
self.mapView.map = self.mobileMapPackage.maps.first
}
}
mobileMapPackage = updatedMobileMapPackage
case .failure(let error):
presentAlert(error: error)
}
}
// MARK: UIViewController
override func viewDidLoad() {
super.viewDidLoad()
// add the source code button item to the right of navigation bar
(self.navigationItem.rightBarButtonItem as? SourceCodeBarButtonItem)?.filenames = [
"ApplyScheduledUpdatesToPreplannedMapAreaViewController"
]
}
}
| apache-2.0 | 4c88fb72dd8dc87d7d084eeea4d21f18 | 42.157895 | 133 | 0.610976 | 5.624143 | false | false | false | false |
kripple/bti-watson | ios-app/Carthage/Checkouts/AlamofireObjectMapper/Carthage/Checkouts/ObjectMapper/Carthage/Checkouts/Nimble/NimbleTests/Helpers/utils.swift | 46 | 3294 | import Foundation
import Nimble
import XCTest
func failsWithErrorMessage(messages: [String], file: String = __FILE__, line: UInt = __LINE__, preferOriginalSourceLocation: Bool = false, closure: () throws -> Void) {
var filePath = file
var lineNumber = line
let recorder = AssertionRecorder()
withAssertionHandler(recorder, closure: closure)
for msg in messages {
var lastFailure: AssertionRecord?
var foundFailureMessage = false
for assertion in recorder.assertions {
lastFailure = assertion
if assertion.message.stringValue == msg {
foundFailureMessage = true
break
}
}
if foundFailureMessage {
continue
}
if preferOriginalSourceLocation {
if let failure = lastFailure {
filePath = failure.location.file
lineNumber = failure.location.line
}
}
if let lastFailure = lastFailure {
let msg = "Got failure message: \"\(lastFailure.message.stringValue)\", but expected \"\(msg)\""
XCTFail(msg, file: filePath, line: lineNumber)
} else {
XCTFail("expected failure message, but got none", file: filePath, line: lineNumber)
}
}
}
func failsWithErrorMessage(message: String, file: String = __FILE__, line: UInt = __LINE__, preferOriginalSourceLocation: Bool = false, closure: () -> Void) {
return failsWithErrorMessage(
[message],
file: file,
line: line,
preferOriginalSourceLocation: preferOriginalSourceLocation,
closure: closure
)
}
func failsWithErrorMessageForNil(message: String, file: String = __FILE__, line: UInt = __LINE__, preferOriginalSourceLocation: Bool = false, closure: () -> Void) {
failsWithErrorMessage("\(message) (use beNil() to match nils)", file: file, line: line, preferOriginalSourceLocation: preferOriginalSourceLocation, closure: closure)
}
func deferToMainQueue(action: () -> Void) {
dispatch_async(dispatch_get_main_queue()) {
NSThread.sleepForTimeInterval(0.01)
action()
}
}
public class NimbleHelper : NSObject {
class func expectFailureMessage(message: NSString, block: () -> Void, file: String, line: UInt) {
failsWithErrorMessage(message as String, file: file, line: line, preferOriginalSourceLocation: true, closure: block)
}
class func expectFailureMessages(messages: [NSString], block: () -> Void, file: String, line: UInt) {
failsWithErrorMessage(messages as! [String], file: file, line: line, preferOriginalSourceLocation: true, closure: block)
}
class func expectFailureMessageForNil(message: NSString, block: () -> Void, file: String, line: UInt) {
failsWithErrorMessageForNil(message as String, file: file, line: line, preferOriginalSourceLocation: true, closure: block)
}
}
extension NSDate {
convenience init(dateTimeString:String) {
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
dateFormatter.locale = NSLocale(localeIdentifier: "en_US_POSIX")
let date = dateFormatter.dateFromString(dateTimeString)!
self.init(timeInterval:0, sinceDate:date)
}
} | mit | 5a52af1d1bad729bbed9698132faae78 | 36.873563 | 169 | 0.656648 | 4.998483 | false | false | false | false |
JJJayway/ReactiveSwift | Reactive/Event.swift | 1 | 2745 | //
// Event.swift
// Reactive
//
// Created by Jens Jakob Jensen on 25/08/14.
// Copyright (c) 2014 Jayway. All rights reserved.
//
import class Foundation.NSError
/// This maps a struct inside a class to get Hashable and Equatable (used by Splitter), and to avoid a bug in beta 6 (in the definition of Event)
public class Box<T>: Hashable, Equatable {
public let value: T
init(_ value: T) {
self.value = value
}
public func unbox() -> T {
return value
}
public var hashValue: Int {
return reflect(self).objectIdentifier!.hashValue
}
}
public func ==<T>(lhs: Box<T>, rhs: Box<T>) -> Bool {
return lhs === rhs
}
// MARK: -
public enum Event<T> {
/// A value.
/// Box the value due to an unimplemented feature in beta 6: "unimplemented IR generation feature non-fixed multi-payload enum layout".
case Value(Box<T>)
/// Completed without error. This is an ending event: No more events will be emitted.
case Completed
/// Stopped prematurely without error (terminated). This is an ending event: No more events will be emitted.
case Stopped
/// Error. This is an ending event: No more events will be emitted.
case Error(NSError)
public func convertNonValue<U>() -> Event<U> {
switch self {
case .Value(_): fatalError("convertNonValue() cannot convert Event values!")
case .Completed: return .Completed
case .Stopped: return .Stopped
case .Error(let error): return .Error(error)
}
}
public var isValue: Bool {
switch self {
case .Value(_):
return true
default:
return false
}
}
public var isCompleted: Bool {
switch self {
case .Completed:
return true
default:
return false
}
}
public var isStopped: Bool {
switch self {
case .Stopped:
return true
default:
return false
}
}
public var isError: Bool {
switch self {
case .Error(_):
return true
default:
return false
}
}
public var isEnd: Bool {
return !isValue
}
public var value: T? {
switch self {
case .Value(let valueBox):
return valueBox.unbox()
default:
return nil
}
}
public static func fromValue(value: T) -> Event {
return .Value(Box(value))
}
public var error: NSError? {
switch self {
case .Error(let error):
return error
default:
return nil
}
}
}
| mit | 1e46505f9eb90834fba381e179a32407 | 24.183486 | 145 | 0.552277 | 4.514803 | false | false | false | false |
codefellows/sea-c47-iOS | Sample Code/Session1.playground/Contents.swift | 1 | 1655 | 1
1123432534534
//this is my comment
2 + 2
2 * 3.14159265359 * 30
2 * 3.14159265359 * 10
let pi = 3.14159265359
2 * pi * 100
let myName = "Brad"
//myName = "Bob"
//pi = 345.45
func doSomething() {
println("did something")
}
doSomething()
func addNumbers(a : Int, b: Int, c : Int) -> Int {
//let total = a + b + c
return a + b + c
}
addNumbers(324, 34, 2345)
//Calculate the circumference of a circle given the radius
func calculateCircumferenceForCircleGivenRadius(radius : Float) -> Float {
let pi : Float = 3.14159265359
// let myDoubler : Float = 2.0
return 2.0 * pi * radius
}
//calculateCircumferenceForCircleGivenRadius(45.0)
class Stick {
var broken = false
var length : Int
var width : Int
var weight = 5
var attackDamage = 20
init (startingLength : Int, startingWidth : Int) {
length = startingLength
width = startingWidth
}
func shake() {
println("shaking!")
let numberOfShakes = 10
broken = false
}
func breakStick() {
broken = true
length = length / 2
}
func sizeOfStick() -> Int {
return width * length
}
}
let bigStick = Stick(startingLength: 50, startingWidth: 10)
bigStick.breakStick()
bigStick.broken
bigStick.broken
bigStick.shake()
let boomStick = Stick(startingLength: 20, startingWidth: 20)
boomStick.shake()
bigStick.breakStick()
boomStick.attackDamage = 1000
let size = boomStick.sizeOfStick()
boomStick.breakStick()
let newSize = boomStick.sizeOfStick()
class SelfieStick : Stick {
}
let mySelfieStick = SelfieStick(startingLength: 20, startingWidth: 5)
mySelfieStick.length
mySelfieStick.breakStick()
| mit | a99df9477453f7888caca8cfd35d73f6 | 13.517544 | 74 | 0.676133 | 3.506356 | false | false | false | false |
brentdax/swift | stdlib/public/SDK/CryptoTokenKit/TKSmartCard.swift | 20 | 1788 | //===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
@_exported import CryptoTokenKit
import Foundation
@available(macOS 10.10, *)
extension TKSmartCard {
public func send(ins: UInt8, p1: UInt8, p2: UInt8, data: Data? = nil,
le: Int? = nil, reply: @escaping (Data?, UInt16, Error?) -> Void) {
self.__sendIns(ins, p1: p1, p2: p2, data: data,
le: le.map { NSNumber(value: $0) }, reply: reply)
}
@available(macOS 10.12, *)
public func send(ins: UInt8, p1: UInt8, p2: UInt8, data: Data? = nil,
le: Int? = nil) throws -> (sw: UInt16, response: Data) {
var sw: UInt16 = 0
let response = try self.__sendIns(ins, p1: p1, p2: p2, data: data,
le: le.map { NSNumber(value: $0) }, sw: &sw)
return (sw: sw, response: response)
}
@available(macOS 10.12, *)
public func withSession<T>(_ body: @escaping () throws -> T) throws -> T {
var result: T?
try self.__inSession(executeBlock: {
(errorPointer: NSErrorPointer) -> Bool in
do {
result = try body()
return true
} catch let error as NSError {
errorPointer?.pointee = error
return false
}
})
// it is safe to force unwrap the result here, as the self.__inSession
// function rethrows the errors which happened inside the block
return result!
}
}
| apache-2.0 | 5c826f4198c94311506835dd271d00f3 | 32.111111 | 80 | 0.579418 | 3.764211 | false | false | false | false |
AliceAponasko/LJReader | LJReader/Controllers/FeedTableDataSource.swift | 1 | 1553 | //
// FeedTableDataSource.swift
// LJReader
//
// Created by Alice Aponasko on 9/11/16.
// Copyright © 2016 aliceaponasko. All rights reserved.
//
import UIKit
class FeedTableDataSource: NSObject, UITableViewDataSource {
let timeZone = NSTimeZone(abbreviation: "GMT")
var articles = [FeedEntry]()
var authors = [String]()
var dateFormatter = NSDateFormatter()
override init() {
super.init()
dateFormatter.dateFormat = "EEE, dd MMM yyyy HH:mm:ss zzz"
dateFormatter.timeZone = timeZone
}
func numberOfSectionsInTableView(
tableView: UITableView) -> Int {
return 1
}
func tableView(
tableView: UITableView,
numberOfRowsInSection section: Int) -> Int {
return articles.count
}
func tableView(
tableView: UITableView,
cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell: FeedCell
if let feedCell = tableView.dequeueReusableCellWithIdentifier(
FeedCell.cellID) as? FeedCell {
cell = feedCell
} else {
tableView.registerClass(
FeedCell.self,
forCellReuseIdentifier: FeedCell.cellID)
cell = FeedCell()
}
let article = articles[indexPath.row]
let pubDate = dateFormatter.dateFromString(article.pubDate)!
cell.setFromArticle(
article,
pubDate: pubDate,
width: tableView.frame.width)
return cell
}
}
| mit | d69c74880e0fbcc2e733892512c3d9d2 | 22.164179 | 74 | 0.61018 | 5.139073 | false | false | false | false |
HongliYu/firefox-ios | Client/Frontend/Browser/TabPeekViewController.swift | 1 | 7793 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import UIKit
import Shared
import Storage
import WebKit
protocol TabPeekDelegate: AnyObject {
func tabPeekDidAddBookmark(_ tab: Tab)
@discardableResult func tabPeekDidAddToReadingList(_ tab: Tab) -> ReadingListItem?
func tabPeekRequestsPresentationOf(_ viewController: UIViewController)
func tabPeekDidCloseTab(_ tab: Tab)
}
class TabPeekViewController: UIViewController, WKNavigationDelegate {
fileprivate static let PreviewActionAddToBookmarks = NSLocalizedString("Add to Bookmarks", tableName: "3DTouchActions", comment: "Label for preview action on Tab Tray Tab to add current tab to Bookmarks")
fileprivate static let PreviewActionCopyURL = NSLocalizedString("Copy URL", tableName: "3DTouchActions", comment: "Label for preview action on Tab Tray Tab to copy the URL of the current tab to clipboard")
fileprivate static let PreviewActionCloseTab = NSLocalizedString("Close Tab", tableName: "3DTouchActions", comment: "Label for preview action on Tab Tray Tab to close the current tab")
weak var tab: Tab?
fileprivate weak var delegate: TabPeekDelegate?
fileprivate var clientPicker: UINavigationController?
fileprivate var isBookmarked: Bool = false
fileprivate var isInReadingList: Bool = false
fileprivate var hasRemoteClients: Bool = false
fileprivate var ignoreURL: Bool = false
fileprivate var screenShot: UIImageView?
fileprivate var previewAccessibilityLabel: String!
fileprivate var webView: WKWebView?
// Preview action items.
override var previewActionItems: [UIPreviewActionItem] {
get {
return previewActions
}
}
lazy var previewActions: [UIPreviewActionItem] = {
var actions = [UIPreviewActionItem]()
let urlIsTooLongToSave = self.tab?.urlIsTooLong ?? false
if !self.ignoreURL && !urlIsTooLongToSave {
if !self.isBookmarked {
actions.append(UIPreviewAction(title: TabPeekViewController.PreviewActionAddToBookmarks, style: .default) { [weak self] previewAction, viewController in
guard let wself = self, let tab = wself.tab else { return }
wself.delegate?.tabPeekDidAddBookmark(tab)
})
}
if self.hasRemoteClients {
actions.append(UIPreviewAction(title: Strings.SendToDeviceTitle, style: .default) { [weak self] previewAction, viewController in
guard let wself = self, let clientPicker = wself.clientPicker else { return }
wself.delegate?.tabPeekRequestsPresentationOf(clientPicker)
})
}
// only add the copy URL action if we don't already have 3 items in our list
// as we are only allowed 4 in total and we always want to display close tab
if actions.count < 3 {
actions.append(UIPreviewAction(title: TabPeekViewController.PreviewActionCopyURL, style: .default) {[weak self] previewAction, viewController in
guard let wself = self, let url = wself.tab?.canonicalURL else { return }
UIPasteboard.general.url = url
SimpleToast().showAlertWithText(Strings.AppMenuCopyURLConfirmMessage, bottomContainer: wself.view)
})
}
}
actions.append(UIPreviewAction(title: TabPeekViewController.PreviewActionCloseTab, style: .destructive) { [weak self] previewAction, viewController in
guard let wself = self, let tab = wself.tab else { return }
wself.delegate?.tabPeekDidCloseTab(tab)
})
return actions
}()
init(tab: Tab, delegate: TabPeekDelegate?) {
self.tab = tab
self.delegate = delegate
super.init(nibName: nil, bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
webView?.navigationDelegate = nil
self.webView = nil
}
override func viewDidLoad() {
super.viewDidLoad()
if let webViewAccessibilityLabel = tab?.webView?.accessibilityLabel {
previewAccessibilityLabel = String(format: NSLocalizedString("Preview of %@", tableName: "3DTouchActions", comment: "Accessibility label, associated to the 3D Touch action on the current tab in the tab tray, used to display a larger preview of the tab."), webViewAccessibilityLabel)
}
// if there is no screenshot, load the URL in a web page
// otherwise just show the screenshot
setupWebView(tab?.webView)
guard let screenshot = tab?.screenshot else { return }
setupWithScreenshot(screenshot)
}
fileprivate func setupWithScreenshot(_ screenshot: UIImage) {
let imageView = UIImageView(image: screenshot)
self.view.addSubview(imageView)
imageView.snp.makeConstraints { make in
make.edges.equalTo(self.view)
}
screenShot = imageView
screenShot?.accessibilityLabel = previewAccessibilityLabel
}
fileprivate func setupWebView(_ webView: WKWebView?) {
guard let webView = webView, let url = webView.url, !isIgnoredURL(url) else { return }
let clonedWebView = WKWebView(frame: webView.frame, configuration: webView.configuration)
clonedWebView.allowsLinkPreview = false
clonedWebView.accessibilityLabel = previewAccessibilityLabel
self.view.addSubview(clonedWebView)
clonedWebView.snp.makeConstraints { make in
make.edges.equalTo(self.view)
}
clonedWebView.navigationDelegate = self
self.webView = clonedWebView
clonedWebView.load(URLRequest(url: url))
}
func setState(withProfile browserProfile: BrowserProfile, clientPickerDelegate: ClientPickerViewControllerDelegate) {
assert(Thread.current.isMainThread)
guard let tab = self.tab else {
return
}
guard let displayURL = tab.url?.absoluteString, !displayURL.isEmpty else {
return
}
let mainQueue = DispatchQueue.main
browserProfile.bookmarks.modelFactory >>== {
$0.isBookmarked(displayURL).uponQueue(mainQueue) {
self.isBookmarked = $0.successValue ?? false
}
}
browserProfile.remoteClientsAndTabs.getClientGUIDs().uponQueue(mainQueue) {
guard let clientGUIDs = $0.successValue else {
return
}
self.hasRemoteClients = !clientGUIDs.isEmpty
let clientPickerController = ClientPickerViewController()
clientPickerController.clientPickerDelegate = clientPickerDelegate
clientPickerController.profile = browserProfile
clientPickerController.profileNeedsShutdown = false
if let url = tab.url?.absoluteString {
clientPickerController.shareItem = ShareItem(url: url, title: tab.title, favicon: nil)
}
self.clientPicker = UINavigationController(rootViewController: clientPickerController)
}
let result = browserProfile.readingList.getRecordWithURL(displayURL).value.successValue
self.isInReadingList = !(result?.url.isEmpty ?? true)
self.ignoreURL = isIgnoredURL(displayURL)
}
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
screenShot?.removeFromSuperview()
screenShot = nil
}
}
| mpl-2.0 | ab0ece82abb1715fb9e16137244ad7eb | 42.536313 | 294 | 0.674323 | 5.472612 | false | false | false | false |
kylef/JSONSchema.swift | Sources/RefResolver.swift | 1 | 3145 | import Foundation
func urlSplitFragment(url: String) -> (String, String) {
guard let hashIndex = url.index(of: "#") else {
return (url, "")
}
return (
String(url.prefix(upTo: hashIndex)),
String(url.suffix(from: url.index(after: hashIndex)))
)
}
func urlJoin(_ lhs: String, _ rhs: String) -> String {
if lhs.isEmpty {
return rhs
}
if rhs.isEmpty {
return lhs
}
return URL(string: rhs, relativeTo: URL(string: lhs)!)!.absoluteString
}
func urlNormalise(_ value: String) -> String {
if value.hasSuffix("#"), let index = value.lastIndex(of: "#") {
return String(value.prefix(upTo: index))
}
return value
}
func urlEqual(_ lhs: String, _ rhs: String) -> Bool {
return urlNormalise(lhs) == urlNormalise(rhs)
}
class RefResolver {
let referrer: [String: Any]
var store: [String: Any]
var stack: [String]
let idField: String
let defsField: String
init(schema: [String: Any], metaschemes: [String: Any], idField: String = "$id", defsField: String = "$defs") {
self.referrer = schema
self.store = metaschemes
self.idField = idField
self.defsField = defsField
if let id = schema[idField] as? String {
self.store[id] = schema
self.stack = [id]
} else {
self.store[""] = schema
self.stack = [""]
}
storeDefinitions(from: schema)
}
init(resolver: RefResolver) {
referrer = resolver.referrer
store = resolver.store
stack = resolver.stack
idField = resolver.idField
defsField = resolver.defsField
}
func storeDefinitions(from document: Any) {
guard
let document = document as? [String: Any],
let defs = document[defsField] as? [String: Any]
else {
return
}
for (_, defs) in defs {
guard let def = defs as? [String: Any] else { continue }
let id = def[idField] as? String
let anchor = def["$anchor"] as? String
let url: String
if let anchor = anchor {
url = urlJoin(stack.last!, "\(id ?? "")#\(anchor)")
} else if let id = id {
url = urlJoin(stack.last!, id)
} else { continue }
self.store[url] = def
// recurse
self.stack.append(url)
storeDefinitions(from: def)
self.stack.removeLast()
}
}
func resolve(reference: String) -> Any? {
let url = urlJoin(stack.last!, reference)
return resolve(url: url)
}
func resolve(url: String) -> Any? {
if let document = store[url] {
return document
}
let (url, fragment) = urlSplitFragment(url: url)
guard let document = store[url] else {
return nil
}
if let document = document as? [String: Any] {
return resolve(document: document, fragment: fragment)
}
if fragment == "" {
return document
}
return nil
}
func resolve(document: [String: Any], fragment: String) -> Any? {
guard !fragment.isEmpty else {
return document
}
guard let reference = (fragment as NSString).removingPercentEncoding else {
return nil
}
let pointer = JSONPointer(path: reference)
return pointer.resolve(document: document)
}
}
| bsd-3-clause | 81e46f64836476222e0df63b08dffe35 | 21.464286 | 113 | 0.612083 | 3.74851 | false | false | false | false |
jeffreybergier/WaterMe2 | WaterMe/Frameworks/Datum/Datum/Wrapper/ReminderVessel/CD_ReminderVesselWrapper.swift | 1 | 4040 | //
// CD_ReminderVesselWrapper.swift
// Datum
//
// Created by Jeffrey Bergier on 2020/05/20.
// Copyright © 2020 Saturday Apps.
//
// This file is part of WaterMe. Simple Plant Watering Reminders for iOS.
//
// WaterMe 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.
//
// WaterMe 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 WaterMe. If not, see <http://www.gnu.org/licenses/>.
//
import CoreData
internal struct CD_ReminderVesselWrapper: ReminderVessel {
internal let wrappedObject: CD_ReminderVessel
internal let context: LazyContext
internal init(_ wrappedObject: CD_ReminderVessel, context: @escaping LazyContext) {
self.wrappedObject = wrappedObject
self.context = context
}
public var uuid: String { self.wrappedObject.objectID.uriRepresentation().absoluteString }
public var displayName: String? { self.wrappedObject.displayName }
public var icon: ReminderVesselIcon? { self.wrappedObject.icon }
public var kind: ReminderVesselKind { self.wrappedObject.kind }
public var isModelComplete: ModelCompleteError? { self.wrappedObject.isModelComplete }
public var shortLabelSafeDisplayName: String? { self.wrappedObject.shortLabelSafeDisplayName }
func observe(_ block: @escaping (ReminderVesselChange) -> Void) -> ObservationToken {
let queue = DispatchQueue.main
let vessel = self.wrappedObject
let token1 = vessel.observe(\.displayName) { _, _ in
queue.async { block(.change(.init(changedDisplayName: true))) }
}
let token2 = vessel.observe(\.iconEmojiString) { _, _ in
queue.async { block(.change(.init(changedIconEmoji: true))) }
}
let token3 = vessel.observe(\.iconImageData) { _, _ in
queue.async { block(.change(.init(changedIconEmoji: true))) }
}
let token4 = vessel.observe(\.kindString) { _, _ in
queue.async { block(.change(.init(changedPointlessBloop: true))) }
}
let token5 = NotificationCenter.default.addObserver(forName: .NSManagedObjectContextDidSave,
object: nil,
queue: nil)
{ [weak wrappedObject] notification in
guard let wrappedObject = wrappedObject else { return }
let deletedObjects = notification.userInfo?[NSDeletedObjectsKey] as? NSSet
if deletedObjects?.contains(wrappedObject) == true {
queue.async { block(.deleted) }
return
}
}
return Token.wrap { [token1, token2, token3, token4, Token.wrap { token5 }] }
}
func observeReminders(_ block: @escaping (ReminderCollectionChange) -> Void) -> ObservationToken {
let request = CD_Reminder.fetchRequest() as! NSFetchRequest<CD_Reminder>
request.predicate = NSPredicate(format: "\(#keyPath(CD_Reminder.vessel)) == %@", self.wrappedObject)
request.sortDescriptors = [NSSortDescriptor(key: #keyPath(CD_Reminder.dateCreated), ascending: false)]
let context = self.context()
let controller = NSFetchedResultsController(fetchRequest: request,
managedObjectContext: context,
sectionNameKeyPath: nil,
cacheName: nil)
let query = CD_ReminderQuery(controller, context: self.context)
return query.observe(block)
}
}
| gpl-3.0 | beaf9e35955f74a152f7fa7b71b425a8 | 47.083333 | 110 | 0.636296 | 4.943696 | false | false | false | false |
ndleon09/SwiftSample500px | pictures/Modules/Detail/LocationItem.swift | 1 | 934 | //
// DetailItem.swift
// pictures
//
// Created by Nelson Dominguez on 27/06/16.
// Copyright © 2016 Nelson Dominguez. All rights reserved.
//
import Foundation
import TableViewKit
class LocationItem: Item {
var drawer: CellDrawer.Type = LocationDrawer.self
var height: Height? = Height.static(320.0)
var latitude: Double
var longitude: Double
init(latitude: Double, longitude: Double) {
self.latitude = latitude
self.longitude = longitude
}
}
class LocationDrawer: CellDrawer {
static var type: CellType = CellType.nib(UINib(nibName: String(describing: LocationCell.self), bundle: nil), LocationCell.self)
static func draw(_ cell: UITableViewCell, with item: Any) {
let item = item as! LocationItem
let cell = cell as! LocationCell
cell.setLocation(latitude: item.latitude, longitude: item.longitude)
}
}
| mit | b23517272d3f1a973ea613d2c7bbf6ac | 24.216216 | 131 | 0.662379 | 4.319444 | false | false | false | false |
Nautiyalsachin/SwiftMQTT | SwiftMQTT/SwiftMQTT/MQTTSessionStream.swift | 1 | 4777 | //
// MQTTSessionStream.swift
// SwiftMQTT
//
// Created by Ankit Aggarwal on 12/11/15.
// Copyright © 2015 Ankit. All rights reserved.
//
/*
OCI Changes:
Bug Fix - do not handshake until ports are ready
Changed name of file to match primary class
Propagate error object to delegate
Make MQTTSessionStreamDelegate var weak
MQTTSessionStream is now not recycled (RAII design pattern)
Move the little bit of parsing out of this class. This only manages the stream.
Always use dedicated queue for streams
Remove all MQTT model dependencies
*/
import Foundation
protocol MQTTSessionStreamDelegate: class {
func mqttReady(_ ready: Bool, in stream: MQTTSessionStream)
func mqttErrorOccurred(in stream: MQTTSessionStream, error: Error?)
func mqttReceived(in stream: MQTTSessionStream, _ read: StreamReader)
}
class MQTTSessionStream: NSObject {
fileprivate let inputStream: InputStream?
fileprivate let outputStream: OutputStream?
fileprivate weak var delegate: MQTTSessionStreamDelegate?
private var sessionQueue: DispatchQueue
fileprivate var inputReady = false
fileprivate var outputReady = false
init(host: String, port: UInt16, ssl: Bool, timeout: TimeInterval, delegate: MQTTSessionStreamDelegate?) {
var inputStream: InputStream?
var outputStream: OutputStream?
Stream.getStreamsToHost(withName: host, port: Int(port), inputStream: &inputStream, outputStream: &outputStream)
var parts = host.components(separatedBy: ".")
parts.insert("stream\(port)", at: 0)
let label = parts.reversed().joined(separator: ".")
self.sessionQueue = DispatchQueue(label: label, qos: .background, target: nil)
self.delegate = delegate
self.inputStream = inputStream
self.outputStream = outputStream
super.init()
inputStream?.delegate = self
outputStream?.delegate = self
sessionQueue.async { [weak self] in
let currentRunLoop = RunLoop.current
inputStream?.schedule(in: currentRunLoop, forMode: .defaultRunLoopMode)
outputStream?.schedule(in: currentRunLoop, forMode: .defaultRunLoopMode)
inputStream?.open()
outputStream?.open()
if ssl {
let securityLevel = StreamSocketSecurityLevel.negotiatedSSL.rawValue
inputStream?.setProperty(securityLevel, forKey: Stream.PropertyKey.socketSecurityLevelKey)
outputStream?.setProperty(securityLevel, forKey: Stream.PropertyKey.socketSecurityLevelKey)
}
if timeout > 0 {
DispatchQueue.global().asyncAfter(deadline: .now() + timeout) {
self?.connectTimeout()
}
}
currentRunLoop.run()
}
}
deinit {
inputStream?.close()
inputStream?.remove(from: .current, forMode: .defaultRunLoopMode)
outputStream?.close()
outputStream?.remove(from: .current, forMode: .defaultRunLoopMode)
}
var write: StreamWriter? {
if let outputStream = outputStream, outputReady {
return outputStream.write
}
return nil
}
internal func connectTimeout() {
if inputReady == false || outputReady == false {
delegate?.mqttReady(false, in: self)
}
}
}
extension MQTTSessionStream: StreamDelegate {
@objc
internal func stream(_ aStream: Stream, handle eventCode: Stream.Event) {
switch eventCode {
case Stream.Event.openCompleted:
let wasReady = inputReady && outputReady
if aStream == inputStream {
inputReady = true
}
else if aStream == outputStream {
// output almost ready
}
if !wasReady && inputReady && outputReady {
delegate?.mqttReady(true, in: self)
}
break
case Stream.Event.hasBytesAvailable:
if aStream == inputStream {
delegate?.mqttReceived(in: self, inputStream!.read)
}
break
case Stream.Event.errorOccurred:
delegate?.mqttErrorOccurred(in: self, error: aStream.streamError)
break
case Stream.Event.endEncountered:
if aStream.streamError != nil {
delegate?.mqttErrorOccurred(in: self, error: aStream.streamError)
}
break
case Stream.Event.hasSpaceAvailable:
let wasReady = inputReady && outputReady
if aStream == outputStream {
outputReady = true
}
if !wasReady && inputReady && outputReady {
delegate?.mqttReady(true, in: self)
}
break
default:
break
}
}
}
| mit | f897851dc224b0d34d75eb0c436e2241 | 33.114286 | 120 | 0.635678 | 5.174431 | false | false | false | false |
nghialv/MaterialKit | Source/MKTextField.swift | 2 | 8702 | //
// MKTextField.swift
// MaterialKit
//
// Created by LeVan Nghia on 11/14/14.
// Copyright (c) 2014 Le Van Nghia. All rights reserved.
//
import UIKit
import QuartzCore
@IBDesignable
public class MKTextField : UITextField {
@IBInspectable public var padding: CGSize = CGSize(width: 5, height: 5)
@IBInspectable public var floatingLabelBottomMargin: CGFloat = 2.0
@IBInspectable public var floatingPlaceholderEnabled: Bool = false {
didSet {
self.updateFloatingLabelText()
}
}
@IBInspectable public var maskEnabled: Bool = true {
didSet {
mkLayer.maskEnabled = maskEnabled
}
}
@IBInspectable public var cornerRadius: CGFloat = 0 {
didSet {
self.layer.cornerRadius = self.cornerRadius
mkLayer.superLayerDidResize()
}
}
@IBInspectable public var elevation: CGFloat = 0 {
didSet {
mkLayer.elevation = elevation
}
}
@IBInspectable public var shadowOffset: CGSize = CGSizeZero {
didSet {
mkLayer.shadowOffset = shadowOffset
}
}
@IBInspectable public var roundingCorners: UIRectCorner = UIRectCorner.AllCorners {
didSet {
mkLayer.roundingCorners = roundingCorners
}
}
@IBInspectable public var rippleEnabled: Bool = true {
didSet {
mkLayer.rippleEnabled = rippleEnabled
}
}
@IBInspectable public var rippleDuration: CFTimeInterval = 0.35 {
didSet {
mkLayer.rippleDuration = rippleDuration
}
}
@IBInspectable public var rippleScaleRatio: CGFloat = 1.0 {
didSet {
mkLayer.rippleScaleRatio = rippleScaleRatio
}
}
@IBInspectable public var rippleLayerColor: UIColor = UIColor(hex: 0xEEEEEE) {
didSet {
mkLayer.setRippleColor(rippleLayerColor)
}
}
@IBInspectable public var backgroundAnimationEnabled: Bool = true {
didSet {
mkLayer.backgroundAnimationEnabled = backgroundAnimationEnabled
}
}
override public var bounds: CGRect {
didSet {
mkLayer.superLayerDidResize()
}
}
// floating label
@IBInspectable public var floatingLabelFont: UIFont = UIFont.boldSystemFontOfSize(10.0) {
didSet {
floatingLabel.font = floatingLabelFont
}
}
@IBInspectable public var floatingLabelTextColor: UIColor = UIColor.lightGrayColor() {
didSet {
floatingLabel.textColor = floatingLabelTextColor
}
}
@IBInspectable public var bottomBorderEnabled: Bool = true {
didSet {
bottomBorderLayer?.removeFromSuperlayer()
bottomBorderLayer = nil
if bottomBorderEnabled {
bottomBorderLayer = CALayer()
bottomBorderLayer?.frame = CGRect(x: 0, y: layer.bounds.height - 1, width: bounds.width, height: 1)
bottomBorderLayer?.backgroundColor = UIColor.MKColor.Grey.P500.CGColor
layer.addSublayer(bottomBorderLayer!)
}
}
}
@IBInspectable public var bottomBorderWidth: CGFloat = 1.0
@IBInspectable public var bottomBorderColor: UIColor = UIColor.lightGrayColor() {
didSet {
if bottomBorderEnabled {
bottomBorderLayer?.backgroundColor = bottomBorderColor.CGColor
}
}
}
@IBInspectable public var bottomBorderHighlightWidth: CGFloat = 1.75
override public var attributedPlaceholder: NSAttributedString? {
didSet {
updateFloatingLabelText()
}
}
private lazy var mkLayer: MKLayer = MKLayer(withView: self)
private var floatingLabel: UILabel!
private var bottomBorderLayer: CALayer?
override public init(frame: CGRect) {
super.init(frame: frame)
setupLayer()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupLayer()
}
private func setupLayer() {
mkLayer.elevation = self.elevation
self.layer.cornerRadius = self.cornerRadius
mkLayer.elevationOffset = self.shadowOffset
mkLayer.roundingCorners = self.roundingCorners
mkLayer.maskEnabled = self.maskEnabled
mkLayer.rippleScaleRatio = self.rippleScaleRatio
mkLayer.rippleDuration = self.rippleDuration
mkLayer.rippleEnabled = self.rippleEnabled
mkLayer.backgroundAnimationEnabled = self.backgroundAnimationEnabled
mkLayer.setRippleColor(self.rippleLayerColor)
layer.borderWidth = 1.0
borderStyle = .None
// floating label
floatingLabel = UILabel()
floatingLabel.font = floatingLabelFont
floatingLabel.alpha = 0.0
updateFloatingLabelText()
addSubview(floatingLabel)
}
override public func layoutSubviews() {
super.layoutSubviews()
bottomBorderLayer?.backgroundColor = isFirstResponder() ? tintColor.CGColor : bottomBorderColor.CGColor
let borderWidth = isFirstResponder() ? bottomBorderHighlightWidth : bottomBorderWidth
bottomBorderLayer?.frame = CGRect(x: 0, y: layer.bounds.height - borderWidth, width: layer.bounds.width, height: borderWidth)
if !floatingPlaceholderEnabled {
return
}
if let text = text where text.isEmpty == false {
floatingLabel.textColor = isFirstResponder() ? tintColor : floatingLabelTextColor
if floatingLabel.alpha == 0 {
showFloatingLabel()
}
} else {
hideFloatingLabel()
}
}
override public func textRectForBounds(bounds: CGRect) -> CGRect {
let rect = super.textRectForBounds(bounds)
var newRect = CGRect(x: rect.origin.x + padding.width, y: rect.origin.y,
width: rect.size.width - 2 * padding.width, height: rect.size.height)
if !floatingPlaceholderEnabled {
return newRect
}
if let text = text where text.isEmpty == false {
let dTop = floatingLabel.font.lineHeight + floatingLabelBottomMargin
newRect = UIEdgeInsetsInsetRect(newRect, UIEdgeInsets(top: dTop, left: 0.0, bottom: 0.0, right: 0.0))
}
return newRect
}
override public func editingRectForBounds(bounds: CGRect) -> CGRect {
return textRectForBounds(bounds)
}
// MARK: Touch
public override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
super.touchesBegan(touches, withEvent: event)
mkLayer.touchesBegan(touches, withEvent: event)
}
public override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
super.touchesEnded(touches, withEvent: event)
mkLayer.touchesEnded(touches, withEvent: event)
}
public override func touchesCancelled(touches: Set<UITouch>?, withEvent event: UIEvent?) {
super.touchesCancelled(touches, withEvent: event)
mkLayer.touchesCancelled(touches, withEvent: event)
}
public override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {
super.touchesMoved(touches, withEvent: event)
mkLayer.touchesMoved(touches, withEvent: event)
}
}
// MARK - private methods
private extension MKTextField {
private func setFloatingLabelOverlapTextField() {
let textRect = textRectForBounds(bounds)
var originX = textRect.origin.x
switch textAlignment {
case .Center:
originX += textRect.size.width / 2 - floatingLabel.bounds.width / 2
case .Right:
originX += textRect.size.width - floatingLabel.bounds.width
default:
break
}
floatingLabel.frame = CGRect(x: originX, y: padding.height,
width: floatingLabel.frame.size.width, height: floatingLabel.frame.size.height)
}
private func showFloatingLabel() {
let curFrame = floatingLabel.frame
floatingLabel.frame = CGRect(x: curFrame.origin.x, y: bounds.height / 2, width: curFrame.width, height: curFrame.height)
UIView.animateWithDuration(0.45, delay: 0.0, options: .CurveEaseOut,
animations: {
self.floatingLabel.alpha = 1.0
self.floatingLabel.frame = curFrame
}, completion: nil)
}
private func hideFloatingLabel() {
floatingLabel.alpha = 0.0
}
private func updateFloatingLabelText() {
floatingLabel.attributedText = attributedPlaceholder
floatingLabel.sizeToFit()
setFloatingLabelOverlapTextField()
}
}
| mit | 0e4e0f41e22cf605ce7fe6281e33a3d0 | 32.728682 | 133 | 0.64353 | 5.312576 | false | false | false | false |
wordpress-mobile/WordPress-iOS | WordPress/Classes/Networking/WordPressOrgRestApi+WordPress.swift | 2 | 1634 | import Foundation
import WordPressKit
private func makeAuthenticator(blog: Blog) -> Authenticator? {
return blog.account != nil
? makeTokenAuthenticator(blog: blog)
: makeCookieNonceAuthenticator(blog: blog)
}
private func makeTokenAuthenticator(blog: Blog) -> Authenticator? {
guard let token = blog.authToken else {
DDLogError("Failed to initialize a .com API client with blog: \(blog)")
return nil
}
return TokenAuthenticator(token: token)
}
private func makeCookieNonceAuthenticator(blog: Blog) -> Authenticator? {
guard let loginURL = try? blog.loginUrl().asURL(),
let adminURL = try? blog.adminUrl(withPath: "").asURL(),
let username = blog.username,
let password = blog.password,
let version = blog.version as String? else {
DDLogError("Failed to initialize a .org API client with blog: \(blog)")
return nil
}
return CookieNonceAuthenticator(username: username, password: password, loginURL: loginURL, adminURL: adminURL, version: version)
}
private func apiBase(blog: Blog) -> URL? {
precondition(blog.account == nil, ".com support has not been implemented yet")
return try? blog.url(withPath: "wp-json/").asURL()
}
extension WordPressOrgRestApi {
@objc public convenience init?(blog: Blog) {
guard let apiBase = apiBase(blog: blog),
let authenticator = makeAuthenticator(blog: blog) else {
return nil
}
self.init(
apiBase: apiBase,
authenticator: authenticator,
userAgent: WPUserAgent.wordPress()
)
}
}
| gpl-2.0 | 8c5ceeb7e72b1db8cbc1aecefbeae8d7 | 33.041667 | 133 | 0.660343 | 4.464481 | false | false | false | false |
jeremy-w/ImageSlicer | ImageSlicing/Job.swift | 1 | 8130 | // Copyright © 2016 Jeremy W. Sherman. Released with NO WARRANTY.
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
import Cocoa
class Job {
var imageFrom: URL?
var image: NSImage?
var cuts: [Cut]
var selections: [Mark]
var undoing: Undoing?
init(image: NSImage?, cuts: [Cut] = [], selections: [Mark] = []) {
self.image = image
self.cuts = cuts
self.selections = selections
}
func add(cut: Cut, at index: Int? = nil) {
let target = index ?? cuts.count
cuts.insert(cut, at: target)
undo(actionName: NSLocalizedString("Add Cut", comment: "job action")) {
$0.removeCut(at: target)
}
}
func remove(cut: Cut) {
guard let index = cuts.firstIndex(of: cut) else {
NSLog("%@", "\(#function): Ignoring request to remove absent cut \(cut)")
return
}
removeCut(at: index)
}
func removeCut(at index: Int) {
let cut = cuts.remove(at: index)
undo(actionName: NSLocalizedString("Delete Cut", comment: "job action")) {
$0.add(cut: cut, at: index)
}
}
func add(mark: Mark, at index: Int? = nil) {
let target = index ?? selections.count
selections.insert(mark, at: target)
undo(actionName: NSLocalizedString("Add Mark", comment: "job action")) {
$0.removeMark(at: target)
}
}
func remove(mark: Mark) {
guard let index = selections.firstIndex(of: mark) else {
NSLog("%@", "\(#function): Ignoring request to remove absent mark \(mark)")
return
}
removeMark(at: index)
}
func removeMark(at index: Int) {
let mark = selections.remove(at: index)
undo(actionName: NSLocalizedString("Delete Mark", comment: "job action")) {
$0.add(mark: mark, at: index)
}
}
var subimages: [Subimage] {
guard let image = image else {
return []
}
var subimages = [Subimage(
rect: CGRect(origin: .zero, size: image.size))]
for cut in cuts {
let at = cut.at
let index = subimages.firstIndex(where: { $0.contains(point: at) })!
let withinSubimage = subimages[index]
let children = cut.slice(subimage: withinSubimage)
subimages.replaceSubrange(index ..< (index + 1), with: children)
}
return subimages
}
func rename(mark: Mark, to name: String) {
guard let index = selections.firstIndex(of: mark) else { return }
let oldMark = selections[index]
let renamedMark = Mark(around: oldMark.around, name: name)
let markRange = index ..< (index + 1)
selections.replaceSubrange(markRange, with: [renamedMark])
let actionName = NSLocalizedString("Rename Mark", comment: "job action")
undo(actionName: actionName) {
$0.selections.replaceSubrange(markRange, with: [oldMark])
$0.undo(actionName: actionName) {
$0.selections.replaceSubrange(markRange, with: [renamedMark])
}
}
}
/// - returns: the file URLs created
func exportSelectedSubimages(directory: URL, dryRun: Bool) -> [URL] {
var created: [URL] = []
let subimages = self.subimages
selections.forEach { selection in
guard let index = subimages.firstIndex(where: { $0.contains(point: selection.around) }) else {
NSLog("%@", "\(#function): error: selection \(selection) not contained by any subimage!")
return
}
let subimage = subimages[index]
guard let bitmap = bitmapFor(subregion: subimage) else {
return
}
let fileURL = directory.appendingPathComponent("\(selection.name).png", isDirectory: false)
guard !dryRun else {
created.append(fileURL)
return
}
let data = bitmap.representation(using: .png, properties: [:])
do {
try data?.write(to: fileURL, options: .withoutOverwriting)
created.append(fileURL)
} catch {
NSLog("%@", "\(#function): error: failed writing \(String(describing: data?.count)) bytes to file \(fileURL.absoluteURL.path): \(error)")
}
}
NSLog("%@", "created: \(created)")
return created
}
func bitmapFor(subregion: Subimage) -> NSBitmapImageRep? {
guard let image = image else {
return nil
}
let subregion = subregion.rect.integral
let size = subregion.size
guard let bitmap = NSBitmapImageRep(
bitmapDataPlanes: nil,
pixelsWide: Int(subregion.size.width), pixelsHigh: Int(subregion.size.height),
bitsPerSample: 8, samplesPerPixel: 4,
hasAlpha: true, isPlanar: false,
colorSpaceName: .calibratedRGB,
bytesPerRow: 4*Int(subregion.size.width), bitsPerPixel: 32) else {
NSLog("%@", "\(#function): error: failed to create bitmap image rep")
return nil
}
let bitmapContext = NSGraphicsContext(bitmapImageRep: bitmap)
let old = NSGraphicsContext.current
NSGraphicsContext.saveGraphicsState()
NSGraphicsContext.current = bitmapContext
let target = CGRect(origin: .zero, size: size)
image.draw(
in: target,
from: subregion,
operation: .copy,
fraction: 1.0,
respectFlipped: true, hints: nil)
NSGraphicsContext.current = old
NSGraphicsContext.restoreGraphicsState()
return bitmap
}
}
// MARK: - Undo
extension Job {
func undo(actionName: String, closure: @escaping (Job) -> Void) {
guard let undoing = undoing else { return }
undoing.record(actionName: actionName) { [weak self] in
guard let me = self else { return }
closure(me)
}
}
}
// MARK: - De/Serialization
extension Job {
class Keys {
static let From = "from"
static let Image = "image"
static let Cuts = "cuts"
static let Selections = "selections"
}
var asDictionary: [String: AnyObject] {
var dictionary: [String: AnyObject] = [:]
if let imageFrom = imageFrom {
dictionary[Keys.From] = imageFrom as AnyObject
}
if let image = image {
dictionary[Keys.Image] = image
}
dictionary[Keys.Cuts] = cuts.map { $0.asDictionary } as AnyObject
dictionary[Keys.Selections] = selections.map { $0.asDictionary } as AnyObject
NSLog("%@", "\(#function): pickled \(self): \(dictionary)")
return dictionary
}
convenience init?(dictionary: [String: AnyObject]) {
NSLog("%@", "\(#function): unpickling: \(dictionary)")
let from = dictionary[Keys.From] as? URL
var image: NSImage? = nil
if let mustBeNSImageIfPresent = dictionary[Keys.Image] {
guard let validImage = mustBeNSImageIfPresent as? NSImage else {
return nil
}
image = validImage
}
guard let cutDicts = dictionary[Keys.Cuts] as? [[String: AnyObject]] else {
return nil
}
let cuts = cutDicts.compactMap { Cut(dictionary: $0) }
guard cuts.count == cutDicts.count else {
return nil
}
guard let selectionDicts = dictionary[Keys.Selections] as? [[String: AnyObject]] else {
return nil
}
let selections = selectionDicts.compactMap { Mark(dictionary: $0) }
guard selections.count == selectionDicts.count else {
return nil
}
self.init(image: image, cuts: cuts, selections: selections)
self.imageFrom = from
}
}
| mpl-2.0 | f1271ddaf11cf18e70e0ce598c81024e | 31.130435 | 153 | 0.570058 | 4.554062 | false | false | false | false |
thiagolioy/Notes | Tests/MixolydianModeSpec.swift | 1 | 11951 | //
// MixolydianModeSpec.swift
// Notes
//
// Created by Thiago Lioy on 03/09/17.
// Copyright © 2017 com.tplioy. All rights reserved.
//
import Foundation
import Quick
import Nimble
@testable import Notes
class MixolydianModeSpec: QuickSpec {
override func spec() {
describe("Mixolydian Mode") {
var mode: MixolydianMode!
beforeEach {
mode = MixolydianMode(key: Note(name: .C, intonation: .natural))
}
it("should have the expected names") {
expect(mode.names.first!).to(equal("Mixolydian Mode"))
}
it("should have the expected intervals") {
expect(mode.intervals).to(equal([
.wholestep,.wholestep,.halfstep,
.wholestep,.wholestep,.halfstep,
.wholestep
]))
}
context("C natural") {
it("should have the expected notes in key of C Natural") {
let key = Note(name: .C, intonation: .natural)
let notes = MixolydianMode(key: key).scaleNotes()
expect(notes).to(equal([
Note(name: .C, intonation: .natural),
Note(name: .D, intonation: .natural),
Note(name: .E, intonation: .natural),
Note(name: .F, intonation: .natural),
Note(name: .G, intonation: .natural),
Note(name: .A, intonation: .natural),
Note(name: .B, intonation: .flat),
Note(name: .C, intonation: .natural)
]))
}
}
context("G natural") {
it("should have the expected notes in key of G Natural") {
let key = Note(name: .G, intonation: .natural)
let notes = MixolydianMode(key: key).scaleNotes()
expect(notes).to(equal([
Note(name: .G, intonation: .natural),
Note(name: .A, intonation: .natural),
Note(name: .B, intonation: .natural),
Note(name: .C, intonation: .natural),
Note(name: .D, intonation: .natural),
Note(name: .E, intonation: .natural),
Note(name: .F, intonation: .natural),
Note(name: .G, intonation: .natural)
]))
}
}
context("D natural") {
it("should have the expected notes in key of D Natural") {
let key = Note(name: .D, intonation: .natural)
let notes = MixolydianMode(key: key).scaleNotes()
expect(notes).to(equal([
Note(name: .D, intonation: .natural),
Note(name: .E, intonation: .natural),
Note(name: .F, intonation: .sharp),
Note(name: .G, intonation: .natural),
Note(name: .A, intonation: .natural),
Note(name: .B, intonation: .natural),
Note(name: .C, intonation: .natural),
Note(name: .D, intonation: .natural)
]))
}
}
context("A natural") {
it("should have the expected notes in key of A Natural") {
let key = Note(name: .A, intonation: .natural)
let notes = MixolydianMode(key: key).scaleNotes()
expect(notes).to(equal([
Note(name: .A, intonation: .natural),
Note(name: .B, intonation: .natural),
Note(name: .C, intonation: .sharp),
Note(name: .D, intonation: .natural),
Note(name: .E, intonation: .natural),
Note(name: .F, intonation: .sharp),
Note(name: .G, intonation: .natural),
Note(name: .A, intonation: .natural)
]))
}
}
context("E natural") {
it("should have the expected notes in key of E Natural") {
let key = Note(name: .E, intonation: .natural)
let notes = MixolydianMode(key: key).scaleNotes()
expect(notes).to(equal([
Note(name: .E, intonation: .natural),
Note(name: .F, intonation: .sharp),
Note(name: .G, intonation: .sharp),
Note(name: .A, intonation: .natural),
Note(name: .B, intonation: .natural),
Note(name: .C, intonation: .sharp),
Note(name: .D, intonation: .natural),
Note(name: .E, intonation: .natural)
]))
}
}
context("B natural") {
it("should have the expected notes in key of B Natural") {
let key = Note(name: .B, intonation: .natural)
let notes = MixolydianMode(key: key).scaleNotes()
expect(notes).to(equal([
Note(name: .B, intonation: .natural),
Note(name: .C, intonation: .sharp),
Note(name: .D, intonation: .sharp),
Note(name: .E, intonation: .natural),
Note(name: .F, intonation: .sharp),
Note(name: .G, intonation: .sharp),
Note(name: .A, intonation: .natural),
Note(name: .B, intonation: .natural)
]))
}
}
context("F sharp") {
it("should have the expected notes") {
let key = Note(name: .F, intonation: .sharp)
let notes = MixolydianMode(key: key).scaleNotes()
expect(notes).to(equal([
Note(name: .F, intonation: .sharp),
Note(name: .G, intonation: .sharp),
Note(name: .A, intonation: .sharp),
Note(name: .B, intonation: .natural),
Note(name: .C, intonation: .sharp),
Note(name: .D, intonation: .sharp),
Note(name: .E, intonation: .natural),
Note(name: .F, intonation: .sharp)
]))
}
}
context("G flat") {
it("should have the expected notes") {
let key = Note(name: .G, intonation: .flat)
let notes = MixolydianMode(key: key).scaleNotes()
expect(notes).to(equal([
Note(name: .G, intonation: .flat),
Note(name: .A, intonation: .flat),
Note(name: .B, intonation: .flat),
Note(name: .C, intonation: .flat),
Note(name: .D, intonation: .flat),
Note(name: .E, intonation: .flat),
Note(name: .F, intonation: .flat),
Note(name: .G, intonation: .flat)
]))
}
}
context("D flat") {
it("should have the expected notes") {
let key = Note(name: .D, intonation: .flat)
let notes = MixolydianMode(key: key).scaleNotes()
expect(notes).to(equal([
Note(name: .D, intonation: .flat),
Note(name: .E, intonation: .flat),
Note(name: .F, intonation: .natural),
Note(name: .G, intonation: .flat),
Note(name: .A, intonation: .flat),
Note(name: .B, intonation: .flat),
Note(name: .C, intonation: .flat),
Note(name: .D, intonation: .flat)
]))
}
}
context("A flat") {
it("should have the expected notes") {
let key = Note(name: .A, intonation: .flat)
let notes = MixolydianMode(key: key).scaleNotes()
expect(notes).to(equal([
Note(name: .A, intonation: .flat),
Note(name: .B, intonation: .flat),
Note(name: .C, intonation: .natural),
Note(name: .D, intonation: .flat),
Note(name: .E, intonation: .flat),
Note(name: .F, intonation: .natural),
Note(name: .G, intonation: .flat),
Note(name: .A, intonation: .flat)
]))
}
}
context("E flat") {
it("should have the expected notes") {
let key = Note(name: .E, intonation: .flat)
let notes = MixolydianMode(key: key).scaleNotes()
expect(notes).to(equal([
Note(name: .E, intonation: .flat),
Note(name: .F, intonation: .natural),
Note(name: .G, intonation: .natural),
Note(name: .A, intonation: .flat),
Note(name: .B, intonation: .flat),
Note(name: .C, intonation: .natural),
Note(name: .D, intonation: .flat),
Note(name: .E, intonation: .flat)
]))
}
}
context("B flat") {
it("should have the expected notes") {
let key = Note(name: .B, intonation: .flat)
let notes = MixolydianMode(key: key).scaleNotes()
expect(notes).to(equal([
Note(name: .B, intonation: .flat),
Note(name: .C, intonation: .natural),
Note(name: .D, intonation: .natural),
Note(name: .E, intonation: .flat),
Note(name: .F, intonation: .natural),
Note(name: .G, intonation: .natural),
Note(name: .A, intonation: .flat),
Note(name: .B, intonation: .flat)
]))
}
}
context("F natural") {
it("should have the expected notes") {
let key = Note(name: .F, intonation: .natural)
let notes = MixolydianMode(key: key).scaleNotes()
expect(notes).to(equal([
Note(name: .F, intonation: .natural),
Note(name: .G, intonation: .natural),
Note(name: .A, intonation: .natural),
Note(name: .B, intonation: .flat),
Note(name: .C, intonation: .natural),
Note(name: .D, intonation: .natural),
Note(name: .E, intonation: .flat),
Note(name: .F, intonation: .natural)
]))
}
}
}
}
}
| mit | 5b635c90bc99b804db0358c1549afb25 | 43.259259 | 80 | 0.403347 | 5.070004 | false | false | false | false |
hollance/swift-algorithm-club | Points Lines Planes/Points Lines Planes/2D/Line2D.swift | 2 | 5272 | //
// Line2D.swift
// Points Lines Planes
//
// Created by Jaap Wijnen on 24-10-17.
//
struct Line2D: Equatable {
var slope: Slope
var offset: Double
var direction: Direction
enum Slope: Equatable {
case finite(slope: Double)
case infinite(offset: Double)
}
enum Direction: Equatable {
case increasing
case decreasing
}
init(from p1: Point2D, to p2: Point2D) {
if p1 == p2 { fatalError("Points can not be equal when creating a line between them") }
if p1.x == p2.x {
self.slope = .infinite(offset: p1.x)
self.offset = 0
self.direction = p1.y < p2.y ? .increasing : .decreasing
return
}
let slope = (p1.y - p2.y)/(p1.x - p2.x)
self.slope = .finite(slope: slope)
offset = (p1.y + p2.y - slope * (p1.x + p2.x))/2
if slope >= 0 {
// so a horizontal line going left to right is called increasing
self.direction = p1.x < p2.x ? .increasing : .decreasing
} else {
self.direction = p1.x < p2.x ? .decreasing : .increasing
}
}
fileprivate init(slope: Slope, offset: Double, direction: Direction) {
self.slope = slope
self.offset = offset
self.direction = direction
}
// returns y coordinate on line for given x
func y(at x: Double) -> Double {
switch self.slope {
case .finite(let slope):
return slope * x + self.offset
case .infinite:
fatalError("y can be anywhere on vertical line")
}
}
// returns x coordinate on line for given y
func x(at y: Double) -> Double {
switch self.slope {
case .finite(let slope):
if slope == 0 {
fatalError("x can be anywhere on horizontal line")
}
return (y - self.offset)/slope
case .infinite(let offset):
return offset
}
}
// finds intersection point between two lines. returns nil when lines don't intersect or lie on top of each other.
func intersect(with line: Line2D) -> Point2D? {
if self == line { return nil }
switch (self.slope, line.slope) {
case (.infinite, .infinite):
// lines are either parallel or on top of each other.
return nil
case (.finite(let slope1), .finite(let slope2)):
if slope1 == slope2 { return nil } // lines are parallel
// lines are not parallel calculate intersection point
let x = (line.offset - self.offset)/(slope1 - slope2)
let y = (slope1 + slope2) * x + self.offset + line.offset
return Point2D(x: x, y: y)
case (.infinite(let offset), .finite):
// one line is vertical so we only check what y value the other line has at that point
let x = offset
let y = line.y(at: x)
return Point2D(x: x, y: y)
case (.finite, .infinite(let offset)):
// one line is vertical so we only check what y value the other line has at that point
// lines are switched with respect to case above this one
let x = offset
let y = self.y(at: x)
return Point2D(x: x, y: y)
}
}
// returns a line perpendicular to self at the given y coordinate
// direction of perpendicular lines always changes clockwise
func perpendicularLineAt(y: Double) -> Line2D {
return perpendicularLineAt(p: Point2D(x: self.x(at: y), y: y))
}
// returns a line perpendicular to self at the given x coordinate
// direction of perpendicular lines always changes clockwise
func perpendicularLineAt(x: Double) -> Line2D {
return perpendicularLineAt(p: Point2D(x: x, y: self.y(at: x)))
}
private func perpendicularLineAt(p: Point2D) -> Line2D {
switch self.slope {
case .finite(let slope):
if slope == 0 {
// line is horizontal so new line will be vertical
let dir: Direction = self.direction == .increasing ? .decreasing : .increasing
return Line2D(slope: .infinite(offset: p.x), offset: 0, direction: dir)
}
// line is neither horizontal nor vertical
// we make a new line through the point p with new slope -1/slope
let offset = (slope + 1/slope)*p.x + self.offset
// determine direction of new line based on direction of the old line and its slope
let dir: Direction
switch self.direction {
case .increasing:
dir = slope > 0 ? .decreasing : .increasing
case .decreasing:
dir = slope > 0 ? .increasing : .decreasing
}
return Line2D(slope: .finite(slope: -1/slope), offset: offset, direction: dir)
case .infinite:
// line is vertical so new line will be horizontal
let dir: Direction = self.direction == .increasing ? .increasing : .decreasing
return Line2D(slope: .finite(slope: 0), offset: p.y, direction: dir)
}
}
}
| mit | c91853b6fb32c485370fc4650788a628 | 36.390071 | 118 | 0.559939 | 4.204147 | false | false | false | false |
Praesentia/MedKit-Swift | Source/LocationController.swift | 1 | 4034 | /*
-----------------------------------------------------------------------------
This source file is part of MedKit.
Copyright 2017-2018 Jon Griffeth
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
public class LocationController: ResourceController, ResourceObserver {
public typealias Value = LocationProtocolV1.Value
// MARK: - Properties
public weak var delegate : LocationControllerDelegate?
public private(set) var location : Value
public private(set) var timeModified : TimeInterval
// MARK: - Private
private typealias LocationProtocol = LocationProtocolV1
private typealias Notification = LocationProtocolV1.Notification
// MARK: - Initialiers
/**
Initialize instance.
*/
override public init(for resource: Resource)
{
location = Value()
timeModified = 0
super.init(for: resource)
}
// MARK: - ResourceController
override public func start()
{
resource.addObserver(self) { error in
self.delegate?.locationControllerDidStart(self)
}
}
override public func stop()
{
resource.removeObserver(self) { error in
self.delegate?.locationController(self, didStopForReason: error)
}
}
// MARK: - Value Management
public func readValue(completionHandler completion: @escaping (Error?) -> Void)
{
let message = LocationProtocol.Method.ReadValue()
resource.call(message: message) { reply, error in
if error == nil, let reply = reply {
do {
let update = try reply.decode(LocationProtocol.Method.ReadValue.Reply.self)
self.location = update.value
self.timeModified = update.time.timeInterval
}
catch {
}
}
completion(error)
}
}
public func writeValue(location: Value, completionHandler completion: @escaping (Error?) -> Void)
{
let message = LocationProtocol.Method.WriteValue(args: location)
resource.call(message: message) { reply, error in
if error == nil, let reply = reply {
do {
let update = try reply.decode(LocationProtocol.Method.WriteValue.Reply.self)
self.location = update.value
self.timeModified = update.time.timeInterval
}
catch {
}
}
completion(error)
}
}
// MARK: - ResourceObserver
/**
Decode resource notifications.
- Parameters:
- resource:
- decoder:
*/
public func resource(_ resource: Resource, didNotify notification: AnyCodable)
{
do {
let container = try notification.decoder.container(keyedBy: Notification.CodingKeys.self)
let type = try container.decode(Notification.NotificationType.self, forKey: .type)
switch type {
case .didUpdate :
let update = try container.decode(Notification.DidUpdate.Args.self, forKey: .args)
location = update.value
timeModified = update.time.timeInterval
delegate?.locationControllerDidUpdate(self)
}
}
catch {
}
}
}
// End of File
| apache-2.0 | 29561aa1984bfdd8fc84642ca7db8b8b | 26.256757 | 101 | 0.579574 | 5.232166 | false | false | false | false |
ResearchSuite/ResearchSuiteAppFramework-iOS | Source/Core/Classes/RSAFActivityTableViewCell.swift | 1 | 1094 | //
// RSAFActivityTableViewCell.swift
// Pods
//
// Created by James Kizer on 3/28/17.
//
//
import UIKit
open class RSAFActivityTableViewCell: UITableViewCell {
@IBOutlet weak var uncheckedView: UIView!
@IBOutlet weak var checkmarkImageView: UIImageView!
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var subtitleLabel: UILabel!
@IBOutlet weak var timeLabel: UILabel?
var complete: Bool = false {
didSet {
self.uncheckedView.isHidden = complete
self.checkmarkImageView.isHidden = !complete
}
}
override open func layoutSubviews() {
super.layoutSubviews()
self.uncheckedView.layer.borderColor = UIColor.lightGray.cgColor
self.uncheckedView.layer.borderWidth = 1
self.uncheckedView.layer.cornerRadius = self.uncheckedView.bounds.size.height / 2
self.timeLabel?.textColor = self.tintColor
}
override open func tintColorDidChange() {
super.tintColorDidChange()
self.timeLabel?.textColor = self.tintColor
}
}
| apache-2.0 | 35bceb7f4178df1ef3226c39b16c51d7 | 25.682927 | 89 | 0.664534 | 4.950226 | false | false | false | false |
acumenrev/CANNavApp | CANNavApp/CANNavApp/Classes/TUtilsSwift.swift | 1 | 3015 | //
// TUtilsSwift.swift
// dotabuff
//
// Created by Tri Vo on 6/25/16.
// Copyright © 2016 acumen. All rights reserved.
//
import UIKit
import CocoaLumberjack
class TUtilsSwift: NSObject {
enum TLogLevel {
case DEBUG
case INFO
case WARN
case VERBOSE
}
/**
Checks string is NULL
- parameter value: String value need to be checked
- returns: return true
*/
static func checkNullString(value : String?) -> String {
if value == nil {
return ""
}
if TUtilsSwift.checkStringNullOrEmpty(value) == true {
return ""
}
return value!
}
/**
Check string NULL or EMPTY
- parameter value: String balue need to be checked
- returns: true if value is null or empty
*/
static func checkStringNullOrEmpty(value : String?) -> Bool {
if value == nil {
return true
}
if value!.isEmpty {
return true
}
let newValue = value!.stringByReplacingOccurrencesOfString(" ", withString: "")
if newValue.isEmpty {
return true
}
return false
}
/**
Save image data to local disk
- parameter imgData: Image Data
- parameter filePath: file path
- returns: true if everything goes ok
*/
static func saveImageToLocalDisk(imgData : UIImage, filePath : String) -> Bool {
let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as String
let filePathWithFileName = paths.stringByAppendingString(filePath)
let fileManager = NSFileManager.defaultManager()
if fileManager.fileExistsAtPath(filePathWithFileName) == false {
// create file
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), {
UIImagePNGRepresentation(imgData)?.writeToFile(filePathWithFileName, atomically: true)
})
}
return true
}
/**
Log
- parameter stringValue: String value need to be logged
- parameter logLevel: Log Level
*/
static func log(stringValue : String, logLevel : TLogLevel) -> Void {
switch logLevel {
case .DEBUG:
DDLogDebug(stringValue)
break
case .VERBOSE:
DDLogVerbose(stringValue)
break
case .INFO:
DDLogInfo(stringValue)
break
case .WARN:
DDLogWarn(stringValue)
break
default:
DDLogDebug(stringValue)
break
}
}
/**
Get AppDelegate instance
- returns: AppDelegate instance
*/
static func appDelegate() -> AppDelegate {
return (UIApplication.sharedApplication().delegate as! AppDelegate)
}
}
| apache-2.0 | c94324b37182a9da68185794c1bc2dfb | 23.704918 | 111 | 0.557731 | 5.420863 | false | false | false | false |
atrick/swift | test/Interop/Cxx/class/nested-records-module-interface.swift | 5 | 2398 | // RUN: %target-swift-ide-test -print-module -module-to-print=NestedRecords -I %S/Inputs -source-filename=x -enable-experimental-cxx-interop | %FileCheck %s
// CHECK: struct S1 {
// CHECK: struct S2 {
// CHECK: var A: Bool
// CHECK: }
// CHECK: }
// CHECK: struct S3 {
// CHECK: struct S4 {
// CHECK: }
// CHECK: }
// CHECK: struct U1 {
// CHECK: struct U2 {
// CHECK: }
// CHECK: }
// CHECK: struct U3 {
// CHECK: struct E1 : Equatable, RawRepresentable {
// CHECK: typealias RawValue = {{UInt32|Int32}}
// CHECK: }
// CHECK: }
// CHECK: struct U4 {
// CHECK: struct S5 {
// CHECK: }
// CHECK: }
// CHECK: struct S6 {
// CHECK: init()
// CHECK: struct E3 : Equatable, RawRepresentable {
// CHECK: typealias RawValue = {{UInt32|Int32}}
// CHECK: }
// CHECK: }
// CHECK: struct S7 {
// CHECK: struct U5 {
// CHECK: struct U6 {
// CHECK: }
// CHECK: }
// CHECK: }
// CHECK: struct S8 {
// CHECK: struct S9 {
// CHECK: struct U7 {
// CHECK: }
// CHECK: }
// CHECK: }
// CHECK: struct S10 {
// CHECK: struct U8 {
// CHECK: struct E4 : Equatable, RawRepresentable {
// CHECK: typealias RawValue = {{UInt32|Int32}}
// CHECK: }
// CHECK: }
// CHECK: }
// CHECK: struct HasForwardDeclaredNestedType {
// CHECK: init()
// CHECK: struct ForwardDeclaredType {
// CHECK: init()
// CHECK: }
// CHECK: struct NormalSubType {
// CHECK: init()
// CHECK: }
// CHECK: }
// CHECK: struct HasForwardDeclaredTemplateChild {
// CHECK: init()
// CHECK: struct ForwardDeclaredClassTemplate<T> {
// CHECK: }
// CHECK: struct DeclaresForwardDeclaredClassTemplateFriend {
// CHECK: init()
// CHECK: }
// CHECK: }
// CHECK: enum NestedDeclIsAFirstForwardDeclaration {
// CHECK: struct ForwardDeclaresFriend {
// CHECK: init()
// CHECK: }
// CHECK: struct ForwardDeclaredFriend {
// CHECK: init()
// CHECK: }
// CHECK: static func takesFriend(_ f: NestedDeclIsAFirstForwardDeclaration.ForwardDeclaredFriend)
// CHECK: struct HasNestedForwardDeclaration {
// CHECK: init()
// CHECK: struct IsNestedForwardDeclaration {
// CHECK: init()
// CHECK: init(a: Int32)
// CHECK: var a: Int32
// CHECK: }
// CHECK: }
// CHECK: static func takesHasNestedForwardDeclaration(_: NestedDeclIsAFirstForwardDeclaration.HasNestedForwardDeclaration)
// CHECK: }
| apache-2.0 | 1106ed2768ee7284f78addea037670a7 | 24.242105 | 156 | 0.610926 | 3.244926 | false | false | false | false |
breadwallet/breadwallet-ios | breadwalletTests/RequestUrlTests.swift | 1 | 3825 | //
// RequestUrlTests.swift
// breadwalletTests
//
// Created by Adrian Corscadden on 2019-10-06.
// Copyright © 2019 Breadwinner AG. All rights reserved.
//
// See the LICENSE file at the project root for license information.
//
import XCTest
@testable import breadwallet
class RequestUrlTests : XCTestCase {
//MARK: Without Amounts
func testBTCLegacyUri() {
let address = "12A1MyfXbW6RhdRAZEqofac5jCQQjwEPBu"
let uri = TestCurrencies.btc.addressURI(address)
XCTAssertNotNil(uri)
XCTAssertEqual(uri, "bitcoin:12A1MyfXbW6RhdRAZEqofac5jCQQjwEPBu")
}
func testBTCSegwitUri() {
let address = "bc1qgu4y0m03kerspt2vzgr8aysplxvuasrxpyejer"
let uri = TestCurrencies.btc.addressURI(address)
XCTAssertNotNil(uri)
XCTAssertEqual(uri, "bitcoin:bc1qgu4y0m03kerspt2vzgr8aysplxvuasrxpyejer")
}
func testBCHUri() {
let address = "qr2g8fyjy0csdujuxcg02syrp5eaqgtn9ytlk3650u"
let uri = TestCurrencies.bch.addressURI(address)
XCTAssertNotNil(uri)
XCTAssertEqual(uri, "bitcoincash:qr2g8fyjy0csdujuxcg02syrp5eaqgtn9ytlk3650u")
}
func testEthUri() {
let address = "0xbDFdAd139440D2Db9BA2aa3B7081C2dE39291508"
let uri = TestCurrencies.eth.addressURI(address)
XCTAssertNotNil(uri)
XCTAssertEqual(uri, "ethereum:0xbDFdAd139440D2Db9BA2aa3B7081C2dE39291508")
}
func testTokenUri() {
let address = "0xbDFdAd139440D2Db9BA2aa3B7081C2dE39291508"
let uri = TestCurrencies.brd.addressURI(address)
XCTAssertNotNil(uri)
XCTAssertEqual(uri, "ethereum:0xbDFdAd139440D2Db9BA2aa3B7081C2dE39291508?tokenaddress=0x558ec3152e2eb2174905cd19aea4e34a23de9ad6")
}
//MARK: With Amounts
func testBTCLegacyUriWithAmount() {
let address = "12A1MyfXbW6RhdRAZEqofac5jCQQjwEPBu"
let amount = Amount(tokenString: "1", currency: TestCurrencies.btc)
let uri = PaymentRequest.requestString(withAddress: address, forAmount: amount)
XCTAssertNotNil(uri)
XCTAssertEqual(uri, "bitcoin:12A1MyfXbW6RhdRAZEqofac5jCQQjwEPBu?amount=1")
}
func testBTCSegwitUriWithAmount() {
let address = "bc1qgu4y0m03kerspt2vzgr8aysplxvuasrxpyejer"
let amount = Amount(tokenString: "1", currency: TestCurrencies.btc)
let uri = PaymentRequest.requestString(withAddress: address, forAmount: amount)
XCTAssertNotNil(uri)
XCTAssertEqual(uri, "bitcoin:bc1qgu4y0m03kerspt2vzgr8aysplxvuasrxpyejer?amount=1")
}
func testBCHUriWithAmount() {
let address = "qr2g8fyjy0csdujuxcg02syrp5eaqgtn9ytlk3650u"
let amount = Amount(tokenString: "1", currency: TestCurrencies.bch)
let uri = PaymentRequest.requestString(withAddress: address, forAmount: amount)
XCTAssertNotNil(uri)
XCTAssertEqual(uri, "bitcoincash:qr2g8fyjy0csdujuxcg02syrp5eaqgtn9ytlk3650u?amount=1")
}
func testEthUriWithAmount() {
let address = "0xbDFdAd139440D2Db9BA2aa3B7081C2dE39291508"
let amount = Amount(tokenString: "1", currency: TestCurrencies.eth)
let uri = PaymentRequest.requestString(withAddress: address, forAmount: amount)
XCTAssertNotNil(uri)
XCTAssertEqual(uri, "ethereum:0xbDFdAd139440D2Db9BA2aa3B7081C2dE39291508?amount=1")
}
func testTokenUriWithAmount() {
let address = "0xbDFdAd139440D2Db9BA2aa3B7081C2dE39291508"
let amount = Amount(tokenString: "1", currency: TestCurrencies.brd)
let uri = PaymentRequest.requestString(withAddress: address, forAmount: amount)
XCTAssertNotNil(uri)
XCTAssertEqual(uri, "ethereum:0xbDFdAd139440D2Db9BA2aa3B7081C2dE39291508?tokenaddress=0x558ec3152e2eb2174905cd19aea4e34a23de9ad6&amount=1")
}
}
| mit | e34648c79d3aec7217df42fce03f0e45 | 40.11828 | 147 | 0.721496 | 3.470054 | false | true | false | false |
tbkka/swift-protobuf | Sources/SwiftProtobuf/Google_Protobuf_Any+Extensions.swift | 3 | 5334 | // Sources/SwiftProtobuf/Google_Protobuf_Any+Extensions.swift - Well-known Any type
//
// Copyright (c) 2014 - 2017 Apple Inc. and the project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See LICENSE.txt for license information:
// https://github.com/apple/swift-protobuf/blob/master/LICENSE.txt
//
// -----------------------------------------------------------------------------
///
/// Extends the `Google_Protobuf_Any` type with various custom behaviors.
///
// -----------------------------------------------------------------------------
// Explicit import of Foundation is necessary on Linux,
// don't remove unless obsolete on all platforms
import Foundation
public let defaultAnyTypeURLPrefix: String = "type.googleapis.com"
extension Google_Protobuf_Any {
/// Initialize an Any object from the provided message.
///
/// This corresponds to the `pack` operation in the C++ API.
///
/// Unlike the C++ implementation, the message is not immediately
/// serialized; it is merely stored until the Any object itself
/// needs to be serialized. This design avoids unnecessary
/// decoding/recoding when writing JSON format.
///
/// - Parameters:
/// - partial: If `false` (the default), this method will check
/// `Message.isInitialized` before encoding to verify that all required
/// fields are present. If any are missing, this method throws
/// `BinaryEncodingError.missingRequiredFields`.
/// - typePrefix: The prefix to be used when building the `type_url`.
/// Defaults to "type.googleapis.com".
/// - Throws: `BinaryEncodingError.missingRequiredFields` if `partial` is
/// false and `message` wasn't fully initialized.
public init(
message: Message,
partial: Bool = false,
typePrefix: String = defaultAnyTypeURLPrefix
) throws {
if !partial && !message.isInitialized {
throw BinaryEncodingError.missingRequiredFields
}
self.init()
typeURL = buildTypeURL(forMessage:message, typePrefix: typePrefix)
_storage.state = .message(message)
}
/// Creates a new `Google_Protobuf_Any` by decoding the given string
/// containing a serialized message in Protocol Buffer text format.
///
/// - Parameters:
/// - textFormatString: The text format string to decode.
/// - extensions: An `ExtensionMap` used to look up and decode any
/// extensions in this message or messages nested within this message's
/// fields.
/// - Throws: an instance of `TextFormatDecodingError` on failure.
public init(
textFormatString: String,
extensions: ExtensionMap? = nil
) throws {
self.init()
if !textFormatString.isEmpty {
if let data = textFormatString.data(using: String.Encoding.utf8) {
try data.withUnsafeBytes { (body: UnsafeRawBufferPointer) in
if let baseAddress = body.baseAddress, body.count > 0 {
var textDecoder = try TextFormatDecoder(
messageType: Google_Protobuf_Any.self,
utf8Pointer: baseAddress,
count: body.count,
extensions: extensions)
try decodeTextFormat(decoder: &textDecoder)
if !textDecoder.complete {
throw TextFormatDecodingError.trailingGarbage
}
}
}
}
}
}
/// Returns true if this `Google_Protobuf_Any` message contains the given
/// message type.
///
/// The check is performed by looking at the passed `Message.Type` and the
/// `typeURL` of this message.
///
/// - Parameter type: The concrete message type.
/// - Returns: True if the receiver contains the given message type.
public func isA<M: Message>(_ type: M.Type) -> Bool {
return _storage.isA(type)
}
#if swift(>=4.2)
public func hash(into hasher: inout Hasher) {
_storage.hash(into: &hasher)
}
#else // swift(>=4.2)
public var hashValue: Int {
return _storage.hashValue
}
#endif // swift(>=4.2)
}
extension Google_Protobuf_Any {
internal func textTraverse(visitor: inout TextFormatEncodingVisitor) {
_storage.textTraverse(visitor: &visitor)
try! unknownFields.traverse(visitor: &visitor)
}
}
extension Google_Protobuf_Any: _CustomJSONCodable {
// Custom text format decoding support for Any objects.
// (Note: This is not a part of any protocol; it's invoked
// directly from TextFormatDecoder whenever it sees an attempt
// to decode an Any object)
internal mutating func decodeTextFormat(
decoder: inout TextFormatDecoder
) throws {
// First, check if this uses the "verbose" Any encoding.
// If it does, and we have the type available, we can
// eagerly decode the contained Message object.
if let url = try decoder.scanner.nextOptionalAnyURL() {
try _uniqueStorage().decodeTextFormat(typeURL: url, decoder: &decoder)
} else {
// This is not using the specialized encoding, so we can use the
// standard path to decode the binary value.
try decodeMessage(decoder: &decoder)
}
}
internal func encodedJSONString(options: JSONEncodingOptions) throws -> String {
return try _storage.encodedJSONString(options: options)
}
internal mutating func decodeJSON(from decoder: inout JSONDecoder) throws {
try _uniqueStorage().decodeJSON(from: &decoder)
}
}
| apache-2.0 | cd300e698fc7a09c3e75e720e9b838bd | 36.300699 | 83 | 0.664792 | 4.562874 | false | false | false | false |
codefellows/sea-d34-iOS | Sample Code/Week 3/GithubToGo/GithubToGo/GithubService.swift | 1 | 2452 | //
// GithubService.swift
// GithubToGo
//
// Created by Bradley Johnson on 4/13/15.
// Copyright (c) 2015 BPJ. All rights reserved.
//
import Foundation
class GithubService : NSObject, NSURLSessionDataDelegate {
static let sharedInstance : GithubService = GithubService()
let githubSearchRepoURL = "https://api.github.com/search/repositories"
let localURL = "http://127.0.0.1:3000"
func fetchReposForSearch(searchTerm : String, completionHandler : ( [Repository]?, String?) ->(Void)) {
let queryString = "?q=\(searchTerm)"
let requestURL = githubSearchRepoURL + queryString
let url = NSURL(string: requestURL)
let request = NSMutableURLRequest(URL: url!)
if let token = NSUserDefaults.standardUserDefaults().objectForKey("githubToken") as? String {
request.setValue("token \(token)", forHTTPHeaderField: "Authorization")
}
let dataTask = NSURLSession.sharedSession().dataTaskWithRequest(request, completionHandler: { (data, response, error) -> Void in
if let httpResponse = response as? NSHTTPURLResponse {
println(httpResponse.statusCode)
if httpResponse.statusCode == 200 {
let repos = RepoJSONParser.reposFromJSONData(data)
NSOperationQueue.mainQueue().addOperationWithBlock({ () -> Void in
completionHandler(repos,nil)
})
}
}
//this is our callback
})
dataTask.resume()
}
func fetchUsersForSearch(search : String, completionHandler : ([User]?, String?) -> (Void)) {
let searchURL = "https://api.github.com/search/users?q="
let url = searchURL + search
let request = NSMutableURLRequest(URL: NSURL(string: url)!)
if let token = NSUserDefaults.standardUserDefaults().objectForKey("githubToken") as? String {
request.setValue("token \(token)", forHTTPHeaderField: "Authorization")
}
let dataTask = NSURLSession.sharedSession().dataTaskWithRequest(request, completionHandler: { (data, response, error) -> Void in
let users = UserJSONParser.usersFromJSONData(data)
NSOperationQueue.mainQueue().addOperationWithBlock({ () -> Void in
println("hi")
completionHandler(users,nil)
})
// NSOperationQueue.mainQueue().addOperationWithBlock({ () -> Void in
//
// completionHandler(users, nil)
// })
})
dataTask.resume()
}
}
| mit | eb64d8c300f36e060abaedd8d27d8df8 | 31.693333 | 132 | 0.654976 | 4.884462 | false | false | false | false |
kesun421/firefox-ios | Client/Frontend/Browser/ClipboardBarDisplayHandler.swift | 1 | 6114 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import Shared
public struct ClipboardBarToastUX {
static let ToastDelay = DispatchTimeInterval.milliseconds(4000)
}
protocol ClipboardBarDisplayHandlerDelegate: class {
func shouldDisplay(clipboardBar bar: ButtonToast)
}
class ClipboardBarDisplayHandler: NSObject {
weak var delegate: (ClipboardBarDisplayHandlerDelegate & SettingsDelegate)?
weak var settingsDelegate: SettingsDelegate?
weak var tabManager: TabManager?
private var sessionStarted = true
private var sessionRestored = false
private var firstTabLoaded = false
private var prefs: Prefs
private var lastDisplayedURL: String?
private var firstTab: Tab?
var clipboardToast: ButtonToast?
init(prefs: Prefs, tabManager: TabManager) {
self.prefs = prefs
self.tabManager = tabManager
super.init()
NotificationCenter.default.addObserver(self, selector: #selector(SELUIPasteboardChanged), name: NSNotification.Name.UIPasteboardChanged, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(SELAppWillEnterForegroundNotification), name: NSNotification.Name.UIApplicationWillEnterForeground, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(SELDidRestoreSession), name: NotificationDidRestoreSession, object: nil)
}
deinit {
if !firstTabLoaded {
firstTab?.webView?.removeObserver(self, forKeyPath: "URL")
}
}
@objc private func SELUIPasteboardChanged() {
// UIPasteboardChanged gets triggered when callng UIPasteboard.general
NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIPasteboardChanged, object: nil)
UIPasteboard.general.asyncURL().uponQueue(.main) { res in
defer {
NotificationCenter.default.addObserver(self, selector: #selector(self.SELUIPasteboardChanged), name: NSNotification.Name.UIPasteboardChanged, object: nil)
}
guard let copiedURL: URL? = res.successValue,
let url = copiedURL else {
return
}
self.lastDisplayedURL = url.absoluteString
}
}
@objc private func SELAppWillEnterForegroundNotification() {
sessionStarted = true
checkIfShouldDisplayBar()
}
@objc private func SELDidRestoreSession() {
DispatchQueue.main.sync {
if let tabManager = self.tabManager,
let firstTab = tabManager.selectedTab,
let webView = firstTab.webView {
self.firstTab = firstTab
webView.addObserver(self, forKeyPath: "URL", options: .new, context: nil)
} else {
firstTabLoaded = true
}
NotificationCenter.default.removeObserver(self, name: NotificationDidRestoreSession, object: nil)
sessionRestored = true
checkIfShouldDisplayBar()
}
}
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey: Any]?, context: UnsafeMutableRawPointer?) {
// Ugly hack to ensure we wait until we're finished restoring the session on the first tab
// before checking if we should display the clipboard bar.
guard sessionRestored,
let path = keyPath,
path == "URL",
let firstTab = self.firstTab,
let webView = firstTab.webView,
let url = firstTab.url?.absoluteString,
!url.startsWith("\(WebServer.sharedInstance.base)/about/sessionrestore?history=") else {
return
}
webView.removeObserver(self, forKeyPath: "URL")
firstTabLoaded = true
checkIfShouldDisplayBar()
}
private func shouldDisplayBar(_ copiedURL: String) -> Bool {
if !sessionStarted ||
!sessionRestored ||
!firstTabLoaded ||
isClipboardURLAlreadyDisplayed(copiedURL) ||
self.prefs.intForKey(IntroViewControllerSeenProfileKey) == nil {
return false
}
sessionStarted = false
return true
}
// If we already displayed this URL on the previous session, or in an already open
// tab, we shouldn't display it again
private func isClipboardURLAlreadyDisplayed(_ clipboardURL: String) -> Bool {
if lastDisplayedURL == clipboardURL {
return true
}
if let url = URL(string: clipboardURL),
let _ = tabManager?.getTabFor(url) {
return true
}
return false
}
func checkIfShouldDisplayBar() {
guard self.prefs.boolForKey("showClipboardBar") ?? false else {
// There's no point in doing any of this work unless the
// user has asked for it in settings.
return
}
UIPasteboard.general.asyncURL().uponQueue(.main) { res in
guard let copiedURL: URL? = res.successValue,
let url = copiedURL else {
return
}
let absoluteString = url.absoluteString
guard self.shouldDisplayBar(absoluteString) else {
return
}
self.lastDisplayedURL = absoluteString
self.clipboardToast =
ButtonToast(
labelText: Strings.GoToCopiedLink,
descriptionText: url.absoluteDisplayString,
buttonText: Strings.GoButtonTittle,
completion: { buttonPressed in
if buttonPressed {
self.delegate?.settingsOpenURLInNewTab(url)
}
})
if let toast = self.clipboardToast {
self.delegate?.shouldDisplay(clipboardBar: toast)
}
}
}
}
| mpl-2.0 | e4194804f2c9ac15f070eec2b9b752d2 | 35.831325 | 185 | 0.62774 | 5.513075 | false | false | false | false |
milseman/swift | stdlib/public/core/StringCore.swift | 5 | 24427 | //===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
/// The core implementation of a highly-optimizable String that
/// can store both ASCII and UTF-16, and can wrap native Swift
/// _StringBuffer or NSString instances.
///
/// Usage note: when elements are 8 bits wide, this code may
/// dereference one past the end of the byte array that it owns, so
/// make sure that storage is allocated! You want a null terminator
/// anyway, so it shouldn't be a burden.
//
// Implementation note: We try hard to avoid branches in this code, so
// for example we use integer math to avoid switching on the element
// size with the ternary operator. This is also the cause of the
// extra element requirement for 8 bit elements. See the
// implementation of subscript(Int) -> UTF16.CodeUnit below for details.
@_fixed_layout
public struct _StringCore {
//===--------------------------------------------------------------------===//
// Internals
public var _baseAddress: UnsafeMutableRawPointer?
var _countAndFlags: UInt
public var _owner: AnyObject?
/// (private) create the implementation of a string from its component parts.
init(
baseAddress: UnsafeMutableRawPointer?,
_countAndFlags: UInt,
owner: AnyObject?
) {
self._baseAddress = baseAddress
self._countAndFlags = _countAndFlags
self._owner = owner
_invariantCheck()
}
func _invariantCheck() {
// Note: this code is intentionally #if'ed out. It unconditionally
// accesses lazily initialized globals, and thus it is a performance burden
// in non-checked builds.
#if INTERNAL_CHECKS_ENABLED
_sanityCheck(count >= 0)
if _baseAddress == nil {
#if _runtime(_ObjC)
_sanityCheck(hasCocoaBuffer,
"Only opaque cocoa strings may have a null base pointer")
#endif
_sanityCheck(elementWidth == 2,
"Opaque cocoa strings should have an elementWidth of 2")
}
else if _baseAddress == _emptyStringBase {
_sanityCheck(!hasCocoaBuffer)
_sanityCheck(count == 0, "Empty string storage with non-zero count")
_sanityCheck(_owner == nil, "String pointing at empty storage has owner")
}
else if let buffer = nativeBuffer {
_sanityCheck(!hasCocoaBuffer)
_sanityCheck(elementWidth == buffer.elementWidth,
"_StringCore elementWidth doesn't match its buffer's")
_sanityCheck(_baseAddress! >= buffer.start)
_sanityCheck(_baseAddress! <= buffer.usedEnd)
_sanityCheck(_pointer(toElementAt: count) <= buffer.usedEnd)
}
#endif
}
/// Bitmask for the count part of `_countAndFlags`.
var _countMask: UInt {
return UInt.max &>> 2
}
/// Bitmask for the flags part of `_countAndFlags`.
var _flagMask: UInt {
return ~_countMask
}
/// Value by which to multiply a 2nd byte fetched in order to
/// assemble a UTF-16 code unit from our contiguous storage. If we
/// store ASCII, this will be zero. Otherwise, it will be 0x100.
var _highByteMultiplier: UTF16.CodeUnit {
return UTF16.CodeUnit(elementShift) &<< 8
}
/// Returns a pointer to the Nth element of contiguous
/// storage. Caveats: The string must have contiguous storage; the
/// element may be 1 or 2 bytes wide, depending on elementWidth; the
/// result may be null if the string is empty.
func _pointer(toElementAt n: Int) -> UnsafeMutableRawPointer {
_sanityCheck(hasContiguousStorage && n >= 0 && n <= count)
return _baseAddress! + (n &<< elementShift)
}
static func _copyElements(
_ srcStart: UnsafeMutableRawPointer, srcElementWidth: Int,
dstStart: UnsafeMutableRawPointer, dstElementWidth: Int,
count: Int
) {
// Copy the old stuff into the new storage
if _fastPath(srcElementWidth == dstElementWidth) {
// No change in storage width; we can use memcpy
_memcpy(
dest: dstStart,
src: srcStart,
size: UInt(count &<< (srcElementWidth - 1)))
}
else if srcElementWidth < dstElementWidth {
// Widening ASCII to UTF-16; we need to copy the bytes manually
var dest = dstStart.assumingMemoryBound(to: UTF16.CodeUnit.self)
var src = srcStart.assumingMemoryBound(to: UTF8.CodeUnit.self)
let srcEnd = src + count
while src != srcEnd {
dest.pointee = UTF16.CodeUnit(src.pointee)
dest += 1
src += 1
}
}
else {
// Narrowing UTF-16 to ASCII; we need to copy the bytes manually
var dest = dstStart.assumingMemoryBound(to: UTF8.CodeUnit.self)
var src = srcStart.assumingMemoryBound(to: UTF16.CodeUnit.self)
let srcEnd = src + count
while src != srcEnd {
dest.pointee = UTF8.CodeUnit(src.pointee)
dest += 1
src += 1
}
}
}
//===--------------------------------------------------------------------===//
// Initialization
public init(
baseAddress: UnsafeMutableRawPointer?,
count: Int,
elementShift: Int,
hasCocoaBuffer: Bool,
owner: AnyObject?
) {
_sanityCheck(elementShift == 0 || elementShift == 1)
self._baseAddress = baseAddress
self._countAndFlags
= (UInt(truncatingIfNeeded: elementShift) &<< (UInt.bitWidth - 1))
| ((hasCocoaBuffer ? 1 : 0) &<< (UInt.bitWidth - 2))
| UInt(truncatingIfNeeded: count)
self._owner = owner
_sanityCheck(UInt(count) & _flagMask == (0 as UInt),
"String too long to represent")
_invariantCheck()
}
/// Create a _StringCore that covers the entire length of the _StringBuffer.
init(_ buffer: _StringBuffer) {
self = _StringCore(
baseAddress: buffer.start,
count: buffer.usedCount,
elementShift: buffer.elementShift,
hasCocoaBuffer: false,
owner: buffer._anyObject
)
}
/// Create the implementation of an empty string.
///
/// - Note: There is no null terminator in an empty string.
public init() {
self._baseAddress = _emptyStringBase
self._countAndFlags = 0
self._owner = nil
_invariantCheck()
}
//===--------------------------------------------------------------------===//
// Properties
/// The number of elements stored
/// - Complexity: O(1).
public var count: Int {
get {
return Int(_countAndFlags & _countMask)
}
set(newValue) {
_sanityCheck(UInt(newValue) & _flagMask == 0)
_countAndFlags = (_countAndFlags & _flagMask) | UInt(newValue)
}
}
/// Left shift amount to apply to an offset N so that when
/// added to a UnsafeMutableRawPointer, it traverses N elements.
var elementShift: Int {
return Int(_countAndFlags &>> (UInt.bitWidth - 1))
}
/// The number of bytes per element.
///
/// If the string does not have an ASCII buffer available (including the case
/// when we don't have a utf16 buffer) then it equals 2.
public var elementWidth: Int {
return elementShift &+ 1
}
public var hasContiguousStorage: Bool {
#if _runtime(_ObjC)
return _fastPath(_baseAddress != nil)
#else
return true
#endif
}
/// Are we using an `NSString` for storage?
public var hasCocoaBuffer: Bool {
return Int((_countAndFlags &<< 1)._value) < 0
}
public var startASCII: UnsafeMutablePointer<UTF8.CodeUnit> {
_sanityCheck(elementWidth == 1, "String does not contain contiguous ASCII")
return _baseAddress!.assumingMemoryBound(to: UTF8.CodeUnit.self)
}
/// True iff a contiguous ASCII buffer available.
public var isASCII: Bool {
return elementWidth == 1
}
public var startUTF16: UnsafeMutablePointer<UTF16.CodeUnit> {
_sanityCheck(
count == 0 || elementWidth == 2,
"String does not contain contiguous UTF-16")
return _baseAddress!.assumingMemoryBound(to: UTF16.CodeUnit.self)
}
public var asciiBuffer: UnsafeMutableBufferPointer<UTF8.CodeUnit>? {
if elementWidth != 1 {
return nil
}
return UnsafeMutableBufferPointer(start: startASCII, count: count)
}
/// the native _StringBuffer, if any, or `nil`.
public var nativeBuffer: _StringBuffer? {
if !hasCocoaBuffer {
return _owner.map {
unsafeBitCast($0, to: _StringBuffer.self)
}
}
return nil
}
#if _runtime(_ObjC)
/// the Cocoa String buffer, if any, or `nil`.
public var cocoaBuffer: _CocoaString? {
if hasCocoaBuffer {
return _owner
}
return nil
}
#endif
//===--------------------------------------------------------------------===//
// slicing
/// Returns the given sub-`_StringCore`.
public subscript(bounds: Range<Int>) -> _StringCore {
_precondition(
bounds.lowerBound >= 0,
"subscript: subrange start precedes String start")
_precondition(
bounds.upperBound <= count,
"subscript: subrange extends past String end")
let newCount = bounds.upperBound - bounds.lowerBound
_sanityCheck(UInt(newCount) & _flagMask == 0)
if hasContiguousStorage {
return _StringCore(
baseAddress: _pointer(toElementAt: bounds.lowerBound),
_countAndFlags: (_countAndFlags & _flagMask) | UInt(newCount),
owner: _owner)
}
#if _runtime(_ObjC)
return _cocoaStringSlice(self, bounds)
#else
_sanityCheckFailure("subscript: non-native string without objc runtime")
#endif
}
/// Get the Nth UTF-16 Code Unit stored.
@_versioned
func _nthContiguous(_ position: Int) -> UTF16.CodeUnit {
let p =
UnsafeMutablePointer<UInt8>(_pointer(toElementAt: position)._rawValue)
// Always dereference two bytes, but when elements are 8 bits we
// multiply the high byte by 0.
// FIXME(performance): use masking instead of multiplication.
#if _endian(little)
return UTF16.CodeUnit(p.pointee)
+ UTF16.CodeUnit((p + 1).pointee) * _highByteMultiplier
#else
return _highByteMultiplier == 0 ? UTF16.CodeUnit(p.pointee) : UTF16.CodeUnit((p + 1).pointee) + UTF16.CodeUnit(p.pointee) * _highByteMultiplier
#endif
}
/// Get the Nth UTF-16 Code Unit stored.
public subscript(position: Int) -> UTF16.CodeUnit {
@inline(__always)
get {
_precondition(
position >= 0,
"subscript: index precedes String start")
_precondition(
position <= count,
"subscript: index points past String end")
if _fastPath(_baseAddress != nil) {
return _nthContiguous(position)
}
#if _runtime(_ObjC)
return _cocoaStringSubscript(self, position)
#else
_sanityCheckFailure("subscript: non-native string without objc runtime")
#endif
}
}
var _unmanagedASCII : UnsafeBufferPointer<Unicode.ASCII.CodeUnit>? {
@inline(__always)
get {
guard _fastPath(_baseAddress != nil && elementWidth == 1) else {
return nil
}
return UnsafeBufferPointer(
start: _baseAddress!.assumingMemoryBound(
to: Unicode.ASCII.CodeUnit.self),
count: count
)
}
}
var _unmanagedUTF16 : UnsafeBufferPointer<UTF16.CodeUnit>? {
@inline(__always)
get {
guard _fastPath(_baseAddress != nil && elementWidth != 1) else {
return nil
}
return UnsafeBufferPointer(
start: _baseAddress!.assumingMemoryBound(to: UTF16.CodeUnit.self),
count: count
)
}
}
/// Write the string, in the given encoding, to output.
func encode<Encoding: Unicode.Encoding>(
_ encoding: Encoding.Type,
into processCodeUnit: (Encoding.CodeUnit) -> Void)
{
defer { _fixLifetime(self) }
if let bytes = _unmanagedASCII {
if encoding == Unicode.ASCII.self
|| encoding == Unicode.UTF8.self
|| encoding == Unicode.UTF16.self
|| encoding == Unicode.UTF32.self {
bytes.forEach {
processCodeUnit(Encoding.CodeUnit(truncatingIfNeeded: $0))
}
}
else {
// TODO: be sure tests exercise this code path.
for b in bytes {
Encoding._encode(
Unicode.Scalar(_unchecked: UInt32(b))).forEach(processCodeUnit)
}
}
}
else if let content = _unmanagedUTF16 {
var i = content.makeIterator()
Unicode.UTF16.ForwardParser._parse(&i) {
Encoding._transcode($0, from: UTF16.self).forEach(processCodeUnit)
}
}
else if hasCocoaBuffer {
#if _runtime(_ObjC)
_StringCore(
_cocoaStringToContiguous(
source: cocoaBuffer!, range: 0..<count, minimumCapacity: 0)
).encode(encoding, into: processCodeUnit)
#else
_sanityCheckFailure("encode: non-native string without objc runtime")
#endif
}
}
/// Attempt to claim unused capacity in the String's existing
/// native buffer, if any. Return zero and a pointer to the claimed
/// storage if successful. Otherwise, returns a suggested new
/// capacity and a null pointer.
///
/// - Note: If successful, effectively appends garbage to the String
/// until it has newSize UTF-16 code units; you must immediately copy
/// valid UTF-16 into that storage.
///
/// - Note: If unsuccessful because of insufficient space in an
/// existing buffer, the suggested new capacity will at least double
/// the existing buffer's storage.
@inline(__always)
mutating func _claimCapacity(
_ newSize: Int, minElementWidth: Int) -> (Int, UnsafeMutableRawPointer?) {
if _fastPath(
(nativeBuffer != nil) && elementWidth >= minElementWidth
&& isKnownUniquelyReferenced(&_owner)
) {
var buffer = nativeBuffer!
// In order to grow the substring in place, this _StringCore should point
// at the substring at the end of a _StringBuffer. Otherwise, some other
// String is using parts of the buffer beyond our last byte.
let usedEnd = _pointer(toElementAt:count)
// Attempt to claim unused capacity in the buffer
if _fastPath(buffer.start == _baseAddress && newSize <= buffer.capacity) {
buffer.usedEnd = buffer.start + (newSize &<< elementShift)
count = newSize
return (0, usedEnd)
}
else if newSize > buffer.capacity {
// Growth failed because of insufficient storage; double the size
return (Swift.max(_growArrayCapacity(buffer.capacity), newSize), nil)
}
}
return (newSize, nil)
}
/// Ensure that this String references a _StringBuffer having
/// a capacity of at least newSize elements of at least the given width.
/// Effectively appends garbage to the String until it has newSize
/// UTF-16 code units. Returns a pointer to the garbage code units;
/// you must immediately copy valid data into that storage.
@inline(__always)
mutating func _growBuffer(
_ newSize: Int, minElementWidth: Int
) -> UnsafeMutableRawPointer {
let (newCapacity, existingStorage)
= _claimCapacity(newSize, minElementWidth: minElementWidth)
if _fastPath(existingStorage != nil) {
return existingStorage!
}
let oldCount = count
_copyInPlace(
newSize: newSize,
newCapacity: newCapacity,
minElementWidth: minElementWidth)
return _pointer(toElementAt:oldCount)
}
/// Replace the storage of self with a native _StringBuffer having a
/// capacity of at least newCapacity elements of at least the given
/// width. Effectively appends garbage to the String until it has
/// newSize UTF-16 code units.
mutating func _copyInPlace(
newSize: Int, newCapacity: Int, minElementWidth: Int
) {
_sanityCheck(newCapacity >= newSize)
let oldCount = count
// Allocate storage.
let newElementWidth =
minElementWidth >= elementWidth
? minElementWidth
: isRepresentableAsASCII() ? 1 : 2
let newStorage = _StringBuffer(capacity: newCapacity, initialSize: newSize,
elementWidth: newElementWidth)
if hasContiguousStorage {
_StringCore._copyElements(
_baseAddress!, srcElementWidth: elementWidth,
dstStart: UnsafeMutableRawPointer(newStorage.start),
dstElementWidth: newElementWidth, count: oldCount)
}
else {
#if _runtime(_ObjC)
// Opaque cocoa buffers might not store ASCII, so assert that
// we've allocated for 2-byte elements.
// FIXME: can we get Cocoa to tell us quickly that an opaque
// string is ASCII? Do we care much about that edge case?
_sanityCheck(newStorage.elementShift == 1)
_cocoaStringReadAll(cocoaBuffer!,
newStorage.start.assumingMemoryBound(to: UTF16.CodeUnit.self))
#else
_sanityCheckFailure("_copyInPlace: non-native string without objc runtime")
#endif
}
self = _StringCore(newStorage)
}
/// Append `c` to `self`.
///
/// - Complexity: O(1) when amortized over repeated appends of equal
/// character values.
mutating func append(_ c: Unicode.Scalar) {
let width = UTF16.width(c)
append(
width == 2 ? UTF16.leadSurrogate(c) : UTF16.CodeUnit(c.value),
width == 2 ? UTF16.trailSurrogate(c) : nil
)
}
/// Append `u` to `self`.
///
/// - Complexity: Amortized O(1).
public mutating func append(_ u: UTF16.CodeUnit) {
append(u, nil)
}
mutating func append(_ u0: UTF16.CodeUnit, _ u1: UTF16.CodeUnit?) {
_invariantCheck()
let minBytesPerCodeUnit = u0 <= 0x7f ? 1 : 2
let utf16Width = u1 == nil ? 1 : 2
let destination = _growBuffer(
count + utf16Width, minElementWidth: minBytesPerCodeUnit)
if _fastPath(elementWidth == 1) {
_sanityCheck(_pointer(toElementAt:count) == destination + 1)
destination.assumingMemoryBound(to: UTF8.CodeUnit.self)[0]
= UTF8.CodeUnit(u0)
}
else {
let destination16
= destination.assumingMemoryBound(to: UTF16.CodeUnit.self)
destination16[0] = u0
if u1 != nil {
destination16[1] = u1!
}
}
_invariantCheck()
}
@inline(never)
mutating func append(_ rhs: _StringCore) {
_invariantCheck()
let minElementWidth
= elementWidth >= rhs.elementWidth
? elementWidth
: rhs.isRepresentableAsASCII() ? 1 : 2
let destination = _growBuffer(
count + rhs.count, minElementWidth: minElementWidth)
if _fastPath(rhs.hasContiguousStorage) {
_StringCore._copyElements(
rhs._baseAddress!, srcElementWidth: rhs.elementWidth,
dstStart: destination, dstElementWidth:elementWidth, count: rhs.count)
}
else {
#if _runtime(_ObjC)
_sanityCheck(elementWidth == 2)
_cocoaStringReadAll(rhs.cocoaBuffer!,
destination.assumingMemoryBound(to: UTF16.CodeUnit.self))
#else
_sanityCheckFailure("subscript: non-native string without objc runtime")
#endif
}
_invariantCheck()
}
/// Returns `true` iff the contents of this string can be
/// represented as pure ASCII.
///
/// - Complexity: O(*n*) in the worst case.
func isRepresentableAsASCII() -> Bool {
if _slowPath(!hasContiguousStorage) {
return false
}
if _fastPath(elementWidth == 1) {
return true
}
let unsafeBuffer =
UnsafeBufferPointer(
start: _baseAddress!.assumingMemoryBound(to: UTF16.CodeUnit.self),
count: count)
return !unsafeBuffer.contains { $0 > 0x7f }
}
}
extension _StringCore : RandomAccessCollection {
public typealias Indices = CountableRange<Int>
public // @testable
var startIndex: Int {
return 0
}
public // @testable
var endIndex: Int {
return count
}
}
extension _StringCore : RangeReplaceableCollection {
/// Replace the elements within `bounds` with `newElements`.
///
/// - Complexity: O(`bounds.count`) if `bounds.upperBound
/// == self.endIndex` and `newElements.isEmpty`, O(*n*) otherwise.
public mutating func replaceSubrange<C>(
_ bounds: Range<Int>,
with newElements: C
) where C : Collection, C.Element == UTF16.CodeUnit {
_precondition(
bounds.lowerBound >= 0,
"replaceSubrange: subrange start precedes String start")
_precondition(
bounds.upperBound <= count,
"replaceSubrange: subrange extends past String end")
let width = elementWidth == 2 || newElements.contains { $0 > 0x7f } ? 2 : 1
let replacementCount = numericCast(newElements.count) as Int
let replacedCount = bounds.count
let tailCount = count - bounds.upperBound
let growth = replacementCount - replacedCount
let newCount = count + growth
// Successfully claiming capacity only ensures that we can modify
// the newly-claimed storage without observably mutating other
// strings, i.e., when we're appending. Already-used characters
// can only be mutated when we have a unique reference to the
// buffer.
let appending = bounds.lowerBound == endIndex
let existingStorage = !hasCocoaBuffer && (
appending || isKnownUniquelyReferenced(&_owner)
) ? _claimCapacity(newCount, minElementWidth: width).1 : nil
if _fastPath(existingStorage != nil) {
let rangeStart = _pointer(toElementAt:bounds.lowerBound)
let tailStart = rangeStart + (replacedCount &<< elementShift)
if growth > 0 {
(tailStart + (growth &<< elementShift)).copyBytes(
from: tailStart, count: tailCount &<< elementShift)
}
if _fastPath(elementWidth == 1) {
var dst = rangeStart.assumingMemoryBound(to: UTF8.CodeUnit.self)
for u in newElements {
dst.pointee = UInt8(truncatingIfNeeded: u)
dst += 1
}
}
else {
var dst = rangeStart.assumingMemoryBound(to: UTF16.CodeUnit.self)
for u in newElements {
dst.pointee = u
dst += 1
}
}
if growth < 0 {
(tailStart + (growth &<< elementShift)).copyBytes(
from: tailStart, count: tailCount &<< elementShift)
}
}
else {
var r = _StringCore(
_StringBuffer(
capacity: newCount,
initialSize: 0,
elementWidth:
width == 1 ? 1
: isRepresentableAsASCII() && !newElements.contains { $0 > 0x7f } ? 1
: 2
))
r.append(contentsOf: self[0..<bounds.lowerBound])
r.append(contentsOf: newElements)
r.append(contentsOf: self[bounds.upperBound..<count])
self = r
}
}
public mutating func reserveCapacity(_ n: Int) {
if _fastPath(!hasCocoaBuffer) {
if _fastPath(isKnownUniquelyReferenced(&_owner)) {
let bounds: Range<UnsafeRawPointer>
= UnsafeRawPointer(_pointer(toElementAt:0))
..< UnsafeRawPointer(_pointer(toElementAt:count))
if _fastPath(nativeBuffer!.hasCapacity(n, forSubRange: bounds)) {
return
}
}
}
_copyInPlace(
newSize: count,
newCapacity: Swift.max(count, n),
minElementWidth: 1)
}
public mutating func append<S : Sequence>(contentsOf s: S)
where S.Element == UTF16.CodeUnit {
var width = elementWidth
if width == 1 {
if let hasNonAscii = s._preprocessingPass({
s.contains { $0 > 0x7f }
}) {
width = hasNonAscii ? 2 : 1
}
}
let growth = s.underestimatedCount
var iter = s.makeIterator()
if _fastPath(growth > 0) {
let newSize = count + growth
let destination = _growBuffer(newSize, minElementWidth: width)
if elementWidth == 1 {
let destination8
= destination.assumingMemoryBound(to: UTF8.CodeUnit.self)
for i in 0..<growth {
destination8[i] = UTF8.CodeUnit(iter.next()!)
}
}
else {
let destination16
= destination.assumingMemoryBound(to: UTF16.CodeUnit.self)
for i in 0..<growth {
destination16[i] = iter.next()!
}
}
}
// Append any remaining elements
for u in IteratorSequence(iter) {
self.append(u)
}
}
}
// Used to support a tighter invariant: all strings with contiguous
// storage have a non-NULL base address.
var _emptyStringStorage: UInt32 = 0
var _emptyStringBase: UnsafeMutableRawPointer {
return UnsafeMutableRawPointer(Builtin.addressof(&_emptyStringStorage))
}
| apache-2.0 | f5b7f739357e4f19ec63499f09b61ef9 | 30.80599 | 147 | 0.639129 | 4.564088 | false | false | false | false |
zetasq/Aztec | Source/Sockets/sockaddr_in+Init.swift | 1 | 806 | //
// sockaddr_in+Init.swift
// Aztec
//
// Created by Zhu Shengqi on 21/04/2017.
// Copyright © 2017 Zhu Shengqi. All rights reserved.
//
import Foundation
extension sockaddr_in {
static let zero: sockaddr_in = {
var address = sockaddr_in()
bzero(&address, MemoryLayout.size(ofValue: address))
address.sin_len = __uint8_t(MemoryLayout.size(ofValue: address))
address.sin_family = sa_family_t(AF_INET)
return address
}()
static let localWIFI: sockaddr_in = {
var address = sockaddr_in()
bzero(&address, MemoryLayout.size(ofValue: address))
address.sin_len = __uint8_t(MemoryLayout.size(ofValue: address))
address.sin_family = sa_family_t(AF_INET)
address.sin_addr.s_addr = IN_LINKLOCALNETNUM
return address
}()
}
| mit | a338047466cd9fa68391a0359e2496e3 | 22 | 68 | 0.652174 | 3.515284 | false | false | false | false |
overtake/TelegramSwift | Telegram-Mac/GalleryTouchBarThumbItemView.swift | 1 | 2792 | //
// GalleryTouchBarThumbItemView.swift
// Telegram
//
// Created by Mikhail Filimonov on 20/09/2018.
// Copyright © 2018 Telegram. All rights reserved.
//
import Cocoa
import TGUIKit
import TelegramCore
import Postbox
import SwiftSignalKit
@available(OSX 10.12.2, *)
class GalleryTouchBarThumbItemView: NSScrubberItemView {
fileprivate let imageView: TransformImageView = TransformImageView()
override init(frame frameRect: NSRect) {
super.init(frame: frameRect)
addSubview(imageView)
}
func update(_ item: MGalleryItem) {
var signal:Signal<ImageDataTransformation, NoError>?
var size: NSSize?
if let item = item as? MGalleryPhotoItem {
signal = chatWebpageSnippetPhoto(account: item.context.account, imageReference: item.entry.imageReference(item.media), scale: backingScaleFactor, small: true, secureIdAccessContext: item.secureIdAccessContext)
size = item.media.representations.first?.dimensions.size
} else if let item = item as? MGalleryGIFItem {
signal = chatMessageImageFile(account: item.context.account, fileReference: item.entry.fileReference(item.media), scale: backingScaleFactor)
size = item.media.videoSize
} else if let item = item as? MGalleryExternalVideoItem {
signal = chatWebpageSnippetPhoto(account: item.context.account, imageReference: item.entry.imageReference(item.mediaImage), scale: backingScaleFactor, small: true, secureIdAccessContext: nil)
size = item.mediaImage.representations.first?.dimensions.size
} else if let item = item as? MGalleryVideoItem {
signal = chatMessageImageFile(account: item.context.account, fileReference: item.entry.fileReference(item.media), scale: backingScaleFactor)
size = item.media.videoSize
} else if let item = item as? MGalleryPeerPhotoItem {
signal = chatMessagePhoto(account: item.context.account, imageReference: item.entry.imageReference(item.media), scale: backingScaleFactor)
size = item.media.representations.first?.dimensions.size
}
item.fetch()
if let signal = signal, let size = size {
imageView.setSignal(signal)
let arguments = TransformImageArguments(corners: ImageCorners(radius: 4.0), imageSize:size.aspectFilled(NSMakeSize(36, 30)), boundingSize: NSMakeSize(36, 30), intrinsicInsets: NSEdgeInsets())
imageView.set(arguments: arguments)
}
imageView.setFrameSize(36, 30)
}
override func layout() {
super.layout()
imageView.center()
}
required init?(coder decoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| gpl-2.0 | 28efd18d9d753af5218ecec3458adaf9 | 43.301587 | 221 | 0.690075 | 4.754685 | false | false | false | false |
s-aska/Justaway-for-iOS | Justaway/Twitter.swift | 1 | 45067 | import UIKit
import Accounts
import EventBox
import KeyClip
import TwitterAPI
import OAuthSwift
import SwiftyJSON
import Async
import Reachability
let twitterAuthorizeNotification = Notification.Name.init(rawValue: "TwitterAuthorizeNotification")
class Twitter {
// MARK: - Types
enum ConnectionStatus {
case connecting
case connected
case disconnecting
case disconnected
}
enum StreamingMode: String {
case Manual = "Manual"
case AutoOnWiFi = "AutoOnWiFi"
case AutoAlways = "AutoAlways"
}
enum Event: String {
case CreateStatus = "CreateStatus"
case CreateFavorites = "CreateFavorites"
case DestroyFavorites = "DestroyFavorites"
case CreateRetweet = "CreateRetweet"
case DestroyRetweet = "DestroyRetweet"
case DestroyStatus = "DestroyStatus"
case CreateMessage = "CreateMessage"
case DestroyMessage = "DestroyMessage"
case StreamingStatusChanged = "StreamingStatusChanged"
case ListMemberAdded = "ListMemberAdded"
case ListMemberRemoved = "ListMemberRemoved"
func Name() -> Notification.Name {
return Notification.Name.init(rawValue: self.rawValue)
}
}
struct Static {
static var reachability: Reachability? // keep memory
static var streamingMode = StreamingMode.Manual
static var onWiFi = false
static var connectionStatus: ConnectionStatus = .disconnected
static var connectionID: String = Date(timeIntervalSinceNow: 0).timeIntervalSince1970.description
static var streamingRequest: StreamingRequest?
static var favorites = [String: Bool]()
static var retweets = [String: String]()
static var messages = [String: [TwitterMessage]]()
static var backgroundTaskIdentifier: UIBackgroundTaskIdentifier = UIBackgroundTaskInvalid
fileprivate static let favoritesQueue = DispatchQueue(label: "pw.aska.justaway.twitter.favorites", attributes: [])
fileprivate static let retweetsQueue = DispatchQueue(label: "pw.aska.justaway.twitter.retweets", attributes: [])
fileprivate static let messagesSemaphore = DispatchSemaphore(value: 1)
}
class var connectionStatus: ConnectionStatus { return Static.connectionStatus }
class var streamingMode: StreamingMode { return Static.streamingMode }
class var messages: [String: [TwitterMessage]] {
get {
Static.messagesSemaphore.wait(timeout: DispatchTime.distantFuture)
let messages = Static.messages
Static.messagesSemaphore.signal()
return messages
}
set {
_ = Static.messagesSemaphore.wait(timeout: DispatchTime.distantFuture)
Static.messages = newValue
Static.messagesSemaphore.signal()
}
}
class var enableStreaming: Bool {
switch Static.streamingMode {
case .Manual:
return false
case .AutoAlways:
return true
case .AutoOnWiFi:
return Static.onWiFi
}
}
// MARK: - Class Methods
class func setup() {
guard let r = Reachability.init() else {
print("Unable to create Reachability")
return
}
Static.reachability = r
Static.reachability?.whenReachable = { reachability in
NSLog("whenReachable")
Async.main {
if reachability.isReachableViaWiFi {
NSLog("Reachable via WiFi")
Static.onWiFi = true
} else {
NSLog("Reachable via Cellular")
Static.onWiFi = false
}
}
Async.main(after: 2) {
Twitter.startStreamingIfEnable()
}
return
}
Static.reachability?.whenUnreachable = { reachability in
Async.main {
NSLog("whenUnreachable")
Static.onWiFi = false
}
}
do {
try Static.reachability?.startNotifier()
} catch {
print("Unable to start notifier")
}
if let streamingModeString: String = KeyClip.load("settings.streamingMode") {
if let streamingMode = StreamingMode(rawValue: streamingModeString) {
Static.streamingMode = streamingMode
} else {
_ = KeyClip.delete("settings.streamingMode")
}
}
}
class func addOAuthAccount() {
let failure: ((OAuthSwiftError) -> Void) = {
error in
if error._code == 401 {
ErrorAlert.show("Twitter auth failure", message: error.localizedDescription)
} else if error._code == 429 {
ErrorAlert.show("Twitter auth failure", message: "API Limit")
} else {
ErrorAlert.show("Twitter auth failure", message: error.localizedDescription)
EventBox.post(twitterAuthorizeNotification)
}
}
let oauthswift = OAuth1Swift(
consumerKey: twitterConsumerKey,
consumerSecret: twitterConsumerSecret,
requestTokenUrl: "https://api.twitter.com/oauth/request_token",
authorizeUrl: "https://api.twitter.com/oauth/authorize",
accessTokenUrl: "https://api.twitter.com/oauth/access_token"
)
oauthswift.authorizeURLHandler = SafariOAuthURLHandler()
oauthswift.authorize(withCallbackURL: "justaway://success", success: {
credential, response, parameters in
let client = OAuthClient(
consumerKey: twitterConsumerKey,
consumerSecret: twitterConsumerSecret,
accessToken: credential.oauthToken,
accessTokenSecret: credential.oauthTokenSecret)
client.get("https://api.twitter.com/1.1/account/verify_credentials.json")
.responseJSON { (json: JSON) -> Void in
let user = TwitterUserFull(json)
let exToken = AccountSettingsStore.get()?.find(user.userID)?.exToken ?? ""
let account = Account(
client: client,
userID: user.userID,
screenName: user.screenName,
name: user.name,
profileImageURL: user.profileImageURL,
profileBannerURL: user.profileBannerURL,
exToken: exToken)
Twitter.refreshAccounts([account])
}
}, failure: failure)
}
class func addACAccount(_ silent: Bool) {
let accountStore = ACAccountStore()
let accountType = accountStore.accountType(withAccountTypeIdentifier: ACAccountTypeIdentifierTwitter)
// Prompt the user for permission to their twitter account stored in the phone's settings
accountStore.requestAccessToAccounts(with: accountType, options: nil) {
granted, error in
if granted {
let twitterAccounts = accountStore.accounts(with: accountType) as? [ACAccount] ?? []
if twitterAccounts.count == 0 {
if !silent {
MessageAlert.show("Error", message: "There are no Twitter accounts configured. You can add or create a Twitter account in Settings.")
}
EventBox.post(twitterAuthorizeNotification)
} else {
Twitter.refreshAccounts(
twitterAccounts.map({ (account: ACAccount) in
let userID = account.value(forKeyPath: "properties.user_id") as? String ?? ""
if let account = AccountSettingsStore.get()?.find(userID), account.isOAuth {
return account
}
let exToken = AccountSettingsStore.get()?.find(userID)?.exToken ?? ""
return Account(
client: AccountClient(account: account),
userID: userID,
screenName: account.username,
name: account.username,
profileImageURL: nil,
profileBannerURL: nil,
exToken: exToken)
})
)
}
} else {
if !silent {
MessageAlert.show("Error", message: "Twitter requires you to authorize Justaway for iOS to use your account.")
}
EventBox.post(twitterAuthorizeNotification)
}
}
}
class func refreshAccounts(_ newAccounts: [Account]) {
let accountSettings: AccountSettings
if let storeAccountSettings = AccountSettingsStore.get() {
accountSettings = storeAccountSettings.merge(newAccounts)
} else if newAccounts.count > 0 {
accountSettings = AccountSettings(current: 0, accounts: newAccounts)
} else {
return
}
let userIDs = accountSettings.accounts.map({ $0.userID }).joined(separator: ",")
let success: (([JSON]) -> Void) = { (rows) in
let users = rows.map { TwitterUserFull($0) }
// Save Device
AccountSettingsStore.save(accountSettings.update(users))
EventBox.post(twitterAuthorizeNotification)
}
let parameters = ["user_id": userIDs]
accountSettings.account()?.client
.get("https://api.twitter.com/1.1/users/lookup.json", parameters: parameters)
.responseJSONArray(success, failure: { (code, message, error) -> Void in
AccountSettingsStore.save(accountSettings)
EventBox.post(twitterAuthorizeNotification)
})
}
class func client() -> Client? {
let client = AccountSettingsStore.get()?.account()?.client
if let c = client as? AccountClient {
NSLog("debugDescription:\(c.debugDescription)")
}
return client
}
class func getHomeTimeline(maxID: String? = nil, sinceID: String? = nil, success: @escaping ([TwitterStatus]) -> Void, failure: @escaping (NSError) -> Void) {
var parameters = [String: String]()
if let maxID = maxID {
parameters["max_id"] = maxID
parameters["count"] = "200"
}
if let sinceID = sinceID {
parameters["since_id"] = sinceID
parameters["count"] = "200"
}
let success = { (array: [JSON]) -> Void in
let statuses = array.map({ TwitterStatus($0) })
success(statuses)
if maxID == nil {
let dictionary = ["statuses": statuses.map({ $0.dictionaryValue })]
if KeyClip.save("homeTimeline", dictionary: dictionary as NSDictionary) {
NSLog("homeTimeline cache success.")
}
}
}
client()?
.get("https://api.twitter.com/1.1/statuses/home_timeline.json", parameters: parameters)
.responseJSONArray(success, failure: { (code, message, error) -> Void in
failure(error)
})
}
class func getStatuses(_ statusIDs: [String], success: @escaping ([TwitterStatus]) -> Void, failure: @escaping (NSError) -> Void) {
let parameters = ["id": statusIDs.joined(separator: ",")]
let success = { (array: [JSON]) -> Void in
success(array.map({ TwitterStatus($0) }))
}
client()?
.get("https://api.twitter.com/1.1/statuses/lookup.json", parameters: parameters)
.responseJSONArray(success, failure: { (code, message, error) -> Void in
failure(error)
})
}
class func getUsers(_ userIDs: [String], success: @escaping ([TwitterUser]) -> Void, failure: @escaping (NSError) -> Void) {
let parameters = ["user_id": userIDs.joined(separator: ",")]
let success = { (array: [JSON]) -> Void in
success(array.map({ TwitterUser($0) }))
}
client()?
.get("https://api.twitter.com/1.1/users/lookup.json", parameters: parameters)
.responseJSONArray(success, failure: { (code, message, error) -> Void in
failure(error)
})
}
class func getUsers(_ userIDs: [String], success: @escaping ([TwitterUserFull]) -> Void, failure: @escaping (NSError) -> Void) {
let parameters = ["user_id": userIDs.joined(separator: ",")]
let success = { (array: [JSON]) -> Void in
success(array.map({ TwitterUserFull($0) }))
}
client()?
.get("https://api.twitter.com/1.1/users/lookup.json", parameters: parameters)
.responseJSONArray(success, failure: { (code, message, error) -> Void in
failure(error)
})
}
class func getUsers(_ keyword: String, page: Int = 1, success: @escaping ([TwitterUserFull]) -> Void, failure: @escaping (NSError) -> Void) {
let parameters = ["q": keyword, "count": "200", "page": String(page), "include_entities": "false"]
let success = { (array: [JSON]) -> Void in
success(array.map({ TwitterUserFull($0) }))
}
client()?
.get("https://api.twitter.com/1.1/users/search.json", parameters: parameters)
.responseJSONArray(success, failure: { (code, message, error) -> Void in
failure(error)
})
}
class func getRetweeters(_ statusID: String, success: @escaping ([TwitterUserFull]) -> Void, failure: @escaping (NSError) -> Void) {
let retweetersSuccess = { (json: JSON) -> Void in
guard let ids = json["ids"].array?.map({ $0.string ?? "" }).filter({ !$0.isEmpty }) else {
success([])
return
}
Twitter.getUsers(ids, success: success, failure: failure)
}
let parameters = ["id": statusID, "count": "100", "stringify_ids": "true"]
client()?
.get("https://api.twitter.com/1.1/statuses/retweeters/ids.json", parameters: parameters)
.responseJSON(retweetersSuccess, failure: { (code, message, error) -> Void in
failure(error)
})
}
class func getUserTimeline(_ userID: String, maxID: String? = nil, sinceID: String? = nil, success: @escaping ([TwitterStatus]) -> Void, failure: @escaping (NSError) -> Void) {
var parameters = ["user_id": userID]
if let maxID = maxID {
parameters["max_id"] = maxID
parameters["count"] = "200"
}
if let sinceID = sinceID {
parameters["since_id"] = sinceID
parameters["count"] = "200"
}
let success = { (array: [JSON]) -> Void in
success(array.map({ TwitterStatus($0) }))
}
client()?
.get("https://api.twitter.com/1.1/statuses/user_timeline.json", parameters: parameters)
.responseJSONArray(success, failure: { (code, message, error) -> Void in
failure(error)
})
}
class func getMentionTimeline(maxID: String? = nil, sinceID: String? = nil, success: @escaping ([TwitterStatus]) -> Void, failure: @escaping (NSError) -> Void) {
var parameters: [String: String] = [:]
if let maxID = maxID {
parameters["max_id"] = maxID
parameters["count"] = "200"
}
if let sinceID = sinceID {
parameters["since_id"] = sinceID
parameters["count"] = "200"
}
let success = { (array: [JSON]) -> Void in
let statuses = array.map({ TwitterStatus($0) })
success(statuses)
if maxID == nil {
let dictionary = ["statuses": statuses.map({ $0.dictionaryValue })]
if KeyClip.save("mentionTimeline", dictionary: dictionary as NSDictionary) {
NSLog("mentionTimeline cache success.")
}
}
}
client()?
.get("https://api.twitter.com/1.1/statuses/mentions_timeline.json", parameters: parameters)
.responseJSONArray(success, failure: { (code, message, error) -> Void in
failure(error)
})
}
class func getSearchTweets(_ keyword: String, maxID: String? = nil, sinceID: String? = nil, excludeRetweets: Bool = true, resultType: String = "recent", success: @escaping ([TwitterStatus], [String: JSON]) -> Void, failure: @escaping (NSError) -> Void) {
var parameters: [String: String] = ["count": "200", "q": keyword + (excludeRetweets ? " exclude:retweets" : ""), "result_type": resultType]
if let maxID = maxID {
parameters["max_id"] = maxID
}
if let sinceID = sinceID {
parameters["since_id"] = sinceID
}
let success = { (json: JSON) -> Void in
if let statuses = json["statuses"].array,
let search_metadata = json["search_metadata"].dictionary {
success(statuses.map({ TwitterStatus($0) }), search_metadata)
}
}
NSLog("parameters:\(parameters)")
client()?
.get("https://api.twitter.com/1.1/search/tweets.json", parameters: parameters)
.responseJSON(success, failure: { (code, message, error) -> Void in
failure(error)
})
}
class func getListsStatuses(_ listID: String, maxID: String? = nil, sinceID: String? = nil, success: @escaping ([TwitterStatus]) -> Void, failure: @escaping (NSError) -> Void) {
var parameters = ["list_id": listID]
if let maxID = maxID {
parameters["max_id"] = maxID
parameters["count"] = "200"
}
if let sinceID = sinceID {
parameters["since_id"] = sinceID
parameters["count"] = "200"
}
let success = { (array: [JSON]) -> Void in
success(array.map({ TwitterStatus($0) }))
}
client()?.get("https://api.twitter.com/1.1/lists/statuses.json", parameters: parameters)
.responseJSONArray(success, failure: { (code, message, error) -> Void in
failure(error)
})
}
class func getFavorites(_ userID: String, maxID: String? = nil, sinceID: String? = nil, success: @escaping ([TwitterStatus]) -> Void, failure: @escaping (NSError) -> Void) {
var parameters = ["user_id": userID]
if let maxID = maxID {
parameters["max_id"] = maxID
parameters["count"] = "200"
}
if let sinceID = sinceID {
parameters["since_id"] = sinceID
parameters["count"] = "200"
}
let success = { (array: [JSON]) -> Void in
success(array.map({ TwitterStatus($0) }))
}
client()?.get("https://api.twitter.com/1.1/favorites/list.json", parameters: parameters)
.responseJSONArray(success, failure: { (code, message, error) -> Void in
failure(error)
})
}
class func getDirectMessages(_ success: @escaping ([TwitterMessage]) -> Void) {
guard let account = AccountSettingsStore.get()?.account() else {
success([])
return
}
let client = account.client
let parameters = ["count": "200", "full_text": "true"]
let successReceived = { (array: [JSON]) -> Void in
let reveivedArray = array
let successSent = { (array: [JSON]) -> Void in
var idMap = [String: Bool]()
success((reveivedArray + array)
.map({ TwitterMessage($0, ownerID: account.userID) })
.filter({ (message: TwitterMessage) -> Bool in
if idMap[message.id] != nil {
return false
} else {
idMap[message.id] = true
return true
}
})
.sorted(by: {
return $0.0.createdAt.date.timeIntervalSince1970 > $0.1.createdAt.date.timeIntervalSince1970
}))
}
client.get("https://api.twitter.com/1.1/direct_messages/sent.json", parameters: parameters)
.responseJSONArray(successSent)
}
client.get("https://api.twitter.com/1.1/direct_messages.json", parameters: parameters)
.responseJSONArray(successReceived)
}
class func getFriendships(_ targetID: String, success: @escaping (TwitterRelationship) -> Void) {
guard let account = AccountSettingsStore.get()?.account() else {
return
}
let parameters = ["source_id": account.userID, "target_id": targetID]
let success = { (json: JSON) -> Void in
if let source: JSON = json["relationship"]["source"] {
let relationship = TwitterRelationship(source)
success(relationship)
}
}
client()?.get("https://api.twitter.com/1.1/friendships/show.json", parameters: parameters)
.responseJSON(success)
}
class func getFollowingUsers(_ userID: String, cursor: String = "-1", success: @escaping (_ users: [TwitterUserFull], _ nextCursor: String?) -> Void, failure: @escaping (NSError) -> Void) {
let parameters = ["user_id": userID, "cursor": cursor, "count": "200"]
let success = { (json: JSON) -> Void in
if let users = json["users"].array {
success(users.map({ TwitterUserFull($0) }), json["next_cursor_str"].string)
}
}
client()?
.get("https://api.twitter.com/1.1/friends/list.json", parameters: parameters)
.responseJSON(success, failure: { (code, message, error) -> Void in
failure(error)
})
}
class func getFollowerUsers(_ userID: String, cursor: String = "-1", success: @escaping (_ users: [TwitterUserFull], _ nextCursor: String?) -> Void, failure: @escaping (NSError) -> Void) {
let parameters = ["user_id": userID, "cursor": cursor, "count": "200"]
let success = { (json: JSON) -> Void in
if let users = json["users"].array {
success(users.map({ TwitterUserFull($0) }), json["next_cursor_str"].string)
}
}
client()?
.get("https://api.twitter.com/1.1/followers/list.json", parameters: parameters)
.responseJSON(success, failure: { (code, message, error) -> Void in
failure(error)
})
}
class func getListsMemberOf(_ userID: String, success: @escaping ([TwitterList]) -> Void, failure: @escaping (NSError) -> Void) {
let parameters = ["user_id": userID, "count": "200"]
let success = { (json: JSON) -> Void in
if let lists = json["lists"].array {
success(lists.map({ TwitterList($0) }))
}
}
client()?
.get("https://api.twitter.com/1.1/lists/memberships.json", parameters: parameters)
.responseJSON(success, failure: { (code, message, error) -> Void in
failure(error)
})
}
class func getSavedSearches(_ success: @escaping ([String]) -> Void, failure: @escaping (NSError) -> Void) {
let success = { (array: [JSON]) -> Void in
success(array.map({ $0["query"].string ?? "" }))
}
client()?
.get("https://api.twitter.com/1.1/saved_searches/list.json", parameters: [:])
.responseJSONArray(success, failure: { (code, message, error) -> Void in
failure(error)
})
}
class func getLists(_ success: @escaping ([TwitterList]) -> Void, failure: @escaping (NSError) -> Void) {
let success = { (array: [JSON]) -> Void in
success(array.map({ TwitterList($0) }))
}
client()?
.get("https://api.twitter.com/1.1/lists/list.json", parameters: [:])
.responseJSONArray(success, failure: { (code, message, error) -> Void in
failure(error)
})
}
class func statusUpdate(_ status: String, inReplyToStatusID: String?, images: [Data], mediaIds: [String]) {
if images.count == 0 {
return statusUpdate(status, inReplyToStatusID: inReplyToStatusID, mediaIds: mediaIds)
}
var images = images
let image = images.remove(at: 0)
Async.background { () -> Void in
client()?
.postMedia(image)
.responseJSON { (json: JSON) -> Void in
var mediaIds = mediaIds
if let media_id = json["media_id_string"].string {
mediaIds.append(media_id)
}
self.statusUpdate(status, inReplyToStatusID: inReplyToStatusID, images: images, mediaIds: mediaIds)
}
}
}
class func statusUpdate(_ status: String, inReplyToStatusID: String?, mediaIds: [String]) {
var parameters = [String: String]()
parameters["status"] = status
if let inReplyToStatusID = inReplyToStatusID {
parameters["in_reply_to_status_id"] = inReplyToStatusID
}
if mediaIds.count > 0 {
parameters["media_ids"] = mediaIds.joined(separator: ",")
}
client()?.post("https://api.twitter.com/1.1/statuses/update.json", parameters: parameters).responseJSONWithError(nil, failure: nil)
}
class func postDirectMessage(_ text: String, userID: String) {
guard let account = AccountSettingsStore.get()?.account() else {
return
}
let parameters = ["text": text, "user_id": userID]
account.client.post("https://api.twitter.com/1.1/direct_messages/new.json", parameters: parameters).responseJSONWithError({ (json) in
let message = TwitterMessage(json, ownerID: account.userID)
if Twitter.messages[account.userID] != nil {
Twitter.messages[account.userID]?.insert(message, at: 0)
} else {
Twitter.messages[account.userID] = [message]
}
EventBox.post(Event.CreateMessage.Name(), sender: message)
}, failure: nil)
}
}
// MARK: - Virtual
extension Twitter {
class func reply(_ status: TwitterStatus) {
if let account = AccountSettingsStore.get()?.account() {
let prefix = "@\(status.user.screenName) "
var users = status.mentions
if let actionedBy = status.actionedBy {
users.append(actionedBy)
}
let mentions = users.filter({ $0.userID != status.user.userID && account.userID != $0.userID }).map({ "@\($0.screenName) " }).joined(separator: "")
let range = NSRange.init(location: prefix.characters.count, length: mentions.characters.count)
EditorViewController.show(prefix + mentions, range: range, inReplyToStatus: status)
}
}
class func quoteURL(_ status: TwitterStatus) {
EditorViewController.show(" \(status.statusURL)", range: NSRange(location: 0, length: 0), inReplyToStatus: status)
}
}
// MARK: - REST API
extension Twitter {
class func isFavorite(_ statusID: String, handler: @escaping (Bool) -> Void) {
Async.custom(queue: Static.favoritesQueue) {
handler(Static.favorites[statusID] == true)
}
}
class func toggleFavorite(_ statusID: String) {
Async.custom(queue: Static.favoritesQueue) {
if Static.favorites[statusID] == true {
Twitter.destroyFavorite(statusID)
} else {
Async.background {
Twitter.createFavorite(statusID)
}
}
}
}
class func createFavorite(_ statusID: String) {
Async.custom(queue: Static.favoritesQueue) {
if Static.favorites[statusID] == true {
ErrorAlert.show("Like failure", message: "already like.")
return
}
Static.favorites[statusID] = true
EventBox.post(Event.CreateFavorites.Name(), sender: statusID as AnyObject)
let parameters = ["id": statusID]
client()?
.post("https://api.twitter.com/1.1/favorites/create.json", parameters: parameters)
.responseJSONWithError({ (json) -> Void in
}, failure: { (code, message, error) -> Void in
if code == 139 {
ErrorAlert.show("Like failure", message: "already like.")
} else {
Async.custom(queue: Static.favoritesQueue) {
Static.favorites.removeValue(forKey: statusID)
EventBox.post(Event.DestroyFavorites.Name(), sender: statusID as AnyObject)
}
ErrorAlert.show("Like failure", message: message ?? error.localizedDescription)
}
})
}
}
class func destroyFavorite(_ statusID: String) {
Async.custom(queue: Static.favoritesQueue) {
if Static.favorites[statusID] == nil {
ErrorAlert.show("Unlike failure", message: "missing like.")
return
}
Static.favorites.removeValue(forKey: statusID)
EventBox.post(Event.DestroyFavorites.Name(), sender: statusID as AnyObject)
let parameters = ["id": statusID]
client()?
.post("https://api.twitter.com/1.1/favorites/destroy.json", parameters: parameters)
.responseJSONWithError({ (json: JSON) -> Void in
}, failure: { (code, message, error) -> Void in
if code == 34 {
ErrorAlert.show("Unlike failure", message: "missing like.")
} else {
Async.custom(queue: Static.favoritesQueue) {
Static.favorites[statusID] = true
EventBox.post(Event.CreateFavorites.Name(), sender: statusID as AnyObject)
}
ErrorAlert.show("Unlike failure", message: message ?? error.localizedDescription)
}
})
}
}
class func isRetweet(_ statusID: String, handler: @escaping (String?) -> Void) {
Async.custom(queue: Static.retweetsQueue) {
handler(Static.retweets[statusID])
}
}
class func createRetweet(_ statusID: String) {
Async.custom(queue: Static.retweetsQueue) {
if Static.retweets[statusID] != nil {
ErrorAlert.show("Retweet failure", message: "already retweets.")
return
}
Static.retweets[statusID] = "0"
EventBox.post(Event.CreateRetweet.Name(), sender: statusID as AnyObject)
client()?
.post("https://api.twitter.com/1.1/statuses/retweet/\(statusID).json")
.responseJSONWithError({ (json: JSON) -> Void in
Async.custom(queue: Static.retweetsQueue) {
if let id = json["id_str"].string {
Static.retweets[statusID] = id
}
}
return
}, failure: { (code, message, error) -> Void in
if code == 34 {
ErrorAlert.show("Retweet failure", message: "already retweets.")
} else {
Async.custom(queue: Static.retweetsQueue) {
Static.retweets.removeValue(forKey: statusID)
EventBox.post(Event.DestroyRetweet.Name(), sender: statusID as AnyObject)
}
ErrorAlert.show("Retweet failure", message: message ?? error.localizedDescription)
}
})
}
}
class func destroyRetweet(_ statusID: String, retweetedStatusID: String) {
Async.custom(queue: Static.retweetsQueue) {
if Static.retweets[statusID] == nil {
ErrorAlert.show("Unod Retweet failure", message: "missing retweets.")
return
}
Static.retweets.removeValue(forKey: statusID)
EventBox.post(Event.DestroyRetweet.Name(), sender: statusID as AnyObject)
client()?
.post("https://api.twitter.com/1.1/statuses/destroy/\(retweetedStatusID).json", parameters: [:])
.responseJSONWithError({ (json: JSON) -> Void in
}, failure: { (code, message, error) -> Void in
if code == 34 {
ErrorAlert.show("Undo Retweet failure", message: "missing retweets.")
} else {
Async.custom(queue: Static.retweetsQueue) {
Static.retweets[statusID] = retweetedStatusID
EventBox.post(Event.CreateRetweet.Name(), sender: statusID as AnyObject)
}
ErrorAlert.show("Undo Retweet failure", message: message ?? error.localizedDescription)
}
})
}
}
class func destroyStatus(_ account: Account, statusID: String) {
account
.client
.post("https://api.twitter.com/1.1/statuses/destroy/\(statusID).json")
.responseJSONWithError({ (json: JSON) -> Void in
EventBox.post(Event.DestroyStatus.Name(), sender: statusID as AnyObject)
}, failure: { (code, message, error) -> Void in
ErrorAlert.show("Undo Tweet failure code:\(code)", message: message ?? error.localizedDescription)
})
}
class func destroyMessage(_ account: Account, messageID: String) {
account
.client
.post("https://api.twitter.com/1.1/direct_messages/destroy.json", parameters: ["id": messageID])
.responseJSONWithError({ (json: JSON) -> Void in
if let messages = Twitter.messages[account.userID] {
Twitter.messages[account.userID] = messages.filter({ $0.id != messageID })
}
EventBox.post(Event.DestroyMessage.Name(), sender: messageID as AnyObject)
}, failure: nil)
}
class func follow(_ userID: String, success: (() -> Void)? = nil) {
guard let account = AccountSettingsStore.get()?.account() else {
return
}
let parameters = ["user_id": userID]
account.client
.post("https://api.twitter.com/1.1/friendships/create.json", parameters: parameters)
.responseJSON({ (json: JSON) -> Void in
Relationship.follow(account, targetUserID: userID)
if let success = success {
success()
} else {
ErrorAlert.show("Follow success")
}
})
}
class func unfollow(_ userID: String, success: (() -> Void)? = nil) {
guard let account = AccountSettingsStore.get()?.account() else {
return
}
let parameters = ["user_id": userID]
account.client
.post("https://api.twitter.com/1.1/friendships/destroy.json", parameters: parameters)
.responseJSON({ (json: JSON) -> Void in
Relationship.unfollow(account, targetUserID: userID)
if let success = success {
success()
} else {
ErrorAlert.show("Unfollow success")
}
})
}
class func turnOnNotification(_ userID: String) {
let parameters = ["user_id": userID, "device": "true"]
client()?.post("https://api.twitter.com/1.1/friendships/update.json", parameters: parameters)
.responseJSON({ (json: JSON) -> Void in
ErrorAlert.show("Turn on notification success")
})
}
class func turnOffNotification(_ userID: String) {
let parameters = ["user_id": userID, "device": "false"]
client()?
.post("https://api.twitter.com/1.1/friendships/update.json", parameters: parameters)
.responseJSON({ (json: JSON) -> Void in
ErrorAlert.show("Turn off notification success")
})
}
class func turnOnRetweets(_ userID: String) {
guard let account = AccountSettingsStore.get()?.account() else {
return
}
let parameters = ["user_id": userID, "retweets": "true"]
account.client
.post("https://api.twitter.com/1.1/friendships/update.json", parameters: parameters)
.responseJSON({ (json: JSON) -> Void in
Relationship.turnOnRetweets(account, targetUserID: userID)
ErrorAlert.show("Turn on retweets success")
})
}
class func turnOffRetweets(_ userID: String) {
guard let account = AccountSettingsStore.get()?.account() else {
return
}
let parameters = ["user_id": userID, "retweets": "false"]
account.client
.post("https://api.twitter.com/1.1/friendships/update.json", parameters: parameters)
.responseJSON({ (json: JSON) -> Void in
Relationship.turnOffRetweets(account, targetUserID: userID)
ErrorAlert.show("Turn off retweets success")
})
}
class func mute(_ userID: String) { //
guard let account = AccountSettingsStore.get()?.account() else {
return
}
let parameters = ["user_id": userID]
account.client
.post("https://api.twitter.com/1.1/mutes/users/create.json", parameters: parameters)
.responseJSON({ (json: JSON) -> Void in
Relationship.mute(account, targetUserID: userID)
ErrorAlert.show("Mute success")
})
}
class func unmute(_ userID: String) {
guard let account = AccountSettingsStore.get()?.account() else {
return
}
let parameters = ["user_id": userID]
account.client
.post("https://api.twitter.com/1.1/mutes/users/destroy.json", parameters: parameters)
.responseJSON({ (json: JSON) -> Void in
Relationship.unmute(account, targetUserID: userID)
ErrorAlert.show("Unmute success")
})
}
class func block(_ userID: String) {
guard let account = AccountSettingsStore.get()?.account() else {
return
}
let parameters = ["user_id": userID]
account.client
.post("https://api.twitter.com/1.1/blocks/create.json", parameters: parameters)
.responseJSON({ (json: JSON) -> Void in
Relationship.block(account, targetUserID: userID)
ErrorAlert.show("Block success")
})
}
class func unblock(_ userID: String) {
guard let account = AccountSettingsStore.get()?.account() else {
return
}
let parameters = ["user_id": userID]
account.client
.post("https://api.twitter.com/1.1/blocks/destroy.json", parameters: parameters)
.responseJSON({ (json: JSON) -> Void in
Relationship.unblock(account, targetUserID: userID)
ErrorAlert.show("Unblock success")
})
}
class func reportSpam(_ userID: String) {
let parameters = ["user_id": userID]
client()?
.post("https://api.twitter.com/1.1/users/report_spam.json", parameters: parameters)
.responseJSON({ (json: JSON) -> Void in
ErrorAlert.show("Report success")
})
}
}
extension TwitterAPI.Request {
public func responseJSON(_ success: @escaping ((JSON) -> Void)) {
return responseJSONWithError(success, failure: nil)
}
public func responseJSON(_ success: @escaping ((JSON) -> Void), failure: ((_ code: Int?, _ message: String?, _ error: NSError) -> Void)?) {
return responseJSONWithError(success, failure: failure)
}
public func responseJSONArray(_ success: @escaping (([JSON]) -> Void)) {
let s = { (json: JSON) in
if let array = json.array {
success(array)
}
}
responseJSONWithError(s, failure: nil)
}
public func responseJSONArray(_ success: @escaping (([JSON]) -> Void), failure: ((_ code: Int?, _ message: String?, _ error: NSError) -> Void)?) {
let s = { (json: JSON) in
if let array = json.array {
success(array)
}
}
responseJSONWithError(s, failure: failure)
}
public func responseJSONWithError(_ success: ((JSON) -> Void)?, failure: ((_ code: Int?, _ message: String?, _ error: NSError) -> Void)?) {
UIApplication.shared.isNetworkActivityIndicatorVisible = true
let url = self.originalRequest.url?.absoluteString ?? "-"
let account = AccountSettingsStore.get()?.accounts.filter({ $0.client.serialize == self.originalClient.serialize }).first
response { (responseData, response, error) -> Void in
UIApplication.shared.isNetworkActivityIndicatorVisible = false
if let error = error {
if let failure = failure {
failure(nil, nil, error)
} else {
ErrorAlert.show("Twitter API Error", message: "url:\(url) error:\(error.localizedDescription)")
}
} else if let data = responseData {
let json = JSON(data: data)
if json.error != nil {
let HTTPResponse = response
let HTTPStatusCode = HTTPResponse?.statusCode ?? 0
let error = NSError.init(domain: NSURLErrorDomain, code: HTTPStatusCode, userInfo: [
NSLocalizedDescriptionKey: "Twitter API Error\nURL:\(url)\nHTTP StatusCode:\(HTTPStatusCode)",
NSLocalizedRecoverySuggestionErrorKey: "-"
])
if let failure = failure {
failure(nil, nil, error)
} else {
ErrorAlert.show("Twitter API Error", message: error.localizedDescription)
}
} else if let errors = json["errors"].array {
let code = errors[0]["code"].int ?? 0
let message = errors[0]["message"].string ?? "Unknown"
let HTTPResponse = response
let HTTPStatusCode = HTTPResponse?.statusCode ?? 0
var localizedDescription = "Twitter API Error\nErrorMessage:\(message)\nErrorCode:\(code)\nURL:\(url)\nHTTP StatusCode:\(HTTPStatusCode)"
var recoverySuggestion = "-"
if HTTPStatusCode == 401 && code == 89 {
localizedDescription = "Was revoked access"
if let account = account {
localizedDescription += " @\(account.screenName)"
}
if (account?.client as? OAuthClient) != nil {
recoverySuggestion = "1. Open the menu (upper left).\n2. Open the Accounts.\n3. Tap the [Add]\n4. Choose via Justaway for iOS\n5. Authorize app."
} else {
recoverySuggestion = "1. Tap the Home button.\n2. Open the [Settings].\n3. Open the [Twitter].\n4. Delete all account.\n5. Add all account.\n6. Open the Justaway."
}
}
let error = NSError.init(domain: NSURLErrorDomain, code: HTTPStatusCode, userInfo: [
NSLocalizedDescriptionKey: localizedDescription,
NSLocalizedRecoverySuggestionErrorKey: recoverySuggestion
])
if let failure = failure {
failure(code, message, error)
} else {
ErrorAlert.show("Twitter API Error", message: error.localizedDescription)
}
} else {
success?(json)
}
}
}
}
}
| mit | 4b83ea27317856f58306838110f5ff59 | 42.126316 | 258 | 0.547629 | 4.972636 | false | false | false | false |
qiuncheng/study-for-swift | learn-rx-swift/Chocotastic-starter/Pods/RxCocoa/RxCocoa/iOS/DataSources/RxTableViewReactiveArrayDataSource.swift | 9 | 3033 | //
// RxTableViewReactiveArrayDataSource.swift
// RxCocoa
//
// Created by Krunoslav Zaher on 6/26/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
#if os(iOS) || os(tvOS)
import Foundation
import UIKit
#if !RX_NO_MODULE
import RxSwift
#endif
// objc monkey business
class _RxTableViewReactiveArrayDataSource
: NSObject
, UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func _tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 0
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return _tableView(tableView, numberOfRowsInSection: section)
}
fileprivate func _tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
rxAbstractMethod()
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
return _tableView(tableView, cellForRowAt: indexPath)
}
}
class RxTableViewReactiveArrayDataSourceSequenceWrapper<S: Sequence>
: RxTableViewReactiveArrayDataSource<S.Iterator.Element>
, RxTableViewDataSourceType {
typealias Element = S
override init(cellFactory: @escaping CellFactory) {
super.init(cellFactory: cellFactory)
}
func tableView(_ tableView: UITableView, observedEvent: Event<S>) {
UIBindingObserver(UIElement: self) { tableViewDataSource, sectionModels in
let sections = Array(sectionModels)
tableViewDataSource.tableView(tableView, observedElements: sections)
}.on(observedEvent)
}
}
// Please take a look at `DelegateProxyType.swift`
class RxTableViewReactiveArrayDataSource<Element>
: _RxTableViewReactiveArrayDataSource
, SectionedViewDataSourceType {
typealias CellFactory = (UITableView, Int, Element) -> UITableViewCell
var itemModels: [Element]? = nil
func modelAtIndex(_ index: Int) -> Element? {
return itemModels?[index]
}
func model(_ indexPath: IndexPath) throws -> Any {
precondition(indexPath.section == 0)
guard let item = itemModels?[indexPath.item] else {
throw RxCocoaError.itemsNotYetBound(object: self)
}
return item
}
let cellFactory: CellFactory
init(cellFactory: @escaping CellFactory) {
self.cellFactory = cellFactory
}
override func _tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return itemModels?.count ?? 0
}
override func _tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
return cellFactory(tableView, indexPath.item, itemModels![indexPath.row])
}
// reactive
func tableView(_ tableView: UITableView, observedElements: [Element]) {
self.itemModels = observedElements
tableView.reloadData()
}
}
#endif
| mit | 63583c8b01c8404f7975b68434fe79a9 | 28.153846 | 113 | 0.685686 | 5.319298 | false | false | false | false |
LeeShiYoung/LSYWeibo | LSYWeiBo/Emoji/EmojiTextAttachment.swift | 1 | 674 | //
// EmojiTextAttachment.swift
// LSYWeiBo
//
// Created by 李世洋 on 16/5/27.
// Copyright © 2016年 李世洋. All rights reserved.
//
import UIKit
class EmojiTextAttachment: NSTextAttachment {
// 表情文字
var title: String?
class func emojiAttachment(emoticon: Emoticon, font: UIFont) -> NSAttributedString {
let attachment = EmojiTextAttachment()
attachment.title = emoticon.chs
attachment.image = UIImage(contentsOfFile: emoticon.pngPath!)
let size = font.lineHeight
attachment.bounds = CGRectMake(0, -4, size, size)
return NSAttributedString(attachment: attachment)
}
}
| artistic-2.0 | b4a6ea0cae0e2c069ad106b9b0aed98b | 25.04 | 88 | 0.663594 | 4.489655 | false | false | false | false |
ZamzamInc/ZamzamKit | Tests/ZamzamKitTests/Extensions/DictionaryTests.swift | 1 | 2770 | //
// DictionaryTests.swift
// ZamzamCore
//
// Created by Basem Emara on 2020-03-24.
// Copyright © 2018 Zamzam Inc. All rights reserved.
//
import XCTest
import ZamzamCore
final class DictionaryTests: XCTestCase {}
extension DictionaryTests {
func testIntialValue() throws {
// Given
var dictionary = [
"abc": 123,
"def": 456,
"xyz": 789
]
// When
let value = dictionary["abc", initial: 999]
XCTAssertNil(dictionary["lmn"])
let value2 = dictionary["lmn", initial: 555]
// Then
XCTAssertAllEqual(dictionary["abc"], value, 123)
XCTAssertAllEqual(dictionary["lmn"], value2, 555)
}
}
extension DictionaryTests {
func testJSONString() throws {
// Given
let dictionary: [String: Any] = [
"id": 1,
"name": "Joe",
"friends": [
[
"id": 2,
"name": "Pat",
"pets": ["dog"]
],
[
"id": 3,
"name": "Sue",
"pets": ["bird", "fish"]
]
],
"pets": []
]
let expected: [String: Any]
// When
guard let json = dictionary.jsonString() else {
XCTFail("String could not be converted to JSON")
return
}
guard let data = json.data(using: .utf8),
let decoded = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any] else {
XCTFail("String could not be converted to JSON")
return
}
expected = decoded
// Then
XCTAssert(json.contains("\"id\":1"))
XCTAssert(json.contains("\"name\":\"Joe\""))
XCTAssert(json.contains("\"friends\":[{"))
XCTAssert(json.contains("\"pets\":[\"dog\"]"))
XCTAssert(json.contains("\"name\":\"Sue\""))
XCTAssert(json.contains("\"pets\":[\""))
XCTAssertNotNil(dictionary["id"] as? Int)
XCTAssertEqual(dictionary["id"] as? Int, expected["id"] as? Int)
XCTAssertNotNil(dictionary["name"] as? String)
XCTAssertEqual(dictionary["name"] as? String, expected["name"] as? String)
XCTAssertNotNil(dictionary["pets"] as? [String])
XCTAssertEqual(dictionary["pets"] as? [String], expected["pets"] as? [String])
XCTAssertNotNil(((dictionary["friends"] as? [[String: Any]])?.first)?["name"] as? String)
XCTAssertEqual(
((dictionary["friends"] as? [[String: Any]])?.first)?["name"] as? String,
((expected["friends"] as? [[String: Any]])?.first)?["name"] as? String
)
}
}
| mit | 218adba9af8b7a5bb9e5413a5b85fb44 | 28.147368 | 108 | 0.508126 | 4.584437 | false | true | false | false |
OlegNovosad/Severenity | iOS/Severenity/Interactors/SettingsInteractor.swift | 2 | 2394 | //
// SettingsInteractor.swift
// Severenity
//
// Created by Yuriy Yasinskyy on 30.11.16.
// Copyright © 2016 severenity. All rights reserved.
//
import UIKit
import MessageUI
class SettingsInteractor: NSObject {
weak var delegate: SettingsInteractorDelegate?
// MARK: Init
override init() {
super.init()
WireFrame.sharedInstance.viperInteractors[kSettingsInteractor] = self
}
// MARK: ShopPresenter events
func sendLogFileEmail() {
Log.info(message: "SettingsInteractor was called from SettingsPresenter to send log file via email", sender: self)
sendLogEmail()
}
}
// MARK: MFMailComposeViewControllerDelegate
extension SettingsInteractor: MFMailComposeViewControllerDelegate {
func sendLogEmail() {
let emailController = MFMailComposeViewController()
emailController.mailComposeDelegate = self
if MFMailComposeViewController.canSendMail(), let filePath = kDocumentDirPath?.appendingPathComponent(kLogFileName) {
emailController.setSubject("Severenity")
emailController.setMessageBody("Severenity log file", isHTML: false)
emailController.setToRecipients(["[email protected]"])
do {
let fileData = try Data.init(contentsOf: filePath)
let mimeType = "text/txt"
emailController.addAttachmentData(fileData, mimeType: mimeType, fileName: "log.txt")
} catch {
Log.error(message: "Cannot find log file", sender: self)
}
delegate?.present(controller: emailController)
} else {
Log.error(message: "Email service is not set up on device", sender: self)
}
}
func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) {
switch result {
case .sent:
Log.info(message: "Email with log file was sent", sender: self)
case .saved:
Log.info(message: "Email with log file was saved", sender: self)
case .cancelled:
Log.info(message: "Email with log file was canceled", sender: self)
case .failed:
Log.error(message: "Failed to send email with log file", sender: self)
}
delegate?.dismissController()
}
}
| apache-2.0 | 8ce9781a78857e294816a9c0e498fb04 | 33.185714 | 133 | 0.646887 | 5.048523 | false | false | false | false |
hyeonjae/SwiftMoment | SwiftMoment/SwiftMoment/Duration.swift | 4 | 2032 | //
// Duration.swift
// SwiftMoment
//
// Created by Adrian on 19/01/15.
// Copyright (c) 2015 Adrian Kosmaczewski. All rights reserved.
//
import Foundation
public struct Duration: Equatable {
let interval: NSTimeInterval
public init(value: NSTimeInterval) {
self.interval = value
}
public init(value: Int) {
self.interval = NSTimeInterval(value)
}
public var years: Double {
return interval / 31536000 // 365 days
}
public var quarters: Double {
return interval / 7776000 // 3 months
}
public var months: Double {
return interval / 2592000 // 30 days
}
public var days: Double {
return interval / 86400 // 24 hours
}
public var hours: Double {
return interval / 3600 // 60 minutes
}
public var minutes: Double {
return interval / 60
}
public var seconds: Double {
return interval
}
public func ago() -> Moment {
return moment().subtract(self)
}
public func add(duration: Duration) -> Duration {
return Duration(value: self.interval + duration.interval)
}
public func subtract(duration: Duration) -> Duration {
return Duration(value: self.interval - duration.interval)
}
public func isEqualTo(duration: Duration) -> Bool {
return self.interval == duration.interval
}
}
extension Duration: CustomStringConvertible {
public var description: String {
let formatter = NSDateComponentsFormatter()
formatter.calendar = NSCalendar(identifier: NSCalendarIdentifierGregorian)
formatter.calendar?.timeZone = NSTimeZone(abbreviation: "UTC")!
formatter.allowedUnits = [.Year, .Month, .WeekOfMonth, .Day, .Hour, .Minute, .Second]
let referenceDate = NSDate(timeIntervalSinceReferenceDate: 0)
let intervalDate = NSDate(timeInterval: self.interval, sinceDate: referenceDate)
return formatter.stringFromDate(referenceDate, toDate: intervalDate)!
}
}
| bsd-2-clause | 646ed3c53fe8b21efe45f671dc17a066 | 25.051282 | 93 | 0.651083 | 4.747664 | false | false | false | false |
wrutkowski/Lucid-Weather-Clock | Pods/Charts/Charts/Classes/Highlight/ChartHighlighter.swift | 6 | 3892 | //
// ChartHighlighter.swift
// Charts
//
// Created by Daniel Cohen Gindi on 26/7/15.
//
// 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
open class ChartHighlighter : NSObject
{
/// instance of the data-provider
open weak var chart: BarLineChartViewBase?
public init(chart: BarLineChartViewBase)
{
self.chart = chart
}
/// Returns a Highlight object corresponding to the given x- and y- touch positions in pixels.
/// - parameter x:
/// - parameter y:
/// - returns:
open func getHighlight(x: CGFloat, y: CGFloat) -> ChartHighlight?
{
let xIndex = getXIndex(x)
guard let selectionDetail = getSelectionDetail(xIndex: xIndex, y: y, dataSetIndex: nil)
else { return nil }
return ChartHighlight(xIndex: xIndex, value: selectionDetail.value, dataIndex: selectionDetail.dataIndex, dataSetIndex: selectionDetail.dataSetIndex, stackIndex: -1)
}
/// Returns the corresponding x-index for a given touch-position in pixels.
/// - parameter x:
/// - returns:
open func getXIndex(_ x: CGFloat) -> Int
{
// create an array of the touch-point
var pt = CGPoint(x: x, y: 0.0)
// take any transformer to determine the x-axis value
self.chart?.getTransformer(ChartYAxis.AxisDependency.left).pixelToValue(&pt)
return Int(round(pt.x))
}
/// Returns the corresponding ChartSelectionDetail for a given xIndex and y-touch position in pixels.
/// - parameter xIndex:
/// - parameter y:
/// - parameter dataSetIndex: A dataset index to look at - or nil, to figure that out automatically
/// - returns:
open func getSelectionDetail(xIndex: Int, y: CGFloat, dataSetIndex: Int?) -> ChartSelectionDetail?
{
let valsAtIndex = getSelectionDetailsAtIndex(xIndex, dataSetIndex: dataSetIndex)
let leftdist = ChartUtils.getMinimumDistance(valsAtIndex, y: y, axis: ChartYAxis.AxisDependency.left)
let rightdist = ChartUtils.getMinimumDistance(valsAtIndex, y: y, axis: ChartYAxis.AxisDependency.right)
let axis = leftdist < rightdist ? ChartYAxis.AxisDependency.left : ChartYAxis.AxisDependency.right
let detail = ChartUtils.closestSelectionDetailByPixelY(valsAtIndex: valsAtIndex, y: y, axis: axis)
return detail
}
/// Returns a list of SelectionDetail object corresponding to the given xIndex.
/// - parameter xIndex:
/// - parameter dataSetIndex: A dataset index to look at - or nil, to figure that out automatically
/// - returns:
open func getSelectionDetailsAtIndex(_ xIndex: Int, dataSetIndex: Int?) -> [ChartSelectionDetail]
{
var vals = [ChartSelectionDetail]()
var pt = CGPoint()
guard let data = self.chart?.data
else { return vals }
for i in 0 ..< data.dataSetCount
{
if dataSetIndex != nil && dataSetIndex != i
{
continue
}
if let dataSet = data.getDataSetByIndex(i) {
// dont include datasets that cannot be highlighted
if !dataSet.highlightEnabled
{
continue
}
// extract all y-values from all DataSets at the given x-index
let yVals: [Double] = dataSet.yValsForXIndex(xIndex)
for yVal in yVals
{
pt.y = CGFloat(yVal)
self.chart!.getTransformer(dataSet.axisDependency).pointValueToPixel(&pt)
if !pt.y.isNaN
{
vals.append(ChartSelectionDetail(y: pt.y, value: yVal, dataSetIndex: i, dataSet: dataSet))
}
}
}
}
return vals
}
}
| mit | da8b4460d59444a7e0efcd508a02a687 | 31.705882 | 173 | 0.634121 | 4.683514 | false | false | false | false |
banxi1988/BXPopover | Example/Pods/BXModel/Pod/Classes/SimpleGenericDataSource.swift | 1 | 3320 | //
// GenericDataSource.swift
// Pods
//
// Created by Haizhen Lee on 15/11/8.
//
//
import UIKit
public protocol BXDataSourceContainer{
typealias ItemType
func updateItems<S:SequenceType where S.Generator.Element == ItemType>(items:S)
func appendItems<S:SequenceType where S.Generator.Element == ItemType>(items:S)
var numberOfItems:Int{ get }
}
public class SimpleGenericDataSource<T>:NSObject,UITableViewDataSource,UICollectionViewDataSource,BXDataSourceContainer{
public var reuseIdentifier = "cell"
var items = [T]()
public var section = 0
public typealias ItemType = T
public typealias DidSelectedItemBlock = ( (T,atIndexPath:NSIndexPath) -> Void )
public init(items:[T] = []){
self.items = items
}
public func itemAtIndexPath(indexPath:NSIndexPath) -> T{
return items[indexPath.row]
}
public func numberOfRows() -> Int {
return self.items.count
}
// MARK: UITableViewDataSource
public func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
public func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return numberOfRows()
}
public func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(self.reuseIdentifier, forIndexPath: indexPath)
configureTableViewCell(cell, atIndexPath: indexPath)
return cell
}
// MARK: UICollectionViewDataSource
public final func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
return 1
}
public final func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int{
return numberOfRows()
}
// The cell that is returned must be retrieved from a call to -dequeueReusableCellWithReuseIdentifier:forIndexPath:
public func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell{
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(self.reuseIdentifier, forIndexPath: indexPath)
configureCollectionViewCell(cell, atIndexPath: indexPath)
return cell
}
// MARK : Helper
public func configureCollectionViewCell(cell:UICollectionViewCell,atIndexPath indexPath:NSIndexPath){
}
public func configureTableViewCell(cell:UITableViewCell,atIndexPath indexPath:NSIndexPath){
}
// MARK: BXDataSourceContainer
// cause /Users/banxi/Workspace/BXModel/Pod/Classes/SimpleGenericTableViewAdapter.swift:50:25: Declarations from extensions cannot be overridden yet
public func updateItems<S : SequenceType where S.Generator.Element == ItemType>(items: S) {
self.items.removeAll()
self.items.appendContentsOf(items)
}
public func appendItems<S : SequenceType where S.Generator.Element == ItemType>(items: S) {
self.items.appendContentsOf(items)
}
public var numberOfItems:Int{
return self.items.count
}
}
extension SimpleGenericDataSource where T:Equatable{
public func indexOfItem(item:T) -> Int?{
return self.items.indexOf(item)
}
} | mit | 6eda6ef4172496ffa2c1e154b7ac6185 | 31.558824 | 150 | 0.718373 | 5.244866 | false | false | false | false |
netbe/translationsExample | translations/CollectionViewController.swift | 1 | 2788 | //
// CollectionViewController.swift
// translations
//
// Created by François Benaiteau on 27/11/15.
// Copyright © 2015 Sinnerschrader Mobile. All rights reserved.
//
import UIKit
private let reuseIdentifier = "cell"
enum CollectionType {
case None
case Fruits
case Colors
}
class CollectionViewController: UICollectionViewController, UICollectionViewDelegateFlowLayout {
var selectedSource: Array<String>?
@IBOutlet weak var flowLayout: UICollectionViewFlowLayout!
var collectionSourceType: CollectionType = .None {
didSet {
switch collectionSourceType {
case .Fruits:
selectedSource = fruits
title = "Fruits"
case .Colors:
selectedSource = colors
title = "Colors"
case .None:
selectedSource = nil
}
}
}
let fruits = ["Apple",
"Apricot",
"Avocado",
"Banana",
"Berry",
"Blueberry",
"Blackberry",
"Cranberry",
"Grapefruit",
"Grape",
"Kiwi",
"Lemon",
"Lychee",
"Macadamia",
"Nectarine",
"Orange",
"Peach",
"Peanut",
"Pine apple",
"Raspberry",
"Plum",
"Strawberry",
"Tomato",
"Walnut",
"Watermelon"]
let colors = ["black",
"darkGray",
"lightGray",
"white",
"gray",
"red",
"green",
"blue",
"cyan",
"yellow",
"magenta",
"orange",
"purple",
"brown"]
override func viewDidLoad() {
super.viewDidLoad()
}
// MARK: UICollectionViewDataSource
override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
return 1
}
override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
if let count = self.selectedSource?.count {
return count
}
return 0
}
override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! BasicCell
cell.titleLabel.text = self.selectedSource![indexPath.row]
return cell
}
// MARK: UICollectionViewDelegateFlowLayout
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
return CGSizeMake(CGRectGetWidth(self.view.frame), 60)
}
}
| mit | cd466d5330f24b66b57b88faac73f6af | 24.327273 | 169 | 0.586863 | 5.197761 | false | false | false | false |
LawrenceHan/iOS-project-playground | Swift_A_Big_Nerd_Ranch_Guide/Generics.playground/Contents.swift | 1 | 3548 | //: Playground - noun: a place where people can play
import Cocoa
var str = "Hello, playground"
struct StackGenerator<T>: GeneratorType {
var stack: Stack<T>
mutating func next() -> T? {
return stack.pop()
}
}
struct Stack<Element>: SequenceType {
var items = [Element]()
mutating func push(newItem: Element) {
items.append(newItem)
}
mutating func pop() -> Element? {
guard !items.isEmpty else {
return nil
}
return items.removeLast()
}
func map<U>(f: Element -> U) -> Stack<U> {
var mappedItems = [U]()
for item in items {
mappedItems.append(f(item))
}
return Stack<U>(items: mappedItems)
}
func filter(f: Element -> Bool) -> Stack<Element> {
var filteredItems = [Element]()
for item in items {
if f(item) {
filteredItems.append(item)
}
}
return Stack<Element>(items: filteredItems)
}
func generate() -> StackGenerator<Element> {
return StackGenerator(stack: self)
}
}
var intStack = Stack<Int>()
intStack.push(1)
intStack.push(2)
var doubledStack = intStack.map { 2 * $0 }
print(intStack.pop())
print(intStack.pop())
print(intStack.pop())
print(doubledStack.pop())
print(doubledStack.pop())
var stringStack = Stack<String>()
stringStack.push("this is a string")
stringStack.push("another string")
print(stringStack.pop())
func myMap<T, U>(items: [T], f: (T) -> (U)) -> [U] {
var result = [U]()
for item in items {
result.append(f(item))
}
return result
}
let strings = ["one", "two", "three"]
let stringLengths = myMap(strings) { $0.characters.count }
print(stringLengths)
func checkIfEqual<T: Equatable>(first: T, _ second: T) -> Bool {
return first == second
}
print(checkIfEqual(1, 1))
print(checkIfEqual("a string", "a string"))
print(checkIfEqual("a string", "a different string"))
func checkIfDescriptionsMatch<T: CustomStringConvertible, U: CustomStringConvertible>
(first: T, _ second: U) -> Bool {
return first.description == second.description
}
print(checkIfDescriptionsMatch(Int(1), UInt(1)))
print(checkIfDescriptionsMatch(1, 1.0))
print(checkIfDescriptionsMatch(Float(1.0), Double(1.0)))
var myStack = Stack<Int>()
myStack.push(10)
myStack.push(20)
myStack.push(30)
var myStackGenerator = StackGenerator(stack: myStack)
while let value = myStackGenerator.next() {
print("got \(value)")
}
for value in myStack {
print("for-in loop: got \(value)")
}
print(myStack)
func pushItemsOntoStack<Element, S: SequenceType where S.Generator.Element == Element>
(inout stack: Stack<Element>, fromSequence sequence: S) {
for item in sequence {
stack.push(item)
}
}
pushItemsOntoStack(&myStack, fromSequence: [1, 2, 3])
for value in myStack {
print("after pushing: got \(value)")
}
var myOtherStack = Stack<Int>()
pushItemsOntoStack(&myOtherStack, fromSequence: [1, 2, 3])
pushItemsOntoStack(&myStack, fromSequence: myOtherStack)
for value in myStack {
print("after pushing items onto stack, got \(value)")
}
let filteredStack = myStack.filter { $0 > 10 }
print(filteredStack)
func findAll<T: Equatable>(array: [T], element: T) -> [Int] {
var indices = [Int]()
var index = 0
for item in array {
if item == element {
indices.append(index)
}
index++
}
return indices
}
let numbers = [5, 3, 7, 3, 9]
findAll(numbers, element: 3)
| mit | c622efdbf2216491a82f43e0db537bc4 | 22.038961 | 86 | 0.630778 | 3.587462 | false | false | false | false |
powerytg/Accented | Accented/UI/Search/SearchResultBaseViewController.swift | 1 | 1931 | //
// SearchResultBaseViewController.swift
// Accented
//
// Base view controller for search result pages
//
// Created by Tiangong You on 8/26/17.
// Copyright © 2017 Tiangong You. All rights reserved.
//
import UIKit
class SearchResultBaseViewController: UIViewController {
@IBOutlet weak var backButton: UIButton!
@IBOutlet weak var searchButton: UIButton!
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var searchButtonSpacingConstraint: NSLayoutConstraint!
var keyword : String?
var tag : String?
init(keyword : String) {
self.keyword = keyword
super.init(nibName: "SearchResultBaseViewController", bundle: nil)
}
init(tag : String) {
self.tag = tag
super.init(nibName: "SearchResultBaseViewController", bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
if keyword == nil && tag == nil {
fatalError("Keyword and tag cannot be both nil")
}
if ThemeManager.sharedInstance.currentTheme is DarkTheme {
backButton.setImage(UIImage(named: "DetailBackButton"), for: .normal)
} else {
backButton.setImage(UIImage(named: "LightDetailBackButton"), for: .normal)
}
// Setup title
titleLabel.textColor = ThemeManager.sharedInstance.currentTheme.titleTextColor
titleLabel.preferredMaxLayoutWidth = 120
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
@IBAction func backButtonDidTap(_ sender: AnyObject) {
_ = navigationController?.popViewController(animated: true)
}
@IBAction func searchButtonDidTap(_ sender: AnyObject) {
NavigationService.sharedInstance.navigateToSearch(from: self)
}
}
| mit | bc6712ae9541dadfef4caea60165ee77 | 28.242424 | 86 | 0.662176 | 5.039164 | false | false | false | false |
AlphaJian/PaperCalculator | PaperCalculator/PaperCalculator/Views/Report/QuestionReportTableView.swift | 1 | 3484 | //
// QuestionReportTableView.swift
// PaperCalculator
//
// Created by appledev018 on 10/11/16.
// Copyright © 2016 apple. All rights reserved.
//
import UIKit
class QuestionReportTableView: UITableView, UITableViewDelegate, UITableViewDataSource {
//
// ReviewPaperTableView.swift
// PaperCalculator
//
// Created by Jian Zhang on 9/28/16.
// Copyright © 2016 apple. All rights reserved.
//
var model = DataManager.shareManager.paperModel.copySelf()
var singleMarkHandler : ReturnWithThreeParmsBlock!
var multiMarkHandler : ReturnWithThreeParmsBlock!
var nextPaperHandler : ButtonTouchUpBlock!
override init(frame: CGRect, style: UITableViewStyle) {
super.init(frame: frame, style: style)
self.delegate = self
self.dataSource = self
self.register(QuestionReportTableViewCell.classForCoder(), forCellReuseIdentifier: "cell")
self.separatorStyle = .none
}
required init?(coder aDecoder: NSCoder) {
fatalError("")
}
func numberOfSections(in tableView: UITableView) -> Int {
return model.sectionQuestionArr.count + 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if section == model.sectionQuestionArr.count {
return 1
} else {
let sectionModel = model.sectionQuestionArr[section]
return sectionModel.cellQuestionArr.count
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if indexPath.section == DataManager.shareManager.paperModel.sectionQuestionArr.count {
let cell = RankReportTableViewCell()
cell.initUI()
return cell
} else {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! QuestionReportTableViewCell
cell.selectionStyle = .none
cell.clearCell()
cell.initUI(index: indexPath)
return cell
}
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let view = UIView(frame: CGRect(x: 0, y: 0, width: self.frame.width, height: 50))
view.backgroundColor = UIColor.white
let lbl = UILabel(frame: CGRect(x: 20, y: 0, width: view.frame.width - 20, height: 50))
if section == model.sectionQuestionArr.count {
lbl.text = "其他"
} else {
lbl.text = "第 \(section + 1) 大题"
}
lbl.font = mediumFont
lbl.textColor = darkBlue
view.addSubview(lbl)
return view
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
if indexPath.section == model.sectionQuestionArr.count {
return 90
} else {
return 40
}
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 50
}
}
| gpl-3.0 | 685b384360c06dc49ac70391cf609a8e | 30.853211 | 108 | 0.553571 | 5.502377 | false | false | false | false |
tanbiao/TitleLabelView | TitleLabelView/TextAlertView.swift | 1 | 1244 | //
// TextAlertView.swift
// TitleLabelView
//
// Created by 西乡流水 on 17/5/16.
// Copyright © 2017年 西乡流水. All rights reserved.
//
import UIKit
import VideoToolbox
class TextAlertView: UIView
{
fileprivate var text : String
fileprivate lazy var contentView : UIScrollView = {
let contentView = UIScrollView(frame: self.bounds)
return contentView
}()
fileprivate lazy var textLabel : UILabel = {
let textLabel = UILabel(frame: self.contentView.bounds)
return textLabel
}()
init(text : String,textFont : UIFont,point: CGPoint)
{
self.text = text
let frame = CGRect.zero
super.init(frame: frame)
let size = String.size(text: text, textFont: textFont)
self.frame.size = CGSize(width: size.width + 2, height: size.height + 2)
self.center.x = point.x
self.center.y = point.y + size.height + 2
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
extension TextAlertView
{
func setUpInit()
{
addSubview(contentView)
contentView.addSubview(textLabel)
}
}
| gpl-3.0 | c6c64d0cba658e7181451ef805bc7b35 | 21.272727 | 80 | 0.604898 | 4.195205 | false | false | false | false |
hamilyjing/JJSwiftStudy | Playground/GuidedTour.playground/Pages/Control Flow.xcplaygroundpage/Contents.swift | 1 | 4166 | //: ## Control Flow
//:
//: Use `if` and `switch` to make conditionals, and use `for`-`in`, `for`, `while`, and `repeat`-`while` to make loops. Parentheses around the condition or loop variable are optional. Braces around the body are required.
//:
let individualScores = [75, 43, 103, 87, 12]
var teamScore = 0
for score in individualScores {
if score > 50 {
teamScore += 3
} else {
teamScore += 1
}
}
print(teamScore)
//: In an `if` statement, the conditional must be a Boolean expression—this means that code such as `if score { ... }` is an error, not an implicit comparison to zero.
//:
//: You can use `if` and `let` together to work with values that might be missing. These values are represented as optionals. An optional value either contains a value or contains `nil` to indicate that a value is missing. Write a question mark (`?`) after the type of a value to mark the value as optional.
//:
var optionalString: String? = "Hello"
print(optionalString == nil)
var optionalName: String? = "John Appleseed"
var greeting = "Hello!"
if let name = optionalName {
greeting = "Hello, \(name)"
}
//: - Experiment:
//: Change `optionalName` to `nil`. What greeting do you get? Add an `else` clause that sets a different greeting if `optionalName` is `nil`.
//:
//: If the optional value is `nil`, the conditional is `false` and the code in braces is skipped. Otherwise, the optional value is unwrapped and assigned to the constant after `let`, which makes the unwrapped value available inside the block of code.
//:
//: Another way to handle optional values is to provide a default value using the `??` operator. If the optional value is missing, the default value is used instead.
//:
let nickName: String? = nil
let fullName: String = "John Appleseed"
let informalGreeting = "Hi \(nickName ?? fullName)"
//: Switches support any kind of data and a wide variety of comparison operations—they aren’t limited to integers and tests for equality.
//:
let vegetable = "red pepper"
switch vegetable {
case "celery":
print("Add some raisins and make ants on a log.")
case "cucumber", "watercress":
print("That would make a good tea sandwich.")
case let x where x.hasSuffix("pepper"):
print("Is it a spicy \(x)?")
default:
print("Everything tastes good in soup.")
}
//: - Experiment:
//: Try removing the default case. What error do you get?
//:
//: Notice how `let` can be used in a pattern to assign the value that matched the pattern to a constant.
//:
//: After executing the code inside the switch case that matched, the program exits from the switch statement. Execution doesn’t continue to the next case, so there is no need to explicitly break out of the switch at the end of each case’s code.
//:
//: You use `for`-`in` to iterate over items in a dictionary by providing a pair of names to use for each key-value pair. Dictionaries are an unordered collection, so their keys and values are iterated over in an arbitrary order.
//:
let interestingNumbers = [
"Prime": [2, 3, 5, 7, 11, 13],
"Fibonacci": [1, 1, 2, 3, 5, 8],
"Square": [1, 4, 9, 16, 25],
]
var largest = 0
for (kind, numbers) in interestingNumbers {
for number in numbers {
if number > largest {
largest = number
}
}
}
print(largest)
//: - Experiment:
//: Add another variable to keep track of which kind of number was the largest, as well as what that largest number was.
//:
//: Use `while` to repeat a block of code until a condition changes. The condition of a loop can be at the end instead, ensuring that the loop is run at least once.
//:
var n = 2
while n < 100 {
n = n * 2
}
print(n)
var m = 2
repeat {
m = m * 2
} while m < 5
print(m)
//: You can keep an index in a loop by using `..<` to make a range of indexes.
//:
var total = 0
for i in 1..<2 { // [1,2)
total += i
}
print(total) // 1
var total1 = 0
for i in 1...2 { // [1,2]
total1 += i
}
print(total1) // 3
//: Use `..<` to make a range that omits its upper value, and use `...` to make a range that includes both values.
//:
//: [Previous](@previous) | [Next](@next)
| mit | 2ed0ed435ad94e3de1aa5bececdd27b7 | 36.107143 | 307 | 0.674928 | 3.833948 | false | false | false | false |
hackcity2017/iOS-client-application | hackcity/TemperatureCollectionViewCell.swift | 1 | 790 | //
// TemperatureCollectionViewCell.swift
// hackcity
//
// Created by Remi Robert on 26/03/2017.
// Copyright © 2017 Remi Robert. All rights reserved.
//
import UIKit
import SnapKit
import MKRingProgressView
class TemperatureCollectionViewCell: UICollectionViewCell {
@IBOutlet weak var temperatureCell: UILabel!
@IBOutlet weak var containerView: UIView!
override func awakeFromNib() {
super.awakeFromNib()
self.containerView.layer.cornerRadius = 5
self.layer.masksToBounds = false
self.layer.shadowOffset = CGSize(width: 0, height: 0)
self.layer.shadowRadius = 5
self.layer.shadowOpacity = 0.1
}
func configure(value: Double) {
self.temperatureCell.text = "\(String(format: "%.0f", value))°C"
}
}
| mit | 509d69e1c60ea70bea216fcda916c79a | 25.266667 | 72 | 0.685279 | 4.259459 | false | false | false | false |
TrustWallet/trust-wallet-ios | Trust/UI/Form/SliderTextFieldRow.swift | 1 | 7205 | // Copyright DApps Platform Inc. All rights reserved.
import Foundation
import Eureka
open class SliderTextFieldCell: Cell<Float>, CellType, UITextFieldDelegate {
private var awakeFromNibCalled = false
@IBOutlet open weak var titleLabel: UILabel!
@IBOutlet open weak var valueLabel: UILabel!
@IBOutlet open weak var slider: UISlider!
lazy var textField: UITextField = {
let textField = UITextField()
textField.translatesAutoresizingMaskIntoConstraints = false
textField.addTarget(self, action: #selector(textFieldDidChange(textField:)), for: .editingChanged)
textField.keyboardType = .numberPad
textField.delegate = self
textField.returnKeyType = .done
textField.textAlignment = .right
textField.layer.cornerRadius = 5
textField.layer.borderColor = Colors.lightGray.cgColor
textField.layer.borderWidth = 0.3
textField.rightViewMode = .always
textField.rightView = UIView.spacerWidth(5)
return textField
}()
open var formatter: NumberFormatter?
public required init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: .value1, reuseIdentifier: reuseIdentifier)
let _ = NotificationCenter.default.addObserver(forName: Notification.Name.UIContentSizeCategoryDidChange, object: nil, queue: nil) { [weak self] _ in
guard let me = self else { return }
if me.shouldShowTitle {
me.titleLabel = me.textLabel
me.valueLabel = me.detailTextLabel
me.addConstraints()
}
}
}
deinit {
guard !awakeFromNibCalled else { return }
NotificationCenter.default.removeObserver(self, name: Notification.Name.UIContentSizeCategoryDidChange, object: nil)
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
awakeFromNibCalled = true
}
open override func setup() {
super.setup()
if !awakeFromNibCalled {
// title
let title = textLabel
textLabel?.translatesAutoresizingMaskIntoConstraints = false
textLabel?.setContentHuggingPriority(UILayoutPriority(500), for: .horizontal)
self.titleLabel = title
// let value = detailTextLabel
// value?.translatesAutoresizingMaskIntoConstraints = false
// value?.setContentHuggingPriority(UILayoutPriority(500), for: .horizontal)
// self.valueLabel = value
detailTextLabel?.isHidden = true
let slider = UISlider()
slider.translatesAutoresizingMaskIntoConstraints = false
slider.setContentHuggingPriority(UILayoutPriority(500), for: .horizontal)
self.slider = slider
if shouldShowTitle {
contentView.addSubview(titleLabel)
//contentView.addSubview(valueLabel!)
contentView.addSubview(textField)
}
contentView.addSubview(slider)
addConstraints()
}
selectionStyle = .none
slider.minimumValue = sliderRow.minimumValue
slider.maximumValue = sliderRow.maximumValue
slider.addTarget(self, action: #selector(SliderTextFieldCell.valueChanged), for: .valueChanged)
}
open override func update() {
super.update()
titleLabel.text = row.title
//valueLabel.text = row.displayValueFor?(row.value)
//valueLabel.isHidden = !shouldShowTitle && !awakeFromNibCalled
titleLabel.isHidden = textField.isHidden
slider.value = row.value ?? 0.0
slider.isEnabled = !row.isDisabled
textField.text = row.displayValueFor?(row.value)
}
func addConstraints() {
guard !awakeFromNibCalled else { return }
textField.heightAnchor.constraint(equalToConstant: 30).isActive = true
textField.widthAnchor.constraint(equalToConstant: 140).isActive = true
let views: [String: Any] = ["titleLabel": titleLabel, "textField": textField, "slider": slider]
let metrics = ["vPadding": 12.0, "spacing": 12.0]
if shouldShowTitle {
contentView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-[titleLabel]-[textField]-|", options: NSLayoutFormatOptions.alignAllLastBaseline, metrics: metrics, views: views))
contentView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-vPadding-[titleLabel]-spacing-[slider]-vPadding-|", options: NSLayoutFormatOptions.alignAllLeft, metrics: metrics, views: views))
} else {
contentView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-vPadding-[slider]-vPadding-|", options: NSLayoutFormatOptions.alignAllLeft, metrics: metrics, views: views))
}
contentView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-[slider]-|", options: NSLayoutFormatOptions.alignAllLastBaseline, metrics: metrics, views: views))
}
@objc func valueChanged() {
let roundedValue: Float
let steps = Float(sliderRow.steps)
if steps > 0 {
let stepValue = round((slider.value - slider.minimumValue) / (slider.maximumValue - slider.minimumValue) * steps)
let stepAmount = (slider.maximumValue - slider.minimumValue) / steps
roundedValue = stepValue * stepAmount + self.slider.minimumValue
} else {
roundedValue = slider.value
}
row.value = roundedValue
row.updateCell()
textField.text = "\(Int(roundedValue))"
}
var shouldShowTitle: Bool {
return row?.title?.isEmpty == false
}
private var sliderRow: SliderTextFieldRow {
return row as! SliderTextFieldRow
}
@objc func textFieldDidChange(textField: UITextField) {
let value = Float(textField.text ?? "0") ?? sliderRow.minimumValue
let minValue = min(value, sliderRow.minimumValue)
let maxValue = max(value, sliderRow.maximumValue)
sliderRow.minimumValue = minValue
sliderRow.maximumValue = maxValue
slider.maximumValue = minValue
slider.maximumValue = maxValue
row.value = value
slider.value = value
}
@objc public func textFieldShouldReturn(_ textField: UITextField) -> Bool {
return true
}
open override func cellCanBecomeFirstResponder() -> Bool {
return !row.isDisabled && textField.canBecomeFirstResponder == true
}
open override func cellBecomeFirstResponder(withDirection: Direction) -> Bool {
return textField.becomeFirstResponder()
}
open override func cellResignFirstResponder() -> Bool {
return textField.resignFirstResponder()
}
}
/// A row that displays a UISlider. If there is a title set then the title and value will appear above the UISlider.
public final class SliderTextFieldRow: Row<SliderTextFieldCell>, RowType {
public var minimumValue: Float = 0.0
public var maximumValue: Float = 10.0
public var steps: UInt = 20
required public init(tag: String?) {
super.init(tag: tag)
}
}
| gpl-3.0 | 181955f6479309ab553b7439648b8958 | 38.157609 | 222 | 0.668147 | 5.437736 | false | false | false | false |
Rehsco/StyledAuthenticationView | AuthenticationDemo/AuthenticationDemoService.swift | 1 | 8832 | //
// AuthenticationDemoService.swift
// StyledAuthenticationView
//
// Created by Martin Rehder on 09.02.2017.
// Copyright © 2017 Martin Jacob Rehder. All rights reserved.
//
import UIKit
import MJRFlexStyleComponents
class AuthenticationDemoService {
private var authView: AuthenticationView?
func updateAuthenticationViewLayout(newSize size: CGSize) {
authView?.frame = CGRect(origin: .zero, size: size)
authView?.setNeedsLayout()
}
// MARK: Authentication handling
static let pinCodeEvaluator: ((String) -> Bool) = {
digits in
if digits == "123456" { // Use some kind of secure store to fetch a real pin code
return true
}
return false
}
static let passwordEvaluator: ((String) -> Bool) = {
password in
if password == "pass" { // Use some kind of secure store to fetch a real password
return true
}
return false
}
// Demo colors, fonts and layout styling
private func applyAuthViewStyle() {
let config = StyledAuthenticationViewConfiguration()
config.pinStyle = FlexShapeStyle(style: .roundedFixed(cornerRadius: 10))
config.pinBorderColor = .gray
config.pinSelectionColor = .lightGray
config.pinFont = UIFont.systemFont(ofSize: 18)
config.pinTextColor = .gray
config.cancelDeleteButtonTextColor = .gray
config.cancelDeleteButtonFont = UIFont.systemFont(ofSize: 18)
config.headerTextColor = .gray
config.headerTextFont = UIFont.systemFont(ofSize: 18)
config.passwordStyle = FlexShapeStyle(style: .roundedFixed(cornerRadius: 5))
config.passwordBorderColor = .gray
authView?.backgroundColor = .white
authView?.configuration = config
}
func authenticate(useTouchID: Bool, usePin: Bool, usePassword: Bool, authSuccess: @escaping ((Bool) -> Void)) {
if let appDelegate = UIApplication.shared.delegate as? AppDelegate {
if self.authView == nil {
if let tvc = appDelegate.getTopViewController() {
self.authView = AuthenticationView(frame: UIScreen.main.bounds)
self.applyAuthViewStyle()
if let liv = self.authView {
DispatchQueue.main.async {
tvc.view.addSubview(liv)
liv.pinCodeEvaluator = AuthenticationDemoService.pinCodeEvaluator
liv.passwordEvaluator = AuthenticationDemoService.passwordEvaluator
liv.authenticate(useTouchID: useTouchID, usePin: usePin, usePassword: usePassword, authHandler: {
success, errorType in
if !success {
let alertView = UIAlertController(title: "Error", message: errorType.description(), preferredStyle:.alert)
let okAction = UIAlertAction(title: "Ok", style: .default) { _ in
authSuccess(success)
self.dismissAuthView()
}
alertView.addAction(okAction)
tvc.present(alertView, animated: true) {}
}
else {
self.dismissAuthView()
authSuccess(success)
}
})
}
}
}
}
}
}
private func dismissAuthView() {
DispatchQueue.main.async {
if let liv = self.authView {
UIView.animate(withDuration: 0.5, animations: {
liv.alpha = 0
}, completion: { _ in
liv.removeFromSuperview()
self.authView = nil
})
}
}
}
// MARK: - Pin Handling
func createNewPin(createPinSuccess: @escaping ((Bool) -> Void)) {
if let appDelegate = UIApplication.shared.delegate as? AppDelegate {
if self.authView == nil {
if let tvc = appDelegate.getTopViewController() {
self.authView = AuthenticationView(frame: UIScreen.main.bounds)
self.applyAuthViewStyle()
if let liv = self.authView {
DispatchQueue.main.async {
tvc.view.addSubview(liv)
liv.createPINCode(createPinHandler: { (newPin, success, errorType) in
if success {
NSLog("Save the new PIN: \(newPin)")
}
else {
NSLog(errorType.description())
}
self.dismissAuthView()
createPinSuccess(success)
})
}
}
}
}
}
}
func changePin(createPinSuccess: @escaping ((Bool) -> Void)) {
if let appDelegate = UIApplication.shared.delegate as? AppDelegate {
if self.authView == nil {
if let tvc = appDelegate.getTopViewController() {
self.authView = AuthenticationView(frame: UIScreen.main.bounds)
self.applyAuthViewStyle()
if let liv = self.authView {
DispatchQueue.main.async {
tvc.view.addSubview(liv)
liv.pinCodeEvaluator = AuthenticationDemoService.pinCodeEvaluator
liv.changePINCode(createPinHandler: { (newPin, success, errorType) in
if success {
NSLog("Save the changed PIN: \(newPin)")
}
else {
NSLog(errorType.description())
}
self.dismissAuthView()
createPinSuccess(success)
})
}
}
}
}
}
}
// MARK: - Password handling
func createNewPassword(createPasswordSuccess: @escaping ((Bool) -> Void)) {
if let appDelegate = UIApplication.shared.delegate as? AppDelegate {
if self.authView == nil {
if let tvc = appDelegate.getTopViewController() {
self.authView = AuthenticationView(frame: UIScreen.main.bounds)
self.applyAuthViewStyle()
if let liv = self.authView {
DispatchQueue.main.async {
tvc.view.addSubview(liv)
liv.createPassword(createPasswordHandler: { (newPassword, success) in
if success {
NSLog("Save the new password: \(newPassword)")
}
self.dismissAuthView()
createPasswordSuccess(success)
})
}
}
}
}
}
}
func changePassword(createPasswordSuccess: @escaping ((Bool) -> Void)) {
if let appDelegate = UIApplication.shared.delegate as? AppDelegate {
if self.authView == nil {
if let tvc = appDelegate.getTopViewController() {
self.authView = AuthenticationView(frame: UIScreen.main.bounds)
self.applyAuthViewStyle()
if let liv = self.authView {
DispatchQueue.main.async {
tvc.view.addSubview(liv)
liv.passwordEvaluator = AuthenticationDemoService.passwordEvaluator
liv.changePassword(createPasswordHandler: { (newPassword, success) in
if success {
NSLog("Save the changed password: \(newPassword)")
}
self.dismissAuthView()
createPasswordSuccess(success)
})
}
}
}
}
}
}
}
| mit | 03f1a4dcc432455f4a299a70d0621a58 | 41.661836 | 142 | 0.472766 | 6.38078 | false | true | false | false |
roambotics/swift | SwiftCompilerSources/Sources/SIL/BasicBlock.swift | 3 | 4562 | //===--- BasicBlock.swift - Defines the BasicBlock class ------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import Basic
import SILBridging
final public class BasicBlock : ListNode, CustomStringConvertible, HasShortDescription {
public var next: BasicBlock? { SILBasicBlock_next(bridged).block }
public var previous: BasicBlock? { SILBasicBlock_previous(bridged).block }
// Needed for ReverseList<BasicBlock>.reversed(). Never use directly.
public var _firstInList: BasicBlock { SILFunction_firstBlock(function.bridged).block! }
// Needed for List<BasicBlock>.reversed(). Never use directly.
public var _lastInList: BasicBlock { SILFunction_lastBlock(function.bridged).block! }
public var function: Function { SILBasicBlock_getFunction(bridged).function }
public var description: String {
let stdString = SILBasicBlock_debugDescription(bridged)
return String(_cxxString: stdString)
}
public var shortDescription: String { name }
public var arguments: ArgumentArray { ArgumentArray(block: self) }
public var instructions: List<Instruction> {
List(first: SILBasicBlock_firstInst(bridged).instruction)
}
public var terminator: TermInst {
SILBasicBlock_lastInst(bridged).instruction as! TermInst
}
public var successors: SuccessorArray { terminator.successors }
public var predecessors: PredecessorList {
PredecessorList(startAt: SILBasicBlock_getFirstPred(bridged))
}
public var singlePredecessor: BasicBlock? {
var preds = predecessors
if let p = preds.next() {
if preds.next() == nil {
return p
}
}
return nil
}
public var hasSinglePredecessor: Bool { singlePredecessor != nil }
/// The index of the basic block in its function.
/// This has O(n) complexity. Only use it for debugging
public var index: Int {
for (idx, block) in function.blocks.enumerated() {
if block == self { return idx }
}
fatalError()
}
public var name: String { "bb\(index)" }
public var bridged: BridgedBasicBlock { BridgedBasicBlock(obj: SwiftObject(self)) }
}
public func == (lhs: BasicBlock, rhs: BasicBlock) -> Bool { lhs === rhs }
public func != (lhs: BasicBlock, rhs: BasicBlock) -> Bool { lhs !== rhs }
public struct ArgumentArray : RandomAccessCollection {
fileprivate let block: BasicBlock
public var startIndex: Int { return 0 }
public var endIndex: Int { SILBasicBlock_getNumArguments(block.bridged) }
public subscript(_ index: Int) -> Argument {
SILBasicBlock_getArgument(block.bridged, index).argument
}
}
public struct SuccessorArray : RandomAccessCollection, FormattedLikeArray {
private let succArray: BridgedArrayRef
init(succArray: BridgedArrayRef) {
self.succArray = succArray
}
public var startIndex: Int { return 0 }
public var endIndex: Int { return Int(succArray.numElements) }
public subscript(_ index: Int) -> BasicBlock {
assert(index >= 0 && index < endIndex)
let s = BridgedSuccessor(succ: succArray.data! + index &* BridgedSuccessorSize);
return SILSuccessor_getTargetBlock(s).block
}
}
public struct PredecessorList : CollectionLikeSequence, IteratorProtocol {
private var currentSucc: OptionalBridgedSuccessor
public init(startAt: OptionalBridgedSuccessor) { currentSucc = startAt }
public mutating func next() -> BasicBlock? {
if let succPtr = currentSucc.succ {
let succ = BridgedSuccessor(succ: succPtr)
currentSucc = SILSuccessor_getNext(succ)
return SILSuccessor_getContainingInst(succ).instruction.block
}
return nil
}
}
// Bridging utilities
extension BridgedBasicBlock {
public var block: BasicBlock { obj.getAs(BasicBlock.self) }
public var optional: OptionalBridgedBasicBlock {
OptionalBridgedBasicBlock(obj: self.obj)
}
}
extension OptionalBridgedBasicBlock {
public var block: BasicBlock? { obj.getAs(BasicBlock.self) }
public static var none: OptionalBridgedBasicBlock {
OptionalBridgedBasicBlock(obj: nil)
}
}
extension Optional where Wrapped == BasicBlock {
public var bridged: OptionalBridgedBasicBlock {
OptionalBridgedBasicBlock(obj: self?.bridged.obj)
}
}
| apache-2.0 | d8daa3a57298790d4022d92899339753 | 31.126761 | 89 | 0.713941 | 4.543825 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.