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
brocktonpoint/CCCodeExample
CCCodeExample/ShadowCollectionViewCell.swift
1
1805
/* The MIT License (MIT) Copyright (c) 2015 CawBox 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 @IBDesignable class ShadowCollectionViewCell: UICollectionViewCell { @IBOutlet weak var imageView: RoundedImageView? @IBOutlet weak var titleLabel: UILabel? var photoID: Int = -1 @IBInspectable var hasShadow: Bool = true { didSet { layer.shadowOpacity = hasShadow ? 1 : 0 layer.shadowColor = UIColor.blackColor().CGColor layer.shadowOffset = CGSize (width: 0, height: 1) layer.shadowRadius = 2 guard let view = imageView else { return } layer.shadowPath = UIBezierPath (roundedRect: view.frame, cornerRadius: 10).CGPath } } }
mit
0553801b984a0ee189ca8ae73b44e475
35.836735
94
0.709141
4.958791
false
false
false
false
badoo/Chatto
ChattoAdditions/sources/Chat Items/Composable/Layout/LayoutAssembler.swift
1
6776
// // The MIT License (MIT) // // Copyright (c) 2015-present Badoo Trading Limited. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. public struct LayoutAssembler { // MARK: - Type declarations public typealias Key = AnyBindingKey private typealias LayoutCache = [AnyBindingKey: AnyCachedLayoutProvider] public enum Error: Swift.Error { case notFound(Key) case internalInconsistency case layoutWasNotCalculated(Key) } // MARK: - Private properties private let hierarchy: MessageViewHierarchy private var makeSizeProviders: [AnyBindingKey: (Any) throws -> AnySizeProvider] = [:] private var makeCachingProviders: [AnyBindingKey: (Any) throws -> AnyCachedLayoutProvider] = [:] private var layoutApplicators: [AnyBindingKey: (Any, Any) throws -> Void] = [:] // MARK: - Instantiation public init(hierarchy: MessageViewHierarchy) { self.hierarchy = hierarchy } // MARK: - Public API // TODO: Remove #746 public mutating func populateSizeProviders<Key: BindingKeyProtocol>(for key: Key) where Key.LayoutProvider.Layout: SizeContainer, Key.View: ManualLayoutViewProtocol, Key.View.Layout == Key.LayoutProvider.Layout { let erasedKey = AnyBindingKey(key) self.makeSizeProviders[erasedKey] = { anyLayoutProvider in guard let layoutProvider = anyLayoutProvider as? CachingLayoutProvider<Key.LayoutProvider.Layout> else { throw Error.internalInconsistency } return AnySizeProvider(layoutProvider) } self.makeCachingProviders[erasedKey] = { anyLayoutProvider in guard let layoutProvider = anyLayoutProvider as? Key.LayoutProvider else { throw Error.internalInconsistency } return CachingLayoutProvider(layoutProvider) } self.layoutApplicators[erasedKey] = { anyView, anyLayout in guard let view = anyView as? Key.View, let layout = anyLayout as? Key.LayoutProvider.Layout else { throw Error.internalInconsistency } view.apply(layout: layout) } } public func assembleRootSizeProvider(layoutProviders: [Key: Any]) throws -> AnySizeProvider { let key = self.hierarchy.root var layoutCache: LayoutCache = [:] return try self.assemble(for: key, with: layoutProviders, layoutCache: &layoutCache) } // TODO: #747 public func applyLayout(with context: LayoutContext, views: [Key: Any], layoutProviders: [Key: Any]) throws { var layoutCache: LayoutCache = [:] // TODO: Check keys let rootLayoutProvider = try self.assemble(for: self.hierarchy.root, with: layoutProviders, layoutCache: &layoutCache) // perform layout to cache results _ = try rootLayoutProvider.layout(for: context) for (key, view) in views { guard let applicator = self.layoutApplicators[key] else { throw Error.notFound(key) } guard let cachedLayout = layoutCache[key]?.lastPerformedLayoutResult else { throw Error.layoutWasNotCalculated(key) } try applicator(view, cachedLayout) } } // MARK: - Private private func assemble(for key: Key, with providers: [Key: Any], layoutCache: inout LayoutCache) throws -> AnySizeProvider { guard let layoutProvider = providers[key] else { throw Error.notFound(key) } guard let makeSizeProvider = makeSizeProviders[key] else { throw Error.notFound(key) } guard let makeCachingProvider = makeCachingProviders[key] else { throw Error.notFound(key) } let resultLayoutProvider: Any switch try self.hierarchy.children(of: key) { case .no: resultLayoutProvider = layoutProvider case .single(let childKey): let child = try self.assemble(for: childKey, with: providers, layoutCache: &layoutCache) guard var container = layoutProvider as? SingleContainerLayoutProviderProtocol else { throw Error.internalInconsistency } container.childLayoutProvider = child resultLayoutProvider = container case .multiple(let childrenKeys): let children: [AnySizeProvider] = try childrenKeys.map { try self.assemble(for: $0, with: providers, layoutCache: &layoutCache) } guard var container = layoutProvider as? MultipleContainerLayoutProviderProtocol else { throw Error.internalInconsistency } container.childrenLayoutProviders = children resultLayoutProvider = container } let cachingContainer = try makeCachingProvider(resultLayoutProvider) layoutCache[key] = cachingContainer let sizeProvider = try makeSizeProvider(cachingContainer) return sizeProvider } } public protocol AnyCachedLayoutProvider { var lastPerformedLayoutResult: Any? { get } } private final class CachingLayoutProvider<Layout: LayoutModel>: LayoutProviderProtocol { private let _layout: (LayoutContext) throws -> Layout private(set) var lastLayout: Layout? init<Base: LayoutProviderProtocol>(_ base: Base) where Base.Layout == Layout { self._layout = { try base.layout(for: $0) } } func layout(for context: LayoutContext) throws -> Layout { let layout = try self._layout(context) self.lastLayout = layout return layout } } extension CachingLayoutProvider: AnyCachedLayoutProvider { var lastPerformedLayoutResult: Any? { self.lastLayout } }
mit
3e09b1167186d36aa6d0ba18d732b37b
37.282486
138
0.674882
4.741777
false
false
false
false
acegreen/Bitcoin-Sample-iOS-App
Pods/LTMorphingLabel/LTMorphingLabel/LTMorphingLabel+Burn.swift
1
7984
// // LTMorphingLabel+Burn.swift // https://github.com/lexrus/LTMorphingLabel // // The MIT License (MIT) // Copyright (c) 2016 Lex Tang, http://lexrus.com // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files // (the “Software”), to deal in the Software without restriction, // including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, // and to permit persons to whom the Software is furnished to do so, // subject to the following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. // IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY // CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, // TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE // SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // import UIKit extension LTMorphingLabel { fileprivate func burningImageForCharLimbo( _ charLimbo: LTCharacterLimbo, withProgress progress: CGFloat ) -> (UIImage, CGRect) { let maskedHeight = charLimbo.rect.size.height * max(0.01, progress) let maskedSize = CGSize( width: charLimbo.rect.size.width, height: maskedHeight ) UIGraphicsBeginImageContextWithOptions( maskedSize, false, UIScreen.main.scale ) let rect = CGRect( x: 0, y: 0, width: charLimbo.rect.size.width, height: maskedHeight ) String(charLimbo.char).draw(in: rect, withAttributes: [ NSFontAttributeName: self.font, NSForegroundColorAttributeName: self.textColor ]) let newImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() let newRect = CGRect( x: charLimbo.rect.origin.x, y: charLimbo.rect.origin.y, width: charLimbo.rect.size.width, height: maskedHeight ) return (newImage!, newRect) } func BurnLoad() { startClosures["Burn\(LTMorphingPhases.start)"] = { self.emitterView.removeAllEmitters() } progressClosures["Burn\(LTMorphingPhases.progress)"] = { index, progress, isNewChar in if !isNewChar { return min(1.0, max(0.0, progress)) } let j = Float(sin(Float(index))) * 1.5 return min(1.0, max(0.0001, progress + self.morphingCharacterDelay * j)) } effectClosures["Burn\(LTMorphingPhases.disappear)"] = { char, index, progress in return LTCharacterLimbo( char: char, rect: self.previousRects[index], alpha: CGFloat(1.0 - progress), size: self.font.pointSize, drawingProgress: 0.0 ) } effectClosures["Burn\(LTMorphingPhases.appear)"] = { char, index, progress in if char != " " { let rect = self.newRects[index] let emitterPosition = CGPoint( x: rect.origin.x + rect.size.width / 2.0, y: CGFloat(progress) * rect.size.height / 1.2 + rect.origin.y ) self.emitterView.createEmitter( "c\(index)", particleName: "Fire", duration: self.morphingDuration ) { (layer, cell) in layer.emitterSize = CGSize( width: rect.size.width, height: 1 ) layer.renderMode = kCAEmitterLayerAdditive layer.emitterMode = kCAEmitterLayerOutline cell.emissionLongitude = CGFloat(M_PI / 2.0) cell.scale = self.font.pointSize / 160.0 cell.scaleSpeed = self.font.pointSize / 100.0 cell.birthRate = Float(self.font.pointSize) cell.emissionLongitude = CGFloat(arc4random_uniform(30)) cell.emissionRange = CGFloat(M_PI_4) cell.alphaSpeed = self.morphingDuration * -3.0 cell.yAcceleration = 10 cell.velocity = CGFloat(10 + Int(arc4random_uniform(3))) cell.velocityRange = 10 cell.spin = 0 cell.spinRange = 0 cell.lifetime = self.morphingDuration / 3.0 }.update { (layer, cell) in layer.emitterPosition = emitterPosition }.play() self.emitterView.createEmitter( "s\(index)", particleName: "Smoke", duration: self.morphingDuration ) { (layer, cell) in layer.emitterSize = CGSize( width: rect.size.width, height: 10 ) layer.renderMode = kCAEmitterLayerAdditive layer.emitterMode = kCAEmitterLayerVolume cell.emissionLongitude = CGFloat(M_PI / 2.0) cell.scale = self.font.pointSize / 40.0 cell.scaleSpeed = self.font.pointSize / 100.0 cell.birthRate = Float(self.font.pointSize) / Float(arc4random_uniform(10) + 10) cell.emissionLongitude = 0 cell.emissionRange = CGFloat(M_PI_4) cell.alphaSpeed = self.morphingDuration * -3 cell.yAcceleration = -5 cell.velocity = CGFloat(20 + Int(arc4random_uniform(15))) cell.velocityRange = 20 cell.spin = CGFloat(Float(arc4random_uniform(30)) / 10.0) cell.spinRange = 3 cell.lifetime = self.morphingDuration }.update { (layer, cell) in layer.emitterPosition = emitterPosition }.play() } return LTCharacterLimbo( char: char, rect: self.newRects[index], alpha: 1.0, size: self.font.pointSize, drawingProgress: CGFloat(progress) ) } drawingClosures["Burn\(LTMorphingPhases.draw)"] = { (charLimbo: LTCharacterLimbo) in if charLimbo.drawingProgress > 0.0 { let (charImage, rect) = self.burningImageForCharLimbo( charLimbo, withProgress: charLimbo.drawingProgress ) charImage.draw(in: rect) return true } return false } skipFramesClosures["Burn\(LTMorphingPhases.skipFrames)"] = { return 1 } } }
mit
26453128626aa8ffe2609391fffa73d5
38.88
84
0.498621
5.508287
false
false
false
false
Limon-O-O/Lego
Modules/Lego/Lego/AppDelegate.swift
1
1841
// // AppDelegate.swift // Lego // // Created by Limon.F on 19/2/2017. // Copyright © 2017 Limon.F. All rights reserved. // import UIKit import Mediator import Networking import Mediator_Door @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { let didLogin = Mediator.shared.door.didLogin() Networking.ServiceConfigure.accessToken = Mediator.shared.door.accessToken() if !didLogin { // startDoorStory() } return true } func applicationWillResignActive(_ application: UIApplication) {} func applicationDidEnterBackground(_ application: UIApplication) {} func applicationWillEnterForeground(_ application: UIApplication) {} func applicationDidBecomeActive(_ application: UIApplication) {} func applicationWillTerminate(_ application: UIApplication) {} } // MARK: - Custom Methods extension AppDelegate { func startDoorStory() { let callbackAction: ([String: Any]) -> Void = { [weak self] info in guard let _ = info["userID"] as? Int else { return } self?.startMainStory() print("Door callbacked with info: \(info)") } guard let welcomeViewController = Mediator.shared.door.welcomeViewController(callbackAction) else { return } window?.rootViewController = welcomeViewController } func startMainStory() { let storyboard = UIStoryboard(name: "Main", bundle: nil) let rootViewController = storyboard.instantiateViewController(withIdentifier: "MainTabBarController") window?.rootViewController = rootViewController } }
mit
41fc4624cfc468d3f4c74027db4e85f0
24.205479
144
0.685326
5.287356
false
false
false
false
wowiwj/WDayDayCook
WDayDayCook/WDayDayCook/Controllers/Mine/MineFootPrintsViewController.swift
1
4342
// // MineFootPrintsViewController.swift // WDayDayCook // // Created by wangju on 16/9/12. // Copyright © 2016年 wangju. All rights reserved. // import UIKit private let reuseIdentifier = "Cell" class MineFootPrintsViewController: UICollectionViewController { override func viewDidLoad() { super.viewDidLoad() collectionView?.backgroundColor = UIColor.yellow // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Register cell classes self.collectionView!.register(UICollectionViewCell.self, forCellWithReuseIdentifier: reuseIdentifier) WDHUD.setContainerView(toView: self.collectionView!, parentView: {(containerView) in let messageView = ShowHUBMessage() containerView.addSubview(messageView) messageView.frame = containerView.bounds messageView.descriptionLabel.text = "四处逛逛,开启美味之旅吧" messageView.infoButton.setTitle("去逛逛", for: UIControlState()) messageView.infoButton.addTarget(self, action: #selector(MineFootPrintsViewController.messageInfoButtonClicked), for: UIControlEvents.touchUpInside) }) showHUB() // Do any additional setup after loading the view. } func showHUB() { WDHUD.showInView(self.collectionView) } func hideHUB() { WDHUD.hideInView(self.collectionView) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using [segue destinationViewController]. // Pass the selected object to the new view controller. } */ // MARK: UICollectionViewDataSource override func numberOfSections(in collectionView: UICollectionView) -> Int { // #warning Incomplete implementation, return the number of sections return 0 } override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of items return 0 } override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) // Configure the cell return cell } // MARK: UICollectionViewDelegate /* // Uncomment this method to specify if the specified item should be highlighted during tracking override func collectionView(collectionView: UICollectionView, shouldHighlightItemAtIndexPath indexPath: NSIndexPath) -> Bool { return true } */ /* // Uncomment this method to specify if the specified item should be selected override func collectionView(collectionView: UICollectionView, shouldSelectItemAtIndexPath indexPath: NSIndexPath) -> Bool { return true } */ /* // Uncomment these methods to specify if an action menu should be displayed for the specified item, and react to actions performed on the item override func collectionView(collectionView: UICollectionView, shouldShowMenuForItemAtIndexPath indexPath: NSIndexPath) -> Bool { return false } override func collectionView(collectionView: UICollectionView, canPerformAction action: Selector, forItemAtIndexPath indexPath: NSIndexPath, withSender sender: AnyObject?) -> Bool { return false } override func collectionView(collectionView: UICollectionView, performAction action: Selector, forItemAtIndexPath indexPath: NSIndexPath, withSender sender: AnyObject?) { } */ // MARK: - 消息的监听 @objc fileprivate func messageInfoButtonClicked() { self.tabBarController?.selectedIndex = 0 } }
mit
0e257389be2779aa692da4bb06c62759
31.568182
185
0.686206
5.817321
false
false
false
false
stardust139/ios-charts
Charts/Classes/Charts/RadarChartView.swift
1
9370
// // RadarChartView.swift // Charts // // Created by Daniel Cohen Gindi on 4/3/15. // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/ios-charts // import Foundation import CoreGraphics import UIKit /// Implementation of the RadarChart, a "spidernet"-like chart. It works best /// when displaying 5-10 entries per DataSet. public class RadarChartView: PieRadarChartViewBase { /// width of the web lines that come from the center. public var webLineWidth = CGFloat(1.5) /// width of the web lines that are in between the lines coming from the center public var innerWebLineWidth = CGFloat(0.75) /// color for the web lines that come from the center public var webColor = UIColor(red: 122/255.0, green: 122/255.0, blue: 122.0/255.0, alpha: 1.0) /// color for the web lines in between the lines that come from the center. public var innerWebColor = UIColor(red: 122/255.0, green: 122/255.0, blue: 122.0/255.0, alpha: 1.0) /// transparency the grid is drawn with (0.0 - 1.0) public var webAlpha: CGFloat = 150.0 / 255.0 /// flag indicating if the web lines should be drawn or not public var drawWeb = true /// modulus that determines how many labels and web-lines are skipped before the next is drawn private var _skipWebLineCount = 0 /// the object reprsenting the y-axis labels private var _yAxis: ChartYAxis! /// the object representing the x-axis labels private var _xAxis: ChartXAxis! internal var _yAxisRenderer: ChartYAxisRendererRadarChart! internal var _xAxisRenderer: ChartXAxisRendererRadarChart! public override init(frame: CGRect) { super.init(frame: frame) } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } internal override func initialize() { super.initialize() _yAxis = ChartYAxis(position: .Left) _xAxis = ChartXAxis() _xAxis.spaceBetweenLabels = 0 renderer = RadarChartRenderer(chart: self, animator: _animator, viewPortHandler: _viewPortHandler) _yAxisRenderer = ChartYAxisRendererRadarChart(viewPortHandler: _viewPortHandler, yAxis: _yAxis, chart: self) _xAxisRenderer = ChartXAxisRendererRadarChart(viewPortHandler: _viewPortHandler, xAxis: _xAxis, chart: self) } internal override func calcMinMax() { super.calcMinMax() let minLeft = _data.getYMin(.Left) let maxLeft = _data.getYMax(.Left) _chartXMax = Double(_data.xVals.count) - 1.0 _deltaX = CGFloat(abs(_chartXMax - _chartXMin)) let leftRange = CGFloat(abs(maxLeft - (_yAxis.isStartAtZeroEnabled ? 0.0 : minLeft))) let topSpaceLeft = Double(leftRange * _yAxis.spaceTop) let bottomSpaceLeft = Double(leftRange * _yAxis.spaceBottom) // Consider sticking one of the edges of the axis to zero (0.0) if _yAxis.isStartAtZeroEnabled { if minLeft < 0.0 && maxLeft < 0.0 { // If the values are all negative, let's stay in the negative zone _yAxis.axisMinimum = min(0.0, !isnan(_yAxis.customAxisMin) ? _yAxis.customAxisMin : (minLeft - bottomSpaceLeft)) _yAxis.axisMaximum = 0.0 } else if minLeft >= 0.0 { // We have positive values only, stay in the positive zone _yAxis.axisMinimum = 0.0 _yAxis.axisMaximum = max(0.0, !isnan(_yAxis.customAxisMax) ? _yAxis.customAxisMax : (maxLeft + topSpaceLeft)) } else { // Stick the minimum to 0.0 or less, and maximum to 0.0 or more (startAtZero for negative/positive at the same time) _yAxis.axisMinimum = min(0.0, !isnan(_yAxis.customAxisMin) ? _yAxis.customAxisMin : (minLeft - bottomSpaceLeft)) _yAxis.axisMaximum = max(0.0, !isnan(_yAxis.customAxisMax) ? _yAxis.customAxisMax : (maxLeft + topSpaceLeft)) } } else { // Use the values as they are _yAxis.axisMinimum = !isnan(_yAxis.customAxisMin) ? _yAxis.customAxisMin : (minLeft - bottomSpaceLeft) _yAxis.axisMaximum = !isnan(_yAxis.customAxisMax) ? _yAxis.customAxisMax : (maxLeft + topSpaceLeft) } _chartXMax = Double(_data.xVals.count) - 1.0 _deltaX = CGFloat(abs(_chartXMax - _chartXMin)) _yAxis.axisRange = abs(_yAxis.axisMaximum - _yAxis.axisMinimum) } public override func getMarkerPosition(entry entry: ChartDataEntry, highlight: ChartHighlight) -> CGPoint { let angle = self.sliceAngle * CGFloat(entry.xIndex) + self.rotationAngle let val = CGFloat(entry.value) * self.factor let c = self.centerOffsets let p = CGPoint(x: c.x + val * cos(angle * ChartUtils.Math.FDEG2RAD), y: c.y + val * sin(angle * ChartUtils.Math.FDEG2RAD)) return p } public override func notifyDataSetChanged() { if (_dataNotSet) { return } calcMinMax() _yAxis?._defaultValueFormatter = _defaultValueFormatter _yAxisRenderer?.computeAxis(yMin: _yAxis.axisMinimum, yMax: _yAxis.axisMaximum) _xAxisRenderer?.computeAxis(xValAverageLength: _data.xValAverageLength, xValues: _data.xVals) if (_legend !== nil && !_legend.isLegendCustom) { _legendRenderer?.computeLegend(_data) } calculateOffsets() setNeedsDisplay() } public override func drawRect(rect: CGRect) { super.drawRect(rect) if (_dataNotSet) { return } let optionalContext = UIGraphicsGetCurrentContext() guard let context = optionalContext else { return } _xAxisRenderer?.renderAxisLabels(context: context) if (drawWeb) { renderer!.drawExtras(context: context) } _yAxisRenderer.renderLimitLines(context: context) renderer!.drawData(context: context) if (valuesToHighlight()) { renderer!.drawHighlighted(context: context, indices: _indicesToHighlight) } _yAxisRenderer.renderAxisLabels(context: context) renderer!.drawValues(context: context) _legendRenderer.renderLegend(context: context) drawDescription(context: context) drawMarkers(context: context) } /// - returns: the factor that is needed to transform values into pixels. public var factor: CGFloat { let content = _viewPortHandler.contentRect return min(content.width / 2.0, content.height / 2.0) / CGFloat(_yAxis.axisRange) } /// - returns: the angle that each slice in the radar chart occupies. public var sliceAngle: CGFloat { return 360.0 / CGFloat(_data.xValCount) } public override func indexForAngle(angle: CGFloat) -> Int { // take the current angle of the chart into consideration let a = ChartUtils.normalizedAngleFromAngle(angle - self.rotationAngle) let sliceAngle = self.sliceAngle for (var i = 0; i < _data.xValCount; i++) { if (sliceAngle * CGFloat(i + 1) - sliceAngle / 2.0 > a) { return i } } return 0 } /// - returns: the object that represents all y-labels of the RadarChart. public var yAxis: ChartYAxis { return _yAxis } /// - returns: the object that represents all x-labels that are placed around the RadarChart. public var xAxis: ChartXAxis { return _xAxis } /// Sets the number of web-lines that should be skipped on chart web before the next one is drawn. This targets the lines that come from the center of the RadarChart. /// if count = 1 -> 1 line is skipped in between public var skipWebLineCount: Int { get { return _skipWebLineCount } set { _skipWebLineCount = max(0, newValue) } } internal override var requiredLegendOffset: CGFloat { return _legend.font.pointSize * 4.0 } internal override var requiredBaseOffset: CGFloat { return _xAxis.isEnabled && _xAxis.isDrawLabelsEnabled ? _xAxis.labelWidth : 10.0 } public override var radius: CGFloat { let content = _viewPortHandler.contentRect return min(content.width / 2.0, content.height / 2.0) } /// - returns: the maximum value this chart can display on it's y-axis. public override var chartYMax: Double { return _yAxis.axisMaximum; } /// - returns: the minimum value this chart can display on it's y-axis. public override var chartYMin: Double { return _yAxis.axisMinimum; } /// - returns: the range of y-values this chart can display. public var yRange: Double { return _yAxis.axisRange} }
apache-2.0
9f984db1ad95256532e26b9f180e8586
31.996479
170
0.610886
4.741903
false
false
false
false
smartmobilefactory/FolioReaderKit
Source/EPUBCore/FRResource.swift
5
703
// // FRResource.swift // FolioReaderKit // // Created by Heberti Almeida on 29/04/15. // Copyright (c) 2015 Folio Reader. All rights reserved. // import UIKit class FRResource: NSObject { var id: String! var properties: String? var href: String! var fullHref: String! var mediaType: MediaType! var mediaOverlay: String? func basePath() -> String! { if href == nil || href.isEmpty { return nil } var paths = fullHref.components(separatedBy: "/") paths.removeLast() return paths.joined(separator: "/") } } // MARK: Equatable func ==(lhs: FRResource, rhs: FRResource) -> Bool { return lhs.id == rhs.id && lhs.href == rhs.href }
bsd-3-clause
be79f881e1c9e4bc57964c0fe335163b
21.677419
57
0.625889
3.820652
false
false
false
false
badoo/Chatto
Chatto/sources/ChatController/ChatMessages/ChatMessageCollectionAdapter.swift
1
32902
// // Copyright (c) Badoo Trading Limited, 2010-present. All rights reserved. // import UIKit public protocol CompanionCollectionProvider { var chatItemCompanionCollection: ChatItemCompanionCollection { get } } public protocol ChatMessageCollectionAdapterProtocol: CompanionCollectionProvider, UICollectionViewDataSource, UICollectionViewDelegate { var delegate: ChatMessageCollectionAdapterDelegate? { get set } func startProcessingUpdates() func stopProcessingUpdates() func setup(in collectionView: UICollectionView) // TODO: Remove from the adapter func indexPath(of itemId: String) -> IndexPath? func refreshContent(completionBlock: (() -> Void)?) func scheduleSpotlight(for itemId: String) } extension ChatMessageCollectionAdapterProtocol { public func indexPath(of itemId: String) -> IndexPath? { guard let itemIndex = self.chatItemCompanionCollection.indexOf(itemId) else { return nil } return IndexPath(row: itemIndex, section: 0) } } public protocol ChatMessageCollectionAdapterDelegate: AnyObject { var isFirstLoad: Bool { get } func chatMessageCollectionAdapterDidUpdateItems(withUpdateType updateType: UpdateType) func chatMessageCollectionAdapterShouldAnimateCellOnDisplay() -> Bool } public typealias ReferenceIndexPathRestoreProvider = (ChatItemCompanionCollection, CollectionChanges) -> (IndexPath?, IndexPath?) // TODO: Add unit tests /** Component responsible to coordinate all chat messages updates and their display logic in a collection view. After its initialisation, this component will start observing view model updates and dispatch update operations into the `updateQueue`. Taking into account the initial `configuration` injected into this component, whenever we receive a chat items update call, the elements difference between updates gets calculated and propagated into the collection view. In order to decouple this component from the customisation of elements to be displayed, we delegate this responsibility to the `chatItemsDecorator` and `chatItemPresenterFactory` injected during its initialisation. These item customisation components will be used while presenting chat items in the collection view. */ public final class ChatMessageCollectionAdapter: NSObject, ChatMessageCollectionAdapterProtocol { private let chatItemsDecorator: ChatItemsDecoratorProtocol private let chatItemPresenterFactory: ChatItemPresenterFactoryProtocol private let chatMessagesViewModel: ChatMessagesViewModelProtocol private let configuration: Configuration private let referenceIndexPathRestoreProvider: ReferenceIndexPathRestoreProvider private let collectionUpdatesQueue: SerialTaskQueueProtocol private var nextDidEndScrollingAnimationHandlers: [() -> Void] private var isFirstUpdate: Bool // TODO: To remove private weak var collectionView: UICollectionView? public weak var delegate: ChatMessageCollectionAdapterDelegate? // TODO: Check properties that can be moved to private private(set) var isLoadingContents: Bool private(set) var layoutModel = ChatCollectionViewLayoutModel.createModel(0, itemsLayoutData: []) private(set) var onAllBatchUpdatesFinished: (() -> Void)? private(set) var unfinishedBatchUpdatesCount: Int = 0 private(set) var visibleCells: [IndexPath: UICollectionViewCell] = [:] // @see visibleCellsAreValid(changes:) private let presentersByCell = NSMapTable<UICollectionViewCell, AnyObject>(keyOptions: .weakMemory, valueOptions: .weakMemory) public private(set) var chatItemCompanionCollection = ChatItemCompanionCollection(items: []) public init(chatItemsDecorator: ChatItemsDecoratorProtocol, chatItemPresenterFactory: ChatItemPresenterFactoryProtocol, chatMessagesViewModel: ChatMessagesViewModelProtocol, configuration: Configuration, referenceIndexPathRestoreProvider: @escaping ReferenceIndexPathRestoreProvider, updateQueue: SerialTaskQueueProtocol) { self.chatItemsDecorator = chatItemsDecorator self.chatItemPresenterFactory = chatItemPresenterFactory self.chatMessagesViewModel = chatMessagesViewModel self.configuration = configuration self.referenceIndexPathRestoreProvider = referenceIndexPathRestoreProvider self.collectionUpdatesQueue = updateQueue self.isFirstUpdate = true self.isLoadingContents = true self.nextDidEndScrollingAnimationHandlers = [] super.init() self.configureChatMessagesViewModel() } public func startProcessingUpdates() { self.collectionUpdatesQueue.start() } public func stopProcessingUpdates() { self.collectionUpdatesQueue.stop() } private func configureChatMessagesViewModel() { self.chatMessagesViewModel.delegate = self } public func setup(in collectionView: UICollectionView) { collectionView.dataSource = self if self.configuration.isRegisteringPresentersAutomatically { self.chatItemPresenterFactory.configure(withCollectionView: collectionView) } self.collectionView = collectionView } public func refreshContent(completionBlock: (() -> Void)?) { self.enqueueModelUpdate(updateType: .normal, completionBlock: completionBlock) } public func scheduleSpotlight(for itemId: String) { guard let collectionView = self.collectionView else { return } guard let itemIndexPath = self.indexPath(of: itemId) else { return } guard let presenter = self.chatItemCompanionCollection[itemId]?.presenter else { return } let contentOffsetWillBeChanged = !collectionView.indexPathsForVisibleItems.contains(itemIndexPath) if contentOffsetWillBeChanged { self.nextDidEndScrollingAnimationHandlers.append { [weak presenter] in presenter?.spotlight() } } else { presenter.spotlight() } } } extension ChatMessageCollectionAdapter: ChatDataSourceDelegateProtocol { public func chatDataSourceDidUpdate(_ chatDataSource: ChatDataSourceProtocol) { self.enqueueModelUpdate(updateType: .normal) } public func chatDataSourceDidUpdate(_ chatDataSource: ChatDataSourceProtocol, updateType: UpdateType) { if !self.configuration.isRegisteringPresentersAutomatically && self.isFirstUpdate, let collectionView = self.collectionView { self.chatItemPresenterFactory.configure(withCollectionView: collectionView) self.isFirstUpdate = false } self.enqueueModelUpdate(updateType: updateType) } private func enqueueModelUpdate(updateType: UpdateType, completionBlock: (() -> Void)? = nil) { if self.configuration.coalesceUpdates { self.collectionUpdatesQueue.flushQueue() } let updateBlock: TaskClosure = { [weak self] runNextTask in guard let sSelf = self else { return } let oldItems = sSelf.chatItemCompanionCollection let newItems = sSelf.chatMessagesViewModel.chatItems sSelf.updateModels( newItems: newItems, oldItems: oldItems, updateType: updateType ) { guard let sSelf = self else { return } if sSelf.collectionUpdatesQueue.isEmpty { sSelf.enqueueMessageCountReductionIfNeeded() } sSelf.delegate?.chatMessageCollectionAdapterDidUpdateItems(withUpdateType: updateType) completionBlock?() DispatchQueue.main.async { // Reduces inconsistencies before next update: https://github.com/diegosanchezr/UICollectionViewStressing runNextTask() } } } self.collectionUpdatesQueue.addTask(updateBlock) } private func updateModels(newItems: [ChatItemProtocol], oldItems: ChatItemCompanionCollection, updateType: UpdateType, completion: @escaping () -> Void) { guard let collectionView = self.collectionView else { completion() return } let collectionViewWidth = collectionView.bounds.width let updateType: UpdateType = (self.delegate?.isFirstLoad == true) ? .firstLoad : updateType let performInBackground = updateType != .firstLoad self.isLoadingContents = true let performBatchUpdates: (CollectionChanges, @escaping () -> Void) -> Void = { [weak self] changes, updateModelClosure in self?.performBatchUpdates( updateModelClosure: updateModelClosure, changes: changes, updateType: updateType ) { self?.isLoadingContents = false completion() } } let createModelUpdate = { [weak self] in return self?.createModelUpdates( newItems: newItems, oldItems: oldItems, collectionViewWidth: collectionViewWidth ) } if performInBackground { DispatchQueue.global(qos: .userInitiated).async { guard let modelUpdate = createModelUpdate() else { return } DispatchQueue.main.async { performBatchUpdates(modelUpdate.changes, modelUpdate.updateModelClosure) } } } else { guard let modelUpdate = createModelUpdate() else { return } performBatchUpdates(modelUpdate.changes, modelUpdate.updateModelClosure) } } private func enqueueMessageCountReductionIfNeeded() { let chatItems = self.chatMessagesViewModel.chatItems guard let preferredMaxMessageCount = self.configuration.preferredMaxMessageCount, chatItems.count > preferredMaxMessageCount else { return } self.collectionUpdatesQueue.addTask { [weak self] completion in guard let sSelf = self else { return } sSelf.chatMessagesViewModel.adjustNumberOfMessages( preferredMaxCount: sSelf.configuration.preferredMaxMessageCountAdjustment, focusPosition: sSelf.focusPosition ) { didAdjust in guard didAdjust, let sSelf = self else { completion() return } let newItems = sSelf.chatMessagesViewModel.chatItems let oldItems = sSelf.chatItemCompanionCollection sSelf.updateModels( newItems: newItems, oldItems: oldItems, updateType: .messageCountReduction, completion: completion ) } } } private func createModelUpdates(newItems: [ChatItemProtocol], oldItems: ChatItemCompanionCollection, collectionViewWidth: CGFloat) -> (changes: CollectionChanges, updateModelClosure: () -> Void) { let newDecoratedItems = self.chatItemsDecorator.decorateItems(newItems) let changes = generateChanges( oldCollection: oldItems.map(HashableItem.init), newCollection: newDecoratedItems.map(HashableItem.init) ) let itemCompanionCollection = self.createCompanionCollection(fromChatItems: newDecoratedItems, previousCompanionCollection: oldItems) let layoutModel = self.createLayoutModel(itemCompanionCollection, collectionViewWidth: collectionViewWidth) let updateModelClosure : () -> Void = { [weak self] in self?.layoutModel = layoutModel self?.chatItemCompanionCollection = itemCompanionCollection } return (changes, updateModelClosure) } // Returns scrolling position in interval [0, 1], 0 top, 1 bottom public var focusPosition: Double { guard let collectionView = self.collectionView else { return 0 } if collectionView.isCloseToBottom(threshold: self.configuration.autoloadingFractionalThreshold) { return 1 } if collectionView.isCloseToTop(threshold: self.configuration.autoloadingFractionalThreshold) { return 0 } let contentHeight = collectionView.contentSize.height guard contentHeight > 0 else { return 0.5 } // Rough estimation let collectionViewContentYOffset = collectionView.contentOffset.y let midContentOffset = collectionViewContentYOffset + collectionView.visibleRect().height / 2 return min(max(0, Double(midContentOffset / contentHeight)), 1.0) } private func createCompanionCollection(fromChatItems newItems: [DecoratedChatItem], previousCompanionCollection oldItems: ChatItemCompanionCollection) -> ChatItemCompanionCollection { return ChatItemCompanionCollection(items: newItems.map { (decoratedChatItem) -> ChatItemCompanion in /* We use an assumption, that message having a specific messageId never changes its type. If such changes has to be supported, then generation of changes has to suppport reloading items. Otherwise, updateVisibleCells may try to update the existing cells with new presenters which aren't able to work with another types. */ let presenter: ChatItemPresenterProtocol = { guard let oldChatItemCompanion = oldItems[decoratedChatItem.uid] ?? oldItems[decoratedChatItem.chatItem.uid], oldChatItemCompanion.chatItem.type == decoratedChatItem.chatItem.type, oldChatItemCompanion.presenter.isItemUpdateSupported else { return self.chatItemPresenterFactory.createChatItemPresenter(decoratedChatItem.chatItem) } oldChatItemCompanion.presenter.update(with: decoratedChatItem.chatItem) return oldChatItemCompanion.presenter }() return ChatItemCompanion(uid: decoratedChatItem.uid, chatItem: decoratedChatItem.chatItem, presenter: presenter, decorationAttributes: decoratedChatItem.decorationAttributes) }) } private func createLayoutModel(_ items: ChatItemCompanionCollection, collectionViewWidth: CGFloat) -> ChatCollectionViewLayoutModel { // swiftlint:disable:next nesting typealias IntermediateItemLayoutData = (height: CGFloat?, bottomMargin: CGFloat) typealias ItemLayoutData = (height: CGFloat, bottomMargin: CGFloat) // swiftlint:disable:previous nesting func createLayoutModel(intermediateLayoutData: [IntermediateItemLayoutData]) -> ChatCollectionViewLayoutModel { let layoutData = intermediateLayoutData.map { (intermediateLayoutData: IntermediateItemLayoutData) -> ItemLayoutData in return (height: intermediateLayoutData.height!, bottomMargin: intermediateLayoutData.bottomMargin) } return ChatCollectionViewLayoutModel.createModel(collectionViewWidth, itemsLayoutData: layoutData) } let isInBackground = !Thread.isMainThread var intermediateLayoutData = [IntermediateItemLayoutData]() var itemsForMainThread = [(index: Int, itemCompanion: ChatItemCompanion)]() for (index, itemCompanion) in items.enumerated() { var height: CGFloat? let bottomMargin: CGFloat = itemCompanion.decorationAttributes?.bottomMargin ?? 0 if !isInBackground || itemCompanion.presenter.canCalculateHeightInBackground { height = itemCompanion.presenter.heightForCell(maximumWidth: collectionViewWidth, decorationAttributes: itemCompanion.decorationAttributes) } else { itemsForMainThread.append((index: index, itemCompanion: itemCompanion)) } intermediateLayoutData.append((height: height, bottomMargin: bottomMargin)) } if itemsForMainThread.count > 0 { DispatchQueue.main.sync { for (index, itemCompanion) in itemsForMainThread { let height = itemCompanion.presenter.heightForCell( maximumWidth: collectionViewWidth, decorationAttributes: itemCompanion.decorationAttributes ) intermediateLayoutData[index].height = height } } } return createLayoutModel(intermediateLayoutData: intermediateLayoutData) } private func performBatchUpdates(updateModelClosure: @escaping () -> Void, // swiftlint:disable:this cyclomatic_complexity changes: CollectionChanges, updateType: UpdateType, completion: @escaping () -> Void) { guard let collectionView = self.collectionView else { completion() return } let usesBatchUpdates: Bool do { // Recover from too fast updates... let visibleCellsAreValid = self.visibleCellsAreValid(changes: changes) let wantsReloadData = updateType != .normal && updateType != .firstSync let hasUnfinishedBatchUpdates = self.unfinishedBatchUpdatesCount > 0 // This can only happen when enabling self.updatesConfig.fastUpdates // a) It's unsafe to perform reloadData while there's a performBatchUpdates animating: https://github.com/diegosanchezr/UICollectionViewStressing/tree/master/GhostCells // Note: using reloadSections instead reloadData is safe and might not need a delay. However, using always reloadSections causes flickering on pagination and a crash on the first layout that needs a workaround. Let's stick to reloaData for now // b) If it's a performBatchUpdates but visible cells are invalid let's wait until all finish (otherwise we would give wrong cells to presenters in updateVisibleCells) let mustDelayUpdate = hasUnfinishedBatchUpdates && (wantsReloadData || !visibleCellsAreValid) guard !mustDelayUpdate else { // For reference, it is possible to force the current performBatchUpdates to finish in the next run loop, by cancelling animations: // self.collectionView.subviews.forEach { $0.layer.removeAllAnimations() } self.onAllBatchUpdatesFinished = { [weak self] in self?.onAllBatchUpdatesFinished = nil self?.performBatchUpdates( updateModelClosure: updateModelClosure, changes: changes, updateType: updateType, completion: completion ) } return } // ... if they are still invalid the only thing we can do is a reloadData let mustDoReloadData = !visibleCellsAreValid // Only way to recover from this inconsistent state usesBatchUpdates = !wantsReloadData && !mustDoReloadData } let scrollAction: ScrollAction do { // Scroll action if updateType != .pagination && updateType != .firstSync && collectionView.isScrolledAtBottom() { scrollAction = .scrollToBottom } else { let (oldReferenceIndexPath, newReferenceIndexPath) = self.referenceIndexPathRestoreProvider(self.chatItemCompanionCollection, changes) let oldRect = self.rectAtIndexPath(oldReferenceIndexPath) scrollAction = .preservePosition( rectForReferenceIndexPathBeforeUpdate: oldRect, referenceIndexPathAfterUpdate: newReferenceIndexPath ) } } let myCompletion: () -> Void do { // Completion var myCompletionExecuted = false myCompletion = { if myCompletionExecuted { return } myCompletionExecuted = true completion() } } let adjustScrollViewToBottom = { [weak self, weak collectionView] in guard let sSelf = self, let collectionView = collectionView else { return } switch scrollAction { case .scrollToBottom: collectionView.scrollToBottom( animated: updateType == .normal, animationDuration: sSelf.configuration.updatesAnimationDuration ) case .preservePosition(let oldRect, let indexPath): let newRect = sSelf.rectAtIndexPath(indexPath) collectionView.scrollToPreservePosition(oldRefRect: oldRect, newRefRect: newRect) } } if usesBatchUpdates { UIView.animate( withDuration: self.configuration.updatesAnimationDuration, animations: { [weak self] () -> Void in guard let sSelf = self else { return } sSelf.unfinishedBatchUpdatesCount += 1 collectionView.performBatchUpdates({ [weak self] in guard let sSelf = self else { return } updateModelClosure() sSelf.updateVisibleCells(changes) // For instance, to support removal of tails collectionView.deleteItems(at: Array(changes.deletedIndexPaths)) collectionView.insertItems(at: Array(changes.insertedIndexPaths)) for move in changes.movedIndexPaths { collectionView.moveItem(at: move.indexPathOld, to: move.indexPathNew) } }, completion: { [weak self] _ in defer { myCompletion() } guard let sSelf = self else { return } sSelf.unfinishedBatchUpdatesCount -= 1 if sSelf.unfinishedBatchUpdatesCount == 0, let onAllBatchUpdatesFinished = self?.onAllBatchUpdatesFinished { DispatchQueue.main.async(execute: onAllBatchUpdatesFinished) } }) } ) } else { self.visibleCells = [:] updateModelClosure() collectionView.reloadData() collectionView.collectionViewLayout.prepare() collectionView.setNeedsLayout() collectionView.layoutIfNeeded() } adjustScrollViewToBottom() if !usesBatchUpdates || self.configuration.fastUpdates { myCompletion() } } private func visibleCellsAreValid(changes: CollectionChanges) -> Bool { guard self.configuration.fastUpdates else { return true } // After performBatchUpdates, indexPathForCell may return a cell refering to the state before the update // if self.updatesConfig.fastUpdates is enabled, very fast updates could result in `updateVisibleCells` updating wrong cells. // See more: https://github.com/diegosanchezr/UICollectionViewStressing let updatesFromVisibleCells = updated(collection: self.visibleCells, withChanges: changes) let updatesFromCollectionViewApi = updated(collection: self.visibleCellsFromCollectionViewApi(), withChanges: changes) return updatesFromVisibleCells == updatesFromCollectionViewApi } private func visibleCellsFromCollectionViewApi() -> [IndexPath: UICollectionViewCell] { guard let collectionView = self.collectionView else { return [:] } var visibleCells: [IndexPath: UICollectionViewCell] = [:] collectionView.indexPathsForVisibleItems.forEach { indexPath in guard let cell = collectionView.cellForItem(at: indexPath) else { return } visibleCells[indexPath] = cell } return visibleCells } private func rectAtIndexPath(_ indexPath: IndexPath?) -> CGRect? { guard let collectionView = self.collectionView else { return nil } guard let indexPath = indexPath else { return nil } return collectionView.collectionViewLayout.layoutAttributesForItem(at: indexPath)?.frame } private func updateVisibleCells(_ changes: CollectionChanges) { // Datasource should be already updated! assert(self.visibleCellsAreValid(changes: changes), "Invalid visible cells. Don't call me") let cellsToUpdate = updated(collection: self.visibleCellsFromCollectionViewApi(), withChanges: changes) self.visibleCells = cellsToUpdate cellsToUpdate.forEach { (indexPath, cell) in let presenter = self.presenterForIndex( indexPath.item, chatItemCompanionCollection: self.chatItemCompanionCollection ) presenter.configureCell(cell, decorationAttributes: self.chatItemCompanionCollection[indexPath.item].decorationAttributes) presenter.cellWillBeShown(cell) // `createModelUpdates` may have created a new presenter instance for existing visible cell so we need to tell it that its cell is visible } } private func presenterForIndexPath(_ indexPath: IndexPath) -> ChatItemPresenterProtocol { return self.presenterForIndex( indexPath.item, chatItemCompanionCollection: self.chatItemCompanionCollection ) } private func presenterForIndex(_ index: Int, chatItemCompanionCollection items: ChatItemCompanionCollection) -> ChatItemPresenterProtocol { // This can happen from didEndDisplayingCell if we reloaded with less messages return index < items.count ? items[index].presenter : DummyChatItemPresenter() } } extension ChatMessageCollectionAdapter: ChatCollectionViewLayoutModelProviderProtocol { public var chatCollectionViewLayoutModel: ChatCollectionViewLayoutModel { guard let collectionView = self.collectionView else { return self.layoutModel } if self.layoutModel.calculatedForWidth != collectionView.bounds.width { self.layoutModel = self.createLayoutModel( self.chatItemCompanionCollection, collectionViewWidth: collectionView.bounds.width ) } return self.layoutModel } } extension ChatMessageCollectionAdapter { public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return self.chatItemCompanionCollection.count } public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let presenter = self.presenterForIndexPath(indexPath) let cell = presenter.dequeueCell(collectionView: collectionView, indexPath: indexPath) let decorationAttributes = self.chatItemCompanionCollection[indexPath.item].decorationAttributes presenter.configureCell(cell, decorationAttributes: decorationAttributes) return cell } } extension ChatMessageCollectionAdapter { public func collectionView(_ collectionView: UICollectionView, didEndDisplaying cell: UICollectionViewCell, forItemAt indexPath: IndexPath) { // Carefull: this index path can refer to old data source after an update. Don't use it to grab items from the model // Instead let's use a mapping presenter <--> cell if let oldPresenterForCell = self.presentersByCell.object(forKey: cell) as? ChatItemPresenterProtocol { self.presentersByCell.removeObject(forKey: cell) oldPresenterForCell.cellWasHidden(cell) } guard self.configuration.fastUpdates else { return } if let visibleCell = self.visibleCells[indexPath], visibleCell === cell { self.visibleCells[indexPath] = nil } else { self.visibleCells.forEach { indexPath, storedCell in guard cell === storedCell else { return } // Inconsistency found, likely due to very fast updates self.visibleCells[indexPath] = nil } } } public func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) { // Here indexPath should always referer to updated data source. let presenter = self.presenterForIndexPath(indexPath) self.presentersByCell.setObject(presenter, forKey: cell) if self.configuration.fastUpdates { self.visibleCells[indexPath] = cell } let shouldAnimate = self.delegate?.chatMessageCollectionAdapterShouldAnimateCellOnDisplay() ?? false if !shouldAnimate { UIView.performWithoutAnimation { // See https://github.com/badoo/Chatto/issues/133 presenter.cellWillBeShown(cell) cell.layoutIfNeeded() } } else { presenter.cellWillBeShown(cell) } } public func collectionView(_ collectionView: UICollectionView, shouldShowMenuForItemAt indexPath: IndexPath) -> Bool { return self.presenterForIndexPath(indexPath).shouldShowMenu() } public func collectionView(_ collectionView: UICollectionView, canPerformAction action: Selector, forItemAt indexPath: IndexPath, withSender sender: Any?) -> Bool { return self.presenterForIndexPath(indexPath).canPerformMenuControllerAction(action) } public func collectionView(_ collectionView: UICollectionView, performAction action: Selector, forItemAt indexPath: IndexPath, withSender sender: Any?) { self.presenterForIndexPath(indexPath).performMenuControllerAction(action) } public func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) { for handler in self.nextDidEndScrollingAnimationHandlers { handler() } self.nextDidEndScrollingAnimationHandlers = [] } } public extension ChatMessageCollectionAdapter { struct Configuration { public var autoloadingFractionalThreshold: CGFloat public var coalesceUpdates: Bool public var fastUpdates: Bool public var isRegisteringPresentersAutomatically: Bool public var preferredMaxMessageCount: Int? public var preferredMaxMessageCountAdjustment: Int public var updatesAnimationDuration: TimeInterval public init(autoloadingFractionalThreshold: CGFloat, coalesceUpdates: Bool, fastUpdates: Bool, isRegisteringPresentersAutomatically: Bool, preferredMaxMessageCount: Int?, preferredMaxMessageCountAdjustment: Int, updatesAnimationDuration: TimeInterval) { self.autoloadingFractionalThreshold = autoloadingFractionalThreshold self.coalesceUpdates = coalesceUpdates self.fastUpdates = fastUpdates self.isRegisteringPresentersAutomatically = isRegisteringPresentersAutomatically self.preferredMaxMessageCount = preferredMaxMessageCount self.preferredMaxMessageCountAdjustment = preferredMaxMessageCountAdjustment self.updatesAnimationDuration = updatesAnimationDuration } } } public extension ChatMessageCollectionAdapter.Configuration { static var `default`: Self { return .init( autoloadingFractionalThreshold: 0.05, coalesceUpdates: true, fastUpdates: true, isRegisteringPresentersAutomatically: true, preferredMaxMessageCount: 500, preferredMaxMessageCountAdjustment: 400, updatesAnimationDuration: 0.33 ) } } private struct HashableItem: Hashable { private let uid: String private let type: String init(_ decoratedChatItem: DecoratedChatItem) { self.uid = decoratedChatItem.uid self.type = decoratedChatItem.chatItem.type } init(_ chatItemCompanion: ChatItemCompanion) { self.uid = chatItemCompanion.uid self.type = chatItemCompanion.chatItem.type } } private enum ScrollAction { case scrollToBottom case preservePosition(rectForReferenceIndexPathBeforeUpdate: CGRect?, referenceIndexPathAfterUpdate: IndexPath?) }
mit
32f8bf6f6708961196a4b2824d560a47
44.195055
357
0.666586
5.958348
false
false
false
false
crspybits/SMSyncServer
iOS/iOSTests/Pods/SMCoreLib/SMCoreLib/Classes/Network/SMMultiPeer.swift
3
5127
// // SMMultiPeer.swift // // Modified from example by Ralf Ebert on 28/04/15. // https://www.ralfebert.de/tutorials/ios-swift-multipeer-connectivity/ // import Foundation import MultipeerConnectivity public protocol SMMultiPeerDelegate : class { func didReceive(data data:NSData, fromPeer:String) } public class SMMultiPeer : NSObject { private let ServiceType = "SMMultiPeer" private let myPeerId = MCPeerID(displayName: UIDevice.currentDevice().name) private let serviceAdvertiser : MCNearbyServiceAdvertiser private let serviceBrowser : MCNearbyServiceBrowser public weak var delegate:SMMultiPeerDelegate? public override init() { self.serviceAdvertiser = MCNearbyServiceAdvertiser(peer: self.myPeerId, discoveryInfo: nil, serviceType: self.ServiceType) self.serviceBrowser = MCNearbyServiceBrowser(peer: self.myPeerId, serviceType: self.ServiceType) super.init() self.serviceAdvertiser.delegate = self self.serviceAdvertiser.startAdvertisingPeer() self.serviceBrowser.delegate = self self.serviceBrowser.startBrowsingForPeers() } deinit { self.serviceAdvertiser.stopAdvertisingPeer() self.serviceBrowser.stopBrowsingForPeers() } public lazy var session: MCSession = { let session = MCSession(peer: self.myPeerId, securityIdentity: nil, encryptionPreference: MCEncryptionPreference.Required) session.delegate = self return session }() // returns true iff there was no error sending. public func sendData(data:NSData) -> Bool { var result:Bool = true if session.connectedPeers.count > 0 { var error : NSError? do { try self.session.sendData(data, toPeers: self.session.connectedPeers, withMode: MCSessionSendDataMode.Reliable) } catch let error1 as NSError { error = error1 Log.error("\(error)") result = false } } else { result = false } return result } // returns true iff there was no error sending. public func sendString(string : String) -> Bool { return self.sendData(string.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!) } } extension SMMultiPeer : MCNearbyServiceAdvertiserDelegate { public func advertiser(advertiser: MCNearbyServiceAdvertiser, didNotStartAdvertisingPeer error: NSError) { NSLog("%@", "didNotStartAdvertisingPeer: \(error)") } public func advertiser(advertiser: MCNearbyServiceAdvertiser, didReceiveInvitationFromPeer peerID: MCPeerID, withContext context: NSData?, invitationHandler: ((Bool, MCSession) -> Void)) { NSLog("%@", "didReceiveInvitationFromPeer \(peerID)") invitationHandler(true, self.session) } } extension SMMultiPeer : MCNearbyServiceBrowserDelegate { public func browser(browser: MCNearbyServiceBrowser, didNotStartBrowsingForPeers error: NSError) { NSLog("%@", "didNotStartBrowsingForPeers: \(error)") } public func browser(browser: MCNearbyServiceBrowser, foundPeer peerID: MCPeerID, withDiscoveryInfo info: [String : String]?) { NSLog("%@", "foundPeer: \(peerID)") NSLog("%@", "invitePeer: \(peerID)") browser.invitePeer(peerID, toSession: self.session, withContext: nil, timeout: 10) } public func browser(browser: MCNearbyServiceBrowser, lostPeer peerID: MCPeerID) { NSLog("%@", "lostPeer: \(peerID)") } } extension MCSessionState { func stringValue() -> String { switch(self) { case .NotConnected: return "NotConnected" case .Connecting: return "Connecting" case .Connected: return "Connected" } } } extension SMMultiPeer : MCSessionDelegate { public func session(session: MCSession, peer peerID: MCPeerID, didChangeState state: MCSessionState) { NSLog("%@", "peer \(peerID) didChangeState: \(state.stringValue())") } public func session(session: MCSession, didReceiveData data: NSData, fromPeer peerID: MCPeerID) { NSLog("%@", "didReceiveData: \(data.length) bytes") //let str = NSString(data: data, encoding: NSUTF8StringEncoding) as! String self.delegate?.didReceive(data: data, fromPeer: peerID.displayName) } public func session(session: MCSession, didReceiveStream stream: NSInputStream, withName streamName: String, fromPeer peerID: MCPeerID) { NSLog("%@", "didReceiveStream") } public func session(session: MCSession, didFinishReceivingResourceWithName resourceName: String, fromPeer peerID: MCPeerID, atURL localURL: NSURL, withError error: NSError?) { NSLog("%@", "didFinishReceivingResourceWithName") } public func session(session: MCSession, didStartReceivingResourceWithName resourceName: String, fromPeer peerID: MCPeerID, withProgress progress: NSProgress) { NSLog("%@", "didStartReceivingResourceWithName") } }
gpl-3.0
f35f9b9be683470d2e49d65afcbc20ec
36.698529
192
0.678369
5.189271
false
false
false
false
kentya6/Fuwari
Fuwari/LocalizedString.swift
1
1495
// // LocalizedString.swift // Fuwari // // Created by Kengo Yokoyama on 2016/12/11. // Copyright © 2016年 AppKnop. All rights reserved. // import Cocoa enum LocalizedString: String { case CheckForUpdates = "Check for Updates..." case Preference = "Preferences..." case QuitFuwari = "Quit Fuwari" case OK = "OK" case Cancel = "Cancel" case LaunchFuwari = "Launch Fuwari on system startup?" case LaunchSettingInfo = "You can change this setting in the Preferences if you want." case LaunchOnStartup = "Launch on system startup" case DontLaunch = "Don't Launch" case Capture = "Capture" case About = "About" case Save = "Save" case Upload = "Upload" case UploadTextTitle = "Upload Text Title" case UploadTextBody = "Upload Text Body" case Copy = "Copy" case Close = "Close" case ResetWindow = "Reset Window" case ZoomReset = "Zoom Reset" case ZoomIn = "Zoom In" case ZoomOut = "Zoom Out" case ShowAllSpaces = "Show All Spaces" case ShowCurrentSpace = "Show Current Space" case TabGeneral = "General" case TabMenu = "Menu" case TabShortcuts = "Shortcuts" case TabUpdates = "Updates" var value: String { return NSLocalizedString(rawValue, comment: "") } }
mit
ca30ec1eb6382c62a812beac1ab20dbb
32.909091
90
0.569035
4.121547
false
false
false
false
teambition/RefreshView
Sources/Contant.swift
2
1712
// // Contant.swift // RefreshView // // Created by ZouLiangming on 16/2/18. // Copyright © 2016年 ZouLiangming. All rights reserved. // import Foundation import UIKit let kRefreshHeaderKey = "header" let kRefreshFooterKey = "footer" let kRefreshLoadingKey = "loading" let kRefreshHeaderTag = 999 let kRefreshFooterTag = 9999 let kRefreshLoadingTag = 99999 let kCustomRefreshSlowAnimationTime = 0.4 let kCustomRefreshFastAnimationTime = 0.25 let kCustomRefreshFooterMargin: CGFloat = 10.0 let kCustomRefreshAnimationKey = "custom_rotation" let kCustomRefreshFooterStatusColor = UIColor(red: 166/255, green: 166/255, blue: 166/255, alpha: 1) let kPai = CGFloat.pi let kRefreshKeyPathContentOffset = "contentOffset" let kRefreshKeyPathContentInset = "contentInset" let kRefreshKeyPathContentSize = "contentSize" let kRefreshKeyPathPanState = "state" let kRefreshHeaderFullCircleOffset: CGFloat = 80.0 let kRefreshHeaderHeight: CGFloat = 54.0 let kRefreshFooterHeight: CGFloat = 44.0 let kRefreshNotCircleHeight: CGFloat = 16 let kRefreshFastAnimationDuration = 0.25 struct TableViewSelectors { static let reloadData = #selector(UITableView.reloadData) static let endUpdates = #selector(UITableView.endUpdates) static let numberOfSections = #selector(UITableViewDataSource.numberOfSections(in:)) } struct CollectionViewSelectors { static let reloadData = #selector(UICollectionView.reloadData) static let numberOfSections = #selector(UICollectionViewDataSource.numberOfSections(in:)) } public enum RefreshState: String { case idle = "Idle" case pulling = "Pulling" case refreshing = "Refreshing" case willRefresh = "WillRefresh" case noMoreData = "NoMoreData" }
mit
9dfd545e0b3d68763f041c4a82a2af4f
31.245283
100
0.784669
4.168293
false
false
false
false
swtlovewtt/WTKit
Sources/WTKit/Foundation.swift
1
11867
// // Foundation.swift // 宋文通 // // Created by 宋文通 on 2019/8/7. // Copyright © 2019 newsdog. All rights reserved. // import Foundation func dprint<T>(_ items:T, separator: String = " ", terminator: String = "\n",file:String = #file, function:String = #function, line:Int = #line) -> Void { #if DEBUG cprint(items, separator: separator, terminator: terminator,file:file, function:function, line:line) #endif } func cprint<T>(_ items: T, separator: String = " ", terminator: String = "\n",file:String = #file, function:String = #function, line:Int = #line) -> Void { print("\((file as NSString).lastPathComponent)[\(line)], \(function): \(items)", separator: separator, terminator: terminator) } public extension Data{ func utf8String() -> String { return String.init(data: self, encoding: .utf8) ?? "not utf8 string" } } func debugBlock(_ block:()->Void) -> Void { #if DEBUG block() #endif } public extension Locale{ static func en_US() -> Locale { return Locale.init(identifier: "en_US") } static func korea() -> Locale{ return Locale.init(identifier: "ko-Kore_KR") } } public extension Double{ func numberObject() -> NSNumber { return NSNumber.init(value: self) } } public extension DispatchQueue{ static func backgroundQueue()->DispatchQueue{ return DispatchQueue.global(qos: DispatchQoS.QoSClass.background) } static func utilityQueue()->DispatchQueue{ return DispatchQueue.global(qos: DispatchQoS.QoSClass.utility) } static func userInitiatedQueue()->DispatchQueue{ return DispatchQueue.global(qos: DispatchQoS.QoSClass.userInitiated) } static func userInteractiveQueue()->DispatchQueue{ return DispatchQueue.global(qos: DispatchQoS.QoSClass.userInteractive) } //安全同步到主线程 static func safeSyncInMain(execute work: @escaping @convention(block) () -> Swift.Void){ let main:DispatchQueue = DispatchQueue.main if Thread.isMainThread { main.async(execute: work) }else{ main.sync(execute: work) } // print("425 wt test") } //异步回到主线程 static func asyncInMain(execute work: @escaping @convention(block) () -> Swift.Void){ DispatchQueue.main.async(execute: work) } func perform( closure: @escaping () -> Void, afterDelay:Double) -> Void { let time = Int64(afterDelay * Double(NSEC_PER_SEC)) let t:DispatchTime = DispatchTime.now() + Double(time) / Double(NSEC_PER_SEC) self.asyncAfter(deadline: t, execute: closure) } } enum URLSessionError:Error { case noURL case nodata case parseEror case none case ok } public extension URLSession{ @discardableResult func dataTask<T:Codable>(withPath urlPath:String,complectionHandler: @escaping (T?,Error?) -> Void) -> URLSessionDataTask?{ guard let url = URL.init(string: urlPath) else { DispatchQueue.main.async { complectionHandler(nil,URLSessionError.noURL) } return nil } return dataTask(with: url, completionHandler: complectionHandler) } @discardableResult func dataTask<T:Codable>(with url: URL, completionHandler: @escaping (T?,Error?) -> Void ) -> URLSessionDataTask{ return dataTask(with: URLRequest.init(url: url), completionHandler: completionHandler) } @discardableResult func dataTask<T:Codable>(with request: URLRequest, completionHandler: @escaping (T?,Error?) -> Void) -> URLSessionDataTask{ let task = dataTask(with: request) { (data, urlres, err) in if err != nil{ completionHandler(nil,err) } guard let data = data else{ DispatchQueue.main.async { completionHandler(nil,URLSessionError.nodata) } return } do{ let obj = try JSONDecoder().decode(T.self, from: data) DispatchQueue.main.async { completionHandler(obj,.none) } }catch{ DispatchQueue.main.async { completionHandler(nil,error) } } } task.resume() return task } @discardableResult static func useCacheElseLoadURLData(with url: URL, completionHandler: @escaping (Data?, URLResponse?, Error?) -> Void) -> URLSessionDataTask { var request = URLRequest.init(url: url) request.cachePolicy = .returnCacheDataElseLoad let task = URLSession.shared.dataTask(with: request, completionHandler: { (data,res,err) in DispatchQueue.main.async { completionHandler(data,res,err) } }) task.resume() return task } } public struct URLRequestPrinter:CustomDebugStringConvertible,CustomStringConvertible { var request:URLRequest public var description: String{ var components: [String] = [] if let HTTPMethod = request.httpMethod { components.append(HTTPMethod) } if let urlString = request.url?.absoluteString { components.append(urlString) } return components.joined(separator: " ") } public var debugDescription: String{ var components = ["$ curl -v"] guard let url = request.url else { return "$ curl command could not be created" } if let httpMethod = request.httpMethod, httpMethod != "GET" { components.append("-X \(httpMethod)") } /* if let credentialStorage = self.session.configuration.urlCredentialStorage { let protectionSpace = URLProtectionSpace( host: host, port: url.port ?? 0, protocol: url.scheme, realm: host, authenticationMethod: NSURLAuthenticationMethodHTTPBasic ) if let credentials = credentialStorage.credentials(for: protectionSpace)?.values { for credential in credentials { guard let user = credential.user, let password = credential.password else { continue } components.append("-u \(user):\(password)") } } else { if let credential = delegate.credential, let user = credential.user, let password = credential.password { components.append("-u \(user):\(password)") } } } if session.configuration.httpShouldSetCookies { if let cookieStorage = session.configuration.httpCookieStorage, let cookies = cookieStorage.cookies(for: url), !cookies.isEmpty { let string = cookies.reduce("") { $0 + "\($1.name)=\($1.value);" } #if swift(>=3.2) components.append("-b \"\(string[..<string.index(before: string.endIndex)])\"") #else components.append("-b \"\(string.substring(to: string.characters.index(before: string.endIndex)))\"") #endif } }*/ var headers: [AnyHashable: Any] = [:] /* session.configuration.httpAdditionalHeaders?.filter { $0.0 != AnyHashable("Cookie") } .forEach { headers[$0.0] = $0.1 } */ request.allHTTPHeaderFields?.filter { $0.0 != "Cookie" } .forEach { headers[$0.0] = $0.1 } components += headers.map { let escapedValue = String(describing: $0.value).replacingOccurrences(of: "\"", with: "\\\"") return "-H \"\($0.key): \(escapedValue)\"" } if let httpBodyData = request.httpBody, let httpBody = String(data: httpBodyData, encoding: .utf8) { var escapedBody = httpBody.replacingOccurrences(of: "\\\"", with: "\\\\\"") escapedBody = escapedBody.replacingOccurrences(of: "\"", with: "\\\"") components.append("-d \"\(escapedBody)\"") } components.append("\"\(url.absoluteString)\"") return components.joined(separator: " \\\n\t") } } public extension URLRequest{ func converToPrinter() -> URLRequestPrinter { return URLRequestPrinter.init(request: self) } var curlString: String { // Logging URL requests in whole may expose sensitive data, // or open up possibility for getting access to your user data, // so make sure to disable this feature for production builds! #if !DEBUG return "" #else var result = "curl -k " if let method = httpMethod { result += "-X \(method) \\\n" } if let headers = allHTTPHeaderFields { for (header, value) in headers { result += "-H \"\(header): \(value)\" \\\n" } } if let body = httpBody, !body.isEmpty, let string = String(data: body, encoding: .utf8), !string.isEmpty { result += "-d '\(string)' \\\n" } if let url = url { result += url.absoluteString } return result #endif } } public extension Date{ } public extension TimeZone{ } public extension DateFormatter{ //https://nsdateformatter.com static let globalFormatter:DateFormatter = { let f = DateFormatter() f.dateFormat = "yyyy-MM-dd" return f }() } public extension Bundle{ func appName() -> String { let appName: String = Bundle.main.object(forInfoDictionaryKey: "CFBundleName") as! String return appName } static var customBundle:Bundle = Bundle.main static func setCustomBundle(with newBundle:Bundle){ } static func getCustomBundle() -> Bundle { return Bundle.main } } public extension String{ func localized(_ lang:String) ->String { var bundle = Bundle.main if let path = Bundle.main.path(forResource: lang, ofType: "lproj") { bundle = Bundle(path: path) ?? Bundle.main } return NSLocalizedString(self, tableName: nil, bundle: bundle, value: "", comment: "") } func convertToLocalizedString(_ tableName: String? = nil, bundle: Bundle = Bundle.main, value: String = "", comment: String) -> String{ return NSLocalizedString(self, tableName: tableName, bundle: bundle, value: value, comment: comment) } func convertTextToFullWidth()->String{ if #available(OSX 10.11, iOS 9.0, *) { return self.applyingTransform(.fullwidthToHalfwidth, reverse: true) ?? "" } else { // Fallback on earlier versions } return "" } func converToHalfWidth() -> String { var dict = [String:String]() for (index,ele) in String.fullWidthPunctuation().enumerated(){ for (index2,ele2) in String.halfWidthPunctuation().enumerated(){ if index == index2{ dict["\(ele)"] = "\(ele2)" } } } var result = "" result = self for (k,v) in dict { result = result.replacingOccurrences(of: k, with: v) } return result } static func fullWidthPunctuation()->String{ return "“”,。:¥" } static func halfWidthPunctuation()->String{ return "\"\",.:¥" } } func convertCodableTypeToParameters<T:Codable,B>(_ t:T) -> B? { do{ let data = try JSONEncoder().encode(t) let json = try JSONSerialization.jsonObject(with: data, options: []) if let j = json as? B{ return j } }catch{ return nil } return nil }
mit
e488f34ac6e3bb81e5cfba7511357ddb
33.237681
156
0.581866
4.624902
false
false
false
false
onevcat/CotEditor
CotEditor/Sources/Pair.swift
1
7179
// // Pair.swift // // CotEditor // https://coteditor.com // // Created by 1024jp on 2016-08-19. // // --------------------------------------------------------------------------- // // © 2016-2021 1024jp // // 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 // // https://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. // struct Pair<T> { var begin: T var end: T init(_ begin: T, _ end: T) { self.begin = begin self.end = end } } extension Pair: Equatable where T: Equatable { } extension Pair: Hashable where T: Hashable { } // MARK: BracePair typealias BracePair = Pair<Character> extension Pair where T == Character { static let braces: [BracePair] = [BracePair("(", ")"), BracePair("{", "}"), BracePair("[", "]")] static let ltgt = BracePair("<", ">") static let doubleQuotes = BracePair("\"", "\"") enum PairIndex { case begin(String.Index) case end(String.Index) case odd } } extension StringProtocol where Self.Index == String.Index { /// Find the mate of a brace pair. /// /// - Parameters: /// - index: The character index of the brace character to find the mate. /// - candidates: Brace pairs to find. /// - range: The range of characters to find in. /// - pairToIgnore: The brace pair in which brace characters should be ignored. /// - Returns: The character index of the matched pair. func indexOfBracePair(at index: Index, candidates: [BracePair], in range: Range<Index>? = nil, ignoring pairToIgnore: BracePair? = nil) -> BracePair.PairIndex? { guard !self.isCharacterEscaped(at: index) else { return nil } let character = self[index] guard let pair = candidates.first(where: { $0.begin == character || $0.end == character }) else { return nil } switch character { case pair.begin: guard let endIndex = self.indexOfBracePair(beginIndex: index, pair: pair, until: range?.upperBound, ignoring: pairToIgnore) else { return .odd } return .end(endIndex) case pair.end: guard let beginIndex = self.indexOfBracePair(endIndex: index, pair: pair, until: range?.lowerBound, ignoring: pairToIgnore) else { return .odd } return .begin(beginIndex) default: preconditionFailure() } } /// Find character index of matched opening brace before a given index. /// /// This method ignores escaped characters. /// /// - Parameters: /// - endIndex: The character index of the closing brace of the pair to find. /// - pair: The brace pair to find. /// - beginIndex: The lower boundary of the find range. /// - pairToIgnore: The brace pair in which brace characters should be ignored. /// - Returns: The character index of the matched opening brace, or `nil` if not found. func indexOfBracePair(endIndex: Index, pair: BracePair, until beginIndex: Index? = nil, ignoring pairToIgnore: BracePair? = nil) -> Index? { assert(endIndex <= self.endIndex) let beginIndex = beginIndex ?? self.startIndex guard beginIndex < endIndex else { return nil } var index = endIndex var nestDepth = 0 var ignoredNestDepth = 0 while index > beginIndex { index = self.index(before: index) switch self[index] { case pair.begin where ignoredNestDepth == 0: guard !self.isCharacterEscaped(at: index) else { continue } if nestDepth == 0 { return index } // found nestDepth -= 1 case pair.end where ignoredNestDepth == 0: guard !self.isCharacterEscaped(at: index) else { continue } nestDepth += 1 case pairToIgnore?.begin: guard !self.isCharacterEscaped(at: index) else { continue } ignoredNestDepth -= 1 case pairToIgnore?.end: guard !self.isCharacterEscaped(at: index) else { continue } ignoredNestDepth += 1 default: break } } return nil } /// Find character index of matched closing brace after a given index. /// /// This method ignores escaped characters. /// /// - Parameters: /// - beginIndex: The character index of the opening brace of the pair to find. /// - pair: The brace pair to find. /// - endIndex: The upper boundary of the find range. /// - pairToIgnore: The brace pair in which brace characters should be ignored. /// - Returns: The character index of the matched closing brace, or `nil` if not found. func indexOfBracePair(beginIndex: Index, pair: BracePair, until endIndex: Index? = nil, ignoring pairToIgnore: BracePair? = nil) -> Index? { assert(beginIndex >= self.startIndex) // avoid (endIndex == self.startIndex) guard !self.isEmpty, endIndex.flatMap({ $0 > self.startIndex }) != false else { return nil } let endIndex = self.index(before: endIndex ?? self.endIndex) guard beginIndex < endIndex else { return nil } var index = beginIndex var nestDepth = 0 var ignoredNestDepth = 0 while index < endIndex { index = self.index(after: index) switch self[index] { case pair.end where ignoredNestDepth == 0: guard !self.isCharacterEscaped(at: index) else { continue } if nestDepth == 0 { return index } // found nestDepth -= 1 case pair.begin where ignoredNestDepth == 0: guard !self.isCharacterEscaped(at: index) else { continue } nestDepth += 1 case pairToIgnore?.end: guard !self.isCharacterEscaped(at: index) else { continue } ignoredNestDepth -= 1 case pairToIgnore?.begin: guard !self.isCharacterEscaped(at: index) else { continue } ignoredNestDepth += 1 default: break } } return nil } }
apache-2.0
b4b6e15375b6d9aa116c5bdd40c71465
34.014634
165
0.550432
4.763106
false
false
false
false
Brightify/ReactantUI
Sources/Tokenizer/Properties/Types/Implementation/ParagraphStyle.swift
1
1631
// // ParagraphStyle.swift // LiveUI-iOS // // Created by Matyáš Kříž on 05/06/2018. // import Foundation public struct ParagraphStyle: MultipleAttributeSupportedPropertyType { public let properties: [Property] public func generate(context: SupportedPropertyTypeContext) -> String { return """ { let p = NSMutableParagraphStyle() \(properties.map { "p.\($0.name) = \($0.anyValue.generate(context: context.child(for: $0.anyValue)))" }.joined(separator: "\n")) return p }() """ } #if SanAndreas // TODO public func dematerialize(context: SupportedPropertyTypeContext) -> String { fatalError("Implement me!") } #endif public static func materialize(from attributes: [String: String]) throws -> ParagraphStyle { let properties = Properties.paragraphStyle.allProperties.compactMap { $0 as? AttributePropertyDescription } return try ParagraphStyle(properties: PropertyHelper.deserializeSupportedProperties(properties: properties, from: attributes)) } public static var xsdType: XSDType { return .builtin(.string) } } #if canImport(UIKit) import UIKit extension ParagraphStyle { public func runtimeValue(context: SupportedPropertyTypeContext) -> Any? { let paragraphStyle = NSMutableParagraphStyle() for property in properties { let value = property.anyValue.runtimeValue(context: context.child(for: property.anyValue)) paragraphStyle.setValue(value, forKey: property.name) } return paragraphStyle } } #endif
mit
9a5806cc5fb786045f5127237f0c07b9
29.111111
140
0.671587
4.853731
false
false
false
false
onmyway133/Configurable
Example/ConstructionDemo/ConstructionDemo/Sources/AppDelegate.swift
2
738
import UIKit import Construction @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? lazy var navigationController: UINavigationController = { [unowned self] in let controller = UINavigationController(rootViewController: self.viewController) return controller }() lazy var viewController: ViewController = { let controller = ViewController() return controller }() func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { window = UIWindow(frame: UIScreen.mainScreen().bounds) window?.rootViewController = navigationController window?.makeKeyAndVisible() return true } }
mit
876ec4f468d053428e1b0c7f1c1f2642
27.384615
125
0.758808
6
false
false
false
false
per-dalsgaard/20-apps-in-20-weeks
App 12 - Scribe/Scribe/ViewController.swift
1
2213
// // ViewController.swift // Scribe // // Created by Per Kristensen on 19/04/2017. // Copyright © 2017 Per Dalsgaard. All rights reserved. // import UIKit import Speech import AVFoundation class ViewController: UIViewController, AVAudioPlayerDelegate { @IBOutlet weak var activitySpinner: UIActivityIndicatorView! @IBOutlet weak var transcriptionTextView: UITextView! var audioPlayer: AVAudioPlayer! override func viewDidLoad() { super.viewDidLoad() activitySpinner.isHidden = true } @IBAction func playButtonPressed(_ sender: UIButton) { transcriptionTextView.text = "" activitySpinner.isHidden = false activitySpinner.startAnimating() requestSpeechAuth() } func requestSpeechAuth() { SFSpeechRecognizer.requestAuthorization { authStatus in if authStatus == .authorized { if let path = Bundle.main.url(forResource: "test", withExtension: "m4a") { do { self.audioPlayer = try AVAudioPlayer(contentsOf: path) self.audioPlayer.delegate = self self.audioPlayer.play() } catch { // TODO: Handle error } let recognizer = SFSpeechRecognizer() let request = SFSpeechURLRecognitionRequest(url: path) recognizer?.recognitionTask(with: request, resultHandler: { (result, error) in if let error = error { print("There was an error: \(error)") } else { if let transcription = result?.bestTranscription.formattedString { self.transcriptionTextView.text = transcription } } }) } } } } func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) { self.audioPlayer.stop() activitySpinner.stopAnimating() activitySpinner.isHidden = true } }
mit
d1a776ecd98604d451018d474980ea16
32.014925
98
0.548825
6.060274
false
false
false
false
PavelGnatyuk/SimplePurchase
SimplePurchase/SimplePurchase/in-app purchase/AppProductInfoUpdater.swift
1
2004
// // AppProductInfoUpdater.swift // // Update product information from the App Store only if a predefined time period has past. // For example, an application may check if the prices on the App Store were changed when the app // was in the background. // // // Created by Pavel Gnatyuk on 27/04/2017. // // import Foundation /** Class requesting the product information from the App Store only if a predefined time period has past. */ class AppProductInfoUpdater: ProductInfoUpdater { let purchaseController: PurchaseController let timeout: TimeInterval private(set) var lastTime: Date? init(purchaseController: PurchaseController, timeout: TimeInterval) { self.purchaseController = purchaseController self.timeout = timeout } var updateNeeded: Bool { // If the purchase controller is not ready to request the product information we cannot continue // and the update is not needed. if !self.purchaseController.isReadyToRequest { return false } // A bit a strange case after the previous check: the product info has been requested but // not via this Updater instance. if self.lastTime == nil { return true } // We are here if the purchase manager has requested the products from the App Store // and so contains the prices. // So we need to update these products' information if a predefined timeout has past. // // `lastTime` is not nil here for sure, because it can be privaty set only from this class. guard let interval = self.lastTime?.timeIntervalSinceNow else { return true } return interval == 0 || -interval > self.timeout } func updateIfNeeded() -> Bool { if self.updateNeeded == false { return false } lastTime = Date() return self.purchaseController.requestProducts() } }
apache-2.0
f3d1712216eb4a911bb57b9619259e27
31.852459
104
0.647206
4.8523
false
false
false
false
leeaken/LTMap
LTMap/LTLocationMap/LocationPick/Controller/LTLocationSearchResultVC.swift
1
4877
// // LTLocationSearchResultVC.swift // LTMap // // Created by aken on 2017/6/3. // Copyright © 2017年 LTMap. All rights reserved. // import UIKit import MJRefresh class LTLocationSearchResultVC: UIViewController { // MARK: -- 公共成员 var dataSource = [LTPoiModel]() var hastNext:Bool = false var isKeyboardSearch:Bool = false { didSet { resettRequestParameter() } } weak var searchBar:UISearchBar? var coordinate:CLLocationCoordinate2D? { didSet { searchParam.location = coordinate } } weak open var delegate: LTLocationSearchResultVCDelegate? var searchParam = LTPOISearchAroundArg() fileprivate var poiManager = LTGeocodeManager() fileprivate lazy var tableView:UITableView = { let myTableView = UITableView(frame: CGRect.zero, style: .plain) myTableView.delegate = self myTableView.dataSource = self return myTableView }() override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. view.backgroundColor = UIColor.white self.edgesForExtendedLayout = [] //.all self.automaticallyAdjustsScrollViewInsets = false self.extendedLayoutIncludesOpaqueBars = true self.definesPresentationContext = false setupUI() addViewContrains() searchParam.offset = LTLocationCommon.POISearchPageSize; searchParam.page = 1; searchParam.radius = LTLocationCommon.POISearchRadius; } func setupUI() { view.addSubview(tableView) tableView.mj_footer = MJRefreshBackNormalFooter(refreshingBlock: { [weak self] in if self?.hastNext == true { self?.searchParam.page = (self?.searchParam.page!)! + 1; if (self?.isKeyboardSearch)! { self?.searchPlaceWithKeyWord(keyword: self?.searchParam.keyword, adCode: self?.searchParam.city) }else { self?.searchInputTipsAutoCompletionWithKeyword(keyword: self?.searchParam.keyword, cityName: self?.searchParam.city) } }else { self?.tableView.mj_footer.isHidden = true; } }) } private func addViewContrains() { tableView.snp.makeConstraints { make in make.edges.equalTo(view) } } // MARK: -- 公共方法 func reloadData() { tableView.reloadData() } func resettRequestParameter() { dataSource.removeAll() searchParam.offset = LTLocationCommon.POISearchPageSize; searchParam.page = 1; searchParam.radius = LTLocationCommon.POISearchRadius; searchParam.city = "" searchParam.keyword = "" tableView.mj_footer.isHidden = false; hastNext = false } func searchInputTipsAutoCompletionWithKeyword(keyword:String?,cityName:String?) { searchParam.city = cityName searchParam.keyword = keyword poiManager.searchInputTipsAutoCompletionWithKeyword(param:searchParam) { [weak self](array, hasNext) in self?.tableView.mj_footer.endRefreshing() // self?.hastNext = hastNext as! Bool if array.count > 0 { self?.dataSource.append(contentsOf: array) self?.reloadData() } } } func searchPlaceWithKeyWord(keyword:String?,adCode:String?) { searchParam.city = adCode searchParam.keyword = keyword poiManager.searchPlaceWithKeyWord(param:searchParam) { [weak self](array, hastNext) in self?.tableView.mj_footer.endRefreshing() self?.hastNext = hastNext as! Bool if array.count > 0 { self?.dataSource.append(contentsOf: array) self?.tableView.reloadData() self?.tableView.mj_footer.isHidden = false; } if self?.hastNext == false { self?.tableView.mj_footer.isHidden = true; } } } } protocol LTLocationSearchResultVCDelegate : NSObjectProtocol { func tableViewDidSelectAt(selectedIndex:Int,model:LTPoiModel) }
mit
f1e36e06fe98edd7fa79e526cfd74de1
24.97861
136
0.539522
5.571101
false
false
false
false
miracl/amcl
version3/swift/TestALL.swift
2
46732
/* Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you 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. */ // // TestALL.swift // // Created by Michael Scott on 02/07/2015. // Copyright (c) 2015 Michael Scott. All rights reserved. // /* Test Elliptic curve and MPIN APIs */ import Foundation import amcl // comment out for Xcode import ed25519 import nist256 import goldilocks import bn254 import bls383 import bls24 import bls48 import rsa2048 public func printBinary(_ array: [UInt8]) { for i in 0 ..< array.count { let h=String(format:"%02x",array[i]) print("\(h)", terminator: "") } print(" "); } public func TestRSA_2048(_ rng: inout RAND) { let RFS=RSA.RFS var message="Hello World\n" var pub=rsa_public_key(Int(CONFIG_FF.FFLEN)) var priv=rsa_private_key(Int(CONFIG_FF.HFLEN)) var ML=[UInt8](repeating: 0,count: RFS) var C=[UInt8](repeating: 0,count: RFS) var S=[UInt8](repeating: 0,count: RFS) print("\nGenerating RSA public/private key pair") RSA.KEY_PAIR(&rng,65537,&priv,&pub) let M=[UInt8](message.utf8) print("Encrypting test string\n"); let E=RSA.OAEP_ENCODE(RSA.HASH_TYPE,M,&rng,nil); /* OAEP encode message m to e */ RSA.ENCRYPT(pub,E,&C); /* encrypt encoded message */ print("Ciphertext= 0x", terminator: ""); printBinary(C) print("Decrypting test string\n"); RSA.DECRYPT(priv,C,&ML) var MS=RSA.OAEP_DECODE(RSA.HASH_TYPE,nil,&ML) /* OAEP encode message m to e */ message="" for i in 0 ..< MS.count { message+=String(UnicodeScalar(MS[i])) } print(message); print("Signing message") RSA.PKCS15(RSA.HASH_TYPE,M,&C) RSA.DECRYPT(priv,C,&S); // create signature in S print("Signature= 0x",terminator: ""); printBinary(S) RSA.ENCRYPT(pub,S,&ML); var cmp=true if C.count != ML.count {cmp=false} else { for j in 0 ..< C.count { if C[j] != ML[j] {cmp=false} } } if cmp {print("\nSignature is valid\n")} else {print("\nSignature is INVALID\n")} RSA.PRIVATE_KEY_KILL(priv); } public func TestECDH_ed25519(_ rng: inout RAND) { let pp=String("M0ng00se"); let EGS=ed25519.ECDH.EGS let EFS=ed25519.ECDH.EFS let EAS=ed25519.CONFIG_CURVE.AESKEY let sha=ed25519.CONFIG_CURVE.HASH_TYPE var S1=[UInt8](repeating: 0,count: EGS) var W0=[UInt8](repeating: 0,count: 2*EFS+1) var W1=[UInt8](repeating: 0,count: 2*EFS+1) var Z0=[UInt8](repeating: 0,count: EFS) var Z1=[UInt8](repeating: 0,count: EFS) var SALT=[UInt8](repeating: 0,count: 8) var P1=[UInt8](repeating: 0,count: 3) var P2=[UInt8](repeating: 0,count: 4) var V=[UInt8](repeating: 0,count: 2*EFS+1) var M=[UInt8](repeating: 0,count: 17) var T=[UInt8](repeating: 0,count: 12) var CS=[UInt8](repeating: 0,count: EGS) var DS=[UInt8](repeating: 0,count: EGS) var NULLRNG : RAND? = nil var REALRNG : RAND? = rng for i in 0 ..< 8 {SALT[i]=UInt8(i+1)} // set Salt print("\nAlice's Passphrase= " + pp) let PW=[UInt8]( (pp).utf8 ) /* private key S0 of size EGS bytes derived from Password and Salt */ /* Note use of curve name here to disambiguate between supported curves!! */ /* Not needed if only one curve supported */ var S0=ed25519.ECDH.PBKDF2(sha,PW,SALT,1000,EGS) print("Alice's private key= 0x",terminator: ""); printBinary(S0) /* Generate Key pair S/W */ ed25519.ECDH.KEY_PAIR_GENERATE(&NULLRNG,&S0,&W0); print("Alice's public key= 0x",terminator: ""); printBinary(W0) var res=ed25519.ECDH.PUBLIC_KEY_VALIDATE(W0); if res != 0 { print("ECP Public Key is invalid!"); return; } /* Random private key for other party */ ed25519.ECDH.KEY_PAIR_GENERATE(&REALRNG,&S1,&W1) print("Servers private key= 0x",terminator: ""); printBinary(S1) print("Servers public key= 0x",terminator: ""); printBinary(W1); res=ed25519.ECDH.PUBLIC_KEY_VALIDATE(W1) if res != 0 { print("ECP Public Key is invalid!") return } /* Calculate common key using DH - IEEE 1363 method */ ed25519.ECDH.ECPSVDP_DH(S0,W1,&Z0) ed25519.ECDH.ECPSVDP_DH(S1,W0,&Z1) var same=true for i in 0 ..< EFS { if Z0[i] != Z1[i] {same=false} } if (!same) { print("*** ECPSVDP-DH Failed") return } let KEY=ed25519.ECDH.KDF2(sha,Z0,nil,EAS) print("Alice's DH Key= 0x",terminator: ""); printBinary(KEY) print("Servers DH Key= 0x",terminator: ""); printBinary(KEY) if ed25519.CONFIG_CURVE.CURVETYPE != ed25519.CONFIG_CURVE.MONTGOMERY { print("Testing ECIES") P1[0]=0x0; P1[1]=0x1; P1[2]=0x2 P2[0]=0x0; P2[1]=0x1; P2[2]=0x2; P2[3]=0x3 for i in 0...16 {M[i]=UInt8(i&0xff)} let C=ed25519.ECDH.ECIES_ENCRYPT(sha,P1,P2,&REALRNG,W1,M,&V,&T) print("Ciphertext= ") print("V= 0x",terminator: ""); printBinary(V) print("C= 0x",terminator: ""); printBinary(C) print("T= 0x",terminator: ""); printBinary(T) M=ed25519.ECDH.ECIES_DECRYPT(sha,P1,P2,V,C,T,S1) if M.count==0 { print("*** ECIES Decryption Failed\n") return } else {print("Decryption succeeded")} print("Message is 0x",terminator: ""); printBinary(M) print("Testing ECDSA") if ed25519.ECDH.ECPSP_DSA(sha,&rng,S0,M,&CS,&DS) != 0 { print("***ECDSA Signature Failed") return } print("Signature= ") print("C= 0x",terminator: ""); printBinary(CS) print("D= 0x",terminator: ""); printBinary(DS) if ed25519.ECDH.ECPVP_DSA(sha,W0,M,CS,DS) != 0 { print("***ECDSA Verification Failed") return } else {print("ECDSA Signature/Verification succeeded ")} } rng=REALRNG! } public func TestECDH_nist256(_ rng: inout RAND) { let pp=String("M0ng00se"); let EGS=nist256.ECDH.EGS let EFS=nist256.ECDH.EFS let EAS=nist256.CONFIG_CURVE.AESKEY let sha=nist256.CONFIG_CURVE.HASH_TYPE var S1=[UInt8](repeating: 0,count: EGS) var W0=[UInt8](repeating: 0,count: 2*EFS+1) var W1=[UInt8](repeating: 0,count: 2*EFS+1) var Z0=[UInt8](repeating: 0,count: EFS) var Z1=[UInt8](repeating: 0,count: EFS) var SALT=[UInt8](repeating: 0,count: 8) var P1=[UInt8](repeating: 0,count: 3) var P2=[UInt8](repeating: 0,count: 4) var V=[UInt8](repeating: 0,count: 2*EFS+1) var M=[UInt8](repeating: 0,count: 17) var T=[UInt8](repeating: 0,count: 12) var CS=[UInt8](repeating: 0,count: EGS) var DS=[UInt8](repeating: 0,count: EGS) var NULLRNG : RAND? = nil var REALRNG : RAND? = rng for i in 0 ..< 8 {SALT[i]=UInt8(i+1)} // set Salt print("\nAlice's Passphrase= " + pp) let PW=[UInt8]( (pp).utf8 ) /* private key S0 of size EGS bytes derived from Password and Salt */ /* Note use of curve name here to disambiguate between supported curves!! */ /* Not needed if only one curve supported */ var S0=nist256.ECDH.PBKDF2(sha,PW,SALT,1000,EGS) print("Alice's private key= 0x",terminator: ""); printBinary(S0) /* Generate Key pair S/W */ nist256.ECDH.KEY_PAIR_GENERATE(&NULLRNG,&S0,&W0); print("Alice's public key= 0x",terminator: ""); printBinary(W0) var res=nist256.ECDH.PUBLIC_KEY_VALIDATE(W0); if res != 0 { print("ECP Public Key is invalid!"); return; } /* Random private key for other party */ nist256.ECDH.KEY_PAIR_GENERATE(&REALRNG,&S1,&W1) print("Servers private key= 0x",terminator: ""); printBinary(S1) print("Servers public key= 0x",terminator: ""); printBinary(W1); res=nist256.ECDH.PUBLIC_KEY_VALIDATE(W1) if res != 0 { print("ECP Public Key is invalid!") return } /* Calculate common key using DH - IEEE 1363 method */ nist256.ECDH.ECPSVDP_DH(S0,W1,&Z0) nist256.ECDH.ECPSVDP_DH(S1,W0,&Z1) var same=true for i in 0 ..< EFS { if Z0[i] != Z1[i] {same=false} } if (!same) { print("*** ECPSVDP-DH Failed") return } let KEY=nist256.ECDH.KDF2(sha,Z0,nil,EAS) print("Alice's DH Key= 0x",terminator: ""); printBinary(KEY) print("Servers DH Key= 0x",terminator: ""); printBinary(KEY) if nist256.CONFIG_CURVE.CURVETYPE != nist256.CONFIG_CURVE.MONTGOMERY { print("Testing ECIES") P1[0]=0x0; P1[1]=0x1; P1[2]=0x2 P2[0]=0x0; P2[1]=0x1; P2[2]=0x2; P2[3]=0x3 for i in 0...16 {M[i]=UInt8(i&0xff)} let C=nist256.ECDH.ECIES_ENCRYPT(sha,P1,P2,&REALRNG,W1,M,&V,&T) print("Ciphertext= ") print("V= 0x",terminator: ""); printBinary(V) print("C= 0x",terminator: ""); printBinary(C) print("T= 0x",terminator: ""); printBinary(T) M=nist256.ECDH.ECIES_DECRYPT(sha,P1,P2,V,C,T,S1) if M.count==0 { print("*** ECIES Decryption Failed\n") return } else {print("Decryption succeeded")} print("Message is 0x",terminator: ""); printBinary(M) print("Testing ECDSA") if nist256.ECDH.ECPSP_DSA(sha,&rng,S0,M,&CS,&DS) != 0 { print("***ECDSA Signature Failed") return } print("Signature= ") print("C= 0x",terminator: ""); printBinary(CS) print("D= 0x",terminator: ""); printBinary(DS) if nist256.ECDH.ECPVP_DSA(sha,W0,M,CS,DS) != 0 { print("***ECDSA Verification Failed") return } else {print("ECDSA Signature/Verification succeeded ")} } rng=REALRNG! } public func TestECDH_goldilocks(_ rng: inout RAND) { let pp=String("M0ng00se"); let EGS=goldilocks.ECDH.EGS let EFS=goldilocks.ECDH.EFS let EAS=goldilocks.CONFIG_CURVE.AESKEY let sha=goldilocks.CONFIG_CURVE.HASH_TYPE var S1=[UInt8](repeating: 0,count: EGS) var W0=[UInt8](repeating: 0,count: 2*EFS+1) var W1=[UInt8](repeating: 0,count: 2*EFS+1) var Z0=[UInt8](repeating: 0,count: EFS) var Z1=[UInt8](repeating: 0,count: EFS) var SALT=[UInt8](repeating: 0,count: 8) var P1=[UInt8](repeating: 0,count: 3) var P2=[UInt8](repeating: 0,count: 4) var V=[UInt8](repeating: 0,count: 2*EFS+1) var M=[UInt8](repeating: 0,count: 17) var T=[UInt8](repeating: 0,count: 12) var CS=[UInt8](repeating: 0,count: EGS) var DS=[UInt8](repeating: 0,count: EGS) var NULLRNG : RAND? = nil var REALRNG : RAND? = rng for i in 0 ..< 8 {SALT[i]=UInt8(i+1)} // set Salt print("\nAlice's Passphrase= " + pp) let PW=[UInt8]( (pp).utf8 ) /* private key S0 of size EGS bytes derived from Password and Salt */ /* Note use of curve name here to disambiguate between supported curves!! */ /* Not needed if only one curve supported */ var S0=goldilocks.ECDH.PBKDF2(sha,PW,SALT,1000,EGS) print("Alice's private key= 0x",terminator: ""); printBinary(S0) /* Generate Key pair S/W */ goldilocks.ECDH.KEY_PAIR_GENERATE(&NULLRNG,&S0,&W0); print("Alice's public key= 0x",terminator: ""); printBinary(W0) var res=goldilocks.ECDH.PUBLIC_KEY_VALIDATE(W0); if res != 0 { print("ECP Public Key is invalid!"); return; } /* Random private key for other party */ goldilocks.ECDH.KEY_PAIR_GENERATE(&REALRNG,&S1,&W1) print("Servers private key= 0x",terminator: ""); printBinary(S1) print("Servers public key= 0x",terminator: ""); printBinary(W1); res=goldilocks.ECDH.PUBLIC_KEY_VALIDATE(W1) if res != 0 { print("ECP Public Key is invalid!") return } /* Calculate common key using DH - IEEE 1363 method */ goldilocks.ECDH.ECPSVDP_DH(S0,W1,&Z0) goldilocks.ECDH.ECPSVDP_DH(S1,W0,&Z1) var same=true for i in 0 ..< EFS { if Z0[i] != Z1[i] {same=false} } if (!same) { print("*** ECPSVDP-DH Failed") return } let KEY=goldilocks.ECDH.KDF2(sha,Z0,nil,EAS) print("Alice's DH Key= 0x",terminator: ""); printBinary(KEY) print("Servers DH Key= 0x",terminator: ""); printBinary(KEY) if goldilocks.CONFIG_CURVE.CURVETYPE != goldilocks.CONFIG_CURVE.MONTGOMERY { print("Testing ECIES") P1[0]=0x0; P1[1]=0x1; P1[2]=0x2 P2[0]=0x0; P2[1]=0x1; P2[2]=0x2; P2[3]=0x3 for i in 0...16 {M[i]=UInt8(i&0xff)} let C=goldilocks.ECDH.ECIES_ENCRYPT(sha,P1,P2,&REALRNG,W1,M,&V,&T) print("Ciphertext= ") print("V= 0x",terminator: ""); printBinary(V) print("C= 0x",terminator: ""); printBinary(C) print("T= 0x",terminator: ""); printBinary(T) M=goldilocks.ECDH.ECIES_DECRYPT(sha,P1,P2,V,C,T,S1) if M.count==0 { print("*** ECIES Decryption Failed\n") return } else {print("Decryption succeeded")} print("Message is 0x",terminator: ""); printBinary(M) print("Testing ECDSA") if goldilocks.ECDH.ECPSP_DSA(sha,&rng,S0,M,&CS,&DS) != 0 { print("***ECDSA Signature Failed") return } print("Signature= ") print("C= 0x",terminator: ""); printBinary(CS) print("D= 0x",terminator: ""); printBinary(DS) if goldilocks.ECDH.ECPVP_DSA(sha,W0,M,CS,DS) != 0 { print("***ECDSA Verification Failed") return } else {print("ECDSA Signature/Verification succeeded ")} } rng=REALRNG! } public func TestMPIN_bn254(_ rng: inout RAND) { let PERMITS=true let PINERROR=true let FULL=true let SINGLE_PASS=true let EGS=bn254.MPIN.EGS let EFS=bn254.MPIN.EFS let G1S=2*EFS+1 // Group 1 Size let G2S=4*EFS; // Group 2 Size let EAS=bn254.CONFIG_CURVE.AESKEY let sha=bn254.CONFIG_CURVE.HASH_TYPE var S=[UInt8](repeating: 0,count: EGS) var SST=[UInt8](repeating: 0,count: G2S) var TOKEN=[UInt8](repeating: 0,count: G1S) var PERMIT=[UInt8](repeating: 0,count: G1S) var SEC=[UInt8](repeating: 0,count: G1S) var xID=[UInt8](repeating: 0,count: G1S) var xCID=[UInt8](repeating: 0,count: G1S) var X=[UInt8](repeating: 0,count: EGS) var Y=[UInt8](repeating: 0,count: EGS) var E=[UInt8](repeating: 0,count: 12*EFS) var F=[UInt8](repeating: 0,count: 12*EFS) var HID=[UInt8](repeating: 0,count: G1S) var HTID=[UInt8](repeating: 0,count: G1S) var G1=[UInt8](repeating: 0,count: 12*EFS) var G2=[UInt8](repeating: 0,count: 12*EFS) var R=[UInt8](repeating: 0,count: EGS) var Z=[UInt8](repeating: 0,count: G1S) var W=[UInt8](repeating: 0,count: EGS) var T=[UInt8](repeating: 0,count: G1S) var CK=[UInt8](repeating: 0,count: EAS) var SK=[UInt8](repeating: 0,count: EAS) var HSID=[UInt8]() // Trusted Authority set-up bn254.MPIN.RANDOM_GENERATE(&rng,&S) print("\nMPIN Master Secret s: 0x",terminator: ""); printBinary(S) // Create Client Identity let IDstr = "[email protected]" let CLIENT_ID=[UInt8](IDstr.utf8) var HCID=bn254.MPIN.HASH_ID(sha,CLIENT_ID) // Either Client or TA calculates Hash(ID) - you decide! print("Client ID= "); printBinary(CLIENT_ID) // Client and Server are issued secrets by DTA bn254.MPIN.GET_SERVER_SECRET(S,&SST); print("Server Secret SS: 0x",terminator: ""); printBinary(SST); bn254.MPIN.GET_CLIENT_SECRET(&S,HCID,&TOKEN); print("Client Secret CS: 0x",terminator: ""); printBinary(TOKEN); // Client extracts PIN from secret to create Token var pin:Int32=1234 print("Client extracts PIN= \(pin)") var rtn=bn254.MPIN.EXTRACT_PIN(sha,CLIENT_ID,pin,&TOKEN) if rtn != 0 {print("FAILURE: EXTRACT_PIN rtn: \(rtn)")} print("Client Token TK: 0x",terminator: ""); printBinary(TOKEN); if FULL { bn254.MPIN.PRECOMPUTE(TOKEN,HCID,&G1,&G2); } var date:Int32=0 if (PERMITS) { date=bn254.MPIN.today() // Client gets "Time Token" permit from DTA bn254.MPIN.GET_CLIENT_PERMIT(sha,date,S,HCID,&PERMIT) print("Time Permit TP: 0x",terminator: ""); printBinary(PERMIT) // This encoding makes Time permit look random - Elligator squared bn254.MPIN.ENCODING(&rng,&PERMIT); print("Encoded Time Permit TP: 0x",terminator: ""); printBinary(PERMIT) bn254.MPIN.DECODING(&PERMIT) print("Decoded Time Permit TP: 0x",terminator: ""); printBinary(PERMIT) } // ***** NOW ENTER PIN ******* pin=1234 // ************************** // Set date=0 and PERMIT=null if time permits not in use //Client First pass: Inputs CLIENT_ID, optional RNG, pin, TOKEN and PERMIT. Output xID =x .H(CLIENT_ID) and re-combined secret SEC //If PERMITS are is use, then date!=0 and PERMIT is added to secret and xCID = x.(H(CLIENT_ID)+H(date|H(CLIENT_ID))) //Random value x is supplied externally if RNG=null, otherwise generated and passed out by RNG //IMPORTANT: To save space and time.. //If Time Permits OFF set xCID = null, HTID=null and use xID and HID only //If Time permits are ON, AND pin error detection is required then all of xID, xCID, HID and HTID are required //If Time permits are ON, AND pin error detection is NOT required, set xID=null, HID=null and use xCID and HTID only. var pxID:[UInt8]?=xID var pxCID:[UInt8]?=xCID var pHID:[UInt8]=HID var pHTID:[UInt8]?=HTID var pE:[UInt8]?=E var pF:[UInt8]?=F var pPERMIT:[UInt8]?=PERMIT var REALRNG : RAND? = rng if date != 0 { if (!PINERROR) { pxID=nil; // problem here - either comment out here or dont use with ! later on // pHID=nil; } } else { pPERMIT=nil; pxCID=nil; pHTID=nil; } if (!PINERROR) { pE=nil; pF=nil; } if (SINGLE_PASS) { print("MPIN Single Pass") let timeValue = bn254.MPIN.GET_TIME() rtn=bn254.MPIN.CLIENT(sha,date,CLIENT_ID,&REALRNG,&X,pin,TOKEN,&SEC,&pxID,&pxCID,pPERMIT,timeValue,&Y) if rtn != 0 {print("FAILURE: CLIENT rtn: \(rtn)")} if (FULL) { HCID=bn254.MPIN.HASH_ID(sha,CLIENT_ID); bn254.MPIN.GET_G1_MULTIPLE(&REALRNG,1,&R,HCID,&Z); // Also Send Z=r.ID to Server, remember random r } rtn=bn254.MPIN.SERVER(sha,date,&pHID,&pHTID,&Y,SST,pxID,pxCID!,SEC,&pE,&pF,CLIENT_ID,timeValue) if rtn != 0 {print("FAILURE: SERVER rtn: \(rtn)")} if (FULL) { // Also send T=w.ID to client, remember random w HSID=bn254.MPIN.HASH_ID(sha,CLIENT_ID); if date != 0 {bn254.MPIN.GET_G1_MULTIPLE(&REALRNG,0,&W,pHTID!,&T)} else {bn254.MPIN.GET_G1_MULTIPLE(&REALRNG,0,&W,pHID,&T)} } } else { print("MPIN Multi Pass"); // Send U=x.ID to server, and recreate secret from token and pin rtn=bn254.MPIN.CLIENT_1(sha,date,CLIENT_ID,&REALRNG,&X,pin,TOKEN,&SEC,&pxID,&pxCID,pPERMIT) if rtn != 0 {print("FAILURE: CLIENT_1 rtn: \(rtn)")} if (FULL) { HCID=bn254.MPIN.HASH_ID(sha,CLIENT_ID); bn254.MPIN.GET_G1_MULTIPLE(&REALRNG,1,&R,HCID,&Z); // Also Send Z=r.ID to Server, remember random r } // Server calculates H(ID) and H(T|H(ID)) (if time permits enabled), and maps them to points on the curve HID and HTID resp. bn254.MPIN.SERVER_1(sha,date,CLIENT_ID,&pHID,&pHTID); // Server generates Random number Y and sends it to Client bn254.MPIN.RANDOM_GENERATE(&REALRNG!,&Y); if (FULL) { // Also send T=w.ID to client, remember random w HSID=bn254.MPIN.HASH_ID(sha,CLIENT_ID); if date != 0 {bn254.MPIN.GET_G1_MULTIPLE(&REALRNG,0,&W,pHTID!,&T)} else {bn254.MPIN.GET_G1_MULTIPLE(&REALRNG,0,&W,pHID,&T)} } // Client Second Pass: Inputs Client secret SEC, x and y. Outputs -(x+y)*SEC rtn=bn254.MPIN.CLIENT_2(X,Y,&SEC); if rtn != 0 {print("FAILURE: CLIENT_2 rtn: \(rtn)")} // Server Second pass. Inputs hashed client id, random Y, -(x+y)*SEC, xID and xCID and Server secret SST. E and F help kangaroos to find error. // If PIN error not required, set E and F = null rtn=bn254.MPIN.SERVER_2(date,pHID,pHTID,Y,SST,pxID,pxCID,SEC,&pE,&pF); if rtn != 0 {print("FAILURE: SERVER_1 rtn: \(rtn)")} } if (rtn == bn254.MPIN.BAD_PIN) { print("Server says - Bad Pin. I don't know you. Feck off.\n"); if (PINERROR) { let err=bn254.MPIN.KANGAROO(pE,pF); if err != 0 {print("(Client PIN is out by \(err))\n")} } return; } else {print("Server says - PIN is good! You really are "+IDstr)} if (FULL) { var H=bn254.MPIN.HASH_ALL(sha,HCID,pxID,pxCID,SEC,Y,Z,T); bn254.MPIN.CLIENT_KEY(sha,G1,G2,pin,R,X,H,T,&CK); print("Client Key = 0x",terminator: ""); printBinary(CK) H=bn254.MPIN.HASH_ALL(sha,HSID,pxID,pxCID,SEC,Y,Z,T); bn254.MPIN.SERVER_KEY(sha,Z,SST,W,H,pHID,pxID!,pxCID,&SK); print("Server Key = 0x",terminator: ""); printBinary(SK) } rng=REALRNG! } public func TestMPIN_bls383(_ rng: inout RAND) { let PERMITS=true let PINERROR=true let FULL=true let SINGLE_PASS=true let EGS=bls383.MPIN.EGS let EFS=bls383.MPIN.EFS let G1S=2*EFS+1 // Group 1 Size let G2S=4*EFS; // Group 2 Size let EAS=bls383.CONFIG_CURVE.AESKEY let sha=bls383.CONFIG_CURVE.HASH_TYPE var S=[UInt8](repeating: 0,count: EGS) var SST=[UInt8](repeating: 0,count: G2S) var TOKEN=[UInt8](repeating: 0,count: G1S) var PERMIT=[UInt8](repeating: 0,count: G1S) var SEC=[UInt8](repeating: 0,count: G1S) var xID=[UInt8](repeating: 0,count: G1S) var xCID=[UInt8](repeating: 0,count: G1S) var X=[UInt8](repeating: 0,count: EGS) var Y=[UInt8](repeating: 0,count: EGS) var E=[UInt8](repeating: 0,count: 12*EFS) var F=[UInt8](repeating: 0,count: 12*EFS) var HID=[UInt8](repeating: 0,count: G1S) var HTID=[UInt8](repeating: 0,count: G1S) var G1=[UInt8](repeating: 0,count: 12*EFS) var G2=[UInt8](repeating: 0,count: 12*EFS) var R=[UInt8](repeating: 0,count: EGS) var Z=[UInt8](repeating: 0,count: G1S) var W=[UInt8](repeating: 0,count: EGS) var T=[UInt8](repeating: 0,count: G1S) var CK=[UInt8](repeating: 0,count: EAS) var SK=[UInt8](repeating: 0,count: EAS) var HSID=[UInt8]() // Trusted Authority set-up bls383.MPIN.RANDOM_GENERATE(&rng,&S) print("\nMPIN Master Secret s: 0x",terminator: ""); printBinary(S) // Create Client Identity let IDstr = "[email protected]" let CLIENT_ID=[UInt8](IDstr.utf8) var HCID=bls383.MPIN.HASH_ID(sha,CLIENT_ID) // Either Client or TA calculates Hash(ID) - you decide! print("Client ID= "); printBinary(CLIENT_ID) // Client and Server are issued secrets by DTA bls383.MPIN.GET_SERVER_SECRET(S,&SST); print("Server Secret SS: 0x",terminator: ""); printBinary(SST); bls383.MPIN.GET_CLIENT_SECRET(&S,HCID,&TOKEN); print("Client Secret CS: 0x",terminator: ""); printBinary(TOKEN); // Client extracts PIN from secret to create Token var pin:Int32=1234 print("Client extracts PIN= \(pin)") var rtn=bls383.MPIN.EXTRACT_PIN(sha,CLIENT_ID,pin,&TOKEN) if rtn != 0 {print("FAILURE: EXTRACT_PIN rtn: \(rtn)")} print("Client Token TK: 0x",terminator: ""); printBinary(TOKEN); if FULL { bls383.MPIN.PRECOMPUTE(TOKEN,HCID,&G1,&G2); } var date:Int32=0 if (PERMITS) { date=bls383.MPIN.today() // Client gets "Time Token" permit from DTA bls383.MPIN.GET_CLIENT_PERMIT(sha,date,S,HCID,&PERMIT) print("Time Permit TP: 0x",terminator: ""); printBinary(PERMIT) // This encoding makes Time permit look random - Elligator squared bls383.MPIN.ENCODING(&rng,&PERMIT); print("Encoded Time Permit TP: 0x",terminator: ""); printBinary(PERMIT) bls383.MPIN.DECODING(&PERMIT) print("Decoded Time Permit TP: 0x",terminator: ""); printBinary(PERMIT) } // ***** NOW ENTER PIN ******* pin=1234 // ************************** // Set date=0 and PERMIT=null if time permits not in use //Client First pass: Inputs CLIENT_ID, optional RNG, pin, TOKEN and PERMIT. Output xID =x .H(CLIENT_ID) and re-combined secret SEC //If PERMITS are is use, then date!=0 and PERMIT is added to secret and xCID = x.(H(CLIENT_ID)+H(date|H(CLIENT_ID))) //Random value x is supplied externally if RNG=null, otherwise generated and passed out by RNG //IMPORTANT: To save space and time.. //If Time Permits OFF set xCID = null, HTID=null and use xID and HID only //If Time permits are ON, AND pin error detection is required then all of xID, xCID, HID and HTID are required //If Time permits are ON, AND pin error detection is NOT required, set xID=null, HID=null and use xCID and HTID only. var pxID:[UInt8]?=xID var pxCID:[UInt8]?=xCID var pHID:[UInt8]=HID var pHTID:[UInt8]?=HTID var pE:[UInt8]?=E var pF:[UInt8]?=F var pPERMIT:[UInt8]?=PERMIT var REALRNG : RAND? = rng if date != 0 { if (!PINERROR) { pxID=nil; // problem here - either comment out here or dont use with ! later on // pHID=nil; } } else { pPERMIT=nil; pxCID=nil; pHTID=nil; } if (!PINERROR) { pE=nil; pF=nil; } if (SINGLE_PASS) { print("MPIN Single Pass") let timeValue = bls383.MPIN.GET_TIME() rtn=bls383.MPIN.CLIENT(sha,date,CLIENT_ID,&REALRNG,&X,pin,TOKEN,&SEC,&pxID,&pxCID,pPERMIT,timeValue,&Y) if rtn != 0 {print("FAILURE: CLIENT rtn: \(rtn)")} if (FULL) { HCID=bls383.MPIN.HASH_ID(sha,CLIENT_ID); bls383.MPIN.GET_G1_MULTIPLE(&REALRNG,1,&R,HCID,&Z); // Also Send Z=r.ID to Server, remember random r } rtn=bls383.MPIN.SERVER(sha,date,&pHID,&pHTID,&Y,SST,pxID,pxCID!,SEC,&pE,&pF,CLIENT_ID,timeValue) if rtn != 0 {print("FAILURE: SERVER rtn: \(rtn)")} if (FULL) { // Also send T=w.ID to client, remember random w HSID=bls383.MPIN.HASH_ID(sha,CLIENT_ID); if date != 0 {bls383.MPIN.GET_G1_MULTIPLE(&REALRNG,0,&W,pHTID!,&T)} else {bls383.MPIN.GET_G1_MULTIPLE(&REALRNG,0,&W,pHID,&T)} } } else { print("MPIN Multi Pass"); // Send U=x.ID to server, and recreate secret from token and pin rtn=bls383.MPIN.CLIENT_1(sha,date,CLIENT_ID,&REALRNG,&X,pin,TOKEN,&SEC,&pxID,&pxCID,pPERMIT) if rtn != 0 {print("FAILURE: CLIENT_1 rtn: \(rtn)")} if (FULL) { HCID=bls383.MPIN.HASH_ID(sha,CLIENT_ID); bls383.MPIN.GET_G1_MULTIPLE(&REALRNG,1,&R,HCID,&Z); // Also Send Z=r.ID to Server, remember random r } // Server calculates H(ID) and H(T|H(ID)) (if time permits enabled), and maps them to points on the curve HID and HTID resp. bls383.MPIN.SERVER_1(sha,date,CLIENT_ID,&pHID,&pHTID); // Server generates Random number Y and sends it to Client bls383.MPIN.RANDOM_GENERATE(&REALRNG!,&Y); if (FULL) { // Also send T=w.ID to client, remember random w HSID=bls383.MPIN.HASH_ID(sha,CLIENT_ID); if date != 0 {bls383.MPIN.GET_G1_MULTIPLE(&REALRNG,0,&W,pHTID!,&T)} else {bls383.MPIN.GET_G1_MULTIPLE(&REALRNG,0,&W,pHID,&T)} } // Client Second Pass: Inputs Client secret SEC, x and y. Outputs -(x+y)*SEC rtn=bls383.MPIN.CLIENT_2(X,Y,&SEC); if rtn != 0 {print("FAILURE: CLIENT_2 rtn: \(rtn)")} // Server Second pass. Inputs hashed client id, random Y, -(x+y)*SEC, xID and xCID and Server secret SST. E and F help kangaroos to find error. // If PIN error not required, set E and F = null rtn=bls383.MPIN.SERVER_2(date,pHID,pHTID,Y,SST,pxID,pxCID,SEC,&pE,&pF); if rtn != 0 {print("FAILURE: SERVER_1 rtn: \(rtn)")} } if (rtn == bls383.MPIN.BAD_PIN) { print("Server says - Bad Pin. I don't know you. Feck off.\n"); if (PINERROR) { let err=bls383.MPIN.KANGAROO(pE,pF); if err != 0 {print("(Client PIN is out by \(err))\n")} } return; } else {print("Server says - PIN is good! You really are "+IDstr)} if (FULL) { var H=bls383.MPIN.HASH_ALL(sha,HCID,pxID,pxCID,SEC,Y,Z,T); bls383.MPIN.CLIENT_KEY(sha,G1,G2,pin,R,X,H,T,&CK); print("Client Key = 0x",terminator: ""); printBinary(CK) H=bls383.MPIN.HASH_ALL(sha,HSID,pxID,pxCID,SEC,Y,Z,T); bls383.MPIN.SERVER_KEY(sha,Z,SST,W,H,pHID,pxID!,pxCID,&SK); print("Server Key = 0x",terminator: ""); printBinary(SK) } rng=REALRNG! } public func TestMPIN_bls24(_ rng: inout RAND) { let PERMITS=true let PINERROR=true let FULL=true let SINGLE_PASS=true let EGS=bls24.MPIN192.EGS let EFS=bls24.MPIN192.EFS let G1S=2*EFS+1 // Group 1 Size let G2S=8*EFS; // Group 2 Size let EAS=bls24.CONFIG_CURVE.AESKEY let sha=bls24.CONFIG_CURVE.HASH_TYPE var S=[UInt8](repeating: 0,count: EGS) var SST=[UInt8](repeating: 0,count: G2S) var TOKEN=[UInt8](repeating: 0,count: G1S) var PERMIT=[UInt8](repeating: 0,count: G1S) var SEC=[UInt8](repeating: 0,count: G1S) var xID=[UInt8](repeating: 0,count: G1S) var xCID=[UInt8](repeating: 0,count: G1S) var X=[UInt8](repeating: 0,count: EGS) var Y=[UInt8](repeating: 0,count: EGS) var E=[UInt8](repeating: 0,count: 24*EFS) var F=[UInt8](repeating: 0,count: 24*EFS) var HID=[UInt8](repeating: 0,count: G1S) var HTID=[UInt8](repeating: 0,count: G1S) var G1=[UInt8](repeating: 0,count: 24*EFS) var G2=[UInt8](repeating: 0,count: 24*EFS) var R=[UInt8](repeating: 0,count: EGS) var Z=[UInt8](repeating: 0,count: G1S) var W=[UInt8](repeating: 0,count: EGS) var T=[UInt8](repeating: 0,count: G1S) var CK=[UInt8](repeating: 0,count: EAS) var SK=[UInt8](repeating: 0,count: EAS) var HSID=[UInt8]() // Trusted Authority set-up MPIN192.RANDOM_GENERATE(&rng,&S) print("\nMPIN Master Secret s: 0x",terminator: ""); printBinary(S) // Create Client Identity let IDstr = "[email protected]" let CLIENT_ID=[UInt8](IDstr.utf8) var HCID=MPIN192.HASH_ID(sha,CLIENT_ID) // Either Client or TA calculates Hash(ID) - you decide! print("Client ID= "); printBinary(CLIENT_ID) // Client and Server are issued secrets by DTA MPIN192.GET_SERVER_SECRET(S,&SST); print("Server Secret SS: 0x",terminator: ""); printBinary(SST); MPIN192.GET_CLIENT_SECRET(&S,HCID,&TOKEN); print("Client Secret CS: 0x",terminator: ""); printBinary(TOKEN); // Client extracts PIN from secret to create Token var pin:Int32=1234 print("Client extracts PIN= \(pin)") var rtn=MPIN192.EXTRACT_PIN(sha,CLIENT_ID,pin,&TOKEN) if rtn != 0 {print("FAILURE: EXTRACT_PIN rtn: \(rtn)")} print("Client Token TK: 0x",terminator: ""); printBinary(TOKEN); if FULL { MPIN192.PRECOMPUTE(TOKEN,HCID,&G1,&G2); } var date:Int32=0 if (PERMITS) { date=MPIN192.today() // Client gets "Time Token" permit from DTA MPIN192.GET_CLIENT_PERMIT(sha,date,S,HCID,&PERMIT) print("Time Permit TP: 0x",terminator: ""); printBinary(PERMIT) // This encoding makes Time permit look random - Elligator squared MPIN192.ENCODING(&rng,&PERMIT); print("Encoded Time Permit TP: 0x",terminator: ""); printBinary(PERMIT) MPIN192.DECODING(&PERMIT) print("Decoded Time Permit TP: 0x",terminator: ""); printBinary(PERMIT) } // ***** NOW ENTER PIN ******* pin=1234 // ************************** // Set date=0 and PERMIT=null if time permits not in use //Client First pass: Inputs CLIENT_ID, optional rng, pin, TOKEN and PERMIT. Output xID =x .H(CLIENT_ID) and re-combined secret SEC //If PERMITS are is use, then date!=0 and PERMIT is added to secret and xCID = x.(H(CLIENT_ID)+H(date|H(CLIENT_ID))) //Random value x is supplied externally if RNG=null, otherwise generated and passed out by RNG //IMPORTANT: To save space and time.. //If Time Permits OFF set xCID = null, HTID=null and use xID and HID only //If Time permits are ON, AND pin error detection is required then all of xID, xCID, HID and HTID are required //If Time permits are ON, AND pin error detection is NOT required, set xID=null, HID=null and use xCID and HTID only. var pxID:[UInt8]?=xID var pxCID:[UInt8]?=xCID var pHID:[UInt8]=HID var pHTID:[UInt8]?=HTID var pE:[UInt8]?=E var pF:[UInt8]?=F var pPERMIT:[UInt8]?=PERMIT var REALRNG : RAND? = rng if date != 0 { if (!PINERROR) { pxID=nil; // problem here - either comment out here or dont use with ! later on // pHID=nil; } } else { pPERMIT=nil; pxCID=nil; pHTID=nil; } if (!PINERROR) { pE=nil; pF=nil; } if (SINGLE_PASS) { print("MPIN Single Pass") let timeValue = MPIN192.GET_TIME() rtn=MPIN192.CLIENT(sha,date,CLIENT_ID,&REALRNG,&X,pin,TOKEN,&SEC,&pxID,&pxCID,pPERMIT,timeValue,&Y) if rtn != 0 {print("FAILURE: CLIENT rtn: \(rtn)")} if (FULL) { HCID=MPIN192.HASH_ID(sha,CLIENT_ID); MPIN192.GET_G1_MULTIPLE(&REALRNG,1,&R,HCID,&Z); // Also Send Z=r.ID to Server, remember random r } rtn=MPIN192.SERVER(sha,date,&pHID,&pHTID,&Y,SST,pxID,pxCID!,SEC,&pE,&pF,CLIENT_ID,timeValue) if rtn != 0 {print("FAILURE: SERVER rtn: \(rtn)")} if (FULL) { // Also send T=w.ID to client, remember random w HSID=MPIN192.HASH_ID(sha,CLIENT_ID); if date != 0 {MPIN192.GET_G1_MULTIPLE(&REALRNG,0,&W,pHTID!,&T)} else {MPIN192.GET_G1_MULTIPLE(&REALRNG,0,&W,pHID,&T)} } } else { print("MPIN Multi Pass"); // Send U=x.ID to server, and recreate secret from token and pin rtn=MPIN192.CLIENT_1(sha,date,CLIENT_ID,&REALRNG,&X,pin,TOKEN,&SEC,&pxID,&pxCID,pPERMIT) if rtn != 0 {print("FAILURE: CLIENT_1 rtn: \(rtn)")} if (FULL) { HCID=MPIN192.HASH_ID(sha,CLIENT_ID); MPIN192.GET_G1_MULTIPLE(&REALRNG,1,&R,HCID,&Z); // Also Send Z=r.ID to Server, remember random r } // Server calculates H(ID) and H(T|H(ID)) (if time permits enabled), and maps them to points on the curve HID and HTID resp. MPIN192.SERVER_1(sha,date,CLIENT_ID,&pHID,&pHTID); // Server generates Random number Y and sends it to Client MPIN192.RANDOM_GENERATE(&REALRNG!,&Y); if (FULL) { // Also send T=w.ID to client, remember random w HSID=MPIN192.HASH_ID(sha,CLIENT_ID); if date != 0 {MPIN192.GET_G1_MULTIPLE(&REALRNG,0,&W,pHTID!,&T)} else {MPIN192.GET_G1_MULTIPLE(&REALRNG,0,&W,pHID,&T)} } // Client Second Pass: Inputs Client secret SEC, x and y. Outputs -(x+y)*SEC rtn=MPIN192.CLIENT_2(X,Y,&SEC); if rtn != 0 {print("FAILURE: CLIENT_2 rtn: \(rtn)")} // Server Second pass. Inputs hashed client id, random Y, -(x+y)*SEC, xID and xCID and Server secret SST. E and F help kangaroos to find error. // If PIN error not required, set E and F = null rtn=MPIN192.SERVER_2(date,pHID,pHTID,Y,SST,pxID,pxCID,SEC,&pE,&pF); if rtn != 0 {print("FAILURE: SERVER_1 rtn: \(rtn)")} } if (rtn == MPIN192.BAD_PIN) { print("Server says - Bad Pin. I don't know you. Feck off.\n"); if (PINERROR) { let err=MPIN192.KANGAROO(pE,pF); if err != 0 {print("(Client PIN is out by \(err))\n")} } return; } else {print("Server says - PIN is good! You really are "+IDstr)} if (FULL) { var H=MPIN192.HASH_ALL(sha,HCID,pxID,pxCID,SEC,Y,Z,T); MPIN192.CLIENT_KEY(sha,G1,G2,pin,R,X,H,T,&CK); print("Client Key = 0x",terminator: ""); printBinary(CK) H=MPIN192.HASH_ALL(sha,HSID,pxID,pxCID,SEC,Y,Z,T); MPIN192.SERVER_KEY(sha,Z,SST,W,H,pHID,pxID!,pxCID,&SK); print("Server Key = 0x",terminator: ""); printBinary(SK) } rng=REALRNG! } public func TestMPIN_bls48(_ rng: inout RAND) { let PERMITS=true let PINERROR=true let FULL=true let SINGLE_PASS=true let EGS=bls48.MPIN256.EGS let EFS=bls48.MPIN256.EFS let G1S=2*EFS+1 // Group 1 Size let G2S=16*EFS; // Group 2 Size let EAS=bls48.CONFIG_CURVE.AESKEY let sha=bls48.CONFIG_CURVE.HASH_TYPE var S=[UInt8](repeating: 0,count: EGS) var SST=[UInt8](repeating: 0,count: G2S) var TOKEN=[UInt8](repeating: 0,count: G1S) var PERMIT=[UInt8](repeating: 0,count: G1S) var SEC=[UInt8](repeating: 0,count: G1S) var xID=[UInt8](repeating: 0,count: G1S) var xCID=[UInt8](repeating: 0,count: G1S) var X=[UInt8](repeating: 0,count: EGS) var Y=[UInt8](repeating: 0,count: EGS) var E=[UInt8](repeating: 0,count: 48*EFS) var F=[UInt8](repeating: 0,count: 48*EFS) var HID=[UInt8](repeating: 0,count: G1S) var HTID=[UInt8](repeating: 0,count: G1S) var G1=[UInt8](repeating: 0,count: 48*EFS) var G2=[UInt8](repeating: 0,count: 48*EFS) var R=[UInt8](repeating: 0,count: EGS) var Z=[UInt8](repeating: 0,count: G1S) var W=[UInt8](repeating: 0,count: EGS) var T=[UInt8](repeating: 0,count: G1S) var CK=[UInt8](repeating: 0,count: EAS) var SK=[UInt8](repeating: 0,count: EAS) var HSID=[UInt8]() // Trusted Authority set-up MPIN256.RANDOM_GENERATE(&rng,&S) print("\nMPIN Master Secret s: 0x",terminator: ""); printBinary(S) // Create Client Identity let IDstr = "[email protected]" let CLIENT_ID=[UInt8](IDstr.utf8) var HCID=MPIN256.HASH_ID(sha,CLIENT_ID) // Either Client or TA calculates Hash(ID) - you decide! print("Client ID= "); printBinary(CLIENT_ID) // Client and Server are issued secrets by DTA MPIN256.GET_SERVER_SECRET(S,&SST); print("Server Secret SS: 0x",terminator: ""); printBinary(SST); MPIN256.GET_CLIENT_SECRET(&S,HCID,&TOKEN); print("Client Secret CS: 0x",terminator: ""); printBinary(TOKEN); // Client extracts PIN from secret to create Token var pin:Int32=1234 print("Client extracts PIN= \(pin)") var rtn=MPIN256.EXTRACT_PIN(sha,CLIENT_ID,pin,&TOKEN) if rtn != 0 {print("FAILURE: EXTRACT_PIN rtn: \(rtn)")} print("Client Token TK: 0x",terminator: ""); printBinary(TOKEN); if FULL { MPIN256.PRECOMPUTE(TOKEN,HCID,&G1,&G2); } var date:Int32=0 if (PERMITS) { date=MPIN256.today() // Client gets "Time Token" permit from DTA MPIN256.GET_CLIENT_PERMIT(sha,date,S,HCID,&PERMIT) print("Time Permit TP: 0x",terminator: ""); printBinary(PERMIT) // This encoding makes Time permit look random - Elligator squared MPIN256.ENCODING(&rng,&PERMIT); print("Encoded Time Permit TP: 0x",terminator: ""); printBinary(PERMIT) MPIN256.DECODING(&PERMIT) print("Decoded Time Permit TP: 0x",terminator: ""); printBinary(PERMIT) } // ***** NOW ENTER PIN ******* pin=1234 // ************************** // Set date=0 and PERMIT=null if time permits not in use //Client First pass: Inputs CLIENT_ID, optional rng, pin, TOKEN and PERMIT. Output xID =x .H(CLIENT_ID) and re-combined secret SEC //If PERMITS are is use, then date!=0 and PERMIT is added to secret and xCID = x.(H(CLIENT_ID)+H(date|H(CLIENT_ID))) //Random value x is supplied externally if RNG=null, otherwise generated and passed out by RNG //IMPORTANT: To save space and time.. //If Time Permits OFF set xCID = null, HTID=null and use xID and HID only //If Time permits are ON, AND pin error detection is required then all of xID, xCID, HID and HTID are required //If Time permits are ON, AND pin error detection is NOT required, set xID=null, HID=null and use xCID and HTID only. var pxID:[UInt8]?=xID var pxCID:[UInt8]?=xCID var pHID:[UInt8]=HID var pHTID:[UInt8]?=HTID var pE:[UInt8]?=E var pF:[UInt8]?=F var pPERMIT:[UInt8]?=PERMIT var REALRNG : RAND? = rng if date != 0 { if (!PINERROR) { pxID=nil; // problem here - either comment out here or dont use with ! later on // pHID=nil; } } else { pPERMIT=nil; pxCID=nil; pHTID=nil; } if (!PINERROR) { pE=nil; pF=nil; } if (SINGLE_PASS) { print("MPIN Single Pass") let timeValue = MPIN256.GET_TIME() rtn=MPIN256.CLIENT(sha,date,CLIENT_ID,&REALRNG,&X,pin,TOKEN,&SEC,&pxID,&pxCID,pPERMIT,timeValue,&Y) if rtn != 0 {print("FAILURE: CLIENT rtn: \(rtn)")} if (FULL) { HCID=MPIN256.HASH_ID(sha,CLIENT_ID); MPIN256.GET_G1_MULTIPLE(&REALRNG,1,&R,HCID,&Z); // Also Send Z=r.ID to Server, remember random r } rtn=MPIN256.SERVER(sha,date,&pHID,&pHTID,&Y,SST,pxID,pxCID!,SEC,&pE,&pF,CLIENT_ID,timeValue) if rtn != 0 {print("FAILURE: SERVER rtn: \(rtn)")} if (FULL) { // Also send T=w.ID to client, remember random w HSID=MPIN256.HASH_ID(sha,CLIENT_ID); if date != 0 {MPIN256.GET_G1_MULTIPLE(&REALRNG,0,&W,pHTID!,&T)} else {MPIN256.GET_G1_MULTIPLE(&REALRNG,0,&W,pHID,&T)} } } else { print("MPIN Multi Pass"); // Send U=x.ID to server, and recreate secret from token and pin rtn=MPIN256.CLIENT_1(sha,date,CLIENT_ID,&REALRNG,&X,pin,TOKEN,&SEC,&pxID,&pxCID,pPERMIT) if rtn != 0 {print("FAILURE: CLIENT_1 rtn: \(rtn)")} if (FULL) { HCID=MPIN256.HASH_ID(sha,CLIENT_ID); MPIN256.GET_G1_MULTIPLE(&REALRNG,1,&R,HCID,&Z); // Also Send Z=r.ID to Server, remember random r } // Server calculates H(ID) and H(T|H(ID)) (if time permits enabled), and maps them to points on the curve HID and HTID resp. MPIN256.SERVER_1(sha,date,CLIENT_ID,&pHID,&pHTID); // Server generates Random number Y and sends it to Client MPIN256.RANDOM_GENERATE(&REALRNG!,&Y); if (FULL) { // Also send T=w.ID to client, remember random w HSID=MPIN256.HASH_ID(sha,CLIENT_ID); if date != 0 {MPIN256.GET_G1_MULTIPLE(&REALRNG,0,&W,pHTID!,&T)} else {MPIN256.GET_G1_MULTIPLE(&REALRNG,0,&W,pHID,&T)} } // Client Second Pass: Inputs Client secret SEC, x and y. Outputs -(x+y)*SEC rtn=MPIN256.CLIENT_2(X,Y,&SEC); if rtn != 0 {print("FAILURE: CLIENT_2 rtn: \(rtn)")} // Server Second pass. Inputs hashed client id, random Y, -(x+y)*SEC, xID and xCID and Server secret SST. E and F help kangaroos to find error. // If PIN error not required, set E and F = null rtn=MPIN256.SERVER_2(date,pHID,pHTID,Y,SST,pxID,pxCID,SEC,&pE,&pF); if rtn != 0 {print("FAILURE: SERVER_1 rtn: \(rtn)")} } if (rtn == MPIN256.BAD_PIN) { print("Server says - Bad Pin. I don't know you. Feck off.\n"); if (PINERROR) { let err=MPIN256.KANGAROO(pE,pF); if err != 0 {print("(Client PIN is out by \(err))\n")} } return; } else {print("Server says - PIN is good! You really are "+IDstr)} if (FULL) { var H=MPIN256.HASH_ALL(sha,HCID,pxID,pxCID,SEC,Y,Z,T); MPIN256.CLIENT_KEY(sha,G1,G2,pin,R,X,H,T,&CK); print("Client Key = 0x",terminator: ""); printBinary(CK) H=MPIN256.HASH_ALL(sha,HSID,pxID,pxCID,SEC,Y,Z,T); MPIN256.SERVER_KEY(sha,Z,SST,W,H,pHID,pxID!,pxCID,&SK); print("Server Key = 0x",terminator: ""); printBinary(SK) } rng=REALRNG! } var RAW=[UInt8](repeating: 0,count: 100) var rng=RAND() rng.clean(); for i in 0 ..< 100 {RAW[i]=UInt8(i&0xff)} rng.seed(100,RAW) TestECDH_ed25519(&rng) TestECDH_nist256(&rng) TestECDH_goldilocks(&rng) TestRSA_2048(&rng) TestMPIN_bn254(&rng) TestMPIN_bls383(&rng) TestMPIN_bls24(&rng) TestMPIN_bls48(&rng)
apache-2.0
ec9cc2fad5e8f04674a6584cdcbcdc1c
31.748423
151
0.586943
3.135324
false
false
false
false
skitil/brocotd
Snk/AppDelegate.swift
1
5482
// Created Sanjay Madan on May 26, 2015 // Copyright (c) 2015 mowglii.com import Cocoa // MARK: Main window final class MainWindow: NSWindow { // The main window is non-resizable and non-zoomable. // Its fixed size is determined by the MainVC's view. // The window uses the NSFullSizeContentViewWindowMask // so that we can draw our own custom title bar. convenience init() { self.init(contentRect: NSZeroRect, styleMask: [.titled, .closable, .miniaturizable, .fullSizeContentView], backing: .buffered, defer: false) self.titlebarAppearsTransparent = true self.standardWindowButton(.zoomButton)?.alphaValue = 0 } // The app terminates when the main window is closed. override func close() { NSApplication.shared().terminate(nil) } // Fade the contentView when the window resigns Main. override func becomeMain() { super.becomeMain() contentView?.alphaValue = 1 } override func resignMain() { super.resignMain() contentView?.alphaValue = 0.6 } } // MARK: - App delegate // // AppDelegate handles the main window (it owns the main // window controller), clears the high scores, and toggles // the board size. @NSApplicationMain final class AppDelegate: NSObject, NSApplicationDelegate { @IBOutlet var themesMenu: NSMenu? let mainWC = NSWindowController(window: MainWindow()) func applicationDidFinishLaunching(_ aNotification: Notification) { UserDefaults.standard.register(defaults: [ kHiScoreSlowKey: 0 as AnyObject, kHiScoreMediumKey: 0 as AnyObject, kHiScoreFastKey: 0 as AnyObject, kEnableSoundsKey: 1 as AnyObject, kEnableMusicKey: 1 as AnyObject, kBigBoardKey: 0 as AnyObject ]) setupThemesMenu() showMainWindow() } func showMainWindow() { // If we are re-showing the window (because the // user toggled its size or changed its theme), // first make sure it is not miniturized and // not showing. if mainWC.window?.isMiniaturized == true { mainWC.window?.deminiaturize(nil) } mainWC.window?.orderOut(nil) mainWC.contentViewController = MainVC() // Fade the window in. mainWC.window?.alphaValue = 0 mainWC.showWindow(self) mainWC.window?.center() moDispatch(after: 0.1) { self.mainWC.window?.animator().alphaValue = 1 } } @IBAction func clearScores(_ sender: AnyObject) { // Called from the Clear Scores... menu item. // Show an alert to confirm the user really // wants to erase their saved high scores. let alert = NSAlert() alert.messageText = NSLocalizedString("Clear scores?", comment: "") alert.informativeText = NSLocalizedString("Do you really want to clear your best scores?", comment: "") alert.addButton(withTitle: NSLocalizedString("No", comment: "")) alert.addButton(withTitle: NSLocalizedString("Yes", comment: "")) if alert.runModal() == NSAlertSecondButtonReturn { UserDefaults.standard.set(0, forKey: kHiScoreSlowKey) UserDefaults.standard.set(0, forKey: kHiScoreMediumKey) UserDefaults.standard.set(0, forKey: kHiScoreFastKey) } } @IBAction func toggleSize(_ sender: AnyObject) { // Called from Toggle Size menu item. // Toggle between standard and big board size. // Set the user default to the new value, set // kScale and kStep to their new values, hide // the main window and then re-show it. // Re-showing the window will re-instantiate // MainVC with the new sizes. SharedAudio.stopEverything() let bigBoard = kScale == 1 ? true : false UserDefaults.standard.set(bigBoard, forKey: kBigBoardKey) kScale = bigBoard ? 2 : 1 kStep = kBaseStep * Int(kScale) showMainWindow() } func selectTheme(_ sender: NSMenuItem) { let newIndex = sender.tag let oldIndex = SharedTheme.themeIndex guard newIndex != oldIndex else { return } // Uncheck old theme menu item, check new one. themesMenu?.item(at: oldIndex)?.state = 0 themesMenu?.item(at: newIndex)?.state = 1 // Save the theme name and set the theme manager // to use the new one. let savedName = SharedTheme.themes[newIndex].name.rawValue UserDefaults.standard.set(savedName, forKey: kThemeNameKey) SharedTheme.setTheme(savedName: savedName) showMainWindow() } func setupThemesMenu() { // Set the theme manager to use the saved theme. SharedTheme.setTheme(savedName: UserDefaults.standard.string(forKey: kThemeNameKey)) // Create menu items for the themes in the theme // manager's 'themes' array. for (index, theme) in SharedTheme.themes.enumerated() { let item = NSMenuItem() item.title = theme.name.rawValue item.state = index == SharedTheme.themeIndex ? 1 : 0 item.tag = index item.action = #selector(selectTheme(_:)) themesMenu?.addItem(item) } } }
mit
bf95fc06fb432e17171402c5991ab735
32.631902
148
0.616198
4.669506
false
false
false
false
neoneye/SwiftyFORM
Example/TextField/TextFieldEditingEndViewController.swift
1
1016
// MIT license. Copyright (c) 2021 SwiftyFORM. All rights reserved. import UIKit import SwiftyFORM class TextFieldEditingEndViewController: FormViewController { override func populate(_ builder: FormBuilder) { builder.navigationTitle = "Editing End" builder.demo_showInfo("Shows an alert after editing has finished") builder += SectionHeaderTitleFormItem().title("Write a new nickname") builder += textField } lazy var textField: TextFieldFormItem = { var instance = TextFieldFormItem() instance.title = "Nickname" instance.placeholder = "Example EvilBot1337" instance.autocorrectionType = .no instance.textEditingEndBlock = { [weak self] value in self?.presentAlert(value) } return instance }() func presentAlert(_ value: String) { let alert = UIAlertController(title: "Editing End Callback", message: "Value is '\(value)'", preferredStyle: .alert) alert.addAction(UIAlertAction(title: "Ok", style: .cancel)) present(alert, animated: true) } }
mit
58499b9a24094fd3d17c2cca15a9f58e
34.034483
118
0.723425
4.37931
false
false
false
false
brentsimmons/Evergreen
Account/Sources/Account/CloudKit/CloudKitAccountZone.swift
1
12012
// // CloudKitAccountZone.swift // Account // // Created by Maurice Parker on 3/21/20. // Copyright © 2020 Ranchero Software, LLC. All rights reserved. // import Foundation import os.log import RSCore import RSWeb import RSParser import CloudKit enum CloudKitAccountZoneError: LocalizedError { case unknown var errorDescription: String? { return NSLocalizedString("An unexpected CloudKit error occurred.", comment: "An unexpected CloudKit error occurred.") } } final class CloudKitAccountZone: CloudKitZone { var zoneID: CKRecordZone.ID var log = OSLog(subsystem: Bundle.main.bundleIdentifier!, category: "CloudKit") weak var container: CKContainer? weak var database: CKDatabase? var delegate: CloudKitZoneDelegate? struct CloudKitWebFeed { static let recordType = "AccountWebFeed" struct Fields { static let url = "url" static let name = "name" static let editedName = "editedName" static let homePageURL = "homePageURL" static let containerExternalIDs = "containerExternalIDs" } } struct CloudKitContainer { static let recordType = "AccountContainer" struct Fields { static let isAccount = "isAccount" static let name = "name" } } init(container: CKContainer) { self.container = container self.database = container.privateCloudDatabase self.zoneID = CKRecordZone.ID(zoneName: "Account", ownerName: CKCurrentUserDefaultName) migrateChangeToken() } func importOPML(rootExternalID: String, items: [RSOPMLItem], completion: @escaping (Result<Void, Error>) -> Void) { var records = [CKRecord]() var feedRecords = [String: CKRecord]() func processFeed(feedSpecifier: RSOPMLFeedSpecifier, containerExternalID: String) { if let webFeedRecord = feedRecords[feedSpecifier.feedURL], var containerExternalIDs = webFeedRecord[CloudKitWebFeed.Fields.containerExternalIDs] as? [String] { containerExternalIDs.append(containerExternalID) webFeedRecord[CloudKitWebFeed.Fields.containerExternalIDs] = containerExternalIDs } else { let webFeedRecord = newWebFeedCKRecord(feedSpecifier: feedSpecifier, containerExternalID: containerExternalID) records.append(webFeedRecord) feedRecords[feedSpecifier.feedURL] = webFeedRecord } } for item in items { if let feedSpecifier = item.feedSpecifier { processFeed(feedSpecifier: feedSpecifier, containerExternalID: rootExternalID) } else { if let title = item.titleFromAttributes { let containerRecord = newContainerCKRecord(name: title) records.append(containerRecord) item.children?.forEach { itemChild in if let feedSpecifier = itemChild.feedSpecifier { processFeed(feedSpecifier: feedSpecifier, containerExternalID: containerRecord.externalID) } } } } } save(records, completion: completion) } /// Persist a web feed record to iCloud and return the external key func createWebFeed(url: String, name: String?, editedName: String?, homePageURL: String?, container: Container, completion: @escaping (Result<String, Error>) -> Void) { let recordID = CKRecord.ID(recordName: url.md5String, zoneID: zoneID) let record = CKRecord(recordType: CloudKitWebFeed.recordType, recordID: recordID) record[CloudKitWebFeed.Fields.url] = url record[CloudKitWebFeed.Fields.name] = name if let editedName = editedName { record[CloudKitWebFeed.Fields.editedName] = editedName } if let homePageURL = homePageURL { record[CloudKitWebFeed.Fields.homePageURL] = homePageURL } guard let containerExternalID = container.externalID else { completion(.failure(CloudKitZoneError.corruptAccount)) return } record[CloudKitWebFeed.Fields.containerExternalIDs] = [containerExternalID] save(record) { result in switch result { case .success: completion(.success(record.externalID)) case .failure(let error): completion(.failure(error)) } } } /// Rename the given web feed func renameWebFeed(_ webFeed: WebFeed, editedName: String?, completion: @escaping (Result<Void, Error>) -> Void) { guard let externalID = webFeed.externalID else { completion(.failure(CloudKitZoneError.corruptAccount)) return } let recordID = CKRecord.ID(recordName: externalID, zoneID: zoneID) let record = CKRecord(recordType: CloudKitWebFeed.recordType, recordID: recordID) record[CloudKitWebFeed.Fields.editedName] = editedName save(record) { result in switch result { case .success: completion(.success(())) case .failure(let error): completion(.failure(error)) } } } /// Removes a web feed from a container and optionally deletes it, calling the completion with true if deleted func removeWebFeed(_ webFeed: WebFeed, from: Container, completion: @escaping (Result<Bool, Error>) -> Void) { guard let fromContainerExternalID = from.externalID else { completion(.failure(CloudKitZoneError.corruptAccount)) return } fetch(externalID: webFeed.externalID) { result in switch result { case .success(let record): if let containerExternalIDs = record[CloudKitWebFeed.Fields.containerExternalIDs] as? [String] { var containerExternalIDSet = Set(containerExternalIDs) containerExternalIDSet.remove(fromContainerExternalID) if containerExternalIDSet.isEmpty { self.delete(externalID: webFeed.externalID) { result in switch result { case .success: completion(.success(true)) case .failure(let error): completion(.failure(error)) } } } else { record[CloudKitWebFeed.Fields.containerExternalIDs] = Array(containerExternalIDSet) self.save(record) { result in switch result { case .success: completion(.success(false)) case .failure(let error): completion(.failure(error)) } } } } case .failure(let error): if let ckError = ((error as? CloudKitError)?.error as? CKError), ckError.code == .unknownItem { completion(.success(true)) } else { completion(.failure(error)) } } } } func moveWebFeed(_ webFeed: WebFeed, from: Container, to: Container, completion: @escaping (Result<Void, Error>) -> Void) { guard let fromContainerExternalID = from.externalID, let toContainerExternalID = to.externalID else { completion(.failure(CloudKitZoneError.corruptAccount)) return } fetch(externalID: webFeed.externalID) { result in switch result { case .success(let record): if let containerExternalIDs = record[CloudKitWebFeed.Fields.containerExternalIDs] as? [String] { var containerExternalIDSet = Set(containerExternalIDs) containerExternalIDSet.remove(fromContainerExternalID) containerExternalIDSet.insert(toContainerExternalID) record[CloudKitWebFeed.Fields.containerExternalIDs] = Array(containerExternalIDSet) self.save(record, completion: completion) } case .failure(let error): completion(.failure(error)) } } } func addWebFeed(_ webFeed: WebFeed, to: Container, completion: @escaping (Result<Void, Error>) -> Void) { guard let toContainerExternalID = to.externalID else { completion(.failure(CloudKitZoneError.corruptAccount)) return } fetch(externalID: webFeed.externalID) { result in switch result { case .success(let record): if let containerExternalIDs = record[CloudKitWebFeed.Fields.containerExternalIDs] as? [String] { var containerExternalIDSet = Set(containerExternalIDs) containerExternalIDSet.insert(toContainerExternalID) record[CloudKitWebFeed.Fields.containerExternalIDs] = Array(containerExternalIDSet) self.save(record, completion: completion) } case .failure(let error): completion(.failure(error)) } } } func findWebFeedExternalIDs(for folder: Folder, completion: @escaping (Result<[String], Error>) -> Void) { guard let folderExternalID = folder.externalID else { completion(.failure(CloudKitAccountZoneError.unknown)) return } let predicate = NSPredicate(format: "containerExternalIDs CONTAINS %@", folderExternalID) let ckQuery = CKQuery(recordType: CloudKitWebFeed.recordType, predicate: predicate) query(ckQuery) { result in switch result { case .success(let records): let webFeedExternalIds = records.map { $0.externalID } completion(.success(webFeedExternalIds)) case .failure(let error): completion(.failure(error)) } } } func findOrCreateAccount(completion: @escaping (Result<String, Error>) -> Void) { let predicate = NSPredicate(format: "isAccount = \"1\"") let ckQuery = CKQuery(recordType: CloudKitContainer.recordType, predicate: predicate) database?.perform(ckQuery, inZoneWith: zoneID) { [weak self] records, error in guard let self = self else { return } switch CloudKitZoneResult.resolve(error) { case .success: DispatchQueue.main.async { if records!.count > 0 { completion(.success(records![0].externalID)) } else { self.createContainer(name: "Account", isAccount: true, completion: completion) } } case .retry(let timeToWait): self.retryIfPossible(after: timeToWait) { self.findOrCreateAccount(completion: completion) } case .zoneNotFound, .userDeletedZone: self.createZoneRecord() { result in switch result { case .success: self.findOrCreateAccount(completion: completion) case .failure(let error): DispatchQueue.main.async { completion(.failure(CloudKitError(error))) } } } default: self.createContainer(name: "Account", isAccount: true, completion: completion) } } } func createFolder(name: String, completion: @escaping (Result<String, Error>) -> Void) { createContainer(name: name, isAccount: false, completion: completion) } func renameFolder(_ folder: Folder, to name: String, completion: @escaping (Result<Void, Error>) -> Void) { guard let externalID = folder.externalID else { completion(.failure(CloudKitZoneError.corruptAccount)) return } let recordID = CKRecord.ID(recordName: externalID, zoneID: zoneID) let record = CKRecord(recordType: CloudKitContainer.recordType, recordID: recordID) record[CloudKitContainer.Fields.name] = name save(record) { result in switch result { case .success: completion(.success(())) case .failure(let error): completion(.failure(error)) } } } func removeFolder(_ folder: Folder, completion: @escaping (Result<Void, Error>) -> Void) { delete(externalID: folder.externalID, completion: completion) } } private extension CloudKitAccountZone { func newWebFeedCKRecord(feedSpecifier: RSOPMLFeedSpecifier, containerExternalID: String) -> CKRecord { let record = CKRecord(recordType: CloudKitWebFeed.recordType, recordID: generateRecordID()) record[CloudKitWebFeed.Fields.url] = feedSpecifier.feedURL if let editedName = feedSpecifier.title { record[CloudKitWebFeed.Fields.editedName] = editedName } if let homePageURL = feedSpecifier.homePageURL { record[CloudKitWebFeed.Fields.homePageURL] = homePageURL } record[CloudKitWebFeed.Fields.containerExternalIDs] = [containerExternalID] return record } func newContainerCKRecord(name: String) -> CKRecord { let record = CKRecord(recordType: CloudKitContainer.recordType, recordID: generateRecordID()) record[CloudKitContainer.Fields.name] = name record[CloudKitContainer.Fields.isAccount] = "0" return record } func createContainer(name: String, isAccount: Bool, completion: @escaping (Result<String, Error>) -> Void) { let record = CKRecord(recordType: CloudKitContainer.recordType, recordID: generateRecordID()) record[CloudKitContainer.Fields.name] = name record[CloudKitContainer.Fields.isAccount] = isAccount ? "1" : "0" save(record) { result in switch result { case .success: completion(.success(record.externalID)) case .failure(let error): completion(.failure(error)) } } } }
mit
c0ba469c6fadab82b7001da8ded0720d
32.363889
169
0.721755
3.935452
false
false
false
false
dduan/swift
validation-test/compiler_crashers_fixed/01861-swift-parser-parseexprclosure.swift
11
741
// 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 // RUN: not %target-swift-frontend %s -parse protocol a { enum S) -> { } class func d enum A = T) -> String { func a")() -> Any, () -> Void>(bytes: X<d typealias e : d = b: H.B) -> T : c, Any, A { class B == d..b["A class a { func b<T: () -> T, q:Any) { func g: NSObject { struct d.E == Swift.h: T) { typealias F = c: S<T where B : P> () { } } if true { } } init <A> { f: A { let a<S : A { } }
apache-2.0
6f2a988fa6a2dc1d99b5be057ee32402
22.903226
78
0.624831
2.861004
false
false
false
false
SimoKutlin/tweetor
tweetor/TweetMapViewController.swift
1
3866
// // TweetMapViewController.swift // tweetor // // Created by simo.kutlin on 03.05.17. // Copyright © 2017 simo.kutlin All rights reserved. // import MapKit import UIKit class TweetMapViewController: UIViewController, MKMapViewDelegate { // MARK: - UI elements @IBOutlet weak var resultMap: MKMapView! var tweets: [Tweet] = [] var geoParams: (CLLocationCoordinate2D, Double)? // MARK: - UI preparation override func viewDidLoad() { super.viewDidLoad() resultMap.delegate = self updateGUI() } private func updateGUI() { var pins: [TweetAnnotation] = [] for tweet in self.tweets { if let userData = tweet.user { let coordinates = CLLocationCoordinate2DMake(tweet.latitude, tweet.longitude) let annotation = TweetAnnotation(coordinates, tweet) annotation.title = "@" + userData.username annotation.subtitle = tweet.text pins += [annotation] } } self.resultMap.addAnnotations(pins) self.resultMap.showsUserLocation = true // Zoom to search location if let coordinate = self.geoParams?.0, let radius = self.geoParams?.1 { let zoomRadius = MKCoordinateSpanMake(radius / 400, radius / 400) let zoomRegion = MKCoordinateRegion(center: coordinate, span: zoomRadius) self.resultMap.setRegion(zoomRegion, animated: true) } } // MARK: - UI functionality func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? { if annotation is MKUserLocation { return nil } let identifier = "pin" var annotationView = mapView.dequeueReusableAnnotationView(withIdentifier: identifier) if annotationView == nil { annotationView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: identifier) annotationView?.isEnabled = true annotationView?.canShowCallout = true } else { annotationView!.annotation = annotation } let detailButton = UIButton(type: .detailDisclosure) annotationView?.rightCalloutAccessoryView = detailButton let subtitleView = UILabel() subtitleView.font = subtitleView.font.withSize(12.0) subtitleView.numberOfLines = 0 subtitleView.text = annotation.subtitle! annotationView?.leftCalloutAccessoryView = subtitleView return annotationView } func mapView(_ mapView: MKMapView, annotationView view: MKAnnotationView, calloutAccessoryControlTapped control: UIControl) { performSegue(withIdentifier: "TweetDetailSegue", sender: view.annotation) } // MARK: - Navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if let identifier = segue.identifier { switch identifier { case "TweetDetailSegue": if let seguedToMVC = segue.destination as? TweetDetailViewController, let annotation = sender as? TweetAnnotation { seguedToMVC.tweetData = annotation.tweet } default: break } } } @objc private func backSegue() { self.navigationController!.performSegue(withIdentifier: "BackToResultListSegue", sender: self) } // other stuff xcode gave me override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
6f8daa41fb9f811e589e61d15ee5b446
29.674603
129
0.596636
5.768657
false
false
false
false
Quick/Nimble
Tests/NimbleTests/Matchers/ThrowAssertionTest.swift
1
2113
import Foundation import XCTest import Nimble private let error: Error = NSError(domain: "test", code: 0, userInfo: nil) final class ThrowAssertionTest: XCTestCase { func testPositiveMatch() { #if arch(x86_64) || arch(arm64) expect { () -> Void in fatalError() }.to(throwAssertion()) #endif } func testErrorThrown() { #if arch(x86_64) || arch(arm64) expect { throw error }.toNot(throwAssertion()) #endif } func testPostAssertionCodeNotRun() { #if arch(x86_64) || arch(arm64) var reachedPoint1 = false var reachedPoint2 = false expect { reachedPoint1 = true precondition(false, "condition message") reachedPoint2 = true }.to(throwAssertion()) expect(reachedPoint1) == true expect(reachedPoint2) == false #endif } func testNegativeMatch() { #if arch(x86_64) || arch(arm64) var reachedPoint1 = false expect { reachedPoint1 = true }.toNot(throwAssertion()) expect(reachedPoint1) == true #endif } func testPositiveMessage() { #if arch(x86_64) || arch(arm64) failsWithErrorMessage("expected to throw an assertion") { expect { () -> Void? in return }.to(throwAssertion()) } failsWithErrorMessage("expected to throw an assertion; threw error instead <\(error)>") { expect { throw error }.to(throwAssertion()) } #endif } func testNegativeMessage() { #if arch(x86_64) || arch(arm64) failsWithErrorMessage("expected to not throw an assertion") { expect { () -> Void in fatalError() }.toNot(throwAssertion()) } #endif } func testNonVoidClosure() { #if arch(x86_64) || arch(arm64) expect { () -> Int in fatalError() }.to(throwAssertion()) #endif } func testChainOnThrowAssertion() { #if arch(x86_64) || arch(arm64) expect { () -> Int in return 5 }.toNot(throwAssertion()).to(equal(5)) #endif } }
apache-2.0
cdb142464ff7caaf016067282254bdb5
26.441558
97
0.573592
4.268687
false
true
false
false
casd82/powerup-iOS
PowerupTests/StorySequencePlayerUnitTests.swift
2
4174
import XCTest @testable import Powerup class StorySequencePlayerUnitTests: XCTestCase { override func setUp() { super.setUp() } override func tearDown() { super.tearDown() } /** Test all steps described in StorySequences() to ensure there are no errors in the dataset. The dataset is being generated by parsing StorySequences.json, which is created externally using the web tool PowerUp Story Designer. This allows the same data file to be used cross platform, but may introduce inconsistencies or errors in strings. - Author: Cadence Holmes 2018 - check that all media assets exist - check that position and animation strings match an enum case More thorough, functional tests are performed in UI Testing. */ func testDataSet() { // for checking values against enum cases func checkPosCases(position: String) -> Bool { for pos in StorySequence.ImagePosition.cases { if position == pos.rawValue { return true } } return false } // for checking values against enum cases func checkAniCases(position: String) -> Bool { for pos in StorySequence.ImageAnimation.cases { if position == pos.rawValue { return true } } return false } // get the real datasource let storySequences = StorySequences() // setup a mirror so we can loop through its properties, which organize sequences into collections let mirror = Mirror(reflecting: storySequences) // loop through all collections, which must be dictionaries of StorySequence() for child in mirror.children { let coll = child.value as? Dictionary<Int, StorySequence> guard let collections = coll else { return } // loop through all models which must be a StorySequence() for key in collections.keys { let sequence: StorySequence! = collections[key] let steps = sequence.steps let fileName: String? = sequence.music // if there should be music, check that the file exists let musicCheck = (fileName != nil) ? (NSDataAsset(name: fileName!) != nil) : true XCTAssert(musicCheck) for key in steps.keys { let step: StorySequence.Step! = steps[key] let lftEvent: StorySequence.Event! = step.lftEvent let rgtEvent: StorySequence.Event! = step.rgtEvent // check each side independently if lftEvent != nil { // if there should be an image, check that the file exists let lftImageCheck = (lftEvent.image != nil) ? (UIImage(named: lftEvent.image!) != nil) : true XCTAssert(lftImageCheck) // check that position strings match an enum case let lftPosCheck = (lftEvent.position != nil) ? checkPosCases(position: lftEvent.position!.rawValue) : true XCTAssert(lftPosCheck) // check that animation strings match an enum case let lftAniCheck = (lftEvent.imgAnim != nil) ? checkAniCases(position: lftEvent.imgAnim!.rawValue) : true XCTAssert(lftAniCheck) } if rgtEvent != nil { let rgtImageCheck = (rgtEvent.image != nil) ? (UIImage(named: rgtEvent.image!) != nil) : true XCTAssert(rgtImageCheck) let rgtPosCheck = (rgtEvent.position != nil) ? checkPosCases(position: rgtEvent.position!.rawValue) : true XCTAssert(rgtPosCheck) let rgtAniCheck = (rgtEvent.imgAnim != nil) ? checkAniCases(position: rgtEvent.imgAnim!.rawValue) : true XCTAssert(rgtAniCheck) } } } } } }
gpl-2.0
e03ff1f594c7bc07b718af7e22f66606
38.377358
343
0.567561
5.256927
false
true
false
false
Geor9eLau/WorkHelper
Carthage/Checkouts/SwiftCharts/SwiftCharts/Layers/ChartDividersLayer.swift
1
3293
// // ChartDividersLayer.swift // SwiftCharts // // Created by ischuetz on 21/04/15. // Copyright (c) 2015 ivanschuetz. All rights reserved. // import UIKit public struct ChartDividersLayerSettings { let linesColor: UIColor let linesWidth: CGFloat let start: CGFloat // points from start to axis, axis is 0 let end: CGFloat // points from axis to end, axis is 0 let onlyVisibleValues: Bool public init(linesColor: UIColor = UIColor.gray, linesWidth: CGFloat = 0.3, start: CGFloat = 5, end: CGFloat = 5, onlyVisibleValues: Bool = false) { self.linesColor = linesColor self.linesWidth = linesWidth self.start = start self.end = end self.onlyVisibleValues = onlyVisibleValues } } public enum ChartDividersLayerAxis { case x, y, xAndY } open class ChartDividersLayer: ChartCoordsSpaceLayer { fileprivate let settings: ChartDividersLayerSettings fileprivate let xScreenLocs: [CGFloat] fileprivate let yScreenLocs: [CGFloat] let axis: ChartDividersLayerAxis public init(xAxis: ChartAxisLayer, yAxis: ChartAxisLayer, innerFrame: CGRect, axis: ChartDividersLayerAxis = .xAndY, settings: ChartDividersLayerSettings) { self.axis = axis self.settings = settings func screenLocs(_ axisLayer: ChartAxisLayer) -> [CGFloat] { let values = settings.onlyVisibleValues ? axisLayer.axisValues.filter{!$0.hidden} : axisLayer.axisValues return values.map{axisLayer.screenLocForScalar($0.scalar)} } self.xScreenLocs = screenLocs(xAxis) self.yScreenLocs = screenLocs(yAxis) super.init(xAxis: xAxis, yAxis: yAxis, innerFrame: innerFrame) } fileprivate func drawLine(context: CGContext, color: UIColor, width: CGFloat, p1: CGPoint, p2: CGPoint) { ChartDrawLine(context: context, p1: p1, p2: p2, width: width, color: color) } override open func chartViewDrawing(context: CGContext, chart: Chart) { let xScreenLocs = self.xScreenLocs let yScreenLocs = self.yScreenLocs if self.axis == .x || self.axis == .xAndY { for xScreenLoc in xScreenLocs { let x1 = xScreenLoc let y1 = self.xAxis.lineP1.y + (self.xAxis.low ? -self.settings.end : self.settings.end) let x2 = xScreenLoc let y2 = self.xAxis.lineP1.y + (self.xAxis.low ? self.settings.start : -self.settings.start) self.drawLine(context: context, color: self.settings.linesColor, width: self.settings.linesWidth, p1: CGPoint(x: x1, y: y1), p2: CGPoint(x: x2, y: y2)) } } if self.axis == .y || self.axis == .xAndY { for yScreenLoc in yScreenLocs { let x1 = self.yAxis.lineP1.x + (self.yAxis.low ? -self.settings.start : self.settings.start) let y1 = yScreenLoc let x2 = self.yAxis.lineP1.x + (self.yAxis.low ? self.settings.end : self.settings.end) let y2 = yScreenLoc self.drawLine(context: context, color: self.settings.linesColor, width: self.settings.linesWidth, p1: CGPoint(x: x1, y: y1), p2: CGPoint(x: x2, y: y2)) } } } }
mit
4e54db4b0a6f5717c4967095acd57ef5
38.674699
167
0.633161
3.887839
false
false
false
false
zixun/CocoaChinaPlus
Code/CocoaChinaPlus/Application/Business/CocoaChina/Article/CCPArticleViewController.swift
1
8277
// // CCPArticleViewController.swift // CocoaChinaPlus // // Created by 子循 on 15/7/23. // Copyright © 2015年 zixun. All rights reserved. // import UIKit import Alamofire import Kingfisher import MBProgressHUD import RxSwift import SwViewCapture import Log4G enum CCPArticleViewType { case blog case bbs } class CCPArticleViewController: ZXBaseViewController { fileprivate var webview:CCCocoaChinaWebView! fileprivate var cuteView:ZXCuteView! //文章的wap链接 fileprivate var wapURL : String! //文章的identity fileprivate var identity : String! fileprivate var type : CCPArticleViewType! fileprivate let disposeBag = DisposeBag() fileprivate var semaphore = DispatchSemaphore(value: 0) required init(navigatorURL URL: URL?, query: Dictionary<String, String>) { super.init(navigatorURL: URL, query: query) if query["identity"] != nil { self.identity = query["identity"] self.wapURL = CCURLHelper.generateWapURL(query["identity"]!) self.type = .blog }else if query["link"] != nil { self.wapURL = query["link"] self.type = .bbs } } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override func viewDidLoad() { super.viewDidLoad() self.webview = CCCocoaChinaWebView(frame: self.view.bounds) self.view.addSubview(self.webview) self.open(wapURL) //cuteview逻辑 self.cuteViewHandle() //RightBarButtonItems逻辑 if self.type == .blog { self.addRightBarButtonItems() } } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) self.cuteView.removeFromSuperview() } func open(_ urlString:String) { let url = URL(string: urlString)! if url.host == "www.cocoachina.com" { self.webview.open(urlString) } } } // MARK: Private extension CCPArticleViewController { fileprivate func addRightBarButtonItems() { let image = self._isLiked() ? R.image.nav_like_yes() : R.image.nav_like_no() let likeButton = UIButton(frame: CGRect(x: 0, y: 0, width: 44, height: 44)) likeButton.setImage(image, for: UIControlState()) let collectionItem = UIBarButtonItem(customView: likeButton) let shareButton = UIButton(frame: CGRect(x: 0, y: 0, width: 44, height: 44)) shareButton.setImage(R.image.share(), for: UIControlState()) shareButton.rx.tap.bindNext { [unowned self] _ in UMSocialUIManager.setPreDefinePlatforms([UMSocialPlatformType.sina,UMSocialPlatformType.wechatSession,UMSocialPlatformType.wechatTimeLine,UMSocialPlatformType.wechatFavorite]) UMSocialUIManager.showShareMenuViewInWindow(platformSelectionBlock: { [unowned self] (type:UMSocialPlatformType, userInfo:[AnyHashable : Any]?) in let messageObject:UMSocialMessageObject = UMSocialMessageObject.init() messageObject.text = kADText() if type == UMSocialPlatformType.sina { let shareObject = UMShareImageObject() //设置微博分享参数 self.webview.scrollView.swContentCapture({ [unowned self] (image:UIImage?) in shareObject.shareImage = image shareObject.title = self.webview.title + " " + self.wapURL shareObject.descr = kADText() self.semaphore.signal() }) _ = self.semaphore.wait(timeout: DispatchTime.distantFuture) messageObject.shareObject = shareObject }else { let shareObject = UMShareWebpageObject() shareObject.title = self.webview.title shareObject.descr = kADText() shareObject.webpageUrl = self.wapURL messageObject.shareObject = shareObject } UMSocialManager.default().share(to: type, messageObject: messageObject, currentViewController: self, completion: { (shareResponse:Any?, error:Error?) in if error != nil { Log4G.error("Share Fail with error :\(error)") }else{ Log4G.log("Share succeed") } }) }) }.addDisposableTo(self.disposeBag) let shareItem = UIBarButtonItem(customView: shareButton) self.navigationItem.rightBarButtonItemsFixedSpace(items: [collectionItem,shareItem]) likeButton.rx.tap.bindNext { [unowned self] _ in if self._isLiked() { let result = CCArticleService.decollectArticleById(self.identity) if result { MBProgressHUD.showText("取消成功") likeButton.setImage(R.image.nav_like_no(), for: UIControlState.normal) }else { MBProgressHUD.showText("取消失败") } }else { if !CCArticleService.isArticleExsitById(self.identity) { //如果文章不存在,说明是push之类的进来的 let model = CCArticleModel() model.identity = self.identity model.title = self.webview.title model.imageURL = self.webview.imageURL CCArticleService.insertArtice(model) } let result = CCArticleService.collectArticleById(self.identity) if result { MBProgressHUD.showText("收藏成功") likeButton.setImage(R.image.nav_like_yes(), for: UIControlState.normal) }else { MBProgressHUD.showText("收藏失败") } } let scaleAnimation = CAKeyframeAnimation(keyPath: "transform.scale") scaleAnimation.duration = 0.3 scaleAnimation.values = [1.0,1.2,1.0] scaleAnimation.keyTimes = [0.0,0.5,1.0] scaleAnimation.isRemovedOnCompletion = true scaleAnimation.timingFunctions = [CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseIn), CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseOut)] likeButton.layer.add(scaleAnimation, forKey: "likeButtonscale") }.addDisposableTo(self.disposeBag) } fileprivate func cuteViewHandle() { let point = CGPoint(x: self.view.xMax - 50, y: self.view.yMax - 150) self.cuteView = ZXCuteView(point: point, superView: self.view, bubbleWidth: 40) self.cuteView.tapCallBack = {[weak self] () -> Void in if let sself = self { sself._addAnimationForBackTop() } } } /** 文章是否已经标记为收藏 - returns: 是否收藏 */ fileprivate func _isLiked() ->Bool { return CCArticleService.isArticleCollectioned(self.identity) } fileprivate func _addAnimationForBackTop() { //将webview置顶 for subview in self.webview.subviews { if subview.isKind(of: UIScrollView.self) { (subview as! UIScrollView).setContentOffset(CGPoint.zero, animated: true) } } //置顶动画 self.cuteView.removeAniamtionLikeGameCenterBubble() UIView.animate(withDuration: 0.5, animations: { () -> Void in self.cuteView.frontView?.transform = CGAffineTransform(scaleX: 1.8, y: 1.8) self.cuteView.frontView?.alpha = 0.0 }, completion: { (finished) -> Void in self.cuteView.frontView?.transform = CGAffineTransform(scaleX: 1, y: 1) self.cuteView.frontView?.alpha = 1.0 self.cuteView.addAniamtionLikeGameCenterBubble() }) } }
mit
3da0ed2cc27a800305e649f496ee7c40
36.75814
187
0.577852
4.914044
false
false
false
false
YunsChou/LovePlay
LovePlay-Swift3/LovePlay/Class/Zone/Controller/DiscussListViewController.swift
1
6037
// // DiscussListViewController.swift // LovePlay // // Created by weiying on 2017/6/6. // Copyright © 2017年 yuns. All rights reserved. // import UIKit import Alamofire class DiscussListViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { var discussListDatas : [DiscussListModel]? = [DiscussListModel]() var discussListTopDatas : [DiscussListModel]? = [DiscussListModel]() fileprivate var _fid : String? var fid : String? { set { _fid = newValue } get { return _fid } } override func viewDidLoad() { super.viewDidLoad() self.addSubViews() self.loadData() } //MARK: - private private func addSubViews() { self.view.addSubview(self.tableView) } private func loadData() { self.loadListData() self.loadImgData() } private func loadListData() { let urlStr = DiscussListURL let params : [String : Any] = ["version":"163", "module":"forumdisplay", "fid":_fid!, "tpp":"15", "charset":"utf-8", "page": "1"] Alamofire.request(urlStr, method: .get, parameters: params).responseJSON { (response) in switch response.result.isSuccess { case true : print(response.result.value!) if let value = response.result.value as? NSDictionary { let variables = value["Variables"] as? NSDictionary let forum_threadlist = variables?["forum_threadlist"] as? [NSDictionary] var discussList : [DiscussListModel]? = [DiscussListModel]() for dict in forum_threadlist! { let listModel = DiscussListModel.deserialize(from: dict) discussList?.append(listModel!) } //区分列表数据 self.sectionDiscussList(discussList: discussList!) //刷新列表 self.tableView.reloadData() } case false : print(response.result.error!) } } } private func loadImgData() { let urlStr = BaseURL + DiscussListImgURL + "/\(_fid!)" Alamofire.request(urlStr).responseJSON { (response) in switch response.result.isSuccess { case true : print(response.result.value!) if let value = response.result.value as? NSDictionary { let info = value["info"] as? NSDictionary let imgModel = DiscussImgModel.deserialize(from: info) //添加headerView self.setupTableViewHeader(imgModel: imgModel!) } case false : print(response.result.error!) } } } private func sectionDiscussList(discussList : [DiscussListModel]) { for listModel in discussList { if listModel.displayorder == 1 { self.discussListTopDatas?.append(listModel) }else{ self.discussListDatas?.append(listModel) } } } private func setupTableViewHeader(imgModel : DiscussImgModel) { self.headerView.imgModel = imgModel self.tableView.tableHeaderView = self.headerView } //MARK: - tableView dataSource func numberOfSections(in tableView: UITableView) -> Int { return 2 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { switch section { case 0: if (self.discussListTopDatas?.isEmpty)! { return 0 } return (self.discussListTopDatas?.count)! case 1: if (self.discussListDatas?.isEmpty)! { return 0 } return (self.discussListDatas?.count)! default: return 0 } } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { switch indexPath.section { case 0: let listModel = self.discussListTopDatas?[indexPath.row] let cell : DiscussListTopCell = DiscussListTopCell.cellWithTableView(tableView: tableView) cell.listModel = listModel return cell case 1: let listModel = self.discussListDatas?[indexPath.row] let cell : DiscussListCell = DiscussListCell.cellWithTableView(tableView: tableView) cell.listModel = listModel return cell default: return UITableViewCell() } } //MARK: - tableView delegate func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let listModel = self.discussListDatas?[indexPath.row] let detailViewControlelr = DiscussDetailViewController() detailViewControlelr.tid = listModel?.tid self.navigationController?.pushViewController(detailViewControlelr, animated: true) } //MARK: - setter / getter lazy var tableView : UITableView = { let tableView : UITableView = UITableView(frame: self.view.bounds, style: .plain) tableView.delegate = self tableView.dataSource = self tableView.separatorStyle = UITableViewCellSeparatorStyle.none tableView.tableFooterView = UIView() tableView.rowHeight = UITableViewAutomaticDimension tableView.estimatedRowHeight = 60 return tableView }() lazy var headerView : DiscussListHeaderView = { let headerView : DiscussListHeaderView = DiscussListHeaderView(frame: CGRect(x: 0, y: 0, width: self.tableView.width, height: 150)) return headerView }() override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
04a9fd9e823a725ed906e814cb5e38c1
33.147727
139
0.583361
5.088908
false
false
false
false
exponent/exponent
ios/versioned/sdk44/ExpoSystemUI/ExpoSystemUI/ExpoSystemUIModule.swift
2
2071
// Copyright 2021-present 650 Industries. (AKA Expo) All rights reserved. import ABI44_0_0ExpoModulesCore public class ExpoSystemUIModule: Module { public func definition() -> ModuleDefinition { name("ExpoSystemUI") onCreate { // TODO: Maybe read from the app manifest instead of from Info.plist. // Set / reset the initial color on reload and app start. let color = Bundle.main.object(forInfoDictionaryKey: "ABI44_0_0RCTRootViewBackgroundColor") as? Int Self.setBackgroundColorAsync(color: color) } function("getBackgroundColorAsync") { () -> String? in Self.getBackgroundColor() } function("setBackgroundColorAsync") { (color: Int) in Self.setBackgroundColorAsync(color: color) } } static func getBackgroundColor() -> String? { var color: String? = nil ABI44_0_0EXUtilities.performSynchronously { // Get the root view controller of the delegate window. if let window = UIApplication.shared.delegate?.window, let backgroundColor = window?.rootViewController?.view.backgroundColor?.cgColor { color = ABI44_0_0EXUtilities.hexString(with: backgroundColor) } } return color } static func setBackgroundColorAsync(color: Int?) { ABI44_0_0EXUtilities.performSynchronously { if (color == nil) { if let window = UIApplication.shared.delegate?.window { window?.backgroundColor = nil window?.rootViewController?.view.backgroundColor = UIColor.white } return } let backgroundColor = ABI44_0_0EXUtilities.uiColor(color) // Set the app-wide window, this could have future issues when running multiple ABI44_0_0React apps, // i.e. dev client can't use expo-system-ui. // Without setting the window backgroundColor, native-stack modals will show the wrong color. if let window = UIApplication.shared.delegate?.window { window?.backgroundColor = backgroundColor window?.rootViewController?.view.backgroundColor = backgroundColor } } } }
bsd-3-clause
4c90354018abb0d8ff4c5b5e4501e4ca
35.982143
142
0.689522
4.531729
false
false
false
false
icylydia/PlayWithLeetCode
189. Rotate Array/solution.swift
1
1091
class Solution { func rotate(inout nums: [Int], _ k: Int) { let kt = k % nums.count if kt == 0 { return } var i = 0 var j = nums.count - 1 var step = kt var swapper = 0 while i != j { if step * 2 == (j - i + 1) { for p in 0..<step { swapper = nums[p + i] nums[p + i] = nums[step + i + p] nums[step + i + p] = swapper } break } if step * 2 < (j - i + 1) { for p in 0..<step { swapper = nums[p + i] nums[p + i] = nums[j - step + 1 + p] nums[j - step + 1 + p] = swapper } i = step + i continue } if step * 2 > (j - i + 1) { for p in 0..<(j - i + 1 - step) { swapper = nums[p + i] nums[p + i] = nums[i + step + p] nums[i + step + p] = swapper } let len = j - i + 1 j = step + i - 1 step = step * 2 - len continue } } } }
mit
dac8dc4f5827b971765f0a087eba93bb
25
47
0.340972
3.073239
false
false
false
false
kgoedecke/loopback-swift-realm-example
loopback-swift-realm-example/WidgetViewController.swift
1
3950
// // WidgetViewController.swift // loopback-swift-realm-example // // Created by Kevin Goedecke on 2/26/16. // Copyright © 2016 kevingoedecke. All rights reserved. // import UIKit import RealmSwift class WidgetViewController: UIViewController { @IBOutlet weak var saveButton: UIBarButtonItem! @IBOutlet weak var nameTextField: UITextField! var selectedWidget: Widget! override func viewDidLoad() { super.viewDidLoad() if let selectedWidget = selectedWidget { self.nameTextField.text = selectedWidget.name } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ override func shouldPerformSegueWithIdentifier(identifier: String?, sender: AnyObject?) -> Bool { if validateFields() { if let _ = selectedWidget { updateWidget() } else { addNewWidget() } return true } else { return false } } func addNewWidget() { let widgetRemote = AppDelegate.widgetRepository.modelWithDictionary(nil) as! WidgetRemote widgetRemote.name = self.nameTextField.text! widgetRemote.updated = NSDate() widgetRemote.saveWithSuccess({ () -> Void in // Add Local Object with remote_id let realm = try! Realm() try! realm.write { let newWidget = Widget(remoteWidget: widgetRemote) realm.add(newWidget) self.selectedWidget = newWidget } }, failure: { (error: NSError!) -> Void in NSLog(error.description) // Save with no remote_id let realm = try! Realm() try! realm.write { let newWidget = Widget() newWidget.name = self.nameTextField.text! realm.add(newWidget) self.selectedWidget = newWidget } }) } func updateWidget() { let realm = try! Realm() try! realm.write { self.selectedWidget.name = self.nameTextField.text! self.selectedWidget.updated = NSDate() self.selectedWidget.syncWithRemote() } } func validateFields() -> Bool { if(nameTextField.text == "") { let alertController = UIAlertController(title: "Error", message: "Please enter a name", preferredStyle: .Alert) let alertAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.Destructive) { alert in alertController.dismissViewControllerAnimated(true, completion: nil) } alertController.addAction(alertAction) presentViewController(alertController, animated: true, completion: nil) return false } else { return true } } // MARK: - Actions @IBAction func cancelButton(sender: UIBarButtonItem) { self.dismissViewControllerAnimated(true, completion: nil) navigationController!.popViewControllerAnimated(true) } @IBAction func unwindFromWidgets(segue: UIStoryboardSegue) { if segue.identifier == "ShowDetail" { let widgetsController = segue.sourceViewController as! WidgetTableViewController selectedWidget = widgetsController.selectedWidget nameTextField.text = selectedWidget.name } } }
mit
3bb8086c2d9100266a28be466f0801c9
30.846774
123
0.591289
5.365489
false
false
false
false
ccloveswift/CLSCommon
Classes/Core/extension_path.swift
1
1149
// // extension_url.swift // Booom // // Created by TT on 2017/1/8. // Copyright © 2017年 TT. All rights reserved. // import Foundation extension URL { public static func e_gotDocumentsURL() -> URL { let str = String.e_gotDocuments() return URL.init(string: str)! } public static func e_gotLibraryURL() -> URL { let str = String.e_gotLibrary() return URL.init(string: str)! } } extension String { public static func e_gotDocuments() -> String { let documentsPaths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true) let documentsPath = documentsPaths[0] return documentsPath } public static func e_gotLibrary() -> String { let libraryPaths = NSSearchPathForDirectoriesInDomains(.libraryDirectory, .userDomainMask, true) let libraryPath = libraryPaths[0] return libraryPath } }
mit
2de4a56d308c29167f0eeb2e074cf322
22.387755
87
0.532286
5.281106
false
false
false
false
daferpi/p5App
p5App/p5App/ChildARAnnotationView.swift
1
3280
// // ChildARAnnotationView.swift // p5App // // Created by Abel Fernandez on 21/05/2017. // Copyright © 2017 Daferpi. All rights reserved. // import UIKit import HDAugmentedReality class ChildARAnnotationView: ARAnnotationView, UIGestureRecognizerDelegate { open var titleLabel: UILabel? open var infoButton: UIButton? open var image:UIImage? open var littleDescription:String? private var imageView:UIImageView? open var arFrame: CGRect = CGRect.zero // Just for test stacking override open func initialize() { super.initialize() self.loadUi() } func loadUi() { // Title label self.titleLabel?.removeFromSuperview() let label = UILabel() label.font = UIFont.systemFont(ofSize: 10) label.numberOfLines = 0 label.backgroundColor = UIColor.clear label.textColor = UIColor.white self.addSubview(label) self.titleLabel = label // Info button self.infoButton?.removeFromSuperview() let button = UIButton(type: UIButtonType.detailDisclosure) button.isUserInteractionEnabled = false // Whole view will be tappable, using it for appearance button.tintColor = UIColor.white self.addSubview(button) self.infoButton = button //ImageView self.imageView?.removeFromSuperview() let imgView = UIImageView(frame: CGRect(x: 0 , y: 0, width: 40, height: 40)) self.addSubview(imgView) self.imageView = imgView // Gesture let tapGesture = UITapGestureRecognizer(target: self, action: #selector(ChildARAnnotationView.tapGesture)) self.addGestureRecognizer(tapGesture) // Other self.backgroundColor = UIColor.green.withAlphaComponent(0.5) self.layer.cornerRadius = 5 if self.annotation != nil { self.bindUi() } } func layoutUi() { let buttonWidth: CGFloat = 40 let buttonHeight: CGFloat = 40 self.imageView?.frame = CGRect(x: 55, y: 5, width: 40, height: 40); self.titleLabel?.frame = CGRect(x: 40, y: 20, width: self.frame.size.width - buttonWidth - 5, height: self.frame.size.height); self.infoButton?.frame = CGRect(x: self.frame.size.width - buttonWidth, y: self.frame.size.height/2 - buttonHeight/2, width: buttonWidth, height: buttonHeight); } // This method is called whenever distance/azimuth is set override open func bindUi() { if let annotation = self.annotation, let title = annotation.title { self.titleLabel?.text = title } if let image = self.image { let reduceImage = image.resizeImage(newWidth: 40) self.imageView?.image = reduceImage } } open override func layoutSubviews() { super.layoutSubviews() self.layoutUi() } open func tapGesture() { if let annotation = self.annotation { let alertView = UIAlertView(title: annotation.title, message: self.littleDescription, delegate: nil, cancelButtonTitle: "OK") alertView.show() } } }
mit
77faf2ee97c744e7e5c41bfc3dc9974e
29.933962
168
0.617871
4.677603
false
false
false
false
UPetersen/LibreMonitor
LibreMonitor/ModelCoreData/CoreDataStack.swift
1
5841
// // CoreDataStack.swift // LibreMonitor // // Created by Uwe Petersen on 13.04.16. // Copyright © 2016 Uwe Petersen. All rights reserved. // import Foundation import UIKit import CoreData class CoreDataStack: NSObject { // var managedObjectContext: NSManagedObjectContext override init() { } // override init() { // // // This resource is the same name as your xcdatamodeld contained in your project. // guard let modelURL = NSBundle.mainBundle().URLForResource("DataModel", withExtension:"momd") else { // fatalError("Error loading model from bundle") // } // // // The managed object model for the application. It is a fatal error for the application not to be able to find and load its model. // guard let mom = NSManagedObjectModel(contentsOfURL: modelURL) else { // fatalError("Error initializing mom from: \(modelURL)") // } // // let psc = NSPersistentStoreCoordinator(managedObjectModel: mom) // // managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType) // managedObjectContext.persistentStoreCoordinator = psc // // dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0)) { // let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask) // let docURL = urls[urls.endIndex-1] // /* The directory the application uses to store the Core Data store file. // This code uses a file named "DataModel.sqlite" in the application's documents directory. // */ // let storeURL = docURL.URLByAppendingPathComponent("DataModel.sqlite") // do { // try psc.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: storeURL, options: nil) // } catch { // fatalError("Error migrating store: \(error)") // } // } // } lazy var applicationDocumentsDirectory: URL = { // The directory the application uses to store the Core Data store file. This code uses a directory named "UPP.LibreMonitor" in the application's documents Application Support directory. var urls = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask) return urls[urls.count-1] }() lazy var managedObjectModel: NSManagedObjectModel = { // The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model. let modelURL = Bundle.main.url(forResource: "LibreMonitor", withExtension: "momd")! return NSManagedObjectModel(contentsOf: modelURL)! }() lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = { // The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. // Create the coordinator and store let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel) let url = self.applicationDocumentsDirectory.appendingPathComponent("SingleViewCoreData.sqlite") var failureReason = "There was an error creating or loading the application's saved data." do { try coordinator.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: url, options: nil) } catch { // Report any error we got. var dict = [String: AnyObject]() dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" as AnyObject? dict[NSLocalizedFailureReasonErrorKey] = failureReason as AnyObject? dict[NSUnderlyingErrorKey] = error as NSError let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict) // Replace this with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)") abort() } return coordinator }() lazy var managedObjectContext: NSManagedObjectContext = { // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail. let coordinator = self.persistentStoreCoordinator var managedObjectContext = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType) managedObjectContext.persistentStoreCoordinator = coordinator return managedObjectContext }() // MARK: - Core Data Saving support func saveContext () { if managedObjectContext.hasChanges { do { try managedObjectContext.save() } catch { // Replace this implementation with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. let nserror = error as NSError NSLog("Unresolved error \(nserror), \(nserror.userInfo)") abort() } } } }
apache-2.0
7fd9af9fb96077659f6454d0ade8e78e
50.681416
291
0.671404
5.514636
false
false
false
false
NemProject/NEMiOSApp
NEMWallet/Application/Settings/SettingsManager.swift
1
15462
// // SettingsManager.swift // // This file is covered by the LICENSE file in the root of this project. // Copyright (c) 2016 NEM // import Foundation import CoreStore import KeychainSwift /** The manager responsible for all tasks regarding application settings. Use the singleton 'sharedInstace' of this manager to perform all kinds of tasks regarding application settings. */ final class SettingsManager { // MARK: - Manager Properties /** The singleton for the settings manager. Only use this singelton to interact with the settings manager. */ static let sharedInstance = SettingsManager() /** The keychain object used to access the keychain. This leverages the dependency 'KeychainSwift'. */ private var keychain: KeychainSwift { let keychain = KeychainSwift() keychain.synchronizable = true return keychain } /// The user defaults object used to access the user defaults store. private let userDefaults = UserDefaults.standard // MARK: - Manager Lifecycle private init() {} // Prevents others from creating own instances of this manager and not using the singleton. // MARK: - Public Manager Methods /** The current status of the application setup. The application setup is a process the user has to complete on first launch of the application, where he is able to choose an application password and more. - Returns: A bool indicating whether the application setup was already completed or not. */ public func setupIsCompleted() -> Bool { let setupIsCompleted = userDefaults.bool(forKey: "setupStatus") return setupIsCompleted } /** The current status of the Touch ID authentication setting. The user is able to activate authentication via Touch ID in the settings. - Returns: True if authentication via Touch ID is activated and false if not. */ public func touchIDAuthenticationIsActivated() -> Bool { let touchIDAuthenticationIsActivated = userDefaults.bool(forKey: "authenticationTouchIDStatus") return touchIDAuthenticationIsActivated } /** The authentication salt. All private keys get encrypted using the application password and this salt. - Returns: The current authentication salt of the application. */ open func authenticationSalt() -> String? { let authenticationSalt = keychain.get("authenticationSalt") return authenticationSalt } /** Sets the setup status for the application. - Parameter setupDone: Bool whether the setup was completed successfully or not. */ open func setSetupStatus(setupDone: Bool) { let userDefaults = UserDefaults.standard userDefaults.set(setupDone, forKey: "setupStatus") } /** Sets the setup default servers status for the application. - Parameter createdDefaultServers: Bool whether the default server were created successfully or not. */ open func setDefaultServerStatus(createdDefaultServers: Bool) { let userDefaults = UserDefaults.standard userDefaults.set(createdDefaultServers, forKey: "defaultServerStatus") } /** Gets and returns the default server status. - Returns: Bool indicating whether the default server were already successfully created or not. */ open func defaultServerStatus() -> Bool { let userDefaults = UserDefaults.standard let defaultServerStatus = userDefaults.bool(forKey: "defaultServerStatus") return defaultServerStatus } /** Sets the authentication password for the application. - Parameter applicationPassword: The authentication password that should get set for the application. */ open func setApplicationPassword(applicationPassword: String) { let salt = authenticationSalt() let saltData = salt != nil ? NSData(bytes: salt!.asByteArray(), length: salt!.asByteArray().count) : NSData().generateRandomIV(32) as NSData let passwordHash = try! HashManager.generateAesKeyForString(applicationPassword, salt: saltData, roundCount: 2000)! setAuthenticationSalt(authenticationSalt: saltData.hexadecimalString()) setSetupStatus(setupDone: true) keychain.set(passwordHash.hexadecimalString(), forKey: "applicationPassword") } /** Gets and returns the currently set authentication password. - Returns: The current authentication password of the application. */ open func applicationPassword() -> String { let applicationPassword = keychain.get("applicationPassword") ?? String() return applicationPassword } /** Sets the authentication salt for the application. - Parameter authenticationSalt: The authentication salt that should get set for the application. */ open func setAuthenticationSalt(authenticationSalt: String) { keychain.set(authenticationSalt, forKey: "authenticationSalt") } /** Sets the invoice message prefix for the application. - Parameter invoiceMessagePrefix: The invoice message prefix which should get set for the application. */ open func setInvoiceMessagePrefix(invoiceMessagePrefix: String) { let userDefaults = UserDefaults.standard userDefaults.set(invoiceMessagePrefix, forKey: "invoiceMessagePrefix") } /** Gets and returns the invoice message prefix. - Returns: The invoice message prefix as a string. */ open func invoiceMessagePrefix() -> String { let userDefaults = UserDefaults.standard let invoiceMessagePrefix = userDefaults.object(forKey: "invoiceMessagePrefix") as? String ?? String() return invoiceMessagePrefix } /** Sets the invoice message postfix for the application. - Parameter invoiceMessagePostfix: The invoice message postfix which should get set for the application. */ open func setInvoiceMessagePostfix(invoiceMessagePostfix: String) { let userDefaults = UserDefaults.standard userDefaults.set(invoiceMessagePostfix, forKey: "invoiceMessagePostfix") } /** Gets and returns the invoice message postfix. - Returns: The invoice message postfix as a string. */ open func invoiceMessagePostfix() -> String { let userDefaults = UserDefaults.standard let invoiceMessagePostfix = userDefaults.object(forKey: "invoiceMessagePostfix") as? String ?? String() return invoiceMessagePostfix } /** Sets the invoice default message for the application. - Parameter invoiceDefaultMessage: The invoice default message which should get set for the application. */ open func setInvoiceDefaultMessage(invoiceDefaultMessage: String) { let userDefaults = UserDefaults.standard userDefaults.set(invoiceDefaultMessage, forKey: "invoiceDefaultMessage") } /** Gets and returns the invoice default message. - Returns: The invoice default message as a string. */ open func invoiceDefaultMessage() -> String { let userDefaults = UserDefaults.standard let invoiceDefaultMessage = userDefaults.object(forKey: "invoiceDefaultMessage") as? String ?? String() return invoiceDefaultMessage } /** Sets the authentication touch id status. - Parameter authenticationTouchIDStatus: The status of the authentication touch id setting that should get set. */ open func setAuthenticationTouchIDStatus(authenticationTouchIDStatus: Bool) { let userDefaults = UserDefaults.standard userDefaults.set(authenticationTouchIDStatus, forKey: "authenticationTouchIDStatus") } /** Fetches all stored servers from the database. - Returns: An array of servers. */ open func servers() -> [Server] { let servers = DatabaseManager.sharedInstance.dataStack.fetchAll(From(Server.self)) ?? [] return servers } /** Creates a new server object and stores that object in the database. - Parameter protocolType: The protocol type of the new server (http/https). - Parameter address: The address of the new server. - Parameter port: The port of the new server. - Returns: The result of the operation - success or failure. */ open func create(server address: String, withProtocolType protocolType: String, andPort port: String, completion: @escaping (_ result: Result) -> Void) { DatabaseManager.sharedInstance.dataStack.perform( asynchronous: { (transaction) -> Void in let server = transaction.create(Into(Server.self)) server.address = address server.protocolType = protocolType server.port = port server.isDefault = false }, success: { return completion(.success) }, failure: { (error) in return completion(.failure) } ) } /** Creates all default server objects and stores those objects in the database. - Returns: The result of the operation - success or failure. */ open func createDefaultServers(completion: @escaping (_ result: Result) -> Void) { DatabaseManager.sharedInstance.dataStack.perform( asynchronous: { (transaction) -> Void in let mainBundle = Bundle.main let resourcePath = Constants.activeNetwork == Constants.testNetwork ? mainBundle.path(forResource: "TestnetDefaultServers", ofType: "plist")! : mainBundle.path(forResource: "DefaultServers", ofType: "plist")! let defaultServers = NSDictionary(contentsOfFile: resourcePath)! as! [String: [String]] for (_, defaultServer) in defaultServers { let server = transaction.create(Into(Server.self)) server.protocolType = defaultServer[0] server.address = defaultServer[1] server.port = defaultServer[2] server.isDefault = true } }, success: { self.setActiveServer(server: self.servers().first!) self.setDefaultServerStatus(createdDefaultServers: true) return completion(.success) }, failure: { (error) in return completion(.failure) } ) } /** Deletes the provided server object from the database. - Parameter server: The server object that should get deleted. */ open func delete(server: Server) { if server == activeServer() { var servers = self.servers() for (index, serverObj) in servers.enumerated() where server.address == serverObj.address { servers.remove(at: index) } self.setActiveServer(server: servers.first!) } DatabaseManager.sharedInstance.dataStack.perform( asynchronous: { (transaction) -> Void in transaction.delete(server) }, completion: { _ in } ) } /** Updates the properties for a server in the database. - Parameter server: The existing server that should get updated. - Parameter protocolType: The new protocol type for the server that should get updated. - Parameter address: The new address for the server that should get updated. - Parameter port: The new port for the server that should get updated. */ open func updateProperties(forServer server: Server, withNewProtocolType protocolType: String, andNewAddress address: String, andNewPort port: String, completion: @escaping (_ result: Result) -> Void) { DatabaseManager.sharedInstance.dataStack.perform( asynchronous: { (transaction) -> Void in let editableServer = transaction.edit(server)! editableServer.protocolType = protocolType editableServer.address = address editableServer.port = port if server.address != address && server == self.activeServer() { self.setActiveServer(serverAddress: address) } }, success: { return completion(.success) }, failure: { (error) in return completion(.failure) } ) } /** Validates if a server with the provided server address already got added to the application or not. - Parameter serverAddress: The address of the server that should get checked for existence. - Throws: - ServerAdditionValidation.ServerAlreadyPresent if a server with the provided address already got added to the application. - Returns: A bool indicating that no server with the provided address was added to the application. */ open func validateServerExistence(forServerWithAddress serverAddress: String) throws -> Bool { let servers = self.servers() for server in servers where server.address == serverAddress { throw ServerAdditionValidation.serverAlreadyPresent(serverAddress: server.address) } return true } /** Sets the currently active server. - Parameter server: The server which should get set as the currently active server. */ open func setActiveServer(server: Server) { let userDefaults = UserDefaults.standard userDefaults.set(server.address, forKey: "activeServer") } /** Sets the currently active server. - Parameter serverAddress: The address of the server which should get set as the currently active server. */ open func setActiveServer(serverAddress: String) { let userDefaults = UserDefaults.standard userDefaults.set(serverAddress, forKey: "activeServer") } /** Fetches and returns the currently active server. - Returns: The currently active server. */ open func activeServer() -> Server { var activeServer: Server? let userDefaults = UserDefaults.standard let activeServerIdentifier = userDefaults.string(forKey: "activeServer")! for server in servers() where server.address == activeServerIdentifier { activeServer = server } return activeServer! } }
mit
d81c5c70c0c6ca05c0e02c4f04d13d3d
34.463303
224
0.624369
5.68665
false
false
false
false
vkozlovskyi/JellyView
JellyView-Example/JellyView/Path/TopSidePathBuilder.swift
1
4207
// // Created by Vladimir Kozlovskyi on 7/26/18. // Copyright (c) 2018 Vladimir Kozlovskyi. All rights reserved. // import UIKit public struct TopSidePathBuilder: PathBuilder { func buildCurrentPath(inputData: PathInputData) -> Path { let width = inputData.frame.width let outerDelta = inputData.outerPointRatio * width let extraSpace = inputData.frame.width / Constants.extraSpaceDivider let fstStartPoint = CGPoint(x: -extraSpace, y: 0) let fstEndPoint = CGPoint(x: inputData.touchPoint.x, y: inputData.touchPoint.y) let fstControlPoint1 = CGPoint(x: inputData.touchPoint.x * inputData.innerPointRatio, y: 0) let fstControlPoint2 = CGPoint(x: inputData.touchPoint.x - outerDelta, y: inputData.touchPoint.y) let sndStartPoint = fstEndPoint let sndEndPoint = CGPoint(x: width + extraSpace, y: 0) let sndControlPoint1 = CGPoint(x: inputData.touchPoint.x + outerDelta, y: inputData.touchPoint.y) let sndControlPoint2 = CGPoint(x: inputData.touchPoint.x + (width - inputData.touchPoint.x) * (1.0 - inputData.innerPointRatio), y: 0) let fstCurve = Curve(startPoint: fstStartPoint, endPoint: fstEndPoint, controlPoint1: fstControlPoint1, controlPoint2: fstControlPoint2) let sndCurve = Curve(startPoint: sndStartPoint, endPoint: sndEndPoint, controlPoint1: sndControlPoint1, controlPoint2: sndControlPoint2) let path = Path(fstCurve: fstCurve, sndCurve: sndCurve) return path } func buildInitialPath(inputData: PathInputData) -> Path { let width = inputData.frame.width let outerDelta = inputData.outerPointRatio * width let centerY = width / 2 let extraSpace = inputData.frame.width / Constants.extraSpaceDivider let fstStartPoint = CGPoint(x: -extraSpace, y: 0) let fstEndPoint = CGPoint(x: centerY, y: 0) let fstControlPoint1 = CGPoint(x: centerY * inputData.innerPointRatio, y: 0) let fstControlPoint2 = CGPoint(x: centerY - outerDelta, y: 0) let sndStartPoint = fstEndPoint let sndEndPoint = CGPoint(x: width + extraSpace, y: 0) let sndControlPoint1 = CGPoint(x: centerY + outerDelta, y: 0) let sndControlPoint2: CGPoint = CGPoint(x: centerY + (width - centerY) * (1.0 - inputData.innerPointRatio), y: 0) let fstCurve = Curve(startPoint: fstStartPoint, endPoint: fstEndPoint, controlPoint1: fstControlPoint1, controlPoint2: fstControlPoint2) let sndCurve = Curve(startPoint: sndStartPoint, endPoint: sndEndPoint, controlPoint1: sndControlPoint1, controlPoint2: sndControlPoint2) let path = Path(fstCurve: fstCurve, sndCurve: sndCurve) return path } func buildExpandedPath(inputData: PathInputData) -> Path { let extraSpace = inputData.frame.width / Constants.extraSpaceDivider let height = inputData.frame.height * 2 let width = inputData.frame.width let centerX = width / 2 let fstStartPoint: CGPoint = CGPoint(x: -extraSpace, y: 0) let fstEndPoint: CGPoint = CGPoint(x: centerX, y: height) let fstControlPoint1: CGPoint = CGPoint(x: -extraSpace, y: height / 2) let fstControlPoint2: CGPoint = CGPoint(x: centerX / 2, y: height) let sndStartPoint: CGPoint = fstEndPoint let sndEndPoint: CGPoint = CGPoint(x: width + extraSpace, y: 0) let sndControlPoint1: CGPoint = CGPoint(x: centerX + extraSpace, y: height) let sndControlPoint2: CGPoint = CGPoint(x: width + extraSpace, y: height / 2) let fstCurve = Curve(startPoint: fstStartPoint, endPoint: fstEndPoint, controlPoint1: fstControlPoint1, controlPoint2: fstControlPoint2) let sndCurve = Curve(startPoint: sndStartPoint, endPoint: sndEndPoint, controlPoint1: sndControlPoint1, controlPoint2: sndControlPoint2) let path = Path(fstCurve: fstCurve, sndCurve: sndCurve) return path } }
mit
dd98f56b412819018df56dfee1161083
41.07
138
0.658902
4.271066
false
false
false
false
tokyovigilante/CesiumKit
CesiumKit/Core/GeometryPipeline.swift
1
71929
// // GeometryPipeline.swift // CesiumKit // // Created by Ryan Walklin on 13/09/14. // Copyright (c) 2014 Test Toast. All rights reserved. // struct GeometryPipeline { /* /** * Content pipeline functions for geometries. * * @namespace * @alias GeometryPipeline * * @see Geometry */ var GeometryPipeline = {}; function addTriangle(lines, index, i0, i1, i2) { lines[index++] = i0; lines[index++] = i1; lines[index++] = i1; lines[index++] = i2; lines[index++] = i2; lines[index] = i0; } function trianglesToLines(triangles) { var count = triangles.length; var size = (count / 3) * 6; var lines = IndexDatatype.createTypedArray(count, size); var index = 0; for ( var i = 0; i < count; i += 3, index += 6) { addTriangle(lines, index, triangles[i], triangles[i + 1], triangles[i + 2]); } return lines; } function triangleStripToLines(triangles) { var count = triangles.length; if (count >= 3) { var size = (count - 2) * 6; var lines = IndexDatatype.createTypedArray(count, size); addTriangle(lines, 0, triangles[0], triangles[1], triangles[2]); var index = 6; for ( var i = 3; i < count; ++i, index += 6) { addTriangle(lines, index, triangles[i - 1], triangles[i], triangles[i - 2]); } return lines; } return new Uint16Array(); } function triangleFanToLines(triangles) { if (triangles.length > 0) { var count = triangles.length - 1; var size = (count - 1) * 6; var lines = IndexDatatype.createTypedArray(count, size); var base = triangles[0]; var index = 0; for ( var i = 1; i < count; ++i, index += 6) { addTriangle(lines, index, base, triangles[i], triangles[i + 1]); } return lines; } return new Uint16Array(); } /** * Converts a geometry's triangle indices to line indices. If the geometry has an <code>indices</code> * and its <code>primitiveType</code> is <code>TRIANGLES</code>, <code>TRIANGLE_STRIP</code>, * <code>TRIANGLE_FAN</code>, it is converted to <code>LINES</code>; otherwise, the geometry is not changed. * <p> * This is commonly used to create a wireframe geometry for visual debugging. * </p> * * @param {Geometry} geometry The geometry to modify. * @returns {Geometry} The modified <code>geometry</code> argument, with its triangle indices converted to lines. * * @exception {DeveloperError} geometry.primitiveType must be TRIANGLES, TRIANGLE_STRIP, or TRIANGLE_FAN. * * @example * geometry = Cesium.GeometryPipeline.toWireframe(geometry); */ GeometryPipeline.toWireframe = function(geometry) { //>>includeStart('debug', pragmas.debug); if (!defined(geometry)) { throw new DeveloperError('geometry is required.'); } //>>includeEnd('debug'); var indices = geometry.indices; if (defined(indices)) { switch (geometry.primitiveType) { case PrimitiveType.TRIANGLES: geometry.indices = trianglesToLines(indices); break; case PrimitiveType.TRIANGLE_STRIP: geometry.indices = triangleStripToLines(indices); break; case PrimitiveType.TRIANGLE_FAN: geometry.indices = triangleFanToLines(indices); break; default: throw new DeveloperError('geometry.primitiveType must be TRIANGLES, TRIANGLE_STRIP, or TRIANGLE_FAN.'); } geometry.primitiveType = PrimitiveType.LINES; } return geometry; }; /** * Creates a new {@link Geometry} with <code>LINES</code> representing the provided * attribute (<code>attributeName</code>) for the provided geometry. This is used to * visualize vector attributes like normals, binormals, and tangents. * * @param {Geometry} geometry The <code>Geometry</code> instance with the attribute. * @param {String} [attributeName='normal'] The name of the attribute. * @param {Number} [length=10000.0] The length of each line segment in meters. This can be negative to point the vector in the opposite direction. * @returns {Geometry} A new <code>Geometry<code> instance with line segments for the vector. * * @exception {DeveloperError} geometry.attributes must have an attribute with the same name as the attributeName parameter. * * @example * var geometry = Cesium.GeometryPipeline.createLineSegmentsForVectors(instance.geometry, 'binormal', 100000.0), */ GeometryPipeline.createLineSegmentsForVectors = function(geometry, attributeName, length) { attributeName = defaultValue(attributeName, 'normal'); //>>includeStart('debug', pragmas.debug); if (!defined(geometry)) { throw new DeveloperError('geometry is required.'); } if (!defined(geometry.attributes.position)) { throw new DeveloperError('geometry.attributes.position is required.'); } if (!defined(geometry.attributes[attributeName])) { throw new DeveloperError('geometry.attributes must have an attribute with the same name as the attributeName parameter, ' + attributeName + '.'); } //>>includeEnd('debug'); length = defaultValue(length, 10000.0); var positions = geometry.attributes.position.values; var vectors = geometry.attributes[attributeName].values; var positionsLength = positions.length; var newPositions = new Float64Array(2 * positionsLength); var j = 0; for (var i = 0; i < positionsLength; i += 3) { newPositions[j++] = positions[i]; newPositions[j++] = positions[i + 1]; newPositions[j++] = positions[i + 2]; newPositions[j++] = positions[i] + (vectors[i] * length); newPositions[j++] = positions[i + 1] + (vectors[i + 1] * length); newPositions[j++] = positions[i + 2] + (vectors[i + 2] * length); } var newBoundingSphere; var bs = geometry.boundingSphere; if (defined(bs)) { newBoundingSphere = new BoundingSphere(bs.center, bs.radius + length); } return new Geometry({ attributes : { position : new GeometryAttribute({ componentDatatype : ComponentDatatype.DOUBLE, componentsPerAttribute : 3, values : newPositions }) }, primitiveType : PrimitiveType.LINES, boundingSphere : newBoundingSphere }); }; */ /** * Creates an object that maps attribute names to unique locations (indices) * for matching vertex attributes and shader programs. * * @param {Geometry} geometry The geometry, which is not modified, to create the object for. * @returns {Object} An object with attribute name / index pairs. * * @example * var attributeLocations = Cesium.GeometryPipeline.createAttributeLocations(geometry); * // Example output * // { * // 'position' : 0, * // 'normal' : 1 * // } */ static func createAttributeLocations (_ geometry: Geometry) -> [String: Int] { // There can be a WebGL performance hit when attribute 0 is disabled, so // assign attribute locations to well-known attributes. let semantics = [ "position", "positionHigh", "positionLow", // From VertexFormat.position - after 2D projection and high-precision encoding "position3DHigh", "position3DLow", "position2DHigh", "position2DLow", // From Primitive "pickColor", // From VertexFormat "normal", "st", "binormal", "tangent", // From compressing texture coordinates and normals "compressedAttributes" ] let attributes = geometry.attributes var indices = [String: Int]() var j = 0 // Attribute locations for well-known attributes for semantic in semantics { if attributes[semantic] != nil { indices[semantic] = j j += 1 } } // Locations for custom attributes for attribute in attributes { if indices[attribute.name] == nil { indices[attribute.name] = j j += 1 } } return indices } /* /** * Reorders a geometry's attributes and <code>indices</code> to achieve better performance from the GPU's pre-vertex-shader cache. * * @param {Geometry} geometry The geometry to modify. * @returns {Geometry} The modified <code>geometry</code> argument, with its attributes and indices reordered for the GPU's pre-vertex-shader cache. * * @exception {DeveloperError} Each attribute array in geometry.attributes must have the same number of attributes. * * @see GeometryPipeline.reorderForPostVertexCache * * @example * geometry = Cesium.GeometryPipeline.reorderForPreVertexCache(geometry); */ GeometryPipeline.reorderForPreVertexCache = function(geometry) { //>>includeStart('debug', pragmas.debug); if (!defined(geometry)) { throw new DeveloperError('geometry is required.'); } //>>includeEnd('debug'); var numVertices = Geometry.computeNumberOfVertices(geometry); var indices = geometry.indices; if (defined(indices)) { var indexCrossReferenceOldToNew = new Int32Array(numVertices); for ( var i = 0; i < numVertices; i++) { indexCrossReferenceOldToNew[i] = -1; } // Construct cross reference and reorder indices var indicesIn = indices; var numIndices = indicesIn.length; var indicesOut = IndexDatatype.createTypedArray(numVertices, numIndices); var intoIndicesIn = 0; var intoIndicesOut = 0; var nextIndex = 0; var tempIndex; while (intoIndicesIn < numIndices) { tempIndex = indexCrossReferenceOldToNew[indicesIn[intoIndicesIn]]; if (tempIndex !== -1) { indicesOut[intoIndicesOut] = tempIndex; } else { tempIndex = indicesIn[intoIndicesIn]; indexCrossReferenceOldToNew[tempIndex] = nextIndex; indicesOut[intoIndicesOut] = nextIndex; ++nextIndex; } ++intoIndicesIn; ++intoIndicesOut; } geometry.indices = indicesOut; // Reorder attributes var attributes = geometry.attributes; for ( var property in attributes) { if (attributes.hasOwnProperty(property) && defined(attributes[property]) && defined(attributes[property].values)) { var attribute = attributes[property]; var elementsIn = attribute.values; var intoElementsIn = 0; var numComponents = attribute.componentsPerAttribute; var elementsOut = ComponentDatatype.createTypedArray(attribute.componentDatatype, nextIndex * numComponents); while (intoElementsIn < numVertices) { var temp = indexCrossReferenceOldToNew[intoElementsIn]; if (temp !== -1) { for (i = 0; i < numComponents; i++) { elementsOut[numComponents * temp + i] = elementsIn[numComponents * intoElementsIn + i]; } } ++intoElementsIn; } attribute.values = elementsOut; } } } return geometry; }; /** * Reorders a geometry's <code>indices</code> to achieve better performance from the GPU's * post vertex-shader cache by using the Tipsify algorithm. If the geometry <code>primitiveType</code> * is not <code>TRIANGLES</code> or the geometry does not have an <code>indices</code>, this function has no effect. * * @param {Geometry} geometry The geometry to modify. * @param {Number} [cacheCapacity=24] The number of vertices that can be held in the GPU's vertex cache. * @returns {Geometry} The modified <code>geometry</code> argument, with its indices reordered for the post-vertex-shader cache. * * @exception {DeveloperError} cacheCapacity must be greater than two. * * @see GeometryPipeline.reorderForPreVertexCache * @see {@link http://gfx.cs.princeton.edu/pubs/Sander_2007_%3ETR/tipsy.pdf|Fast Triangle Reordering for Vertex Locality and Reduced Overdraw} * by Sander, Nehab, and Barczak * * @example * geometry = Cesium.GeometryPipeline.reorderForPostVertexCache(geometry); */ GeometryPipeline.reorderForPostVertexCache = function(geometry, cacheCapacity) { //>>includeStart('debug', pragmas.debug); if (!defined(geometry)) { throw new DeveloperError('geometry is required.'); } //>>includeEnd('debug'); var indices = geometry.indices; if ((geometry.primitiveType === PrimitiveType.TRIANGLES) && (defined(indices))) { var numIndices = indices.length; var maximumIndex = 0; for ( var j = 0; j < numIndices; j++) { if (indices[j] > maximumIndex) { maximumIndex = indices[j]; } } geometry.indices = Tipsify.tipsify({ indices : indices, maximumIndex : maximumIndex, cacheSize : cacheCapacity }); } return geometry; }; function copyAttributesDescriptions(attributes) { var newAttributes = {}; for ( var attribute in attributes) { if (attributes.hasOwnProperty(attribute) && defined(attributes[attribute]) && defined(attributes[attribute].values)) { var attr = attributes[attribute]; newAttributes[attribute] = new GeometryAttribute({ componentDatatype : attr.componentDatatype, componentsPerAttribute : attr.componentsPerAttribute, normalize : attr.normalize, values : [] }); } } return newAttributes; } function copyVertex(destinationAttributes, sourceAttributes, index) { for ( var attribute in sourceAttributes) { if (sourceAttributes.hasOwnProperty(attribute) && defined(sourceAttributes[attribute]) && defined(sourceAttributes[attribute].values)) { var attr = sourceAttributes[attribute]; for ( var k = 0; k < attr.componentsPerAttribute; ++k) { destinationAttributes[attribute].values.push(attr.values[(index * attr.componentsPerAttribute) + k]); } } } } /** * Splits a geometry into multiple geometries, if necessary, to ensure that indices in the * <code>indices</code> fit into unsigned shorts. This is used to meet the WebGL requirements * when unsigned int indices are not supported. * <p> * If the geometry does not have any <code>indices</code>, this function has no effect. * </p> * * @param {Geometry} geometry The geometry to be split into multiple geometries. * @returns {Geometry[]} An array of geometries, each with indices that fit into unsigned shorts. * * @exception {DeveloperError} geometry.primitiveType must equal to PrimitiveType.TRIANGLES, PrimitiveType.LINES, or PrimitiveType.POINTS * @exception {DeveloperError} All geometry attribute lists must have the same number of attributes. * * @example * var geometries = Cesium.GeometryPipeline.fitToUnsignedShortIndices(geometry); */ GeometryPipeline.fitToUnsignedShortIndices = function(geometry) { //>>includeStart('debug', pragmas.debug); if (!defined(geometry)) { throw new DeveloperError('geometry is required.'); } if ((defined(geometry.indices)) && ((geometry.primitiveType !== PrimitiveType.TRIANGLES) && (geometry.primitiveType !== PrimitiveType.LINES) && (geometry.primitiveType !== PrimitiveType.POINTS))) { throw new DeveloperError('geometry.primitiveType must equal to PrimitiveType.TRIANGLES, PrimitiveType.LINES, or PrimitiveType.POINTS.'); } //>>includeEnd('debug'); var geometries = []; // If there's an index list and more than 64K attributes, it is possible that // some indices are outside the range of unsigned short [0, 64K - 1] var numberOfVertices = Geometry.computeNumberOfVertices(geometry); if (defined(geometry.indices) && (numberOfVertices > CesiumMath.SIXTY_FOUR_KILOBYTES)) { var oldToNewIndex = []; var newIndices = []; var currentIndex = 0; var newAttributes = copyAttributesDescriptions(geometry.attributes); var originalIndices = geometry.indices; var numberOfIndices = originalIndices.length; var indicesPerPrimitive; if (geometry.primitiveType === PrimitiveType.TRIANGLES) { indicesPerPrimitive = 3; } else if (geometry.primitiveType === PrimitiveType.LINES) { indicesPerPrimitive = 2; } else if (geometry.primitiveType === PrimitiveType.POINTS) { indicesPerPrimitive = 1; } for ( var j = 0; j < numberOfIndices; j += indicesPerPrimitive) { for (var k = 0; k < indicesPerPrimitive; ++k) { var x = originalIndices[j + k]; var i = oldToNewIndex[x]; if (!defined(i)) { i = currentIndex++; oldToNewIndex[x] = i; copyVertex(newAttributes, geometry.attributes, x); } newIndices.push(i); } if (currentIndex + indicesPerPrimitive > CesiumMath.SIXTY_FOUR_KILOBYTES) { geometries.push(new Geometry({ attributes : newAttributes, indices : newIndices, primitiveType : geometry.primitiveType, boundingSphere : geometry.boundingSphere })); // Reset for next vertex-array oldToNewIndex = []; newIndices = []; currentIndex = 0; newAttributes = copyAttributesDescriptions(geometry.attributes); } } if (newIndices.length !== 0) { geometries.push(new Geometry({ attributes : newAttributes, indices : newIndices, primitiveType : geometry.primitiveType, boundingSphere : geometry.boundingSphere })); } } else { // No need to split into multiple geometries geometries.push(geometry); } return geometries; }; var scratchProjectTo2DCartesian3 = new Cartesian3(); var scratchProjectTo2DCartographic = new Cartographic(); /** * Projects a geometry's 3D <code>position</code> attribute to 2D, replacing the <code>position</code> * attribute with separate <code>position3D</code> and <code>position2D</code> attributes. * <p> * If the geometry does not have a <code>position</code>, this function has no effect. * </p> * * @param {Geometry} geometry The geometry to modify. * @param {String} attributeName The name of the attribute. * @param {String} attributeName3D The name of the attribute in 3D. * @param {String} attributeName2D The name of the attribute in 2D. * @param {Object} [projection=new GeographicProjection()] The projection to use. * @returns {Geometry} The modified <code>geometry</code> argument with <code>position3D</code> and <code>position2D</code> attributes. * * @exception {DeveloperError} geometry must have attribute matching the attributeName argument. * @exception {DeveloperError} The attribute componentDatatype must be ComponentDatatype.DOUBLE. * @exception {DeveloperError} Could not project a point to 2D. * * @example * geometry = Cesium.GeometryPipeline.projectTo2D(geometry, 'position', 'position3D', 'position2D'); */ GeometryPipeline.projectTo2D = function(geometry, attributeName, attributeName3D, attributeName2D, projection) { //>>includeStart('debug', pragmas.debug); if (!defined(geometry)) { throw new DeveloperError('geometry is required.'); } if (!defined(attributeName)) { throw new DeveloperError('attributeName is required.'); } if (!defined(attributeName3D)) { throw new DeveloperError('attributeName3D is required.'); } if (!defined(attributeName2D)) { throw new DeveloperError('attributeName2D is required.'); } if (!defined(geometry.attributes[attributeName])) { throw new DeveloperError('geometry must have attribute matching the attributeName argument: ' + attributeName + '.'); } if (geometry.attributes[attributeName].componentDatatype !== ComponentDatatype.DOUBLE) { throw new DeveloperError('The attribute componentDatatype must be ComponentDatatype.DOUBLE.'); } //>>includeEnd('debug'); var attribute = geometry.attributes[attributeName]; projection = (defined(projection)) ? projection : new GeographicProjection(); var ellipsoid = projection.ellipsoid; // Project original values to 2D. var values3D = attribute.values; var projectedValues = new Float64Array(values3D.length); var index = 0; for ( var i = 0; i < values3D.length; i += 3) { var value = Cartesian3.fromArray(values3D, i, scratchProjectTo2DCartesian3); var lonLat = ellipsoid.cartesianToCartographic(value, scratchProjectTo2DCartographic); if (!defined(lonLat)) { throw new DeveloperError('Could not project point (' + value.x + ', ' + value.y + ', ' + value.z + ') to 2D.'); } var projectedLonLat = projection.project(lonLat, scratchProjectTo2DCartesian3); projectedValues[index++] = projectedLonLat.x; projectedValues[index++] = projectedLonLat.y; projectedValues[index++] = projectedLonLat.z; } // Rename original cartesians to WGS84 cartesians. geometry.attributes[attributeName3D] = attribute; // Replace original cartesians with 2D projected cartesians geometry.attributes[attributeName2D] = new GeometryAttribute({ componentDatatype : ComponentDatatype.DOUBLE, componentsPerAttribute : 3, values : projectedValues }); delete geometry.attributes[attributeName]; return geometry; }; var encodedResult = { high : 0.0, low : 0.0 }; /** * Encodes floating-point geometry attribute values as two separate attributes to improve * rendering precision. * <p> * This is commonly used to create high-precision position vertex attributes. * </p> * * @param {Geometry} geometry The geometry to modify. * @param {String} attributeName The name of the attribute. * @param {String} attributeHighName The name of the attribute for the encoded high bits. * @param {String} attributeLowName The name of the attribute for the encoded low bits. * @returns {Geometry} The modified <code>geometry</code> argument, with its encoded attribute. * * @exception {DeveloperError} geometry must have attribute matching the attributeName argument. * @exception {DeveloperError} The attribute componentDatatype must be ComponentDatatype.DOUBLE. * * @example * geometry = Cesium.GeometryPipeline.encodeAttribute(geometry, 'position3D', 'position3DHigh', 'position3DLow'); */ GeometryPipeline.encodeAttribute = function(geometry, attributeName, attributeHighName, attributeLowName) { //>>includeStart('debug', pragmas.debug); if (!defined(geometry)) { throw new DeveloperError('geometry is required.'); } if (!defined(attributeName)) { throw new DeveloperError('attributeName is required.'); } if (!defined(attributeHighName)) { throw new DeveloperError('attributeHighName is required.'); } if (!defined(attributeLowName)) { throw new DeveloperError('attributeLowName is required.'); } if (!defined(geometry.attributes[attributeName])) { throw new DeveloperError('geometry must have attribute matching the attributeName argument: ' + attributeName + '.'); } if (geometry.attributes[attributeName].componentDatatype !== ComponentDatatype.DOUBLE) { throw new DeveloperError('The attribute componentDatatype must be ComponentDatatype.DOUBLE.'); } //>>includeEnd('debug'); var attribute = geometry.attributes[attributeName]; var values = attribute.values; var length = values.length; var highValues = new Float32Array(length); var lowValues = new Float32Array(length); for (var i = 0; i < length; ++i) { EncodedCartesian3.encode(values[i], encodedResult); highValues[i] = encodedResult.high; lowValues[i] = encodedResult.low; } var componentsPerAttribute = attribute.componentsPerAttribute; geometry.attributes[attributeHighName] = new GeometryAttribute({ componentDatatype : ComponentDatatype.FLOAT, componentsPerAttribute : componentsPerAttribute, values : highValues }); geometry.attributes[attributeLowName] = new GeometryAttribute({ componentDatatype : ComponentDatatype.FLOAT, componentsPerAttribute : componentsPerAttribute, values : lowValues }); delete geometry.attributes[attributeName]; return geometry; }; var scratchCartesian3 = new Cartesian3(); function transformPoint(matrix, attribute) { if (defined(attribute)) { var values = attribute.values; var length = values.length; for (var i = 0; i < length; i += 3) { Cartesian3.unpack(values, i, scratchCartesian3); Matrix4.multiplyByPoint(matrix, scratchCartesian3, scratchCartesian3); Cartesian3.pack(scratchCartesian3, values, i); } } } function transformVector(matrix, attribute) { if (defined(attribute)) { var values = attribute.values; var length = values.length; for (var i = 0; i < length; i += 3) { Cartesian3.unpack(values, i, scratchCartesian3); Matrix3.multiplyByVector(matrix, scratchCartesian3, scratchCartesian3); scratchCartesian3 = Cartesian3.normalize(scratchCartesian3, scratchCartesian3); Cartesian3.pack(scratchCartesian3, values, i); } } } var inverseTranspose = new Matrix4(); var normalMatrix = new Matrix3(); /** * Transforms a geometry instance to world coordinates. This is used as a prerequisite * to batch together several instances with {@link GeometryPipeline.combine}. This changes * the instance's <code>modelMatrix</code> to {@link Matrix4.IDENTITY} and transforms the * following attributes if they are present: <code>position</code>, <code>normal</code>, * <code>binormal</code>, and <code>tangent</code>. * * @param {GeometryInstance} instance The geometry instance to modify. * @returns {GeometryInstance} The modified <code>instance</code> argument, with its attributes transforms to world coordinates. * * @see GeometryPipeline.combine * * @example * for (var i = 0; i < instances.length; ++i) { * Cesium.GeometryPipeline.transformToWorldCoordinates(instances[i]); * } * var geometry = Cesium.GeometryPipeline.combine(instances); */ GeometryPipeline.transformToWorldCoordinates = function(instance) { //>>includeStart('debug', pragmas.debug); if (!defined(instance)) { throw new DeveloperError('instance is required.'); } //>>includeEnd('debug'); var modelMatrix = instance.modelMatrix; if (Matrix4.equals(modelMatrix, Matrix4.IDENTITY)) { // Already in world coordinates return instance; } var attributes = instance.geometry.attributes; // Transform attributes in known vertex formats transformPoint(modelMatrix, attributes.position); transformPoint(modelMatrix, attributes.prevPosition); transformPoint(modelMatrix, attributes.nextPosition); if ((defined(attributes.normal)) || (defined(attributes.binormal)) || (defined(attributes.tangent))) { Matrix4.inverse(modelMatrix, inverseTranspose); Matrix4.transpose(inverseTranspose, inverseTranspose); Matrix4.getRotation(inverseTranspose, normalMatrix); transformVector(normalMatrix, attributes.normal); transformVector(normalMatrix, attributes.binormal); transformVector(normalMatrix, attributes.tangent); } var boundingSphere = instance.geometry.boundingSphere; if (defined(boundingSphere)) { instance.geometry.boundingSphere = BoundingSphere.transform(boundingSphere, modelMatrix, boundingSphere); } instance.modelMatrix = Matrix4.clone(Matrix4.IDENTITY); return instance; }; function findAttributesInAllGeometries(instances) { var length = instances.length; var attributesInAllGeometries = {}; var attributes0 = instances[0].geometry.attributes; var name; for (name in attributes0) { if (attributes0.hasOwnProperty(name) && defined(attributes0[name]) && defined(attributes0[name].values)) { var attribute = attributes0[name]; var numberOfComponents = attribute.values.length; var inAllGeometries = true; // Does this same attribute exist in all geometries? for (var i = 1; i < length; ++i) { var otherAttribute = instances[i].geometry.attributes[name]; if ((!defined(otherAttribute)) || (attribute.componentDatatype !== otherAttribute.componentDatatype) || (attribute.componentsPerAttribute !== otherAttribute.componentsPerAttribute) || (attribute.normalize !== otherAttribute.normalize)) { inAllGeometries = false; break; } numberOfComponents += otherAttribute.values.length; } if (inAllGeometries) { attributesInAllGeometries[name] = new GeometryAttribute({ componentDatatype : attribute.componentDatatype, componentsPerAttribute : attribute.componentsPerAttribute, normalize : attribute.normalize, values : ComponentDatatype.createTypedArray(attribute.componentDatatype, numberOfComponents) }); } } } return attributesInAllGeometries; } var tempScratch = new Cartesian3(); /** * Combines geometry from several {@link GeometryInstance} objects into one geometry. * This concatenates the attributes, concatenates and adjusts the indices, and creates * a bounding sphere encompassing all instances. * <p> * If the instances do not have the same attributes, a subset of attributes common * to all instances is used, and the others are ignored. * </p> * <p> * This is used by {@link Primitive} to efficiently render a large amount of static data. * </p> * * @param {GeometryInstance[]} [instances] The array of {@link GeometryInstance} objects whose geometry will be combined. * @returns {Geometry} A single geometry created from the provided geometry instances. * * @exception {DeveloperError} All instances must have the same modelMatrix. * @exception {DeveloperError} All instance geometries must have an indices or not have one. * @exception {DeveloperError} All instance geometries must have the same primitiveType. * * @see GeometryPipeline.transformToWorldCoordinates * * @example * for (var i = 0; i < instances.length; ++i) { * Cesium.GeometryPipeline.transformToWorldCoordinates(instances[i]); * } * var geometry = Cesium.GeometryPipeline.combine(instances); */ GeometryPipeline.combine = function(instances) { //>>includeStart('debug', pragmas.debug); if ((!defined(instances)) || (instances.length < 1)) { throw new DeveloperError('instances is required and must have length greater than zero.'); } //>>includeEnd('debug'); var length = instances.length; var name; var i; var j; var k; var m = instances[0].modelMatrix; var haveIndices = (defined(instances[0].geometry.indices)); var primitiveType = instances[0].geometry.primitiveType; //>>includeStart('debug', pragmas.debug); for (i = 1; i < length; ++i) { if (!Matrix4.equals(instances[i].modelMatrix, m)) { throw new DeveloperError('All instances must have the same modelMatrix.'); } if ((defined(instances[i].geometry.indices)) !== haveIndices) { throw new DeveloperError('All instance geometries must have an indices or not have one.'); } if (instances[i].geometry.primitiveType !== primitiveType) { throw new DeveloperError('All instance geometries must have the same primitiveType.'); } } //>>includeEnd('debug'); // Find subset of attributes in all geometries var attributes = findAttributesInAllGeometries(instances); var values; var sourceValues; var sourceValuesLength; // Combine attributes from each geometry into a single typed array for (name in attributes) { if (attributes.hasOwnProperty(name)) { values = attributes[name].values; k = 0; for (i = 0; i < length; ++i) { sourceValues = instances[i].geometry.attributes[name].values; sourceValuesLength = sourceValues.length; for (j = 0; j < sourceValuesLength; ++j) { values[k++] = sourceValues[j]; } } } } // Combine index lists var indices; if (haveIndices) { var numberOfIndices = 0; for (i = 0; i < length; ++i) { numberOfIndices += instances[i].geometry.indices.length; } var numberOfVertices = Geometry.computeNumberOfVertices(new Geometry({ attributes : attributes, primitiveType : PrimitiveType.POINTS })); var destIndices = IndexDatatype.createTypedArray(numberOfVertices, numberOfIndices); var destOffset = 0; var offset = 0; for (i = 0; i < length; ++i) { var sourceIndices = instances[i].geometry.indices; var sourceIndicesLen = sourceIndices.length; for (k = 0; k < sourceIndicesLen; ++k) { destIndices[destOffset++] = offset + sourceIndices[k]; } offset += Geometry.computeNumberOfVertices(instances[i].geometry); } indices = destIndices; } // Create bounding sphere that includes all instances var center = new Cartesian3(); var radius = 0.0; var bs; for (i = 0; i < length; ++i) { bs = instances[i].geometry.boundingSphere; if (!defined(bs)) { // If any geometries have an undefined bounding sphere, then so does the combined geometry center = undefined; break; } Cartesian3.add(bs.center, center, center); } if (defined(center)) { Cartesian3.divideByScalar(center, length, center); for (i = 0; i < length; ++i) { bs = instances[i].geometry.boundingSphere; var tempRadius = Cartesian3.magnitude(Cartesian3.subtract(bs.center, center, tempScratch)) + bs.radius; if (tempRadius > radius) { radius = tempRadius; } } } return new Geometry({ attributes : attributes, indices : indices, primitiveType : primitiveType, boundingSphere : (defined(center)) ? new BoundingSphere(center, radius) : undefined }); }; var normal = new Cartesian3(); var v0 = new Cartesian3(); var v1 = new Cartesian3(); var v2 = new Cartesian3(); /** * Computes per-vertex normals for a geometry containing <code>TRIANGLES</code> by averaging the normals of * all triangles incident to the vertex. The result is a new <code>normal</code> attribute added to the geometry. * This assumes a counter-clockwise winding order. * * @param {Geometry} geometry The geometry to modify. * @returns {Geometry} The modified <code>geometry</code> argument with the computed <code>normal</code> attribute. * * @exception {DeveloperError} geometry.indices length must be greater than 0 and be a multiple of 3. * @exception {DeveloperError} geometry.primitiveType must be {@link PrimitiveType.TRIANGLES}. * * @example * Cesium.GeometryPipeline.computeNormal(geometry); */ GeometryPipeline.computeNormal = function(geometry) { //>>includeStart('debug', pragmas.debug); if (!defined(geometry)) { throw new DeveloperError('geometry is required.'); } if (!defined(geometry.attributes.position) || !defined(geometry.attributes.position.values)) { throw new DeveloperError('geometry.attributes.position.values is required.'); } if (!defined(geometry.indices)) { throw new DeveloperError('geometry.indices is required.'); } if (geometry.indices.length < 2 || geometry.indices.length % 3 !== 0) { throw new DeveloperError('geometry.indices length must be greater than 0 and be a multiple of 3.'); } if (geometry.primitiveType !== PrimitiveType.TRIANGLES) { throw new DeveloperError('geometry.primitiveType must be PrimitiveType.TRIANGLES.'); } //>>includeEnd('debug'); var indices = geometry.indices; var attributes = geometry.attributes; var vertices = attributes.position.values; var numVertices = attributes.position.values.length / 3; var numIndices = indices.length; var normalsPerVertex = new Array(numVertices); var normalsPerTriangle = new Array(numIndices / 3); var normalIndices = new Array(numIndices); for ( var i = 0; i < numVertices; i++) { normalsPerVertex[i] = { indexOffset : 0, count : 0, currentCount : 0 }; } var j = 0; for (i = 0; i < numIndices; i += 3) { var i0 = indices[i]; var i1 = indices[i + 1]; var i2 = indices[i + 2]; var i03 = i0 * 3; var i13 = i1 * 3; var i23 = i2 * 3; v0.x = vertices[i03]; v0.y = vertices[i03 + 1]; v0.z = vertices[i03 + 2]; v1.x = vertices[i13]; v1.y = vertices[i13 + 1]; v1.z = vertices[i13 + 2]; v2.x = vertices[i23]; v2.y = vertices[i23 + 1]; v2.z = vertices[i23 + 2]; normalsPerVertex[i0].count++; normalsPerVertex[i1].count++; normalsPerVertex[i2].count++; Cartesian3.subtract(v1, v0, v1); Cartesian3.subtract(v2, v0, v2); normalsPerTriangle[j] = Cartesian3.cross(v1, v2, new Cartesian3()); j++; } var indexOffset = 0; for (i = 0; i < numVertices; i++) { normalsPerVertex[i].indexOffset += indexOffset; indexOffset += normalsPerVertex[i].count; } j = 0; var vertexNormalData; for (i = 0; i < numIndices; i += 3) { vertexNormalData = normalsPerVertex[indices[i]]; var index = vertexNormalData.indexOffset + vertexNormalData.currentCount; normalIndices[index] = j; vertexNormalData.currentCount++; vertexNormalData = normalsPerVertex[indices[i + 1]]; index = vertexNormalData.indexOffset + vertexNormalData.currentCount; normalIndices[index] = j; vertexNormalData.currentCount++; vertexNormalData = normalsPerVertex[indices[i + 2]]; index = vertexNormalData.indexOffset + vertexNormalData.currentCount; normalIndices[index] = j; vertexNormalData.currentCount++; j++; } var normalValues = new Float32Array(numVertices * 3); for (i = 0; i < numVertices; i++) { var i3 = i * 3; vertexNormalData = normalsPerVertex[i]; if (vertexNormalData.count > 0) { Cartesian3.clone(Cartesian3.ZERO, normal); for (j = 0; j < vertexNormalData.count; j++) { Cartesian3.add(normal, normalsPerTriangle[normalIndices[vertexNormalData.indexOffset + j]], normal); } Cartesian3.normalize(normal, normal); normalValues[i3] = normal.x; normalValues[i3 + 1] = normal.y; normalValues[i3 + 2] = normal.z; } else { normalValues[i3] = 0.0; normalValues[i3 + 1] = 0.0; normalValues[i3 + 2] = 1.0; } } geometry.attributes.normal = new GeometryAttribute({ componentDatatype : ComponentDatatype.FLOAT, componentsPerAttribute : 3, values : normalValues }); return geometry; }; var normalScratch = new Cartesian3(); var normalScale = new Cartesian3(); var tScratch = new Cartesian3(); /** * Computes per-vertex binormals and tangents for a geometry containing <code>TRIANGLES</code>. * The result is new <code>binormal</code> and <code>tangent</code> attributes added to the geometry. * This assumes a counter-clockwise winding order. * <p> * Based on <a href="http://www.terathon.com/code/tangent.html">Computing Tangent Space Basis Vectors * for an Arbitrary Mesh</a> by Eric Lengyel. * </p> * * @param {Geometry} geometry The geometry to modify. * @returns {Geometry} The modified <code>geometry</code> argument with the computed <code>binormal</code> and <code>tangent</code> attributes. * * @exception {DeveloperError} geometry.indices length must be greater than 0 and be a multiple of 3. * @exception {DeveloperError} geometry.primitiveType must be {@link PrimitiveType.TRIANGLES}. * * @example * Cesium.GeometryPipeline.computeBinormalAndTangent(geometry); */ GeometryPipeline.computeBinormalAndTangent = function(geometry) { //>>includeStart('debug', pragmas.debug); if (!defined(geometry)) { throw new DeveloperError('geometry is required.'); } //>>includeEnd('debug'); var attributes = geometry.attributes; var indices = geometry.indices; //>>includeStart('debug', pragmas.debug); if (!defined(attributes.position) || !defined(attributes.position.values)) { throw new DeveloperError('geometry.attributes.position.values is required.'); } if (!defined(attributes.normal) || !defined(attributes.normal.values)) { throw new DeveloperError('geometry.attributes.normal.values is required.'); } if (!defined(attributes.st) || !defined(attributes.st.values)) { throw new DeveloperError('geometry.attributes.st.values is required.'); } if (!defined(indices)) { throw new DeveloperError('geometry.indices is required.'); } if (indices.length < 2 || indices.length % 3 !== 0) { throw new DeveloperError('geometry.indices length must be greater than 0 and be a multiple of 3.'); } if (geometry.primitiveType !== PrimitiveType.TRIANGLES) { throw new DeveloperError('geometry.primitiveType must be PrimitiveType.TRIANGLES.'); } //>>includeEnd('debug'); var vertices = geometry.attributes.position.values; var normals = geometry.attributes.normal.values; var st = geometry.attributes.st.values; var numVertices = geometry.attributes.position.values.length / 3; var numIndices = indices.length; var tan1 = new Array(numVertices * 3); for ( var i = 0; i < tan1.length; i++) { tan1[i] = 0; } var i03; var i13; var i23; for (i = 0; i < numIndices; i += 3) { var i0 = indices[i]; var i1 = indices[i + 1]; var i2 = indices[i + 2]; i03 = i0 * 3; i13 = i1 * 3; i23 = i2 * 3; var i02 = i0 * 2; var i12 = i1 * 2; var i22 = i2 * 2; var ux = vertices[i03]; var uy = vertices[i03 + 1]; var uz = vertices[i03 + 2]; var wx = st[i02]; var wy = st[i02 + 1]; var t1 = st[i12 + 1] - wy; var t2 = st[i22 + 1] - wy; var r = 1.0 / ((st[i12] - wx) * t2 - (st[i22] - wx) * t1); var sdirx = (t2 * (vertices[i13] - ux) - t1 * (vertices[i23] - ux)) * r; var sdiry = (t2 * (vertices[i13 + 1] - uy) - t1 * (vertices[i23 + 1] - uy)) * r; var sdirz = (t2 * (vertices[i13 + 2] - uz) - t1 * (vertices[i23 + 2] - uz)) * r; tan1[i03] += sdirx; tan1[i03 + 1] += sdiry; tan1[i03 + 2] += sdirz; tan1[i13] += sdirx; tan1[i13 + 1] += sdiry; tan1[i13 + 2] += sdirz; tan1[i23] += sdirx; tan1[i23 + 1] += sdiry; tan1[i23 + 2] += sdirz; } var binormalValues = new Float32Array(numVertices * 3); var tangentValues = new Float32Array(numVertices * 3); for (i = 0; i < numVertices; i++) { i03 = i * 3; i13 = i03 + 1; i23 = i03 + 2; var n = Cartesian3.fromArray(normals, i03, normalScratch); var t = Cartesian3.fromArray(tan1, i03, tScratch); var scalar = Cartesian3.dot(n, t); Cartesian3.multiplyBy(scalar: n, scalar, normalScale); Cartesian3.normalize(Cartesian3.subtract(t, normalScale, t), t); tangentValues[i03] = t.x; tangentValues[i13] = t.y; tangentValues[i23] = t.z; Cartesian3.normalize(Cartesian3.cross(n, t, t), t); binormalValues[i03] = t.x; binormalValues[i13] = t.y; binormalValues[i23] = t.z; } geometry.attributes.tangent = new GeometryAttribute({ componentDatatype : ComponentDatatype.FLOAT, componentsPerAttribute : 3, values : tangentValues }); geometry.attributes.binormal = new GeometryAttribute({ componentDatatype : ComponentDatatype.FLOAT, componentsPerAttribute : 3, values : binormalValues }); return geometry; }; function indexTriangles(geometry) { if (defined(geometry.indices)) { return geometry; } var numberOfVertices = Geometry.computeNumberOfVertices(geometry); //>>includeStart('debug', pragmas.debug); if (numberOfVertices < 3) { throw new DeveloperError('The number of vertices must be at least three.'); } if (numberOfVertices % 3 !== 0) { throw new DeveloperError('The number of vertices must be a multiple of three.'); } //>>includeEnd('debug'); var indices = IndexDatatype.createTypedArray(numberOfVertices, numberOfVertices); for (var i = 0; i < numberOfVertices; ++i) { indices[i] = i; } geometry.indices = indices; return geometry; } function indexTriangleFan(geometry) { var numberOfVertices = Geometry.computeNumberOfVertices(geometry); //>>includeStart('debug', pragmas.debug); if (numberOfVertices < 3) { throw new DeveloperError('The number of vertices must be at least three.'); } //>>includeEnd('debug'); var indices = IndexDatatype.createTypedArray(numberOfVertices, (numberOfVertices - 2) * 3); indices[0] = 1; indices[1] = 0; indices[2] = 2; var indicesIndex = 3; for (var i = 3; i < numberOfVertices; ++i) { indices[indicesIndex++] = i - 1; indices[indicesIndex++] = 0; indices[indicesIndex++] = i; } geometry.indices = indices; geometry.primitiveType = PrimitiveType.TRIANGLES; return geometry; } function indexTriangleStrip(geometry) { var numberOfVertices = Geometry.computeNumberOfVertices(geometry); //>>includeStart('debug', pragmas.debug); if (numberOfVertices < 3) { throw new DeveloperError('The number of vertices must be at least 3.'); } //>>includeEnd('debug'); var indices = IndexDatatype.createTypedArray(numberOfVertices, (numberOfVertices - 2) * 3); indices[0] = 0; indices[1] = 1; indices[2] = 2; if (numberOfVertices > 3) { indices[3] = 0; indices[4] = 2; indices[5] = 3; } var indicesIndex = 6; for (var i = 3; i < numberOfVertices - 1; i += 2) { indices[indicesIndex++] = i; indices[indicesIndex++] = i - 1; indices[indicesIndex++] = i + 1; if (i + 2 < numberOfVertices) { indices[indicesIndex++] = i; indices[indicesIndex++] = i + 1; indices[indicesIndex++] = i + 2; } } geometry.indices = indices; geometry.primitiveType = PrimitiveType.TRIANGLES; return geometry; } function indexLines(geometry) { if (defined(geometry.indices)) { return geometry; } var numberOfVertices = Geometry.computeNumberOfVertices(geometry); //>>includeStart('debug', pragmas.debug); if (numberOfVertices < 2) { throw new DeveloperError('The number of vertices must be at least two.'); } if (numberOfVertices % 2 !== 0) { throw new DeveloperError('The number of vertices must be a multiple of 2.'); } //>>includeEnd('debug'); var indices = IndexDatatype.createTypedArray(numberOfVertices, numberOfVertices); for (var i = 0; i < numberOfVertices; ++i) { indices[i] = i; } geometry.indices = indices; return geometry; } function indexLineStrip(geometry) { var numberOfVertices = Geometry.computeNumberOfVertices(geometry); //>>includeStart('debug', pragmas.debug); if (numberOfVertices < 2) { throw new DeveloperError('The number of vertices must be at least two.'); } //>>includeEnd('debug'); var indices = IndexDatatype.createTypedArray(numberOfVertices, (numberOfVertices - 1) * 2); indices[0] = 0; indices[1] = 1; var indicesIndex = 2; for (var i = 2; i < numberOfVertices; ++i) { indices[indicesIndex++] = i - 1; indices[indicesIndex++] = i; } geometry.indices = indices; geometry.primitiveType = PrimitiveType.LINES; return geometry; } function indexLineLoop(geometry) { var numberOfVertices = Geometry.computeNumberOfVertices(geometry); //>>includeStart('debug', pragmas.debug); if (numberOfVertices < 2) { throw new DeveloperError('The number of vertices must be at least two.'); } //>>includeEnd('debug'); var indices = IndexDatatype.createTypedArray(numberOfVertices, numberOfVertices * 2); indices[0] = 0; indices[1] = 1; var indicesIndex = 2; for (var i = 2; i < numberOfVertices; ++i) { indices[indicesIndex++] = i - 1; indices[indicesIndex++] = i; } indices[indicesIndex++] = numberOfVertices - 1; indices[indicesIndex] = 0; geometry.indices = indices; geometry.primitiveType = PrimitiveType.LINES; return geometry; } function indexPrimitive(geometry) { switch (geometry.primitiveType) { case PrimitiveType.TRIANGLE_FAN: return indexTriangleFan(geometry); case PrimitiveType.TRIANGLE_STRIP: return indexTriangleStrip(geometry); case PrimitiveType.TRIANGLES: return indexTriangles(geometry); case PrimitiveType.LINE_STRIP: return indexLineStrip(geometry); case PrimitiveType.LINE_LOOP: return indexLineLoop(geometry); case PrimitiveType.LINES: return indexLines(geometry); } return geometry; } function offsetPointFromXZPlane(p, isBehind) { if (Math.abs(p.y) < CesiumMath.EPSILON11){ if (isBehind) { p.y = -CesiumMath.EPSILON11; } else { p.y = CesiumMath.EPSILON11; } } } var c3 = new Cartesian3(); function getXZIntersectionOffsetPoints(p, p1, u1, v1) { Cartesian3.add(p, Cartesian3.multiplyBy(scalar: Cartesian3.subtract(p1, p, c3), p.y/(p.y-p1.y), c3), u1); Cartesian3.clone(u1, v1); offsetPointFromXZPlane(u1, true); offsetPointFromXZPlane(v1, false); } var u1 = new Cartesian3(); var u2 = new Cartesian3(); var q1 = new Cartesian3(); var q2 = new Cartesian3(); var splitTriangleResult = { positions : new Array(7), indices : new Array(3 * 3) }; function splitTriangle(p0, p1, p2) { // In WGS84 coordinates, for a triangle approximately on the // ellipsoid to cross the IDL, first it needs to be on the // negative side of the plane x = 0. if ((p0.x >= 0.0) || (p1.x >= 0.0) || (p2.x >= 0.0)) { return undefined; } var p0Behind = p0.y < 0.0; var p1Behind = p1.y < 0.0; var p2Behind = p2.y < 0.0; offsetPointFromXZPlane(p0, p0Behind); offsetPointFromXZPlane(p1, p1Behind); offsetPointFromXZPlane(p2, p2Behind); var numBehind = 0; numBehind += p0Behind ? 1 : 0; numBehind += p1Behind ? 1 : 0; numBehind += p2Behind ? 1 : 0; var indices = splitTriangleResult.indices; if (numBehind === 1) { indices[1] = 3; indices[2] = 4; indices[5] = 6; indices[7] = 6; indices[8] = 5; if (p0Behind) { getXZIntersectionOffsetPoints(p0, p1, u1, q1); getXZIntersectionOffsetPoints(p0, p2, u2, q2); indices[0] = 0; indices[3] = 1; indices[4] = 2; indices[6] = 1; } else if (p1Behind) { getXZIntersectionOffsetPoints(p1, p2, u1, q1); getXZIntersectionOffsetPoints(p1, p0, u2, q2); indices[0] = 1; indices[3] = 2; indices[4] = 0; indices[6] = 2; } else if (p2Behind) { getXZIntersectionOffsetPoints(p2, p0, u1, q1); getXZIntersectionOffsetPoints(p2, p1, u2, q2); indices[0] = 2; indices[3] = 0; indices[4] = 1; indices[6] = 0; } } else if (numBehind === 2) { indices[2] = 4; indices[4] = 4; indices[5] = 3; indices[7] = 5; indices[8] = 6; if (!p0Behind) { getXZIntersectionOffsetPoints(p0, p1, u1, q1); getXZIntersectionOffsetPoints(p0, p2, u2, q2); indices[0] = 1; indices[1] = 2; indices[3] = 1; indices[6] = 0; } else if (!p1Behind) { getXZIntersectionOffsetPoints(p1, p2, u1, q1); getXZIntersectionOffsetPoints(p1, p0, u2, q2); indices[0] = 2; indices[1] = 0; indices[3] = 2; indices[6] = 1; } else if (!p2Behind) { getXZIntersectionOffsetPoints(p2, p0, u1, q1); getXZIntersectionOffsetPoints(p2, p1, u2, q2); indices[0] = 0; indices[1] = 1; indices[3] = 0; indices[6] = 2; } } var positions = splitTriangleResult.positions; positions[0] = p0; positions[1] = p1; positions[2] = p2; splitTriangleResult.length = 3; if (numBehind === 1 || numBehind === 2) { positions[3] = u1; positions[4] = u2; positions[5] = q1; positions[6] = q2; splitTriangleResult.length = 7; } return splitTriangleResult; } var u0Scratch = new Cartesian2(); var u1Scratch = new Cartesian2(); var u2Scratch = new Cartesian2(); var v0Scratch = new Cartesian3(); var v1Scratch = new Cartesian3(); var v2Scratch = new Cartesian3(); var computeScratch = new Cartesian3(); function computeTriangleAttributes(i0, i1, i2, dividedTriangle, normals, binormals, tangents, texCoords) { if (!defined(normals) && !defined(binormals) && !defined(tangents) && !defined(texCoords)) { return; } var positions = dividedTriangle.positions; var p0 = positions[0]; var p1 = positions[1]; var p2 = positions[2]; var n0, n1, n2; var b0, b1, b2; var t0, t1, t2; var s0, s1, s2; var v0 = v0Scratch; var v1 = v1Scratch; var v2 = v2Scratch; var u0 = u0Scratch; var u1 = u1Scratch; var u2 = u2Scratch; if (defined(normals)) { n0 = Cartesian3.fromArray(normals, i0 * 3); n1 = Cartesian3.fromArray(normals, i1 * 3); n2 = Cartesian3.fromArray(normals, i2 * 3); } if (defined(binormals)) { b0 = Cartesian3.fromArray(binormals, i0 * 3); b1 = Cartesian3.fromArray(binormals, i1 * 3); b2 = Cartesian3.fromArray(binormals, i2 * 3); } if (defined(tangents)) { t0 = Cartesian3.fromArray(tangents, i0 * 3); t1 = Cartesian3.fromArray(tangents, i1 * 3); t2 = Cartesian3.fromArray(tangents, i2 * 3); } if (defined(texCoords)) { s0 = Cartesian2.fromArray(texCoords, i0 * 2); s1 = Cartesian2.fromArray(texCoords, i1 * 2); s2 = Cartesian2.fromArray(texCoords, i2 * 2); } for (var i = 3; i < positions.length; ++i) { var point = positions[i]; var coords = barycentricCoordinates(point, p0, p1, p2); if (defined(normals)) { v0 = Cartesian3.multiplyBy(scalar: n0, coords.x, v0); v1 = Cartesian3.multiplyBy(scalar: n1, coords.y, v1); v2 = Cartesian3.multiplyBy(scalar: n2, coords.z, v2); var normal = Cartesian3.add(v0, v1, computeScratch); Cartesian3.add(normal, v2, normal); Cartesian3.normalize(normal, normal); normals.push(normal.x, normal.y, normal.z); } if (defined(binormals)) { v0 = Cartesian3.multiplyBy(scalar: b0, coords.x, v0); v1 = Cartesian3.multiplyBy(scalar: b1, coords.y, v1); v2 = Cartesian3.multiplyBy(scalar: b2, coords.z, v2); var binormal = Cartesian3.add(v0, v1, computeScratch); Cartesian3.add(binormal, v2, binormal); Cartesian3.normalize(binormal, binormal); binormals.push(binormal.x, binormal.y, binormal.z); } if (defined(tangents)) { v0 = Cartesian3.multiplyBy(scalar: t0, coords.x, v0); v1 = Cartesian3.multiplyBy(scalar: t1, coords.y, v1); v2 = Cartesian3.multiplyBy(scalar: t2, coords.z, v2); var tangent = Cartesian3.add(v0, v1, computeScratch); Cartesian3.add(tangent, v2, tangent); Cartesian3.normalize(tangent, tangent); tangents.push(tangent.x, tangent.y, tangent.z); } if (defined(texCoords)) { u0 = Cartesian2.multiplyBy(scalar: s0, coords.x, u0); u1 = Cartesian2.multiplyBy(scalar: s1, coords.y, u1); u2 = Cartesian2.multiplyBy(scalar: s2, coords.z, u2); var texCoord = Cartesian2.add(u0, u1, u0); Cartesian2.add(texCoord, u2, texCoord); texCoords.push(texCoord.x, texCoord.y); } } } function wrapLongitudeTriangles(geometry) { var attributes = geometry.attributes; var positions = attributes.position.values; var normals = (defined(attributes.normal)) ? attributes.normal.values : undefined; var binormals = (defined(attributes.binormal)) ? attributes.binormal.values : undefined; var tangents = (defined(attributes.tangent)) ? attributes.tangent.values : undefined; var texCoords = (defined(attributes.st)) ? attributes.st.values : undefined; var indices = geometry.indices; var newPositions = Array.prototype.slice.call(positions, 0); var newNormals = (defined(normals)) ? Array.prototype.slice.call(normals, 0) : undefined; var newBinormals = (defined(binormals)) ? Array.prototype.slice.call(binormals, 0) : undefined; var newTangents = (defined(tangents)) ? Array.prototype.slice.call(tangents, 0) : undefined; var newTexCoords = (defined(texCoords)) ? Array.prototype.slice.call(texCoords, 0) : undefined; var newIndices = []; var len = indices.length; for (var i = 0; i < len; i += 3) { var i0 = indices[i]; var i1 = indices[i + 1]; var i2 = indices[i + 2]; var p0 = Cartesian3.fromArray(positions, i0 * 3); var p1 = Cartesian3.fromArray(positions, i1 * 3); var p2 = Cartesian3.fromArray(positions, i2 * 3); var result = splitTriangle(p0, p1, p2); if (defined(result)) { newPositions[i0 * 3 + 1] = result.positions[0].y; newPositions[i1 * 3 + 1] = result.positions[1].y; newPositions[i2 * 3 + 1] = result.positions[2].y; if (result.length > 3) { var positionsLength = newPositions.length / 3; for(var j = 0; j < result.indices.length; ++j) { var index = result.indices[j]; if (index < 3) { newIndices.push(indices[i + index]); } else { newIndices.push(index - 3 + positionsLength); } } for (var k = 3; k < result.positions.length; ++k) { var position = result.positions[k]; newPositions.push(position.x, position.y, position.z); } computeTriangleAttributes(i0, i1, i2, result, newNormals, newBinormals, newTangents, newTexCoords); } else { newIndices.push(i0, i1, i2); } } else { newIndices.push(i0, i1, i2); } } geometry.attributes.position.values = new Float64Array(newPositions); if (defined(newNormals)) { attributes.normal.values = ComponentDatatype.createTypedArray(attributes.normal.componentDatatype, newNormals); } if (defined(newBinormals)) { attributes.binormal.values = ComponentDatatype.createTypedArray(attributes.binormal.componentDatatype, newBinormals); } if (defined(newTangents)) { attributes.tangent.values = ComponentDatatype.createTypedArray(attributes.tangent.componentDatatype, newTangents); } if (defined(newTexCoords)) { attributes.st.values = ComponentDatatype.createTypedArray(attributes.st.componentDatatype, newTexCoords); } var numberOfVertices = Geometry.computeNumberOfVertices(geometry); geometry.indices = IndexDatatype.createTypedArray(numberOfVertices, newIndices); } var offsetScratch = new Cartesian3(); var offsetPointScratch = new Cartesian3(); function wrapLongitudeLines(geometry) { var attributes = geometry.attributes; var positions = attributes.position.values; var indices = geometry.indices; var newPositions = Array.prototype.slice.call(positions, 0); var newIndices = []; var xzPlane = Plane.fromPointNormal(Cartesian3.ZERO, Cartesian3.UNIT_Y); var length = indices.length; for ( var i = 0; i < length; i += 2) { var i0 = indices[i]; var i1 = indices[i + 1]; var prev = Cartesian3.fromArray(positions, i0 * 3); var cur = Cartesian3.fromArray(positions, i1 * 3); if (Math.abs(prev.y) < CesiumMath.EPSILON6){ if (prev.y < 0.0) { prev.y = -CesiumMath.EPSILON6; } else { prev.y = CesiumMath.EPSILON6; } newPositions[i0 * 3 + 1] = prev.y; } if (Math.abs(cur.y) < CesiumMath.EPSILON6){ if (cur.y < 0.0) { cur.y = -CesiumMath.EPSILON6; } else { cur.y = CesiumMath.EPSILON6; } newPositions[i1 * 3 + 1] = cur.y; } newIndices.push(i0); // intersects the IDL if either endpoint is on the negative side of the yz-plane if (prev.x < 0.0 || cur.x < 0.0) { // and intersects the xz-plane var intersection = IntersectionTests.lineSegmentPlane(prev, cur, xzPlane); if (defined(intersection)) { // move point on the xz-plane slightly away from the plane var offset = Cartesian3.multiplyBy(scalar: Cartesian3.UNIT_Y, 5.0 * CesiumMath.EPSILON9, offsetScratch); if (prev.y < 0.0) { Cartesian3.negate(offset, offset); } var index = newPositions.length / 3; newIndices.push(index, index + 1); var offsetPoint = Cartesian3.add(intersection, offset, offsetPointScratch); newPositions.push(offsetPoint.x, offsetPoint.y, offsetPoint.z); Cartesian3.negate(offset, offset); Cartesian3.add(intersection, offset, offsetPoint); newPositions.push(offsetPoint.x, offsetPoint.y, offsetPoint.z); } } newIndices.push(i1); } geometry.attributes.position.values = new Float64Array(newPositions); var numberOfVertices = Geometry.computeNumberOfVertices(geometry); geometry.indices = IndexDatatype.createTypedArray(numberOfVertices, newIndices); } /** * Splits the geometry's primitives, by introducing new vertices and indices,that * intersect the International Date Line so that no primitives cross longitude * -180/180 degrees. This is not required for 3D drawing, but is required for * correcting drawing in 2D and Columbus view. * * @param {Geometry} geometry The geometry to modify. * @returns {Geometry} The modified <code>geometry</code> argument, with it's primitives split at the International Date Line. * * @example * geometry = Cesium.GeometryPipeline.wrapLongitude(geometry); */ GeometryPipeline.wrapLongitude = function(geometry) { //>>includeStart('debug', pragmas.debug); if (!defined(geometry)) { throw new DeveloperError('geometry is required.'); } //>>includeEnd('debug'); var boundingSphere = geometry.boundingSphere; if (defined(boundingSphere)) { var minX = boundingSphere.center.x - boundingSphere.radius; if (minX > 0 || BoundingSphere.intersect(boundingSphere, Cartesian4.UNIT_Y) !== Intersect.INTERSECTING) { return geometry; } } indexPrimitive(geometry); if (geometry.primitiveType === PrimitiveType.TRIANGLES) { wrapLongitudeTriangles(geometry); } else if (geometry.primitiveType === PrimitiveType.LINES) { wrapLongitudeLines(geometry); } return geometry; }; */ }
apache-2.0
f5877924c946f291ca8b7f75e02ba9a3
37.505889
157
0.573065
4.45933
false
false
false
false
zxwWei/SWiftWeiBlog
XWWeibo/XWWeibo/Classes/Model(模型)/Home(首页)/Controller/XWHomeTableVC.swift
1
2894
// // XWHomeTableVC.swift // XWWeibo // // Created by apple on 15/10/26. // Copyright © 2015年 ZXW. All rights reserved. // import UIKit class XWHomeTableVC: XWcompassVc { override func viewDidLoad() { super.viewDidLoad() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { // #warning Incomplete implementation, return the number of sections return 0 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows return 0 } /* override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath) // Configure the cell... return cell } */ /* // Override to support conditional editing of the table view. override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } */ /* // Override to support editing the table view. override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { // Delete the row from the data source tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } else if editingStyle == .Insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } */ /* // Override to support rearranging the table view. override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the item to be re-orderable. return true } */ /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
apache-2.0
4e8e8d279916f646d9ba2fee64172211
30.086022
157
0.672086
5.403738
false
false
false
false
Magnat12/MGExtraSwift
MGExtraSwift/Classes/UITableView+MGExtra.swift
1
668
// // UITableView+MGExtra.swift // eLearning // // Created by Vitaliy Gozhenko on 26/11/16. // Copyright © 2016 Appstructors. All rights reserved. // import UIKit extension UITableView { public func relayoutTableHeaderView() { guard let tableHeaderView = tableHeaderView else { return } let labels = tableHeaderView.findViewsOfClass(viewClass: UILabel.self) for label in labels { label.preferredMaxLayoutWidth = label.width } tableHeaderView.setNeedsLayout() tableHeaderView.layoutIfNeeded() tableHeaderView.height = tableHeaderView.systemLayoutSizeFitting(UILayoutFittingCompressedSize).height self.tableHeaderView = tableHeaderView } }
mit
4bae0eab9f503de89ee0a0901ef032aa
25.68
104
0.776612
4.417219
false
false
false
false
minsOne/R.swift
R.swift/func.swift
1
8965
// // func.swift // R.swift // // Created by Mathijs Kadijk on 14-12-14. // From: https://github.com/mac-cain13/R.swift // License: MIT License // import Foundation // MARK: Helper functions let indent = indentWithString(IndentationString) func warn(warning: String) { println("warning: \(warning)") } func fail(error: String) { println("error: \(error)") } func failOnError(error: NSError?) { if let error = error { fail("\(error)") } } func inputDirectories(processInfo: NSProcessInfo) -> [NSURL] { return processInfo.arguments.skip(1).map { NSURL(fileURLWithPath: $0 as! String)! } } func filterDirectoryContentsRecursively(fileManager: NSFileManager, filter: (NSURL) -> Bool)(url: NSURL) -> [NSURL] { var assetFolders = [NSURL]() let errorHandler: (NSURL!, NSError!) -> Bool = { url, error in failOnError(error) return true } if let enumerator = fileManager.enumeratorAtURL(url, includingPropertiesForKeys: [NSURLIsDirectoryKey], options: NSDirectoryEnumerationOptions.SkipsHiddenFiles|NSDirectoryEnumerationOptions.SkipsPackageDescendants, errorHandler: errorHandler) { while let enumeratorItem: AnyObject = enumerator.nextObject() { if let url = enumeratorItem as? NSURL where filter(url) { assetFolders.append(url) } } } return assetFolders } func sanitizedSwiftName(name: String, lowercaseFirstCharacter: Bool = true) -> String { var components = name.componentsSeparatedByCharactersInSet(NSCharacterSet(charactersInString: " -")) let firstComponent = components.removeAtIndex(0) let swiftName = components.reduce(firstComponent) { $0 + $1.capitalizedString } let capitalizedSwiftName = lowercaseFirstCharacter ? swiftName.lowercaseFirstCharacter : swiftName return contains(SwiftKeywords, capitalizedSwiftName) ? "`\(capitalizedSwiftName)`" : capitalizedSwiftName } func writeResourceFile(code: String, toFolderURL folderURL: NSURL) { let outputURL = folderURL.URLByAppendingPathComponent(ResourceFilename) var error: NSError? code.writeToURL(outputURL, atomically: true, encoding: NSUTF8StringEncoding, error: &error) failOnError(error) } func readResourceFile(folderURL: NSURL) -> String? { let inputURL = folderURL.URLByAppendingPathComponent(ResourceFilename) if let resourceFileString = String(contentsOfURL: inputURL, encoding: NSUTF8StringEncoding, error: nil) { return resourceFileString } return nil } // MARK: Struct/function generators // Image func imageStructFromAssetFolders(assetFolders: [AssetFolder]) -> Struct { let vars = distinct(assetFolders.flatMap { $0.imageAssets }) .map { Var(isStatic: true, name: $0, type: Type._UIImage.asOptional(), getter: "return UIImage(named: \"\($0)\")") } return Struct(type: Type(name: "image"), lets: [], vars: vars, functions: [], structs: []) } // Segue func segueStructFromStoryboards(storyboards: [Storyboard]) -> Struct { let vars = distinct(storyboards.flatMap { $0.segues }) .map { Var(isStatic: true, name: $0, type: Type._String, getter: "return \"\($0)\"") } return Struct(type: Type(name: "segue"), lets: [], vars: vars, functions: [], structs: []) } // Storyboard func storyboardStructFromStoryboards(storyboards: [Storyboard]) -> Struct { return Struct(type: Type(name: "storyboard"), lets: [], vars: [], functions: [], structs: storyboards.map(storyboardStructForStoryboard)) } func storyboardStructForStoryboard(storyboard: Storyboard) -> Struct { let instanceVars = [Var(isStatic: true, name: "instance", type: Type._UIStoryboard, getter: "return UIStoryboard(name: \"\(storyboard.name)\", bundle: nil)")] let initialViewControllerVar = catOptionals([storyboard.initialViewController.map { Var(isStatic: true, name: "initialViewController", type: $0.type.asOptional(), getter: "return instance.instantiateInitialViewController() as? \($0.type.asNonOptional())") }]) let viewControllerVars = catOptionals(storyboard.viewControllers .map { vc in vc.storyboardIdentifier.map { return Var(isStatic: true, name: $0, type: vc.type.asOptional(), getter: "return instance.instantiateViewControllerWithIdentifier(\"\($0)\") as? \(vc.type.asNonOptional())") } }) let validateImagesLines = distinct(storyboard.usedImageIdentifiers) .map { "assert(UIImage(named: \"\($0)\") != nil, \"[R.swift] Image named '\($0)' is used in storyboard '\(storyboard.name)', but couldn't be loaded.\")" } let validateImagesFunc = Function(isStatic: true, name: "validateImages", generics: nil, parameters: [], returnType: Type._Void, body: join("\n", validateImagesLines)) let validateViewControllersLines = catOptionals(storyboard.viewControllers .map { vc in vc.storyboardIdentifier.map { "assert(\(sanitizedSwiftName($0)) != nil, \"[R.swift] ViewController with identifier '\(sanitizedSwiftName($0))' could not be loaded from storyboard '\(storyboard.name)' as '\(vc.type)'.\")" } }) let validateViewControllersFunc = Function(isStatic: true, name: "validateViewControllers", generics: nil, parameters: [], returnType: Type._Void, body: join("\n", validateViewControllersLines)) return Struct(type: Type(name: sanitizedSwiftName(storyboard.name)), lets: [], vars: instanceVars + initialViewControllerVar + viewControllerVars, functions: [validateImagesFunc, validateViewControllersFunc], structs: []) } // Nib func nibStructFromNibs(nibs: [Nib]) -> Struct { return Struct(type: Type(name: "nib"), lets: [], vars: nibs.map(nibVarForNib), functions: [], structs: []) } func internalNibStructFromNibs(nibs: [Nib]) -> Struct { return Struct(type: Type(name: "nib"), lets: [], vars: [], functions: [], structs: nibs.map(nibStructForNib)) } func nibVarForNib(nib: Nib) -> Var { let structType = Type(name: "_R.nib._\(nib.name)") return Var(isStatic: true, name: nib.name, type: structType, getter: "return \(structType)()") } func nibStructForNib(nib: Nib) -> Struct { let instantiateParameters = [ Function.Parameter(name: "ownerOrNil", type: Type._AnyObject.asOptional()), Function.Parameter(name: "options", localName: "optionsOrNil", type: Type(name: "[NSObject : AnyObject]", optional: true)) ] let instanceVar = Var( isStatic: false, name: "instance", type: Type._UINib, getter: "return UINib.init(nibName: \"\(nib.name)\", bundle: nil)" ) let instantiateFunc = Function( isStatic: false, name: "instantiateWithOwner", generics: nil, parameters: instantiateParameters, returnType: Type(name: "[AnyObject]"), body: "return instance.instantiateWithOwner(ownerOrNil, options: optionsOrNil)" ) let viewFuncs = zip(nib.rootViews, Ordinals) .map { (view: $0.0, ordinal: $0.1) } .map { Function( isStatic: false, name: "\($0.ordinal.word)View", generics: nil, parameters: instantiateParameters, returnType: $0.view.asOptional(), body: "return \(instantiateFunc.callName)(ownerOrNil, options: optionsOrNil)[\($0.ordinal.number - 1)] as? \($0.view)" ) } let reuseIdentifierVars: [Var] let reuseProtocols: [Type] if let reusable = nib.reusables.first where nib.rootViews.count == 1 && nib.reusables.count == 1 { let reusableVar = varFromReusable(reusable) reuseIdentifierVars = [Var( isStatic: false, name: "reuseIdentifier", type: reusableVar.type, getter: reusableVar.getter )] reuseProtocols = [ReusableProtocol.type] } else { reuseIdentifierVars = [] reuseProtocols = [] } let sanitizedName = sanitizedSwiftName(nib.name, lowercaseFirstCharacter: false) return Struct( type: Type(name: "_\(sanitizedName)"), implements: [NibResourceProtocol.type] + reuseProtocols, lets: [], vars: [instanceVar] + reuseIdentifierVars, functions: [instantiateFunc] + viewFuncs, structs: [] ) } // Reuse identifiers func reuseIdentifierStructFromReusables(reusables: [Reusable]) -> Struct { let reuseIdentifierVars = reusables.map(varFromReusable) return Struct(type: Type(name: "reuseIdentifier"), lets: [], vars: reuseIdentifierVars, functions: [], structs: []) } func varFromReusable(reusable: Reusable) -> Var { return Var( isStatic: true, name: reusable.identifier, type: ReuseIdentifier.type.withGenericType(reusable.type), getter: "return \(ReuseIdentifier.type.name)(identifier: \"\(reusable.identifier)\")" ) } // Validation func validateAllFunctionWithStoryboards(storyboards: [Storyboard]) -> Function { return Function(isStatic: true, name: "validate", generics: nil, parameters: [], returnType: Type._Void, body: join("\n", storyboards.map(swiftCallStoryboardValidators))) } func swiftCallStoryboardValidators(storyboard: Storyboard) -> String { return "storyboard.\(sanitizedSwiftName(storyboard.name)).validateImages()\n" + "storyboard.\(sanitizedSwiftName(storyboard.name)).validateViewControllers()" }
mit
bf4b283115b379299e60b29a70235b4f
35.741803
246
0.708087
4.101098
false
false
false
false
yuxiuyu/TrendBet
TrendBetting_0531换首页/Pods/Charts/Source/Charts/Renderers/XAxisRendererHorizontalBarChart.swift
4
12756
// // XAxisRendererHorizontalBarChart.swift // Charts // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/Charts // import Foundation import CoreGraphics #if !os(OSX) import UIKit #endif open class XAxisRendererHorizontalBarChart: XAxisRenderer { internal weak var chart: BarChartView? @objc public init(viewPortHandler: ViewPortHandler, xAxis: XAxis?, transformer: Transformer?, chart: BarChartView) { super.init(viewPortHandler: viewPortHandler, xAxis: xAxis, transformer: transformer) self.chart = chart } open override func computeAxis(min: Double, max: Double, inverted: Bool) { var min = min, max = max if let transformer = self.transformer { // calculate the starting and entry point of the y-labels (depending on // zoom / contentrect bounds) if viewPortHandler.contentWidth > 10 && !viewPortHandler.isFullyZoomedOutY { let p1 = transformer.valueForTouchPoint(CGPoint(x: viewPortHandler.contentLeft, y: viewPortHandler.contentBottom)) let p2 = transformer.valueForTouchPoint(CGPoint(x: viewPortHandler.contentLeft, y: viewPortHandler.contentTop)) if inverted { min = Double(p2.y) max = Double(p1.y) } else { min = Double(p1.y) max = Double(p2.y) } } } computeAxisValues(min: min, max: max) } open override func computeSize() { guard let xAxis = self.axis as? XAxis else { return } let longest = xAxis.getLongestLabel() as NSString let labelSize = longest.size(withAttributes: [NSAttributedStringKey.font: xAxis.labelFont]) let labelWidth = floor(labelSize.width + xAxis.xOffset * 3.5) let labelHeight = labelSize.height let labelRotatedSize = CGSize(width: labelSize.width, height: labelHeight).rotatedBy(degrees: xAxis.labelRotationAngle) xAxis.labelWidth = labelWidth xAxis.labelHeight = labelHeight xAxis.labelRotatedWidth = round(labelRotatedSize.width + xAxis.xOffset * 3.5) xAxis.labelRotatedHeight = round(labelRotatedSize.height) } open override func renderAxisLabels(context: CGContext) { guard let xAxis = self.axis as? XAxis else { return } if !xAxis.isEnabled || !xAxis.isDrawLabelsEnabled || chart?.data === nil { return } let xoffset = xAxis.xOffset if xAxis.labelPosition == .top { drawLabels(context: context, pos: viewPortHandler.contentRight + xoffset, anchor: CGPoint(x: 0.0, y: 0.5)) } else if xAxis.labelPosition == .topInside { drawLabels(context: context, pos: viewPortHandler.contentRight - xoffset, anchor: CGPoint(x: 1.0, y: 0.5)) } else if xAxis.labelPosition == .bottom { drawLabels(context: context, pos: viewPortHandler.contentLeft - xoffset, anchor: CGPoint(x: 1.0, y: 0.5)) } else if xAxis.labelPosition == .bottomInside { drawLabels(context: context, pos: viewPortHandler.contentLeft + xoffset, anchor: CGPoint(x: 0.0, y: 0.5)) } else { // BOTH SIDED drawLabels(context: context, pos: viewPortHandler.contentRight + xoffset, anchor: CGPoint(x: 0.0, y: 0.5)) drawLabels(context: context, pos: viewPortHandler.contentLeft - xoffset, anchor: CGPoint(x: 1.0, y: 0.5)) } } /// draws the x-labels on the specified y-position open override func drawLabels(context: CGContext, pos: CGFloat, anchor: CGPoint) { guard let xAxis = self.axis as? XAxis, let transformer = self.transformer else { return } let labelFont = xAxis.labelFont let labelTextColor = xAxis.labelTextColor let labelRotationAngleRadians = xAxis.labelRotationAngle.DEG2RAD let centeringEnabled = xAxis.isCenterAxisLabelsEnabled // pre allocate to save performance (dont allocate in loop) var position = CGPoint(x: 0.0, y: 0.0) for i in stride(from: 0, to: xAxis.entryCount, by: 1) { // only fill x values position.x = 0.0 if centeringEnabled { position.y = CGFloat(xAxis.centeredEntries[i]) } else { position.y = CGFloat(xAxis.entries[i]) } transformer.pointValueToPixel(&position) if viewPortHandler.isInBoundsY(position.y) { if let label = xAxis.valueFormatter?.stringForValue(xAxis.entries[i], axis: xAxis) { drawLabel( context: context, formattedLabel: label, x: pos, y: position.y, attributes: [NSAttributedStringKey.font: labelFont, NSAttributedStringKey.foregroundColor: labelTextColor], anchor: anchor, angleRadians: labelRotationAngleRadians) } } } } @objc open func drawLabel( context: CGContext, formattedLabel: String, x: CGFloat, y: CGFloat, attributes: [NSAttributedStringKey : Any], anchor: CGPoint, angleRadians: CGFloat) { ChartUtils.drawText( context: context, text: formattedLabel, point: CGPoint(x: x, y: y), attributes: attributes, anchor: anchor, angleRadians: angleRadians) } open override var gridClippingRect: CGRect { var contentRect = viewPortHandler.contentRect let dy = self.axis?.gridLineWidth ?? 0.0 contentRect.origin.y -= dy / 2.0 contentRect.size.height += dy return contentRect } private var _gridLineSegmentsBuffer = [CGPoint](repeating: CGPoint(), count: 2) open override func drawGridLine(context: CGContext, x: CGFloat, y: CGFloat) { if viewPortHandler.isInBoundsY(y) { context.beginPath() context.move(to: CGPoint(x: viewPortHandler.contentLeft, y: y)) context.addLine(to: CGPoint(x: viewPortHandler.contentRight, y: y)) context.strokePath() } } open override func renderAxisLine(context: CGContext) { guard let xAxis = self.axis as? XAxis else { return } if !xAxis.isEnabled || !xAxis.isDrawAxisLineEnabled { return } context.saveGState() context.setStrokeColor(xAxis.axisLineColor.cgColor) context.setLineWidth(xAxis.axisLineWidth) if xAxis.axisLineDashLengths != nil { context.setLineDash(phase: xAxis.axisLineDashPhase, lengths: xAxis.axisLineDashLengths) } else { context.setLineDash(phase: 0.0, lengths: []) } if xAxis.labelPosition == .top || xAxis.labelPosition == .topInside || xAxis.labelPosition == .bothSided { context.beginPath() context.move(to: CGPoint(x: viewPortHandler.contentRight, y: viewPortHandler.contentTop)) context.addLine(to: CGPoint(x: viewPortHandler.contentRight, y: viewPortHandler.contentBottom)) context.strokePath() } if xAxis.labelPosition == .bottom || xAxis.labelPosition == .bottomInside || xAxis.labelPosition == .bothSided { context.beginPath() context.move(to: CGPoint(x: viewPortHandler.contentLeft, y: viewPortHandler.contentTop)) context.addLine(to: CGPoint(x: viewPortHandler.contentLeft, y: viewPortHandler.contentBottom)) context.strokePath() } context.restoreGState() } open override func renderLimitLines(context: CGContext) { guard let xAxis = self.axis as? XAxis, let transformer = self.transformer else { return } var limitLines = xAxis.limitLines if limitLines.count == 0 { return } let trans = transformer.valueToPixelMatrix var position = CGPoint(x: 0.0, y: 0.0) for i in 0 ..< limitLines.count { let l = limitLines[i] if !l.isEnabled { continue } context.saveGState() defer { context.restoreGState() } var clippingRect = viewPortHandler.contentRect clippingRect.origin.y -= l.lineWidth / 2.0 clippingRect.size.height += l.lineWidth context.clip(to: clippingRect) position.x = 0.0 position.y = CGFloat(l.limit) position = position.applying(trans) context.beginPath() context.move(to: CGPoint(x: viewPortHandler.contentLeft, y: position.y)) context.addLine(to: CGPoint(x: viewPortHandler.contentRight, y: position.y)) context.setStrokeColor(l.lineColor.cgColor) context.setLineWidth(l.lineWidth) if l.lineDashLengths != nil { context.setLineDash(phase: l.lineDashPhase, lengths: l.lineDashLengths!) } else { context.setLineDash(phase: 0.0, lengths: []) } context.strokePath() let label = l.label // if drawing the limit-value label is enabled if l.drawLabelEnabled && label.count > 0 { let labelLineHeight = l.valueFont.lineHeight let xOffset: CGFloat = 4.0 + l.xOffset let yOffset: CGFloat = l.lineWidth + labelLineHeight + l.yOffset if l.labelPosition == .rightTop { ChartUtils.drawText(context: context, text: label, point: CGPoint( x: viewPortHandler.contentRight - xOffset, y: position.y - yOffset), align: .right, attributes: [NSAttributedStringKey.font: l.valueFont, NSAttributedStringKey.foregroundColor: l.valueTextColor]) } else if l.labelPosition == .rightBottom { ChartUtils.drawText(context: context, text: label, point: CGPoint( x: viewPortHandler.contentRight - xOffset, y: position.y + yOffset - labelLineHeight), align: .right, attributes: [NSAttributedStringKey.font: l.valueFont, NSAttributedStringKey.foregroundColor: l.valueTextColor]) } else if l.labelPosition == .leftTop { ChartUtils.drawText(context: context, text: label, point: CGPoint( x: viewPortHandler.contentLeft + xOffset, y: position.y - yOffset), align: .left, attributes: [NSAttributedStringKey.font: l.valueFont, NSAttributedStringKey.foregroundColor: l.valueTextColor]) } else { ChartUtils.drawText(context: context, text: label, point: CGPoint( x: viewPortHandler.contentLeft + xOffset, y: position.y + yOffset - labelLineHeight), align: .left, attributes: [NSAttributedStringKey.font: l.valueFont, NSAttributedStringKey.foregroundColor: l.valueTextColor]) } } } } }
apache-2.0
da883ba17086817b8631f3efb8f52207
34.433333
135
0.537159
5.514916
false
false
false
false
LiulietLee/BilibiliCD
BCD/ViewController/MainViewController.swift
1
7604
// // MainViewController.swift // BCD // // Created by Liuliet.Lee on 17/6/2017. // Copyright © 2017 Liuliet.Lee. All rights reserved. // import UIKit import SWRevealViewController import ViewAnimator import LLDialog class MainViewController: UIViewController, UITextFieldDelegate { @IBOutlet weak var typeLabel: UILabel! @IBOutlet weak var searchField: UITextField! @IBOutlet weak var goButton: UIButton! @IBOutlet weak var menu: UIBarButtonItem! private var manager = HistoryManager() var cover = BilibiliCover(bvid: "") var currentCoverType: CoverType { get { cover.type } set { if newValue == .bvideo { searchField.keyboardType = .asciiCapable searchField.autocorrectionType = .no typeLabel.text = "视频 BV" cover = BilibiliCover(bvid: "") } else { searchField.keyboardType = .numberPad cover = BilibiliCover(id: 0, type: newValue) switch newValue { case .video: typeLabel.text = "视频 AV" case .article: typeLabel.text = "专栏 CV" case .live: typeLabel.text = "直播间 LV" default: break } } searchField.text = "" } } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.navigationController?.navigationBar.barTintColor = .white view.endEditing(true) NotificationCenter.default.addObserver( self, selector: #selector(getURLFromPasteboard), name: UIApplication.didBecomeActiveNotification, object: nil ) #if targetEnvironment(macCatalyst) NotificationCenter.default.addObserver( self, selector: #selector(getURLFromPasteboard), name: Notification.Name(rawValue: "NSWindowDidBecomeKeyNotification"), object: nil ) #endif navigationController?.navigationBar.setBackgroundImage(UIImage(), for: .default) navigationController?.navigationBar.shadowImage = UIImage() navigationController?.navigationBar.isTranslucent = true } override func viewWillDisappear(_ animated: Bool) { navigationController?.navigationBar.setBackgroundImage(nil, for: .default) navigationController?.navigationBar.shadowImage = nil navigationController?.navigationBar.isTranslucent = false super.viewWillDisappear(animated) } override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) NotificationCenter.default.removeObserver(self) view.endEditing(true) } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) getURLFromPasteboard() } @objc private func getURLFromPasteboard() { BilibiliCover.fromPasteboard { [weak self] (newCover) in guard self != nil, let newCover = newCover, self!.cover != newCover else { return } DispatchQueue.main.async { guard let self = self, !isShowingImage else { return } self.currentCoverType = newCover.type self.cover = newCover self.searchField.text = String(newCover.shortDescription.dropFirst(2)) self.goButton.isEnabled = true guard self.manager.itemInHistory(cover: newCover) == nil else { return } isShowingImage = true self.performSegue(withIdentifier: "showImageVC", sender: self) } } } override func viewDidLoad() { super.viewDidLoad() isShowingImage = false searchField.delegate = self searchField.addTarget(self, action: #selector(searchFieldDidChanged), for: .editingChanged) searchField.layer.borderColor = UIColor.clear.cgColor goButton.isEnabled = false menu.target = revealViewController() menu.action = #selector(SWRevealViewController.revealToggle(_:)) view.addGestureRecognizer(revealViewController().panGestureRecognizer()) let backItem = UIBarButtonItem() backItem.title = "" navigationItem.backBarButtonItem = backItem if !pasteBoardTipWillAppear() { promptToShowAppTutorialIfNeeded() promptToShowAutoHidTutorialIfNeeded() } } @IBAction func switchCoverType() { let currentType = cover.type.rawValue let nextType = currentType % 4 + 1 currentCoverType = CoverType(rawValue: nextType)! goButton.isEnabled = false view.endEditing(true) } private func promptToShowAutoHidTutorialIfNeeded() { guard needToDisplayAutoHideTutorial else { return } LLDialog() .set(title: "(=・ω・=)") .set(message: "想了解下「自动和谐」的什么东西嘛?") .setNegativeButton(withTitle: "不想") .setPositiveButton(withTitle: "好的", target: self, action: #selector(showAutoHidTutorial)) .show() } private func promptToShowAppTutorialIfNeeded() { guard needToDisplayAppTutorial else { return } LLDialog() .set(title: "(=・ω・=)") .set(message: "想看看这个 App 的使用说明嘛?") .setNegativeButton(withTitle: "不想") .setPositiveButton(withTitle: "好的", target: self, action: #selector(showAppTutorial)) .show() } private func pasteBoardTipWillAppear() -> Bool { guard needToShowPasteBoardTip else { return false } LLDialog() .set(title: "关于剪贴板的使用") .set(message: "每当打开 Bili Cita 首页的时候,App 会自动扫描剪贴板的内容,这么做的目的是找到剪贴板中的 BV 号并自动进行搜索。App 不会将剪贴板的内容存储或上传到任何地方。") .setPositiveButton(withTitle: "好的", target: self, action: #selector(pastBoardTipDidDisappear)) .show() return true } @objc private func pastBoardTipDidDisappear() { promptToShowAppTutorialIfNeeded() promptToShowAutoHidTutorialIfNeeded() } @objc private func showAutoHidTutorial() { let vc = HisTutViewController() vc.page = "AutoHide" present(vc, animated: true) } @objc private func showAppTutorial() { let tutorialViewController = storyboard?.instantiateViewController(withIdentifier: "TutorialViewController") as! TutorialViewController present(tutorialViewController, animated: true) } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if let vc = segue.destination as? ImageViewController { vc.cover = cover view.endEditing(true) if let eCover = manager.itemInHistory(cover: cover) { vc.itemFromHistory = eCover } } } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { view.endEditing(true) } @objc func searchFieldDidChanged() { if currentCoverType == .bvideo { cover.bvid = searchField.text! } else { cover.number = UInt64(searchField.text!) ?? 0 } goButton.isEnabled = searchField.text != "" } }
gpl-3.0
395c8310d59fa0ff229f20715baf193f
35.572139
143
0.615699
4.930248
false
false
false
false
google/JacquardSDKiOS
Tests/TouchDataTests.swift
1
1922
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import XCTest @testable import JacquardSDK extension TouchData: Equatable { public static func == (lhs: TouchData, rhs: TouchData) -> Bool { return lhs.sequence == rhs.sequence && lhs.proximity == rhs.proximity && lhs.lines.0 == rhs.lines.0 && lhs.lines.1 == rhs.lines.1 && lhs.lines.2 == rhs.lines.2 && lhs.lines.3 == rhs.lines.3 && lhs.lines.4 == rhs.lines.4 && lhs.lines.5 == rhs.lines.5 && lhs.lines.6 == rhs.lines.6 && lhs.lines.7 == rhs.lines.7 && lhs.lines.8 == rhs.lines.8 && lhs.lines.9 == rhs.lines.9 && lhs.lines.10 == rhs.lines.10 && lhs.lines.11 == rhs.lines.11 } } class TouchDataTests: XCTestCase { func testInit() { let td0 = TouchData(sequence: 0, proximity: 0, lines: (0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)) XCTAssertEqual(td0, TouchData.empty) let td1 = TouchData(sequence: 1, proximity: 2, lines: (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12)) let proto = Google_Jacquard_Protocol_TouchData.with { $0.sequence = 1 $0.diffDataScaled = Data([2, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]) } let td2 = TouchData(proto) XCTAssertEqual(td1, td2) } func testLinesArray() { let td = TouchData(sequence: 1, proximity: 2, lines: (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12)) XCTAssertEqual(td.linesArray, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]) } }
apache-2.0
1813a7eb395f45f2635c63ed8b579a8b
39.041667
99
0.64256
3.095008
false
true
false
false
DukeLenny/Weibo
Weibo/Weibo/Class/Tool/Other/Constant.swift
1
968
// // Constant.swift // Weibo // // Created by LiDinggui on 2017/9/29. // Copyright © 2017年 DAQSoft. All rights reserved. // import UIKit let NavigationBarTintColor = UIColor.darkGray let NavigationBarHighlightedTintColor = UIColor.orange let NavigationBarBarTintColor = UIColor.hex(0xF6F6F6) let NavigationBarBackImageName = "navigationbar_back_withtext" let NavigationBarBackHighlightedImageName = "navigationbar_back_withtext_highlighted" let TabBarTintColor = UIColor.black let BarButtonItemFont = UIFont.systemFont(ofSize: 16.0) let BarButtonItemTitle = "返回" let ScreenWidth = UIScreen.main.bounds.size.width let ScreenHeight = UIScreen.main.bounds.size.height let Application = UIApplication.shared let APPDELEGATE = Application.delegate let Window = APPDELEGATE?.window let StatusBarHeight = Application.statusBarFrame.size.height let TopBarHeight = StatusBarHeight + navigationBarHeight() let SystemVersion = UIDevice.current.systemVersion
mit
e4427ef4603790ca2cd0a96d4907f183
30
85
0.810614
4.124464
false
false
false
false
Enziferum/iosBoss
iosBoss/WebViewProxy.swift
1
2229
// // WebViewProxy.swift // iosBoss // // Created by AlexRaag on 30/08/2017. // Copyright © 2017 AlexRaag. All rights reserved. // import WebKit /** TODO Section Block TODO Does We Need Inheritance from NSobject??? Update WebView && add Support WKWebView features */ //MARK:WebViewWrapper /** Handle WebView. Has Methods to manipulate Base Needed Features. Also All WebView features Can be used by **getView()** */ //Allow public class WebViewProxy{ public init(){ let Config = WKWebViewConfiguration() let Size = UIScreen.main.bounds self.view = WKWebView(frame: Size, configuration: Config) } public convenience init(UrlPath:String){ self.init() Url=URL(string: UrlPath)! } /** Allows Manipulate WebView */ open func getView()->WKWebView{ return view } open func setDelegete(UIDelegete:WKUIDelegate ,NavDelegate:WKNavigationDelegate){ view.uiDelegate = UIDelegete view.navigationDelegate = NavDelegate } open func MakeRequest(){ let Request = URLRequest(url: Url!) view.load(Request) } //MARK: JavaScript Evaluate /** Simply Evaluates Js Code. No handler. - Returns:**WILL** Return completionHandler */ open func UseJs(with Path:String){ do { view.evaluateJavaScript(try GetDataBundle(Path: Path) , completionHandler: { (answer,error) in if error != nil { print("Cannot Evaluate JsCode") } }) } //Catch error// catch { } } /** Proxe Feature in Future */ private func GetDataBundle(Path:String)throws->String{ JsUrl = Bundle.main.path(forResource: Path, ofType: "js") JsString = try String(contentsOfFile: JsUrl!, encoding: String.Encoding.utf8) if JsString == nil { // must be here throw part // } return JsString! } var view:WKWebView var Url:URL? var JsUrl,JsString:String? }
mit
10dd4f54306aa74fc17fa8d2871eee66
20.219048
85
0.563285
4.565574
false
false
false
false
tensorflow/swift-models
MiniGo/Strategies/MCTS/MCTSNode.swift
1
7246
// Copyright 2019 The TensorFlow 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. /// Tree node for the MCTS algorithm. class MCTSNode { private let boardSize: Int /// Total visited count for this node during simulations. private var totalVisitedCount: Int = 0 /// The corresponding board state for this node. let boardState: BoardState /// All children (nodes) for this node in the `MCTSTree`. var children: [Move: MCTSNode] = [:] private struct Action { let move: Move var prior: Float var qValueTotal: Float var visitedCount: Int } /// The `actionSpace` consists of all legal actions for current `BoardState`. The first action is /// `.pass`, followed by all legal positions. /// /// Note: `prior` in `actionSpace` must be normalized to form a valid probability. private var actionSpace: [Action] /// Creates a MCTS node. /// /// - Precondition: The `distribution` is not expected to be normalized. And it is allowed to /// have positive values for illegal positions. init( boardSize: Int, boardState: BoardState, distribution: MCTSPrediction.Distribution ) { self.boardSize = boardSize self.boardState = boardState var actions: [Move] = [.pass] // .pass must be the first one. actions.reserveCapacity(boardState.legalMoves.count + 1) boardState.legalMoves.forEach { actions.append(.place(position: $0)) } var priorOverActions = Array(repeating: Float(0), count: actions.count) var sum: Float = 0 for (index, action) in actions.enumerated() { let prior: Float switch action { case .pass: assert(index == 0) prior = distribution.pass case .place(let position): assert(index > 0) prior = distribution.positions[position.x][position.y].scalars[0] } sum += prior priorOverActions[index] = prior } self.actionSpace = actions.enumerated().map { Action(move: $1, prior: priorOverActions[$0] / sum, qValueTotal: 0.0, visitedCount: 0) } } } /// Supports the node backing up. extension MCTSNode { /// Backs up the reward. func backUp(for move: Move, withRewardForBlackPlayer rewardForBlackPlayer: Float) { guard let index = actionSpace.firstIndex(where: { $0.move == move }) else { fatalError("The action \(move) taken must be legal (all legal actions: \(actionSpace)).") } totalVisitedCount += 1 actionSpace[index].visitedCount += 1 actionSpace[index].qValueTotal += rewardForBlackPlayer * (boardState.nextPlayerColor == .black ? 1.0 : -1.0) } } /// Supports selecting the action. extension MCTSNode { /// Returns the next move to take based on current learned statistic in Node. func nextMove(withExplorationEnabled: Bool) -> Move { precondition(totalVisitedCount > 0, "The node has not been visited after creation.") if withExplorationEnabled { return sampleFromPMF(actionSpace) { Float($0.visitedCount) }.move } else { return maxScoringElement(actionSpace) { Float($0.visitedCount) }.move } } /// Selects the action based on PUCT algorithm for simulation. /// /// PUCT stands for predictor + UCT, where UCT stands for UCB applied to trees. The /// action is selected based on the statistic in the search tree and has some levels of /// exploration. Initially, this algorithm prefers action with high prior probability and low /// visit count but asymptotically prefers action with high action value. /// /// See the AlphaGoZero paper and its references for details. var actionByPUCT: Move { guard totalVisitedCount > 0 else { // If the node has not be visited after creation, we select the move based on prior // probability. return nextMoveWithHighestPrior } return nextMoveWithHighestActionValue } } extension MCTSNode { private var nextMoveWithHighestPrior: Move { return maxScoringElement(actionSpace) { $0.prior }.move } private var nextMoveWithHighestActionValue: Move { return maxScoringElement( actionSpace, withScoringFunction: { // See the AlphaGoZero paper ("Methods" -> "Select" section) for the formula of action // value. let visitedCount = $0.visitedCount var actionValue = $0.prior * (Float(totalVisitedCount) / (1.0 + Float(visitedCount))).squareRoot() if visitedCount > 0 { actionValue += $0.qValueTotal / Float(visitedCount) } return actionValue } ).move } } extension MCTSNode { /// A general algorithm to find the element with highest score. If there are multiple, /// breaks the tie randomly. private func maxScoringElement<T>( _ elements: [T], withScoringFunction scoringFunction: (T) -> Float ) -> T { precondition(!elements.isEmpty) var candidateIndexes = [0] var highestValue = scoringFunction(elements[0]) for index in elements.indices.dropFirst() { let v = scoringFunction(elements[index]) if v > highestValue { highestValue = v candidateIndexes = [index] } else if abs(v - highestValue) < .ulpOfOne { precondition(!candidateIndexes.isEmpty) candidateIndexes.append(index) } } // Breaks the tie randomly. assert(!candidateIndexes.isEmpty) return elements[candidateIndexes.randomElement()!] } /// Samples an element according to the PMF. private func sampleFromPMF<T>(_ elements: [T], with pmfFunction: (T) -> Float) -> T { precondition(!elements.isEmpty) var cdf: [Float] = [] var currentSum: Float = 0.0 for element in elements { let probability = pmfFunction(element) assert(probability >= 0) currentSum += probability cdf.append(currentSum) } let sampleSpace = 10000 let sample = Int.random(in: 0..<sampleSpace) let threshold = Float(sample) / Float(sampleSpace) * currentSum for (i, element) in elements.enumerated() where threshold < cdf[i] { return element } return elements[elements.count - 1] } }
apache-2.0
223c8075ce5b36e9c676169d0420be3c
35.41206
102
0.619652
4.47284
false
false
false
false
cailingyun2010/swift-keyboard
01-表情键盘/EmotionView/EmotionPackage.swift
1
5519
// // EmoticonPackage.swift // 表情键盘界面布局 // // Created by xiaomage on 15/9/16. // Copyright © 2015年 小码哥. All rights reserved. // import UIKit /* 结构: 1. 加载emoticons.plist拿到每组表情的路径 emoticons.plist(字典) 存储了所有组表情的数据 |----packages(字典数组) |-------id(存储了对应组表情对应的文件夹) 2. 根据拿到的路径加载对应组表情的info.plist info.plist(字典) |----id(当前组表情文件夹的名称) |----group_name_cn(组的名称) |----emoticons(字典数组, 里面存储了所有表情) |----chs(表情对应的文字) |----png(表情对应的图片) |----code(emoji表情对应的十六进制字符串) */ class EmoticonPackage: NSObject { /// 当前组表情文件夹的名称 var id: String? /// 组的名称 var group_name_cn : String? /// 当前组所有的表情对象 var emoticons: [Emoticon]? /// 获取所有组的表情数组 // 浪小花 -> 一组 -> 所有的表情模型(emoticons) // 默认 -> 一组 -> 所有的表情模型(emoticons) // emoji -> 一组 -> 所有的表情模型(emoticons) class func loadPackages() -> [EmoticonPackage] { var packages = [EmoticonPackage]() // 0.创建最近组 let pk = EmoticonPackage(id: "") pk.group_name_cn = "最近" pk.emoticons = [Emoticon]() pk.appendEmtyEmoticons() packages.append(pk) let path = NSBundle.mainBundle().pathForResource("emoticons.plist", ofType: nil, inDirectory: "Emoticons.bundle")! // 1.加载emoticons.plist let dict = NSDictionary(contentsOfFile: path)! // 2.或emoticons中获取packages let dictArray = dict["packages"] as! [[String:AnyObject]] // 3.遍历packages数组 for d in dictArray { // 4.取出ID, 创建对应的组 let package = EmoticonPackage(id: d["id"]! as! String) packages.append(package) package.loadEmoticons() package.appendEmtyEmoticons() } return packages } /// 加载每一组中所有的表情 func loadEmoticons() { let emoticonDict = NSDictionary(contentsOfFile: infoPath("info.plist"))! group_name_cn = emoticonDict["group_name_cn"] as? String let dictArray = emoticonDict["emoticons"] as! [[String: String]] emoticons = [Emoticon]() var index = 0 for dict in dictArray{ // 固定102 if index == 20 { print("添加删除") emoticons?.append(Emoticon(isRemoveButton: true)) index = 0 } emoticons?.append(Emoticon(dict: dict, id: id!)) index++ } } /** 追加空白按钮 如果一页不足21个,那么就添加一些空白按钮补齐 */ func appendEmtyEmoticons() { print(emoticons?.count) let count = emoticons!.count % 21 print("count = \(count)") // 追加空白按钮 for _ in count..<20 { // 追加空白按钮 emoticons?.append(Emoticon(isRemoveButton: false)) } // 追加一个删除按钮 emoticons?.append(Emoticon(isRemoveButton: true)) print(emoticons?.count) print("---------") } /** 获取指定文件的全路径 :param: fileName 文件的名称 :returns: 全路径 */ func infoPath(fileName: String) -> String { return (EmoticonPackage.emoticonPath().stringByAppendingPathComponent(id!) as NSString).stringByAppendingPathComponent(fileName) } /// 获取微博表情的主路径 class func emoticonPath() -> NSString{ return (NSBundle.mainBundle().bundlePath as NSString).stringByAppendingPathComponent("Emoticons.bundle") } init(id: String) { self.id = id } } class Emoticon: NSObject { /// 表情对应的文字 var chs: String? /// 表情对应的图片 var png: String? { didSet{ imagePath = (EmoticonPackage.emoticonPath().stringByAppendingPathComponent(id!) as NSString).stringByAppendingPathComponent(png!) } } /// emoji表情对应的十六进制字符串 var code: String?{ didSet{ // 1.从字符串中取出十六进制的数 // 创建一个扫描器, 扫描器可以从字符串中提取我们想要的数据 let scanner = NSScanner(string: code!) // 2.将十六进制转换为字符串 var result:UInt32 = 0 scanner.scanHexInt(&result) // 3.将十六进制转换为emoji字符串 emojiStr = "\(Character(UnicodeScalar(result)))" } } var emojiStr: String? /// 当前表情对应的文件夹 var id: String? /// 表情图片的全路径 var imagePath: String? /// 标记是否是删除按钮 var isRemoveButton: Bool = false init(isRemoveButton: Bool) { super.init() self.isRemoveButton = isRemoveButton } init(dict: [String: String], id: String) { super.init() self.id = id setValuesForKeysWithDictionary(dict) } override func setValue(value: AnyObject?, forUndefinedKey key: String) { } }
mit
2846cc38991abbcfd723cd46d57cd2bd
24.380435
141
0.557173
4.154804
false
false
false
false
camdenfullmer/UnsplashSwift
Source/Extensions.swift
1
2425
// Extensions.swift // // Copyright (c) 2016 Camden Fullmer (http://camdenfullmer.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 extension UIColor { static func colorWithHexString(hex: String) -> UIColor { guard hex.hasPrefix("#") else { return UIColor.blackColor() } guard let hexString: String = hex.substringFromIndex(hex.startIndex.advancedBy(1)), var hexValue: UInt32 = 0 where NSScanner(string: hexString).scanHexInt(&hexValue) else { return UIColor.blackColor() } guard hexString.characters.count == 6 else { return UIColor.blackColor() } let divisor = CGFloat(255) let red = CGFloat((hexValue & 0xFF0000) >> 16) / divisor let green = CGFloat((hexValue & 0x00FF00) >> 8) / divisor let blue = CGFloat( hexValue & 0x0000FF ) / divisor return UIColor(red: red, green: green, blue: blue, alpha: 1) } } extension NSURL { var queryPairs : [String : String] { var results = [String: String]() let pairs = self.query?.componentsSeparatedByString("&") ?? [] for pair in pairs { let kv = pair.componentsSeparatedByString("=") results.updateValue(kv[1], forKey: kv[0]) } return results } }
mit
2e8412e422212d02aaa12db037e892f0
39.416667
91
0.657732
4.584121
false
false
false
false
Coledunsby/TwitterClient
TwitterClient/Tweet.swift
1
1163
// // Tweet.swift // TwitterClient // // Created by Cole Dunsby on 2017-06-05. // Copyright © 2017 Cole Dunsby. All rights reserved. // import RealmSwift import SwiftRandom /// Represents a tweet object in the realm database final class Tweet: Object { /// The unique identifier of the tweet dynamic var id = UUID().uuidString /// The user who posted the tweet dynamic var user: User! /// The content of the tweet dynamic var message = "" /// The post date of the tweet dynamic var date = Date() convenience init(user: User, message: String, date: Date = Date()) { self.init() self.user = user self.message = message self.date = date } override static func primaryKey() -> String? { return "id" } } extension Tweet { static func random(withUser user: User? = nil) -> Tweet { return Tweet( user: user ?? User.random(), message: (0 ..< Int.random(1, 3)).map({ _ in Randoms.randomFakeConversation() }).joined(separator: " "), date: Date.randomWithinDaysBeforeToday(30) ) } }
mit
abc9146233a34732872250e3d4007d4b
23.208333
116
0.591222
4.179856
false
false
false
false
apple/swift-experimental-string-processing
Sources/RegexBenchmark/CLI.swift
1
3226
import ArgumentParser @main struct Runner: ParsableCommand { @Argument(help: "Patterns for benchmarks to run") var specificBenchmarks: [String] = [] @Option(help: "How many samples to collect for each benchmark") var samples = 30 @Flag(help: "Debug benchmark regexes") var debug = false @Option(help: "Load results from this file instead of rerunning") var load: String? @Option(help: "The file results should be saved to") var save: String? @Option(help: "The result file to compare against") var compare: String? @Option(help: "Compare compile times with the given results file") var compareCompileTime: String? @Flag(help: "Show comparison chart") var showChart: Bool = false @Flag(help: "Compare with NSRegularExpression") var compareWithNS: Bool = false @Option(help: "Save comparison results as csv") var saveComparison: String? @Flag(help: "Quiet mode") var quiet = false @Flag(help: "Exclude running NSRegex benchmarks") var excludeNs = false @Flag(help: """ Enable tracing of the engine (warning: lots of output). Prints out processor state each cycle Note: swift-experimental-string-processing must be built with processor measurements enabled swift build -c release -Xswiftc -DPROCESSOR_MEASUREMENTS_ENABLED """) var enableTracing: Bool = false @Flag(help: """ Enable engine metrics (warning: lots of output). Prints out cycle count, instruction counts, number of backtracks Note: swift-experimental-string-processing must be built with processor measurements enabled swift build -c release -Xswiftc -DPROCESSOR_MEASUREMENTS_ENABLED """) var enableMetrics: Bool = false @Flag(help: "Include firstMatch benchmarks in CrossBenchmark (off by default)") var includeFirst: Bool = false mutating func run() throws { var runner = BenchmarkRunner( suiteName: "DefaultRegexSuite", samples: samples, quiet: quiet, enableTracing: enableTracing, enableMetrics: enableMetrics, includeFirstOverride: includeFirst) runner.registerDefault() if !self.specificBenchmarks.isEmpty { runner.suite = runner.suite.filter { b in specificBenchmarks.contains { pattern in try! Regex(pattern).firstMatch(in: b.name) != nil } } } if debug { runner.debug() return } if let loadFile = load { try runner.load(from: loadFile) } else { if excludeNs { runner.suite = runner.suite.filter { b in !b.name.contains("NS") } } runner.run() } if let saveFile = save { try runner.save(to: saveFile) } if saveComparison != nil && compareWithNS && compare != nil { print("Unable to save both comparison results, specify only one compare operation") return } if compareWithNS { try runner.compareWithNS(showChart: showChart, saveTo: saveComparison) } if let compareFile = compare { try runner.compare( against: compareFile, showChart: showChart, saveTo: saveComparison) } if let compareFile = compareCompileTime { try runner.compareCompileTimes(against: compareFile, showChart: showChart) } } }
apache-2.0
24ee78908523c2fd3d44711bb6bafc6c
27.548673
113
0.683509
4.178756
false
false
false
false
AntonTheDev/CoreFlightAnimation
Source/FAInterpolation/FASpring.swift
3
5932
// // FAInterpolation+SpringEngine.swift // FlightAnimator // // Created by Anton Doudarev on 4/23/16. // Copyright © 2016 Anton Doudarev. All rights reserved. // import Foundation import UIKit let CGFLT_EPSILON = CGFloat(FLT_EPSILON) public struct FASpring { private var equilibriumPosition : CGFloat private var angularFrequency : CGFloat = 10.0 private var dampingRatio : CGFloat = 1.0 private var positionVelocity : CGFloat = 1.0 private var positionValue : CGFloat = 1.0 private var positionValues : Array<CGFloat> = Array<CGFloat>() // Shared Constants private var c1 : CGFloat = 0.0 private var c2 : CGFloat = 0.0 // Over Damped Constants private var za : CGFloat = 0.0 private var zb : CGFloat = 0.0 private var z1 : CGFloat = 0.0 private var z2 : CGFloat = 0.0 // Under Damped Constants private var omegaZeta : CGFloat = 0.0 private var alpha : CGFloat = 0.0 private var c3 : CGFloat = 0.0 /** Designated initializer. Initializes a Spring object stored by the Spring animation to calulate value in time based on the preconfigured spring at the start of the animation - parameter finalValue: The final resting value - parameter initialValue: The intial v``alue in time for the animation - parameter velocity: The intial velociy for the value - parameter frequency: The angular frequency of the spring - parameter ratio: the damping ratio of the spring - returns: Preconfigured Spring */ init(finalValue: CGFloat, initialValue : CGFloat, positionVelocity velocity: CGFloat, angularFrequency frequency: CGFloat, dampingRatio ratio: CGFloat) { self.dampingRatio = ratio self.angularFrequency = frequency self.equilibriumPosition = finalValue self.positionValue = initialValue self.positionVelocity = velocity if self.angularFrequency < CGFLT_EPSILON { print("No motion") } if self.dampingRatio < 0.0 { self.dampingRatio = 0.0 } // Over Damped if self.dampingRatio > 1.0 + CGFLT_EPSILON { za = -angularFrequency * dampingRatio zb = angularFrequency * sqrt(dampingRatio * dampingRatio - 1.0) z1 = za - zb z2 = za + zb c1 = (positionVelocity - (positionValue - equilibriumPosition) * z2) / (-2.0 * zb) c2 = (positionValue - equilibriumPosition) - c1 } // Critically Damped else if (self.dampingRatio > 1.0 - CGFLT_EPSILON) { c1 = positionVelocity + angularFrequency * (positionValue - equilibriumPosition) c2 = (positionValue - equilibriumPosition) } // Under Damped else { omegaZeta = angularFrequency * dampingRatio alpha = angularFrequency * sqrt(1.0 - dampingRatio * dampingRatio) c1 = (positionValue - equilibriumPosition) c2 = (positionVelocity + omegaZeta * (positionValue - equilibriumPosition)) / alpha } } /** This method calculates the current CGFLoat value in time based on the configuration of the spring at initialization - parameter deltaTime: The current time interval for the animation - returns: The current value in time, based on the velocity, angular frequency and damping */ func updatedValue(deltaTime: CGFloat) -> CGFloat { // Over Damped if dampingRatio > 1.0 + CGFLT_EPSILON { let expTerm1 = exp(z1 * deltaTime) let expTerm2 = exp(z2 * deltaTime) let position = equilibriumPosition + c1 * expTerm1 + c2 * expTerm2 return position } // Critically Damped else if (dampingRatio > 1.0 - CGFLT_EPSILON) { let expTerm = exp( -angularFrequency * deltaTime ) let c3 = (c1 * deltaTime + c2) * expTerm let p = equilibriumPosition + c3 return ceil(p) } // Under Damped else { let change = alpha * deltaTime let expTerm = exp( -omegaZeta * deltaTime) let cosTerm = cos(change) let sinTerm = sin(change) let exp2 = expTerm * (c1 * cosTerm + c2 * sinTerm) return equilibriumPosition + exp2 } } /** When a spring animation A is in motion, and is replaced by animation B in motion, we candetermine the current velocity of the animating CGFloat value in time. The time difference is derived by subtacting the start time of the layer in animation A from the current layer time - parameter deltaTime: The time difference from the start time of the animation - returns: The current velocity of the single CGFoloat value animating */ func velocity(deltaTime : CGFloat) -> CGFloat { // Over Damped if dampingRatio > 1.0 + CGFLT_EPSILON { let expTerm1 = exp(z1 * deltaTime) let expTerm2 = exp(z2 * deltaTime) return c1 * z1 * expTerm1 + c2 * z2 * expTerm2 } // Critically Damped else if (dampingRatio > 1.0 - CGFLT_EPSILON) { let expTerm = exp( -angularFrequency * deltaTime ) let c3 = (c1 * deltaTime + c2) * expTerm return (c1 * expTerm) - (c3 * self.angularFrequency) } // Under Damped else { let change = alpha * deltaTime let expTerm = exp( -omegaZeta * deltaTime) let cosTerm = cos(change) let sinTerm = sin(change) return -expTerm * ((c1 * omegaZeta - c2 * alpha) * cosTerm + (c1 * alpha + c2 * omegaZeta) * sinTerm) } } }
mit
a5564b3f0724a6073677bbdd5d96bb41
36.537975
158
0.59737
4.266906
false
false
false
false
rivetlogic/liferay-mobile-directory-ios
MobilePeopleDirectory/PersonViewController.swift
1
7540
// // PersonViewController.swift // MobilePeopleDirectory // // Created by Martin Zary on 1/6/15. // Copyright (c) 2015 Rivet Logic. All rights reserved. // import UIKit class PersonViewController: UITableViewController, UIScrollViewDelegate { @IBOutlet weak var name: UILabel! @IBOutlet weak var city: UILabel! @IBOutlet weak var jobTitle: UILabel! @IBOutlet weak var screenName: UILabel! @IBOutlet weak var bgImage: UIImageView! @IBOutlet weak var portrait: UIImageView! var imageHelper:ImageHelper = ImageHelper() var appHelper = AppHelper() var detailItem: Person? var alertHelper = AlertHelper() var headerView: UIView! private let kTableHeaderHeight: CGFloat = 275.0 var skypeId: String! var emailId: String! var phoneNo: String! var detailsArray = [] func configureView() { // Update the user interface for the detail item. if let detail = self.detailItem { if let nameLabel = self.name { nameLabel.text = detail.valueForKey("fullName")!.description } if let cityLabel = self.city { cityLabel.text = detail.valueForKey("city")!.description } if let nameLabel = self.jobTitle { nameLabel.text = detail.valueForKey("jobTitle")!.description } if let screenNameLabel = self.screenName { screenNameLabel.text = detail.valueForKey("screenName")!.description } skypeId = detail.valueForKey("skypeName")!.description emailId = detail.valueForKey("emailAddress")!.description phoneNo = detail.valueForKey("userPhone")!.description let url = NSURL(string: LiferayServerContext.server + detail.valueForKey("portraitUrl")!.description) if imageHelper.hasUserImage(detail.valueForKey("portraitUrl")!.description) { imageHelper.addImageFromData(portrait, image: detail.portraitImage) imageHelper.addImageFromData(bgImage, image: detail.portraitImage) } else { portrait.image = UIImage(named: "UserDefaultImage") bgImage.image = UIImage(named: "UserDefaultImage") } bgImage.image = imageHelper.convertImageToGrayScale(bgImage.image!) imageHelper.addThumbnailStyles(portrait, radius: 60.0) imageHelper.addBlurStyles(bgImage) } let skype = ["title":"Skype", "value":skypeId, "icon":"skype"] let email = ["title":"Email", "value":emailId, "icon":"mail"] let phone = ["title":"Phone", "value":phoneNo, "icon":"call"] detailsArray = [skype,email,phone] tableView.reloadData() } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. self.configureView() self.navigationController?.navigationBarHidden = true headerView = tableView.tableHeaderView tableView.tableHeaderView = nil tableView.addSubview(headerView) tableView.contentInset = UIEdgeInsets(top: kTableHeaderHeight, left: 0, bottom: 0, right: 0) tableView.contentOffset = CGPoint(x: 0, y: -kTableHeaderHeight) updateHeaderView() } override func viewWillAppear(animated: Bool) { super.viewWillAppear(true) let appDelegate: AppDelegate = appHelper.getAppDelegate() appDelegate.statusBar.backgroundColor = UIColor.clearColor() } func updateHeaderView() { var headerRect = CGRect(x: 0, y: -kTableHeaderHeight, width: tableView.bounds.width, height: kTableHeaderHeight) if tableView.contentOffset.y < -kTableHeaderHeight { headerRect.origin.y = tableView.contentOffset.y headerRect.size.height = -tableView.contentOffset.y } headerView.frame = headerRect } // MARK: - Table View override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return detailsArray.count } override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return 70.0 } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("PersonDetailCell", forIndexPath: indexPath) as! UITableViewCell let lblTitel: UILabel = cell.contentView.viewWithTag(102) as! UILabel let lblValue: UILabel = cell.contentView.viewWithTag(103) as! UILabel let imgIcon: UIImageView = cell.contentView.viewWithTag(101) as! UIImageView let cellData = detailsArray.objectAtIndex(indexPath.row) as! NSDictionary lblTitel.text = cellData["title"] as? String lblValue.text = cellData["value"] as? String imgIcon.image = UIImage(named:(cellData["icon"] as! String)) if indexPath.row % 2 == 0 { cell.contentView.backgroundColor = UIColor(red: 241.0/255.0, green: 241.0/255.0, blue: 241.0/255.0, alpha: 1.0) } else { cell.contentView.backgroundColor = UIColor.whiteColor() } return cell } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { let cellData = detailsArray.objectAtIndex(indexPath.row) as! NSDictionary let value: String = cellData["value"] as! String let whitespaceSet = NSCharacterSet.whitespaceCharacterSet() switch indexPath.row { case 0: if value.stringByTrimmingCharactersInSet(whitespaceSet) != "" { UIApplication.sharedApplication().openURL(NSURL(string: "skype://" + value + "?call")!) } break; case 1: if value.stringByTrimmingCharactersInSet(whitespaceSet) != "" { UIApplication.sharedApplication().openURL(NSURL(string: "mailto:" + value)!) } break; case 2: if value.stringByTrimmingCharactersInSet(whitespaceSet) != "" { UIApplication.sharedApplication().openURL(NSURL(string: "tel://" + value)!) } break; default: break; } } //MARK: - ScrollView Delegate override func scrollViewDidScroll(scrollView: UIScrollView) { updateHeaderView() } func logout(sender:UIBarButtonItem) { self.alertHelper.confirmationMessage(self, title: "Please confirm", message: "Are you sure you want to logout?", okButtonText: "Yes", cancelButtonText: "No", confirmed: { _ in self.appHelper.logout(self) }) } @IBAction func backButtonTap(sender: AnyObject) { self.parentViewController?.navigationController?.popViewControllerAnimated(true) } @IBAction func cancelPresssed(sender: AnyObject) { } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
gpl-3.0
5286e0ee28aa5f811a8c3acade9efa0e
35.601942
183
0.62374
5.153794
false
false
false
false
notohiro/NowCastMapView
NowCastMapView/TileModel.swift
1
5195
// // TileModel.swift // NowCastMapView // // Created by Hiroshi Noto on 8/26/16. // Copyright © 2016 Hiroshi Noto. All rights reserved. // import Foundation import MapKit /// A `TileProvider` protocol defines a way to request a `TileModel.Task`. public protocol TileProvider { var baseTime: BaseTime { get } /// Returns task to obtain tiles within given MapRect. /// Call `resume()` method of returning value to obtain image from internet. /// /// - Parameters: /// - request: The request you need to get tiles. /// - completionHandler: The completion handler to call when the load request is complete. /// - Returns: The task to process given request. func tiles(with request: TileModel.Request, completionHandler: (([Tile]) -> Void)?) throws -> TileModel.Task } /// A `TileAvailability` protocol defines a way to check the service availability. public protocol TileAvailability { /// Returns the serivce availability within given MapRect. /// /// - Parameter coordinates: The `Coordinates` you want to know. /// - Returns: `Coordinates` contains service area or not. static func isServiceAvailable(within coordinates: Coordinates) -> Bool /// Returns the serivce availability at given coordinate. /// /// - Parameter coordinate: The coordinate you want to know. /// - Returns: The service availability at coordinate. static func isServiceAvailable(at coordinate: CLLocationCoordinate2D) -> Bool } /// The delegate of a `TileModel` object must adopt the `TileModelDelegate` protocol. /// The `TileModelDelegate` protocol describes the methods that `TileModel` objects /// call on their delegates to handle requested events. public protocol TileModelDelegate: class { /// Tells the delegate that a request has finished and added tiles in model's cache. func tileModel(_ model: TileModel, task: TileModel.Task, added tile: Tile) /// Tells the delegate that a request has finished with error. func tileModel(_ model: TileModel, task: TileModel.Task, failed url: URL, error: Error) } /// An `TileModel` object lets you load the `Tile` by providing a `Request` object. open class TileModel { // MARK: - TileProvider public let baseTime: BaseTime // MARK: - Public Properties open private(set) var tasks = [Task]() open weak private(set) var delegate: TileModelDelegate? // MARK: - Private Properties private let semaphore = DispatchSemaphore(value: 1) // MARK: - Public Functions public init(baseTime: BaseTime, delegate: TileModelDelegate? = nil) { self.baseTime = baseTime self.delegate = delegate } public func cancelAll() { let tasks = self.tasks tasks.forEach { $0.invalidateAndCancel() } } // MARK: - Internal Functions internal func remove(_ task: Task) { semaphore.wait() defer { self.semaphore.signal() } guard let index = tasks.index(of: task) else { return } tasks.remove(at: index) } internal func isProcessing(_ tile: Tile) -> Bool { // thread safe let tasks = self.tasks var processing = false tasks.forEach { task in if task.processingTiles[tile.url] != nil { processing = true } } return processing } } // MARK: - TileProvider extension TileModel: TileProvider { open func tiles(with request: TileModel.Request, completionHandler: (([Tile]) -> Void)?) throws -> Task { semaphore.wait() defer { semaphore.signal() } let task = try Task(model: self, request: request, baseTime: baseTime, delegate: delegate, completionHandler: completionHandler) tasks.append(task) return task } } // MARK: - TileAvailability extension TileModel: TileAvailability { public static func isServiceAvailable(within coordinates: Coordinates) -> Bool { if coordinates.origin.latitude >= Constants.terminalLatitude && coordinates.terminal.latitude <= Constants.originLatitude && coordinates.origin.longitude <= Constants.terminalLongitude && coordinates.terminal.longitude >= Constants.originLongitude { return true } else { return false } } public static func isServiceAvailable(at coordinate: CLLocationCoordinate2D) -> Bool { if coordinate.latitude >= Constants.terminalLatitude && coordinate.latitude <= Constants.originLatitude && coordinate.longitude <= Constants.terminalLongitude && coordinate.longitude >= Constants.originLongitude { return true } else { return false } } public static var serviceAreaMapRect: MKMapRect { return MKMapRect(coordinates: TileModel.serviceAreaCoordinates) } public static var serviceAreaCoordinates: Coordinates { let origin = CLLocationCoordinate2DMake(Constants.originLatitude, Constants.originLongitude) let terminal = CLLocationCoordinate2DMake(Constants.terminalLatitude, Constants.terminalLongitude) return Coordinates(origin: origin, terminal: terminal) } }
mit
7db08720fe9558b5f0efc6b25c773d03
31.666667
112
0.676742
4.71753
false
false
false
false
kartikjain/SwiftXMPP
SwiftXMPP/AppDelegate.swift
1
7083
// // AppDelegate.swift // SwiftXMPP // // Created by Felix Grabowski on 10/06/14. // Copyright (c) 2014 Felix Grabowski. All rights reserved. // import UIKit import XMPPFramework @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate, XMPPStreamDelegate { var window: UIWindow? var viewController: BuddyListViewController? var password: String = "" var isOpen: Bool = false var xmppStream: XMPPStream? var chatDelegate: ChatDelegate? var messageDelegate: MessageDelegate? var loginServer: String = "" func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { self.connect() } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } func setupStream () { xmppStream = XMPPStream() xmppStream!.addDelegate(self, delegateQueue: dispatch_get_main_queue()) } func goOffline() { var presence = XMPPPresence(type: "unavailable") xmppStream!.sendElement(presence) } func goOnline() { print("goOnline") var presence = XMPPPresence(type: "away") xmppStream!.sendElement(presence) } func connect() -> Bool { print("connecting") setupStream() //NSUserDefaults.standardUserDefaults().setValue("[email protected]", forKey: "userID") let b = NSUserDefaults.standardUserDefaults().stringForKey("userID") print("user defaults: " + "\(b)") var jabberID: String? = NSUserDefaults.standardUserDefaults().stringForKey("userID") var myPassword: String? = NSUserDefaults.standardUserDefaults().stringForKey("userPassword") var server: String? = NSUserDefaults.standardUserDefaults().stringForKey("loginServer") if server != nil{ loginServer = server! } xmppStream!.hostName = "localhost" if let stream = xmppStream { if !stream.isDisconnected() { return true } if jabberID == nil || myPassword == nil{ print("no jabberID set:" + "\(jabberID)") print("no password set:" + "\(myPassword)") return false } stream.myJID = XMPPJID.jidWithString(jabberID) password = myPassword! var error: NSError? do{ print(xmppStream!.hostName) print(xmppStream!.myJID) try xmppStream!.connectWithTimeout(XMPPStreamTimeoutNone) // var alert = UIAlertController(title: "Alert", message: "Cannot connect ", preferredStyle: UIAlertControllerStyle.Alert) // alert.addAction(UIAlertAction(title: "Click", style: UIAlertActionStyle.Default, handler: nil)) // self.window?.rootViewController?.presentViewController(alert, animated: true, completion: nil) return false }catch let error as NSError { print("error thrown while connecting \(error)") } } return true } func disconnect() { goOffline() xmppStream!.disconnect() // println("disconnecting") } func xmppStreamDidConnect(sender: XMPPStream) { print("xmppStreamDidConnect") isOpen = true var error: NSError? do { try xmppStream!.authenticateWithPassword(password) }catch let error as NSError { print("error thrown while authenticating \(error)") } } func xmppStreamDidAuthenticate(sender: XMPPStream) { // println("didAuthenticate") goOnline() } func xmppStream(sender: XMPPStream?, didReceiveMessage: XMPPMessage?) { if let message:XMPPMessage = didReceiveMessage { //println("message: \(message)") if let msg: String = message.elementForName("body")?.stringValue() { if let from: String = message.attributeForName("from")?.stringValue() { var m: NSMutableDictionary = [:] m["msg"] = msg m["sender"] = from print("messageReceived") if messageDelegate != nil { messageDelegate!.newMessageReceived(m) } } } else { return } } } func xmppStream(sender: XMPPStream?, didReceivePresence: XMPPPresence?) { // println("didReceivePresence") if let presence = didReceivePresence { var presenceType = presence.type() var myUsername = sender?.myJID.user var presenceFromUser = presence.from().user print(chatDelegate) if chatDelegate != nil { if presenceFromUser != myUsername { if presenceType == "available" { chatDelegate?.newBuddyOnLine("\(presenceFromUser)" + "@" + "\(loginServer)") } else if presenceType == "unavailable" { chatDelegate?.buddyWentOffline("\(presenceFromUser)" + "@" + "\(loginServer)") } } } // println(presenceType) } } }
mit
9f85a31b1d9604990bfc26e0fa0af916
36.08377
285
0.592687
5.625894
false
false
false
false
kenwilcox/PlayThatSong
PlayThatSong/ViewController.swift
1
5477
// // ViewController.swift // PlayThatSong // // Created by Kenneth Wilcox on 3/29/15. // Copyright (c) 2015 Kenneth Wilcox. All rights reserved. // import UIKit import AVFoundation class ViewController: UIViewController { //MARK: Properties @IBOutlet weak var playButton: UIButton! @IBOutlet weak var currentSongLabel: UILabel! var audioSession: AVAudioSession! var audioQueuePlayer: AVQueuePlayer! var currentSongIndex:Int! //MARK: Overrides override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. self.configureAudioSession() self.configureAudioQueuePlayer() NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("handleRequest:"), name: "WatchKitDidMakeRequest", object: nil) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: IBActions @IBAction func playButtonPressed(sender: UIButton) { self.playMusic() self.updateUI() } @IBAction func playPreviousButtonPressed(sender: AnyObject) { if currentSongIndex > 0 { self.audioQueuePlayer.pause() self.audioQueuePlayer.seekToTime(kCMTimeZero, toleranceBefore: kCMTimeZero, toleranceAfter: kCMTimeZero) let temporaryNowPlayIndex = currentSongIndex let temporaryPlayList = self.createSongs() self.audioQueuePlayer.removeAllItems() for var index = temporaryNowPlayIndex - 1; index < temporaryPlayList.count; index++ { self.audioQueuePlayer.insertItem(temporaryPlayList[index] as! AVPlayerItem, afterItem: nil) } self.currentSongIndex = temporaryNowPlayIndex - 1 self.audioQueuePlayer.seekToTime(kCMTimeZero, toleranceBefore: kCMTimeZero, toleranceAfter: kCMTimeZero) self.audioQueuePlayer.play() } self.updateUI() } @IBAction func playNextButtonPressed(sender: AnyObject) { self.audioQueuePlayer.advanceToNextItem() self.currentSongIndex = self.currentSongIndex + 1 self.updateUI() } //MARK: AVFoundation func configureAudioSession() { var categoryError:NSError? var activeError: NSError? self.audioSession = AVAudioSession.sharedInstance() self.audioSession.setCategory(AVAudioSessionCategoryPlayback, error: &categoryError) println("error \(categoryError)") var success = self.audioSession.setActive(true, error: &activeError) if !success { println("Error making audio session active \(activeError)") } } func configureAudioQueuePlayer() { let songs = createSongs() self.audioQueuePlayer = AVQueuePlayer(items: songs) for var songIndex = 0; songIndex < songs.count; songIndex++ { NSNotificationCenter.defaultCenter().addObserver(self, selector: "songEnded:", name: AVPlayerItemDidPlayToEndTimeNotification, object: songs[songIndex]) } } func playMusic() { if audioQueuePlayer.rate > 0 && audioQueuePlayer.error == nil { self.audioQueuePlayer.pause() } else if currentSongIndex == nil { self.audioQueuePlayer.play() self.currentSongIndex = 0 } else { self.audioQueuePlayer.play() } } func createSongs() -> [AnyObject] { let solitude = NSBundle.mainBundle().pathForResource("CLASSICAL SOLITUDE", ofType: "wav") let doldesh = NSBundle.mainBundle().pathForResource("Timothy Pinkham - The Knolls of Doldesh", ofType: "mp3") let signal = NSBundle.mainBundle().pathForResource("Open Source - Sending My Signal", ofType: "mp3") let songs: [AnyObject] = [ AVPlayerItem(URL: NSURL.fileURLWithPath(solitude!)), AVPlayerItem(URL: NSURL.fileURLWithPath(doldesh!)), AVPlayerItem(URL: NSURL.fileURLWithPath(signal!)) ] return songs } //MARK: NSNotifications func songEnded(notification: NSNotification) { self.currentSongIndex = self.currentSongIndex + 1 updateUI() } //MARK: Helper functions func updateUI() { self.currentSongLabel.text = currentSongName() if audioQueuePlayer.rate > 0 && audioQueuePlayer.error == nil { self.playButton.setTitle("Pause", forState: UIControlState.Normal) } else { self.playButton.setTitle("Play", forState: UIControlState.Normal) } } func currentSongName() -> String { var currentSong: String if currentSongIndex == 0 { currentSong = "Classical Solitude" } else if currentSongIndex == 1 { currentSong = "The Knolls of Doldesh" } else if currentSongIndex == 2 { currentSong = "Sending my Signal" } else { currentSong = "No Song Playing" println("Something went wrong!") } return currentSong } //MARK: WatchKit Notification func handleRequest(notification : NSNotification) { let watchKitInfo = notification.object! as! WatchKitInfo if watchKitInfo.playerRequest != nil { let requestedAction: String = watchKitInfo.playerRequest! switch requestedAction { case "Play": self.playMusic() case "Next": self.playNextButtonPressed(self) case "Previous": self.playPreviousButtonPressed(self) default: println("default Value printed something went wrong") } let currentSongDictionary = ["CurrentSong" : currentSongName()] watchKitInfo.replyBlock(currentSongDictionary) self.updateUI() } } }
mit
24a34d71fcf7539870b8e6bb35e90f2a
31.217647
141
0.695454
4.661277
false
false
false
false
Kalito98/Find-me-a-band
Find me a band/Find me a band/Models/BandModel.swift
1
1080
// // BandModel.swift // Find me a band // // Created by Kaloyan Yanev on 3/30/17. // Copyright © 2017 Kaloyan Yanev. All rights reserved. // import Foundation import Gloss struct BandModel: Decodable { let bandId: String? let name: String? let email: String? let phone: String? let bandMembers: [String]? let creator: String? let genre: String? init?(json: JSON) { self.bandId = "_id" <~~ json self.name = "name" <~~ json self.email = "contactEmail" <~~ json self.phone = "contactPhone" <~~ json self.bandMembers = "bandMembers" <~~ json self.creator = "creator" <~~ json self.genre = "genre" <~~ json } func toJSON() -> JSON? { return jsonify([ "_id" ~~> self.bandId, "name" ~~> self.name, "contactEmail" ~~> self.email, "contactPhone" ~~> self.phone, "bandMembers" ~~> self.bandMembers, "creator" ~~> self.creator, "genere" ~~> self.genre ]) } }
mit
2b5a528a92a25c227449d7e61ae99587
23.522727
56
0.526413
3.839858
false
false
false
false
wibosco/WhiteBoardCodingChallenges
WhiteBoardCodingChallenges/Challenges/HackerRank/MissingNumbers/MissingNumbers.swift
1
1356
// // MissingNumbers.swift // WhiteBoardCodingChallenges // // Created by William Boles on 12/07/2016. // Copyright © 2016 Boles. All rights reserved. // import UIKit //https://www.hackerrank.com/challenges/missing-numbers/problem class MissingNumbers: NSObject { // MARK: Missing class func missingNumbers(complete: [Int], incomplete: [Int]) -> [Int] { var occurrences = [Int: Int]() for i in 0..<complete.count { let completeValue = complete[i] if let existingCount = occurrences[completeValue] { occurrences[completeValue] = existingCount+1 } else { occurrences[completeValue] = 1 } if i < incomplete.count { let incompleteValue = incomplete[i] if let existingCount = occurrences[incompleteValue] { occurrences[incompleteValue] = existingCount-1 } else { occurrences[incompleteValue] = -1 } } } var missing = [Int]() for key in occurrences.keys { if occurrences[key] != 0 { missing.append(key) } } return missing.sorted(by: { (a, b) -> Bool in return b > a }) } }
mit
540c574260d5993cccfb4af478dafd60
27.229167
76
0.519557
4.754386
false
false
false
false
RevenueCat/purchases-ios
Tests/UnitTests/Mocks/MockAttributionTypeFactory.swift
1
1908
// // Copyright RevenueCat Inc. All Rights Reserved. // // Licensed under the MIT License (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://opensource.org/licenses/MIT // // Created by Andrés Boedo on 2/25/21. // import Foundation #if canImport(AppTrackingTransparency) import AppTrackingTransparency #endif @testable import RevenueCat class MockAdClientProxy: AfficheClientProxy { static var mockAttributionDetails: [String: NSObject] = [ "Version3.1": [ "iad-campaign-id": 15292426, "iad-attribution": true ] as NSObject ] static var mockError: Error? static var requestAttributionDetailsCallCount = 0 override func requestAttributionDetails(_ completionHandler: @escaping AttributionDetailsBlock) { Self.requestAttributionDetailsCallCount += 1 completionHandler(Self.mockAttributionDetails, Self.mockError) } } @available(iOS 14, macOS 11, tvOS 14, *) class MockTrackingManagerProxy: TrackingManagerProxy { static var mockAuthorizationStatus: ATTrackingManager.AuthorizationStatus = .authorized override func trackingAuthorizationStatus() -> Int { Int(Self.mockAuthorizationStatus.rawValue) } } class MockAttributionTypeFactory: AttributionTypeFactory { static var shouldReturnAdClientProxy = true override func afficheClientProxy() -> AfficheClientProxy? { Self.shouldReturnAdClientProxy ? MockAdClientProxy() : nil } static var shouldReturnTrackingManagerProxy = true override func atFollowingProxy() -> TrackingManagerProxy? { if #available(iOS 14, macOS 11, tvOS 14, *) { return Self.shouldReturnTrackingManagerProxy ? MockTrackingManagerProxy() : nil } else { return nil } } }
mit
1ada53eb8fb8ae097777a5bcef69422a
27.462687
101
0.701626
4.529691
false
false
false
false
carolight/Resizable
Resizable/DragHandle.swift
1
1054
// // DragHandle.swift // Resizable // // Created by Caroline on 7/09/2014. // Copyright (c) 2014 Caroline. All rights reserved. // let diameter:CGFloat = 40 import UIKit class DragHandle: UIView { var fillColor = UIColor.darkGrayColor() var strokeColor = UIColor.lightGrayColor() var strokeWidth:CGFloat = 2.0 required init(coder aDecoder: NSCoder) { fatalError("Use init(fillColor:, strokeColor:)") } init(fillColor:UIColor, strokeColor:UIColor, strokeWidth width:CGFloat = 2.0) { super.init(frame:CGRectMake(0, 0, diameter, diameter)) self.fillColor = fillColor self.strokeColor = strokeColor self.strokeWidth = width self.backgroundColor = UIColor.clearColor() } override func drawRect(rect: CGRect) { super.drawRect(rect) var handlePath = UIBezierPath(ovalInRect: CGRectInset(rect, 10 + strokeWidth, 10 + strokeWidth)) fillColor.setFill() handlePath.fill() strokeColor.setStroke() handlePath.lineWidth = strokeWidth handlePath.stroke() } }
bsd-2-clause
4db702b11bdf4b48dacdfb1a12718d33
24.707317
102
0.690702
4.199203
false
false
false
false
eonil/prototype-signet.swift
Sources/Channel.swift
1
6458
// // Channel.swift // TransmitterExperiment1 // // Created by Hoon H. on 2017/05/27. // Copyright © 2017 Eonil. All rights reserved. // /// /// You can watch station from a channel. /// But a station cannot watch any other. /// /// Stations expose state mutator. /// Stations provides editable source value /// storage for channel network. /// public class MutableChannel<T>: Channel<T> { public public(set) override var state: T { get { return super.state } set { super.state = newValue } } } /// /// You can watch a channel from a transmitter. /// But a transmitter does not provide state mutator. /// You can only read from it. /// public class TransmittableChannel<T>: Channel<T> { /// /// Idempotent. /// public func watch(_ source: Channel<T>) { watch(source, with: { $0 }) } public override func watch<S>(_ source: Channel<S>, with map: @escaping (S) -> T) { super.watch(source, with: map) } /// /// Watches two sources, and produces reduced state. /// /// This produces for each time any of two sources emits a new state. /// Latest state of each other will be used for reducing. /// Latest state is stored in an internal shared storage, so this will work /// even one of source dies early. /// /// Idempotent. /// public func watch<A,B>(_ sourceA: Channel<A>, _ sourceB: Channel<B>, with reduce: @escaping (A,B) -> T) { var sharedStorageBox = MutableBox(WatchByReduceSharedStorage(a: sourceA.state, b: sourceB.state)) weak var aa = sourceA weak var bb = sourceB func getLatestSourceAState() -> A { guard let aa = aa else { return sharedStorageBox.value.a } return aa.state } func getLatestSourceBState() -> B { guard let bb = bb else { return sharedStorageBox.value.b } return bb.state } watch(sourceA) { (_ a: A) -> T in sharedStorageBox.value.a = a let b = getLatestSourceBState() return reduce(a, b) } watch(sourceB) { (_ b: B) -> T in sharedStorageBox.value.b = b let a = getLatestSourceAState() return reduce(a, b) } } private struct WatchByReduceSharedStorage<A,B> { var a: A var b: B } public override func unwatch() { super.unwatch() } } /// /// An object which can be watched by a channel. /// This is read-only representation of mutating state over time. /// /// `Watchable`s store its current state, but code users cannot /// mutate the state directly. You need to use one of its /// subclasses for your needs. /// /// - `Station` for mutable source value storage node. /// - `Transmitter` for transformation/delivery node. /// /// Channels together build a value transformation /// network. This is a sort of push-FRP. /// /// - Note: /// Channel implements all functionalities of /// `TransmittableChannel` and `MutableChannel`. /// The classes exists only for logical access control of /// interfaces. /// /// - Note: /// This class does not compromise with /// ownership and delay. /// /// - No cycles. Everything is weakly referenced. /// - No event delay. Everything is delivered immediately. /// /// Also, /// /// - All methods are idempotent. It may cause extra /// calculations, but result is same. /// public class Channel<T> { public var delegate: ((T) -> Void)? private var stateImpl: T private var bridges = [ObjectIdentifier: (T) -> Void]() private var receptorIDs = [ObjectIdentifier]() private var unwatchImpl: (() -> Void)? public init(_ initialState: T) { stateImpl = initialState } deinit { unwatchImpl?() } public fileprivate(set) var state: T { get { return stateImpl } set { stateImpl = newValue delegate?(newValue) propagateState() } } /// /// Idempotent. /// fileprivate func watch<S>(_ source: Channel<S>, with map: @escaping (S) -> T) { source.addReceptor(self) source.setMappingFunctionOfBridgeToReceptor(self, map) weak var ss = self unwatchImpl = { [weak source] () -> Void in guard let ss = ss else { return } // Dead self. guard let source = source else { return } // Dead source. source.removeReceptor(ss) ss.unwatchImpl = nil } } /// /// Idempotent. /// fileprivate func unwatch() { unwatchImpl?() } /// /// Idempotent. /// private func setMappingFunctionOfBridgeToReceptor<U>(_ receptor: Channel<U>, _ map: @escaping (T) -> U) { let bridgeID = ObjectIdentifier(receptor) weak var ss = self weak var rr = receptor let bridgeFunction = { (_ originalValue: T) -> Void in guard let ss = ss else { return } guard let rr = rr else { ss.removeReceptorByID(bridgeID) return } let mappedValue = map(originalValue) rr.state = mappedValue rr.propagateState() } bridges[bridgeID] = bridgeFunction } /// /// Channel owns the map function. /// This method weakly captures `receptor`. /// /// This function is idempotent. Which means /// duplicated call with same parameter is no-op. /// As a result, supplied receptor will be registered /// only once regardless of number of calls to this /// function. /// /// Idempotent. /// private func addReceptor<U>(_ receptor: Channel<U>) { let receptorID = ObjectIdentifier(receptor) guard receptorIDs.contains(receptorID) == false else { return } receptorIDs.append(receptorID) } /// /// Idempotent. /// private func removeReceptor<U>(_ receptor: Channel<U>) { removeReceptorByID(ObjectIdentifier(receptor)) } /// /// Idempotent. /// private func removeReceptorByID(_ receptorID: ObjectIdentifier) { receptorIDs = receptorIDs.filter({ $0 != receptorID }) bridges[receptorID] = nil } /// /// Idempotent. /// private func propagateState() { for receptorID in receptorIDs { bridges[receptorID]?(state) } } }
mit
5b40b292e9261912306c5459badd30ab
28.484018
109
0.58634
4.033104
false
false
false
false
seraphjiang/JHUIKit
JHUIKit/Classes/JHCircleImageView.swift
1
1694
// // JHCircleImageView.swift // Pods // // Created by Huan Jiang on 5/5/16. // Copyright © 2016 quanware.com. All rights reserved. // import UIKit import QuartzCore /// A Image with circle mask @IBDesignable public class JHCircleImageView: UIView { let lineWidth = 10.0 var imageLayer: CALayer! /// image property you could assign image and see effective immediately through interface builder @IBInspectable public var image: UIImage! { didSet { updateLayerProperties() } } /** relayout layer */ public override func layoutSubviews() { if (imageLayer == nil) { let insetBounds = CGRectInset(bounds, 1, 1) let innerPath = UIBezierPath(ovalInRect: insetBounds) let imageMaskLayer = CAShapeLayer() imageMaskLayer.path = innerPath.CGPath imageMaskLayer.fillColor = UIColor.blackColor().CGColor imageMaskLayer.frame = bounds layer.addSublayer(imageMaskLayer) imageLayer = CALayer() imageLayer.mask = imageMaskLayer imageLayer.frame = bounds imageLayer.backgroundColor = UIColor.lightGrayColor().CGColor imageLayer.contentsGravity = kCAGravityResizeAspectFill layer.addSublayer(imageLayer) } imageLayer.frame = layer.bounds updateLayerProperties() } /** update layer after content changed */ public func updateLayerProperties() { if (imageLayer != nil) { if let i = image { imageLayer.contents = i.CGImage } } } }
mit
4845b62910c18a3636b3c68b6a602912
26.770492
101
0.60189
5.374603
false
false
false
false
JonathanAhrenkiel-Frellsen/WorkWith-fitnes
KomITEksamen/KomITEksamen/CelenderViewController.swift
1
3349
// // CelenderViewController.swift // KomITEksamen // // Created by Jonathans Macbook Pro on 26/04/2017. // Copyright © 2017 skycode. All rights reserved. // import UIKit import EventKit import FirebaseAuth import Firebase class CelenderViewController: UIViewController { var eventName = String() var eventStartDate = String() var eventEndDate = String() var activeDays = [String] () override func viewDidLoad() { super.viewDidLoad() let userID = FIRAuth.auth()?.currentUser?.uid // DataService.ds.REF_USER.child(userID!).observeSingleEvent(of: .value, with: { (snapshot) in // if let eventDict = snapshot.value as? Dictionary<String, AnyObject> { // let user = UsersModel(userData: eventDict) // // self.eventName = user.category // // // reformats the string date stored in firebase and formats it as Date // // alternativly i could have stored secundsSince 1970 in firebase af int, and format from there, but i'm lazy xd, this would also solve time zone problems //// let dateFormatter = DateFormatter() //// dateFormatter.dateFormat = "yyyy-MM-dd" //// //// let dateStart = dateFormatter.date(from: user.startDate) //// let dateEnd = dateFormatter.date(from: user.startDate) // // self.eventStartDate = user.startDate // self.eventEndDate = user.endDate // // self.activeDays = user.acriveDays.components(separatedBy: [","]) // // for day in self.activeDays { // let date = Date() // let formatter = DateFormatter() // // formatter.dateFormat = "dd.MM.yyyy" // // let currentDate = formatter.string(from: date) // // //self.getDayOfWeek(today: currentDate) // // print(currentDate) // } // } // }) func getDayOfWeek(today:String)->Int { let formatter = DateFormatter() formatter.dateFormat = "yyyy-MM-dd" let todayDate = formatter.date(from: today)! let myCalendar = NSCalendar(calendarIdentifier: NSCalendar.Identifier.gregorian)! let myComponents = myCalendar.components(.weekday, from: todayDate) let weekDay = myComponents.weekday return weekDay! } // let eventStore = EKEventStore(); // // if let calendarForEvent = eventStore.calendarWithIdentifier(self.calendar.calendarIdentifier) { // let newEvent = EKEvent(eventStore: eventStore) // // newEvent.calendar = calendarForEvent // newEvent.title = "Some Event Name" // newEvent.startDate = eventStartDate // newEvent.endDate = eventEndDate // } //let event = EKEvent(eventStore: eventStore) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
lgpl-3.0
3f6cf86487d397d31f1e82277ce35a0f
36.2
172
0.548984
4.930781
false
false
false
false
blockchain/My-Wallet-V3-iOS
Modules/FeatureNotificationPreferences/Tests/FeatureNotificationPreferencesUITests/FeatureNotificationPreferencesTestMocks.swift
1
842
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import Combine import Errors import FeatureNotificationPreferencesData import FeatureNotificationPreferencesDomain import FeatureNotificationPreferencesMocks class NotificationPreferencesRepositoryMock: NotificationPreferencesRepositoryAPI { // MARK: - Mock Properties var fetchSettingsCalled = false var updateCalled = false var fetchPreferencesSubject = CurrentValueSubject<[NotificationPreference], NetworkError>([]) func fetchPreferences() -> AnyPublisher<[NotificationPreference], NetworkError> { fetchSettingsCalled = true return fetchPreferencesSubject.eraseToAnyPublisher() } func update(preferences: UpdatedPreferences) -> AnyPublisher<Void, NetworkError> { updateCalled = true return .just(()) } }
lgpl-3.0
be0064833a8a09834ab7b47d1ccd56c3
31.346154
97
0.770511
6.05036
false
false
false
false
blockchain/My-Wallet-V3-iOS
Modules/FeatureNFT/Sources/FeatureNFTData/Core/Client/APIClient.swift
1
3005
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import Combine import Errors import FeatureNFTDomain import Foundation import NetworkKit import ToolKit public protocol FeatureNFTClientAPI { func fetchAssetsFromEthereumAddress( _ address: String ) -> AnyPublisher<Nft, NabuNetworkError> func fetchAssetsFromEthereumAddress( _ address: String, pageKey: String ) -> AnyPublisher<Nft, NabuNetworkError> func registerEmailForNFTViewWaitlist( _ email: String ) -> AnyPublisher<Void, NabuNetworkError> } public final class APIClient: FeatureNFTClientAPI { private enum Path { static let assets = [ "nft-market-api", "nft", "account_assets" ] static let waitlist = [ "explorer-gateway", "features", "subscribe" ] } fileprivate enum Parameter { static let cursor = "cursor" } // MARK: - Private Properties private let retailRequestBuilder: RequestBuilder private let retailNetworkAdapter: NetworkAdapterAPI private let defaultRequestBuilder: RequestBuilder private let defaultNetworkAdapter: NetworkAdapterAPI // MARK: - Setup public init( retailNetworkAdapter: NetworkAdapterAPI, defaultNetworkAdapter: NetworkAdapterAPI, retailRequestBuilder: RequestBuilder, defaultRequestBuilder: RequestBuilder ) { self.retailNetworkAdapter = retailNetworkAdapter self.retailRequestBuilder = retailRequestBuilder self.defaultNetworkAdapter = defaultNetworkAdapter self.defaultRequestBuilder = defaultRequestBuilder } // MARK: - FeatureNFTClientAPI public func fetchAssetsFromEthereumAddress( _ address: String ) -> AnyPublisher<Nft, NabuNetworkError> { let request = defaultRequestBuilder.get( // NOTE: Space here due to backend bug path: Path.assets + [address], contentType: .json )! return defaultNetworkAdapter.perform(request: request) } public func fetchAssetsFromEthereumAddress( _ address: String, pageKey: String ) -> AnyPublisher<Nft, NabuNetworkError> { let param = URLQueryItem( name: Parameter.cursor, value: pageKey ) let request = defaultRequestBuilder.get( path: Path.assets + [address], parameters: [param], contentType: .json )! return defaultNetworkAdapter.perform(request: request) } public func registerEmailForNFTViewWaitlist( _ email: String ) -> AnyPublisher<Void, NabuNetworkError> { let payload = ViewWaitlistRequest(email: email) let request = defaultRequestBuilder.post( path: Path.waitlist, body: try? JSONEncoder().encode(payload) )! return defaultNetworkAdapter.perform(request: request) } }
lgpl-3.0
e7571fd3ad3da55d49b2d1c5b4339055
27.884615
62
0.649467
5.197232
false
false
false
false
ljcoder2015/LJTool
LJTool/Color/DesignToken.swift
1
4875
// // DesignToken.swift // dreamCatcher // // Created by 雷军 on 2020/3/9. // Copyright © 2020 ljcoder. All rights reserved. // import UIKit public struct DesignToken { // Color public static let cd_1 = UIColor.lj.color(0x000000) public static let cg_1 = UIColor.lj.color(0x1c2029) public static let cg_2 = UIColor.lj.color(0x666666) public static let cg_3 = UIColor.lj.color(0x999999) public static let cg_4 = UIColor.lj.color(0xcccccc) public static let cg_5 = UIColor.lj.color(0xdfdfdf) public static let cg_6 = UIColor.lj.color(0xF5F5F5) public static let cg_9 = UIColor.lj.color(0x16161A) public static let cg_11 = UIColor.lj.color(0x25252B) public static let cg_12 = UIColor.lj.color(0x333337) public static let cg_13 = UIColor.lj.color(0x333333) public static let cg_17 = UIColor.lj.color(0x424245) public static let cg_18 = UIColor.lj.color(0x1d1d21) public static let cg_19 = UIColor.lj.color(0xbbbbbb) public static let cp_1 = UIColor.lj.color(0x1d1965) public static let cr_1 = UIColor.lj.color(r: 255, g: 28, b: 28) public static let cr_2 = UIColor.lj.color(0xFA799C) public static let cr_3 = UIColor.lj.color(0xE91E63) public static let cr_4 = UIColor.lj.color(0xFA5151) public static let cb_1 = UIColor.lj.color(0x3296FA) public static let cb_2 = UIColor.lj.color(0x272d3c) public static let cb_3 = UIColor.lj.color(0x194579) public static let cb_4 = UIColor.lj.color(0x0091ea) public static let cb_5 = UIColor.lj.color(0x10AEFF) public static let cgr_1 = UIColor.lj.color(0x1aad19) public static let cgr_2 = UIColor.lj.color(0x4CAF50) public static let cgr_3 = UIColor.lj.color(r: 109, g: 191, b: 102) public static let cy_1 = UIColor.lj.color(0xf5b906) public static let cy_2 = UIColor.lj.color(r: 227, g: 184, b: 43) public static let cy_3 = UIColor.lj.color(0xffd600) public static let cy_4 = UIColor.lj.color(0xFFC300) public static let cw_1 = UIColor.lj.color(0xffffff) public static let color_green_1: UIColor = UIColor.lj.color(0xDFF9CD) // 间距 public static let dim_1: CGFloat = 0 public static let dim_2: CGFloat = 1 public static let dim_3: CGFloat = 2 public static let dim_4: CGFloat = 3 public static let dim_5: CGFloat = 6 public static let dim_6: CGFloat = 9 public static let dim_7: CGFloat = 12 public static let dim_8: CGFloat = 15 public static let dim_9: CGFloat = 18 // 导角 public static let radius_large: CGFloat = 12 public static let radius_medium: CGFloat = 6 public static let radius_secondary_medium: CGFloat = 4 public static let radius_small: CGFloat = 2 public static let radius_angle: CGFloat = 0 // 文字大小 public static let font_size_big1: CGFloat = 18 public static let font_size_big2: CGFloat = 17 public static let font_size_big3: CGFloat = 16 public static let font_size_meddle1: CGFloat = 15 public static let font_size_meddle2: CGFloat = 14 } // MARK: UI配色 public extension DesignToken { // 品牌色 static let color_brand1_1 = UIColor.lj.color(0xEEF3F9) static let color_brand1_7 = UIColor.lj.color(0xFF8126) // 橙色 // public static let color_brand1_6 = UIColor.lj.color(r: 99, g: 174, b: 232) // 蓝色 static let color_brand1_6 = UIColor.lj.color(0xFE6A6D) // 红色 // public static let color_brand1_6 = UIColor.lj.color(r: 108, g: 192, b: 102) // 微信绿 static let color_brand1_9 = UIColor.lj.color(0x3E71F7) // 主题文字色 static let color_text_1 = UIColor.lj.color(0xffffff) // 分割线颜色 static let color_line_1 = UIColor.lj.color(0xeeeeee) } // MARK: 莫兰迪色 extension DesignToken { /// 0xc1cbd7 public static let color_Morandi_1: UIColor = UIColor.lj.color(r: 233, g: 241, b: 230, alpha: 1) /// 0xe0e5df public static let color_Morandi_2: UIColor = UIColor.lj.color(0xe0e5df) /// 0x9ca8b8 public static let color_Morandi_3: UIColor = UIColor.lj.color(r: 234, g: 234, b: 234, alpha: 1) /// 0xececea public static let color_Morandi_4: UIColor = UIColor.lj.color(0xececea) /// 0xfffaf4 public static let color_Morandi_5: UIColor = UIColor.lj.color(r: 254, g: 248, b: 207, alpha: 1) /// 0xfdf9ee public static let color_Morandi_6: UIColor = UIColor.lj.color(0xfdf9ee) /// 0xd3d4cc public static let color_Morandi_7: UIColor = UIColor.lj.color(r: 237, g: 237, b: 254, alpha: 1) /// 0xead0d1 public static let color_Morandi_8: UIColor = UIColor.lj.color(r: 251, g: 224, b: 223, alpha: 1) /// 0xfaead3 public static let color_Morandi_9: UIColor = UIColor.lj.color(0xfaead3) /// 0xf0ebe5 public static let color_Morandi_10: UIColor = UIColor.lj.color(0xf0ebe5) }
mit
49ada8db80f87477d96efc7074d63775
39.319328
99
0.675698
2.978274
false
false
false
false
jad6/CV
Swift/Jad's CV/Sections/ExtraCurricular/ExtraCurricularTableViewController.swift
1
1899
// // ExtraCurricularTableViewController.swift // Jad's CV // // Created by Jad Osseiran on 25/07/2014. // Copyright (c) 2014 Jad. All rights reserved. // import UIKit //FIXME: Generics //class ExtraCurricularTableViewController<T: ExtraCurricularActivity>: ExperienceTableViewController<T> { class ExtraCurricularTableViewController: ExperienceTableViewController { //MARK:- Properties //TODO: re-enable that once Swift supports class variables // private class let extraCurricularCellIdentifier = "Extra Curricular Cell" private class func extraCurricularCellIdentifier() -> String { return "Extra Curricular Cell" } //MARK:- Init override init(nibName nibNameOrNil: String!, bundle nibBundleOrNil: NSBundle!) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) } // init() { // super.init(style: .Plain, listData: ExtraCurricularActivity.extraCurricularActivitiesListData()) // // self.title = "Extra Curricular" // self.tableView.registerClass(ExtraCurricularTableViewCell.self, forCellReuseIdentifier: ExtraCurricularTableViewController.extraCurricularCellIdentifier()) // } //MARK:- Abstract Methods override func listView(listView: UIView, configureCell cell: UIView, withObject object: Any, atIndexPath indexPath: NSIndexPath) { super.listView(listView, configureCell: cell, withObject: object, atIndexPath: indexPath) if let activity = object as? ExtraCurricularActivity { if let tableCell = cell as? ExtraCurricularTableViewCell { tableCell.activityImageView.image = activity.organisationImage } } } override func cellIdentifierForIndexPath(indexPath: NSIndexPath) -> String { return ExtraCurricularTableViewController.extraCurricularCellIdentifier() } }
bsd-3-clause
ffd865422ea97fbedbc6e3ff0ff1a2f7
35.519231
165
0.7109
4.906977
false
false
false
false
san2ride/iOS10-FHG1.0
FHG1.1/FHG1.1/DNATableViewController.swift
1
1952
// // DNATableViewController.swift // FHG1.1 // // Created by don't touch me on 2/7/17. // Copyright © 2017 trvl, LLC. All rights reserved. // import UIKit class DNATableViewController: UITableViewController { override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 128, height: 42)) imageView.contentMode = .scaleAspectFit let image = UIImage(named: "fhgnew4") imageView.image = image navigationItem.titleView = imageView } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let url : URL? switch indexPath.section { case 0: switch indexPath.row { case 0: url = URL(string: "http://www.thefhguide.com/project-8-dna.html#goal-1") case 1: url = URL(string: "http://www.thefhguide.com/project-8-dna.html#goal-2") case 2: url = URL(string: "http://www.thefhguide.com/project-8-dna.html#goal-3") case 3: url = URL(string: "http://www.thefhguide.com/project-8-dna.html#goal-4") case 4: url = URL(string: "http://www.thefhguide.com/project-8-dna.html#goal-5") case 5: url = URL(string: "http://www.thefhguide.com/project-8-dna.html#goal-6") case 6: url = URL(string: "http://www.thefhguide.com/project-8-dna.html#goal-7") case 7: url = URL(string: "http://www.thefhguide.com/project-8-dna.html#goal-8") default: return; } default: return; } if url != nil { UIApplication.shared.open(url!, options: [:], completionHandler: nil) } } }
mit
4cb89699bffc94497208507b8342098b
30.467742
92
0.540748
3.933468
false
false
false
false
karwa/swift-corelibs-foundation
Foundation/NSAttributedString.swift
3
7454
// 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 class NSAttributedString : NSObject, NSCopying, NSMutableCopying, NSSecureCoding { private let _cfinfo = _CFInfo(typeID: CFAttributedStringGetTypeID()) private let _string: NSString private let _attributeArray: CFRunArrayRef public required init?(coder aDecoder: NSCoder) { NSUnimplemented() } public func encodeWithCoder(_ aCoder: NSCoder) { NSUnimplemented() } static public func supportsSecureCoding() -> Bool { return true } public override func copy() -> AnyObject { return copyWithZone(nil) } public func copyWithZone(_ zone: NSZone) -> AnyObject { NSUnimplemented() } public override func mutableCopy() -> AnyObject { return mutableCopyWithZone(nil) } public func mutableCopyWithZone(_ zone: NSZone) -> AnyObject { NSUnimplemented() } public var string: String { return _string._swiftObject } public func attributesAtIndex(_ location: Int, effectiveRange range: NSRangePointer) -> [String : AnyObject] { var cfRange = CFRange() return withUnsafeMutablePointer(&cfRange) { (rangePointer: UnsafeMutablePointer<CFRange>) -> [String : AnyObject] in // Get attributes value using CoreFoundation function let value = CFAttributedStringGetAttributes(_cfObject, location, rangePointer) // Convert the value to [String : AnyObject] let dictionary = unsafeBitCast(value, to: NSDictionary.self) var results = [String : AnyObject]() for (key, value) in dictionary { guard let stringKey = (key as? NSString)?._swiftObject else { continue } results[stringKey] = value } // Update effective range let hasAttrs = results.count > 0 range.pointee.location = hasAttrs ? rangePointer.pointee.location : NSNotFound range.pointee.length = hasAttrs ? rangePointer.pointee.length : 0 return results } } public var length: Int { return CFAttributedStringGetLength(_cfObject) } public func attribute(_ attrName: String, atIndex location: Int, effectiveRange range: NSRangePointer) -> AnyObject? { var cfRange = CFRange() return withUnsafeMutablePointer(&cfRange) { (rangePointer: UnsafeMutablePointer<CFRange>) -> AnyObject? in // Get attribute value using CoreFoundation function let attribute = CFAttributedStringGetAttribute(_cfObject, location, attrName._cfObject, rangePointer) // Update effective range and return the result if let attribute = attribute { range.pointee.location = rangePointer.pointee.location range.pointee.length = rangePointer.pointee.length return attribute } else { range.pointee.location = NSNotFound range.pointee.length = 0 return nil } } } public func attributedSubstringFromRange(_ range: NSRange) -> NSAttributedString { NSUnimplemented() } public func attributesAtIndex(_ location: Int, longestEffectiveRange range: NSRangePointer, inRange rangeLimit: NSRange) -> [String : AnyObject] { NSUnimplemented() } public func attribute(_ attrName: String, atIndex location: Int, longestEffectiveRange range: NSRangePointer, inRange rangeLimit: NSRange) -> AnyObject? { NSUnimplemented() } public func isEqualToAttributedString(_ other: NSAttributedString) -> Bool { NSUnimplemented() } public init(string str: String) { _string = str._nsObject _attributeArray = CFRunArrayCreate(kCFAllocatorDefault) super.init() addAttributesToAttributeArray(attrs: nil) } public init(string str: String, attributes attrs: [String : AnyObject]?) { _string = str._nsObject _attributeArray = CFRunArrayCreate(kCFAllocatorDefault) super.init() addAttributesToAttributeArray(attrs: attrs) } public init(attributedString attrStr: NSAttributedString) { NSUnimplemented() } private func addAttributesToAttributeArray(attrs: [String : AnyObject]?) { guard _string.length > 0 else { return } let range = CFRange(location: 0, length: _string.length) if let attrs = attrs { CFRunArrayInsert(_attributeArray, range, attrs._cfObject) } else { let emptyAttrs = [String : AnyObject]() CFRunArrayInsert(_attributeArray, range, emptyAttrs._cfObject) } } public func enumerateAttributesInRange(_ enumerationRange: NSRange, options opts: NSAttributedStringEnumerationOptions, usingBlock block: ([String : AnyObject], NSRange, UnsafeMutablePointer<ObjCBool>) -> Void) { NSUnimplemented() } public func enumerateAttribute(_ attrName: String, inRange enumerationRange: NSRange, options opts: NSAttributedStringEnumerationOptions, usingBlock block: (AnyObject?, NSRange, UnsafeMutablePointer<ObjCBool>) -> Void) { NSUnimplemented() } } extension NSAttributedString: _CFBridgable { internal var _cfObject: CFAttributedString { return unsafeBitCast(self, to: CFAttributedString.self) } } public struct NSAttributedStringEnumerationOptions : OptionSet { public let rawValue : UInt public init(rawValue: UInt) { self.rawValue = rawValue } public static let Reverse = NSAttributedStringEnumerationOptions(rawValue: 1 << 1) public static let LongestEffectiveRangeNotRequired = NSAttributedStringEnumerationOptions(rawValue: 1 << 20) } public class NSMutableAttributedString : NSAttributedString { public func replaceCharactersInRange(_ range: NSRange, withString str: String) { NSUnimplemented() } public func setAttributes(_ attrs: [String : AnyObject]?, range: NSRange) { NSUnimplemented() } public var mutableString: NSMutableString { NSUnimplemented() } public func addAttribute(_ name: String, value: AnyObject, range: NSRange) { NSUnimplemented() } public func addAttributes(_ attrs: [String : AnyObject], range: NSRange) { NSUnimplemented() } public func removeAttribute(_ name: String, range: NSRange) { NSUnimplemented() } public func replaceCharactersInRange(_ range: NSRange, withAttributedString attrString: NSAttributedString) { NSUnimplemented() } public func insertAttributedString(_ attrString: NSAttributedString, atIndex loc: Int) { NSUnimplemented() } public func appendAttributedString(_ attrString: NSAttributedString) { NSUnimplemented() } public func deleteCharactersInRange(_ range: NSRange) { NSUnimplemented() } public func setAttributedString(_ attrString: NSAttributedString) { NSUnimplemented() } public func beginEditing() { NSUnimplemented() } public func endEditing() { NSUnimplemented() } }
apache-2.0
707d82f91d7497e791c7d0b860cb8293
41.594286
244
0.673598
5.73826
false
false
false
false
LX314/GitHubApp
NetWorking/LXNetworking.swift
1
6056
// // LXNetworking.swift // MyGitHub // // Created by John LXThyme on 2017/3/28. // Copyright © 2017年 John LXThyme. All rights reserved. // import UIKit import Alamofire class LXNetworking: NSObject { func initNetworking() { var manager: SessionManager? = nil let config: URLSessionConfiguration = URLSessionConfiguration.default config.timeoutIntervalForRequest = 15; manager = SessionManager(configuration: config) // manager?.request(<#T##url: URLConvertible##URLConvertible#>) } class func get(path: String, param: [String: Any], completion: @escaping(Any) ->Void) { self.request(method: .get, path: path, param: param, completion: completion) } class func post(path: String, param: [String: Any], completion: @escaping(Any) ->Void) { self.request(method: .post, path: path, param: param, completion: completion) } class func post(path: String, param: [String: Any], headers: [String: String], completion: @escaping(Any) ->Void) { self.request(method: .post, path: path, param: param, headers: headers, completion: completion) } /** "Access-Control-Allow-Origin" = "*"; "Access-Control-Expose-Headers" = "ETag, Link, X-GitHub-OTP, X-RateLimit-Limit, X-RateLimit-Remaining, X-RateLimit-Reset, X-OAuth-Scopes, X-Accepted-OAuth-Scopes, X-Poll-Interval"; "Cache-Control" = "private, max-age=60, s-maxage=60"; "Content-Encoding" = gzip; "Content-Security-Policy" = "default-src 'none'"; "Content-Type" = "application/json; charset=utf-8"; Date = "Tue, 28 Mar 2017 13:42:50 GMT"; Etag = "W/\"9bf54ce26b66a6e449bd39a6cdafe32d\""; Link = "<https://api.github.com/user/starred?access_token=a0e54de5f998ef030252ba39ef9e394d91d51958&page=2>; rel=\"next\", <https://api.github.com/user/starred?access_token=a0e54de5f998ef030252ba39ef9e394d91d51958&page=29>; rel=\"last\""; Server = "GitHub.com"; Status = "200 OK"; "Strict-Transport-Security" = "max-age=31536000; includeSubdomains; preload"; "Transfer-Encoding" = Identity; Vary = "Accept, Authorization, Cookie, X-GitHub-OTP, Accept-Encoding"; "X-Accepted-OAuth-Scopes" = ""; "X-Content-Type-Options" = nosniff; "X-Frame-Options" = deny; "X-GitHub-Media-Type" = "github.v3; format=json"; "X-GitHub-Request-Id" = "937E:1046C:673FFF:812E94:58DA6858"; "X-OAuth-Client-Id" = 86c2568b2f7c6400fa0c; "X-OAuth-Scopes" = "gist, repo, user"; "X-RateLimit-Limit" = 5000; "X-RateLimit-Remaining" = 4999; "X-RateLimit-Reset" = 1490712170; "X-Served-By" = 7efb7ae49588ef0269c6a1c1bd3721d9; "X-XSS-Protection" = "1; mode=block"; */ class func request(method: HTTPMethod, path: String, param: [String: Any], completion: @escaping(Any) ->Void) { Alamofire.request(path, method: method, parameters: param) .responseJSON { (response) in debugPrint("result:\(response.result)") switch response.result { case .success: let jsonObj = response.result.value! completion(jsonObj) case .failure(let error): judgeErrorType(response: response) assert(true, "ERROR:\(error)") } } } class func request(method: HTTPMethod, path: String, param: [String: Any], headers: [String: String], completion: @escaping(Any) ->Void) { Alamofire.request(path, method: method, parameters: param, encoding: JSONEncoding.prettyPrinted, headers: headers) .responseJSON { (response) in debugPrint("result:\(response.result)") switch response.result { case .success: let jsonObj = response.result.value! completion(jsonObj) case .failure(let error): judgeErrorType(response: response) assert(true, "ERROR:\(error)") } } } class func judgeErrorType(response: DataResponse<Any>) { guard case let .failure(error) = response.result else { return } if let error = error as? AFError { switch error { case .invalidURL(let url): print("Invalid URL: \(url) - \(error.localizedDescription)") case .parameterEncodingFailed(let reason): print("Parameter encoding failed: \(error.localizedDescription)") print("Failure Reason: \(reason)") case .multipartEncodingFailed(let reason): print("Multipart encoding failed: \(error.localizedDescription)") print("Failure Reason: \(reason)") case .responseValidationFailed(let reason): print("Response validation failed: \(error.localizedDescription)") print("Failure Reason: \(reason)") switch reason { case .dataFileNil, .dataFileReadFailed: print("Downloaded file could not be read") case .missingContentType(let acceptableContentTypes): print("Content Type Missing: \(acceptableContentTypes)") case .unacceptableContentType(let acceptableContentTypes, let responseContentType): print("Response content type: \(responseContentType) was unacceptable: \(acceptableContentTypes)") case .unacceptableStatusCode(let code): print("Response status code was unacceptable: \(code)") } case .responseSerializationFailed(let reason): print("Response serialization failed: \(error.localizedDescription)") print("Failure Reason: \(reason)") } print("Underlying error: \(error.underlyingError)") } else if let error = error as? URLError { print("URLError occurred: \(error)") } else { print("Unknown error: \(error)") } } }
mit
737da8cbd53202bf59fffc396d491b5c
46.661417
242
0.610111
4.171606
false
false
false
false
inamiy/VTree
Sources/Text.swift
1
721
public enum Text { case text(String) case attributedText(NSAttributedString) } extension Text { var text: String? { guard case let .text(text) = self else { return nil } return text } var attributedText: NSAttributedString? { guard case let .attributedText(attributedText) = self else { return nil } return attributedText } } extension Text: ExpressibleByStringLiteral { public init(stringLiteral value: String) { self = .text(value) } public init(extendedGraphemeClusterLiteral value: String) { self = .text(value) } public init(unicodeScalarLiteral value: String) { self = .text(value) } }
mit
b80eac26fd77007762b7a7d5291b485c
17.973684
81
0.628294
4.534591
false
false
false
false
revealapp/Revert
Shared/Sources/Static.swift
1
980
// // Copyright © 2015 Itty Bitty Apps. All rights reserved. import Foundation import MapKit struct Static { struct Formatter { static var ddmmyy: DateFormatter = { let dateFormatter = DateFormatter() dateFormatter.dateFormat = "dd MMM YYYY" return dateFormatter }() static var decimal: NumberFormatter = { let numberFormatter = NumberFormatter() numberFormatter.alwaysShowsDecimalSeparator = true numberFormatter.locale = Locale.current numberFormatter.maximumFractionDigits = 2 numberFormatter.minimumFractionDigits = 1 numberFormatter.minimumIntegerDigits = 1 return numberFormatter }() } struct Region { static let Australia: MKCoordinateRegion = { let center = CLLocationCoordinate2D(latitude: -24.291451, longitude: 134.126772) let span = MKCoordinateSpan(latitudeDelta: 50, longitudeDelta: 50) return MKCoordinateRegion(center: center, span: span) }() } }
bsd-3-clause
a061e71bc0594ab10a8661399bb8b7ef
27.794118
86
0.706844
5.207447
false
false
false
false
eliasbagley/Pesticide
debugdrawer/TouchTrackerView.swift
1
1481
// // CrosshairOverlay.swift // debugdrawer // // Created by Elias Bagley on 11/22/14. // Copyright (c) 2014 Rocketmade. All rights reserved. // import Foundation let radius:CGFloat = 15 class TouchTrackerView : UIView { let circle : UIView = UIView() required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override init(frame: CGRect) { circle = UIView() super.init(frame: frame) circle.backgroundColor = UIColor(red: 1, green: 1, blue: 1, alpha: 0.9) circle.layer.cornerRadius = radius/2 circle.layer.borderColor = UIColor.grayColor().CGColor circle.layer.borderWidth = 1 circle.alpha = 0 circle.setTranslatesAutoresizingMaskIntoConstraints(false) circle.frame = CGRectMake(0, 0, radius, radius) self.addSubview(circle) } // pass touches though this overlay view override func pointInside(point: CGPoint, withEvent event: UIEvent?) -> Bool { self.setFramesFromPoint(point) showCircle() hideCircle() return false } func setFramesFromPoint(point: CGPoint) { circle.frame = CGRectMake(point.x, point.y, radius, radius) } func showCircle() { self.circle.alpha = 1; } func hideCircle() { UIView.animateWithDuration(0.15, delay: 0.1, options: .CurveEaseIn, animations: { () -> Void in self.circle.alpha = 0 }, completion: nil) } }
mit
1ccfcaa8dba6a62cdb756fba9c601c4a
24.101695
103
0.629305
4.102493
false
false
false
false
osorioabel/checklist-app
checklist-app/checklist-app/Models/Checklist.swift
1
1216
// // Checklist.swift // checklist-app // // Created by Abel Osorio on 2/16/16. // Copyright © 2016 Abel Osorio. All rights reserved. // import UIKit class Checklist: NSObject, NSCoding { var name = "" var items = [CheckListItem]() var iconName: String convenience init(name: String) { self.init(name: name, iconName: "No Icon") } init(name: String, iconName: String) { self.name = name self.iconName = iconName super.init() } required init?(coder aDecoder: NSCoder) { name = aDecoder.decodeObjectForKey("Name") as! String items = aDecoder.decodeObjectForKey("Items") as! [CheckListItem] iconName = aDecoder.decodeObjectForKey("IconName") as! String super.init() } func encodeWithCoder(aCoder: NSCoder) { aCoder.encodeObject(name, forKey: "Name") aCoder.encodeObject(items, forKey: "Items") aCoder.encodeObject(iconName, forKey: "IconName") } func countUncheckedItems() -> Int { var count = 0 for item in items where !item.checked { count += 1 } return count } }
mit
876c4d338b798b442bf41d2f996f1453
22.823529
72
0.58107
4.386282
false
false
false
false
nathanborror/NBKit
NBKit/NBKit/UI Elements/NBLabel.swift
1
1136
/* NBLabel.swift NBKit Created by Nathan Borror on 10/27/14. Copyright (c) 2014 Nathan Borror. All rights reserved. Abstract: The `NBLabel` offers a simpler way to create UILabels with padding. */ import UIKit public class NBLabel: UILabel { public var padding:UIEdgeInsets? override public func drawTextInRect(rect: CGRect) { guard let padding = self.padding else { return } return super.drawTextInRect(UIEdgeInsetsInsetRect(rect, padding)) } override public func textRectForBounds(bounds: CGRect, limitedToNumberOfLines numberOfLines: Int) -> CGRect { guard let padding = self.padding else { return super.textRectForBounds(bounds, limitedToNumberOfLines: numberOfLines) } var rect = super.textRectForBounds(UIEdgeInsetsInsetRect(bounds, padding), limitedToNumberOfLines: numberOfLines) rect.origin.x += padding.left rect.origin.y += padding.top rect.size.width += (padding.left + padding.right) rect.size.height += (padding.top + padding.bottom) return rect } }
bsd-3-clause
ffdedb506cdff1b95b646c4ca9d07a01
29.702703
121
0.672535
4.580645
false
false
false
false
danielmartin/swift
test/Driver/Dependencies/one-way-while-editing.swift
3
1870
/// other ==> main // RUN: %empty-directory(%t) // RUN: cp -r %S/Inputs/one-way/* %t // RUN: touch -t 201401240005 %t/* // RUN: cd %t && not %swiftc_driver -c -driver-use-frontend-path %S/Inputs/modify-non-primary-files.py -output-file-map %t/output.json -incremental -driver-always-rebuild-dependents ./main.swift ./other.swift -module-name main -j1 -v 2>&1 | %FileCheck %s // CHECK: Handled main.swift // CHECK: Handled other.swift // CHECK-NOT: error // CHECK: error: input file 'other.swift' was modified during the build // CHECK-NOT: error // RUN: cd %t && %swiftc_driver -c -driver-use-frontend-path %S/Inputs/update-dependencies.py -output-file-map %t/output.json -incremental -driver-always-rebuild-dependents ./main.swift ./other.swift -module-name main -j1 -v 2>&1 | %FileCheck -check-prefix=CHECK-RECOVER %s // CHECK-RECOVER: Handled main.swift // CHECK-RECOVER: Handled other.swift // RUN: touch -t 201401240005 %t/* // RUN: cd %t && not %swiftc_driver -c -driver-use-frontend-path %S/Inputs/modify-non-primary-files.py -output-file-map %t/output.json -incremental -driver-always-rebuild-dependents ./other.swift ./main.swift -module-name main -j1 -v 2>&1 | %FileCheck -check-prefix=CHECK-REVERSED %s // CHECK-REVERSED: Handled other.swift // CHECK-REVERSED: Handled main.swift // CHECK-REVERSED-NOT: error // CHECK-REVERSED: error: input file 'main.swift' was modified during the build // CHECK-REVERSED-NOT: error // RUN: cd %t && %swiftc_driver -c -driver-use-frontend-path %S/Inputs/update-dependencies.py -output-file-map %t/output.json -incremental -driver-always-rebuild-dependents ./main.swift ./other.swift -module-name main -j1 -v 2>&1 | %FileCheck -check-prefix=CHECK-REVERSED-RECOVER %s // CHECK-REVERSED-RECOVER-NOT: Handled other.swift // CHECK-REVERSED-RECOVER: Handled main.swift // CHECK-REVERSED-RECOVER-NOT: Handled other.swift
apache-2.0
9fc12fa82fa023e78376a3cbb4c6745c
54
283
0.724599
3.080725
false
false
true
false
0x7fffffff/Stone
Sources/Event.swift
2
2509
// // PhoenixEvent.swift // Stone // // Created by Michael MacCallum on 5/19/16. // Copyright © 2016 Tethr. All rights reserved. // import Unbox import Wrap import Foundation public func == (lhs: Event, rhs: Event) -> Bool { return lhs.rawValue == rhs.rawValue } public func == (lhs: Event, rhs: Event.PhoenixEvent) -> Bool { return lhs.rawValue == rhs.rawValue } public func != (lhs: Event, rhs: Event.PhoenixEvent) -> Bool { return !(lhs == rhs) } /** Used to represent any event received from a Phoenix server. Covers default events that the server may send such as "phx_join" or "phx_reply", as well as presence related events, and the ability to specify custom events. The full list of built in events is as follows. - Join - Reply - Leave - Close - Error - Heartbeat - State - Diff - Default - Presence - Custom */ public enum Event: RawRepresentable, Hashable, Equatable, CustomStringConvertible { public enum PhoenixEvent: String { case Join = "phx_join" case Reply = "phx_reply" case Leave = "phx_leave" case Close = "phx_close" case Error = "phx_error" case Heartbeat = "heartbeat" public enum PresenceEvent: String { case State = "presence_state" case Diff = "presence_diff" } } case phoenix(PhoenixEvent) case presence(PhoenixEvent.PresenceEvent) case custom(String) public var description: String { return rawValue } public var isDefault: Bool { return PhoenixEvent(rawValue: rawValue) != nil } public var rawValue: String { switch self { case .phoenix(let known): return known.rawValue case .presence(let presence): return presence.rawValue case .custom(let str): return str } } public var hashValue: Int { return rawValue.hashValue } public init?(rawValue: String) { if let def = PhoenixEvent(rawValue: rawValue) { self = .phoenix(def) } else if let presence = PhoenixEvent.PresenceEvent(rawValue: rawValue) { self = .presence(presence) } else { self = .custom(rawValue) } } } extension Event: UnboxableRawType { public static func unboxFallbackValue() -> Stone.Event { return .custom("") } public static func transform(unboxedNumber: NSNumber) -> Event? { return nil } public static func transform(_ unboxedInt: Int) -> Event? { return nil } public static func transform(unboxedString: String) -> Event? { return Stone.Event(rawValue: unboxedString) } } extension Stone.Event: WrappableEnum { public func wrap() -> AnyObject? { return rawValue as AnyObject? } }
mit
9e78b9f70f16de78028706cafdd2ca52
20.254237
112
0.699761
3.308707
false
false
false
false
OrlSan/ASViewControllerSwift
Sample/DetailCellNode.swift
1
1356
// // DetailCellNode.swift // Sample // // Created by Orlando on 22/07/17. // Copyright © 2017 Orlando. All rights reserved. // import UIKit import AsyncDisplayKit class DetailCellNode: ASCellNode { var row: Int = 0 var imageCategory: String = "abstract" var imageNode: ASNetworkImageNode? // The image URL private var imageURL: URL { get { let imageSize: CGSize = self.calculatedSize let urlWith = Int(imageSize.width) let urlHeight = Int(imageSize.height) return URL(string: "https://lorempixel.com/\(urlWith)/\(urlHeight)/\(imageCategory)/\(row)")! } } required init(coder aDecoder: NSCoder) { fatalError("Texture doest not support Storyboards") } override init() { super.init() self.automaticallyManagesSubnodes = true self.imageNode = ASNetworkImageNode() self.imageNode?.backgroundColor = ASDisplayNodeDefaultPlaceholderColor() } //MARK - ASDisplayNode override func layoutSpecThatFits(_ constrainedSize: ASSizeRange) -> ASLayoutSpec { return ASRatioLayoutSpec.init(ratio: 1.0, child: self.imageNode!) } override func layoutDidFinish() { super.layoutDidFinish() self.imageNode?.url = self.imageURL } }
mit
d9dd5c332dda396594a771d191ae3788
25.568627
105
0.626568
4.804965
false
false
false
false
danielpi/NSOutlineViewInSwift
NSSourceListInSwift/NSSourceListInSwift/Model.swift
1
3106
// // Model.swift // NSSourceListInSwift // // Created by Daniel Pink on 2/12/2014. // Copyright (c) 2014 Electronic Innovations. All rights reserved. // import Cocoa // It is important that every object in the model that will be // displayed in the source list can be identified and can be // used to create the table cell view by itself. // This protocol is used to determine how a particular item displays. Since all // model objects inherit from it, we do not need to perform a case-by-case setup // of our source table cells. It also makes the model expandable - we can add // more taxanomical rankings at any time so long as they conform to the protocol. protocol SourceListItemDisplayable: class { var name: String { get } var icon: NSImage? { get } func cellID() -> String func count() -> Int func childAtIndex(index: Int) -> SourceListItemDisplayable? } // By making count and cellID functions, we can add default implementations to // the protocol. Any object that implements the protocol but does not implement // the associated method will use these defaults. This cannot be done with stored // properties since these cannot be placed into extensions. extension SourceListItemDisplayable { func cellID() -> String { return "DataCell" } func count() -> Int { return 0 } func childAtIndex(index: Int) -> SourceListItemDisplayable? { return nil } } // If the model objects don't subclass NSObject the program tends to crash. class Life: NSObject, SourceListItemDisplayable { let name: String var genus: [Genus] = [] let icon: NSImage? = nil init(name: String) { self.name = name super.init() } func cellID() -> String { return "HeaderCell" } func count() -> Int { return genus.count } func childAtIndex(index: Int) -> SourceListItemDisplayable? { return genus[index] } } class Genus: NSObject, SourceListItemDisplayable { let name: String var species: [Species] = [] let icon: NSImage? init(name: String, icon: NSImage?) { self.name = name self.icon = icon super.init() } func count() -> Int { return species.count } func childAtIndex(index: Int) -> SourceListItemDisplayable? { return species[index] } } class Species: NSObject, SourceListItemDisplayable { let name: String let genus: Genus let icon: NSImage? init(name: String, icon: NSImage?, genus: Genus) { self.name = name self.genus = genus self.icon = icon super.init() genus.species.append(self) } } // NOTE: I would personally remove the above model and replace it with something like this: enum TaxonomyType { case Life, Domain, Kingdom, Phylum, Class, Order, Family, Genus, Species } class TaxonomyItem: NSObject { let name: String let type: TaxonomyType let icon: NSImage? var children = [TaxonomyItem]() init(name: String, type: TaxonomyType, icon: NSImage?, parent: TaxonomyItem?) { self.name = name self.type = type self.icon = icon super.init() if let parent = parent { parent.children.append(self) } } }
mit
e19230f5da8f7e5f6b29f9b6ed12db5d
24.891667
91
0.689955
3.68446
false
false
false
false
codestergit/swift
test/SILGen/objc_bridging_any.swift
2
43323
// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -emit-silgen %s | %FileCheck %s // REQUIRES: objc_interop import Foundation import objc_generics protocol P {} protocol CP: class {} struct KnownUnbridged {} // CHECK-LABEL: sil hidden @_T017objc_bridging_any11passingToId{{.*}}F func passingToId<T: CP, U>(receiver: NSIdLover, string: String, nsString: NSString, object: AnyObject, classGeneric: T, classExistential: CP, generic: U, existential: P, error: Error, any: Any, knownUnbridged: KnownUnbridged, optionalA: String?, optionalB: NSString?, optionalC: Any?) { // CHECK: bb0([[SELF:%.*]] : $NSIdLover, // CHECK: debug_value [[STRING:%.*]] : $String // CHECK: debug_value [[NSSTRING:%.*]] : $NSString // CHECK: debug_value [[OBJECT:%.*]] : $AnyObject // CHECK: debug_value [[CLASS_GENERIC:%.*]] : $T // CHECK: debug_value [[CLASS_EXISTENTIAL:%.*]] : $CP // CHECK: debug_value_addr [[GENERIC:%.*]] : $*U // CHECK: debug_value_addr [[EXISTENTIAL:%.*]] : $*P // CHECK: debug_value [[ERROR:%.*]] : $Error // CHECK: debug_value_addr [[ANY:%.*]] : $*Any // CHECK: debug_value [[KNOWN_UNBRIDGED:%.*]] : $KnownUnbridged // CHECK: debug_value [[OPT_STRING:%.*]] : $Optional<String> // CHECK: debug_value [[OPT_NSSTRING:%.*]] : $Optional<NSString> // CHECK: debug_value_addr [[OPT_ANY:%.*]] : $*Optional<Any> // CHECK: [[BORROWED_SELF:%.*]] = begin_borrow [[SELF]] // CHECK: [[METHOD:%.*]] = class_method [volatile] [[BORROWED_SELF]] // CHECK: [[BORROWED_STRING:%.*]] = begin_borrow [[STRING]] // CHECK: [[STRING_COPY:%.*]] = copy_value [[BORROWED_STRING]] // CHECK: [[BRIDGE_STRING:%.*]] = function_ref @_T0SS10FoundationE19_bridgeToObjectiveCSo8NSStringCyF // CHECK: [[BORROWED_STRING_COPY:%.*]] = begin_borrow [[STRING_COPY]] // CHECK: [[BRIDGED:%.*]] = apply [[BRIDGE_STRING]]([[BORROWED_STRING_COPY]]) // CHECK: [[ANYOBJECT:%.*]] = init_existential_ref [[BRIDGED]] : $NSString : $NSString, $AnyObject // CHECK: end_borrow [[BORROWED_STRING_COPY]] from [[STRING_COPY]] // CHECK: destroy_value [[STRING_COPY]] // CHECK: end_borrow [[BORROWED_STRING]] from [[STRING]] // CHECK: apply [[METHOD]]([[ANYOBJECT]], [[BORROWED_SELF]]) // CHECK: destroy_value [[ANYOBJECT]] // CHECK: end_borrow [[BORROWED_SELF]] from [[SELF]] receiver.takesId(string) // CHECK: [[BORROWED_SELF:%.*]] = begin_borrow [[SELF]] // CHECK: [[METHOD:%.*]] = class_method [volatile] [[BORROWED_SELF]] : $NSIdLover, // CHECK: [[BORROWED_NSSTRING:%.*]] = begin_borrow [[NSSTRING]] // CHECK: [[NSSTRING_COPY:%.*]] = copy_value [[BORROWED_NSSTRING]] // CHECK: [[ANYOBJECT:%.*]] = init_existential_ref [[NSSTRING_COPY]] : $NSString : $NSString, $AnyObject // CHECK: end_borrow [[BORROWED_NSSTRING]] from [[NSSTRING]] // CHECK: apply [[METHOD]]([[ANYOBJECT]], [[BORROWED_SELF]]) // CHECK: destroy_value [[ANYOBJECT]] // CHECK: end_borrow [[BORROWED_SELF]] from [[SELF]] receiver.takesId(nsString) // CHECK: [[BORROWED_SELF:%.*]] = begin_borrow [[SELF]] // CHECK: [[METHOD:%.*]] = class_method [volatile] [[BORROWED_SELF]] : $NSIdLover, // CHECK: [[BORROWED_CLASS_GENERIC:%.*]] = begin_borrow [[CLASS_GENERIC]] // CHECK: [[CLASS_GENERIC_COPY:%.*]] = copy_value [[BORROWED_CLASS_GENERIC]] // CHECK: [[ANYOBJECT:%.*]] = init_existential_ref [[CLASS_GENERIC_COPY]] : $T : $T, $AnyObject // CHECK: end_borrow [[BORROWED_CLASS_GENERIC]] from [[CLASS_GENERIC]] // CHECK: apply [[METHOD]]([[ANYOBJECT]], [[BORROWED_SELF]]) // CHECK: destroy_value [[ANYOBJECT]] // CHECK: end_borrow [[BORROWED_SELF]] from [[SELF]] receiver.takesId(classGeneric) // CHECK: [[BORROWED_SELF:%.*]] = begin_borrow [[SELF]] // CHECK: [[METHOD:%.*]] = class_method [volatile] [[BORROWED_SELF]] : $NSIdLover, // CHECK: [[BORROWED_OBJECT:%.*]] = begin_borrow [[OBJECT]] // CHECK: [[OBJECT_COPY:%.*]] = copy_value [[BORROWED_OBJECT]] // CHECK: end_borrow [[BORROWED_OBJECT]] from [[OBJECT]] // CHECK: apply [[METHOD]]([[OBJECT_COPY]], [[BORROWED_SELF]]) // CHECK: destroy_value [[OBJECT_COPY]] // CHECK: end_borrow [[BORROWED_SELF]] from [[SELF]] receiver.takesId(object) // CHECK: [[BORROWED_SELF:%.*]] = begin_borrow [[SELF]] // CHECK: [[METHOD:%.*]] = class_method [volatile] [[BORROWED_SELF]] : $NSIdLover, // CHECK: [[BORROWED_CLASS_EXISTENTIAL:%.*]] = begin_borrow [[CLASS_EXISTENTIAL]] // CHECK: [[CLASS_EXISTENTIAL_COPY:%.*]] = copy_value [[BORROWED_CLASS_EXISTENTIAL]] // CHECK: [[OPENED:%.*]] = open_existential_ref [[CLASS_EXISTENTIAL_COPY]] : $CP // CHECK: [[ANYOBJECT:%.*]] = init_existential_ref [[OPENED]] // CHECK: end_borrow [[BORROWED_CLASS_EXISTENTIAL]] from [[CLASS_EXISTENTIAL]] // CHECK: apply [[METHOD]]([[ANYOBJECT]], [[BORROWED_SELF]]) // CHECK: destroy_value [[ANYOBJECT]] // CHECK: end_borrow [[BORROWED_SELF]] from [[SELF]] receiver.takesId(classExistential) // These cases perform a universal bridging conversion. // CHECK: [[BORROWED_SELF:%.*]] = begin_borrow [[SELF]] // CHECK: [[METHOD:%.*]] = class_method [volatile] [[BORROWED_SELF]] : $NSIdLover, // CHECK: [[COPY:%.*]] = alloc_stack $U // CHECK: copy_addr [[GENERIC]] to [initialization] [[COPY]] // CHECK: // function_ref _bridgeAnythingToObjectiveC // CHECK: [[BRIDGE_ANYTHING:%.*]] = function_ref // CHECK: [[ANYOBJECT:%.*]] = apply [[BRIDGE_ANYTHING]]<U>([[COPY]]) // CHECK: dealloc_stack [[COPY]] // CHECK: apply [[METHOD]]([[ANYOBJECT]], [[BORROWED_SELF]]) // CHECK: destroy_value [[ANYOBJECT]] // CHECK: end_borrow [[BORROWED_SELF]] from [[SELF]] receiver.takesId(generic) // CHECK: [[BORROWED_SELF:%.*]] = begin_borrow [[SELF]] // CHECK: [[METHOD:%.*]] = class_method [volatile] [[BORROWED_SELF]] : $NSIdLover, // CHECK: [[COPY:%.*]] = alloc_stack $P // CHECK: copy_addr [[EXISTENTIAL]] to [initialization] [[COPY]] // CHECK: [[OPENED_COPY:%.*]] = open_existential_addr immutable_access [[COPY]] : $*P to $*[[OPENED_TYPE:@opened.*P]], // CHECK: [[TMP:%.*]] = alloc_stack $[[OPENED_TYPE]] // CHECK: copy_addr [[OPENED_COPY]] to [initialization] [[TMP]] // CHECK: // function_ref _bridgeAnythingToObjectiveC // CHECK: [[BRIDGE_ANYTHING:%.*]] = function_ref // CHECK: [[ANYOBJECT:%.*]] = apply [[BRIDGE_ANYTHING]]<[[OPENED_TYPE]]>([[TMP]]) // CHECK: dealloc_stack [[TMP]] // CHECK: destroy_addr [[COPY]] // CHECK: dealloc_stack [[COPY]] // CHECK: apply [[METHOD]]([[ANYOBJECT]], [[BORROWED_SELF]]) // CHECK: destroy_value [[ANYOBJECT]] // CHECK: end_borrow [[BORROWED_SELF]] from [[SELF]] receiver.takesId(existential) // CHECK: [[BORROWED_SELF:%.*]] = begin_borrow [[SELF]] // CHECK: [[METHOD:%.*]] = class_method [volatile] [[BORROWED_SELF]] : $NSIdLover, // CHECK: [[BORROWED_ERROR:%.*]] = begin_borrow [[ERROR]] // CHECK: [[ERROR_COPY:%.*]] = copy_value [[BORROWED_ERROR]] : $Error // CHECK: [[ERROR_BOX:%[0-9]+]] = open_existential_box [[ERROR_COPY]] : $Error to $*@opened([[ERROR_ARCHETYPE:"[^"]*"]]) Error // CHECK: [[ERROR_STACK:%[0-9]+]] = alloc_stack $@opened([[ERROR_ARCHETYPE]]) Error // CHECK: copy_addr [[ERROR_BOX]] to [initialization] [[ERROR_STACK]] : $*@opened([[ERROR_ARCHETYPE]]) Error // CHECK: [[BRIDGE_FUNCTION:%[0-9]+]] = function_ref @_T0s27_bridgeAnythingToObjectiveCs9AnyObject_pxlF // CHECK: [[BRIDGED_ERROR:%[0-9]+]] = apply [[BRIDGE_FUNCTION]]<@opened([[ERROR_ARCHETYPE]]) Error>([[ERROR_STACK]]) // CHECK: dealloc_stack [[ERROR_STACK]] : $*@opened([[ERROR_ARCHETYPE]]) Error // CHECK: destroy_value [[ERROR_COPY]] : $Error // CHECK: end_borrow [[BORROWED_ERROR]] from [[ERROR]] // CHECK: apply [[METHOD]]([[BRIDGED_ERROR]], [[BORROWED_SELF]]) // CHECK: destroy_value [[BRIDGED_ERROR]] : $AnyObject // CHECK: end_borrow [[BORROWED_SELF]] from [[SELF]] receiver.takesId(error) // CHECK: [[BORROWED_SELF:%.*]] = begin_borrow [[SELF]] // CHECK: [[METHOD:%.*]] = class_method [volatile] [[BORROWED_SELF]] : $NSIdLover, // CHECK: [[COPY:%.*]] = alloc_stack $Any // CHECK: copy_addr [[ANY]] to [initialization] [[COPY]] // CHECK: [[OPENED_COPY:%.*]] = open_existential_addr immutable_access [[COPY]] : $*Any to $*[[OPENED_TYPE:@opened.*Any]], // CHECK: [[TMP:%.*]] = alloc_stack $[[OPENED_TYPE]] // CHECK: copy_addr [[OPENED_COPY]] to [initialization] [[TMP]] // CHECK: // function_ref _bridgeAnythingToObjectiveC // CHECK: [[BRIDGE_ANYTHING:%.*]] = function_ref // CHECK: [[ANYOBJECT:%.*]] = apply [[BRIDGE_ANYTHING]]<[[OPENED_TYPE]]>([[TMP]]) // CHECK: destroy_addr [[COPY]] // CHECK: dealloc_stack [[COPY]] // CHECK: apply [[METHOD]]([[ANYOBJECT]], [[BORROWED_SELF]]) // CHECK: destroy_value [[ANYOBJECT]] // CHECK: end_borrow [[BORROWED_SELF]] from [[SELF]] receiver.takesId(any) // CHECK: [[BORROWED_SELF:%.*]] = begin_borrow [[SELF]] // CHECK: [[METHOD:%.*]] = class_method [volatile] [[BORROWED_SELF]] : $NSIdLover, // CHECK: [[TMP:%.*]] = alloc_stack $KnownUnbridged // CHECK: store [[KNOWN_UNBRIDGED]] to [trivial] [[TMP]] // CHECK: [[BRIDGE_ANYTHING:%.*]] = function_ref @_T0s27_bridgeAnythingToObjectiveC{{.*}}F // CHECK: [[ANYOBJECT:%.*]] = apply [[BRIDGE_ANYTHING]]<KnownUnbridged>([[TMP]]) // CHECK: apply [[METHOD]]([[ANYOBJECT]], [[BORROWED_SELF]]) // CHECK: end_borrow [[BORROWED_SELF]] from [[SELF]] receiver.takesId(knownUnbridged) // These cases bridge using Optional's _ObjectiveCBridgeable conformance. // CHECK: [[BORROWED_SELF:%.*]] = begin_borrow [[SELF]] // CHECK: [[METHOD:%.*]] = class_method [volatile] [[BORROWED_SELF]] : $NSIdLover, // CHECK: [[BORROWED_OPT_STRING:%.*]] = begin_borrow [[OPT_STRING]] // CHECK: [[OPT_STRING_COPY:%.*]] = copy_value [[BORROWED_OPT_STRING]] // CHECK: [[BRIDGE_OPTIONAL:%.*]] = function_ref @_T0Sq19_bridgeToObjectiveCs9AnyObject_pyF // CHECK: [[TMP:%.*]] = alloc_stack $Optional<String> // CHECK: store [[OPT_STRING_COPY]] to [init] [[TMP]] // CHECK: [[ANYOBJECT:%.*]] = apply [[BRIDGE_OPTIONAL]]<String>([[TMP]]) // CHECK: end_borrow [[BORROWED_OPT_STRING]] from [[OPT_STRING]] // CHECK: apply [[METHOD]]([[ANYOBJECT]], [[BORROWED_SELF]]) // CHECK: end_borrow [[BORROWED_SELF]] from [[SELF]] receiver.takesId(optionalA) // CHECK: [[BORROWED_SELF:%.*]] = begin_borrow [[SELF]] // CHECK: [[METHOD:%.*]] = class_method [volatile] [[BORROWED_SELF]] : $NSIdLover, // CHECK: [[BORROWED_OPT_NSSTRING:%.*]] = begin_borrow [[OPT_NSSTRING]] // CHECK: [[OPT_NSSTRING_COPY:%.*]] = copy_value [[BORROWED_OPT_NSSTRING]] // CHECK: [[BRIDGE_OPTIONAL:%.*]] = function_ref @_T0Sq19_bridgeToObjectiveCs9AnyObject_pyF // CHECK: [[TMP:%.*]] = alloc_stack $Optional<NSString> // CHECK: store [[OPT_NSSTRING_COPY]] to [init] [[TMP]] // CHECK: [[ANYOBJECT:%.*]] = apply [[BRIDGE_OPTIONAL]]<NSString>([[TMP]]) // CHECK: end_borrow [[BORROWED_OPT_NSSTRING]] from [[OPT_NSSTRING]] // CHECK: apply [[METHOD]]([[ANYOBJECT]], [[BORROWED_SELF]]) // CHECK: end_borrow [[BORROWED_SELF]] from [[SELF]] receiver.takesId(optionalB) // CHECK: [[BORROWED_SELF:%.*]] = begin_borrow [[SELF]] // CHECK: [[METHOD:%.*]] = class_method [volatile] [[BORROWED_SELF]] : $NSIdLover, // CHECK: [[TMP:%.*]] = alloc_stack $Optional<Any> // CHECK: copy_addr [[OPT_ANY]] to [initialization] [[TMP]] // CHECK: [[BRIDGE_OPTIONAL:%.*]] = function_ref @_T0Sq19_bridgeToObjectiveCs9AnyObject_pyF // CHECK: [[ANYOBJECT:%.*]] = apply [[BRIDGE_OPTIONAL]]<Any>([[TMP]]) // CHECK: apply [[METHOD]]([[ANYOBJECT]], [[BORROWED_SELF]]) // CHECK: end_borrow [[BORROWED_SELF]] from [[SELF]] receiver.takesId(optionalC) // TODO: Property and subscript setters } // Workaround for rdar://problem/28318984. Skip the peephole for types with // nontrivial SIL lowerings because we don't correctly form the substitutions // for a generic _bridgeAnythingToObjectiveC call. func zim() {} struct Zang {} // CHECK-LABEL: sil hidden @_T017objc_bridging_any27typesWithNontrivialLoweringySo9NSIdLoverC8receiver_tF func typesWithNontrivialLowering(receiver: NSIdLover) { // CHECK: init_existential_addr {{%.*}} : $*Any, $() -> () receiver.takesId(zim) // CHECK: init_existential_addr {{%.*}} : $*Any, $Zang.Type receiver.takesId(Zang.self) // CHECK: init_existential_addr {{%.*}} : $*Any, $(() -> (), Zang.Type) receiver.takesId((zim, Zang.self)) // CHECK: apply {{%.*}}<(Int, String)> receiver.takesId((0, "one")) } // CHECK-LABEL: sil hidden @_T017objc_bridging_any19passingToNullableId{{.*}}F func passingToNullableId<T: CP, U>(receiver: NSIdLover, string: String, nsString: NSString, object: AnyObject, classGeneric: T, classExistential: CP, generic: U, existential: P, error: Error, any: Any, knownUnbridged: KnownUnbridged, optString: String?, optNSString: NSString?, optObject: AnyObject?, optClassGeneric: T?, optClassExistential: CP?, optGeneric: U?, optExistential: P?, optAny: Any?, optKnownUnbridged: KnownUnbridged?, optOptA: String??, optOptB: NSString??, optOptC: Any??) { // CHECK: bb0([[SELF:%.*]] : $NSIdLover, // CHECK: [[STRING:%.*]] : $String, // CHECK: [[NSSTRING:%.*]] : $NSString // CHECK: [[OBJECT:%.*]] : $AnyObject // CHECK: [[CLASS_GENERIC:%.*]] : $T // CHECK: [[CLASS_EXISTENTIAL:%.*]] : $CP // CHECK: [[GENERIC:%.*]] : $*U // CHECK: [[EXISTENTIAL:%.*]] : $*P // CHECK: [[ERROR:%.*]] : $Error // CHECK: [[ANY:%.*]] : $*Any, // CHECK: [[KNOWN_UNBRIDGED:%.*]] : $KnownUnbridged, // CHECK: [[OPT_STRING:%.*]] : $Optional<String>, // CHECK: [[OPT_NSSTRING:%.*]] : $Optional<NSString> // CHECK: [[OPT_OBJECT:%.*]] : $Optional<AnyObject> // CHECK: [[OPT_CLASS_GENERIC:%.*]] : $Optional<T> // CHECK: [[OPT_CLASS_EXISTENTIAL:%.*]] : $Optional<CP> // CHECK: [[OPT_GENERIC:%.*]] : $*Optional<U> // CHECK: [[OPT_EXISTENTIAL:%.*]] : $*Optional<P> // CHECK: [[OPT_ANY:%.*]] : $*Optional<Any> // CHECK: [[OPT_KNOWN_UNBRIDGED:%.*]] : $Optional<KnownUnbridged> // CHECK: [[OPT_OPT_A:%.*]] : $Optional<Optional<String>> // CHECK: [[OPT_OPT_B:%.*]] : $Optional<Optional<NSString>> // CHECK: [[OPT_OPT_C:%.*]] : $*Optional<Optional<Any>> // CHECK: [[BORROWED_SELF:%.*]] = begin_borrow [[SELF]] // CHECK: [[METHOD:%.*]] = class_method [volatile] [[BORROWED_SELF]] // CHECK: [[BORROWED_STRING:%.*]] = begin_borrow [[STRING]] // CHECK: [[STRING_COPY:%.*]] = copy_value [[BORROWED_STRING]] // CHECK: [[BRIDGE_STRING:%.*]] = function_ref @_T0SS10FoundationE19_bridgeToObjectiveCSo8NSStringCyF // CHECK: [[BORROWED_STRING_COPY:%.*]] = begin_borrow [[STRING_COPY]] // CHECK: [[BRIDGED:%.*]] = apply [[BRIDGE_STRING]]([[BORROWED_STRING_COPY]]) // CHECK: [[ANYOBJECT:%.*]] = init_existential_ref [[BRIDGED]] : $NSString : $NSString, $AnyObject // CHECK: [[OPT_ANYOBJECT:%.*]] = enum {{.*}} [[ANYOBJECT]] // CHECK: end_borrow [[BORROWED_STRING_COPY]] from [[STRING_COPY]] // CHECK: destroy_value [[STRING_COPY]] // CHECK: apply [[METHOD]]([[OPT_ANYOBJECT]], [[BORROWED_SELF]]) // CHECK: destroy_value [[OPT_ANYOBJECT]] // CHECK: end_borrow [[BORROWED_SELF]] from [[SELF]] receiver.takesNullableId(string) // CHECK: [[BORROWED_SELF:%.*]] = begin_borrow [[SELF]] // CHECK: [[METHOD:%.*]] = class_method [volatile] [[BORROWED_SELF]] : $NSIdLover, // CHECK: [[BORROWED_NSSTRING:%.*]] = begin_borrow [[NSSTRING]] // CHECK: [[NSSTRING_COPY:%.*]] = copy_value [[BORROWED_NSSTRING]] // CHECK: [[ANYOBJECT:%.*]] = init_existential_ref [[NSSTRING_COPY]] : $NSString : $NSString, $AnyObject // CHECK: [[OPT_ANYOBJECT:%.*]] = enum {{.*}} [[ANYOBJECT]] // CHECK: end_borrow [[BORROWED_NSSTRING]] from [[NSSTRING]] // CHECK: apply [[METHOD]]([[OPT_ANYOBJECT]], [[BORROWED_SELF]]) // CHECK: end_borrow [[BORROWED_SELF]] from [[SELF]] receiver.takesNullableId(nsString) // CHECK: [[BORROWED_SELF:%.*]] = begin_borrow [[SELF]] // CHECK: [[METHOD:%.*]] = class_method [volatile] [[BORROWED_SELF]] : $NSIdLover, // CHECK: [[BORROWED_OBJECT:%.*]] = begin_borrow [[OBJECT]] // CHECK: [[OBJECT_COPY:%.*]] = copy_value [[BORROWED_OBJECT]] // CHECK: [[OPT_ANYOBJECT:%.*]] = enum {{.*}} [[OBJECT_COPY]] // CHECK: end_borrow [[BORROWED_OBJECT]] from [[OBJECT]] // CHECK: apply [[METHOD]]([[OPT_ANYOBJECT]], [[BORROWED_SELF]]) // CHECK: end_borrow [[BORROWED_SELF]] from [[SELF]] receiver.takesNullableId(object) // CHECK: [[BORROWED_SELF:%.*]] = begin_borrow [[SELF]] // CHECK: [[METHOD:%.*]] = class_method [volatile] [[BORROWED_SELF]] : $NSIdLover, // CHECK: [[BORROWED_CLASS_GENERIC:%.*]] = begin_borrow [[CLASS_GENERIC]] // CHECK: [[CLASS_GENERIC_COPY:%.*]] = copy_value [[BORROWED_CLASS_GENERIC]] // CHECK: [[ANYOBJECT:%.*]] = init_existential_ref [[CLASS_GENERIC_COPY]] : $T : $T, $AnyObject // CHECK: [[OPT_ANYOBJECT:%.*]] = enum {{.*}} [[ANYOBJECT]] // CHECK: end_borrow [[BORROWED_CLASS_GENERIC]] from [[CLASS_GENERIC]] // CHECK: apply [[METHOD]]([[OPT_ANYOBJECT]], [[BORROWED_SELF]]) // CHECK: end_borrow [[BORROWED_SELF]] from [[SELF]] receiver.takesNullableId(classGeneric) // CHECK: [[BORROWED_SELF:%.*]] = begin_borrow [[SELF]] // CHECK: [[METHOD:%.*]] = class_method [volatile] [[BORROWED_SELF]] : $NSIdLover, // CHECK: [[BORROWED_CLASS_EXISTENTIAL:%.*]] = begin_borrow [[CLASS_EXISTENTIAL]] // CHECK: [[CLASS_EXISTENTIAL_COPY:%.*]] = copy_value [[BORROWED_CLASS_EXISTENTIAL]] // CHECK: [[OPENED:%.*]] = open_existential_ref [[CLASS_EXISTENTIAL_COPY]] : $CP // CHECK: [[ANYOBJECT:%.*]] = init_existential_ref [[OPENED]] // CHECK: [[OPT_ANYOBJECT:%.*]] = enum {{.*}} [[ANYOBJECT]] // CHECK: end_borrow [[BORROWED_CLASS_EXISTENTIAL]] from [[CLASS_EXISTENTIAL]] // CHECK: apply [[METHOD]]([[OPT_ANYOBJECT]], [[BORROWED_SELF]]) // CHECK: end_borrow [[BORROWED_SELF]] from [[SELF]] receiver.takesNullableId(classExistential) // CHECK: [[BORROWED_SELF:%.*]] = begin_borrow [[SELF]] // CHECK: [[METHOD:%.*]] = class_method [volatile] [[BORROWED_SELF]] : $NSIdLover, // CHECK-NEXT: [[COPY:%.*]] = alloc_stack $U // CHECK-NEXT: copy_addr [[GENERIC]] to [initialization] [[COPY]] // CHECK-NEXT: // function_ref _bridgeAnythingToObjectiveC // CHECK-NEXT: [[BRIDGE_ANYTHING:%.*]] = function_ref // CHECK-NEXT: [[ANYOBJECT:%.*]] = apply [[BRIDGE_ANYTHING]]<U>([[COPY]]) // CHECK-NEXT: [[OPT_ANYOBJECT:%.*]] = enum {{.*}} [[ANYOBJECT]] // CHECK-NEXT: dealloc_stack [[COPY]] // CHECK-NEXT: apply [[METHOD]]([[OPT_ANYOBJECT]], [[BORROWED_SELF]]) // CHECK-NEXT: destroy_value [[OPT_ANYOBJECT]] // CHECK-NEXT: end_borrow [[BORROWED_SELF]] from [[SELF]] receiver.takesNullableId(generic) // CHECK: [[BORROWED_SELF:%.*]] = begin_borrow [[SELF]] // CHECK: [[METHOD:%.*]] = class_method [volatile] [[BORROWED_SELF]] : $NSIdLover, // CHECK-NEXT: [[COPY:%.*]] = alloc_stack $P // CHECK-NEXT: copy_addr [[EXISTENTIAL]] to [initialization] [[COPY]] // CHECK-NEXT: [[OPENED_COPY:%.*]] = open_existential_addr immutable_access [[COPY]] : $*P to $*[[OPENED_TYPE:@opened.*P]], // CHECK: [[TMP:%.*]] = alloc_stack $[[OPENED_TYPE]] // CHECK: copy_addr [[OPENED_COPY]] to [initialization] [[TMP]] // CHECK-NEXT: // function_ref _bridgeAnythingToObjectiveC // CHECK-NEXT: [[BRIDGE_ANYTHING:%.*]] = function_ref // CHECK-NEXT: [[ANYOBJECT:%.*]] = apply [[BRIDGE_ANYTHING]]<[[OPENED_TYPE]]>([[TMP]]) // CHECK-NEXT: [[OPT_ANYOBJECT:%.*]] = enum {{.*}} [[ANYOBJECT]] // CHECK-NEXT: dealloc_stack [[TMP]] // CHECK-NEXT: destroy_addr [[COPY]] // CHECK-NEXT: dealloc_stack [[COPY]] // CHECK-NEXT: apply [[METHOD]]([[OPT_ANYOBJECT]], [[BORROWED_SELF]]) // CHECK-NEXT: destroy_value [[OPT_ANYOBJECT]] // CHECK-NEXT: end_borrow [[BORROWED_SELF]] from [[SELF]] receiver.takesNullableId(existential) // CHECK: [[BORROWED_SELF:%.*]] = begin_borrow [[SELF]] // CHECK: [[METHOD:%.*]] = class_method [volatile] [[BORROWED_SELF]] : $NSIdLover, // CHECK: [[BORROWED_ERROR:%.*]] = begin_borrow [[ERROR]] // CHECK-NEXT: [[ERROR_COPY:%.*]] = copy_value [[BORROWED_ERROR]] : $Error // CHECK-NEXT: [[ERROR_BOX:%[0-9]+]] = open_existential_box [[ERROR_COPY]] : $Error to $*@opened([[ERROR_ARCHETYPE:"[^"]*"]]) Error // CHECK-NEXT: [[ERROR_STACK:%[0-9]+]] = alloc_stack $@opened([[ERROR_ARCHETYPE]]) Error // CHECK-NEXT: copy_addr [[ERROR_BOX]] to [initialization] [[ERROR_STACK]] : $*@opened([[ERROR_ARCHETYPE]]) Error // CHECK: [[BRIDGE_FUNCTION:%[0-9]+]] = function_ref @_T0s27_bridgeAnythingToObjectiveCs9AnyObject_pxlF // CHECK-NEXT: [[BRIDGED_ERROR:%[0-9]+]] = apply [[BRIDGE_FUNCTION]]<@opened([[ERROR_ARCHETYPE]]) Error>([[ERROR_STACK]]) // CHECK-NEXT: [[BRIDGED_ERROR_OPT:%[0-9]+]] = enum $Optional<AnyObject>, #Optional.some!enumelt.1, [[BRIDGED_ERROR]] : $AnyObject // CHECK-NEXT: dealloc_stack [[ERROR_STACK]] : $*@opened([[ERROR_ARCHETYPE]]) Error // CHECK-NEXT: destroy_value [[ERROR_COPY]] : $Error // CHECK-NEXT: end_borrow [[BORROWED_ERROR]] from [[ERROR]] // CHECK-NEXT: apply [[METHOD]]([[BRIDGED_ERROR_OPT]], [[BORROWED_SELF]]) // CHECK-NEXT: destroy_value [[BRIDGED_ERROR_OPT]] // CHECK-NEXT: end_borrow [[BORROWED_SELF]] from [[SELF]] receiver.takesNullableId(error) // CHECK: [[BORROWED_SELF:%.*]] = begin_borrow [[SELF]] // CHECK: [[METHOD:%.*]] = class_method [volatile] [[BORROWED_SELF]] : $NSIdLover, // CHECK-NEXT: [[COPY:%.*]] = alloc_stack $Any // CHECK-NEXT: copy_addr [[ANY]] to [initialization] [[COPY]] // CHECK-NEXT: [[OPENED_COPY:%.*]] = open_existential_addr immutable_access [[COPY]] : $*Any to $*[[OPENED_TYPE:@opened.*Any]], // CHECK: [[TMP:%.*]] = alloc_stack $[[OPENED_TYPE]] // CHECK: copy_addr [[OPENED_COPY]] to [initialization] [[TMP]] // CHECK-NEXT: // function_ref _bridgeAnythingToObjectiveC // CHECK-NEXT: [[BRIDGE_ANYTHING:%.*]] = function_ref // CHECK-NEXT: [[ANYOBJECT:%.*]] = apply [[BRIDGE_ANYTHING]]<[[OPENED_TYPE]]>([[TMP]]) // CHECK-NEXT: [[OPT_ANYOBJECT:%.*]] = enum {{.*}} [[ANYOBJECT]] // CHECK-NEXT: dealloc_stack [[TMP]] // CHECK-NEXT: destroy_addr [[COPY]] // CHECK-NEXT: dealloc_stack [[COPY]] // CHECK-NEXT: apply [[METHOD]]([[OPT_ANYOBJECT]], [[BORROWED_SELF]]) // CHECK-NEXT: destroy_value [[OPT_ANYOBJECT]] // CHECK-NEXT: end_borrow [[BORROWED_SELF]] from [[SELF]] receiver.takesNullableId(any) // CHECK: [[BORROWED_SELF:%.*]] = begin_borrow [[SELF]] // CHECK: [[METHOD:%.*]] = class_method [volatile] [[BORROWED_SELF]] : $NSIdLover, // CHECK: [[TMP:%.*]] = alloc_stack $KnownUnbridged // CHECK: store [[KNOWN_UNBRIDGED]] to [trivial] [[TMP]] // CHECK: [[BRIDGE_ANYTHING:%.*]] = function_ref @_T0s27_bridgeAnythingToObjectiveC{{.*}}F // CHECK: [[ANYOBJECT:%.*]] = apply [[BRIDGE_ANYTHING]]<KnownUnbridged>([[TMP]]) // CHECK: [[OPT_ANYOBJECT:%.*]] = enum {{.*}} [[ANYOBJECT]] // CHECK: apply [[METHOD]]([[OPT_ANYOBJECT]], [[BORROWED_SELF]]) // CHECK: end_borrow [[BORROWED_SELF]] from [[SELF]] receiver.takesNullableId(knownUnbridged) // CHECK: [[BORROWED_SELF:%.*]] = begin_borrow [[SELF]] // CHECK: [[METHOD:%.*]] = class_method [volatile] [[BORROWED_SELF]] // CHECK: [[BORROWED_OPT_STRING:%.*]] = begin_borrow [[OPT_STRING]] // CHECK: [[OPT_STRING_COPY:%.*]] = copy_value [[BORROWED_OPT_STRING]] // CHECK: switch_enum [[OPT_STRING_COPY]] : $Optional<String>, case #Optional.some!enumelt.1: [[SOME_BB:bb[0-9]+]], case #Optional.none!enumelt: [[NONE_BB:bb[0-9]+]] // // CHECK: [[SOME_BB]]([[STRING_DATA:%.*]] : $String): // CHECK: [[BRIDGE_STRING:%.*]] = function_ref @_T0SS10FoundationE19_bridgeToObjectiveCSo8NSStringCyF // CHECK: [[BORROWED_STRING_DATA:%.*]] = begin_borrow [[STRING_DATA]] // CHECK: [[BRIDGED:%.*]] = apply [[BRIDGE_STRING]]([[BORROWED_STRING_DATA]]) // CHECK: [[ANYOBJECT:%.*]] = init_existential_ref [[BRIDGED]] : $NSString : $NSString, $AnyObject // CHECK: [[OPT_ANYOBJECT:%.*]] = enum {{.*}} [[ANYOBJECT]] // CHECK: end_borrow [[BORROWED_STRING_DATA]] from [[STRING_DATA]] // CHECK: destroy_value [[STRING_DATA]] // CHECK: br [[JOIN:bb.*]]([[OPT_ANYOBJECT]] // // CHECK: [[NONE_BB]]: // CHECK: [[OPT_NONE:%.*]] = enum $Optional<AnyObject>, #Optional.none!enumelt // CHECK: br [[JOIN]]([[OPT_NONE]] // // CHECK: [[JOIN]]([[PHI:%.*]] : $Optional<AnyObject>): // CHECK: end_borrow [[BORROWED_OPT_STRING]] from [[OPT_STRING]] // CHECK: apply [[METHOD]]([[PHI]], [[BORROWED_SELF]]) // CHECK: destroy_value [[PHI]] // CHECK: end_borrow [[BORROWED_SELF]] from [[SELF]] receiver.takesNullableId(optString) // CHECK: [[BORROWED_SELF:%.*]] = begin_borrow [[SELF]] // CHECK: [[METHOD:%.*]] = class_method [volatile] [[BORROWED_SELF]] receiver.takesNullableId(optNSString) // CHECK: [[BORROWED_SELF:%.*]] = begin_borrow [[SELF]] // CHECK: [[METHOD:%.*]] = class_method [volatile] [[BORROWED_SELF]] // CHECK: [[BORROWED_OPT_OBJECT:%.*]] = begin_borrow [[OPT_OBJECT]] // CHECK: [[OPT_OBJECT_COPY:%.*]] = copy_value [[BORROWED_OPT_OBJECT]] // CHECK: apply [[METHOD]]([[OPT_OBJECT_COPY]], [[BORROWED_SELF]]) receiver.takesNullableId(optObject) receiver.takesNullableId(optClassGeneric) receiver.takesNullableId(optClassExistential) receiver.takesNullableId(optGeneric) receiver.takesNullableId(optExistential) receiver.takesNullableId(optAny) receiver.takesNullableId(optKnownUnbridged) receiver.takesNullableId(optOptA) receiver.takesNullableId(optOptB) receiver.takesNullableId(optOptC) } protocol Anyable { init(any: Any) init(anyMaybe: Any?) var anyProperty: Any { get } var maybeAnyProperty: Any? { get } } // Make sure we generate correct bridging thunks class SwiftIdLover : NSObject, Anyable { func methodReturningAny() -> Any {} // SEMANTIC ARC TODO: This is another case of pattern matching the body of one // function in a different function... Just pattern match the unreachable case // to preserve behavior. We should check if it is correct. // CHECK-LABEL: sil hidden @_T017objc_bridging_any12SwiftIdLoverC18methodReturningAnyypyF : $@convention(method) (@guaranteed SwiftIdLover) -> @out Any // CHECK: unreachable // CHECK: } // end sil function '_T017objc_bridging_any12SwiftIdLoverC18methodReturningAnyypyF' // CHECK-LABEL: sil hidden [thunk] @_T017objc_bridging_any12SwiftIdLoverC18methodReturningAnyypyFTo : $@convention(objc_method) (SwiftIdLover) -> @autoreleased AnyObject { // CHECK: bb0([[SELF:%[0-9]+]] : $SwiftIdLover): // CHECK: [[NATIVE_RESULT:%.*]] = alloc_stack $Any // CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]] : $SwiftIdLover // CHECK: [[BORROWED_SELF_COPY:%.*]] = begin_borrow [[SELF_COPY]] // CHECK: [[NATIVE_IMP:%.*]] = function_ref @_T017objc_bridging_any12SwiftIdLoverC18methodReturningAnyypyF // CHECK: apply [[NATIVE_IMP]]([[NATIVE_RESULT]], [[BORROWED_SELF_COPY]]) // CHECK: end_borrow [[BORROWED_SELF_COPY]] from [[SELF_COPY]] // CHECK: destroy_value [[SELF_COPY]] // CHECK: [[OPEN_RESULT:%.*]] = open_existential_addr immutable_access [[NATIVE_RESULT]] // CHECK: [[TMP:%.*]] = alloc_stack // CHECK: copy_addr [[OPEN_RESULT]] to [initialization] [[TMP]] // CHECK: [[BRIDGE_ANYTHING:%.*]] = function_ref @_T0s27_bridgeAnythingToObjectiveC{{.*}}F // CHECK: [[OBJC_RESULT:%.*]] = apply [[BRIDGE_ANYTHING]]<{{.*}}>([[TMP]]) // CHECK: return [[OBJC_RESULT]] // CHECK: } // end sil function '_T017objc_bridging_any12SwiftIdLoverC18methodReturningAnyypyFTo' func methodReturningOptionalAny() -> Any? {} // CHECK-LABEL: sil hidden @_T017objc_bridging_any12SwiftIdLoverC26methodReturningOptionalAnyypSgyF // CHECK-LABEL: sil hidden [thunk] @_T017objc_bridging_any12SwiftIdLoverC26methodReturningOptionalAnyypSgyFTo // CHECK: function_ref @_T0s27_bridgeAnythingToObjectiveC{{.*}}F @objc func methodTakingAny(a: Any) {} // CHECK-LABEL: sil hidden [thunk] @_T017objc_bridging_any12SwiftIdLoverC15methodTakingAnyyyp1a_tFTo : $@convention(objc_method) (AnyObject, SwiftIdLover) -> () // CHECK: bb0([[ARG:%.*]] : $AnyObject, [[SELF:%.*]] : $SwiftIdLover): // CHECK-NEXT: [[ARG_COPY:%.*]] = copy_value [[ARG]] // CHECK-NEXT: [[SELF_COPY:%.*]] = copy_value [[SELF]] // CHECK-NEXT: [[OPTIONAL_ARG_COPY:%.*]] = unchecked_ref_cast [[ARG_COPY]] // CHECK-NEXT: // function_ref // CHECK-NEXT: [[BRIDGE_TO_ANY:%.*]] = function_ref [[BRIDGE_TO_ANY_FUNC:@.*]] : // CHECK-NEXT: [[RESULT:%.*]] = alloc_stack $Any // CHECK-NEXT: [[RESULT_VAL:%.*]] = apply [[BRIDGE_TO_ANY]]([[RESULT]], [[OPTIONAL_ARG_COPY]]) // CHECK-NEXT: [[BORROWED_SELF_COPY:%.*]] = begin_borrow [[SELF_COPY]] // CHECK-NEXT: // function_ref // CHECK-NEXT: [[METHOD:%.*]] = function_ref @_T017objc_bridging_any12SwiftIdLoverC15methodTakingAnyyyp1a_tF // CHECK-NEXT: apply [[METHOD]]([[RESULT]], [[BORROWED_SELF_COPY]]) // CHECK-NEXT: end_borrow [[BORROWED_SELF_COPY]] from [[SELF_COPY]] // CHECK-NEXT: dealloc_stack [[RESULT]] // CHECK-NEXT: destroy_value [[SELF_COPY]] // CHECK-NEXT: return func methodTakingOptionalAny(a: Any?) {} // CHECK-LABEL: sil hidden @_T017objc_bridging_any12SwiftIdLoverC23methodTakingOptionalAnyyypSg1a_tF // CHECK-LABEL: sil hidden [thunk] @_T017objc_bridging_any12SwiftIdLoverC23methodTakingOptionalAnyyypSg1a_tFTo // CHECK: function_ref [[BRIDGE_TO_ANY_FUNC]] // CHECK-LABEL: sil hidden @_T017objc_bridging_any12SwiftIdLoverC017methodTakingBlockH3AnyyyypcF : $@convention(method) (@owned @callee_owned (@in Any) -> (), @guaranteed SwiftIdLover) -> () // CHECK-LABEL: sil hidden [thunk] @_T017objc_bridging_any12SwiftIdLoverC017methodTakingBlockH3AnyyyypcFTo : $@convention(objc_method) (@convention(block) (AnyObject) -> (), SwiftIdLover) -> () // CHECK: bb0([[BLOCK:%.*]] : $@convention(block) (AnyObject) -> (), [[SELF:%.*]] : $SwiftIdLover): // CHECK-NEXT: [[BLOCK_COPY:%.*]] = copy_block [[BLOCK]] // CHECK-NEXT: [[SELF_COPY:%.*]] = copy_value [[SELF]] // CHECK: [[THUNK_FN:%.*]] = function_ref @_T0s9AnyObject_pIyBy_ypIxi_TR // CHECK-NEXT: [[THUNK:%.*]] = partial_apply [[THUNK_FN]]([[BLOCK_COPY]]) // CHECK: [[BORROWED_SELF_COPY:%.*]] = begin_borrow [[SELF_COPY]] // CHECK-NEXT: // function_ref // CHECK-NEXT: [[METHOD:%.*]] = function_ref @_T017objc_bridging_any12SwiftIdLoverC017methodTakingBlockH3AnyyyypcF // CHECK-NEXT: [[RESULT:%.*]] = apply [[METHOD]]([[THUNK]], [[BORROWED_SELF_COPY]]) // CHECK-NEXT: end_borrow [[BORROWED_SELF_COPY]] from [[SELF_COPY]] // CHECK-NEXT: destroy_value [[SELF_COPY]] // CHECK-NEXT: return [[RESULT]] // CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] @_T0s9AnyObject_pIyBy_ypIxi_TR // CHECK: bb0([[ANY:%.*]] : $*Any, [[BLOCK:%.*]] : $@convention(block) (AnyObject) -> ()): // CHECK-NEXT: [[OPENED_ANY:%.*]] = open_existential_addr immutable_access [[ANY]] : $*Any to $*[[OPENED_TYPE:@opened.*Any]], // CHECK: [[TMP:%.*]] = alloc_stack // CHECK: copy_addr [[OPENED_ANY]] to [initialization] [[TMP]] // CHECK-NEXT: // function_ref _bridgeAnythingToObjectiveC // CHECK-NEXT: [[BRIDGE_ANYTHING:%.*]] = function_ref // CHECK-NEXT: [[BRIDGED:%.*]] = apply [[BRIDGE_ANYTHING]]<[[OPENED_TYPE]]>([[TMP]]) // CHECK-NEXT: apply [[BLOCK]]([[BRIDGED]]) // CHECK-NEXT: [[VOID:%.*]] = tuple () // CHECK-NEXT: destroy_value [[BLOCK]] // CHECK-NEXT: destroy_value [[BRIDGED]] // CHECK-NEXT: dealloc_stack [[TMP]] // CHECK-NEXT: destroy_addr [[ANY]] // CHECK-NEXT: return [[VOID]] @objc func methodTakingBlockTakingAny(_: (Any) -> ()) {} // CHECK-LABEL: sil hidden @_T017objc_bridging_any12SwiftIdLoverC29methodReturningBlockTakingAnyyypcyF : $@convention(method) (@guaranteed SwiftIdLover) -> @owned @callee_owned (@in Any) -> () // CHECK-LABEL: sil hidden [thunk] @_T017objc_bridging_any12SwiftIdLoverC29methodReturningBlockTakingAnyyypcyFTo : $@convention(objc_method) (SwiftIdLover) -> @autoreleased @convention(block) (AnyObject) -> () // CHECK: bb0([[SELF:%.*]] : $SwiftIdLover): // CHECK-NEXT: [[SELF_COPY:%.*]] = copy_value [[SELF]] // CHECK-NEXT: [[BORROWED_SELF_COPY:%.*]] = begin_borrow [[SELF_COPY]] // CHECK-NEXT: // function_ref // CHECK-NEXT: [[METHOD:%.*]] = function_ref @_T017objc_bridging_any12SwiftIdLoverC29methodReturningBlockTakingAnyyypcyF // CHECK-NEXT: [[RESULT:%.*]] = apply [[METHOD:%.*]]([[BORROWED_SELF_COPY]]) // CHECK-NEXT: end_borrow [[BORROWED_SELF_COPY]] from [[SELF_COPY]] // CHECK-NEXT: destroy_value [[SELF_COPY]] // CHECK-NEXT: [[BLOCK_STORAGE:%.*]] = alloc_stack $@block_storage @callee_owned (@in Any) -> () // CHECK-NEXT: [[BLOCK_STORAGE_ADDR:%.*]] = project_block_storage [[BLOCK_STORAGE]] // CHECK-NEXT: store [[RESULT:%.*]] to [init] [[BLOCK_STORAGE_ADDR]] // CHECK: [[THUNK_FN:%.*]] = function_ref @_T0ypIxi_s9AnyObject_pIyBy_TR // CHECK-NEXT: [[BLOCK_HEADER:%.*]] = init_block_storage_header [[BLOCK_STORAGE]] : $*@block_storage @callee_owned (@in Any) -> (), invoke [[THUNK_FN]] // CHECK-NEXT: [[BLOCK:%.*]] = copy_block [[BLOCK_HEADER]] // CHECK-NEXT: dealloc_stack [[BLOCK_STORAGE]] // CHECK-NEXT: destroy_value [[RESULT]] // CHECK-NEXT: return [[BLOCK]] // CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] @_T0ypIxi_s9AnyObject_pIyBy_TR : $@convention(c) (@inout_aliasable @block_storage @callee_owned (@in Any) -> (), AnyObject) -> () // CHECK: bb0([[BLOCK_STORAGE:%.*]] : $*@block_storage @callee_owned (@in Any) -> (), [[ANY:%.*]] : $AnyObject): // CHECK-NEXT: [[BLOCK_STORAGE_ADDR:%.*]] = project_block_storage [[BLOCK_STORAGE]] // CHECK-NEXT: [[FUNCTION:%.*]] = load [copy] [[BLOCK_STORAGE_ADDR]] // CHECK-NEXT: [[ANY_COPY:%.*]] = copy_value [[ANY]] // CHECK-NEXT: [[OPTIONAL:%.*]] = unchecked_ref_cast [[ANY_COPY]] // CHECK-NEXT: // function_ref // CHECK-NEXT: [[BRIDGE_TO_ANY:%.*]] = function_ref [[BRIDGE_TO_ANY_FUNC:@.*]] : // CHECK-NEXT: [[RESULT:%.*]] = alloc_stack $Any // CHECK-NEXT: [[RESULT_VAL:%.*]] = apply [[BRIDGE_TO_ANY]]([[RESULT]], [[OPTIONAL]]) // CHECK-NEXT: apply [[FUNCTION]]([[RESULT]]) // CHECK-NEXT: [[VOID:%.*]] = tuple () // CHECK-NEXT: dealloc_stack [[RESULT]] // CHECK-NEXT: return [[VOID]] : $() @objc func methodTakingBlockTakingOptionalAny(_: (Any?) -> ()) {} @objc func methodReturningBlockTakingAny() -> ((Any) -> ()) {} // CHECK-LABEL: sil hidden @_T017objc_bridging_any12SwiftIdLoverC29methodTakingBlockReturningAnyyypycF : $@convention(method) (@owned @callee_owned () -> @out Any, @guaranteed SwiftIdLover) -> () { // CHECK-LABEL: sil hidden [thunk] @_T017objc_bridging_any12SwiftIdLoverC29methodTakingBlockReturningAnyyypycFTo : $@convention(objc_method) (@convention(block) () -> @autoreleased AnyObject, SwiftIdLover) -> () // CHECK: bb0([[BLOCK:%.*]] : $@convention(block) () -> @autoreleased AnyObject, [[ANY:%.*]] : $SwiftIdLover): // CHECK-NEXT: [[BLOCK_COPY:%.*]] = copy_block [[BLOCK]] // CHECK-NEXT: [[ANY_COPY:%.*]] = copy_value [[ANY]] // CHECK-NEXT: // function_ref // CHECK-NEXT: [[THUNK_FN:%.*]] = function_ref @_T0s9AnyObject_pIyBa_ypIxr_TR // CHECK-NEXT: [[THUNK:%.*]] = partial_apply [[THUNK_FN]]([[BLOCK_COPY]]) // CHECK-NEXT: [[BORROWED_ANY_COPY:%.*]] = begin_borrow [[ANY_COPY]] // CHECK-NEXT: // function_ref // CHECK-NEXT: [[METHOD:%.*]] = function_ref @_T017objc_bridging_any12SwiftIdLoverC29methodTakingBlockReturningAnyyypycF // CHECK-NEXT: [[RESULT:%.*]] = apply [[METHOD]]([[THUNK]], [[BORROWED_ANY_COPY]]) // CHECK-NEXT: end_borrow [[BORROWED_ANY_COPY]] from [[ANY_COPY]] // CHECK-NEXT: destroy_value [[ANY_COPY]] // CHECK-NEXT: return [[RESULT]] // CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] @_T0s9AnyObject_pIyBa_ypIxr_TR : $@convention(thin) (@owned @convention(block) () -> @autoreleased AnyObject) -> @out Any // CHECK: bb0([[ANY_ADDR:%.*]] : $*Any, [[BLOCK:%.*]] : $@convention(block) () -> @autoreleased AnyObject): // CHECK-NEXT: [[BRIDGED:%.*]] = apply [[BLOCK]]() // CHECK-NEXT: [[OPTIONAL:%.*]] = unchecked_ref_cast [[BRIDGED]] // CHECK-NEXT: // function_ref // CHECK-NEXT: [[BRIDGE_TO_ANY:%.*]] = function_ref [[BRIDGE_TO_ANY_FUNC:@.*]] : // CHECK-NEXT: [[RESULT:%.*]] = alloc_stack $Any // CHECK-NEXT: [[RESULT_VAL:%.*]] = apply [[BRIDGE_TO_ANY]]([[RESULT]], [[OPTIONAL]]) // TODO: Should elide the copy // CHECK-NEXT: copy_addr [take] [[RESULT]] to [initialization] [[ANY_ADDR]] // CHECK-NEXT: [[EMPTY:%.*]] = tuple () // CHECK-NEXT: dealloc_stack [[RESULT]] // CHECK-NEXT: destroy_value [[BLOCK]] // CHECK-NEXT: return [[EMPTY]] @objc func methodReturningBlockTakingOptionalAny() -> ((Any?) -> ()) {} @objc func methodTakingBlockReturningAny(_: () -> Any) {} // CHECK-LABEL: sil hidden @_T017objc_bridging_any12SwiftIdLoverC020methodReturningBlockH3AnyypycyF : $@convention(method) (@guaranteed SwiftIdLover) -> @owned @callee_owned () -> @out Any // CHECK-LABEL: sil hidden [thunk] @_T017objc_bridging_any12SwiftIdLoverC020methodReturningBlockH3AnyypycyFTo : $@convention(objc_method) (SwiftIdLover) -> @autoreleased @convention(block) () -> @autoreleased AnyObject // CHECK: bb0([[SELF:%.*]] : $SwiftIdLover): // CHECK-NEXT: [[SELF_COPY:%.*]] = copy_value [[SELF]] // CHECK-NEXT: [[BORROWED_SELF_COPY:%.*]] = begin_borrow [[SELF_COPY]] // CHECK-NEXT: // function_ref // CHECK-NEXT: [[METHOD:%.*]] = function_ref @_T017objc_bridging_any12SwiftIdLoverC020methodReturningBlockH3AnyypycyF // CHECK-NEXT: [[FUNCTION:%.*]] = apply [[METHOD]]([[BORROWED_SELF_COPY]]) // CHECK-NEXT: end_borrow [[BORROWED_SELF_COPY]] from [[SELF_COPY]] // CHECK-NEXT: destroy_value [[SELF_COPY]] // CHECK-NEXT: [[BLOCK_STORAGE:%.*]] = alloc_stack $@block_storage @callee_owned () -> @out Any // CHECK-NEXT: [[BLOCK_STORAGE_ADDR:%.*]] = project_block_storage [[BLOCK_STORAGE]] // CHECK-NEXT: store [[FUNCTION]] to [init] [[BLOCK_STORAGE_ADDR]] // CHECK-NEXT: // function_ref // CHECK-NEXT: [[THUNK_FN:%.*]] = function_ref @_T0ypIxr_s9AnyObject_pIyBa_TR // CHECK-NEXT: [[BLOCK_HEADER:%.*]] = init_block_storage_header [[BLOCK_STORAGE]] : $*@block_storage @callee_owned () -> @out Any, invoke [[THUNK_FN]] // CHECK-NEXT: [[BLOCK:%.*]] = copy_block [[BLOCK_HEADER]] // CHECK-NEXT: dealloc_stack [[BLOCK_STORAGE]] // CHECK-NEXT: destroy_value [[FUNCTION]] // CHECK-NEXT: return [[BLOCK]] // CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] @_T0ypIxr_s9AnyObject_pIyBa_TR : $@convention(c) (@inout_aliasable @block_storage @callee_owned () -> @out Any) -> @autoreleased AnyObject // CHECK: bb0(%0 : $*@block_storage @callee_owned () -> @out Any): // CHECK-NEXT: [[BLOCK_STORAGE_ADDR:%.*]] = project_block_storage %0 // CHECK-NEXT: [[FUNCTION:%.*]] = load [copy] [[BLOCK_STORAGE_ADDR]] // CHECK-NEXT: [[RESULT:%.*]] = alloc_stack $Any // CHECK-NEXT: apply [[FUNCTION]]([[RESULT]]) // CHECK-NEXT: [[OPENED:%.*]] = open_existential_addr immutable_access [[RESULT]] : $*Any to $*[[OPENED_TYPE:@opened.*Any]], // CHECK: [[TMP:%.*]] = alloc_stack $[[OPENED_TYPE]] // CHECK: copy_addr [[OPENED]] to [initialization] [[TMP]] // CHECK-NEXT: // function_ref _bridgeAnythingToObjectiveC // CHECK-NEXT: [[BRIDGE_ANYTHING:%.*]] = function_ref // CHECK-NEXT: [[BRIDGED:%.*]] = apply [[BRIDGE_ANYTHING]]<[[OPENED_TYPE]]>([[TMP]]) // CHECK-NEXT: dealloc_stack [[TMP]] // CHECK-NEXT: destroy_addr [[RESULT]] // CHECK-NEXT: dealloc_stack [[RESULT]] // CHECK-NEXT: return [[BRIDGED]] @objc func methodTakingBlockReturningOptionalAny(_: () -> Any?) {} @objc func methodReturningBlockReturningAny() -> (() -> Any) {} @objc func methodReturningBlockReturningOptionalAny() -> (() -> Any?) {} // CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] @_T0ypSgIxr_s9AnyObject_pSgIyBa_TR // CHECK: function_ref @_T0s27_bridgeAnythingToObjectiveC{{.*}}F override init() { super.init() } @objc dynamic required convenience init(any: Any) { self.init() } @objc dynamic required convenience init(anyMaybe: Any?) { self.init() } @objc dynamic var anyProperty: Any @objc dynamic var maybeAnyProperty: Any? subscript(_: IndexForAnySubscript) -> Any { get {} set {} } @objc func methodReturningAnyOrError() throws -> Any {} } class IndexForAnySubscript {} func dynamicLookup(x: AnyObject) { _ = x.anyProperty _ = x[IndexForAnySubscript()] } extension GenericClass { // CHECK-LABEL: sil hidden @_T0So12GenericClassC17objc_bridging_anyE23pseudogenericAnyErasureypx1x_tF : func pseudogenericAnyErasure(x: T) -> Any { // CHECK: bb0([[ANY_OUT:%.*]] : $*Any, [[ARG:%.*]] : $T, [[SELF:%.*]] : $GenericClass<T> // CHECK: [[ANY_BUF:%.*]] = init_existential_addr [[ANY_OUT]] : $*Any, $AnyObject // CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]] // CHECK: [[ARG_COPY:%.*]] = copy_value [[BORROWED_ARG]] // CHECK: [[ANYOBJECT:%.*]] = init_existential_ref [[ARG_COPY]] : $T : $T, $AnyObject // CHECK: store [[ANYOBJECT]] to [init] [[ANY_BUF]] // CHECK: end_borrow [[BORROWED_ARG]] from [[ARG]] // CHECK: destroy_value [[ARG]] return x } // CHECK: } // end sil function '_T0So12GenericClassC17objc_bridging_anyE23pseudogenericAnyErasureypx1x_tF' } // Make sure AnyHashable erasure marks Hashable conformance as used class AnyHashableClass : NSObject { // CHECK-LABEL: sil hidden @_T017objc_bridging_any16AnyHashableClassC07returnsdE0s0dE0VyF // CHECK: [[FN:%.*]] = function_ref @_swift_convertToAnyHashable // CHECK: apply [[FN]]<GenericOption>({{.*}}) func returnsAnyHashable() -> AnyHashable { return GenericOption.multithreaded } } // CHECK-LABEL: sil_witness_table shared [serialized] GenericOption: Hashable module objc_generics { // CHECK-NEXT: base_protocol Equatable: GenericOption: Equatable module objc_generics // CHECK-NEXT: method #Hashable.hashValue!getter.1: {{.*}} : @_T0SC13GenericOptionVs8Hashable13objc_genericssACP9hashValueSifgTW // CHECK-NEXT: }
apache-2.0
eb056c8af953fff223604604fe925469
56.995984
220
0.612031
3.594077
false
false
false
false
drunknbass/Emby.ApiClient.Swift
Emby.ApiClient/model/session/ClientCapabilities.swift
3
964
// // ClientCapabilities.swift // Emby.ApiClient // import Foundation public struct ClientCapabilities { let playableMediaTypes: [String]? let supportedCommands: [String]? let supportsMediaControl: Bool? let messageCallbackUrl: String? let supportsContentUploading: Bool? let supportsPersistentIdentifier: Bool? let supportsSync: Bool? let supportsOfflineAccess: Bool? let deviceProfile: DeviceProfile? let supportedLiveMediaTypes: [String]? let appStoreUrl: String? let iconUrl: String? public init() { playableMediaTypes = nil supportedCommands = nil supportsMediaControl = nil messageCallbackUrl = nil supportsContentUploading = nil supportsPersistentIdentifier = nil supportsSync = nil supportsOfflineAccess = nil deviceProfile = nil supportedLiveMediaTypes = nil appStoreUrl = nil iconUrl = nil } }
mit
921fbf5798ee3f6682bf2e319fe05bd5
25.805556
43
0.681535
5.020833
false
false
false
false
codefellows/sea-b19-ios
Projects/Week3FIlterApp/Week3FIlterApp/ViewController.swift
1
7402
// // ViewController.swift // Week3App // // Created by Bradley Johnson on 8/3/14. // Copyright (c) 2014 learnswift. All rights reserved. // import UIKit import Photos class ViewController: UIViewController, SelectedPhotoDelegate, PHPhotoLibraryChangeObserver { var collectionsFetchResults = [PHFetchResult]() var collectionsLocalizedTitles = [String]() var selectedAsset : PHAsset? let adjustmentFormatterIndentifier = "com.filterappdemo.cf" var context = CIContext(options: nil) @IBOutlet weak var imageView: UIImageView! override func viewDidLoad() { super.viewDidLoad() PHPhotoLibrary.sharedPhotoLibrary().registerChangeObserver(self) // var smartAlbums = PHAssetCollection.fetchAssetCollectionsWithType(PHAssetCollectionType.SmartAlbum, subtype: PHAssetCollectionSubtype.AlbumRegular, options: nil) // var topLevelUserCollections = PHCollectionList.fetchTopLevelUserCollectionsWithOptions(nil) // self.collectionsFetchResults = [smartAlbums,topLevelUserCollections] // self.collectionsLocalizedTitles = ["Smart Albums", "Albums"] // Do any additional setup after loading the view, typically from a nib. } // // func numberOfSectionsInTableView(tableView: UITableView!) -> Int { // // return 1 + self.collectionsFetchResults.count // } // override func prepareForSegue(segue: UIStoryboardSegue!, sender: AnyObject!) { // // if segue.identifier == "Photo" { // var gridVC = segue.destinationViewController as GridViewController // gridVC.assetsFetchResults = PHAsset.fetchAssetsWithOptions(nil) // // } // } //MARK: UICollectionViewDataSource // func tableView(tableView: UITableView!, numberOfRowsInSection section: Int) -> Int { // // if section == 0 { // return 1 // } // else { // var fetchResult = self.collectionsFetchResults[section - 1] as PHFetchResult // var numberOfRows = fetchResult.count // return numberOfRows // } // } // // func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! { // // let cell = tableView.dequeueReusableCellWithIdentifier("AlbumsCell", forIndexPath: indexPath) as UITableViewCell // if indexPath.section == 0 { // cell.textLabel.text = "All Photos" // } // else { // var fetchResult = self.collectionsFetchResults[indexPath.section - 1] // var collection = fetchResult[indexPath.row] as PHCollection // cell.textLabel.text = collection.localizedTitle // } // return cell // } // override func prepareForSegue(segue: UIStoryboardSegue!, sender: AnyObject!) { if segue.identifier == "ShowGrid" { let gridVC = segue.destinationViewController as GridViewController gridVC.assetsFetchResults = PHAsset.fetchAssetsWithOptions(nil) gridVC.delegate = self } } func photoSelected(asset : PHAsset) -> Void { self.selectedAsset = asset self.updateImage() // var targetSize = CGSize(width: CGRectGetWidth(self.imageView.bounds), height: CGRectGetHeight(self.imageView.bounds)) // // PHImageManager.defaultManager().requestImageForAsset(asset, targetSize: targetSize, contentMode: PHImageContentMode.AspectFit, options: nil, resultHandler: {(result : UIImage!, [NSObject : AnyObject]!) -> Void in // // if result { // self.imageView.image = result // } // // }) } @IBAction func handleSepiaPressed(sender: AnyObject) { var options = PHContentEditingInputRequestOptions() options.canHandleAdjustmentData = {(data : PHAdjustmentData!) -> Bool in return data.formatIdentifier == self.adjustmentFormatterIndentifier && data.formatVersion == "1.0" } self.selectedAsset!.requestContentEditingInputWithOptions(options, completionHandler: { ( contentEditingInput : PHContentEditingInput!, info : [NSObject : AnyObject]!) -> Void in //grabbing the image and converting it to CIImage var url = contentEditingInput.fullSizeImageURL var orientation = contentEditingInput.fullSizeImageOrientation var inputImage = CIImage(contentsOfURL: url) inputImage = inputImage.imageByApplyingOrientation(orientation) //creating the filter var filterName = "CISepiaTone" var filter = CIFilter(name: filterName) filter.setDefaults() filter.setValue(inputImage, forKey: kCIInputImageKey) var outputImage = filter.outputImage var cgimg = self.context.createCGImage(outputImage, fromRect: outputImage.extent()) var finalImage = UIImage(CGImage: cgimg) var jpegData = UIImageJPEGRepresentation(finalImage, 1.0) //create our adjustmentdata var adjustmentData = PHAdjustmentData(formatIdentifier: self.adjustmentFormatterIndentifier, formatVersion: "1.0", data: jpegData) var contentEditingOutput = PHContentEditingOutput(contentEditingInput:contentEditingInput) jpegData.writeToURL(contentEditingOutput.renderedContentURL, atomically: true) contentEditingOutput.adjustmentData = adjustmentData //requesting the change PHPhotoLibrary.sharedPhotoLibrary().performChanges({ //change block var request = PHAssetChangeRequest(forAsset: self.selectedAsset) request.contentEditingOutput = contentEditingOutput }, completionHandler: { (success : Bool,error : NSError!) -> Void in //completionHandler for the change if !success { println(error.localizedDescription) } }) }) } func updateImage() { var targetSize = self.imageView.frame.size PHImageManager.defaultManager().requestImageForAsset(self.selectedAsset, targetSize: targetSize, contentMode: PHImageContentMode.AspectFill, options: nil) { (result : UIImage!, info : [NSObject : AnyObject]!) -> Void in self.imageView.image = result } } func photoLibraryDidChange(changeInstance: PHChange!) { NSOperationQueue.mainQueue().addOperationWithBlock { () -> Void in if self.selectedAsset != nil { var changeDetails = changeInstance.changeDetailsForObject(self.selectedAsset) if changeDetails != nil { self.selectedAsset = changeDetails.objectAfterChanges as? PHAsset if changeDetails.assetContentChanged { self.updateImage() } } } } } }
gpl-2.0
73b711ff9c137a00dc4df340ae6f00d9
38.164021
227
0.610646
5.702619
false
false
false
false
RicardoAnjos/CringleApp
CringleApp/Controllers/JoschkaTableViewController.swift
1
2511
// // JoschkaViewController.swift // CringleApp // // Created by Ricardo Jorge Lemos dos Anjos on 23/10/2016. // Copyright © 2016 Ricardo Jorge Lemos dos Anjos. All rights reserved. // import UIKit class JoschkaTableViewController: GenericTableViewController, SwitchCellDelegate { var notificationsIndexPath : IndexPath? override func viewDidLoad() { super.viewDidLoad() self.title = "Joschka".localized } // MARK: - Table view data source override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell : UITableViewCell if(indexPath.section==0){ cell = self.getLabelCell(indexPath: indexPath) (cell as! LabelCell).customImageView.setThemeColor() (cell as! LabelCell).customTextLabel.setThemeColor() }else if(indexPath.section==1){ cell = self.getSwitchCell(indexPath: indexPath) (cell as! SwitchCell).delegate = self self.notificationsIndexPath = indexPath }else{ cell = self.getLabelCell(indexPath: indexPath) if(indexPath.row == 2){ (cell as! LabelCell).customImageView.setRedColor() (cell as! LabelCell).customTextLabel.setRedColor() } } return cell } override func insertData(){ let row00 = DataObject(text: "SendMoney".localized, image: "UploadUnfilledIcon") let row01 = DataObject(text: "RequestMoney".localized,image: "DownloadUnfilledIcon") let row10 = SwitchObject(text: "Notifications".localized,image: "AlarmFilledIcon", isOn:false) let row20 = DataObject(text: "Call".localized,image: "CallFilledIcon") let row21 = DataObject(text: "ShowContact".localized,image: "ProfileFilledIcon") let row22 = DataObject(text: "DeleteCourse".localized,image: "RemoveIcon") let section1 = Section(sectionName: " ", rows: [row00,row01]) let section2 = Section(sectionName: " ", rows: [row10]) let section3 = Section(sectionName: " ", rows: [row20, row21, row22]) self.tableViewData = [section1, section2, section3] } //MARK: - SwitchCellDelegate func switchDidChange(state:Bool){ let dataObject = self.tableViewData[(self.notificationsIndexPath?.section)!].rows[(self.notificationsIndexPath?.row)!] as! SwitchObject dataObject.isOn = state } }
mit
5eac08aad05a67688e52d2985987c689
37.615385
143
0.645418
4.474153
false
false
false
false
xu6148152/binea_project_for_ios
SportDemo/SportDemo/Shared/utility/UIGlobal.swift
1
7773
// // UIGlobal.swift // SportDemo // // Created by Binea Xu on 8/9/15. // Copyright (c) 2015 Binea Xu. All rights reserved. // import Foundation import UIKit import MBProgressHUD.MBProgressHUD import TWMessageBarManager.TWMessageBarManager import AVFoundation import AssetsLibrary import BlocksKit class UIGlobal{ static let kDefaultDuration: CGFloat = 3.0 static let kToastMininumInterval: NSTimeInterval = 3 static var ZEPPGREENCOLOR: UIColor{ get{ return UIColorFromARGB(0xD1EE00) } } static func appWindow() -> UIWindow { return (UIApplication.sharedApplication().delegate as! AppDelegate).appWindow! } static func UIColorFromARGB(rgbValue: UInt) -> UIColor { return UIColor( red: CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0, green: CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0, blue: CGFloat(rgbValue & 0x0000FF) / 255.0, alpha: CGFloat((rgbValue & 0xff000000 > 0 ? ((Float)((rgbValue & 0xFF000000) >> 24))/255.0 : 1.0)) ) } static func showMessage(message: String, minimunInterval: NSTimeInterval, messageType: TWMessageBarMessageType){ hideLoading() let messageTimeDict: NSMutableDictionary = NSMutableDictionary() let date: NSDate? = messageTimeDict.objectForKey(message) as? NSDate if date != nil && NSDate().timeIntervalSinceDate(date!) <= minimunInterval{ return } TWMessageBarManager.sharedInstance().hideAll() messageTimeDict.setObject(NSDate(), forKey: message) TWMessageBarManager.sharedInstance().showMessageWithTitle(nil, description: message, type: messageType, duration: kDefaultDuration) } static func showSuccessMessage(message: String){ if !message.isEmpty { showMessage(message, minimunInterval: kToastMininumInterval, messageType: TWMessageBarMessageType.Success) } } static func showErrorMessage(message: String){ if !message.isEmpty { showMessage(message, minimunInterval: kToastMininumInterval, messageType: TWMessageBarMessageType.Error) } } static func showLoadingWithMessage(message: String){ var hub: MBProgressHUD if let loading = MBProgressHUD.showHUDAddedTo(appWindow(), animated: true){ loading.mode = MBProgressHUDMode.Indeterminate loading.detailsLabelText = message hub = loading }else{ hub = createHUDMessage(message, mode: MBProgressHUDMode.Indeterminate) } hub.alpha = 0 UIView.animateWithDuration(0.2, animations: { () -> Void in hub.alpha = 0.6 }) } static func hideLoading(){ MBProgressHUD.hideAllHUDsForView(appWindow(), animated: true) } static func createHUDMessage(message: String, mode: MBProgressHUDMode) ->MBProgressHUD{ let hub = MBProgressHUD(window: appWindow()) hub.removeFromSuperViewOnHide = true hub.mode = mode hub.detailsLabelText = message hub.detailsLabelFont = UIFont(name: "Avenir-Medium", size: 16) appWindow().addSubview(hub) hub.show(false) return hub } static func showImagePickerControllerInViewController(viewController: UIViewController?, addtionalConstruction: ((picker: UIImagePickerController) -> Void), didFinishPickingMedia: (info: NSDictionary) -> Void, didCancel: (() -> Void)?){ guard let _ = viewController else{ return } let statusBarHidden = UIApplication.sharedApplication().statusBarHidden let imagePicker = UIImagePickerController() imagePicker.modalPresentationStyle = UIModalPresentationStyle.CurrentContext imagePicker.allowsEditing = true addtionalConstruction(picker: imagePicker) if !authImagePick(imagePicker, isShowAlert: true) { return; } let time: NSTimeInterval = 2.0 let delay = dispatch_time(DISPATCH_TIME_NOW, Int64(time * Double(NSEC_PER_SEC))) var hideImagePickerController = { imagePicker.dismissViewControllerAnimated(true, completion: nil) if statusBarHidden { dispatch_after(delay, dispatch_get_main_queue(), { () -> Void in UIApplication.sharedApplication().setStatusBarHidden(true, withAnimation: UIStatusBarAnimation.Fade) }) } } ZPControl.presentViewController(imagePicker, animated: true, modalPresentationStyle: ZEPP.IPAD_REGULAR ? UIModalPresentationStyle.CurrentContext : UIModalPresentationStyle.FullScreen) { } // imagePickerController.bk_didCancelBlock = ^(UIImagePickerController *picker) { // ZPInvokeBlock(hideImagePickerController); // ZPInvokeBlock(didCancel); // }; // imagePickerController.bk_didFinishPickingMediaBlock = ^(UIImagePickerController *picker, NSDictionary *meta) { // ZPInvokeBlock(hideImagePickerController); // ZPInvokeBlock(didFinishPickingMedia, meta); // }; // // // // [ZPControl presentViewController:imagePickerController // animated:YES // modalPresentationStyle:IPAD_REGULAR ? UIModalPresentationCurrentContext : UIModalPresentationFullScreen // completion:^{ // // }]; } static func authImagePick(picker: UIImagePickerController, isShowAlert: Bool) -> Bool { var authPass = true var message = "" if picker.sourceType == UIImagePickerControllerSourceType.Camera { let authorizationStatus = AVCaptureDevice.authorizationStatusForMediaType(AVMediaTypeVideo) if AVAuthorizationStatus.Restricted == authorizationStatus || AVAuthorizationStatus.Denied == authorizationStatus { message = NSLocalizedString("str_var_camera_access_denied_alert_message", comment: "str_var_camera_access_denied_alert_message").uppercaseString authPass = false } } else { let status = ALAssetsLibrary.authorizationStatus() if status == ALAuthorizationStatus.Restricted || status == ALAuthorizationStatus.Denied { message = NSLocalizedString("str_var_photolib_access_denied_alert_message", comment: "str_var_photolib_access_denied_alert_message") authPass = false } } if !authPass && isShowAlert { ZPDialogPopoverView.showDialog(NSLocalizedString("str_camera_access_denied_alert_title", comment: "str_camera_access_denied_alert_title"), message: message, customView: nil, actionTitle: NSLocalizedString("str_camera_access_denied_action_title", comment: "str_camera_access_denied_action_title"), actionBlock: { UIGlobal.openSettingsApp() }, cancelTitle: NSLocalizedString("str_cancel", comment: "str_cancel"), cancelBlock: {}, buttonType: ZPPopoverButtonType.ZPPopoverButtonNegative) } return authPass } static func openSettingsApp() { if let url = NSURL(string: UIApplicationOpenSettingsURLString) { if UIApplication.sharedApplication().canOpenURL(url) { UIApplication.sharedApplication().openURL(url) } } } static func backgroundColor() -> UIColor { return UIColorFromARGB(0x1E2022) } }
mit
a846984f99c4cb952869885ec31141f6
37.671642
323
0.636562
5.276986
false
false
false
false
Ben21hao/edx-app-ios-enterprise-new
Source/ChoiceLabel.swift
3
2813
// // ChoiceLabel.swift // edX // // Created by Akiva Leffert on 12/4/15. // Copyright © 2015 edX. All rights reserved. // import Foundation class ChoiceLabel : UIView { private static let iconSize : CGFloat = 20 // Want all icons to take up the same amount of space (including padding) // So add a little extra space to account for wide icons private static let minIconSize : CGFloat = iconSize + 6 private let iconView = UIImageView() private let titleLabel = UILabel() private let valueLabel = UILabel() private let titleTextStyle = OEXMutableTextStyle(weight: .Normal, size: .Large, color: OEXStyles.sharedStyles().neutralBlackT()) private let valueTextStyle = OEXTextStyle(weight: .Normal, size: .Large, color: OEXStyles.sharedStyles().neutralDark()) override init(frame : CGRect) { super.init(frame : frame) setup() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setup() } private func setup() { let titleStack = TZStackView(arrangedSubviews: [iconView, titleLabel]) titleStack.alignment = .Center titleStack.spacing = StandardHorizontalMargin / 2 titleStack.setContentHuggingPriority(UILayoutPriorityRequired, forAxis: .Horizontal) let stack = TZStackView(arrangedSubviews: [titleStack, valueLabel]) stack.alignment = .Center stack.spacing = StandardHorizontalMargin self.addSubview(stack) stack.snp_makeConstraints {make in make.top.equalTo(self).offset(StandardVerticalMargin) make.bottom.equalTo(self).offset(-StandardVerticalMargin) make.leading.equalTo(self) make.trailing.lessThanOrEqualTo(self) } iconView.contentMode = iconView.isRightToLeft ? .Right : .Left iconView.setContentCompressionResistancePriority(UILayoutPriorityDefaultHigh, forAxis: .Horizontal) iconView.tintColor = titleTextStyle.color iconView.snp_makeConstraints { make in make.width.equalTo(self.dynamicType.minIconSize).priorityMedium() } iconView.hidden = true valueLabel.setContentCompressionResistancePriority(UILayoutPriorityDefaultLow, forAxis: .Horizontal) } var titleText : String? { didSet { self.titleLabel.attributedText = titleTextStyle.attributedStringWithText(titleText) } } var valueText: String? { didSet { self.valueLabel.attributedText = valueTextStyle.attributedStringWithText(valueText) } } var icon: Icon? { didSet { iconView.image = icon?.imageWithFontSize(self.dynamicType.iconSize) iconView.hidden = icon == nil } } }
apache-2.0
296a17f2bd11b253117a39dc721e12d2
35.519481
132
0.665718
5.178637
false
false
false
false
ibari/StationToStation
Pods/p2.OAuth2/OAuth2/OAuth2ClientCredentials.swift
1
3772
// // OAuth2ClientCredentials.swift // OAuth2 // // Created by Pascal Pfiffner on 5/27/15. // Copyright 2015 Pascal Pfiffner // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import Foundation /** Class to handle two-legged OAuth2 requests of the "client_credentials" type. */ public class OAuth2ClientCredentials: OAuth2 { public override func authorize(# params: [String : String]?, autoDismiss: Bool) { if hasUnexpiredAccessToken() { self.didAuthorize([String: String]()) } else { logIfVerbose("No access token, requesting a new one") obtainAccessToken() { error in if let error = error { self.didFail(error) } else { self.didAuthorize([String: String]()) } } } } /** If there is a refresh token, use it to receive a fresh access token. :param: callback The callback to call after the refresh token exchange has finished */ func obtainAccessToken(callback: ((error: NSError?) -> Void)) { let post = tokenRequest() logIfVerbose("Requesting new access token from \(post.URL?.description)") performRequest(post) { (data, status, error) -> Void in var myError = error if let data = data, let json = self.parseAccessTokenResponse(data, error: &myError) { self.logIfVerbose("Did get access token [\(nil != self.accessToken)]") callback(error: nil) } else { callback(error: myError ?? genOAuth2Error("Unknown error when requesting access token")) } } } /** Creates a POST request with x-www-form-urlencoded body created from the supplied URL's query part. Made public to enable unit testing. */ public func tokenRequest() -> NSMutableURLRequest { if clientId.isEmpty { NSException(name: "OAuth2IncompleteSetup", reason: "I do not yet have a client id, cannot request a token", userInfo: nil).raise() } if nil == clientSecret { NSException(name: "OAuth2IncompleteSetup", reason: "I do not yet have a client secret, cannot request a token", userInfo: nil).raise() } let req = NSMutableURLRequest(URL: authURL) req.HTTPMethod = "POST" req.setValue("application/x-www-form-urlencoded; charset=utf-8", forHTTPHeaderField: "Content-Type") req.setValue("application/json", forHTTPHeaderField: "Accept") req.HTTPBody = "grant_type=client_credentials".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true) // add Authorization header logIfVerbose("Adding “Authorization” header as “Basic client-key:client-secret”") let pw = "\(clientId.wwwFormURLEncodedString):\(clientSecret!.wwwFormURLEncodedString)" if let utf8 = pw.dataUsingEncoding(NSUTF8StringEncoding) { req.setValue("Basic \(utf8.base64EncodedStringWithOptions(nil))", forHTTPHeaderField: "Authorization") } else { logIfVerbose("ERROR: for some reason failed to base-64 encode the client-key:client-secret combo") } return req } override func parseAccessTokenResponse(data: NSData, error: NSErrorPointer) -> OAuth2JSON? { if let json = super.parseAccessTokenResponse(data, error: error) { if let type = json["token_type"] as? String where "bearer" != type { logIfVerbose("WARNING: expecting “bearer” token type but got “\(type)”") } return json } return nil } }
gpl-2.0
484839858260b7414b13e0427a107b55
33.458716
137
0.710064
3.872165
false
false
false
false
niunaruto/DeDaoAppSwift
testSwift/Pods/RxSwift/RxSwift/Schedulers/OperationQueueScheduler.swift
27
2134
// // OperationQueueScheduler.swift // RxSwift // // Created by Krunoslav Zaher on 4/4/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // import class Foundation.Operation import class Foundation.OperationQueue import class Foundation.BlockOperation import Dispatch /// Abstracts the work that needs to be performed on a specific `NSOperationQueue`. /// /// This scheduler is suitable for cases when there is some bigger chunk of work that needs to be performed in background and you want to fine tune concurrent processing using `maxConcurrentOperationCount`. public class OperationQueueScheduler: ImmediateSchedulerType { public let operationQueue: OperationQueue public let queuePriority: Operation.QueuePriority /// Constructs new instance of `OperationQueueScheduler` that performs work on `operationQueue`. /// /// - parameter operationQueue: Operation queue targeted to perform work on. /// - parameter queuePriority: Queue priority which will be assigned to new operations. public init(operationQueue: OperationQueue, queuePriority: Operation.QueuePriority = .normal) { self.operationQueue = operationQueue self.queuePriority = queuePriority } /** Schedules an action to be executed recursively. - parameter state: State passed to the action to be executed. - parameter action: Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in recursive invocation state. - returns: The disposable object used to cancel the scheduled action (best effort). */ public func schedule<StateType>(_ state: StateType, action: @escaping (StateType) -> Disposable) -> Disposable { let cancel = SingleAssignmentDisposable() let operation = BlockOperation { if cancel.isDisposed { return } cancel.setDisposable(action(state)) } operation.queuePriority = self.queuePriority self.operationQueue.addOperation(operation) return cancel } }
mit
e441337cc5d7ef1e4db620f1a83e8bfb
37.089286
206
0.720113
5.511628
false
false
false
false
herobin22/TopOmnibus
TopOmnibus/TopOmnibus/TopNews/View/OYNewsTopicView.swift
1
4684
// // OYNewsTopicView.swift // TopOmnibus // // Created by Gold on 2016/11/3. // Copyright © 2016年 herob. All rights reserved. // // 将标题滚动条分离在一个view里 import UIKit class OYNewsTopicView: UIView { lazy var dataSource: [OYNewsTopicModel] = { var arr = [OYNewsTopicModel]() for topic in NewsTopics { let model = OYNewsTopicModel(topic: topic) arr.append(model) } return arr }() let flowLayout: UICollectionViewFlowLayout = UICollectionViewFlowLayout() lazy var collectionView: UICollectionView = { return UICollectionView(frame: self.bounds, collectionViewLayout: self.flowLayout) }() /// 点击回调 var didSelectTopic: ((_ num: Int) ->Void)? /// 当前滚动的进度,用于改变topic的颜色 var process: CGFloat = 0 { didSet { let intProcess = Int(process) let firstProcess = process - CGFloat(intProcess) let secondProcess = CGFloat(intProcess+1) - process let firstModel = self.dataSource[intProcess] firstModel.process = 1-firstProcess if intProcess == self.dataSource.count-1 {// 防止数组越界 collectionView.reloadItems(at: [IndexPath(item: intProcess, section: 0)]) return } let secondModel = self.dataSource[intProcess+1] secondModel.process = 1-secondProcess collectionView.reloadItems(at: [IndexPath(item: intProcess, section: 0), IndexPath(item: intProcess+1, section: 0)]) } } /// 当前滚动的进度,用于改变topic的偏移量 var processInt: Int = 0 { didSet { /// 记录indexPath lastIndexPath = IndexPath(item: processInt, section: 0) let offsetX = (CGFloat(processInt)+0.5)*flowLayout.itemSize.width if offsetX < mainWidth/2 { collectionView.setContentOffset(CGPoint.zero, animated: true) return } if (collectionView.contentSize.width-offsetX) < mainWidth/2 { collectionView.setContentOffset(CGPoint(x: collectionView.contentSize.width-mainWidth, y: 0), animated: true) return } collectionView.setContentOffset(CGPoint(x: offsetX-mainWidth/2, y: 0), animated: true) } } /// 记录上一个点击的item fileprivate var lastIndexPath: IndexPath = IndexPath(item: 0, section: 0) override init(frame: CGRect) { super.init(frame: frame) setupCollectionView() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func setupCollectionView() { self.addSubview(self.collectionView) collectionView.contentInset = UIEdgeInsets.zero collectionView.dataSource = self collectionView.delegate = self collectionView.backgroundColor = #colorLiteral(red: 0.9411764706, green: 0.9411764706, blue: 0.9411764706, alpha: 1) collectionView.showsHorizontalScrollIndicator = false collectionView.showsVerticalScrollIndicator = false collectionView.scrollsToTop = false flowLayout.minimumLineSpacing = 0 flowLayout.minimumInteritemSpacing = 0 flowLayout.scrollDirection = .horizontal collectionView.register(OYNewsTopicCell.self, forCellWithReuseIdentifier: OYNewsTopicCellID) } override func layoutSubviews() { super.layoutSubviews() collectionView.frame = self.bounds flowLayout.itemSize = CGSize(width: 50, height: collectionView.bounds.size.height) } } extension OYNewsTopicView: UICollectionViewDataSource, UICollectionViewDelegate { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return dataSource.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: OYNewsTopicCellID, for: indexPath) as! OYNewsTopicCell cell.model = self.dataSource[indexPath.item] return cell } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { // 刷新上一个cell let model = self.dataSource[lastIndexPath.item] model.process = 0 collectionView.reloadItems(at: [lastIndexPath]) didSelectTopic?(indexPath.item) lastIndexPath = indexPath processInt = indexPath.item } }
mit
aeca712a31b3a2ce81970735a88001d0
37.880342
129
0.655309
4.966157
false
false
false
false
Nosrac/Dictater
Dictater.swift
1
3788
// // Dictater.swift // Dictater // // Created by Kyle Carson on 9/2/15. // Copyright © 2015 Kyle Carson. All rights reserved. // import Foundation import Cocoa class Dictater { enum PreferenceKeys : String { case SkipBoundary = "skipBoundary" case HasBeenUsed = "hasBeenUsed" case FontName = "fontName" case FontSize = "fontSize" case LineHeightMultiple = "lineHeightMultiple" case ProgressBarEnabled = "progressBarEnabled" case AutoScrollEnabled = "autoScrollEnabled" } static let TextAppearanceChangedNotification = "Dictater.FontChanged" static func setupDefaults() { let font = self.defaultFont UserDefaults.standard.register( defaults: [ PreferenceKeys.SkipBoundary.rawValue : Speech.Boundary.Sentence.rawValue, PreferenceKeys.HasBeenUsed.rawValue : false, PreferenceKeys.FontName.rawValue : font.fontName, PreferenceKeys.FontSize.rawValue : Double(font.pointSize), PreferenceKeys.LineHeightMultiple.rawValue : 1.2, PreferenceKeys.ProgressBarEnabled.rawValue : true, PreferenceKeys.AutoScrollEnabled.rawValue : true, ]) } static var skipBoundary : Speech.Boundary { get { let rawValue = UserDefaults.standard.integer(forKey: PreferenceKeys.SkipBoundary.rawValue) if let boundary = Speech.Boundary(rawValue: rawValue) { return boundary } return .Sentence } set { UserDefaults.standard.set(newValue.rawValue, forKey: PreferenceKeys.SkipBoundary.rawValue) } } static var hasBeenUsed : Bool { get { return UserDefaults.standard.bool(forKey: PreferenceKeys.HasBeenUsed.rawValue) } set { UserDefaults.standard.set(newValue, forKey: PreferenceKeys.HasBeenUsed.rawValue) } } static var autoScrollEnabled : Bool { get { return UserDefaults.standard.bool(forKey: PreferenceKeys.AutoScrollEnabled.rawValue) } set { UserDefaults.standard.set(newValue, forKey: PreferenceKeys.AutoScrollEnabled.rawValue) } } static var isProgressBarEnabled : Bool { get { return UserDefaults.standard.bool(forKey: PreferenceKeys.ProgressBarEnabled.rawValue) } set { UserDefaults.standard.set(newValue, forKey: PreferenceKeys.ProgressBarEnabled.rawValue) } } static var font : NSFont { let cgfloat = CGFloat(self.fontSize) return NSFont(name: self.fontName, size: cgfloat) ?? self.defaultFont } static var defaultFont : NSFont { return NSFont.messageFont(ofSize: 14) } static var fontName : String { get { if let string = UserDefaults.standard.string(forKey: PreferenceKeys.FontName.rawValue) { return string } else { return self.defaultFont.fontName } } set { UserDefaults.standard.set(newValue, forKey: PreferenceKeys.FontName.rawValue) NotificationCenter.default.post(name: NSNotification.Name(rawValue: self.TextAppearanceChangedNotification), object: nil) } } static var fontSize : Int { get { return UserDefaults.standard.integer(forKey: PreferenceKeys.FontSize.rawValue) } set { UserDefaults.standard.set(newValue, forKey: PreferenceKeys.FontSize.rawValue) NotificationCenter.default.post(name: NSNotification.Name(rawValue: self.TextAppearanceChangedNotification), object: nil) } } static var lineHeightMultiple : Double { get { return UserDefaults.standard.double(forKey: PreferenceKeys.LineHeightMultiple.rawValue) } set { UserDefaults.standard.set(newValue, forKey: PreferenceKeys.LineHeightMultiple.rawValue) NotificationCenter.default.post(name: NSNotification.Name(rawValue: self.TextAppearanceChangedNotification), object: nil) } } class ParagraphStyle : NSParagraphStyle { let multiple = Dictater.lineHeightMultiple override var lineHeightMultiple : CGFloat { return CGFloat(self.multiple) } } }
mit
b8a00e0b3114f85adaac58148dd7e63a
23.275641
124
0.744653
3.734714
false
false
false
false
almazrafi/Metatron
Tests/MetatronTests/ID3v2/ID3v2TagGenresTest.swift
1
28151
// // ID3v2TagGenresTest.swift // Metatron // // Copyright (c) 2016 Almaz Ibragimov // // 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 XCTest @testable import Metatron class ID3v2TagGenresTest: XCTestCase { // MARK: Instance Methods func test() { let tag = ID3v2Tag() do { let value: [String] = [] tag.genres = value XCTAssert(tag.genres == value) let frame = tag.appendFrameSet(ID3v2FrameID.tcon).mainFrame XCTAssert(frame.stuff == nil) do { tag.version = ID3v2Version.v2 XCTAssert(tag.toData() == nil) } do { tag.version = ID3v2Version.v3 XCTAssert(tag.toData() == nil) } do { tag.version = ID3v2Version.v4 XCTAssert(tag.toData() == nil) } frame.imposeStuff(format: ID3v2ContentTypeFormat.regular).fields = value XCTAssert(tag.genres == value) } do { let value = [""] tag.genres = value XCTAssert(tag.genres == []) let frame = tag.appendFrameSet(ID3v2FrameID.tcon).mainFrame XCTAssert(frame.stuff == nil) do { tag.version = ID3v2Version.v2 XCTAssert(tag.toData() == nil) } do { tag.version = ID3v2Version.v3 XCTAssert(tag.toData() == nil) } do { tag.version = ID3v2Version.v4 XCTAssert(tag.toData() == nil) } frame.imposeStuff(format: ID3v2ContentTypeFormat.regular).fields = value XCTAssert(tag.genres == []) } do { let value = ["Abc 123"] tag.genres = value XCTAssert(tag.genres == value) let frame = tag.appendFrameSet(ID3v2FrameID.tcon).mainFrame XCTAssert(frame.stuff(format: ID3v2ContentTypeFormat.regular).fields == value) do { tag.version = ID3v2Version.v2 guard let data = tag.toData() else { return XCTFail() } guard let other = ID3v2Tag(fromData: data) else { return XCTFail() } XCTAssert(other.genres == value) } do { tag.version = ID3v2Version.v3 guard let data = tag.toData() else { return XCTFail() } guard let other = ID3v2Tag(fromData: data) else { return XCTFail() } XCTAssert(other.genres == value) } do { tag.version = ID3v2Version.v4 guard let data = tag.toData() else { return XCTFail() } guard let other = ID3v2Tag(fromData: data) else { return XCTFail() } XCTAssert(other.genres == value) } frame.imposeStuff(format: ID3v2ContentTypeFormat.regular).fields = value XCTAssert(tag.genres == value) } do { let value = ["Абв 123"] tag.genres = value XCTAssert(tag.genres == value) let frame = tag.appendFrameSet(ID3v2FrameID.tcon).mainFrame XCTAssert(frame.stuff(format: ID3v2ContentTypeFormat.regular).fields == value) do { tag.version = ID3v2Version.v2 guard let data = tag.toData() else { return XCTFail() } guard let other = ID3v2Tag(fromData: data) else { return XCTFail() } XCTAssert(other.genres == value) } do { tag.version = ID3v2Version.v3 guard let data = tag.toData() else { return XCTFail() } guard let other = ID3v2Tag(fromData: data) else { return XCTFail() } XCTAssert(other.genres == value) } do { tag.version = ID3v2Version.v4 guard let data = tag.toData() else { return XCTFail() } guard let other = ID3v2Tag(fromData: data) else { return XCTFail() } XCTAssert(other.genres == value) } frame.imposeStuff(format: ID3v2ContentTypeFormat.regular).fields = value XCTAssert(tag.genres == value) } do { let value = ["Abc 1", "Abc 2"] tag.genres = value XCTAssert(tag.genres == value) let frame = tag.appendFrameSet(ID3v2FrameID.tcon).mainFrame XCTAssert(frame.stuff(format: ID3v2ContentTypeFormat.regular).fields == value) do { tag.version = ID3v2Version.v2 guard let data = tag.toData() else { return XCTFail() } guard let other = ID3v2Tag(fromData: data) else { return XCTFail() } XCTAssert(other.genres == value) } do { tag.version = ID3v2Version.v3 guard let data = tag.toData() else { return XCTFail() } guard let other = ID3v2Tag(fromData: data) else { return XCTFail() } XCTAssert(other.genres == value) } do { tag.version = ID3v2Version.v4 guard let data = tag.toData() else { return XCTFail() } guard let other = ID3v2Tag(fromData: data) else { return XCTFail() } XCTAssert(other.genres == value) } frame.imposeStuff(format: ID3v2ContentTypeFormat.regular).fields = value XCTAssert(tag.genres == value) } do { let value = ["", "Abc 2"] tag.genres = value XCTAssert(tag.genres == ["Abc 2"]) let frame = tag.appendFrameSet(ID3v2FrameID.tcon).mainFrame XCTAssert(frame.stuff(format: ID3v2ContentTypeFormat.regular).fields == ["Abc 2"]) do { tag.version = ID3v2Version.v2 guard let data = tag.toData() else { return XCTFail() } guard let other = ID3v2Tag(fromData: data) else { return XCTFail() } XCTAssert(other.genres == ["Abc 2"]) } do { tag.version = ID3v2Version.v3 guard let data = tag.toData() else { return XCTFail() } guard let other = ID3v2Tag(fromData: data) else { return XCTFail() } XCTAssert(other.genres == ["Abc 2"]) } do { tag.version = ID3v2Version.v4 guard let data = tag.toData() else { return XCTFail() } guard let other = ID3v2Tag(fromData: data) else { return XCTFail() } XCTAssert(other.genres == ["Abc 2"]) } frame.imposeStuff(format: ID3v2ContentTypeFormat.regular).fields = value XCTAssert(tag.genres == ["Abc 2"]) } do { let value = ["Abc 1", ""] tag.genres = value XCTAssert(tag.genres == ["Abc 1"]) let frame = tag.appendFrameSet(ID3v2FrameID.tcon).mainFrame XCTAssert(frame.stuff(format: ID3v2ContentTypeFormat.regular).fields == ["Abc 1"]) do { tag.version = ID3v2Version.v2 guard let data = tag.toData() else { return XCTFail() } guard let other = ID3v2Tag(fromData: data) else { return XCTFail() } XCTAssert(other.genres == ["Abc 1"]) } do { tag.version = ID3v2Version.v3 guard let data = tag.toData() else { return XCTFail() } guard let other = ID3v2Tag(fromData: data) else { return XCTFail() } XCTAssert(other.genres == ["Abc 1"]) } do { tag.version = ID3v2Version.v4 guard let data = tag.toData() else { return XCTFail() } guard let other = ID3v2Tag(fromData: data) else { return XCTFail() } XCTAssert(other.genres == ["Abc 1"]) } frame.imposeStuff(format: ID3v2ContentTypeFormat.regular).fields = value XCTAssert(tag.genres == ["Abc 1"]) } do { let value = ["", ""] tag.genres = value XCTAssert(tag.genres == []) let frame = tag.appendFrameSet(ID3v2FrameID.tcon).mainFrame XCTAssert(frame.stuff == nil) do { tag.version = ID3v2Version.v2 XCTAssert(tag.toData() == nil) } do { tag.version = ID3v2Version.v3 XCTAssert(tag.toData() == nil) } do { tag.version = ID3v2Version.v4 XCTAssert(tag.toData() == nil) } frame.imposeStuff(format: ID3v2ContentTypeFormat.regular).fields = value XCTAssert(tag.genres == []) } do { let value = [Array<String>(repeating: "Abc", count: 123).joined(separator: "\n")] tag.genres = value XCTAssert(tag.genres == value) let frame = tag.appendFrameSet(ID3v2FrameID.tcon).mainFrame XCTAssert(frame.stuff(format: ID3v2ContentTypeFormat.regular).fields == value) do { tag.version = ID3v2Version.v2 guard let data = tag.toData() else { return XCTFail() } guard let other = ID3v2Tag(fromData: data) else { return XCTFail() } XCTAssert(other.genres == value) } do { tag.version = ID3v2Version.v3 guard let data = tag.toData() else { return XCTFail() } guard let other = ID3v2Tag(fromData: data) else { return XCTFail() } XCTAssert(other.genres == value) } do { tag.version = ID3v2Version.v4 guard let data = tag.toData() else { return XCTFail() } guard let other = ID3v2Tag(fromData: data) else { return XCTFail() } XCTAssert(other.genres == value) } frame.imposeStuff(format: ID3v2ContentTypeFormat.regular).fields = value XCTAssert(tag.genres == value) } do { let value = Array<String>(repeating: "Abc", count: 123) tag.genres = value XCTAssert(tag.genres == value) let frame = tag.appendFrameSet(ID3v2FrameID.tcon).mainFrame XCTAssert(frame.stuff(format: ID3v2ContentTypeFormat.regular).fields == value) do { tag.version = ID3v2Version.v2 guard let data = tag.toData() else { return XCTFail() } guard let other = ID3v2Tag(fromData: data) else { return XCTFail() } XCTAssert(other.genres == value) } do { tag.version = ID3v2Version.v3 guard let data = tag.toData() else { return XCTFail() } guard let other = ID3v2Tag(fromData: data) else { return XCTFail() } XCTAssert(other.genres == value) } do { tag.version = ID3v2Version.v4 guard let data = tag.toData() else { return XCTFail() } guard let other = ID3v2Tag(fromData: data) else { return XCTFail() } XCTAssert(other.genres == value) } frame.imposeStuff(format: ID3v2ContentTypeFormat.regular).fields = value XCTAssert(tag.genres == value) } do { let value = ["(Abc 1)Abc 2 Abc 3"] tag.genres = value XCTAssert(tag.genres == value) let frame = tag.appendFrameSet(ID3v2FrameID.tcon).mainFrame XCTAssert(frame.stuff(format: ID3v2ContentTypeFormat.regular).fields == value) do { tag.version = ID3v2Version.v2 guard let data = tag.toData() else { return XCTFail() } guard let other = ID3v2Tag(fromData: data) else { return XCTFail() } XCTAssert(other.genres == ["(Abc 1)", "Abc 2 Abc 3"]) } do { tag.version = ID3v2Version.v3 guard let data = tag.toData() else { return XCTFail() } guard let other = ID3v2Tag(fromData: data) else { return XCTFail() } XCTAssert(other.genres == ["(Abc 1)", "Abc 2 Abc 3"]) } do { tag.version = ID3v2Version.v4 guard let data = tag.toData() else { return XCTFail() } guard let other = ID3v2Tag(fromData: data) else { return XCTFail() } XCTAssert(other.genres == ["(Abc 1)", "Abc 2 Abc 3"]) } frame.imposeStuff(format: ID3v2ContentTypeFormat.regular).fields = value XCTAssert(tag.genres == value) } do { let value = ["Abc 1(Abc 2)Abc 3"] tag.genres = value XCTAssert(tag.genres == value) let frame = tag.appendFrameSet(ID3v2FrameID.tcon).mainFrame XCTAssert(frame.stuff(format: ID3v2ContentTypeFormat.regular).fields == value) do { tag.version = ID3v2Version.v2 guard let data = tag.toData() else { return XCTFail() } guard let other = ID3v2Tag(fromData: data) else { return XCTFail() } XCTAssert(other.genres == ["Abc 1", "(Abc 2)", "Abc 3"]) } do { tag.version = ID3v2Version.v3 guard let data = tag.toData() else { return XCTFail() } guard let other = ID3v2Tag(fromData: data) else { return XCTFail() } XCTAssert(other.genres == ["Abc 1", "(Abc 2)", "Abc 3"]) } do { tag.version = ID3v2Version.v4 guard let data = tag.toData() else { return XCTFail() } guard let other = ID3v2Tag(fromData: data) else { return XCTFail() } XCTAssert(other.genres == value) } frame.imposeStuff(format: ID3v2ContentTypeFormat.regular).fields = value XCTAssert(tag.genres == value) } do { let value = ["Abc 1 Abc 2(Abc 3)"] tag.genres = value XCTAssert(tag.genres == value) let frame = tag.appendFrameSet(ID3v2FrameID.tcon).mainFrame XCTAssert(frame.stuff(format: ID3v2ContentTypeFormat.regular).fields == value) do { tag.version = ID3v2Version.v2 guard let data = tag.toData() else { return XCTFail() } guard let other = ID3v2Tag(fromData: data) else { return XCTFail() } XCTAssert(other.genres == ["Abc 1 Abc 2", "(Abc 3)"]) } do { tag.version = ID3v2Version.v3 guard let data = tag.toData() else { return XCTFail() } guard let other = ID3v2Tag(fromData: data) else { return XCTFail() } XCTAssert(other.genres == ["Abc 1 Abc 2", "(Abc 3)"]) } do { tag.version = ID3v2Version.v4 guard let data = tag.toData() else { return XCTFail() } guard let other = ID3v2Tag(fromData: data) else { return XCTFail() } XCTAssert(other.genres == value) } frame.imposeStuff(format: ID3v2ContentTypeFormat.regular).fields = value XCTAssert(tag.genres == value) } do { let value = ["(Abc 1)", "Abc 2 Abc 3"] tag.genres = value XCTAssert(tag.genres == value) let frame = tag.appendFrameSet(ID3v2FrameID.tcon).mainFrame XCTAssert(frame.stuff(format: ID3v2ContentTypeFormat.regular).fields == value) do { tag.version = ID3v2Version.v2 guard let data = tag.toData() else { return XCTFail() } guard let other = ID3v2Tag(fromData: data) else { return XCTFail() } XCTAssert(other.genres == value) } do { tag.version = ID3v2Version.v3 guard let data = tag.toData() else { return XCTFail() } guard let other = ID3v2Tag(fromData: data) else { return XCTFail() } XCTAssert(other.genres == value) } do { tag.version = ID3v2Version.v4 guard let data = tag.toData() else { return XCTFail() } guard let other = ID3v2Tag(fromData: data) else { return XCTFail() } XCTAssert(other.genres == value) } frame.imposeStuff(format: ID3v2ContentTypeFormat.regular).fields = value XCTAssert(tag.genres == value) } do { let value = ["Abc 1", "(Abc 2)", "Abc 3"] tag.genres = value XCTAssert(tag.genres == value) let frame = tag.appendFrameSet(ID3v2FrameID.tcon).mainFrame XCTAssert(frame.stuff(format: ID3v2ContentTypeFormat.regular).fields == value) do { tag.version = ID3v2Version.v2 guard let data = tag.toData() else { return XCTFail() } guard let other = ID3v2Tag(fromData: data) else { return XCTFail() } XCTAssert(other.genres == value) } do { tag.version = ID3v2Version.v3 guard let data = tag.toData() else { return XCTFail() } guard let other = ID3v2Tag(fromData: data) else { return XCTFail() } XCTAssert(other.genres == value) } do { tag.version = ID3v2Version.v4 guard let data = tag.toData() else { return XCTFail() } guard let other = ID3v2Tag(fromData: data) else { return XCTFail() } XCTAssert(other.genres == value) } frame.imposeStuff(format: ID3v2ContentTypeFormat.regular).fields = value XCTAssert(tag.genres == value) } do { let value = ["Abc 1 Abc 2", "(Abc 3)"] tag.genres = value XCTAssert(tag.genres == value) let frame = tag.appendFrameSet(ID3v2FrameID.tcon).mainFrame XCTAssert(frame.stuff(format: ID3v2ContentTypeFormat.regular).fields == value) do { tag.version = ID3v2Version.v2 guard let data = tag.toData() else { return XCTFail() } guard let other = ID3v2Tag(fromData: data) else { return XCTFail() } XCTAssert(other.genres == value) } do { tag.version = ID3v2Version.v3 guard let data = tag.toData() else { return XCTFail() } guard let other = ID3v2Tag(fromData: data) else { return XCTFail() } XCTAssert(other.genres == value) } do { tag.version = ID3v2Version.v4 guard let data = tag.toData() else { return XCTFail() } guard let other = ID3v2Tag(fromData: data) else { return XCTFail() } XCTAssert(other.genres == value) } frame.imposeStuff(format: ID3v2ContentTypeFormat.regular).fields = value XCTAssert(tag.genres == value) } do { let value = ["()", "Abc 2 Abc 3"] tag.genres = value XCTAssert(tag.genres == value) let frame = tag.appendFrameSet(ID3v2FrameID.tcon).mainFrame XCTAssert(frame.stuff(format: ID3v2ContentTypeFormat.regular).fields == value) do { tag.version = ID3v2Version.v2 guard let data = tag.toData() else { return XCTFail() } guard let other = ID3v2Tag(fromData: data) else { return XCTFail() } XCTAssert(other.genres == value) } do { tag.version = ID3v2Version.v3 guard let data = tag.toData() else { return XCTFail() } guard let other = ID3v2Tag(fromData: data) else { return XCTFail() } XCTAssert(other.genres == value) } do { tag.version = ID3v2Version.v4 guard let data = tag.toData() else { return XCTFail() } guard let other = ID3v2Tag(fromData: data) else { return XCTFail() } XCTAssert(other.genres == value) } frame.imposeStuff(format: ID3v2ContentTypeFormat.regular).fields = value XCTAssert(tag.genres == value) } do { let value = ["Abc 1", "()", "Abc 3"] tag.genres = value XCTAssert(tag.genres == value) let frame = tag.appendFrameSet(ID3v2FrameID.tcon).mainFrame XCTAssert(frame.stuff(format: ID3v2ContentTypeFormat.regular).fields == value) do { tag.version = ID3v2Version.v2 guard let data = tag.toData() else { return XCTFail() } guard let other = ID3v2Tag(fromData: data) else { return XCTFail() } XCTAssert(other.genres == value) } do { tag.version = ID3v2Version.v3 guard let data = tag.toData() else { return XCTFail() } guard let other = ID3v2Tag(fromData: data) else { return XCTFail() } XCTAssert(other.genres == value) } do { tag.version = ID3v2Version.v4 guard let data = tag.toData() else { return XCTFail() } guard let other = ID3v2Tag(fromData: data) else { return XCTFail() } XCTAssert(other.genres == value) } frame.imposeStuff(format: ID3v2ContentTypeFormat.regular).fields = value XCTAssert(tag.genres == value) } do { let value = ["Abc 1 Abc 2", "()"] tag.genres = value XCTAssert(tag.genres == value) let frame = tag.appendFrameSet(ID3v2FrameID.tcon).mainFrame XCTAssert(frame.stuff(format: ID3v2ContentTypeFormat.regular).fields == value) do { tag.version = ID3v2Version.v2 guard let data = tag.toData() else { return XCTFail() } guard let other = ID3v2Tag(fromData: data) else { return XCTFail() } XCTAssert(other.genres == value) } do { tag.version = ID3v2Version.v3 guard let data = tag.toData() else { return XCTFail() } guard let other = ID3v2Tag(fromData: data) else { return XCTFail() } XCTAssert(other.genres == value) } do { tag.version = ID3v2Version.v4 guard let data = tag.toData() else { return XCTFail() } guard let other = ID3v2Tag(fromData: data) else { return XCTFail() } XCTAssert(other.genres == value) } frame.imposeStuff(format: ID3v2ContentTypeFormat.regular).fields = value XCTAssert(tag.genres == value) } } }
mit
c9ddf060665d7214e5c6ff9bcfe48ad2
25.380506
94
0.457475
4.891901
false
false
false
false
impossibleventures/pusher-websocket-swift
Sources/PusherSwift.swift
1
28620
// // PusherSwift.swift // // Created by Hamilton Chapman on 19/02/2015. // // import Foundation import CommonCrypto import Starscream import Reachability public typealias PusherEventJSON = Dictionary<String, AnyObject> public typealias PusherUserInfoObject = Dictionary<String, AnyObject> public typealias PusherUserData = PresenceChannelMember let PROTOCOL = 7 let VERSION = "0.1.6" let CLIENT_NAME = "pusher-websocket-swift" public class Pusher { public let connection: PusherConnection public init(key: String, options: Dictionary<String, Any>? = nil) { let pusherClientOptions = PusherClientOptions(options: options) let urlString = constructUrl(key, options: pusherClientOptions) let ws = WebSocket(url: NSURL(string: urlString)!) connection = PusherConnection(key: key, socket: ws, url: urlString, options: pusherClientOptions) connection.createGlobalChannel() } public func subscribe(channelName: String) -> PusherChannel { return self.connection.subscribe(channelName) } public func unsubscribe(channelName: String) { self.connection.unsubscribe(channelName) } public func bind(callback: (AnyObject?) -> Void) -> String { return self.connection.addCallbackToGlobalChannel(callback) } public func unbind(callbackId: String) { self.connection.removeCallbackFromGlobalChannel(callbackId) } public func unbindAll() { self.connection.removeAllCallbacksFromGlobalChannel() } public func disconnect() { self.connection.disconnect() } public func connect() { self.connection.connect() } } public enum AuthMethod { case Endpoint case Internal case NoMethod } func constructUrl(key: String, options: PusherClientOptions) -> String { var url = "" if let encrypted = options.encrypted where !encrypted { let defaultPort = (options.port ?? 80) url = "ws://\(options.host!):\(defaultPort)/app/\(key)" } else { let defaultPort = (options.port ?? 443) url = "wss://\(options.host!):\(defaultPort)/app/\(key)" } return "\(url)?client=\(CLIENT_NAME)&version=\(VERSION)&protocol=\(PROTOCOL)" } public struct PusherClientOptions { public let authEndpoint: String? public let secret: String? public let userDataFetcher: (() -> PusherUserData)? public let authMethod: AuthMethod? public let attemptToReturnJSONObject: Bool? public let encrypted: Bool? public let host: String? public let port: Int? public let autoReconnect: Bool? public let authRequestCustomizer: (NSMutableURLRequest -> NSMutableURLRequest)? public init(options: [String:Any]?) { let validKeys = ["encrypted", "attemptToReturnJSONObject", "authEndpoint", "secret", "userDataFetcher", "port", "host", "autoReconnect", "authRequestCustomizer"] if let options = options { for (key, _) in options { if !validKeys.contains(key) { print("Invalid key in options: \(key)") } } } let defaults: [String:AnyObject?] = [ "encrypted": true, "attemptToReturnJSONObject": true, "authEndpoint": nil, "secret": nil, "userDataFetcher": nil, "autoReconnect": true, "authRequestCustomizer": nil, "host": "ws.pusherapp.com", "port": nil ] var optionsMergedWithDefaults: [String:Any] = [:] for (key, value) in defaults { if let options = options, optionsValue = options[key] { optionsMergedWithDefaults[key] = optionsValue } else { optionsMergedWithDefaults[key] = value } } self.encrypted = optionsMergedWithDefaults["encrypted"] as? Bool self.authEndpoint = optionsMergedWithDefaults["authEndpoint"] as? String self.secret = optionsMergedWithDefaults["secret"] as? String self.userDataFetcher = optionsMergedWithDefaults["userDataFetcher"] as? () -> PusherUserData self.attemptToReturnJSONObject = optionsMergedWithDefaults["attemptToReturnJSONObject"] as? Bool self.host = optionsMergedWithDefaults["host"] as? String self.port = optionsMergedWithDefaults["port"] as? Int self.autoReconnect = optionsMergedWithDefaults["autoReconnect"] as? Bool self.authRequestCustomizer = optionsMergedWithDefaults["authRequestCustomizer"] as? (NSMutableURLRequest -> NSMutableURLRequest) if let _ = authEndpoint { self.authMethod = .Endpoint } else if let _ = secret { self.authMethod = .Internal } else { self.authMethod = .NoMethod } } } public class PusherConnection: WebSocketDelegate { public let url: String public let key: String public var options: PusherClientOptions public var globalChannel: GlobalChannel! public var socketId: String? public var connected = false public var channels = PusherChannels() public var socket: WebSocket! public var URLSession: NSURLSession public init(key: String, socket: WebSocket, url: String, options: PusherClientOptions, URLSession: NSURLSession = NSURLSession.sharedSession()) { self.url = url self.key = key self.options = options self.URLSession = URLSession self.socket = socket self.socket.delegate = self } private func subscribe(channelName: String) -> PusherChannel { let newChannel = channels.add(channelName, connection: self) if self.connected { if !self.authorize(newChannel) { print("Unable to subscribe to channel: \(newChannel.name)") } } return newChannel } private func unsubscribe(channelName: String) { if let chan = self.channels.find(channelName) where chan.subscribed { self.sendEvent("pusher:unsubscribe", data: [ "channel": channelName ] ) self.channels.remove(channelName) } } private func sendEvent(event: String, data: AnyObject, channelName: String? = nil) { if event.componentsSeparatedByString("-")[0] == "client" { sendClientEvent(event, data: data, channelName: channelName) } else { self.socket.writeString(JSONStringify(["event": event, "data": data])) } } private func sendClientEvent(event: String, data: AnyObject, channelName: String?) { if let cName = channelName { if isPresenceChannel(cName) || isPrivateChannel(cName) { self.socket.writeString(JSONStringify(["event": event, "data": data, "channel": cName])) } else { print("You must be subscribed to a private or presence channel to send client events") } } } private func JSONStringify(value: AnyObject) -> String { if NSJSONSerialization.isValidJSONObject(value) { do { let data = try NSJSONSerialization.dataWithJSONObject(value, options: []) if let string = NSString(data: data, encoding: NSUTF8StringEncoding) { return string as String } } catch _ { } } return "" } public func disconnect() { if self.connected { self.socket.disconnect() } } public func connect() { if self.connected { return } else { self.socket.connect() } } private func createGlobalChannel() { self.globalChannel = GlobalChannel(connection: self) } private func addCallbackToGlobalChannel(callback: (AnyObject?) -> Void) -> String { return globalChannel.bind(callback) } private func removeCallbackFromGlobalChannel(callbackId: String) { globalChannel.unbind(callbackId) } private func removeAllCallbacksFromGlobalChannel() { globalChannel.unbindAll() } private func handleSubscriptionSucceededEvent(json: PusherEventJSON) { if let channelName = json["channel"] as? String, chan = self.channels.find(channelName) { chan.subscribed = true if isPresenceChannel(channelName) { if let presChan = self.channels.find(channelName) as? PresencePusherChannel { if let data = json["data"] as? String, dataJSON = getPusherEventJSONFromString(data) { if let presenceData = dataJSON["presence"] as? Dictionary<String, AnyObject>, presenceHash = presenceData["hash"] as? Dictionary<String, AnyObject> { presChan.addExistingMembers(presenceHash) } } } } for (eventName, data) in chan.unsentEvents { chan.unsentEvents.removeValueForKey(channelName) chan.trigger(eventName, data: data) } } } private func handleConnectionEstablishedEvent(json: PusherEventJSON) { if let data = json["data"] as? String { if let connectionData = getPusherEventJSONFromString(data), socketId = connectionData["socket_id"] as? String { self.connected = true self.socketId = socketId for (_, channel) in self.channels.channels { if !channel.subscribed { if !self.authorize(channel) { print("Unable to subscribe to channel: \(channel.name)") } } } } } } private func handleMemberAddedEvent(json: PusherEventJSON) { if let data = json["data"] as? String { if let channelName = json["channel"] as? String, chan = self.channels.find(channelName) as? PresencePusherChannel { if let memberJSON = getPusherEventJSONFromString(data) { chan.addMember(memberJSON) } else { print("Unable to add member") } } } } private func handleMemberRemovedEvent(json: PusherEventJSON) { if let data = json["data"] as? String { if let channelName = json["channel"] as? String, chan = self.channels.find(channelName) as? PresencePusherChannel { if let memberJSON = getPusherEventJSONFromString(data) { chan.removeMember(memberJSON) } else { print("Unable to remove member") } } } } public func getPusherEventJSONFromString(string: String) -> Dictionary<String, AnyObject>? { let data = (string as NSString).dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false) do { if let jsonData = data, jsonObject = try NSJSONSerialization.JSONObjectWithData(jsonData, options: []) as? Dictionary<String, AnyObject> { return jsonObject } else { // TODO: Move below print("Unable to parse string from WebSocket: \(string)") } } catch let error as NSError { print(error.localizedDescription) } return nil } public func getEventDataJSONFromString(string: String) -> AnyObject { let data = (string as NSString).dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false) do { if let jsonData = data, jsonObject: AnyObject = try NSJSONSerialization.JSONObjectWithData(jsonData, options: []) { return jsonObject } else { print("Returning data string instead because unable to parse string as JSON - check that your JSON is valid.") } } catch let error as NSError { print("Returning data string instead because unable to parse string as JSON - check that your JSON is valid.") print(error.localizedDescription) } return string } public func handleEvent(eventName: String, jsonObject: Dictionary<String,AnyObject>) { switch eventName { case "pusher_internal:subscription_succeeded": handleSubscriptionSucceededEvent(jsonObject) case "pusher:connection_established": handleConnectionEstablishedEvent(jsonObject) case "pusher_internal:member_added": handleMemberAddedEvent(jsonObject) case "pusher_internal:member_removed": handleMemberRemovedEvent(jsonObject) default: callGlobalCallbacks(eventName, jsonObject: jsonObject) if let channelName = jsonObject["channel"] as? String, internalChannel = self.channels.find(channelName) { if let eName = jsonObject["event"] as? String, eData = jsonObject["data"] as? String { internalChannel.handleEvent(eName, eventData: eData) } } } } private func callGlobalCallbacks(eventName: String, jsonObject: Dictionary<String,AnyObject>) { if let channelName = jsonObject["channel"] as? String, eName = jsonObject["event"] as? String, eData = jsonObject["data"] as? String { if let globalChannel = self.globalChannel { globalChannel.handleEvent(channelName, eventName: eName, eventData: eData) } } } private func authorize(channel: PusherChannel, callback: ((Dictionary<String, String>?) -> Void)? = nil) -> Bool { if !isPresenceChannel(channel.name) && !isPrivateChannel(channel.name) { subscribeToNormalChannel(channel) } else if let endpoint = self.options.authEndpoint where self.options.authMethod == .Endpoint { if let socket = self.socketId { sendAuthorisationRequest(endpoint, socket: socket, channel: channel, callback: callback) } else { print("socketId value not found. You may not be connected.") return false } } else if let secret = self.options.secret where self.options.authMethod == .Internal { var msg = "" var channelData = "" if isPresenceChannel(channel.name) { channelData = getUserDataJSON() msg = "\(self.socketId!):\(channel.name):\(channelData)" } else { msg = "\(self.socketId!):\(channel.name)" } let secretBuff = UnsafeMutablePointer<UInt8>.alloc(secret.utf8.count) for (index, value) in secret.utf8.enumerate() { secretBuff[index] = value } var msgBuff = [UInt8]() msgBuff += msg.utf8 let hmacBuff = CC_SHA256(msgBuff, CC_LONG(msgBuff.count), secretBuff) let signature = NSData(bytes: hmacBuff, length: 32).toHexString() let auth = "\(self.key):\(signature)".lowercaseString if isPrivateChannel(channel.name) { self.handlePrivateChannelAuth(auth, channel: channel, callback: callback) } else { self.handlePresenceChannelAuth(auth, channel: channel, channelData: channelData, callback: callback) } } else { print("Authentication method required for private / presence channels but none provided.") return false } return true } private func getUserDataJSON() -> String { if let userDataFetcher = self.options.userDataFetcher { let userData = userDataFetcher() if let userInfo: AnyObject = userData.userInfo { return JSONStringify(["user_id": userData.userId, "user_info": userInfo]) } else { return JSONStringify(["user_id": userData.userId]) } } else { if let socketId = self.socketId { return JSONStringify(["user_id": socketId]) } else { print("Authentication failed. You may not be connected") return "" } } } private func subscribeToNormalChannel(channel: PusherChannel) { self.sendEvent("pusher:subscribe", data: [ "channel": channel.name ] ) } private func sendAuthorisationRequest(endpoint: String, socket: String, channel: PusherChannel, callback: ((Dictionary<String, String>?) -> Void)? = nil) { guard let url = NSURL(string: endpoint) else { print("Malformed auth endpoint: \(endpoint)") return } var request = NSMutableURLRequest(URL: url) request.HTTPMethod = "POST" let bodyData = "socket_id=\(socket)&channel_name=\(channel.name)".dataUsingEncoding(NSUTF8StringEncoding) request.HTTPBody = bodyData request.allHTTPHeaderFields = [ "Content-Type": "application/x-www-form-urlencoded" ] if let handler = self.options.authRequestCustomizer { request = handler(request) } let task = URLSession.dataTaskWithRequest(request, completionHandler: { data, response, error in if error != nil { print("Error authorizing channel [\(channel.name)]: \(error)") } if let httpResponse = response as? NSHTTPURLResponse where (httpResponse.statusCode >= 200 && httpResponse.statusCode < 300) { do { if let json = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? Dictionary<String, AnyObject> { self.handleAuthResponse(json, channel: channel, callback: callback) } } catch { print("Error authorizing channel [\(channel.name)]") } } else { if let d = data { print ("Error authorizing channel [\(channel.name)]: \(String(data: d, encoding: NSUTF8StringEncoding))") } else { print("Error authorizing channel [\(channel.name)]") } } }) task.resume() } private func handleAuthResponse(json: Dictionary<String, AnyObject>, channel: PusherChannel, callback: ((Dictionary<String, String>?) -> Void)? = nil) { if let auth = json["auth"] as? String { if let channelData = json["channel_data"] as? String { handlePresenceChannelAuth(auth, channel: channel, channelData: channelData, callback: callback) } else { handlePrivateChannelAuth(auth, channel: channel, callback: callback) } } } private func handlePresenceChannelAuth(auth: String, channel: PusherChannel, channelData: String, callback: ((Dictionary<String, String>?) -> Void)? = nil) { if let cBack = callback { cBack(["auth": auth, "channel_data": channelData]) } else { self.sendEvent("pusher:subscribe", data: [ "channel": channel.name, "auth": auth, "channel_data": channelData ] ) } } private func handlePrivateChannelAuth(auth: String, channel: PusherChannel, callback: ((Dictionary<String, String>?) -> Void)? = nil) { if let cBack = callback { cBack(["auth": auth]) } else { self.sendEvent("pusher:subscribe", data: [ "channel": channel.name, "auth": auth ] ) } } // MARK: WebSocketDelegate Implementation public func websocketDidReceiveMessage(ws: WebSocket, text: String) { if let pusherPayloadObject = getPusherEventJSONFromString(text), eventName = pusherPayloadObject["event"] as? String { self.handleEvent(eventName, jsonObject: pusherPayloadObject) } else { print("Unable to handle incoming Websocket message") } } public func websocketDidDisconnect(ws: WebSocket, error: NSError?) { if let error = error { print("Websocket is disconnected: \(error.localizedDescription)") } self.connected = false for (_, channel) in self.channels.channels { channel.subscribed = false } if let reconnect = self.options.autoReconnect where reconnect { print("Attempting to reconnect") let reachability = try! Reachability.reachabilityForInternetConnection() if let reachability = try? Reachability.reachabilityForInternetConnection() { if reachability.currentReachabilityStatus == .NotReachable { print("Network not currently reachable, will attempt reconnect when reachability is reestablished") reachability.whenReachable = { [weak self] reachability in if self?.connected == nil || self?.connected == false { print("Reachability reestablished, reconnecting") self?.socket.connect() } } } else { print("Reachability confirmed, reconnecting") self.socket.connect() } } else { print("Unable to confirm reachability, attempting to reconnect anyway") self.socket.connect() } if let _ = try? reachability.startNotifier() {} } } public func websocketDidConnect(ws: WebSocket) {} public func websocketDidReceiveData(ws: WebSocket, data: NSData) {} } public struct EventHandler { let id: String let callback: (AnyObject?) -> Void } public class PusherChannel { public var eventHandlers: [String: [EventHandler]] = [:] public var subscribed = false public let name: String public let connection: PusherConnection public var unsentEvents = [String: AnyObject]() public init(name: String, connection: PusherConnection) { self.name = name self.connection = connection } public func bind(eventName: String, callback: (AnyObject?) -> Void) -> String { let randomId = NSUUID().UUIDString let eventHandler = EventHandler(id: randomId, callback: callback) if self.eventHandlers[eventName] != nil { self.eventHandlers[eventName]?.append(eventHandler) } else { self.eventHandlers[eventName] = [eventHandler] } return randomId } public func unbind(eventName: String, callbackId: String) { if let eventSpecificHandlers = self.eventHandlers[eventName] { self.eventHandlers[eventName] = eventSpecificHandlers.filter({ $0.id != callbackId }) } } public func unbindAll() { self.eventHandlers = [:] } public func unbindAllForEventName(eventName: String) { self.eventHandlers[eventName] = [] } public func handleEvent(eventName: String, eventData: String) { if let eventHandlerArray = self.eventHandlers[eventName] { if let _ = connection.options.attemptToReturnJSONObject { for eventHandler in eventHandlerArray { eventHandler.callback(connection.getEventDataJSONFromString(eventData)) } } else { for eventHandler in eventHandlerArray { eventHandler.callback(eventData) } } } } public func trigger(eventName: String, data: AnyObject) { if subscribed { self.connection.sendEvent(eventName, data: data, channelName: self.name) } else { unsentEvents[eventName] = data } } } public class PresencePusherChannel: PusherChannel { public var members: [PresenceChannelMember] override init(name: String, connection: PusherConnection) { self.members = [] super.init(name: name, connection: connection) } private func addMember(memberJSON: Dictionary<String, AnyObject>) { if let userId = memberJSON["user_id"] as? String { if let userInfo = memberJSON["user_info"] as? PusherUserInfoObject { members.append(PresenceChannelMember(userId: userId, userInfo: userInfo)) } else { members.append(PresenceChannelMember(userId: userId)) } } else if let userId = memberJSON["user_id"] as? Int { if let userInfo = memberJSON["user_info"] as? PusherUserInfoObject { members.append(PresenceChannelMember(userId: String(userId), userInfo: userInfo)) } else { members.append(PresenceChannelMember(userId: String(userId))) } } } private func addExistingMembers(memberHash: Dictionary<String, AnyObject>) { for (userId, userInfo) in memberHash { if let userInfo = userInfo as? PusherUserInfoObject { self.members.append(PresenceChannelMember(userId: userId, userInfo: userInfo)) } else { self.members.append(PresenceChannelMember(userId: userId)) } } } private func removeMember(memberJSON: Dictionary<String, AnyObject>) { if let userId = memberJSON["user_id"] as? String { self.members = self.members.filter({ $0.userId != userId }) } else if let userId = memberJSON["user_id"] as? Int { self.members = self.members.filter({ $0.userId != String(userId) }) } } } public struct PresenceChannelMember { public let userId: String public let userInfo: AnyObject? public init(userId: String, userInfo: AnyObject? = nil) { self.userId = userId self.userInfo = userInfo } } public class GlobalChannel: PusherChannel { public var globalCallbacks: [String: (AnyObject?) -> Void] = [:] init(connection: PusherConnection) { super.init(name: "pusher_global_internal_channel", connection: connection) } private func handleEvent(channelName: String, eventName: String, eventData: String) { for (_, callback) in self.globalCallbacks { callback(["channel": channelName, "event": eventName, "data": eventData]) } } private func bind(callback: (AnyObject?) -> Void) -> String { let randomId = NSUUID().UUIDString self.globalCallbacks[randomId] = callback return randomId } private func unbind(callbackId: String) { globalCallbacks.removeValueForKey(callbackId) } override public func unbindAll() { globalCallbacks = [:] } } public class PusherChannels { public var channels = [String: PusherChannel]() private func add(channelName: String, connection: PusherConnection) -> PusherChannel { if let channel = self.channels[channelName] { return channel } else { var newChannel: PusherChannel if isPresenceChannel(channelName) { newChannel = PresencePusherChannel(name: channelName, connection: connection) } else { newChannel = PusherChannel(name: channelName, connection: connection) } self.channels[channelName] = newChannel return newChannel } } private func remove(channelName: String) { self.channels.removeValueForKey(channelName) } private func find(channelName: String) -> PusherChannel? { return self.channels[channelName] } } private func isPresenceChannel(channelName: String) -> Bool { return (channelName.componentsSeparatedByString("-")[0] == "presence") ? true : false } private func isPrivateChannel(channelName: String) -> Bool { return (channelName.componentsSeparatedByString("-")[0] == "private") ? true : false } extension NSData { func toHexString() -> String { if length == 0 { return "" } var dataBuffer = [UInt8](count: 0, repeatedValue: 0) getBytes(&dataBuffer, length: length) let hexString: NSMutableString = "" for byte in dataBuffer { hexString.appendFormat("%02lx", byte) } return hexString as String } }
mit
c016f1c5df034e191b41c5d4375b3dd9
36.36423
173
0.601398
5.007874
false
false
false
false
IBM-Swift/Kitura-net
Sources/KituraNet/ClientRequest.swift
1
29812
/* * 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 LoggerAPI import CCurl import Socket import Foundation // The public API for ClientRequest erroneously defines the port as an Int16, which is // insufficient to hold all possible port values. To avoid a breaking change, we allow // UInt16 bit patterns to be passed in, under the guises of an Int16, which we will // then convert back to UInt16. // // User code must perform the equivalent conversion in order to pass in a value that // is greater than Int16.max. // fileprivate extension Int16 { func toUInt16() -> UInt16 { return UInt16(bitPattern: self) } } // MARK: ClientRequest /** This class provides a set of low level APIs for issuing HTTP requests to another server. A new instance of the request can be created, along with options if the user would like to specify certain parameters such as HTTP headers, HTTP methods, host names, and SSL credentials. `Data` and `String` objects can be added to a `ClientRequest` too, and URLs can be parsed. ### Usage Example: ### ````swift //Function to create a new `ClientRequest` using a URL. public static func request(_ url: String, callback: @escaping ClientRequest.Callback) -> ClientRequest { return ClientRequest(url: url, callback: callback) } //Create a new `ClientRequest` using a URL. let request = HTTP.request("http://localhost/8080") {response in ... } ```` */ public class ClientRequest { /// Initialize the one time initialization struct to cause one time initializations to occur static private let oneTime = OneTimeInitializations() /** The set of HTTP headers to be sent with the request. ### Usage Example: ### ````swift clientRequest.headers["Content-Type"] = ["text/plain"] ```` */ public var headers = [String: String]() /** The URL for the request. ### Usage Example: ### ````swift clientRequest.url = "https://localhost:8080" ```` */ public private(set) var url: String = "" /** The HTTP method (i.e. GET, POST, PUT, DELETE) for the request. ### Usage Example: ### ````swift clientRequest.method = "post" ```` */ public private(set) var method: String = "get" /** The username to be used if using Basic Auth authentication. ### Usage Example: ### ````swift clientRequest.userName = "user1" ```` */ public private(set) var userName: String? /** The password to be used if using Basic Auth authentication. ### Usage Example: ### ````swift clientRequest.password = "sUpeR_seCurE_paSsw0rd" ```` */ public private(set) var password: String? /** The maximum number of redirects before failure. - Note: The `ClientRequest` class will automatically follow redirect responses. To avoid redirect loops, it will at maximum follow `maxRedirects` redirects. ### Usage Example: ### ````swift clientRequest.maxRedirects = 10 ```` */ public private(set) var maxRedirects = 10 /** If true, the "Connection: close" header will be added to the request that is sent. ### Usage Example: ### ````swift ClientRequest.closeConnection = false ```` */ public private(set) var closeConnection = false /// Handle for working with libCurl private var handle: UnsafeMutableRawPointer? /// List of header information private var headersList: UnsafeMutablePointer<curl_slist>? /// BufferList to store bytes to be written fileprivate var writeBuffers = BufferList() /// Response instance for communicating with client fileprivate var response: ClientResponse? /// The callback to receive the response private var callback: Callback /// Should SSL verification be disabled private var disableSSLVerification = false /// Should HTTP/2 protocol be used private var useHTTP2 = false /// The Unix domain socket path used for the request private var unixDomainSocketPath: String? = nil /// Data that represents the "HTTP/2 " header status line prefix fileprivate static let Http2StatusLineVersion = "HTTP/2 ".data(using: .utf8)! /// Data that represents the "HTTP/2.0 " (with a minor) header status line prefix fileprivate static let Http2StatusLineVersionWithMinor = "HTTP/2.0 ".data(using: .utf8)! /// The hostname of the remote server private var hostName: String? /// The port number of the remote server private var port: Int? private var path = "" /** Client request options enum. This allows the client to specify certain parameteres such as HTTP headers, HTTP methods, host names, and SSL credentials. ### Usage Example: ### ````swift //If present in the options provided, the client will try to use HTTP/2 protocol for the connection. Options.useHTTP2 ```` */ public enum Options { /// Specifies the HTTP method (i.e. PUT, POST...) to be sent in the request case method(String) /// Specifies the schema (i.e. HTTP, HTTPS) to be used in the URL of request case schema(String) /// Specifies the host name to be used in the URL of request case hostname(String) /// Specifies the port to be used in the URL of request. /// /// Note that an Int16 is incapable of representing all possible port values, however /// it forms part of the Kitura-net 2.0 API. In order to pass a port number greater /// than 32,767 (Int16.max), use the following code: /// ``` /// let portNumber: UInt16 = 65535 /// let portOption: ClientRequest.Options = .port(Int16(bitPattern: portNumber)) /// ``` case port(Int16) /// Specifies the path to be used in the URL of request case path(String) /// Specifies the HTTP headers to be sent with the request case headers([String: String]) /// Specifies the user name to be sent with the request, when using basic auth authentication case username(String) /// Specifies the password to be sent with the request, when using basic auth authentication case password(String) /// Specifies the maximum number of redirect responses that will be followed (i.e. re-issue the /// request to the location received in the redirect response) case maxRedirects(Int) /// If present, the SSL credentials of the remote server will not be verified. /// /// - Note: This is very useful when working with self signed certificates. case disableSSLVerification /// If present, the client will try to use HTTP/2 protocol for the connection. case useHTTP2 } /** Response callback closure type. ### Usage Example: ### ````swift var ClientRequest.headers["Content-Type"] = ["text/plain"] ```` - Parameter ClientResponse: The `ClientResponse` object that describes the response that was received from the remote server. */ public typealias Callback = (ClientResponse?) -> Void /// Initializes a `ClientRequest` instance /// /// - Parameter url: url for the request /// - Parameter callback: The closure of type `Callback` to be used for the callback. init(url: String, callback: @escaping Callback) { self.url = url self.callback = callback if let url = URL(string: url) { removeHttpCredentialsFromUrl(url) } } private func removeHttpCredentialsFromUrl(_ url: URL) { if let host = url.host { self.hostName = host } if let port = url.port { self.port = port } if let username = url.user { self.userName = username } if let password = url.password { self.password = password } var fullPath = url.path // query strings and parameters need to be appended here if let query = url.query { fullPath += "?" fullPath += query } self.path = fullPath self.url = "\(url.scheme ?? "http")://\(self.hostName ?? "unknown")\(self.port.map { ":\($0)" } ?? "")\(fullPath)" if let username = self.userName, let password = self.password { self.headers["Authorization"] = createHTTPBasicAuthHeader(username: username, password: password) } return } /// Initializes a `ClientRequest` instance /// /// - Parameter options: An array of `Options' describing the request. /// - Parameter unixDomainSocketPath: Specifies the path of a Unix domain socket that the client should connect to. /// - Parameter callback: The closure of type `Callback` to be used for the callback. init(options: [Options], unixDomainSocketPath: String? = nil, callback: @escaping Callback) { self.unixDomainSocketPath = unixDomainSocketPath self.callback = callback var theSchema = "http://" var hostName = "localhost" var path = "" var port = "" for option in options { switch(option) { case .method, .headers, .maxRedirects, .disableSSLVerification, .useHTTP2: // call set() for Options that do not construct the URL set(option) case .schema(var schema): if !schema.contains("://") && !schema.isEmpty { schema += "://" } theSchema = schema case .hostname(let host): hostName = host case .port(let thePort): let portNumber = thePort.toUInt16() port = ":\(portNumber)" case .path(var thePath): if thePath.first != "/" { thePath = "/" + thePath } path = thePath case .username(let userName): self.userName = userName case .password(let password): self.password = password } } if let username = self.userName, let password = self.password { self.headers["Authorization"] = createHTTPBasicAuthHeader(username: username, password: password) } url = "\(theSchema)\(hostName)\(port)\(path)" } /** Set a single option in the request. URL parameters must be set in init(). ### Usage Example: ### ````swift var options: [ClientRequest.Options] = [] options.append(.port(Int16(port))) clientRequest.set(options) ```` - Parameter option: An `Options` instance describing the change to be made to the request. */ public func set(_ option: Options) { switch(option) { case .schema, .hostname, .port, .path, .username, .password: Log.error("Must use ClientRequest.init() to set URL components") case .method(let method): self.method = method case .headers(let headers): for (key, value) in headers { self.headers[key] = value } case .maxRedirects(let maxRedirects): self.maxRedirects = maxRedirects case .disableSSLVerification: self.disableSSLVerification = true case .useHTTP2: self.useHTTP2 = true } } /** Parse an URL (String) into an array of ClientRequest.Options. ### Usage Example: ### ````swift let url: String = "http://www.website.com" let parsedOptions = clientRequest.parse(url) ```` - Parameter urlString: A String object referencing a URL. - Returns: An array of `ClientRequest.Options` */ public class func parse(_ urlString: String) -> [ClientRequest.Options] { if let url = URL(string: urlString) { return parse(url) } return [] } /** Parse an URL Foudation object into an array of ClientRequest.Options. ### Usage Example: ### ````swift let url: URL = URL(string: "http://www.website.com")! let parsedOptions = clientRequest.parse(url) ```` - Parameter url: Foundation URL object. - Returns: An array of `ClientRequest.Options` */ public class func parse(_ url: URL) -> [ClientRequest.Options] { var options: [ClientRequest.Options] = [] if let scheme = url.scheme { options.append(.schema("\(scheme)://")) } if let host = url.host { options.append(.hostname(host)) } var fullPath = url.path // query strings and parameters need to be appended here if let query = url.query { fullPath += "?" fullPath += query } options.append(.path(fullPath)) if let port = url.port { options.append(.port(Int16(bitPattern: UInt16(port)))) } if let username = url.user { options.append(.username(username)) } if let password = url.password { options.append(.password(password)) } return options } /// Instance destruction deinit { if let handle = handle { curl_easy_cleanup(handle) } if headersList != nil { curl_slist_free_all(headersList) } } /** Add a String to the body of the request to be sent. ### Usage Example: ### ````swift let stringToSend: String = "send something" clientRequest.write(from: stringToSend) ```` - Parameter from: The String to be added to the request. */ public func write(from string: String) { if let data = string.data(using: .utf8) { write(from: data) } } /** Add the bytes in a Data struct to the body of the request to be sent. ### Usage Example: ### ````swift let string = "some some more stuff" if let data: Data = string.data(using: .utf8) { clientRequest.write(from: data) } ```` - Parameter from: The Data Struct containing the bytes to be added to the request. */ public func write(from data: Data) { writeBuffers.append(data: data) } /** Add a String to the body of the request to be sent and then send the request to the remote server. ### Usage Example: ### ````swift let data: String = "send something" clientRequest.end(from: data, close: true) ```` - Parameter data: The String to be added to the request. - Parameter close: If true, add the "Connection: close" header to the set of headers sent with the request. */ public func end(_ data: String, close: Bool = false) { write(from: data) end(close: close) } /** Add the bytes in a Data struct to the body of the request to be sent and then send the request to the remote server. ### Usage Example: ### ````swift let stringToSend = "send this" let data: Data = stringToSend.data(using: .utf8) { clientRequest.end(from: data, close: true) } ```` - Parameter data: The Data struct containing the bytes to be added to the request. - Parameter close: If true, add the "Connection: close" header to the set of headers sent with the request. */ public func end(_ data: Data, close: Bool = false) { write(from: data) end(close: close) } /** Send the request to the remote server. ### Usage Example: ### ````swift clientRequest.end(true) ```` - Parameter close: If true, add the "Connection: close" header to the set of headers sent with the request. */ public func end(close: Bool = false) { closeConnection = close guard let urlBuffer = url.cString(using: .utf8) else { callback(nil) return } prepareHandle(using: urlBuffer) let invoker = CurlInvoker(handle: handle!, maxRedirects: maxRedirects) invoker.delegate = self let skipBody = (method.uppercased() == "HEAD") response = ClientResponse(skipBody: skipBody) var code = invoker.invoke() guard code == CURLE_OK else { Log.error("ClientRequest Error, Failed to invoke HTTP request. CURL Return code=\(code)") callback(nil) return } code = curlHelperGetInfoLong(handle!, CURLINFO_RESPONSE_CODE, &response!.status) guard code == CURLE_OK else { Log.error("ClientRequest Error. Failed to get response code. CURL Return code=\(code)") callback(nil) return } var httpStatusCode = response!.httpStatusCode repeat { let parseStatus = response!.parse() guard parseStatus.error == nil else { Log.error("ClientRequest error. Failed to parse response. Error=\(parseStatus.error!)") callback(nil) return } guard parseStatus.state == .messageComplete else { Log.error("ClientRequest error. Failed to parse response. Status=\(parseStatus.state)") callback(nil) return } httpStatusCode = response!.httpStatusCode } while httpStatusCode == .continue || httpStatusCode == .switchingProtocols self.callback(self.response) } /// Prepare the handle /// /// Parameter using: The URL to use when preparing the handle private func prepareHandle(using urlBuffer: [CChar]) { handle = curl_easy_init() // HTTP parser does the decoding curlHelperSetOptInt(handle!, CURLOPT_HTTP_TRANSFER_DECODING, 0) curlHelperSetOptString(self.handle!, CURLOPT_URL, UnsafePointer(urlBuffer)) if disableSSLVerification { curlHelperSetOptInt(handle!, CURLOPT_SSL_VERIFYHOST, 0) curlHelperSetOptInt(handle!, CURLOPT_SSL_VERIFYPEER, 0) } setMethodAndContentLength() setupHeaders() curlHelperSetOptString(handle!, CURLOPT_COOKIEFILE, "") // To see the messages sent by libCurl, uncomment the next line of code //curlHelperSetOptInt(handle, CURLOPT_VERBOSE, 1) if useHTTP2 { curlHelperSetOptInt(handle!, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_2_0) } if let socketPath = unixDomainSocketPath?.cString(using: .utf8) { curlHelperSetUnixSocketPath(handle!, UnsafePointer(socketPath)) } } /// Sets the HTTP method and Content-Length in libCurl private func setMethodAndContentLength() { let methodUpperCase = method.uppercased() let count = writeBuffers.count switch(methodUpperCase) { case "GET": curlHelperSetOptBool(handle!, CURLOPT_HTTPGET, CURL_TRUE) case "POST": curlHelperSetOptBool(handle!, CURLOPT_POST, CURL_TRUE) curlHelperSetOptInt(handle!, CURLOPT_POSTFIELDSIZE, count) case "PUT": curlHelperSetOptBool(handle!, CURLOPT_UPLOAD, CURL_TRUE) curlHelperSetOptInt(handle!, CURLOPT_INFILESIZE, count) case "HEAD": curlHelperSetOptBool(handle!, CURLOPT_NOBODY, CURL_TRUE) case "PATCH": curlHelperSetOptString(handle!, CURLOPT_CUSTOMREQUEST, methodUpperCase) curlHelperSetOptBool(handle!, CURLOPT_UPLOAD, CURL_TRUE) curlHelperSetOptInt(handle!, CURLOPT_INFILESIZE, count) default: curlHelperSetOptString(handle!, CURLOPT_CUSTOMREQUEST, methodUpperCase) } } /// Sets the headers in libCurl to the ones in headers private func setupHeaders() { if closeConnection { headers["Connection"] = "close" } // Unless the user has provided an Expect header, set an empty one to disable // curl's default Expect: 100-continue behaviour, since Kitura does not support it. if !headers.keys.contains("Expect") { headers["Expect"] = "" } for (headerKey, headerValue) in headers { if let headerString = "\(headerKey): \(headerValue)".cString(using: .utf8) { headersList = curl_slist_append(headersList, UnsafePointer(headerString)) } } curlHelperSetOptList(handle!, CURLOPT_HTTPHEADER, headersList) } private func createHTTPBasicAuthHeader(username: String, password: String) -> String { let authHeader = "\(username):\(password)" let data = Data(authHeader.utf8) return "Basic \(data.base64EncodedString())" } } // MARK: CurlInvokerDelegate extension extension ClientRequest: CurlInvokerDelegate { /// libCurl callback to recieve data sent by the server fileprivate func curlWriteCallback(_ buf: UnsafeMutablePointer<Int8>, size: Int) -> Int { response?.responseBuffers.append(bytes: UnsafeRawPointer(buf).assumingMemoryBound(to: UInt8.self), length: size) return size } /// libCurl callback to provide the data to send to the server fileprivate func curlReadCallback(_ buf: UnsafeMutablePointer<Int8>, size: Int) -> Int { let count = writeBuffers.fill(buffer: UnsafeMutableRawPointer(buf).assumingMemoryBound(to: UInt8.self), length: size) return count } /// libCurl callback to recieve header sent by the server. Being called per each header line. fileprivate func curlHeaderCallback(_ buf: UnsafeMutablePointer<Int8>, size: Int) -> Int { // If the header status line begins with 'HTTP/2 ' we replace it with 'HTTP/2.0' because // otherwise the CHTTPParser will parse this line incorrectly and won't extract the status code #if swift(>=5.0) ClientRequest.Http2StatusLineVersion.withUnsafeBytes() { (rawPtr: UnsafeRawBufferPointer) -> Void in if memcmp(rawPtr.baseAddress!, buf, ClientRequest.Http2StatusLineVersion.count) == 0 { ClientRequest.Http2StatusLineVersionWithMinor.withUnsafeBytes() { (p: UnsafeRawBufferPointer) -> Void in response?.responseBuffers.append(bytes: p.bindMemory(to: UInt8.self).baseAddress!, length: ClientRequest.Http2StatusLineVersionWithMinor.count) response?.responseBuffers.append(bytes: UnsafeRawPointer(buf).assumingMemoryBound(to: UInt8.self) + ClientRequest.Http2StatusLineVersion.count, length: size - ClientRequest.Http2StatusLineVersion.count) } } else { response?.responseBuffers.append(bytes: UnsafeRawPointer(buf).assumingMemoryBound(to: UInt8.self), length: size) } } #else ClientRequest.Http2StatusLineVersion.withUnsafeBytes() { (ptr: UnsafePointer<UInt8>) -> Void in if memcmp(ptr, buf, ClientRequest.Http2StatusLineVersion.count) == 0 { ClientRequest.Http2StatusLineVersionWithMinor.withUnsafeBytes() { (p: UnsafePointer<UInt8>) -> Void in response?.responseBuffers.append(bytes: p, length: ClientRequest.Http2StatusLineVersionWithMinor.count) response?.responseBuffers.append(bytes: UnsafeRawPointer(buf).assumingMemoryBound(to: UInt8.self) + ClientRequest.Http2StatusLineVersion.count, length: size - ClientRequest.Http2StatusLineVersion.count) } } else { response?.responseBuffers.append(bytes: UnsafeRawPointer(buf).assumingMemoryBound(to: UInt8.self), length: size) } } #endif return size } /// libCurl callback invoked when a redirect is about to be done fileprivate func prepareForRedirect() { response?.responseBuffers.reset() writeBuffers.rewind() } } /// Helper class for invoking commands through libCurl private class CurlInvoker { /// Pointer to the libCurl handle private var handle: UnsafeMutableRawPointer /// Delegate that can have a read or write callback fileprivate weak var delegate: CurlInvokerDelegate? /// Maximum number of redirects private let maxRedirects: Int /// Initializes a new CurlInvoker instance fileprivate init(handle: UnsafeMutableRawPointer, maxRedirects: Int) { self.handle = handle self.maxRedirects = maxRedirects } /// Run the HTTP method through the libCurl library /// /// - Returns: a status code for the success of the operation fileprivate func invoke() -> CURLcode { var rc: CURLcode = CURLE_FAILED_INIT guard let delegate = self.delegate else { return rc } withUnsafeMutablePointer(to: &self.delegate) {ptr in self.prepareHandle(ptr) var redirected = false var redirectCount = 0 repeat { rc = curl_easy_perform(handle) if rc == CURLE_OK { var redirectUrl: UnsafeMutablePointer<Int8>? = nil let infoRc = curlHelperGetInfoCString(handle, CURLINFO_REDIRECT_URL, &redirectUrl) if infoRc == CURLE_OK { if redirectUrl != nil { redirectCount += 1 if redirectCount <= maxRedirects { // Prepare to do a redirect curlHelperSetOptString(handle, CURLOPT_URL, redirectUrl) var status: Int = -1 let codeRc = curlHelperGetInfoLong(handle, CURLINFO_RESPONSE_CODE, &status) // If the status code was 303 See Other, ensure that // the redirect is done with a GET query rather than // whatever might have just been used. if codeRc == CURLE_OK && status == 303 { _ = curlHelperSetOptInt(handle, CURLOPT_HTTPGET, 1) } redirected = true delegate.prepareForRedirect() } else { redirected = false } } else { redirected = false } } } } while rc == CURLE_OK && redirected } return rc } /// Prepare the handle /// /// - Parameter ptr: pointer to the CurlInvokerDelegat private func prepareHandle(_ ptr: UnsafeMutablePointer<CurlInvokerDelegate?>) { curlHelperSetOptReadFunc(handle, ptr) { (buf: UnsafeMutablePointer<Int8>?, size: Int, nMemb: Int, privateData: UnsafeMutableRawPointer?) -> Int in let p = privateData?.assumingMemoryBound(to: CurlInvokerDelegate.self).pointee return (p?.curlReadCallback(buf!, size: size*nMemb))! } curlHelperSetOptWriteFunc(handle, ptr) { (buf: UnsafeMutablePointer<Int8>?, size: Int, nMemb: Int, privateData: UnsafeMutableRawPointer?) -> Int in let p = privateData?.assumingMemoryBound(to: CurlInvokerDelegate.self).pointee return (p?.curlWriteCallback(buf!, size: size*nMemb))! } curlHelperSetOptHeaderFunc(handle, ptr) { (buf: UnsafeMutablePointer<Int8>?, size: Int, nMemb: Int, privateData: UnsafeMutableRawPointer?) -> Int in let p = privateData?.assumingMemoryBound(to: CurlInvokerDelegate.self).pointee return (p?.curlHeaderCallback(buf!, size: size*nMemb))! } } } /// Delegate protocol for objects operated by CurlInvoker private protocol CurlInvokerDelegate: class { func curlWriteCallback(_ buf: UnsafeMutablePointer<Int8>, size: Int) -> Int func curlReadCallback(_ buf: UnsafeMutablePointer<Int8>, size: Int) -> Int func curlHeaderCallback(_ buf: UnsafeMutablePointer<Int8>, size: Int) -> Int func prepareForRedirect() } /// Singleton struct for one time initializations private struct OneTimeInitializations { init() { curl_global_init(Int(CURL_GLOBAL_SSL)) } }
apache-2.0
fbd326c5486b7db770024586281f2a8c
34.114252
366
0.594995
4.71336
false
false
false
false
hanquochan/Charts
Source/Charts/Charts/ChartViewBase.swift
6
37456
// // ChartViewBase.swift // Charts // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/Charts // // Based on https://github.com/PhilJay/MPAndroidChart/commit/c42b880 import Foundation import CoreGraphics #if !os(OSX) import UIKit #endif @objc public protocol ChartViewDelegate { /// Called when a value has been selected inside the chart. /// - parameter entry: The selected Entry. /// - parameter highlight: The corresponding highlight object that contains information about the highlighted position such as dataSetIndex etc. @objc optional func chartValueSelected(_ chartView: ChartViewBase, entry: ChartDataEntry, highlight: Highlight) // Called when nothing has been selected or an "un-select" has been made. @objc optional func chartValueNothingSelected(_ chartView: ChartViewBase) // Callbacks when the chart is scaled / zoomed via pinch zoom gesture. @objc optional func chartScaled(_ chartView: ChartViewBase, scaleX: CGFloat, scaleY: CGFloat) // Callbacks when the chart is moved / translated via drag gesture. @objc optional func chartTranslated(_ chartView: ChartViewBase, dX: CGFloat, dY: CGFloat) } open class ChartViewBase: NSUIView, ChartDataProvider, AnimatorDelegate { // MARK: - Properties /// - returns: The object representing all x-labels, this method can be used to /// acquire the XAxis object and modify it (e.g. change the position of the /// labels) open var xAxis: XAxis { return _xAxis } /// The default IValueFormatter that has been determined by the chart considering the provided minimum and maximum values. internal var _defaultValueFormatter: IValueFormatter? = DefaultValueFormatter(decimals: 0) /// object that holds all data that was originally set for the chart, before it was modified or any filtering algorithms had been applied internal var _data: ChartData? /// Flag that indicates if highlighting per tap (touch) is enabled fileprivate var _highlightPerTapEnabled = true /// If set to true, chart continues to scroll after touch up open var dragDecelerationEnabled = true /// Deceleration friction coefficient in [0 ; 1] interval, higher values indicate that speed will decrease slowly, for example if it set to 0, it will stop immediately. /// 1 is an invalid value, and will be converted to 0.999 automatically. fileprivate var _dragDecelerationFrictionCoef: CGFloat = 0.9 /// if true, units are drawn next to the values in the chart internal var _drawUnitInChart = false /// The object representing the labels on the x-axis internal var _xAxis: XAxis! /// The `Description` object of the chart. /// This should have been called just "description", but open var chartDescription: Description? /// This property is deprecated - Use `chartDescription.text` instead. @available(*, deprecated: 1.0, message: "Use `chartDescription.text` instead.") open var descriptionText: String { get { return chartDescription?.text ?? "" } set { chartDescription?.text = newValue } } /// This property is deprecated - Use `chartDescription.font` instead. @available(*, deprecated: 1.0, message: "Use `chartDescription.font` instead.") open var descriptionFont: NSUIFont? { get { return chartDescription?.font } set { if let value = newValue { chartDescription?.font = value } } } /// This property is deprecated - Use `chartDescription.textColor` instead. @available(*, deprecated: 1.0, message: "Use `chartDescription.textColor` instead.") open var descriptionTextColor: NSUIColor? { get { return chartDescription?.textColor } set { if let value = newValue { chartDescription?.textColor = value } } } /// This property is deprecated - Use `chartDescription.textAlign` instead. @available(*, deprecated: 1.0, message: "Use `chartDescription.textAlign` instead.") open var descriptionTextAlign: NSTextAlignment { get { return chartDescription?.textAlign ?? NSTextAlignment.right } set { chartDescription?.textAlign = newValue } } /// This property is deprecated - Use `chartDescription.position` instead. @available(*, deprecated: 1.0, message: "Use `chartDescription.position` instead.") open var descriptionTextPosition: CGPoint? { get { return chartDescription?.position } set { chartDescription?.position = newValue } } /// The legend object containing all data associated with the legend internal var _legend: Legend! /// delegate to receive chart events open weak var delegate: ChartViewDelegate? /// text that is displayed when the chart is empty open var noDataText = "No chart data available." /// Font to be used for the no data text. open var noDataFont: NSUIFont! = NSUIFont(name: "HelveticaNeue", size: 12.0) /// color of the no data text open var noDataTextColor: NSUIColor = NSUIColor.black internal var _legendRenderer: LegendRenderer! /// object responsible for rendering the data open var renderer: DataRenderer? open var highlighter: IHighlighter? /// object that manages the bounds and drawing constraints of the chart internal var _viewPortHandler: ViewPortHandler! /// object responsible for animations internal var _animator: Animator! /// flag that indicates if offsets calculation has already been done or not fileprivate var _offsetsCalculated = false /// array of Highlight objects that reference the highlighted slices in the chart internal var _indicesToHighlight = [Highlight]() /// `true` if drawing the marker is enabled when tapping on values /// (use the `marker` property to specify a marker) open var drawMarkers = true /// - returns: `true` if drawing the marker is enabled when tapping on values /// (use the `marker` property to specify a marker) open var isDrawMarkersEnabled: Bool { return drawMarkers } /// The marker that is displayed when a value is clicked on the chart open var marker: IMarker? fileprivate var _interceptTouchEvents = false /// An extra offset to be appended to the viewport's top open var extraTopOffset: CGFloat = 0.0 /// An extra offset to be appended to the viewport's right open var extraRightOffset: CGFloat = 0.0 /// An extra offset to be appended to the viewport's bottom open var extraBottomOffset: CGFloat = 0.0 /// An extra offset to be appended to the viewport's left open var extraLeftOffset: CGFloat = 0.0 open func setExtraOffsets(left: CGFloat, top: CGFloat, right: CGFloat, bottom: CGFloat) { extraLeftOffset = left extraTopOffset = top extraRightOffset = right extraBottomOffset = bottom } // MARK: - Initializers public override init(frame: CGRect) { super.init(frame: frame) initialize() } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) initialize() } deinit { self.removeObserver(self, forKeyPath: "bounds") self.removeObserver(self, forKeyPath: "frame") } internal func initialize() { #if os(iOS) self.backgroundColor = NSUIColor.clear #endif _animator = Animator() _animator.delegate = self _viewPortHandler = ViewPortHandler() _viewPortHandler.setChartDimens(width: bounds.size.width, height: bounds.size.height) chartDescription = Description() _legend = Legend() _legendRenderer = LegendRenderer(viewPortHandler: _viewPortHandler, legend: _legend) _xAxis = XAxis() self.addObserver(self, forKeyPath: "bounds", options: .new, context: nil) self.addObserver(self, forKeyPath: "frame", options: .new, context: nil) } // MARK: - ChartViewBase /// The data for the chart open var data: ChartData? { get { return _data } set { _data = newValue _offsetsCalculated = false if _data == nil { return } // calculate how many digits are needed setupDefaultFormatter(min: _data!.getYMin(), max: _data!.getYMax()) for set in _data!.dataSets { if set.needsFormatter || set.valueFormatter === _defaultValueFormatter { set.valueFormatter = _defaultValueFormatter } } // let the chart know there is new data notifyDataSetChanged() } } /// Clears the chart from all data (sets it to null) and refreshes it (by calling setNeedsDisplay()). open func clear() { _data = nil _offsetsCalculated = false _indicesToHighlight.removeAll() lastHighlighted = nil setNeedsDisplay() } /// Removes all DataSets (and thereby Entries) from the chart. Does not set the data object to nil. Also refreshes the chart by calling setNeedsDisplay(). open func clearValues() { _data?.clearValues() setNeedsDisplay() } /// - returns: `true` if the chart is empty (meaning it's data object is either null or contains no entries). open func isEmpty() -> Bool { guard let data = _data else { return true } if data.entryCount <= 0 { return true } else { return false } } /// Lets the chart know its underlying data has changed and should perform all necessary recalculations. /// It is crucial that this method is called everytime data is changed dynamically. Not calling this method can lead to crashes or unexpected behaviour. open func notifyDataSetChanged() { fatalError("notifyDataSetChanged() cannot be called on ChartViewBase") } /// Calculates the offsets of the chart to the border depending on the position of an eventual legend or depending on the length of the y-axis and x-axis labels and their position internal func calculateOffsets() { fatalError("calculateOffsets() cannot be called on ChartViewBase") } /// calcualtes the y-min and y-max value and the y-delta and x-delta value internal func calcMinMax() { fatalError("calcMinMax() cannot be called on ChartViewBase") } /// calculates the required number of digits for the values that might be drawn in the chart (if enabled), and creates the default value formatter internal func setupDefaultFormatter(min: Double, max: Double) { // check if a custom formatter is set or not var reference = Double(0.0) if let data = _data , data.entryCount >= 2 { reference = fabs(max - min) } else { let absMin = fabs(min) let absMax = fabs(max) reference = absMin > absMax ? absMin : absMax } if _defaultValueFormatter is DefaultValueFormatter { // setup the formatter with a new number of digits let digits = ChartUtils.decimals(reference) (_defaultValueFormatter as? DefaultValueFormatter)?.decimals = digits } } open override func draw(_ rect: CGRect) { let optionalContext = NSUIGraphicsGetCurrentContext() guard let context = optionalContext else { return } let frame = self.bounds if _data === nil && noDataText.characters.count > 0 { context.saveGState() defer { context.restoreGState() } ChartUtils.drawMultilineText( context: context, text: noDataText, point: CGPoint(x: frame.width / 2.0, y: frame.height / 2.0), attributes: [NSFontAttributeName: noDataFont, NSForegroundColorAttributeName: noDataTextColor], constrainedToSize: self.bounds.size, anchor: CGPoint(x: 0.5, y: 0.5), angleRadians: 0.0) return } if !_offsetsCalculated { calculateOffsets() _offsetsCalculated = true } } /// Draws the description text in the bottom right corner of the chart (per default) internal func drawDescription(context: CGContext) { // check if description should be drawn guard let description = chartDescription, description.isEnabled, let descriptionText = description.text, descriptionText.characters.count > 0 else { return } var position = description.position // if no position specified, draw on default position if position == nil { let frame = self.bounds position = CGPoint( x: frame.width - _viewPortHandler.offsetRight - description.xOffset, y: frame.height - _viewPortHandler.offsetBottom - description.yOffset - description.font.lineHeight) } var attrs = [String : AnyObject]() attrs[NSFontAttributeName] = description.font attrs[NSForegroundColorAttributeName] = description.textColor ChartUtils.drawText( context: context, text: descriptionText, point: position!, align: description.textAlign, attributes: attrs) } // MARK: - Highlighting /// - returns: The array of currently highlighted values. This might an empty if nothing is highlighted. open var highlighted: [Highlight] { return _indicesToHighlight } /// Set this to false to prevent values from being highlighted by tap gesture. /// Values can still be highlighted via drag or programmatically. /// **default**: true open var highlightPerTapEnabled: Bool { get { return _highlightPerTapEnabled } set { _highlightPerTapEnabled = newValue } } /// - returns: `true` if values can be highlighted via tap gesture, `false` ifnot. open var isHighLightPerTapEnabled: Bool { return highlightPerTapEnabled } /// Checks if the highlight array is null, has a length of zero or if the first object is null. /// - returns: `true` if there are values to highlight, `false` ifthere are no values to highlight. open func valuesToHighlight() -> Bool { return _indicesToHighlight.count > 0 } /// Highlights the values at the given indices in the given DataSets. Provide /// null or an empty array to undo all highlighting. /// This should be used to programmatically highlight values. /// This method *will not* call the delegate. open func highlightValues(_ highs: [Highlight]?) { // set the indices to highlight _indicesToHighlight = highs ?? [Highlight]() if _indicesToHighlight.isEmpty { self.lastHighlighted = nil } else { self.lastHighlighted = _indicesToHighlight[0] } // redraw the chart setNeedsDisplay() } /// Highlights any y-value at the given x-value in the given DataSet. /// Provide -1 as the dataSetIndex to undo all highlighting. /// This method will call the delegate. /// - parameter x: The x-value to highlight /// - parameter dataSetIndex: The dataset index to search in open func highlightValue(x: Double, dataSetIndex: Int) { highlightValue(x: x, dataSetIndex: dataSetIndex, callDelegate: true) } /// Highlights the value at the given x-value and y-value in the given DataSet. /// Provide -1 as the dataSetIndex to undo all highlighting. /// This method will call the delegate. /// - parameter x: The x-value to highlight /// - parameter y: The y-value to highlight. Supply `NaN` for "any" /// - parameter dataSetIndex: The dataset index to search in open func highlightValue(x: Double, y: Double, dataSetIndex: Int) { highlightValue(x: x, y: y, dataSetIndex: dataSetIndex, callDelegate: true) } /// Highlights any y-value at the given x-value in the given DataSet. /// Provide -1 as the dataSetIndex to undo all highlighting. /// - parameter x: The x-value to highlight /// - parameter dataSetIndex: The dataset index to search in /// - parameter callDelegate: Should the delegate be called for this change open func highlightValue(x: Double, dataSetIndex: Int, callDelegate: Bool) { highlightValue(x: x, y: Double.nan, dataSetIndex: dataSetIndex, callDelegate: callDelegate) } /// Highlights the value at the given x-value and y-value in the given DataSet. /// Provide -1 as the dataSetIndex to undo all highlighting. /// - parameter x: The x-value to highlight /// - parameter y: The y-value to highlight. Supply `NaN` for "any" /// - parameter dataSetIndex: The dataset index to search in /// - parameter callDelegate: Should the delegate be called for this change open func highlightValue(x: Double, y: Double, dataSetIndex: Int, callDelegate: Bool) { guard let data = _data else { Swift.print("Value not highlighted because data is nil") return } if dataSetIndex < 0 || dataSetIndex >= data.dataSetCount { highlightValue(nil, callDelegate: callDelegate) } else { highlightValue(Highlight(x: x, y: y, dataSetIndex: dataSetIndex), callDelegate: callDelegate) } } /// Highlights the values represented by the provided Highlight object /// This method *will not* call the delegate. /// - parameter highlight: contains information about which entry should be highlighted open func highlightValue(_ highlight: Highlight?) { highlightValue(highlight, callDelegate: false) } /// Highlights the value selected by touch gesture. open func highlightValue(_ highlight: Highlight?, callDelegate: Bool) { var entry: ChartDataEntry? var h = highlight if h == nil { _indicesToHighlight.removeAll(keepingCapacity: false) } else { // set the indices to highlight entry = _data?.entryForHighlight(h!) if entry == nil { h = nil _indicesToHighlight.removeAll(keepingCapacity: false) } else { _indicesToHighlight = [h!] } } if callDelegate && delegate != nil { if h == nil { delegate!.chartValueNothingSelected?(self) } else { // notify the listener delegate!.chartValueSelected?(self, entry: entry!, highlight: h!) } } // redraw the chart setNeedsDisplay() } /// - returns: The Highlight object (contains x-index and DataSet index) of the /// selected value at the given touch point inside the Line-, Scatter-, or /// CandleStick-Chart. open func getHighlightByTouchPoint(_ pt: CGPoint) -> Highlight? { if _data === nil { Swift.print("Can't select by touch. No data set.") return nil } return self.highlighter?.getHighlight(x: pt.x, y: pt.y) } /// The last value that was highlighted via touch. open var lastHighlighted: Highlight? // MARK: - Markers /// draws all MarkerViews on the highlighted positions internal func drawMarkers(context: CGContext) { // if there is no marker view or drawing marker is disabled guard let marker = marker , isDrawMarkersEnabled && valuesToHighlight() else { return } for i in 0 ..< _indicesToHighlight.count { let highlight = _indicesToHighlight[i] guard let set = data?.getDataSetByIndex(highlight.dataSetIndex), let e = _data?.entryForHighlight(highlight) else { continue } let entryIndex = set.entryIndex(entry: e) if entryIndex > Int(Double(set.entryCount) * _animator.phaseX) { continue } let pos = getMarkerPosition(highlight: highlight) // check bounds if !_viewPortHandler.isInBounds(x: pos.x, y: pos.y) { continue } // callbacks to update the content marker.refreshContent(entry: e, highlight: highlight) // draw the marker marker.draw(context: context, point: pos) } } /// - returns: The actual position in pixels of the MarkerView for the given Entry in the given DataSet. open func getMarkerPosition(highlight: Highlight) -> CGPoint { return CGPoint(x: highlight.drawX, y: highlight.drawY) } // MARK: - Animation /// - returns: The animator responsible for animating chart values. open var chartAnimator: Animator! { return _animator } /// Animates the drawing / rendering of the chart on both x- and y-axis with the specified animation time. /// If `animate(...)` is called, no further calling of `invalidate()` is necessary to refresh the chart. /// - parameter xAxisDuration: duration for animating the x axis /// - parameter yAxisDuration: duration for animating the y axis /// - parameter easingX: an easing function for the animation on the x axis /// - parameter easingY: an easing function for the animation on the y axis open func animate(xAxisDuration: TimeInterval, yAxisDuration: TimeInterval, easingX: ChartEasingFunctionBlock?, easingY: ChartEasingFunctionBlock?) { _animator.animate(xAxisDuration: xAxisDuration, yAxisDuration: yAxisDuration, easingX: easingX, easingY: easingY) } /// Animates the drawing / rendering of the chart on both x- and y-axis with the specified animation time. /// If `animate(...)` is called, no further calling of `invalidate()` is necessary to refresh the chart. /// - parameter xAxisDuration: duration for animating the x axis /// - parameter yAxisDuration: duration for animating the y axis /// - parameter easingOptionX: the easing function for the animation on the x axis /// - parameter easingOptionY: the easing function for the animation on the y axis open func animate(xAxisDuration: TimeInterval, yAxisDuration: TimeInterval, easingOptionX: ChartEasingOption, easingOptionY: ChartEasingOption) { _animator.animate(xAxisDuration: xAxisDuration, yAxisDuration: yAxisDuration, easingOptionX: easingOptionX, easingOptionY: easingOptionY) } /// Animates the drawing / rendering of the chart on both x- and y-axis with the specified animation time. /// If `animate(...)` is called, no further calling of `invalidate()` is necessary to refresh the chart. /// - parameter xAxisDuration: duration for animating the x axis /// - parameter yAxisDuration: duration for animating the y axis /// - parameter easing: an easing function for the animation open func animate(xAxisDuration: TimeInterval, yAxisDuration: TimeInterval, easing: ChartEasingFunctionBlock?) { _animator.animate(xAxisDuration: xAxisDuration, yAxisDuration: yAxisDuration, easing: easing) } /// Animates the drawing / rendering of the chart on both x- and y-axis with the specified animation time. /// If `animate(...)` is called, no further calling of `invalidate()` is necessary to refresh the chart. /// - parameter xAxisDuration: duration for animating the x axis /// - parameter yAxisDuration: duration for animating the y axis /// - parameter easingOption: the easing function for the animation open func animate(xAxisDuration: TimeInterval, yAxisDuration: TimeInterval, easingOption: ChartEasingOption) { _animator.animate(xAxisDuration: xAxisDuration, yAxisDuration: yAxisDuration, easingOption: easingOption) } /// Animates the drawing / rendering of the chart on both x- and y-axis with the specified animation time. /// If `animate(...)` is called, no further calling of `invalidate()` is necessary to refresh the chart. /// - parameter xAxisDuration: duration for animating the x axis /// - parameter yAxisDuration: duration for animating the y axis open func animate(xAxisDuration: TimeInterval, yAxisDuration: TimeInterval) { _animator.animate(xAxisDuration: xAxisDuration, yAxisDuration: yAxisDuration) } /// Animates the drawing / rendering of the chart the x-axis with the specified animation time. /// If `animate(...)` is called, no further calling of `invalidate()` is necessary to refresh the chart. /// - parameter xAxisDuration: duration for animating the x axis /// - parameter easing: an easing function for the animation open func animate(xAxisDuration: TimeInterval, easing: ChartEasingFunctionBlock?) { _animator.animate(xAxisDuration: xAxisDuration, easing: easing) } /// Animates the drawing / rendering of the chart the x-axis with the specified animation time. /// If `animate(...)` is called, no further calling of `invalidate()` is necessary to refresh the chart. /// - parameter xAxisDuration: duration for animating the x axis /// - parameter easingOption: the easing function for the animation open func animate(xAxisDuration: TimeInterval, easingOption: ChartEasingOption) { _animator.animate(xAxisDuration: xAxisDuration, easingOption: easingOption) } /// Animates the drawing / rendering of the chart the x-axis with the specified animation time. /// If `animate(...)` is called, no further calling of `invalidate()` is necessary to refresh the chart. /// - parameter xAxisDuration: duration for animating the x axis open func animate(xAxisDuration: TimeInterval) { _animator.animate(xAxisDuration: xAxisDuration) } /// Animates the drawing / rendering of the chart the y-axis with the specified animation time. /// If `animate(...)` is called, no further calling of `invalidate()` is necessary to refresh the chart. /// - parameter yAxisDuration: duration for animating the y axis /// - parameter easing: an easing function for the animation open func animate(yAxisDuration: TimeInterval, easing: ChartEasingFunctionBlock?) { _animator.animate(yAxisDuration: yAxisDuration, easing: easing) } /// Animates the drawing / rendering of the chart the y-axis with the specified animation time. /// If `animate(...)` is called, no further calling of `invalidate()` is necessary to refresh the chart. /// - parameter yAxisDuration: duration for animating the y axis /// - parameter easingOption: the easing function for the animation open func animate(yAxisDuration: TimeInterval, easingOption: ChartEasingOption) { _animator.animate(yAxisDuration: yAxisDuration, easingOption: easingOption) } /// Animates the drawing / rendering of the chart the y-axis with the specified animation time. /// If `animate(...)` is called, no further calling of `invalidate()` is necessary to refresh the chart. /// - parameter yAxisDuration: duration for animating the y axis open func animate(yAxisDuration: TimeInterval) { _animator.animate(yAxisDuration: yAxisDuration) } // MARK: - Accessors /// - returns: The current y-max value across all DataSets open var chartYMax: Double { return _data?.yMax ?? 0.0 } /// - returns: The current y-min value across all DataSets open var chartYMin: Double { return _data?.yMin ?? 0.0 } open var chartXMax: Double { return _xAxis._axisMaximum } open var chartXMin: Double { return _xAxis._axisMinimum } open var xRange: Double { return _xAxis.axisRange } /// * /// - note: (Equivalent of getCenter() in MPAndroidChart, as center is already a standard in iOS that returns the center point relative to superview, and MPAndroidChart returns relative to self)* /// - returns: The center point of the chart (the whole View) in pixels. open var midPoint: CGPoint { let bounds = self.bounds return CGPoint(x: bounds.origin.x + bounds.size.width / 2.0, y: bounds.origin.y + bounds.size.height / 2.0) } /// - returns: The center of the chart taking offsets under consideration. (returns the center of the content rectangle) open var centerOffsets: CGPoint { return _viewPortHandler.contentCenter } /// - returns: The Legend object of the chart. This method can be used to get an instance of the legend in order to customize the automatically generated Legend. open var legend: Legend { return _legend } /// - returns: The renderer object responsible for rendering / drawing the Legend. open var legendRenderer: LegendRenderer! { return _legendRenderer } /// - returns: The rectangle that defines the borders of the chart-value surface (into which the actual values are drawn). open var contentRect: CGRect { return _viewPortHandler.contentRect } /// - returns: The ViewPortHandler of the chart that is responsible for the /// content area of the chart and its offsets and dimensions. open var viewPortHandler: ViewPortHandler! { return _viewPortHandler } /// - returns: The bitmap that represents the chart. open func getChartImage(transparent: Bool) -> NSUIImage? { NSUIGraphicsBeginImageContextWithOptions(bounds.size, isOpaque || !transparent, NSUIMainScreen()?.nsuiScale ?? 1.0) guard let context = NSUIGraphicsGetCurrentContext() else { return nil } let rect = CGRect(origin: CGPoint(x: 0, y: 0), size: bounds.size) if isOpaque || !transparent { // Background color may be partially transparent, we must fill with white if we want to output an opaque image context.setFillColor(NSUIColor.white.cgColor) context.fill(rect) if let backgroundColor = self.backgroundColor { context.setFillColor(backgroundColor.cgColor) context.fill(rect) } } nsuiLayer?.render(in: context) let image = NSUIGraphicsGetImageFromCurrentImageContext() NSUIGraphicsEndImageContext() return image } public enum ImageFormat { case jpeg case png } /// Saves the current chart state with the given name to the given path on /// the sdcard leaving the path empty "" will put the saved file directly on /// the SD card chart is saved as a PNG image, example: /// saveToPath("myfilename", "foldername1/foldername2") /// /// - parameter to: path to the image to save /// - parameter format: the format to save /// - parameter compressionQuality: compression quality for lossless formats (JPEG) /// /// - returns: `true` if the image was saved successfully open func save(to path: String, format: ImageFormat, compressionQuality: Double) -> Bool { guard let image = getChartImage(transparent: format != .jpeg) else { return false } var imageData: Data! switch (format) { case .png: imageData = NSUIImagePNGRepresentation(image) break case .jpeg: imageData = NSUIImageJPEGRepresentation(image, CGFloat(compressionQuality)) break } do { try imageData.write(to: URL(fileURLWithPath: path), options: .atomic) } catch { return false } return true } internal var _viewportJobs = [ViewPortJob]() open override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { if keyPath == "bounds" || keyPath == "frame" { let bounds = self.bounds if (_viewPortHandler !== nil && (bounds.size.width != _viewPortHandler.chartWidth || bounds.size.height != _viewPortHandler.chartHeight)) { _viewPortHandler.setChartDimens(width: bounds.size.width, height: bounds.size.height) // This may cause the chart view to mutate properties affecting the view port -- lets do this // before we try to run any pending jobs on the view port itself notifyDataSetChanged() // Finish any pending viewport changes while (!_viewportJobs.isEmpty) { let job = _viewportJobs.remove(at: 0) job.doJob() } } } } open func removeViewportJob(_ job: ViewPortJob) { if let index = _viewportJobs.index(where: { $0 === job }) { _viewportJobs.remove(at: index) } } open func clearAllViewportJobs() { _viewportJobs.removeAll(keepingCapacity: false) } open func addViewportJob(_ job: ViewPortJob) { if _viewPortHandler.hasChartDimens { job.doJob() } else { _viewportJobs.append(job) } } /// **default**: true /// - returns: `true` if chart continues to scroll after touch up, `false` ifnot. open var isDragDecelerationEnabled: Bool { return dragDecelerationEnabled } /// Deceleration friction coefficient in [0 ; 1] interval, higher values indicate that speed will decrease slowly, for example if it set to 0, it will stop immediately. /// 1 is an invalid value, and will be converted to 0.999 automatically. /// /// **default**: true open var dragDecelerationFrictionCoef: CGFloat { get { return _dragDecelerationFrictionCoef } set { var val = newValue if val < 0.0 { val = 0.0 } if val >= 1.0 { val = 0.999 } _dragDecelerationFrictionCoef = val } } /// The maximum distance in screen pixels away from an entry causing it to highlight. /// **default**: 500.0 open var maxHighlightDistance: CGFloat = 500.0 /// the number of maximum visible drawn values on the chart only active when `drawValuesEnabled` is enabled open var maxVisibleCount: Int { return Int(INT_MAX) } // MARK: - AnimatorDelegate open func animatorUpdated(_ chartAnimator: Animator) { setNeedsDisplay() } open func animatorStopped(_ chartAnimator: Animator) { } // MARK: - Touches open override func nsuiTouchesBegan(_ touches: Set<NSUITouch>, withEvent event: NSUIEvent?) { if !_interceptTouchEvents { super.nsuiTouchesBegan(touches, withEvent: event) } } open override func nsuiTouchesMoved(_ touches: Set<NSUITouch>, withEvent event: NSUIEvent?) { if !_interceptTouchEvents { super.nsuiTouchesMoved(touches, withEvent: event) } } open override func nsuiTouchesEnded(_ touches: Set<NSUITouch>, withEvent event: NSUIEvent?) { if !_interceptTouchEvents { super.nsuiTouchesEnded(touches, withEvent: event) } } open override func nsuiTouchesCancelled(_ touches: Set<NSUITouch>?, withEvent event: NSUIEvent?) { if !_interceptTouchEvents { super.nsuiTouchesCancelled(touches, withEvent: event) } } }
apache-2.0
f414ee1c68717be8f5bef080fde18240
34.946257
199
0.623158
5.299377
false
false
false
false
shorlander/firefox-ios
Storage/ThirdParty/SwiftData.swift
1
44834
/* 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/. */ /* * This is a heavily modified version of SwiftData.swift by Ryan Fowler * This has been enhanced to support custom files, correct binding, versioning, * and a streaming results via Cursors. The API has also been changed to use NSError, Cursors, and * to force callers to request a connection before executing commands. Database creation helpers, savepoint * helpers, image support, and other features have been removed. */ // SwiftData.swift // // Copyright (c) 2014 Ryan Fowler // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation import UIKit import Shared import XCGLogger private let DatabaseBusyTimeout: Int32 = 3 * 1000 private let log = Logger.syncLogger /** * Handle to a SQLite database. * Each instance holds a single connection that is shared across all queries. */ open class SwiftData { let filename: String static var EnableWAL = true static var EnableForeignKeys = true /// Used to keep track of the corrupted databases we've logged. static var corruptionLogsWritten = Set<String>() /// Used for testing. static var ReuseConnections = true /// For thread-safe access to the shared connection. fileprivate let sharedConnectionQueue: DispatchQueue /// Shared connection to this database. fileprivate var sharedConnection: ConcreteSQLiteDBConnection? fileprivate var key: String? fileprivate var prevKey: String? /// A simple state flag to track whether we should accept new connection requests. /// If a connection request is made while the database is closed, a /// FailedSQLiteDBConnection will be returned. fileprivate(set) var closed = false init(filename: String, key: String? = nil, prevKey: String? = nil) { self.filename = filename self.sharedConnectionQueue = DispatchQueue(label: "SwiftData queue: \(filename)", attributes: []) // Ensure that multi-thread mode is enabled by default. // See https://www.sqlite.org/threadsafe.html assert(sqlite3_threadsafe() == 2) self.key = key self.prevKey = prevKey } fileprivate func getSharedConnection() -> ConcreteSQLiteDBConnection? { var connection: ConcreteSQLiteDBConnection? sharedConnectionQueue.sync { if self.closed { log.warning(">>> Database is closed for \(self.filename)") return } if self.sharedConnection == nil { log.debug(">>> Creating shared SQLiteDBConnection for \(self.filename) on thread \(Thread.current).") self.sharedConnection = ConcreteSQLiteDBConnection(filename: self.filename, flags: SwiftData.Flags.readWriteCreate.toSQL(), key: self.key, prevKey: self.prevKey) } connection = self.sharedConnection } return connection } /** * The real meat of all the execute methods. This is used internally to open and * close a database connection and run a block of code inside it. */ func withConnection(_ flags: SwiftData.Flags, synchronous: Bool=true, cb: @escaping (_ db: SQLiteDBConnection) -> NSError?) -> NSError? { /** * We use a weak reference here instead of strongly retaining the connection because we don't want * any control over when the connection deallocs. If the only owner of the connection (SwiftData) * decides to dealloc it, we should respect that since the deinit method of the connection is tied * to the app lifecycle. This is to prevent background disk access causing springboard crashes. */ weak var conn = getSharedConnection() let queue = self.sharedConnectionQueue if synchronous { var error: NSError? = nil queue.sync { /** * By the time this dispatch block runs, it is possible the user has backgrounded the app * and the connection has been dealloc'ed since we last grabbed the reference */ guard let connection = SwiftData.ReuseConnections ? conn : ConcreteSQLiteDBConnection(filename: filename, flags: flags.toSQL(), key: self.key, prevKey: self.prevKey) else { error = cb(FailedSQLiteDBConnection()) ?? NSError(domain: "mozilla", code: 0, userInfo: [NSLocalizedDescriptionKey: "Could not create a connection"]) return } error = cb(connection) } return error } queue.async { guard let connection = SwiftData.ReuseConnections ? conn : ConcreteSQLiteDBConnection(filename: self.filename, flags: flags.toSQL(), key: self.key, prevKey: self.prevKey) else { let _ = cb(FailedSQLiteDBConnection()) return } let _ = cb(connection) } return nil } func transaction(_ transactionClosure: @escaping (_ db: SQLiteDBConnection) -> Bool) -> NSError? { return self.transaction(synchronous: true, transactionClosure: transactionClosure) } /** * Helper for opening a connection, starting a transaction, and then running a block of code inside it. * The code block can return true if the transaction should be committed. False if we should roll back. */ func transaction(synchronous: Bool=true, transactionClosure: @escaping (_ db: SQLiteDBConnection) -> Bool) -> NSError? { return withConnection(SwiftData.Flags.readWriteCreate, synchronous: synchronous) { db in if let err = db.executeChange("BEGIN EXCLUSIVE") { log.error("BEGIN EXCLUSIVE failed. Error code: \(err.code), \(err)") SentryIntegration.shared.sendWithStacktrace(message: "BEGIN EXCLUSIVE failed. Error code: \(err.code), \(err)", tag: "SwiftData", severity: .error) return err } if transactionClosure(db) { log.verbose("Op in transaction succeeded. Committing.") if let err = db.executeChange("COMMIT") { log.error("COMMIT failed. Rolling back. Error code: \(err.code), \(err)") SentryIntegration.shared.sendWithStacktrace(message: "COMMIT failed. Rolling back. Error code: \(err.code), \(err)", tag: "SwiftData", severity: .error) if let rollbackErr = db.executeChange("ROLLBACK") { log.error("ROLLBACK after failed COMMIT failed. Error code: \(rollbackErr.code), \(rollbackErr)") SentryIntegration.shared.sendWithStacktrace(message: "ROLLBACK after failed COMMIT failed. Error code: \(rollbackErr.code), \(rollbackErr)", tag: "SwiftData", severity: .error) } return err } } else { log.error("Op in transaction failed. Rolling back.") SentryIntegration.shared.sendWithStacktrace(message: "Op in transaction failed. Rolling back.", tag: "SwiftData", severity: .error) if let err = db.executeChange("ROLLBACK") { log.error("ROLLBACK after failed op in transaction failed. Error code: \(err.code), \(err)") SentryIntegration.shared.sendWithStacktrace(message: "ROLLBACK after failed op in transaction failed. Error code: \(err.code), \(err)", tag: "SwiftData", severity: .error) return err } } return nil } } /// Don't use this unless you know what you're doing. The deinitializer /// should be used to achieve refcounting semantics. func forceClose() { sharedConnectionQueue.sync { self.closed = true self.sharedConnection = nil } } /// Reopens a database that had previously been force-closed. /// Does nothing if this database is already open. func reopenIfClosed() { sharedConnectionQueue.sync { self.closed = false } } public enum Flags { case readOnly case readWrite case readWriteCreate fileprivate func toSQL() -> Int32 { switch self { case .readOnly: return SQLITE_OPEN_READONLY case .readWrite: return SQLITE_OPEN_READWRITE case .readWriteCreate: return SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE } } } } /** * Wrapper class for a SQLite statement. * This class helps manage the statement lifecycle. By holding a reference to the SQL connection, we ensure * the connection is never deinitialized while the statement is active. This class is responsible for * finalizing the SQL statement once it goes out of scope. */ private class SQLiteDBStatement { var pointer: OpaquePointer? fileprivate let connection: ConcreteSQLiteDBConnection init(connection: ConcreteSQLiteDBConnection, query: String, args: [Any?]?) throws { self.connection = connection let status = sqlite3_prepare_v2(connection.sqliteDB, query, -1, &pointer, nil) if status != SQLITE_OK { throw connection.createErr("During: SQL Prepare \(query)", status: Int(status)) } if let args = args, let bindError = bind(args) { throw bindError } } /// Binds arguments to the statement. fileprivate func bind(_ objects: [Any?]) -> NSError? { let count = Int(sqlite3_bind_parameter_count(pointer)) if count < objects.count { return connection.createErr("During: Bind", status: 202) } if count > objects.count { return connection.createErr("During: Bind", status: 201) } for (index, obj) in objects.enumerated() { var status: Int32 = SQLITE_OK // Doubles also pass obj as Int, so order is important here. if obj is Double { status = sqlite3_bind_double(pointer, Int32(index+1), obj as! Double) } else if obj is Int { status = sqlite3_bind_int(pointer, Int32(index+1), Int32(obj as! Int)) } else if obj is Bool { status = sqlite3_bind_int(pointer, Int32(index+1), (obj as! Bool) ? 1 : 0) } else if obj is String { typealias CFunction = @convention(c) (UnsafeMutableRawPointer?) -> Void let transient = unsafeBitCast(-1, to: CFunction.self) status = sqlite3_bind_text(pointer, Int32(index+1), (obj as! String).cString(using: String.Encoding.utf8)!, -1, transient) } else if obj is Data { status = sqlite3_bind_blob(pointer, Int32(index+1), ((obj as! Data) as NSData).bytes, -1, nil) } else if obj is Date { let timestamp = (obj as! Date).timeIntervalSince1970 status = sqlite3_bind_double(pointer, Int32(index+1), timestamp) } else if obj is UInt64 { status = sqlite3_bind_double(pointer, Int32(index+1), Double(obj as! UInt64)) } else if obj == nil { status = sqlite3_bind_null(pointer, Int32(index+1)) } if status != SQLITE_OK { return connection.createErr("During: Bind", status: Int(status)) } } return nil } func close() { if nil != self.pointer { sqlite3_finalize(self.pointer) self.pointer = nil } } deinit { if nil != self.pointer { sqlite3_finalize(self.pointer) } } } protocol SQLiteDBConnection { var lastInsertedRowID: Int { get } var numberOfRowsModified: Int { get } func executeChange(_ sqlStr: String) -> NSError? func executeChange(_ sqlStr: String, withArgs args: Args?) -> NSError? func executeQuery<T>(_ sqlStr: String, factory: @escaping ((SDRow) -> T)) -> Cursor<T> func executeQuery<T>(_ sqlStr: String, factory: @escaping ((SDRow) -> T), withArgs args: Args?) -> Cursor<T> func executeQueryUnsafe<T>(_ sqlStr: String, factory: @escaping ((SDRow) -> T), withArgs args: Args?) -> Cursor<T> func interrupt() func checkpoint() func checkpoint(_ mode: Int32) func vacuum() -> NSError? } // Represents a failure to open. class FailedSQLiteDBConnection: SQLiteDBConnection { func executeChange(_ sqlStr: String, withArgs args: Args?) -> NSError? { return self.fail("Non-open connection; can't execute change.") } fileprivate func fail(_ str: String) -> NSError { return NSError(domain: "mozilla", code: 0, userInfo: [NSLocalizedDescriptionKey: str]) } var lastInsertedRowID: Int { return 0 } var numberOfRowsModified: Int { return 0 } func executeChange(_ sqlStr: String) -> NSError? { return self.fail("Non-open connection; can't execute change.") } func executeQuery<T>(_ sqlStr: String) -> Cursor<T> { return Cursor<T>(err: self.fail("Non-open connection; can't execute query.")) } func executeQuery<T>(_ sqlStr: String, factory: @escaping ((SDRow) -> T)) -> Cursor<T> { return Cursor<T>(err: self.fail("Non-open connection; can't execute query.")) } func executeQuery<T>(_ sqlStr: String, factory: @escaping ((SDRow) -> T), withArgs args: Args?) -> Cursor<T> { return Cursor<T>(err: self.fail("Non-open connection; can't execute query.")) } func executeQueryUnsafe<T>(_ sqlStr: String, factory: @escaping ((SDRow) -> T), withArgs args: Args?) -> Cursor<T> { return Cursor<T>(err: self.fail("Non-open connection; can't execute query.")) } func interrupt() {} func checkpoint() {} func checkpoint(_ mode: Int32) {} func vacuum() -> NSError? { return self.fail("Non-open connection; can't vacuum.") } } open class ConcreteSQLiteDBConnection: SQLiteDBConnection { fileprivate var sqliteDB: OpaquePointer? fileprivate let filename: String fileprivate let debug_enabled = false fileprivate let queue: DispatchQueue open var version: Int { get { return pragma("user_version", factory: IntFactory) ?? 0 } set { let _ = executeChange("PRAGMA user_version = \(newValue)") } } fileprivate func setKey(_ key: String?) -> NSError? { sqlite3_key(sqliteDB, key ?? "", Int32((key ?? "").characters.count)) let cursor = executeQuery("SELECT count(*) FROM sqlite_master;", factory: IntFactory, withArgs: nil as Args?) if cursor.status != .success { return NSError(domain: "mozilla", code: 0, userInfo: [NSLocalizedDescriptionKey: "Invalid key"]) } return nil } fileprivate func reKey(_ oldKey: String?, newKey: String?) -> NSError? { sqlite3_key(sqliteDB, oldKey ?? "", Int32((oldKey ?? "").characters.count)) sqlite3_rekey(sqliteDB, newKey ?? "", Int32((newKey ?? "").characters.count)) // Check that the new key actually works sqlite3_key(sqliteDB, newKey ?? "", Int32((newKey ?? "").characters.count)) let cursor = executeQuery("SELECT count(*) FROM sqlite_master;", factory: IntFactory, withArgs: nil as Args?) if cursor.status != .success { return NSError(domain: "mozilla", code: 0, userInfo: [NSLocalizedDescriptionKey: "Rekey failed"]) } return nil } func interrupt() { log.debug("Interrupt") sqlite3_interrupt(sqliteDB) } fileprivate func pragma<T: Equatable>(_ pragma: String, expected: T?, factory: @escaping (SDRow) -> T, message: String) throws { let cursorResult = self.pragma(pragma, factory: factory) if cursorResult != expected { log.error("\(message): \(cursorResult.debugDescription), \(expected.debugDescription)") throw NSError(domain: "mozilla", code: 0, userInfo: [NSLocalizedDescriptionKey: "PRAGMA didn't return expected output: \(message)."]) } } fileprivate func pragma<T>(_ pragma: String, factory: @escaping (SDRow) -> T) -> T? { let cursor = executeQueryUnsafe("PRAGMA \(pragma)", factory: factory, withArgs: [] as Args) defer { cursor.close() } return cursor[0] } fileprivate func prepareShared() { if SwiftData.EnableForeignKeys { let _ = pragma("foreign_keys=ON", factory: IntFactory) } // Retry queries before returning locked errors. sqlite3_busy_timeout(self.sqliteDB, DatabaseBusyTimeout) } fileprivate func prepareEncrypted(_ flags: Int32, key: String?, prevKey: String? = nil) throws { // Setting the key needs to be the first thing done with the database. if let _ = setKey(key) { if let err = closeCustomConnection(immediately: true) { log.error("Couldn't close connection: \(err). Failing to open.") throw err } if let err = openWithFlags(flags) { log.error("Error opening database with flags. Error code: \(err.code), \(err)") SentryIntegration.shared.sendWithStacktrace(message: "Error opening database with flags. Error code: \(err.code), \(err)", tag: "SwiftData", severity: .error) throw err } if let err = reKey(prevKey, newKey: key) { // Note: Don't log the error here as it may contain sensitive data. log.error("Unable to encrypt database.") SentryIntegration.shared.sendWithStacktrace(message: "Unable to encrypt database.", tag: "SwiftData", severity: .error) throw err } } if SwiftData.EnableWAL { log.info("Enabling WAL mode.") try pragma("journal_mode=WAL", expected: "wal", factory: StringFactory, message: "WAL journal mode set") } self.prepareShared() } fileprivate func prepareCleartext() throws { // If we just created the DB -- i.e., no tables have been created yet -- then // we can set the page size right now and save a vacuum. // // For where these values come from, see Bug 1213623. // // Note that sqlcipher uses cipher_page_size instead, but we don't set that // because it needs to be set from day one. let desiredPageSize = 32 * 1024 let _ = pragma("page_size=\(desiredPageSize)", factory: IntFactory) let currentPageSize = pragma("page_size", factory: IntFactory) // This has to be done without WAL, so we always hop into rollback/delete journal mode. if currentPageSize != desiredPageSize { try pragma("journal_mode=DELETE", expected: "delete", factory: StringFactory, message: "delete journal mode set") try pragma("page_size=\(desiredPageSize)", expected: nil, factory: IntFactory, message: "Page size set") log.info("Vacuuming to alter database page size from \(currentPageSize ?? 0) to \(desiredPageSize).") if let err = self.vacuum() { log.error("Vacuuming failed: \(err).") } else { log.debug("Vacuuming succeeded.") } } if SwiftData.EnableWAL { log.info("Enabling WAL mode.") let desiredPagesPerJournal = 16 let desiredCheckpointSize = desiredPagesPerJournal * desiredPageSize let desiredJournalSizeLimit = 3 * desiredCheckpointSize /* * With whole-module-optimization enabled in Xcode 7.2 and 7.2.1, the * compiler seems to eagerly discard these queries if they're simply * inlined, causing a crash in `pragma`. * * Hackily hold on to them. */ let journalModeQuery = "journal_mode=WAL" let autoCheckpointQuery = "wal_autocheckpoint=\(desiredPagesPerJournal)" let journalSizeQuery = "journal_size_limit=\(desiredJournalSizeLimit)" try withExtendedLifetime(journalModeQuery, { try pragma(journalModeQuery, expected: "wal", factory: StringFactory, message: "WAL journal mode set") }) try withExtendedLifetime(autoCheckpointQuery, { try pragma(autoCheckpointQuery, expected: desiredPagesPerJournal, factory: IntFactory, message: "WAL autocheckpoint set") }) try withExtendedLifetime(journalSizeQuery, { try pragma(journalSizeQuery, expected: desiredJournalSizeLimit, factory: IntFactory, message: "WAL journal size limit set") }) } self.prepareShared() } init?(filename: String, flags: Int32, key: String? = nil, prevKey: String? = nil) { log.debug("Opening connection to \(filename).") self.filename = filename self.queue = DispatchQueue(label: "SQLite connection: \(filename)", attributes: []) if let failure = openWithFlags(flags) { log.warning("Opening connection to \(filename) failed: \(failure).") return nil } if key == nil && prevKey == nil { do { try self.prepareCleartext() } catch { return nil } } else { do { try self.prepareEncrypted(flags, key: key, prevKey: prevKey) } catch { return nil } } } deinit { log.debug("deinit: closing connection on thread \(Thread.current).") let _ = self.queue.sync { self.closeCustomConnection() } } open var lastInsertedRowID: Int { return Int(sqlite3_last_insert_rowid(sqliteDB)) } open var numberOfRowsModified: Int { return Int(sqlite3_changes(sqliteDB)) } func checkpoint() { self.checkpoint(SQLITE_CHECKPOINT_FULL) } /** * Blindly attempts a WAL checkpoint on all attached databases. */ func checkpoint(_ mode: Int32) { guard sqliteDB != nil else { log.warning("Trying to checkpoint a nil DB!") return } log.debug("Running WAL checkpoint on \(self.filename) on thread \(Thread.current).") sqlite3_wal_checkpoint_v2(sqliteDB, nil, mode, nil, nil) log.debug("WAL checkpoint done on \(self.filename).") } func vacuum() -> NSError? { return self.executeChange("VACUUM") } /// Creates an error from a sqlite status. Will print to the console if debug_enabled is set. /// Do not call this unless you're going to return this error. fileprivate func createErr(_ description: String, status: Int) -> NSError { var msg = SDError.errorMessageFromCode(status) if debug_enabled { log.debug("SwiftData Error -> \(description)") log.debug(" -> Code: \(status) - \(msg)") } if let errMsg = String(validatingUTF8: sqlite3_errmsg(sqliteDB)) { msg += " " + errMsg if debug_enabled { log.debug(" -> Details: \(errMsg)") } } return NSError(domain: "org.mozilla", code: status, userInfo: [NSLocalizedDescriptionKey: msg]) } /// Open the connection. This is called when the db is created. You should not call it yourself. fileprivate func openWithFlags(_ flags: Int32) -> NSError? { let status = sqlite3_open_v2(filename.cString(using: String.Encoding.utf8)!, &sqliteDB, flags, nil) if status != SQLITE_OK { return createErr("During: Opening Database with Flags", status: Int(status)) } return nil } /// Closes a connection. This is called via deinit. Do not call this yourself. fileprivate func closeCustomConnection(immediately: Bool=false) -> NSError? { log.debug("Closing custom connection for \(self.filename) on \(Thread.current).") // TODO: add a lock here? let db = self.sqliteDB self.sqliteDB = nil // Don't bother trying to call sqlite3_close multiple times. guard db != nil else { log.warning("Connection was nil.") return nil } var status = sqlite3_close(db) if status != SQLITE_OK { log.error("Got status \(status) while attempting to close.") SentryIntegration.shared.sendWithStacktrace(message: "Got status \(status) while attempting to close.", tag: "SwiftData", severity: .error) if immediately { return createErr("During: closing database with flags", status: Int(status)) } // Note that if we use sqlite3_close_v2, this will still return SQLITE_OK even if // there are outstanding prepared statements status = sqlite3_close_v2(db) if status != SQLITE_OK { // Based on the above comment regarding sqlite3_close_v2, this shouldn't happen. log.error("Got status \(status) while attempting to close_v2.") SentryIntegration.shared.sendWithStacktrace(message: "Got status \(status) while attempting to close_v2.", tag: "SwiftData", severity: .error) return createErr("During: closing database with flags", status: Int(status)) } } log.debug("Closed \(self.filename).") return nil } open func executeChange(_ sqlStr: String) -> NSError? { return self.executeChange(sqlStr, withArgs: nil) } /// Executes a change on the database. open func executeChange(_ sqlStr: String, withArgs args: Args?) -> NSError? { var error: NSError? let statement: SQLiteDBStatement? do { statement = try SQLiteDBStatement(connection: self, query: sqlStr, args: args) } catch let error1 as NSError { error = error1 statement = nil } // Close, not reset -- this isn't going to be reused. defer { statement?.close() } if let error = error { // Special case: Write additional info to the database log in the case of a database corruption. if error.code == Int(SQLITE_CORRUPT) { writeCorruptionInfoForDBNamed(filename, toLogger: Logger.corruptLogger) SentryIntegration.shared.sendWithStacktrace(message: "SQLITE_CORRUPT for DB \(filename), \(error)", tag: "SwiftData", severity: .error) } let message = "SQL error. Error code: \(error.code), \(error) for SQL \(sqlStr.characters.prefix(500))." log.error(message) SentryIntegration.shared.sendWithStacktrace(message: message, tag: "SwiftData", severity: .error) return error } let status = sqlite3_step(statement!.pointer) if status != SQLITE_DONE && status != SQLITE_OK { error = createErr("During: SQL Step \(sqlStr)", status: Int(status)) } return error } func executeQuery<T>(_ sqlStr: String, factory: @escaping ((SDRow) -> T)) -> Cursor<T> { return self.executeQuery(sqlStr, factory: factory, withArgs: nil) } /// Queries the database. /// Returns a cursor pre-filled with the complete result set. func executeQuery<T>(_ sqlStr: String, factory: @escaping ((SDRow) -> T), withArgs args: Args?) -> Cursor<T> { var error: NSError? let statement: SQLiteDBStatement? do { statement = try SQLiteDBStatement(connection: self, query: sqlStr, args: args) } catch let error1 as NSError { error = error1 statement = nil } // Close, not reset -- this isn't going to be reused, and the FilledSQLiteCursor // consumes everything. defer { statement?.close() } if let error = error { // Special case: Write additional info to the database log in the case of a database corruption. if error.code == Int(SQLITE_CORRUPT) { writeCorruptionInfoForDBNamed(filename, toLogger: Logger.corruptLogger) SentryIntegration.shared.sendWithStacktrace(message: "SQLITE_CORRUPT for DB \(filename), \(error)", tag: "SwiftData", severity: .error) } let message = "SQL error. Error code: \(error.code), \(error) for SQL \(sqlStr.characters.prefix(500))." log.error(message) SentryIntegration.shared.sendWithStacktrace(message: message, tag: "SwiftData", severity: .error) return Cursor<T>(err: error) } return FilledSQLiteCursor<T>(statement: statement!, factory: factory) } func writeCorruptionInfoForDBNamed(_ dbFilename: String, toLogger logger: XCGLogger) { DispatchQueue.global(qos: DispatchQoS.default.qosClass).sync { guard !SwiftData.corruptionLogsWritten.contains(dbFilename) else { return } logger.error("Corrupt DB detected! DB filename: \(dbFilename)") let dbFileSize = ("file://\(dbFilename)".asURL)?.allocatedFileSize() ?? 0 logger.error("DB file size: \(dbFileSize) bytes") logger.error("Integrity check:") let args: [Any?]? = nil let messages = self.executeQueryUnsafe("PRAGMA integrity_check", factory: StringFactory, withArgs: args) defer { messages.close() } if messages.status == CursorStatus.success { for message in messages { logger.error(message) } logger.error("----") } else { logger.error("Couldn't run integrity check: \(messages.statusMessage).") } // Write call stack. logger.error("Call stack: ") for message in Thread.callStackSymbols { logger.error(" >> \(message)") } logger.error("----") // Write open file handles. let openDescriptors = FSUtils.openFileDescriptors() logger.error("Open file descriptors: ") for (k, v) in openDescriptors { logger.error(" \(k): \(v)") } logger.error("----") SwiftData.corruptionLogsWritten.insert(dbFilename) } } // func executeQueryUnsafe<T>(_ sqlStr: String, factory: @escaping ((SDRow) -> T), withArgs args: Args?) -> Cursor<T> { // return self.executeQueryUnsafe(sqlStr, factory: factory, withArgs: args) // } /** * Queries the database. * Returns a live cursor that holds the query statement and database connection. * Instances of this class *must not* leak outside of the connection queue! */ func executeQueryUnsafe<T>(_ sqlStr: String, factory: @escaping ((SDRow) -> T), withArgs args: Args?) -> Cursor<T> { var error: NSError? let statement: SQLiteDBStatement? do { statement = try SQLiteDBStatement(connection: self, query: sqlStr, args: args) } catch let error1 as NSError { error = error1 statement = nil } if let error = error { return Cursor(err: error) } return LiveSQLiteCursor(statement: statement!, factory: factory) } } /// Helper for queries that return a single integer result. func IntFactory(_ row: SDRow) -> Int { return row[0] as! Int } /// Helper for queries that return a single String result. func StringFactory(_ row: SDRow) -> String { return row[0] as! String } /// Wrapper around a statement for getting data from a row. This provides accessors for subscript indexing /// and a generator for iterating over columns. class SDRow: Sequence { // The sqlite statement this row came from. fileprivate let statement: SQLiteDBStatement // The columns of this database. The indices of these are assumed to match the indices // of the statement. fileprivate let columnNames: [String] fileprivate init(statement: SQLiteDBStatement, columns: [String]) { self.statement = statement self.columnNames = columns } // Return the value at this index in the row fileprivate func getValue(_ index: Int) -> Any? { let i = Int32(index) let type = sqlite3_column_type(statement.pointer, i) var ret: Any? = nil switch type { case SQLITE_NULL, SQLITE_INTEGER: //Everyone expects this to be an Int. On Ints larger than 2^31 this will lose information. ret = Int(truncatingBitPattern: sqlite3_column_int64(statement.pointer, i)) case SQLITE_TEXT: if let text = sqlite3_column_text(statement.pointer, i) { return String(cString: text) } case SQLITE_BLOB: if let blob = sqlite3_column_blob(statement.pointer, i) { let size = sqlite3_column_bytes(statement.pointer, i) ret = Data(bytes: blob, count: Int(size)) } case SQLITE_FLOAT: ret = Double(sqlite3_column_double(statement.pointer, i)) default: log.warning("SwiftData Warning -> Column: \(index) is of an unrecognized type, returning nil") } return ret } // Accessor getting column 'key' in the row subscript(key: Int) -> Any? { return getValue(key) } // Accessor getting a named column in the row. This (currently) depends on // the columns array passed into this Row to find the correct index. subscript(key: String) -> Any? { get { if let index = columnNames.index(of: key) { return getValue(index) } return nil } } // Allow iterating through the row. This is currently broken. func makeIterator() -> AnyIterator<Any> { let nextIndex = 0 return AnyIterator() { // This crashes the compiler. Yay! if nextIndex < self.columnNames.count { return nil // self.getValue(nextIndex) } return nil } } } /// Helper for pretty printing SQL (and other custom) error codes. private struct SDError { fileprivate static func errorMessageFromCode(_ errorCode: Int) -> String { switch errorCode { case -1: return "No error" // SQLite error codes and descriptions as per: http://www.sqlite.org/c3ref/c_abort.html case 0: return "Successful result" case 1: return "SQL error or missing database" case 2: return "Internal logic error in SQLite" case 3: return "Access permission denied" case 4: return "Callback routine requested an abort" case 5: return "The database file is busy" case 6: return "A table in the database is locked" case 7: return "A malloc() failed" case 8: return "Attempt to write a readonly database" case 9: return "Operation terminated by sqlite3_interrupt()" case 10: return "Some kind of disk I/O error occurred" case 11: return "The database disk image is malformed" case 12: return "Unknown opcode in sqlite3_file_control()" case 13: return "Insertion failed because database is full" case 14: return "Unable to open the database file" case 15: return "Database lock protocol error" case 16: return "Database is empty" case 17: return "The database schema changed" case 18: return "String or BLOB exceeds size limit" case 19: return "Abort due to constraint violation" case 20: return "Data type mismatch" case 21: return "Library used incorrectly" case 22: return "Uses OS features not supported on host" case 23: return "Authorization denied" case 24: return "Auxiliary database format error" case 25: return "2nd parameter to sqlite3_bind out of range" case 26: return "File opened that is not a database file" case 27: return "Notifications from sqlite3_log()" case 28: return "Warnings from sqlite3_log()" case 100: return "sqlite3_step() has another row ready" case 101: return "sqlite3_step() has finished executing" // Custom SwiftData errors // Binding errors case 201: return "Not enough objects to bind provided" case 202: return "Too many objects to bind provided" // Custom connection errors case 301: return "A custom connection is already open" case 302: return "Cannot open a custom connection inside a transaction" case 303: return "Cannot open a custom connection inside a savepoint" case 304: return "A custom connection is not currently open" case 305: return "Cannot close a custom connection inside a transaction" case 306: return "Cannot close a custom connection inside a savepoint" // Index and table errors case 401: return "At least one column name must be provided" case 402: return "Error extracting index names from sqlite_master" case 403: return "Error extracting table names from sqlite_master" // Transaction and savepoint errors case 501: return "Cannot begin a transaction within a savepoint" case 502: return "Cannot begin a transaction within another transaction" // Unknown error default: return "Unknown error" } } } /// Provides access to the result set returned by a database query. /// The entire result set is cached, so this does not retain a reference /// to the statement or the database connection. private class FilledSQLiteCursor<T>: ArrayCursor<T> { fileprivate init(statement: SQLiteDBStatement, factory: (SDRow) -> T) { var status = CursorStatus.success var statusMessage = "" let data = FilledSQLiteCursor.getValues(statement, factory: factory, status: &status, statusMessage: &statusMessage) super.init(data: data, status: status, statusMessage: statusMessage) } /// Return an array with the set of results and release the statement. fileprivate class func getValues(_ statement: SQLiteDBStatement, factory: (SDRow) -> T, status: inout CursorStatus, statusMessage: inout String) -> [T] { var rows = [T]() var count = 0 status = CursorStatus.success statusMessage = "Success" var columns = [String]() let columnCount = sqlite3_column_count(statement.pointer) for i in 0..<columnCount { let columnName = String(cString: sqlite3_column_name(statement.pointer, i)) columns.append(columnName) } while true { let sqlStatus = sqlite3_step(statement.pointer) if sqlStatus != SQLITE_ROW { if sqlStatus != SQLITE_DONE { // NOTE: By setting our status to failure here, we'll report our count as zero, // regardless of how far we've read at this point. status = CursorStatus.failure statusMessage = SDError.errorMessageFromCode(Int(sqlStatus)) } break } count += 1 let row = SDRow(statement: statement, columns: columns) let result = factory(row) rows.append(result) } return rows } } /// Wrapper around a statement to help with iterating through the results. private class LiveSQLiteCursor<T>: Cursor<T> { fileprivate var statement: SQLiteDBStatement! // Function for generating objects of type T from a row. fileprivate let factory: (SDRow) -> T // Status of the previous fetch request. fileprivate var sqlStatus: Int32 = 0 // Number of rows in the database // XXX - When Cursor becomes an interface, this should be a normal property, but right now // we can't override the Cursor getter for count with a stored property. fileprivate var _count: Int = 0 override var count: Int { get { if status != .success { return 0 } return _count } } fileprivate var position: Int = -1 { didSet { // If we're already there, shortcut out. if oldValue == position { return } var stepStart = oldValue // If we're currently somewhere in the list after this position // we'll have to jump back to the start. if position < oldValue { sqlite3_reset(self.statement.pointer) stepStart = -1 } // Now step up through the list to the requested position for _ in stepStart..<position { sqlStatus = sqlite3_step(self.statement.pointer) } } } init(statement: SQLiteDBStatement, factory: @escaping (SDRow) -> T) { self.factory = factory self.statement = statement // The only way I know to get a count. Walk through the entire statement to see how many rows there are. var count = 0 self.sqlStatus = sqlite3_step(statement.pointer) while self.sqlStatus != SQLITE_DONE { count += 1 self.sqlStatus = sqlite3_step(statement.pointer) } sqlite3_reset(statement.pointer) self._count = count super.init(status: .success, msg: "success") } // Helper for finding all the column names in this statement. fileprivate lazy var columns: [String] = { // This untangles all of the columns and values for this row when its created let columnCount = sqlite3_column_count(self.statement.pointer) var columns = [String]() for i: Int32 in 0 ..< columnCount { let columnName = String(cString: sqlite3_column_name(self.statement.pointer, i)) columns.append(columnName) } return columns }() override subscript(index: Int) -> T? { get { if status != .success { return nil } self.position = index if self.sqlStatus != SQLITE_ROW { return nil } let row = SDRow(statement: statement, columns: self.columns) return self.factory(row) } } override func close() { statement = nil super.close() } }
mpl-2.0
9006eff2cb281ab99a4e760a87b3e9c0
38.190559
200
0.600348
4.810515
false
false
false
false
niekang/WeiBo
WeiBo/Class/Utils/Base/PageStateManager.swift
1
2466
// // PageStateManager.swift // WeiBo // // Created by MC on 2019/8/27. // Copyright © 2019 com.nk. All rights reserved. // import UIKit public protocol LoadViewProtocol: UIView { func startLoading() func stopLoading() } class PageStateManager { private var emptyView: UIView? private var errorView: UIView? private var loadView: LoadViewProtocol? private var pageView: UIView? public typealias ReloadCallback = () -> Void private var reloadCallback: ReloadCallback? init(_ pageView: UIView, emptyView: UIView? = nil, errorView: UIView? = nil, loadView: LoadViewProtocol? = nil) { self.setEmptyView(emptyView) self.setErrorView(errorView) self.setLoadView(loadView) } //MARK: - public method public func setEmptyView(_ emptyView: UIView?) { guard let emptyView = emptyView else { return } self.emptyView?.removeFromSuperview() self.emptyView = emptyView self.pageView?.addSubview(emptyView) } public func setErrorView(_ errorView: UIView?) { guard let errorView = errorView else { return } self.errorView?.removeFromSuperview() self.errorView = errorView self.pageView?.addSubview(errorView) } public func setLoadView(_ loadView: LoadViewProtocol?) { guard let loadView = loadView else { return } self.loadView?.removeFromSuperview() self.loadView = loadView self.pageView?.addSubview(loadView) } public func setReloadCallback(reloadCallback: @escaping ReloadCallback) { self.reloadCallback = reloadCallback } public func showContent() { self.emptyView?.isHidden = true self.loadView?.isHidden = true self.loadView?.stopLoading() self.errorView?.isHidden = true } public func showEmpty() { self.showView(self.emptyView) } public func showLoading() { self.showView(self.loadView) self.loadView?.startLoading() } public func showError() { self.showView(self.errorView) } //MARK: - private method private func showView(_ view: UIView?) { guard let view = view else { return } self.showContent() view.isHidden = false self.pageView?.bringSubviewToFront(view) } }
apache-2.0
cbe97b5a81cd486c7c7a03e79b212661
24.677083
117
0.614199
4.900596
false
false
false
false
OverSwift/VisualReader
Shared/Utils/Source/Shared/Color+Hex.swift
1
3483
// // Color+Hex.swift // Utils // // Created by Sergiy Loza on 06.05.17. // Copyright © 2017 Sergiy Loza. All rights reserved. // import Foundation #if os(iOS) || os(tvOS) import UIKit public typealias Color = UIColor #elseif os(macOS) import Cocoa public typealias Color = NSColor #endif public extension Color { class func colorWithRGBHex(_ hex: Int, alpha: Float = 1.0) -> Color { let r = Float((hex >> 16) & 0xFF) let g = Float((hex >> 8) & 0xFF) let b = Float((hex) & 0xFF) #if os(iOS) || os(tvOS) return Color(red: CGFloat(r / 255.0), green: CGFloat(g / 255.0), blue:CGFloat(b / 255.0), alpha: CGFloat(alpha)) #elseif os(macOS) return Color(calibratedRed: CGFloat(r / 255.0), green: CGFloat(g / 255.0), blue:CGFloat(b / 255.0), alpha: CGFloat(alpha)) #endif } public convenience init(hex: String, alpha:CGFloat = 1.0) { var red: CGFloat = 0.0 var green: CGFloat = 0.0 var blue: CGFloat = 0.0 var alpha: CGFloat = alpha if hex.hasPrefix("#") { let index = hex.characters.index(hex.startIndex, offsetBy: 1) let hex = hex.substring(from: index) let scanner = Scanner(string: hex) var hexValue: CUnsignedLongLong = 0 if scanner.scanHexInt64(&hexValue) { switch (hex.characters.count) { case 3: red = CGFloat((hexValue & 0xF00) >> 8) / 15.0 green = CGFloat((hexValue & 0x0F0) >> 4) / 15.0 blue = CGFloat(hexValue & 0x00F) / 15.0 case 4: red = CGFloat((hexValue & 0xF000) >> 12) / 15.0 green = CGFloat((hexValue & 0x0F00) >> 8) / 15.0 blue = CGFloat((hexValue & 0x00F0) >> 4) / 15.0 alpha = CGFloat(hexValue & 0x000F) / 15.0 case 6: red = CGFloat((hexValue & 0xFF0000) >> 16) / 255.0 green = CGFloat((hexValue & 0x00FF00) >> 8) / 255.0 blue = CGFloat(hexValue & 0x0000FF) / 255.0 case 8: red = CGFloat((hexValue & 0xFF000000) >> 24) / 255.0 green = CGFloat((hexValue & 0x00FF0000) >> 16) / 255.0 blue = CGFloat((hexValue & 0x0000FF00) >> 8) / 255.0 alpha = CGFloat(hexValue & 0x000000FF) / 255.0 default: print("Invalid RGB string, number of characters after '#' should be either 3, 4, 6 or 8", terminator: "") } } else { print("Scan hex error") } } else { print("Invalid RGB string, missing '#' as prefix", terminator: "") } self.init(red:red, green:green, blue:blue, alpha:alpha) } 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(r: Int, g: Int, b: Int, a:CGFloat) { assert(r >= 0 && r <= 255, "Invalid red component") assert(g >= 0 && g <= 255, "Invalid green component") assert(b >= 0 && b <= 255, "Invalid blue component") self.init(red: CGFloat(r) / 255.0, green: CGFloat(g) / 255.0, blue: CGFloat(b) / 255.0, alpha: a) } convenience init(netHex:Int) { self.init(red:(netHex >> 16) & 0xff, green:(netHex >> 8) & 0xff, blue:netHex & 0xff) } }
bsd-3-clause
0a19846dffc6ce3f8ef5d49c9c41467d
36.042553
128
0.565192
3.344861
false
false
false
false
insanoid/SwiftyJSONAccelerator
Core/Helpers/JSONHelper.swift
1
5306
// // JSONHelper.swift // SwiftyJSONAccelerator // // Created by Karthik on 16/10/2015. // Copyright © 2015 Karthikeya Udupa K M. All rights reserved. // import Foundation import SwiftyJSON /// A structure to store JSON parsed response in a systematic manner struct JSONParserResponse { let parsedObject: AnyObject? let error: NSError? /// Provides a easy way to know if the response is valid or not. var isValid: Bool { return parsedObject != nil } } /// Provide helpers to handle JSON content that the user provided. enum JSONHelper { /// Validate if the string that is provided can be converted into a valid JSON. /// /// - Parameter jsonString: Input string that is to be checked as JSON. /// - Returns: Bool indicating if it is a JSON or NSError with the error about the validation. static func isStringValidJSON(_ jsonString: String?) -> JSONParserResponse { return convertToObject(jsonString) } /// Convert the given string into an object. /// /// - Parameter jsonString: Input string that needs to be converted. /// - Returns: `JSONParserResponse` which contains the parsed object or the error. static func convertToObject(_ jsonString: String?) -> JSONParserResponse { guard let jsonValueString = jsonString else { return JSONParserResponse(parsedObject: nil, error: nil) } let jsonData = jsonValueString.data(using: String.Encoding.utf8)! do { let object = try JSONSerialization.jsonObject(with: jsonData, options: JSONSerialization.ReadingOptions.allowFragments) return JSONParserResponse(parsedObject: object as AnyObject?, error: nil) } catch let error as NSError { return JSONParserResponse(parsedObject: nil, error: error) } } /// Formats the given string into beautiful JSON with indentation. /// /// - Parameter jsonString: JSON string that has to be formatted. /// - Returns: String with JSON but well formatted. static func prettyJSON(_ jsonString: String?) -> String? { let response = convertToObject(jsonString) if response.isValid { return prettyJSON(object: response.parsedObject) } return nil } /// Format the given Object into beautiful JSON with indentation. /// /// - Parameter passedObject: Object that has to be formatted. /// - Returns: String with JSON but well formatted. static func prettyJSON(object passedObject: AnyObject?) -> String? { guard let object = passedObject else { return nil } do { let data = try JSONSerialization.data(withJSONObject: object, options: JSONSerialization.WritingOptions.prettyPrinted) return String(data: data, encoding: String.Encoding.utf8) } catch { return nil } } /// Reduce an array of JSON objects to a single JSON object with all possible keys (merge all keys into one single object). /// /// - Parameter items: An array of JSON items that have to be reduced. /// - Returns: Reduced JSON with the common key/value pairs. static func reduce(_ items: [JSON]) -> JSON { return items.reduce([:]) { source, item -> JSON in var finalObject = source for (key, jsonValue) in item { if let newValue = jsonValue.dictionary { finalObject[key] = reduce([JSON(newValue), finalObject[key]]) } else if let newValue = jsonValue.array, newValue.first != nil && (newValue.first!.dictionary != nil || newValue.first!.array != nil) { finalObject[key] = JSON([reduce(newValue + finalObject[key].arrayValue)]) // swiftlint:disable all // swift-format-ignore } else if jsonValue != JSON.null || !finalObject[key].exists() { finalObject[key] = jsonValue } // swiftlint:enable all } return finalObject } } } // Helper methods for JSON Object extension JSON { /// Extensive value types with differentiation between the number types. /// /// - Returns: Value type of the JSON value func detailedValueType() -> VariableType { switch type { case .string: return .string case .bool: return .bool case .array: return .array case .number: switch CFNumberGetType(numberValue as CFNumber) { case .sInt8Type, .sInt16Type, .sInt32Type, .sInt64Type, .charType, .shortType, .intType, .longType, .longLongType, .cfIndexType, .nsIntegerType: return .int case .float32Type, .float64Type, .floatType, .cgFloatType, .doubleType: return .float // Covers any future types for CFNumber. @unknown default: return .float } case .null: return .null default: return .object } } }
mit
972ed67e5eb694f8aac58bf0f40e49e9
36.359155
152
0.596041
4.971884
false
false
false
false
utahiosmac/jobs
Sources/Errors.swift
2
757
// // Errors.swift // Jobs // import Foundation public let JobErrorDomain = "JobErrorDomain" public enum JobError: Int { case cancelled case timedOut public var localizedDescription: String { switch self { case .cancelled: return "The job was cancelled" case .timedOut: return "The job timed out" } } } extension NSError { public convenience init(jobError: JobError, description: String? = nil, extra: Dictionary<NSObject, AnyObject> = [:]) { var info: [AnyHashable : Any] = extra info[NSLocalizedDescriptionKey] = description ?? jobError.localizedDescription self.init(domain: JobErrorDomain, code: jobError.rawValue, userInfo: info) } }
mit
08aac7b3627cf23fb22d08a9b2ccfde5
23.419355
123
0.643329
4.505952
false
false
false
false
jkennington/SwiftGraph
Sources/Search.swift
1
9147
// // Search.swift // SwiftGraph // // Copyright (c) 2014-2016 David Kopec // // 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. /// Functions for searching a graph & utility functions for supporting them /// Find a route from one vertex to another using a depth first search. /// /// - parameter from: The index of the starting vertex. /// - parameter to: The index of the ending vertex. /// - returns: An array of Edges containing the entire route, or an empty array if no route could be found public func dfs<T: Equatable>(from: Int, to: Int, graph: Graph<T>) -> [Edge] { // pretty standard dfs that doesn't visit anywhere twice; pathDict tracks route var visited: [Bool] = [Bool](repeating: false, count: graph.vertexCount) let stack: Stack<Int> = Stack<Int>() var pathDict: [Int: Edge] = [Int: Edge]() stack.push(from) var found: Bool = false while !stack.isEmpty { let v: Int = stack.pop() if v == to { found = true break } visited[v] = true for e in graph.edgesForIndex(v) { if !visited[e.v] { stack.push(e.v) pathDict[e.v] = e } } } // figure out route of edges based on pathDict if found { return pathDictToPath(from: from, to: to, pathDict: pathDict) } return [] } /// Find a route from one vertex to another using a depth first search. /// /// - parameter from: The starting vertex. /// - parameter to: The ending vertex. /// - returns: An array of Edges containing the entire route, or an empty array if no route could be found public func dfs<T: Equatable>(from: T, to: T, graph: Graph<T>) -> [Edge] { if let u = graph.indexOfVertex(from) { if let v = graph.indexOfVertex(to) { return dfs(from: u, to: v, graph: graph) } } return [] } /// Find a route from one vertex to another using a breadth first search. /// /// - parameter from: The index of the starting vertex. /// - parameter to: The index of the ending vertex. /// - returns: An array of Edges containing the entire route, or an empty array if no route could be found public func bfs<T: Equatable>(from: Int, to: Int, graph: Graph<T>) -> [Edge] { // pretty standard dfs that doesn't visit anywhere twice; pathDict tracks route var visited: [Bool] = [Bool](repeating: false, count: graph.vertexCount) let queue: Queue<Int> = Queue<Int>() var pathDict: [Int: Edge] = [Int: Edge]() queue.push(from) var found: Bool = false while !queue.isEmpty { let v: Int = queue.pop() if v == to { found = true break } for e in graph.edgesForIndex(v) { if !visited[e.v] { visited[e.v] = true queue.push(e.v) pathDict[e.v] = e } } } // figure out route of edges based on pathDict if found { return pathDictToPath(from: from, to: to, pathDict: pathDict) } return [] } /// Find a route from one vertex to another using a breadth first search. /// /// - parameter from: The starting vertex. /// - parameter to: The ending vertex. /// - returns: An array of Edges containing the entire route, or an empty array if no route could be found public func bfs<T: Equatable>(from: T, to: T, graph: Graph<T>) -> [Edge] { if let u = graph.indexOfVertex(from) { if let v = graph.indexOfVertex(to) { return bfs(from: u, to: v, graph: graph) } } return [] } /// Represents a node in the priority queue used /// for selecting the next struct DijkstraNode<D: Comparable>: Comparable, Equatable { let vertice: Int let distance: D } func < <D: Comparable>(lhs: DijkstraNode<D>, rhs: DijkstraNode<D>) -> Bool { return lhs.distance < rhs.distance } func == <D: Comparable>(lhs: DijkstraNode<D>, rhs: DijkstraNode<D>) -> Bool { return lhs.distance == rhs.distance } /// Finds the shortest paths from some route vertex to every other vertex in the graph. Note this doesn't yet use a priority queue, so it is very slow. /// /// - parameter graph: The WeightedGraph to look within. /// - parameter root: The index of the root node to build the shortest paths from. /// - parameter startDistance: The distance to get to the root node (typically 0). /// - returns: Returns a tuple of two things: the first, an array containing the distances, the second, a dictionary containing the edge to reach each vertex. Use the function pathDictToPath() to convert the dictionary into something useful for a specific point. public func dijkstra<T: Equatable, W: Comparable & Summable> (graph: WeightedGraph<T, W>, root: Int, startDistance: W) -> ([W?], [Int: WeightedEdge<W>]) { var distances: [W?] = [W?](repeating: nil, count: graph.vertexCount) distances[root] = startDistance var queue: PriorityQueue<DijkstraNode<W>> = PriorityQueue<DijkstraNode<W>>(ascending: true) var pathDict: [Int: WeightedEdge<W>] = [Int: WeightedEdge<W>]() queue.push(DijkstraNode(vertice: root, distance: startDistance)) while !queue.isEmpty { let u = queue.pop()!.vertice for e in graph.edgesForIndex(u) { if let we = e as? WeightedEdge<W> { //if queue.contains(we.v) { var alt: W if let dist = distances[we.u] { alt = we.weight + dist } else { alt = we.weight } if let dist = distances[we.v] { if alt < dist { distances[we.v] = alt pathDict[we.v] = we } } else { if !(we.v == root) { distances[we.v] = alt pathDict[we.v] = we queue.push(DijkstraNode(vertice: we.v, distance: alt)) } } //} } } } return (distances, pathDict) } /// A convenience version of dijkstra() that allows the supply of root vertice /// instead of the index of the root vertice. public func dijkstra<T: Equatable, W: Comparable & Summable> (graph: WeightedGraph<T, W>, root: T, startDistance: W) -> ([W?], [Int: WeightedEdge<W>]) { if let u = graph.indexOfVertex(root) { return dijkstra(graph: graph, root: u, startDistance: startDistance) } return ([], [:]) } /// Helper function to get easier access to Dijkstra results. public func distanceArrayToVertexDict<T: Equatable, W: Comparable & Summable>(distances: [W?], graph: WeightedGraph<T, W>) -> [T : W?] { var distanceDict: [T: W?] = [T: W?]() for i in 0..<distances.count { distanceDict[graph.vertexAtIndex(i)] = distances[i] } return distanceDict } /// Utility function that takes an array of Edges and converts it to an ordered list of vertices /// /// - parameter edges: Array of edges to convert. /// - parameter graph: The graph the edges exist within. /// - returns: An array of vertices from the graph. public func edgesToVertices<T: Equatable>(edges: [Edge], graph: Graph<T>) -> [T] { var vs: [T] = [T]() if let first = edges.first { vs.append(graph.vertexAtIndex(first.u)) vs += edges.map({graph.vertexAtIndex($0.v)}) } return vs } //version for Dijkstra with weighted edges public func edgesToVertices<T: Equatable, W: Comparable & Summable>(edges: [WeightedEdge<W>], graph: Graph<T>) -> [T] { var vs: [T] = [T]() if let first = edges.first { vs.append(graph.vertexAtIndex(first.u)) vs += edges.map({graph.vertexAtIndex($0.v)}) } return vs } /// Takes a dictionary of edges to reach each node and returns an array of edges /// that goes from `from` to `to` public func pathDictToPath(from: Int, to: Int, pathDict:[Int:Edge]) -> [Edge] { if pathDict.count == 0 { return [] } var edgePath: [Edge] = [Edge]() var e: Edge = pathDict[to]! edgePath.append(e) while (e.u != from) { e = pathDict[e.u]! edgePath.append(e) } return Array(edgePath.reversed()) } // version for Dijkstra public func pathDictToPath<W: Comparable & Summable>(from: Int, to: Int, pathDict:[Int:WeightedEdge<W>]) -> [WeightedEdge<W>] { var edgePath: [WeightedEdge<W>] = [WeightedEdge<W>]() var e: WeightedEdge<W> = pathDict[to]! edgePath.append(e) while (e.u != from) { e = pathDict[e.u]! edgePath.append(e) } return Array(edgePath.reversed()) }
apache-2.0
2b6f4b05e285a6f34a47a0cfdaa337c8
36.032389
262
0.610473
3.820802
false
false
false
false
ngageoint/fog-machine
Demo/FogViewshed/FogViewshed/Models/Viewshed/VanKreveld/VanKreveldViewshed.swift
1
5873
import Foundation import Buckets /** Finds a viewshed using Van Kreveld's method. More acurate, but slower. */ public class VanKreveldViewshed : ViewsehdAlgorithm { let elevationDataGrid: DataGrid let observer: Observer init(elevationDataGrid: DataGrid, observer: Observer) { self.elevationDataGrid = elevationDataGrid self.observer = observer } public func runViewshed() -> DataGrid { // elevation data let elevationGrid: [[Int]] = elevationDataGrid.data let rowSize:Int = elevationDataGrid.data.count let columnSize:Int = elevationDataGrid.data[0].count let oxiyi:(Int, Int) = elevationDataGrid.latLonToIndex(observer.position) // get the cell the observer exists in let oxi:Int = oxiyi.0 let oyi:Int = oxiyi.1 var oh:Double = Double(elevationGrid[oyi][oxi]) + observer.elevationInMeters // FIXME: if there a better way to deal with this? // if the elevation data where the observer is positioned is bad, just set elevation to above sea level if(elevationGrid[oyi][oxi] == Srtm.DATA_VOID) { oh = observer.elevationInMeters } let oxd:Double = Double(oxi) let oyd:Double = Double(oyi) let oVKCell = VanKreveldCell(x: oxi, y: oyi, h: oh) // outputs var viewshed:[[Int]] = [[Int]](count:rowSize, repeatedValue:[Int](count:columnSize, repeatedValue:Viewshed.NO_DATA)) viewshed[oyi][oxi] = Viewshed.OBSERVER func priorityQueueOrder(n1: VanKreveldSweepEventNode, _ n2: VanKreveldSweepEventNode) -> Bool { let angle1:Double = atan(oVKCell, c2: n1.cell, type: n1.eventType) let angle2:Double = atan(oVKCell, c2: n2.cell, type: n2.eventType) if(angle1 > angle2) { return false } else if(angle1 < angle2) { return true } else { let distance1:Double = sqrt(pow(oxd - Double(n1.cell.x), 2) + pow(oyd - Double(n1.cell.y), 2)) let distance2:Double = sqrt(pow(oxd - Double(n2.cell.x), 2) + pow(oyd - Double(n2.cell.y), 2)) if(distance1 > distance2) { return false } else { return true } } } //var test:Double = atan(VanKreveldCell(x: 0, y: 0, h: 0),c2:VanKreveldCell(x: 45, y: 45, h: 0), type: VanKreveldEventType.ENTER) var allCells = PriorityQueue(priorityQueueOrder) // find min and max for this grid for xi in 0 ..< rowSize { for yi in 0 ..< columnSize { // the observer can see itself, don't run this if(oxi == xi && oyi == yi) { continue } let elevation_at_xy = elevationGrid[xi][yi] if(elevation_at_xy == Srtm.DATA_VOID || elevation_at_xy == Srtm.NO_DATA) { continue } let xyVKCell = VanKreveldCell(x: xi, y: yi, h: Double(elevation_at_xy)) allCells.enqueue(VanKreveldSweepEventNode(eventType: VanKreveldEventType.ENTER, cell: xyVKCell)) allCells.enqueue(VanKreveldSweepEventNode(eventType: VanKreveldEventType.CENTER, cell: xyVKCell)) allCells.enqueue(VanKreveldSweepEventNode(eventType: VanKreveldEventType.EXIT, cell: xyVKCell)) } } var kreveldActive: KreveldActiveBinaryTree = KreveldActiveBinaryTree(reference: oVKCell) while !allCells.isEmpty { let currentKreveldSweepEventNode: VanKreveldSweepEventNode = allCells.dequeue()! let cell:VanKreveldCell = currentKreveldSweepEventNode.cell switch currentKreveldSweepEventNode.eventType { case VanKreveldEventType.ENTER: kreveldActive.insert(cell) case VanKreveldEventType.CENTER: NSLog("cell: \(cell.x), \(cell.y)") let x:Int = cell.x let y:Int = cell.y if (kreveldActive.isVisible(cell)) { viewshed[x][y] = Viewshed.VISIBLE } else { viewshed[x][y] = Viewshed.NOT_VISIBLE } case VanKreveldEventType.EXIT: kreveldActive.delete(cell) } } viewshed[oyi][oxi] = Viewshed.OBSERVER return DataGrid(data: viewshed, boundingBoxAreaExtent: elevationDataGrid.boundingBoxAreaExtent, resolution: elevationDataGrid.resolution) } func atan(c1: VanKreveldCell, c2: VanKreveldCell, type: VanKreveldEventType) -> Double { let dy:Double = Double(c2.y - c1.y) let dx:Double = Double(c2.x - c1.x) var angle:Double = 0 if(type == VanKreveldEventType.CENTER) { angle = (atan2(dy, dx) + 2*M_PI)%(2*M_PI) } else { if(type == VanKreveldEventType.ENTER) { angle = 2*M_PI } else if(type == VanKreveldEventType.EXIT) { angle = 0 } for i in 0 ..< 2 { for j in 0 ..< 2 { let tAngle = (atan2(dy - 0.5 + Double(i), dx - 0.5 + Double(j)) + 2*M_PI)%(2*M_PI) if(type == VanKreveldEventType.ENTER) { angle = min(angle, tAngle) } else if(type == VanKreveldEventType.EXIT) { angle = max(angle, tAngle) } } } } return angle } }
mit
961217b68c4bdada5b863d9ba3760312
38.682432
145
0.536864
4.124298
false
false
false
false